{"openapi": "3.1.0", "info": {"title": "Magic Heidi API", "version": "1.0.0", "description": "Swiss invoicing and bookkeeping over HTTP. The API works on the same data as the Magic Heidi apps: clients, invoices and quotes, expenses, categories, bank accounts and settings.\n\n## Authentication\nSend your API key with every request:\n\n```bash\ncurl https://api.magicheidi.ch/v1/clients \\\n  -H \"Authorization: Bearer $MAGIC_HEIDI_API_KEY\"\n```\n\nYou find the key in the app under Settings → App information. It gives full access to the account, so keep it secret; `POST /signout` replaces it. The `X-API-Key` header works too. Only `GET /health` and `GET /openapi.json` work without a key.\n\n## Responses\nEvery answer is JSON with a `success` flag. A success carries `data`:\n\n```json\n{\n  \"success\": true,\n  \"data\": {\"id\": \"client_123\", \"name\": \"ACME GmbH\"}\n}\n```\n\nAn error has a 4xx or 5xx status and says what went wrong:\n\n```json\n{\n  \"success\": false,\n  \"error\": \"Document not found\",\n  \"code\": \"not_found\"\n}\n```\n\nShow `error` to people and branch on `code`, which is stable. Some errors add `details`: a write that fails validation stores nothing and lists every invalid field in `details.errors`. A write that succeeds but ignores part of the request, such as an unknown field, says so in `warnings` next to `data`.\n\n## Lists\n`GET /clients`, `/invoices`, `/invoice-items`, `/categories`, `/expenses` and `/bank-accounts` return `{items, count, nextCursor, truncated}`. Send `limit` to get one page, and pass `nextCursor` back as `cursor` until it is null. Without `limit`, one call reads at most 5000 documents and returns the matches among them; `truncated: true` means it stopped there, and `nextCursor` continues. Unknown query parameters are rejected with 400 `invalid_query`.\n\n## Dates and money\n- Dates are in Swiss time (Europe/Zurich). Send a day as `2026-03-01`, or a date-time with its offset, `2026-03-01T09:30:00+01:00`. Date-times come back in Swiss time. Year filters and invoice numbers follow the Swiss calendar year.\n- Amounts are decimal numbers: `1250.5` is 1,250.50. Invoice amounts are in the invoice's `currency`; an expense `amount` is always in CHF.\n- VAT rates are percentages: `8.1` is 8.1%.\n\n## Safe retries\nSend your own `id` when you create something. Sending it again answers 409 `already_exists` instead of creating a duplicate. `POST /letters` takes an `Idempotency-Key` header for the same purpose.\n\n## Rate limits\nAt most 300 per minute per account, over the whole API. Generating a PDF (30 per minute), emailing an invoice (20 per minute) and sending a letter (10 per minute) have lower limits of their own. Over a limit the answer is 429 `rate_limited`, with a `Retry-After` header in seconds.\n", "contact": {"name": "Magic Heidi support", "email": "hello@magicheidi.ch", "url": "https://magicheidi.ch/support"}}, "servers": [{"url": "https://api.magicheidi.ch/v1"}], "security": [{"ApiKeyBearer": []}, {"ApiKeyHeader": []}, {"FirebaseIdToken": []}], "tags": [{"name": "Getting started", "description": "Check that the API is up and download this specification."}, {"name": "Clients", "description": "The people and companies you invoice."}, {"name": "Invoices", "description": "Invoices and quotes: create, change and delete them."}, {"name": "Sending", "description": "Turn an invoice into a PDF and deliver it by email or by post."}, {"name": "Payments", "description": "Record the payments your clients make and match bank statements to invoices."}, {"name": "Invoice items", "description": "Your catalog of products and services, to fill invoice lines quickly."}, {"name": "Expenses", "description": "Your business costs: record them by hand or from a scanned receipt."}, {"name": "Categories", "description": "Expense categories and payment methods."}, {"name": "Bank accounts", "description": "The accounts printed on your invoices, where clients pay you (not the connections that import transactions)."}, {"name": "Bank connections", "description": "Connect the user's bank through Swiss open banking to import transactions automatically."}, {"name": "Imports", "description": "Bring data in from files: client and product lists, expense lists, invoice lists and bank statements."}, {"name": "Linked addresses", "description": "Receipts emailed to `import@scan.magicheidi.ch` become expenses of the account whose login email sent them. A linked address is another address the account forwards receipts from, confirmed with a code emailed to it."}, {"name": "Company register", "description": "Look up Swiss companies to fill in client and company details."}, {"name": "Invoicing settings", "description": "Your company profile, VAT setup and invoice defaults."}, {"name": "Account", "description": "Subscription, exports, yearly backups and signing out everywhere."}, {"name": "Archive", "description": "Read-only: the stored files of a business year, for long-term archiving with Magic Heidi Archiv."}, {"name": "AI Invoice API", "description": "Free and without an API key: AI assistants make a Swiss invoice PDF with a QR-bill for their user. The PDF has the invoice body (the default template, or the caller's own HTML), the banner \"Erstellt mit Magic Heidi · magicheidi.ch\" and the payment part (the QR-bill), which is always drawn from the JSON fields. The guide for AI models is `GET /ai-invoice`; these operations alone: `GET /ai-invoice/openapi.json`. Rendering (checks included) is limited to 20 requests per minute and 300 per day per IP address; the guide, the template and stored files to 300 requests per minute per IP address."}], "paths": {"/health": {"get": {"tags": ["Getting started"], "operationId": "health_check", "summary": "Check the API is up", "description": "Answers `{status: ok}` while the API is up. Needs no API key.", "security": [], "responses": {"200": {"description": "The API is up", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"type": "object", "properties": {"status": {"type": "string", "const": "ok"}}, "required": ["status"]}}, "required": ["data"]}]}, "examples": {"ok": {"summary": "Healthy", "value": {"success": true, "data": {"status": "ok"}}}}}}}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/openapi.json": {"get": {"tags": ["Getting started"], "operationId": "get_openapi_spec", "summary": "Get this specification", "description": "Returns this OpenAPI 3.1 document, for code generators and API tools. Needs no API key. A readable version is at `/v1/docs`.", "security": [], "responses": {"200": {"description": "This OpenAPI document (not wrapped in `success`/`data`)", "content": {"application/json": {"schema": {"type": "object", "description": "This OpenAPI document, not wrapped in `success`/`data`."}, "examples": {"spec": {"summary": "OpenAPI document", "value": {"openapi": "3.1.0", "info": {"title": "Magic Heidi API", "version": "1.0.0"}}}}}}}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/clients": {"get": {"tags": ["Clients"], "operationId": "list_clients", "summary": "List clients", "description": "Returns your clients, sorted alphabetically by `name`.", "parameters": [{"name": "limit", "in": "query", "required": false, "schema": {"type": "integer", "minimum": 1, "maximum": 5000}, "description": "Page size. Omit for the whole list (up to 5000 documents read).", "example": 50}, {"name": "cursor", "in": "query", "required": false, "schema": {"type": "string"}, "description": "`nextCursor` of the previous page, unchanged.", "example": "WyJ6IixudWxsLCJpbnZfMTIzIl0"}], "responses": {"200": {"description": "The clients", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"type": "object", "properties": {"items": {"type": "array", "items": {"$ref": "#/components/schemas/ClientRecord"}}, "count": {"type": "integer", "minimum": 0, "description": "Number of `items` in this response."}, "nextCursor": {"type": ["string", "null"], "description": "Pass it as `cursor` to get the items after these; null when there are no more. It may lead to an empty page."}, "truncated": {"type": "boolean", "description": "true when the list stopped at the 5000 documents one call reads, so items may be missing: continue with `nextCursor`, or narrow the filters."}}, "required": ["items", "count", "nextCursor", "truncated"]}}, "required": ["data"]}]}, "examples": {"several": {"summary": "Several results", "value": {"success": true, "data": {"items": [{"id": "client_123", "ccEmails": ["finance@acme.ch"], "notes": "", "details": "", "files": [], "name": "ACME GmbH", "email": "billing@acme.ch", "street": "Bahnhofstrasse", "buildingNumber": "12", "zip": "8001", "city": "Zürich", "country": "CH"}, {"id": "client_private_1", "ccEmails": [], "notes": "", "details": "", "files": [], "name": "Max Muster", "email": "max@example.com", "street": "Musterweg", "buildingNumber": "5", "zip": "3007", "city": "Bern", "country": "CH"}], "count": 2, "nextCursor": null, "truncated": false}}}, "firstPage": {"summary": "First page of several (`limit=1`)", "value": {"success": true, "data": {"items": [{"id": "client_123", "ccEmails": ["finance@acme.ch"], "notes": "", "details": "", "files": [], "name": "ACME GmbH", "email": "billing@acme.ch", "street": "Bahnhofstrasse", "buildingNumber": "12", "zip": "8001", "city": "Zürich", "country": "CH"}], "count": 1, "nextCursor": "WyJzIiwiQUNNRSBHbWJIIiwiY2xpZW50XzEyMyJd", "truncated": false}}}, "empty": {"summary": "No results", "value": {"success": true, "data": {"items": [], "count": 0, "nextCursor": null, "truncated": false}}}}}}}, "400": {"$ref": "#/components/responses/InvalidQuery"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "post": {"tags": ["Clients"], "operationId": "create_client", "summary": "Create a client", "description": "Creates a client. Only `name` is required. Send the street name in `street` and the house number in `buildingNumber`.\n\nTo update a client that may already exist, use `POST /clients/save`.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Client"}, "examples": {"businessClient": {"summary": "Business client with a CC address", "value": {"name": "ACME GmbH", "email": "billing@acme.ch", "street": "Bahnhofstrasse", "buildingNumber": "12", "zip": "8001", "city": "Zürich", "country": "CH", "ccEmails": ["finance@acme.ch"]}}, "privateClient": {"summary": "Private person", "value": {"name": "Max Muster", "email": "max@example.com", "street": "Musterweg", "buildingNumber": "5", "zip": "3007", "city": "Bern", "country": "CH"}}, "withNotes": {"summary": "Client with your own id and a private note", "value": {"id": "client_123", "name": "ACME GmbH", "email": "accounts-payable@acme.ch", "notes": "Main contact for software projects"}}}}}}, "responses": {"201": {"description": "The created client", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/ClientRecord"}}, "required": ["data"]}]}, "examples": {"created": {"summary": "Created", "value": {"success": true, "data": {"id": "client_123", "ccEmails": ["finance@acme.ch"], "notes": "", "details": "", "files": [], "name": "ACME GmbH", "email": "billing@acme.ch", "street": "Bahnhofstrasse", "buildingNumber": "12", "zip": "8001", "city": "Zürich", "country": "CH"}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "409": {"$ref": "#/components/responses/Conflict"}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/clients/save": {"post": {"tags": ["Clients"], "operationId": "save_client", "summary": "Create or update a client", "description": "Creates the client, or updates it if you already have it. Useful when syncing from another system.\n\n- With an `id`, that client is updated, or created with that id.\n- Without an `id`, the client with exactly the same `name`, else the same `email`, is updated. When neither matches, a new client is created.\n\nAn update changes only the fields you send. Send `upsert: false` to always create. The answer is 201 for a new client and 200 for an updated one.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/SaveClientRequest"}, "examples": {"businessClient": {"summary": "Business client", "value": {"client": {"name": "ACME GmbH", "email": "billing@acme.ch", "street": "Bahnhofstrasse", "buildingNumber": "12", "zip": "8001", "city": "Zürich", "country": "CH", "ccEmails": ["finance@acme.ch"]}}}, "flat": {"summary": "Without the `client` wrapper", "value": {"name": "ACME GmbH", "email": "billing@acme.ch", "street": "Bahnhofstrasse", "buildingNumber": "12", "zip": "8001", "city": "Zürich", "country": "CH"}}, "updateById": {"summary": "Update by id", "value": {"client": {"id": "client_123", "name": "ACME GmbH", "email": "accounts-payable@acme.ch", "ccEmails": ["finance@acme.ch", "cfo@acme.ch"], "notes": "Main contact for software projects"}}}, "privateClient": {"summary": "Private person", "value": {"client": {"name": "Max Muster", "email": "max@example.com", "street": "Musterweg", "buildingNumber": "5", "zip": "3007", "city": "Bern", "country": "CH"}}}}}}}, "responses": {"200": {"description": "An existing client was updated", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/ClientRecord"}}, "required": ["data"]}]}, "examples": {"updated": {"summary": "Existing client updated", "value": {"success": true, "data": {"id": "client_123", "ccEmails": ["finance@acme.ch", "cfo@acme.ch"], "notes": "Main contact for software projects", "details": "", "files": [], "name": "ACME GmbH", "email": "accounts-payable@acme.ch", "street": "Bahnhofstrasse", "buildingNumber": "12", "zip": "8001", "city": "Zürich", "country": "CH"}}}}}}}, "201": {"description": "A new client was created", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/ClientRecord"}}, "required": ["data"]}]}, "examples": {"createdBusiness": {"summary": "New business client", "value": {"success": true, "data": {"id": "client_123", "ccEmails": ["finance@acme.ch"], "notes": "", "details": "", "files": [], "name": "ACME GmbH", "email": "billing@acme.ch", "street": "Bahnhofstrasse", "buildingNumber": "12", "zip": "8001", "city": "Zürich", "country": "CH"}}}, "createdPrivate": {"summary": "New private client", "value": {"success": true, "data": {"id": "client_private_1", "ccEmails": [], "notes": "", "details": "", "files": [], "name": "Max Muster", "email": "max@example.com", "street": "Musterweg", "buildingNumber": "5", "zip": "3007", "city": "Bern", "country": "CH"}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/clients/{clientId}": {"get": {"tags": ["Clients"], "operationId": "get_client", "summary": "Get a client", "description": "Returns one client.", "parameters": [{"name": "clientId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The client's `id`.", "example": "client_123"}], "responses": {"200": {"description": "The client", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/ClientRecord"}}, "required": ["data"]}]}, "examples": {"found": {"summary": "Found", "value": {"success": true, "data": {"id": "client_123", "ccEmails": ["finance@acme.ch"], "notes": "", "details": "", "files": [], "name": "ACME GmbH", "email": "billing@acme.ch", "street": "Bahnhofstrasse", "buildingNumber": "12", "zip": "8001", "city": "Zürich", "country": "CH"}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "patch": {"tags": ["Clients"], "operationId": "update_client", "summary": "Update a client", "description": "Changes the fields you send and keeps the others. Returns the updated client.", "parameters": [{"name": "clientId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The client's `id`.", "example": "client_123"}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ClientPatch"}, "examples": {"email": {"summary": "New email", "value": {"email": "billing-new@acme.ch"}}, "address": {"summary": "New address", "value": {"street": "Neue Gasse", "buildingNumber": "4", "zip": "8002", "city": "Zürich"}}, "ccEmails": {"summary": "New CC addresses", "value": {"ccEmails": ["finance@acme.ch", "bookkeeper@acme.ch"]}}, "notes": {"summary": "Private note", "value": {"notes": "Preferred billing contact is the finance team"}}}}}}, "responses": {"200": {"description": "The updated client", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/ClientRecord"}}, "required": ["data"]}]}, "examples": {"updated": {"summary": "Updated", "value": {"success": true, "data": {"id": "client_123", "ccEmails": ["finance@acme.ch"], "notes": "", "details": "", "files": [], "name": "ACME GmbH", "email": "billing@acme.ch", "street": "Bahnhofstrasse", "buildingNumber": "12", "zip": "8001", "city": "Zürich", "country": "CH"}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "delete": {"tags": ["Clients"], "operationId": "delete_client", "summary": "Delete a client", "description": "Deletes the client. A client that still has invoices or quotes cannot be deleted: the 409 answer lists up to 5 of them in `details.invoiceIds`.", "parameters": [{"name": "clientId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The client's `id`.", "example": "client_123"}], "responses": {"200": {"description": "The client was deleted", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/DeleteResult"}}, "required": ["data"]}]}, "examples": {"deleted": {"summary": "Deleted", "value": {"success": true, "data": {"deleted": true, "id": "client_123"}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "409": {"description": "The client still has invoices", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"hasInvoices": {"summary": "Client still has invoices", "value": {"success": false, "error": "Cannot delete a client that still has invoices. Delete the client's invoices first.", "code": "has_dependents", "details": {"invoiceIds": ["inv_123", "inv_124"]}}}}}}}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/invoices": {"get": {"tags": ["Invoices"], "operationId": "list_invoices", "summary": "List invoices", "description": "Returns your invoices and quotes, newest `date` first. Filters can be combined.", "parameters": [{"name": "status", "in": "query", "required": false, "schema": {"type": "string", "enum": ["paid", "unpaid"]}, "description": "Only paid or only unpaid invoices.", "example": "unpaid"}, {"name": "type", "in": "query", "required": false, "schema": {"type": "string", "enum": ["invoice", "quote"]}, "description": "Only invoices or only quotes.", "example": "invoice"}, {"name": "year", "in": "query", "required": false, "schema": {"type": "integer"}, "description": "Only invoices dated in this Swiss calendar year.", "example": 2025}, {"name": "clientId", "in": "query", "required": false, "schema": {"type": "string"}, "description": "Only this client's invoices and quotes.", "example": "client_123"}, {"name": "limit", "in": "query", "required": false, "schema": {"type": "integer", "minimum": 1, "maximum": 5000}, "description": "Page size. Omit for the whole list (up to 5000 documents read).", "example": 50}, {"name": "cursor", "in": "query", "required": false, "schema": {"type": "string"}, "description": "`nextCursor` of the previous page, unchanged.", "example": "WyJ6IixudWxsLCJpbnZfMTIzIl0"}], "responses": {"200": {"description": "The invoices", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"type": "object", "properties": {"items": {"type": "array", "items": {"$ref": "#/components/schemas/InvoiceRecord"}}, "count": {"type": "integer", "minimum": 0, "description": "Number of `items` in this response."}, "nextCursor": {"type": ["string", "null"], "description": "Pass it as `cursor` to get the items after these; null when there are no more. It may lead to an empty page."}, "truncated": {"type": "boolean", "description": "true when the list stopped at the 5000 documents one call reads, so items may be missing: continue with `nextCursor`, or narrow the filters."}}, "required": ["items", "count", "nextCursor", "truncated"]}}, "required": ["data"]}]}, "examples": {"several": {"summary": "Several results", "value": {"success": true, "data": {"items": [{"id": "inv_123", "clientRef": "users/<uid>/clients/client_123", "language": "de", "vatMode": "additive", "payments": {"proof": null, "items": []}, "date": "2026-02-25T00:00:00+01:00", "items": [{"id": "line_1", "name": "Software development", "price": 180, "units": 8, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}, {"id": "line_2", "name": "Project management", "price": 160, "units": 2, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}], "exchangeRate": null, "version": 11, "isPaid": false, "sent": false, "vatEnabled": true, "bankId": "bank_chf", "type": "normal", "currency": "CHF", "recurring": "disabled", "recurringDueDate": null, "recurringAutoSend": false, "description": "Vielen Dank für Ihren Auftrag.", "headerDescription": "", "disableRounding": true, "sentEmailHistory": [], "generationCount": 0, "hideQuotePricing": false, "isArchived": false, "clientId": "client_123", "number": 11, "totals": {"subtotal": 1760.0, "vat": 142.56, "total": 1902.56, "paid": 0.0, "due": 1902.56}, "dueDate": "2026-03-27"}, {"id": "quote_456", "clientRef": "users/<uid>/clients/client_123", "language": "en", "vatMode": "additive", "payments": {"proof": null, "items": []}, "date": "2026-02-25T00:00:00+01:00", "items": [{"id": "line_q1", "name": "Discovery workshop", "price": 900, "units": 1, "vatRate": 0, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}], "exchangeRate": null, "version": 3, "isPaid": false, "sent": false, "vatEnabled": false, "bankId": null, "type": "quote", "currency": "EUR", "recurring": "disabled", "recurringDueDate": null, "recurringAutoSend": false, "description": "Quote valid for 30 days", "headerDescription": "", "disableRounding": true, "sentEmailHistory": [], "generationCount": 0, "hideQuotePricing": false, "isArchived": false, "clientId": "client_123", "number": 3, "totals": {"subtotal": 900.0, "vat": 0.0, "total": 900.0, "paid": 0.0, "due": 900.0}, "dueDate": "2026-03-11"}], "count": 2, "nextCursor": null, "truncated": false}}}, "firstPage": {"summary": "First page of several (`limit=1`)", "value": {"success": true, "data": {"items": [{"id": "inv_123", "clientRef": "users/<uid>/clients/client_123", "language": "de", "vatMode": "additive", "payments": {"proof": null, "items": []}, "date": "2026-02-25T00:00:00+01:00", "items": [{"id": "line_1", "name": "Software development", "price": 180, "units": 8, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}, {"id": "line_2", "name": "Project management", "price": 160, "units": 2, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}], "exchangeRate": null, "version": 11, "isPaid": false, "sent": false, "vatEnabled": true, "bankId": "bank_chf", "type": "normal", "currency": "CHF", "recurring": "disabled", "recurringDueDate": null, "recurringAutoSend": false, "description": "Vielen Dank für Ihren Auftrag.", "headerDescription": "", "disableRounding": true, "sentEmailHistory": [], "generationCount": 0, "hideQuotePricing": false, "isArchived": false, "clientId": "client_123", "number": 11, "totals": {"subtotal": 1760.0, "vat": 142.56, "total": 1902.56, "paid": 0.0, "due": 1902.56}, "dueDate": "2026-03-27"}], "count": 1, "nextCursor": "WyJ0IiwiMjAyNi0wMi0yNVQwMDowMDowMCswMTowMCIsImludl8xMjMiXQ", "truncated": false}}}, "empty": {"summary": "No results", "value": {"success": true, "data": {"items": [], "count": 0, "nextCursor": null, "truncated": false}}}}}}}, "400": {"$ref": "#/components/responses/InvalidQuery"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "post": {"tags": ["Invoices"], "operationId": "create_invoice", "summary": "Create an invoice or quote", "description": "Creates an invoice, or a quote with `type: quote`. It starts unpaid and unsent.\n\nSend at least one line in `items`, and the client: either the `clientId` of an existing client, or a `client` object, which is matched by name or email and created if new. Everything else has a default: the next invoice number, today's date, the account's language and VAT mode.\n\nNext, create the PDF with `POST /invoices/{invoiceId}/generate` and email it with `POST /invoices/{invoiceId}/send`.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/CreateInvoiceRequest"}, "examples": {"invoiceWithVat": {"summary": "Invoice for a new or existing client", "value": {"client": {"name": "ACME GmbH", "email": "billing@acme.ch", "street": "Bahnhofstrasse", "buildingNumber": "12", "zip": "8001", "city": "Zürich", "country": "CH", "ccEmails": ["finance@acme.ch"]}, "language": "de", "currency": "CHF", "bankId": "bank_chf", "vatEnabled": true, "vatMode": "additive", "description": "Vielen Dank für Ihren Auftrag.", "items": [{"name": "Software development", "units": 8, "price": 180, "vatRate": 8.1}, {"name": "Project management", "units": 2, "price": 160, "vatRate": 8.1}]}}, "quoteNoVat": {"summary": "Quote in EUR without VAT", "value": {"clientId": "client_123", "date": "2026-02-25", "language": "en", "type": "quote", "currency": "EUR", "vatEnabled": false, "description": "Quote valid for 30 days", "items": [{"name": "Discovery workshop", "units": 1, "price": 900, "vatRate": 0}]}}, "hourlyDetails": {"summary": "Line with the hours worked", "value": {"clientId": "client_123", "language": "en", "currency": "CHF", "vatEnabled": true, "vatMode": "inclusive", "headerDescription": "Consulting services", "items": [{"name": "Consulting", "units": 1, "price": 1200, "vatRate": 8.1, "details": {"type": "HourlyRateDetails", "date": "2026-02-25", "from": "09:00", "to": "17:00"}}]}}, "recurring": {"summary": "Monthly recurring invoice", "value": {"clientId": "client_123", "language": "de", "currency": "CHF", "type": "normal", "recurring": "monthly", "vatEnabled": true, "vatMode": "additive", "description": "Monatliches Hosting und Wartung", "items": [{"name": "Hosting", "units": 1, "price": 95, "vatRate": 8.1}, {"name": "Wartung", "units": 1, "price": 180, "vatRate": 8.1}]}}, "lastYear": {"summary": "Dated last year, confirmed, with your own id for safe retries", "value": {"id": "inv_2025_late", "clientId": "client_123", "date": "2025-12-30", "confirmDate": true, "items": [{"name": "December support", "units": 4, "price": 150, "vatRate": 8.1}]}}, "nested": {"summary": "The invoice wrapped in `invoice`", "value": {"clientId": "client_123", "invoice": {"items": [{"name": "Consulting", "units": 2, "price": 150, "vatRate": 8.1}]}}}}}}}, "responses": {"201": {"description": "The created invoice", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/InvoiceRecord"}}, "required": ["data"]}]}, "examples": {"invoice": {"summary": "Invoice created", "value": {"success": true, "data": {"id": "inv_123", "clientRef": "users/<uid>/clients/client_123", "language": "de", "vatMode": "additive", "payments": {"proof": null, "items": []}, "date": "2026-02-25T00:00:00+01:00", "items": [{"id": "line_1", "name": "Software development", "price": 180, "units": 8, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}, {"id": "line_2", "name": "Project management", "price": 160, "units": 2, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}], "exchangeRate": null, "version": 11, "isPaid": false, "sent": false, "vatEnabled": true, "bankId": "bank_chf", "type": "normal", "currency": "CHF", "recurring": "disabled", "recurringDueDate": null, "recurringAutoSend": false, "description": "Vielen Dank für Ihren Auftrag.", "headerDescription": "", "disableRounding": true, "sentEmailHistory": [], "generationCount": 0, "hideQuotePricing": false, "isArchived": false, "clientId": "client_123", "number": 11, "totals": {"subtotal": 1760.0, "vat": 142.56, "total": 1902.56, "paid": 0.0, "due": 1902.56}, "dueDate": "2026-03-27"}}}, "quote": {"summary": "Quote created", "value": {"success": true, "data": {"id": "quote_456", "clientRef": "users/<uid>/clients/client_123", "language": "en", "vatMode": "additive", "payments": {"proof": null, "items": []}, "date": "2026-02-25T00:00:00+01:00", "items": [{"id": "line_q1", "name": "Discovery workshop", "price": 900, "units": 1, "vatRate": 0, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}], "exchangeRate": null, "version": 3, "isPaid": false, "sent": false, "vatEnabled": false, "bankId": null, "type": "quote", "currency": "EUR", "recurring": "disabled", "recurringDueDate": null, "recurringAutoSend": false, "description": "Quote valid for 30 days", "headerDescription": "", "disableRounding": true, "sentEmailHistory": [], "generationCount": 0, "hideQuotePricing": false, "isArchived": false, "clientId": "client_123", "number": 3, "totals": {"subtotal": 900.0, "vat": 0.0, "total": 900.0, "paid": 0.0, "due": 900.0}, "dueDate": "2026-03-11"}}}, "createdWithWarning": {"summary": "Created, but `vat_rate` was ignored (the line got the default 8.1%)", "value": {"success": true, "data": {"id": "inv_123", "clientRef": "users/<uid>/clients/client_123", "language": "de", "vatMode": "additive", "payments": {"proof": null, "items": []}, "date": "2026-02-25T00:00:00+01:00", "items": [{"id": "line_1", "name": "Software development", "price": 180, "units": 8, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}, {"id": "line_2", "name": "Project management", "price": 160, "units": 2, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}], "exchangeRate": null, "version": 11, "isPaid": false, "sent": false, "vatEnabled": true, "bankId": "bank_chf", "type": "normal", "currency": "CHF", "recurring": "disabled", "recurringDueDate": null, "recurringAutoSend": false, "description": "Vielen Dank für Ihren Auftrag.", "headerDescription": "", "disableRounding": true, "sentEmailHistory": [], "generationCount": 0, "hideQuotePricing": false, "isArchived": false, "clientId": "client_123", "number": 11, "totals": {"subtotal": 1760.0, "vat": 142.56, "total": 1902.56, "paid": 0.0, "due": 1902.56}, "dueDate": "2026-03-27"}, "warnings": [{"field": "items[0].vat_rate", "code": "unknown_field", "message": "unknown field, ignored (not stored); did you mean `vatRate`?", "suggested": "vatRate"}]}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "409": {"description": "An invoice with this `id` already exists", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"alreadyExists": {"summary": "Duplicate id", "value": {"success": false, "error": "Invoice 'inv_123' already exists", "code": "already_exists"}}}}}}, "429": {"$ref": "#/components/responses/RateLimited"}, "503": {"description": "Too many simultaneous changes to the account's invoices; nothing was saved. Retry after `Retry-After` seconds", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"contended": {"summary": "Contended", "value": {"success": false, "error": "Too many simultaneous changes to this account's invoices; nothing was saved. Try again.", "code": "upstream_unavailable"}}}}}, "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}, "example": 2}}}}}}, "/invoices/{invoiceId}": {"get": {"tags": ["Invoices"], "operationId": "get_invoice", "summary": "Get an invoice", "description": "Returns one invoice or quote.", "parameters": [{"name": "invoiceId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The invoice's (or quote's) `id`.", "example": "inv_123"}], "responses": {"200": {"description": "The invoice", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/InvoiceRecord"}}, "required": ["data"]}]}, "examples": {"found": {"summary": "Found", "value": {"success": true, "data": {"id": "inv_123", "clientRef": "users/<uid>/clients/client_123", "language": "de", "vatMode": "additive", "payments": {"proof": null, "items": []}, "date": "2026-02-25T00:00:00+01:00", "items": [{"id": "line_1", "name": "Software development", "price": 180, "units": 8, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}, {"id": "line_2", "name": "Project management", "price": 160, "units": 2, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}], "exchangeRate": null, "version": 11, "isPaid": false, "sent": false, "vatEnabled": true, "bankId": "bank_chf", "type": "normal", "currency": "CHF", "recurring": "disabled", "recurringDueDate": null, "recurringAutoSend": false, "description": "Vielen Dank für Ihren Auftrag.", "headerDescription": "", "disableRounding": true, "sentEmailHistory": [], "generationCount": 0, "hideQuotePricing": false, "isArchived": false, "clientId": "client_123", "number": 11, "totals": {"subtotal": 1760.0, "vat": 142.56, "total": 1902.56, "paid": 0.0, "due": 1902.56}, "dueDate": "2026-03-27"}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "patch": {"tags": ["Invoices"], "operationId": "update_invoice", "summary": "Update an invoice", "description": "Changes the fields you send and keeps the others.\n\n- `items` and `payments.items` are replaced as a whole: send every line you want to keep.\n- You can send back an invoice as you received it. Unchanged fields are not validated again, and the computed `number`, `totals` and `dueDate` are ignored.\n- Send `version` to renumber the invoice and `clientId` to move it to another client.\n\nTo record a payment, use `POST /invoices/{invoiceId}/record-payment`.", "parameters": [{"name": "invoiceId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The invoice's (or quote's) `id`.", "example": "inv_123"}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Invoice"}, "examples": {"texts": {"summary": "New header and footer text", "value": {"description": "Zahlbar innert 30 Tagen.", "headerDescription": "Projekt Phase 2"}}, "noVat": {"summary": "Turn VAT off", "value": {"vatEnabled": false}}, "recurring": {"summary": "Repeat every month", "value": {"recurring": "monthly"}}, "items": {"summary": "Replace the lines", "value": {"items": [{"name": "Software development", "units": 8, "price": 180, "vatRate": 8.1}, {"name": "Project management", "units": 2, "price": 160, "vatRate": 8.1}]}}}}}}, "responses": {"200": {"description": "The updated invoice", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/InvoiceRecord"}}, "required": ["data"]}]}, "examples": {"updated": {"summary": "Updated", "value": {"success": true, "data": {"id": "inv_123", "clientRef": "users/<uid>/clients/client_123", "language": "de", "vatMode": "additive", "payments": {"proof": null, "items": []}, "date": "2026-02-25T00:00:00+01:00", "items": [{"id": "line_1", "name": "Software development", "price": 180, "units": 8, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}, {"id": "line_2", "name": "Project management", "price": 160, "units": 2, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}], "exchangeRate": null, "version": 11, "isPaid": false, "sent": false, "vatEnabled": true, "bankId": "bank_chf", "type": "normal", "currency": "CHF", "recurring": "disabled", "recurringDueDate": null, "recurringAutoSend": false, "description": "Vielen Dank für Ihren Auftrag.", "headerDescription": "", "disableRounding": true, "sentEmailHistory": [], "generationCount": 0, "hideQuotePricing": false, "isArchived": false, "clientId": "client_123", "number": 11, "totals": {"subtotal": 1760.0, "vat": 142.56, "total": 1902.56, "paid": 0.0, "due": 1902.56}, "dueDate": "2026-03-27"}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}, "503": {"description": "Too many simultaneous changes to the account's invoices; nothing was saved. Retry after `Retry-After` seconds", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"contended": {"summary": "Contended", "value": {"success": false, "error": "Too many simultaneous changes to this account's invoices; nothing was saved. Try again.", "code": "upstream_unavailable"}}}}}, "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}, "example": 2}}}}}, "delete": {"tags": ["Invoices"], "operationId": "delete_invoice", "summary": "Delete an invoice", "description": "Permanently deletes the invoice or quote.", "parameters": [{"name": "invoiceId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The invoice's (or quote's) `id`.", "example": "inv_123"}], "responses": {"200": {"description": "The invoice was deleted", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/DeleteResult"}}, "required": ["data"]}]}, "examples": {"deleted": {"summary": "Deleted", "value": {"success": true, "data": {"deleted": true, "id": "inv_123"}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/invoices/{invoiceId}/generate": {"post": {"tags": ["Sending"], "operationId": "generate_invoice_pdf", "summary": "Generate the invoice PDF", "description": "Renders the invoice or quote as a PDF with a Swiss QR bill and returns a link to it. The link works for 7 days. Generate again after changing the invoice.\n\n- An invoice without a bank account (`bankId`) gets one now, saved on the invoice: the last one used for this client and currency, else the first that fits the currency.\n- `overrides` changes this PDF only and is not stored. Use it for a payment reminder (`invoice.paymentStatus: late`) or to render a quote (`invoice.type: quote`).\n- `testMode: true` uses sample company and bank details instead of yours.", "parameters": [{"name": "invoiceId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The invoice's (or quote's) `id`.", "example": "inv_123"}], "requestBody": {"required": false, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/GenerateOptions"}, "examples": {"default": {"summary": "The invoice as it is", "value": {}}, "quote": {"summary": "As a quote", "value": {"overrides": {"invoice": {"type": "quote"}}}}, "reminder": {"summary": "As a payment reminder, in German", "value": {"locale": "de", "overrides": {"invoice": {"paymentStatus": "late"}}}}, "testMode": {"summary": "With sample company details", "value": {"testMode": true, "locale": "en"}}}}}}, "responses": {"200": {"description": "The PDF was generated", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/GenerateResult"}}, "required": ["data"]}]}, "examples": {"invoice": {"summary": "Invoice PDF", "value": {"success": true, "data": {"url": "https://storage.googleapis.com/magic-heidi.appspot.com/users/<uid>/invoices/inv_123.pdf?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Expires=604800&X-Goog-Signature=...", "filename": "Rechnung_2026_0011", "expiresAt": "2026-03-04T10:15:00+01:00"}}}, "quote": {"summary": "Quote PDF", "value": {"success": true, "data": {"url": "https://storage.googleapis.com/magic-heidi.appspot.com/users/<uid>/invoices/inv_123.pdf?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Expires=604800&X-Goog-Signature=...", "filename": "Offerte_2026_0003", "expiresAt": "2026-03-04T10:15:00+01:00"}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"description": "Too many requests: at most 30 per minute on this endpoint, and 300 per minute per account over the whole API", "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}, "example": 23}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"endpointLimit": {"summary": "Endpoint limit reached", "value": {"success": false, "error": "Too many requests: at most 30 requests per minute on this endpoint. Retry in 12 seconds.", "code": "rate_limited", "details": {"limit": "30/minute", "scope": "endpoint", "retryAfter": 12}}}, "accountLimit": {"summary": "Account limit reached", "value": {"success": false, "error": "Too many requests: at most 300 requests per minute per account. Retry in 23 seconds.", "code": "rate_limited", "details": {"limit": "300/minute", "scope": "account", "retryAfter": 23}}}}}}}, "502": {"description": "The PDF service failed or returned no file; retry", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"noFile": {"summary": "No file", "value": {"success": false, "error": "The PDF service returned no file; try again", "code": "upstream_unavailable"}}}}}}, "503": {"description": "A service behind the API is temporarily unavailable; retry later", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"unavailable": {"summary": "Temporarily unavailable", "value": {"success": false, "error": "This action is temporarily unavailable.", "code": "upstream_unavailable"}}}}}}}}}, "/invoices/{invoiceId}/send": {"post": {"tags": ["Sending"], "operationId": "send_invoice", "summary": "Email the invoice", "description": "Emails the invoice PDF to your client in your company's name, from `invoice@magicheidi.ch`, and marks the invoice sent. The last generated PDF is attached, so generate it first.\n\n- The email goes to `toEmail`, by default the client's email and CC addresses.\n- Replies go to `invoiceReplyToEmail` from your invoicing settings, else `userEmail`, else the account email.\n- The subject and text follow the document: invoice, quote, payment reminder, payment confirmation, order confirmation or delivery bill. Pass the same `overrides` you generated the PDF with.\n\nWhen the mail service fails or does not confirm, the answer is 502 and the attempt is logged in `sentEmailHistory` with `success: false`. The email may still have gone out: do not retry automatically, or your client may get it twice.", "parameters": [{"name": "invoiceId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The invoice's (or quote's) `id`.", "example": "inv_123"}], "requestBody": {"required": false, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/SendOptions"}, "examples": {"invoice": {"summary": "To a given address, in German", "value": {"toEmail": "billing@acme.ch", "ccEmails": ["finance@acme.ch"], "locale": "de"}}, "quote": {"summary": "As a quote", "value": {"toEmail": "procurement@acme.ch", "ccEmails": [], "locale": "en", "overrides": {"invoice": {"type": "quote"}}, "invoiceStatus": "quote"}}, "reminder": {"summary": "Payment reminder", "value": {"toEmail": "billing@acme.ch", "ccEmails": ["finance@acme.ch"], "locale": "de", "invoiceStatus": "reminder", "overrides": {"invoice": {"paymentStatus": "late"}}}}, "confirmation": {"summary": "Payment confirmation", "value": {"toEmail": "billing@acme.ch", "ccEmails": [], "locale": "de", "invoiceStatus": "confirmation", "overrides": {"invoice": {"paymentStatus": "paid"}}}}}}}}, "responses": {"200": {"description": "The email was sent", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/SendResult"}}, "required": ["data"]}]}, "examples": {"sent": {"summary": "Sent", "value": {"success": true, "data": {"sent": true, "toEmail": "billing@acme.ch", "ccEmails": ["finance@acme.ch"]}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"description": "Too many emails: at most 20 per minute on this endpoint and one email every 10 seconds, and 300 per minute per account over the whole API", "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}, "example": 23}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"endpointLimit": {"summary": "Endpoint limit reached", "value": {"success": false, "error": "Too many requests: at most 20 requests per minute on this endpoint. Retry in 12 seconds.", "code": "rate_limited", "details": {"limit": "20/minute", "scope": "endpoint", "retryAfter": 12}}}, "accountLimit": {"summary": "Account limit reached", "value": {"success": false, "error": "Too many requests: at most 300 requests per minute per account. Retry in 23 seconds.", "code": "rate_limited", "details": {"limit": "300/minute", "scope": "account", "retryAfter": 23}}}}}}}, "502": {"description": "The mail service failed or did not confirm; the attempt is logged with `success: false` and the email may have gone out, so do not retry automatically", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"notConfirmed": {"summary": "Not confirmed", "value": {"success": false, "error": "The email service did not confirm that the email was sent, but it may have gone out. The attempt is logged in the invoice's sentEmailHistory with success: false. Do not send it again before checking with the recipient, so they do not get it twice", "code": "upstream_unavailable"}}}}}}, "503": {"description": "A service behind the API is temporarily unavailable; retry later", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"unavailable": {"summary": "Temporarily unavailable", "value": {"success": false, "error": "This action is temporarily unavailable.", "code": "upstream_unavailable"}}}}}}}}}, "/letters": {"post": {"tags": ["Sending"], "operationId": "send_letter", "summary": "Send an invoice by post", "description": "Prints the invoice's last generated PDF in colour, double-sided, and posts it with economy postage to the client address on the invoice, in any country. Each letter uses one of the account's letters; with none left the answer is 402 and nothing is sent.\n\n- `sendTo` posts it to another address: a cover sheet with that address is added in front of the invoice.\n- Send one `Idempotency-Key` header per letter. A retry with the same key returns the same letter instead of posting it twice. The same key with another invoice or `sendTo` answers 409.\n\nThe answer has the letter's `id` and `status`. Follow its delivery with `GET /letters/{letterId}`.", "parameters": [{"name": "Idempotency-Key", "in": "header", "required": true, "schema": {"type": "string", "minLength": 1, "maxLength": 200}, "description": "Your id for this letter; sending again with the same key returns the same letter.", "example": "send-inv_123-2026-03-02"}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "properties": {"invoiceId": {"type": "string", "description": "The invoice to send."}, "sendTo": {"anyOf": [{"$ref": "#/components/schemas/LetterAddress"}, {"type": "null"}]}}, "required": ["invoiceId"]}, "examples": {"letter": {"summary": "Send invoice inv_123", "value": {"invoiceId": "inv_123"}}, "sendTo": {"summary": "Send a copy to your business address", "value": {"invoiceId": "inv_123", "sendTo": {"name": "Magic Heidi AG", "street": "Route de Vaux", "buildingNumber": "1", "zip": "1126", "city": "Vaux", "country": "CH"}}}}}}}, "responses": {"202": {"description": "The letter was accepted, or this Idempotency-Key was used before", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/LetterSubmission"}}, "required": ["data"]}]}, "examples": {"accepted": {"summary": "Accepted", "value": {"success": true, "data": {"id": "9b1f6c2e4d7a4f0e8c3b5a1d2e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f", "status": "processing"}}}}}}, "headers": {"Location": {"description": "URL of the letter's delivery details.", "schema": {"type": "string"}}}}, "400": {"description": "Invalid `invoiceId`, `Idempotency-Key`, or `sendTo` (including an address that cannot fit)", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "402": {"description": "No letters left (`code: insufficient_letters`); nothing was sent", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}, "404": {"description": "The invoice does not exist or has no generated PDF yet", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}, "409": {"description": "This Idempotency-Key was used for another letter (`code: conflict`)", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}, "413": {"description": "The request is larger than 21 MB", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}, "422": {"description": "The invoice PDF is invalid, or the final PDF including its cover exceeds 20 MB", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}, "429": {"description": "Too many requests: at most 10 per minute on this endpoint, and 300 per minute per account over the whole API", "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}, "example": 23}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"endpointLimit": {"summary": "Endpoint limit reached", "value": {"success": false, "error": "Too many requests: at most 10 requests per minute on this endpoint. Retry in 12 seconds.", "code": "rate_limited", "details": {"limit": "10/minute", "scope": "endpoint", "retryAfter": 12}}}, "accountLimit": {"summary": "Account limit reached", "value": {"success": false, "error": "Too many requests: at most 300 requests per minute per account. Retry in 23 seconds.", "code": "rate_limited", "details": {"limit": "300/minute", "scope": "account", "retryAfter": 23}}}}}}}, "502": {"description": "Sending could not be confirmed; check `GET /letters` before sending again", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}, "503": {"description": "Sending letters is temporarily unavailable", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}}}, "get": {"tags": ["Sending"], "operationId": "list_letters", "summary": "List letters", "description": "Returns the letters you sent by post, newest first. Page through them with `limit` and `cursor`.", "parameters": [{"name": "invoiceId", "in": "query", "required": false, "schema": {"type": "string"}, "description": "Only the letters of this invoice.", "example": "inv_123"}, {"name": "cursor", "in": "query", "required": false, "schema": {"type": "string"}, "description": "`nextCursor` of the previous page."}, {"name": "limit", "in": "query", "required": false, "schema": {"type": "integer", "default": 20, "minimum": 1, "maximum": 100}, "description": "Letters per page, 1-100 (default 20)."}], "responses": {"200": {"description": "The letters, newest first", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"type": "object", "properties": {"items": {"type": "array", "items": {"$ref": "#/components/schemas/Letter"}}, "count": {"type": "integer", "description": "Number of letters in `items`."}, "nextCursor": {"type": ["string", "null"]}, "truncated": {"type": "boolean", "description": "Always false: letters are never cut short."}}, "required": ["items", "count", "nextCursor", "truncated"]}}, "required": ["data"]}]}, "examples": {"letters": {"summary": "One letter", "value": {"success": true, "data": {"items": [{"id": "9b1f6c2e4d7a4f0e8c3b5a1d2e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f", "invoiceId": "inv_123", "invoiceSnapshot": {"version": 11, "date": "2026-03-01T00:00:00+01:00", "currency": "CHF", "type": "normal"}, "status": "dispatched", "requestedAt": "2026-03-02T10:15:00+01:00", "updatedAt": "2026-03-02T17:40:00+01:00", "dispatchedAt": "2026-03-02T17:40:00+01:00", "deliveredAt": null, "failedAt": null, "undeliverableAt": null, "recipientAddress": "ACME GmbH, Bahnhofstrasse 12, 8001 Zürich", "recipientCountry": "CH", "error": null, "environment": "production"}], "count": 1, "nextCursor": null, "truncated": false}}}}}}}, "400": {"description": "Unknown query parameter, `limit` out of range, or `cursor` not from a previous page (`code: invalid_query`)", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}, "503": {"description": "Letters are temporarily unavailable", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}}}}, "/letters/{letterId}": {"get": {"tags": ["Sending"], "operationId": "get_letter", "summary": "Get a letter", "description": "Returns one letter with its delivery events, oldest first.", "parameters": [{"name": "letterId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The letter's `id` (from `POST /letters` or `GET /letters`).", "example": "9b1f6c2e4d7a4f0e8c3b5a1d2e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f"}], "responses": {"200": {"description": "The letter and its events", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"allOf": [{"$ref": "#/components/schemas/Letter"}, {"type": "object", "properties": {"events": {"type": "array", "items": {"type": "object", "properties": {"eventId": {"type": "string"}, "category": {"type": "string"}, "reason": {"type": ["string", "null"]}, "occurredAt": {"type": "string", "format": "date-time"}, "receivedAt": {"type": "string", "format": "date-time"}, "timeSource": {"type": "string", "enum": ["event", "webhook"]}}}}}}]}}, "required": ["data"]}]}, "examples": {"letter": {"summary": "Dispatched letter", "value": {"success": true, "data": {"id": "9b1f6c2e4d7a4f0e8c3b5a1d2e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f", "invoiceId": "inv_123", "invoiceSnapshot": {"version": 11, "date": "2026-03-01T00:00:00+01:00", "currency": "CHF", "type": "normal"}, "status": "dispatched", "requestedAt": "2026-03-02T10:15:00+01:00", "updatedAt": "2026-03-02T17:40:00+01:00", "dispatchedAt": "2026-03-02T17:40:00+01:00", "deliveredAt": null, "failedAt": null, "undeliverableAt": null, "recipientAddress": "ACME GmbH, Bahnhofstrasse 12, 8001 Zürich", "recipientCountry": "CH", "error": null, "environment": "production", "events": [{"eventId": "ev_1", "category": "sent", "reason": null, "occurredAt": "2026-03-02T17:40:00+01:00", "receivedAt": "2026-03-02T17:40:05+01:00", "timeSource": "event"}]}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}, "503": {"description": "Letters are temporarily unavailable", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}}}}, "/invoices/{invoiceId}/record-payment": {"post": {"tags": ["Payments"], "operationId": "record_invoice_payment", "summary": "Record a payment", "description": "Adds a payment to the invoice and marks it sent. The invoice becomes paid once its payments cover the total; send `markPaid` to decide yourself.\n\nName the payment method with `methodId` or `methodName`. A paid quote becomes an invoice.", "parameters": [{"name": "invoiceId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The invoice's (or quote's) `id`.", "example": "inv_123"}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/RecordPayment"}, "examples": {"bankTransfer": {"summary": "Paid in full by bank transfer", "value": {"amount": 1902.56, "methodName": "Bank transfer", "date": "2026-02-25", "markPaid": true}}, "partial": {"summary": "Partial payment; the invoice stays unpaid", "value": {"amount": 500.0, "methodName": "Bank transfer", "date": "2026-02-10", "markPaid": false}}, "twint": {"summary": "TWINT payment today", "value": {"amount": 129.9, "methodName": "TWINT"}}, "existingMethod": {"summary": "With an existing payment method id", "value": {"amount": 2400, "methodId": "pm_bank", "date": "2026-02-28", "markPaid": true}}}}}}, "responses": {"200": {"description": "The invoice with the payment", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/InvoiceRecord"}}, "required": ["data"]}]}, "examples": {"fullPayment": {"summary": "Paid in full", "value": {"success": true, "data": {"id": "inv_123", "clientRef": "users/<uid>/clients/client_123", "language": "de", "vatMode": "additive", "payments": {"proof": null, "items": [{"id": "pay_1", "methodId": "pm_bank", "amount": 1902.56, "date": "2026-02-25T00:00:00+01:00"}]}, "date": "2026-02-25T00:00:00+01:00", "items": [{"id": "line_1", "name": "Software development", "price": 180, "units": 8, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}, {"id": "line_2", "name": "Project management", "price": 160, "units": 2, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}], "exchangeRate": null, "version": 11, "isPaid": true, "sent": true, "vatEnabled": true, "bankId": "bank_chf", "type": "normal", "currency": "CHF", "recurring": "disabled", "recurringDueDate": null, "recurringAutoSend": false, "description": "Vielen Dank für Ihren Auftrag.", "headerDescription": "", "disableRounding": true, "sentEmailHistory": [{"email": "billing@acme.ch", "ccEmails": ["finance@acme.ch"], "isTest": false, "success": true, "invoiceStatus": "invoice", "date": "2026-02-25T11:40:00+01:00"}], "generationCount": 1, "hideQuotePricing": false, "isArchived": false, "clientId": "client_123", "number": 11, "totals": {"subtotal": 1760.0, "vat": 142.56, "total": 1902.56, "paid": 1902.56, "due": 0.0}, "dueDate": "2026-03-27"}}}, "partialPayment": {"summary": "Partly paid", "value": {"success": true, "data": {"id": "inv_123", "clientRef": "users/<uid>/clients/client_123", "language": "de", "vatMode": "additive", "payments": {"proof": null, "items": [{"id": "pay_1", "methodId": "pm_bank", "amount": 500.0, "date": "2026-02-10T00:00:00+01:00"}]}, "date": "2026-02-25T00:00:00+01:00", "items": [{"id": "line_1", "name": "Software development", "price": 180, "units": 8, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}, {"id": "line_2", "name": "Project management", "price": 160, "units": 2, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}], "exchangeRate": null, "version": 11, "isPaid": false, "sent": true, "vatEnabled": true, "bankId": "bank_chf", "type": "normal", "currency": "CHF", "recurring": "disabled", "recurringDueDate": null, "recurringAutoSend": false, "description": "Vielen Dank für Ihren Auftrag.", "headerDescription": "", "disableRounding": true, "sentEmailHistory": [], "generationCount": 0, "hideQuotePricing": false, "isArchived": false, "clientId": "client_123", "number": 11, "totals": {"subtotal": 1760.0, "vat": 142.56, "total": 1902.56, "paid": 500.0, "due": 1402.56}, "dueDate": "2026-03-27"}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}, "503": {"description": "Too many simultaneous changes to the account's invoices; nothing was saved. Retry after `Retry-After` seconds", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"contended": {"summary": "Contended", "value": {"success": false, "error": "Too many simultaneous changes to this account's invoices; nothing was saved. Try again.", "code": "upstream_unavailable"}}}}}, "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}, "example": 2}}}}}}, "/invoices/scan-statement": {"post": {"tags": ["Payments"], "operationId": "match_statement_to_invoices", "summary": "Mark invoices paid from a bank statement", "description": "Reads the incoming payments from bank statement files (CSV or Excel) and matches them to your unpaid invoices. It only records payments and never creates invoices or expenses. To import a whole statement, use `POST /statements/import`.\n\n- A payment that names the invoice reference (such as `NA001`), or pays the exact total and clearly names the client, is recorded and marks the invoice paid.\n- A smaller payment that clearly identifies an invoice is recorded as a partial payment.\n- Weaker matches, and payments above what is still due, come back in `suggestions` and are not recorded.\n\nUploading the same statement again records nothing twice.", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object", "properties": {"files": {"type": "string", "format": "binary", "description": "A CSV or Excel bank statement; repeat the field for several files (`file` works too)."}, "markPaid": {"type": "string", "enum": ["true", "false"], "description": "`false`: record the payments but leave the invoices unpaid. Default `true`."}}, "required": ["files"]}}}}, "responses": {"200": {"description": "The statement was matched: the payments recorded, the suggestions and the unmatched payments", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/StatementMatchResult"}}, "required": ["data"]}]}, "examples": {"matched": {"summary": "One invoice paid, one suggestion", "value": {"success": true, "data": {"summary": {"transactions": 42, "invoicesScanned": 7, "markedPaid": 1, "partialPayments": 0, "suggestions": 1, "unmatched": 18}, "applied": [{"invoiceId": "inv_123", "hash": "NA011", "clientName": "ACME GmbH", "total": 1730.16, "amount": 1730.16, "action": "full", "tier": "high", "reason": "reference match", "transactionDate": "2026-03-04", "markedPaid": true, "alreadyRecorded": false}], "suggestions": [{"invoiceId": "inv_140", "hash": "NA014", "clientName": "Muster AG", "total": 540.0, "amount": 540.0, "tier": "low", "reason": "exact amount only (no name/reference)", "transactionDate": "2026-03-06"}], "unmatched": [{"date": "2026-03-07", "amount": 120.0, "description": "Gutschrift TWINT", "creditUnknown": false}], "parseErrors": []}}}}}}}, "400": {"description": "No file was uploaded", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"noFile": {"summary": "Missing file", "value": {"success": false, "error": "Missing file field `files`", "code": "invalid_request"}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "422": {"description": "No bank transactions could be read from the files; `details.parseErrors` says why", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"unreadable": {"summary": "Nothing readable", "value": {"success": false, "error": "Could not parse any bank transactions from the uploaded file(s)", "code": "parse_failed", "details": {"code": "parse_failed", "parseErrors": [{"file": "kontoauszug.pdf", "error": "Unsupported file type"}]}}}}}}}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/invoice-items": {"get": {"tags": ["Invoice items"], "operationId": "list_invoice_items", "summary": "List invoice items", "description": "Returns your products and services, sorted by `name`.", "parameters": [{"name": "limit", "in": "query", "required": false, "schema": {"type": "integer", "minimum": 1, "maximum": 5000}, "description": "Page size. Omit for the whole list (up to 5000 documents read).", "example": 50}, {"name": "cursor", "in": "query", "required": false, "schema": {"type": "string"}, "description": "`nextCursor` of the previous page, unchanged.", "example": "WyJ6IixudWxsLCJpbnZfMTIzIl0"}], "responses": {"200": {"description": "The invoice items", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"type": "object", "properties": {"items": {"type": "array", "items": {"$ref": "#/components/schemas/CatalogItemRecord"}}, "count": {"type": "integer", "minimum": 0, "description": "Number of `items` in this response."}, "nextCursor": {"type": ["string", "null"], "description": "Pass it as `cursor` to get the items after these; null when there are no more. It may lead to an empty page."}, "truncated": {"type": "boolean", "description": "true when the list stopped at the 5000 documents one call reads, so items may be missing: continue with `nextCursor`, or narrow the filters."}}, "required": ["items", "count", "nextCursor", "truncated"]}}, "required": ["data"]}]}, "examples": {"several": {"summary": "Several results", "value": {"success": true, "data": {"items": [{"id": "tmpl_consulting", "name": "Consulting hour", "price": 180, "units": 1, "vatRate": 8.1, "discount": 0, "usageCount": 2, "details": null, "isCreditNoteItem": false}, {"id": "tmpl_day", "name": "On-site consulting day", "price": 1440, "units": 1, "vatRate": 8.1, "discount": 0, "usageCount": 0, "details": null, "isCreditNoteItem": false}], "count": 2, "nextCursor": null, "truncated": false}}}, "firstPage": {"summary": "First page of several (`limit=1`)", "value": {"success": true, "data": {"items": [{"id": "tmpl_consulting", "name": "Consulting hour", "price": 180, "units": 1, "vatRate": 8.1, "discount": 0, "usageCount": 2, "details": null, "isCreditNoteItem": false}], "count": 1, "nextCursor": "WyJzIiwiQ29uc3VsdGluZyBob3VyIiwidG1wbF9jb25zdWx0aW5nIl0", "truncated": false}}}, "empty": {"summary": "No results", "value": {"success": true, "data": {"items": [], "count": 0, "nextCursor": null, "truncated": false}}}}}}}, "400": {"$ref": "#/components/responses/InvalidQuery"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "post": {"tags": ["Invoice items"], "operationId": "create_invoice_item", "summary": "Create an invoice item", "description": "Adds a product or service to your catalog. Only `name` is required; `price` defaults to 0, `units` to 1 and `vatRate` to 8.1. To put it on an invoice, copy its fields into a line of the invoice's `items`.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/CatalogItem"}, "examples": {"hour": {"summary": "Hourly rate", "value": {"name": "Consulting hour", "price": 180, "units": 1, "vatRate": 8.1}}, "day": {"summary": "Day rate with working hours", "value": {"name": "On-site consulting day", "price": 1440, "units": 1, "vatRate": 8.1, "details": {"type": "HourlyRateDetails", "date": "2026-02-20", "from": "09:00", "to": "17:00"}}}, "flatFee": {"summary": "Flat fee", "value": {"name": "Travel flat fee", "price": 120, "units": 1, "vatRate": 8.1}}, "discount": {"summary": "Discount line", "value": {"name": "Discount", "price": -50, "units": 1, "vatRate": 0}}}}}}, "responses": {"201": {"description": "The created invoice item", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/CatalogItemRecord"}}, "required": ["data"]}]}, "examples": {"created": {"summary": "Created", "value": {"success": true, "data": {"id": "tmpl_consulting", "name": "Consulting hour", "price": 180, "units": 1, "vatRate": 8.1, "discount": 0, "usageCount": 2, "details": null, "isCreditNoteItem": false}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "409": {"$ref": "#/components/responses/Conflict"}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/invoice-items/{itemId}": {"get": {"tags": ["Invoice items"], "operationId": "get_invoice_item", "summary": "Get an invoice item", "description": "Returns one product or service of your catalog.", "parameters": [{"name": "itemId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The invoice item's `id` (from `GET /invoice-items`).", "example": "tmpl_consulting"}], "responses": {"200": {"description": "The invoice item", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/CatalogItemRecord"}}, "required": ["data"]}]}, "examples": {"found": {"summary": "Found", "value": {"success": true, "data": {"id": "tmpl_consulting", "name": "Consulting hour", "price": 180, "units": 1, "vatRate": 8.1, "discount": 0, "usageCount": 2, "details": null, "isCreditNoteItem": false}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "patch": {"tags": ["Invoice items"], "operationId": "update_invoice_item", "summary": "Update an invoice item", "description": "Changes the fields you send and keeps the others. Invoices that already use the item keep their lines as they are.", "parameters": [{"name": "itemId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The invoice item's `id` (from `GET /invoice-items`).", "example": "tmpl_consulting"}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/CatalogItemPatch"}, "examples": {"rename": {"summary": "Rename", "value": {"name": "Senior consulting hour"}}, "price": {"summary": "New price", "value": {"price": 195}}, "hours": {"summary": "Set working hours", "value": {"details": {"type": "HourlyRateDetails", "date": "2026-02-20", "from": "09:00", "to": "17:00"}}}}}}}, "responses": {"200": {"description": "The updated invoice item", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/CatalogItemRecord"}}, "required": ["data"]}]}, "examples": {"updated": {"summary": "Updated", "value": {"success": true, "data": {"id": "tmpl_consulting", "name": "Consulting hour", "price": 180, "units": 1, "vatRate": 8.1, "discount": 0, "usageCount": 2, "details": null, "isCreditNoteItem": false}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "delete": {"tags": ["Invoice items"], "operationId": "delete_invoice_item", "summary": "Delete an invoice item", "description": "Removes the product or service from your catalog. Invoice lines copied from it are not affected.", "parameters": [{"name": "itemId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The invoice item's `id` (from `GET /invoice-items`).", "example": "tmpl_consulting"}], "responses": {"200": {"description": "The invoice item was deleted", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/DeleteResult"}}, "required": ["data"]}]}, "examples": {"deleted": {"summary": "Deleted", "value": {"success": true, "data": {"deleted": true, "id": "tmpl_consulting"}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/expenses": {"get": {"tags": ["Expenses"], "operationId": "list_expenses", "summary": "List expenses", "description": "Returns your expenses, newest `date` first. Filters can be combined.", "parameters": [{"name": "status", "in": "query", "required": false, "schema": {"type": "string", "enum": ["paid", "unpaid"]}, "description": "Only paid or only unpaid expenses.", "example": "unpaid"}, {"name": "year", "in": "query", "required": false, "schema": {"type": "integer"}, "description": "Only expenses dated in this Swiss calendar year.", "example": 2025}, {"name": "categoryId", "in": "query", "required": false, "schema": {"type": "string"}, "description": "Only expenses of this category (`categoryID`).", "example": "cat_travel"}, {"name": "limit", "in": "query", "required": false, "schema": {"type": "integer", "minimum": 1, "maximum": 5000}, "description": "Page size. Omit for the whole list (up to 5000 documents read).", "example": 50}, {"name": "cursor", "in": "query", "required": false, "schema": {"type": "string"}, "description": "`nextCursor` of the previous page, unchanged.", "example": "WyJ6IixudWxsLCJpbnZfMTIzIl0"}], "responses": {"200": {"description": "The expenses", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"type": "object", "properties": {"items": {"type": "array", "items": {"$ref": "#/components/schemas/ExpenseRecord"}}, "count": {"type": "integer", "minimum": 0, "description": "Number of `items` in this response."}, "nextCursor": {"type": ["string", "null"], "description": "Pass it as `cursor` to get the items after these; null when there are no more. It may lead to an empty page."}, "truncated": {"type": "boolean", "description": "true when the list stopped at the 5000 documents one call reads, so items may be missing: continue with `nextCursor`, or narrow the filters."}}, "required": ["items", "count", "nextCursor", "truncated"]}}, "required": ["data"]}]}, "examples": {"several": {"summary": "Several results", "value": {"success": true, "data": {"items": [{"id": "exp_123", "categoryID": "cat_travel", "paymentMethodID": "pm_card", "description": "SBB ticket client meeting", "documents": [], "amount": 82.4, "vatRate": 8.1, "originalAmount": null, "originalCurrency": null, "withholdingTax": false, "isPaid": true, "date": "2026-02-20T00:00:00+01:00"}, {"id": "exp_125", "categoryID": "cat_travel", "paymentMethodID": "pm_card", "description": "SBB ticket client meeting", "documents": [], "amount": 82.4, "vatRate": 8.1, "originalAmount": null, "originalCurrency": null, "withholdingTax": false, "isPaid": false, "date": "2026-02-20T00:00:00+01:00"}], "count": 2, "nextCursor": null, "truncated": false}}}, "firstPage": {"summary": "First page of several (`limit=1`)", "value": {"success": true, "data": {"items": [{"id": "exp_123", "categoryID": "cat_travel", "paymentMethodID": "pm_card", "description": "SBB ticket client meeting", "documents": [], "amount": 82.4, "vatRate": 8.1, "originalAmount": null, "originalCurrency": null, "withholdingTax": false, "isPaid": true, "date": "2026-02-20T00:00:00+01:00"}], "count": 1, "nextCursor": "WyJ0IiwiMjAyNi0wMi0yMFQwMDowMDowMCswMTowMCIsImV4cF8xMjMiXQ", "truncated": false}}}, "empty": {"summary": "No results", "value": {"success": true, "data": {"items": [], "count": 0, "nextCursor": null, "truncated": false}}}}}}}, "400": {"$ref": "#/components/responses/InvalidQuery"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "post": {"tags": ["Expenses"], "operationId": "create_expense", "summary": "Create an expense", "description": "Records an expense. `amount` is in CHF with VAT included; for a receipt in another currency, also send `originalAmount` and `originalCurrency`.\n\nSet the category and payment method by id (`categoryID`, `paymentMethodID`) or by name (`category`, `paymentMethod`), which creates them if missing. To create an expense from a receipt file, use `POST /expenses/scan-and-create`.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/CreateExpenseRequest"}, "examples": {"travel": {"summary": "Train ticket paid by card", "value": {"description": "SBB ticket client meeting", "amount": 82.4, "vatRate": 8.1, "date": "2026-02-20", "category": "Travel", "paymentMethod": "Credit Card", "isPaid": true}}, "cash": {"summary": "Office supplies paid in cash", "value": {"description": "Office supplies", "amount": 23.8, "vatRate": 8.1, "category": "Office", "paymentMethod": "Cash", "date": "2026-02-18", "isPaid": true}}, "foreignCurrency": {"summary": "Receipt in USD", "value": {"description": "SaaS subscription", "amount": 92.0, "vatRate": 0, "originalAmount": 99.0, "originalCurrency": "USD", "category": "Software", "paymentMethod": "Credit Card", "isPaid": true}}, "unpaid": {"summary": "Unpaid bill, with category ids and your own id", "value": {"id": "exp_accounting_2026_02", "description": "Accounting services invoice", "amount": 540, "vatRate": 8.1, "categoryID": "cat_professional", "paymentMethodID": "pm_bank", "isPaid": false}}, "nested": {"summary": "The expense wrapped in `expense`", "value": {"expense": {"description": "Parking", "amount": 6, "vatRate": 8.1}}}}}}}, "responses": {"201": {"description": "The created expense", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/ExpenseRecord"}}, "required": ["data"]}]}, "examples": {"created": {"summary": "Created", "value": {"success": true, "data": {"id": "exp_123", "categoryID": "cat_travel", "paymentMethodID": "pm_card", "description": "SBB ticket client meeting", "documents": [], "amount": 82.4, "vatRate": 8.1, "originalAmount": null, "originalCurrency": null, "withholdingTax": false, "isPaid": true, "date": "2026-02-20T00:00:00+01:00"}}}, "foreignCurrency": {"summary": "Receipt in USD", "value": {"success": true, "data": {"id": "exp_124", "categoryID": "cat_software", "paymentMethodID": "pm_card", "description": "SaaS subscription", "documents": [], "amount": 92.0, "vatRate": 0, "originalAmount": 99.0, "originalCurrency": "USD", "withholdingTax": false, "isPaid": true, "date": "2026-02-21T00:00:00+01:00"}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "409": {"description": "An expense with this `id` already exists", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"alreadyExists": {"summary": "Duplicate id", "value": {"success": false, "error": "Expense 'exp_123' already exists", "code": "already_exists"}}}}}}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/expenses/scan-and-create": {"post": {"tags": ["Expenses"], "operationId": "scan_receipt_to_expense", "summary": "Create an expense from a receipt", "description": "Reads an uploaded receipt or supplier invoice (PDF, image or HTML) and creates the expense, with the file attached.\n\nThe amount, date, VAT and description come from the receipt. The category and payment method are picked from yours, or created when none fits. A receipt in another currency is converted to CHF. Returns what was read (`scan`) and the created `expense`.", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object", "properties": {"expense": {"type": "string", "format": "binary", "description": "The receipt: PDF, image or HTML."}}, "required": ["expense"]}}}}, "responses": {"201": {"description": "The receipt was read and the expense created", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/ScanAndCreateResult"}}, "required": ["data"]}]}, "examples": {"created": {"summary": "Expense created", "value": {"success": true, "data": {"scan": {"description": "SBB ticket client meeting", "date": "2026-02-20", "paid": true, "vat_rate": 8.1, "vat_amount": 6.2, "currency": "CHF", "amount": 82.4, "category": "Travel", "payment_method": "Credit Card", "withholding_tax_relevant": false}, "expense": {"id": "exp_123", "categoryID": "cat_travel", "paymentMethodID": "pm_card", "description": "SBB ticket client meeting", "documents": [{"digest": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", "name": "sbb-ticket.pdf", "path": "users/<uid>/expenses/9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08.pdf", "size": 48213, "uploadDate": "2026-02-20T09:05:12+01:00", "url": "https://firebasestorage.googleapis.com/v0/b/magic-heidi.appspot.com/o/users%2F...%2Fexpenses%2F9f86...pdf?alt=media&token=..."}], "amount": 82.4, "vatRate": 8.1, "originalAmount": null, "originalCurrency": null, "withholdingTax": false, "isPaid": true, "date": "2026-02-20T00:00:00+01:00"}, "scanLocale": "en"}}}, "foreignCurrency": {"summary": "Receipt in USD, converted to CHF", "value": {"success": true, "data": {"scan": {"description": "SaaS subscription", "date": "2026-02-20", "paid": true, "vat_rate": 0.0, "vat_amount": 0.0, "currency": "USD", "amount": 92.0, "category": "Software", "payment_method": "Credit Card", "withholding_tax_relevant": false, "amount_original": 99.0}, "expense": {"id": "exp_124", "categoryID": "cat_software", "paymentMethodID": "pm_card", "description": "SaaS subscription", "documents": [{"digest": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", "name": "sbb-ticket.pdf", "path": "users/<uid>/expenses/9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08.pdf", "size": 48213, "uploadDate": "2026-02-20T09:05:12+01:00", "url": "https://firebasestorage.googleapis.com/v0/b/magic-heidi.appspot.com/o/users%2F...%2Fexpenses%2F9f86...pdf?alt=media&token=..."}], "amount": 92.0, "vatRate": 0, "originalAmount": 99.0, "originalCurrency": "USD", "withholdingTax": false, "isPaid": true, "date": "2026-02-20T00:00:00+01:00"}, "scanLocale": "en"}}}}}}}, "400": {"description": "No file or an empty file was uploaded, or what was read is not a valid expense", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"missingFile": {"summary": "Missing file", "value": {"success": false, "error": "Missing required file field `expense`", "code": "invalid_request"}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}, "502": {"description": "The receipt could not be read", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"scanFailed": {"summary": "Not readable", "value": {"success": false, "error": "Expense scan failed", "code": "upstream_unavailable"}}}}}}, "503": {"description": "Receipt scanning is temporarily unavailable", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"unavailable": {"summary": "Unavailable", "value": {"success": false, "error": "Expense scan is temporarily unavailable.", "code": "upstream_unavailable"}}}}}}}}}, "/expenses/{expenseId}": {"get": {"tags": ["Expenses"], "operationId": "get_expense", "summary": "Get an expense", "description": "Returns one expense.", "parameters": [{"name": "expenseId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The expense's `id`.", "example": "exp_123"}], "responses": {"200": {"description": "The expense", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/ExpenseRecord"}}, "required": ["data"]}]}, "examples": {"found": {"summary": "Found", "value": {"success": true, "data": {"id": "exp_123", "categoryID": "cat_travel", "paymentMethodID": "pm_card", "description": "SBB ticket client meeting", "documents": [], "amount": 82.4, "vatRate": 8.1, "originalAmount": null, "originalCurrency": null, "withholdingTax": false, "isPaid": true, "date": "2026-02-20T00:00:00+01:00"}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "patch": {"tags": ["Expenses"], "operationId": "update_expense", "summary": "Update an expense", "description": "Changes the fields you send and keeps the others. Set the category and payment method by id here; names are only accepted by `POST /expenses`.", "parameters": [{"name": "expenseId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The expense's `id`.", "example": "exp_123"}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Expense"}, "examples": {"paid": {"summary": "Mark paid", "value": {"isPaid": true}}, "amount": {"summary": "New amount and VAT", "value": {"amount": 89.4, "vatRate": 8.1}}, "category": {"summary": "New category and payment method", "value": {"categoryID": "cat_travel", "paymentMethodID": "pm_card"}}, "foreignCurrency": {"summary": "Original amount in USD", "value": {"originalAmount": 99, "originalCurrency": "USD"}}}}}}, "responses": {"200": {"description": "The updated expense", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/ExpenseRecord"}}, "required": ["data"]}]}, "examples": {"updated": {"summary": "Updated", "value": {"success": true, "data": {"id": "exp_123", "categoryID": "cat_travel", "paymentMethodID": "pm_card", "description": "SBB ticket client meeting", "documents": [], "amount": 82.4, "vatRate": 8.1, "originalAmount": null, "originalCurrency": null, "withholdingTax": false, "isPaid": true, "date": "2026-02-20T00:00:00+01:00"}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "delete": {"tags": ["Expenses"], "operationId": "delete_expense", "summary": "Delete an expense", "description": "Permanently deletes the expense.", "parameters": [{"name": "expenseId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The expense's `id`.", "example": "exp_123"}], "responses": {"200": {"description": "The expense was deleted", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/DeleteResult"}}, "required": ["data"]}]}, "examples": {"deleted": {"summary": "Deleted", "value": {"success": true, "data": {"deleted": true, "id": "exp_123"}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/categories": {"get": {"tags": ["Categories"], "operationId": "list_categories", "summary": "List categories", "description": "Returns your expense categories and payment methods, sorted by name. Filter with `type`.", "parameters": [{"name": "type", "in": "query", "required": false, "schema": {"type": "string", "enum": ["expense", "payment"]}, "description": "`expense`: only expense categories; `payment`: only payment methods.", "example": "payment"}, {"name": "limit", "in": "query", "required": false, "schema": {"type": "integer", "minimum": 1, "maximum": 5000}, "description": "Page size. Omit for the whole list (up to 5000 documents read).", "example": 50}, {"name": "cursor", "in": "query", "required": false, "schema": {"type": "string"}, "description": "`nextCursor` of the previous page, unchanged.", "example": "WyJ6IixudWxsLCJpbnZfMTIzIl0"}], "responses": {"200": {"description": "The categories", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"type": "object", "properties": {"items": {"type": "array", "items": {"$ref": "#/components/schemas/CategoryRecord"}}, "count": {"type": "integer", "minimum": 0, "description": "Number of `items` in this response."}, "nextCursor": {"type": ["string", "null"], "description": "Pass it as `cursor` to get the items after these; null when there are no more. It may lead to an empty page."}, "truncated": {"type": "boolean", "description": "true when the list stopped at the 5000 documents one call reads, so items may be missing: continue with `nextCursor`, or narrow the filters."}}, "required": ["items", "count", "nextCursor", "truncated"]}}, "required": ["data"]}]}, "examples": {"several": {"summary": "Several results", "value": {"success": true, "data": {"items": [{"id": "pm_bank", "name": "Bank transfer", "emoji": "🏦", "type": "payment"}, {"id": "cat_travel", "name": "Travel", "emoji": "🚆", "type": "expense"}], "count": 2, "nextCursor": null, "truncated": false}}}, "firstPage": {"summary": "First page of several (`limit=1`)", "value": {"success": true, "data": {"items": [{"id": "pm_bank", "name": "Bank transfer", "emoji": "🏦", "type": "payment"}], "count": 1, "nextCursor": "WyJzIiwiQmFuayB0cmFuc2ZlciIsInBtX2JhbmsiXQ", "truncated": false}}}, "empty": {"summary": "No results", "value": {"success": true, "data": {"items": [], "count": 0, "nextCursor": null, "truncated": false}}}}}}}, "400": {"$ref": "#/components/responses/InvalidQuery"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "post": {"tags": ["Categories"], "operationId": "create_category", "summary": "Create a category", "description": "Creates an expense category (`type: expense`, the default) or a payment method (`type: payment`). Only `name` is required.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Category"}, "examples": {"expense": {"summary": "Expense category", "value": {"name": "Travel", "emoji": "🚆", "type": "expense"}}, "software": {"summary": "Another expense category", "value": {"name": "Software", "emoji": "💻", "type": "expense"}}, "paymentMethod": {"summary": "Payment method", "value": {"name": "Bank transfer", "emoji": "🏦", "type": "payment"}}, "cash": {"summary": "Cash", "value": {"name": "Cash", "emoji": "💵", "type": "payment"}}}}}}, "responses": {"201": {"description": "The created category", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/CategoryRecord"}}, "required": ["data"]}]}, "examples": {"created": {"summary": "Created", "value": {"success": true, "data": {"id": "cat_travel", "name": "Travel", "emoji": "🚆", "type": "expense"}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "409": {"$ref": "#/components/responses/Conflict"}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/categories/{categoryId}": {"get": {"tags": ["Categories"], "operationId": "get_category", "summary": "Get a category", "description": "Returns one expense category or payment method.", "parameters": [{"name": "categoryId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The category's or payment method's `id`.", "example": "cat_travel"}], "responses": {"200": {"description": "The category", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/CategoryRecord"}}, "required": ["data"]}]}, "examples": {"found": {"summary": "Found", "value": {"success": true, "data": {"id": "cat_travel", "name": "Travel", "emoji": "🚆", "type": "expense"}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "patch": {"tags": ["Categories"], "operationId": "update_category", "summary": "Update a category", "description": "Changes the fields you send and keeps the others.", "parameters": [{"name": "categoryId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The category's or payment method's `id`.", "example": "cat_travel"}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/CategoryPatch"}, "examples": {"rename": {"summary": "Rename", "value": {"name": "Travel & transport"}}, "emoji": {"summary": "New emoji", "value": {"emoji": "✈️"}}, "both": {"summary": "Name and emoji", "value": {"name": "Bank transfer", "emoji": "🏦"}}}}}}, "responses": {"200": {"description": "The updated category", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/CategoryRecord"}}, "required": ["data"]}]}, "examples": {"updated": {"summary": "Updated", "value": {"success": true, "data": {"id": "cat_travel", "name": "Travel", "emoji": "🚆", "type": "expense"}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "delete": {"tags": ["Categories"], "operationId": "delete_category", "summary": "Delete a category", "description": "Deletes the expense category or payment method. One that expenses still use cannot be deleted: the 409 answer lists up to 5 of them in `details.expenseIds`. Invoice payments may keep the id of a deleted payment method.", "parameters": [{"name": "categoryId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The category's or payment method's `id`.", "example": "cat_travel"}], "responses": {"200": {"description": "The category was deleted", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/DeleteResult"}}, "required": ["data"]}]}, "examples": {"deleted": {"summary": "Deleted", "value": {"success": true, "data": {"deleted": true, "id": "cat_travel"}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "409": {"description": "Expenses still use the category", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"inUse": {"summary": "Category still used", "value": {"success": false, "error": "Cannot delete a category that expenses still use. Move them to another category first.", "code": "has_dependents", "details": {"expenseIds": ["exp_123"]}}}}}}}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/bank-accounts": {"get": {"tags": ["Bank accounts"], "operationId": "list_bank_accounts", "summary": "List bank accounts", "description": "Returns the accounts your invoices can show for payment. To import bank transactions, see `GET /bank/connections` instead. Unknown query parameters are ignored here.", "parameters": [{"name": "limit", "in": "query", "required": false, "schema": {"type": "integer", "minimum": 1, "maximum": 50}, "description": "Page size, 1-50. Omit for all accounts.", "example": 10}, {"name": "cursor", "in": "query", "required": false, "schema": {"type": "string"}, "description": "`nextCursor` of the previous page, unchanged.", "example": "WyJ6IixudWxsLCJpbnZfMTIzIl0"}], "responses": {"200": {"description": "The bank accounts", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"type": "object", "properties": {"items": {"type": "array", "items": {"$ref": "#/components/schemas/BankAccountRecord"}}, "count": {"type": "integer", "minimum": 0, "description": "Number of `items` in this response."}, "nextCursor": {"type": ["string", "null"], "description": "Pass it as `cursor` to get the items after these; null when there are no more. It may lead to an empty page."}, "truncated": {"type": "boolean", "description": "true when the list stopped at the 5000 documents one call reads, so items may be missing: continue with `nextCursor`, or narrow the filters."}}, "required": ["items", "count", "nextCursor", "truncated"]}}, "required": ["data"]}]}, "examples": {"accounts": {"summary": "Two accounts", "value": {"success": true, "data": {"items": [{"id": "bank_chf", "type": "iban", "name": "PostFinance", "currency": "CHF", "iban": "CH0700700112900411647"}, {"id": "bank_usd", "type": "custom", "name": "USD account", "currency": "USD", "data": "Routing 021000021 / Account 123456"}], "count": 2, "nextCursor": null, "truncated": false}}}}}}}, "400": {"$ref": "#/components/responses/InvalidQuery"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "post": {"tags": ["Bank accounts"], "operationId": "create_bank_account", "summary": "Add a bank account", "description": "Adds an account to print on invoices.\n\n- An `iban` account is in CHF or EUR, the currencies of the Swiss QR bill. A CHF IBAN also serves EUR invoices.\n- For any other currency, add a `custom` account in that currency, with the payment details as text in `data`.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/CreateBankAccountRequest"}, "examples": {"iban": {"summary": "CHF IBAN account", "value": {"type": "iban", "name": "PostFinance", "currency": "CHF", "iban": "CH07 0070 0112 9004 1164 7"}}, "custom": {"summary": "USD account with the details as text", "value": {"type": "custom", "name": "USD account", "currency": "USD", "data": "Routing 021000021 / Account 123456"}}}}}}, "responses": {"201": {"description": "The added bank account", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/BankAccountRecord"}}, "required": ["data"]}]}, "examples": {"iban": {"summary": "CHF IBAN account", "value": {"success": true, "data": {"id": "bank_chf", "type": "iban", "name": "PostFinance", "currency": "CHF", "iban": "CH0700700112900411647"}}}, "custom": {"summary": "USD account", "value": {"success": true, "data": {"id": "bank_usd", "type": "custom", "name": "USD account", "currency": "USD", "data": "Routing 021000021 / Account 123456"}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "409": {"$ref": "#/components/responses/Conflict"}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/bank-accounts/{bankAccountId}": {"get": {"tags": ["Bank accounts"], "operationId": "get_bank_account", "summary": "Get a bank account", "description": "Returns one of the accounts printed on invoices.", "parameters": [{"name": "bankAccountId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The bank account's `id` (from `GET /bank-accounts`).", "example": "bank_chf"}], "responses": {"200": {"description": "The bank account", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/BankAccountRecord"}}, "required": ["data"]}]}, "examples": {"found": {"summary": "Found", "value": {"success": true, "data": {"id": "bank_chf", "type": "iban", "name": "PostFinance", "currency": "CHF", "iban": "CH0700700112900411647"}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "patch": {"tags": ["Bank accounts"], "operationId": "update_bank_account", "summary": "Update a bank account", "description": "Changes the fields you send and keeps the others. The result must still be a valid account: an `iban` account needs a valid CHF or EUR IBAN, a `custom` one needs `data`.", "parameters": [{"name": "bankAccountId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The bank account's `id` (from `GET /bank-accounts`).", "example": "bank_chf"}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/UpdateBankAccountRequest"}, "examples": {"rename": {"summary": "Rename", "value": {"name": "Main account"}}, "wrapped": {"summary": "Rename, wrapped in `bankAccount`", "value": {"bankAccount": {"name": "Main account"}}}, "iban": {"summary": "New IBAN", "value": {"iban": "CH93 0076 2011 6238 5295 7"}}}}}}, "responses": {"200": {"description": "The updated bank account", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/BankAccountRecord"}}, "required": ["data"]}]}, "examples": {"renamed": {"summary": "Renamed", "value": {"success": true, "data": {"id": "bank_chf", "type": "iban", "name": "Main account", "currency": "CHF", "iban": "CH0700700112900411647"}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "delete": {"tags": ["Bank accounts"], "operationId": "delete_bank_account", "summary": "Delete a bank account", "description": "Removes the account. An account that invoices still use cannot be removed: the 409 answer lists up to 5 of them in `details.invoiceIds`.", "parameters": [{"name": "bankAccountId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The bank account's `id` (from `GET /bank-accounts`).", "example": "bank_chf"}], "responses": {"200": {"description": "The bank account was deleted", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/DeleteResult"}}, "required": ["data"]}]}, "examples": {"deleted": {"summary": "Deleted", "value": {"success": true, "data": {"deleted": true, "id": "bank_usd"}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "409": {"description": "Invoices use the account", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"usedByInvoices": {"summary": "Used by invoices", "value": {"success": false, "error": "Cannot delete a bank account used by invoices. Set those invoices to another bank account first.", "code": "has_dependents", "details": {"invoiceIds": ["inv_123"]}}}}}}}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/bank/providers": {"get": {"tags": ["Bank connections"], "operationId": "list_bank_providers", "summary": "List banks to connect", "description": "Returns the Swiss banks that can be connected. Show them in a bank picker and pass the chosen `providerId` to `POST /bank/connect`. `data` is a plain array, not a paged list.", "parameters": [{"name": "logos", "in": "query", "required": false, "schema": {"type": "boolean", "default": false}, "description": "`true`: include each bank's logo in `logo`, as a `data:` URI."}], "responses": {"200": {"description": "The banks", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"type": "array", "items": {"$ref": "#/components/schemas/BankProvider"}}}, "required": ["data"]}]}, "examples": {"providers": {"summary": "Two banks", "value": {"success": true, "data": [{"providerId": "IIDX00761", "name": "Aargauische Kantonalbank", "abbreviation": "AKB", "url": "https://www.akb.ch/", "logo": null}, {"providerId": "IIDX08710", "name": "Bank CIC", "abbreviation": "CIC", "url": "https://www.cic.ch/", "logo": null}]}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}, "502": {"description": "The bank or the open-banking service refused or failed; its message is passed on", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}}}}, "/bank/connect": {"post": {"tags": ["Bank connections"], "operationId": "connect_bank", "summary": "Connect a bank", "description": "Starts connecting a bank and returns the `authorizationUri` to open in the user's browser.\n\n1. Call this with a `providerId` from `GET /bank/providers`.\n2. Open `authorizationUri`. The user signs in at their bank and grants read access to their accounts; Magic Heidi never sees their bank credentials.\n3. When they are back, call `POST /bank/sync` to complete the connection and import the transactions.\n\nThe connection is `pending` until its first sync, then `active`.\n\n`actions` chooses what a sync does with the transactions; all three are on unless you switch one off, and at least one must stay on. Connecting a bank again keeps the actions you leave out.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "properties": {"providerId": {"type": "string", "description": "The bank, from `GET /bank/providers`."}, "scope": {"type": "string", "enum": ["urn:blink:xs2a:ais"], "default": "urn:blink:xs2a:ais", "description": "The access asked for; only reading account information is supported."}, "actions": {"type": "object", "properties": {"createInvoices": {"type": "boolean", "description": "Payouts from card terminals and platforms that match no invoice become paid invoices."}, "importExpenses": {"type": "boolean", "description": "Outgoing payments become paid expenses."}, "markPaid": {"type": "boolean", "description": "Incoming payments are recorded on the unpaid invoices they match."}}, "description": "What a sync does with the transactions. Default: all three."}}, "required": ["providerId"]}, "examples": {"connect": {"summary": "Connect a bank", "value": {"providerId": "IIDX00761"}}, "choose": {"summary": "Connect without importing expenses", "value": {"providerId": "IIDX00761", "actions": {"importExpenses": false}}}}}}}, "responses": {"201": {"description": "Connection started; open `authorizationUri` in the user's browser", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/BankConnectResult"}}, "required": ["data"]}]}, "examples": {"connect": {"summary": "Consent link and connection id", "value": {"success": true, "data": {"authorizationUri": "https://tools-blink-xe.np.six-group.com/serviceprovider/api/consent-flow/v2/oauth/authorize?response_type=code&redirect_uri=...&provider_id=IIDX00761&scope=urn:blink:xs2a:ais", "connectionId": "3f2c9b7a-1d4e-4c88-9a11-0b6d2e7c5a90"}}}}}}}, "400": {"description": "`providerId`, `scope` or `actions` is invalid, or the bank cannot be connected", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}, "502": {"description": "The bank or the open-banking service refused or failed; its message is passed on", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}}}}, "/bank/connections": {"get": {"tags": ["Bank connections"], "operationId": "list_bank_connections", "summary": "List bank connections", "description": "Returns the bank connections, each with its `status`, the bank's name and the accounts found on the last sync. A connection in `error` (consent refused, expired or revoked) is fixed by connecting the bank again. `data` is a plain array, not a paged list.", "responses": {"200": {"description": "The bank connections", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"type": "array", "items": {"$ref": "#/components/schemas/BankConnection"}}}, "required": ["data"]}]}, "examples": {"connections": {"summary": "One active connection", "value": {"success": true, "data": [{"id": "3f2c9b7a-1d4e-4c88-9a11-0b6d2e7c5a90", "providerId": "IIDX00761", "providerName": "Aargauische Kantonalbank", "status": "active", "sixStatus": "valid", "scope": "urn:blink:xs2a:ais", "actions": {"createInvoices": true, "importExpenses": true, "markPaid": true}, "accounts": [{"id": "1", "iban": "CH0208401000051138778", "currency": "CHF", "owner": "Hans Muster", "designation": "Privatkonto"}], "createdAt": "2026-07-17T16:05:00+02:00", "lastSyncedAt": "2026-07-17T16:06:12+02:00", "lastSyncAttemptAt": "2026-07-17T16:06:12+02:00", "lastSyncError": null}]}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/bank/connections/{connectionId}": {"patch": {"tags": ["Bank connections"], "operationId": "update_bank_connection", "summary": "Change what a bank connection does", "description": "Switches a connection's `actions` on or off; the ones you leave out stay as they are, and at least one must stay on. It applies from the next sync. An action switched back on picks up the transactions of the last few days, not older ones.", "parameters": [{"name": "connectionId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The bank connection's `id` (from `GET /bank/connections`).", "example": "3f2c9b7a-1d4e-4c88-9a11-0b6d2e7c5a90"}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "properties": {"actions": {"type": "object", "properties": {"createInvoices": {"type": "boolean", "description": "Payouts from card terminals and platforms that match no invoice become paid invoices."}, "importExpenses": {"type": "boolean", "description": "Outgoing payments become paid expenses."}, "markPaid": {"type": "boolean", "description": "Incoming payments are recorded on the unpaid invoices they match."}}, "description": "The actions to change."}}, "required": ["actions"]}, "examples": {"expenses_off": {"summary": "Stop importing expenses", "value": {"actions": {"importExpenses": false}}}}}}}, "responses": {"200": {"description": "The updated connection", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/BankConnection"}}, "required": ["data"]}]}, "examples": {"updated": {"summary": "Expenses are no longer imported", "value": {"success": true, "data": {"id": "3f2c9b7a-1d4e-4c88-9a11-0b6d2e7c5a90", "providerId": "IIDX00761", "providerName": "Aargauische Kantonalbank", "status": "active", "sixStatus": "valid", "scope": "urn:blink:xs2a:ais", "actions": {"createInvoices": true, "importExpenses": false, "markPaid": true}, "accounts": [], "createdAt": "2026-07-17T16:05:00+02:00", "lastSyncedAt": "2026-07-17T16:06:12+02:00", "lastSyncAttemptAt": "2026-07-17T16:06:12+02:00", "lastSyncError": null}}}}}}}, "400": {"description": "`actions` is missing or invalid, or would switch every action off", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "delete": {"tags": ["Bank connections"], "operationId": "disconnect_bank", "summary": "Disconnect a bank", "description": "Withdraws the consent at the bank and removes the connection. The connection is removed even when the bank does not confirm; `revoked` says whether it did.", "parameters": [{"name": "connectionId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The bank connection's `id` (from `GET /bank/connections`).", "example": "3f2c9b7a-1d4e-4c88-9a11-0b6d2e7c5a90"}], "responses": {"200": {"description": "The connection was removed", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/BankDisconnectResult"}}, "required": ["data"]}]}, "examples": {"disconnected": {"summary": "Consent withdrawn and connection removed", "value": {"success": true, "data": {"deleted": true, "id": "3f2c9b7a-1d4e-4c88-9a11-0b6d2e7c5a90", "revoked": true}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/bank/sync": {"post": {"tags": ["Bank connections"], "operationId": "sync_bank_connections", "summary": "Import new bank transactions", "description": "Imports the latest transactions of every connected account and books them. It also completes pending connections. A connection skips the steps its `actions` switch off.\n\n- Incoming payments are matched to your unpaid invoices.\n- Payouts from card terminals and platforms (SumUp, Stripe, Apple…) that match no invoice become paid invoices.\n- Outgoing payments become paid expenses, each with one of your categories. No category is invented: `needCategory` counts the expenses none fitted.\n- Other incoming payments are left for you, counted in `unmatchedCredits`.\n\nAccounts that could not be read (`failedAccounts`), or whose bank day is not final yet (`deferredAccounts`), are retried on the next sync. `details` lists the rows behind the counts.", "responses": {"200": {"description": "The transactions were imported", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/BankSyncResult"}}, "required": ["data"]}]}, "examples": {"sync": {"summary": "Counts and the rows behind them", "value": {"success": true, "data": {"syncedConnections": 1, "skippedConnections": 0, "failedAccounts": 0, "deferredAccounts": 1, "invoicesMatched": 1, "invoicesCreated": 1, "partialPayments": 0, "unmatchedCredits": 1, "expensesCreated": 1, "needCategory": 0, "details": {"matched": [{"label": "Muster AG", "sublabel": "2026-08-20 · +1500.00 CHF · RF18 5390 0754 7034", "reason": "Paid Muster AG · reference match", "invoiceId": "6c2f..."}], "invoices_created": [{"label": "SUMUP PAYMENTS LIMITED", "sublabel": "2026-08-20 · +39.40 CHF", "reason": "Created paid invoice · Sumup payout 20.08.2026", "invoiceId": "9a1b..."}], "expenses_created": [{"label": "Swisscom Mobile-Abo August", "sublabel": "2026-08-20 · -89.99 CHF", "reason": "Categorised as Büroausgaben", "expenseId": "a450..."}], "unmatched_credits": [{"label": "Incoming transfer", "sublabel": "2026-08-20 · +450.50 CHF", "reason": "No matching invoice", "date": "2026-08-20", "amount": 450.5}], "pending": [{"label": "Kartenzahlung Migros", "sublabel": "2026-08-21 · -23.10 CHF", "reason": "Not booked yet"}], "skipped_accounts": [{"label": "Sparkonto", "reason": "Bank data is not finalized yet; retry later"}], "reversals": [{"label": "Storno Lastschrift", "sublabel": "2026-08-19 · +120.00 CHF", "reason": "Reversal — review the original payment"}]}}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}, "502": {"description": "The bank or the open-banking service refused or failed; its message is passed on", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}}}}, "/clients/import": {"post": {"tags": ["Imports"], "operationId": "import_clients", "summary": "Import clients from a spreadsheet", "description": "Creates clients from a spreadsheet, such as an export from another invoicing tool. Columns are recognised automatically, in any language and layout.\n\nRows without a usable name, rows that are not clients, and clients you already have (same name or email) are skipped.", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object", "properties": {"file": {"type": "string", "format": "binary", "description": "A CSV or Excel (.xlsx/.xls) file of clients."}, "locale": {"type": "string", "description": "Language for the texts the import writes (`de`, `en`, `fr` or `it`). Defaults to the account language."}}, "required": ["file"]}}}}, "responses": {"201": {"description": "The file was imported; the summary says what happened to each row", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/SpreadsheetImportResult"}}, "required": ["data"]}]}, "examples": {"imported": {"summary": "Imported", "value": {"success": true, "data": {"success": true, "total_rows": 25, "dropped_invalid": 1, "skipped_duplicate": 4, "skipped_by_ai": 2, "ai_failures": 0, "imported": 18, "errors": [], "dry_run": false, "structure_source": "ai", "details": {"imported": [{"label": "ACME GmbH", "sublabel": "billing@acme.ch"}], "skipped_duplicate": [{"label": "Muster AG", "sublabel": "info@muster.ch", "reason": "already in your clients"}]}}}}}}}}, "400": {"description": "No file, an empty file, or a file that could not be read; `details` holds the import summary", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"noFile": {"summary": "Missing file", "value": {"success": false, "error": "Missing required file field `file`", "code": "invalid_request"}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}, "502": {"description": "Saving the imported clients failed; retry", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}}}}, "/invoice-items/import": {"post": {"tags": ["Imports"], "operationId": "import_invoice_items", "summary": "Import invoice items from a spreadsheet", "description": "Adds products and services from a spreadsheet to your catalog. Name, price, quantity and VAT columns are recognised automatically.\n\nRows without a usable name, inactive rows and items you already have (same name) are skipped.", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object", "properties": {"file": {"type": "string", "format": "binary", "description": "A CSV or Excel (.xlsx/.xls) file of invoice items."}, "locale": {"type": "string", "description": "Language for the texts the import writes (`de`, `en`, `fr` or `it`). Defaults to the account language."}}, "required": ["file"]}}}}, "responses": {"201": {"description": "The file was imported; the summary says what happened to each row", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/SpreadsheetImportResult"}}, "required": ["data"]}]}, "examples": {"imported": {"summary": "Imported", "value": {"success": true, "data": {"success": true, "total_rows": 25, "dropped_invalid": 1, "skipped_duplicate": 4, "skipped_by_ai": 2, "ai_failures": 0, "imported": 18, "errors": [], "dry_run": false, "structure_source": "ai", "details": {"imported": [{"label": "ACME GmbH", "sublabel": "billing@acme.ch"}], "skipped_duplicate": [{"label": "Muster AG", "sublabel": "info@muster.ch", "reason": "already in your clients"}]}}}}}}}}, "400": {"description": "No file, an empty file, or a file that could not be read; `details` holds the import summary", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"noFile": {"summary": "Missing file", "value": {"success": false, "error": "Missing required file field `file`", "code": "invalid_request"}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}, "502": {"description": "Saving the imported invoice items failed; retry", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}}}}, "/expenses/import": {"post": {"tags": ["Imports"], "operationId": "import_expenses", "summary": "Import expenses from a file", "description": "Creates expenses from a file that lists costs only, such as an expense report or a card statement. For a bank statement that also has income, use `POST /statements/import`.\n\n- In a spreadsheet, columns are recognised automatically, in any language and layout. Rows without a date, amount or description are dropped.\n- From a camt statement, only booked outgoing payments are imported. Incoming money and reversals are counted in `skipped_credits`.\n- Expenses you already have (same amount, date within a day) are skipped, so importing a file twice creates nothing twice.\n- Each expense gets one of your categories and payment methods; none are invented.\n- Amounts in another currency are converted to CHF, keeping the original in `originalAmount` and `originalCurrency`.", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object", "properties": {"file": {"type": "string", "format": "binary", "description": "A CSV or Excel (.xlsx/.xls) file of expenses, or a camt.052/053/054 XML bank statement."}, "locale": {"type": "string", "description": "Language for the texts the import writes (`de`, `en`, `fr` or `it`). Defaults to the account language."}}, "required": ["file"]}}}}, "responses": {"201": {"description": "The file was imported; the summary says what happened to each row", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/ExpenseImportResult"}}, "required": ["data"]}]}, "examples": {"imported": {"summary": "Imported", "value": {"success": true, "data": {"success": true, "total_rows": 19, "dropped_invalid": 0, "skipped_credits": 0, "skipped_pre_ai_duplicate": 0, "skipped_post_ai_duplicate": 0, "skipped_duplicate": 0, "skipped_by_ai": 7, "ai_failures": 0, "imported": 12, "errors": [], "dry_run": false, "structure_source": "heuristic", "learnedExamples": 40, "details": {"imported": [{"label": "Swisscom Mobile-Abo August", "sublabel": "2026-08-20 · 89.99 CHF"}], "skipped_by_ai": [{"label": "Umbuchung Sparkonto", "sublabel": "2026-08-21 · 500.00", "reason": "transfer between own accounts"}]}}}}}}}}, "400": {"description": "No file, an empty file, or a file that could not be read; `details` holds the import summary", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"noFile": {"summary": "Missing file", "value": {"success": false, "error": "Missing required file field `file`", "code": "invalid_request"}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}, "502": {"description": "Saving the imported expenses failed; retry", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}}}}, "/statements/import": {"post": {"tags": ["Imports"], "operationId": "import_bank_statement", "summary": "Import a bank statement", "description": "The one call for a bank statement: it books both its costs and its income.\n\n- Outgoing payments become expenses, as with `POST /expenses/import`.\n- Incoming payments first settle your unpaid invoices. The rest become paid invoices when they are revenue, as with `POST /invoices/import`.\n\nThe two halves run independently, and either can be turned off with `importExpenses` or `createInvoices`. Whatever failed is listed in `parseErrors`.", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object", "properties": {"files": {"type": "string", "format": "binary", "description": "A bank statement: CSV, Excel, or ISO 20022 camt.052/053/054 XML; repeat the field for several files."}, "locale": {"type": "string", "description": "Language for the texts the import writes (`de`, `en`, `fr` or `it`). Defaults to the account language."}, "dryRun": {"type": "string", "enum": ["true", "false"], "description": "`true`: report what would be imported without saving anything. Default `false`."}, "markPaid": {"type": "string", "enum": ["true", "false"], "description": "`false`: record payments on matched invoices but leave them unpaid. Default `true`."}, "importExpenses": {"type": "string", "enum": ["true", "false"], "description": "`false`: skip the outgoing payments. Default `true`."}, "createInvoices": {"type": "string", "enum": ["true", "false"], "description": "`false`: skip the incoming payments. Default `true`."}}, "required": ["files"]}}}}, "responses": {"201": {"description": "The statement was imported: a summary, then the full result of each half", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/StatementImportResult"}}, "required": ["data"]}]}, "examples": {"imported": {"summary": "Imported", "value": {"success": true, "data": {"dryRun": false, "summary": {"files": 1, "expensesImported": 12, "invoicesCreated": 91, "markedPaid": 2, "duplicatesSkipped": 0, "nonInvoiceable": 1, "unclassified": 1}, "expenses": {"success": true, "total_rows": 19, "dropped_invalid": 0, "skipped_credits": 0, "skipped_pre_ai_duplicate": 0, "skipped_post_ai_duplicate": 0, "skipped_duplicate": 0, "skipped_by_ai": 7, "ai_failures": 0, "imported": 12, "errors": [], "dry_run": false, "structure_source": "heuristic", "learnedExamples": 40, "details": {"imported": [{"label": "Swisscom Mobile-Abo August", "sublabel": "2026-08-20 · 89.99 CHF"}], "skipped_by_ai": [{"label": "Umbuchung Sparkonto", "sublabel": "2026-08-21 · 500.00", "reason": "transfer between own accounts"}]}}, "invoices": {"success": true, "total_rows": 123, "matched": {"markedPaid": 2, "partialPayments": 0, "applied": [], "suggestions": []}, "imported": 91, "created": [{"invoiceId": "abc123", "version": 41, "importRef": "camt:8f2a1c…", "clientId": "cli_1", "clientName": "Sumup", "clientCreated": true, "amount": 39.4, "currency": "CHF", "date": "2026-01-30", "itemName": "Versement Sumup du 30.01.2026", "kind": "acquirer_payout"}], "skipped_duplicate": 0, "skippedDuplicates": [], "nonInvoiceable": [{"date": "2026-01-07", "amount": 220.0, "currency": "CHF", "description": "Dépôt bancomat CHF 220.00", "counterparty": "", "importRef": "camt:41c9e0…", "reason": "card_transaction"}], "unclassified": [{"date": "2026-07-24", "amount": 70.0, "currency": "CHF", "description": "Crédit Instant Payment Oscar Jon Hamilton", "counterparty": "Oscar Jon Hamilton", "importRef": "camt:5d0e7b…", "aiReason": "identifiable payer but no reference to a service"}], "ai_failures": 0, "errors": [], "dry_run": false, "learnedExamples": 12, "reclaimed": 0, "details": {"created": [{"label": "Sumup", "sublabel": "2026-01-30 · 39.40 CHF", "reason": "Versement Sumup du 30.01.2026"}], "matched": [], "skipped_duplicate": [], "non_invoiceable": [{"label": "Dépôt bancomat CHF 220.00", "sublabel": "2026-01-07 · 220.00 CHF", "reason": "card_transaction", "payload": {"credit": {"importRef": "camt:41c9e0…", "amount": 220.0, "currency": "CHF", "date": "2026-01-07", "description": "Dépôt bancomat CHF 220.00"}, "clientName": "Dépôt bancomat CHF 220.00", "itemName": "Dépôt bancomat CHF 220.00"}}], "unclassified": [{"label": "Oscar Jon Hamilton", "sublabel": "2026-07-24 · 70.00 CHF", "reason": "identifiable payer but no reference to a service", "payload": {"credit": {"importRef": "camt:5d0e7b…", "amount": 70.0, "currency": "CHF", "date": "2026-07-24", "counterparty": "Oscar Jon Hamilton", "description": "Crédit Instant Payment Oscar Jon Hamilton"}, "clientName": "Oscar Jon Hamilton", "itemName": "Oscar Jon Hamilton"}}], "skipped_debits": []}}, "parseErrors": []}}}}}}}, "400": {"description": "No file was uploaded, or both halves were turned off", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"noFile": {"summary": "Missing file", "value": {"success": false, "error": "Missing required file field `files`", "code": "invalid_request"}}, "nothingToDo": {"summary": "Both halves off", "value": {"success": false, "error": "Nothing to do: importExpenses and createInvoices are both false", "code": "invalid_request"}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "422": {"description": "Nothing could be imported from the files; `details.parseErrors` says why", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"nothingImported": {"summary": "Nothing imported", "value": {"success": false, "error": "Could not import anything from the uploaded file(s)", "code": "import_failed", "details": {"code": "import_failed", "parseErrors": [{"file": "kontoauszug.pdf", "phase": "expenses", "error": "Unsupported file type"}]}}}}}}}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/invoices/import": {"post": {"tags": ["Imports"], "operationId": "import_invoices_from_statement", "summary": "Create invoices from a bank statement's income", "description": "Books only the income of a bank statement, without its costs.\n\n- An incoming payment that matches an unpaid invoice is recorded on it and marks it paid.\n- A remaining payment becomes a paid invoice only when it is clearly a customer paying for goods or services. Payouts from card terminals, app stores and marketplaces (SumUp, TWINT, Stripe, PayPal, Apple, Google, Shopify…) become one invoice per payout.\n- Cash deposits, refunds, transfers between your own accounts and payments already booked are left out.\n- Payments that are not clearly revenue come back under `unclassified` (unsure) or `nonInvoiceable` (not revenue). Each row carries a `payload` to create the invoice anyway with `POST /invoices/from-credit`.\n\nCreated invoices are paid on the transaction date, VAT included, so their total is the money received. Importing the same statement again creates nothing twice.\n\nA spreadsheet that is an invoice list from another tool is imported as `POST /invoices/import-history` does, unless `dryRun` is set; its invoices are listed under `details.created`.", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object", "properties": {"file": {"type": "string", "format": "binary", "description": "A bank statement: CSV, Excel, or ISO 20022 camt.052/053/054 XML."}, "locale": {"type": "string", "description": "Language for the texts the import writes (`de`, `en`, `fr` or `it`). Defaults to the account language."}, "markPaid": {"type": "string", "enum": ["true", "false"], "description": "`false`: record payments on matched invoices but leave them unpaid. Default `true`."}, "dryRun": {"type": "string", "enum": ["true", "false"], "description": "`true`: report what would be imported without saving anything. Default `false`."}, "groupByMonth": {"type": "string", "enum": ["true", "false"], "description": "For an invoice list, `true` merges its rows into one invoice per month even when they name their clients. Default `false`."}}, "required": ["file"]}}}}, "responses": {"201": {"description": "The statement was imported: what was matched, created, skipped and left for review", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/InvoiceImportResult"}}, "required": ["data"]}]}, "examples": {"imported": {"summary": "Imported", "value": {"success": true, "data": {"success": true, "total_rows": 123, "matched": {"markedPaid": 2, "partialPayments": 0, "applied": [], "suggestions": []}, "imported": 91, "created": [{"invoiceId": "abc123", "version": 41, "importRef": "camt:8f2a1c…", "clientId": "cli_1", "clientName": "Sumup", "clientCreated": true, "amount": 39.4, "currency": "CHF", "date": "2026-01-30", "itemName": "Versement Sumup du 30.01.2026", "kind": "acquirer_payout"}], "skipped_duplicate": 0, "skippedDuplicates": [], "nonInvoiceable": [{"date": "2026-01-07", "amount": 220.0, "currency": "CHF", "description": "Dépôt bancomat CHF 220.00", "counterparty": "", "importRef": "camt:41c9e0…", "reason": "card_transaction"}], "unclassified": [{"date": "2026-07-24", "amount": 70.0, "currency": "CHF", "description": "Crédit Instant Payment Oscar Jon Hamilton", "counterparty": "Oscar Jon Hamilton", "importRef": "camt:5d0e7b…", "aiReason": "identifiable payer but no reference to a service"}], "ai_failures": 0, "errors": [], "dry_run": false, "learnedExamples": 12, "reclaimed": 0, "details": {"created": [{"label": "Sumup", "sublabel": "2026-01-30 · 39.40 CHF", "reason": "Versement Sumup du 30.01.2026"}], "matched": [], "skipped_duplicate": [], "non_invoiceable": [{"label": "Dépôt bancomat CHF 220.00", "sublabel": "2026-01-07 · 220.00 CHF", "reason": "card_transaction", "payload": {"credit": {"importRef": "camt:41c9e0…", "amount": 220.0, "currency": "CHF", "date": "2026-01-07", "description": "Dépôt bancomat CHF 220.00"}, "clientName": "Dépôt bancomat CHF 220.00", "itemName": "Dépôt bancomat CHF 220.00"}}], "unclassified": [{"label": "Oscar Jon Hamilton", "sublabel": "2026-07-24 · 70.00 CHF", "reason": "identifiable payer but no reference to a service", "payload": {"credit": {"importRef": "camt:5d0e7b…", "amount": 70.0, "currency": "CHF", "date": "2026-07-24", "counterparty": "Oscar Jon Hamilton", "description": "Crédit Instant Payment Oscar Jon Hamilton"}, "clientName": "Oscar Jon Hamilton", "itemName": "Oscar Jon Hamilton"}}], "skipped_debits": []}}}}}}}}, "400": {"description": "No file, an empty file, or a file that could not be read; `details` holds the import summary", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"noFile": {"summary": "Missing file", "value": {"success": false, "error": "Missing required file field `file`", "code": "invalid_request"}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}, "502": {"description": "Saving the imported invoices failed; retry", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}}}}, "/invoices/import-mooncare": {"post": {"tags": ["Imports"], "operationId": "import_mooncare", "summary": "Import a Mooncare export", "description": "Imports invoices from a Mooncare export: XLSX or CSV, CHF only, up to 5 MB and 200 invoices. The file is read by fixed rules, without AI, and nothing is emailed. All rows are validated first and saved together, so an invalid file writes nothing.\n\n- The client is the `Cliente` column, else the insurer, else an anonymous client.\n- The six service categories and the dated payments are kept. The header note carries the Mooncare number and the insurer.\n- Invoices get new Magic Heidi numbers; the original numbers are kept.\n- Totals rounded to 5 rappen use the app's rounding. Any other difference between the categories and the total, up to CHF 0.05, becomes a separate rounding line; a larger one fails validation.\n- Importing a file again skips the invoices already imported and never updates their payments. An invoice is recognised by its payment reference (`No. de référence`), else by number, date and client.\n\nFiles with unevaluated Excel formulas or truncated rows are rejected. At most 6 imports per minute per account.", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object", "properties": {"file": {"type": "string", "format": "binary"}}, "required": ["file"]}}}}, "responses": {"201": {"description": "Imported and skipped counts", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"type": "object"}}, "required": ["data"]}]}}}}, "400": {"description": "Invalid Mooncare file; nothing written", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}, "503": {"description": "Storage unavailable; retry the same file safely", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}}}}, "/invoices/import-history": {"post": {"tags": ["Imports"], "operationId": "import_invoice_history", "summary": "Import an invoice list from another tool", "description": "Creates invoices from an invoice list exported by another tool (bexio, Zervant, a spreadsheet). Use it when moving to Magic Heidi; for a bank statement, use `POST /statements/import`. Columns are recognised automatically, in any language and layout.\n\n- Paid invoices get their payments on the dates in the file. Without a payment date, the due date is used if it has passed, else the invoice date. Open and overdue invoices stay unpaid.\n- Cancelled invoices, drafts, credit notes and quotes are skipped (`skipped_status`), as are rows without a client, date or amount (`dropped_invalid`) and invoices you already have (`skipped_duplicate`). Importing the same file twice creates nothing twice.\n- The digits of the original number become the invoice number (`RE-00064` becomes 64), so your sequence continues. A number already taken that year moves after the year's highest (`renumbered`). The original is kept as `importedNumber`.\n- A column of VAT amounts per rate splits an invoice exactly; otherwise the rate comes from net and gross. Only Swiss rates in force on the invoice date are written. A mixed-rate invoice read from its totals alone is split approximately and listed under `details.check_vat`.\n- Clients and payment methods you do not have yet are created. Without a payment-method column, the method is \"Import\".\n- A file that names no client, such as a practice export without patient names (OneDoc), is merged into one invoice per month for a general client (`grouped`). `groupByMonth` does this for any file. A month is imported once: to import it again with more rows, delete that month's invoice first.", "requestBody": {"required": true, "content": {"multipart/form-data": {"schema": {"type": "object", "properties": {"file": {"type": "string", "format": "binary", "description": "A CSV or Excel (.xlsx/.xls/.ods) invoice list."}, "groupByMonth": {"type": "string", "enum": ["true", "false"], "description": "For an invoice list, `true` merges its rows into one invoice per month even when they name their clients. Default `false`."}}, "required": ["file"]}}}}, "responses": {"201": {"description": "The list was imported; the summary says what happened to each row", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/InvoiceHistoryImportResult"}}, "required": ["data"]}]}, "examples": {"imported": {"summary": "Imported", "value": {"success": true, "data": {"success": true, "total_rows": 183, "imported": 172, "grouped": 0, "renumbered": 1, "skipped_duplicate": 8, "skipped_status": 3, "dropped_invalid": 0, "clients_created": 41, "errors": [], "details": {"imported": [{"label": "ACME GmbH", "sublabel": "RE-00064", "date": "2025-03-05", "amount": 1297.2}], "renumbered": [{"label": "Muster AG", "sublabel": "RE-00005 → 65", "reason": "number already used that year"}], "skipped_duplicate": [{"label": "Bäckerei Keller", "sublabel": "RE-00012", "reason": "already in Magic Heidi", "date": "2025-01-20", "amount": 441.1}], "skipped_status": [{"label": "Studio Nord", "sublabel": "RE-00031", "reason": "cancelled"}], "check_vat": [{"label": "Hotel Alpenblick", "sublabel": "RE-00048", "reason": "mixed VAT, split as 8.1% / 2.6%: please check"}]}}}}}}}}, "400": {"description": "No file, a file that could not be read, or a file that is not an invoice list", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"noFile": {"summary": "Missing file", "value": {"success": false, "error": "Missing required file field `file`", "code": "invalid_request"}}, "notAnInvoiceList": {"summary": "Not an invoice list", "value": {"success": false, "error": "This file doesn't look like an invoice list: it needs a client, a date and an amount per invoice", "code": "invalid_request", "details": {"success": false, "error": "This file doesn't look like an invoice list: it needs a client, a date and an amount per invoice"}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}, "502": {"description": "The columns could not be read by the AI, or saving the invoices failed; retry", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"columnsNotRead": {"summary": "AI unavailable", "value": {"success": false, "error": "Could not read the columns of this file; try again", "code": "upstream_unavailable", "details": {"success": false, "error": "Could not read the columns of this file; try again", "error_kind": "ai"}}}}}}}}}}, "/invoices/from-credit": {"post": {"tags": ["Imports"], "operationId": "create_invoice_from_credit", "summary": "Create an invoice for a skipped payment", "description": "Creates a paid invoice for one incoming payment that an import left out (`unclassified` or `nonInvoiceable`) but that is revenue after all.\n\nPost the row's `payload` from the import's `details` as it is, optionally with another `clientName` or `itemName`. The invoice is paid on the transaction date, VAT included. Posting the same payment again returns the first invoice, with `alreadyExisted: true` and status 200, so the call is safe to retry.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "properties": {"credit": {"type": "object", "properties": {"date": {"type": "string", "format": "date"}, "amount": {"type": "number", "description": "Positive."}, "currency": {"type": "string", "default": "CHF"}, "counterparty": {"type": "string"}, "description": {"type": "string"}, "importRef": {"type": "string", "description": "The payment's fingerprint from the import; makes the call safe to retry."}}, "required": ["date", "amount"]}, "clientName": {"type": "string", "description": "Who to invoice. Defaults to the payer, then the payment's description."}, "itemName": {"type": "string", "description": "What was sold. Defaults to the client name."}}, "required": ["credit"]}, "examples": {"payout": {"summary": "A Google payout", "value": {"credit": {"date": "2026-06-16", "amount": 1669.74, "currency": "CHF", "counterparty": "GOOGLE PAYMENT CORP", "importRef": "camt:8f2a1c…"}, "clientName": "Google", "itemName": "Google payout 16.06.2026"}}, "fromImport": {"summary": "A row's `payload`, as the import returned it", "value": {"credit": {"importRef": "camt:5d0e7b…", "amount": 70.0, "currency": "CHF", "date": "2026-07-24", "counterparty": "Oscar Jon Hamilton", "description": "Crédit Instant Payment Oscar Jon Hamilton"}, "clientName": "Oscar Jon Hamilton", "itemName": "Oscar Jon Hamilton"}}}}}}, "responses": {"200": {"description": "This payment was booked before; the existing invoice is returned", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/CreditInvoice"}}, "required": ["data"]}]}, "examples": {"alreadyExisted": {"summary": "Booked before", "value": {"success": true, "data": {"invoiceId": "9a1b2c3d", "version": 42, "alreadyExisted": true}}}}}}}, "201": {"description": "The invoice was created", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/CreditInvoice"}}, "required": ["data"]}]}, "examples": {"created": {"summary": "Created", "value": {"success": true, "data": {"invoiceId": "9a1b2c3d", "version": 42, "importRef": "camt:5d0e7b…", "clientId": "cli_7", "clientName": "Oscar Jon Hamilton", "clientCreated": true, "amount": 70.0, "currency": "CHF", "date": "2026-07-24", "itemName": "Oscar Jon Hamilton", "alreadyExisted": false}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}, "503": {"description": "Too many simultaneous changes to the account's invoices; nothing was saved. Retry after `Retry-After` seconds", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"contended": {"summary": "Contended", "value": {"success": false, "error": "Too many simultaneous changes to this account's invoices; nothing was saved. Try again.", "code": "upstream_unavailable"}}}}}, "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}, "example": 2}}}}}}, "/linked-emails": {"get": {"tags": ["Linked addresses"], "operationId": "list_linked_emails", "summary": "List linked addresses", "description": "Returns the confirmed addresses, oldest first, without the account's login email. An address waiting for its code is not listed. The list is never paged: at most 10 addresses.", "responses": {"200": {"description": "The linked addresses", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"type": "object", "properties": {"items": {"type": "array", "items": {"$ref": "#/components/schemas/LinkedEmail"}}, "count": {"type": "integer", "minimum": 0, "description": "Number of `items` in this response."}, "nextCursor": {"type": ["string", "null"], "description": "Pass it as `cursor` to get the items after these; null when there are no more. It may lead to an empty page."}, "truncated": {"type": "boolean", "description": "true when the list stopped at the 5000 documents one call reads, so items may be missing: continue with `nextCursor`, or narrow the filters."}}, "required": ["items", "count", "nextCursor", "truncated"]}}, "required": ["data"]}]}, "examples": {"one": {"summary": "One linked address", "value": {"success": true, "data": {"items": [{"email": "anna@muster-treuhand.ch", "createdAt": "2026-11-19T12:10:17+00:00"}], "count": 1, "nextCursor": null, "truncated": false}}}, "none": {"summary": "None yet", "value": {"success": true, "data": {"items": [], "count": 0, "nextCursor": null, "truncated": false}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "post": {"tags": ["Linked addresses"], "operationId": "send_linked_email_code", "summary": "Email a code to an address", "description": "Emails the address a code, valid for 24 hours. Nothing is linked until `POST /linked-emails/verify` gets that code. Call it again to resend: only the newest code works. At most 3 codes per minute go to one address.\n\nThe address is trimmed and lowercased: show and reuse the `email` of the answer. An address waiting for its code is not stored as pending, so the app keeps it until it is verified.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/LinkEmailRequest"}, "examples": {"address": {"summary": "Link an address", "value": {"email": "anna@muster-treuhand.ch"}}, "french": {"summary": "With the email in French", "value": {"email": "anna@muster-treuhand.ch", "locale": "fr"}}}}}}, "responses": {"200": {"description": "The code was emailed", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"type": "object", "properties": {"email": {"type": "string", "format": "email", "description": "The address, lowercase."}, "codeSent": {"type": "boolean"}}, "required": ["email", "codeSent"]}}, "required": ["data"]}]}, "examples": {"sent": {"summary": "Sent", "value": {"success": true, "data": {"email": "anna@muster-treuhand.ch", "codeSent": true}}}}}}}, "400": {"description": "Invalid address, or the email could not be sent", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"invalid": {"summary": "Not an email address", "value": {"success": false, "error": "Invalid request. email: must be an email address like name@example.ch", "code": "validation_failed", "details": {"code": "validation_failed", "errors": [{"code": "invalid_format", "field": "email", "message": "must be an email address like name@example.ch"}]}}}, "notSent": {"summary": "The address refused the email", "value": {"success": false, "error": "This address could not be emailed. Please check it.", "code": "email_not_sent"}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "403": {"description": "The account has no login email yet", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"guest": {"summary": "Guest account", "value": {"success": false, "error": "Sign in with your email address before linking another one.", "code": "account_required"}}}}}}, "409": {"description": "The address cannot be linked", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"accountEmail": {"summary": "The account's own email", "value": {"success": false, "error": "This is your account's email address: receipts from it are already imported.", "code": "account_email"}}, "alreadyLinked": {"summary": "Already linked", "value": {"success": false, "error": "This address is already linked.", "code": "already_linked"}}, "limitReached": {"summary": "Ten addresses linked", "value": {"success": false, "error": "At most 10 addresses can be linked. Remove one first.", "code": "limit_reached"}}}}}}, "429": {"description": "Too many requests: at most 3 codes per minute to one address, 10 per hour on this endpoint, and 300 requests per minute per account over the whole API", "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}, "example": 23}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"endpointLimit": {"summary": "Endpoint limit reached", "value": {"success": false, "error": "Too many requests: at most 10 requests per hour on this endpoint. Retry in 12 seconds.", "code": "rate_limited", "details": {"limit": "10/hour", "scope": "endpoint", "retryAfter": 12}}}, "accountLimit": {"summary": "Account limit reached", "value": {"success": false, "error": "Too many requests: at most 300 requests per minute per account. Retry in 23 seconds.", "code": "rate_limited", "details": {"limit": "300/minute", "scope": "account", "retryAfter": 23}}}, "addressLimit": {"summary": "Three codes sent to this address", "value": {"success": false, "error": "Too many codes sent to this address. Please try again in a minute.", "code": "rate_limited", "details": {"retryAfter": 60}}}}}}}}}}, "/linked-emails/verify": {"post": {"tags": ["Linked addresses"], "operationId": "verify_linked_email", "summary": "Link an address with its code", "description": "Links the address when `code` is the newest one emailed to it for this account. The code proves the inbox is yours, so an address linked to another account moves to this one. A login email wins over a link: the address of another Magic Heidi account cannot be linked, which only this call reports (`account_exists`).\n\nA wrong code (`invalid_code`) leaves the emailed code valid, so the user can try again, up to 20 times per hour. The 403 and the other 409 answers come before the code is checked.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/VerifyLinkedEmailRequest"}, "examples": {"code": {"summary": "Enter the code", "value": {"email": "anna@muster-treuhand.ch", "code": "2LLXM"}}}}}}, "responses": {"201": {"description": "The address is linked", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/LinkedEmail"}}, "required": ["data"]}]}, "examples": {"linked": {"summary": "Linked", "value": {"success": true, "data": {"email": "anna@muster-treuhand.ch", "createdAt": "2026-11-19T12:10:17+00:00"}}}}}}}, "400": {"description": "Wrong or expired code, or an invalid body", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"invalidCode": {"summary": "Wrong or expired code", "value": {"success": false, "error": "This code is wrong or has expired.", "code": "invalid_code"}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "403": {"description": "The account has no login email yet", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"guest": {"summary": "Guest account", "value": {"success": false, "error": "Sign in with your email address before linking another one.", "code": "account_required"}}}}}}, "409": {"description": "The address cannot be linked", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"accountExists": {"summary": "Login of another account", "value": {"success": false, "error": "This address is the login of another Magic Heidi account, which already imports the receipts sent from it.", "code": "account_exists"}}, "accountEmail": {"summary": "The account's own email", "value": {"success": false, "error": "This is your account's email address: receipts from it are already imported.", "code": "account_email"}}, "alreadyLinked": {"summary": "Already linked", "value": {"success": false, "error": "This address is already linked.", "code": "already_linked"}}, "limitReached": {"summary": "Ten addresses linked", "value": {"success": false, "error": "At most 10 addresses can be linked. Remove one first.", "code": "limit_reached"}}}}}}, "429": {"description": "Too many requests: at most 20 per hour on this endpoint, and 300 per minute per account over the whole API", "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}, "example": 23}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"endpointLimit": {"summary": "Endpoint limit reached", "value": {"success": false, "error": "Too many requests: at most 20 requests per hour on this endpoint. Retry in 12 seconds.", "code": "rate_limited", "details": {"limit": "20/hour", "scope": "endpoint", "retryAfter": 12}}}, "accountLimit": {"summary": "Account limit reached", "value": {"success": false, "error": "Too many requests: at most 300 requests per minute per account. Retry in 23 seconds.", "code": "rate_limited", "details": {"limit": "300/minute", "scope": "account", "retryAfter": 23}}}}}}}}}}, "/linked-emails/{email}": {"delete": {"tags": ["Linked addresses"], "operationId": "delete_linked_email", "summary": "Remove a linked address", "description": "Removes the address: receipts sent from it are no longer imported. For an address still waiting for its code, the answer is 404 and that code stops working: use it to cancel a pending address.", "parameters": [{"name": "email", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The linked address, URL-encoded like any path value.", "example": "anna@muster-treuhand.ch"}], "responses": {"200": {"description": "The address was removed", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"type": "object", "properties": {"deleted": {"type": "boolean"}, "email": {"type": "string", "format": "email", "description": "The address, lowercase."}}, "required": ["deleted", "email"]}}, "required": ["data"]}]}, "examples": {"removed": {"summary": "Removed", "value": {"success": true, "data": {"deleted": true, "email": "anna@muster-treuhand.ch"}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"description": "The account has no such linked address", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"notFound": {"summary": "Not linked", "value": {"success": false, "error": "Linked address not found", "code": "not_found"}}}}}}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/companies/autocomplete": {"get": {"tags": ["Company register"], "operationId": "search_companies", "summary": "Search Swiss companies", "description": "Type-ahead search in the Swiss commercial register, to fill in a client's name and address. Matching ignores accents and works on word beginnings: `bellev rest` finds `Restaurant Bellevue`.\n\nBusinesses outside the commercial register are searched too, with `source` `uid`: a copy of the sole proprietors in the federal UID register, and the businesses earlier lookups in that register found. A query of 4 characters or more that matches nothing looks it up there, a few times an hour, so a repeated query can return more. Up to 2 looked-up businesses always get a place: when the other matches leave fewer free, the last ones give way.\n\nThe VAT status is known for few companies. To check, pass a company's `companyUid` to `GET /companies/vat-number`.", "parameters": [{"name": "q", "in": "query", "required": false, "schema": {"type": "string"}, "description": "Company name or part of it, 2 characters or more to find any. `query` works too.", "example": "viandar"}, {"name": "limit", "in": "query", "required": false, "schema": {"type": "integer", "default": 10, "minimum": 1, "maximum": 20}, "description": "Most companies to return, 1-20 (default 10). A value out of range is clamped; a non-number means 10."}], "responses": {"200": {"description": "The matching companies", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/CompanySearchResult"}}, "required": ["data"]}]}, "examples": {"results": {"summary": "One company", "value": {"success": true, "data": {"items": [{"id": "1755463", "name": "Viandar GmbH", "name_lines": ["Viandar GmbH"], "street": "Dorfstrasse", "buildingNumber": "12", "zip": "3920", "city": "Zermatt", "uid": "", "companyUid": "CHE-241.529.293", "legalForm": "GmbH / Sàrl", "legalFormCode": "0107", "source": "zefix"}], "count": 1, "query": "viandar"}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}, "502": {"description": "The search failed", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"failed": {"summary": "Failed", "value": {"success": false, "error": "Company search failed", "code": "upstream_unavailable"}}}}}}, "503": {"description": "The search is temporarily unavailable", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"unavailable": {"summary": "Unavailable", "value": {"success": false, "error": "Company search is temporarily unavailable.", "code": "upstream_unavailable"}}}}}}}}}, "/companies/vat-number": {"get": {"tags": ["Company register"], "operationId": "get_vat_number", "summary": "Look up a company's VAT number", "description": "Checks the federal UID register and returns the company's Swiss VAT number, if it has one. Fill in a VAT number only when `vatRegistered` is true.", "parameters": [{"name": "uid", "in": "query", "required": true, "schema": {"type": "string"}, "description": "Swiss company number (UID), e.g. `CHE-242.294.601`; separators optional.", "example": "CHE-242.294.601"}], "responses": {"200": {"description": "The VAT registration", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/VatNumberResult"}}, "required": ["data"]}]}, "examples": {"registered": {"summary": "Registered for VAT", "value": {"success": true, "data": {"uid": "CHE-242.294.601", "vatRegistered": true, "vatNumber": "CHE-242.294.601 MWST"}}}, "notRegistered": {"summary": "Not registered for VAT", "value": {"success": true, "data": {"uid": "CHE-116.229.879", "vatRegistered": false, "vatNumber": null}}}}}}}, "400": {"description": "`uid` is not a Swiss UID", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"invalid": {"summary": "Not a UID", "value": {"success": false, "error": "`uid` must be a Swiss UID like CHE-123.456.789", "code": "invalid_request"}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}, "503": {"description": "The UID register is temporarily unavailable", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"unavailable": {"summary": "Unavailable", "value": {"success": false, "error": "VAT register check is temporarily unavailable.", "code": "upstream_unavailable"}}}}}}}}}, "/invoicing-settings": {"get": {"tags": ["Invoicing settings"], "operationId": "get_invoicing_settings", "summary": "Get invoicing settings", "description": "Returns your company profile as printed on invoices (`company`), your invoice defaults (`settings`), the account language (`locale`) and the account `email`.", "responses": {"200": {"description": "The invoicing settings", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/InvoicingSettings"}}, "required": ["data"]}]}, "examples": {"settings": {"summary": "Invoicing settings", "value": {"success": true, "data": {"email": "anna@muster-consulting.ch", "locale": "de", "company": {"name": "Muster Consulting GmbH", "vatEnabled": true, "vatMode": "additive", "vatTaxMethod": "effective", "banks": [{"id": "bank_chf", "type": "iban", "name": "PostFinance", "currency": "CHF", "iban": "CH0700700112900411647"}]}, "bankData": {"name": "Muster Consulting GmbH", "iban": "CH0700700112900411647", "vatEnabled": true, "vatMode": "additive", "vatTaxMethod": "effective"}, "settings": {"invoiceDefaultDescription": "Vielen Dank für Ihren Auftrag.", "invoicePaymentDueInDays": 30, "lastUsedVatRate": 8.1}}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}}}, "patch": {"tags": ["Invoicing settings"], "operationId": "update_invoicing_settings", "summary": "Update invoicing settings", "description": "Changes the fields you send and keeps the others; nested objects are merged. Send at least one of `company`, `settings` and `locale`. The account `email` cannot be changed here.\n\nTo manage bank accounts one by one, use `/bank-accounts`.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/InvoicingSettingsPatch"}, "examples": {"company": {"summary": "Company address and VAT", "value": {"company": {"name": "Muster Consulting GmbH", "street": "Bahnhofstrasse", "buildingNumber": "12", "zip": "8001", "city": "Zürich", "country": "CH", "vatEnabled": true, "vatNumber": "CHE-123.456.789 MWST", "vatMode": "additive", "vatTaxMethod": "effective"}, "settings": {"invoiceDefaultDescription": "Vielen Dank für Ihren Auftrag.", "invoicePaymentDueInDays": 30, "invoicePaymentReference": "Kundennummer", "lastUsedVatRate": 8.1, "allowCustomVatRate": true}}}, "flatTax": {"summary": "VAT with the net tax rate method", "value": {"company": {"vatEnabled": true, "vatMode": "additive", "vatTaxMethod": "flat", "vatNumber": "CHE-123.456.789 MWST"}, "settings": {"flatVatTaxRate": 6.1, "invoiceDefaultDescription": "Merci pour votre confiance."}}}, "quoteDefaults": {"summary": "Quote defaults and language", "value": {"locale": "en", "settings": {"invoiceDefaultQuoteDescription": "This quote is valid for 30 days.", "invoiceShowQuoteSignatureFields": true, "lastUsedInvoiceType": "quote"}}}, "paymentTerms": {"summary": "Payment terms and reply-to address", "value": {"settings": {"invoicePaymentDueInDays": 14, "invoiceReplyToEmail": "billing@muster-consulting.ch", "invoicePaymentReference": "PO / customer ref"}}}}}}}, "responses": {"200": {"description": "The updated invoicing settings", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/InvoicingSettings"}}, "required": ["data"]}]}, "examples": {"updated": {"summary": "Updated", "value": {"success": true, "data": {"locale": "de", "company": {"name": "Muster Consulting GmbH", "vatEnabled": true, "vatMode": "additive", "vatTaxMethod": "effective", "banks": [{"id": "bank_chf", "type": "iban", "name": "PostFinance", "currency": "CHF", "iban": "CH0700700112900411647"}]}, "bankData": {"name": "Muster Consulting GmbH", "iban": "CH0700700112900411647", "vatEnabled": true, "vatMode": "additive", "vatTaxMethod": "effective"}, "settings": {"invoiceDefaultDescription": "Vielen Dank für Ihren Auftrag.", "invoicePaymentDueInDays": 30, "lastUsedVatRate": 8.1}}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/subscription": {"get": {"tags": ["Account"], "operationId": "get_subscription", "summary": "Get the subscription", "description": "Returns whether the account has Magic Heidi Pro, where it was bought (`platform`), the product and its dates. `expiresDate` is null for a lifetime subscription.", "responses": {"200": {"description": "The subscription", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/Subscription"}}, "required": ["data"]}]}, "examples": {"lifetime": {"summary": "Lifetime, bought on the web", "value": {"success": true, "data": {"subscribed": true, "platform": "web", "productIdentifier": "rc_promo_pro_lifetime", "purchaseDate": "2025-06-15T12:30:00+02:00", "expiresDate": null, "entitlement": "pro", "email": "anna@muster-consulting.ch"}}}, "ios": {"summary": "Yearly, bought on iOS", "value": {"success": true, "data": {"subscribed": true, "platform": "ios", "productIdentifier": "mh_pro_yearly", "purchaseDate": "2025-09-01T14:00:00+02:00", "expiresDate": "2026-09-01T14:00:00+02:00", "entitlement": "pro", "email": "anna@muster-consulting.ch"}}}, "expired": {"summary": "Expired, bought on Android", "value": {"success": true, "data": {"subscribed": false, "platform": "android", "productIdentifier": "mh_pro_monthly", "purchaseDate": "2025-11-01T09:00:00+01:00", "expiresDate": "2025-12-01T09:00:00+01:00", "entitlement": "pro", "email": "anna@muster-consulting.ch"}}}, "never": {"summary": "Never subscribed", "value": {"success": true, "data": {"subscribed": false, "platform": null, "productIdentifier": null, "purchaseDate": null, "expiresDate": null, "entitlement": null, "email": "anna@muster-consulting.ch"}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}, "502": {"description": "The subscription could not be read", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"unavailable": {"summary": "Unavailable", "value": {"success": false, "error": "Could not retrieve subscription information", "code": "upstream_unavailable"}}}}}}}}}, "/exports": {"post": {"tags": ["Account"], "operationId": "create_export", "summary": "Export all account data", "description": "Starts a zip of the whole account: every invoice and quote PDF, receipt, client file, payment proof and the logo, sorted into folders by year; an overview workbook (`.xlsx`) with one sheet per entity; a README; and the complete data as JSON under `_data/`. Folder names, sheets and the README follow the account language (de, fr, it, else en).\n\nReturns 202 with the export to poll with `GET /exports/{exportId}`; it is usually ready within minutes, and the account owner also gets an email with the link unless `notify` is false. While an export is running, or one finished in the last 10 minutes with the same `includeFiles`, that one is returned instead of starting another. The download link works for 7 days.", "requestBody": {"required": false, "content": {"application/json": {"schema": {"type": "object", "properties": {"includeFiles": {"type": "boolean", "default": true, "description": "false: only the overview workbook, README and JSON, no documents."}, "notify": {"type": "boolean", "default": true, "description": "Email the download link to the account owner when ready."}}}, "examples": {"everything": {"summary": "Everything, with files", "value": {}}, "dataOnly": {"summary": "Tables and JSON only, no email", "value": {"includeFiles": false, "notify": false}}}}}}, "responses": {"200": {"description": "A ready export from the last 10 minutes", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/Export"}}, "required": ["data"]}]}, "examples": {"recent": {"summary": "A ready export from the last 10 minutes", "value": {"success": true, "data": {"id": "Xk2pQ9rT4vW8yZ1a", "status": "ready", "includeFiles": true, "createdAt": "2026-10-13T10:00:00+02:00", "finishedAt": "2026-10-13T10:03:12+02:00", "expiresAt": "2026-10-20T10:03:12+02:00", "downloadUrl": "https://storage.googleapis.com/magic-heidi.appspot.com/exports/uid/Xk2pQ9rT4vW8yZ1a.zip?X-Goog-Signature=...", "sizeBytes": 23264226, "counts": {"invoices": 374, "quotes": 1, "clients": 15, "expenses": 6, "products": 27, "categories": 9, "letters": 0, "bankConnections": 0, "files": 216, "missingFiles": 1}, "missingFiles": ["Ausgaben/2026/2026-03-14 – Train – 42.50 CHF.pdf: Datei nicht gefunden"], "missingCount": 1, "error": null}}}}}}}, "202": {"description": "Export started or already running", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/Export"}}, "required": ["data"]}]}, "examples": {"started": {"summary": "Export started", "value": {"success": true, "data": {"id": "Xk2pQ9rT4vW8yZ1a", "status": "pending", "includeFiles": true, "createdAt": "2026-10-13T10:00:00+02:00", "finishedAt": null, "expiresAt": null, "downloadUrl": null, "sizeBytes": null, "counts": null, "missingFiles": [], "missingCount": 0, "error": null}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"description": "Too many requests: at most 3 per minute on this endpoint, and 300 per minute per account over the whole API", "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}, "example": 23}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"endpointLimit": {"summary": "Endpoint limit reached", "value": {"success": false, "error": "Too many requests: at most 3 requests per minute on this endpoint. Retry in 12 seconds.", "code": "rate_limited", "details": {"limit": "3/minute", "scope": "endpoint", "retryAfter": 12}}}, "accountLimit": {"summary": "Account limit reached", "value": {"success": false, "error": "Too many requests: at most 300 requests per minute per account. Retry in 23 seconds.", "code": "rate_limited", "details": {"limit": "300/minute", "scope": "account", "retryAfter": 23}}}}}}}, "502": {"description": "The export could not be started; it is marked failed. Try again.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}, "503": {"description": "A service behind the API is temporarily unavailable; retry later", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"unavailable": {"summary": "Temporarily unavailable", "value": {"success": false, "error": "This action is temporarily unavailable.", "code": "upstream_unavailable"}}}}}}}}, "get": {"tags": ["Account"], "operationId": "list_exports", "summary": "List exports", "description": "The 20 most recent exports, newest first. The list is never paged.", "responses": {"200": {"description": "The exports", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"type": "object", "properties": {"items": {"type": "array", "items": {"$ref": "#/components/schemas/Export"}}, "count": {"type": "integer", "minimum": 0, "description": "Number of `items` in this response."}, "nextCursor": {"type": ["string", "null"], "description": "Pass it as `cursor` to get the items after these; null when there are no more. It may lead to an empty page."}, "truncated": {"type": "boolean", "description": "true when the list stopped at the 5000 documents one call reads, so items may be missing: continue with `nextCursor`, or narrow the filters."}}, "required": ["items", "count", "nextCursor", "truncated"]}}, "required": ["data"]}]}, "examples": {"exports": {"summary": "Recent exports", "value": {"success": true, "data": {"items": [{"id": "Xk2pQ9rT4vW8yZ1a", "status": "ready", "includeFiles": true, "createdAt": "2026-10-13T10:00:00+02:00", "finishedAt": "2026-10-13T10:03:12+02:00", "expiresAt": "2026-10-20T10:03:12+02:00", "downloadUrl": "https://storage.googleapis.com/magic-heidi.appspot.com/exports/uid/Xk2pQ9rT4vW8yZ1a.zip?X-Goog-Signature=...", "sizeBytes": 23264226, "counts": {"invoices": 374, "quotes": 1, "clients": 15, "expenses": 6, "products": 27, "categories": 9, "letters": 0, "bankConnections": 0, "files": 216, "missingFiles": 1}, "missingFiles": ["Ausgaben/2026/2026-03-14 – Train – 42.50 CHF.pdf: Datei nicht gefunden"], "missingCount": 1, "error": null}], "count": 1, "nextCursor": null, "truncated": false}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/exports/{exportId}": {"get": {"tags": ["Account"], "operationId": "get_export", "summary": "Get an export", "description": "The export's status: `pending` or `running` while it builds, `ready` with a `downloadUrl`, `failed` with an `error`, or `expired` after 7 days (start a new one). `missingFiles` lists documents that could not be included, also listed in the zip's README.", "parameters": [{"name": "exportId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The export's `id` (from `POST /exports` or `GET /exports`).", "example": "Xk2pQ9rT4vW8yZ1a"}], "responses": {"200": {"description": "The export", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/Export"}}, "required": ["data"]}]}, "examples": {"ready": {"summary": "Ready to download", "value": {"success": true, "data": {"id": "Xk2pQ9rT4vW8yZ1a", "status": "ready", "includeFiles": true, "createdAt": "2026-10-13T10:00:00+02:00", "finishedAt": "2026-10-13T10:03:12+02:00", "expiresAt": "2026-10-20T10:03:12+02:00", "downloadUrl": "https://storage.googleapis.com/magic-heidi.appspot.com/exports/uid/Xk2pQ9rT4vW8yZ1a.zip?X-Goog-Signature=...", "sizeBytes": 23264226, "counts": {"invoices": 374, "quotes": 1, "clients": 15, "expenses": 6, "products": 27, "categories": 9, "letters": 0, "bankConnections": 0, "files": 216, "missingFiles": 1}, "missingFiles": ["Ausgaben/2026/2026-03-14 – Train – 42.50 CHF.pdf: Datei nicht gefunden"], "missingCount": 1, "error": null}}}, "running": {"summary": "Still building", "value": {"success": true, "data": {"id": "Xk2pQ9rT4vW8yZ1a", "status": "running", "includeFiles": true, "createdAt": "2026-10-13T10:00:00+02:00", "finishedAt": null, "expiresAt": null, "downloadUrl": null, "sizeBytes": null, "counts": null, "missingFiles": [], "missingCount": 0, "error": null}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "404": {"$ref": "#/components/responses/NotFound"}, "429": {"$ref": "#/components/responses/RateLimited"}}}}, "/backups": {"post": {"tags": ["Account"], "operationId": "export_backup", "summary": "Email a yearly backup", "description": "Builds a ZIP of the year's invoices, expenses and receipts and emails a download link, valid for 3 days. The link only travels by email, to `email` or by default the account email; the answer says where it will go.", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "properties": {"year": {"type": "integer", "minimum": 2000, "description": "Calendar year to export."}, "email": {"type": ["string", "null"], "format": "email", "description": "Where to send the download link. Defaults to the account email."}}, "required": ["year"]}, "examples": {"year": {"summary": "One year, to the account email", "value": {"year": 2025}}, "email": {"summary": "To another address", "value": {"year": 2025, "email": "treuhand@example.ch"}}}}}}, "responses": {"202": {"description": "The backup was started; the download link is emailed", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/BackupResult"}}, "required": ["data"]}]}, "examples": {"started": {"summary": "Started", "value": {"success": true, "data": {"email": "anna@muster-consulting.ch", "year": 2025}}}}}}}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"description": "Too many backups: at most 3 per minute, and 300 requests per minute per account", "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}, "example": 23}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"accountLimit": {"summary": "Account limit reached", "value": {"success": false, "error": "Too many requests: at most 300 requests per minute per account. Retry in 23 seconds.", "code": "rate_limited", "details": {"limit": "300/minute", "scope": "account", "retryAfter": 23}}}}}}}, "502": {"description": "The backup service failed; retry", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}}}}, "503": {"description": "A service behind the API is temporarily unavailable; retry later", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"unavailable": {"summary": "Temporarily unavailable", "value": {"success": false, "error": "This action is temporarily unavailable.", "code": "upstream_unavailable"}}}}}}}}}, "/signout": {"post": {"tags": ["Account"], "operationId": "sign_out_everywhere", "summary": "Sign out everywhere and replace the API key", "description": "Signs out every device and replaces the API key. The key used for this call stops working at once, so every integration that holds it needs the new key from the app. Use it when the key may have leaked.", "responses": {"200": {"description": "Everyone was signed out", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"type": "object", "properties": {"message": {"type": "string"}}, "required": ["message"]}}, "required": ["data"]}]}, "examples": {"signedOut": {"summary": "Signed out", "value": {"success": true, "data": {"message": "Signed out all users"}}}}}}}, "401": {"$ref": "#/components/responses/Unauthorized"}, "429": {"$ref": "#/components/responses/RateLimited"}, "502": {"description": "Signing out failed; the old key still works, so retry", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"failed": {"summary": "Failed", "value": {"success": false, "error": "Could not sign out users", "code": "upstream_unavailable"}}}}}}}}}, "/archive/documents": {"get": {"tags": ["Archive"], "operationId": "list_archive_documents", "summary": "List the stored documents of a period", "description": "Returns the files to archive for the days `from` to `to` (both included, Swiss time): the PDF of every invoice that was sent or paid, its payment proof if one was uploaded, and every expense receipt. Drafts, quotes and archived invoices are left out.\n\n- Files are the stored ones; nothing is rendered here. A document without a stored file has `file: null` and `missing: notFound`.\n- `md5` and `generation` let you recognise a file you already fetched without downloading it again.\n- Download links work for 15 minutes. Call again for new ones.\n- At most 100 entries come per page. Follow `nextCursor` until it is null.\n\nThis is the only endpoint that also accepts an OAuth access token with the scope `archive:read` from `https://mcp.magicheidi.ch`, sent as `Authorization: Bearer`. Such a token gets 403 everywhere else.", "parameters": [{"name": "from", "in": "query", "required": true, "schema": {"type": "string", "format": "date", "description": "Calendar day, YYYY-MM-DD."}, "description": "First day, YYYY-MM-DD.", "example": "2025-01-01"}, {"name": "to", "in": "query", "required": true, "schema": {"type": "string", "format": "date", "description": "Calendar day, YYYY-MM-DD."}, "description": "Last day, YYYY-MM-DD; at most 400 days after `from`.", "example": "2025-12-31"}, {"name": "cursor", "in": "query", "required": false, "schema": {"type": "string"}, "description": "`nextCursor` of the previous page, unchanged.", "example": "i.WyJ0IiwiMjAyNS0wMy0wMVQwMDowMDowMCswMTowMCIsImludl8xMjQiXQ"}], "responses": {"200": {"description": "The documents of the period", "content": {"application/json": {"schema": {"allOf": [{"$ref": "#/components/schemas/SuccessEnvelope"}, {"type": "object", "properties": {"data": {"$ref": "#/components/schemas/ArchiveDocumentPage"}}, "required": ["data"]}]}, "examples": {"several": {"summary": "An invoice with its payment proof, and a receipt", "value": {"success": true, "data": {"items": [{"sourceId": "invoice:inv_123", "kind": "invoice", "number": "14", "counterparty": "Muster AG", "description": null, "date": "2025-03-01", "amount": "1250.00", "currency": "CHF", "status": "paid", "file": {"name": "14 Muster AG.pdf", "contentType": "application/pdf", "size": 48211, "md5": "1B2M2Y8AsgTpgAmY7PhCfg==", "generation": "1712345678901234", "url": "https://storage.googleapis.com/magic-heidi.appspot.com/users/uid/invoices/inv_123.pdf?X-Goog-Signature=abc"}}, {"sourceId": "invoice:inv_123:proof", "kind": "payment_proof", "number": "14", "counterparty": "Muster AG", "description": null, "date": "2025-03-01", "amount": "1250.00", "currency": "CHF", "status": "paid", "file": {"name": "Zahlung.jpg", "contentType": "image/jpeg", "size": 90211, "md5": "rL0Y20zC+Fzt72VPzMSk2A==", "generation": "1712345678904321", "url": "https://storage.googleapis.com/magic-heidi.appspot.com/users/uid/invoices/inv_123.payment_proof.jpg?X-Goog-Signature=abc"}}, {"sourceId": "expense:exp_123:3f9c", "kind": "expense", "number": null, "counterparty": null, "description": "SBB ticket client meeting", "date": "2025-02-20", "amount": "82.40", "currency": "CHF", "status": "paid", "file": {"name": "sbb.pdf", "contentType": "application/pdf", "size": 30122, "md5": "CY9rzUYh03PK3k6DJie09g==", "generation": "1712345678905555", "url": "https://storage.googleapis.com/magic-heidi.appspot.com/users/uid/expenses/3f9c.pdf?X-Goog-Signature=abc"}}], "nextCursor": null}}}, "missing": {"summary": "An invoice whose PDF was never stored, with more to come", "value": {"success": true, "data": {"items": [{"sourceId": "invoice:inv_124", "kind": "invoice", "number": "15", "counterparty": "Muster AG", "description": null, "date": "2025-03-01", "amount": "1250.00", "currency": "CHF", "status": "sent", "file": null, "missing": "notFound"}], "nextCursor": "i.WyJ0IiwiMjAyNS0wMy0wMVQwMDowMDowMCswMTowMCIsImludl8xMjQiXQ"}}}, "empty": {"summary": "Nothing in the period", "value": {"success": true, "data": {"items": [], "nextCursor": null}}}}}}}, "400": {"$ref": "#/components/responses/InvalidQuery"}, "401": {"$ref": "#/components/responses/Unauthorized"}, "403": {"description": "The access token may not call this endpoint", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"forbidden": {"summary": "An OAuth access token without `archive:read`", "value": {"success": false, "error": "This access token is not allowed to call this endpoint", "code": "forbidden"}}}}}}, "429": {"description": "Too many requests: at most 60 per minute on this endpoint, and 300 per minute per account over the whole API", "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}, "example": 23}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"endpointLimit": {"summary": "Endpoint limit reached", "value": {"success": false, "error": "Too many requests: at most 60 requests per minute on this endpoint. Retry in 12 seconds.", "code": "rate_limited", "details": {"limit": "60/minute", "scope": "endpoint", "retryAfter": 12}}}, "accountLimit": {"summary": "Account limit reached", "value": {"success": false, "error": "Too many requests: at most 300 requests per minute per account. Retry in 23 seconds.", "code": "rate_limited", "details": {"limit": "300/minute", "scope": "account", "retryAfter": 23}}}}}}}, "502": {"description": "The file storage did not answer; retry", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"storage": {"summary": "Storage unavailable", "value": {"success": false, "error": "The file storage did not answer; try again", "code": "upstream_unavailable"}}}}}}}}}, "/ai-invoice": {"get": {"tags": ["AI Invoice API"], "operationId": "ai_invoice_link", "summary": "Guide, or an invoice PDF from a link", "description": "Without `data` or `d`: the guide for AI models, as Markdown.\n\nWith `data` (the request JSON, URL-encoded) or `d` (the request JSON, base64url, padding optional): the invoice PDF, rendered on the spot and shown inline (`invoice-<number>.pdf`); with `check=1` the check (`AiInvoiceCheck`) instead. Nothing is stored. The link must carry `invoice.date`. Errors are indented JSON, readable in a browser. Links over 4000 characters get 414 `uri_too_long`: use POST.", "security": [], "parameters": [{"name": "data", "in": "query", "required": false, "schema": {"type": "string"}, "description": "The request (see `AiInvoiceRequest`) as URL-encoded JSON.", "example": "{\"creditor\":{\"name\":\"Muster GmbH\",\"street\":\"Bahnhofstrasse 1\",\"postal_code\":\"8001\",\"city\":\"Zürich\",\"iban\":\"CH9300762011623852957\"},\"invoice\":{\"number\":\"1\",\"date\":\"2026-11-30\"},\"items\":[{\"description\":\"Beratung\",\"unit_price\":100}]}"}, {"name": "d", "in": "query", "required": false, "schema": {"type": "string"}, "description": "The request as base64url-encoded JSON, instead of `data`."}, {"name": "check", "in": "query", "required": false, "schema": {"type": "string", "enum": ["1", "true", "yes"]}, "description": "`1` (or `true`, `yes`): check and render like the real request, but answer `AiInvoiceCheck` JSON (totals, VAT, lines, pages, warnings, the GET link) instead of the PDF. Nothing is stored. Counts against the same rate limits.", "example": "1"}], "responses": {"200": {"description": "The guide (no `data` or `d`), the PDF, or with `check=1` the check; the PDF and the check carry the X-RateLimit headers", "headers": {"X-RateLimit-Limit": {"description": "Renders allowed per minute for this IP address.", "schema": {"type": "integer"}}, "X-RateLimit-Remaining": {"description": "Renders left in the current minute.", "schema": {"type": "integer"}}, "X-RateLimit-Reset": {"description": "Seconds until the minute resets.", "schema": {"type": "integer"}}, "X-AI-Invoice-Warning": {"description": "On a PDF: `example_iban` when it is made out to an example IBAN of the guide (the PDF is then a specimen and its QR code pays nothing).", "schema": {"type": "string", "enum": ["example_iban"]}}}, "content": {"text/markdown": {"schema": {"type": "string"}}, "application/pdf": {"schema": {"type": "string", "format": "binary"}}, "application/json": {"schema": {"type": "object", "properties": {"success": {"type": "boolean", "const": true}, "data": {"$ref": "#/components/schemas/AiInvoiceCheck"}}, "required": ["success", "data"]}, "examples": {"check": {"summary": "check=1", "value": {"success": true, "data": {"valid": true, "currency": "CHF", "total": "1297.20", "subtotal": "1200.00", "vat": [{"rate": "8.1", "base": "1200.00", "amount": "97.20"}], "lines": [{"index": 0, "amount": "1200.00", "vat_rate": "8.1"}], "pages": 1, "reference_type": "NON", "link": "https://api.magicheidi.ch/v1/ai-invoice?data=%7B%22creditor%22:...", "warnings": [{"code": "example_iban", "field": "creditor.iban", "message": "`creditor.iban` is one of the example IBANs in this guide (a regular IBAN). Never use it for a user's invoice: payments would go to a stranger. The PDF is marked as a specimen and its QR code pays nothing. Ask the user for their own IBAN."}]}}}}}}}, "400": {"description": "The invoice has problems; `error` lists each one with how to fix it, `details.errors` one per field", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceError"}, "examples": {"qrIban": {"summary": "QR-IBAN without a QR reference", "value": {"success": false, "error": "No invoice was made. Fix this problem and send the request again:\n1. `creditor.iban` is a QR-IBAN, so `reference` must be a 27-digit QR reference. Either add one or use the regular IBAN of the account.\nRead GET /v1/ai-invoice for the full guide.", "code": "validation_failed", "details": {"code": "validation_failed", "errors": [{"field": "reference", "code": "required", "message": "`creditor.iban` is a QR-IBAN, so `reference` must be a 27-digit QR reference. Either add one or use the regular IBAN of the account."}]}}}}}}}, "414": {"description": "The link is over 4000 characters; send the JSON with POST instead", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceError"}, "examples": {"tooLong": {"summary": "Too long", "value": {"success": false, "error": "This link is 5230 characters long; links over 4000 characters fail on the way to us. Send the same JSON with POST /v1/ai-invoice instead. Read GET /v1/ai-invoice for the full guide.", "code": "uri_too_long"}}}}}}, "422": {"description": "The body is too long (over 10 pages in total) or too slow, big or deep to render", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceError"}, "examples": {"tooManyPages": {"summary": "Too many pages", "value": {"success": false, "error": "The invoice body is 14 pages long; at most 10 pages are allowed in total, including an extra page for the payment part if one is needed. Shorten it: fewer or shorter items, smaller fonts or less spacing.", "code": "unprocessable", "details": {"reason": "too_many_pages"}}}}}}}, "429": {"description": "Too many requests from this IP address (at most 20 renders per minute and 300 per day (checks included)), or from all callers together", "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceError"}, "examples": {"limited": {"summary": "Limit reached", "value": {"success": false, "error": "Too many requests: at most 20 requests per minute on this endpoint. Retry in 12 seconds.", "code": "rate_limited", "details": {"limit": "20/minute", "scope": "endpoint", "retryAfter": 12}}}}}}}, "500": {"description": "Rendering failed on our side; try again", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceError"}, "examples": {"failed": {"summary": "Failed", "value": {"success": false, "error": "The invoice could not be rendered because of an error on our side. Try again.", "code": "internal_error", "details": {"reason": "render_failed"}}}}}}}, "503": {"description": "Busy rendering other invoices (after queuing up to 8 seconds); retry after `Retry-After` seconds", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceError"}, "examples": {"busy": {"summary": "Busy", "value": {"success": false, "error": "Too many invoices are being made right now. Try again in a few seconds.", "code": "upstream_unavailable", "details": {"reason": "busy"}}}}}}, "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}}}}}}, "post": {"tags": ["AI Invoice API"], "operationId": "ai_invoice_create", "summary": "Make an invoice PDF", "description": "Renders the invoice and stores the PDF for 24 hours: the answer is a link to it, which needs no login. With `Accept: application/pdf` (and not application/json) the answer is the PDF itself and nothing is stored. With `?check=1` the answer is the check (`AiInvoiceCheck`) and nothing is stored. At most 500 KB per request. Amounts use commercial rounding (half up).", "security": [], "parameters": [{"name": "check", "in": "query", "required": false, "schema": {"type": "string", "enum": ["1", "true", "yes"]}, "description": "`1` (or `true`, `yes`): check and render like the real request, but answer `AiInvoiceCheck` JSON (totals, VAT, lines, pages, warnings, the GET link) instead of the PDF. Nothing is stored. Counts against the same rate limits.", "example": "1"}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceRequest"}, "examples": {"example": {"summary": "Default template", "value": {"language": "de", "creditor": {"name": "Muster GmbH", "street": "Bahnhofstrasse", "building_number": "1", "postal_code": "8001", "city": "Zürich", "iban": "CH93 0076 2011 6238 5295 7"}, "debtor": {"name": "Beispiel AG", "street": "Seestrasse", "building_number": "5", "postal_code": "6003", "city": "Luzern"}, "invoice": {"number": "2026-001", "date": "2026-11-30", "due_date": "2026-12-30", "vat_number": "CHE-123.456.788 MWST"}, "items": [{"description": "Webdesign", "quantity": 10, "unit": "h", "unit_price": 120, "vat_rate": 8.1}]}}}}}}, "responses": {"200": {"description": "A link to the PDF, valid 24 hours; with `check=1` the check", "content": {"application/json": {"schema": {"type": "object", "properties": {"success": {"type": "boolean", "const": true}, "data": {"oneOf": [{"$ref": "#/components/schemas/AiInvoiceLink"}, {"$ref": "#/components/schemas/AiInvoiceCheck"}]}}, "required": ["success", "data"]}, "examples": {"link": {"summary": "Link", "value": {"success": true, "data": {"url": "https://api.magicheidi.ch/v1/ai-invoice/files/q3Vb9xK2mN7pR4sT8wY1zA5cE6fH0jL3.pdf", "expires_at": "2026-12-01T14:03:00+01:00", "pages": 1, "warnings": []}}}, "check": {"summary": "check=1", "value": {"success": true, "data": {"valid": true, "currency": "CHF", "total": "1297.20", "subtotal": "1200.00", "vat": [{"rate": "8.1", "base": "1200.00", "amount": "97.20"}], "lines": [{"index": 0, "amount": "1200.00", "vat_rate": "8.1"}], "pages": 1, "reference_type": "NON", "link": "https://api.magicheidi.ch/v1/ai-invoice?data=%7B%22creditor%22:...", "warnings": [{"code": "example_iban", "field": "creditor.iban", "message": "`creditor.iban` is one of the example IBANs in this guide (a regular IBAN). Never use it for a user's invoice: payments would go to a stranger. The PDF is marked as a specimen and its QR code pays nothing. Ask the user for their own IBAN."}]}}}}}}, "headers": {"X-RateLimit-Limit": {"description": "Renders allowed per minute for this IP address.", "schema": {"type": "integer"}}, "X-RateLimit-Remaining": {"description": "Renders left in the current minute.", "schema": {"type": "integer"}}, "X-RateLimit-Reset": {"description": "Seconds until the minute resets.", "schema": {"type": "integer"}}, "X-AI-Invoice-Warning": {"description": "On a PDF: `example_iban` when it is made out to an example IBAN of the guide (the PDF is then a specimen and its QR code pays nothing).", "schema": {"type": "string", "enum": ["example_iban"]}}}}, "400": {"description": "The invoice has problems; `error` lists each one with how to fix it, `details.errors` one per field", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceError"}, "examples": {"qrIban": {"summary": "QR-IBAN without a QR reference", "value": {"success": false, "error": "No invoice was made. Fix this problem and send the request again:\n1. `creditor.iban` is a QR-IBAN, so `reference` must be a 27-digit QR reference. Either add one or use the regular IBAN of the account.\nRead GET /v1/ai-invoice for the full guide.", "code": "validation_failed", "details": {"code": "validation_failed", "errors": [{"field": "reference", "code": "required", "message": "`creditor.iban` is a QR-IBAN, so `reference` must be a 27-digit QR reference. Either add one or use the regular IBAN of the account."}]}}}}}}}, "413": {"description": "The request is over 500 KB", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceError"}, "examples": {"tooLarge": {"summary": "Too large", "value": {"success": false, "error": "The request is 812 KB, larger than 500 KB. Make it smaller: a smaller logo or images, less HTML.", "code": "payload_too_large"}}}}}}, "422": {"description": "The body is too long (over 10 pages in total) or too slow, big or deep to render", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceError"}, "examples": {"tooManyPages": {"summary": "Too many pages", "value": {"success": false, "error": "The invoice body is 14 pages long; at most 10 pages are allowed in total, including an extra page for the payment part if one is needed. Shorten it: fewer or shorter items, smaller fonts or less spacing.", "code": "unprocessable", "details": {"reason": "too_many_pages"}}}}}}}, "429": {"description": "Too many requests from this IP address (at most 20 renders per minute and 300 per day (checks included)), or from all callers together", "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceError"}, "examples": {"limited": {"summary": "Limit reached", "value": {"success": false, "error": "Too many requests: at most 20 requests per minute on this endpoint. Retry in 12 seconds.", "code": "rate_limited", "details": {"limit": "20/minute", "scope": "endpoint", "retryAfter": 12}}}}}}}, "500": {"description": "Rendering failed on our side; try again", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceError"}, "examples": {"failed": {"summary": "Failed", "value": {"success": false, "error": "The invoice could not be rendered because of an error on our side. Try again.", "code": "internal_error", "details": {"reason": "render_failed"}}}}}}}, "503": {"description": "Busy rendering other invoices (after queuing up to 8 seconds); retry after `Retry-After` seconds", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceError"}, "examples": {"busy": {"summary": "Busy", "value": {"success": false, "error": "Too many invoices are being made right now. Try again in a few seconds.", "code": "upstream_unavailable", "details": {"reason": "busy"}}}}}}, "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}}}}}}}, "/ai-invoice/template": {"get": {"tags": ["AI Invoice API"], "operationId": "ai_invoice_template", "summary": "Get the default invoice body", "description": "The default template's HTML and CSS, filled with sample data, to copy, change and send back as `html` (or to see the class names `css` can restyle). The banner and the payment part are not part of it.", "security": [], "parameters": [{"name": "language", "in": "query", "required": false, "schema": {"type": "string", "enum": ["de", "fr", "it", "en"], "default": "de"}, "description": "Language of the labels.", "example": "de"}], "responses": {"200": {"description": "The invoice body as an HTML document", "content": {"text/html": {"schema": {"type": "string"}}}}, "429": {"description": "Too many requests from this IP address (at most 300 requests per minute), or from all callers together", "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceError"}, "examples": {"limited": {"summary": "Limit reached", "value": {"success": false, "error": "Too many requests: at most 20 requests per minute on this endpoint. Retry in 12 seconds.", "code": "rate_limited", "details": {"limit": "20/minute", "scope": "endpoint", "retryAfter": 12}}}}}}}}}}, "/ai-invoice/openapi.json": {"get": {"tags": ["AI Invoice API"], "operationId": "ai_invoice_openapi", "summary": "Get the AI Invoice API's own specification", "description": "An OpenAPI 3.1 document with only the AI Invoice API's operations, for tools and models.", "security": [], "responses": {"200": {"description": "The OpenAPI document (not wrapped in `success`/`data`)", "content": {"application/json": {"schema": {"type": "object"}}}}, "429": {"description": "Too many requests from this IP address (at most 300 requests per minute), or from all callers together", "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceError"}, "examples": {"limited": {"summary": "Limit reached", "value": {"success": false, "error": "Too many requests: at most 20 requests per minute on this endpoint. Retry in 12 seconds.", "code": "rate_limited", "details": {"limit": "20/minute", "scope": "endpoint", "retryAfter": 12}}}}}}}}}}, "/ai-invoice/files/{fileId}.pdf": {"get": {"tags": ["AI Invoice API"], "operationId": "ai_invoice_file", "summary": "Download a stored invoice PDF", "description": "The PDF behind a `url` from `POST /ai-invoice`, for 24 hours after it was made. After that, or for an unknown link: 404, as JSON, or as a short page in four languages for a browser (Accept text/html).", "security": [], "parameters": [{"name": "fileId", "in": "path", "required": true, "schema": {"type": "string"}, "description": "The id in the `url` that `POST /ai-invoice` returned.", "example": "q3Vb9xK2mN7pR4sT8wY1zA5cE6fH0jL3"}], "responses": {"200": {"description": "The PDF, shown inline", "content": {"application/pdf": {"schema": {"type": "string", "format": "binary"}}}}, "404": {"description": "No PDF at this link, or it expired after 24 hours", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceError"}, "examples": {"expired": {"summary": "Expired", "value": {"success": false, "error": "This invoice link expired at 2026-12-01T14:03:00+01:00 (links work for 24 hours). Make the invoice again.", "code": "not_found"}}}}, "text/html": {"schema": {"type": "string"}}}}, "429": {"description": "Too many requests from this IP address (at most 300 requests per minute), or from all callers together", "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AiInvoiceError"}, "examples": {"limited": {"summary": "Limit reached", "value": {"success": false, "error": "Too many requests: at most 20 requests per minute on this endpoint. Retry in 12 seconds.", "code": "rate_limited", "details": {"limit": "20/minute", "scope": "endpoint", "retryAfter": 12}}}}}}}}}}}, "components": {"securitySchemes": {"ApiKeyBearer": {"type": "http", "scheme": "bearer", "description": "Your API key as `Authorization: Bearer <API key>`."}, "ApiKeyHeader": {"type": "apiKey", "in": "header", "name": "X-API-Key", "description": "Your API key in the `X-API-Key` header."}, "FirebaseIdToken": {"type": "http", "scheme": "bearer", "bearerFormat": "JWT", "description": "Magic Heidi apps only: the signed-in user's ID token. Integrations use the API key."}}, "schemas": {"AiInvoiceCheck": {"type": "object", "properties": {"valid": {"type": "boolean", "const": true}, "currency": {"type": "string", "enum": ["CHF", "EUR"]}, "total": {"type": "string", "description": "The amount the payment part asks for, 2 decimals, e.g. `1297.20`."}, "subtotal": {"type": ["string", "null"], "description": "Without VAT; null with `html` and no `items`."}, "vat": {"type": "array", "description": "Per VAT rate in the items, 0 % included; empty when no item has a VAT rate or without `items`.", "items": {"type": "object", "properties": {"rate": {"type": "string", "description": "Percent, e.g. `8.1` or `0`."}, "base": {"type": "string", "description": "The lines of this rate without VAT."}, "amount": {"type": "string"}}, "required": ["rate", "base", "amount"]}}, "lines": {"type": "array", "description": "Each item's amount as printed (quantity x unit price, rounded half up to the cent).", "items": {"type": "object", "properties": {"index": {"type": "integer", "minimum": 0}, "amount": {"type": "string"}, "vat_rate": {"type": ["string", "null"], "description": "Null when no item has a VAT rate."}}, "required": ["index", "amount", "vat_rate"]}}, "pages": {"type": "integer", "minimum": 1, "description": "Pages of the PDF, payment part included."}, "reference_type": {"type": "string", "enum": ["QRR", "SCOR", "NON"]}, "link": {"type": ["string", "null"], "description": "The GET link that renders this invoice (its date pinned); null when it would be over 4000 characters."}, "warnings": {"type": "array", "description": "Accepted, but probably not what you want. More codes may be added.", "items": {"$ref": "#/components/schemas/AiInvoiceWarning"}}}, "required": ["valid", "currency", "total", "subtotal", "vat", "lines", "pages", "reference_type", "link", "warnings"], "description": "What `check=1` answers instead of the PDF. Amounts are strings with 2 decimals."}, "AiInvoiceError": {"type": "object", "properties": {"success": {"type": "boolean", "const": false}, "error": {"type": "string", "description": "Every problem with how to fix it, for the model and for people."}, "code": {"type": "string", "enum": ["invalid_request", "invalid_query", "validation_failed", "not_found", "method_not_allowed", "payload_too_large", "uri_too_long", "unprocessable", "rate_limited", "upstream_unavailable", "internal_error"]}, "details": {"type": "object", "properties": {"code": {"type": "string"}, "errors": {"type": "array", "description": "With `validation_failed`: one entry per field.", "items": {"type": "object", "properties": {"field": {"type": "string", "description": "JSON path, e.g. `items[0].vat_rate`."}, "code": {"type": "string", "enum": ["required", "invalid_type", "invalid_format", "invalid_enum", "too_long", "out_of_range", "unknown_field", "ambiguous_number"]}, "message": {"type": "string", "description": "What is wrong and what to send instead."}}, "required": ["field", "code", "message"]}}, "reason": {"type": "string", "description": "With 422, 500 and 503: `too_many_pages`, `render_timeout`, `render_limit`, `too_deep`, `render_failed`, `busy`."}, "limit": {"type": "string"}, "scope": {"type": "string"}, "retryAfter": {"type": "integer"}}}}, "required": ["success", "error", "code"], "description": "The error envelope of these routes."}, "AiInvoiceLink": {"type": "object", "properties": {"url": {"type": "string", "format": "uri", "description": "The PDF, for 24 hours. No login needed."}, "expires_at": {"type": "string", "format": "date-time", "description": "Swiss time with offset, whole seconds."}, "pages": {"type": "integer", "minimum": 1}, "warnings": {"type": "array", "description": "The same warnings as `check=1`.", "items": {"$ref": "#/components/schemas/AiInvoiceWarning"}}}, "required": ["url", "expires_at", "pages", "warnings"]}, "AiInvoiceRequest": {"type": "object", "properties": {"language": {"type": "string", "enum": ["de", "fr", "it", "en"], "default": "de"}, "currency": {"type": "string", "enum": ["CHF", "EUR"], "default": "CHF"}, "creditor": {"type": "object", "properties": {"name": {"type": "string", "maxLength": 70}, "street": {"type": "string", "maxLength": 70, "description": "A house number at its end is split off into `building_number`."}, "building_number": {"type": "string", "maxLength": 16}, "postal_code": {"type": "string", "maxLength": 16, "description": "4 digits in Switzerland and Liechtenstein."}, "city": {"type": "string", "maxLength": 35}, "country": {"type": "string", "default": "CH", "description": "ISO 3166-1 alpha-2."}, "iban": {"type": "string", "description": "A CH or LI IBAN; spaces, dashes, dots and lowercase are fine. A QR-IBAN needs a QR `reference`."}}, "required": ["name", "street", "postal_code", "city", "iban"], "description": "Who gets paid.", "additionalProperties": false}, "debtor": {"type": "object", "properties": {"name": {"type": "string", "maxLength": 70}, "street": {"type": "string", "maxLength": 70, "description": "A house number at its end is split off into `building_number`."}, "building_number": {"type": "string", "maxLength": 16}, "postal_code": {"type": "string", "maxLength": 16, "description": "4 digits in Switzerland and Liechtenstein."}, "city": {"type": "string", "maxLength": 35}, "country": {"type": "string", "default": "CH", "description": "ISO 3166-1 alpha-2."}}, "required": ["name", "postal_code", "city"], "description": "Who pays. Without it the payment part has an empty box for name and address.", "additionalProperties": false}, "reference": {"type": "string", "maxLength": 40, "description": "A 27-digit QR reference (required with a QR-IBAN, only allowed with one) or an RF creditor reference (only with a regular IBAN). Spaces and lowercase `rf` are fine."}, "message": {"type": "string", "maxLength": 140, "description": "Message on the payment part, passed to the bank. Default: \"Rechnung/Facture/Fattura/Invoice <invoice.number>\"."}, "amount": {"type": "number", "minimum": 0.01, "maximum": 999999999.99, "description": "The amount to pay, at most 2 decimals. Computed from `items` when left out; required with `html`. When both are sent they must agree."}, "invoice": {"type": "object", "properties": {"number": {"type": "string", "maxLength": 40, "description": "The user's next invoice number. Required with the default template."}, "date": {"type": "string", "format": "date", "description": "YYYY-MM-DD. Required in a GET link; POST defaults to today."}, "due_date": {"type": "string", "format": "date"}, "title": {"type": "string", "maxLength": 80, "description": "Default: Rechnung, Facture, Fattura or Invoice."}, "intro": {"type": "string", "maxLength": 3000}, "notes": {"type": "string", "maxLength": 3000}, "logo": {"type": "string", "maxLength": 400000, "description": "Default template only: a data: URI of a PNG, JPEG, GIF, WebP or SVG image. URLs are not fetched."}, "vat_number": {"type": "string", "maxLength": 40, "description": "The seller's VAT number: a Swiss UID with a valid check digit, e.g. `CHE-123.456.788 MWST` (separators optional; MWST, TVA or IVA optional), or a Liechtenstein one (5 digits). Required when an item has a `vat_rate` above 0."}}, "additionalProperties": false}, "items": {"type": "array", "minItems": 1, "maxItems": 200, "items": {"type": "object", "properties": {"description": {"type": "string", "maxLength": 1000, "description": "Text after a line break is shown smaller."}, "quantity": {"type": "number", "default": 1, "minimum": -1000000, "maximum": 1000000, "description": "At most 3 decimals."}, "unit": {"type": "string", "maxLength": 20}, "unit_price": {"type": "number", "minimum": -10000000, "maximum": 10000000, "description": "At most 2 decimals."}, "vat_rate": {"type": "number", "enum": [0, 2.5, 2.6, 3.7, 3.8, 7.7, 8.1], "description": "Percent. Send it on every item or on none (none: no VAT is charged); 0 for VAT-exempt lines. 8.1, 2.6 and 3.8 from 2024; the old 7.7, 2.5 and 3.7 only for an `invoice.date` before 2024."}}, "required": ["description", "unit_price"], "additionalProperties": false}}, "prices_include_vat": {"type": "boolean", "default": false, "description": "For the whole invoice."}, "css": {"type": "string", "maxLength": 100000, "description": "Added after the default template's stylesheet (and after your `html`)."}, "html": {"type": "string", "maxLength": 450000, "description": "The whole invoice body as HTML, replacing the default template. No placeholders. Nothing is fetched (images as data: URIs); the bottom 115 mm of the last page must stay free."}}, "required": ["creditor"], "description": "An invoice for the AI Invoice API. Unknown fields are refused, with the field to use instead.", "additionalProperties": false, "allOf": [{"if": {"required": ["html"]}, "then": {"required": ["amount"]}, "else": {"required": ["invoice", "items"], "properties": {"invoice": {"required": ["number"]}}}}, {"if": {"required": ["items"], "properties": {"items": {"contains": {"required": ["vat_rate"], "properties": {"vat_rate": {"exclusiveMinimum": 0}}}}}}, "then": {"required": ["invoice"], "properties": {"invoice": {"required": ["vat_number"]}}}}, {"if": {"required": ["items"], "properties": {"items": {"contains": {"required": ["vat_rate"]}}}}, "then": {"properties": {"items": {"items": {"required": ["vat_rate"]}}}}}]}, "AiInvoiceWarning": {"type": "object", "properties": {"code": {"type": "string", "enum": ["example_iban", "example_vat_number", "ignored_with_html", "missing_glyphs", "unusual_date", "vat_rate_not_in_force", "payment_part_on_extra_page", "message_left_out"]}, "field": {"type": "string"}, "message": {"type": "string"}}, "required": ["code", "field", "message"]}, "ArchiveDocument": {"type": "object", "properties": {"sourceId": {"type": "string", "description": "Stable identity: `invoice:{id}`, `invoice:{id}:proof` or `expense:{id}:{digest}`, the digest being the SHA-256 the receipt is stored under."}, "kind": {"type": "string", "enum": ["invoice", "payment_proof", "expense"]}, "number": {"type": ["string", "null"], "description": "The invoice number; null for an expense."}, "counterparty": {"type": ["string", "null"], "description": "The client's name; null for an expense."}, "description": {"type": ["string", "null"], "description": "The expense's description; null for an invoice."}, "date": {"type": ["string", "null"], "format": "date", "description": "Swiss calendar day of the invoice or expense. A payment proof carries its invoice's."}, "amount": {"type": ["string", "null"], "description": "With two decimals: the invoice total in `currency`, or the expense amount in CHF."}, "currency": {"type": "string"}, "status": {"type": "string", "enum": ["paid", "sent", "unpaid"], "description": "`paid` or `sent` for an invoice and its payment proof, `paid` or `unpaid` for an expense."}, "file": {"anyOf": [{"$ref": "#/components/schemas/ArchiveFile"}, {"type": "null"}], "description": "null when no file is stored; `missing` then says why."}, "missing": {"type": "string", "enum": ["notFound"], "description": "Only when `file` is null. `notFound`: nothing is stored for this document, for example an invoice whose PDF was never generated."}}, "required": ["sourceId", "kind", "number", "counterparty", "description", "date", "amount", "currency", "status", "file"]}, "ArchiveDocumentPage": {"type": "object", "properties": {"items": {"type": "array", "items": {"$ref": "#/components/schemas/ArchiveDocument"}}, "nextCursor": {"type": ["string", "null"], "description": "Pass it as `cursor` for the documents after these; null when there are no more. A page can be short or empty and still have one."}}, "required": ["items", "nextCursor"]}, "ArchiveFile": {"type": "object", "properties": {"name": {"type": "string", "description": "Suggested file name."}, "contentType": {"type": "string"}, "size": {"type": "integer", "description": "Bytes."}, "md5": {"type": ["string", "null"], "description": "MD5 of the stored object, base64 as the storage reports it; null for the few objects that have none."}, "generation": {"type": "string", "description": "Changes whenever the stored object is replaced: the same `sourceId` with the same `generation` is the same file."}, "url": {"type": "string", "description": "Download link for exactly this `generation`, valid for 15 minutes."}}, "required": ["name", "contentType", "size", "md5", "generation", "url"], "description": "A stored file. Nothing is rendered for this endpoint."}, "BackupResult": {"type": "object", "properties": {"email": {"type": "string", "description": "Where the download link is emailed."}, "year": {"type": "integer", "description": "The exported calendar year."}}, "required": ["email", "year"], "description": "The backup that was started."}, "BankAccount": {"type": "object", "properties": {"id": {"type": "string", "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "type": {"type": "string", "enum": ["iban", "custom"]}, "name": {"type": "string", "maxLength": 100, "minLength": 1, "description": "Label shown in the app."}, "currency": {"type": "string", "pattern": "^[A-Z]{3}$", "description": "Must be an ISO 4217 currency code like CHF, EUR or USD. IBAN accounts: CHF or EUR (a CHF IBAN also covers EUR invoices); any other currency needs type `custom`."}, "iban": {"type": "string", "maxLength": 64, "description": "type iban: a valid IBAN; spaces are removed."}, "data": {"type": "string", "maxLength": 2000, "description": "type custom: the account details as text."}}, "required": ["type", "name", "currency"]}, "BankAccountPatch": {"type": "object", "properties": {"id": {"type": "string", "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "type": {"type": "string", "enum": ["iban", "custom"]}, "name": {"type": "string", "maxLength": 100, "minLength": 1, "description": "Label shown in the app."}, "currency": {"type": "string", "pattern": "^[A-Z]{3}$", "description": "Must be an ISO 4217 currency code like CHF, EUR or USD. IBAN accounts: CHF or EUR (a CHF IBAN also covers EUR invoices); any other currency needs type `custom`."}, "iban": {"type": "string", "maxLength": 64, "description": "type iban: a valid IBAN; spaces are removed."}, "data": {"type": "string", "maxLength": 2000, "description": "type custom: the account details as text."}}}, "BankAccountRecord": {"type": "object", "properties": {"id": {"type": "string"}, "type": {"type": "string", "enum": ["iban", "custom"]}, "name": {"type": "string", "description": "Label shown in the app."}, "currency": {"type": "string", "description": "Must be an ISO 4217 currency code like CHF, EUR or USD. IBAN accounts: CHF or EUR (a CHF IBAN also covers EUR invoices); any other currency needs type `custom`."}, "iban": {"type": "string", "description": "type iban: a valid IBAN; spaces are removed."}, "data": {"type": "string", "description": "type custom: the account details as text."}}, "required": ["id"], "description": "An account printed on invoices for payment."}, "BankConnectResult": {"type": "object", "properties": {"authorizationUri": {"type": "string", "description": "Open it in the user's browser to grant consent."}, "connectionId": {"type": "string"}}, "required": ["authorizationUri", "connectionId"]}, "BankConnection": {"type": "object", "properties": {"id": {"type": "string"}, "providerId": {"type": "string"}, "providerName": {"type": ["string", "null"], "description": "The bank's name, for display."}, "status": {"type": "string", "enum": ["pending", "active", "error"], "description": "`pending` until the user grants consent, then `active`. `error` when consent was refused, expired or revoked: connect the same bank again to fix it."}, "sixStatus": {"type": "string", "description": "The consent state as the open-banking provider reports it."}, "scope": {"type": "string"}, "actions": {"type": "object", "properties": {"createInvoices": {"type": "boolean", "description": "Payouts from card terminals and platforms that match no invoice become paid invoices."}, "importExpenses": {"type": "boolean", "description": "Outgoing payments become paid expenses."}, "markPaid": {"type": "boolean", "description": "Incoming payments are recorded on the unpaid invoices they match."}}, "required": ["createInvoices", "importExpenses", "markPaid"], "description": "What a sync does with this connection's transactions."}, "accounts": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string"}, "iban": {"type": ["string", "null"]}, "currency": {"type": ["string", "null"]}, "owner": {"type": ["string", "null"]}, "designation": {"type": ["string", "null"]}}}, "description": "Accounts found on the last sync."}, "createdAt": {"type": ["string", "null"], "format": "date-time", "description": "In Swiss time with its offset, e.g. 2026-03-01T00:00:00+01:00."}, "lastSyncedAt": {"type": ["string", "null"], "format": "date-time", "description": "Last sync that retrieved every account."}, "lastSyncAttemptAt": {"type": ["string", "null"], "format": "date-time", "description": "In Swiss time with its offset, e.g. 2026-03-01T00:00:00+01:00."}, "lastSyncError": {"type": ["string", "null"]}}, "required": ["id", "providerId", "status", "actions"], "description": "A connection to the user's bank for importing transactions."}, "BankDisconnectResult": {"type": "object", "properties": {"deleted": {"type": "boolean", "const": true}, "id": {"type": "string"}, "revoked": {"type": "boolean", "description": "Whether the bank confirmed the consent was revoked."}}, "required": ["deleted", "id", "revoked"]}, "BankProvider": {"type": "object", "properties": {"providerId": {"type": "string", "description": "Pass it to `POST /bank/connect`."}, "name": {"type": ["string", "null"]}, "abbreviation": {"type": ["string", "null"]}, "url": {"type": ["string", "null"]}, "logo": {"type": ["string", "null"], "description": "A `data:` URI (SVG) with `?logos=true`, else null."}}, "required": ["providerId"]}, "BankSyncResult": {"type": "object", "properties": {"syncedConnections": {"type": "integer", "minimum": 0, "description": "Connections synced completely."}, "skippedConnections": {"type": "integer", "minimum": 0, "description": "Connections not (fully) synced; see `details.skipped_connections`."}, "failedAccounts": {"type": "integer", "minimum": 0, "description": "Accounts whose transactions could not be retrieved."}, "deferredAccounts": {"type": "integer", "minimum": 0, "description": "Accounts whose booking days are not final yet."}, "invoicesMatched": {"type": "integer", "minimum": 0, "description": "Unpaid invoices paid in full by a credit."}, "invoicesCreated": {"type": "integer", "minimum": 0, "description": "Paid invoices created from payouts."}, "partialPayments": {"type": "integer", "minimum": 0, "description": "Partial payments recorded on invoices."}, "unmatchedCredits": {"type": "integer", "minimum": 0, "description": "Credits matching no invoice."}, "expensesCreated": {"type": "integer", "minimum": 0, "description": "Expenses created from debits."}, "needCategory": {"type": "integer", "minimum": 0, "description": "Created expenses that still need a category."}, "details": {"type": "object", "additionalProperties": {"type": "array", "items": {"$ref": "#/components/schemas/DetailRow"}}, "description": "The rows behind the counts, by bucket, at most 200 each; a bucket is present only when it has rows. `matched`: credits applied to an invoice (with `invoiceId`). `invoices_created`: payouts booked as paid invoices (with `invoiceId`). `expenses_created`: debits booked as expenses (with `expenseId`). `unmatched_credits`: credits with no invoice, with `date` and `amount` so you can offer to create one. `already_imported`; `pending`: not booked by the bank yet; `skipped_connections` and `skipped_accounts`: with the reason nothing was fetched; `reversals`: reversed payments to review."}}, "required": ["syncedConnections", "skippedConnections", "failedAccounts", "deferredAccounts", "invoicesMatched", "invoicesCreated", "partialPayments", "unmatchedCredits", "expensesCreated", "needCategory", "details"], "description": "Result of a bank sync."}, "CatalogItem": {"type": "object", "properties": {"id": {"type": "string", "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "catalogItemId": {"type": ["string", "null"], "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "name": {"type": "string", "maxLength": 2000, "description": "Required, not blank. First line is the title; more lines allowed."}, "price": {"type": "number", "minimum": -10000000, "maximum": 10000000, "description": "Unit price in the invoice currency; negative for a discount line."}, "units": {"type": "number", "minimum": -1000000, "maximum": 1000000, "description": "Quantity; fractions allowed; negative for a discount or credit line."}, "vatRate": {"type": "number", "minimum": 0, "maximum": 100, "description": "Percent: 0, 2.6, 3.8 or 8.1 (7.7, 2.5, 3.7 for dates before 2024)."}, "discount": {"type": "number", "minimum": 0, "maximum": 100, "description": "Percent off this line."}, "usageCount": {"type": "integer", "minimum": 0, "maximum": 1000000}, "details": {"type": ["object", "null"], "properties": {"type": {"type": "string", "enum": ["HourlyRateDetails"]}, "date": {"type": "string", "description": "Work date. Defaults to the invoice date (catalog items: now)."}, "from": {"type": "string", "maxLength": 5, "minLength": 1, "pattern": "^(?:([01]\\d|2[0-3]):[0-5]\\d)$", "description": "Start, HH:mm."}, "to": {"type": "string", "maxLength": 5, "minLength": 1, "pattern": "^(?:([01]\\d|2[0-3]):[0-5]\\d)$", "description": "End, HH:mm; not before `from`."}}, "required": ["type", "from", "to"]}, "isCreditNoteItem": {"type": "boolean", "description": "Marks a credit-note line (the app uses it for credit-note numbering). Negative `units` or `price` (discount lines) do not need it."}, "unitBasis": {"type": ["object", "null"], "properties": {"type": {"type": "string", "enum": ["preset", "custom"]}, "value": {"type": "string", "maxLength": 20, "minLength": 1, "description": "A preset name for `preset`, a 1-20 character label for `custom`."}}, "required": ["type", "value"], "description": "What `units` counts: {type: preset, value: hour|day|piece|kilometer|kilogram|squareMeter|flatRate} or {type: custom, value: 'm³'}. null = no unit."}}, "required": ["name"]}, "CatalogItemPatch": {"type": "object", "properties": {"id": {"type": "string", "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "catalogItemId": {"type": ["string", "null"], "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "name": {"type": "string", "maxLength": 2000, "description": "Required, not blank. First line is the title; more lines allowed."}, "price": {"type": "number", "minimum": -10000000, "maximum": 10000000, "description": "Unit price in the invoice currency; negative for a discount line."}, "units": {"type": "number", "minimum": -1000000, "maximum": 1000000, "description": "Quantity; fractions allowed; negative for a discount or credit line."}, "vatRate": {"type": "number", "minimum": 0, "maximum": 100, "description": "Percent: 0, 2.6, 3.8 or 8.1 (7.7, 2.5, 3.7 for dates before 2024)."}, "discount": {"type": "number", "minimum": 0, "maximum": 100, "description": "Percent off this line."}, "usageCount": {"type": "integer", "minimum": 0, "maximum": 1000000}, "details": {"type": ["object", "null"], "properties": {"type": {"type": "string", "enum": ["HourlyRateDetails"]}, "date": {"type": "string", "description": "Work date. Defaults to the invoice date (catalog items: now)."}, "from": {"type": "string", "maxLength": 5, "minLength": 1, "pattern": "^(?:([01]\\d|2[0-3]):[0-5]\\d)$", "description": "Start, HH:mm."}, "to": {"type": "string", "maxLength": 5, "minLength": 1, "pattern": "^(?:([01]\\d|2[0-3]):[0-5]\\d)$", "description": "End, HH:mm; not before `from`."}}, "required": ["type", "from", "to"]}, "isCreditNoteItem": {"type": "boolean", "description": "Marks a credit-note line (the app uses it for credit-note numbering). Negative `units` or `price` (discount lines) do not need it."}, "unitBasis": {"type": ["object", "null"], "properties": {"type": {"type": "string", "enum": ["preset", "custom"]}, "value": {"type": "string", "maxLength": 20, "minLength": 1, "description": "A preset name for `preset`, a 1-20 character label for `custom`."}}, "required": ["type", "value"], "description": "What `units` counts: {type: preset, value: hour|day|piece|kilometer|kilogram|squareMeter|flatRate} or {type: custom, value: 'm³'}. null = no unit."}}}, "CatalogItemRecord": {"type": "object", "properties": {"id": {"type": "string"}, "catalogItemId": {"type": ["string", "null"]}, "name": {"type": "string", "description": "Required, not blank. First line is the title; more lines allowed."}, "price": {"type": "number", "description": "Unit price in the invoice currency; negative for a discount line."}, "units": {"type": "number", "description": "Quantity; fractions allowed; negative for a discount or credit line."}, "vatRate": {"type": "number", "description": "Percent: 0, 2.6, 3.8 or 8.1 (7.7, 2.5, 3.7 for dates before 2024)."}, "discount": {"type": "number", "description": "Percent off this line."}, "usageCount": {"type": "integer"}, "details": {"type": ["object", "null"], "properties": {"type": {"type": "string", "enum": ["HourlyRateDetails"]}, "date": {"type": "string", "description": "Work date. Defaults to the invoice date (catalog items: now)."}, "from": {"type": "string", "description": "Start, HH:mm."}, "to": {"type": "string", "description": "End, HH:mm; not before `from`."}}}, "isCreditNoteItem": {"type": "boolean", "description": "Marks a credit-note line (the app uses it for credit-note numbering). Negative `units` or `price` (discount lines) do not need it."}, "unitBasis": {"type": ["object", "null"], "properties": {"type": {"type": "string", "enum": ["preset", "custom"]}, "value": {"type": "string", "description": "A preset name for `preset`, a 1-20 character label for `custom`."}}, "description": "What `units` counts: {type: preset, value: hour|day|piece|kilometer|kilogram|squareMeter|flatRate} or {type: custom, value: 'm³'}. null = no unit."}}, "required": ["id"], "description": "A product or service of your catalog (`/invoice-items`)."}, "Category": {"type": "object", "properties": {"id": {"type": "string", "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "name": {"type": "string", "maxLength": 100, "minLength": 1}, "emoji": {"type": ["string", "null"], "maxLength": 32}, "type": {"type": "string", "enum": ["expense", "payment"]}}, "required": ["name"]}, "CategoryPatch": {"type": "object", "properties": {"id": {"type": "string", "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "name": {"type": "string", "maxLength": 100, "minLength": 1}, "emoji": {"type": ["string", "null"], "maxLength": 32}, "type": {"type": "string", "enum": ["expense", "payment"]}}}, "CategoryRecord": {"type": "object", "properties": {"id": {"type": "string"}, "name": {"type": "string"}, "emoji": {"type": ["string", "null"]}, "type": {"type": "string", "enum": ["expense", "payment"]}}, "required": ["id"], "description": "An expense category (`type: expense`) or payment method (`type: payment`)."}, "Client": {"type": "object", "properties": {"id": {"type": "string", "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "name": {"type": "string", "maxLength": 300, "minLength": 1, "description": "May be multi-line (e.g. company + c/o)."}, "street": {"type": "string", "maxLength": 100, "description": "Street name without the number."}, "buildingNumber": {"type": "string", "maxLength": 16}, "zip": {"type": "string", "maxLength": 16, "description": "CH: 4 digits, 1000-9658."}, "city": {"type": "string", "maxLength": 100}, "country": {"type": "string", "pattern": "^[A-Z]{2}$", "description": "Must be an ISO 3166-1 alpha-2 country code like CH, DE or FR. Default CH."}, "email": {"type": "string", "maxLength": 254, "format": "email"}, "ccEmails": {"type": "array", "items": {"type": "string", "maxLength": 254, "minLength": 1, "format": "email"}, "maxItems": 10}, "notes": {"type": "string", "maxLength": 5000, "description": "Private note; never printed on invoices."}, "details": {"type": "string", "maxLength": 1000, "description": "Extra debtor line, e.g. the client's UID."}, "files": {"type": "array", "items": {"type": "object", "properties": {"path": {"type": "string", "maxLength": 1024, "minLength": 1, "description": "Storage path of the uploaded file."}, "name": {"type": "string", "maxLength": 255, "minLength": 1}, "size": {"type": "integer", "minimum": 1, "maximum": 1000000000, "description": "Bytes."}, "digest": {"type": "string", "maxLength": 64, "minLength": 64, "pattern": "^(?:[0-9a-f]{64})$"}, "url": {"type": ["string", "null"], "maxLength": 4096}, "uploadDate": {"type": ["string", "null"], "description": "Date or date-time."}, "type": {"type": "string", "enum": ["CloudFile"], "description": "Always `CloudFile`; may be omitted."}}, "required": ["path", "name", "size", "digest"], "description": "An uploaded file."}, "maxItems": 100}, "invoiceEmailSubjects": {"type": "object", "propertyNames": {"enum": ["invoice", "quote", "orderConfirmation", "deliveryBill", "paymentReminder", "paymentConfirmation", "creditNote"]}, "additionalProperties": {"type": "string", "maxLength": 500}}}, "required": ["name"]}, "ClientPatch": {"type": "object", "properties": {"id": {"type": "string", "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "name": {"type": "string", "maxLength": 300, "minLength": 1, "description": "May be multi-line (e.g. company + c/o)."}, "street": {"type": "string", "maxLength": 100, "description": "Street name without the number."}, "buildingNumber": {"type": "string", "maxLength": 16}, "zip": {"type": "string", "maxLength": 16, "description": "CH: 4 digits, 1000-9658."}, "city": {"type": "string", "maxLength": 100}, "country": {"type": "string", "pattern": "^[A-Z]{2}$", "description": "Must be an ISO 3166-1 alpha-2 country code like CH, DE or FR. Default CH."}, "email": {"type": "string", "maxLength": 254, "format": "email"}, "ccEmails": {"type": "array", "items": {"type": "string", "maxLength": 254, "minLength": 1, "format": "email"}, "maxItems": 10}, "notes": {"type": "string", "maxLength": 5000, "description": "Private note; never printed on invoices."}, "details": {"type": "string", "maxLength": 1000, "description": "Extra debtor line, e.g. the client's UID."}, "files": {"type": "array", "items": {"type": "object", "properties": {"path": {"type": "string", "maxLength": 1024, "minLength": 1, "description": "Storage path of the uploaded file."}, "name": {"type": "string", "maxLength": 255, "minLength": 1}, "size": {"type": "integer", "minimum": 1, "maximum": 1000000000, "description": "Bytes."}, "digest": {"type": "string", "maxLength": 64, "minLength": 64, "pattern": "^(?:[0-9a-f]{64})$"}, "url": {"type": ["string", "null"], "maxLength": 4096}, "uploadDate": {"type": ["string", "null"], "description": "Date or date-time."}, "type": {"type": "string", "enum": ["CloudFile"], "description": "Always `CloudFile`; may be omitted."}}, "required": ["path", "name", "size", "digest"], "description": "An uploaded file."}, "maxItems": 100}, "invoiceEmailSubjects": {"type": "object", "propertyNames": {"enum": ["invoice", "quote", "orderConfirmation", "deliveryBill", "paymentReminder", "paymentConfirmation", "creditNote"]}, "additionalProperties": {"type": "string", "maxLength": 500}}}}, "ClientRecord": {"type": "object", "properties": {"id": {"type": "string"}, "name": {"type": "string", "description": "May be multi-line (e.g. company + c/o)."}, "street": {"type": "string", "description": "Street name without the number."}, "buildingNumber": {"type": "string"}, "zip": {"type": "string", "description": "CH: 4 digits, 1000-9658."}, "city": {"type": "string"}, "country": {"type": "string", "description": "Must be an ISO 3166-1 alpha-2 country code like CH, DE or FR. Default CH."}, "email": {"type": "string"}, "ccEmails": {"type": "array", "items": {"type": "string"}}, "notes": {"type": "string", "description": "Private note; never printed on invoices."}, "details": {"type": "string", "description": "Extra debtor line, e.g. the client's UID."}, "files": {"type": "array", "items": {"type": "object", "properties": {"path": {"type": "string", "description": "Storage path of the uploaded file."}, "name": {"type": "string"}, "size": {"type": "integer", "description": "Bytes."}, "digest": {"type": "string"}, "url": {"type": ["string", "null"]}, "uploadDate": {"type": ["string", "null"], "description": "Date or date-time."}, "type": {"type": "string", "enum": ["CloudFile"], "description": "Always `CloudFile`; may be omitted."}}, "description": "An uploaded file."}}, "invoiceEmailSubjects": {"type": "object", "propertyNames": {"enum": ["invoice", "quote", "orderConfirmation", "deliveryBill", "paymentReminder", "paymentConfirmation", "creditNote"]}, "additionalProperties": {"type": "string"}}, "address": {"type": "string", "deprecated": true, "description": "Address as one line, only on records saved before addresses had separate fields."}}, "required": ["id"], "description": "A client."}, "Company": {"type": "object", "properties": {"id": {"type": "string"}, "name": {"type": "string", "description": "Formatted for an invoice: at most 2 lines of 70 characters."}, "name_lines": {"type": "array", "items": {"type": "string"}, "description": "`name` split into its lines."}, "street": {"type": "string", "description": "Street name only, or the whole address line when it has no house number."}, "buildingNumber": {"type": "string", "description": "Empty when the address has none (PO box, c/o)."}, "zip": {"type": ["string", "null"]}, "city": {"type": ["string", "null"]}, "uid": {"type": ["string", "null"], "description": "The company's UID, CHE-XXX.XXX.XXX, to fill in as the VAT number: set only when the company is known to be registered for VAT, which is the case for few. Otherwise empty: see `companyUid`."}, "companyUid": {"type": ["string", "null"], "description": "The company's UID, CHE-XXX.XXX.XXX, whether or not it is registered for VAT. For `source` `uid` it is also the `id`."}, "legalForm": {"type": ["string", "null"], "description": "For example `AG / SA` or `GmbH / Sàrl`."}, "legalFormCode": {"type": ["string", "null"], "description": "eCH-0097 legal form code."}, "source": {"type": "string", "enum": ["zefix", "uid"], "description": "`zefix`: the commercial register. `uid`: businesses from the federal UID register that are not in the commercial register, mostly sole proprietors."}}, "description": "A company from the Swiss commercial register or the UID register."}, "CompanySearchResult": {"type": "object", "properties": {"items": {"type": "array", "items": {"$ref": "#/components/schemas/Company"}}, "count": {"type": "integer", "minimum": 0}, "query": {"type": "string"}}, "required": ["items", "count", "query"]}, "CreateBankAccountRequest": {"description": "The account, or the account wrapped in `bankAccount`.", "anyOf": [{"$ref": "#/components/schemas/BankAccount"}, {"type": "object", "properties": {"bankAccount": {"$ref": "#/components/schemas/BankAccount"}}, "required": ["bankAccount"]}]}, "CreateExpenseRequest": {"description": "The expense, or the expense wrapped in `expense`.", "anyOf": [{"$ref": "#/components/schemas/Expense"}, {"type": "object", "properties": {"expense": {"$ref": "#/components/schemas/Expense"}}, "required": ["expense"]}]}, "CreateInvoiceRequest": {"description": "The invoice with `clientId` (or a `client` object) and at least one line in `items`. `{clientId, invoice: {...}}` is accepted too.", "anyOf": [{"allOf": [{"$ref": "#/components/schemas/Invoice"}, {"type": "object", "properties": {"items": {"minItems": 1}}, "required": ["items"]}, {"type": "object", "properties": {"client": {"$ref": "#/components/schemas/Client", "description": "Instead of `clientId`: the client, matched by name or email like `POST /clients/save`, else created."}}}]}, {"type": "object", "properties": {"invoice": {"allOf": [{"$ref": "#/components/schemas/Invoice"}, {"type": "object", "properties": {"items": {"minItems": 1}}, "required": ["items"]}]}, "clientId": {"type": "string", "description": "Existing client id."}, "client": {"$ref": "#/components/schemas/Client", "description": "Instead of `clientId`: the client, matched by name or email like `POST /clients/save`, else created."}, "confirmDate": {"type": "boolean", "description": "Send true to confirm an invoice date outside the current year."}}, "required": ["invoice"]}]}, "CreditInvoice": {"type": "object", "properties": {"invoiceId": {"type": "string"}, "version": {"type": ["integer", "null"], "description": "Invoice number."}, "importRef": {"type": ["string", "null"]}, "clientId": {"type": "string"}, "clientName": {"type": "string"}, "clientCreated": {"type": "boolean"}, "amount": {"type": "number"}, "currency": {"type": "string"}, "date": {"type": "string", "format": "date", "description": "Calendar day, YYYY-MM-DD."}, "itemName": {"type": "string"}, "kind": {"type": "string", "enum": ["customer_payment", "acquirer_payout"]}, "alreadyExisted": {"type": "boolean", "description": "`POST /invoices/from-credit` only."}}, "required": ["invoiceId"], "description": "A paid invoice created from a bank credit."}, "DeleteResult": {"type": "object", "properties": {"deleted": {"type": "boolean", "const": true}, "id": {"type": "string"}}, "required": ["deleted", "id"]}, "DetailRow": {"type": "object", "properties": {"label": {"type": "string", "description": "Who or what the row is (payer, description, name)."}, "sublabel": {"type": "string", "description": "Date, amount and reference, for display."}, "reason": {"type": "string", "description": "Why the row landed in this bucket."}, "date": {"type": "string", "format": "date", "description": "Set on rows that can still be booked by hand."}, "amount": {"type": "number", "description": "Set on rows that can still be booked by hand."}, "invoiceId": {"type": "string"}, "expenseId": {"type": "string"}, "payload": {"type": "object", "description": "Ready-made body for `POST /invoices/from-credit`, to create the invoice anyway."}}, "required": ["label"], "description": "One row of an import or bank sync summary, as the apps show it."}, "ErrorEnvelope": {"type": "object", "properties": {"success": {"type": "boolean", "const": false}, "error": {"type": "string", "description": "What went wrong, for people."}, "code": {"type": "string", "description": "Machine-readable reason; branch on it, not on `error`. `invalid_request` (malformed request), `invalid_query` (query parameter), `validation_failed` (see `details.errors`), `unauthorized`, `not_found`, `method_not_allowed`, `already_exists` (the `id` sent to a create is taken), `has_dependents` (other documents still use it), `conflict`, `payload_too_large`, `uri_too_long` (a link over 4000 characters), `unprocessable`, `parse_failed` and `import_failed` (file imports), `insufficient_letters` (no letters left), `invalid_code`, `email_not_sent`, `account_required`, `account_email`, `already_linked`, `limit_reached` and `account_exists` (linked addresses), `rate_limited`, `upstream_unavailable` (a service behind the API failed; retry later), `internal_error`. More codes may be added.", "examples": ["invalid_request", "invalid_query", "validation_failed", "unauthorized", "session_expired", "forbidden", "not_found", "method_not_allowed", "conflict", "already_exists", "has_dependents", "payload_too_large", "uri_too_long", "unsupported_media_type", "unprocessable", "parse_failed", "import_failed", "insufficient_letters", "rate_limited", "upstream_unavailable", "internal_error", "invalid_code", "email_not_sent", "account_required", "account_email", "already_linked", "limit_reached", "account_exists"]}, "details": {"description": "More about the error where useful, e.g. `details.errors` for `validation_failed`."}}, "required": ["success", "error", "code"], "example": {"success": false, "error": "Document not found", "code": "not_found"}}, "Expense": {"type": "object", "properties": {"id": {"type": "string", "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "description": {"type": "string", "maxLength": 2000, "description": "First line is the title."}, "amount": {"type": "number", "minimum": -10000000, "maximum": 10000000, "description": "CHF, VAT included; negative for a refund."}, "vatRate": {"type": "number", "minimum": 0, "maximum": 100, "description": "Percent: 0, 2.6, 3.8, 8.1, or 100 for a VAT-only entry."}, "date": {"type": "string", "description": "Receipt date: not in the future, at most 5 calendar years back."}, "categoryID": {"type": ["string", "null"], "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$", "description": "Expense category id (a `type: expense` category from GET /categories)."}, "paymentMethodID": {"type": ["string", "null"], "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$", "description": "Payment method id (a `type: payment` category from GET /categories)."}, "originalAmount": {"type": ["number", "null"], "minimum": -1000000000000.0, "maximum": 1000000000000.0, "description": "Amount in `originalCurrency`."}, "originalCurrency": {"type": ["string", "null"], "pattern": "^[A-Z]{3}$", "description": "Must be an ISO 4217 currency code like CHF, EUR or USD."}, "withholdingTax": {"type": "boolean"}, "isPaid": {"type": "boolean"}, "documents": {"type": "array", "items": {"type": "object", "properties": {"path": {"type": "string", "maxLength": 1024, "minLength": 1, "description": "Storage path of the uploaded file."}, "name": {"type": "string", "maxLength": 255, "minLength": 1}, "size": {"type": "integer", "minimum": 1, "maximum": 1000000000, "description": "Bytes."}, "digest": {"type": "string", "maxLength": 64, "minLength": 64, "pattern": "^(?:[0-9a-f]{64})$"}, "url": {"type": ["string", "null"], "maxLength": 4096}, "uploadDate": {"type": ["string", "null"], "description": "Date or date-time."}, "type": {"type": "string", "enum": ["CloudFile"], "description": "Always `CloudFile`; may be omitted."}}, "required": ["path", "name", "size", "digest"], "description": "An uploaded file."}, "maxItems": 20}, "category": {"type": "string", "maxLength": 100, "description": "POST /expenses only: category name, created if missing."}, "paymentMethod": {"type": "string", "maxLength": 100, "description": "POST /expenses only: payment method name, created if missing."}}}, "ExpenseImportResult": {"type": "object", "properties": {"success": {"type": "boolean", "const": true}, "total_rows": {"type": "integer", "minimum": 0}, "dropped_invalid": {"type": "integer", "minimum": 0, "description": "Rows missing the minimum fields."}, "skipped_duplicate": {"type": "integer", "minimum": 0, "description": "Rows that already exist."}, "skipped_by_ai": {"type": "integer", "minimum": 0, "description": "Rows judged not to belong, e.g. not a client."}, "ai_failures": {"type": "integer", "minimum": 0}, "imported": {"type": "integer", "minimum": 0}, "errors": {"type": "array", "items": {"type": "string"}, "description": "Problems with single rows; the other rows were still imported."}, "dry_run": {"type": "boolean"}, "structure_source": {"type": ["string", "null"], "description": "How the columns were recognised."}, "details": {"type": "object", "additionalProperties": {"type": "array", "items": {"$ref": "#/components/schemas/DetailRow"}}, "description": "The rows behind the counts, by bucket (at most 200 rows per bucket)."}, "skipped_credits": {"type": "integer", "minimum": 0, "description": "Incoming money and reversals, which are no expenses."}, "skipped_pre_ai_duplicate": {"type": "integer", "minimum": 0}, "skipped_post_ai_duplicate": {"type": "integer", "minimum": 0}, "learnedExamples": {"type": "integer", "minimum": 0, "description": "Your earlier expenses used as examples for naming and categories."}}, "description": "Result of an expense import."}, "ExpenseRecord": {"type": "object", "properties": {"id": {"type": "string"}, "description": {"type": "string", "description": "First line is the title."}, "amount": {"type": "number", "description": "CHF, VAT included; negative for a refund."}, "vatRate": {"type": "number", "description": "Percent: 0, 2.6, 3.8, 8.1, or 100 for a VAT-only entry."}, "date": {"type": "string", "description": "Receipt date: not in the future, at most 5 calendar years back."}, "categoryID": {"type": ["string", "null"], "description": "Expense category id (a `type: expense` category from GET /categories)."}, "paymentMethodID": {"type": ["string", "null"], "description": "Payment method id (a `type: payment` category from GET /categories)."}, "originalAmount": {"type": ["number", "null"], "description": "Amount in `originalCurrency`."}, "originalCurrency": {"type": ["string", "null"], "description": "Must be an ISO 4217 currency code like CHF, EUR or USD."}, "withholdingTax": {"type": "boolean"}, "isPaid": {"type": "boolean"}, "documents": {"type": "array", "items": {"type": "object", "properties": {"path": {"type": "string", "description": "Storage path of the uploaded file."}, "name": {"type": "string"}, "size": {"type": "integer", "description": "Bytes."}, "digest": {"type": "string"}, "url": {"type": ["string", "null"]}, "uploadDate": {"type": ["string", "null"], "description": "Date or date-time."}, "type": {"type": "string", "enum": ["CloudFile"], "description": "Always `CloudFile`; may be omitted."}}, "description": "An uploaded file."}}}, "required": ["id"], "description": "An expense. `amount` is in CHF."}, "ExpenseScan": {"type": "object", "properties": {"description": {"type": ["string", "null"]}, "date": {"type": ["string", "null"]}, "paid": {"type": ["boolean", "null"]}, "vat_rate": {"type": ["number", "null"]}, "vat_amount": {"type": ["number", "null"]}, "currency": {"type": ["string", "null"]}, "amount": {"type": ["number", "null"], "description": "In CHF (converted for a foreign receipt)."}, "amount_original": {"type": ["number", "null"], "description": "In `currency`, for a foreign receipt."}, "category": {"type": ["string", "null"]}, "payment_method": {"type": ["string", "null"]}, "withholding_tax_relevant": {"type": ["boolean", "null"]}}, "description": "What was read from the receipt, before it was stored."}, "Export": {"type": "object", "properties": {"id": {"type": "string"}, "status": {"type": "string", "enum": ["pending", "running", "ready", "failed", "expired"]}, "includeFiles": {"type": "boolean", "description": "false: tables and JSON only, no documents."}, "createdAt": {"type": "string", "format": "date-time", "description": "In Swiss time with its offset, e.g. 2026-03-01T00:00:00+01:00."}, "finishedAt": {"type": ["string", "null"], "format": "date-time", "description": "In Swiss time with its offset, e.g. 2026-03-01T00:00:00+01:00."}, "expiresAt": {"type": ["string", "null"], "format": "date-time", "description": "When the zip and `downloadUrl` stop working."}, "downloadUrl": {"type": ["string", "null"], "description": "Signed link to the zip; only while `ready`."}, "sizeBytes": {"type": ["integer", "null"]}, "counts": {"type": ["object", "null"], "additionalProperties": {"type": "integer", "minimum": 0}, "description": "Records and files in the zip: invoices, quotes, clients, expenses, products, categories, letters, bankConnections, files, missingFiles."}, "missingFiles": {"type": "array", "items": {"type": "string"}, "description": "Documents that could not be included, as `path in zip: reason` (first 200)."}, "missingCount": {"type": "integer", "minimum": 0}, "error": {"type": ["string", "null"], "description": "Why the export failed."}}, "required": ["id", "status", "includeFiles", "createdAt", "downloadUrl"], "description": "A full account export."}, "GenerateOptions": {"type": "object", "properties": {"version": {"type": "string", "enum": ["v1l"], "description": "PDF layout version. Omit it: v1l, the current one, is the only one."}, "testMode": {"type": "boolean", "description": "true: use sample company and bank details instead of the account's, to try things out."}, "locale": {"type": ["string", "null"], "enum": ["de", "en", "fr", "it", null]}, "overrides": {"$ref": "#/components/schemas/InvoiceOverrides"}}}, "GenerateResult": {"type": "object", "properties": {"url": {"type": "string", "description": "Signed HTTPS link to the PDF, valid for 7 days."}, "filename": {"type": ["string", "null"], "description": "Suggested file name, without `.pdf`."}, "expiresAt": {"type": ["string", "null"], "format": "date-time", "description": "When `url` stops working (Swiss time). Generate again for a new link."}}, "required": ["url", "filename", "expiresAt"], "description": "The generated PDF."}, "Invoice": {"type": "object", "properties": {"id": {"type": "string", "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "clientId": {"type": "string", "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$", "description": "Id of one of your clients."}, "clientRef": {"type": "string", "maxLength": 300, "minLength": 1, "description": "Deprecated reference to the client; use `clientId`."}, "date": {"type": "string", "description": "Invoice date (a date only is fine). Must be in this or last calendar year and at most 92 days ahead; a date outside the current Swiss calendar year also needs `confirmDate: true`."}, "confirmDate": {"type": "boolean", "description": "Send true to confirm an invoice date outside the current year."}, "type": {"type": "string", "enum": ["normal", "quote"], "description": "`normal` is an invoice, `quote` a quote."}, "version": {"type": "integer", "minimum": 1, "maximum": 1000000, "description": "Invoice number, unique per (Swiss calendar year of `date`, `type`). Omit to get the next one."}, "language": {"type": "string", "enum": ["de", "en", "fr", "it"], "description": "Language the app shows the document in. A PDF or email made through the API uses the `locale` you pass to generate or send, by default the account language."}, "currency": {"type": "string", "pattern": "^[A-Z]{3}$", "description": "Must be an ISO 4217 currency code like CHF, EUR or USD."}, "exchangeRate": {"type": ["number", "null"], "exclusiveMinimum": 0, "maximum": 10000000, "description": "CHF -> currency rate: units of `currency` per 1 CHF (about 1.07 for EUR). Non-CHF invoices only; leave it null: when a foreign-currency invoice is paid (app or API) the rate of its latest payment date is stored. A rate sent here is kept."}, "vatEnabled": {"type": "boolean", "description": "false: the invoice has no VAT."}, "vatMode": {"type": "string", "enum": ["additive", "inclusive"], "description": "`additive`: prices are without VAT, which is added on top. `inclusive`: prices already include VAT."}, "isPaid": {"type": "boolean"}, "sent": {"type": "boolean"}, "isArchived": {"type": "boolean"}, "disableRounding": {"type": "boolean", "description": "false rounds the total to 0.05."}, "hideQuotePricing": {"type": "boolean"}, "generationCount": {"type": "integer", "minimum": 0, "maximum": 10000, "description": "How many times the PDF was generated."}, "description": {"type": "string", "maxLength": 5000, "description": "Text below the items."}, "headerDescription": {"type": "string", "maxLength": 5000, "description": "Text above the items."}, "recurring": {"type": "string", "enum": ["disabled", "monthly", "quarterly", "yearly", "biYearly", "triYearly"], "description": "biYearly = every 6 months, triYearly = every 4 months."}, "recurringDueDate": {"type": ["string", "null"], "description": "When the recurrence stops."}, "recurringAutoSend": {"type": "boolean", "description": "Send each new copy automatically."}, "bankId": {"type": ["string", "null"], "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$", "description": "Id from GET /bank-accounts; null picks one by client and currency. The account must be in the invoice currency, or a CHF IBAN for a EUR invoice; GBP, USD and other currencies need a `custom` account in that currency."}, "items": {"type": "array", "items": {"$ref": "#/components/schemas/InvoiceItem"}, "maxItems": 500}, "payments": {"type": "object", "properties": {"proof": {"type": ["object", "null"], "properties": {"path": {"type": "string", "maxLength": 1024, "minLength": 1, "description": "Storage path of the uploaded file."}, "name": {"type": "string", "maxLength": 255, "minLength": 1}, "size": {"type": "integer", "minimum": 1, "maximum": 1000000000, "description": "Bytes."}, "digest": {"type": "string", "maxLength": 64, "minLength": 64, "pattern": "^(?:[0-9a-f]{64})$"}, "url": {"type": ["string", "null"], "maxLength": 4096}, "uploadDate": {"type": ["string", "null"], "description": "Date or date-time."}, "type": {"type": "string", "enum": ["CloudFile"], "description": "Always `CloudFile`; may be omitted."}}, "required": ["path", "name", "size", "digest"]}, "items": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": ["string", "null"], "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "methodId": {"type": "string", "maxLength": 128, "pattern": "^(?:[^/\\s]+)$", "description": "Id of a payment method (a `type: payment` category from GET /categories)."}, "amount": {"type": "number", "minimum": -100000000, "maximum": 100000000, "description": "In the invoice currency; negative for a credit note (negative total)."}, "date": {"type": "string", "description": "When the money arrived; not in the future. Defaults to now."}}, "required": ["methodId", "amount"]}, "maxItems": 500}}}, "sentEmailHistory": {"type": "array", "items": {"type": "object", "properties": {"email": {"type": "string", "maxLength": 254, "minLength": 1, "format": "email"}, "isTest": {"type": "boolean"}, "date": {"type": "string", "description": "Date or date-time."}, "success": {"type": "boolean"}, "ccEmails": {"type": "array", "items": {"type": "string", "maxLength": 254, "minLength": 1, "format": "email"}, "maxItems": 20}, "note": {"type": ["string", "null"], "maxLength": 5000}, "invoiceStatus": {"type": "string", "enum": ["quote", "invoice", "reminder", "confirmation", "orderConfirmation", "deliveryBill", "advancePayment"]}}, "required": ["email", "isTest", "date", "success"]}, "maxItems": 1000}}}, "InvoiceHistoryImportResult": {"type": "object", "properties": {"success": {"type": "boolean", "const": true}, "total_rows": {"type": "integer", "minimum": 0}, "imported": {"type": "integer", "minimum": 0, "description": "Invoices created."}, "grouped": {"type": "integer", "minimum": 0, "description": "Rows merged into one invoice per month."}, "renumbered": {"type": "integer", "minimum": 0, "description": "Imported invoices whose number was already used that year."}, "skipped_duplicate": {"type": "integer", "minimum": 0, "description": "Invoices imported before or already in Magic Heidi."}, "skipped_status": {"type": "integer", "minimum": 0, "description": "Cancelled invoices, drafts, credit notes and quotes."}, "dropped_invalid": {"type": "integer", "minimum": 0, "description": "Rows missing a client, date or amount."}, "clients_created": {"type": "integer", "minimum": 0}, "errors": {"type": "array", "items": {"type": "string"}, "description": "Problems with single rows; the other rows were still imported."}, "details": {"type": "object", "additionalProperties": {"type": "array", "items": {"$ref": "#/components/schemas/DetailRow"}}, "description": "The rows behind the counts, by bucket (at most 200 rows per bucket)."}}, "description": "Result of an invoice list import."}, "InvoiceImportResult": {"type": "object", "properties": {"success": {"type": "boolean", "const": true}, "total_rows": {"type": "integer", "minimum": 0}, "matched": {"type": "object", "properties": {"markedPaid": {"type": "integer", "minimum": 0}, "partialPayments": {"type": "integer", "minimum": 0}, "applied": {"type": "array", "items": {"$ref": "#/components/schemas/StatementMatch"}}, "suggestions": {"type": "array", "items": {"$ref": "#/components/schemas/StatementSuggestion"}}}, "description": "Credits that settled existing unpaid invoices."}, "imported": {"type": "integer", "minimum": 0, "description": "Invoices created."}, "created": {"type": "array", "items": {"$ref": "#/components/schemas/CreditInvoice"}}, "skipped_duplicate": {"type": "integer", "minimum": 0}, "skippedDuplicates": {"type": "array", "items": {"$ref": "#/components/schemas/StatementCredit"}}, "nonInvoiceable": {"type": "array", "items": {"$ref": "#/components/schemas/StatementCredit"}, "description": "Credits judged not to be revenue (cash deposits, refunds, own transfers)."}, "unclassified": {"type": "array", "items": {"$ref": "#/components/schemas/StatementCredit"}, "description": "Credits left for review; nothing was created."}, "ai_failures": {"type": "integer", "minimum": 0}, "errors": {"type": "array", "items": {"type": "string"}, "description": "Problems with single rows; the other rows were still imported."}, "dry_run": {"type": "boolean"}, "learnedExamples": {"type": "integer", "minimum": 0}, "reclaimed": {"type": "integer", "minimum": 0}, "details": {"type": "object", "additionalProperties": {"type": "array", "items": {"$ref": "#/components/schemas/DetailRow"}}, "description": "The rows behind the counts, by bucket (at most 200 rows per bucket)."}}, "description": "Result of an invoice import from statement credits."}, "InvoiceItem": {"type": "object", "properties": {"id": {"type": ["string", "null"], "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "catalogItemId": {"type": ["string", "null"], "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "name": {"type": "string", "maxLength": 2000, "description": "Required, not blank. First line is the title; more lines allowed."}, "price": {"type": "number", "minimum": -10000000, "maximum": 10000000, "description": "Unit price in the invoice currency; negative for a discount line."}, "units": {"type": "number", "minimum": -1000000, "maximum": 1000000, "description": "Quantity; fractions allowed; negative for a discount or credit line."}, "vatRate": {"type": "number", "minimum": 0, "maximum": 100, "description": "Percent: 0, 2.6, 3.8 or 8.1 (7.7, 2.5, 3.7 for dates before 2024)."}, "discount": {"type": "number", "minimum": 0, "maximum": 100, "description": "Percent off this line."}, "usageCount": {"type": "integer", "minimum": 0, "maximum": 1000000}, "details": {"type": ["object", "null"], "properties": {"type": {"type": "string", "enum": ["HourlyRateDetails"]}, "date": {"type": "string", "description": "Work date. Defaults to the invoice date (catalog items: now)."}, "from": {"type": "string", "maxLength": 5, "minLength": 1, "pattern": "^(?:([01]\\d|2[0-3]):[0-5]\\d)$", "description": "Start, HH:mm."}, "to": {"type": "string", "maxLength": 5, "minLength": 1, "pattern": "^(?:([01]\\d|2[0-3]):[0-5]\\d)$", "description": "End, HH:mm; not before `from`."}}, "required": ["type", "from", "to"]}, "isCreditNoteItem": {"type": "boolean", "description": "Marks a credit-note line (the app uses it for credit-note numbering). Negative `units` or `price` (discount lines) do not need it."}, "unitBasis": {"type": ["object", "null"], "properties": {"type": {"type": "string", "enum": ["preset", "custom"]}, "value": {"type": "string", "maxLength": 20, "minLength": 1, "description": "A preset name for `preset`, a 1-20 character label for `custom`."}}, "required": ["type", "value"], "description": "What `units` counts: {type: preset, value: hour|day|piece|kilometer|kilogram|squareMeter|flatRate} or {type: custom, value: 'm³'}. null = no unit."}}, "required": ["name"]}, "InvoiceItemRecord": {"type": "object", "properties": {"id": {"type": ["string", "null"]}, "catalogItemId": {"type": ["string", "null"]}, "name": {"type": "string", "description": "Required, not blank. First line is the title; more lines allowed."}, "price": {"type": "number", "description": "Unit price in the invoice currency; negative for a discount line."}, "units": {"type": "number", "description": "Quantity; fractions allowed; negative for a discount or credit line."}, "vatRate": {"type": "number", "description": "Percent: 0, 2.6, 3.8 or 8.1 (7.7, 2.5, 3.7 for dates before 2024)."}, "discount": {"type": "number", "description": "Percent off this line."}, "usageCount": {"type": "integer"}, "details": {"type": ["object", "null"], "properties": {"type": {"type": "string", "enum": ["HourlyRateDetails"]}, "date": {"type": "string", "description": "Work date. Defaults to the invoice date (catalog items: now)."}, "from": {"type": "string", "description": "Start, HH:mm."}, "to": {"type": "string", "description": "End, HH:mm; not before `from`."}}}, "isCreditNoteItem": {"type": "boolean", "description": "Marks a credit-note line (the app uses it for credit-note numbering). Negative `units` or `price` (discount lines) do not need it."}, "unitBasis": {"type": ["object", "null"], "properties": {"type": {"type": "string", "enum": ["preset", "custom"]}, "value": {"type": "string", "description": "A preset name for `preset`, a 1-20 character label for `custom`."}}, "description": "What `units` counts: {type: preset, value: hour|day|piece|kilometer|kilogram|squareMeter|flatRate} or {type: custom, value: 'm³'}. null = no unit."}}, "description": "A line of an invoice."}, "InvoiceOverrides": {"type": ["object", "null"], "properties": {"invoice": {"type": ["object", "null"], "properties": {"paymentStatus": {"type": "string", "enum": ["orderConfirmation", "deliveryBill", "creditNote", "normal", "late", "paid"]}, "type": {"type": "string", "enum": ["normal", "quote"]}, "date": {"type": ["string", "null"], "description": "Epoch milliseconds (as the app sends) or ISO 8601."}, "description": {"type": ["string", "null"], "maxLength": 5000}, "advancePayment": {"type": "number", "minimum": 0, "maximum": 100000000}, "items": {"type": ["array", "null"], "items": {"$ref": "#/components/schemas/InvoiceItem"}, "maxItems": 500}, "referenceInvoiceNumber": {"type": ["string", "null"], "maxLength": 64}}}}, "description": "Changes for this document only; not stored on the invoice."}, "InvoiceRecord": {"type": "object", "properties": {"id": {"type": "string"}, "clientRef": {"type": "string", "description": "The client as a path, `users/{uid}/clients/{clientId}`; use `clientId` instead.", "readOnly": true}, "date": {"type": "string", "description": "Invoice date (a date only is fine). Must be in this or last calendar year and at most 92 days ahead; a date outside the current Swiss calendar year also needs `confirmDate: true`."}, "type": {"type": "string", "enum": ["normal", "quote"], "description": "`normal` is an invoice, `quote` a quote."}, "version": {"type": "integer", "description": "The invoice number, like `number`. Send `version` to renumber an invoice."}, "language": {"type": "string", "enum": ["de", "en", "fr", "it"], "description": "Language the app shows the document in. A PDF or email made through the API uses the `locale` you pass to generate or send, by default the account language."}, "currency": {"type": "string", "description": "Must be an ISO 4217 currency code like CHF, EUR or USD."}, "exchangeRate": {"type": ["number", "null"], "description": "CHF -> currency rate: units of `currency` per 1 CHF (about 1.07 for EUR). Non-CHF invoices only; leave it null: when a foreign-currency invoice is paid (app or API) the rate of its latest payment date is stored. A rate sent here is kept."}, "vatEnabled": {"type": "boolean", "description": "false: the invoice has no VAT."}, "vatMode": {"type": "string", "enum": ["additive", "inclusive"], "description": "`additive`: prices are without VAT, which is added on top. `inclusive`: prices already include VAT."}, "isPaid": {"type": "boolean"}, "sent": {"type": "boolean"}, "isArchived": {"type": "boolean"}, "disableRounding": {"type": "boolean", "description": "false rounds the total to 0.05."}, "hideQuotePricing": {"type": "boolean"}, "generationCount": {"type": "integer", "description": "How many times the PDF was generated.", "readOnly": true}, "description": {"type": "string", "description": "Text below the items."}, "headerDescription": {"type": "string", "description": "Text above the items."}, "recurring": {"type": "string", "enum": ["disabled", "monthly", "quarterly", "yearly", "biYearly", "triYearly"], "description": "biYearly = every 6 months, triYearly = every 4 months."}, "recurringDueDate": {"type": ["string", "null"], "description": "When the recurrence stops."}, "recurringAutoSend": {"type": "boolean", "description": "Send each new copy automatically."}, "bankId": {"type": ["string", "null"], "description": "Id from GET /bank-accounts; null picks one by client and currency. The account must be in the invoice currency, or a CHF IBAN for a EUR invoice; GBP, USD and other currencies need a `custom` account in that currency."}, "items": {"type": "array", "items": {"$ref": "#/components/schemas/InvoiceItemRecord"}}, "payments": {"type": "object", "properties": {"proof": {"type": ["object", "null"], "properties": {"path": {"type": "string", "description": "Storage path of the uploaded file."}, "name": {"type": "string"}, "size": {"type": "integer", "description": "Bytes."}, "digest": {"type": "string"}, "url": {"type": ["string", "null"]}, "uploadDate": {"type": ["string", "null"], "description": "Date or date-time."}, "type": {"type": "string", "enum": ["CloudFile"], "description": "Always `CloudFile`; may be omitted."}}}, "items": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": ["string", "null"]}, "methodId": {"type": "string", "description": "Id of a payment method (a `type: payment` category from GET /categories)."}, "amount": {"type": "number", "description": "In the invoice currency; negative for a credit note (negative total)."}, "date": {"type": "string", "description": "When the money arrived; not in the future. Defaults to now."}}}}}}, "sentEmailHistory": {"type": "array", "items": {"type": "object", "properties": {"email": {"type": "string"}, "isTest": {"type": "boolean"}, "date": {"type": "string", "description": "Date or date-time."}, "success": {"type": "boolean"}, "ccEmails": {"type": "array", "items": {"type": "string"}}, "note": {"type": ["string", "null"]}, "invoiceStatus": {"type": "string", "enum": ["quote", "invoice", "reminder", "confirmation", "orderConfirmation", "deliveryBill", "advancePayment"]}}}, "readOnly": true}, "clientId": {"type": ["string", "null"], "readOnly": true, "description": "The client's id. To change the client, send `clientId` in a PATCH."}, "number": {"type": ["integer", "null"], "readOnly": true, "description": "The invoice number, unique per type and Swiss year (the same as `version`)."}, "totals": {"type": "object", "properties": {"subtotal": {"type": "number", "description": "The lines without VAT (with inclusive VAT, the VAT taken out)."}, "vat": {"type": "number", "description": "VAT; 0 when VAT is off on the invoice or for the company."}, "total": {"type": "number", "description": "What the client pays, with the invoice's rounding."}, "paid": {"type": "number", "description": "Sum of the recorded `payments.items`."}, "due": {"type": "number", "description": "`total - paid`, rounded like the invoice; 0 once the invoice is marked paid (`isPaid`), even without a recorded payment. Negative on an unpaid credit note."}}, "required": ["subtotal", "vat", "total", "paid", "due"], "readOnly": true, "description": "Computed like the app: per-line rounding, the company's VAT switch, discounts, payments."}, "dueDate": {"type": ["string", "null"], "format": "date", "description": "Payment due day: `date` plus `invoicePaymentDueInDays` of the invoicing settings (30 when unset, as on the PDF); quotes use `quotePaymentDueInDays` (14 when unset).", "readOnly": true}}, "required": ["id", "clientId", "number", "totals", "dueDate"], "description": "An invoice or quote, with its computed `clientId`, `number`, `totals` and `dueDate`. Read-only fields are set by Magic Heidi and ignored when sent back."}, "InvoicingSettings": {"type": "object", "properties": {"email": {"type": ["string", "null"], "description": "The account email. `GET` only."}, "locale": {"type": ["string", "null"], "description": "App language: de, en, fr or it."}, "company": {"type": "object", "properties": {"name": {"type": "string"}, "street": {"type": "string", "description": "Street name without the number."}, "buildingNumber": {"type": "string"}, "zip": {"type": "string", "description": "CH: 4 digits, 1000-9658."}, "city": {"type": "string"}, "country": {"type": "string", "description": "Must be an ISO 3166-1 alpha-2 country code like CH, DE or FR. Default CH."}, "details": {"type": "string", "description": "'Additional information' on the QR bill."}, "vatNumber": {"type": "string", "description": "e.g. CHE-123.456.789 MWST, or empty."}, "vatEnabled": {"type": "boolean"}, "vatMode": {"type": "string", "enum": ["additive", "inclusive"]}, "vatTaxMethod": {"type": "string", "enum": ["effective", "flat"]}, "banks": {"type": "array", "items": {"$ref": "#/components/schemas/BankAccountRecord"}}}, "description": "Company profile printed on invoices."}, "bankData": {"type": "object", "properties": {"name": {"type": "string"}, "street": {"type": "string", "description": "Street name without the number."}, "buildingNumber": {"type": "string"}, "zip": {"type": "string", "description": "CH: 4 digits, 1000-9658."}, "city": {"type": "string"}, "country": {"type": "string", "description": "Must be an ISO 3166-1 alpha-2 country code like CH, DE or FR. Default CH."}, "details": {"type": "string", "description": "'Additional information' on the QR bill."}, "vatNumber": {"type": "string", "description": "e.g. CHE-123.456.789 MWST, or empty."}, "vatEnabled": {"type": "boolean"}, "vatMode": {"type": "string", "enum": ["additive", "inclusive"]}, "vatTaxMethod": {"type": "string", "enum": ["effective", "flat"]}, "banks": {"type": "array", "items": {"$ref": "#/components/schemas/BankAccountRecord"}}, "iban": {"type": "string"}, "secondaryIban": {"type": "string"}, "address": {"type": "string"}, "accountCHF": {"type": "string"}, "accountEUR": {"type": "string"}, "accountGBP": {"type": "string"}, "accountUSD": {"type": "string"}, "accountAUD": {"type": "string"}, "accountNZD": {"type": "string"}, "accountNOK": {"type": "string"}, "accountCZK": {"type": "string"}}, "description": "An older copy of part of `company`; use `company`.", "deprecated": true}, "settings": {"type": "object", "properties": {"lastUsedVatRate": {"type": ["number", "null"]}, "lastUsedInvoiceType": {"type": "string", "enum": ["normal", "quote"]}, "lastUsedInvoiceItemHourlyRate": {"type": "number"}, "lastUsedAdvancePaymentPercentage": {"type": "number"}, "lastUsedAdvancePaymentNote": {"type": "string"}, "allowCustomVatRate": {"type": "boolean"}, "invoiceShowQuoteSignatureFields": {"type": "boolean"}, "invoiceShowPaymentDueDate": {"type": "boolean"}, "invoiceQRAccountName": {"type": "string", "description": "Creditor name on the QR bill (QR limit 70)."}, "invoiceDefaultDescription": {"type": "string"}, "invoiceDefaultQuoteDescription": {"type": "string"}, "invoiceReplyToEmail": {"type": "string"}, "invoicePaymentReference": {"type": "string", "description": "QR bill additional message (QR limit 140)."}, "invoicePaymentDueInDays": {"type": "integer"}, "quotePaymentDueInDays": {"type": "integer"}, "flatVatTaxRate": {"type": "number", "description": "ESTV flat tax rate in percent."}, "countToggleExpenseToPaid": {"type": "integer"}}, "description": "Invoice defaults."}}, "required": ["locale", "company", "bankData", "settings"]}, "InvoicingSettingsPatch": {"type": "object", "properties": {"locale": {"type": "string", "enum": ["de", "en", "fr", "it"]}, "company": {"type": "object", "properties": {"name": {"type": "string", "maxLength": 300}, "street": {"type": "string", "maxLength": 100, "description": "Street name without the number."}, "buildingNumber": {"type": "string", "maxLength": 16}, "zip": {"type": "string", "maxLength": 16, "description": "CH: 4 digits, 1000-9658."}, "city": {"type": "string", "maxLength": 100}, "country": {"type": "string", "pattern": "^[A-Z]{2}$", "description": "Must be an ISO 3166-1 alpha-2 country code like CH, DE or FR. Default CH."}, "details": {"type": "string", "maxLength": 1000, "description": "'Additional information' on the QR bill."}, "vatNumber": {"type": "string", "maxLength": 40, "description": "e.g. CHE-123.456.789 MWST, or empty."}, "vatEnabled": {"type": "boolean"}, "vatMode": {"type": "string", "enum": ["additive", "inclusive"]}, "vatTaxMethod": {"type": "string", "enum": ["effective", "flat"]}, "banks": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string", "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "type": {"type": "string", "enum": ["iban", "custom"]}, "name": {"type": "string", "maxLength": 100, "minLength": 1, "description": "Label shown in the app."}, "currency": {"type": "string", "pattern": "^[A-Z]{3}$", "description": "Must be an ISO 4217 currency code like CHF, EUR or USD. IBAN accounts: CHF or EUR (a CHF IBAN also covers EUR invoices); any other currency needs type `custom`."}, "iban": {"type": "string", "maxLength": 64, "description": "type iban: a valid IBAN; spaces are removed."}, "data": {"type": "string", "maxLength": 2000, "description": "type custom: the account details as text."}}, "required": ["id", "type", "name", "currency"]}, "maxItems": 50}}}, "bankData": {"type": "object", "properties": {"name": {"type": "string", "maxLength": 300}, "street": {"type": "string", "maxLength": 100, "description": "Street name without the number."}, "buildingNumber": {"type": "string", "maxLength": 16}, "zip": {"type": "string", "maxLength": 16, "description": "CH: 4 digits, 1000-9658."}, "city": {"type": "string", "maxLength": 100}, "country": {"type": "string", "pattern": "^[A-Z]{2}$", "description": "Must be an ISO 3166-1 alpha-2 country code like CH, DE or FR. Default CH."}, "details": {"type": "string", "maxLength": 1000, "description": "'Additional information' on the QR bill."}, "vatNumber": {"type": "string", "maxLength": 40, "description": "e.g. CHE-123.456.789 MWST, or empty."}, "vatEnabled": {"type": "boolean"}, "vatMode": {"type": "string", "enum": ["additive", "inclusive"]}, "vatTaxMethod": {"type": "string", "enum": ["effective", "flat"]}, "banks": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string", "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "type": {"type": "string", "enum": ["iban", "custom"]}, "name": {"type": "string", "maxLength": 100, "minLength": 1, "description": "Label shown in the app."}, "currency": {"type": "string", "pattern": "^[A-Z]{3}$", "description": "Must be an ISO 4217 currency code like CHF, EUR or USD. IBAN accounts: CHF or EUR (a CHF IBAN also covers EUR invoices); any other currency needs type `custom`."}, "iban": {"type": "string", "maxLength": 64, "description": "type iban: a valid IBAN; spaces are removed."}, "data": {"type": "string", "maxLength": 2000, "description": "type custom: the account details as text."}}, "required": ["id", "type", "name", "currency"]}, "maxItems": 50}, "iban": {"type": "string", "maxLength": 64}, "secondaryIban": {"type": "string", "maxLength": 64}, "address": {"type": "string", "maxLength": 200}, "accountCHF": {"type": "string", "maxLength": 2000}, "accountEUR": {"type": "string", "maxLength": 2000}, "accountGBP": {"type": "string", "maxLength": 2000}, "accountUSD": {"type": "string", "maxLength": 2000}, "accountAUD": {"type": "string", "maxLength": 2000}, "accountNZD": {"type": "string", "maxLength": 2000}, "accountNOK": {"type": "string", "maxLength": 2000}, "accountCZK": {"type": "string", "maxLength": 2000}}, "description": "Deprecated; use `company`.", "deprecated": true}, "settings": {"type": "object", "properties": {"notificationToken": {"type": ["string", "null"], "maxLength": 4096}, "lastUsedVatRate": {"type": ["number", "null"], "minimum": 0, "maximum": 100}, "lastUsedInvoiceType": {"type": "string", "enum": ["normal", "quote"]}, "lastUsedInvoiceItemHourlyRate": {"type": "number", "minimum": 0, "maximum": 10000000}, "lastUsedAdvancePaymentPercentage": {"type": "number", "minimum": 0, "maximum": 100}, "lastUsedAdvancePaymentNote": {"type": "string", "maxLength": 5000}, "allowCustomVatRate": {"type": "boolean"}, "invoiceShowQuoteSignatureFields": {"type": "boolean"}, "invoiceShowPaymentDueDate": {"type": "boolean"}, "invoiceQRAccountName": {"type": "string", "maxLength": 70, "description": "Creditor name on the QR bill (QR limit 70)."}, "invoiceDefaultDescription": {"type": "string", "maxLength": 5000}, "invoiceDefaultQuoteDescription": {"type": "string", "maxLength": 5000}, "invoiceReplyToEmail": {"type": "string", "maxLength": 254, "format": "email"}, "invoicePaymentReference": {"type": "string", "maxLength": 140, "description": "QR bill additional message (QR limit 140)."}, "invoicePaymentDueInDays": {"type": "integer", "minimum": 0, "maximum": 365}, "quotePaymentDueInDays": {"type": "integer", "minimum": 0, "maximum": 365}, "flatVatTaxRate": {"type": "number", "minimum": 0, "maximum": 100, "description": "ESTV flat tax rate in percent."}, "countToggleExpenseToPaid": {"type": "integer", "minimum": 0, "maximum": 1000000}}}}}, "Letter": {"type": "object", "properties": {"id": {"type": "string"}, "invoiceId": {"type": "string", "description": "The invoice that was sent."}, "status": {"type": "string", "enum": ["sending", "processing", "dispatched", "delivered", "failed", "undeliverable", "needs_review", "unpaid"], "description": "`processing`: the PDF was accepted and is being checked; `dispatched`: handed to the post; then `delivered`, or `failed` / `undeliverable` / `needs_review`. `unpaid`: the letter balance could not be checked and nothing was sent; retry with the same Idempotency-Key."}, "requestedAt": {"type": ["string", "null"], "format": "date-time"}, "updatedAt": {"type": ["string", "null"], "format": "date-time"}, "dispatchedAt": {"type": ["string", "null"], "format": "date-time"}, "deliveredAt": {"type": ["string", "null"], "format": "date-time"}, "failedAt": {"type": ["string", "null"], "format": "date-time"}, "undeliverableAt": {"type": ["string", "null"], "format": "date-time"}, "recipientAddress": {"type": ["string", "null"], "description": "As read from the PDF."}, "recipientCountry": {"type": ["string", "null"]}, "sendTo": {"anyOf": [{"$ref": "#/components/schemas/LetterAddress"}, {"type": "null"}]}, "error": {"type": ["object", "null"]}, "invoiceSnapshot": {"type": ["object", "null"], "description": "The invoice's number (`version`), date, currency and type (`normal` or `quote`) when it was sent."}, "environment": {"type": "string", "description": "The Pingen environment: `production`, or `staging` for a test letter that is not posted."}}, "description": "An invoice sent by post, and where it is in delivery."}, "LetterAddress": {"type": "object", "properties": {"name": {"type": "string", "maxLength": 120, "minLength": 1}, "street": {"type": "string", "maxLength": 120, "minLength": 1}, "buildingNumber": {"type": "string", "maxLength": 20, "description": "Optional if included in street."}, "zip": {"type": "string", "maxLength": 20, "minLength": 1}, "city": {"type": "string", "maxLength": 120, "minLength": 1}, "country": {"type": "string", "pattern": "^[A-Z]{2}$", "description": "Must be an ISO 3166-1 alpha-2 country code like CH, DE or FR."}}, "required": ["name", "street", "zip", "city", "country"], "description": "Alternative postal recipient. Adds an address cover sheet and blank reverse before the unchanged invoice. Omit or send null to use the address printed on the invoice."}, "LetterSubmission": {"type": "object", "properties": {"id": {"type": "string"}, "status": {"type": "string", "enum": ["sending", "processing", "dispatched", "delivered", "failed", "undeliverable", "needs_review", "unpaid"], "description": "`processing`: the PDF was accepted and is being checked; `dispatched`: handed to the post; then `delivered`, or `failed` / `undeliverable` / `needs_review`. `unpaid`: the letter balance could not be checked and nothing was sent; retry with the same Idempotency-Key."}}, "required": ["id", "status"], "description": "The letter that was accepted. Get the letter for its delivery details.", "additionalProperties": false}, "LinkEmailRequest": {"type": "object", "properties": {"email": {"type": "string", "format": "email", "description": "The address to link."}, "locale": {"type": "string", "enum": ["de", "en", "fr", "it"], "description": "Language of the code email. Defaults to the account's language; an account without one, or any other value, gets English."}}, "required": ["email"]}, "LinkedEmail": {"type": "object", "properties": {"email": {"type": "string", "format": "email", "description": "The address, lowercase."}, "createdAt": {"type": "string", "format": "date-time", "description": "When the address was confirmed."}}, "required": ["email", "createdAt"], "description": "An address the account forwards receipts from."}, "RecordPayment": {"type": "object", "properties": {"id": {"type": ["string", "null"], "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$"}, "amount": {"type": "number", "minimum": -100000000, "maximum": 100000000, "description": "Not 0. Positive, except on a credit note (an invoice with a negative total): there the refund is negative, e.g. -120 for a credit note of -120."}, "methodId": {"type": ["string", "null"], "maxLength": 128, "minLength": 1, "pattern": "^(?:[^/\\s]+)$", "description": "Payment method id (a `type: payment` category from GET /categories)."}, "methodName": {"type": ["string", "null"], "maxLength": 100, "minLength": 1, "description": "Payment method name; created if missing."}, "date": {"type": ["string", "null"], "description": "Defaults to now; not in the future."}, "markPaid": {"type": ["boolean", "null"], "description": "Omit to mark the invoice paid only once the payments cover its total (like the app); true/false to decide explicitly."}}, "required": ["amount"], "anyOf": [{"required": ["methodId"]}, {"required": ["methodName"]}]}, "SaveClientRequest": {"description": "The client wrapped in `client`, or the client object itself.", "anyOf": [{"type": "object", "properties": {"client": {"$ref": "#/components/schemas/Client"}, "upsert": {"type": "boolean", "default": true, "description": "false: always create, never match an existing client by name or email."}}, "required": ["client"]}, {"allOf": [{"$ref": "#/components/schemas/Client"}, {"type": "object", "properties": {"upsert": {"type": "boolean", "default": true, "description": "false: always create, never match an existing client by name or email."}}}]}]}, "ScanAndCreateResult": {"type": "object", "properties": {"scan": {"$ref": "#/components/schemas/ExpenseScan"}, "expense": {"$ref": "#/components/schemas/ExpenseRecord"}, "scanLocale": {"type": "string", "description": "Language the receipt was read in."}}, "required": ["scan", "expense", "scanLocale"]}, "SendOptions": {"type": "object", "properties": {"toEmail": {"type": ["string", "null"], "maxLength": 254, "format": "email", "description": "Defaults to the client's email."}, "ccEmails": {"type": ["array", "null"], "items": {"type": "string", "maxLength": 254, "minLength": 1, "format": "email"}, "maxItems": 20, "description": "Defaults to the client's CC addresses when `toEmail` is omitted."}, "userEmail": {"type": ["string", "null"], "maxLength": 254, "format": "email", "description": "Reply-to address when the invoicing settings have no `invoiceReplyToEmail`. Defaults to the account email."}, "locale": {"type": ["string", "null"], "enum": ["de", "en", "fr", "it", null]}, "testMode": {"type": "boolean", "description": "true: use sample company and bank details instead of the account's, to try things out. The email is still sent to `toEmail`."}, "invoiceStatus": {"type": ["string", "null"], "enum": ["invoice", "quote", "offer", "reminder", "confirmation", "orderConfirmation", "deliveryBill", "advancePayment", null], "description": "Label for the `sentEmailHistory` entry only; it does not change the email. Use `overrides` for that."}, "overrides": {"$ref": "#/components/schemas/InvoiceOverrides"}}}, "SendResult": {"type": "object", "properties": {"sent": {"type": "boolean", "const": true, "description": "The mail service accepted the email."}, "toEmail": {"type": "string", "description": "The recipient: the one sent, else the client's email."}, "ccEmails": {"type": "array", "items": {"type": "string"}, "description": "The CC recipients: the ones sent, else the client's CC addresses (only when `toEmail` was omitted)."}}, "required": ["sent", "toEmail", "ccEmails"], "description": "Who the invoice email went to."}, "SpreadsheetImportResult": {"type": "object", "properties": {"success": {"type": "boolean", "const": true}, "total_rows": {"type": "integer", "minimum": 0}, "dropped_invalid": {"type": "integer", "minimum": 0, "description": "Rows missing the minimum fields."}, "skipped_duplicate": {"type": "integer", "minimum": 0, "description": "Rows that already exist."}, "skipped_by_ai": {"type": "integer", "minimum": 0, "description": "Rows judged not to belong, e.g. not a client."}, "ai_failures": {"type": "integer", "minimum": 0}, "imported": {"type": "integer", "minimum": 0}, "errors": {"type": "array", "items": {"type": "string"}, "description": "Problems with single rows; the other rows were still imported."}, "dry_run": {"type": "boolean"}, "structure_source": {"type": ["string", "null"], "description": "How the columns were recognised."}, "details": {"type": "object", "additionalProperties": {"type": "array", "items": {"$ref": "#/components/schemas/DetailRow"}}, "description": "The rows behind the counts, by bucket (at most 200 rows per bucket)."}}, "description": "Result of a client or invoice item import."}, "StatementCredit": {"type": "object", "properties": {"date": {"type": "string", "format": "date", "description": "Calendar day, YYYY-MM-DD."}, "amount": {"type": "number"}, "currency": {"type": "string"}, "description": {"type": ["string", "null"]}, "counterparty": {"type": ["string", "null"]}, "importRef": {"type": ["string", "null"], "description": "Fingerprint of the bank transaction."}, "reason": {"type": "string", "description": "`nonInvoiceable`: why it is not revenue."}, "aiReason": {"type": "string", "description": "`unclassified`: why it was left for review."}, "suggestedClientName": {"type": ["string", "null"]}, "suggestedItemName": {"type": ["string", "null"]}, "layer": {"type": "string", "description": "`skippedDuplicates`: which duplicate check matched."}}, "description": "One incoming bank credit."}, "StatementImportResult": {"type": "object", "properties": {"dryRun": {"type": "boolean"}, "summary": {"type": "object", "properties": {"files": {"type": "integer", "minimum": 0}, "expensesImported": {"type": "integer", "minimum": 0}, "invoicesCreated": {"type": "integer", "minimum": 0}, "markedPaid": {"type": "integer", "minimum": 0}, "duplicatesSkipped": {"type": "integer", "minimum": 0}, "nonInvoiceable": {"type": "integer", "minimum": 0}, "unclassified": {"type": "integer", "minimum": 0}}}, "expenses": {"$ref": "#/components/schemas/ExpenseImportResult", "description": "The expense half; `{}` when it was off or failed."}, "invoices": {"$ref": "#/components/schemas/InvoiceImportResult", "description": "The invoice half; `{}` when it was off or failed."}, "parseErrors": {"type": "array", "items": {"type": "object", "properties": {"file": {"type": "string"}, "phase": {"type": "string"}, "error": {"type": "string"}}}, "description": "Files (or halves) that could not be imported, with the reason."}}, "required": ["dryRun", "summary", "expenses", "invoices", "parseErrors"]}, "StatementMatch": {"type": "object", "properties": {"invoiceId": {"type": "string"}, "hash": {"type": ["string", "null"], "description": "The invoice reference, e.g. NA011."}, "clientName": {"type": ["string", "null"]}, "total": {"type": ["number", "null"]}, "amount": {"type": "number"}, "action": {"type": "string", "enum": ["full", "partial"]}, "tier": {"type": "string", "enum": ["high", "medium", "partial"]}, "reason": {"type": "string"}, "transactionDate": {"type": ["string", "null"], "format": "date", "description": "Calendar day, YYYY-MM-DD."}, "markedPaid": {"type": "boolean"}, "alreadyRecorded": {"type": "boolean", "description": "The payment was recorded before (the statement was imported again)."}}, "description": "A payment applied to an invoice."}, "StatementMatchResult": {"type": "object", "properties": {"summary": {"type": "object", "properties": {"transactions": {"type": "integer", "minimum": 0}, "invoicesScanned": {"type": "integer", "minimum": 0}, "markedPaid": {"type": "integer", "minimum": 0}, "partialPayments": {"type": "integer", "minimum": 0}, "suggestions": {"type": "integer", "minimum": 0}, "unmatched": {"type": "integer", "minimum": 0}}}, "applied": {"type": "array", "items": {"$ref": "#/components/schemas/StatementMatch"}}, "suggestions": {"type": "array", "items": {"$ref": "#/components/schemas/StatementSuggestion"}}, "unmatched": {"type": "array", "items": {"type": "object", "properties": {"date": {"type": ["string", "null"], "format": "date", "description": "Calendar day, YYYY-MM-DD."}, "amount": {"type": ["number", "null"]}, "description": {"type": ["string", "null"]}, "creditUnknown": {"type": ["boolean", "null"]}}}}, "parseErrors": {"type": "array", "items": {"type": "object", "properties": {"file": {"type": "string"}, "error": {"type": "string"}}}}}, "required": ["summary", "applied", "suggestions", "unmatched", "parseErrors"]}, "StatementSuggestion": {"type": "object", "properties": {"invoiceId": {"type": "string"}, "hash": {"type": ["string", "null"]}, "clientName": {"type": ["string", "null"]}, "total": {"type": ["number", "null"]}, "amount": {"type": "number"}, "tier": {"type": "string"}, "reason": {"type": "string"}, "transactionDate": {"type": ["string", "null"], "format": "date", "description": "Calendar day, YYYY-MM-DD."}}, "description": "A possible match that was not applied; check it and record the payment by hand."}, "Subscription": {"type": "object", "properties": {"subscribed": {"type": "boolean", "description": "Whether Magic Heidi Pro is active now."}, "platform": {"type": ["string", "null"], "description": "Where it was bought: web, ios, android, macos or amazon."}, "productIdentifier": {"type": ["string", "null"]}, "purchaseDate": {"type": ["string", "null"], "format": "date-time", "description": "In Swiss time with its offset, e.g. 2026-03-01T00:00:00+01:00."}, "expiresDate": {"type": ["string", "null"], "format": "date-time", "description": "null for a lifetime subscription (or none)."}, "entitlement": {"type": ["string", "null"]}, "email": {"type": ["string", "null"]}}, "required": ["subscribed", "platform", "productIdentifier", "purchaseDate", "expiresDate", "entitlement"]}, "SuccessEnvelope": {"type": "object", "properties": {"success": {"type": "boolean", "const": true}, "data": {}, "warnings": {"type": "array", "items": {"$ref": "#/components/schemas/Warning"}, "description": "Writes only, and only when there is something to report: parts of the request that were ignored. The write itself succeeded."}}, "required": ["success"], "example": {"success": true, "data": {}}}, "UpdateBankAccountRequest": {"description": "The account, or the account wrapped in `bankAccount`.", "anyOf": [{"$ref": "#/components/schemas/BankAccountPatch"}, {"type": "object", "properties": {"bankAccount": {"$ref": "#/components/schemas/BankAccountPatch"}}, "required": ["bankAccount"]}]}, "ValidationError": {"type": "object", "description": "Returned with HTTP 400 when a write fails validation. Nothing is stored, and every problem is reported at once, one entry per field.", "properties": {"success": {"type": "boolean", "const": false}, "error": {"type": "string", "description": "Human-readable summary."}, "code": {"type": "string", "description": "`validation_failed`; `invalid_request` when the body is no JSON object."}, "details": {"type": "object", "properties": {"code": {"type": "string", "const": "validation_failed", "description": "Same as the top-level `code`."}, "errors": {"type": "array", "items": {"type": "object", "properties": {"field": {"type": "string", "description": "JSON path, e.g. `invoice.items[2].vatRate`."}, "code": {"type": "string", "enum": ["required", "null_not_allowed", "invalid_type", "wrong_type", "invalid_format", "invalid_enum", "too_long", "too_short", "out_of_range", "implausible_date", "date_confirmation_required", "not_found", "invalid_reference", "not_allowed", "duplicate", "read_only", "wrong_sign"], "description": "Machine-readable reason."}, "message": {"type": "string", "description": "What is wrong and what to send instead."}, "allowed": {"type": "array", "description": "The accepted values, when the field takes one of a fixed set."}, "min": {"description": "Lowest accepted value, length or date."}, "max": {"description": "Highest accepted value, length or date."}, "suggested": {"description": "A value that would be accepted, e.g. the next free invoice number."}}, "required": ["field", "code", "message"]}}}}}, "example": {"success": false, "error": "Invalid request. invoice.date: invoice date 2025-07-11 is in 2025, not the current year 2026. ... (+1 more; see details.errors)", "code": "validation_failed", "details": {"code": "validation_failed", "errors": [{"field": "invoice.date", "code": "date_confirmation_required", "message": "invoice date 2025-07-11 is in 2025, not the current year 2026. If that is intended (e.g. last year's work invoiced late), confirm with the user and resend with `confirmDate: true`; otherwise fix the year.", "year": 2025, "currentYear": 2026}, {"field": "invoice.items[0].vatRate", "code": "invalid_enum", "message": "7.7 is not a Swiss VAT rate; use one of 0, 2.6, 3.8, 8.1. Other rates are only accepted when the user enabled custom VAT rates in the app settings.", "allowed": [0, 2.6, 3.8, 8.1]}]}}}, "VatNumberResult": {"type": "object", "properties": {"uid": {"type": "string"}, "vatRegistered": {"type": "boolean"}, "vatNumber": {"type": ["string", "null"], "description": "`CHE-XXX.XXX.XXX MWST` when registered, else null."}}, "required": ["uid", "vatRegistered", "vatNumber"]}, "VerifyLinkedEmailRequest": {"type": "object", "properties": {"email": {"type": "string", "format": "email", "description": "The address the code was emailed to."}, "code": {"type": "string", "minLength": 1, "maxLength": 20, "description": "The 5-character code from the email; case and spaces are ignored."}}, "required": ["email", "code"]}, "Warning": {"type": "object", "description": "Something a write ignored instead of storing it.", "properties": {"field": {"type": "string", "description": "JSON path, e.g. `invoice.items[0].vat_rate`."}, "code": {"type": "string", "enum": ["unknown_field", "read_only"], "description": "`unknown_field`: not a field of this object, so it was not stored. `read_only`: a computed field (e.g. an invoice's `totals`) sent with another value than it has."}, "message": {"type": "string"}, "suggested": {"type": "string", "description": "The field that was probably meant, e.g. `vatRate` for `vat_rate`."}}, "required": ["field", "code", "message"], "example": {"field": "invoice.items[0].vat_rate", "code": "unknown_field", "message": "unknown field, ignored (not stored); did you mean `vatRate`?", "suggested": "vatRate"}}}, "responses": {"Unauthorized": {"description": "Missing or invalid credentials", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"missingOrInvalidApiKey": {"summary": "Missing or invalid API key", "value": {"success": false, "error": "Missing or invalid API key: send it as `X-API-Key` or `Authorization: Bearer`", "code": "unauthorized"}}}}}}, "BadRequest": {"description": "Invalid request body; every problem is listed in `details.errors`", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ValidationError"}, "examples": {"validationError": {"summary": "Validation error", "value": {"success": false, "error": "Invalid request. invoice.date: invoice date 2025-07-11 is in 2025, not the current year 2026. ... (+1 more; see details.errors)", "code": "validation_failed", "details": {"code": "validation_failed", "errors": [{"field": "invoice.date", "code": "date_confirmation_required", "message": "invoice date 2025-07-11 is in 2025, not the current year 2026. If that is intended (e.g. last year's work invoiced late), confirm with the user and resend with `confirmDate: true`; otherwise fix the year.", "year": 2025, "currentYear": 2026}, {"field": "invoice.items[0].vatRate", "code": "invalid_enum", "message": "7.7 is not a Swiss VAT rate; use one of 0, 2.6, 3.8, 8.1. Other rates are only accepted when the user enabled custom VAT rates in the app settings.", "allowed": [0, 2.6, 3.8, 8.1]}]}}}, "invalidJson": {"summary": "Body is not JSON", "value": {"success": false, "error": "Request body must be JSON", "code": "invalid_request"}}}}}}, "InvalidQuery": {"description": "Invalid query parameter. An unknown parameter is named in `details.rejected`, next to the accepted ones in `details.allowed`; a bad filter value has no `details`.", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"unknownParameter": {"summary": "Unknown query parameter", "value": {"success": false, "error": "Unsupported query parameter(s) on this list endpoint.", "code": "invalid_query", "details": {"rejected": ["sort"], "allowed": ["clientId", "cursor", "limit", "status", "type", "year"]}}}, "invalidFilter": {"summary": "Invalid filter value", "value": {"success": false, "error": "Invalid `year`. Use a 4-digit integer.", "code": "invalid_query"}}, "invalidCursor": {"summary": "Cursor not from a previous page", "value": {"success": false, "error": "Invalid `cursor`. Send the `nextCursor` of the previous page unchanged.", "code": "invalid_query"}}}}}}, "NotFound": {"description": "Not found", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"notFound": {"summary": "Not found", "value": {"success": false, "error": "Document not found", "code": "not_found"}}}}}}, "Conflict": {"description": "A document with this `id` already exists (`code: already_exists`)", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"alreadyExists": {"summary": "Duplicate id", "value": {"success": false, "error": "Document 'abc123' already exists", "code": "already_exists"}}}}}}, "RateLimited": {"description": "Too many requests: at most 300 per minute per account over the whole API. Wait `Retry-After` seconds.", "headers": {"Retry-After": {"description": "Seconds to wait before retrying.", "schema": {"type": "integer", "minimum": 1}, "example": 23}}, "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ErrorEnvelope"}, "examples": {"accountLimit": {"summary": "Account limit reached", "value": {"success": false, "error": "Too many requests: at most 300 requests per minute per account. Retry in 23 seconds.", "code": "rate_limited", "details": {"limit": "300/minute", "scope": "account", "retryAfter": 23}}}}}}}}}}