# PVLedger JSON API

Send JSON objects to `/api/v1`. Log in with `POST /auth/login`, body `{"username":"…","password":"…"}`, and header `X-CSRF-Token: login`. Retain the session cookie and the returned `csrf` value. Send that token as `X-CSRF-Token` with authenticated writes. Use `GET /auth/me` to retrieve it alongside the instance’s `default_currency` ID.

Collection responses expose `items`, `page`, `page_size`, `total`, and resource field metadata. Set `page_size` between 1 and 100. Sort using `sort=date` or `sort=-date` for resources with a date field. Income can be filtered using `id_account`, integer `status`, and inclusive `from` and `to` UTC epoch seconds. Account-history lists accept the date filters, use a fixed page size of 50, and return the parent account's currency.

Standard collection writes use POST, detail updates use PATCH, and detail deletion uses DELETE. Use the column names from the [database specification](../spec/pvledger_database_spec.md) as keys and omit `id` from request bodies. PostgreSQL and MariaDB/MySQL adapters are deferred. Actual and planned income writes require `id_account` referencing an authorized current account, `name`, `amount` and `date` in UTC epoch seconds. Planned income also requires `status` as 0 Planned, 1 Processed, 2 Processed with changes or 3 Declined. Omit `status` from actual-income writes, filters and export columns. Income currency comes from the linked account. Account history is read-only through the API.

Creating an actual expense subtracts its numeric amount from the authorized current account. Creating actual income adds its amount. A missing opening balance or an expense currency that differs from the account currency returns HTTP 422. Signed values use the same arithmetic. Editing or deleting an existing entry has no posting effect. Planned entries have no posting effect.

Changing a current or savings account balance with PATCH, or by posting an actual entry, appends its new absolute balance to the matching history. The timestamp is the server’s UTC Unix second at the update, including for backdated entries. Multiple changes in the same second have distinct history IDs. An unchanged amount produces no snapshot. Opening an account establishes its initial value.

Requests can return an error object of the form `{"error":{"code":"constraint","message":"…"}}`. Use the code for client-side decisions since messages follow the instance locale. A successful deletion returns status 204.

## Data workflows

- `GET /lookups/{resource}?page=1` returns up to 100 authorized `{id,label}` entries. Use the collection's foreign-key `resource` metadata to choose a lookup, including `accounts/current` and `accounts/savings`. Non-administrators can resolve their own user label.
- `POST /import/preview` accepts the browser's parsed rows with `dataset: "expenses"`, `id_account`, `id_currency` and `id_category`. Each row contains a name, positive amount and UTC timestamp. Optional fields include description, source currency ISO code, source identifier and a file parser error. The response includes the mapped rows and a ten-minute token. A new preview replaces the previous one in that session.
- `POST /import/commit` accepts `{"token":"…","confirm":true,"rows":[0,2]}`. Indices select rows in preview order, including any duplicates the operator explicitly chose. Validation errors make a row ineligible. Each selected expense debits the account and records its changed balance. All rows, balance updates and snapshots commit together. A successful commit consumes the token. Account access, reference validity and new duplicate conflicts are checked at commit time.
- `POST /export/preview` and `POST /export/download` accept the same selection, for example `{"dataset":"history/savings","format":"csv","filters":{"id_account":2},"columns":["date","amount","id_account_label","id_currency_label"]}`. Preview returns available columns, the full count, the row limit and up to ten sample rows. Download rechecks visibility and returns a named attachment. Choose `csv`, `ods` or `xlsx` for any tabular dataset with selectable columns. Spreadsheet downloads preserve the column order, numeric amounts, raw UTC epoch seconds and literal text. Integers exceeding 15 digits are exported as exact text. Formats `qif`, `ofx` and `qfx` support actual expenses or actual income for one account and currency, with fixed fields. Omit `columns` for these formats. The server requires the session CSRF header for both requests.
- `GET /reports/expense-categories` returns category sums per currency. `GET /reports/spending` sums actual expenses by expense currency and UTC day. Each item contains `id_currency`, `currency`, `day` (midnight UTC in Unix seconds), and `amount`. Days with a recorded amount appear in chronological order within each currency. `GET /reports/balances?account_type=savings` returns individual stored snapshot points. These reports accept `id_account`, `id_currency`, and inclusive UTC `from` and `to` filters on the underlying records and support up to 5,000 result rows.
- `GET /reports/estimates` accepts the same account, currency and date filters. Omit the account ID to include all visible current accounts. Each item has `day`, `id_currency`, `currency`, `basis`, `income`, `expenses` and `net`. Through today (UTC) the basis is `actual`. Future days use `planned` entries with status 0, including planned expenses with an unset status. Income uses its current account's currency and expenses use their recorded currency.
- `GET /reports/balance-projection` accepts `id_currency` and an inclusive `to` timestamp. Results include today's recorded balance and one row per UTC day with qualifying plans, per account and per currency total. Each row has `id_currency`, `currency`, `account_type`, `id_account`, `account`, `day` (UTC midnight in Unix seconds), `delta` (net planned change) and `amount` (projected balance). For currency totals, the three account fields are null. From tomorrow, the report uses status 0 planned income and status 0 or unset planned expenses in the account's currency. Savings balances contribute to totals and have no planned changes.
- `GET /reports/fund-distribution` accepts `id_currency` and returns visible current and savings accounts with recorded balances. Each item has `account_type` (`current` or `savings`), `id_account`, `account`, `id_currency`, `currency` and the signed `amount`. Results are ordered by currency ID and descending balance.

## Database backup and recovery

Administrators can download an online SQLite snapshot with `GET /settings/backup`. Restore it with `POST /settings/restore` using the session CSRF header. Send the raw file with a fixed Content-Length and Content-Type `application/octet-stream` or `application/vnd.sqlite3`. The transfer limit for a snapshot is 64 MiB.

Before setup completes, `POST /setup/restore` accepts the same file using the setup form’s token in `X-CSRF-Token`. After successful restoration either endpoint returns 204, clears existing sessions and accepts login with credentials from the backup. A malformed, incompatible or uninitialized backup returns 422. The setup route closes once an instance is initialized.

See the [OpenAPI document](openapi.yaml) for routes and response codes.
