# Databek Counter API guide

Counter (counter.databek.com) runs stock counts in shops and warehouses: an admin imports the accounting system's
stock list as a session, counters scan items on their phones (offline first) and the admin watches the differences live
and downloads the result for the accounting system. This guide covers the HTTP API behind the counter phone and the
admin's files.

## At a glance

| Topic | Rule |
|---|---|
| Base URL | `https://counter.databek.com`, paths under `/api/…` (no version segment) plus the upload actions under `/app/inventories/new/upload/…` |
| Format | JSON in and out unless stated (Excel downloads, Server-Sent Events, multipart uploads) |
| Auth | One httpOnly session cookie, `__Host-counter_session`, for every role; no API keys |
| Numbers | Quantities and money are decimal strings (`"12.5"`), never floats |
| IDs | UUID strings |
| Time | ISO 8601 with offset in JSON, except the stats' `activity[].at` and `byCounter[].lastAt` (text such as `2026-11-08 04:30:12.512+00`: a space instead of `T`, a short offset); the product shows `Asia/Tashkent` |
| Request id | Every response except uploads and static files carries `X-Request-ID` (yours, or a new one) |

## Who calls it

- **The counter phone** (the PWA at `/count`): catalog, lookups, entries, totals, zone and heartbeat under
  `/api/count/*`. A counter login works for one session only.
- **The admin** (`org_admin`): live session data and Excel files under `/api/sessions/*` and `/api/reports/*`,
  spreadsheet uploads under `/app/inventories/new/upload/*`.
- **Monitoring**: `GET /healthz`.

Counter has no integration key today. An integration acts as one of these logins with its cookie. Most of the admin
web (stores, sessions, counters, settings) runs on Next.js server actions, which are not a public API: stores,
counters and join links are made in the web app. No endpoint lists stores or sessions; a session's id is the `<id>`
in its admin address `/app/inventories/<id>`, and a store's id is the `open` value in the Stores page address once
its row is opened (`/app/stores?open=<id>`).

## Authentication

1. **Admin.** Sign in at `/login` in a browser (e-mail and password with a human check, or Google:
   `GET /api/auth/google?next=/app` redirects to Google, which comes back to `GET /api/auth/google/callback`). The
   answer sets `__Host-counter_session` (httpOnly, Secure, Path=/, no Domain, SameSite=Lax). There is no sign-in
   API: an integration signs in once in a browser and copies the cookie's value from the browser's storage.
2. **Counter.** On the web app's Counters page the admin adds each counter by name for a session and gets that
   counter's personal join link, `https://counter.databek.com/join/<token>`. Opening it in a browser signs the phone
   in as that counter (`org_counter`) for that one session and sets the same cookie. With the "one device" setting a
   second device is refused until the admin releases the first. When an admin is signed in on that browser, the join
   page asks first: continuing ends the admin login and signs the browser in as the counter.
3. Send the cookie on every call:

```bash
curl https://counter.databek.com/api/count/me \
  -H "Cookie: __Host-counter_session=<cookie value>"
```

An admin login lasts 30 days, a counter login 14 days. A counter login ends sooner after the idle auto-logout set in
the settings, when its link is revoked, or 7 days after its session closes. A login that ended answers 401; sign in
again or open the join link again.

**Writes and other sites.** There is no CSRF header. A write (any method but GET and HEAD) must come from the site's
own pages: a browser's `Sec-Fetch-Site` must be `same-origin` (or `none`); where a browser sends no `Sec-Fetch-Site`,
`Origin` must be `https://counter.databek.com`. Another site's page, a sibling `*.databek.com` host included, gets
403 `request.cross_site`. A server-side client that sends neither header is not refused by this rule.

## Flow 1: a counter phone counts offline and syncs

1. `GET /api/count/me`: who the counter is, the session (`status`, `itemCount`, `catalogVersion`), store,
   organization, settings, zones, the counter's zone and `recounts` (`[{itemId, epoch, counted, open}]` for items
   an admin sent to recount).
2. `GET /api/count/catalog`: the whole item list for offline search (`id`, barcode `b`, alternate codes `c`, article
   `a`, name `n`, unit `u`; never book quantities or prices) and its `version`. Next time send
   `If-None-Match: <version>` with that `version` exactly as it came (quotes included); 304 when the phone already has
   it. Send `Accept-Encoding: gzip`.
