# Sales Module — User Guide

A practical reference for working with invoices, customers, and customer payments in Brix Accounting. Covers what the system allows, what it prevents, and which roles can perform each action.

---

## Table of Contents

1. [Roles & What They Can Do](#1-roles--what-they-can-do)
2. [Customers](#2-customers)
3. [Invoices — Overview](#3-invoices--overview)
4. [Invoice Lifecycle](#4-invoice-lifecycle)
5. [Creating an Invoice](#5-creating-an-invoice)
6. [Editing an Invoice](#6-editing-an-invoice)
7. [Posting an Invoice](#7-posting-an-invoice)
8. [Voiding an Invoice](#8-voiding-an-invoice)
9. [Deleting a Draft Invoice](#9-deleting-a-draft-invoice)
10. [Customer Payments & Allocations](#10-customer-payments--allocations)
11. [Negative Stock / Oversell Invoices](#11-negative-stock--oversell-invoices)
12. [What the System Does Automatically](#12-what-the-system-does-automatically)
13. [What the System Does NOT Allow](#13-what-the-system-does-not-allow)
14. [Quick Answers — Common Scenarios](#14-quick-answers--common-scenarios)

---

## 1. Roles & What They Can Do

| Action | ADMIN | ACCOUNTANT | CASHIER |
|--------|:-----:|:----------:|:-------:|
| View invoices, customers, payments | ✓ | ✓ | ✓ |
| Create / edit customers | ✓ | ✓ | ✗ |
| Delete customers | ✓ | ✗ | ✗ |
| Create draft invoice | ✓ | ✓ | ✓ |
| Edit draft invoice | ✓ | ✓ | ✗ |
| Post invoice | ✓ | ✓ | ✓ |
| Amend open unpaid invoice | ✓ | ✓ | ✗ |
| **Void invoice** | **✓** | **✗** | **✗** |
| **Delete draft invoice** | **✓** | **✗** | **✗** |
| Upload attachments to invoice | ✓ | ✓ | ✗ |
| View / list attachments | ✓ | ✓ | ✓ |
| Record customer payment | ✓ | ✓ | ✓ |
| Apply / update payment allocations | ✓ | ✓ | ✗ |
| **Replace all payment allocations** | **✓** | **✗** | **✗** |
| **Void payment** | **✓** | **✗** | **✗** |
| Set `allow_negative_stock` on invoice | ✓ | ✗ | ✗ |

> **CASHIER** can create and post invoices and record customer payments (with allocations on create). They cannot edit customers, amend invoices, void or delete documents, or amend existing payments.

---

## 2. Customers

### What you can do

- Create a customer with a display name, email, phone, address, type (`RETAIL`, `WHOLESALE`, `CORPORATE`, `GOVERNMENT`), and default payment terms.
- Update any customer field at any time.
- Filter customer list by active status, outstanding balance, or available credit.
- View a customer's **AR balance** (total owed across open invoices), **credit balance** (unapplied advance payments), and **net balance** (AR minus credit).

### What is not allowed

- **CASHIER** cannot create or update customers.
- Only **ADMIN** can delete a customer.
- A customer's snapshot on existing invoices is **never updated** when you edit the customer — historical invoices always show the customer details as they were at invoice creation time.

### Customer balance fields explained

| Field | Meaning |
|-------|---------|
| `balance` | Sum of outstanding balances across all OPEN + PARTIAL invoices |
| `credit_balance` | Sum of unapplied amounts on posted payments (advance/overpayment) |
| `net_balance` | `balance − credit_balance` (floored at 0) — what the customer truly still owes |

---

## 3. Invoices — Overview

An invoice records a sale to a customer. It goes through a lifecycle from draft to paid (or voided). The invoice drives accounts receivable (A/R), inventory consumption, and journal entries automatically when posted.

### Key fields

| Field | Notes |
|-------|-------|
| `invoice_number` | Auto-assigned (`INV-0001`, `INV-0002`, …), unique per company, never changes |
| `customer_id` | Set on create; **cannot be changed** afterwards |
| `customer_snapshot` | Bill-to block for print/PDF. Defaults from the customer on create; overridable per invoice on create, draft edit, or unpaid amend. Does **not** change the customer master record |
| `txn_date` / `due_date` | Due date must be on or after transaction date |
| `payment_terms` | Defaults from the customer record; overridable per invoice |
| `balance` | `0` while draft; set to `total_amount` on post; reduced as payments are applied |
| `status` | See lifecycle below |
| `memo` | Printed on the invoice document |
| `notes` | Internal notes; not printed |

---

## 4. Invoice Lifecycle

```
DRAFT  ──[POST]──▶  OPEN  ──[payments]──▶  PARTIAL ──[remaining payment]──▶  PAID
  │                   │
  │                   ├──[PATCH, unpaid only]──▶  OPEN (amended)
  │                   └──[VOID, ADMIN only]──▶    VOIDED
  │
  └──[DELETE, ADMIN only]──▶  removed
```

| Status | What it means | Editable? |
|--------|--------------|-----------|
| `DRAFT` | Saved but not yet official; no GL or inventory impact; `balance = 0` | Yes — full edit |
| `OPEN` | Posted; A/R recognized; inventory consumed; `balance = total_amount` | Only if fully unpaid (amend) |
| `PARTIAL` | One or more payments applied; still has outstanding balance | **No** |
| `PAID` | Fully paid; `balance = 0` | **No** |
| `VOIDED` | Reversed by admin; GL and inventory restored; `balance = 0` | **No** (terminal) |

### Status transitions triggered by payments

| Condition after payment | Status |
|-------------------------|--------|
| `balance = total_amount` (no payments yet) | `OPEN` |
| `0 < balance < total_amount` | `PARTIAL` |
| `balance = 0` | `PAID` |

---

## 5. Creating an Invoice

**Who can do it:** ADMIN, ACCOUNTANT

### Steps

1. Select a **customer** (must exist in your company).
2. Set `txn_date` and `due_date` (due date must be ≥ invoice date).
3. Add at least **one line item**:
   - Choose an item from the catalog.
   - Set `qty` (minimum `0.0001`) and `unit_price` (minimum `0`).
   - Optionally apply a discount — use **one** of:
     - `discount_percent` (0–100) for a percentage discount, or
     - `discount_amount` (flat currency amount, must not exceed `qty × unit_price`) for a fixed-amount discount.
     - Sending both on the same line returns `422`. The response always includes both fields regardless of which was supplied.
   - Optionally select a `tax_code_id`; if not set and the item is taxable, the company's default tax code applies.
   - Optionally add a `description` (up to 1000 characters) for line-level notes.
4. Optionally add `memo` (printed) and/or `notes` (internal).
5. Save — the invoice is created in **DRAFT** status.

### What the system does automatically on create

- Assigns the next sequential `invoice_number` for the company.
- Defaults `customer_snapshot` from the customer (name, email, phone, address). Accept optional `customer_snapshot` overrides merged into that snapshot (QuickBooks-style Bill to editing without updating the customer record).
- Calculates all line totals, discounts, taxes, and the invoice total server-side.
- Validates stock availability for `INVENTORY` items (fails if insufficient, unless `allow_negative_stock` is enabled by an ADMIN).
- Validates that referenced items and tax codes belong to the same company.

### Constraints

| Rule | Details |
|------|---------|
| Minimum qty | `0.0001` — zero-qty lines are not accepted |
| Minimum unit price | `0` — free items (price = 0) are allowed |
| Discount percent | 0 to 100 only |
| Due date | Must be on or after `txn_date` |
| At least 1 line | Required on create |
| Active items only | Inactive items are rejected |
| Sufficient stock | `INVENTORY` items must have enough stock, unless `allow_negative_stock` is set (ADMIN only) |

---

## 6. Editing an Invoice

### Draft invoices

**Who can edit:** ADMIN, ACCOUNTANT

Any field can be changed freely while the invoice is in `DRAFT`. Sending a `lines` array **replaces all existing lines** entirely — it is not a merge.

### Open, unpaid invoices (amend)

**Who can amend:** ADMIN, ACCOUNTANT

An `OPEN` invoice can be amended **only if all of the following are true**:

- Status is exactly `OPEN` (not `PARTIAL`, `PAID`, or `VOIDED`).
- `balance` equals `total_amount` — no payment has been applied yet.
- No `PaymentAllocation` rows exist for this invoice.
- No backorder rows have been cleared by a bill receipt or inventory adjustment.

When these conditions are met, amending works as an atomic **unpost → edit → repost**:

1. The system reverses the existing journal entry and restores FIFO inventory layers.
2. Your changes are applied (header fields and/or lines).
3. Stock is checked again with the new quantities.
4. The invoice is re-posted: new journal entries are created and inventory is consumed.

> **Important:** An open amend is not a cosmetic edit — it reverses and re-creates real GL and inventory transactions. The `invoice_number`, `customer_id`, and `transaction_id` do not change.

### What cannot be changed on update

| Field | Changeable? |
|-------|------------|
| `invoice_number` | **No** — auto-assigned, immutable |
| `customer_id` | **No** — set on create, cannot be changed |
| `transaction_id` | **No** — system-assigned |
| Totals (`total_amount`, `balance`, `tax_total`, etc.) | **No** — always recalculated by the server |

---

## 7. Posting an Invoice

**Who can post:** ADMIN, ACCOUNTANT

Posting finalizes a draft invoice and makes it official.

### What happens on post

1. **Inventory consumed** — for `INVENTORY` items, FIFO layers are consumed and `qty_on_hand` is reduced. If `allow_negative_stock` is enabled, any shortfall becomes a **backorder**.
2. **Journal entries created:**
   - DR Accounts Receivable for `total_amount`
   - CR Sales Revenue for `sub_total`
   - CR VAT Payable for `tax_total` (if tax > 0)
   - DR COGS / CR Inventory Asset (if inventory items present)
3. **Status** set to `OPEN`, **balance** set to `total_amount`.
4. **Customer AR balance** increased by `total_amount`.
5. `InvoicePosted` event fired.

### If posting fails

If anything goes wrong during posting (e.g. insufficient stock, missing GL account), the **draft invoice is automatically deleted** — including all its lines, the spine transaction, and any attachments. You must create a new draft and fix the underlying issue before retrying.

> There is no way to recover a draft that failed to post. Fix the root cause first (e.g. receive inventory, configure the GL account), then create a fresh draft.

---

## 8. Voiding an Invoice

**Who can void:** ADMIN only

### Conditions required

- Invoice status must be exactly **`OPEN`**.
- You **cannot void** a `PARTIAL` or `PAID` invoice — you must first remove all payment allocations (see [Customer Payments](#10-customer-payments--allocations)).
- You **cannot void** an invoice whose backorder lines have already been cleared by a bill receipt or inventory adjustment — those transactions must be reversed first.

### What happens on void

1. FIFO inventory layers are restored and `qty_on_hand` increases.
2. Any backorder rows are reversed (if the invoice had oversold items).
3. The auto-generated journal entry is reversed.
4. Customer AR balance is **decreased** by the invoice's remaining `balance` (not the original total — relevant if partial payments were removed before voiding).
5. Status set to `VOIDED`, balance set to `0`.
6. `InvoiceVoided` event fired.

> **Void is permanent.** A voided invoice cannot be reopened, re-posted, or deleted. It is kept in the system as a permanent audit record.

---

## 9. Deleting a Draft Invoice

**Who can delete:** ADMIN only

- Only `DRAFT` invoices can be deleted.
- Deletion permanently removes the invoice, all its lines, and the spine transaction.
- ACCOUNTANT cannot delete drafts — they must ask an ADMIN.

---

## 10. Customer Payments & Allocations

Customer payments are recorded separately from invoices and then **allocated** to one or more invoices.

### Recording a payment

**Who can record:** ADMIN, ACCOUNTANT

- Each payment has a `total_amount` (minimum `0.01`), payment method, date, reference, and optional memo.
- A payment can be recorded **without any allocations** (advance/prepayment). The amount becomes unapplied credit on the customer's account.
- Allocations can be added later via the apply-allocations endpoint.

### Allocating a payment to an invoice

**Who can apply allocations:** ADMIN, ACCOUNTANT

| Rule | Detail |
|------|--------|
| Invoice must be `OPEN` or `PARTIAL` | Cannot allocate to `DRAFT`, `PAID`, or `VOIDED` invoices |
| Invoice must belong to the same customer | Cross-customer allocation is not allowed |
| Each invoice can appear only once per payment | No duplicate allocations on the same payment |
| Allocation cannot exceed invoice balance | `amount_applied` ≤ invoice `balance` |
| Sum of allocations ≤ payment total | Overpayment is allowed; excess becomes unapplied credit |

### Effect of allocation on invoice status

After each allocation, the invoice balance is recalculated:

- `balance > 0` → `PARTIAL`
- `balance = 0` → `PAID`

### Replacing all allocations (ADMIN only)

An ADMIN can replace all allocations on a payment at once. This deallocates everything first, then re-applies the new set. Use this to correct allocation mistakes.

### Amending a payment

**Who can amend:** ADMIN, ACCOUNTANT

- Header fields (amount, date, method, reference, memo) and allocations can be changed.
- Decreasing the payment amount is blocked if it would go below what has already been allocated.
- GL adjustment entries are created for amount or method changes.
- Voided payments **cannot** be amended.

### Voiding a payment

**Who can void:** ADMIN only

Voiding a payment:
1. Removes all allocations (restores invoice balances back toward `OPEN`/`PARTIAL`).
2. Reverses all GL entries from the original payment and any amendments.
3. Customer AR balance is not changed by the payment void itself — the invoice balances increase again, which increases AR.

> A voided payment is permanent and cannot be reinstated.

---

## 11. Negative Stock / Oversell Invoices

By default, the system **blocks posting** an invoice if there is not enough stock for `INVENTORY` items.

### Enabling oversell (ADMIN only)

An ADMIN can set `allow_negative_stock: true` on an invoice **only if** the company has `allow_negative_inventory` enabled.

When this flag is set:
- Stock validation is skipped during draft create and update.
- On post, available FIFO layers are consumed first; any shortfall becomes a **backorder** with estimated COGS.
- `qty_on_hand` for the item can go negative.

### Clearing backorders

Backorders are cleared when a vendor bill receipt or inventory adjustment arrives with enough stock. Once cleared:

- The invoice **cannot be amended or voided** until the clearing transaction (bill/adjustment) is reversed first.
- COGS is trued up to actual cost when backorders clear.

---

## 12. What the System Does Automatically

| Event | What the system does |
|-------|---------------------|
| **Invoice created** | Assigns invoice number, freezes customer snapshot, calculates all line totals and taxes |
| **Invoice posted** | Consumes FIFO inventory, posts AR/Revenue/Tax/COGS journal entries, sets balance, increases customer AR balance |
| **Invoice amended** | Reverses old GL + inventory, applies changes, re-validates stock, re-posts |
| **Invoice voided** | Reverses GL + inventory, clears backorders, decreases customer AR balance |
| **Draft post fails** | Auto-deletes the draft invoice, lines, and transaction |
| **Payment recorded** | Posts Cash/Bank DR, AR CR journal entry |
| **Payment allocated** | Reduces invoice balance, updates invoice status to PARTIAL or PAID, reduces customer AR balance |
| **Payment voided** | Reverses all GL entries, removes all allocations, restores invoice balances |
| **Item snapshot** | Frozen on each invoice line at creation — changes to item catalog do not affect existing invoices |

---

## 13. What the System Does NOT Allow

### Invoice restrictions

| Attempt | What happens |
|---------|-------------|
| Create invoice as CASHIER | Allowed — creates a draft |
| Set `allow_negative_stock` as ACCOUNTANT | `403 Forbidden` (ADMIN only) |
| Use an inactive item on an invoice | `422 Unprocessable` — item guard rejects inactive items |
| Set `qty` to 0 or negative | `422` — minimum is `0.0001` |
| Set `unit_price` to a negative value | `422` — minimum is `0` |
| Set `discount_percent` above 100 | `422` |
| Send both `discount_percent` and `discount_amount` on the same line | `422` — mutually exclusive |
| Set `discount_amount` greater than `qty × unit_price` | `422` — cannot exceed line gross |
| Set `due_date` before `txn_date` | `422` |
| Create an invoice with no lines | `422` — at least one line is required |
| Change `customer_id` after creation | The field is ignored on update; customer cannot be reassigned |
| Edit a `PARTIAL` invoice | `403` — amend is only allowed on fully unpaid `OPEN` invoices |
| Edit a `PAID` invoice | `403` — terminal status, no edits allowed |
| Edit a `VOIDED` invoice | `403` — terminal status |
| Post an already-posted invoice | `403` — post is only allowed from `DRAFT` |
| Void a `PARTIAL` or `PAID` invoice directly | `403` — you must remove all payment allocations first, then void |
| Void an invoice as ACCOUNTANT | `403` — ADMIN only |
| Void after backorder was cleared | `422` — the clearing transaction must be reversed first |
| Delete a posted invoice | `403` — only `DRAFT` can be deleted, and only by ADMIN |
| Negative invoice (negative total amount) | Not possible — qty and unit price both have `min: 0` floors |
| Credit notes / credit memos | **Not supported** — there is no credit note document type in the system |
| Recover a failed draft post | Not possible — the draft is deleted automatically on post failure |

### Payment restrictions

| Attempt | What happens |
|---------|-------------|
| Record payment as CASHIER | Allowed on create (with allocations) |
| Allocate to a `DRAFT`, `PAID`, or `VOIDED` invoice | `422` |
| Allocate more than the invoice's remaining balance | `422` |
| Allocate the same invoice twice on the same payment | `422` |
| Decrease payment amount below allocated total | `422` |
| Amend a voided payment | `403` |
| Void a payment as ACCOUNTANT | `403` — ADMIN only |
| Replace allocations as ACCOUNTANT | `403` — ADMIN only |
| Allocate to an invoice from a different customer | `422` |

---

## 14. Quick Answers — Common Scenarios

### How do I make an invoice?

1. Create a draft (`POST /invoices`) — fill in the customer, dates, and lines.
2. Review the draft. Edit freely while it is in `DRAFT`.
3. Post it (`POST /invoices/{id}/post`) when ready.

---

### Can I edit an invoice after it's been posted?

Yes, **if** no payment has been applied yet. The invoice must be `OPEN` and its balance must equal its total (no allocations). Use the same update endpoint (`PATCH /invoices/{id}`). The system will automatically reverse and re-post the GL entries.

Once any payment is applied (`PARTIAL` or `PAID`), the invoice **cannot be edited**. To edit a partially paid invoice you must first remove the payment allocations, then amend, then re-apply.

---

### Can I make a negative invoice?

No. The system enforces a minimum `qty` of `0.0001` and a minimum `unit_price` of `0`. A negative total invoice is not possible.

The closest alternative is to void the invoice (ADMIN only, `OPEN` status only) and re-create a correct one, or to adjust the amounts using a credit on the customer's payment account (advance/overpayment that creates a `credit_balance`).

---

### Can ADMIN make an invoice with negative stock (oversell)?

Yes, **if** the company has `allow_negative_inventory` enabled. The ADMIN sets `allow_negative_stock: true` on the invoice at create time. Stock validation is skipped, and any shortfall on post becomes a backorder row. ACCOUNTANT and CASHIER cannot use this flag.

---

### What happens if posting fails?

The draft invoice is **permanently deleted** — lines, transaction, and attachments. There is no recovery. Fix the root cause (e.g. receive stock, configure the GL account) and create a new draft.

---

### Can I void an invoice that has been partially paid?

Not directly. You must:
1. Remove the payment allocations from all payments applied to this invoice.
2. Once the invoice is back to `OPEN` with `balance = total_amount`, an ADMIN can void it.

---

### Can I void a PAID invoice?

No. The system only allows voiding an `OPEN` invoice. A `PAID` or `PARTIAL` invoice must have all allocations removed first (see above).

---

### How do I handle an overpayment?

Record the payment for the full amount received. Allocate it to the invoice(s) up to the invoice balance. The remaining unapplied amount becomes the customer's `credit_balance`. You can apply this credit to future invoices via the apply-allocations endpoint.

---

### How do I apply a customer's advance / credit to a new invoice?

Once the new invoice is posted (`OPEN`), use `POST /customer-payments/{payment_id}/allocations` to allocate some or all of the unapplied credit on the advance payment to the new invoice.

---

### Is there a credit note feature?

No. The system does not have a credit note or credit memo document. The available workarounds are:

- **Void** the invoice (ADMIN, `OPEN` only) and re-create a corrected one.
- **Amend** the invoice while it is `OPEN` and unpaid to change quantities or prices.
- **Overpayment credit** — a payment whose total exceeds its allocations leaves a `credit_balance` on the customer that can offset future invoices.

---

## Related API Docs

| Topic | File |
|-------|------|
| Invoice API reference | [invoices.md](./api/invoices.md) |
| Customer API reference | [customers.md](./api/customers.md) |
| Customer payments & allocations | [customer-payments.md](./api/customer-payments.md) |
| Negative stock / backorders | [negative-stock.md](./api/negative-stock.md) |
| Sales transaction hub | [sales-transactions.md](./api/sales-transactions.md) |
| Attachments | [attachments.md](./api/attachments.md) |
| Items catalog | [items.md](./api/items.md) |
| Tax codes | [tax-codes.md](./api/tax-codes.md) |
