# EntryHarbor Agent API v1

Outside agents manage organization data through `/api/agent/v1`. This API uses an
account-owned API token created under **Admin > Agent access**. The public guide
is `/api/agent/v1/docs`; the machine-readable contract is
`/api/agent/v1/openapi.json`, on the same API origin. Documentation is public;
organization data always requires an API token. Use HTTPS outside local development.

Agents can begin at `https://entryharbor.com/`. The homepage advertises this guide
and the OpenAPI document through HTML link metadata and HTTP Link headers.
`/llms.txt` supplies a short agent-readable overview, and
`/.well-known/api-catalog` supplies the RFC 9727 API catalog in Linkset JSON.
The public Developers page is linked discreetly in the application footer.
Discovery resources contain public documentation only; data operations still
require a scoped token. API links point to the API origin, including when they
are discovered through the frontend site.

## Get connected

1. An organization administrator creates a named token, chooses **All organizations
   I administer** or specific organizations, and optionally sets an expiration.
2. Copy the complete token when it is first shown. EntryHarbor stores only its hash
   and a display prefix. The secret cannot be retrieved later.
3. Give the agent the API origin, this guide, the OpenAPI URL, and the token through
   your secure credential mechanism.
4. Send `Authorization: Bearer <token>` on every data request. Never put the token
   in URLs, prompts committed to source control, or logs. Agent tokens do not sign in
   to the app. Interactive sign-in JWTs can use the shared frontend routes below.
5. Start with `GET /api/agent/v1/organizations` and use an ID from that response.

All scope means every organization the token's owner **currently administers**,
including organizations added in the future. Selected scope means the chosen
organizations intersected with the owner's current administrator memberships.
Accountant membership and account-level Super Admin alone do not grant delegation.
Expiry, revocation, removal, and demotion are checked on subsequent requests.

Administrators can create several tokens for independent agents and revoke each
under **Admin > Agent access**. To change a token's scope, revoke it and create a
replacement. Token management uses the administrator's interactive account session,
not the agent credential. Revocation remains available after admin access is lost.

## Available data

Every resource route starts with `/api/agent/v1/organizations/{organizationId}`.

| Resource suffix | Operations |
| --- | --- |
| (none) | Read organization settings |
| `/categories` | List, create; update/delete at `/{id}` |
| `/payment-accounts` | List, create; update/delete at `/{id}` |
| `/ledger` | List, create; read/update/delete at `/{id}` |
| `/receipts` | Search; read at `/{id}` |
| `/reports/pnl?from=YYYY-MM-DD&to=YYYY-MM-DD` | Read profit and loss |
| `/reports/balance-sheet?asOf=YYYY-MM-DD` | Read balance sheet |
| `/customers` | List, create; update at `/{id}` |
| `/invoice-taxes` | Read configured tax IDs and rates |
| `/invoices` | List, create; read/update at `/{id}` |
| `/invoices/{id}/issue` | Issue using a concurrency version |
| `/invoices/{id}/void` | Void using a concurrency version and reason |

Use the OpenAPI document for exact methods, query parameters, request properties,
response properties, numeric enum values, and errors. Organization membership,
invitations, account settings, personal tax/pay stubs, platform administration,
Stripe onboarding, email sending, receipt upload, receipt review decisions, and loan
lifecycle operations are managed through the application.

## Receipt workflows on the frontend API routes

Send the same agent bearer token to these paths on the same API origin. These
are the routes used by the web app. Use organization IDs returned by
`GET /api/agent/v1/organizations`. The token must authorize both the source and
the destination for a transfer.

| Method and path | What to send |
| --- | --- |
| `GET /api/Receipt?organizationId={id}` | Find receipts in an authorized organization. Use `page` and `pageSize` to paginate, `inLedger` to filter on posting state, or repeat `tag` for each tag name. |
| `GET /api/Receipt/{id}` or `GET /api/Receipt/{id}/review` | Read the receipt, its tag names, the linked ledger ID if present, and its draft version. |
| `GET /api/Tag?organizationId={id}` | List the organization's existing tags. |
| `PUT /api/Receipt/{id}` | Save the complete editable draft, with `expectedConcurrencyVersion` and the desired `tags` array of names. |
| `POST /api/Receipt/{id}/transfer` | Send `{"organizationId": 12}` with the destination ID. Existing tag names carry over to the destination. If the receipt has a ledger entry, the transfer detaches it. The entry stays in the source organization and the receipt arrives unposted. Detaching a ledger entry requires source admin access. |
| `GET /api/Category?organizationId={id}` | List categories. Select an expense category when posting a receipt. |
| `GET /api/PaymentAccount?organizationId={id}` | List payment accounts to use when posting. |
| `GET /api/Ledger/unposted-receipts?organizationId={id}` | List posting candidates and any suggested categories. |
| `POST /api/Ledger/from-receipt` | Send `receiptId`, optional `categoryId` and `paymentAccountId`, and the partial-posting fields when applicable. |
| `POST /api/Ledger/from-receipts` | Send one optional `paymentAccountId` and `items` containing `receiptId` and optional `categoryId` for each receipt. Posts full totals in a single organization. |

For a tag edit, read the receipt first. Send its editable values
(`vendor`, `receiptDate`, `currencyCode`, `subtotalAmount`, `discountAmount`,
`taxAmount`, `feeAmount`, `tip`, `totalAmount`, `notes`, `items`, and
`adjustments`) along with its `concurrencyVersion` as
`expectedConcurrencyVersion`. Set `tags` to the complete desired list. Include a
new name to create and assign an organization tag, omit a name to remove that
assignment, or pass `[]` to clear all assignments. After a version conflict,
read the current draft before retrying.