3. Optional: `POST /api/count/zone` with `{"zoneId": "<uuid>"}` (or `null`) when the settings let counters choose
   their zone (`counterChoosesZone`); otherwise 403 `zone.locked`.
4. Scan: look the code up in the cached catalog, or online with `GET /api/count/lookup?code=4780012345678` (barcode,
   alternate codes, GTIN padding, then article) or `?q=water%200.5` (URL-encoded; at least 2 characters, the first 6
   words count and every one must match; at most 30 items).
5. Store each count in a local outbox with a new UUID, then upload batches of 1–200:

```http
POST /api/count/entries
Content-Type: application/json

{"entries": [{"id": "2d4f6a8c-1e3b-4d5f-a7c9-e1b3d5f7a9c2",
  "itemId": "0b9e8d7c-6a5f-4e3d-9c2b-1a0f9e8d7c6b", "code": "4780012345678",
  "zoneId": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
  "qtyGood": "12", "qtyDamaged": "0", "qtyReturned": "0",
  "inputMethod": "camera", "rawScan": "4780012345678", "recountEpoch": 0,
  "clientCreatedAt": "2026-11-08T09:30:12.512+05:00"}]}
```

```json
{"accepted": ["2d4f6a8c-1e3b-4d5f-a7c9-e1b3d5f7a9c2"], "late": [],
 "rejected": [{"id": "5c1e…", "reason": "qty"}]}
```

   Each entry is judged on its own: `accepted` is stored, `late` waits for an admin (the session was closed),
   `rejected` holds `{id, reason}` objects that will never fit (`invalid`, `qty`, `total_cap`, `late_full` or
   `full`; drop them from the outbox). Entries are append-only and keyed by their `id`, so resending the same
   batch after a network error is safe. Remove only the `accepted`, `late` and `rejected` ids from the outbox.

   Entries add up: an item's count is the sum of its live entries, so send each new count once and never resend a
   whole stock figure under a new id. To correct a count, delete the earlier entries (step 7). `recountEpoch` is the
   item's `epoch` from `recounts` (0 for an item not listed): after an admin's recount only entries carrying the
   current epoch count, and an entry sent with an older epoch is stored but left out of the totals.
