> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ancha.io/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> These docs describe the Ancha CLI, npm package @ancha-labs/cli, and the hosted workspace at app.ancha.io. Coding agents should start at https://docs.ancha.io/coding-agents. Run the CLI as `ancha` after `npm install -g @ancha-labs/cli`, or as `npx -y @ancha-labs/cli` without installing. Pass --json for machine-readable output, or set ANCHA_JSON=1. Every command ends with a `next:` line naming the next command. Exit codes: 0 pass, 1 a check failed or a comparison regressed, 2 usage, config or authentication error, 3 infrastructure error, 4 unimplemented endpoint with --strict.

# Connect your agent to the QuickBooks Online mock

> Test your agent with QuickBooks Online accounting records, attachments, queries, reports, PDFs and OAuth 2.0 in Ancha, called directly or through Composio.

Use Ancha to test an agent that works with QuickBooks Online. Your agent can create invoices, apply payments and credits, pay bills, post journals, log time, attach files and read reports and PDFs from the same books.

The [QuickBooks Online API mock page](https://ancha.io/tools/quickbooks) has a scene and checks you can copy.

Select this tool with `twins: [quickbooks]` in a scene or `--tools quickbooks` when creating a world. Inspect its API coverage and connection code:

```bash theme={null}
ancha twins coverage quickbooks
ancha connect quickbooks --lang ts
```

## Connect

Ancha supplies these variables to your agent:

| Variable | Value |
| - | - |
| `QUICKBOOKS_API_URL` | Service root. Append `/v3/company/<realmId>` and the resource path. |
| `QUICKBOOKS_REALM_ID` | Company realm ID. |
| `QUICKBOOKS_ACCESS_TOKEN` | Fake access token. Send `Authorization: Bearer <token>`. |
| `QUICKBOOKS_REFRESH_TOKEN` | Fake refresh token for the OAuth refresh grant. |
| `QUICKBOOKS_CLIENT_ID` | Fake OAuth client ID. |
| `QUICKBOOKS_CLIENT_SECRET` | Fake OAuth client secret. |
| `QUICKBOOKS_TOKEN_URL` | Token endpoint, ending in `/oauth2/v1/tokens/bearer`. |

These are the snippets `ancha connect quickbooks --lang ts` and `--lang py` print:

```ts Node theme={null}
const query = new URLSearchParams({ query: "select * from Invoice where Balance > '0'", minorversion: '75' });
const response = await fetch(process.env.QUICKBOOKS_API_URL + '/v3/company/' + process.env.QUICKBOOKS_REALM_ID + '/query?' + query, {
  headers: { Authorization: 'Bearer ' + process.env.QUICKBOOKS_ACCESS_TOKEN, Accept: 'application/json' },
});
const { QueryResponse } = await response.json();
const invoices = QueryResponse.Invoice ?? [];
```

```python Python theme={null}
import os, requests
response = requests.get(os.environ['QUICKBOOKS_API_URL'] + '/v3/company/' + os.environ['QUICKBOOKS_REALM_ID'] + '/query',
    params={'query': "select * from Invoice where Balance > '0'", 'minorversion': '75'},
    headers={'Authorization': 'Bearer ' + os.environ['QUICKBOOKS_ACCESS_TOKEN'], 'Accept': 'application/json'})
invoices = response.json()['QueryResponse'].get('Invoice', [])
```

Build accounting URLs from `QUICKBOOKS_API_URL` and `QUICKBOOKS_REALM_ID`. Send JSON bodies with `Content-Type: application/json`. Responses are JSON; send `Accept: application/xml` for XML. The snippets set `minorversion=75`.

## OAuth 2.0

Send a form-encoded `POST` to `QUICKBOOKS_TOKEN_URL` with `grant_type=refresh_token` and `refresh_token`. Authenticate with HTTP Basic using `QUICKBOOKS_CLIENT_ID` and `QUICKBOOKS_CLIENT_SECRET`, or send them as form fields `client_id` and `client_secret`.

Access tokens last 3,600 seconds on the world's clock. Refresh tokens last 8,726,400 seconds (101 days). A refresh token at least 24 hours old produces a new refresh token. Store the returned `access_token` and `refresh_token`. The response also includes `token_type`, `expires_in` and `x_refresh_token_expires_in`. An earlier refresh token remains valid until expiry or revocation.

To revoke a token, send `POST` to `QUICKBOOKS_API_URL` plus `/oauth2/v1/tokens/revoke` or `/v2/oauth2/tokens/revoke` with JSON `{"token":"<token>"}`. Revoking a refresh token also revokes access tokens issued from it. A successful revoke returns `200` with an empty body.

## Through Composio

An agent that runs QuickBooks tools through Composio keeps that path in [cloud runs](https://docs.ancha.io/cli/run.md#run-in-the-cloud): the agent calls Composio, and Composio's servers call the world's QuickBooks. [`ancha init`](https://docs.ancha.io/cli/init#detect-composio-agents) detects the Composio client and QuickBooks toolkit names or tool slugs, writes the route and adds `COMPOSIO_API_KEY` to `agent.pass_env`, keeping your existing settings:

```yaml ancha.yaml theme={null}
agent:
  command: node dist/agent.js
  routes:
    quickbooks: composio
  pass_env: [COMPOSIO_API_KEY]
```

```bash theme={null}
ancha secrets set COMPOSIO_API_KEY
ancha agent upload
ancha run
```

The secret's value comes from your shell. Signed out, run `ancha login` first. Routed tests run in the cloud.

Each test's world decides which routed tools answer there. QuickBooks-only and NetSuite-only tests can use the same agent configuration. A call to a routed tool the world lacks returns `403 COMPOSIO_ROUTE_REFUSED` with reason `NO_WORLD` and a fix to add the tool to the world or run the call in a test whose world has it. The attempt is graded as usual.

In a world with QuickBooks, the agent keeps its Composio code: direct executions, Tool Router sessions and the session's MCP endpoint all reach the world. Every attempt sets four variables:

| Variable | Value |
| - | - |
| `COMPOSIO_BASE_URL` | Composio's API through the attempt's gateway. The Composio SDKs read it; a client built with an explicit base URL takes this value. |
| `COMPOSIO_API_KEY` | A key for this attempt. The gateway sends the project's key to Composio. |
| `QUICKBOOKS_PUBLIC_URL` | This world's QuickBooks at an address Composio reaches for this attempt only. |
| `COMPOSIO_USER_ID` | The user the route runs every call as. A value the project sets is kept, and the route runs the call as its own user either way. |

* **Direct executions** (`composio.tools.execute`) reach the world whatever user ID, connected account or `custom_auth_params` the agent names: the gateway supplies the world's address and credentials on each call.
* **Sessions** (`composio.create`) reach the world through a QuickBooks connection that the attempt creates in your Composio project for its own user (`ancha-…`). Each session is pinned to that connection. When the attempt ends, it deletes the sessions, the connection and its auth config.
* **MCP**: the session's MCP URL points at the attempt's gateway, so an MCP client in the agent's process reaches the same session with `COMPOSIO_API_KEY`. MCP clients such as Claude Code connect as they do to Composio: their tool calls reach the world, and every other request goes to Composio as sent.
* Before the agent starts, the attempt checks that `QUICKBOOKS_PUBLIC_URL` answers from outside.
* An agent that reads its Composio user from a variable of its own, such as `QUICKBOOKS_USER_ID`, gets it from `ancha init`, which adds it under `agent.env` with any value. `ancha agent upload` names such a variable, with the lines to add, before it uploads.
* An agent that pins its connected account, such as `QUICKBOOKS_CONNECTED_ACCOUNT_ID`, maps it to the attempt's own connection under `agent.env`:

  ```yaml theme={null}
  agent:
    env:
      QUICKBOOKS_CONNECTED_ACCOUNT_ID: "{{composio.quickbooks.connected_account_id}}"
      QUICKBOOKS_AUTH_CONFIG_ID: "{{composio.quickbooks.auth_config_id}}"
  ```

  The attempt then creates its connection before the agent starts, so an agent that checks its account finds it `ACTIVE`, and every call it makes with that account reaches the world. `ancha init` adds the mapping when the agent reads such a variable, moving it out of `pass_env` when it is listed there, and `ancha agent upload` names one that is unset or comes through `pass_env`.
* The gateway keeps every call on the world. A call that names a toolkit outside the declared routes, changes a session's connection, proxies a request or reaches another attempt's session gets `403 COMPOSIO_ROUTE_REFUSED` with a `reason`, and the attempt is invalid with `ROUTE_REFUSED`, so every result rests on calls inside the world.
* Composio's calls reach the world like the agent's own: the world's trace and the [checks](#checks) see them. An execution with no request reaching the world makes the attempt invalid with `ROUTE_NOT_REACHED`.
* The run's summary counts the route under `routes.quickbooks`: executions by path (`via.direct`, `via.session`, `via.mcp`), how many reached the world, refusals, sessions, and the test connection's `connection` and `cleanup`.

## Start with the QuickBooks examples

For an agent that uses QuickBooks, in a project with no tests and no traces, `ancha init` writes Pellmont Building Services' 2025 books. This fictional facilities company has 14 vendors, 8 customers, 42 invoices and 71 bills.

| File | Contents |
| - | - |
| `ancha/worlds/pellmont-building-services.yaml` | The QuickBooks world with Pellmont's books. |
| `ancha/tests/pellmont-duplicates.yaml` | Report the duplicate vendors, invoices and bills entered twice, and the money at stake. The books stay unchanged. |
| `ancha/tests/pellmont-approved-merge.yaml` | Merge the three approved duplicate vendor pairs. Keep the record with the legal suffix, move the other record's bills to it, copy contact details it lacks and make the other record inactive. Nothing else changes. |

`--data none` leaves these examples out. For a routed agent, init also writes a starter test that reads from each routed tool. Store `COMPOSIO_API_KEY`, upload the agent and run the tests with the commands above.

An agent that writes to QuickBooks only behind a flag runs the merge from a second configuration that adds the flag to `agent.command`:

```bash theme={null}
ancha run --config ancha.write.yaml ancha/tests/pellmont-approved-merge.yaml
```

## Endpoints

Paths below are relative to `QUICKBOOKS_API_URL`. Replace `{realmId}` with `QUICKBOOKS_REALM_ID`.

| Method | Path | Use |
| - | - | - |
| `GET` | `/v3/company/{realmId}/{entity}/{id}` | Read an entity. Read company information at `/companyinfo/{realmId}` and preferences at `/preferences` under the company path. |
| `POST` | `/v3/company/{realmId}/{entity}` | Create, update, delete or void an entity with `operation`. |
| `GET` | `/v3/company/{realmId}/query` | Send a query in the `query` parameter. |
| `POST` | `/v3/company/{realmId}/query` | Send query text with `Content-Type: application/text`. |
| `GET` | `/v3/company/{realmId}/reports/{report}` | Read an accounting report. |
| `GET` | `/v3/company/{realmId}/cdc` | Read changed entities with `entities` and `changedSince`. |
| `POST` | `/v3/company/{realmId}/batch` | Submit ordered writes and queries. |
| `POST` | `/v3/company/{realmId}/{entity}/{id}/send` | Send a sales form or purchase order. |
| `GET` | `/v3/company/{realmId}/{entity}/{id}/pdf` | Download an `invoice`, `estimate`, `creditmemo`, `payment`, `purchaseorder`, `refundreceipt` or `salesreceipt` as a PDF. |
| `POST` | `/v3/company/{realmId}/upload` | Upload attachments as `multipart/form-data`. |
| `GET` | `/v3/company/{realmId}/download/{id}` | Download an attachment through its `TempDownloadUri`. |
| `POST` | `/v3/company/{realmId}/taxservice/taxcode` | Create a tax code with new or existing tax rates. |
| `GET` | `/v3/company/{realmId}/exchangerate` | Read a rate with `sourcecurrencycode` and `asofdate`. |
| `POST` | `/v3/company/{realmId}/exchangerate` | Set the rate for a currency and date. |
| `POST` | `/oauth2/v1/tokens/bearer` | Refresh access credentials. |
| `POST` | `/oauth2/v1/tokens/revoke` | Revoke a token. |
| `POST` | `/v2/oauth2/tokens/revoke` | Revoke a token through the alternate path. |

Use lowercase entity names in resource paths, such as `invoice` or `customer`. Responses and query entity names use `Invoice` and `Customer`. Numeric fields take JSON numbers or numeric strings such as `"25.00"`.

For an update, include the current `Id` and `SyncToken`. Set `sparse: true` to merge supplied top-level fields; supplied nested objects and arrays replace their previous values. Without `sparse: true`, the update replaces the record: writable fields it leaves out are cleared. A stale `SyncToken` returns code `5010`.

Set `operation=delete` to delete a transaction. Set `operation=void` to void an `Invoice`, `Payment`, `SalesReceipt` or `BillPayment`. For the latter three, `operation=update&include=void` also voids the transaction. Change a list record's availability with `Active`. A `requestid` query parameter replays the first response stored for that ID within the company.

## Entities

Use these names in queries and checks:

| Work | Entities |
| - | - |
| People and companies | `Customer`, `Vendor`, `Employee` |
| Accounting lists | `Account`, `Item`, `Class`, `Department`, `Term`, `PaymentMethod` |
| Tax setup | `TaxAgency`, `TaxCode`, `TaxRate` |
| Company settings | `CompanyInfo`, `Preferences` |
| Sales and receivables | `Invoice`, `Estimate`, `SalesReceipt`, `CreditMemo`, `RefundReceipt`, `Payment` |
| Purchases and payables | `Bill`, `BillPayment`, `VendorCredit`, `Purchase`, `PurchaseOrder` |
| Banking and journals | `Deposit`, `Transfer`, `JournalEntry` |
| Time and attachments | `TimeActivity`, `Attachable` |
| Inventory | `InventoryAdjustment` |
| Currencies | `ExchangeRate` |

Create tax agencies with `POST /taxagency` and tax codes with their rates through `POST /taxservice/taxcode`. Update `CompanyInfo` with a full or sparse update and `Preferences` with `sparse: true`. Transactions update account balances and the general ledger. Apply payments and credits through `Line[].LinkedTxn` entries that name the related `TxnId` and `TxnType`.

## Currencies

A company keeps its books in its home currency, `Preferences.CurrencyPrefs.HomeCurrency`. With `MultiCurrencyEnabled: true`, customers, vendors and accounts can carry another currency in `CurrencyRef`, and their transactions follow it:

* A transaction without `CurrencyRef` takes its customer's or vendor's currency. Without `ExchangeRate`, it takes the world's latest rate dated on or before its `TxnDate`. The rate stays with the transaction once it is written.
* Totals and balances are in the transaction's currency; `HomeTotalAmt` and `HomeBalance` give the home amounts.
* Receivables and payables in another currency post to an A/R or A/P account in that currency, created on first use as `Accounts Receivable (A/R) - EUR` or `Accounts Payable (A/P) - EUR`.
* A payment settles each invoice or bill at the rate it was written at, and the difference posts to Exchange Gain or Loss.
* Reports are in the home currency.

Amounts use each currency's minor units: none for JPY or KRW, three decimals for BHD, KWD and OMR. Seed rates under `exchangeRates`:

```yaml theme={null}
quickbooks:
  preferences:
    CurrencyPrefs: { MultiCurrencyEnabled: true, HomeCurrency: { value: CAD } }
  exchangeRates:
    - { SourceCurrencyCode: USD, TargetCurrencyCode: CAD, Rate: 1.35, AsOfDate: "2026-11-01" }
  entities:
    Customer:
      - { Id: "1", DisplayName: Ternwick US, CurrencyRef: { value: USD } }
```

## Inventory

An item with `Type: Inventory` tracks its quantity and cost. It names an income account, a Cost of Goods Sold account in `ExpenseAccountRef` and an Other Current Asset account in `AssetAccountRef`, and starts with `QtyOnHand` at `PurchaseCost` on `InvStartDate`. Inventory needs `ForSales`, `ForPurchase`, `QuantityWithPriceAndRate` and `QuantityOnHand` turned on in `ProductAndServicesPrefs`.

* The opening quantity posts to the asset account and to Opening Balance Equity.
* Bills and purchases add cost layers in the home currency. Invoices and sales receipts take cost first in, first out: Cost of Goods Sold is debited and the asset account credited.
* Credit memos and refund receipts restock at the unit cost of the item's latest earlier sale, or at its `PurchaseCost` when it has none. Vendor credits take their units out at layer cost, and the difference from the credit posts to Cost of Goods Sold.
* `InventoryAdjustment` with `QtyDiff` changes quantity on its `TxnDate` against its `AdjustAccountRef`. An item update with a new `QtyOnHand` records the change against the item's Cost of Goods Sold account, on the `InvStartDate` it sends or on the company's current date.
* `Item.QtyOnHand` reads the quantity after every transaction. `InventoryValuationSummary` and `InventoryValuationDetail` give quantity and value on any date.
* A line for an inventory item needs `Qty`, and a transaction dated before the item's `InvStartDate` gets error 6270.

```yaml theme={null}
quickbooks:
  preferences:
    ProductAndServicesPrefs: { ForSales: true, ForPurchase: true, QuantityWithPriceAndRate: true, QuantityOnHand: true }
  entities:
    Account:
      - { Id: "3", Name: Stock, AccountType: Other Current Asset }
      - { Id: "4", Name: Product sales, AccountType: Income }
      - { Id: "5", Name: Product costs, AccountType: Cost of Goods Sold }
    Item:
      - { Id: "1", Name: Brass coupling, Sku: BC-1, Type: Inventory, QtyOnHand: 4, PurchaseCost: 5, UnitPrice: 12, InvStartDate: "2026-11-01",
          AssetAccountRef: { value: "3" }, IncomeAccountRef: { value: "4" }, ExpenseAccountRef: { value: "5" } }
```

## Query

Send a query with `GET /v3/company/{realmId}/query?query=...` or as the text body of `POST /v3/company/{realmId}/query`.

```sql theme={null}
SELECT * FROM Invoice WHERE Balance > '0' ORDERBY Id STARTPOSITION 1 MAXRESULTS 100
```

| Clause | Syntax |
| - | - |
| Selection | `SELECT *`, `SELECT COUNT(*)` or comma-separated top-level fields such as `SELECT Id, Balance`. |
| Conditions | `WHERE` with `=`, `<`, `>`, `<=`, `>=`, `IN (...)` or `LIKE`. Join conditions with `AND`. |
| Values | Single-quoted strings, numbers and `true` or `false`. A text property such as `DocNumber` takes its value in quotes: `DocNumber = '1038'`. Escape a quote with a backslash. |
| Text matching | `LIKE 'Tern%'`, `LIKE '%Studio'` or `LIKE '%wick%'`. Text matching ignores case. |
| Ordering | `ORDERBY` or `ORDER BY` with comma-separated fields and optional `ASC` or `DESC` for each. |
| Paging | `STARTPOSITION` followed by `MAXRESULTS`. Both take positive integers. |

Queries default to `STARTPOSITION 1` and `MAXRESULTS 100`. Request up to 1,000 results per page. Ordering defaults to numeric `Id`; equal sort values also use numeric `Id`. List queries select active records by default. Use `WHERE Active IN (true, false)` to include inactive records.

Use `MetaData.CreateTime` and `MetaData.LastUpdatedTime` in selections, conditions and ordering; field names match in any case. Filter a reference such as `CustomerRef` by its ID. A field projection returns the selected fields plus `Id` and `sparse: true`.

Results appear in `QueryResponse.<Entity>` with `startPosition` and `maxResults`. An empty result has `QueryResponse: {}`. `COUNT(*)` returns `QueryResponse.totalCount`.

## Reports

Read `GET /v3/company/{realmId}/reports/{report}`. JSON responses contain `Header`, `Columns` and `Rows` at the top level.

| Report | Contents |
| - | - |
| `ProfitAndLoss` | Revenue, expenses and net income. |
| `BalanceSheet` | Assets, liabilities and equity. |
| `TrialBalance` | Debit and credit balances by account. |
| `GeneralLedger` | Beginning balances, dated postings and running balances. |
| `AgedReceivables` | Open customer balances by aging bucket. |
| `AgedReceivableDetail` | Open customer transactions with due dates and aging. |
| `AgedPayables` | Open vendor balances by aging bucket. |
| `CustomerBalance` | Open balances by customer. |
| `VendorBalance` | Open balances by vendor. |
| `ProfitAndLossDetail` | Income and expense postings by account with running balances. |
| `TransactionList` | Every transaction in the period with its account and split. |
| `CashFlow` | Operating, investing and financing cash flows with beginning and ending cash. |
| `AccountList` | Accounts with type, detail type, description and balance. |
| `CustomerSales` | Income by customer. |
| `ItemSales` | Quantity, amount, share of sales and average price by product or service. |
| `ClassSales` | Income by class. |
| `DepartmentSales` | Income by department. |
| `CustomerIncome` | Income, expenses and net income by customer. |
| `VendorExpenses` | Expenses by vendor. |
| `CustomerBalanceDetail` | Open customer transactions with running balances. |
| `VendorBalanceDetail` | Open vendor transactions with running balances. |
| `AgedPayableDetail` | Open vendor transactions with due dates and aging. |
| `InventoryValuationSummary` | Quantity on hand, asset value and average cost by inventory item. |
| `InventoryValuationDetail` | Each inventory item's movements with quantity, cost and running value. |

Reports use accrual accounting by default and the company's time zone. Their totals follow the same transactions, applications and ledger as entity reads.

| Parameter | Use |
| - | - |
| `accounting_method` | `Accrual`, the default, or `Cash`. |
| `start_date`, `end_date` | Date range in `YYYY-MM-DD` form. |
| `report_date` | As-of date; takes precedence over `end_date`. |
| `date_macro` | A named period, such as `Today`, `This Month`, `Last Month`, `This Fiscal Year-to-date` or `All`. |
| `summarize_column_by` | `Total` by default. Use `Month`, `Quarter` or `Year` for `ProfitAndLoss` and `BalanceSheet` period columns. |
| `customer`, `vendor` | Comma-separated customer or vendor IDs. |
| `aging_period` | Days per aging bucket. Default `30`. |
| `num_periods` | Number of overdue buckets. Default `4`. |
| `aging_method` | `Report_Date` by default, or `Current` to age against the world's current company date. |
| `arpaid`, `appaid` | `Unpaid` on the receivable and payable aging and balance reports, which list open transactions. |

`ProfitAndLoss` and `GeneralLedger` default to `This Fiscal Year-to-date`. Aging defaults to current, 1–30, 31–60, 61–90 and 91 days or more. Use the aging parameters with the aged reports.

## Change data capture

Send `GET /v3/company/{realmId}/cdc` with comma-separated `entities` and an ISO date or datetime in `changedSince`. For example, set `entities=Invoice,Payment`. Choose a time within the last 30 days on the world's clock. Dates and datetimes without an offset use the company's time zone.

The response contains `CDCResponse[].QueryResponse[]`, one entry per requested entity type. It returns the current body once per changed ID, newest change first, including changes caused by payment applications. Deleted records carry `status: "Deleted"`, `Id` and `MetaData.LastUpdatedTime`. Each type returns up to 1,000 records; `totalCount` gives its full changed-record count. The change history starts after seeding.

## Batch

Send `POST /v3/company/{realmId}/batch` with a `BatchItemRequest` array of 1–30 items. Give each item a unique, nonempty string `bId`.

An entity item contains `operation: "create"`, `"update"` or `"delete"` and one entity body. A query item contains `Query` with query text. Responses appear in `BatchItemResponse`, with the same `bId` and either the result or a `Fault`.

Items execute in order. Each successful write commits independently, and later queries see it. An item fault leaves earlier successful writes in place. Use `requestid` on the batch URL to replay the whole response.

## Sending

Send `POST /v3/company/{realmId}/{entity}/{id}/send` for an `Invoice`, `Estimate`, `SalesReceipt`, `CreditMemo` or `PurchaseOrder`. Supply `sendTo` as a query parameter or set `BillEmail.Address` on the record.

A send sets `EmailStatus` to `EmailSent`, records `DeliveryInfo` and adds a send event with the entity, recipient, document number and world time. Use `quickbooks.sent` to check that event.

## Attachments

Upload files with `POST /v3/company/{realmId}/upload` as `multipart/form-data`. Send each file as a pair of parts: `file_metadata_0` holds the `Attachable` JSON, with `AttachableRef` naming the entity it belongs to, and `file_content_0` holds the bytes. Number further files `_1`, `_2` and so on. The response lists each new `Attachable` under `AttachableResponse`.

An `Attachable` read or query returns `TempDownloadUri`, a signed link to the file that stays valid for five minutes of world time. Query a record's attachments with `WHERE AttachableRef.EntityRef.Type = 'Invoice' AND AttachableRef.EntityRef.Value = '2'`.

## Starter data

Inspect the starter records and the fields you can use in a scene:

```bash theme={null}
ancha sandbox configuration --tools quickbooks --json
ancha twins seed quickbooks
```

The starter company is **Larchmere Field Services**, realm `9341458206001234`, with USD books and the `America/Los_Angeles` time zone.

| Records | Detail |
| - | - |
| Customers | Ternwick Studio (`1`), Morrowfen Survey (`2`), Kestrel Loomworks (`3`) and its Kestrel workshop job (`4`). Ternwick's billing email is `accounts@ternwick.example`. |
| Vendors | Brindle Quay Supply (`5`), Sablewick Hosting (`6`) and inactive Alderfen Equipment (`7`). |
| Items | Site review (`1`, `Service`) and Cable kit (`2`, `NonInventory`). |
| Lists and tax | Field operations class, West workshop department, Net 30 terms, Bank transfer payment method, Larchmere local tax code and an 8.25% Larchmere district tax rate. |
| Accounts | Eleven accounts: Operating bank, Undeposited Funds, Trade receivables, Trade payables, Company card, Field service revenue, Materials revenue, Field supplies, Software subscriptions, Sales tax payable and Opening Balance Equity. |
| Invoices | Ternwick's `2` totals 1,200 USD and is 70 days overdue. Morrowfen's `3` totals 900 USD. Kestrel's `4` totals 1,000 USD with 600 USD remaining. |
| Payment | Payment `5` applies 400 USD to Kestrel's invoice `4` and sits in Undeposited Funds. |
| Bills | Brindle Quay's `6` owes 450 USD for field supplies. Sablewick's `7` owes 300 USD for software subscriptions. |
| Journal entry | Entry `1` debits Operating bank and credits Opening Balance Equity by 10,000 USD. |

Starter balances are 10,000 USD in Operating bank, 400 USD in Undeposited Funds, 2,700 USD receivable and 750 USD payable. Across all starter transactions, revenue is 3,100 USD, expenses are 750 USD and net income is 2,350 USD.

## Errors

Accounting validation errors return `400` with `Fault.type: "ValidationFault"` and a `Fault.Error` array. Each entry has `code`, `Message` and `Detail`, plus `element` when a field is identified.

JSON authentication errors use lowercase `fault.type: "AUTHENTICATION"` and `fault.error` entries with `code`, `message`, `detail` and `element`. Their top-level `time` is the world time in milliseconds. XML authentication errors use `Fault` and `Error`.

| Status | Code | Meaning |
| - | - | - |
| `401` | `3200` | Missing, malformed, unknown, expired or revoked access token. |
| `403` | `3100` | Access token belongs to a different realm. |
| `400` | `2010` | Invalid request property or value. |
| `400` | `2020` | Required value is missing. |
| `400` | `2050` | String exceeds its field length. |
| `400` | `2500` | A reference names a record that does not exist. |
| `400` | `610` | The entity ID does not exist, or a reference names an inactive record. |
| `400` | `5010` | Update uses a stale `SyncToken`. |
| `400` | `6240` | Name is already in use. |
| `400` | `6140` | Document number is already in use. |
| `400` | `6000` | Business validation failed. |
| `400` | `4000` | Query syntax is invalid. |
| `400` | `4001` | Query entity or property is invalid. |
| `400` | `500` | Operation is invalid for the resource. |
| `500` | `10000` | Internal error, with `Fault.type: "SystemFault"`. |

Token endpoint errors use `{"error":"<code>"}`: `invalid_client` returns `401`; `invalid_grant` and `unsupported_grant_type` return `400`. A malformed revoke request returns `400` with `invalid_request`.

## Checks

[State checks](https://docs.ancha.io/reference/checks.md#quickbooks-online) read the final records, send events and committed changes:

```yaml theme={null}
- id: invoice_paid
  state: { quickbooks.entity: { type: Invoice, id: "2", fields: { Balance: 0 } } }
- id: one_payment
  state: { quickbooks.count: { type: Payment, where: { CustomerRef.value: "1" }, count: 1 } }
- id: reminder_sent
  state: { quickbooks.sent: { type: Invoice, to: accounts@ternwick.example } }
- id: books_unchanged
  state: { quickbooks.unchanged: { types: [Bill, JournalEntry] } }
```

Intuit and QuickBooks are registered trademarks of Intuit Inc. Ancha is not affiliated with or endorsed by Intuit.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.