# Embedded ledger

> Run your customers' books on Prosaic: a platform workspace, one entity per customer, and their accountant working alongside.

Source: https://developer.prosaic.works/docs/ledger/embedded-ledger

The embedded model gives every one of your customers a real set of double-entry books without you building a ledger. It works like connected accounts on a payments platform: you hold one platform account, and each of your customers is an account inside it.

```text
  Your platform workspace (one per country)
  ├── API key  ──────────────►  your backend
  ├── Entity: Kowhai Cafe Ltd       ◄── your customer #1
  ├── Entity: Harbour Physio Ltd    ◄── your customer #2
  └── Entity: ...                   ◄── one per customer
            ▲
            └── their accountant, invited as an advisor with access to that entity
```

Your customers do not need Prosaic logins. Your backend writes to their books with your API key, and their accountant can work in the same books in the Prosaic app.

## The platform workspace

Sign up at [app.prosaic.works/signup](https://app.prosaic.works/signup). The workspace you get is your platform workspace: it holds your users, your API keys, your chart-of-accounts templates and your customers' entities.

Create your integration's API key for a user who is a workspace owner or admin. A key acts as its user, and owners and admins see every entity in the workspace, including the ones the key creates. See [Authentication](/docs/getting-started/authentication).

## One workspace per country

An entity's country is not chosen per entity. It comes from its workspace, and so does everything that follows from the country:

|                | New Zealand workspace         | Australian workspace          |
| -------------- | ----------------------------- | ----------------------------- |
| Currency       | NZD                           | AUD                           |
| Financial year | Starts 1 April                | Starts 1 July                 |
| Timezone       | Pacific/Auckland              | Australia/Sydney              |
| GST codes      | NZ 15% codes                  | AU 10% codes                  |
| Standard chart | Standard NZ Business Template | Standard AU Business Template |
| GST returns    | Yes                           | Not yet (BAS is coming)       |

If you serve both countries, run two platform workspaces, one each, and route each customer to the right one. A user who is a member of both can use one API key and pick the workspace per request with `x-workspace-id`.

New sign-ups get a New Zealand workspace. Australia is in early access: write to [developer@prosaic.works](mailto:developer@prosaic.works) for an Australian workspace before you create entities in it. A workspace's region is set when it is created, and changing it later is a support request.

## One entity per customer

When a customer signs up to your product, create an entity for them and store its `id` against your customer record.

```ts
const { data: entity } = await prosaic.entities.create({
  name: customer.legalName,
  type: 'company', // individual, company, trust, partnership, rental or other
  accountTemplateId: STANDARD_TEMPLATE_ID,
  isGstRegistered: customer.gstRegistered,
  gstNumber: customer.gstNumber, // NZ: 9 digits. AU: the 11-digit ABN.
});

await db.customers.update(customer.id, { prosaicEntityId: entity.id });
```

- **Chart of accounts.** The entity's accounts are copied from the template you name. Use one of the seeded templates, or build your own with `charts.create` so every customer starts with the accounts your product posts to. See [Chart of accounts](/docs/ledger/chart-of-accounts).
- **GST.** An entity not marked GST registered has every account defaulted to its country's "No GST" code. [Tax in NZ and AU](/docs/ledger/tax-nz-au) lists the GST fields, including the ones that switch on NZ GST returns.
- **Tax rates.** The entity is created with its country's tax rates. Their IDs are in `taxRates[]` on the entity; cache them alongside the entity ID, because every journal line needs one.

## Writing to the books

- **Journals** are the main write: one balanced journal per business event you record, such as a sale, a payout or a fee. See [Journals](/docs/ledger/journals).
- **Bank lines.** `bankAccounts.createWithTransactions` creates a bank account fed by imported files and loads statement lines into it; `bankAccounts.importTransactions` adds lines to an existing one. `importTransactions` skips lines the account already holds, with the same date, amount and description, so re-sending an overlapping batch to an existing account is safe. `createWithTransactions` always creates a new account, so after an uncertain failure check the entity's `bankAccounts[]` before retrying. Imported lines are then reconciled in the app or with `transactions.reconcile`.
- **Invoices and contacts** have their own endpoints ([`invoices.create`](/docs/api/invoices#invoices-create), [`contacts.create`](/docs/api/contacts#contacts-create)). See the [API reference](/docs/api).

Read the results back with the [report endpoints](/docs/ledger/reports): trial balance, P&L, balance sheet and the general ledger.

## Avoiding double-posting

Journal creation has no idempotency key, and the SDK never retries a write on its own. A `4xx` response means nothing was written. But if a create fails without a clear answer (a timeout, a dropped connection or a `5xx`), the journal may or may not exist. Check before you try again:

1. Put your own reference in the journal's `narration`, for example `Order 10442`.
2. Once a create succeeds, store the returned `logicalJournalId` against your record, and skip records that already have one.
3. After an uncertain failure, list the entity's journals around that date and look for your reference before posting again.

```ts
import {
  APIError,
  ConnectionError,
  type JournalsCreateParams,
} from 'prosaic-node';

async function postJournalOnce(
  entityId: string,
  reference: string,
  params: JournalsCreateParams,
): Promise<string | null> {
  try {
    const journal = await prosaic.journals.create(entityId, params);
    return journal.logicalJournalId;
  } catch (error) {
    const uncertain =
      error instanceof ConnectionError ||
      (error instanceof APIError && error.status >= 500);
    if (!uncertain) throw error;

    // The outcome is unknown. Look before posting again.
    for await (const journal of prosaic.journals.list(entityId, {
      dateFrom: dayBefore(params.date),
      dateTo: dayAfter(params.date),
    })) {
      if (journal.narration.includes(reference))
        return journal.logicalJournalId;
    }
    const journal = await prosaic.journals.create(entityId, params);
    return journal.logicalJournalId;
  }
}
```

`dayBefore` and `dayAfter` stand in for your own date helpers. Search a day either side of the journal date, because the list's date filters do not yet adjust for the entity's timezone. `TimeoutError` is a kind of `ConnectionError`, so the check covers timeouts too.

## Giving a customer's accountant access

Many of your customers will have an accountant. You can let them into that customer's books, and only that customer's:

1. In the Prosaic app, go to **Settings → Users → Add new user**.
2. Enter the accountant's name and email, choose the **Advisor** role, and select the customer's entity under **Entity Access**.
3. Prosaic invites them by email. They sign in and switch to your workspace to see the entity.

An advisor can work with the entities they have been given (transactions, journals and reports) but cannot see your other customers or manage users. Change which entities they can reach later from the Users table, under **Actions → Entity access**. Do not make an outside accountant an admin: admins see every entity in the workspace.

Not yet available:

- Inviting users or granting entity access through the API. It is done in the app.
- Moving an entity into the accountant's own firm workspace, or sharing it with another workspace. The entity stays in your platform workspace.
