
## Aggregate order statuses

`POST /v1/order-statuses/aggregate`

Counts statuses grouped by `type` or `notify`. The only numeric field is `sort`, so numeric functions (`sum`, `avg`) are rarely useful — the main scenario is `count` with a filter or grouping.

## Standard fields

All status fields are categorical — suitable only for `groupBy` and `filter`:

| Field | Purpose |
|------|------------|
| `type` | Group by type: `O` (order) or `D` (delivery) |
| `notify` | Group by whether a notification is sent |

The full list of aggregatable fields is shown in the table above.

## Request fields (body)

| Parameter | Type | Required | Description |
|----------|-----|:-----:|---------|
| `aggregate` | array | no | Array of aggregations. For statuses the main option is `count`. The numeric functions accept the only numeric field, `sort`. The count format is `{ "field": "*", "function": "count" }`. Without the parameter — a `count` of the records matching the filter |
| `filter` | object | no | Filtering — the same fields as in [`GET /v1/order-statuses`](./list.md). [Filtering syntax](/docs/filtering) |
| `groupBy` | string \| string[] | no | Field or array of fields to group by (maximum 5) |
| `groupOrderBy` | array | no | Group sorting: `[{ "field": "count", "direction": "desc" }]` |
| `groupLimit` | number | no | Limit on the number of returned groups (1-1000) |

## Examples

### curl — personal key

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/order-statuses/aggregate" \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "groupBy": "type"
  }'
```

### curl — OAuth application

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/order-statuses/aggregate" \
  -H "X-Api-Key: YOUR_APP_KEY" \
  -H "Authorization: Bearer USER_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "groupBy": "type"
  }'
```

### JavaScript — personal key

```javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/order-statuses/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    groupBy: 'type',
  }),
})

const { success, data } = await res.json()
console.log('Status distribution:', data.groups)
```

### JavaScript — OAuth application

```javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/order-statuses/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_APP_KEY',
    'Authorization': 'Bearer USER_SESSION_TOKEN',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    groupBy: 'type',
  }),
})

const { success, data } = await res.json()
```

## Other scenarios

Count records — `count` with field `"*"`, the fastest request without fetching records. Without the `aggregate` array the result is the same:

```json
{ "aggregate": [{ "field": "*", "function": "count" }] }
```

How many statuses have notifications enabled:

```json
{
  "filter": { "notify": true }
}
```

Group by both axes at once:

```json
{
  "groupBy": ["type", "notify"]
}
```

## Response fields

| Field | Type | Description |
|------|-----|---------|
| `success` | boolean | Always `true` on success |
| `data.count` | number | Total number of statuses matching the filter |
| `data.aggregates` | object | Numeric aggregation results — for statuses they are computed over `sort` only; an empty object when no `aggregate` array is passed |
| `data.groups` | array | Groups (only with `groupBy`) |
| `data.meta.totalRecords` | number | Total number of records |
| `data.meta.recordsProcessed` | number | Number of processed records |
| `data.meta.truncated` | boolean | `true` when the numbers were computed over only some of the records that match the filter: fewer records were read than `data.count` promised — including when more than 5000 matched the filter — or the slice was cut short by a sub-page error. The size of the gap is reported in `data.meta.recordsShortfall`, the interrupted slice in `data.meta.pageErrorSample`. Always present, and `false` on a complete response. If the request has neither `groupBy` nor a numeric function, no records are fetched and the flag is always `false` |
| `data.meta.groupTotal` | number | Number of groups before `groupLimit` |
| `data.meta.groupsTruncated` | boolean | Whether the group list was truncated by `groupLimit` |

## Response example

```json
{
  "success": true,
  "data": {
    "count": 9,
    "aggregates": {},
    "groups": [
      { "type": "O", "count": 6, "aggregates": {} },
      { "type": "D", "count": 3, "aggregates": {} }
    ],
    "meta": {
      "totalRecords": 9,
      "recordsProcessed": 9,
      "truncated": false,
      "groupTotal": 2,
      "groupsTruncated": false
    }
  }
}
```

Without `groupBy`, the `data.groups` field is absent from the response.

## Error response example

400 — unknown field in `groupBy`:

```json
{
  "success": false,
  "error": {
    "code": "INVALID_PARAMS",
    "message": "groupBy field 'foo' is not aggregatable on this entity. Available: type, notify."
  }
}
```

## Errors

| HTTP | Code | Description |
|------|-----|---------|
| 400 | `INVALID_PARAMS` | Unknown function or nonexistent field — the message contains a list of allowed fields |
| 400 | `INVALID_PARAMS` | More than 5 fields passed in `groupBy` |
| 400 | `INVALID_PARAMS` | Reserved keywords in `groupBy`: `count`, `aggregates`, `meta`, `groups` |
| 403 | `SCOPE_DENIED` | The API key does not have the `sale` scope |
| 401 | `TOKEN_MISSING` | The API key has no configured tokens |
| 429 | `RATE_LIMITED` | Rate limit exceeded: 300 requests per minute per portal. All API keys of the portal share one limit. The current limit is returned in the `x-ratelimit-limit` header. Retry after the delay in the `Retry-After` header |

For the full list of general API errors, see [Errors](/docs/errors).

## Known specifics

**In practice only `count` is needed.** The only numeric field of a status is `sort`, and it is the only one the `sum` / `avg` / `min` / `max` functions accept; for any other field, they return `400 INVALID_PARAMS`. To count statuses, use `count` (without `aggregate`) with a filter or grouping.

**Small data volume.** A Bitrix24 account holds only dozens of statuses, so the 5000-record ceiling is never reached for this entity.

**The truncation marker travels with the number itself.** When a response arrives with `meta.truncated: true`, the marker `truncated: true` sits inside every field object in `data.aggregates` and on every element of `data.groups`, and `data.meta.warnings` gains a warning with the code `AGGREGATE_TRUNCATED`. A client that reads only the number itself therefore sees that it was computed over only some of the records. None of these markers appear on a complete response. For full details, see [Aggregation POST — the 5000-record ceiling](/docs/entity-api#aggregation-post-the-5000-record-ceiling).

## See also

- [List statuses](./list.md)
- [Search statuses](./search.md)
- [Status fields](./fields.md)
- [Filtering syntax](/docs/filtering)
- [Limits and optimization](/docs/optimization)
