# Hesabchin API — Integration Guide for AI Agents

You are integrating with **Hesabchin (حسابچین)**, an Iranian double-entry accounting SaaS. This document is complete and authoritative:
follow it literally, do not invent endpoints, fields or enum values. If something is not described here, it does not exist.

## 0. Ground rules (read first)

- **Base URL:** `https://hesabchin.ir/api/v1`
- **Auth:** every request needs `Authorization: Bearer <API_KEY>`. Keys look like `hck_…` (48 chars). The key is bound to exactly ONE business; never send a business id.
- **Server-side only.** Never put the key in browser/mobile code. The API sends no CORS headers for third-party origins. Store the key in an environment variable (e.g. `HESABCHIN_API_KEY`).
- **Format:** JSON in, JSON out. Always send `Content-Type: application/json` and `Accept: application/json`. Exception: file endpoints (§12) return binary Excel/PDF files — send `Accept: */*` and save the body as bytes.
- **Money:** integers in **Toman** (IRT). No decimals, no Rial. `150000` means 150,000 Toman.
- **Quantities:** numbers with up to 3 decimals (`2`, `0.5`, `1.250`).
- **Dates:** Gregorian ISO `YYYY-MM-DD` (e.g. `2026-11-13`). Convert Jalali (Shamsi) dates before sending. Timestamps in responses are ISO-8601 with the Tehran offset.
- **Use YOUR ids, not ours.** Store your own id in `external_ref` (e.g. `woo:order:10452`) on parties, products, invoices, quotes, transactions, cheques, payment documents, stock documents and journal vouchers, then read and update by it (§6). Most write bodies also accept codes/SKUs instead of our ids (§6.3). You rarely need to look up our numeric ids.
- **Language:** the `error` field is a stable machine code (English, snake_case). The `message` field is human text, usually Persian — show it to the end user, branch only on `error` and the HTTP status.
- **First call:** `GET /me` — it returns the business, the key's scopes and the business's subscription plan. Use `effective_scopes` to know what you may call and `plan.read_only` to know whether writes are allowed.

`GET /me` response:
```json
{ "business": { "id": 12, "name": "…", "default_tax_percent": 10 },
  "key": { "name": "woo", "scopes": ["products.read", "invoices.write"], "allowed_ips": null, "expires_at": null },
  "plan": { "name": "طرح دو", "scopes": ["…every scope…"], "rate_limit_per_minute": 120, "status": "active", "read_only": false,
            "ends_at": "2027-01-15T10:00:00+03:30",
            "features": { "moodian": true, "multi_warehouse": true, "installments": false, "salesmen": false, "sms_panel": false, "multi_currency": false, "production": false } },
  "effective_scopes": ["products.read", "invoices.write"], "currency": "IRT", "server_time": "…" }
```
- `plan` is the subscription of the key's **business** (subscriptions are bought per business, not per user). `status`: `free` (the business's free plan), `active` (paid plan) or `expired` (no current subscription → `read_only: true`). `ends_at`: end of the current plan (`null` when expired).
- `plan.features`: which plan-gated modules the business has. A route of a module that is `false` answers `402 plan_feature` (§1).

## 1. Access model

The API (with every scope) is available on **every** plan; the plan only sets the rate limit and which optional modules are on. Gates, checked in this order:

1. **IP allowlist** (optional, per key). If the key has allowed IPs/CIDRs and the caller IP is not in it → `403 ip_not_allowed`.
2. **Key scope.** The key itself must carry the scope (`403 insufficient_scope`). Fix: the user must create a key with that scope.
3. **Subscription.** When the business's subscription (or its free plan) has ended, the business is read-only: every `GET` (and backups/exports) still works, but writes return `402 subscription_inactive`. Fix: the business owner renews in the web app. Do not retry.
4. **Plan features.** Routes of a module that is not in the business's plan return `402 plan_feature` (e.g. every Moodian route (§11) on «طرح یک»; also installments, writing salesmen, a second warehouse). The `message` names the feature and the plan that includes it. Fix: the owner upgrades the plan. Do not retry.

### Scopes

| Scope | Grants |
|---|---|
| `parties.read` | List/read customers & suppliers, their statements, categories, bank accounts and shareholders |
| `parties.write` | Create/update/patch/delete/merge parties, batch & upsert, categories, bank accounts, shareholders, share links, Excel import |
| `products.read` | Products, categories, warehouses, stock levels, stock documents, stock turnover, price levels and price resolution |
| `products.write` | Create/update/patch/delete products, batch & upsert, bulk price, barcodes, adjust/transfer stock, warehouses, stock documents, price levels, Excel import |
| `invoices.read` | Invoices, quotes (proformas), PDFs, projects, salesmen, Moodian status |
| `invoices.write` | Create/update/patch/approve/delete invoices and quotes, send them, projects and salesmen |
| `treasury.read` | Cash/bank/petty accounts, transactions, cheques, payment documents, loans, ledger accounts, due-date averaging |
| `treasury.write` | Create/update/delete cash, bank and petty-cash accounts; create/update/delete loans, pay/unpay installments, settle |
| `payments.write` | Transactions of type receipt / payment; multi-line payment documents |
| `expenses.write` | Transactions of type expense; create expense/income categories |
| `incomes.write` | Transactions of type income |
| `transfers.write` | Transactions of type transfer |
| `debts.write` | Transactions of type party_debt / party_credit |
| `cheques.write` | Create, deposit, clear, bounce, spend, revert, reschedule and delete cheques |
| `reports.read` | Every report (JSON, Excel, PDF), chart of accounts, journal vouchers, fiscal years, opening balance, project cards |
| `payroll.read` | Read employees, payslips, advances and payroll liabilities |
| `payroll.write` | Create/update employees, issue/pay/delete payslips, pay advances, remit insurance/tax |
| `assets.read` | Read fixed assets with accumulated depreciation and book value |
| `assets.write` | Buy, depreciate, dispose and delete fixed assets |
| `audit.read` | Read the change log (who did what, when, from which IP) |
| `changes.read` | Read the changes feed for incremental sync (only object types whose read scope the key also has) |
| `webhooks.manage` | List/create/update/delete/test webhook subscriptions |
| `backup.read` | Download a full backup of the business |
| `journal.write` | Manual journal vouchers, chart of accounts, fiscal years and closing, opening balance, party balance documents |
| `moodian.manage` | Send, inquire, correct and cancel e-invoices at the Iranian tax authority (Moodian) and set per-invoice tax attributes |

`POST /transactions`, `PUT /transactions/{id}` and `DELETE /transactions/{id}` need the scope that matches the transaction **type** (§8.3). Every route and its scope is listed in §17.

## 2. Reliability rules

- **Idempotency (use it on every write).** Send `Idempotency-Key: <unique string per logical operation>` (≤ 200 chars; e.g. your own order id) on any `POST`, `PUT`, `PATCH` or `DELETE`. The key is scoped to your API key + method + path and lives 24 hours.
  - The key is **reserved atomically before the request runs**, together with a fingerprint of the request body.
  - Same key, same body, first request finished → the ORIGINAL status and body are replayed with header `Idempotent-Replay: true`; nothing is written again.
  - Same key while the first request is still running → `409 idempotency_in_progress` with `Retry-After: 2`. Wait and retry with the same key; you will then get the replay.
  - Same key, different body → `422 idempotency_key_reused`. Use a new key for a genuinely new operation.
  - A request that fails (4xx/5xx) releases the key, so you can fix the payload and retry with the same key.
- **external_ref is a second, permanent safety net:** creating a second record with the same `external_ref` returns `409 duplicate_external_ref` with `existing_id`, even after 24 hours.
- **Rate limit:** per key, per minute; the number comes from the business's plan (value in `GET /me` → `plan.rate_limit_per_minute`). Every response carries `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` (seconds until the window resets). On `429 rate_limited` wait `Retry-After` seconds, then retry. A batch call (§6.5) counts as one request.
- **Request id:** every v1 response has `X-Request-Id: req_…`. Log it; support can find the exact call with it.
- **Do not hammer on auth errors.** Many rejected requests (401/403) from one IP lock that IP temporarily (`429 too_many_failures`). On 401/403 stop and report to the user.
- **Everything is transactional.** A failed request changes nothing. A successful invoice/transaction/cheque updates stock, the party balance and cash/bank atomically.
- **Never "fix" data by posting opposite amounts.** To undo something, DELETE it (the system reverses all of its effects).
- **Period lock:** nothing dated on or before `locked_until` (`GET /fiscal-years`) can be created, edited or deleted → `422 period_closed`.

## 3. Errors

Body: `{ "error": "<code>", "message": "<text>", "errors": { "<field>": ["…"] } }` (`errors` for `validation`, extra keys where noted).

| HTTP | error | Meaning / what to do |
|---|---|---|
| 401 | missing_api_key, invalid_api_key | Key absent, wrong, revoked or expired. Stop; ask the user for a valid key. |
| 402 | subscription_inactive | The business's subscription or free plan has ended; it is read-only. Reads and backups still work, writes do not. The owner must renew. Do not retry. |
| 402 | plan_feature | The route's module is not in the business's plan (e.g. Moodian on «طرح یک»). The owner must upgrade. Do not retry. |
| 403 | ip_not_allowed, insufficient_scope | See §1. Do not retry. |
| 404 | not_found | The id/ref/code does not exist in this business. |
| 409 | duplicate_external_ref | Another record already has that `external_ref`; `existing_id` tells which. Treat it as "already done". |
| 409 | idempotency_in_progress | Same Idempotency-Key still running; retry after `Retry-After`. |
| 409 | already_exists | Batch `mode: "create"` found an existing record (`existing_id`). |
| 422 | idempotency_key_reused | Idempotency-Key reused with a different body. |
| 422 | validation | A field is missing/invalid; see `errors`. Also: unknown `sort` field, bad `updated_since`, too many `ids`. |
| 422 | batch_invalid | Atomic batch: at least one row invalid, nothing written; `errors: [{index, error, message, errors}]`. |
| 422 | ambiguous_ref | A code/SKU/mobile/barcode matched more than one record; send the id instead. |
| 422 | not_patchable | PATCH /invoices got a field that changes amounts; use PUT. |
| 422 | insufficient_stock | Outflow exceeds stock in that warehouse (now, or at some point in history after an edit). |
| 422 | insufficient_funds | Cash/bank balance too low for this outflow. |
| 422 | over_payment | Amount exceeds the invoice's `remaining`. |
| 422 | over_return | Return quantity exceeds what was sold/bought on the referenced invoice. |
| 422 | bad_party, bad_product, bad_warehouse, bad_money_account, bad_invoice, bad_ref, bad_project, bad_salesman, bad_account, bad_category, bad_cheque | A referenced id/code is invalid or does not match. With alternate keys the failing field is in `errors`. |
| 422 | has_returns, party_locked, paid_more, has_balance, has_stock, has_cheque, in_use, in_document, is_shareholder, cheque_progressed | The record cannot be changed/deleted because something depends on it. |
| 422 | bad_status, bad_type, not_draft, converted | Wrong state for this action (cheque, draft invoice, converted quote). |
| 422 | duplicate_barcode, duplicate_code, duplicate_name, duplicate_number | Unique value already used. |
| 422 | credit_limit_exceeded | An approved sale would push the customer over `credit_limit` (`credit_limit, balance, over`). |
| 422 | unbalanced, bad_line, control_account, party_required, party_not_allowed, auto_entry | Voucher rules (§10). |
| 422 | period_closed | The date is on/before the period lock. |
| 422 | overlap, already_closed, not_closed, closed, not_ended, close_earlier_first, reopen_later_first, bad_distribution | Fiscal-year rules (§10.3). |
| 422 | import_invalid | Excel import has invalid rows; nothing written. |
| 422 | moodian_* | Tax-authority (Moodian) rules (§11). |
| 402 | no_sms_credit | No SMS credit left for sending by SMS. |
| 429 | rate_limited, too_many_failures | Back off (§2). |

## 4. Core concepts you must model correctly

