# Tasur Developer Docs > Developer documentation for Tasur, the AGPLv3 self-hosted, API-first accounting platform. # Getting started # Getting started Tasur is a FastAPI application backed by Postgres, with a server-rendered Jinja/HTMX frontend. There is no JavaScript SPA build step — the engine (`saebooks`) serves the JSON API, and a separate thin web process (`saebooks-web`) renders HTML by proxying the same API endpoints. ## What it is, in one paragraph Tasur is a self-hosted accounting platform aimed at Australian SMEs. It runs as a Docker stack on hardware you control, stores its data in a Postgres database you back up, and is licensed under the GNU AGPLv3. The community edition is fully featured for an SME running a single set of books; the enterprise edition adds operator tooling for accountants and bookkeepers managing many tenants. ## Prerequisites - **Docker 24+** with `docker compose` v2 - **Postgres 15+** — the bundled compose ships Postgres 16-alpine; you can also point at an existing cluster - **A reverse proxy** for TLS termination — Caddy works well; the reference deployment fronts the app with Caddy on a public hostname - **Python 3.12+** if you intend to develop against the codebase outside the container (most contributors don't bother — the compose setup is the dev environment) ## Editions Tasur ships in a single binary; the **edition** gates features at runtime. The Community edition is fully functional for a single-tenant SME out of the box. | Edition | Description | | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `community` | AGPLv3, all SME features. The default — no licence key needed. | | `offline` | Community + multi-currency, inventory, projects/budgets, asset register v2, granular permissions, themes, SMTP relay. Perpetual USB-bound licence. | | `business` | Offline + multi-company (up to 2), AU bank feeds, ABR lookup, Stripe + Paperless integrations. Subscription. | | `pro` | Business + international lookups, ATO SBR e-lodgement, QBO import, SQL tool, scheduled backups, audit snapshots. Subscription. | | `enterprise` | Pro + per-company SISS bank-feed credentials. Subscription + setup fee. Support SLA is contractual. | Set `SAEBOOKS_EDITION=community` (default) or the appropriate tier in the container environment. Editions form a strict superset: every tier includes all features of every tier below it. The licence resolver in `services/licence/` sets the edition at boot from a USB Ed25519 licence (Offline) or a portal JWT (Business / Pro / Enterprise), falling back to `community` when nothing is present. Full detail in [Operations → Deployment](../ops/deployment/). ## Where things live - **`saebooks/`** — the app package (api, services, models, routers, middleware, seed, cli, mcp) - **`alembic/versions/`** — migrations (at the project root, not inside the package) - **`saebooks/services/integrations/`** — external connectors (ATO prefill, Paperless, Stripe, etc.) - **`tests/`** — full test tree, see [Testing](../contributing/testing/) - **This site** is built from a separate docs repository, `saebooks-dev`, and its API and configuration reference pages are generated from the running engine on every build ## Where to next - [Quick start](quickstart/) — get a working dev instance in five minutes. - [Architecture](architecture/) — top-level diagram and the reasoning behind it. - [API conventions](../api/conventions/) — once you have it running, this is where to look first. # Architecture Tasur is built around a clean boundary: the **API is the product**, and everything else — the web UI, document vault, accounting-package sync, ATO lodgement relay, licensing server — is a service orbiting it. This is not a cosmetic distinction. The API is the AGPLv3 licensed artifact. Every service connects to it over HTTP, the same way a third-party integration would. No service reaches into the API's Postgres schema directly. ## The orbit graph TB subgraph "On-prem (customer's server)" API\["saebooks-api\ FastAPI · SQLAlchemy · Postgres\ port 8042 (REST) · 50051 (gRPC)"\] WEB\["saebooks-web\ Jinja2 · HTMX\ port 8080"\] PG\[("Postgres 16 - RLS")\] API --- PG WEB -->|"REST calls"| API end subgraph "SAE Engineering services" LICENSE\["license.saebooks.com.au\ Ed25519 JWT · Stripe"\] LODGE\["lodge.saebooks.com.au\ ATO SBR relay · STP · BAS"\] FEEDS\["feeds.saebooks.com.au\ CDR bank-feed relay\ (SISS Data Services)"\] MARKETING\["tasur.io · saebooks.com.au\ marketing · Stripe Checkout"\] end subgraph "Third-party services (customer-operated)" SYNC\["saebooks-sync\ Xero / MYOB / QBO\ bidirectional adapter"\] VAULT\["saebooks-vault\ invoice attachment store"\] DISCOURSE\["forum.tasur.io\ forum · DiscourseConnect SSO"\] end API -->|"licence check"| LICENSE API -->|"lodge STP/BAS"| LODGE API -->|"bank feed pull"| FEEDS SYNC -->|"REST"| API VAULT -->|"REST"| API WEB -->|"DiscourseConnect"| DISCOURSE ## On-prem components **`saebooks-api`** — the ledger. FastAPI with async SQLAlchemy 2.x on Postgres. Every accounting operation goes through the REST API. No side-channel writes. Runs on port 8042. **`saebooks-web`** — the browser UI. FastAPI + Jinja2 + HTMX. No JavaScript build step (Tailwind CSS is pre-compiled at image build time). Holds a signed session cookie (itsdangerous) that stores the API bearer token. Proxies all data operations through `saebooks-api`. Runs on port 8080 in production; 8043 in local dev. **Postgres** — system of record. Row-level security on every domain table, keyed on `tenant_id`. The current tenant is bound per-request via `SET LOCAL app.current_tenant = '...'`. Cross-tenant access is an explicit, audited code path — not a query-parameter. ## SAE Engineering relays These run on SAE Engineering's infrastructure. Customer installs call out to them; SAE Engineering holds zero customer accounting data. **license.saebooks.com.au** — Ed25519 JWT licence minting. Stripe Checkout webhook → issue trial or paid licence → email to customer. The JWT the customer pastes into their `.env` is verified locally by the API binary (no network call on every request — only a once-daily refresh). **lodge.saebooks.com.au** — ATO SBR relay. Signs and forwards STP/BAS/TPAR/SuperStream envelopes through SAE Engineering's Machine Credential. Customer never touches the credential. SBR lodgement is a Pro+ feature; the lodge-server verifies the licence JWT before forwarding. **feeds.saebooks.com.au** — CDR bank-feed relay. Proxies through SAE Engineering's SISS Data Services (ACSISS) agreement. Customers bring their bank consent; SAE Engineering holds the data-recipient credential. Enterprise feature. **tasur.io and saebooks.com.au**: marketing sites, downloads and Stripe Checkout. Not part of the self-hosted stack. ## Third-party services **saebooks-sync** — bidirectional accounting-package sync (Xero, MYOB, QBO). Not yet shipped. See [Sync overview](../../guides/accounting-sync/). **saebooks-vault** — invoice attachment and document store. Postgres metadata + blob store, separate service. Planned, not yet shipped. **Discourse**: community forum at `forum.tasur.io` (also reachable as `discourse.saebooks.com.au`). Discourse is the DiscourseConnect *identity provider* and Tasur is the *consumer*: the web process's `/auth/discourse/login` redirects to Discourse's `/session/sso_provider`, Discourse authenticates the user, and Tasur consumes the signed identity payload on return. See [DiscourseConnect](../../identity/discourse-connect/). ## Request path (browser to data) ```text Browser → Caddy / reverse proxy (TLS termination) → saebooks-web :8080 (session auth, Jinja render, CSRF) → saebooks-api :8042 (JWT auth, business logic) → Postgres :5432 (RLS-enforced query) ``` State-changing requests carry a CSRF token (double-submit cookie pattern). Origin/Referer enforcement runs before CSRF. ## Multi-tenancy model Every domain table carries `tenant_id UUID NOT NULL`. Postgres RLS policies enforce per-tenant visibility. Each install is single-tenant by default; Enterprise licences enable multi-tenant operator tooling. The discipline holds even on single-tenant installs. No global queries. Every insert asserts `tenant_id`. This is what makes a future cloud-hosted pivot a deployment change rather than a rewrite. See [Tenancy & RLS](../../ops/tenancy/) for the implementation detail. ## Design philosophy - **The API is the product surface.** The OpenAPI spec at `/openapi.json` is the contract. If it's not in the spec, it doesn't exist. - **Stateless app servers.** All state lives in Postgres. The app container is disposable — `docker compose up -d --build` and the new container picks up exactly where the old one left off. - **External services called by config URL.** `LICENSE_SERVER_URL`, `LODGE_SERVER_URL`, `FEEDS_SERVER_URL` default to the SAE Engineering endpoints but can be overridden. An air-gapped install can point at its own relay. - **No vendor lock-in.** Your data is in Postgres. Dump it any time. Import it into anything that can read Postgres. The sync service connects outbound to Xero/MYOB/QBO — not the other way around. Built for the next 20 years, not the last 20. # Quick start From `git clone` to a running Tasur instance in 10 minutes. Just want to run Tasur? This page builds everything **from source** — it's for developers. If you just want working books, the [Install page](../../install/) has two faster paths: the **one-click server** (a single downloaded binary — v0.6, no Docker) and the **Docker Community bundle** (one `docker compose` command against published v0.6.1 images). ## Prerequisites - Docker Engine 24+ with `docker compose` v2 - Git - Python 3 (for secret generation — already on most Linux installs) No Postgres installation needed — the compose stack ships one. Two repos, side by side The SAP bundle builds the API and web frontend from source. The build contexts expect both repos checked out as siblings. A single-repo clone will not work. Source repositories are private for now The Tasur GitHub repositories were made private on 20 November 2026, so the clone step below only works if you have been given access. Until the source is published again, use the one-click server or the Docker Community bundle on the [Install page](../../install/), or try the [full accounting demo](https://demo.tasur.io) in your browser. Ask on the [forum](https://forum.tasur.io/) if you need to build from source. ## 1. Clone both repos ```bash git clone https://github.com/saebooks/saebooks.git git clone https://github.com/saebooks/saebooks-web.git ``` Both repos must sit in the same parent directory. The compose build contexts use relative paths — `../..` for the API and `../../../saebooks-web` for the web frontend. ## 2. Set up your environment ```bash cd saebooks/deploy/sap cp .env.example .env ``` Edit `.env`. At minimum, set the three secrets before starting: ```text # Required — generate before first up POSTGRES_PASSWORD= # see generation command below SAEBOOKS_WEB_SECRET_KEY= # see generation command below # Strongly recommended — without this the API signs JWTs with an empty key, # which causes auth failures on verification SAEBOOKS_SECRET_KEY= # see generation command below ``` Generate each secret: ```bash # POSTGRES_PASSWORD python3 -c "import secrets; print(secrets.token_urlsafe(32))" # SAEBOOKS_WEB_SECRET_KEY python3 -c "import secrets; print(secrets.token_hex(32))" # SAEBOOKS_SECRET_KEY openssl rand -hex 32 ``` ## 3. Build images and start The compose stack builds the API and web images from your local source. The first build takes a few minutes; subsequent builds are fast. ```bash docker compose up -d ``` ## 4. Wait for the API healthcheck Alembic migrations run automatically in the API entrypoint — no manual `alembic upgrade head` step needed for a fresh install. The api container reports healthy once migrations complete (~45 s on first start). ```bash docker compose ps # wait for api to show "healthy" docker compose logs -f api # follow startup output ``` ## 5. Log in Open `http://localhost:8080` in your browser. Tasur will walk you through creating your first company. The Australian chart of accounts and tax codes are available in the first-run setup wizard. To pre-fill company details automatically, set `SEED_COMPANY_NAME`, `SEED_COMPANY_LEGAL_NAME`, and `SEED_COMPANY_ABN` in `.env` before the first start. ## 6. Verify the API ```bash # Obtain a token TOKEN=$(curl -s -X POST http://localhost:8042/api/v1/auth/login \ -H 'Content-Type: application/json' \ -d '{"email":"you@example.com","password":"yourpassword"}' \ | python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])") # List accounts curl -s http://localhost:8042/api/v1/accounts \ -H "Authorization: Bearer $TOKEN" | python3 -m json.tool | head -30 ``` The interactive Swagger UI is at `http://localhost:8042/api/v1/docs`. ## What's running ```text api :8080 — browser UI (Jinja2 + HTMX) api :8042 — JSON REST API (/api/v1/) api :50051 — gRPC (desktop client) db :5432 — Postgres 16 (internal only, not published to host) ``` The web UI is on port 8080. The REST API is on port 8042. The database port is not published to the host by default. ## Troubleshooting **API container exits or restarts** — check `docker compose logs api`. The most common cause is `POSTGRES_PASSWORD` not set, or a mismatch between the `api` and `db` containers. Delete the volume (`docker compose down -v`, **only safe on a fresh install with no data**) if Postgres was initialised with a different password. **Auth failures / tokens rejected** — `SAEBOOKS_SECRET_KEY` is probably missing or empty. The API silently defaults to an empty signing key, which means tokens verify only until the container restarts (or across any instance that has a different value). Set `SAEBOOKS_SECRET_KEY` in `.env` and `docker compose up -d` to recreate the api container. **Migrations seem to hang** — the api waits for Postgres to be ready. Watch `docker compose logs db` alongside `docker compose logs api`. If Postgres shows "database system is ready to accept connections," the migration is running; give it 60 s on a slow host. **Build fails with "path not found"** — confirm both repos are siblings in the same parent directory. The api build context is `../..` (the saebooks repo root) and the web build context is `../../../saebooks-web`. If the parent directory doesn't contain `saebooks-web/`, the build will fail. ## Next steps - [Architecture](../architecture/) — what these containers are actually doing - [Self-host in production](../../guides/self-host-production/) — reverse proxy, TLS, backups, hardening - [API reference](../../api/) — every endpoint documented # Guides # Guides Task-oriented walkthroughs. Each guide takes you end-to-end through a single piece of work — the steps, the API calls, and the decisions you'll have to make on the way. If the [API reference](../api/) is "what exists", this section is "how to actually do something". Reach for guides when you have a goal; reach for the reference when you have a question about a specific endpoint. Pre-1.0 — design preview, not a contract These guides describe the **intended** end-to-end experience. Some of the endpoints and flows referenced are still being implemented; others may change shape before 1.0 ships. Read them as a tour of where Tasur is heading, not as a how-to you can rely on for a production integration today. If you spot a guide step that doesn't match what the live API does, the *API* is currently authoritative — but neither is yet a frozen contract. ## Guide index | Guide | What you'll do | | --------------------------------------------------- | ---------------------------------------------------------------------------------- | | [First chart of accounts](chart-of-accounts/) | Set up the chart, post an opening balances journal, see it in the trial balance | | [Connect a bank feed](connect-bank-feed/) | Create a connection via the relay, complete CDR consent, sync first transactions | | [File your first BAS](file-first-bas/) | Tag transactions, prepare BAS labels, create the settlement entry or lodge via SBR | | [Migrate from Xero / MYOB](migrate-from-xero-myob/) | Export from incumbent, transform to Tasur schema, import | | [Build an integration](build-an-integration/) | OAuth-handoff dance, JWT lifecycle, webhooks, idempotency | | [Self-host in production](self-host-production/) | Compose hardening, Postgres tuning, backup, TLS, observability | ## Conventions used in guides - **Code samples** show `curl`, with `$SAEBOOKS_API_BASE` and `$JWT` as bash variables. Substitute your own. - **JSON payloads** use the canonical key ordering from the OpenAPI spec; key order is not significant on the server. - **Endpoints** link to the relevant section of the [generated reference](../api/reference/) so you can see the full schema if you need it. - **Provisional sections** are flagged with a callout. If the underlying feature ships before the guide is updated, the spec is authoritative — file an issue and we'll catch the prose up. # Accounting-package sync Not yet shipped Bidirectional accounting-package sync is in progress as of v0.6: the Xero OAuth connect/callback/status/trigger API surface exists (Enterprise-tier, feature-flag gated), and the database schema supports external IDs (`external_id`, `external_source`, `external_etag`, `external_payload`) on bills, invoices, credit notes, and payments. The full sync worker and UI are still being built. Don't treat this page as a deployment guide — it describes what's being designed. ## The problem Most small businesses switching to Tasur have an accountant or bookkeeper who works in Xero, MYOB, or QBO. That person won't switch tools. Without a sync story, the customer is stuck: use Tasur for daily ops and manually re-enter everything into the accountant's package, or don't switch at all. The answer is bidirectional sync: customer keeps daily ops in Tasur, accountant keeps seeing clean records in their package, the two stay in step. ## What syncs | Object | Tasur → external | External → Tasur | | ------------------------------ | --------------------------------- | -------------------------------------------------------------- | | Chart of accounts | read-only on connect (never push) | yes — new accounts discovered during sync | | Contacts (customers + vendors) | yes | yes | | Invoices | yes | yes | | Bills | yes | yes | | Payments | yes | yes | | Credit notes | yes | yes | | Journal entries | push only | accountant adjustments come back as journals on the Tasur side | | Bank statement lines | no | no — different concept; stays in Tasur | | Inventory items | no (not in scope) | no | | Fixed assets | no (not in scope) | no | | Payroll | no — handled by STP | no | ## Provider roadmap | Provider | Status | Notes | | -------- | ------- | ------------------------------------------------------------------------------------------------------------------ | | **Xero** | Planned | Xero v2 OAuth, clean API surface, good international coverage. Intended as the first adapter. | | **MYOB** | Planned | AccountRight-Live API; messier auth than Xero. High priority because it's the dominant AU accountant tool. | | **QBO** | Planned | Mapping work partially done (one-shot QBO migration CSV import exists at Pro tier); sync reuses the object shapes. | ## Architecture Sync will be an Enterprise feature, gated by per-provider feature flags. It is designed to run as a separate worker process that calls the Tasur API over HTTP — the same interface a third-party integration would use. The specific flag names and worker name are not yet finalised. flowchart LR XERO[Xero / MYOB / QBO] SYNC\["saebooks-sync worker\ (Enterprise)"\] API\["saebooks-api\ REST API"\] PG[("Postgres")] XERO -->|"OAuth pull"| SYNC SYNC -->|"REST writes"| API API -->|"webhook push"| SYNC API --- PG **Conflict resolution:** last-write-wins with audit trail. A `sync_state` table records `(tenant, provider, external_id, last_pulled_etag)` per synced object so divergence is detectable. Conflicts surface to the operator in a UI rather than silently picking a winner. **Hard-delete and sync:** when sync is active for a tenant, the hard-delete path is blocked for synced object types (invoices, bills, payments, contacts, credit notes). Deletions are pushed as voids (`VOIDED` status in Xero; warn-only for MYOB which doesn't support server-side delete). The UI surfaces a warning when enabling sync that hard-delete becomes unavailable. **OAuth:** each customer registers their own OAuth app with Xero/MYOB/QBO and supplies their own `client_id` + `client_secret`. SAE Engineering does not ship a shared credential. One Xero login can connect multiple Xero organisations — the unique key is `(tenant, provider, external_tenant_id)`. ## Enabling sync (Enterprise) Once shipped, sync is enabled in the web UI under Settings → Integrations. The setup flow: 1. Select provider (Xero, MYOB, or QBO). 1. Enter your OAuth `client_id` and `client_secret`. 1. Authorise the OAuth connection (browser redirect to the provider). 1. Confirm the accounts mapping (Tasur accounts ↔ provider accounts). 1. Run the initial pull (one-shot historical sync from your connect date). 1. Ongoing sync runs on a configurable schedule (default: every 15 minutes). ## What sync doesn't solve Sync is not a migration tool. For an initial migration from Xero or MYOB with historical data, see [Migrate from Xero / MYOB](../migrate-from-xero-myob/). Sync also doesn't eliminate the need to understand both systems. Accounts mapping, tax code matching, and contact deduplication require a one-time setup pass by someone who knows both ledgers. # Build an integration A walkthrough of building a third-party application that talks to Tasur on behalf of a user — the canonical "I have a SaaS and I want to read/write my customer's books" case. ## Choose your auth model | You are | Auth model | | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | | A line-of-business app run *by* the user (or their bookkeeper) | **JWT bearer**, obtained from `POST /api/v1/auth/login` with the user's credentials | | A backend automation that doesn't act on behalf of any user | **API token** — issue a named token via `POST /api/v1/api-tokens` (requires a prior JWT login); use it as a long-lived `Authorization: Bearer` credential | | A self-hosted instance fronted by Discourse, Authentik, or CF Access | **OAuth handoff** — Tasur web handles the SSO callback and mints a JWT internally | No public OAuth consent flow in v0.6 Tasur does not yet expose a public OAuth2 authorisation endpoint (`/oauth/authorize` + consent screen) for third-party SaaS developers. The `/auth/oauth-handoff` endpoint is an internal server-to-server path used by the web layer after a Discourse/Authentik/CF Access callback — it is not intended for, and will reject, arbitrary third-party clients. A public OAuth surface is on the roadmap. For now, integrations authenticate via JWT (`/api/v1/auth/login`) or a named API token. ## Token lifecycle - **JWT access tokens** (from `POST /api/v1/auth/login`) last **8 hours** by default. - Call `POST /api/v1/auth/refresh` with a still-valid token to get a fresh one. Refresh **proactively** — before the token expires rather than catching the 401 and retrying. - **Named API tokens** (from `POST /api/v1/api-tokens`) are long-lived. Set `ttl_days` at creation (1–3650) or omit for no expiry. Revoke via `DELETE /api/v1/api-tokens/{id}`. - On a `401`, do not retry indefinitely — the token may be expired or revoked. Re-authenticate or return the user to the connect flow. ## Idempotency Every write that creates a journal, payment, contact, or document accepts `X-Idempotency-Key: `. Generate a fresh UUID per logical operation and store it alongside the operation in your own database. On retry, replay with the same key — the server returns the original response, you don't double-post. This matters because **agentic retry loops are common**. If your worker crashes between sending a `POST /journals` and persisting the returned journal ID, you'll retry on restart. Without an idempotency key, you've now posted the same journal twice. With one, you get the original response and continue. ## Webhooks Outbound webhook registration not yet available Tasur v0.6 does not yet expose a `POST /api/v1/webhooks` registration endpoint for third-party integrations to receive event pushes. The webhook infrastructure described below reflects the intended design; use polling against the REST API in the meantime. For event-driven integrations, the planned approach is to register a webhook target: ```bash curl -X POST "$SAEBOOKS_API_BASE/webhooks" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-app.example.com/webhooks/saebooks", "events": ["journal.posted", "bank_transaction.received", "bas.prepared"], "secret": "" }' ``` Every delivery will include: - `X-SAEBooks-Signature: t=,v1=` — verify with your secret. The signed payload is `.`. - `X-SAEBooks-Delivery: ` — for idempotent processing on your side; Tasur retries on non-2xx. ## Pagination List endpoints use one of two patterns depending on the resource: **Page-based** (invoices, bills, contacts, and most sub-ledger objects): ```bash curl "$SAEBOOKS_API_BASE/invoices?page=1&page_size=100" \ -H "Authorization: Bearer $JWT" ``` Response: `{items: [...], total: N, limit: 100, offset: 0}`. Advance by incrementing `page`. **Cursor-based** (cashbook, change log, and a small number of streaming endpoints): ```bash curl "$SAEBOOKS_API_BASE/cashbook?cursor=" \ -H "Authorization: Bearer $JWT" ``` Response: `{items: [...], next_cursor: "..."}`. `next_cursor: null` means no more pages. Consult the [API reference](../../api/reference/) for each endpoint's specific pagination style. ## Rate limits `/api/v1/*` does not impose application-level rate limits in v0.6 — enforce limits at your reverse proxy (Caddy's `rate_limit` directive, nginx `limit_req`) if needed for a multi-tenant or public-facing deployment. On `429` from your proxy, back off for `Retry-After` seconds. Don't loop tightly. ## Errors RFC 7807 `application/problem+json`. Switch on `code`, not `detail`: ```json { "type": "https://saebooks.io/problems/resource_archived", "title": "Resource Has Been Archived", "status": 410, "code": "resource_archived", "detail": "Account 1100 is archived and cannot be used on new transactions." } ``` `code` is stable across releases; `title` and `detail` prose are not. Validation errors (422) use `code: "validation_failed"` and include an `errors` array (list of pydantic field errors) rather than a `fields` map. ## Testing Run a local Tasur instance per the [quickstart](../../getting-started/quickstart/). Every API endpoint that exists in production exists locally. There's no separate sandbox — you bring up your own. For automated tests on your side, the dev/test bearer token (`SAEBOOKS_DEV_API_TOKEN`) skips the JWT signing step and lets you hit the API directly. **Never set this in production.** ## Next - [Generated API reference](../../api/reference/) — every endpoint - [LLM agent integration guide](../../llm-agents/) — same content, framed for AI-driven integrations # First chart of accounts This walks through setting up a chart of accounts on a fresh Tasur instance, posting an opening balances journal, and confirming the result in the trial balance. You'll need: - A running Tasur instance ([quickstart](../../getting-started/quickstart/)) - A bearer token for your tenant ([auth](../../api/auth/)) ```bash export SAEBOOKS_API_BASE=https://books.example.com/api/v1 export JWT=... # from POST /auth/login ``` ## 1. Decide the structure The chart is hierarchical, keyed by `code`. The top-level shape is fixed (the account types — `ASSET`, `LIABILITY`, `EQUITY`, `INCOME`, `OTHER_INCOME`, `EXPENSE`, `COST_OF_SALES`, `OTHER_EXPENSE`); below that, codes and grouping are yours. A common Australian SME structure: | Code | Name | Type | | ---- | ------------------ | ------------- | | 1100 | Cash at bank | ASSET | | 1200 | Trade debtors | ASSET | | 1500 | Inventory | ASSET | | 1700 | Plant & equipment | ASSET | | 2100 | Trade creditors | LIABILITY | | 2300 | GST payable | LIABILITY | | 3100 | Owner equity | EQUITY | | 4000 | Sales | INCOME | | 5000 | Cost of goods sold | COST_OF_SALES | | 6000 | Operating expenses | EXPENSE | | 6100 | Wages & salaries | EXPENSE | You don't have to commit upfront — you can add accounts later. But the *codes* are sticky in the sense that reports order on them, so pick a numbering scheme you'll be happy with in a year. ## 2. Seed the chart There is no bulk-create endpoint. Post accounts one at a time to `POST /api/v1/accounts`. The `account_type` values are uppercase enum strings; `tax_code_default` sets the default tax code for a line posted to that account (use the tax code string, e.g. `"GST"`): ```bash curl -X POST "$SAEBOOKS_API_BASE/accounts" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"code":"1100","name":"Cash at bank","account_type":"ASSET"}' curl -X POST "$SAEBOOKS_API_BASE/accounts" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"code":"1200","name":"Trade debtors","account_type":"ASSET"}' curl -X POST "$SAEBOOKS_API_BASE/accounts" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"code":"2100","name":"Trade creditors","account_type":"LIABILITY"}' curl -X POST "$SAEBOOKS_API_BASE/accounts" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"code":"2300","name":"GST payable","account_type":"LIABILITY","tax_code_default":"GST"}' curl -X POST "$SAEBOOKS_API_BASE/accounts" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"code":"3100","name":"Owner equity","account_type":"EQUITY"}' curl -X POST "$SAEBOOKS_API_BASE/accounts" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"code":"4000","name":"Sales","account_type":"INCOME","tax_code_default":"GST"}' curl -X POST "$SAEBOOKS_API_BASE/accounts" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"code":"6000","name":"Operating expenses","account_type":"EXPENSE","tax_code_default":"GST"}' ``` Each call returns the created account with its UUID. Save the UUIDs you need for the next step. Valid `account_type` values: `ASSET`, `LIABILITY`, `EQUITY`, `INCOME`, `OTHER_INCOME`, `EXPENSE`, `COST_OF_SALES`, `OTHER_EXPENSE`. ## 3. Post opening balances Opening balances are a single journal that brings the trial balance up from zero to your "as at" position on day one. It must balance. The journal entries endpoint is `/api/v1/journal_entries`. Lines reference accounts by **UUID** (`account_id`), not by code. The payload fields are `entry_date`, `narration`, and `reference`: ```bash curl -X POST "$SAEBOOKS_API_BASE/journal_entries" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{ "entry_date": "2026-07-01", "narration": "Opening balances", "lines": [ {"account_id":"","debit":"15000.00","credit":"0"}, {"account_id":"","debit":"4200.00","credit":"0"}, {"account_id":"","debit":"0","credit":"3100.00"}, {"account_id":"","debit":"0","credit":"16100.00"} ] }' ``` This creates a `DRAFT` entry. To post it, call: ```bash curl -X POST "$SAEBOOKS_API_BASE/journal_entries//post" \ -H "Authorization: Bearer $JWT" \ -H "If-Match: 1" \ -H "X-Idempotency-Key: $(uuidgen)" ``` The server validates `SUM(debits) = SUM(credits)` at both the schema level and on post; an unbalanced journal returns `422`. ## 4. Verify ```bash curl "$SAEBOOKS_API_BASE/reports/trial_balance?as_of_date=2026-07-01" \ -H "Authorization: Bearer $JWT" ``` You should see your four touched accounts at their opening balances, and every other account at zero. ## What you've built - A chart of accounts you'll add to as the business grows - An immutable opening-balances journal that anchors every report - A trial balance that balances at zero — the precondition for every P&L, balance sheet, and BAS run from here on ## Next - [Connect a bank feed](../connect-bank-feed/) — start ingesting real transactions - [Accounting module](../../modules/accounting/) — the deeper model behind journals and lines # Connect a bank feed Provisional Bank feeds are gated by a `bank_feeds` feature flag — the API router returns `404` on community installs that do not have the flag enabled. Real bank data requires completing SISS onboarding through the `feeds.saebooks.com.au` relay; until onboarding is complete the relay operates in stub mode. See [Bank feeds](../../modules/bank-feeds/) for the broader context. This guide describes the **intended** end-to-end flow. Where a step isn't yet automated, we say so. ## What you're going to do 1. Complete relay onboarding (one-off NDA + provisioning via SAE Engineering) 1. Create a connection — the consumer redirects to their bank, approves CDR consent 1. Wait for the relay to sync (or force a sync via the API) 1. Confirm transactions are landing in `bank_statement_lines` 1. Tune matching rules ## 1. Aggregator credentials CDR access in Australia goes through an accredited aggregator (currently SISS Data Services). Tasur connects to SISS via the `feeds.saebooks.com.au` relay service — the relay holds your ADR credentials; you do not manage SISS client secrets directly on your instance. On the SISS / relay side you need: - An accredited data recipient (ADR) registration *or* a contract riding on theirs - An NDA with SISS - Onboarding through the Tasur relay (provisioned by SAE Engineering; contact support) ## 2. Initiate consent ```bash curl -X POST "$SAEBOOKS_API_BASE/bank-feeds/connections" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{ "bank": "anz-au", "account_label": "ANZ Business Cheque" }' ``` Response: ```json { "id": "", "consent_url": "https://...", "status": "pending_consent" } ``` Send the `consent_url` to the consumer — they authenticate at their bank, approve the consent, and the bank redirects them back to the relay. The relay updates the connection status and schedules the first transaction pull. Stub mode While SISS onboarding is in progress the relay operates in stub mode and returns a deterministic stub response (no real bank data). The `status` field will read `pending_consent` and `consent_url` may be a placeholder. This is expected — the local connection row is created so the UI's in-flight list works. ## 3. First sync By default a sync runs on the relay's schedule. Force one: ```bash curl -X POST "$SAEBOOKS_API_BASE/bank-feeds/sync" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"connection_id": ""}' ``` Response includes `inserted` (count of new statement lines) and `next_cursor`. Transactions land in `GET /api/v1/bank_statement_lines?bank_account_id=...`. ## 4. Matching Each transaction lands with status `UNMATCHED`. Auto-create rules process them — see [Modules → Bank feeds](../../modules/bank-feeds/). Matching rules that auto-post set `auto_create: true`; others queue for manual review. Tune matching rules: ```bash curl -X POST "$SAEBOOKS_API_BASE/bank_rules" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{ "name": "Officeworks", "match_pattern": "OFFICEWORKS", "match_type": "CONTAINS", "account_id": "", "tax_code": "GST", "auto_create": true }' ``` ## Failure modes - **Consent expired.** CDR consent caps at 12 months. When consent lapses the connection status transitions to `revoked`; revoke the local row with `DELETE /api/v1/bank-feeds/connections/{id}` and start a new consent flow. No transactions are lost — syncs just pause. - **Relay unavailable.** The `GET /api/v1/bank-feeds/connections` list endpoint serves from the local mirror and remains usable when the relay is unreachable. Sync calls return `503` and should be retried; the next successful sync catches up. - **Stub mode.** While SISS onboarding is incomplete the relay returns `501` stub responses. The API surfaces these as `200` with `"stub": true` in the response body so the UI can show a banner rather than an error. No real transactions are inserted in stub mode. ## Next - [File your first BAS](../file-first-bas/) — once a quarter of bank transactions have been classified - [Modules → Bank feeds](../../modules/bank-feeds/) — the model behind this guide # File your first BAS The Business Activity Statement is the quarterly (or monthly) GST and PAYG return Australian businesses lodge with the ATO. Tasur prepares the BAS labels from your posted activity; this guide takes you from "the quarter just ended" to "the BAS is filed". ## Prerequisites - Transactions for the period are posted and tagged with tax codes (`GST`, `FRE`, `INP`, etc.) - The trial balance reconciles - Bank reconciliation is complete (no `UNMATCHED` lines for the period) If those aren't true, fix them first — the BAS is downstream of a clean ledger. ## 1. Prepare the BAS The BAS summary endpoint takes explicit date ranges, not a quarter shorthand. For the January–March 2026 quarter: ```bash curl "$SAEBOOKS_API_BASE/reports/bas_summary?from_date=2026-01-01&to_date=2026-03-31" \ -H "Authorization: Bearer $JWT" ``` Response: ```json { "from_date": "2026-01-01", "to_date": "2026-03-31", "g1_total_sales": "...", "g2_export_sales": "...", "g3_other_gst_free_sales": "...", "g10_capital_acquisitions": "...", "g11_other_acquisitions": "...", "label_1a_gst_on_sales": "...", "label_1b_gst_on_purchases": "...", "net_gst": "...", "remit_or_refund": "REMIT" } ``` The web UI at `/reports/bas?from=2026-01-01&to=2026-03-31` shows the same figures in tabular form alongside a "Create settlement entry" action. ## 2. Review The BAS calculation is incremental — every posted transaction tagged with a GST tax code has already contributed. Common checks: - **Cash vs. accruals**. If your company is in cashbook mode, the BAS reads from payments, not invoices. Mismatched mode settings here are the most common cause of a "wrong" BAS. - **Outliers**. Compare against last quarter's labels. A 10× swing on a single label is almost always a tagging error, not a real trading swing. - **Tax-code coverage**. Query `GET /api/v1/accounts` with `include_balance=true` and cross-reference which accounts have `tax_code_default` set. Look for income accounts with no tax code — those lines contribute nothing to G1. ## 3. Lodgement — community / offline / business tiers There is no CSV export endpoint. The web UI at `/reports/bas` is the primary review and settlement surface. Once you're satisfied with the figures: 1. Click **Create settlement entry** in the "Lodge BAS" panel — this POSTs to `/reports/bas/settle` and creates a draft journal that zeroes GST Collected and GST Paid, with the net going to a GST Clearing account. 1. Review and post the draft journal at `/journal/`. 1. Record the ATO payment from your bank account via the standard payments flow. To transcribe labels manually: - **Via your tax agent** — read the `label_1a_gst_on_sales` and `label_1b_gst_on_purchases` values from the API response and hand them to your agent for lodgement through their software. - **Via the ATO Business Portal** — log in at https://www.ato.gov.au/ and transcribe the labels onto the Business Portal BAS form. ## 3'. Lodgement — pro / enterprise tiers Pro and enterprise installs can lodge directly via SBR (Standard Business Reporting). Set up an ATO keystore credential first: ```bash # Upload your ATO keystore (PFX or ATO XML file; password required) curl -X POST "$SAEBOOKS_API_BASE/ato_sbr/keystore" \ -H "Authorization: Bearer $JWT" \ -F "file=@my-ram-credential.p12" \ -F "password=" \ -F "label=RAM credential 2026" # Create a tax return record for the period, then lodge it curl -X POST "$SAEBOOKS_API_BASE/tax_returns" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{ "jurisdiction": "AU", "period_id": "", "return_type": "BAS", "figures": {"G1": "..."} }' curl -X POST "$SAEBOOKS_API_BASE/tax_returns//lodge" \ -H "Authorization: Bearer $JWT" ``` You will need a Machine Credential issued via the [ATO RAM](https://info.authorisationmanager.gov.au/) — same mechanism Xero / MYOB use, running on hardware you control. See the operator guide for credential setup. ## 4. Audit trail Every settlement entry and every SBR lodgement (pro / enterprise) is recorded with the actor, the period, and the resulting label values. The settlement journal entry itself carries full provenance in the journal `change_log`. If the ATO ever asks "where did this number come from?", the trail goes from BAS label → contributing journals → contributing source documents. ## Next - [GST & BAS module](../../modules/gst-bas/) — tax codes in detail, WET/LCT, cash vs accruals switching - [Self-host in production](../self-host-production/) — the SBR Machine Credential setup is the load-bearing piece for pro / enterprise # Migrate from Xero / MYOB / QuickBooks Bringing an existing set of books across to Tasur. The mechanics are the same regardless of the source system — only the export format differs. Cutover date Pick a clean cutover. End-of-quarter (after BAS) is best; end-of-month is fine. Mid-period migration works but doubles the reconciliation work because you're crossing two systems' GST accruals. ## What you migrate vs. what you reset | Migrate | Reset (start fresh in Tasur) | | ------------------------------ | --------------------------------------------- | | Chart of accounts | Bank-feed connections (re-consent in Tasur) | | Customers / vendors / contacts | User accounts (recreate via signup or invite) | | Open invoices and bills | API integrations (re-issue tokens) | | Open credit notes | | | Asset register | | | Trial balance as at cutover | | You do **not** migrate historical transactions. They stay in the incumbent system as a read-only archive — Australian tax law requires five years of retention regardless of which platform you're running today. ## 1. Export from the incumbent | Source | Export endpoint / report | | ----------------- | ------------------------------------------------------------------------- | | Xero | Reports → Export, plus `Reports → Trial Balance` for the cutover snapshot | | MYOB | File → Export Data | | QuickBooks Online | Reports → Export to Excel; Lists → Customer/Vendor → Export | Get four CSVs at minimum: - Chart of accounts (`code, name, type, parent_code`) - Customers (`name, abn, email, billing_address, …`) - Vendors (same shape, separate file) - Trial balance as at cutover date Plus, if you carry assets: - Asset register (required columns: `code, name, purchase_date, cost, depreciation_model_id, cost_account_code, accum_dep_account_code`) ## 2. Transform Tasur provides a QBO CSV import parser (`saebooks/services/imports/qbo.py`) that handles QBO's standard "Customer.csv" / "Vendor.csv" and Account List CSV exports, mapping them to Tasur contacts and chart of accounts. For Xero and MYOB exports, you'll need to normalise the CSV columns to match the Tasur expected headers before upload — the column names vary by source, but the CoA wizard accepts `code, name, type, parent_code` and the contact wizard accepts `name, email, phone, abn` as core columns. ## 3. Import via the wizard API All imports go through the wizard API at `/api/v1/imports/wizards`. There is no single-step bulk endpoint that returns a `job_id` — the wizard is a multi-step flow: start, upload, preview, commit. ```bash # 1. Start a wizard (kind: "coa" for chart of accounts, "qbo" for QBO contacts/CoA) curl -X POST "$SAEBOOKS_API_BASE/imports/wizards" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"kind": "coa"}' # → {"wizard_id": "...", "step": 0, "state": {}} # 2. Upload the CSV (step patch) curl -X POST "$SAEBOOKS_API_BASE/imports/wizards/$WIZARD_ID/step" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d "{\"step\": 0, \"patch\": {\"raw\": \"$(cat accounts.csv | python3 -c 'import sys,json; print(json.dumps(sys.stdin.read()))')\"}}" # 3. Commit curl -X POST "$SAEBOOKS_API_BASE/imports/wizards/$WIZARD_ID/commit" \ -H "Authorization: Bearer $JWT" # → {"new": N, "changed": M, "archived": K} ``` Available `kind` values: `bank_csv`, `bank_ofx`, `coa`, `bill_csv` (community tier); `qbo` (Pro+ — requires `FLAG_QBO_IMPORT`). The asset register import uses the web UI (Settings → Assets → Import CSV) rather than the JSON API — the flow is a two-step preview-then-apply form submission. Use the UI for asset migrations. ## 4. Opening balances The trial-balance snapshot from your incumbent becomes a single opening-balances journal in Tasur — same pattern as a [first chart of accounts](../chart-of-accounts/). The journal date is the day *after* your cutover (so the incumbent owns up to and including the cutover date, Tasur owns from the next day). ## 5. Open AR / AP Open invoices and bills are re-entered as live documents, not history. There is no bulk JSON endpoint for invoices — create them individually via `POST /api/v1/invoices` (one per open invoice), or use the `bill_csv` import wizard for bills: ```bash # Individual invoice curl -X POST "$SAEBOOKS_API_BASE/invoices" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d @invoice.json # Bills in bulk — use the bill_csv wizard (kind: "bill_csv") # Bills are imported as DRAFTS for human review before posting. ``` Each invoice posts the same journal it would have if you'd raised it natively, *minus* any payments — those land via the bank feed once you reconnect. ## 6. Reconcile Run the trial balance in both systems and compare. They should agree to the cent. Any difference is one of: - **A miscoded transformation** (foreign currency line, GST flag, account-type confusion) — fix the script and re-run - **An incumbent-system quirk** (Xero's "system accounts", MYOB's job-cost accruals) — usually resolved by re-mapping to the closest Tasur equivalent - **A genuinely missing entry** — post it manually as an opening-balance adjustment, with a clear narration ## 7. Cut over Stop posting in the incumbent. Direct bank feeds, integrations, and users at Tasur. Keep the incumbent in read-only archive mode for the legal retention period. ## Next - [Connect a bank feed](../connect-bank-feed/) — the next thing you'll want is fresh data flowing in - [File your first BAS](../file-first-bas/) — the first BAS after cutover proves the migration was clean # Mobile Tasur is a server-rendered web app with PWA (Progressive Web App) install support. Open `https://books.example.com` (or your self-hosted URL) in Safari on iOS or Chrome on Android and install it to your home screen for a full-screen, app-like experience. ## Install to your home screen ### iOS (Safari) 1. Open the URL in Safari. 1. Tap the Share button (the box with an arrow pointing up). 1. Scroll down and tap **Add to Home Screen**. 1. Confirm the name and tap **Add**. The app opens in standalone mode — no address bar, no Safari chrome. ### Android (Chrome) 1. Open the URL in Chrome. 1. Tap the three-dot menu in the top-right. 1. Tap **Add to Home screen** (or **Install app** on newer Chrome builds). 1. Confirm. Chrome may also show an install banner at the bottom of the screen automatically. ## What the PWA gives you - **Home screen icon** — no address bar, launches straight to the dashboard. - **Splash screen** — branded loading screen on iOS while the app warms up. - **App shortcuts** — long-press the home screen icon to jump directly to New Invoice, Dashboard, or Reports (Android; iOS 16.4+). - **Static asset caching** — CSS, icons, and the manifest are cached at install; subsequent loads skip the round-trip for those files. - **Offline notice** — if your device has no connectivity, a branded page explains the situation rather than a browser error. Data writes always require a live connection to the ledger. There is no native app on the App Store or Google Play. ## Why no native app? The Tasur API is the product. A native app would be a third-party consumer of that API — a reasonable thing to build, but not what SAE Engineering is building right now. A self-hosted deployment should work from any browser on any device, and for most SME accounting workflows a mobile-responsive web app is sufficient. If you're building a native mobile app on top of the Tasur API, the [Build an integration](../build-an-integration/) guide covers authentication and the API conventions you need. # Self-host in production The quickstart gets you running. This page gets you to a deployment you can trust with real books. ## Posture - **Single-tenant appliance.** One customer's books on one host. Multi-tenant is an Enterprise option; it increases blast radius and operational complexity. Start single-tenant. - **Reverse proxy in front.** Never expose ports 8080, 8042, or 50051 to the public internet. TLS terminates at the proxy. - **Pin to a tagged release.** `main` is fine for dev. In prod you want to know which version posted yesterday's journal. Pin by checking out a release tag in both repos before building. ## Pinning to a release Because images are built from source, you pin a release by checking out the same tag in both repos: ```bash cd ~/projects/saebooks && git fetch --tags && git checkout v0.6 cd ~/projects/saebooks-web && git fetch --tags && git checkout v0.6 cd ~/projects/saebooks/deploy/sap docker compose up -d --build ``` If you want a named local image for your own registry or CI pipeline, build and tag directly: ```bash # From the saebooks repo root docker buildx build --tag saebooks-api:v0.6 . # From the saebooks-web repo root docker buildx build --tag saebooks-web:v0.6 . ``` ## Postgres ### Use the bundled Postgres, or your own The bundled `docker-compose.yml` ships a `db` service (Postgres 16, volume `saebooks_db`). For a single-host appliance this is fine. For anything with HA requirements, point `DATABASE_URL` at a managed Postgres (AWS RDS, Supabase, your own Patroni cluster). ```text DATABASE_URL=postgresql+asyncpg://saebooks:yourpassword@db:5432/saebooks ``` ### Tuning Defaults are conservative. For a single-tenant SME instance with 4 GB RAM: ```ini shared_buffers = 1GB work_mem = 32MB maintenance_work_mem = 256MB effective_cache_size = 3GB wal_compression = on ``` The bigger lever in practice: make sure the data directory is on SSD. `synchronous_commit` and WAL fsync dominate performance at small scale. ### Alembic migrations Migrations run automatically on container start via the entrypoint script. They are designed to be additive-then-cutover so the old app version can serve traffic while the new schema is being applied. If a migration fails, the container exits non-zero — do not restart into the old image. Diagnose first. ```bash # Check what version the DB is at docker compose exec api alembic current # Apply manually (if auto-apply is disabled) docker compose exec api alembic upgrade head ``` ## Compose hardening The SAP bundle at `deploy/sap/` is the base. For a hardened production overlay, extend it with `docker-compose.override.yml`: ```yaml services: api: build: context: ../.. # saebooks repo root restart: unless-stopped environment: SAEBOOKS_EDITION: community # or enterprise SAEBOOKS_SECRET_KEY: ${SAEBOOKS_SECRET_KEY} SAEBOOKS_WEB_SECRET_KEY: ${SAEBOOKS_WEB_SECRET_KEY} DATABASE_URL: ${DATABASE_URL} SAEBOOKS_FIELD_ENCRYPTION_KEY: ${SAEBOOKS_FIELD_ENCRYPTION_KEY} SAEBOOKS_LOG_JSON: "1" # SAEBOOKS_DEV_API_TOKEN must NOT be set — its presence disables JWT auth ports: [] # no host ports — reverse proxy only networks: [internal, revproxy] read_only: true tmpfs: [/tmp] cap_drop: [ALL] security_opt: - no-new-privileges:true web: build: context: ../../../saebooks-web restart: unless-stopped environment: SAEBOOKS_API_URL: http://api:8000 SAEBOOKS_WEB_SECRET_KEY: ${SAEBOOKS_WEB_SECRET_KEY} SAEBOOKS_WEB_LOG_LEVEL: INFO networks: [internal, revproxy] read_only: true tmpfs: [/tmp] cap_drop: [ALL] security_opt: - no-new-privileges:true db: image: postgres:16-alpine restart: unless-stopped volumes: - /var/lib/saebooks/pg:/var/lib/postgresql/data networks: [internal] networks: internal: revproxy: external: true # shared network that your Caddy / nginx joins ``` The `SAEBOOKS_DEV_API_TOKEN` env var is a static bearer token that bypasses JWT auth — it must never be set in production. ## Reverse proxy (Caddy) Caddy is the simplest option. Drop this in your Caddyfile: ```text books.example.com { reverse_proxy localhost:8080 # web UI header { Strict-Transport-Security "max-age=31536000; includeSubDomains" X-Content-Type-Options nosniff Referrer-Policy strict-origin-when-cross-origin X-Frame-Options DENY } } # Optional: expose the REST API directly (for integrators who need direct API access) api.books.example.com { reverse_proxy localhost:8042 # Consider restricting to known IP ranges if only internal tools use this } ``` Caddy will auto-issue and renew a Let's Encrypt cert. Traefik, nginx, and HAProxy all work the same way. Never expose port 8080 or 8042 directly. ## Environment variables ### api service | Variable | Required | Notes | | -------------------------------------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `POSTGRES_PASSWORD` | yes | Set before first up. `python3 -c "import secrets; print(secrets.token_urlsafe(32))"` | | `SAEBOOKS_SECRET_KEY` | **strongly recommended** | JWT signing secret. If unset the API silently defaults to an empty string — tokens sign but fail verification on any restart or across instances. `openssl rand -hex 32` | | `SAEBOOKS_EDITION` | no | `community` (default) | | `SAEBOOKS_FIELD_ENCRYPTION_KEY` | recommended for prod | Fernet key for field-level encryption. Generate: `python3 -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"`. Empty = field encryption disabled. | | `SAEBOOKS_LOG_LEVEL` | no | `INFO` (default); `DEBUG` for diagnostics | | `SAEBOOKS_LOG_JSON` | no | Set `1` for structured JSON logs | | `SENTRY_DSN` | no | Error reporting | | `SMTP_HOST` | no | Empty = emails written to `/app/mail-outbox` (dev mode) | | `SMTP_PORT` | no | `587` (default) | | `SMTP_USER` / `SMTP_PASSWORD` / `SMTP_FROM` | for email | Required when `SMTP_HOST` is set | | `SEED_COMPANY_NAME` / `_LEGAL_NAME` / `_ABN` | no | Pre-fills company details on first DB init only | | `SAEBOOKS_ADMIN_EMAIL` | no | Seeds an initial admin account | ### web service | Variable | Required | Notes | | ------------------------- | -------- | ------------------------------------------------------------------------------------------ | | `SAEBOOKS_API_URL` | yes | Internal URL of the api service — `http://api:8000` | | `SAEBOOKS_WEB_SECRET_KEY` | yes | Session cookie signing secret. `python3 -c "import secrets; print(secrets.token_hex(32))"` | | `SAEBOOKS_WEB_PORT` | no | `8080` (default) | | `SAEBOOKS_WEB_LOG_LEVEL` | no | `INFO` (default) | ## Secrets management Keep secrets out of version control. Recommended approaches: - **0600 `.env` file** on the host, owned by the service user, never committed. The reference pattern used in SAE Engineering's own deployment: ```text ~/projects/saebooks/deploy/sap/.env # 0600, owned by operator user ``` - **Docker secrets / external secret store** — if your organisation runs Vault or AWS Secrets Manager, inject secrets via environment variables at runtime rather than `.env` files. Never commit `.env` to Git. The `.gitignore` in `deploy/sap/` already excludes it. ## Backups Postgres is the only stateful component. The volume `saebooks_db` is unaffected by `docker compose down` — your data survives container rebuilds. Three layers, in order of importance: 1. **WAL archiving** — `archive_command` shipping WAL segments to off-host storage every minute. Enables point-in-time recovery. 1. **Nightly logical dump** — `pg_dump` with 30 days retention: ```bash docker compose exec -T db pg_dump -U saebooks saebooks \ | gzip > /var/lib/saebooks/backups/saebooks-$(date +%Y%m%d).sql.gz ``` 1. **Filesystem snapshot** — ZFS/btrfs/LVM snapshot of the data volume, shipped off-host. **Restore drills are non-optional.** A backup you've never restored from is not a backup. Run a cold-site drill at least quarterly and verify the trial balance reconciles. ## Observability | Path | Auth | Purpose | | ----------------- | ------------------------------- | --------------------- | | `/api/v1/healthz` | none | Liveness — 200 OK | | `/healthz` (web) | none | Web frontend liveness | | `/metrics` | `SAEBOOKS_METRICS_TOKEN` bearer | Prometheus endpoint | Logs are structured JSON on stdout when `SAEBOOKS_LOG_JSON=1`. Ship to whatever you already have (Loki, Elasticsearch, systemd-journal). The `deploy/grafana/` directory in the repo ships a dashboard JSON covering request rate, latency percentiles, DB connections, and per-tenant journal-post throughput. ## Upgrades ```bash # 1. Read CHANGELOG.md for migration warnings # 2. Snapshot Postgres docker compose exec -T db pg_dump -U saebooks saebooks | gzip > pre-upgrade.sql.gz # 3. Pull both repos (or checkout a specific tag) cd ~/projects/saebooks && git pull # or: git checkout cd ~/projects/saebooks-web && git pull # or: git checkout # 4. Rebuild and restart (Alembic runs on startup) cd ~/projects/saebooks/deploy/sap docker compose up -d --build # 5. Smoke-test: login, post a test journal, verify BAS prepare runs ``` If a migration fails, the container exits non-zero. Diagnose the migration output before doing anything else. Restoration path: pipe the pre-upgrade dump back in and restart from the previous checkout. For zero-downtime, run two api containers behind the proxy and roll one at a time. Schema migrations are designed to run additive-then-cutover style; release notes call out any blocking migration. ## Enterprise licence Enterprise installs validate against `license.saebooks.com.au` on start and once daily thereafter. Validation is local (cryptographic — Ed25519 signature check). The daily refresh is a network call. Offline operation is supported for up to 30 days on the cached token, after which the install falls back to Community behaviour. For air-gapped networks, contact SAE Engineering for an extended-offline key. ## Reference: the bosun pattern SAE Engineering's own deployment uses a per-service compose pattern called "bosun": ```text ~/projects/saebooks/deploy/sap/ ├── docker-compose.yml └── .env # 0600, owned by operator user, never committed ``` Data volumes on a separate mount point from the OS. This pattern is worth copying — service isolation via compose project, secrets in 0600 `.env` files, data directories separate from the application. ## Next - [Migrations](../../ops/migrations/) — what Alembic is doing - [Tenancy & RLS](../../ops/tenancy/) — the Postgres posture - [Editions](../../editions/) — enabling Enterprise features # API reference # API reference The Tasur HTTP API. Every accounting operation — journal entries, invoices, payments, reports, reconciliation — is an API endpoint. The browser UI is a consumer of the same API your integration code would use. ## Two ways to explore the API **Interactive docs (Swagger UI)** — every install ships its own Swagger UI at `/api/v1/docs`. Hit "Try it out" on any endpoint, authenticate with a bearer token, and make real calls against your data. ```text https://books.example.com/api/v1/docs # your server http://localhost:8042/api/v1/docs # your local install ``` **Raw OpenAPI spec** — the machine-readable schema is at `/api/v1/openapi.json`. Feed it to your code generator of choice. ```bash curl -s https://books.example.com/api/v1/openapi.json | python3 -m json.tool | head -60 ``` **Generated reference on this site** — [Endpoints (generated)](reference/) renders the OpenAPI schema into this documentation site. Use it for quick lookups without leaving the docs. ## Before you make your first call Read in order: 1. [Authentication](auth/) — how to obtain a token and keep it fresh 1. [Conventions](conventions/) — URL shape, error format, pagination, idempotency, optimistic locking ## Endpoint groups | Group | Base path | What it covers | | --------------------- | -------------------------------- | ----------------------------------------------------------------------- | | Auth | `/api/v1/auth/` | Login, signup, email verification, password reset, magic link, WebAuthn | | API tokens | `/api/v1/api-tokens/` | Long-lived machine API tokens (issue, list, revoke) | | Users | `/api/v1/users/` | User management within a tenant | | Companies | `/api/v1/companies/` | Company settings, multi-company (Enterprise) | | Branches | `/api/v1/branches/` | Sub-branches within a company | | Contacts | `/api/v1/contacts/` | Customers and vendors | | Accounts | `/api/v1/accounts/` | Chart of accounts | | Tax codes | `/api/v1/tax_codes/` | GST, GST-free, export, etc. | | Items | `/api/v1/items/` | Products and services for invoicing | | Journal entries | `/api/v1/journal_entries/` | The ledger — double-entry core | | Invoices | `/api/v1/invoices/` | Sales invoices (AR) | | Bills | `/api/v1/bills/` | Purchase bills (AP) | | Payments | `/api/v1/payments/` | Customer payments + bill payments | | Credit notes | `/api/v1/credit_notes/` | Sales credit notes | | Supplier credit notes | `/api/v1/supplier_credit_notes/` | Purchase-side credit notes | | Quotes | `/api/v1/quotes/` | Sales quotes | | Purchase orders | `/api/v1/purchase_orders/` | PO lifecycle + convert-to-bill | | Expenses | `/api/v1/expenses/` | Cash / card expenditure | | Receipts | `/api/v1/receipts/` | Receipts linked to expenses | | Transfers | `/api/v1/transfers/` | Between own bank accounts | | Intercompany | `/api/v1/intercompany/` | Reciprocal inter-entity postings | | Reclassifications | `/api/v1/reclassifications/` | Reclassify posted transactions | | Bank accounts | `/api/v1/bank_accounts/` | Bank account registry | | Bank statement lines | `/api/v1/bank_statement_lines/` | Imported transactions + matching | | Bank feeds | `/api/v1/bank-feeds/` | Automated bank feed connections | | Bank rules | `/api/v1/bank_rules/` | Auto-coding rules for bank feed lines | | Reconciliation | `/api/v1/reconciliation/` | Match statement lines to journal entries | | Fixed assets | `/api/v1/fixed_assets/` | Asset register, depreciation, disposal | | Depreciation models | `/api/v1/depreciation_models/` | Depreciation rate / method definitions | | Projects | `/api/v1/projects/` | Segments / cost centres | | Recurring invoices | `/api/v1/recurring_invoices/` | Scheduled invoice generation | | Budgets | `/api/v1/budgets/` | Budget entries + variance reporting | | Allocations | `/api/v1/allocation_rules/` | Cost allocations across segments | | Cashbook | `/api/v1/cashbook/` | Cash-basis ledger entries | | Period close | `/api/v1/period-close/` | Lock / unlock accounting periods | | Proration | `/api/v1/proration/` | Period-prorated revenue calculation | | Reports | `/api/v1/reports/` | P&L, balance sheet, BAS, aged receivables, etc. | | Employees | `/api/v1/employees/` | Employee register | | Time entries | `/api/v1/time-entries/` | Time tracking | | Leave | `/api/v1/leave/` | Employee leave requests | | Pay runs | `/api/v1/pay-runs/` | Payroll pay runs | | STP submissions | `/api/v1/stp-submissions/` | Single Touch Payroll | | Super funds | `/api/v1/super-funds/` | Superannuation fund registry | | Super lodgements | `/api/v1/super_lodgements/` | Super payment lodgements | | TPAR | `/api/v1/tpar/` | Taxable payments annual report | | Tax returns | `/api/v1/tax_returns/` | Tax return records | | Statements | `/api/v1/statements/` | Supplier statements | | Statement templates | `/api/v1/statement-templates/` | Statement template management | | Attachments | `/api/v1/attachments/` | File attachments on records | | Documents | `/api/v1/documents/` | AI-powered document extraction | | Imports | `/api/v1/imports/` | CSV / bank statement import | | Audit log | `/api/v1/audit-log/` | Immutable audit trail | | Search | `/api/v1/search` | Full-text across contacts, invoices, journals | | Changes | `/api/v1/changes` | Audit change log | | Snapshot | `/api/v1/snapshot/` | Tenant data snapshot / export | | Licence | `/api/v1/license/` | Current licence state + refresh | | Lodgement | `/api/v1/lodgement/` | ATO SBR probe (Enterprise) | | Health | `/healthz`, `/version` | Liveness, version | ## Hand-written notes The [hand-written endpoint notes](endpoints/) cover the same API but narrated: pagination patterns, idempotency gotchas, why certain endpoints are shaped the way they are, and the soft-delete vs hard-delete distinction. Read those if you're new to the API; use the generated reference once you know what you're looking for. ## Are you an LLM reading this? There are machine-readable indexes at `/llms.txt` and `/llms-full.txt`. The raw OpenAPI document is at `/api/v1/openapi.json` — feed it directly to a code generator rather than scraping this site. See also the [LLM agent integration guide](../llm-agents/). # Authentication The JSON API at `/api/v1/*` uses **bearer authentication**. Tokens are issued by the `/api/v1/auth/login` endpoint and are JWT-signed with `SAEBOOKS_SECRET_KEY`. ## Bearer types ### JWT bearer (standard) Issued by `POST /api/v1/auth/login` (email + password) or by `POST /api/v1/auth/refresh`. Claims: ```json { "sub": "uuid-of-user", "tenant_id": "uuid-of-tenant", "role": "owner | admin | accountant | bookkeeper | viewer", "pwv": 0, "iat": 1714400000, "exp": 1714428800 } ``` `pwv` is the user's `password_version` counter. A password reset increments it, which invalidates every previously-issued token globally on the next request. Tokens issued before migration 0077 carry no `pwv` claim; the missing claim is treated as `0`, matching the column default. Default TTL is **8 hours** (`expires_in: 28800`). The `POST /auth/refresh` endpoint accepts an unexpired access token (via `Authorization: Bearer` header or `{"refresh_token": ""}` body) and issues a fresh one — there is no separate long-lived refresh token. The middleware loads the `User` row for `sub` and stamps `request.state.user` and `request.state.role`. Server-side role gates key off `request.state.role`, **not** the `role` claim directly — so a user whose role was downgraded between token issue and use is bound by the current DB role, not the stale claim. ### Machine API token Issued via `POST /api/v1/api-tokens` (requires an active JWT session — you cannot bootstrap a token from a token). The cleartext token is shown **once** and takes the format: ```text saebk_<64 lowercase hex chars> ``` The `saebk_` prefix lets `require_bearer` route to the API-token branch without attempting JWT decode. Tokens are bcrypt-hashed server-side and verified per-request. Optional `scopes` restrict access (`"read"` for safe methods, `"write"` for mutating methods; empty/`null` means full access). Optional `ttl_days` sets an expiry; omit for non-expiring. Manage tokens at `GET /api-tokens`, `DELETE /api-tokens/{id}`. ### Static dev token (scripts / testing only) `SAEBOOKS_DEV_API_TOKEN` in the environment. When this token is presented as `Authorization: Bearer `, the request is treated as authenticated without a real `User` row. Admin gates fall back to checking `X-Admin: true` in this mode. Production Do not set `SAEBOOKS_DEV_API_TOKEN` in production. ## Admin gate Endpoints that require admin role check: 1. `request.state.role` is `owner` or `admin` (preferred path) 1. `X-Admin: true` — only honoured on the static-token path A bookkeeper-role JWT presenting `X-Admin: true` is rejected with 403. ## Session flow (saebooks-web) The browser UI (`saebooks-web`) does not hold a JWT in `localStorage`. Instead: 1. `POST /login` on the web process validates credentials via the API, receives a JWT, and stores it in a signed server-side session cookie. 1. Every subsequent page request reads the JWT from the session and presents it as `Authorization: Bearer …` in the proxied API call. 1. `GET /auth/discourse/login` (DiscourseConnect) also reads the JWT from the session to fetch the user profile and sign the identity payload for Discourse. Session cookies are `SameSite=strict`, `HttpOnly`, signed with `SAEBOOKS_WEB_SECRET_KEY` using itsdangerous. They are not JWTs. ## Password reset / magic link | Flow | Steps | | ------------------ | --------------------------------------------------------------------------------------- | | Password reset | `POST /auth/password-reset/request` → email → `POST /auth/password-reset/confirm` → JWT | | Magic link | `POST /auth/magic-link/request` → email → `POST /auth/magic-link/consume` → JWT | | Email verification | After signup → `POST /auth/verify-email` → JWT | ## Examples ```bash # Login TOKEN=$(curl -sX POST https://books.example.com/api/v1/auth/login \ -H "Content-Type: application/json" \ -d '{"email":"you@example.com","password":"…"}' \ | python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])") # Authenticated request curl https://books.example.com/api/v1/auth/me \ -H "Authorization: Bearer $TOKEN" # Hard-delete (admin only) curl -X DELETE "https://books.example.com/api/v1/invoices/$ID?hard=true" \ -H "Authorization: Bearer $ADMIN_TOKEN" ``` # Conventions ## URL shape - Base: `https://books.example.com/api/v1` - Resource collection: `/api/v1/` (plural) - Resource item: `/api/v1//{id}` — `id` is always a UUIDv4 - Sub-resource: `/api/v1//{id}/` ## Verbs | Verb | Purpose | | -------- | ----------------------------------------------------------------------- | | `GET` | Read; pagination via `?page=` / `?page_size=` or `?limit=` / `?offset=` | | `POST` | Create; body is JSON, returns the created resource | | `PATCH` | Partial update; body is the diff | | `PUT` | Full replace (rarely used) | | `DELETE` | Soft-delete by default; `?hard=true` for hard-delete (admin) | ## Pagination Offset-based. Most list endpoints accept `?page=` (1-based, default 1) and `?page_size=` (default 50, max 500). Some endpoints use `?limit=` / `?offset=` directly. All list responses share the same envelope: ```text GET /api/v1/invoices?page=1&page_size=50 → { "items": [...], "total": 312, "limit": 50, "offset": 0 } ``` ## Errors All non-2xx JSON responses conform to [RFC 7807 Problem Details](https://www.rfc-editor.org/rfc/rfc7807) (`Content-Type: application/problem+json`): ```json { "type": "https://saebooks.io/problems/invoice_not_found", "title": "Invoice Not Found", "status": 404, "detail": "No invoice with that ID exists in this tenant.", "code": "invoice_not_found" } ``` `code` is a stable machine-readable identifier — key on it rather than parsing `detail` prose. For Pydantic validation failures (`422`), the response adds an `errors` array with per-field detail: ```json { "type": "https://saebooks.io/problems/validation_failed", "title": "Validation Failed", "status": 422, "code": "validation_failed", "detail": "Request body or query parameters failed validation.", "errors": [{"loc": ["body", "amount"], "msg": "must be >= 0", ...}] } ``` HTTP status follows the usual conventions: `400` bad request, `401` missing/bad bearer, `403` role gate failed, `404` not found, `409` write conflict (version mismatch or idempotency key conflict), `422` schema validation failure, `428` precondition required (missing `If-Match`), `5xx` server fault. ## Idempotency Most write endpoints accept `X-Idempotency-Key: `. On the first request the response is stored; retries with the same key and identical body return the stored response verbatim. Submitting the same key with a different request body returns `409` with code `idempotency_key_conflict`. ## Optimistic locking `PATCH` and `DELETE` on versioned resources (invoices, bills, payments, journal entries, etc.) require `If-Match: `, where `` is the integer `version` field from the most-recent `GET` response. A mismatch returns `409` with code `version_mismatch`. Omitting the header on a route that requires it returns `428` with code `precondition_required`. ## Time All timestamps are ISO-8601 with timezone (`...+10:00` for AEST). The server timezone is `Australia/Brisbane`. # Endpoints The live OpenAPI schema is at `https://books.example.com/api/v1/openapi.json` and the Swagger UI at `/api/v1/docs`. All paths below are relative to `https://books.example.com/api/v1`. Roles: `viewer` ⊂ `bookkeeper` ⊂ `accountant` ⊂ `admin` ⊂ `owner`. Hard-delete (`?hard=true`) is admin-only everywhere. ## Authentication | Method | Path | Auth | Notes | | ------ | ------------------------------ | ------ | ----------------------------------------------------------- | | POST | `/auth/login` | none | Email + password → `{access_token, token_type, expires_in}` | | POST | `/auth/refresh` | bearer | Unexpired token → fresh access token | | GET | `/auth/me` | bearer | Current user profile + role + tenant | | POST | `/auth/change-password` | bearer | Old + new password | | POST | `/auth/signup` | none | Create account + tenant (first-run) | | POST | `/auth/verify-email` | none | Email verification token → JWT | | POST | `/auth/resend-verification` | none | Re-send verification email | | POST | `/auth/password-reset/request` | none | Request password-reset email | | POST | `/auth/password-reset/confirm` | none | Reset token + new password → JWT | | POST | `/auth/magic-link/request` | none | Request magic-link email | | POST | `/auth/magic-link/consume` | none | Magic-link token → JWT | ## Users | Method | Path | Role | Notes | | ------ | ------------------------- | ----------- | --------------------------------- | | GET | `/users` | admin | List users in current tenant | | POST | `/users` | admin | Invite / create user | | GET | `/users/{id}` | admin, self | User detail | | PATCH | `/users/{id}` | admin, self | Partial update (role: admin only) | | DELETE | `/users/{id}` | admin | Soft-delete | | DELETE | `/users/{id}?hard=true` | admin | Hard-delete | | GET | `/users/{id}/permissions` | admin | Per-user overrides | | PUT | `/users/{id}/permissions` | admin | Replace permission set | ## Contacts (customers / vendors) | Method | Path | Role | Notes | | ------ | -------------------------- | ----------- | --------------------------------- | | GET | `/contacts` | bookkeeper+ | `?type=customer` / `?type=vendor` | | POST | `/contacts` | bookkeeper+ | | | GET | `/contacts/{id}` | bookkeeper+ | | | PATCH | `/contacts/{id}` | bookkeeper+ | | | DELETE | `/contacts/{id}` | bookkeeper+ | Soft | | DELETE | `/contacts/{id}?hard=true` | admin | | ## Invoices | Method | Path | Role | Notes | | ------ | -------------------------- | ----------- | ----------------------- | | GET | `/invoices` | bookkeeper+ | | | POST | `/invoices` | bookkeeper+ | | | GET | `/invoices/{id}` | bookkeeper+ | | | PATCH | `/invoices/{id}` | bookkeeper+ | | | DELETE | `/invoices/{id}` | bookkeeper+ | Soft; reverses postings | | DELETE | `/invoices/{id}?hard=true` | admin | | ## Bills Same shape as invoices — replace `/invoices` with `/bills`. ## Payments | Method | Path | Role | Notes | | ------ | -------------------------- | ----------- | ----- | | GET | `/payments` | bookkeeper+ | | | POST | `/payments` | bookkeeper+ | | | GET | `/payments/{id}` | bookkeeper+ | | | PATCH | `/payments/{id}` | bookkeeper+ | | | DELETE | `/payments/{id}` | bookkeeper+ | Soft | | DELETE | `/payments/{id}?hard=true` | admin | | ## Credit notes Same shape — `/credit_notes`. ## Journal entries | Method | Path | Role | Notes | | ------ | --------------------------------- | ----------- | --------------------- | | GET | `/journal_entries` | bookkeeper+ | | | POST | `/journal_entries` | bookkeeper+ | Creates + auto-posts | | GET | `/journal_entries/{id}` | bookkeeper+ | | | PATCH | `/journal_entries/{id}` | bookkeeper+ | Draft only | | DELETE | `/journal_entries/{id}` | bookkeeper+ | Soft (posts reversal) | | DELETE | `/journal_entries/{id}?hard=true` | admin | | | POST | `/journal_entries/{id}/post` | bookkeeper+ | Post a draft | | POST | `/journal_entries/{id}/reverse` | bookkeeper+ | Post a reversal | ## Accounts (chart of accounts) | Method | Path | Role | | ------ | ---------------- | ----------- | | GET | `/accounts` | bookkeeper+ | | POST | `/accounts` | admin | | GET | `/accounts/{id}` | bookkeeper+ | | PATCH | `/accounts/{id}` | admin | | DELETE | `/accounts/{id}` | admin | ## Bank accounts | Method | Path | Role | | ------ | --------------------- | ----------- | | GET | `/bank_accounts` | bookkeeper+ | | POST | `/bank_accounts` | admin | | GET | `/bank_accounts/{id}` | bookkeeper+ | | PATCH | `/bank_accounts/{id}` | admin | | DELETE | `/bank_accounts/{id}` | admin | ## Bank statement lines | Method | Path | Role | Notes | | ------ | ---------------------------------------- | ----------- | ----------------------- | | GET | `/bank_statement_lines` | bookkeeper+ | | | POST | `/bank_statement_lines` | bookkeeper+ | Manual import | | GET | `/bank_statement_lines/{id}` | bookkeeper+ | | | PATCH | `/bank_statement_lines/{id}` | bookkeeper+ | | | DELETE | `/bank_statement_lines/{id}` | bookkeeper+ | | | POST | `/bank_statement_lines/{id}/match` | bookkeeper+ | Link to journal/invoice | | POST | `/bank_statement_lines/{id}/unmatch` | bookkeeper+ | | | POST | `/bank_statement_lines/{id}/split_match` | bookkeeper+ | Multi-allocation | ## Reconciliation | Method | Path | Role | Notes | | ------ | ---------------------------------- | ----------- | ------------------------------- | | GET | `/reconciliation/accounts` | bookkeeper+ | Accounts available to reconcile | | GET | `/reconciliation/unmatched` | bookkeeper+ | Unmatched statement lines | | GET | `/reconciliation/suggest/{bsl_id}` | bookkeeper+ | AI-suggested match for a line | | POST | `/reconciliation/match` | bookkeeper+ | Confirm a match | | POST | `/reconciliation/unmatch/{id}` | bookkeeper+ | | | POST | `/reconciliation/auto_match` | bookkeeper+ | Run auto-match across unmatched | ## Reports All report endpoints are `GET /reports/` and accept `?date_from` / `?date_to` (ISO-8601) unless otherwise noted. | Path | Notes | | -------------------------------- | ----------------------------------------- | | `/reports/profit_loss` | P&L statement | | `/reports/balance_sheet` | Balance sheet at a point in time | | `/reports/trial_balance` | Debit/credit totals by account | | `/reports/cashflow` | Cash flow statement (indirect method) | | `/reports/aged_receivables` | AR ageing by contact | | `/reports/aged_payables` | AP ageing by contact | | `/reports/bas_summary` | BAS labels (G1, 1A, 1B, …) | | `/reports/budget_vs_actual` | Variance against budget for period | | `/reports/pl_by_segment` | P&L broken down by project/segment | | `/reports/revenue_by_customer` | Revenue ranked by contact | | `/reports/ytd_turnover` | Rolling 12-month revenue | | `/reports/depreciation_schedule` | Asset register with period charges | | `/reports/fx_revaluation` | FX gain/loss on foreign-currency balances | ## API tokens | Method | Path | Auth | Notes | | ------ | ------------------ | ---- | ------------------------------------------ | | POST | `/api-tokens` | JWT | Issue a new token; cleartext returned once | | GET | `/api-tokens` | JWT | List tokens for the current user | | DELETE | `/api-tokens/{id}` | JWT | Revoke a token | Issuance requires a live JWT session (not another API token). See [Authentication](../auth/#machine-api-token). ## Other resources All standard CRUD resources follow the `GET / POST / GET {id} / PATCH {id} / DELETE {id}` shape documented for invoices unless noted. | Resource | Prefix | Notes | | ------------------------- | ------------------------ | --------------------------- | | Items (products) | `/items` | | | Tax codes | `/tax_codes` | | | Fixed assets | `/fixed_assets` | | | Depreciation models | `/depreciation_models` | | | Projects / segments | `/projects` | | | Recurring invoices | `/recurring_invoices` | | | Quotes | `/quotes` | | | Expenses | `/expenses` | | | Receipts | `/receipts` | | | Transfers | `/transfers` | Between own bank accounts | | Intercompany postings | `/intercompany` | | | Supplier credit notes | `/supplier_credit_notes` | | | Journal templates | `/journal_templates` | | | Reclassifications | `/reclassifications` | | | Account ranges | `/account_ranges` | | | Bank rules | `/bank_rules` | | | Bank feeds | `/bank-feeds` | | | Budgets | `/budgets` | | | Allocations | `/allocation_rules` | | | Cashbook | `/cashbook` | | | Companies | `/companies` | | | Branches | `/branches` | | | Attachments | `/attachments` | | | Imports | `/imports` | CSV / bank statement import | | Documents (AI extraction) | `/documents` | | | Statements | `/statements` | Supplier statements | | Statement templates | `/statement-templates` | | | Period close | `/period-close` | | | Audit log | `/audit-log` | Read-only | | Changes | `/changes` | Audit change log | | Snapshot | `/snapshot` | | | Employees | `/employees` | | | Time entries | `/time-entries` | | | Leave | `/leave` | | | Pay runs | `/pay-runs` | | | STP submissions | `/stp-submissions` | | | Super funds | `/super-funds` | | | Super lodgements | `/super_lodgements` | | | TPAR | `/tpar` | | | Tax returns | `/tax_returns` | | | Search | `/search` | | ## Health | Path | Auth | Notes | | ---------- | ---- | ------------------------ | | `/healthz` | none | Liveness — always 200 OK | | `/version` | none | `{version, edition}` | ## See also - [Authentication](../auth/) - [Conventions](../conventions/) # API reference The interactive reference below is rendered **in your browser** from `openapi.json` — the same spec FastAPI emits at runtime, regenerated on every docs build. (Previously this page inlined the whole spec as static HTML, which made it ~18 MB; it now loads the spec client-side instead.) [**Raw OpenAPI document** (JSON)](https://dev.tasur.io/openapi/saebooks.json) [**Open in Swagger Editor**](https://editor.swagger.io/?url=https://dev.tasur.io/openapi/saebooks.json) # Modules # Accounting core The accounting module is the heart of Tasur. Every other module (bank feeds, GST/BAS, fixed assets, payroll) ultimately produces or consumes journals against the general ledger defined here. ## Chart of accounts A hierarchical list of accounts keyed by `code` (e.g. `1-1000`, `1-1000-01`). Eight account types (the `AccountType` enum): - `ASSET` - `LIABILITY` - `EQUITY` - `INCOME` - `OTHER_INCOME` - `EXPENSE` - `COST_OF_SALES` - `OTHER_EXPENSE` Each account carries a `tenant_id`, a `company_id`, an `is_header` flag (non-posting header rows), an `archived_at` timestamp (soft-delete), an optional `parent_id` (to form the tree), and a `tax_code_default` that informs the default GST code when a line is posted against the account. Bank-side accounts additionally carry ABA/Direct Entry fields (`bsb`, `bank_account_number`, `bank_account_title`, `apca_user_id`, `bank_abbreviation`) and an `account_kind` enum (`BANK_CHECKING`, `BANK_SAVINGS`, `CREDIT_CARD`, `BANK_LOAN`, `CASH`, `OTHER`) so credit cards, loans, and cash all appear in the bank-account list and on the dashboard. Credit-limit accounts carry `credit_limit` and `credit_limit_kind` (`soft` warns when exceeded; `hard` is enforced). Trust bank accounts are marked via `is_trust_account` (NSW Property Act commingling guard). Codes are advisory — they help humans group accounts and drive default report ordering, but the system identifies accounts by UUID. Renaming or recoding an account never breaks history. ## Journals & lines The atomic unit of bookkeeping is a **journal** with two or more **journal lines**. Each line is a debit or a credit against one account, with an amount in the journal currency. The journal is balanced (`SUM(debits) = SUM(credits)`) at post time — an unbalanced journal is rejected. flowchart LR Doc\[Source doc\ invoice / bill / payment\] --> Journal Journal --> Lines Lines --> Posting[(journal_lines)] Posting writes the lines to the `journal_lines` table (with status `POSTED`) and the parent `JournalEntry` is stamped `posted_at`. Reports query `journal_lines` joined to `journal_entries` filtered by status; only `POSTED` and `REVERSED` entries appear in financial reports (draft entries are excluded). ### Source documents and provenance Every journal entry carries an `origin` (a `JournalOrigin` enum stored as a plain string) that declares what created it, plus `source_type` and `source_id` pointing back to the originating record. This provenance keystone makes a hand-authored manual entry a visible exception (`MANUAL`) rather than indistinguishable from an engine-posted one. Declared origins (the full `JournalOrigin` enum): `MANUAL`, `UNKNOWN`, `INVOICE`, `CREDIT_NOTE`, `BILL`, `PAYMENT`, `EXPENSE`, `PAYRUN`, `DEPRECIATION`, `FX_REVAL`, `DEFERRED_REVENUE`, `BANK_REC`, `YEAR_END_CLOSE`, `TRUST_DISTRIBUTION`, `CASHBOOK_BACKFILL`, `FIXED_ASSET`, `REVERSAL`, `INTERCOMPANY`, `TRANSFER`, `SUPPLIER_CREDIT_NOTE`, `RECEIPT`, `RECLASSIFICATION`, `BAD_DEBT_WRITEOFF`, and `BAD_DEBT_RECOVERY`. `UNKNOWN` is the DB column default for pre-provenance rows (no backfill); `MANUAL` is the posting chokepoint default when no machine origin is declared. Journal entries also support optional `flagged_for_review` and `review_note` fields that let a reviewer mark a transaction for follow-up without changing its posting state. ## Reversal vs. hard-delete - **Reversal** posts an opposite journal that nets to zero. The original journal stays in history, and both rows are visible on audit reports. This is the correct path for *correcting* posted activity in a period that has been reported on. - **Hard-delete** removes the journal and its ledger rows. Admin-only, audited, used for bona-fide errors that should not appear in any report (test data accidentally posted to live, duplicate import runs, etc.). Hard-deleting a journal that crosses a closed period requires reopening that period first. ## Periods Period locking is implemented via the `period_locks` table (`PeriodLock` model). A lock has a `locked_through` date; the engine rejects any post dated on or before that date unless the lock is first removed. The lock row itself carries `locked_by` (the actor's user ID) and an optional `reason` field. Unlock is performed by deleting the `PeriodLock` row; no separate audit-log entry is written for the lock or unlock — the `period_locks` table is the record. ## Currency AUD is the default reporting currency. Foreign-currency transactions are stored in their original currency and converted to AUD at the exchange rate on the document date. Unrealised FX gains/losses on open AR/AP are computed on revaluation runs (origin `FX_REVAL`) and posted as their own journals — see `saebooks.services.fx.reval`. ## Reporting The standard reports under `/api/v1/reports/`: | Report | Endpoint | | --------------------- | ------------------------------------ | | Trial balance | `GET /reports/trial_balance` | | Profit & Loss | `GET /reports/profit_loss` | | Balance sheet | `GET /reports/balance_sheet` | | Aged receivables | `GET /reports/aged_receivables` | | Aged payables | `GET /reports/aged_payables` | | Cash flow statement | `GET /reports/cashflow` | | BAS summary | `GET /reports/bas_summary` | | Depreciation schedule | `GET /reports/depreciation_schedule` | | FX revaluation | `GET /reports/fx_revaluation` | | Budget vs actual | `GET /reports/budget_vs_actual` | | P&L by segment | `GET /reports/pl_by_segment` | | Revenue by customer | `GET /reports/revenue_by_customer` | | YTD turnover | `GET /reports/ytd_turnover` | Note: endpoint names use underscores, not hyphens. Reports are computed on demand; there is no nightly aggregation step to break. # Bank feeds Tasur ingests bank transactions via the **CDR (Consumer Data Right)** open-banking framework, brokered through an aggregator (currently SISS Data Services / ACSISS). The integration is generic over the aggregator — adding a second provider is a contract implementation, not a rewrite. Provisional Bank-feed onboarding is gated behind manual NDA + consumer-consent flows administered by the aggregator. The integration code lives in `saebooks.services.bank_feeds` but the production wiring is not yet enabled in the community edition. Self-hosters who want to run feeds today need to plumb in their own aggregator credential pair and accept the NDA terms directly. ## Why CDR Australia's CDR regime is the closed door behind which "screen scraping" used to live. Going through a CDR-accredited aggregator gives: - A consent UI the consumer trusts (it lives at the bank) - Refresh tokens with explicit lifetimes the consumer can revoke - Standardised JSON shapes across all major banks - A defensible audit trail when the ATO or the consumer asks "where did this data come from?" The downside is that aggregator integration is paperwork-heavy — there's an NDA, a fitness-and-propriety check, and quarterly attestations. Tasur abstracts that out so an end customer sees "connect bank" and not "fill in this 38-page form". ## Flow sequenceDiagram actor User participant App as Tasur participant Aggr as Aggregator participant Bank User->>App: Connect bank App->>Aggr: Begin consent Aggr->>Bank: OAuth/CDR consent Bank-->>User: Consent UI User->>Bank: Approve Bank-->>Aggr: Tokens Aggr-->>App: Webhook + tokens loop Daily App->>Aggr: Pull transactions Aggr->>Bank: CDR /accounts/{id}/transactions Bank-->>Aggr: Transactions Aggr-->>App: Normalised JSON App->>App: Match → suggest journal end The pull cadence is configurable per tenant — the default is daily, but high-volume tenants run hourly. Webhooks from the aggregator trigger an out-of-band pull when fresh data is available, so users rarely wait 24 hours to see a transaction. ## Data model Incoming bank lines land in `bank_statement_lines` with one of four states: - `UNMATCHED` — no journal yet; awaiting rule or human review - `PARTIAL` — partially allocated (split across multiple targets) - `MATCHED` — fully reconciled - `IGNORED` — explicitly excluded (test transactions, duplicates) Allocations are recorded as rows in `bsl_matches`, a junction table that links a bank statement line to one or more targets (each `target_type` is either `PAYMENT` or `JOURNAL_ENTRY`). A single deposit can be split across multiple payments — each split gets its own `bsl_matches` row. The sign convention is that amounts on deposit lines are positive and withdrawal lines negative. Each `bank_statement_line` also tracks which `bank_feed_account_id` it came from (the aggregator-side account link) and an `external_id` used to deduplicate on resync. ## Matching pipeline Incoming bank lines run through a rules pipeline, in order: 1. **Bank rules** — per-company rules matched against the line description using one of four match types: `CONTAINS`, `STARTS_WITH`, `EXACT`, or `REGEX`. Rules are ordered by `priority` (descending) then `name`. The first matching rule wins. If the rule has `auto_create=True` a posted journal entry is created automatically; otherwise the rule is suggested for human confirmation. 1. **Manual classification** — lines with no matching rule fall through to the operator UI for manual account selection. Rules map a bank line to a GL account and optional tax code, and can also associate a contact (customer/supplier) and a custom description template. ## Reconciliation Reconciliation runs as an offline sweep (`saebooks.services.bank_feeds.reconcile`). For each active feed account the sweep computes: - **Feed total** — sum of all `bank_statement_lines.amount` for the feed - **GL total** — sum of `journal_lines` (debit − credit) on the linked ledger account for `POSTED` and `REVERSED` entries - **Variance** — `feed_total − gl_total`; anything over $0.01 is flagged - **Unmatched count** — lines still in `UNMATCHED` status - **Staleness** — last statement line older than 7 days Each feed account gets a severity: `ok`, `warn` (unmatched lines), or `error` (stale feed or GL variance). The operator dashboard surfaces this at `/admin/bank-feeds/health`. The sweep is read-only — it writes nothing. The CLI entry point is `python -m saebooks.cli reconcile-feeds`. ## Failure modes - **Consent expired** — consumer has revoked the bank's consent or the 12-month CDR cap has lapsed. The user sees a "reconnect" CTA; no transactions are lost, just paused. - **Aggregator outage** — the daily pull fails, the next pull catches up automatically. Webhooks may be delayed. - **Bank schema change** — the aggregator usually absorbs these; if it doesn't, the integration logs a structured error referencing the offending field and the row is left in `UNMATCHED` status. All three failure modes are visible in the operator dashboard at `/admin/bank-feeds/health`. # Fixed assets Asset register, depreciation schedules, disposal handling, and the plumbing into the general ledger. Designed around the way Australian tax law treats capitalised items, but the underlying model is generic enough to drive other jurisdictions. ## Concepts - **Asset** — a single capitalised item with a cost, in-service date, depreciation model, and three paired GL accounts (cost, accumulated depreciation, depreciation expense). Physical tracking fields (serial number, location, custody person, manufacturer, warranty) are optional. - **Depreciation model** — a row in the `depreciation_models` catalogue (keyed by slug, e.g. `asset_5_year_linear`, `asset_dv_30`) that declares the method and rate. Every asset references one book model; an optional second `tax_model_id` provides a separate tax-depreciation overlay for reporting (never posted to GL). - **Depreciation** — compute-on-demand. There is no stored schedule table. The engine derives "amount owed through date X" from the asset's cost, residual value, in-service date, and model, then subtracts what has already been posted (tracked by the `last_depreciation_posted_through` cursor on the asset row). Re-running with the same through-date is a guaranteed no-op. - **Posting** — `post_depreciation()` in `saebooks.services.assets` posts a Dr Depreciation Expense / Cr Accumulated Depreciation journal per asset and advances the cursor. - **Disposal** — `dispose_asset()` first catches depreciation up to the disposal date, then posts the closeout journal (Dr cash/bank + Dr accumulated depreciation / Cr cost + Cr/Dr gain or loss). A **partial disposal** (`dispose_partial()`) splits the asset into parent (reduced cost, stays active) and child (disposed fraction) rows, then runs the full disposal against the child. - **Convert to inventory** — `convert_to_inventory()` handles items that leave the fixed-asset register and become stock. ## Depreciation methods | Model slug | Method | Notes | | ----------------------- | ------------------- | ------------------------------------------------------ | | `asset_no_depreciation` | `no_depreciation` | Land, non-depreciating assets; always yields $0 | | `asset_3_year_linear` | `linear` | Straight-line over 3 years; `(cost − residual) / life` | | `asset_4_year_linear` | `linear` | Straight-line over 4 years | | `asset_5_year_linear` | `linear` | Straight-line over 5 years | | `asset_10_year_linear` | `linear` | Straight-line over 10 years | | `asset_20_year_linear` | `linear` | Straight-line over 20 years | | `asset_dv_40` | `diminishing_value` | 40% per annum DV; `book_value × rate / 12` per month | | `asset_dv_30` | `diminishing_value` | 30% per annum DV | | `asset_dv_20` | `diminishing_value` | 20% per annum DV | | `asset_dv_15` | `diminishing_value` | 15% per annum DV | | `asset_dv_10` | `diminishing_value` | 10% per annum DV | | `asset_dv_5` | `diminishing_value` | 5% per annum DV | Linear depreciation uses day-count proration (365.25/12 ≈ 30.4375 days/month). Diminishing-value steps month-by-month, prorating the first and last months, and caps at `cost − residual` so book value asymptotes to salvage without overshooting. Method-and-rate calculation lives in `saebooks.services.assets` (`_cumulative_linear` / `_cumulative_dv`). New methods are added by extending the `_cumulative_for_model` dispatch in that module. ## Posting model A typical asset's lifecycle journals look like: | Event | Dr account | Cr account | | ---------------- | ---------------------------- | ----------------------------- | | Acquisition | Asset (`cost_account_id`) | Bank / Trade payables | | Depreciation | Depreciation expense | Accumulated depreciation | | Disposal — sale | Bank (proceeds) + Accum dep | Asset cost + Gain on disposal | | Disposal — scrap | Accum dep + Loss on disposal | Asset cost | The three GL accounts are specified per asset at creation: `cost_account_id`, `accum_dep_account_id`, and `dep_expense_account_id` (all three are required in the API; the CSV import path defaults `dep_expense_account_code` to `6-1500 Depreciation Expense` when the column is omitted). Disposal journals carry `origin = DEPRECIATION` for the catch-up step and `origin = FIXED_ASSET` for the final closeout. Partial disposals split the asset row and dispose only the child fraction. ## ATO compliance Effective lives are represented through the depreciation model catalogue. Override the model on the asset to use a self-determined life — the asset's change log records the override and the user who applied it. Tax depreciation (e.g. for schedules that differ from book) can be tracked via the optional `tax_model_id` on the asset. This is a reporting-only overlay and never drives GL postings — it is used solely to produce the book-vs-tax temporary difference column on the depreciation schedule report. ## Reports | Report | Endpoint | | ---------------------------------- | ------------------------------------------- | | Depreciation schedule (all assets) | `GET /api/v1/reports/depreciation_schedule` | The depreciation schedule report lists all active (non-disposed, non-archived) assets with their cost, accumulated depreciation, net book value, and tax written-down value (when a `tax_model_id` is set) as at a given `as_of_date` (defaults to today). Output is JSON; CSV download is available via the web router. The report also accepts a `method` filter (`STRAIGHT_LINE`, `DECLINING_BALANCE`, `linear`, `diminishing_value`). ## Bulk operations Importing an existing asset register (from a migration off Xero / MYOB / QuickBooks) is a common day-one task. The import is a two-step parse - apply flow (same pattern as the chart-of-accounts import): **Required CSV columns:** `code`, `name`, `purchase_date`, `cost`, `depreciation_model_id`, `cost_account_code`, `accum_dep_account_code` **Optional CSV columns:** `in_service_date`, `residual_value`, `dep_expense_account_code`, `description`, `serial_number`, `manufacturer`, `model_number`, `location`, `custody_person`, `warranty_end` `depreciation_model_id` is the catalogue slug (e.g. `asset_5_year_linear`, `asset_dv_30`). Account codes are the hyphenated form stored in the DB (e.g. `1-3310`). The import is idempotent on `(company_id, code)` — re-running the same CSV twice adds zero new rows. Rows with an existing code are classified as `skip`; parse/resolution failures are classified as `invalid` and reported line-by-line without blocking valid rows. The `apply` step commits all `create` rows atomically. # GST & BAS Tasur handles Australian GST natively — every transaction line carries a `tax_code`, GST is computed at the line level, and the running BAS report is regenerated incrementally as new transactions post. ## Tax codes The shipped AU tax codes: | Code | Rate | `reporting_type` | Meaning | | ----- | ---- | ---------------- | ------------------------------------------------------- | | `GST` | 10% | `taxable` | Standard taxable supply | | `CAP` | 10% | `capital` | Capital acquisition (BAS G10, reported separately) | | `FRE` | 0% | `gst_free` | GST-free (basic food, exports, healthcare, etc.) | | `INP` | 0% | `input_taxed` | Input-taxed sale (residential rent, financial supplies) | | `EXP` | 0% | `export` | Export of goods/services (with documentation) | | `N-T` | 0% | `out_of_scope` | Not reportable (wages, drawings, owner transfers) | | `MGN` | 0% | `margin_scheme` | Margin scheme — Div 75 GSTA 1999 s66-50 | Custom tax codes can be added per tenant. Each code carries a `reporting_type` that the BAS engine uses to bucket lines into G1/G2/G3/G10/G11. The `tax_code_default` on an account drives automatic tagging when a line is posted against that account. Reverse-charge and import codes are not in the standard starter set `RCP` (Reverse Charge — Imported Services, 10%) and `IMP` (GST on Imports, 10%) are AU-jurisdiction codes available via `ensure_international_seed()` but are not part of the seven-code standard AU starter set. Use `INP` for residential-rent / financial-supply input-taxed supplies. ## How GST is computed GST is stored on the journal line, not derived at report time: ```python class JournalLine: debit: Decimal # debit amount (ex-GST for taxable lines) credit: Decimal # credit amount (ex-GST for taxable lines) tax_code_id: UUID | None # FK to tax_codes gst_amount: Decimal | None # GST amount (computed at post) tax_treatment: dict | None # per-line tax snapshot (JSONB) ``` `gst_amount` is locked when the journal is posted. The `tax_treatment` JSONB snapshot captures the tax-code state at post time so audit history stays self-consistent even if a tax code is later edited. Subsequent changes to the tax-code rate only affect *new* journals, never historical postings. GST auto-posting is handled by `saebooks.services.tax_engine.au` (previously `saebooks.services.gst`, now a deprecated shim). When a taxable line posts, the engine creates a corresponding credit/debit on the GST Collected or GST Paid control account configured in company settings (`gst_collected_account_code` / `gst_paid_account_code`). ## BAS preparation `GET /api/v1/reports/bas_summary` accepts a date range and returns the BAS labels as a summary object: ```text GET /api/v1/reports/bas_summary?from_date=2026-01-01&to_date=2026-03-31 ``` Response includes fields for `G1`, `G2`, `G3`, `G10`, `G11`, `1A`, and `1B` as computed from posted journal lines for the period. BAS logic: - **G1** — net sales on `INCOME`/`OTHER_INCOME` accounts with `reporting_type = "taxable"` - **G2** — export sales (`reporting_type = "export"`) - **G3** — GST-free sales (`reporting_type = "gst_free"`) - **G10** — capital purchases (`reporting_type = "capital"`) - **G11** — non-capital taxable purchases (`reporting_type = "taxable"` on expense/COGS accounts) - **1A/1B** — sourced directly from the GST Collected and GST Paid control account balances for the period When `registration_effective_date` falls within the period the report splits pre- and post-registration sales — pre-registration sales are disclosed but excluded from 1A/1B (ATO compliance for mid-quarter GST registration). The BAS settlement journal (clearing GST Collected and GST Paid to the BAS Payments/Receivable account) is generated by `POST /reports/bas/settle` on the web router. ## E-lodgement (SBR) The **community edition** exports a CSV / XML pack for manual lodgement via the ATO Business Portal or your tax agent's software. The **enterprise edition** ships an SBR (Standard Business Reporting) adapter that lodges the BAS directly using a **Machine Credential** issued through the ATO's [Relationship Authorisation Manager (RAM)](https://info.authorisationmanager.gov.au/). This is the same mechanism Xero / MYOB use; Tasur just runs it on hardware you control rather than someone else's SaaS. Setting up the credential is a one-time operator task — see [ATO SBR onboarding](https://www.sbr.gov.au/) for the credential setup, and the lodge-server contract documented under Operations. ## Common gotchas - **Wine equalisation tax (WET)** and **luxury car tax (LCT)** are separate from GST and require the relevant feature flag. They show up as additional BAS labels (`1C`, `1D`, `1E`, `1F`). - **Cash vs. accruals** GST is a *tenant setting* — it determines whether GST is reported in the period of the invoice (accruals) or the payment (cash). Switching mid-year requires a one-off journal to bring opening balances onto the new basis. - **Round-half-to-even** is used for tax-amount rounding to match the ATO's published behaviour. Don't change this unless you have a written ruling that says otherwise. # Operations # Deployment ## Reference stack The reference production deployment runs on a single Linux host (bosun — HPE ML350 Gen10) using Docker Compose with Caddy as the reverse proxy. Services are separated by compose project: ```text /home/sauer/bosun/compose/ ├── saebooks-sauer/ # saebooks-api + saebooks-web + postgres │ ├── docker-compose.yml │ └── .env # secrets, not committed ├── discourse/ # discourse.saebooks.com.au ├── edge-proxy/ # Caddy reverse proxy + ACME └── ... ``` The Postgres data volume is a named volume (`db_data`) within the compose project. Mail outbox files land at `/opt/data/saebooks-sauer/mail-outbox` on the host. ## Caddy routing The web container is reachable from Caddy over the shared `revproxy` Docker network (compose service name `web`, internal port `8080`). The API container (`api`, internal port `8000`) is never exposed publicly — the web process reaches it via the internal compose network at `http://api:8000`. A gRPC-Web proxy (`grpcwebproxy`) is also present for the desktop client. ## Environment variables ### saebooks-api | Variable | Required | Notes | | --------------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `DATABASE_URL` | yes | Owner-role (BYPASSRLS) URL — used by Alembic migrations and pre-auth lookups (`LoginSessionLocal`). `postgresql+asyncpg://saebooks:…@db:5432/` | | `SAEBOOKS_APP_DATABASE_URL` | yes (prod) | Runtime URL for the non-superuser `saebooks_app` role — required when `SAEBOOKS_ENV` is not `dev`/`test`/`ci`; see migration `0056_split_db_role`. | | `SAEBOOKS_APP_DB_PASSWORD` | yes (prod) | Password for `saebooks_app`; also read by migration `0128_app_role`. | | `SAEBOOKS_SECRET_KEY` | yes | HMAC secret for issued JWTs; 32+ random bytes. If unset, a per-process random key is generated (safe for dev/single-process only). | | `SAEBOOKS_EDITION` | no | `community` (default), `offline`, `business`, `pro`, `enterprise`. When set to any value other than `community`, the licence resolver is bypassed entirely (USB and portal JWT drivers are skipped). Intended for development; a warning is logged on startup. | | `STRIPE_SECRET_KEY` | for billing | `sk_test_…` or `sk_live_…` | | `STRIPE_WEBHOOK_SECRET` | for billing | `whsec_…` | ### saebooks-web | Variable | Required | Notes | | -------------------------- | -------------------- | ------------------------------------------------------ | | `SAEBOOKS_WEB_API_URL` | yes | Base URL of saebooks-api (e.g. `http://api:8000`) | | `SAEBOOKS_WEB_SECRET_KEY` | yes | Session cookie signing secret | | `DISCOURSE_SSO_SECRET` | for DiscourseConnect | Shared secret for DiscourseConnect `/auth/discourse/*` | | `SAEBOOKS_WEB_SITE_ORIGIN` | yes | Comma-separated allowed origins for CSRF enforcement | | `SAE_STAFF_USERNAMES` | no | Comma-separated staff usernames for admin bypass | ## Build and deploy The compose files use local build contexts (no registry). To deploy a code change: ```bash # On bosun cd /home/sauer/bosun/compose/saebooks-sauer sudo docker compose build web sudo docker compose up -d web ``` To update the API (includes Alembic upgrade): ```bash sudo docker compose build api sudo docker compose up -d api # Alembic upgrade head runs on container start via entrypoint.sh ``` ## Health probes | Path | Service | Purpose | | ----------------- | -------- | ---------------------------------------------------------------- | | `/healthz` | api, web | Liveness — always 200 while the process is up (no DB round-trip) | | `/api/v1/healthz` | api | Canonical liveness path for external probes | | `/api/v1/version` | api | Edition + package version (unauthenticated) | | `/api/v1/docs` | api | Swagger UI (restrict in prod) | Note A `/readyz` readiness probe has not yet been implemented. The `/healthz` liveness probe intentionally skips the DB round-trip. ## Log access ```bash sudo docker logs saebooks-sauer-web-1 --since 30m sudo docker logs saebooks-sauer-api-1 --since 30m -f ``` The web process tags logs `saebooks_web`; the API tags `saebooks`. ## Backup Nightly `pg_dump` of the database via a cron job or `make backup` (which runs `scripts/backup.sh`). The Postgres data volume is the named volume `db_data` within the compose project. # Migrations Tasur uses **Alembic** for schema migrations. Migration files live in `alembic/versions/` and follow the convention `NNNN_short_slug.py` where `NNNN` is a 4-digit zero-padded sequence (e.g. `0170_ephemeral_demo_tenants.py`). Tip Migration IDs go up monotonically across all branches. **Don't reuse a number** — if you cherry-pick a migration into a different chain, renumber to the next free slot. Alembic will reject a duplicate `revision` ID at runtime, but the friendly fix is to avoid the collision in the first place. ## Adding a migration The Makefile `revision` target wraps `alembic revision`: ```bash make revision m="add foo to bar" # → alembic/versions/NNNN_add_foo_to_bar.py ``` For an autogenerated diff from your model changes, run the command directly: ```bash docker compose exec app alembic revision --autogenerate -m "add foo to bar" ``` Review the generated diff carefully — Alembic autogen handles columns and indexes well but has known blind spots (server defaults, check constraints, enum types). Hand-edit where needed. ## Applying ```bash # Via Makefile (recommended during development) make migrate # Or directly docker compose exec app alembic upgrade head ``` ## Rollback ```bash docker compose exec app alembic downgrade -1 ``` `downgrade -1` walks back one revision. **Be cautious in prod** — downgrades that drop columns or tables are destructive. ## Production deploys `entrypoint.sh` runs `alembic upgrade head` before starting uvicorn on every container start. If a migration fails, the container exits non-zero and the orchestrator restarts it. To force a manual run, exec into a healthy container and run `alembic upgrade head` interactively, then restart the container. Warning Migration `0128_app_role` reads `SAEBOOKS_APP_DB_PASSWORD` from the environment. This variable **must** be set in the compose `.env` before running migrations on a fresh database; the migration refuses to apply if the variable is absent or empty. # Tenancy & RLS Tasur is multi-tenant. Each domain table has a `tenant_id UUID NOT NULL` column, and Postgres row-level security (RLS) enforces that no query can read or write rows from another tenant. ## Mechanism ```sql ALTER TABLE invoices ENABLE ROW LEVEL SECURITY; ALTER TABLE invoices FORCE ROW LEVEL SECURITY; CREATE POLICY tenant_isolation ON invoices FOR ALL USING (tenant_id = current_setting('app.current_tenant', true)::uuid) WITH CHECK (tenant_id = current_setting('app.current_tenant', true)::uuid); ``` `FORCE ROW LEVEL SECURITY` is critical — without it, the table owner (the schema-owner role the app historically connected as) bypasses RLS entirely. `WITH CHECK` gates writes as well as reads, so an `INSERT`/`UPDATE` writing a foreign `tenant_id` is also blocked. Both were added by migration `0055_force_rls_and_complete_policies`. At the start of every SQLAlchemy transaction the app issues: ```sql SET LOCAL app.current_tenant = ''; ``` This is wired via a process-wide `after_begin` SQLAlchemy event listener in `saebooks/api/v1/deps.py`. The listener reads the tenant UUID from `session.info['tenant_id']`, which is stamped by the `get_session` dependency (JSON API paths) or the auth middleware (HTML paths) after resolving the JWT. `SET LOCAL` is transaction-scoped and resets automatically on commit or rollback — no manual teardown needed. ## Database roles Two Postgres roles enforce the split (migrations `0056_split_db_role`, `0128_app_role`): | Role | Used by | `BYPASSRLS` | Purpose | | -------------- | ----------------------- | ----------- | ---------------------------------------------------- | | `saebooks` | Alembic, CLI DDL | yes (owner) | Schema-owner role; not used for request-time queries | | `saebooks_app` | Runtime API, CLI walker | no | `NOSUPERUSER NOBYPASSRLS` — FORCE RLS binds it | The runtime `AsyncSessionLocal` connects as `saebooks_app` (configured via `SAEBOOKS_APP_DATABASE_URL`). Alembic migrations still run as `saebooks` so DDL works without RLS friction. Pre-authentication lookups (login by email, signup uniqueness checks) use a separate `LoginSessionLocal` that connects as the owner role, because `app.current_tenant` is not yet known at login time and FORCE-RLS on the `users` table would otherwise return zero rows for every login. ## Why RLS, not WHERE-clause filtering? RLS is enforced at the planner level, so a forgotten `WHERE tenant_id = ...` (or a SQL injection that bypasses an ORM clause) still can't return another tenant's data. We treat it as the last line of defence — the application also filters explicitly on `tenant_id`, but RLS catches every missed case. ## Audit `audit_log` (migration `0076_audit_log`) records hard-delete and other privileged operations. The log captures actor, target tenant, table, row IDs, and operation. # Identity & SSO # DiscourseConnect (SSO) Discourse is the **identity provider**. Tasur is the **consumer** (relying party). When a user clicks "Log in with Discourse" on the Tasur login page, their browser is sent to Discourse's `/session/sso_provider` endpoint, where Discourse authenticates them and signs a response redirecting them back to Tasur. Architecture direction This is the opposite of the old design (pre-2026-04-29) where Tasur acted as the provider. The old flow used `/forum/session/sso_provider` on Tasur — that path is gone. The current flow originates on Tasur and delegates authentication *to* Discourse. ## How the flow works sequenceDiagram actor User participant App as Tasur (/auth/discourse/login) participant Disc as Discourse (/session/sso_provider) User->>App: Click "Log in with Discourse" App->>App: Generate nonce; sign nonce cookie\ (HMAC-SHA256 with session secret) App-->>User: 303 → discourse.../session/sso_provider?sso=…&sig=… User->>Disc: GET /session/sso_provider?sso=…&sig=… Disc->>Disc: Verify HMAC-SHA256 signature\ Authenticate user (existing session or login prompt) Disc-->>User: 303 → books.example.com/auth/discourse/callback?sso=…&sig=… User->>App: GET /auth/discourse/callback?sso=…&sig=… App->>App: Verify HMAC-SHA256 signature\ Verify nonce cookie (replay protection) App->>App: POST /api/v1/auth/oauth-handoff\ (provider=discourse, external_id, email, display_name) App->>App: Set session cookie (api_token) App-->>User: 303 → / ## Endpoints (saebooks-web) ```text GET https://books.example.com/auth/discourse/login ``` Initiates the flow. Generates a nonce, stores it in an HMAC-signed cookie (`sae_discourse_nonce`, TTL 10 minutes), and redirects the browser to Discourse's `sso_provider` endpoint. ```text GET https://books.example.com/auth/discourse/callback?sso=&sig= ``` Handles the Discourse callback. Both are handled by `saebooks_web/discourse_sso.py`. Neither is an API endpoint — both are browser redirect handlers. ## Payload — inbound (Discourse → Tasur callback) Discourse builds and signs this payload before redirecting the user back. | Field | Notes | | ------------- | -------------------------------------------------------------- | | `nonce` | Echoed back from the outbound payload; checked against cookie. | | `external_id` | Discourse user ID — stable key used as `provider_user_id`. | | `email` | User's verified email on Discourse. | | `username` | Discourse username handle. | | `name` | Display name (falls back to `username` then `email`). | The raw payload is `nonce=…&external_id=…&email=…&…`, base64-encoded and HMAC-SHA256 signed with the shared secret. ## Payload — outbound (Tasur → Discourse login request) Tasur builds and signs this payload before redirecting the user to Discourse. | Field | Notes | | ---------------- | --------------------------------------------------- | | `nonce` | Random; echoed back to prevent replay. | | `return_sso_url` | `https://books.example.com/auth/discourse/callback` | ## Shared secret Both sides hold the same HMAC-SHA256 secret. On Discourse it is the `discourse_connect_secret` site setting. On Tasur it is the `DISCOURSE_SSO_SECRET` environment variable (set on `saebooks-web`). Rotate the secret by updating both sides simultaneously and restarting `saebooks-web`. Any in-flight login attempt during rotation will fail cleanly (the user gets an error page and can retry). ## Session handoff to saebooks-api After verifying the Discourse payload, `saebooks-web` does **not** create a session directly. Instead it calls the internal oauth-handoff endpoint: ```text POST /api/v1/auth/oauth-handoff X-OAuth-Handoff-Secret: { "provider": "discourse", "provider_user_id": "", "email": "", "display_name": "" } ``` On success the API returns `{"access_token": ""}`. The web layer stores this in the session cookie (`session["api_token"]`) and fetches `/api/v1/auth/me` to populate `session["username"]` and `session["user_role"]`. Both `DISCOURSE_SSO_SECRET` and `SAEBOOKS_OAUTH_HANDOFF_SECRET` must be set on `saebooks-web`. Missing either disables the flow or causes a 500 error with a clear message logged. ## Discourse settings These site settings are set via the Discourse admin panel and held in the database (not in the compose env vars): | Setting | Value | | -------------------------- | ------------------------------------------------ | | `enable_discourse_connect` | `true` (Tasur is an SSO consumer) | | `discourse_connect_url` | `https://books.example.com/auth/discourse/login` | | `discourse_connect_secret` | *(shared secret, see above)* | `openid_connect_enabled` must be `false` — it and DiscourseConnect are mutually exclusive. Setting the `DISCOURSE_OPENID_CONNECT_*` env vars in the Discourse compose file forces OIDC on at startup and overrides the database setting; those env vars must be absent. ## Environment variables (saebooks-web) | Variable | Description | | ------------------------------- | ------------------------------------------------------------------------------ | | `DISCOURSE_SSO_SECRET` | Shared HMAC-SHA256 secret; must match `discourse_connect_secret` in Discourse. | | `DISCOURSE_BASE_URL` | Discourse instance base URL (default: `https://discourse.saebooks.com.au`). | | `SAEBOOKS_WEB_PUBLIC_BASE_URL` | Public base URL of saebooks-web (default: `https://app.saebooks.com.au`). | | `SAEBOOKS_OAUTH_HANDOFF_SECRET` | Shared secret for the internal oauth-handoff API call. | Discourse login is disabled (button hidden) when `DISCOURSE_SSO_SECRET` is unset or empty. ## SAE staff flag After a successful Discourse login, the session's `is_sae_staff` flag is set based on the `SAE_STAFF_USERNAMES` env var (comma-separated list of usernames or emails). This gate controls access to internal tooling routes (e.g. `/admin/inspect`, agent routes) and is distinct from the user's `role` field on the account. ## Testing locally Set `DISCOURSE_SSO_SECRET` to any 32+ char value and exercise the callback endpoint directly by building a test payload: ```python import base64, hashlib, hmac, urllib.parse, time, secrets secret = b"your-test-secret" nonce = secrets.token_urlsafe(16) # Build the payload Discourse would return payload = urllib.parse.urlencode({ "nonce": nonce, "external_id": "42", "email": "user@example.com", "username": "testuser", "name": "Test User", }) b64 = base64.b64encode(payload.encode()).decode() sig = hmac.new(secret, b64.encode(), hashlib.sha256).hexdigest() print(f"http://localhost:8043/auth/discourse/callback?sso={urllib.parse.quote(b64)}&sig={sig}") ``` Navigate to the printed URL (you will need a valid nonce cookie, which the `/auth/discourse/login` endpoint sets — run that first, then substitute the nonce from the cookie into the payload above). # Contributing # Releases Tasur follows **semantic versioning** with a calendar-suffix for preview builds. ```text 1.2.3 # stable 1.2.3-rc.1 # release candidate 2026.04+a3f # preview (CalVer + commit) ``` ## Branches - `main` — always green, deployable HEAD - `feature/` — short-lived feature branches - `release/` — cut from `main` for release stabilisation ## Cutting a release 1. Branch `release/1.2` from `main` 1. Bump `pyproject.toml` to `1.2.0-rc.1`, tag, push 1. Run the full test suite + integration smoke 1. Tag `1.2.0` once green; build and push images 1. Merge `release/1.2` back to `main` (fast-forward only) ## Image tagging The CI workflow (`build-images.yml`) builds multi-arch images (`linux/amd64`, `linux/arm64`) on every push to `main` and on version tags. The image name is `saebooks-api`; registry push configuration is pending a registry URL decision. Expected tag convention once configured: ```text saebooks-api:1.2.3 saebooks-api:1.2 saebooks-api:latest ``` ## Changelog Release notes are hand-curated, grouped by version with sub-sections `### Added`, `### Changed`, `### Fixed`, `### Removed`. There is no `CHANGELOG.md` in the repository yet — this convention applies from the first public release. ## Database migrations across releases Aim for **one migration step per release**. If you accumulate many schema changes during a development cycle, squash them into a single migration before tagging — easier to reason about for downstream operators applying the upgrade. A migration that drops a column or table needs a deprecation cycle: land the column-unused change in release N, then the drop in N+1 (or later). Never drop in the same release that stops writing. # Code style Tasur is a Python codebase. We use the standard tools. ## Tooling - **Formatter**: `ruff format` (Black-equivalent, 100 cols) - **Linter**: `ruff check` - **Types**: `mypy` in strict mode for new modules; legacy modules opted-in incrementally - **Tests**: `pytest` with `pytest-asyncio` Run lint and type checks before opening a PR: ```bash make lint # ruff check . make typecheck # mypy saebooks ``` ## Imports ```python from __future__ import annotations ``` at the top of every file. Then standard library, then third-party, then `saebooks.*`. `ruff` handles the sort. ## Naming - `snake_case` for functions, variables, modules. - `PascalCase` for classes. - `SCREAMING_SNAKE_CASE` for module-level constants. - Async functions get a `async_` prefix only when there is a same-named sync sibling and the disambiguation matters. Otherwise just `def` vs `async def`. ## Docstrings Module and public-API docstrings are required. They should explain **why** the code exists, not what each line does. Don't waste lines on restating the function signature. ## Errors - Validate at boundaries (HTTP, external APIs). Trust internal calls. - Raise `HTTPException` from FastAPI handlers; raise typed exceptions from service layers and let the handler translate. - Don't catch and re-log; let exceptions propagate to the global handler unless you can do something useful with them. ## Tests See [Testing](../testing/). # Testing ## Layout ```text tests/ ├── api/ # HTTP-level tests (httpx ASGITransport) │ └── v1/ ├── cli/ # CLI entrypoint tests ├── db/ # Migration and schema drift tests ├── grpc/ # gRPC server tests ├── integration/ # Cross-DB integration tests ├── middleware/ # Middleware-layer tests ├── models/ # Model + schema tests ├── services/ # Service-layer tests └── conftest.py # Shared fixtures ``` ## Run all tests The test stack is isolated: a dedicated Postgres on a private Docker network, a separate test image built from `Dockerfile.test`, and teardown on exit. **The live `app` container is built without dev dependencies — never run `pytest` against it.** ```bash cd /home/sauer/projects/saebooks bash scripts/run-tests.sh # full suite bash scripts/run-tests.sh -k journal # keyword filter bash scripts/run-tests.sh tests/api/v1/test_invoices.py # single file ``` The `Makefile` `test` target (`make test`) runs `pytest` inside a running dev container and is suitable for interactive iteration only after the dev stack is already up: ```bash make test # docker compose exec app pytest -q --asyncio-mode=auto ``` ## Database Tests use a real Postgres database (the same image as prod, fresh per run). **Do not mock the database** — see the project's history of mocked tests passing while real migrations failed in prod. `alembic upgrade head` runs inside the test container before `pytest`, so schema is always migrated from scratch. Tests marked `@pytest.mark.postgres_only` are skipped automatically when the `DATABASE_URL` points at SQLite (Cashbook edition). ## Async fixtures Use `pytest_asyncio` decorators: ```python import pytest_asyncio @pytest_asyncio.fixture async def my_user() -> AsyncIterator[User]: async with AsyncSessionLocal() as session: user = User(...) session.add(user) await session.commit() await session.refresh(user) yield user await session.execute(sa_delete(User).where(User.id == user.id)) await session.commit() ``` ## HTTP tests Use `httpx.AsyncClient` with `ASGITransport`: ```python from httpx import ASGITransport, AsyncClient from saebooks.main import app async def test_endpoint(): async with AsyncClient( transport=ASGITransport(app=app), base_url="http://test" ) as client: r = await client.get("/api/v1/...", headers={"Authorization": f"Bearer {token}"}) assert r.status_code == 200 ``` ## Coverage Aim for high coverage on new code in `saebooks/services/` and `saebooks/api/`. Money arithmetic changes require Hypothesis property tests (see `hypothesis` in the dev dependencies). # LLM agents # LLM agents — integration guide This page exists for **language models** building integrations against Tasur, and for the humans pointing them at this site. If you're a person, you can stop reading; the rest of the docs are written for you. If you're a model, the guidance below is what your operator wants you to follow. Pre-1.0 — do not treat this as a stable contract Tasur is in active development. The OpenAPI spec at `/openapi.json` describes the **current build**, not a frozen public API. Endpoint paths, parameter names, response shapes, and feature availability can change between releases without a deprecation cycle until 1.0. If you generate code from this spec, regenerate on every upgrade and review the diff. Production integrations should wait for the 1.0 release; until then, treat the documentation as a *design preview*. ## Machine-readable indexes - [`/llms.txt`](https://dev.tasur.io/llms.txt) — flat index of every page on this site, with one-line descriptions and `.md` URLs you can fetch directly. - [`/llms-full.txt`](https://dev.tasur.io/llms-full.txt) — concatenated full markdown of every page, suitable for loading into a single context window. - [`/openapi/saebooks.json`](https://dev.tasur.io/openapi/saebooks.json), the OpenAPI 3.1 spec for `/api/v1/*`, regenerated from the running server on every docs build. **This is the source of truth for endpoints and shapes.** - Every documentation page is also available with a `.md` suffix — for example returns the rendered markdown source for that page. ## Spec vs. prose during pre-1.0 When the prose on this site disagrees with the OpenAPI spec, the **spec describes what the running server will currently accept**, but neither the spec nor the prose is yet a public contract. Prose pages illustrate the intended shape; both move. If you generate code, generate from `/openapi.json`, and regenerate on every Tasur version bump. ## API surface preferences Prefer in this order: 1. **`/api/v1/*` JSON endpoints with `Authorization: Bearer `**. This is the public, supported API surface. Every example in these docs uses it. 1. **The web routes (no `/api/` prefix)** — these exist (they back the user-facing UI) but are not a stable contract. They return HTML, redirect, set cookies, and may be reshaped at any release. Don't write integrations against them. 1. **Direct database access** — possible because the user owns the Postgres instance, but undocumented and not version-stable. If you find yourself reaching for it, raise an issue first; an HTTP endpoint is almost always the right answer. ## Native MCP endpoint Every Tasur instance exposes an MCP server at `/mcp/` on the same host as the REST API. No separate container required. Configure your MCP client with: ```json { "mcpServers": { "saebooks": { "transport": "streamable-http", "url": "https://books./mcp/", "headers": { "Authorization": "Bearer saebk_..." } } } } ``` Issue `saebk_*` API tokens at `/admin/api-tokens` (browser session required). Each token is scoped to the issuing user's tenant — the MCP server enforces the same RLS isolation as the REST API. The tool surface is safety-gated via `SAEBOOKS_MCP_MAX_SAFETY`: `safe` (read-only), `mutation`, `void`, or `destructive` (default — all tools registered). A standalone container variant is also available for air-gapped workstations; see `mcp/README.md` in the source tree. ## Auth flow - Obtain a JWT via `POST /api/v1/auth/login` (email + password) **or** `POST /api/v1/auth/oauth-handoff` (server-side, after the user completes an OAuth dance with the host application). - Send `Authorization: Bearer ` on every subsequent request. - Refresh via `POST /api/v1/auth/refresh` before the token expires. - For long-lived integrations, prefer a dedicated *integration user* with its own credentials — not the human user's token. ## Idempotency Any non-idempotent write (POST that creates, PATCH that mutates external state) accepts an `X-Idempotency-Key: ` header. Use one. The server stores the response and returns it verbatim on replay. This matters because **agentic retries are common** — if your harness retries on a 500 without an idempotency key you may post the same journal twice. ## Errors Errors follow RFC 7807 Problem Details. The response body is `application/problem+json` with the shape `{type, title, status, detail, code}`. Read the `code` (machine-readable, stable) before the `detail` (human-readable, may include per-request context). Validation errors (`422`) also include an `errors` array with per-field failure detail. Status codes follow RFC 7231 / 9110: `400` validation, `401` auth, `403` role, `404` not found, `409` write conflict, `422` schema reject, `5xx` server fault. ## Rate limits `/api/v1/*` is rate-limited per IP on sensitive endpoints (signup, magic-link, password-reset). On a `429`, back off using `Retry-After`; do not loop tightly. ## Tenants Tasur is multi-tenant. The JWT carries the tenant ID; you cannot read another tenant's data through a normal token. **Don't try.** If you're building a multi-tenant integration that needs to act across tenants, you want an *operator role* token issued by the deployment owner — see [Tenancy & RLS](../ops/tenancy/). ## What to read first, in order 1. [Conventions](../api/conventions/) — URL shape, time format, pagination 1. [Authentication](../api/auth/) — token issuance and rotation 1. [Generated API reference](../api/reference/) — every endpoint 1. The relevant module page in [Modules](../modules/accounting/) — if your integration touches journals, bank lines, BAS, or assets ## Anti-patterns observed in real integrations - **Polling the same endpoint on a tight loop**. An outbound webhook surface (for push notification of journal posts, bank transactions, etc.) is not yet implemented. Until it ships, use the `/api/v1/changes` feed or poll at a reasonable interval — not sub-second. - **Hardcoding response shapes** instead of reading the spec. Additive changes (new fields) are non-breaking and we ship them freely; integrations that pin every key by index will break on upgrade. Read what you need; ignore what you don't. - **Storing JWTs longer than their expiry** and then re-issuing every refresh on a 401. Refresh proactively before expiry; the refresh endpoint is cheap. - **Sending money values as floats**. All amounts are decimal strings. Parse with a decimal type, not a binary float. ## Reporting issues If a spec/server mismatch is causing your integration to fail, file an issue at the GitHub repo with the offending request, expected shape, and actual shape. The spec is generated; mismatches are always bugs.