# TODO: Arrears – Close Order Logic

## Problem

The query in `arrears.php` has the condition `WHERE pl.action = 'OPEN'`.
When an order line is closed (`action = 'CLOSE'`), it disappears from arrears —
even if the production order has not been completed.

---

## Proposed Plan

### Concept: "Carry-over line"

Instead of changing the existing close logic, we add a mechanism to
**carry forward the unfulfilled remainder** into the same or a new paper order.

---

### Option A — New line in the existing paper order ✅ RECOMMENDED

When the user closes a line (`CLOSE`), the system checks whether `qty_produced < qty_ordered`. If so:
- blocks the close and asks: *"Remaining qty: X. Create carry-over line?"*
- if YES → creates a **new line** in the same paper order with:
  - the same product and customer PN
  - `qty = arrears_qty` (the remainder)
  - `action = 'OPEN'`
  - a new `line_no`
  - optionally a new delivery date

**Pros:** No new tables, simple logic, arrears will automatically show the new line
**Cons:** A single paper order may grow over time

---

### Option B — New "follow-up" paper order

When closing a line with a remainder → option to create a **new paper order** with:
- the same customer, customer order number + suffix `"/FU"` or sequence number
- a carry-over line (qty = remainder)
- a `fk_paper_origin` field pointing to the original paper order

Requires: new column `fk_paper_origin` in `llx_openorderbook_paper`
**Pros:** Clean separation, full history
**Cons:** More changes, DB migration needed

---

### Option C — Change the arrears filter (simplest technically, but risky)

Change the arrears query from `action = 'OPEN'` to `action IN ('OPEN', 'CLOSE')` + filter "only if arrears > 0".

**Pros:** Single line of code
**Cons:** CLOSE lines appear in arrears even when intentionally closed,
no distinction between "closed with remainder" vs "deliberately closed"

---

## Decision

- [x] Option A ✅ Implemented (2026-03-30)
- [ ] Option B
- [ ] Option C