6. Every minute or so: `POST /api/count/me` with `{"pending": <entries still in the outbox>}` (heartbeat; the
   admin's Close dialog warns about them). It answers the same screen data as `GET /api/count/me`.
7. History and totals: `GET /api/count/entries` (own latest, newest first, at most 500, deleted ones included with
   `deleted: true`; `?item=<id>` gives that item's live entries, up to 5000), `GET /api/count/totals` (own totals per
   item: `[itemId, good, damaged, returned, entries]`), `DELETE /api/count/entries/{id}` (soft delete of an own entry
   while the session is open; repeating it answers 200).

## Flow 2: an admin watches a session and downloads the result

- `GET /api/sessions/{id}/stats`: totals, differences (`diffCount`, `diffSum`), uncounted value, damaged, returned,
  unknown codes, per zone and per counter, and the 30 latest entries.
- `GET /api/sessions/{id}/events`: Server-Sent Events: `retry: 3000` and `ready` first, then one `entry` event per new
  or changed entry (`{"type": "entry" | "entry_update", "id", "item_id", "user_id"}`), and a `: ping` comment every
  25 s. Refresh the stats when an `entry` arrives. A user keeps at most 5 streams: a sixth closes the oldest.

```bash
curl -N https://counter.databek.com/api/sessions/<id>/events -H "Cookie: __Host-counter_session=<admin cookie>"
```

- Files: `GET /api/sessions/{id}/export` (the original file with only the fact column filled, ready to import back,
  in the original's format: xlsx, xlsm, xls, ods or csv; `?format=xlsx` turns xls and ods into .xlsx; 409
  `session.no_file` when the session had no file), `GET /api/sessions/{id}/items-export?f=&q=&sort=&dir=` (one tab
  of the items table, .xlsx), `GET /api/sessions/{id}/report` (items, every entry and unknown codes, .xlsx). These
  three share a limit of 30 downloads an hour per admin. `GET /api/reports/compare` (.xlsx, no limit) puts the latest
  closed session of every active store side by side. Sheet headers and file names are Uzbek by design.

## Flow 3: create a session from a spreadsheet

Multipart uploads of up to 20 MB with a `Content-Length` header, one at a time per person, organization and
network; preview and create together 30 an hour per person.

1. `POST /app/inventories/new/upload/preview` with `file` (and optional `templateId`): what the import would read
   (sheet, header row, column mapping, counts). Nothing is stored.
2. `POST /app/inventories/new/upload/create` with `name`, `storeId`, `file` and optional `zones` (zone names
   separated by new lines or commas, at most 50) and `templateId`: a new open session; the answer is
   `{"ok": true, "data": {"id": "<session id>"}}`. The store must exist in the web app first; its id is in the
   Stores page address (`/app/stores?open=<id>`, see "Who calls it").
3. Add the counters in the web app and share their join links (Flow 1).

Templates for unusual files: `POST /app/inventories/new/upload/sample` (sheets, detected header and a first mapping)
and `POST /app/inventories/new/upload/export-preview` (where the counts will land on export).

An upload that reaches the handler answers HTTP 200 with `{"ok": true, "data": …}` or
`{"ok": false, "error": "<text for people>", "field"?}` for any refusal (the hourly limit, a missing or bad field, an
unknown `storeId`, too many items, the organization's limits, an unreadable file); `error` has no stable code.
Transport problems answer an error status (403 `upload.verify_first` for an admin with an unconfirmed e-mail, 404
`upload.not_found`, 408 too slow, 409 another upload running, 413 too large or no `Content-Length`, 429 wait 15
minutes, 503 busy).

## Errors

Two shapes, by group:

- `/api/count/*`: `{"code": "session.closed", "message": "Session is not open", "field": "zoneId"?}`.
- Admin files, live data and uploads: `{"error": {"code": "session.not_found", "message": "Session not found"}}`.
  The live event stream answers `auth` (401 and 403) and `not_found` (404) instead.

`code` is stable; `message` is for display only: fixed English text, except on uploads and on the downloads' 409,
422 and 429, which follow the person's language (Uzbek or Russian).

| Status | Codes | What to do |
|---|---|---|
| 400 | `request.invalid`, `request.invalid_json`, `upload.unreadable` | Fix the body (more than 200 entries is `request.invalid`) |
| 401 | `auth.required` (`auth` on the event stream) | Sign in again or reopen the join link |
| 403 | `auth.forbidden`, `request.cross_site`, `zone.locked`, `upload.verify_first` | Wrong role, another site, zone set by the admin, e-mail not confirmed |
| 404 | `session.not_found`, `entry.not_found`, `zone.not_found`, `upload.not_found` (`not_found` on the event stream) | Check the id |
| 408 | `upload.too_slow` | Upload again on a faster network |
| 409 | `session.closed`, `session.no_file`, `upload.in_progress` | The session is not open, or wait |
| 413 | `request.too_large`, `upload.too_large` | Smaller batch (≤ 1 MB) or file (≤ 20 MB) |
| 422 | `request.invalid`, `sheet.failed` | A bad zone or item id; the spreadsheet job failed or is full: retry later |
| 423 | `session.locked` | The admin locked the session; keep the outbox and retry later |
| 429 | `rate.limited`, `rate_limited`, `upload.too_slow_wait` | Back off (3000 entries a minute per counter; 30 downloads an hour) |
| 500 | `server.error` (counter API only) | Retry later; the id in the message is in the server log |
| 503 | `upload.busy` | Uploads are busy: retry later |

## Webhooks

None. Watch a session with the event stream (`/api/sessions/{id}/events`).

## Health

`GET /healthz` answers `{"status": "ok", "db": true, "release": "8e48c6a"}` (503 `degraded` when the database is
down).

<!-- endpoint-index:start (generated from openapi.json) -->

## Endpoint index

Every operation of `openapi.json` (23), grouped by tag: method and path, who may call it, query parameters, body fields (`*` = required) and the top-level fields of the answer. Schemas, types and examples are in `openapi.json`.

### counting

The counter phone: catalog, entries, totals, zone and heartbeat.

- `GET /api/count/catalog` Session catalog · Counter login (`org_counter`) made by a session's join link; it works for that one session only · headers: `If-None-Match`, `Accept-Encoding` · answers 200: `version`, `items`
- `GET /api/count/entries` Own entries · Counter login (`org_counter`) made by a session's join link; it works for that one session only · query: `item` · answers 200: `entries`
- `POST /api/count/entries` Upload entries · Counter login (`org_counter`) made by a session's join link; it works for that one session only · body (JSON): `entries*` · answers 200: `accepted`, `late`, `rejected`
- `DELETE /api/count/entries/{id}` Delete own entry · Counter login (`org_counter`) made by a session's join link; it works for that one session only · answers 200: `deleted`
- `GET /api/count/lookup` Look up items · Counter login (`org_counter`) made by a session's join link; it works for that one session only · query: `code`, `q` · answers 200: `items`
- `GET /api/count/me` Counter screen data · Counter login (`org_counter`) made by a session's join link; it works for that one session only · answers 200: `user`, `session`, `store`, `org`, `settings`, `zones`, `zoneId`, `tokenExpiresAt`, `release`, `recounts`, `recountTasks`
- `POST /api/count/me` Heartbeat · Counter login (`org_counter`) made by a session's join link; it works for that one session only · body (JSON): `pending*` · answers 200: `user`, `session`, `store`, `org`, `settings`, `zones`, `zoneId`, `tokenExpiresAt`, `release`, `recounts`, `recountTasks`
- `GET /api/count/totals` Own totals · Counter login (`org_counter`) made by a session's join link; it works for that one session only · answers 200: `totals`
- `POST /api/count/zone` Choose zone · Counter login (`org_counter`) made by a session's join link; it works for that one session only · body (JSON): `zoneId*` · answers 200: `zoneId`

### sessions

The admin's live session data and Excel downloads.

- `GET /api/sessions/{id}/events` Live entries (SSE) · Organization admin (`org_admin`) · answers 200: text/event-stream
- `GET /api/sessions/{id}/stats` Session statistics · Organization admin (`org_admin`) · answers 200: `stats`, `activity`
- `GET /api/sessions/{id}/export` Export for import · Organization admin (`org_admin`) · query: `format` · answers 200: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet or application/vnd.ms-excel or text/csv; charset=utf-8 or application/vnd.oasis.opendocument.spreadsheet or application/vnd.ms-excel.sheet.macroEnabled.12
- `GET /api/sessions/{id}/items-export` Items table as Excel · Organization admin (`org_admin`) · query: `f`, `q`, `sort`, `dir` · answers 200: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
- `GET /api/sessions/{id}/report` Full report · Organization admin (`org_admin`) · answers 200: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

### reports

Reports across stores.

- `GET /api/reports/compare` Compare stores · Organization admin (`org_admin`) · answers 200: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

### auth

Google sign-in for admins.

- `GET /api/auth/google` Start Google sign-in · Public: no login · query: `next`
- `GET /api/auth/google/callback` Google sign-in callback · Public: no login · query: `code`, `state`, `error`

### uploads

Spreadsheet uploads of the import wizard and the template builder; any other action than these four answers 404 `upload.not_found`. Until 2026-11-08 they lived under `/app/inventarizatsiyalar/yangi/upload/`; that address answers 308 to the same action here.

- `POST /app/inventories/new/upload/preview` Preview a session import · Organization admin (`org_admin`) · body (multipart/form-data): `file*`, `templateId` · answers 200: JSON
- `POST /app/inventories/new/upload/create` Create a session from a file · Organization admin (`org_admin`) · body (multipart/form-data): `name*`, `storeId*`, `zones`, `templateId`, `file*` · answers 200: JSON
- `POST /app/inventories/new/upload/sample` Analyse a template sample · Organization admin (`org_admin`), for the organization's templates · body (multipart/form-data): `file*`, `sheet` · answers 200: JSON
- `POST /app/inventories/new/upload/export-preview` Preview a template export · Organization admin (`org_admin`), for the organization's templates · body (multipart/form-data): `file*`, `config*` · answers 200: JSON

### system

Health and the service worker's asset list.

- `GET /healthz` Health · Public: no login · answers 200: `status`, `db`, `release`
- `GET /sw-assets` Service worker assets · Public: no login · answers 200: `version`, `assets`

<!-- endpoint-index:end -->
