# Invoice to Loan Flow (Current Backend Behavior)

## Why this flow exists
Each invoice is treated as a receivable (money the customer/company owes you).
So every invoice automatically creates one loan entry under the selected loan account.

## Core business rules
- Invoice is the source of truth for receivable sales.
- Invoice does not create a Bill anymore.
- `accountId` is required when creating an invoice.
- Each invoice automatically creates a new Loan linked to the invoice.
- Loan is auto-created as `loanDirection: outgoing`.
- Loan amount (`principalAmount`) is equal to invoice `totalAmount`.
- Loan status is synced from invoice payment progress:
  - `active` when invoice is not fully paid
  - `closed` when invoice is fully paid

## Required create payload (important fields)
- `invoiceNumber`
- `invoiceDate`
- `dueDate`
- `accountId` (LoanAccount selected in frontend)
- `items[]` where each item must include:
  - `item` (Product ObjectId)
  - `quantity`
  - `unitprice`

Optional financial fields: `subtotal`, `discount`, `tax`, `totalAmount`, `amountPaid`.
If omitted, backend computes them.

## Removed/avoided duplicated fields
To avoid duplication and mismatch, these are no longer part of invoice input/model flow:
- invoice item `name` and `description` as required business data
- `customer` object inside invoice
- `accountName`, `accountPhone`, `accountCompany`
- `taxId`
- `billId`, `billNumber`

You should fetch account/customer style data from related collections, not duplicate it in invoice.

## Relation map (joins)
- `Invoice.accountId` -> `LoanAccount._id`
- `Invoice.loanId` -> `Loan._id`
- `Invoice.items[].item` -> `Product._id`
- `Loan.accountId` -> `LoanAccount._id`

### Populated in invoice endpoints
Invoice list/details now populate:
- `accountId`
- `loanId`
- `items.item`

So frontend can directly read related account/loan/product data without duplicated invoice fields.

## Create flow step-by-step
1. Validate invoice payload.
2. Validate selected `accountId` exists.
3. Normalize financial numbers (subtotal, discount, tax, totalAmount, amountPaid).
4. Validate products and stock for sale invoices.
5. Update stock for sold products.
6. Auto-create Loan using invoice financials/account/date.
7. Create Invoice with `loanId` and `loanNumber` from the new Loan.
8. Return created invoice.

## Update invoice flow
When invoice is updated:
- Financial fields and payment status are recalculated.
- Linked loan is auto-synced with:
  - account
  - principalAmount
  - date
  - status (active/closed)

Manual update of `loanId` or `loanNumber` through invoice update is blocked.

## Payment flow
`PATCH /invoices/:id/payment`
- updates `amountPaid` and/or `paymentStatus` on invoice
- then syncs linked loan status (`active` or `closed`)

## Reporting notes
Because invoice is now the receivable document itself:
- Revenue from invoice sales should come from invoices directly.
- Do not depend on Bill creation for invoice revenue.

Suggested net profit equation:
- `netProfit = (sum bill revenue + sum invoice revenue) - sum costs`

If you want to avoid double counting, ensure bill revenue only includes non-invoice bills.

## Frontend guidance
When creating invoice:
- send selected `accountId`
- send `items[].item` as Product id
- no need to send duplicated product name/description or customer/account text fields

Use populated response data to display product/account/loan details.
