> For the complete documentation index, see [llms.txt](https://cde-inc.gitbook.io/cde-cad-documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cde-inc.gitbook.io/cde-cad-documentation/rest-api/fleet-treasury.md). Agents can also search and read this documentation through its [MCP server](https://cde-inc.gitbook.io/cde-cad-documentation/~gitbook/mcp).

# Fleet & Treasury Analytics

Every department runs its own books. Fine and citation revenue is credited to a department treasury; fleet costs - vehicle registration and insurance, one-time and recurring - are debited from it. This endpoint returns the balance, the income/expense totals, a breakdown by what drove each movement, and the recent ledger.

It is the data behind the Department Hub's Treasury tab, and it is a plain JSON feed, so a community can build its own reporting on top of it - a monthly budget report, a Discord summary, a fleet cost-per-vehicle sheet - without CDE CAD shipping each one.

***

{% hint style="info" %}
**Required headers**

```
Authorization: Bearer <token>
x-community-id: <communityId>
```

The caller needs the **`finance`** permission on the hub. Hub owners and community admins have it implicitly; everyone else gets it from a hub role. Without it the request returns `403`.
{% endhint %}

## Get Treasury Analytics

{% hint style="success" %}
**GET →** /api/hubs/:hubId/treasury
{% endhint %}

|               |           |                                                      |
| ------------- | --------- | ---------------------------------------------------- |
| **Parameter** | **Type**  | **Description**                                      |
| `hubId`       | URL param | The department hub. Scopes to that hub's department. |

**Response:**

```json
{
  "balance": 48250.00,
  "income": 91400.00,
  "expense": 43150.00,
  "byType": [
    { "type": "fine",         "credit": 74200, "debit": 0,     "count": 412 },
    { "type": "citation",     "credit": 17200, "debit": 0,     "count": 189 },
    { "type": "registration", "credit": 0,     "debit": 9600,  "count": 96 },
    { "type": "insurance",    "credit": 0,     "debit": 19200, "count": 96 },
    { "type": "payroll",      "credit": 0,     "debit": 14350, "count": 287 }
  ],
  "transactions": [
    {
      "type": "insurance",
      "direction": "debit",
      "amount": 200,
      "description": "Insurance renewal - E-51",
      "balanceAfter": 48250.00,
      "ref": { "kind": "apparatus", "id": "66f1..." },
      "byName": "System",
      "at": "2026-09-07T04:00:11.412Z"
    }
  ]
}
```

A department with no treasury yet is not an error. It returns zeros and empty arrays, because the account is created lazily on the first transaction:

```json
{ "balance": 0, "income": 0, "expense": 0, "byType": [], "transactions": [] }
```

### Fields

| Field                         | Description                                                                                                             |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `balance`                     | Current balance. Authoritative - maintained by an atomic increment on every movement.                                   |
| `income` / `expense`          | Lifetime totals of every credit and every debit **still in the ledger** (see the retention note below).                 |
| `byType[]`                    | One row per transaction type, with `credit`, `debit` and `count`. This is where the analytics live.                     |
| `transactions[]`              | The 100 most recent movements, newest first.                                                                            |
| `transactions[].balanceAfter` | Running balance snapshot. Best-effort under concurrent writes; `balance` is always correct.                             |
| `transactions[].ref`          | Back-link to what caused it - `{ kind: "apparatus", id }` for a fleet charge, and so on. Absent for manual adjustments. |

### Transaction types

| Type           | Direction | Raised by                                                                         |
| -------------- | --------- | --------------------------------------------------------------------------------- |
| `fine`         | credit    | A fine paid on a report or through banking.                                       |
| `citation`     | credit    | A citation issued to a civilian.                                                  |
| `registration` | debit     | Vehicle registration - charged once when an apparatus is plated, then on renewal. |
| `insurance`    | debit     | Vehicle insurance - same lifecycle as registration.                               |
| `payroll`      | debit     | Duty pay.                                                                         |
| `adjustment`   | either    | A manual correction (see below).                                                  |
| `transfer`     | either    | Movement between accounts.                                                        |
| `other`        | either    | Anything not classified above.                                                    |

***

## Where fleet costs come from

Two things debit a treasury for a vehicle, and they are worth separating when reading `byType`.

**On registration.** Plating a department apparatus charges `registrationFee` and `insuranceFee` once.

**On renewal.** Every hour, any department-scoped apparatus with a plate whose renewal has come due is re-billed `registrationRenewalFee` and `insuranceRenewalFee`, and its plate-lookup validity is pushed forward. Cadence is per community.

Both fee schedules live in community CAD settings:

| Setting                                          | Default | Meaning                                     |
| ------------------------------------------------ | ------- | ------------------------------------------- |
| `cadSettings.vehicleFees.registrationFee`        | `150`   | Charged once, when a rig is first plated.   |
| `cadSettings.vehicleFees.insuranceFee`           | `300`   | Same.                                       |
| `cadSettings.vehicleFees.registrationRenewalFee` | `100`   | Charged every renewal period.               |
| `cadSettings.vehicleFees.insuranceRenewalFee`    | `200`   | Same.                                       |
| `cadSettings.fleetRenewalPeriodDays`             | `30`    | Renewal cadence. **`0` disables renewals.** |

{% hint style="warning" %}
Only **department-scoped, plated** apparatus incur renewals. A rig with no `departmentId`, or no plate, is never billed - so a fleet cost that looks missing is usually a rig that was never assigned to a department.

A rig's first renewal cycle sets its schedule rather than charging it, so a newly plated vehicle is not billed twice in its first period.
{% endhint %}

***

## Adjust the Treasury

A manual deposit, withdrawal or correction. Recorded as an `adjustment` transaction naming the user who made it, so a correction is never anonymous in the ledger.

{% hint style="success" %}
**POST →** /api/hubs/:hubId/treasury/adjust
{% endhint %}

|               |          |                                            |
| ------------- | -------- | ------------------------------------------ |
| **Field**     | **Type** | **Description**                            |
| `direction`   | string   | `credit` or `debit`. Required.             |
| `amount`      | number   | Must be positive. Required.                |
| `description` | string   | Optional. Defaults to `Manual adjustment`. |

```bash
curl -X POST https://your-cad.com/api/hubs/{hubId}/treasury/adjust \
  -H "Authorization: Bearer <token>" \
  -H "x-community-id: <communityId>" \
  -H "Content-Type: application/json" \
  -d '{ "direction": "credit", "amount": 5000, "description": "Grant funding" }'
```

**Response:**

```json
{ "balance": 53250.00 }
```

| Status | Meaning                                                                    |
| ------ | -------------------------------------------------------------------------- |
| `400`  | `direction` is not `credit`/`debit`, or `amount` is not a positive number. |
| `403`  | The caller lacks the `finance` permission on this hub.                     |

***

## From a FiveM server

The same books, over a FiveM API key, for a garage kiosk that charges a department for a vehicle or a Discord bot reporting the month. Summarised by the same code the endpoints above use, so the number a chief reads in game is the number the CAD shows them.

{% hint style="info" %}
**Required header**

```
x-api-key: fvm_your_api_key_here
```

The key is bound to one community and only ever reads its own. Two scopes cover these, both offered under **Money** when you create a key:

| Scope            | Grants                                                                       |
| ---------------- | ---------------------------------------------------------------------------- |
| `treasury:read`  | Balance, totals and the recent ledger. Included in the game-server preset.   |
| `treasury:write` | Credit and debit a department. **Not** in any preset - tick it deliberately. |

`treasury:write` is separate from `banking:write` on purpose: a script that charges a department for a vehicle must not also be able to move a civilian's money.
{% endhint %}

### Read a department's books

{% hint style="success" %}
**GET →** /api/fivem/treasury
{% endhint %}

| Param          | Type  | Description                                                        |
| -------------- | ----- | ------------------------------------------------------------------ |
| `departmentId` | query | The department's id.                                               |
| `department`   | query | Its name or short name instead - `KPD` works, and so does `K.P.D.` |
| `limit`        | query | Transactions to return. Default 50, max 200.                       |

Pass one of `departmentId` or `department`. A department that does not belong to this key's community does not resolve, and the request is refused.

```bash
curl "https://your-cad.com/api/fivem/treasury?department=KPD&limit=10" \
  -H "x-api-key: fvm_your_api_key_here"
```

**Response:** the fields documented above, plus:

```json
{
  "success": true,
  "departmentId": "66f1...",
  "balance": 48250.00,
  "income": 91400.00,
  "expense": 43150.00,
  "byType": [ { "type": "fine", "credit": 74200, "debit": 0, "count": 412 } ],
  "transactions": [ "..." ],
  "transactionCount": 500
}
```

`transactionCount` is how many the ledger holds, so you can tell a full ledger from a page of one.

### Charge or credit a department

{% hint style="success" %}
**POST →** /api/fivem/treasury/adjust
{% endhint %}

| Field                          | Type   | Description                            |
| ------------------------------ | ------ | -------------------------------------- |
| `departmentId` or `department` | string | Which department. Same rules as above. |
| `direction`                    | string | `credit` or `debit`. Required.         |
| `amount`                       | number | Positive. Required.                    |
| `description`                  | string | Optional, trimmed to 200 characters.   |

```bash
curl -X POST https://your-cad.com/api/fivem/treasury/adjust \
  -H "x-api-key: fvm_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{ "department": "KPD", "direction": "debit", "amount": 1500, "description": "Bought unit 512" }'
```

```json
{ "success": true, "departmentId": "66f1...", "balance": 46750.00 }
```

The movement lands in the ledger as an `adjustment` attributed to `FiveM`, so an in-game charge is distinguishable from one a supervisor made by hand. "Who did this" is the first question anybody asks of an adjustment.

| Status | Meaning                                                  |
| ------ | -------------------------------------------------------- |
| `400`  | No department resolved, or `direction`/`amount` invalid. |
| `403`  | The key lacks the scope.                                 |

***

## Reading the numbers correctly

Three things will otherwise make a report wrong.

**The ledger is capped at 500 transactions.** Only the most recent 500 are kept per department. `balance` is unaffected - it is incremented atomically and never recomputed from the list - but `income`, `expense` and `byType` are summed from what remains. On a busy department they are *totals over the retained ledger*, not over all time. Pull regularly and keep your own history if you need lifetime figures.

**`transactions[]` returns 100, the ledger holds 500.** The totals above it cover all 500. Do not sum `transactions[]` and expect to match `income`.

**Treasury movement is best-effort by design.** A ledger write never blocks the thing that caused it: issuing a fine, paying a wage or plating a vehicle succeeds even if the treasury write fails. This is deliberate - a bookkeeping problem should not stop police work - but it means the ledger can under-count where the CAD could not resolve which department a movement belonged to.

{% hint style="warning" %}
**If revenue is not arriving**, the usual cause is a department-name mismatch. Movements are matched to a department by name, normalised, so `KPD` and `K.P.D.` match - but a name the CAD does not recognise at all is skipped. The server logs it, at most once per department per hour:

```
[DepartmentTreasury] No department matches "KPD" in community 66f1... Treasury
movement for it is being skipped - check the department name the CAD/FiveM side is sending.
```

Check that log first. It names the exact string that failed to match.
{% endhint %}