- **Party** = customer and/or supplier (`type`: `customer` | `supplier` | `both`). **`balance` sign:** positive → the party OWES the business (debtor / بدهکار). Negative → the business owes the party (creditor / بستانکار).
- **Money account** = cash box (`cash`), bank account (`bank`) or petty cash (`petty`), each with a live `balance`.
- **Product** with `stock` (sum over warehouses) and `avg_cost` (moving average, display only). `is_service: true` products have no stock.
- **Exact costing:** every stock movement carries an integer `value`; inventory value is exactly the sum of those values and equals the inventory account. Line amount = round(qty × unit_price) − discount.
- **Invoice types:** `sale`, `purchase`, `sale_return`, `purchase_return`. Each has `total`, `paid_amount`, `remaining` (= total − paid_amount). `status`: `approved` (default) or `draft` (no effect on stock, ledger or balances until approved).
- **What an invoice does automatically:** `sale`: stock −qty, party +total, revenue & cost of goods posted. `purchase`: stock +qty, party −total. `sale_return`: stock +qty, party −total (with `ref_invoice_id` offset against the original's `remaining`). `purchase_return`: stock −qty at average cost, party +total.
- **Settlement** = a `receipt`/`payment` transaction, a cheque, or a payment-document row, optionally linked to one invoice (then that invoice's `paid_amount` rises).

## 5. Lists: pagination, sorting, filtering, incremental sync

Every list below that says "list" accepts the same parameters:

| Parameter | Meaning |
|---|---|
| `page`, `per_page` | Offset pagination (`per_page` 1–200, default 25). Response: `{ data, current_page, last_page, per_page, total, from, to, first_page_url, last_page_url, next_page_url, prev_page_url, path }`. |
| `after_id` | **Keyset pagination for sync loops**: rows with `id > after_id`, ordered by id ascending. Response: `{ data, per_page, next_after_id }` (`null` = no more rows). Start with `after_id=0`. Do not combine with `sort`. Prefer this over `page` when the table changes while you read it. |
| `sort` | Comma list of whitelisted fields, `-` prefix = descending: `sort=-date,number`. Unknown field → `422 validation` listing the allowed ones. Default order is unchanged. |
| `ids` | `ids=4,9,12` (≤ 200) → only those rows. |
| `updated_since`, `created_since` | ISO-8601 date or timestamp (`2026-11-15T08:00:00+03:30`; URL-encode `+` as `%2B`): rows with `updated_at` / `created_at` ≥ value. Combine with `sort=updated_at`. |
| `external_ref`, `external_ref_in` | Exact match on your id; `external_ref_in=a,b,c` (≤ 200). |

Sortable fields: parties `id, name, code, created_at, updated_at, balance`; products `id, name, code, sku, sale_price, purchase_price, stock, created_at, updated_at`; invoices `id, number, date, due_date, total, paid_amount, remaining, created_at, updated_at, party.name`; transactions `id, number, date, amount, created_at, updated_at`; cheques `id, due_date, issue_date, amount, status, created_at, updated_at`; quotes, payment documents `id, number, date, total, created_at, updated_at`; stock documents `id, number, date, total_value, created_at, updated_at`; journal vouchers `id, number, date, created_at, updated_at`.

Deleted rows: parties and products are soft-deleted; add `include_deleted=1` to see them (with `deleted_at`) so a sync can propagate deletions. Other resources are hard-deleted; use the changes feed (§7) or webhooks to learn about deletions.

**Stock caveat:** a product's `updated_at` does NOT change when its quantity changes. To sync quantities use the `stock.changed` webhook, the changes feed (`types=product`), or `GET /stock?updated_since=…` (§9.4).

## 6. External references, lookups, upsert, PATCH and batch

### 6.1 external_ref and metadata
Accepted on create/update of parties, products, invoices, quotes, transactions, cheques, payment documents, stock documents and journal vouchers, and returned in every representation and webhook payload:
- `external_ref`: string ≤ 100 (recommended `<system>:<type>:<id>`). Unique per business (for invoices: per business **and type**, so a sale and its return can share an order id). Deleted parties/products free their ref. Omitting the key on update leaves it unchanged; `null` clears it.
- `metadata`: flat object, ≤ 20 keys matching `[a-z0-9_]{1,40}`, values string (≤ 500), number, boolean or null, ≤ 4 KB. Replaced as a whole when sent.
- Duplicate → `409 duplicate_external_ref` with `existing_id`.

### 6.2 Direct lookups (same body as the matching `/{id}` route)
`GET /parties/by-ref/{ref}`, `GET /parties/by-code/{code}`, `GET /products/by-ref/{ref}`, `GET /products/by-code/{code}`, `GET /products/by-sku/{sku}`, `GET /products/by-barcode/{barcode}` (matches any of several `;`-separated barcodes), `GET /invoices/by-ref/{ref}` (add `?type=` when a sale and a return share the ref, else `422 ambiguous_ref`), `GET /invoices/by-number/{type}/{number}`, `GET /quotes/by-ref/{ref}`, `GET /transactions/by-ref/{ref}`, `GET /cheques/by-ref/{ref}`, `GET /payment-documents/by-ref/{ref}`, `GET /stock-documents/by-ref/{ref}`, `GET /journal-entries/by-ref/{ref}`. URL-encode the ref. Not found → `404`.

Exact list filters: parties `code, mobile, national_code, email`; products `code, sku, barcode`; invoices `number` (with `type`), `reference`; transactions `number, reference`; cheques `number, sayad_id`; quotes, payment documents, stock documents, journal vouchers `number`.

### 6.3 Alternate keys in write bodies
Wherever a body takes an id you may send exactly one alternate instead (sending both → `422 validation`; not found → `422 bad_party`/`bad_product`/… with the field in `errors`; several matches → `422 ambiguous_ref`):

| Field | Alternates | Where |
|---|---|---|
| `party_id` | `party_code`, `party_ref` | invoices, quotes, transactions, cheques, payment-document items, stock documents, journal lines |
| `items[].product_id` | `items[].product_code`, `items[].sku`, `items[].barcode`, `items[].product_ref` | invoices, quotes, stock documents |
| `project_id` | `project_code` | invoices, transactions, payment documents, stock documents, journal vouchers |
| `salesman_id` | `salesman_name` (exact) | invoices |
| `invoice_id` | `invoice_ref` | transactions, cheques, payment-document items |
| `ref_invoice_id` | `ref_invoice_ref` | return invoices |
| `lines[].account_id` | `lines[].account_code` | journal vouchers |

### 6.4 Partial update (PATCH) and upsert
- `PATCH /parties/{id}`, `PATCH /products/{id}`: only the keys you send change; `null` clears an optional field. (PUT on parties is a full replace: omitted optional fields are cleared and an omitted `opening_amount` resets the opening balance to 0 — prefer PATCH.)
- `PATCH /invoices/{id}`: only `note, reference, title, due_date, external_ref, metadata, sent` (`sent: true` marks it as delivered without sending; `false` clears `sent_at`). No re-posting; allowed even in a closed period. Any other field → `422 not_patchable`.
- Upsert: `PUT /parties/by-ref/{ref}`, `PUT /parties/by-code/{code}`, `PUT /products/by-ref/{ref}`, `PUT /products/by-sku/{sku}`. Not found → created (`201`), found → patched (`200`). Header `X-Hesabchin-Upsert: created|updated`. The path value is written into the record.

### 6.5 Batch
`POST /products/batch` (`products.write`) and `POST /parties/batch` (`parties.write`):
```json
{ "match_on": "external_ref", "mode": "upsert", "atomic": true, "dry_run": false,
  "items": [
    { "external_ref": "woo:product:812", "name": "T-shirt M black", "sku": "TSHIRT-M-BLK", "sale_price": 450000, "category_path": "Clothing/T-shirts" },
    { "external_ref": "woo:product:813", "sale_price": 470000 } ] }
```
- `match_on`: products `external_ref | code | sku | barcode`; parties `external_ref | code | mobile | national_code`. Default `external_ref`.
- `mode`: `upsert` (default), `create` (existing → row error `already_exists`), `update` (missing → row error `not_found`). Updates are partial (PATCH semantics); a row whose values already match is `unchanged`.
- `atomic: true` (default): every row runs; if any fails NOTHING is written → `422 batch_invalid` with per-row `errors`. `atomic: false`: each row is its own savepoint; good rows are written, bad rows are reported.
- `dry_run: true`: runs everything and rolls back; the response shows what would happen.
- ≤ 500 items per call; one request against the rate limit. Records are unlimited on every plan.
- `category_path` (products): `/`-separated category names, found or created.
- Response `200`: `{ "dry_run": false, "atomic": true, "created": 1, "updated": 1, "unchanged": 0, "failed": 0, "results": [ { "index": 0, "status": "created", "id": 91, "external_ref": "woo:product:812" }, { "index": 1, "status": "updated", "id": 44, "external_ref": "woo:product:813" } ] }`. Failed rows: `{ index, status: "failed", error, message, errors? }`.
- Every created/updated row fires its normal event (so webhooks and the changes feed stay complete).

## 7. Changes feed — `changes.read`

Sync without polling every resource. Built on the change log; each row is one data change with a monotonically increasing `id`.

- `GET /changes?after=18234&limit=1000&types=product,party,invoice&origin=all`
  - `after`: last `id` you processed (exclusive). `0` = from the oldest retained row. `GET /changes/latest` → `{ "id": 18236 }` to start "from now".
  - `limit`: default 200, max 1000. Ordered by id ascending.
  - `types`: `party, party_category, product, product_category, stock_document, invoice, quote, project, salesman, transaction, payment_document, cheque, money_account, loan, journal, account, fiscal_year`. Unknown type → `422`. Types whose read scope the key lacks are skipped silently (e.g. `product` needs `products.read`).
  - `origin`: `all` (default) | `api` | `panel` | `not_me` (everything except changes made by the calling key — the loop-breaker).
- Response:
```json
{ "data": [
    { "id": 18235, "at": "2026-11-15T09:12:44+03:30", "event": "invoice.created", "object_type": "invoice", "action": "created",
      "object_id": 512, "number": 1041, "code": null, "external_ref": "woo:order:10452", "origin": "api", "api_key_id": 3 },
    { "id": 18236, "at": "2026-11-15T09:12:44+03:30", "event": "stock.changed", "object_type": "product", "action": "changed",
      "object_id": 44, "number": null, "code": "000044", "external_ref": "woo:product:813", "origin": "api", "api_key_id": 3 } ],
  "next_after": 18236, "has_more": false }
```
- Rows carry no user names or IPs (those stay behind `audit.read`). Fetch the object itself (`GET /invoices/{id}`) when you need its current state; a later row for a deleted object has `action: "deleted"`.
- Retention: the feed is the change log, kept for at least 90 days (currently never pruned). If you fall further behind, do a full resync with `after_id` lists.

## 8. Endpoints: treasury

### 8.1 Money accounts — `treasury.read` / `treasury.write`
- `GET /money-accounts?type=cash|bank|petty&active=1` → `[{id, account_id, type, name, code, bank_name, branch, account_number, card_number, sheba, holder, pos_number, bank_mobile, switch_no, terminal_no, merchant_id, is_default, is_active, note, opening_balance, balance}]`, ordered by type, then the type's default account first. `active=1` hides inactive accounts (use it for pickers; preselect `is_default`), `active=0` lists only inactive ones.
- `POST /money-accounts` `{ type: "cash"|"bank"|"petty", name, code?, bank_name?, branch?, account_number?, card_number?, sheba?, holder?, pos_number?, bank_mobile?, switch_no?, terminal_no?, merchant_id?, is_default?, is_active?, note?, opening_balance? }` → `201` with `balance`. At most one default per type: saving `is_default: true` clears it on the others of that type; an inactive account is never the default. `PUT /money-accounts/{id}` same body (type is fixed; omitted keys keep their value; `422 negative` if the new opening balance makes it negative). `DELETE /money-accounts/{id}` → `in_use` once it has any movement.
- `GET /money-accounts/{id}/statement?from&to` → `{ account, from, to, opening_balance, statement:[{date, description, debit, credit, balance, entry_id, number, kind, source_type, source_id}], total_debit, total_credit, closing_balance }` (debit = money in; without dates: `{ account, statement }`).
- `GET /ledger-accounts?type=expense|income` → account rows `[{id, code, name, type, system_key}]`. `POST /ledger-accounts` `{ name, type: "expense"|"income" }` (`expenses.write`) creates a category.

### 8.2 Transactions — list
`GET /transactions` (list, §5) — query `type, party_id, from, to, project_id, money_account_id, q, number, reference`. Item: transaction row + `party, money_account, to_money_account, account, project, entry:{id,number}`. `GET /transactions/{id}` → row + `entry`. `GET /transactions/by-ref/{ref}`.

### 8.3 Transactions — write (scope depends on `type`)
`POST /transactions` — common fields: `type` (required), `date` (required), `amount` (required, integer ≥ 1), `note?`, `reference?` (≤ 60), `project_id?`, `external_ref?`, `metadata?`.

| type | scope | extra required fields | effect |
|---|---|---|---|
| `receipt` | payments.write | party_id, money_account_id; optional invoice_id | money account +amount; party balance −amount |
| `payment` | payments.write | party_id, money_account_id; optional invoice_id | money account −amount; party balance +amount |
| `expense` | expenses.write | money_account_id; optional account_id | money account −amount; expense +amount |
| `income` | incomes.write | money_account_id; optional account_id | money account +amount; income +amount |
| `transfer` | transfers.write | money_account_id (from), to_money_account_id; optional `fee` | moves amount; source also pays `fee` to bank charges |
| `party_debt` | debts.write | party_id; optional due_date, account_id | party balance +amount, NO money moves |
| `party_credit` | debts.write | party_id; optional due_date, account_id | party balance −amount, NO money moves |

- `invoice_id` on receipt/payment: the invoice must belong to that party and be approved; receipt matches sale/purchase_return, payment matches purchase/sale_return; amount ≤ `remaining` (`over_payment`).
- Outflows fail with `insufficient_funds` if the account balance is too low.
- `fee` (integer ≥ 0, bank or payment-gateway commission, posted to bank charges) on `receipt` (the account receives amount − fee; the party is still credited the full amount; `bad_fee` if fee ≥ amount), `payment` and `transfer` (the account pays amount + fee). Ignored for other types.
- `PUT /transactions/{id}` — same body without `type` (the type never changes; scope = the existing type's scope). The old effect is reversed and the new one posted under the same number.
- `DELETE /transactions/{id}` reverses it.

### 8.4 Payment documents (multi-line receipts/payments) — `treasury.read` / `payments.write`
A document = N **items** (who: a party or a ledger account, optionally settling an invoice) against M **methods** (how: `cash`, `petty`, `bank`, `cheque`, `party`, `account`). Σ items = Σ methods (`unbalanced` otherwise); bank fees are outside that sum. One balanced voucher per document.
- `GET /payment-documents` (list; query `kind` receive|pay, `from, to, party_id, project_id, q, number`) → page + `total_amount`. Item: document + `kind_label, project, entry, title, items_count, invoices, methods, fees_total`. `GET /payment-documents/items` → one row per item with its `document`. `GET /payment-documents/{id}`, `GET /payment-documents/by-ref/{ref}`.
- `POST /payment-documents` → `201` full document: `{ kind: "receive"|"pay", date, number?, project_id?, description?, external_ref?, metadata?, items: [{ party_id? | account_id?, amount, invoice_id?, description? }] (1–100), methods: [{ method, amount, fee?, reference?, money_account_id?, cheque_id?, party_id?, account_id?, cheque? }] (1–50) }`.
  - `cash`/`petty`/`bank`: `money_account_id` of that type; `fee` = bank fee (receive: account gets amount − fee).
  - `cheque` new: `cheque: { number, due_date, issue_date?, sayad_id?, bank_name?, branch?, note? }` (receive → received cheque, pay → issued cheque). Pay may instead spend an existing received cheque with `cheque_id` (amount must equal the cheque).
  - `party`: offset against another party (`party_id`). `account`: any postable ledger account.
  - Errors: `unbalanced` (`items_total, methods_total, remaining`), `bad_item`, `bad_method`, `bad_fee`, `bad_cheque`, `cheque_party_required`, `cheque_amount_mismatch`, `same_party`, `control_account`, `over_payment`, `insufficient_funds`, `duplicate_number`.
- `PUT /payment-documents/{id}` same body without `kind` (full reverse + re-apply; `cheque_progressed` if a cheque it created has moved on). `DELETE /payment-documents/{id}`.

```json
POST /payment-documents
{ "kind": "receive", "date": "2026-11-13", "external_ref": "erp:rcpt:88",
  "items": [ { "party_ref": "woo:customer:77", "amount": 3000000, "invoice_ref": "woo:order:10452" }, { "party_id": 21, "amount": 1500000 } ],
  "methods": [ { "method": "bank", "money_account_id": 2, "amount": 3000000, "fee": 5000, "reference": "TRX-88123" },
               { "method": "cheque", "amount": 1500000, "cheque": { "number": "441209", "due_date": "2026-12-20" } } ] }
→ 201 { "id": 9, "kind": "receive", "number": 4, "total": 4500000, "external_ref": "erp:rcpt:88", "entry": { "id": 1203, "number": 877 },
        "items": [ … ], "methods": [ … ], "items_total": 4500000, "methods_total": 4500000, "remaining": 0, "fees_total": 5000 }
```

### 8.5 Cheques — `treasury.read` / `cheques.write`
Statuses: `pending` (in hand), `deposited` (in collection), `cleared`, `bounced`, `spent` (endorsed to another party).
- `GET /cheques` (list; query `type` received|issued, `status, party_id, from, to` (due date), `q, tab` normal|overdue|in_collection|collected|returned|spent, `number, sayad_id`). `GET /cheques/{id}` (with `events`), `GET /cheques/by-ref/{ref}`, `GET /cheques/summary` → `{ tabs:{<tab>:{count, amount}}, labels, statuses }`.
- `POST /cheques` `{ type, party_id, number, amount, issue_date, due_date, bank_name?, branch?, sayad_id?, money_account_id? (issued), invoice_id?, note?, external_ref?, metadata? }`. Received → party −amount; issued → party +amount; no cash moves yet.
- `POST /cheques/{id}/deposit` `{ money_account_id (bank), date, note? }` → `deposited`.
- `POST /cheques/{id}/clear` `{ money_account_id, date }` (for a deposited cheque the deposit bank is used) → `cleared`.
- `POST /cheques/{id}/bounce` `{ note?, date? }` → `bounced`; the creation effect is reversed and the invoice link removed.
- `POST /cheques/{id}/spend` `{ party_id, date, note? }` → `spent` (received, pending only).
- `POST /cheques/{id}/revert` `{ note? }` — one step back (deposited → pending, cleared → previous, spent → pending, bounced → previous). `POST /cheques/{id}/undeposit` = revert of a deposited cheque only.
- `POST /cheques/{id}/reschedule` `{ due_date, note? }`. `DELETE /cheques/{id}` (refused with `in_document` for cheques of a payment document).
- `PUT /cheques/{id}` `{ number?, sayad_id?, bank_name?, branch?, due_date?, note? }` corrects a cheque's details in any status (omitted keys stay). The amount, issue date, type and party cannot change (`422` on `amount` if it differs; delete and re-create instead). For a cheque of a payment document only `sayad_id, bank_name, branch, note` (`in_document` otherwise). `period_closed` when the old or new due date, or (for a new number) one of the cheque's journal entries, is in a closed period. A new number is written into the descriptions of the cheque's journal entries; the change is logged as an `edited` event. Returns the cheque with `events`.

### 8.6 Loans (received facilities) — `treasury.read` / `treasury.write`
- `GET /loans` (page; query `status` active|settled, `lender_party_id, q`) → loan + `lender, money_account, total_payable, principal_paid, principal_remaining, interest_paid, interest_remaining, paid_count, remaining_count, overdue_count, next_installment`. `GET /loans/{id}` → + `installments:[{number, due_date, principal, interest, amount, paid, paid_at, overdue, days_left}]`. `GET /loans/installments/due?days=30` → `{ days, installments, total, overdue_count, overdue_total }`.
- `POST /loans/schedule` (`treasury.read`, writes nothing) — same body as create → `{ installments, principal_total, interest_total, total }`.
- `POST /loans` `{ title, money_account_id, date, amount, interest_rate?, installments_count?, period_months?, first_due_date?, lender_party_id?, note?, installments?: [{due_date, principal, interest?}] }` → `201`; the amount enters the money account. `PUT /loans/{id}`, `DELETE /loans/{id}`.
- `POST /loans/{id}/installments/{n}/pay` `{ money_account_id, date, interest? }`, `POST /loans/{id}/installments/{n}/unpay`, `POST /loans/{id}/settle` `{ money_account_id, date, interest? }` (pays all remaining principal).

### 8.7 Tools
- `POST /tools/due-average` (`treasury.read`, writes nothing) `{ items: [{amount, due_date}] (1–1000), base_date? }` → `{ base_date, average_date, days, total, count, items }` (weighted average due date, راس‌گیری).

### 8.8 Multi-currency (optional module) — `treasury.read` / `treasury.write`
The business must have the module switched on (panel settings → «چندارزی»). When it is off, **any** non-empty `currency`, `rate` or `fx_*` field in a write body is rejected with `422 multi_currency_disabled` (send `currency: null` or omit the keys). Base currency is always Toman and has no currency row.
- **Foreign amounts are integers in the currency's smallest unit** (`decimals` of the currency: cents for USD with `decimals: 2`, so `1250` = 12.50 USD). A **rate** is Toman per 1 unit (up to 6 decimals, e.g. `62000` or `"61234.5"`). Toman = round_half_up(fx × rate ÷ 10^decimals). Every regular amount column (`total`, `amount`, `balance`, …) stays in Toman, so reports work unchanged; the `fx_*` columns carry the foreign figures.
- `GET /currencies?date` → `{ enabled, date, data: [{id, code, name, symbol, decimals, is_active, rate, rate_date, in_use}] }` (`rate` = latest rate on/before `date`). `POST /currencies` `{ code (ISO, 3 letters), name, symbol?, decimals? (0–4, default 2), is_active?, rate? }` → `201`. `PUT /currencies/{id}` same body (code and decimals are fixed once used: `currency_in_use`). `DELETE /currencies/{id}` only when unused.
- `GET /currencies/{id}/rates?from&to` → `{ currency, data: [{id, date, rate}] }` newest first. `POST /currencies/{id}/rates` `{ date, rate }` → `201` (one rate per day; same day replaces). `DELETE /currencies/{id}/rates/{rateId}`.
- `GET /exchange-rates/latest?date` → `{ date, rates: { USD: {rate, date} } }`. `POST /exchange-rates` `{ date, rates: { USD: 62000, EUR: 68000 } }` → `{ date, data }` (quick daily entry for several currencies).
- **Documents:** a money account may have `currency` (set on create, or later only while it has no movement; opening balance must be 0). Invoices take `currency` + optional `rate` (default: latest rate on/before the invoice date) and their amounts in `items[].fx_unit_price`, `items[].fx_discount`, `fx_discount`, `fx_shipping`, `extras[].fx_amount`; VAT is computed on the Toman amount and `fx_tax` is its equivalent. Transactions (`POST /transactions`, `POST /invoices/{id}/payments`) take `fx_amount` (+ `rate`, `fx_fee` for a foreign source account, `to_fx_amount` for a transfer into another currency) and return `amount` (Toman), `settled_amount` and `fx_gain_loss`. Payment documents take `currency`, `rate`, `items[].fx_amount`, `methods[].fx_amount`, `methods[].fx_fee`. Settling a foreign invoice posts the realized difference to the system account «سود و زیان تسعیر ارز» (`fx_gain_loss`). Quotes, installments, loans, payroll, discount codes, production and cheques are Toman-only (`422 currency_not_supported`); any other operation on a foreign money account gets `422 foreign_money_account`.

## 9. Endpoints: parties, products and stock

### 9.1 Parties — `parties.read` / `parties.write`
- `GET /parties` (list) — query `q` (name, alias, company, code, mobile, national code), `type` customer|supplier, `tab` customers|suppliers|both|employees|shareholders|no_transactions|inactive, `category_id` (or `none`), `status` debtor|creditor, `all=1` (plain array, max 2000), exact `code, mobile, national_code, email`, plus §5. Item: party row + `balance, category_name`.
- `GET /parties/{id}` → `{ party:{…, balance, category_name, share_url}, credit:{credit_limit, balance, remaining, exceeded}, bank_accounts, statement:[{date, description, debit, credit, balance, source_type, source_id}], open_invoices, pending_cheques }`.
- `POST /parties` body: `name` (2–120), `type`, `mobile?`, `email?`, `national_code?`, `address?`, `note?`, `kind?` person|company, `economic_code?`, `postal_code?` (10 digits), `price_level_id?`, `opening_amount?` + `opening_type?` debtor|creditor, `code?` (empty = automatic), `company?`, `title?`, `alias?`, `category_id?`, `credit_limit?` (null = unlimited), `registration_no?`, `branch_code?`, `phone?`, `phone2?`, `phone3?`, `fax?`, `website?`, `country?`, `province?`, `city?`, `is_employee?`, `taxpayer_status?` (5 registered in the tax system, 6 article-81 persons, 7 not required to register, 8 final consumer), `birth_date?`, `wedding_date?`, `membership_date?` (defaults to the creation day), `external_ref?`, `metadata?` → `201` party with `balance`. For a company, `first_name`/`last_name`/`title` are its contact person.
- `PUT /parties/{id}` full replace, `PATCH /parties/{id}` partial (§6.4), `PUT /parties/by-ref/{ref}` and `PUT /parties/by-code/{code}` upsert, `POST /parties/batch` (§6.5), `GET /parties/by-ref/{ref}`, `GET /parties/by-code/{code}`.
- `DELETE /parties/{id}` — only when balance is 0, no pending cheques and not a shareholder.
- `GET /parties/tabs` → counts per tab `{ all, customers, suppliers, both, employees, shareholders, no_transactions, inactive }`. `GET /parties/next-code` → `{ code }`. `GET /parties/duplicates` → `{ groups:[{field, value, parties}], total }`.
- `POST /parties/{id}/share` → `{ public_token, link }` (public read-only statement page); `DELETE /parties/{id}/share` revokes it.
- `POST /parties/{id}/merge` `{ into_id }` — moves every reference to `into_id` and deletes this party → `{ party, merged_id, moved }`.
- Bank accounts: `GET /parties/{id}/bank-accounts`, `POST /parties/{id}/bank-accounts` `{ bank_name?, account_number?, card_number? (16 digits), sheba? (IR + 24 digits) }`, `PUT /parties/{id}/bank-accounts/{accountId}`, `DELETE /parties/{id}/bank-accounts/{accountId}`.
- Categories: `GET /party-categories` (with `parties_count`), `POST /party-categories` `{ name }`, `PUT /party-categories/{id}`, `DELETE /party-categories/{id}` (parties become uncategorized).
- Shareholders: `GET /shareholders` → `{ shareholders:[{id, name, share_percent, capital_share, capital_balance, current_balance, balance}], total_percent, capital_total }`; `PUT /shareholders` `{ shareholders: [{party_id, share_percent}] }` (must total 100).
- `POST /parties/balance-document` (`journal.write`) `{ party_ids?, date, account_id, description?, dry_run? }` — one manual voucher that zeroes the selected parties' balances against `account_id`.

### 9.2 Products — `products.read` / `products.write`
- `GET /products` (list) — query `q`, `barcode` (exact barcode or sku), exact `code, sku`, `warehouse_id`, `low=1`, `category_id` (with descendants, or `none`), `active` 1|0, `kind` goods|service, `no_transactions=1`, `all=1` (array, max 5000, active only unless `include_inactive=1`), plus §5. Item: product row + `stock, prices, tiers, category_name, last_purchase:{invoice_id, number, date, party_id, party_name, unit_price}, last_price_change_date`.
- `GET /products/{id}` → `{ product, warehouses:[{id, name, stock}], kardex:[{date, type, warehouse, qty, unit_cost, value, balance, source_type, source_id, note}] }`.
- `POST /products` body: `name` (1–150), `sku?`, `barcode?` (several separated by `;`, each unique), `unit?`, `unit2?` + `unit2_ratio?`, `is_service?`, `sale_price?`, `purchase_price?`, `min_stock?`, `tax_code?` (13 digits), `tax_unit?`, `tax_percent?` (own VAT rate), `code?` (empty = automatic), `category_id?`, `is_active?`, `sale_description?`, `purchase_description?`, `track_serial?`, `prices?`, `tiers?` (§9.5), `opening_qty?` + `opening_warehouse_id?` (booked at `purchase_price`), `external_ref?`, `metadata?`.
- `PUT /products/{id}` (omitted keys unchanged; `null` clears only the optional descriptive fields), `PATCH /products/{id}` (same without requiring `name`), `PUT /products/by-ref/{ref}` and `PUT /products/by-sku/{sku}` upsert, `POST /products/batch` (§6.5), lookups `GET /products/by-ref/{ref}`, `GET /products/by-code/{code}`, `GET /products/by-sku/{sku}`, `GET /products/by-barcode/{barcode}`.
- `DELETE /products/{id}` (stock must be 0). `GET /products/next-code`, `GET /products/duplicates`, `GET /products/{id}/price-history` → `[{date, at, field, old, new, bulk}]`.
- `POST /products/bulk-price` `{ product_ids? | category_id? | all?, field: "sale_price"|"purchase_price", mode: "percent"|"amount", value, round_to?, dry_run? }` → `{ count, changed, items:[{id, name, old, new, diff}] }`.
- `POST /products/barcodes` `{ product_ids?, category_id?, prefix?, counter_start?, dry_run? }` — internal EAN-13 for products without a barcode. `POST /products/barcodes/remove` `{ product_ids }`.
- `POST /products/{id}/adjust` `{ warehouse_id, qty (signed), note? }` (valued at average cost). `POST /products/{id}/transfer` `{ from_warehouse_id, to_warehouse_id, qty }`.
- Categories (tree): `GET /product-categories` (flat with `path, depth, products_count`; `?tree=1` nested), `POST /product-categories` `{ name, parent_id? }`, `PUT /product-categories/{id}`, `DELETE /product-categories/{id}`.

### 9.3 Warehouses — `products.read` / `products.write`
`GET /warehouses`, `POST /warehouses` `{ name, address? }`, `PUT /warehouses/{id}`, `DELETE /warehouses/{id}` (only without movements; the last warehouse cannot be deleted).

### 9.4 Stock levels — `products.read`
- `GET /stock` → `{ warehouses, products:[{id, name, sku, code, barcode, external_ref, unit, is_service:false, sale_price, purchase_price, avg_cost, min_stock, stock, by_warehouse:{<warehouse_id>: qty}, value, last_purchase:{date, unit_price, party_id, party_name}|null, warehouse_stock?}], total_value, pagination? }`.
- Filters (each ≤ 2000 values, comma separated): `product_ids, codes, skus, barcodes, external_refs`; `warehouse_id` (products that moved in that warehouse, plus `warehouse_stock`); `updated_since` (products with a stock movement written since then). `page`/`per_page` paginate only when `page` is sent. `total_value` sums the returned rows.
- `POST /stock/query` — the same with arrays in a JSON body (writes nothing): `{ "skus": ["A1","A2"], "warehouse_id": 1 }`.

### 9.5 Pricing — `products.read` / `products.write`
- `GET /price-levels`, `POST /price-levels` `{ name }`, `PUT /price-levels/{id}`, `DELETE /price-levels/{id}`.
- Products carry `prices: [{price_level_id, price}]` and `tiers: [{min_qty, price}]`; send them in POST/PUT (omit = unchanged, `[]` = clear).
- `GET /products/{id}/price?party_id=&qty=` → `{ base_price, level_price, tier, price, rule: "base"|"level"|"tier" }`. The server does not force prices on invoices; send `unit_price` yourself.

### 9.6 Stock documents — `products.read` / `products.write`
Types (`GET /stock-documents/types`): `receipt` (in, at your `unit_cost`), `issue` (out at average cost), `waste`, `transfer` (`to_warehouse_id`), `count` (stock count: `counted_qty` per row, the difference is posted).
- `GET /stock-documents` (list; query `type, from, to, warehouse_id, product_id, q, number`), `GET /stock-documents/{id}`, `GET /stock-documents/by-ref/{ref}`.
- `POST /stock-documents` `{ type, date, warehouse_id, to_warehouse_id?, party_id?, project_id?, account_id? (counter account), description?, external_ref?, metadata?, items: [{ product_id | sku | product_code | barcode | product_ref, qty?, unit_cost?, counted_qty?, description? }] (1–1000) }` → `201`. `PUT /stock-documents/{id}` (same body without `type`; later costs are recomputed), `DELETE /stock-documents/{id}`.
- `POST /stock-documents/count/prepare` `{ warehouse_id, category_id?, q?, product_ids?, only_in_stock? }` → book quantities to count. `POST /stock-documents/cost-preview` `{ warehouse_id, items:[{product_id, qty}] }` → the cost an issue would use. Both write nothing.
- `GET /reports/stock-turnover?from&to&warehouse_id&category_id&q` → `{ products:[{product_id, name, opening_qty, opening_value, in_qty, in_value, out_qty, out_value, closing_qty, closing_value}], totals }`.

```json
POST /stock-documents
{ "type": "receipt", "date": "2026-11-13", "warehouse_id": 1, "external_ref": "wms:grn:771",
  "items": [ { "sku": "TSHIRT-M-BLK", "qty": 40, "unit_cost": 310000 } ] }
→ 201 { "id": 14, "type": "receipt", "number": 3, "total_value": 12400000, "journal_entry_id": 1311, "items": [ { "product_id": 44, "qty": 40, "unit_cost": 310000, "value": 12400000 } ] }
```

## 10. Endpoints: invoices, quotes, projects, salesmen, accounting

### 10.1 Invoices — `invoices.read` / `invoices.write`
- `GET /invoices` (list) — query `type, party_id, status` open|unpaid|partial|paid|overdue|draft|approved|returned (an approved return references it)|api (created with an API key), `state` draft|approved, `project_id, salesman_id, from, to, q`, party filters `city, party_category_id`, `channel` panel|api|pos, exact `number, reference`, `expand=items` (rows inline; `per_page` capped at 50), plus §5. Item includes `party:{id, name, city, category_id, category}`.
- `GET /invoices/{id}` → `{ invoice:{…, items:[…], party, warehouse}, ref, returns, transactions, cheques }`. Lookups: `GET /invoices/by-ref/{ref}`, `GET /invoices/by-number/{type}/{number}`.
- `POST /invoices` body:
  | field | required | notes |
  |---|---|---|
  | type | yes | sale \| purchase \| sale_return \| purchase_return |
  | date | yes | |
  | party_id | yes* | or `party_code` / `party_ref` / inline `party` (below) |
  | warehouse_id | yes | |
  | items | yes | 1–300 rows: `{ product_id (or sku/product_code/barcode/product_ref), qty, unit_price, discount?, description?, tax_percent? }` |
  | status | no | `approved` (default) \| `draft` |
  | number | no | manual number; omitted = next number of that type. Taken → `422 duplicate_number` |
  | due_date, note, reference (≤60), title (≤120) | no | |
  | discount, tax_percent | no | invoice-level discount (Toman) and VAT rate |
  | shipping | no | added to the total |
  | extras | no | ≤ 10 rows `{ title, amount }` (signed: + addition, − deduction) |
  | project_id, salesman_id, commission_percent | no | salesman for sales/returns only |
  | ref_invoice_id | no | returns only: the original invoice of the SAME party |
  | payment | no | `{ amount, money_account_id, fee?, reference? }` immediate settlement (a draft with a payment → `422 draft_payment`) |
  | external_ref, metadata | no | §6.1 |
  | discount_code | no | sale invoices only: a discount code (§10.2b). The server validates it and adds its amount to the row discounts (product/category codes) or to the invoice discount (whole-invoice codes) before VAT. `discount` and `items[].discount` stay your manual discounts. On `PUT`, omit it to keep the current code, send `null` to remove it. Response: `discount_item_id`, `code_discount` (total from the code; already inside `discount`/row `discount`), row `code_discount`. Errors: `422 bad_discount_code` |
  Totals are computed server-side: row total = round(qty × unit_price) − row discount; `net = subtotal − discount`; VAT on net (per-row rate when given); `total = net + tax + shipping + extras_total`.
- **Inline party (guest checkout):** instead of `party_id` send `party: { match_on?, …party fields }`. `match_on` ∈ `external_ref | mobile | national_code | code` (default: the first of those present). Found → used as is (not modified). Not found → created in the same transaction (`type` defaults to customer for sales, supplier for purchases); this needs `parties.write` on the key as well, else `403 insufficient_scope`.
- `PUT /invoices/{id}` — same body without `type`/`payment`; fully re-applies stock and ledger at the invoice's original place in history (`has_returns`, `party_locked`, `paid_more`, `insufficient_stock`). A draft with `status: "approved"` is approved.
- `PATCH /invoices/{id}` — §6.4. `POST /invoices/{id}/approve` approves a draft (`not_draft`). `DELETE /invoices/{id}` reverses everything; linked settlements stay as on-account entries.
- `GET /invoices/{id}/pdf` (`?official=1` → official tax-invoice layout). `POST /invoices/{id}/send` `{ channel: "sms"|"email", to? }` → `{ ok, channel, to, link }`.
- `POST /invoices/{id}/payments` (`payments.write`) `{ money_account_id, amount? (default: the whole remaining), date? (default today), fee?, reference?, note?, project_id?, external_ref?, metadata? }` → `201 { transaction, invoice: { id, paid_amount, remaining } }` — a receipt for sale/purchase_return, a payment for purchase/sale_return (`nothing_to_pay`, `bad_invoice` on drafts, `over_payment`). `fee` is the bank/gateway commission: the account receives amount − fee, the party is credited the full amount and the fee goes to bank charges. `GET /invoices/{id}/payments` → `{ invoice:{id, type, number, total, paid_amount, remaining, external_ref}, transactions, cheques, payment_documents }`.
- `POST /invoices/{id}/share` → `{ public_token, link }`: the public read-only invoice page, without sending anything (repeat calls return the same link). `DELETE /invoices/{id}/share` revokes it (links already sent stop working).

```json
POST /invoices   (Idempotency-Key: order-10452)
{ "type": "sale", "date": "2026-11-15", "warehouse_id": 1, "external_ref": "woo:order:10452", "tax_percent": 10,
  "party": { "match_on": "mobile", "name": "Sara Ahmadi", "mobile": "09121234567", "external_ref": "woo:customer:77" },
  "items": [ { "sku": "TSHIRT-M-BLK", "qty": 2, "unit_price": 450000 } ], "shipping": 50000,
  "payment": { "amount": 1040000, "money_account_id": 2 } }
→ 201 { "id": 512, "type": "sale", "number": 1041, "party_id": 77, "subtotal": 900000, "tax": 90000, "shipping": 50000,
        "total": 1040000, "paid_amount": 1040000, "remaining": 0, "external_ref": "woo:order:10452", "items": [ … ] }
```

### 10.2 Quotes, projects, salesmen — `invoices.read` / `invoices.write`
- Quotes have NO effect on stock or balances until converted. `GET /quotes` (list; query `status, party_id, q, number`), `GET /quotes/{id}`, `GET /quotes/by-ref/{ref}`, `GET /quotes/{id}/pdf`. `POST /quotes` `{ date, valid_until?, party_id, items:[{product_id, qty, unit_price, discount?, description?}], discount?, tax_percent?, note?, external_ref?, metadata? }`; `PUT /quotes/{id}` (not once converted); `PUT /quotes/{id}/status` `{ status: draft|sent|accepted|rejected }`; `DELETE /quotes/{id}`; `POST /quotes/{id}/send` `{ channel, to? }`; `POST /quotes/{id}/convert` `{ date?, due_date?, warehouse_id?, payment?, status?: approved|draft, project_id?, salesman_id?, reference?, title? }` → `201` the new sale invoice (`422 converted` the second time).
- Projects (cost centres; tag invoices, transactions, vouchers, payment and stock documents): `GET /projects?active&q` (array with `income, expense, net`), `GET /projects/{id}`, `POST /projects` `{ name, code?, is_active?, note? }`, `PUT /projects/{id}`, `DELETE /projects/{id}` (`in_use`), `GET /projects/{id}/card?from&to` (`reports.read`).
- Salesmen: `GET /salesmen?active&q`, `GET /salesmen/{id}`, `GET /salesmen/next-code` → `{ code }`, `POST /salesmen` `{ name, code? (empty = next code), party_id?, sale_commission?, return_commission?, fixed_sale_amount?, fixed_return_amount?, ignore_item_discount?, ignore_extras?, post_commission?, is_active?, note? }`, `PUT /salesmen/{id}`, `DELETE /salesmen/{id}`, `GET /reports/sales-by-salesman?from&to&salesman_id&details=1` (`reports.read`).

### 10.2b Discount codes and installment sales — `invoices.read` / `invoices.write` (receipts: `payments.write`)
- **Discount codes** (sales only): `GET /discounts` (page; query `q, type, status` active|inactive|expired) → rows with `usage_count, last_used_at, discount_total, state` (active|inactive|expired|scheduled|used), `product, category`. `GET /discounts/{id}` → + `uses:[{invoice_id, number, amount, date}]`. `POST /discounts` `{ title, code (letters/digits/-/_; unique, case-insensitive), type: invoice|product|category, product_id? (type product), category_id? (type category, includes sub-categories), percent? | amount? (exactly one), from_date?, to_date?, one_time?, is_active?, description? }` → `201`; `PUT /discounts/{id}`; `DELETE /discounts/{id}` (`in_use` once used: deactivate instead). `POST /discounts/check` `{ code, date?, invoice_id?, discount?, items:[{product_id, qty, unit_price, discount?}] }` → `{ discount_item, amount, invoice, lines }` (writes nothing; same validation as the invoice). Apply a code with `discount_code` on `POST/PUT /invoices` (§10.1). One-time codes are locked per request, so two parallel invoices cannot both use one; deleting the invoice frees the code.
- **Installment sales** (فروش اقساطی). An agreement turns the unpaid balance of one customer's approved sale invoices (`source: "invoices"`, `invoice_ids`) — or an amount the person already owes (`source: "party"`, `amount`) — into installments with interest. Principal = base − `down_payment`. The interest is posted as deferred income (contra-receivable 1305) and recognised as income (4150) when each installment is received; the customer's receivable grows by the interest. The principal part of the down payment and of received installments settles the agreement's invoices (oldest first).
- `GET /installments` (page; query `status` active|overdue|settled|cancelled, `party_id, q, from, to, sort` date|number|-number|total|-total) → agreement + `party, invoices, received_total, remaining_total, paid_count, remaining_count, overdue_count, bounced_count, next_installment`. `GET /installments/summary` → `{ counts:{'', active, overdue, settled, cancelled}, total, received, remaining, overdue_total }`. `GET /installments/next-number` → `{ number }`. `GET /installments/invoices?party_id&except` → the customer's invoices that can go into an agreement. `GET /installments/{id}` → + `installments:[{number, due_date, principal, interest, amount, status, state (pending|overdue|paid|bounced|cancelled), paid_at, method, money_account, cheque, journal_entry_id}]`, `entries` (vouchers). `GET /installments/due?days=30` → `{ days, installments, total, overdue_count, overdue_total }`. `GET /installments/report?from&to&status&party_id&agreement_id` (installment status report; `status` also accepts `open`) → `{ rows, totals, counts, labels }`.
- `POST /installments/schedule` — same body as create, writes nothing → the computed agreement + `installments`. `POST /installments` `{ number?, date, party_id, source?: invoices|party, invoice_ids?, amount?, down_payment?, down_money_account_id? (required when down_payment > 0), method?: bank|market, payment_method?: cheque|online|other, installments_count (1–360), annual_rate?, period_days (3|5|7|10|14|15|20|21|30|45|60|90|120|150|180), rounding? (null or 0–5: round the installment to 10^n), first_due_date? (default: date + one period), guarantee?, note?, external_ref?, metadata? }` → `201`. `method: bank` = equal installments (annuity, interest on the declining balance); `market` = flat interest on the whole principal. Periodic rate = annual% × period_days ÷ 360. Periods that are multiples of 30 days fall on the same day of the Jalali month. All math is exact integer Toman; the last installment absorbs rounding. `PUT /installments/{id}` and `DELETE /installments/{id}` only while nothing is received (`has_receipts`). `POST /installments/{id}/cancel` `{ date?, note? }` cancels the open installments and removes their unearned interest from the customer; `POST /installments/{id}/restore` undoes it.
- `POST /installments/{id}/items/{n}/receive` `{ date, method: money|cheque, money_account_id? (money), cheque?: { number, due_date, sayad_id?, bank_name?, branch? } (cheque: a received cheque enters the normal cheque lifecycle), note? }`; `POST /installments/{id}/items/{n}/unreceive` (a cheque must still be pending or bounced: `cheque_in_progress`). Errors: `already_received`, `cancelled`, `invoice_in_agreement`, `bad_schedule`, `bad_down_payment`, `period_closed`.

### 10.3 Accounting core — `reports.read` / `journal.write`
Every operation posts its own balanced voucher. Use this only for adjustments, capital, accruals, corrections and closing.
- **Chart of accounts** (group digit → general → subsidiary): `GET /accounts/tree` → `{ groups:[{digit, name, type, debit, credit, balance, accounts:[node]}], other }`; node = `{ id, code, name, type, nature, level, parent_id, system_key, is_system, is_money, is_control, needs_party, party_mode, is_active, allow_posting, mapped_keys, own_debit, own_credit, debit, credit, balance, children }` (`party_mode`: `required` receivable/payable, `optional` partners' current, employee advances, salaries payable, loans payable and sub-accounts of these, `null` no party allowed; `mapped_keys` = default-account keys currently mapped to this account). `GET /accounts/export?format=xlsx|pdf` downloads the chart with turnover and balances. `POST /accounts` `{ name, type?, parent_id?, code? }`, `PUT /accounts/{id}` `{ name, code?, is_active?, allow_posting? }` (inactive = no new manual vouchers and hidden from pickers; `allow_posting: false` = grouping-only account; existing turnover is untouched; system accounts and accounts used in the account map can't be switched off: `system_account` / `mapped_account`), `DELETE /accounts/{id}` (`system_account`, `has_children`, `in_use` incl. use in a draft voucher, `mapped_account`). `POST /accounts/merge` `{ source_id, target_id }` moves every voucher line, draft line and transaction/payment-document/stock-document reference of the source to the target and deletes the source (trial-balance totals unchanged) → `{ target, source_id, lines_moved, drafts_updated }`; source = non-system leaf account that is not cash/bank; target = same type, active, posting allowed, leaf, not control or cash/bank; party rules of the target must fit the source lines. Errors: `type_mismatch`, `system_account`, `money_account`, `has_children`, `control_account`, `inactive_account`, `party_not_allowed`, `party_required`, `period_closed` (source has turnover in a closed year).
- **Default accounts** (account map): `GET /account-map` → `{ items:[{ key, label, type, type_label, mappable, note, system, mapped, mapped_valid, account }] }` — the account automatic vouchers (invoices, receipts/payments, stock, payroll, assets …) post to for each use; `account` is the effective one. Only income/expense keys are `mappable` (sales, sales_returns, sales_discount, sale_extras, installment_income, other_income, cogs, expense_general, purchase_extras, inventory_adjust, waste, salaries, bank_fees, commission, finance_cost, depreciation, asset_loss); control, receivable/payable, VAT, payroll liabilities, cheques and equity keys are fixed (`note` says why). `PUT /account-map` `{ accounts: { key: account_id | null } }` — keys not sent stay as they are; `null` (or the system account's own id) resets to the default. The account must be of the same type, active and allow posting (`422 validation` with `errors["accounts.<key>"]`). Only new vouchers use the new account; existing ones stay where they were posted.
- **Journal vouchers:** `GET /journal-entries` (list; query `from, to, kind` (manual, auto or a kind), `q, account_id, project_id, number, locked` (1/0)), `GET /journal-entries/counts` (same filters → `{ "": all, manual, auto, locked }`), `GET /journal-entries/kinds`, `GET /journal-entries/next-number` → `{ number }`, `GET /journal-entries/{id}` (each line's `account.path` = [group, general account] above the account name), `GET /journal-entries/by-ref/{ref}`, `GET /journal-entries/export?format=xlsx|pdf` (list with the same filters), `GET /journal-entries/{id}/export?format=xlsx|pdf`. `POST /journal-entries` `{ date, description, number?, project_id?, external_ref?, metadata?, lines: [{ account_id | account_code, debit, credit, party_id? | party_code? | party_ref?, description? }] (2–200) }` → `201`; `number` omitted = next number, given = must be unique (`duplicate_number`). Rules: one of debit/credit > 0 per line (`bad_line`), Σ debit = Σ credit (`unbalanced`), no control accounts (`control_account`), receivable/payable lines need a party (`party_required`), a party is only allowed on accounts whose `party_mode` is not null (`party_not_allowed`), no money account may go negative. `PUT /journal-entries/{id}` replaces the lines (and `number` if sent); `DELETE /journal-entries/{id}`; only unlocked `kind: "manual"` vouchers (`auto_entry` / `entry_locked` otherwise). `POST /journal-entries/{id}/lock`, `POST /journal-entries/{id}/unlock`, `POST /journal-entries/lock` `{ ids, locked }` lock manual vouchers against edit/delete/merge. `POST /journal-entries/renumber` `{ fiscal_year_id }` renumbers an open year's vouchers by date (then id) → `{ changed, total, first, last }` (`period_closed` for a closed year). `POST /journal-entries/{id}/copy` → `201` new manual voucher dated today. `POST /journal-entries/merge` `{ ids (2–200 manual, unlocked, same date), description? }` merges them.
  Draft vouchers: send `status: "draft"` on `POST`/`PUT /journal-entries` to save a manual voucher without touching the books — no ledger lines, no effect on any balance or report; it may be unbalanced and have 1+ lines (only accounts/parties must exist and amounts be ≥ 0). Drafts get a number from the same sequence and keep it when approved. Every voucher has `status` (`approved` | `draft`) and `status_label`; `GET /journal-entries/{id}` of a draft returns its lines (`id: null`) and `balanced`. List/counts/export accept `status=draft|approved` (`counts` adds `draft`, `approved`; `account_id` also finds drafts). `POST /journal-entries/{id}/approve` runs every manual-voucher rule (balanced, ≥ 2 lines, control accounts, parties, `inactive_account`, `posting_not_allowed`, open period, cash/bank not negative) and posts it (`not_draft` if already approved); `POST /journal-entries/approve` `{ ids }` approves several all-or-nothing (the error message names the failing voucher number, plus `entry_id`) → `{ approved, ids, numbers }`. `PUT` without `status` keeps the current status; `PUT` with `status: "approved"` approves a draft, with `status: "draft"` takes an approved manual voucher back off the books. Drafts can't be locked or merged (`draft_entry`), and a fiscal year with drafts can't be closed (`has_drafts`). Manual vouchers reject inactive accounts (`inactive_account`) and accounts with posting switched off (`posting_not_allowed`).
- **Fiscal years:** `GET /fiscal-years` → `{ locked_until, years:[{id, title, start_date, end_date, status, net_profit, closing_entry_id, closed_at}] }`. `GET /fiscal-years/current` → the year containing today (+ `locked_until`), or `404` when none is defined. Reports take plain `from`/`to`; use the year's `start_date`/`end_date`. `POST /fiscal-years` `{ title, start_date, end_date }`; `PUT /fiscal-years/{id}` (same body, open years only: no overlap `overlap`, not on/before `locked_until` `period_closed`). `GET /fiscal-years/{id}/closing-preview` → `{ accounts, total_income, total_expense, net_profit, shareholders, distribution, can_close, blocker, next_year }`. `POST /fiscal-years/{id}/close` `{ distribution?: [{party_id, percent}], retain_percent?, next_year?: {title?, start_date, end_date} }` posts the closing voucher and moves the lock. `POST /fiscal-years/{id}/reopen` (latest closed year only). `DELETE /fiscal-years/{id}` (open years only).
- **Opening balance:** `GET /opening-balance` → the opening position as a balance sheet with `manual.lines` and `selectable_accounts`; `GET /opening-balance/history`; `PUT /opening-balance` `{ date?, lines: [{account_id, debit?, credit?, party_id?}] }` replaces the «other accounts» opening voucher (difference goes to opening equity). Cash/bank, parties and products get their opening amounts from their own resources.
  Opening cheques: `POST /opening-balance/cheques` `{ kind: on_hand | in_collection | issued, party_id, number, amount, due_date, sayad_id?, bank_name?, branch?, issue_date?, money_account_id? (bank; required for in_collection), note?, date? (opening date) }` → `201` + the position. It creates a real cheque (`on_hand`: received, pending; `in_collection`: received, deposited to that bank; `issued`: issued, pending) posted against opening equity (kind `opening`; in-collection cheques also get a same-day `deposit` voucher), so it continues its normal life in `/cheques` (clear, bounce, spend, revert …). Party balances don't change. `PUT /opening-balance/cheques/{id}` (same body) re-posts it and `DELETE /opening-balance/cheques/{id}` removes it — only while nothing else happened to the cheque (`cheque_in_progress`; `not_opening_cheque` for ordinary cheques). `GET /opening-balance` lists them in `cheques:[{ id, kind, kind_label, type, status, status_label, party_id, party_name, number, sayad_id, bank_name, branch, amount, issue_date, due_date, date, money_account_id, money_account_name, editable }]` and counts them in `assets.cheques_receivable`, `assets.cheques_in_collection` and `liabilities.cheques_payable`.

## 11. Moodian (Iranian e-invoicing) — `invoices.read` / `moodian.manage`
Needs the `moodian` plan feature (from «طرح دو» up; `GET /me` → `plan.features.moodian`), otherwise every route here returns `402 plan_feature`. Only approved `sale` and `sale_return` invoices. The setup wizard (keys, certificate, settings) is done once in the web app; until then sends fail with `moodian_not_configured` (`gaps`).
- `GET /moodian/meta` → option lists (invoice types, subjects, settlement types, units, statuses, `limits`).
- `GET /moodian/invoices` (page + `counts`, `tabs`; query `tab` all|not_sent|sent|error|approved|canceled, `type, from, to, q`). Row: invoice + `tax_status, tax_id, invoice_type, pattern, subject, settlement, serial, submission:{status, invoice_status, attempts, …}, overrides`.
- `GET /moodian/invoices/{id}` → `{ invoice, sendable, submissions, preview, can:{send, retry, reissue, inquire, correct, cancel, …}, logs }`.
- `POST /moodian/invoices/send` `{ ids (1–50), queue_only?, reissue? }` → `{ summary:{total, ok, sent, failed}, results:[{id, ok, queued, sent, tax_id?, status, error?, message}] }` (per-invoice errors stay in `results`).
- `POST /moodian/invoices/inquire` `{ ids }` → `{ summary, results:[{id, ok, status, invoice_status, tax_status}] }`.
- `PUT /moodian/invoices/bulk` `{ ids, invoice_type?, pattern?, subject?, settlement?, serial?, reference_tax_id? }` — attributes for the NEXT submission (`null` = automatic) → `{ updated, invoices }`.
- `POST /moodian/invoices/{id}/retry` `{ reissue? }`, `POST /moodian/invoices/{id}/correct` `{ reference_tax_id?, queue_only? }` (corrective submission), `POST /moodian/invoices/{id}/cancel` `{ queue_only? }` → one result object.
- Statuses: submission `pending, sending, sent, success, failed, rejected, canceled`; authority `invoice_status` APPROVED, REJECTED, …

## 12. Reports and files — `reports.read` (and the read scope of each list)
Common query for most reports: `from`, `to`, `project_id`. Only approved invoices count.
- `GET /reports/catalog` → `[{group, title, reports:[{name, title, path, export}]}]` — the list of every report below.
- `GET /reports/dashboard` → `{ sales_today, sales_30d, purchases_30d, receivables, payables, cash, bank, inventory_value, profit_30d, sales_chart, low_stock, upcoming_cheques, due_invoices, recent_invoices }`.
- `GET /reports/trial-balance?from&to` → `{ rows:[{code, name, type, debit, credit, balance, opening_debit, opening_credit, balance_debit, balance_credit}], total_* }`; with `level` (group|general|subsidiary|detail) or `project_id` → level rows `{level, code, name, opening, debit, credit, closing, …}`.
- `GET /reports/profit-loss?from&to` → `{ from, to, income:[{name, key, amount}], expense:[…], net_sales, cogs, gross_profit, other_income, expenses, net_profit }`.
- `GET /reports/balance-sheet?to` → `{ until, assets:[{code, name, amount}], liabilities, equity, total_assets, total_liabilities, total_equity }`.
- `GET /reports/ledger?account_id&from&to&party_id` → `{ account, opening, party, lines:[{date, number, description, party, debit, credit, balance, entry_id}] }`; `party_id` (detail account) keeps only that party's lines, opening included. `GET /reports/journal?from&to&page` → paginated vouchers with lines.
- `GET /reports/aging?date` → `{ as_of, receivables:{rows, totals}, payables:{rows, totals} }`, row `{ party_id, name, total, current, d1_30, d31_60, d61_90, over_90, overdue, oldest_days }` (FIFO against due dates).
- `GET /reports/vat` (`from/to` or Jalali `year` + `season` 1–4) → `{ summary:{output_vat, input_vat, net_vat, payable, refundable, …}, ledger, sales, sales_returns, purchases, purchase_returns, seasons }`.
- `GET /reports/sales-by-product`, `GET /reports/purchases-by-product` (`party_id, category_id, salesman_id, warehouse_id, product_id` — salesman and warehouse of the invoice) → `{ rows:[{product_id, name, qty, net, vat, total, return_qty, net_qty, net_amount, cost?, gross_profit?, margin_percent?}], totals, filters:{party?, salesman?, warehouse?, product?, category?} }` (`filters` = names of the chosen filters).
- `GET /reports/sales-by-invoice`, `GET /reports/purchases-by-invoice` (`party_id, salesman_id, status, without_returns, page, per_page`) → `{ rows, totals, pagination }`. `GET /reports/sales-by-project?from&to&party_id&salesman_id` → `{ rows:[{project_id (null = بدون پروژه), name, invoices, sales, returns, net_sales, vat, total, cost, gross_profit, margin_percent}], totals }`. `GET /reports/invoice-profit` → `{ rows:[{id, number, net, cost, profit, margin_percent}], totals, unlinked_returns, pagination }`.
- `GET /reports/party-summary` → per party `{ opening, sales, sales_returns, purchases, purchase_returns, received, paid, other, balance }`. `GET /reports/debtors-creditors?date&type&party_category_id` → `{ as_of, debtors:{rows, count, total}, creditors, net, filters }` (row `{ party_id, name, code, mobile, category, last_date, amount }`).
- `GET /reports/cash-flow` → `{ opening_cash, total_inflow, total_outflow, net_change, closing_cash, categories, activities, accounts, reconciled }`. `GET /reports/capital` → equity changes per account.
- `GET /reports/explorer?level&parent`, `GET /reports/explorer-detail?party_id` (drill-down), `GET /reports/general-ledger?account_id`, `GET /reports/consolidated-journal?period=month|day`, `GET /reports/consolidated-ledger?account_id&period`.
- `GET /reports/money-statement?money_account_id`, `GET /reports/party-statement?party_id`, `GET /reports/party-card?party_id` (statement + invoice rows `items`, split into `items_sold` (sale + sale_return) and `items_bought` (purchase + purchase_return) with net `items_totals` + `cheques_received`, `cheques_paid` + `drafts`; its export has one sheet per tab, including the detailed statement with invoice items).

**Files** (return a file with `Content-Disposition: attachment`; `format=xlsx` default or `format=pdf`; Excel is right-to-left with Jalali dates):

| Endpoint | Scope | Content |
|---|---|---|
| `GET /reports/export/{name}` | reports.read | any report name from `GET /reports/catalog` (same query as its JSON route), plus `aging` |
| `GET /exports/invoices?type&status&from&to&party_id&city&party_category_id&channel&ids` | invoices.read | invoice list |
| `GET /exports/parties` | parties.read | parties with balances |
| `GET /parties/{id}/statement?from&to` | parties.read | one party's statement |
| `GET /exports/products` | products.read | stock and inventory value |
| `GET /exports/transactions?type&from&to&party_id&money_account_id&project_id&q&ids` | treasury.read | transactions (`money_account_id` matches source or destination) |
| `GET /exports/quotes?status&party_id&from&to&q&ids` | invoices.read | quotes (proforma invoices) |
| `GET /exports/cheques?type&status` | treasury.read | cheques |
| `GET /exports/stock-documents?type&from&to&warehouse_id&product_id&ids` | products.read | warehouse documents (receipt, issue, waste, transfer, stock count) |
| `GET /backup` | backup.read | full backup: an encrypted `.hcb` file that only Hesabchin can restore (as a NEW business); `?format=xlsx` = every table as an Excel sheet (the readable option) |

## 13. Payroll, fixed assets, imports and the change log

- **Payroll** (`payroll.read` / `payroll.write`): `GET /payroll/summary` → `{ salaries_payable, insurance_payable, tax_payable, advances, employees }`. `GET /payroll/employees`, `POST /payroll/employees` `{ name, base_salary, national_code? (10 digits), mobile?, position?, insurance_rate? (7), employer_insurance_rate? (23), hired_at?, is_active?, party_id? }`, `PUT /payroll/employees/{id}`. `party_id` links the employee to a contact (one contact per employee; `null` unlinks): salaries payable, advances and salary payments then carry that contact, so the employee's balance shows on the contact's account card (linking or changing it re-tags the employee's earlier payroll entries, except lines on/before the closed-period date; the response then has `retag: { retagged, skipped_locked, locked_until }`). Merging contacts moves the link to the surviving contact (422 `employee_conflict` if both are linked to different employees). `POST /payroll/employees/{id}/party` (no body) creates a contact from the employee's name, mobile and national code (`is_employee: true`) and links it → the employee with `party`. `GET /payroll/advances`, `POST /payroll/advances` `{ employee_id, amount, money_account_id, date, note? }`. `GET /payroll/payslips?period&year&employee_id`, `POST /payroll/payslips` `{ employee_id, period: "1405-08", date, days_worked?, base_salary?, overtime?, bonus?, housing_allowance?, food_allowance?, shift_pay?, mission_pay?, other_benefits?, child_allowance?, severance?, leave_buyout?, tax?, insurance?, advance_deduction?, loan_deduction?, note? }` (one per employee per period; insurance is computed on base + overtime + bonus + housing + food + shift + mission + other benefits; child allowance, severance and leave buyout are exempt; net = gross − employee insurance − tax − advance − loan; advance + loan ≤ the employee's outstanding advances), `POST /payroll/payslips/batch` `{ period, date, note?, slips: [{ employee_id, …same item fields… }] }` issues many employees' payslips at once (all or nothing; row errors come back as `slips.{index}.{field}`; ≤ 300 rows) → `{ count, slips }`, `PUT /payroll/payslips/{id}` (unpaid only, same body without `employee_id`), `POST /payroll/payslips/{id}/pay` `{ money_account_id, date }`, `DELETE /payroll/payslips/{id}` (unpaid only). `POST /payroll/remit` `{ kind: "insurance"|"tax", amount, money_account_id, date }`.
- **Fixed assets** (`assets.read` / `assets.write`): `GET /assets` → `{ assets:[{…, accumulated, book_value, status}], totals }`. `POST /assets` `{ name, purchase_date, cost, useful_life_months, salvage_value?, code?, note?, source: "cash"|"credit"|"opening", money_account_id?, party_id? }`. `POST /assets/depreciate` `{ until }` (idempotent per month). `POST /assets/{id}/dispose` `{ date, amount, money_account_id? }`. `DELETE /assets/{id}` (before any depreciation).
- **Excel import** (`parties.write` / `products.write`): `POST /imports/parties`, `POST /imports/products` — `multipart/form-data` field `file` (xlsx/xls/csv, ≤ 10 MB, ≤ 5000 rows), `?dry_run=1` to validate only. Columns are matched by Persian header text: parties «نام»*, «نوع», «حقیقی/حقوقی», «موبایل», «ایمیل», «کد ملی / شناسه ملی», «کد اقتصادی», «کد پستی», «نشانی», «مانده اول دوره», «سطح قیمت», «توضیح», «کد حسابداری», «شرکت», «عنوان», «نام مستعار», «دسته‌بندی», «سقف اعتبار», «شماره ثبت», «کد شعبه», «تلفن», «وب‌سایت», «استان», «شهر», «کارمند»; products «نام»*, «کد کالا», «بارکد», «واحد», «قیمت فروش», «قیمت خرید», «حداقل موجودی», «موجودی اول دوره», «انبار», «خدمت», «کد حسابداری», «دسته‌بندی», «واحد فرعی», «ضریب واحد فرعی», «شرح فروش», «شرح خرید», «درصد ارزش افزوده», «غیرفعال». All-or-nothing: `422 import_invalid` with `{ total, errors:[{row, name, errors}], preview }`; success `201 { imported }`. For JSON use the batch endpoints (§6.5).
- **Change log** (`audit.read`): `GET /audit-logs?event&subject_type&subject_id&user_id&from&to&q&page` → paginated `{ id, event, subject_type, subject_id, summary, data, ip, created_at, actor }` (`event` exact or a prefix ending in `.`). `GET /audit-logs/events` → `{ <event>: <Persian label> }`. `GET /audit-logs/export?format=xlsx|pdf` (same filters, ≤ 10000 rows). For machine sync prefer the changes feed (§7).

## 14. Webhooks — `webhooks.manage`

Instead of polling, subscribe to events. Each event is POSTed as JSON to your HTTPS URL.
- `GET /webhooks` → `{ events: {<event>: <label>}, webhooks: [...], deliveries: [last 30] }` — `events` is the authoritative list.
- `POST /webhooks` `{ url, events: ["invoice.created", …] | ["*"], is_active?, skip_own? }` → `201` including `secret` (`whsec_…`, shown ONCE — store it). Max 10 per business.
- `PUT /webhooks/{id}` `{ url, events, is_active?, skip_own? }`, `DELETE /webhooks/{id}`, `POST /webhooks/{id}/test` (sends a `ping` now and returns the delivery).
- `GET /webhooks/{id}/deliveries?status=pending|success|failed&page&per_page` → paginated deliveries `{ id, event_id, event, payload, status, attempts, response_code, error, delivered_at, next_attempt_at, created_at }`, newest first.
- `POST /webhooks/deliveries/{deliveryId}/retry` → sends that delivery again now (same `event_id` and body, attempts restart) and returns it; use it after fixing your endpoint, even when all 6 attempts were used. `422 already_queued` if it has not been tried yet.
- **`skip_own: true`**: events caused by any API key of this business are not delivered to that hook (only panel and system changes are). Use it to avoid echo loops when you both write to and listen to Hesabchin.

**Events:**
- `invoice.created` — Invoice created (also when a quote is converted)
- `invoice.updated` — Invoice edited, patched or approved
- `invoice.approved` — Draft invoice approved
- `invoice.deleted` — Invoice deleted
- `invoice.sent` — Invoice sent to the customer
- `invoice.payment_changed` — paid_amount of an invoice changed (receipt, payment, cheque, bounce, payment document, return offset, deletion)
- `invoice.paid` — remaining of an invoice reached 0
- `transaction.created` — Receipt/payment/expense/income/transfer/debt created
- `transaction.updated` — Transaction edited
- `transaction.deleted` — Transaction deleted
- `payment_document.created` — Payment document created
- `payment_document.updated` — Payment document edited
- `payment_document.deleted` — Payment document deleted
- `cheque.created` — Cheque registered
- `cheque.deposited` — Cheque deposited to a bank for collection
- `cheque.cleared` — Cheque cleared
- `cheque.bounced` — Cheque bounced
- `cheque.spent` — Received cheque endorsed to another party
- `cheque.reverted` — Cheque moved one step back
- `cheque.rescheduled` — Cheque due date changed
- `cheque.deleted` — Cheque deleted
- `party.created` — Party created
- `party.updated` — Party edited/patched
- `party.deleted` — Party deleted
- `party.merged` — Party merged into another
- `product.created` — Product created
- `product.updated` — Product edited/patched (price_changed: true when a price changed)
- `product.deleted` — Product deleted
- `stock.changed` — A product's quantity changed for any reason (one event per product per request)
- `stock.low` — Product reached its minimum stock
- `stock.adjusted` — Manual stock adjustment
- `stock.transferred` — Transfer between warehouses
- `stock_document.created` — Stock document created
- `stock_document.updated` — Stock document edited
- `stock_document.deleted` — Stock document deleted
- `quote.created` — Quote created
- `quote.updated` — Quote edited
- `quote.deleted` — Quote deleted
- `quote.converted` — Quote converted to an invoice
- `quote.sent` — Quote sent
- `journal.created` — Manual voucher created
- `journal.updated` — Manual voucher edited
- `journal.deleted` — Manual voucher deleted
- `project.created` — Project created
- `project.updated` — Project edited
- `project.deleted` — Project deleted
- `salesman.created` — Salesman created
- `salesman.updated` — Salesman edited
- `salesman.deleted` — Salesman deleted
- `money_account.created` — Cash/bank account created
- `money_account.updated` — Cash/bank account edited
- `money_account.deleted` — Cash/bank account deleted
- `loan.created` — Loan created
- `loan.updated` — Loan edited
- `loan.deleted` — Loan deleted
- `loan.installment_paid` — Loan installment paid
- `loan.installment_unpaid` — Loan installment payment reversed
- `loan.settled` — Loan settled early

**Payloads.** `data` is the same object the REST API returns for that resource, or a summary for deletions (`{ id, number?, name?, external_ref? }`). Special payloads:
- `stock.changed`: `{ id, product_id, name, code, sku, barcode, external_ref, stock, by_warehouse: {"1": 12, "2": 0}, cause: "invoice"|"stock_document"|"adjust"|"transfer"|"opening"|…, source_type, source_id, deleted }` — fired once per affected product after the request that moved stock commits, and only if the quantity really changed. This is the event a shop needs to keep its stock in step.
- `invoice.payment_changed`: `{ id, type, number, party_id, external_ref, total, paid_amount, remaining, previous_paid_amount }`; `invoice.paid`: the same without `previous_paid_amount`, when `remaining` reaches 0.

**Request your server receives:**
```
POST <your url>
Content-Type: application/json
X-Hesabchin-Event: invoice.created
X-Hesabchin-Delivery: evt_8f3k…          (same id on retries — use it to de-duplicate)
X-Hesabchin-Origin: api_key | user | system
X-Hesabchin-Signature: t=1763040000,v1=<hex HMAC-SHA256>

{ "id": "evt_8f3k…", "event": "invoice.created", "created_at": "…", "business_id": 12,
  "origin": { "type": "api_key", "api_key_id": 3 }, "data": { …same object the REST API returns… } }
```

**Verify every request** (reject if invalid, or if `t` is older than 5 minutes):
`expected = hex(HMAC_SHA256(secret, t + "." + raw_request_body))`, compared to `v1` in constant time. Use the RAW body bytes, never re-serialized JSON.

**Delivery rules:** answer `2xx` within 10 seconds (do the work asynchronously). Anything else is retried after 10s, 1m, 5m, 30m and 2h (6 attempts). Redirects are not followed. Only public HTTPS URLs are accepted. After 50 consecutive failures the webhook is disabled. Webhooks are part of the API and work on every plan.Order is not guaranteed; use `created_at`, and the changes feed (§7) as the safety net after downtime.

```js
import crypto from 'node:crypto';
function verify(rawBody, header, secret) {
  const { t, v1 } = Object.fromEntries(header.split(',').map((p) => p.split('=')));
  if (Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
  const expected = crypto.createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');
  return expected.length === v1.length && crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(v1));
}
```

## 15. Recipes

**A. Record an online order as a paid sale (one call)**
`POST /invoices` with `Idempotency-Key: order-<id>`, `external_ref: "woo:order:<id>"`, inline `party` (`match_on: "mobile"`), `items[].sku` and `payment` (example in §10.1). A retry after a timeout replays the response; a retry days later returns `409 duplicate_external_ref` with `existing_id` — treat both as success.

**B. Keep two systems in sync**
1. Initial load: `POST /products/batch` and `POST /parties/batch` with `match_on: "external_ref"`, then remember `GET /changes/latest`.
2. Ongoing: webhooks for `stock.changed`, `invoice.*`, `product.*`, `party.*` with `skip_own: true`.
3. Safety net (every few minutes and after downtime): `GET /changes?after=<last id>&origin=not_me`, then fetch the objects that changed.
4. Stock to your shop: `stock.changed` → set the shop quantity to `stock` (or `by_warehouse[<id>]`). Full reconciliation: `POST /stock/query` with your SKUs.

**C. Record an expense**
`POST /transactions` `{ "type":"expense", "date":"2026-11-13", "amount":450000, "money_account_id":1, "note":"Office internet" }`

**D. Customer pays an open invoice later**
`POST /transactions` `{ "type":"receipt", "date":"…", "amount":<≤ remaining>, "party_ref":"woo:customer:77", "money_account_id":2, "invoice_ref":"woo:order:10452", "external_ref":"zarinpal:A00012" }`

**E. Customer pays by cheque**
`POST /cheques` `{ "type":"received", "party_id":…, "number":"441209", "amount":…, "issue_date":"…", "due_date":"…", "invoice_id":… }` → later `/deposit`, `/clear` or `/bounce`.

**F. Refund / return**
`POST /invoices` `{ "type":"sale_return", "ref_invoice_ref":"woo:order:10452", "party_ref":"woo:customer:77", "warehouse_id":1, "items":[…returned rows…], "external_ref":"woo:order:10452" }` (a return may share its sale's ref).

**G. Point-of-sale with a barcode scanner**
`GET /products/by-barcode/<scanned>` → or send `items[].barcode` directly in `POST /invoices`.

**H. Push 5,000 price changes**
`POST /products/batch` in chunks of 500: `{ "match_on": "sku", "mode": "update", "atomic": false, "items": [ { "sku": "A1", "sale_price": 120000 }, … ] }`.

**I. Month-end and year-end**
`POST /assets/depreciate {"until":"<last day>"}`, payroll (`POST /payroll/payslips` → `/pay` → `POST /payroll/remit`), `GET /reports/profit-loss`; at year end `GET /fiscal-years/{id}/closing-preview` → `POST /fiscal-years/{id}/close`.

**J. Adjusting entry**
`POST /journal-entries` `{ "date":"2026-11-13", "description":"Accrued rent", "lines":[{ "account_code":"6105", "debit":12000000, "credit":0 }, { "account_code":"2101", "debit":0, "credit":12000000, "party_code":"000031" }] }`.

## 16. Example (Node.js, no dependencies)

```js
const BASE = 'https://hesabchin.ir/api/v1';
async function hesabchin(path, { method = 'GET', body, idempotencyKey } = {}) {
  const res = await fetch(BASE + path, {
    method,
    headers: {
      Authorization: `Bearer ${process.env.HESABCHIN_API_KEY}`,
      'Content-Type': 'application/json',
      Accept: 'application/json',
      ...(idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
  });
  const data = await res.json().catch(() => ({}));
  if (res.status === 429 || data.error === 'idempotency_in_progress') throw Object.assign(new Error('retry later'), { retryAfter: Number(res.headers.get('Retry-After') || 5) });
  if (res.status === 409 && data.error === 'duplicate_external_ref') return { duplicate: true, id: data.existing_id };
  if (!res.ok) throw Object.assign(new Error(data.message || res.statusText), { status: res.status, code: data.error, details: data.errors, requestId: res.headers.get('X-Request-Id') });
  return data;
}

const invoice = await hesabchin('/invoices', {
  method: 'POST',
  idempotencyKey: 'order-10452',
  body: { type: 'sale', date: '2026-11-13', warehouse_id: 1, tax_percent: 10, external_ref: 'woo:order:10452',
          party: { match_on: 'mobile', name: 'Sara Ahmadi', mobile: '09121234567' },
          items: [{ sku: 'TSHIRT-M-BLK', qty: 3, unit_price: 850000 }],
          payment: { amount: 2805000, money_account_id: 2 } },
});
```

### Checklist before you say "done"
1. `GET /me` succeeds and `effective_scopes` covers every call you make.
2. The API key is read from server-side configuration only.
3. Every write sends an `Idempotency-Key` derived from the caller's own stable id, and records carry `external_ref`.
4. Amounts are integer Toman; dates are Gregorian `YYYY-MM-DD`.
5. 401/403 stop the flow and surface the `message`; 429 and `idempotency_in_progress` wait `Retry-After`; 409 `duplicate_external_ref` is treated as already done; 422 is shown to the user, not retried blindly.
6. Webhook signatures are verified on the raw body and deliveries are de-duplicated by `X-Hesabchin-Delivery`.
7. You verified one full round trip (create → read back → balances match what §4 predicts).

## 17. Endpoint index (every v1 route)

**identity** (هویت)

| Method | Path | Scope |
|---|---|---|
| GET | `/me` | any key |

**sync** (همگام‌سازی)

| Method | Path | Scope |
|---|---|---|
| GET | `/changes` | `changes.read` |
| GET | `/changes/latest` | `changes.read` |

**parties** (اشخاص)

| Method | Path | Scope |
|---|---|---|
| GET | `/parties` | `parties.read` |
| GET | `/parties/{id}` | `parties.read` |
| GET | `/parties/by-ref/{ref}` | `parties.read` |
| GET | `/parties/by-code/{code}` | `parties.read` |
| POST | `/parties` | `parties.write` |
| PUT | `/parties/{id}` | `parties.write` |
| PATCH | `/parties/{id}` | `parties.write` |
| PUT | `/parties/by-ref/{ref}` | `parties.write` |
| PUT | `/parties/by-code/{code}` | `parties.write` |
| POST | `/parties/batch` | `parties.write` |
| DELETE | `/parties/{id}` | `parties.write` |
| GET | `/parties/tabs` | `parties.read` |
| GET | `/parties/next-code` | `parties.read` |
| GET | `/parties/duplicates` | `parties.read` |
| POST | `/parties/{id}/share` | `parties.write` |
| DELETE | `/parties/{id}/share` | `parties.write` |
| POST | `/parties/{id}/merge` | `parties.write` |
| GET | `/parties/{id}/bank-accounts` | `parties.read` |
| POST | `/parties/{id}/bank-accounts` | `parties.write` |
| PUT | `/parties/{id}/bank-accounts/{accountId}` | `parties.write` |
| DELETE | `/parties/{id}/bank-accounts/{accountId}` | `parties.write` |
| GET | `/party-categories` | `parties.read` |
| POST | `/party-categories` | `parties.write` |
| PUT | `/party-categories/{id}` | `parties.write` |
| DELETE | `/party-categories/{id}` | `parties.write` |
| GET | `/shareholders` | `parties.read` |
| PUT | `/shareholders` | `parties.write` |
| GET | `/parties/{id}/statement` | `parties.read` |
| POST | `/parties/balance-document` | `journal.write` |

**products** (کالا، انبار و قیمت)

| Method | Path | Scope |
|---|---|---|
| GET | `/products` | `products.read` |
| GET | `/products/{id}` | `products.read` |
| GET | `/products/by-ref/{ref}` | `products.read` |
| GET | `/products/by-code/{code}` | `products.read` |
| GET | `/products/by-sku/{sku}` | `products.read` |
| GET | `/products/by-barcode/{barcode}` | `products.read` |
| POST | `/products` | `products.write` |
| PUT | `/products/{id}` | `products.write` |
| PATCH | `/products/{id}` | `products.write` |
| PUT | `/products/by-ref/{ref}` | `products.write` |
| PUT | `/products/by-sku/{sku}` | `products.write` |
| POST | `/products/batch` | `products.write` |
| DELETE | `/products/{id}` | `products.write` |
| GET | `/products/next-code` | `products.read` |
| GET | `/products/duplicates` | `products.read` |
| GET | `/products/{id}/price-history` | `products.read` |
| POST | `/products/bulk-price` | `products.write` |
| POST | `/products/barcodes` | `products.write` |
| POST | `/products/barcodes/remove` | `products.write` |
| POST | `/products/{id}/adjust` | `products.write` |
| POST | `/products/{id}/transfer` | `products.write` |
| GET | `/product-categories` | `products.read` |
| POST | `/product-categories` | `products.write` |
| PUT | `/product-categories/{id}` | `products.write` |
| DELETE | `/product-categories/{id}` | `products.write` |
| GET | `/warehouses` | `products.read` |
| POST | `/warehouses` | `products.write` |
| PUT | `/warehouses/{id}` | `products.write` |
| DELETE | `/warehouses/{id}` | `products.write` |
| GET | `/stock` | `products.read` |
| POST | `/stock/query` | `products.read` |
| GET | `/price-levels` | `products.read` |
| POST | `/price-levels` | `products.write` |
| PUT | `/price-levels/{id}` | `products.write` |
| DELETE | `/price-levels/{id}` | `products.write` |
| GET | `/products/{id}/price` | `products.read` |

**stock-documents** (اسناد انبار)

| Method | Path | Scope |
|---|---|---|
| GET | `/stock-documents` | `products.read` |
| GET | `/stock-documents/{id}` | `products.read` |
| GET | `/stock-documents/by-ref/{ref}` | `products.read` |
| GET | `/stock-documents/types` | `products.read` |
| POST | `/stock-documents` | `products.write` |
| PUT | `/stock-documents/{id}` | `products.write` |
| DELETE | `/stock-documents/{id}` | `products.write` |
| POST | `/stock-documents/count/prepare` | `products.read` |
| POST | `/stock-documents/cost-preview` | `products.read` |
| GET | `/reports/stock-turnover` | `products.read` |

**invoices** (فاکتور، پیش‌فاکتور، پروژه و فروشنده)

| Method | Path | Scope |
|---|---|---|
| GET | `/invoices` | `invoices.read` |
| GET | `/invoices/{id}` | `invoices.read` |
| GET | `/invoices/by-ref/{ref}` | `invoices.read` |
| GET | `/invoices/by-number/{type}/{number}` | `invoices.read` |
| POST | `/invoices` | `invoices.write` |
| PUT | `/invoices/{id}` | `invoices.write` |
| PATCH | `/invoices/{id}` | `invoices.write` |
| DELETE | `/invoices/{id}` | `invoices.write` |
| POST | `/invoices/{id}/approve` | `invoices.write` |
| POST | `/invoices/{id}/send` | `invoices.write` |
| GET | `/invoices/{id}/pdf` | `invoices.read` |
| GET | `/invoices/{id}/payments` | `invoices.read` |
| POST | `/invoices/{id}/payments` | `payments.write` |
| POST | `/invoices/{id}/share` | `invoices.write` |
| DELETE | `/invoices/{id}/share` | `invoices.write` |
| GET | `/quotes` | `invoices.read` |
| GET | `/quotes/{id}` | `invoices.read` |
| GET | `/quotes/by-ref/{ref}` | `invoices.read` |
| POST | `/quotes` | `invoices.write` |
| PUT | `/quotes/{id}` | `invoices.write` |
| PUT | `/quotes/{id}/status` | `invoices.write` |
| DELETE | `/quotes/{id}` | `invoices.write` |
| POST | `/quotes/{id}/convert` | `invoices.write` |
| POST | `/quotes/{id}/send` | `invoices.write` |
| GET | `/quotes/{id}/pdf` | `invoices.read` |
| GET | `/projects` | `invoices.read` |
| GET | `/projects/{id}` | `invoices.read` |
| POST | `/projects` | `invoices.write` |
| PUT | `/projects/{id}` | `invoices.write` |
| DELETE | `/projects/{id}` | `invoices.write` |
| GET | `/projects/{id}/card` | `reports.read` |
| GET | `/salesmen` | `invoices.read` |
| GET | `/salesmen/{id}` | `invoices.read` |
| GET | `/salesmen/next-code` | `invoices.read` |
| POST | `/salesmen` | `invoices.write` |
| PUT | `/salesmen/{id}` | `invoices.write` |
| DELETE | `/salesmen/{id}` | `invoices.write` |
| GET | `/reports/sales-by-salesman` | `reports.read` |
| GET | `/discounts` | `invoices.read` |
| GET | `/discounts/{id}` | `invoices.read` |
| POST | `/discounts/check` | `invoices.read` |
| POST | `/discounts` | `invoices.write` |
| PUT | `/discounts/{id}` | `invoices.write` |
| DELETE | `/discounts/{id}` | `invoices.write` |
| GET | `/installments` | `invoices.read` |
| GET | `/installments/summary` | `invoices.read` |
| GET | `/installments/next-number` | `invoices.read` |
| GET | `/installments/invoices` | `invoices.read` |
| POST | `/installments/schedule` | `invoices.read` |
| GET | `/installments/report` | `invoices.read` |
| GET | `/installments/due` | `invoices.read` |
| GET | `/installments/{id}` | `invoices.read` |
| POST | `/installments` | `invoices.write` |
| PUT | `/installments/{id}` | `invoices.write` |
| DELETE | `/installments/{id}` | `invoices.write` |
| POST | `/installments/{id}/cancel` | `invoices.write` |
| POST | `/installments/{id}/restore` | `invoices.write` |
| POST | `/installments/{id}/items/{n}/receive` | `payments.write` |
| POST | `/installments/{id}/items/{n}/unreceive` | `payments.write` |

**treasury** (خزانه: صندوق، بانک، تراکنش، چک، تسهیلات)

| Method | Path | Scope |
|---|---|---|
| GET | `/money-accounts` | `treasury.read` |
| POST | `/money-accounts` | `treasury.write` |
| PUT | `/money-accounts/{id}` | `treasury.write` |
| DELETE | `/money-accounts/{id}` | `treasury.write` |
| GET | `/money-accounts/{id}/statement` | `treasury.read` |
| GET | `/currencies` | `treasury.read` |
| POST | `/currencies` | `treasury.write` |
| PUT | `/currencies/{id}` | `treasury.write` |
| DELETE | `/currencies/{id}` | `treasury.write` |
| GET | `/currencies/{id}/rates` | `treasury.read` |
| POST | `/currencies/{id}/rates` | `treasury.write` |
| DELETE | `/currencies/{id}/rates/{rateId}` | `treasury.write` |
| GET | `/exchange-rates/latest` | `treasury.read` |
| POST | `/exchange-rates` | `treasury.write` |
| GET | `/ledger-accounts` | `treasury.read` |
| POST | `/ledger-accounts` | `expenses.write` |
| GET | `/transactions` | `treasury.read` |
| GET | `/transactions/{id}` | `treasury.read` |
| GET | `/transactions/by-ref/{ref}` | `treasury.read` |
| POST | `/transactions` | by type (§8) |
| PUT | `/transactions/{id}` | by type (§8) |
| DELETE | `/transactions/{id}` | by type (§8) |
| GET | `/payment-documents` | `treasury.read` |
| GET | `/payment-documents/items` | `treasury.read` |
| GET | `/payment-documents/{id}` | `treasury.read` |
| GET | `/payment-documents/by-ref/{ref}` | `treasury.read` |
| POST | `/payment-documents` | `payments.write` |
| PUT | `/payment-documents/{id}` | `payments.write` |
| DELETE | `/payment-documents/{id}` | `payments.write` |
| GET | `/cheques` | `treasury.read` |
| GET | `/cheques/{id}` | `treasury.read` |
| GET | `/cheques/by-ref/{ref}` | `treasury.read` |
| GET | `/cheques/summary` | `treasury.read` |
| POST | `/cheques` | `cheques.write` |
| PUT | `/cheques/{id}` | `cheques.write` |
| POST | `/cheques/{id}/deposit` | `cheques.write` |
| POST | `/cheques/{id}/clear` | `cheques.write` |
| POST | `/cheques/{id}/bounce` | `cheques.write` |
| POST | `/cheques/{id}/spend` | `cheques.write` |
| POST | `/cheques/{id}/revert` | `cheques.write` |
| POST | `/cheques/{id}/undeposit` | `cheques.write` |
| POST | `/cheques/{id}/reschedule` | `cheques.write` |
| DELETE | `/cheques/{id}` | `cheques.write` |
| POST | `/tools/due-average` | `treasury.read` |
| GET | `/loans` | `treasury.read` |
| GET | `/loans/{id}` | `treasury.read` |
| GET | `/loans/installments/due` | `treasury.read` |
| POST | `/loans/schedule` | `treasury.read` |
| POST | `/loans` | `treasury.write` |
| PUT | `/loans/{id}` | `treasury.write` |
| DELETE | `/loans/{id}` | `treasury.write` |
| POST | `/loans/{id}/installments/{n}/pay` | `treasury.write` |
| POST | `/loans/{id}/installments/{n}/unpay` | `treasury.write` |
| POST | `/loans/{id}/settle` | `treasury.write` |

**accounting** (حسابداری: کدینگ، اسناد، سال مالی)

| Method | Path | Scope |
|---|---|---|
| GET | `/accounts/tree` | `reports.read` |
| GET | `/accounts/export` | `reports.read` |
| POST | `/accounts` | `journal.write` |
| PUT | `/accounts/{id}` | `journal.write` |
| DELETE | `/accounts/{id}` | `journal.write` |
| POST | `/accounts/merge` | `journal.write` |
| GET | `/account-map` | `reports.read` |
| PUT | `/account-map` | `journal.write` |
| GET | `/journal-entries` | `reports.read` |
| GET | `/journal-entries/{id}` | `reports.read` |
| GET | `/journal-entries/by-ref/{ref}` | `reports.read` |
| GET | `/journal-entries/kinds` | `reports.read` |
| GET | `/journal-entries/counts` | `reports.read` |
| GET | `/journal-entries/next-number` | `reports.read` |
| GET | `/journal-entries/export` | `reports.read` |
| GET | `/journal-entries/{id}/export` | `reports.read` |
| POST | `/journal-entries` | `journal.write` |
| PUT | `/journal-entries/{id}` | `journal.write` |
| DELETE | `/journal-entries/{id}` | `journal.write` |
| POST | `/journal-entries/{id}/copy` | `journal.write` |
| POST | `/journal-entries/merge` | `journal.write` |
| POST | `/journal-entries/{id}/lock` | `journal.write` |
| POST | `/journal-entries/{id}/unlock` | `journal.write` |
| POST | `/journal-entries/lock` | `journal.write` |
| POST | `/journal-entries/renumber` | `journal.write` |
| POST | `/journal-entries/{id}/approve` | `journal.write` |
| POST | `/journal-entries/approve` | `journal.write` |
| GET | `/fiscal-years` | `reports.read` |
| GET | `/fiscal-years/current` | `reports.read` |
| POST | `/fiscal-years` | `journal.write` |
| PUT | `/fiscal-years/{id}` | `journal.write` |
| GET | `/fiscal-years/{id}/closing-preview` | `reports.read` |
| POST | `/fiscal-years/{id}/close` | `journal.write` |
| POST | `/fiscal-years/{id}/reopen` | `journal.write` |
| DELETE | `/fiscal-years/{id}` | `journal.write` |
| GET | `/opening-balance` | `reports.read` |
| GET | `/opening-balance/history` | `reports.read` |
| PUT | `/opening-balance` | `journal.write` |
| POST | `/opening-balance/cheques` | `journal.write` |
| PUT | `/opening-balance/cheques/{id}` | `journal.write` |
| DELETE | `/opening-balance/cheques/{id}` | `journal.write` |

**reports** (گزارش‌ها)

| Method | Path | Scope |
|---|---|---|
| GET | `/reports/catalog` | `reports.read` |
| GET | `/reports/dashboard` | `reports.read` |
| GET | `/reports/trial-balance` | `reports.read` |
| GET | `/reports/profit-loss` | `reports.read` |
| GET | `/reports/balance-sheet` | `reports.read` |
| GET | `/reports/ledger` | `reports.read` |
| GET | `/reports/journal` | `reports.read` |
| GET | `/reports/aging` | `reports.read` |
| GET | `/reports/vat` | `reports.read` |
| GET | `/reports/sales-by-product` | `reports.read` |
| GET | `/reports/purchases-by-product` | `reports.read` |
| GET | `/reports/sales-by-invoice` | `reports.read` |
| GET | `/reports/purchases-by-invoice` | `reports.read` |
| GET | `/reports/sales-by-project` | `reports.read` |
| GET | `/reports/invoice-profit` | `reports.read` |
| GET | `/reports/party-summary` | `reports.read` |
| GET | `/reports/debtors-creditors` | `reports.read` |
| GET | `/reports/cash-flow` | `reports.read` |
| GET | `/reports/capital` | `reports.read` |
| GET | `/reports/explorer` | `reports.read` |
| GET | `/reports/explorer-detail` | `reports.read` |
| GET | `/reports/general-ledger` | `reports.read` |
| GET | `/reports/consolidated-journal` | `reports.read` |
| GET | `/reports/consolidated-ledger` | `reports.read` |
| GET | `/reports/money-statement` | `reports.read` |
| GET | `/reports/party-statement` | `reports.read` |
| GET | `/reports/party-card` | `reports.read` |
| GET | `/reports/export/{name}` | `reports.read` |

**moodian** (سامانه‌ی مودیان)

| Method | Path | Scope |
|---|---|---|
| GET | `/moodian/meta` | `invoices.read` |
| GET | `/moodian/invoices` | `invoices.read` |
| GET | `/moodian/invoices/{id}` | `invoices.read` |
| POST | `/moodian/invoices/send` | `moodian.manage` |
| POST | `/moodian/invoices/inquire` | `moodian.manage` |
| PUT | `/moodian/invoices/bulk` | `moodian.manage` |
| POST | `/moodian/invoices/{id}/retry` | `moodian.manage` |
| POST | `/moodian/invoices/{id}/correct` | `moodian.manage` |
| POST | `/moodian/invoices/{id}/cancel` | `moodian.manage` |

**other** (حقوق، دارایی، فایل‌ها، لاگ و وب‌هوک)

| Method | Path | Scope |
|---|---|---|
| GET | `/payroll/summary` | `payroll.read` |
| GET | `/payroll/employees` | `payroll.read` |
| POST | `/payroll/employees` | `payroll.write` |
| PUT | `/payroll/employees/{id}` | `payroll.write` |
| POST | `/payroll/employees/{id}/party` | `payroll.write` |
| GET | `/payroll/payslips` | `payroll.read` |
| POST | `/payroll/payslips` | `payroll.write` |
| POST | `/payroll/payslips/batch` | `payroll.write` |
| PUT | `/payroll/payslips/{id}` | `payroll.write` |
| POST | `/payroll/payslips/{id}/pay` | `payroll.write` |
| DELETE | `/payroll/payslips/{id}` | `payroll.write` |
| GET | `/payroll/advances` | `payroll.read` |
| POST | `/payroll/advances` | `payroll.write` |
| POST | `/payroll/remit` | `payroll.write` |
| GET | `/assets` | `assets.read` |
| POST | `/assets` | `assets.write` |
| POST | `/assets/depreciate` | `assets.write` |
| POST | `/assets/{id}/dispose` | `assets.write` |
| DELETE | `/assets/{id}` | `assets.write` |
| GET | `/exports/invoices` | `invoices.read` |
| GET | `/exports/parties` | `parties.read` |
| GET | `/exports/products` | `products.read` |
| GET | `/exports/transactions` | `treasury.read` |
| GET | `/exports/cheques` | `treasury.read` |
| GET | `/exports/stock-documents` | `products.read` |
| GET | `/exports/quotes` | `invoices.read` |
| POST | `/imports/parties` | `parties.write` |
| POST | `/imports/products` | `products.write` |
| GET | `/backup` | `backup.read` |
| GET | `/audit-logs` | `audit.read` |
| GET | `/audit-logs/events` | `audit.read` |
| GET | `/audit-logs/export` | `audit.read` |
| GET | `/webhooks` | `webhooks.manage` |
| POST | `/webhooks` | `webhooks.manage` |
| PUT | `/webhooks/{id}` | `webhooks.manage` |
| DELETE | `/webhooks/{id}` | `webhooks.manage` |
| POST | `/webhooks/{id}/test` | `webhooks.manage` |
| GET | `/webhooks/{id}/deliveries` | `webhooks.manage` |
| POST | `/webhooks/deliveries/{deliveryId}/retry` | `webhooks.manage` |
