{"openapi": "3.0.3", "info": {"title": "expense-service API", "version": "1.0.0", "description": "JSON API of **expense-service**, a small expense-logging service (Go + Gin + Postgres).\n**Authentication:** username + password login with a server-side session in the\n`session` cookie (HttpOnly, SameSite=Lax), or a personal API token\n(`Authorization: Bearer ext_…`). Every `/api` route needs a valid session or token\n(401 otherwise) except `POST /api/auth/login`, `POST /api/auth/register` (first-run only),\n`POST /api/auth/logout`, `GET /api/healthz` and the API description itself.\n**Ownership:** transactions, balances and categories are per user. Lists and writes\nare scoped to the authenticated account; another user's uid is **404**. A transaction\nmay only reference that user's balances and categories.\nState-changing requests must not be cross-site (`Origin` must match the host and\n`Sec-Fetch-Site` must be `same-origin`/`none` when sent; 403 otherwise) and a request body\nmust be `application/json` (415). See docs/auth.md.\nEvery response carries `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`,\n`Referrer-Policy: same-origin` and a `Content-Security-Policy` (`default-src 'self'`,\n`frame-ancestors 'none'`; looser for Swagger UI under `/swagger/`).\n\n## Conventions\n\n- **Identifiers:** every resource is addressed **only by `uid`**, a server-assigned,\n  immutable UUID v4 (lowercase in responses; path uids are matched case-insensitively).\n  Internal numeric row ids never appear in URLs or JSON. A path `{uid}` that is not\n  UUID-shaped (e.g. `/api/transactions/1`) is **400**; an unknown uid is **404**.\n- **Amounts** are exact. Clients send a decimal **string** (`\"120.50\"`, recommended) or a\n  JSON number, which is read as its literal text and never as a float. Responses carry both the\n  decimal string (`amount`, `balance`, `debt`, …) and the **integer minor units**\n  (`amount_minor`, `balance_minor`, …). The number of decimals depends on the currency (ISO 4217):\n  THB/USD 2, JPY/KRW 0, KWD/BHD 3, CLF 4. Input with more decimals than the currency\n  allows is rejected (422), not rounded. Extra trailing zeros are fine (`\"1500.00\"` JPY).\n  There is **no currency conversion** anywhere.\n- **Time:** `spent_at` is an RFC 3339 / ISO 8601 date-time **with an offset**\n  (`2026-10-06T21:06:00+08:00` or `…Z`). Any offset is accepted. The value is stored at second\n  precision with the offset as entered. `created_at` / `updated_at` are UTC (`…Z`).\n  `updated_at` is `null` until the record is first edited.\n- **Optimistic locking (balances and transactions):** every balance and transaction has a\n  `version` (1 on create, +1 on every change, including automatic balance moves caused by\n  transactions). Single-record responses also send it as `ETag: \"<version>\"`.\n  `PUT` must name the version they are based on, either as `If-Match: \"<version>\"`\n  (preferred; `W/\"<version>\"` also accepted) or as `\"version\": <n>` in the body:\n  neither → **428** `version_required`; malformed, or header and body disagree → **400**;\n  stale → **409** `version_conflict` with the current record in `current` and its `ETag`.\n  The version is checked before the body is validated. `DELETE` takes an optional `If-Match`\n  (409 if stale). Categories and users are not versioned.\n- **Errors** are always JSON: `{\"error\": \"…\", \"fields\": {…}, \"code\": \"…\", \"current\": {…}}`.\n  Only `error` is always present. `fields` maps field names to problems (validation, query,\n  conflict and duplicate errors). `code` is one of `version_required`, `version_conflict`,\n  `balance_in_use`, `balance_adjustment_readonly`.\n  Status codes: **400** malformed request (bad JSON, unknown field, wrong JSON type, empty\n  users patch, bad query parameter, bad uid, bad `If-Match`, body over 64 KiB), **404** not found,\n  **409** conflict, **422** validation failed (`fields`), **428** version required,\n  **500** internal error. An unknown path *or method* is a 404 `{\"error\":\"not found\"}`\n  (no 405, no `OPTIONS`/`HEAD` handling, no CORS).\n- **Writes** take `application/json` bodies. Unknown fields are rejected (400). On `POST`/`PUT`\n  a `uid` field is accepted so a response can be sent back, but it is ignored.\n  `PUT` is a **full replacement**: send the whole record (all editable fields). There is no `PATCH`\n  for transactions, balances or categories (a `PATCH` there is a 404 like any unknown method). To\n  clear an optional field (`note`, `to_balance_uid`, `description`), omit it or send `\"\"` in\n  the full `PUT` body. `category_uid` can't be cleared except on a transfer or repay_debt (it is\n  required on every other type). Optional amounts (`interest_amount`, `fee_amount`,\n  `foreign_amount`) are cleared the same way.\n\n## Transaction types\n\n| type | `balance_uid` | `to_balance_uid` | balance effect |\n|---|---|---|---|\n| `expense` (default) | `payment_account` or `credit_card` | not allowed | asset balance −amount / card debt +amount |\n| `income` | `payment_account` or `credit_card` | not allowed | asset balance +amount / card debt −amount (rebate; may go negative = in credit) |\n| `transfer` | any balance | **required**, any balance ≠ source | source −amount, destination +amount (debt moves the other way) |\n| `asset_purchase` | `payment_account` or `credit_card` | **required**, an `other_asset` ≠ source | source like an expense (balance −amount / card debt +amount), destination asset balance +amount |\n| `return_on_investment` | `payment_account` or `credit_card` | **required**, the `other_asset` it came from ≠ source | like income (balance +amount / card debt −amount, may go negative); the linked asset is **not** changed (dividend / interest) |\n| `repay_debt` | `payment_account` | **required**, a `credit_card` or `other_liability` | account balance −(amount + `interest_amount` + `fee_amount`), destination debt −amount (the principal; may go negative = in credit); same currency only. Category only for the interest/fees (optional, expense category) |\n| `balance_adjustment` | the edited balance (any type) | — | server-created; its change is already in the balance. Editing or deleting it moves the balance: `increase` = balance / debt +amount, `decrease` = −amount |\n\nThe transaction `currency` must equal the currency of its balance(s) (422 otherwise); the asset\nlinked by a `return_on_investment` is not moved, so it may be in another currency.\n`balance_adjustment` transactions are created automatically when `PUT /api/balances/{uid}`\nchanges a balance's `balance` (asset) or `debt` (liability). Their `amount` is the absolute difference and\n`adjustment_direction` is `increase` or `decrease`. They cannot be created through this API\n(`type: balance_adjustment` on create, or a replace that turns another transaction into one, is a\n422), but an existing one can be replaced (it stays a `balance_adjustment`; `adjustment_direction`\nis required) or deleted, which moves the balance by the difference or reverts the change.\n"}, "servers": [{"url": "/", "description": "This server"}], "tags": [{"name": "transactions", "description": "Expenses, income, transfers, asset purchases, returns on investment, debt repayments and (server-created, editable) balance adjustments. Writes move the linked balances in the same database transaction."}, {"name": "balances", "description": "Payment accounts, credit cards, other assets and liabilities. Type is fixed after creation. Manual amount edits record a balance_adjustment transaction. A balance can be hidden (kept with its transactions, left out of the list) or deleted (removed together with every transaction that references it)."}, {"name": "categories", "description": "Expense and income categories. Categories belong to the logged-in user (each user has their own set; another user's category uid is a 404). Expense transactions may only use expense categories, income transactions income categories."}, {"name": "reports", "description": "Read-only summaries (income & expenses in a time range; assets & liabilities by account). Amounts are exact decimal strings, per currency, never converted between currencies. `GET /api/reports` lists the available report types."}, {"name": "auth", "description": "Login, logout, first-run registration, current user and password change."}, {"name": "tokens", "description": "Personal API tokens for scripts and AI agents (`Authorization: Bearer ext_...`). Managing tokens needs a browser session; a token cannot list, create or revoke tokens (403 `session_required`)."}, {"name": "users", "description": "User profiles (password hashes are never returned; `has_password` instead)."}, {"name": "meta", "description": "Health check and this API description."}], "security": [{"cookieAuth": []}, {"bearerAuth": []}], "paths": {"/api/transactions": {"post": {"tags": ["transactions"], "operationId": "createTransaction", "summary": "Create a transaction", "description": "Creates an expense, income, transfer, asset purchase or return on investment and moves the linked balance(s) in the same\ndatabase transaction. `type` defaults to `expense`. `type: balance_adjustment` is rejected\n(422). The transaction currency must match the balance currency (422 on `balance_uid` /\n`to_balance_uid`). A `version` in the body is ignored.\n", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/TransactionInput"}, "examples": {"expense": {"$ref": "#/components/examples/TransactionInputExpense"}, "income": {"$ref": "#/components/examples/TransactionInputIncome"}, "transfer": {"$ref": "#/components/examples/TransactionInputTransfer"}}}}}, "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "201": {"description": "Created. Balances have been moved.", "headers": {"ETag": {"$ref": "#/components/headers/ETag"}, "Location": {"$ref": "#/components/headers/LocationTransaction"}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Transaction"}, "examples": {"expense": {"$ref": "#/components/examples/TransactionExpense"}, "transfer": {"$ref": "#/components/examples/TransactionTransfer"}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "409": {"$ref": "#/components/responses/DuplicateImportRef"}, "422": {"$ref": "#/components/responses/TransactionValidationFailed"}, "502": {"$ref": "#/components/responses/FXBadGateway"}, "503": {"$ref": "#/components/responses/FXUnavailable"}, "500": {"$ref": "#/components/responses/InternalError"}}}, "get": {"tags": ["transactions"], "operationId": "listTransactions", "summary": "List transactions", "description": "Newest first (by the absolute instant of `spent_at`, then most recently created).\nAll filters are optional and combine with AND.\n\n**Pagination:** a response holds at most `limit` rows. When more match, `next_cursor`\nis set: send it back as `cursor` with the same filters to get the next page, until\n`next_cursor` is null. Cursors mark a position in the list order (keyset pagination),\nso rows added or deleted between requests don't shift later pages.\n", "parameters": [{"name": "from", "in": "query", "description": "Inclusive lower bound on `spent_at`, as an RFC 3339 date-time with offset. URL-encode `+`\nas `%2B`, although an unencoded `+` (decoded as a space) is also accepted.\n", "schema": {"type": "string", "format": "date-time", "example": "2026-10-01T00:00:00+08:00"}}, {"name": "to", "in": "query", "description": "Inclusive upper bound on `spent_at` (same format as `from`). Must not be earlier than `from`.", "schema": {"type": "string", "format": "date-time", "example": "2026-10-31T23:59:59+08:00"}}, {"name": "type", "in": "query", "description": "Only transactions of this type (case-insensitive). `balance_adjustment` is allowed here.", "schema": {"$ref": "#/components/schemas/TransactionType"}}, {"name": "category_uid", "in": "query", "description": "Only transactions linked to this category.", "schema": {"$ref": "#/components/schemas/Uid"}}, {"name": "balance_uid", "in": "query", "description": "Only transactions that use this balance, as source (`balance_uid`) or destination (`to_balance_uid`).", "schema": {"$ref": "#/components/schemas/Uid"}}, {"name": "limit", "in": "query", "description": "Maximum number of rows per page.", "schema": {"type": "integer", "minimum": 1, "maximum": 5000, "default": 500}}, {"name": "cursor", "in": "query", "description": "The `next_cursor` of the previous page (opaque). Omit for the first page.", "schema": {"type": "string", "example": "MS4xNzkxMjAwMDAwLjQy"}}], "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "The matching transactions.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/TransactionList"}}}}, "400": {"description": "Invalid query parameter(s). Every problem is listed in `fields`.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": "invalid query parameters", "fields": {"type": "must be one of: expense, income, transfer, asset_purchase, return_on_investment, repay_debt, balance_adjustment", "limit": "must be an integer between 1 and 5000", "cursor": "is not a cursor from this API (use next_cursor from the previous page)"}}}}}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/transactions/bulk": {"post": {"tags": ["transactions"], "operationId": "bulkCreateTransactions", "summary": "Create many transactions at once (statement import)", "description": "Creates up to 500 transactions in one request, e.g. rows an AI agent parsed from a bank\nstatement or PDF. Every item has exactly the shape of POST /api/transactions and goes through\nthe same validation, balance resolution and FX conversion; balances move as they would for\nsingle creates, in input order. See docs/bulk-import.md.\n\n* **Phases.** All items are validated first and any Frankfurter rate needed for a\n  cross-currency transfer without `to_amount` is fetched (and cached) **before** the database\n  transaction opens. Then every insert and balance adjustment runs in **one** SQL transaction\n  (each item in a savepoint).\n* **Idempotency.** An item whose `import_ref` already exists on the same `balance_uid` (in the\n  database, or earlier in the same request) is `skipped` with `existing_uid`; it is not an\n  error. The same ref on a different balance is a different key.\n* **atomic** (default `true`): if any item fails nothing is written and the answer is 422\n  (503/502 if a failure was the exchange-rate service being down), with per-item results;\n  items that would have succeeded are `valid`. On success the answer is 201 (200 if every item\n  was skipped).\n* **atomic: false**: valid items are created, failing ones reported; always 200 (inspect\n  `failed`). A Frankfurter outage fails only the affected items (`code`\n  exchange_rate_unavailable).\n* **dry_run: true**: full validation including balance currency checks and FX conversion,\n  then everything is rolled back. Items are `valid`/`skipped`/`failed`, `balances` shows the\n  balances as they would be afterwards. 200 (or 422/503/502 when atomic and an item fails).\n\nLimits: at most 500 items (413 `code` too_many_items) and a 2 MiB body (400). An empty list is\na 400. Unknown fields in an item, `uid` or `version` in an item, or a non-object item fail that\nitem (`code` invalid_item), not the request.\n", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/BulkTransactionRequest"}, "examples": {"statementImport": {"$ref": "#/components/examples/BulkStatementImport"}}}}}, "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "201": {"description": "Atomic batch committed with at least one created item.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/BulkTransactionResponse"}, "examples": {"created": {"$ref": "#/components/examples/BulkResponseCreated"}}}}}, "200": {"description": "Dry run, non-atomic batch (check `failed`), or every item skipped as a duplicate.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/BulkTransactionResponse"}, "examples": {"reimport": {"$ref": "#/components/examples/BulkResponseReimport"}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "403": {"$ref": "#/components/responses/Forbidden"}, "413": {"description": "More than 500 items (`code` too_many_items). Split the import into batches.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "415": {"$ref": "#/components/responses/UnsupportedMediaType"}, "422": {"description": "Atomic batch with at least one failed item; nothing was written. Per-item errors in `results`.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/BulkTransactionResponse"}, "examples": {"failed": {"$ref": "#/components/examples/BulkResponseFailed"}}}}}, "502": {"description": "Atomic batch where Frankfurter answered unexpectedly for an item; nothing was written.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/BulkTransactionResponse"}}}}, "503": {"description": "Atomic batch where Frankfurter was unreachable for an item; nothing was written. Retry later, send `to_amount`, or use `atomic:false`.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/BulkTransactionResponse"}}}}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/transactions/{uid}": {"parameters": [{"$ref": "#/components/parameters/TransactionUid"}], "get": {"tags": ["transactions"], "operationId": "getTransaction", "summary": "Get a transaction", "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "The transaction. `ETag` carries its version.", "headers": {"ETag": {"$ref": "#/components/headers/ETag"}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Transaction"}, "examples": {"expense": {"$ref": "#/components/examples/TransactionExpense"}, "transfer": {"$ref": "#/components/examples/TransactionTransfer"}, "balance_adjustment": {"$ref": "#/components/examples/TransactionAdjustment"}}}}}, "400": {"$ref": "#/components/responses/BadUid"}, "404": {"$ref": "#/components/responses/TransactionNotFound"}, "500": {"$ref": "#/components/responses/InternalError"}}}, "put": {"tags": ["transactions"], "operationId": "replaceTransaction", "summary": "Replace a transaction", "description": "Full replace with the same body and rules as create. Omitted optional fields are cleared\n(e.g. an omitted `note` becomes `\"\"`, and an omitted `type` means `expense`). The old balance\neffect is reversed and the new one applied, all in one database transaction. Requires `If-Match` or\n`\"version\"`. Order of checks: 404 → 400 body → 428/400 version → 409 stale → 422.\n\n**Balance adjustments** can be replaced too. They stay `balance_adjustment` (an omitted `type`\nmeans `balance_adjustment` here; any other type is a 422), `adjustment_direction` is required,\n`balance_uid` may be any balance, and `category_uid`, `to_balance_uid`, `to_amount`,\n`to_currency`, `foreign_amount`, `foreign_currency` and `import_ref` are not allowed (422).\n`adjustment_direction` on any other type is a 422.\n", "parameters": [{"$ref": "#/components/parameters/IfMatch"}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/TransactionInput"}, "examples": {"expense": {"summary": "Replace with version in the body", "value": {"amount": "150", "currency": "THB", "balance_uid": "4dc73a4a-a60b-414e-98bc-3c71298a0af5", "category_uid": "32b0d51e-e81f-41f0-a77c-38e6ec384153", "spent_at": "2026-10-05T09:15:00+07:00", "note": "pad thai + drink", "version": 1}}, "balance_adjustment": {"summary": "Edit a balance adjustment", "value": {"type": "balance_adjustment", "amount": "100", "currency": "THB", "balance_uid": "4dc73a4a-a60b-414e-98bc-3c71298a0af5", "adjustment_direction": "increase", "spent_at": "2026-10-08T21:29:10+08:00", "note": "cash recount", "version": 1}}}}}}, "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "Updated. `version` was incremented; `ETag` carries the new version.", "headers": {"ETag": {"$ref": "#/components/headers/ETag"}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Transaction"}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "404": {"$ref": "#/components/responses/TransactionNotFound"}, "409": {"$ref": "#/components/responses/TransactionConflict"}, "422": {"$ref": "#/components/responses/TransactionValidationFailed"}, "428": {"$ref": "#/components/responses/VersionRequired"}, "502": {"$ref": "#/components/responses/FXBadGateway"}, "503": {"$ref": "#/components/responses/FXUnavailable"}, "500": {"$ref": "#/components/responses/InternalError"}}}, "delete": {"tags": ["transactions"], "operationId": "deleteTransaction", "summary": "Delete a transaction", "description": "Deletes the transaction and reverses its balance effect (balances that no longer exist\nare skipped). `If-Match` is optional; a stale one is a 409. Deleting a `balance_adjustment`\nreverts the manual change it recorded.\n", "parameters": [{"$ref": "#/components/parameters/IfMatchOptional"}], "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "204": {"description": "Deleted."}, "400": {"$ref": "#/components/responses/BadRequest"}, "404": {"$ref": "#/components/responses/TransactionNotFound"}, "409": {"$ref": "#/components/responses/TransactionConflict"}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/balances": {"post": {"tags": ["balances"], "operationId": "createBalance", "summary": "Create a balance", "description": "Assets (`payment_account`, `other_asset`) need `balance` (may be negative). Liabilities\n(`credit_card`, `other_liability`) need `debt` (may be negative, i.e. in credit) and `limit` (≥ 0).\nSending an amount that does not apply to the type is a 422. Names need not be unique: two\nbalances may share a name (each has its own `uid`).\nA `version` in the body is ignored.\n", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/BalanceInput"}, "examples": {"payment_account": {"summary": "Bank account", "value": {"name": "Wallet", "type": "payment_account", "currency": "THB", "balance": "10000"}}, "credit_card": {"summary": "Credit card", "value": {"name": "Credit Card", "type": "credit_card", "currency": "THB", "debt": "52000", "limit": "50000"}}}}}}, "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "201": {"description": "Created.", "headers": {"ETag": {"$ref": "#/components/headers/ETag"}, "Location": {"$ref": "#/components/headers/LocationBalance"}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Balance"}, "examples": {"payment_account": {"$ref": "#/components/examples/BalanceAsset"}, "credit_card": {"$ref": "#/components/examples/BalanceCard"}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "422": {"$ref": "#/components/responses/BalanceValidationFailed"}, "500": {"$ref": "#/components/responses/InternalError"}}}, "get": {"tags": ["balances"], "operationId": "listBalances", "summary": "List balances", "description": "Grouped by type (payment accounts, credit cards, other assets, other liabilities), then by\nname. Hidden balances (`hidden: true`) are left out unless `include_hidden` is set. `totals`\nsums the returned rows per currency.\n", "parameters": [{"name": "type", "in": "query", "description": "Only balances of this type (case-insensitive). Cannot be combined with `payable`.", "schema": {"$ref": "#/components/schemas/BalanceType"}}, {"name": "payable", "in": "query", "description": "`1` or `true` (case-insensitive) returns only `payment_account` and `credit_card`\nbalances. **Any other value is treated as \"not set\"** (not a 400).\n", "schema": {"type": "string", "example": "1"}}, {"name": "include_hidden", "in": "query", "description": "`1` or `true` (case-insensitive) also returns hidden balances (combines with `type` and\n`payable`). Any other value is treated as \"not set\".\n", "schema": {"type": "string", "example": "true"}}], "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "The balances and per-currency totals.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/BalanceList"}}}}, "400": {"description": "Invalid query parameters (`type` unknown, or `type` combined with `payable`).", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "examples": {"type": {"value": {"error": "invalid query parameters", "fields": {"type": "must be one of payment_account, credit_card, other_asset, other_liability"}}}, "combined": {"value": {"error": "invalid query parameters", "fields": {"payable": "cannot be combined with type"}}}}}}}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/balances/{uid}": {"parameters": [{"$ref": "#/components/parameters/BalanceUid"}], "get": {"tags": ["balances"], "operationId": "getBalance", "summary": "Get a balance", "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "The balance. `ETag` carries its version.", "headers": {"ETag": {"$ref": "#/components/headers/ETag"}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Balance"}, "examples": {"payment_account": {"$ref": "#/components/examples/BalanceAsset"}, "credit_card": {"$ref": "#/components/examples/BalanceCard"}}}}}, "400": {"$ref": "#/components/responses/BadUid"}, "404": {"$ref": "#/components/responses/BalanceNotFound"}, "500": {"$ref": "#/components/responses/InternalError"}}}, "put": {"tags": ["balances"], "operationId": "replaceBalance", "summary": "Replace a balance (manual override)", "description": "Full replace with the create rules, except that `type` is immutable: it is still required\nand must equal the stored type (422 on `type` otherwise). The amounts sent override whatever\ntransactions did to the balance. A change of `balance` (assets) or `debt` (liabilities) records\na `balance_adjustment` transaction (editable and deletable afterwards). Limit-only, name, description and currency changes\nrecord nothing. The currency cannot change while transactions reference the balance (409\n`balance_in_use`). An omitted `description` is cleared. Requires `If-Match` or `\"version\"`.\n", "parameters": [{"$ref": "#/components/parameters/IfMatch"}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/BalanceInput"}, "example": {"name": "Wallet", "type": "payment_account", "currency": "THB", "description": "Salary account", "balance": "5000", "version": 3}}}}, "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "Updated. `ETag` carries the new version.", "headers": {"ETag": {"$ref": "#/components/headers/ETag"}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Balance"}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "404": {"$ref": "#/components/responses/BalanceNotFound"}, "409": {"$ref": "#/components/responses/BalanceConflict"}, "422": {"$ref": "#/components/responses/BalanceValidationFailed"}, "428": {"$ref": "#/components/responses/VersionRequired"}, "500": {"$ref": "#/components/responses/InternalError"}}}, "delete": {"tags": ["balances"], "operationId": "deleteBalance", "summary": "Delete a balance and its transactions", "description": "Deletes the balance **together with every transaction that references it** (as `balance_uid`\nor `to_balance_uid`, including returns on investment linked to it and its balance\nadjustments), in one database transaction. Each removed transaction's effect on the user's\nother balances is reversed, as if it had been deleted on its own: e.g. removing a transfer\nfrom account A into the deleted balance puts the amount back on A. To keep the transactions,\nhide the balance instead (`POST /api/balances/{uid}/hide`). `If-Match` is optional; a stale\none is a 409 and nothing is deleted.\n", "parameters": [{"$ref": "#/components/parameters/IfMatchOptional"}], "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "Deleted.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/BalanceDeleted"}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "404": {"$ref": "#/components/responses/BalanceNotFound"}, "409": {"description": "Stale `If-Match`. The body has the current balance and the response has its `ETag`.", "headers": {"ETag": {"$ref": "#/components/headers/ETag"}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/BalanceConflictError"}, "examples": {"version_conflict": {"$ref": "#/components/examples/ErrBalanceVersionConflict"}}}}}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/balances/{uid}/hide": {"parameters": [{"$ref": "#/components/parameters/BalanceUid"}], "post": {"tags": ["balances"], "operationId": "hideBalance", "summary": "Hide a balance", "description": "Marks the balance `hidden`: `GET /api/balances` leaves it out (unless `include_hidden`) and\nthe web page leaves it out of its pickers. Nothing else changes: its amount and its\ntransactions are kept and keep counting (reports included), and it can still be read,\nedited and used by transactions. No body. `If-Match` is optional; a stale one is a 409.\nHiding a hidden balance changes nothing (same version).\n", "parameters": [{"$ref": "#/components/parameters/IfMatchOptional"}], "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "The balance, now hidden. `ETag` carries its version.", "headers": {"ETag": {"$ref": "#/components/headers/ETag"}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Balance"}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "404": {"$ref": "#/components/responses/BalanceNotFound"}, "409": {"$ref": "#/components/responses/BalanceConflict"}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/balances/{uid}/unhide": {"parameters": [{"$ref": "#/components/parameters/BalanceUid"}], "post": {"tags": ["balances"], "operationId": "unhideBalance", "summary": "Show a hidden balance again", "description": "The reverse of hide. No body. `If-Match` is optional; a stale one is a 409.", "parameters": [{"$ref": "#/components/parameters/IfMatchOptional"}], "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "The balance, now visible. `ETag` carries its version.", "headers": {"ETag": {"$ref": "#/components/headers/ETag"}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Balance"}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "404": {"$ref": "#/components/responses/BalanceNotFound"}, "409": {"$ref": "#/components/responses/BalanceConflict"}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/categories": {"post": {"tags": ["categories"], "operationId": "createCategory", "summary": "Create a category", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/CategoryInput"}, "example": {"name": "Food", "type": "expense", "description": "Groceries and restaurants"}}}}, "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "201": {"description": "Created.", "headers": {"Location": {"$ref": "#/components/headers/LocationCategory"}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Category"}, "examples": {"food": {"$ref": "#/components/examples/CategoryFood"}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "409": {"$ref": "#/components/responses/CategoryConflict"}, "422": {"$ref": "#/components/responses/ValidationFailed"}, "500": {"$ref": "#/components/responses/InternalError"}}}, "get": {"tags": ["categories"], "operationId": "listCategories", "summary": "List categories", "description": "The logged-in user's categories, expense first, then income, each by name (case-insensitive).", "parameters": [{"name": "type", "in": "query", "description": "Only categories of this type (case-insensitive).", "schema": {"$ref": "#/components/schemas/CategoryType"}}], "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "The categories.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/CategoryList"}}}}, "400": {"description": "Invalid `type`.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": "invalid query parameters", "fields": {"type": "must be one of: expense, income"}}}}}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/categories/{uid}": {"parameters": [{"$ref": "#/components/parameters/CategoryUid"}], "get": {"tags": ["categories"], "operationId": "getCategory", "summary": "Get a category", "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "The category.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Category"}, "examples": {"food": {"$ref": "#/components/examples/CategoryFood"}}}}}, "400": {"$ref": "#/components/responses/BadUid"}, "404": {"$ref": "#/components/responses/CategoryNotFound"}, "500": {"$ref": "#/components/responses/InternalError"}}}, "put": {"tags": ["categories"], "operationId": "replaceCategory", "summary": "Replace a category", "description": "Full replace (an omitted `description` clears it). Changing `type` while transactions use the category is a 409. Not versioned.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/CategoryInput"}, "example": {"name": "Food & drink", "type": "expense", "description": ""}}}}, "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "Updated.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Category"}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "404": {"$ref": "#/components/responses/CategoryNotFound"}, "409": {"$ref": "#/components/responses/CategoryConflict"}, "422": {"$ref": "#/components/responses/ValidationFailed"}, "500": {"$ref": "#/components/responses/InternalError"}}}, "delete": {"tags": ["categories"], "operationId": "deleteCategory", "summary": "Delete a category", "description": "409 while any transaction references the category (reassign or clear `category_uid` first).", "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "204": {"description": "Deleted."}, "400": {"$ref": "#/components/responses/BadUid"}, "404": {"$ref": "#/components/responses/CategoryNotFound"}, "409": {"description": "The category is used by transactions.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "examples": {"in_use": {"$ref": "#/components/examples/ErrCategoryInUseDelete"}}}}}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/users": {"post": {"tags": ["users"], "operationId": "createUser", "summary": "Create a user profile (disabled)", "description": "**Disabled** (issue #76): always 403 `use_register`. Every user manages only their own\naccount, so a password-less profile created here could neither log in nor be managed.\nCreate accounts with `POST /api/auth/register`.\n", "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "403": {"description": "Creating profiles here is disabled.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": "creating user profiles here is disabled; create an account with POST /api/auth/register", "code": "use_register"}}}}}}, "get": {"tags": ["users"], "operationId": "listUsers", "summary": "List your profile", "description": "Only the logged-in user's own account (one item). Other accounts are never listed.", "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "The users.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/UserList"}}}}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/users/{uid}": {"parameters": [{"$ref": "#/components/parameters/UserUid"}], "get": {"tags": ["users"], "operationId": "getUser", "summary": "Get a user profile", "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "The user (never includes a password hash; see `has_password`).", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/User"}, "examples": {"user": {"$ref": "#/components/examples/UserExample"}}}}}, "400": {"$ref": "#/components/responses/BadUid"}, "404": {"$ref": "#/components/responses/UserNotFound"}, "500": {"$ref": "#/components/responses/InternalError"}}}, "put": {"tags": ["users"], "operationId": "replaceUser", "summary": "Replace a user profile", "description": "Full replace of the profile fields. Omitted `username`/`email` are removed and omitted `preferences` resets every preference to its default. Read-only fields are ignored. Not versioned. A user with a password must keep a username (their login name); removing it is a 422 with code `username_required`. Needs a browser session; an API token gets 403 `session_required`.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/UserInput"}, "example": {"display_name": "Alex E.", "username": "alex", "preferences": {"base_currency": "SGD"}}}}}, "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "403": {"$ref": "#/components/responses/SessionRequired"}, "200": {"description": "Updated.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/User"}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "404": {"$ref": "#/components/responses/UserNotFound"}, "409": {"$ref": "#/components/responses/UserConflict"}, "422": {"$ref": "#/components/responses/ValidationFailed"}, "500": {"$ref": "#/components/responses/InternalError"}}}, "patch": {"tags": ["users"], "operationId": "patchUser", "summary": "Partially update a user profile", "description": "Needs a browser session; an API token gets 403 `session_required`.\nOnly the fields present change. `preferences` **replaces** the whole object (no deep merge;\n`null` resets every preference to its default). `username`/`email`: `null` or `\"\"` removes it. `display_name: null` is a 422.\nRead-only fields are ignored. A patch with nothing else is a 400.\n", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/UserPatch"}, "examples": {"preferences": {"summary": "Replace preferences", "value": {"preferences": {"base_currency": "SGD"}}}, "removeEmail": {"summary": "Remove the email", "value": {"email": null}}}}}}, "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "403": {"$ref": "#/components/responses/SessionRequired"}, "200": {"description": "Updated.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/User"}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "404": {"$ref": "#/components/responses/UserNotFound"}, "409": {"$ref": "#/components/responses/UserConflict"}, "422": {"$ref": "#/components/responses/ValidationFailed"}, "500": {"$ref": "#/components/responses/InternalError"}}}, "delete": {"tags": ["users"], "operationId": "deleteUser", "summary": "Delete a user profile", "description": "Also deletes the user's linked identities, sessions, API tokens and data. The last user who has a password cannot be deleted (409 `last_login_user`), so first-run registration never reopens. Needs a browser session; an API token gets 403 `session_required`.", "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "403": {"$ref": "#/components/responses/SessionRequired"}, "204": {"description": "Deleted."}, "400": {"$ref": "#/components/responses/BadUid"}, "404": {"$ref": "#/components/responses/UserNotFound"}, "409": {"description": "This is the only user who can log in.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": "this is the only account that can log in; it cannot be deleted or lose its password", "code": "last_login_user"}}}}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/users/{uid}/identities": {"parameters": [{"$ref": "#/components/parameters/UserUid"}], "get": {"tags": ["users"], "operationId": "listUserIdentities", "summary": "List a user's linked SSO identities", "description": "Read-only. Identities (Sign in with Apple / Google) will be created by the future SSO flow, so the list is empty for now.", "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "The identities, oldest first.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/IdentityList"}}}}, "400": {"$ref": "#/components/responses/BadUid"}, "404": {"$ref": "#/components/responses/UserNotFound"}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/users/{uid}/preferences": {"parameters": [{"$ref": "#/components/parameters/UserUid"}], "get": {"tags": ["users"], "operationId": "getUserPreferences", "summary": "Get your preferences", "description": "Only for the logged-in user's own uid (404 otherwise). Unset keys show their default.", "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "The effective preferences.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Preferences"}}}}, "400": {"$ref": "#/components/responses/BadUid"}, "404": {"$ref": "#/components/responses/UserNotFound"}, "500": {"$ref": "#/components/responses/InternalError"}}}, "put": {"tags": ["users"], "operationId": "replaceUserPreferences", "summary": "Replace your preferences", "description": "Replaces the whole preferences object; omitted keys go back to their defaults (`{}` resets\neverything). Only for the logged-in user's own uid. Any invalid preference (unsupported\n`base_currency`, wrong type, unknown key, not an object) is a **400** with `fields`.\n", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Preferences"}, "example": {"base_currency": "SGD"}}}}, "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "Updated; the effective preferences.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Preferences"}}}}, "400": {"description": "Malformed body or invalid preferences.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": "invalid preferences", "fields": {"base_currency": "must be a supported ISO 4217 currency code (see /api/currencies)"}}}}}, "404": {"$ref": "#/components/responses/UserNotFound"}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/reports": {"get": {"tags": ["reports"], "operationId": "listReports", "summary": "List report types", "description": "The reports this server offers, in display order. More types may be added later; each has its own `path`.", "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "Available reports.", "content": {"application/json": {"schema": {"type": "object", "required": ["reports", "count"], "properties": {"reports": {"type": "array", "items": {"$ref": "#/components/schemas/ReportInfo"}}, "count": {"type": "integer", "example": 2}}}}}}}}}, "/api/reports/income-expense": {"get": {"tags": ["reports"], "operationId": "incomeExpenseReport", "summary": "Income and expenses in a time range", "description": "Sums the logged-in user's transactions spent in `[from, to]` per currency: `expense`\ntransactions as expenses; `income` and `return_on_investment` as income. The interest and\nfees of a `repay_debt` (`interest_amount` + `fee_amount`, under its category if any) count as\nexpenses; its principal does not. Transfers, asset purchases and balance adjustments are not\ncounted (the same rule as the totals under the web page's transaction list). Each side is also broken down by category,\nlargest first; transactions saved before categories were required are grouped under a\n`null` category. Sums are exact (arbitrary precision); no currency conversion.\n", "parameters": [{"name": "from", "in": "query", "description": "Inclusive lower bound on `spent_at`, RFC 3339 with offset. Omit for no lower bound.", "schema": {"type": "string", "format": "date-time", "example": "2026-11-01T00:00:00+07:00"}}, {"name": "to", "in": "query", "description": "Inclusive upper bound on `spent_at`, RFC 3339 with offset. Omit for no upper bound.", "schema": {"type": "string", "format": "date-time", "example": "2026-11-30T23:59:59+07:00"}}], "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "The report.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/IncomeExpenseReport"}}}}, "400": {"description": "Invalid `from` / `to`, or `to` earlier than `from`.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": "invalid query parameters", "fields": {"to": "must not be earlier than from"}}}}}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/reports/assets-liabilities": {"get": {"tags": ["reports"], "operationId": "assetsLiabilitiesReport", "summary": "Current assets and liabilities", "description": "The logged-in user's balances now, per currency: total assets (balances of\n`payment_account` and `other_asset`), total liabilities (debts of `credit_card` and\n`other_liability`) and net worth, then totals per balance type and every account\n(assets first, then liabilities, each largest first). An amount may be negative (an\noverdrawn account, a card in credit). No currency conversion.\n", "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "The report.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AssetsLiabilitiesReport"}}}}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/currencies": {"get": {"tags": ["meta"], "operationId": "listCurrencies", "summary": "List supported currencies", "description": "ISO 4217 codes accepted by the API, sorted by code, with English name, minor-unit scale\n(decimal places) and a display-only flag emoji for the issuing country or region.\n", "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "Supported currencies.", "content": {"application/json": {"schema": {"type": "object", "required": ["currencies", "count"], "properties": {"currencies": {"type": "array", "items": {"$ref": "#/components/schemas/CurrencyInfo"}}, "count": {"type": "integer"}}}}}}}}}, "/api/exchange-rates": {"get": {"tags": ["meta"], "operationId": "getExchangeRate", "summary": "Look up an exchange rate (Frankfurter / ECB)", "description": "Rate preview for cross-currency transfers (the web form uses it). Rates come from\n[Frankfurter](https://frankfurter.dev) (European Central Bank reference rates, working days\nonly; a weekend/holiday returns the previous working day — see `date`). Cached in the\ndatabase. `from` = `to` answers rate `1` with source `same_currency`.\n", "parameters": [{"name": "from", "in": "query", "required": true, "schema": {"type": "string", "example": "USD"}}, {"name": "to", "in": "query", "required": true, "schema": {"type": "string", "example": "THB"}}, {"name": "date", "in": "query", "required": false, "description": "YYYY-MM-DD. Omitted, today or later means the latest rate.", "schema": {"type": "string", "format": "date"}}], "responses": {"401": {"$ref": "#/components/responses/Unauthorized"}, "200": {"description": "The rate.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ExchangeRate"}}}}, "400": {"description": "Missing/invalid `from`, `to` or `date`.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "422": {"description": "Frankfurter has no rate for this pair (`code` exchange_rate_unsupported).", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "502": {"$ref": "#/components/responses/FXBadGateway"}, "503": {"$ref": "#/components/responses/FXUnavailable"}, "500": {"$ref": "#/components/responses/InternalError"}}}}, "/api/healthz": {"get": {"tags": ["meta"], "operationId": "getHealth", "summary": "Health check", "security": [], "responses": {"200": {"description": "The server is up.", "content": {"application/json": {"schema": {"type": "object", "required": ["status"], "properties": {"status": {"type": "string", "enum": ["ok"]}}, "additionalProperties": false}}}}}}}, "/api/openapi.yaml": {"get": {"tags": ["meta"], "operationId": "getOpenAPIYAML", "summary": "This API description (YAML)", "description": "The OpenAPI 3.0 document embedded in the binary, served as-is. Swagger UI is at `/swagger/`.", "security": [], "responses": {"200": {"description": "OpenAPI document.", "content": {"application/yaml": {"schema": {"type": "string"}}}}}}}, "/api/openapi.json": {"get": {"tags": ["meta"], "operationId": "getOpenAPIJSON", "summary": "This API description (JSON)", "description": "The same document as `/api/openapi.yaml`, converted to JSON.", "security": [], "responses": {"200": {"description": "OpenAPI document.", "content": {"application/json": {"schema": {"type": "object"}}}}}}}, "/api/auth/register": {"post": {"tags": ["auth"], "operationId": "register", "summary": "Create an account (first-run setup, or by a logged-in user)", "description": "Creates a user with a username and password (no email). While **no user has a password**\n(first run) anyone may call it, and the new user is logged in (`Set-Cookie: session=…`).\nAfterwards it is **403** `registration_closed` unless the caller is logged in; a logged-in\ncaller creates the account without switching sessions.\nUsername: 3–32 characters, lowercase letters, digits, `.`, `_`, `-` (stored lowercased,\nunique case-insensitively). Password: 8–72 bytes. `display_name` defaults to the username.\n", "security": [], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["username", "password"], "properties": {"username": {"type": "string", "example": "nat"}, "password": {"type": "string", "format": "password", "minLength": 8, "example": "correct-horse"}, "display_name": {"type": "string", "nullable": true, "example": "Nat"}}, "additionalProperties": false}}}}, "responses": {"201": {"description": "Created (and, on first run, logged in).", "headers": {"Set-Cookie": {"description": "First run only: the session cookie.", "schema": {"type": "string"}}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/User"}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "403": {"$ref": "#/components/responses/Forbidden"}, "409": {"description": "Username already taken.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "415": {"$ref": "#/components/responses/UnsupportedMediaType"}, "422": {"$ref": "#/components/responses/ValidationFailed"}}}}, "/api/auth/login": {"post": {"tags": ["auth"], "operationId": "login", "summary": "Log in", "description": "Checks username (case-insensitive) and password and starts a session (cookie `session`,\nHttpOnly, SameSite=Lax, Secure on TLS, 30 days sliding). Any failure — unknown user, wrong\npassword, disabled user — is the same 401 `invalid username or password`.\nAfter 5 failures for the same username + client IP within 15 minutes, further attempts\nget 429 for 5 minutes (in memory; reset on restart).\n", "security": [], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["username", "password"], "properties": {"username": {"type": "string", "example": "nat"}, "password": {"type": "string", "format": "password"}}, "additionalProperties": false}}}}, "responses": {"200": {"description": "Logged in; the user.", "headers": {"Set-Cookie": {"description": "The session cookie.", "schema": {"type": "string"}}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/User"}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "Invalid username or password.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": "invalid username or password", "code": "invalid_credentials"}}}}, "403": {"$ref": "#/components/responses/Forbidden"}, "429": {"description": "Too many failed attempts; see `Retry-After` (seconds).", "headers": {"Retry-After": {"schema": {"type": "integer"}}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}}, "/api/auth/logout": {"post": {"tags": ["auth"], "operationId": "logout", "summary": "Log out", "description": "Deletes the current session (if any) and clears the cookie. Always 204.", "security": [], "responses": {"204": {"description": "Logged out."}, "403": {"$ref": "#/components/responses/Forbidden"}}}}, "/api/auth/me": {"get": {"tags": ["auth"], "operationId": "getMe", "summary": "The logged-in user", "description": "401 if not logged in; its `code` is `setup_required` when no account with a password exists yet (first run).", "responses": {"200": {"description": "The current user.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/User"}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}}}}, "/api/auth/password": {"put": {"tags": ["auth"], "operationId": "changePassword", "summary": "Change your password", "description": "Verifies `current_password`, sets `new_password` (8–72 bytes) and logs out every **other** session of the user.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "required": ["current_password", "new_password"], "properties": {"current_password": {"type": "string", "format": "password"}, "new_password": {"type": "string", "format": "password", "minLength": 8}}, "additionalProperties": false}}}}, "responses": {"204": {"description": "Password changed."}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "403": {"description": "Current password is incorrect, or a cross-site request.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "415": {"$ref": "#/components/responses/UnsupportedMediaType"}, "422": {"$ref": "#/components/responses/ValidationFailed"}}}}, "/api/tokens": {"get": {"tags": ["tokens"], "operationId": "listTokens", "summary": "List your API tokens", "description": "Active (not revoked) tokens of the logged-in user, newest first. Secrets and hashes are never returned. Session only; a Bearer token gets 403 `session_required`.", "security": [{"cookieAuth": []}], "responses": {"200": {"description": "Your tokens.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/APITokenList"}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "403": {"$ref": "#/components/responses/SessionRequired"}}}, "post": {"tags": ["tokens"], "operationId": "createToken", "summary": "Create an API token", "description": "Creates a token for the logged-in user and returns its plaintext in `token` **once**; only its SHA-256 is stored. Scopes: `read` (GET/HEAD only) and `write` (every method). Tokens can never manage tokens, change the password, register users or log out (403 `session_required`). Session only.\n", "security": [{"cookieAuth": []}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/APITokenInput"}, "example": {"name": "Expense agent", "scopes": ["read", "write"], "expires_in_days": 90}}}}, "responses": {"201": {"description": "The new token, with its plaintext secret (shown only this once).", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/APITokenCreated"}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "403": {"$ref": "#/components/responses/SessionRequired"}, "415": {"$ref": "#/components/responses/UnsupportedMediaType"}, "422": {"$ref": "#/components/responses/ValidationFailed"}}}}, "/api/tokens/{uid}": {"delete": {"tags": ["tokens"], "operationId": "revokeToken", "summary": "Revoke an API token", "description": "Revokes one of your own tokens; it stops working immediately. Another user's token, an unknown or an already revoked one is 404. Session only.", "security": [{"cookieAuth": []}], "parameters": [{"name": "uid", "in": "path", "required": true, "description": "Token uid (UUID).", "schema": {"$ref": "#/components/schemas/Uid"}}], "responses": {"204": {"description": "Revoked."}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "403": {"$ref": "#/components/responses/SessionRequired"}, "404": {"description": "No such active token of yours.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}}}}}, "components": {"securitySchemes": {"cookieAuth": {"type": "apiKey", "in": "cookie", "name": "session", "description": "Session cookie set by `POST /api/auth/login` (or first-run `POST /api/auth/register`)."}, "bearerAuth": {"type": "http", "scheme": "bearer", "bearerFormat": "ext_<43 base64url chars>", "description": "Personal API token from `POST /api/tokens` (Settings → API tokens), sent as `Authorization: Bearer ext_...`. When this header is present the cookie is ignored. Invalid, expired or revoked tokens and disabled users get 401 `invalid_token`; a `read` token on a non-GET request gets 403 `insufficient_scope`; session-only endpoints give 403 `session_required`. Bearer requests skip the Origin / Sec-Fetch-Site CSRF checks (bodies must still be `application/json`).\n"}}, "parameters": {"TransactionUid": {"name": "uid", "in": "path", "required": true, "description": "Transaction uid (UUID, case-insensitive). Numeric ids are not accepted (400).", "schema": {"$ref": "#/components/schemas/Uid"}, "example": "1a8af4f6-006a-4712-baba-eb8f433bccb1"}, "BalanceUid": {"name": "uid", "in": "path", "required": true, "description": "Balance uid (UUID, case-insensitive). Numeric ids are not accepted (400).", "schema": {"$ref": "#/components/schemas/Uid"}, "example": "4dc73a4a-a60b-414e-98bc-3c71298a0af5"}, "CategoryUid": {"name": "uid", "in": "path", "required": true, "description": "Category uid (UUID, case-insensitive).", "schema": {"$ref": "#/components/schemas/Uid"}, "example": "32b0d51e-e81f-41f0-a77c-38e6ec384153"}, "UserUid": {"name": "uid", "in": "path", "required": true, "description": "Your own user uid (UUID, case-insensitive; see `GET /api/auth/me`). Any other uid, existing or not, is 404 `user not found`.", "schema": {"$ref": "#/components/schemas/Uid"}, "example": "3525dd1f-ae96-4c71-b996-06a43679cfa2"}, "IfMatch": {"name": "If-Match", "in": "header", "required": false, "description": "The version this write is based on, as an entity tag: the `ETag` (or `version`) of your last\nread, e.g. `\"3\"` (`W/\"3\"` also accepted; `*` and lists are not). Either this header or\n`\"version\"` in the body is **required** (428 if neither is sent). If both are sent they must agree (400).\nA stale version is a 409.\n", "schema": {"type": "string", "example": "\"3\""}}, "IfMatchOptional": {"name": "If-Match", "in": "header", "required": false, "description": "Optional. The `ETag` of your last read, e.g. `\"3\"`. If sent and stale the delete is refused with 409; if malformed, 400.", "schema": {"type": "string", "example": "\"3\""}}}, "headers": {"ETag": {"description": "The record's `version` as a strong entity tag, e.g. `\"3\"`. Send it back in `If-Match`.", "schema": {"type": "string", "example": "\"1\""}}, "LocationTransaction": {"description": "URL of the new transaction.", "schema": {"type": "string", "example": "/api/transactions/1a8af4f6-006a-4712-baba-eb8f433bccb1"}}, "LocationBalance": {"description": "URL of the new balance.", "schema": {"type": "string", "example": "/api/balances/4dc73a4a-a60b-414e-98bc-3c71298a0af5"}}, "LocationCategory": {"description": "URL of the new category.", "schema": {"type": "string", "example": "/api/categories/32b0d51e-e81f-41f0-a77c-38e6ec384153"}}, "LocationUser": {"description": "URL of the new user.", "schema": {"type": "string", "example": "/api/users/3525dd1f-ae96-4c71-b996-06a43679cfa2"}}}, "responses": {"SessionRequired": {"description": "Called with an API token (`code: session_required`): this endpoint needs a browser session. Or a cross-site request (`code: csrf`).", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": "this endpoint requires a browser session; API tokens cannot use it", "code": "session_required"}}}}, "Unauthorized": {"description": "Not logged in (no, unknown or expired session). `code` is `setup_required` while no account exists yet, else `unauthenticated`.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": "authentication required", "code": "unauthenticated"}}}}, "Forbidden": {"description": "Cross-site request rejected (`code: csrf`), registration closed (`code: registration_closed`), a `read` API token on a mutating request (`code: insufficient_scope`), or an API token on a session-only endpoint (`code: session_required`).", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "UnsupportedMediaType": {"description": "A request body that is not `Content-Type application/json`.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "BadRequest": {"description": "Malformed request: invalid JSON, a body that is not one JSON object, unknown field, wrong JSON\ntype, empty users patch, body over 64 KiB, a uid that is not UUID-shaped, or a malformed / disagreeing `If-Match`.\n", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "examples": {"malformed_json": {"value": {"error": "malformed JSON at byte 12"}}, "unknown_field": {"value": {"error": "unknown field \"account\""}}, "wrong_type": {"value": {"error": "field \"note\" must be a string"}}, "bad_uid": {"$ref": "#/components/examples/ErrBadUid"}, "bad_if_match": {"value": {"error": "If-Match must be a single version entity tag such as \"3\" (the ETag header or \"version\" field of your last read)"}}, "versions_disagree": {"value": {"error": "If-Match (\"3\") and the body \"version\" (2) disagree; send one, or the same value in both"}}}}}}, "BadUid": {"description": "The path uid is not UUID-shaped (e.g. a numeric id).", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "examples": {"bad_uid": {"$ref": "#/components/examples/ErrBadUid"}}}}}, "TransactionNotFound": {"description": "No transaction has this uid.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": "transaction not found"}}}}, "BalanceNotFound": {"description": "No balance has this uid.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": "balance not found"}}}}, "CategoryNotFound": {"description": "No category has this uid.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": "category not found"}}}}, "UserNotFound": {"description": "No user has this uid.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": "user not found"}}}}, "ValidationFailed": {"description": "Validation failed. `fields` lists every invalid field.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ValidationError"}, "example": {"error": "validation failed", "fields": {"name": "is required", "type": "is required (expense or income)"}}}}}, "TransactionValidationFailed": {"description": "Validation failed. `fields` lists every invalid field. This includes an unknown, non-allowed\nor wrong-currency `balance_uid` / `to_balance_uid`, a category of the wrong type,\n`type: balance_adjustment` on create or on another type, another type on a balance adjustment,\nand a missing or misplaced `adjustment_direction`.\n", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ValidationError"}, "examples": {"fields": {"$ref": "#/components/examples/ErrTxValidation"}, "currency_mismatch": {"$ref": "#/components/examples/ErrTxCurrencyMismatch"}, "balance_adjustment": {"$ref": "#/components/examples/ErrTxAdjustmentType"}, "balance_not_allowed": {"value": {"error": "validation failed", "fields": {"balance_uid": "must refer to a payment_account or credit_card balance"}}}}}}}, "BalanceValidationFailed": {"description": "Validation failed (per-type amount rules, immutable `type`, unknown currency, …).", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ValidationError"}, "examples": {"type_changed": {"value": {"error": "validation failed", "fields": {"type": "balance type cannot be changed after creation"}}}, "amount_rules": {"value": {"error": "validation failed", "fields": {"debt": "is required for type credit_card", "balance": "is not used for type credit_card (only for payment_account and other_asset)"}}}, "decimals": {"value": {"error": "validation failed", "fields": {"balance": "has too many decimal places (max 2 for this currency)"}}}}}}}, "VersionRequired": {"description": "Neither `If-Match` nor `\"version\"` was sent.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": "this update needs the version it is based on: send an If-Match header with the ETag of your last read (e.g. If-Match: \"3\") or \"version\" in the body", "code": "version_required"}}}}, "TransactionConflict": {"description": "`version_conflict`: the transaction changed since the version you sent. Nothing was saved,\n`current` is the transaction as it is now, and `ETag` is its version.\n`balance_adjustment_readonly`: the write would create a balance adjustment or change a\ntransaction's type to or from `balance_adjustment` (normally caught as a 422 first).\n", "headers": {"ETag": {"description": "Current version (only with `version_conflict`).", "schema": {"type": "string", "example": "\"2\""}}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/TransactionConflictError"}, "examples": {"version_conflict": {"$ref": "#/components/examples/ErrTxVersionConflict"}, "balance_adjustment_readonly": {"$ref": "#/components/examples/ErrTxReadOnly"}}}}}, "BalanceConflict": {"description": "`version_conflict` (stale version; `current` + `ETag` sent) or `balance_in_use` (currency change\nwhile transactions reference the balance).\n", "headers": {"ETag": {"description": "Current version (only with `version_conflict`).", "schema": {"type": "string", "example": "\"3\""}}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/BalanceConflictError"}, "examples": {"version_conflict": {"$ref": "#/components/examples/ErrBalanceVersionConflict"}, "balance_in_use": {"$ref": "#/components/examples/ErrBalanceInUse"}}}}}, "CategoryConflict": {"description": "Duplicate name within the type among the user's categories (case-insensitive), a type change while transactions use the category, or the per-user limit (500 categories) reached.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "examples": {"duplicate_name": {"value": {"error": "a category with this name and type already exists", "fields": {"name": "is already used by another category of this type (names are case-insensitive)"}}}, "in_use": {"value": {"error": "category is used by transactions (2 transaction(s)); its type cannot change; move those transactions to another category first"}}, "limit": {"value": {"error": "category limit reached (at most 500 categories per user)"}}}}}}, "UserConflict": {"description": "Username or email already used by another user (case-insensitive).", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "examples": {"username": {"value": {"error": "a user with this username already exists", "fields": {"username": "is already taken (usernames are case-insensitive)"}}}, "email": {"value": {"error": "a user with this email already exists", "fields": {"email": "is already used by another user"}}}}}}}, "DuplicateImportRef": {"description": "`import_ref` is already used by another transaction on the same balance (`code` duplicate_import_ref).", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": "import_ref \"KBANK-20261003-000123\" is already used by transaction ea67cb7c-9cef-4323-9b16-59a5139cb582 on this balance", "code": "duplicate_import_ref", "fields": {"import_ref": "is already used on this balance by transaction ea67cb7c-9cef-4323-9b16-59a5139cb582"}}}}}, "FXUnavailable": {"description": "The exchange-rate service (Frankfurter) is unreachable or timed out (`code` exchange_rate_unavailable). Retry later or send `to_amount`.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "FXBadGateway": {"description": "Frankfurter answered with an unexpected response (`code` exchange_rate_unavailable). Retry later or send `to_amount`.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, "InternalError": {"description": "Unexpected server error (details are only logged).", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}, "example": {"error": "internal server error"}}}}}, "schemas": {"APITokenScope": {"type": "string", "enum": ["read", "write"], "description": "`read`: GET/HEAD only. `write`: every method."}, "APIToken": {"type": "object", "required": ["uid", "name", "prefix", "scopes", "created_at", "last_used_at", "expires_at"], "properties": {"uid": {"$ref": "#/components/schemas/Uid"}, "name": {"type": "string", "maxLength": 64, "example": "Expense agent"}, "prefix": {"type": "string", "description": "First characters of the token (non-secret) to tell tokens apart.", "example": "ext_Ab12Cd34"}, "scopes": {"type": "array", "items": {"$ref": "#/components/schemas/APITokenScope"}}, "created_at": {"$ref": "#/components/schemas/Timestamp"}, "last_used_at": {"allOf": [{"$ref": "#/components/schemas/Timestamp"}], "nullable": true, "description": "Last successful use (updated at most once a minute); null if never used."}, "expires_at": {"allOf": [{"$ref": "#/components/schemas/Timestamp"}], "nullable": true, "description": "null means the token does not expire."}}}, "APITokenCreated": {"allOf": [{"$ref": "#/components/schemas/APIToken"}, {"type": "object", "required": ["token"], "properties": {"token": {"type": "string", "description": "The secret. Returned only in this response; store it safely.", "example": "ext_Ab12Cd34Ef56Gh78Ij90Kl12Mn34Op56Qr78St90Uv1"}}}]}, "APITokenInput": {"type": "object", "required": ["name", "scopes"], "additionalProperties": false, "properties": {"name": {"type": "string", "minLength": 1, "maxLength": 64, "description": "Trimmed; 1–64 characters.", "example": "Expense agent"}, "scopes": {"type": "array", "minItems": 1, "items": {"$ref": "#/components/schemas/APITokenScope"}}, "expires_in_days": {"type": "integer", "minimum": 1, "maximum": 3650, "description": "Omit for a token that never expires."}}}, "APITokenList": {"type": "object", "required": ["tokens", "count"], "properties": {"tokens": {"type": "array", "items": {"$ref": "#/components/schemas/APIToken"}}, "count": {"type": "integer"}}}, "Uid": {"type": "string", "format": "uuid", "description": "Server-assigned UUID v4. Lowercase in responses; accepted in any case.", "pattern": "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", "example": "4dc73a4a-a60b-414e-98bc-3c71298a0af5"}, "Currency": {"type": "string", "description": "ISO 4217 code (trimmed and upper-cased on input; responses are upper-case). Determines the minor-unit scale.", "pattern": "^[A-Za-z]{3}$", "example": "THB"}, "CurrencyInfo": {"type": "object", "description": "One supported currency (`GET /api/currencies`).", "required": ["code", "name", "scale", "flag"], "properties": {"code": {"type": "string", "example": "THB", "description": "ISO 4217 code. Send this (never the flag) in requests."}, "name": {"type": "string", "example": "Baht"}, "scale": {"type": "integer", "example": 2, "description": "Minor-unit digits (decimal places allowed in amounts)."}, "flag": {"type": "string", "example": "🇹🇭", "description": "Display-only emoji: the issuing country's flag as two Unicode regional indicator symbols,\nderived from the code's first two letters (ISO 3166-1 alpha-2), with overrides:\nEUR → 🇪🇺, ANG and XCG → 🇨🇼 (Curaçao), and 🌐 for currencies shared by several countries\n(XAF, XOF, XCD, XPF). Platforms without flag emoji show the two letters instead.\n"}}}, "DecimalInput": {"description": "Plain decimal as a JSON string (recommended) or number, read as text (never a float):\nno signs (except where negative values are allowed), commas, symbols or exponents.\nAt most 13 digits before the point, and at most as many decimals as the currency allows.\n", "oneOf": [{"type": "string", "example": "120.50"}, {"type": "number", "example": 120.5}]}, "Timestamp": {"type": "string", "format": "date-time", "description": "RFC 3339 in UTC with second precision.", "example": "2026-10-08T13:28:56Z"}, "Version": {"type": "integer", "format": "int64", "minimum": 1, "description": "Optimistic-locking version (1 on create, +1 on every change).", "example": 1}, "Error": {"type": "object", "description": "Shape of every error response.", "required": ["error"], "properties": {"error": {"type": "string", "description": "Human-readable message."}, "fields": {"type": "object", "description": "Field name → problem (validation, query, conflict and duplicate errors).", "additionalProperties": {"type": "string"}}, "code": {"type": "string", "description": "Stable machine-readable reason, present for some errors only.", "enum": ["version_required", "version_conflict", "balance_in_use", "balance_adjustment_readonly", "exchange_rate_unsupported", "exchange_rate_unavailable"]}, "current": {"type": "object", "description": "With `version_conflict` only, the record (Transaction or Balance) as it is now."}}}, "ValidationError": {"type": "object", "required": ["error", "fields"], "properties": {"error": {"type": "string", "enum": ["validation failed"]}, "fields": {"type": "object", "additionalProperties": {"type": "string"}}}}, "TransactionConflictError": {"type": "object", "required": ["error", "code"], "properties": {"error": {"type": "string"}, "code": {"type": "string", "enum": ["version_conflict", "balance_adjustment_readonly"]}, "fields": {"type": "object", "additionalProperties": {"type": "string"}}, "current": {"$ref": "#/components/schemas/Transaction"}}}, "BalanceConflictError": {"type": "object", "required": ["error"], "properties": {"error": {"type": "string"}, "code": {"type": "string", "enum": ["version_conflict", "balance_in_use"]}, "fields": {"type": "object", "additionalProperties": {"type": "string"}}, "current": {"$ref": "#/components/schemas/Balance"}}}, "TransactionType": {"type": "string", "description": "`expense`, `income`, `transfer`, `asset_purchase` (payment account / credit card → other asset;\na value move, not counted as expense or income), `return_on_investment` (income into a payment\naccount / credit card, linked to the other asset it came from, whose value does not change),\n`repay_debt` (payment account → credit card / other liability, debt down by the principal;\noptional interest and fees paid on top), or the\nserver-created `balance_adjustment` (editable and deletable, never created by clients).\n", "enum": ["expense", "income", "transfer", "asset_purchase", "return_on_investment", "repay_debt", "balance_adjustment"]}, "TransactionWriteType": {"type": "string", "description": "Types a client may write. Empty or omitted means `expense`. `balance_adjustment` is a 422, except\nwhen replacing an existing balance adjustment (where omitted means `balance_adjustment`).\n", "enum": ["expense", "income", "transfer", "asset_purchase", "return_on_investment", "repay_debt"], "default": "expense"}, "AdjustmentDirection": {"type": "string", "enum": ["increase", "decrease"], "description": "Whether the adjustment raises or lowers the adjusted amount (balance of an asset, debt of a liability)."}, "Transaction": {"type": "object", "required": ["uid", "amount", "amount_minor", "currency", "type", "balance_uid", "account", "to_balance_uid", "to_account", "category_uid", "spent_at", "note", "created_at", "updated_at", "version", "adjusts_balances", "adjustment_direction", "to_amount", "to_amount_minor", "to_currency", "exchange_rate", "rate_source", "rate_date", "import_ref", "foreign_amount", "foreign_amount_minor", "foreign_currency", "interest_amount", "interest_amount_minor", "fee_amount", "fee_amount_minor", "conversion_rates"], "properties": {"uid": {"$ref": "#/components/schemas/Uid"}, "amount": {"type": "string", "description": "Positive decimal string in the currency's scale. For a transfer this is the amount leaving the source balance (source currency).", "example": "120.50"}, "amount_minor": {"type": "integer", "format": "int64", "minimum": 1, "description": "The amount in integer minor units (`120.50` THB → 12050).", "example": 12050}, "currency": {"type": "string", "pattern": "^[A-Z]{3}$", "example": "THB"}, "type": {"$ref": "#/components/schemas/TransactionType"}, "balance_uid": {"type": "string", "format": "uuid", "description": "Paying (expense), receiving (income, return_on_investment), source (transfer, asset_purchase, repay_debt) or adjusted (balance_adjustment) balance. May point to a deleted balance.", "example": "4dc73a4a-a60b-414e-98bc-3c71298a0af5"}, "account": {"type": "string", "description": "Snapshot of the balance's name when the transaction was written (read-only).", "example": "Wallet"}, "to_balance_uid": {"type": "string", "format": "uuid", "nullable": true, "description": "Transfer, asset_purchase or repay_debt destination, or the other_asset a return_on_investment is tied to (not moved); `null` for other types.", "example": null}, "to_account": {"type": "string", "nullable": true, "description": "Snapshot of the destination balance's name; `null` unless transfer, asset_purchase, return_on_investment or repay_debt.", "example": null}, "category_uid": {"type": "string", "format": "uuid", "nullable": true, "description": "Linked category (expense/income only). Look the name up via `/api/categories`.", "example": "32b0d51e-e81f-41f0-a77c-38e6ec384153"}, "spent_at": {"type": "string", "format": "date-time", "description": "RFC 3339 at second precision with the offset as entered.", "example": "2026-10-06T21:06:00+08:00"}, "note": {"type": "string", "maxLength": 1000, "example": "Lunch"}, "created_at": {"$ref": "#/components/schemas/Timestamp"}, "updated_at": {"type": "string", "format": "date-time", "nullable": true, "description": "UTC; `null` until edited.", "example": null}, "version": {"$ref": "#/components/schemas/Version"}, "adjusts_balances": {"type": "boolean", "description": "`true` when this transaction's change is reflected in its balances (every transaction,\nbalance adjustments included: the manual edit set the value, so editing or deleting the\nadjustment moves the balance). Editing or deleting a row with `false` leaves balances alone.\n", "example": true}, "adjustment_direction": {"type": "string", "enum": ["increase", "decrease", null], "nullable": true, "description": "Set only for `balance_adjustment` (whether it raised or lowered the balance/debt); `null` otherwise.", "example": null}, "to_amount": {"type": "string", "nullable": true, "description": "Cross-currency transfers only — the amount credited to the destination, in `to_currency`. `null` otherwise (a same-currency transfer moves `amount`).", "example": null}, "to_amount_minor": {"type": "integer", "format": "int64", "nullable": true, "description": "`to_amount` in minor units of `to_currency`; `null` unless cross-currency.", "example": null}, "to_currency": {"type": "string", "nullable": true, "pattern": "^[A-Z]{3}$", "description": "The destination balance's currency, for cross-currency transfers only; `null` otherwise.", "example": null}, "exchange_rate": {"type": "string", "nullable": true, "description": "Units of `to_currency` per 1 `currency` (decimal string, up to 10 significant digits). For a manual rate it is `to_amount / amount`. Stored history; never refetched.", "example": null}, "rate_source": {"type": "string", "nullable": true, "enum": ["frankfurter", "manual", null], "description": "`frankfurter` (ECB reference rate fetched by the server) or `manual` (client sent `to_amount`); `null` unless cross-currency.", "example": null}, "rate_date": {"type": "string", "format": "date", "nullable": true, "description": "Date of the Frankfurter rate used (the previous working day for weekends/holidays); `null` for manual rates and non-cross-currency rows.", "example": null}, "import_ref": {"type": "string", "nullable": true, "maxLength": 200, "description": "Client-chosen idempotency key (e.g. a bank reference or a hash of date+amount+description), unique per `balance_uid`; `null` when not set. See docs/bulk-import.md.", "example": null}, "foreign_amount": {"type": "string", "nullable": true, "description": "Optional amount in another currency, for reference only (expense, income, asset_purchase and\nreturn_on_investment). E.g. a purchase of 25.00 USD paid from a THB account: `amount` is the\nTHB charged, `foreign_amount` 25.00 and `foreign_currency` USD. It never moves a balance and\nis not part of any total. `null` when not recorded.\n", "example": "25.00"}, "foreign_amount_minor": {"type": "integer", "format": "int64", "nullable": true, "minimum": 1, "description": "`foreign_amount` in minor units of `foreign_currency`; `null` when not recorded.", "example": 2500}, "foreign_currency": {"type": "string", "nullable": true, "pattern": "^[A-Z]{3}$", "description": "ISO 4217 code of `foreign_amount`; never equal to `currency`. `null` when not recorded.", "example": "USD"}, "interest_amount": {"type": "string", "nullable": true, "description": "`repay_debt` only: interest paid with the repayment, in `currency`. `amount` is the\nprincipal (the debt goes down by it); the payment account pays `amount` +\n`interest_amount` + `fee_amount`. Counted as an expense in reports. `null` when none.\n", "example": "12.50"}, "interest_amount_minor": {"type": "integer", "format": "int64", "nullable": true, "minimum": 1, "description": "`interest_amount` in minor units of `currency`; `null` when none.", "example": 1250}, "fee_amount": {"type": "string", "nullable": true, "description": "`repay_debt` only: other fees paid with the repayment (late fee, service charge, ...), in `currency`. Paid from the account like `interest_amount`; `null` when none.", "example": "3.00"}, "fee_amount_minor": {"type": "integer", "format": "int64", "nullable": true, "minimum": 1, "description": "`fee_amount` in minor units of `currency`; `null` when none.", "example": 300}, "conversion_rates": {"type": "array", "nullable": true, "readOnly": true, "minItems": 2, "maxItems": 2, "items": {"$ref": "#/components/schemas/ConversionRate"}, "description": "Response-only, computed on the fly (never stored). Cross-currency transfers only: both\ndirections of the rate the transfer actually used, derived from its own amounts. Item 0\nis `currency` → `to_currency` (`to_amount / amount`), item 1 is `to_currency` → `currency`\n(`amount / to_amount`). Decimal strings, up to 10 significant digits, rounded half-up.\nItem 0 equals `exchange_rate` for a manual rate; for a Frankfurter rate it can differ\nslightly because `to_amount` was rounded to the destination's minor unit.\n`null` for same-currency transfers (the rate is trivially 1), for every other type and\nif an amount is zero. Not accepted in request bodies (400 unknown field, like every other\nread-only field except `uid` and `version`).\n", "example": [{"from": "THB", "to": "SGD", "rate": "0.0397"}, {"from": "SGD", "to": "THB", "rate": "25.18891688"}]}}}, "ConversionRate": {"type": "object", "required": ["from", "to", "rate"], "properties": {"from": {"type": "string", "pattern": "^[A-Z]{3}$", "example": "THB"}, "to": {"type": "string", "pattern": "^[A-Z]{3}$", "example": "SGD"}, "rate": {"type": "string", "description": "Units of `to` per 1 `from` (decimal string, up to 10 significant digits).", "example": "0.0397"}}}, "ExchangeRate": {"type": "object", "required": ["from", "to", "rate", "date", "source"], "properties": {"from": {"type": "string", "example": "USD"}, "to": {"type": "string", "example": "THB"}, "rate": {"type": "string", "description": "Units of `to` per 1 `from` (decimal string).", "example": "33.615"}, "date": {"type": "string", "format": "date", "description": "Date the rate applies to (ECB working day; may be earlier than the requested date).", "example": "2026-10-12"}, "source": {"type": "string", "enum": ["frankfurter", "same_currency"], "example": "frankfurter"}}}, "TransactionInput": {"type": "object", "description": "Body of POST and PUT. Unknown fields are a 400.", "required": ["amount", "currency", "balance_uid", "spent_at"], "properties": {"amount": {"allOf": [{"$ref": "#/components/schemas/DecimalInput"}], "description": "Positive amount (> 0) as a decimal string or number."}, "currency": {"$ref": "#/components/schemas/Currency"}, "type": {"$ref": "#/components/schemas/TransactionWriteType"}, "balance_uid": {"type": "string", "format": "uuid", "description": "Source balance. Allowed types depend on `type` (see the table at the top). Its currency must equal `currency`.", "example": "4dc73a4a-a60b-414e-98bc-3c71298a0af5"}, "to_balance_uid": {"type": "string", "format": "uuid", "nullable": true, "description": "Required for `transfer` (any balance, any currency — see `to_amount`) `asset_purchase` (must be an `other_asset` in the same currency) and `return_on_investment` (the `other_asset` the return came from; any currency, its value is not changed) and `repay_debt` (a `credit_card` or `other_liability` in the same currency, whose debt goes down); ≠ `balance_uid`. Not allowed otherwise."}, "to_amount": {"allOf": [{"$ref": "#/components/schemas/DecimalInput"}], "nullable": true, "description": "Transfer only. Amount received by the destination, in its currency.\nCross-currency transfer: sent → manual rate (`exchange_rate = to_amount / amount`);\nomitted → the server converts with the Frankfurter (ECB) rate for the `spent_at` date,\nrounded half-up to the destination currency's scale (422 if the pair is unsupported,\n503/502 if Frankfurter is unreachable — then send `to_amount`). On PUT, omitting it keeps\nthe stored conversion if amount, currency, date and balances are unchanged, else refetches.\nSame-currency transfer: must be omitted or equal `amount`.\n"}, "to_currency": {"type": "string", "nullable": true, "description": "Transfer only, optional. If sent it must equal the destination balance's currency."}, "foreign_amount": {"allOf": [{"$ref": "#/components/schemas/DecimalInput"}], "nullable": true, "description": "Optional, for expense, income, asset_purchase and return_on_investment only (422 otherwise).\nThe amount in `foreign_currency` (> 0, at most that currency's minor digits), e.g. the USD\nprice of a purchase charged to a THB account. Recorded for reference only: balances and\ntotals always use `amount`. Send together with `foreign_currency`, or omit both. PUT is a\nfull replace: omitting both clears a stored foreign amount.\n", "example": "25.00"}, "foreign_currency": {"type": "string", "nullable": true, "description": "ISO 4217 code of `foreign_amount`; required with it, and must differ from `currency`.", "example": "USD"}, "interest_amount": {"allOf": [{"$ref": "#/components/schemas/DecimalInput"}], "nullable": true, "description": "`repay_debt` only (422 otherwise): interest paid on top of the principal (`amount`), in\n`currency`, 0 or more; empty or 0 means none. The payment account pays amount + interest +\nfees; the debt goes down by `amount` only. PUT is a full replace: omitting it clears it.\n", "example": "12.50"}, "fee_amount": {"allOf": [{"$ref": "#/components/schemas/DecimalInput"}], "nullable": true, "description": "`repay_debt` only (422 otherwise): other fees paid on top of the principal, in `currency`; same rules as `interest_amount`.", "example": "3.00"}, "category_uid": {"type": "string", "format": "uuid", "nullable": true, "description": "**Required** for expense, income, asset_purchase and return_on_investment (422 \"is required\nfor an expense\", ... when missing, null or \"\"): an expense category for an expense or\nasset_purchase, an income category for income or return_on_investment. Not allowed for\ntransfers. Optional for repay_debt, and only when it has `interest_amount` or `fee_amount`:\nthe expense category those charges are reported under. Transactions saved before this rule may still have `null` until edited.\n"}, "spent_at": {"type": "string", "format": "date-time", "description": "RFC 3339 / ISO 8601 date-time with an offset (`Z` or `±hh:mm`). Values without an offset are a 422.", "example": "2026-10-06T21:06:00+08:00"}, "note": {"type": "string", "nullable": true, "maxLength": 1000, "description": "Trimmed. Omitted or `null` means empty."}, "adjustment_direction": {"allOf": [{"$ref": "#/components/schemas/AdjustmentDirection"}], "nullable": true, "description": "PUT of a `balance_adjustment` only, and required there: `increase` raises the balance (asset)\nor debt (liability) of `balance_uid` by `amount`, `decrease` lowers it. Empty or `null` on\nother types (a value is a 422). A replaced adjustment moves the balance by the difference.\n"}, "import_ref": {"type": "string", "nullable": true, "maxLength": 200, "description": "Optional idempotency key (trimmed, ≤ 200 characters, no control characters), unique per\n`balance_uid`. On POST and PUT a ref already used by another transaction on the same balance\nis a 409 (`code` duplicate_import_ref); in POST /api/transactions/bulk it is reported as\n`skipped`. On POST, omitted, empty or `null` means none. On PUT, omitted or `null` keeps the\nstored ref and `\"\"` clears it.\n", "example": "KBANK-20261003-000123"}, "uid": {"type": "string", "description": "Accepted and ignored (the uid is immutable)."}, "version": {"type": "integer", "format": "int64", "minimum": 1, "description": "PUT only, as an alternative to `If-Match`. Ignored on POST."}}, "additionalProperties": false}, "BulkTransactionRequest": {"type": "object", "required": ["transactions"], "additionalProperties": false, "properties": {"transactions": {"type": "array", "minItems": 1, "maxItems": 500, "items": {"$ref": "#/components/schemas/TransactionInput"}, "description": "Same item shape as POST /api/transactions (plus optional `import_ref`; `uid`/`version` not accepted). Inserted in this order."}, "atomic": {"type": "boolean", "default": true, "description": "All-or-nothing (true) or insert every valid item (false)."}, "dry_run": {"type": "boolean", "default": false, "description": "Validate and compute effects only; nothing is written."}}}, "BulkItemError": {"type": "object", "required": ["message", "code"], "properties": {"message": {"type": "string", "example": "validation failed"}, "code": {"type": "string", "enum": ["validation_failed", "invalid_item", "exchange_rate_unsupported", "exchange_rate_unavailable", "balance_adjustment_readonly"]}, "fields": {"type": "object", "additionalProperties": {"type": "string"}, "example": {"balance_uid": "balance \"Wallet\" is in THB but the transaction is in USD; the currencies must match"}}}}, "BulkTransactionResult": {"type": "object", "required": ["index", "status"], "properties": {"index": {"type": "integer", "description": "Position in the request array (results keep input order)."}, "status": {"type": "string", "enum": ["created", "skipped", "failed", "valid"], "description": "`valid` = would be created (dry run, or an atomic batch that was rolled back because another item failed)."}, "transaction": {"allOf": [{"$ref": "#/components/schemas/Transaction"}], "description": "For created/valid. For `valid` items nothing was stored, so `uid` and `created_at` are empty and `version` is 0."}, "existing_uid": {"type": "string", "format": "uuid", "description": "For skipped. The transaction that already has this `import_ref` on the balance."}, "error": {"$ref": "#/components/schemas/BulkItemError"}}}, "BulkTransactionResponse": {"type": "object", "required": ["created", "skipped", "failed", "valid", "dry_run", "atomic", "written", "results", "balances"], "properties": {"created": {"type": "integer"}, "skipped": {"type": "integer"}, "failed": {"type": "integer"}, "valid": {"type": "integer", "description": "Items that passed but were not written (dry run or rolled-back atomic batch)."}, "dry_run": {"type": "boolean"}, "atomic": {"type": "boolean"}, "written": {"type": "boolean", "description": "True when the database transaction was committed."}, "results": {"type": "array", "items": {"$ref": "#/components/schemas/BulkTransactionResult"}}, "balances": {"type": "array", "items": {"$ref": "#/components/schemas/Balance"}, "description": "Balances touched by created/valid items, as they are (or would be, for a dry run or a rolled-back batch) after the request."}}}, "TransactionList": {"type": "object", "required": ["transactions", "count", "next_cursor"], "properties": {"transactions": {"type": "array", "items": {"$ref": "#/components/schemas/Transaction"}}, "count": {"type": "integer", "description": "Number of items returned (not the total number of matches).", "example": 1}, "next_cursor": {"type": "string", "nullable": true, "description": "Pass as `cursor` to get the next page; null on the last page.", "example": null}}}, "BalanceType": {"type": "string", "description": "`payment_account` and `other_asset` are assets (they have `balance`); `credit_card` and `other_liability` are liabilities (they have `debt` and `limit`).", "enum": ["payment_account", "credit_card", "other_asset", "other_liability"]}, "Balance": {"type": "object", "description": "Fields that do not apply to the type are `null`: assets have `balance`; liabilities have\n`debt`, `limit`, `available` and `over_limit`.\n", "required": ["uid", "name", "type", "kind", "currency", "description", "balance", "balance_minor", "debt", "debt_minor", "limit", "limit_minor", "available", "available_minor", "over_limit", "hidden", "created_at", "updated_at", "version"], "properties": {"uid": {"$ref": "#/components/schemas/Uid"}, "name": {"type": "string", "maxLength": 100, "example": "Wallet"}, "type": {"$ref": "#/components/schemas/BalanceType"}, "kind": {"type": "string", "enum": ["asset", "liability"], "description": "Derived from `type`."}, "currency": {"type": "string", "pattern": "^[A-Z]{3}$", "example": "THB"}, "description": {"type": "string", "maxLength": 1000, "example": ""}, "balance": {"type": "string", "nullable": true, "description": "Assets only. May be negative (overdraft).", "example": "10000.00"}, "balance_minor": {"type": "integer", "format": "int64", "nullable": true, "example": 1000000}, "debt": {"type": "string", "nullable": true, "description": "Liabilities only. May be negative (in credit).", "example": null}, "debt_minor": {"type": "integer", "format": "int64", "nullable": true, "example": null}, "limit": {"type": "string", "nullable": true, "description": "Liabilities only; ≥ 0.", "example": null}, "limit_minor": {"type": "integer", "format": "int64", "nullable": true, "example": null}, "available": {"type": "string", "nullable": true, "description": "limit − debt (liabilities only). Negative when over the limit.", "example": null}, "available_minor": {"type": "integer", "format": "int64", "nullable": true, "example": null}, "over_limit": {"type": "boolean", "nullable": true, "description": "debt > limit (liabilities only).", "example": null}, "hidden": {"type": "boolean", "description": "Hidden with `POST /api/balances/{uid}/hide`: left out of `GET /api/balances` unless\n`include_hidden` is set. Its transactions are kept. Not a PUT field.\n", "example": false}, "created_at": {"$ref": "#/components/schemas/Timestamp"}, "updated_at": {"type": "string", "format": "date-time", "nullable": true, "description": "UTC; `null` until changed manually or by a transaction.", "example": null}, "version": {"$ref": "#/components/schemas/Version"}}}, "BalanceInput": {"type": "object", "description": "Body of POST and PUT. Amounts that are absent, `null` or `\"\"` count as not provided. Unknown\nfields are a 400. This includes read-only response fields such as `kind`, `*_minor`, `available`,\n`over_limit`, `hidden`, `created_at` and `updated_at` (hide with `POST .../hide`).\n", "required": ["name", "type", "currency"], "properties": {"name": {"type": "string", "maxLength": 100, "description": "Trimmed; unique case-insensitively.", "example": "Wallet"}, "type": {"allOf": [{"$ref": "#/components/schemas/BalanceType"}], "description": "Required. On PUT it must equal the stored type (immutable)."}, "currency": {"$ref": "#/components/schemas/Currency"}, "description": {"type": "string", "nullable": true, "maxLength": 1000}, "balance": {"allOf": [{"$ref": "#/components/schemas/DecimalInput"}], "nullable": true, "description": "Required for assets (may be negative). Not allowed for liabilities."}, "debt": {"allOf": [{"$ref": "#/components/schemas/DecimalInput"}], "nullable": true, "description": "Required for liabilities (may be negative). Not allowed for assets."}, "limit": {"allOf": [{"$ref": "#/components/schemas/DecimalInput"}], "nullable": true, "description": "Required for liabilities (≥ 0). Not allowed for assets."}, "uid": {"type": "string", "description": "Accepted and ignored."}, "version": {"type": "integer", "format": "int64", "minimum": 1, "description": "PUT only, as an alternative to `If-Match`. Ignored on POST."}}, "additionalProperties": false}, "BalanceTotals": {"type": "object", "description": "Sums for one currency over the returned balances (decimal strings only; no conversion).", "required": ["currency", "assets", "liabilities", "net", "credit_limit", "available_credit"], "properties": {"currency": {"type": "string", "example": "THB"}, "assets": {"type": "string", "description": "Sum of asset balances.", "example": "10000.00"}, "liabilities": {"type": "string", "description": "Sum of liability debts.", "example": "52000.00"}, "net": {"type": "string", "description": "assets − liabilities.", "example": "-42000.00"}, "credit_limit": {"type": "string", "description": "Sum of liability limits.", "example": "50000.00"}, "available_credit": {"type": "string", "description": "credit_limit − liabilities.", "example": "-2000.00"}}}, "BalanceDeleted": {"type": "object", "required": ["deleted_transactions"], "properties": {"deleted_transactions": {"type": "integer", "description": "How many transactions were deleted with the balance.", "example": 3}}}, "BalanceList": {"type": "object", "required": ["balances", "count", "totals"], "properties": {"balances": {"type": "array", "items": {"$ref": "#/components/schemas/Balance"}}, "count": {"type": "integer", "example": 2}, "totals": {"type": "array", "description": "One entry per currency, in alphabetical order.", "items": {"$ref": "#/components/schemas/BalanceTotals"}}}}, "ReportInfo": {"type": "object", "required": ["id", "name", "description", "path"], "properties": {"id": {"type": "string", "example": "income-expense"}, "name": {"type": "string", "example": "Income & expenses"}, "description": {"type": "string"}, "path": {"type": "string", "example": "/api/reports/income-expense"}}}, "ReportCategoryAmount": {"type": "object", "required": ["category_uid", "category_name", "amount", "amount_minor", "count"], "properties": {"category_uid": {"type": "string", "format": "uuid", "nullable": true, "description": "null for transactions saved without a category."}, "category_name": {"type": "string", "nullable": true, "example": "Food", "description": "null when there is no category."}, "amount": {"type": "string", "example": "1250.50"}, "amount_minor": {"type": "string", "description": "Integer minor units as a string (sums may exceed 64 bits).", "example": "125050"}, "count": {"type": "integer", "description": "Number of transactions.", "example": 14}}}, "ReportCurrencyFlow": {"type": "object", "required": ["currency", "income", "expense", "net", "income_count", "expense_count", "income_by_category", "expense_by_category"], "properties": {"currency": {"type": "string", "example": "THB"}, "income": {"type": "string", "example": "52000.00"}, "expense": {"type": "string", "example": "18340.25"}, "net": {"type": "string", "description": "income − expense; may be negative.", "example": "33659.75"}, "income_count": {"type": "integer", "example": 2}, "expense_count": {"type": "integer", "example": 41}, "income_by_category": {"type": "array", "description": "Largest first.", "items": {"$ref": "#/components/schemas/ReportCategoryAmount"}}, "expense_by_category": {"type": "array", "description": "Largest first.", "items": {"$ref": "#/components/schemas/ReportCategoryAmount"}}}}, "IncomeExpenseReport": {"type": "object", "required": ["report", "from", "to", "currencies"], "properties": {"report": {"type": "string", "enum": ["income-expense"]}, "from": {"type": "string", "nullable": true, "description": "The from filter as sent; null when not set.", "example": "2026-11-01T00:00:00+07:00"}, "to": {"type": "string", "nullable": true, "description": "The to filter as sent; null when not set.", "example": "2026-11-30T23:59:59+07:00"}, "currencies": {"type": "array", "description": "One entry per currency with income or expenses in the range, alphabetical.", "items": {"$ref": "#/components/schemas/ReportCurrencyFlow"}}}}, "ReportAccountAmount": {"type": "object", "required": ["uid", "name", "type", "kind", "amount", "amount_minor"], "properties": {"uid": {"$ref": "#/components/schemas/Uid"}, "name": {"type": "string", "example": "Wallet"}, "type": {"$ref": "#/components/schemas/BalanceType"}, "kind": {"type": "string", "enum": ["asset", "liability"]}, "amount": {"type": "string", "description": "Balance of an asset or debt of a liability; may be negative.", "example": "4879.50"}, "amount_minor": {"type": "integer", "format": "int64", "example": 487950}}}, "ReportTypeAmount": {"type": "object", "required": ["type", "kind", "amount", "count"], "properties": {"type": {"$ref": "#/components/schemas/BalanceType"}, "kind": {"type": "string", "enum": ["asset", "liability"]}, "amount": {"type": "string", "description": "Sum of balances (assets) or debts (liabilities).", "example": "4879.50"}, "count": {"type": "integer", "description": "Number of balances.", "example": 2}}}, "ReportCurrencyPosition": {"type": "object", "required": ["currency", "assets", "liabilities", "net", "by_type", "accounts"], "properties": {"currency": {"type": "string", "example": "THB"}, "assets": {"type": "string", "example": "54879.50"}, "liabilities": {"type": "string", "example": "12000.00"}, "net": {"type": "string", "description": "assets − liabilities.", "example": "42879.50"}, "by_type": {"type": "array", "description": "Balance types present, in the order payment_account, credit_card, other_asset, other_liability.", "items": {"$ref": "#/components/schemas/ReportTypeAmount"}}, "accounts": {"type": "array", "description": "Assets first, then liabilities; each largest first.", "items": {"$ref": "#/components/schemas/ReportAccountAmount"}}}}, "AssetsLiabilitiesReport": {"type": "object", "required": ["report", "as_of", "currencies"], "properties": {"report": {"type": "string", "enum": ["assets-liabilities"]}, "as_of": {"$ref": "#/components/schemas/Timestamp"}, "currencies": {"type": "array", "description": "One entry per currency with at least one balance, alphabetical.", "items": {"$ref": "#/components/schemas/ReportCurrencyPosition"}}}}, "CategoryType": {"type": "string", "enum": ["expense", "income"]}, "Category": {"type": "object", "required": ["uid", "name", "type", "description", "created_at", "updated_at"], "properties": {"uid": {"$ref": "#/components/schemas/Uid"}, "name": {"type": "string", "maxLength": 100, "example": "Food"}, "type": {"$ref": "#/components/schemas/CategoryType"}, "description": {"type": "string", "maxLength": 1000, "example": "Groceries and restaurants"}, "created_at": {"$ref": "#/components/schemas/Timestamp"}, "updated_at": {"type": "string", "format": "date-time", "nullable": true, "example": null}}}, "CategoryInput": {"type": "object", "description": "Body of POST and PUT. Names are unique per type, case-insensitively. Unknown fields (including `created_at` / `updated_at`) are a 400.", "required": ["name", "type"], "properties": {"name": {"type": "string", "maxLength": 100, "example": "Food"}, "type": {"$ref": "#/components/schemas/CategoryType"}, "description": {"type": "string", "nullable": true, "maxLength": 1000}, "uid": {"type": "string", "description": "Accepted and ignored."}}, "additionalProperties": false}, "CategoryList": {"type": "object", "required": ["categories", "count"], "properties": {"categories": {"type": "array", "items": {"$ref": "#/components/schemas/Category"}}, "count": {"type": "integer", "example": 1}}}, "Preferences": {"type": "object", "description": "The user's preferences, stored server-side as one JSON object per user. Responses always\ncontain every key with its effective value (defaults filled in). On input every key is\noptional (omitted = default) and unknown keys are rejected; more keys will be added over time.\n", "additionalProperties": false, "required": ["base_currency"], "properties": {"base_currency": {"type": "string", "description": "ISO 4217 code from `GET /api/currencies` (trimmed and upper-cased on input). Default `USD`; `\"\"` also means the default.", "pattern": "^[A-Za-z]{3}$", "example": "THB"}}, "example": {"base_currency": "THB"}}, "User": {"type": "object", "description": "A user profile. The password hash is never returned; `has_password` says whether one is set.", "required": ["uid", "username", "email", "email_verified_at", "display_name", "preferences", "status", "has_password", "password_updated_at", "last_login_at", "created_at", "updated_at"], "properties": {"uid": {"$ref": "#/components/schemas/Uid"}, "username": {"type": "string", "nullable": true, "description": "Lowercase, 3–32 characters (letters, digits, `.`, `_`, `-`; starts with a letter or digit). Unique case-insensitively.", "pattern": "^[a-z0-9][a-z0-9._-]{2,31}$", "example": "alex"}, "email": {"type": "string", "format": "email", "nullable": true, "description": "Lowercased; unique.", "example": "alex@example.com"}, "email_verified_at": {"type": "string", "format": "date-time", "nullable": true, "description": "Reserved for a future verification flow.", "example": null}, "display_name": {"type": "string", "maxLength": 100, "example": "Alex Example"}, "preferences": {"$ref": "#/components/schemas/Preferences"}, "status": {"type": "string", "enum": ["active", "disabled"], "description": "Always `active` for now (`disabled` is reserved)."}, "has_password": {"type": "boolean", "example": false}, "password_updated_at": {"type": "string", "format": "date-time", "nullable": true, "example": null}, "last_login_at": {"type": "string", "format": "date-time", "nullable": true, "example": null}, "created_at": {"$ref": "#/components/schemas/Timestamp"}, "updated_at": {"type": "string", "format": "date-time", "nullable": true, "example": null}}}, "UserInput": {"type": "object", "description": "Body of POST and PUT. `password` / `password_hash` and other unknown fields are a 400.\nRead-only fields are accepted and ignored.\n", "required": ["display_name"], "properties": {"display_name": {"type": "string", "maxLength": 100, "description": "Trimmed; required."}, "username": {"type": "string", "nullable": true, "description": "`null`, `\"\"` or omitted means none. Case-insensitive; stored lowercase. 3–32 characters: letters, digits, `.`, `_`, `-`, starting with a letter or digit."}, "email": {"type": "string", "nullable": true, "maxLength": 254, "description": "`null`, `\"\"` or omitted means none. A bare address such as `name@example.com`."}, "preferences": {"type": "object", "additionalProperties": true, "nullable": true, "description": "A `Preferences` object. Omitted or `null` means all defaults. Not an object, an unknown key or an unsupported `base_currency` is a 422 (field `preferences` or `preferences.<key>`)."}, "uid": {"type": "string", "description": "Ignored."}, "status": {"type": "string", "description": "Ignored."}, "has_password": {"type": "boolean", "description": "Ignored."}, "email_verified_at": {"type": "string", "nullable": true, "description": "Ignored."}, "password_updated_at": {"type": "string", "nullable": true, "description": "Ignored."}, "last_login_at": {"type": "string", "nullable": true, "description": "Ignored."}, "created_at": {"type": "string", "nullable": true, "description": "Ignored."}, "updated_at": {"type": "string", "nullable": true, "description": "Ignored."}}, "additionalProperties": false}, "UserPatch": {"type": "object", "description": "At least one of `display_name`, `username`, `email`, `preferences`. Read-only fields are ignored; unknown fields are a 400.", "minProperties": 1, "properties": {"display_name": {"type": "string", "maxLength": 100, "description": "`null` is a 422."}, "username": {"type": "string", "nullable": true, "description": "`null` or `\"\"` removes it."}, "email": {"type": "string", "nullable": true, "description": "`null` or `\"\"` removes it."}, "preferences": {"type": "object", "additionalProperties": true, "nullable": true, "description": "Replaces the whole object (see `Preferences`); `null` resets every preference to its default. Invalid values are a 422."}, "uid": {"type": "string", "description": "Ignored."}, "status": {"type": "string", "description": "Ignored."}, "has_password": {"type": "boolean", "description": "Ignored."}, "email_verified_at": {"type": "string", "nullable": true, "description": "Ignored."}, "password_updated_at": {"type": "string", "nullable": true, "description": "Ignored."}, "last_login_at": {"type": "string", "nullable": true, "description": "Ignored."}, "created_at": {"type": "string", "nullable": true, "description": "Ignored."}, "updated_at": {"type": "string", "nullable": true, "description": "Ignored."}}, "additionalProperties": false}, "UserList": {"type": "object", "required": ["users", "count"], "properties": {"users": {"type": "array", "items": {"$ref": "#/components/schemas/User"}}, "count": {"type": "integer", "example": 1}}}, "Identity": {"type": "object", "description": "A linked SSO account. (`provider`, `provider_subject`) is the provider's stable user id, unique per provider.", "required": ["uid", "user_uid", "provider", "provider_subject", "email", "created_at", "last_used_at"], "properties": {"uid": {"$ref": "#/components/schemas/Uid"}, "user_uid": {"type": "string", "format": "uuid", "example": "3525dd1f-ae96-4c71-b996-06a43679cfa2"}, "provider": {"type": "string", "enum": ["apple", "google"]}, "provider_subject": {"type": "string", "maxLength": 255, "description": "The OIDC `sub` claim.", "example": "001234.abcdef0123456789.0123"}, "email": {"type": "string", "nullable": true, "description": "As reported by the provider (may be a relay address).", "example": null}, "created_at": {"$ref": "#/components/schemas/Timestamp"}, "last_used_at": {"type": "string", "format": "date-time", "nullable": true, "example": null}}}, "IdentityList": {"type": "object", "required": ["identities", "count"], "properties": {"identities": {"type": "array", "items": {"$ref": "#/components/schemas/Identity"}}, "count": {"type": "integer", "example": 0}}}}, "examples": {"BulkStatementImport": {"summary": "Statement import (sample data)", "value": {"atomic": true, "dry_run": false, "transactions": [{"type": "expense", "amount": "45.00", "currency": "THB", "balance_uid": "4dc73a4a-a60b-414e-98bc-3c71298a0af5", "category_uid": "32b0d51e-e81f-41f0-a77c-38e6ec384153", "spent_at": "2026-10-01T08:15:00+07:00", "note": "SAMPLE COFFEE SHOP", "import_ref": "stmt-2026-10:0001"}, {"type": "income", "amount": "30000.00", "currency": "THB", "balance_uid": "4dc73a4a-a60b-414e-98bc-3c71298a0af5", "category_uid": "5d3c1b7a-8f2e-4c61-9a0d-2b7e4f6a1c93", "spent_at": "2026-10-01T09:00:00+07:00", "note": "SAMPLE PAYROLL", "import_ref": "stmt-2026-10:0002"}, {"type": "transfer", "amount": "5000.00", "currency": "THB", "balance_uid": "4dc73a4a-a60b-414e-98bc-3c71298a0af5", "to_balance_uid": "a8465748-a48b-426a-9466-9a6706d8143a", "spent_at": "2026-10-02T12:00:00+07:00", "note": "SAMPLE CARD PAYMENT", "import_ref": "stmt-2026-10:0003"}]}}, "BulkResponseCreated": {"summary": "Committed atomic import", "value": {"created": 1, "skipped": 0, "failed": 0, "valid": 0, "dry_run": false, "atomic": true, "written": true, "results": [{"index": 0, "status": "created", "transaction": {"uid": "ea67cb7c-9cef-4323-9b16-59a5139cb582", "amount": "45.00", "amount_minor": 4500, "currency": "THB", "type": "expense", "balance_uid": "4dc73a4a-a60b-414e-98bc-3c71298a0af5", "account": "Wallet", "to_balance_uid": null, "to_account": null, "category_uid": "32b0d51e-e81f-41f0-a77c-38e6ec384153", "spent_at": "2026-10-01T08:15:00+07:00", "note": "SAMPLE COFFEE SHOP", "created_at": "2026-10-17T05:31:00Z", "updated_at": null, "version": 1, "adjusts_balances": true, "adjustment_direction": null, "to_amount": null, "to_amount_minor": null, "to_currency": null, "exchange_rate": null, "rate_source": null, "rate_date": null, "import_ref": "stmt-2026-10:0001", "foreign_amount": null, "foreign_amount_minor": null, "foreign_currency": null, "interest_amount": null, "interest_amount_minor": null, "fee_amount": null, "fee_amount_minor": null}}], "balances": []}}, "BulkResponseReimport": {"summary": "Same import sent again (all skipped)", "value": {"created": 0, "skipped": 1, "failed": 0, "valid": 0, "dry_run": false, "atomic": true, "written": true, "results": [{"index": 0, "status": "skipped", "existing_uid": "ea67cb7c-9cef-4323-9b16-59a5139cb582"}], "balances": []}}, "BulkResponseFailed": {"summary": "Atomic batch rejected (nothing written)", "value": {"created": 0, "skipped": 0, "failed": 1, "valid": 1, "dry_run": false, "atomic": true, "written": false, "results": [{"index": 0, "status": "valid"}, {"index": 1, "status": "failed", "error": {"message": "validation failed", "code": "validation_failed", "fields": {"type": "balance_adjustment transactions are created automatically when a balance amount is edited (PUT /api/balances/:uid); they cannot be created here, and other transactions cannot be turned into one"}}}], "balances": []}}, "TransactionInputExpense": {"summary": "Expense with a category", "value": {"amount": "120.50", "currency": "THB", "balance_uid": "4dc73a4a-a60b-414e-98bc-3c71298a0af5", "category_uid": "32b0d51e-e81f-41f0-a77c-38e6ec384153", "spent_at": "2026-10-06T21:06:00+08:00", "note": "Lunch"}}, "TransactionInputIncome": {"summary": "Income (amount as a JSON number)", "value": {"type": "income", "amount": 45000, "currency": "THB", "balance_uid": "4dc73a4a-a60b-414e-98bc-3c71298a0af5", "category_uid": "5d3c1b7a-8f2e-4c61-9a0d-2b7e4f6a1c93", "spent_at": "2026-10-01T09:00:00+07:00", "note": "Salary"}}, "TransactionInputTransfer": {"summary": "Transfer (pay a credit card from a bank account)", "value": {"type": "transfer", "amount": "5000", "currency": "THB", "balance_uid": "4dc73a4a-a60b-414e-98bc-3c71298a0af5", "to_balance_uid": "a8465748-a48b-426a-9466-9a6706d8143a", "spent_at": "2026-10-07T22:00:00+08:00"}}, "TransactionExpense": {"summary": "Expense", "value": {"uid": "1a8af4f6-006a-4712-baba-eb8f433bccb1", "amount": "120.50", "amount_minor": 12050, "currency": "THB", "type": "expense", "balance_uid": "4dc73a4a-a60b-414e-98bc-3c71298a0af5", "account": "Wallet", "to_balance_uid": null, "to_account": null, "category_uid": "32b0d51e-e81f-41f0-a77c-38e6ec384153", "spent_at": "2026-10-06T21:06:00+08:00", "note": "Lunch", "created_at": "2026-10-08T13:29:10Z", "updated_at": null, "version": 1, "adjusts_balances": true, "adjustment_direction": null}}, "TransactionTransfer": {"summary": "Transfer", "value": {"uid": "ea67cb7c-9cef-4323-9b16-59a5139cb582", "amount": "5000.00", "amount_minor": 500000, "currency": "THB", "type": "transfer", "balance_uid": "4dc73a4a-a60b-414e-98bc-3c71298a0af5", "account": "Wallet", "to_balance_uid": "a8465748-a48b-426a-9466-9a6706d8143a", "to_account": "Credit Card", "category_uid": null, "spent_at": "2026-10-07T22:00:00+08:00", "note": "", "created_at": "2026-10-08T13:29:10Z", "updated_at": null, "version": 1, "adjusts_balances": true, "adjustment_direction": null}}, "TransactionAdjustment": {"summary": "Balance adjustment (server-created, editable)", "value": {"uid": "18cf7c99-fa61-4924-ab1a-49daa00f3218", "amount": "120.50", "amount_minor": 12050, "currency": "THB", "type": "balance_adjustment", "balance_uid": "4dc73a4a-a60b-414e-98bc-3c71298a0af5", "account": "Wallet", "to_balance_uid": null, "to_account": null, "category_uid": null, "spent_at": "2026-10-08T21:29:10+08:00", "note": "Manual edit of balance: 4879.50 → 5000.00", "created_at": "2026-10-08T13:29:10Z", "updated_at": null, "version": 1, "adjusts_balances": true, "adjustment_direction": "increase"}}, "BalanceAsset": {"summary": "Payment account (asset)", "value": {"uid": "4dc73a4a-a60b-414e-98bc-3c71298a0af5", "name": "Wallet", "type": "payment_account", "kind": "asset", "currency": "THB", "description": "", "balance": "10000.00", "balance_minor": 1000000, "debt": null, "debt_minor": null, "limit": null, "limit_minor": null, "available": null, "available_minor": null, "over_limit": null, "hidden": false, "created_at": "2026-10-08T13:28:56Z", "updated_at": null, "version": 1}}, "BalanceCard": {"summary": "Credit card over its limit (liability)", "value": {"uid": "a8465748-a48b-426a-9466-9a6706d8143a", "name": "Credit Card", "type": "credit_card", "kind": "liability", "currency": "THB", "description": "", "balance": null, "balance_minor": null, "debt": "52000.00", "debt_minor": 5200000, "limit": "50000.00", "limit_minor": 5000000, "available": "-2000.00", "available_minor": -200000, "over_limit": true, "hidden": false, "created_at": "2026-10-08T13:28:56Z", "updated_at": null, "version": 1}}, "CategoryFood": {"summary": "Expense category", "value": {"uid": "32b0d51e-e81f-41f0-a77c-38e6ec384153", "name": "Food", "type": "expense", "description": "Groceries and restaurants", "created_at": "2026-10-08T13:29:10Z", "updated_at": null}}, "UserExample": {"summary": "User profile", "value": {"uid": "3525dd1f-ae96-4c71-b996-06a43679cfa2", "username": "alex", "email": "alex@example.com", "email_verified_at": null, "display_name": "Alex Example", "preferences": {"base_currency": "THB"}, "status": "active", "has_password": false, "password_updated_at": null, "last_login_at": null, "created_at": "2026-10-08T13:29:11Z", "updated_at": null}}, "ErrBadUid": {"summary": "Not a UUID (e.g. a numeric id)", "value": {"error": "uid must be a UUID (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)"}}, "ErrTxValidation": {"summary": "Several invalid fields", "value": {"error": "validation failed", "fields": {"currency": "\"XYZ\" is not a recognised ISO 4217 currency code", "spent_at": "must be an RFC 3339 / ISO 8601 date-time with a timezone offset, e.g. 2026-10-06T21:06:00+08:00"}}}, "ErrTxCurrencyMismatch": {"summary": "Currency differs from the balance's", "value": {"error": "validation failed", "fields": {"balance_uid": "balance \"Wallet\" is in THB but the transaction is in USD; the currencies must match (no exchange-rate conversion yet)"}}}, "ErrTxAdjustmentType": {"summary": "type balance_adjustment cannot be created", "value": {"error": "validation failed", "fields": {"type": "balance_adjustment transactions are created automatically when a balance amount is edited (PUT /api/balances/:uid); they cannot be created here, and other transactions cannot be turned into one"}}}, "ErrTxVersionConflict": {"summary": "Stale version", "value": {"error": "version conflict: this transaction was changed since you read it (now at version 2); nothing was saved. Reload it, re-apply your change and send the new version", "fields": {"version": "is stale; the current version is 2"}, "code": "version_conflict", "current": {"uid": "1a8af4f6-006a-4712-baba-eb8f433bccb1", "amount": "120.50", "amount_minor": 12050, "currency": "THB", "type": "expense", "balance_uid": "4dc73a4a-a60b-414e-98bc-3c71298a0af5", "account": "Wallet", "to_balance_uid": null, "to_account": null, "category_uid": "32b0d51e-e81f-41f0-a77c-38e6ec384153", "spent_at": "2026-10-06T21:06:00+08:00", "note": "chicken rice", "created_at": "2026-10-08T13:29:10Z", "updated_at": "2026-10-08T13:30:52Z", "version": 2, "adjusts_balances": true, "adjustment_direction": null}}}, "ErrTxReadOnly": {"summary": "Balance adjustments cannot be created or converted", "value": {"error": "balance adjustments are created automatically by balance edits; they cannot be created directly, and a transaction cannot change type to or from balance_adjustment", "code": "balance_adjustment_readonly"}}, "ErrBalanceVersionConflict": {"summary": "Stale version", "value": {"error": "version conflict: this balance was changed since you read it (now at version 3); nothing was saved. Reload it, re-apply your change and send the new version", "fields": {"version": "is stale; the current version is 3"}, "code": "version_conflict", "current": {"uid": "4dc73a4a-a60b-414e-98bc-3c71298a0af5", "name": "Wallet", "type": "payment_account", "kind": "asset", "currency": "THB", "description": "", "balance": "4879.50", "balance_minor": 487950, "debt": null, "debt_minor": null, "limit": null, "limit_minor": null, "available": null, "available_minor": null, "over_limit": null, "created_at": "2026-10-08T13:28:56Z", "updated_at": "2026-10-08T13:29:10Z", "version": 3}}}, "ErrBalanceInUse": {"summary": "Currency change while transactions reference the balance", "value": {"error": "balance is used by transactions (2 transaction(s)); its currency cannot change", "fields": {"currency": "cannot change while transactions reference this balance (no exchange-rate conversion)"}, "code": "balance_in_use"}}, "ErrCategoryInUseDelete": {"summary": "Category still referenced", "value": {"error": "category is used by transactions (1 transaction(s)); it cannot be deleted; move those transactions to another category first"}}}}}