A single receipt post uses the receipt total by default. To post a portion,
send `postingAmount` and `expectedReceiptTotal`. For a percentage, also send
`postingPercentage` and `postingBaseAmount`, with `postingAmount` equal to
their calculated result rounded to cents. The ledger entry retains the
receipt link and records the allocation in its notes. A receipt that already
has a ledger entry cannot be posted again.

## Formats and write behavior

- JSON names use camelCase. IDs are integers. For category, payment-account, and
  ledger creation, body `organizationId` must equal the route organization.
- Date-time fields use ISO 8601; prefer UTC with `Z`. Invoice issue/due dates and
  report query dates use `YYYY-MM-DD`. Date filters are inclusive.
- Money is a decimal JSON number, such as `25.50`. Ledger amounts must be positive;
  transaction type determines direction: Expense=0, Income=1, Transfer=2.
- Categories support Expense=0 or Income=1. Transfer=2 is a ledger type, not a
  category type. Payment account kind: Other=0, Checking=1, Savings=2, CreditCard=3,
  Cash=4, PersonalFunds=5. Transfer direction: Out=0, In=1.
- Ledger list accepts page (default 1), pageSize (default 50, maximum 200),
  fromDate, toDate, categoryId, paymentAccountId, type, search, uncategorizedOnly.
  Its response has transactions, totalCount, page, pageSize, and matching totals.
  Receipt search defaults to page 1/pageSize 50 and caps pageSize at 100. It returns
  an array; request the next page until fewer rows than pageSize are returned.
- Category/payment-account lists accept includeArchived=true. Customer/invoice
  lists return all rows; these lists do not take page parameters.
- PUT replaces editable fields. Read current data first and send all editable
  values you intend to preserve, including archive status, mappings, amounts,
  notes, and opening balances. Omitted fields can reset to defaults. Ledger,
  category, and payment-account writes do not offer optimistic version checks;
  coordinate concurrent editing and read the result back.
- Customer and invoice updates require expectedConcurrencyVersion from the last
  read concurrencyVersion. Invoice issue/void also require that version. A stale
  version returns 409: read current state and reconsider the operation.
- Creates return the created object with its ID. Updates return the current object.
  Deletes return `200 {"deleted":true}`. Data responses and token metadata are
  marked no-store. Existing bookkeeping, archive, loan, bank-import, invoice-state,
  and active-checkout protections still apply.
- All related record IDs must belong to the route organization. Existing malformed
  transfer links crossing organizations are blocked; resolve them in the app.
- Writes take effect immediately. There is no idempotency-key support. After a
  timeout or disconnected response, read current state before deciding to retry a
  create or other write. Do not blindly retry financial mutations.

## Example workflow

Set API_ORIGIN to your API host, such as `https://your-api.example`, and TOKEN to
the secret from Admin > Agent access. Use these placeholders in your HTTP client:

```http
GET /api/agent/v1/organizations
Authorization: Bearer <TOKEN>
```

Choose a returned organization ID. If it is 7, list existing categories before
creating one to avoid duplicates:

```http
GET /api/agent/v1/organizations/7/categories?includeArchived=true
Authorization: Bearer <TOKEN>
```

```http
POST /api/agent/v1/organizations/7/categories
Authorization: Bearer <TOKEN>
Content-Type: application/json

{"organizationId":7,"name":"Office supplies","type":0,"taxLineId":null,"scheduleCLine":null,"balanceSheetAccountId":null}
```

Use the returned category ID, here 12, when creating an expense:

```http
POST /api/agent/v1/organizations/7/ledger
Authorization: Bearer <TOKEN>
Content-Type: application/json

{"organizationId":7,"type":0,"transactionDate":"2026-10-27T00:00:00Z","amount":25.50,"payee":"Office supplier","notes":"Paper and pens","categoryId":12,"paymentAccountId":null,"receiptId":null,"transferDirection":null,"transferPeerPaymentAccountId":null}
```

Read the returned transaction ID back with GET `/organizations/7/ledger/{id}`
under the API base. Before editing, preserve every editable field listed in the
LedgerTransactionUpdateRequest schema. Check the result using the list or reports.

For invoices, list/create a customer, inspect `/invoice-taxes`, then create an
invoice with customerId, issueDate, dueDate, notes, and lines containing description,
quantity, unitPrice, and taxIds. Read its concurrencyVersion and POST
`{"expectedConcurrencyVersion":<version>}` to `/invoices/{id}/issue`. Issuance
does not send email or initiate a charge. Eligible draft or issued invoice edits
remain subject to the existing invoice rules.

## Errors and limits

| Status | Meaning / response |
| --- | --- |
| 400 | Malformed JSON, parameter binding, or model validation problem |
| 401 | Missing, invalid, expired, or revoked agent token |
| 403 | Organization excluded, current admin access lost, or cross-organization transfer link |
| 404 | Record absent from the authorized organization |
| 409 | Concurrency conflict or protected bookkeeping/billing operation |
| 422 | Invalid field, body organization mismatch, or invalid related record |
| 429 | More than 120 requests/minute per IP across agent data, shared frontend, and token-management routes |

Domain errors return `{ "code": "...", "message": "..." }`. Automatic 400
responses can use ASP.NET validation-problem JSON. Authentication and rate-limit
responses may have empty bodies. On 429, wait before retrying reads. Verify a
write's outcome before retrying it. An empty organization list means the token
currently authorizes no organizations; it does not grant account-wide access.

## Database setup

Apply migration `20261027205726_AgentApiTokens` before deploying this feature. It adds
AgentApiTokens and AgentApiTokenOrganizations without changing existing financial
records. The migration is not run automatically by application startup.
