# kalcerPOS External API

Machine-readable reference for AI agents and integrations. Human guide (Indonesian): https://docs.kalcerpos.com/docs/features/external-api
OpenAPI 3.1 spec: https://docs.kalcerpos.com/docs/external-api.openapi.json

The External API gives one kalcerPOS store (café/restaurant POS) narrow access: read sales reports, read/create/update products and stock, and create unpaid open bills. It is a paid add-on (Rp 50.000 per month per store) that kalcerPOS admin switches on per store.

## Essentials

| Item | Rule |
|---|---|
| Base URL | `https://<slug>.kalcerpos.com/api/external` (e.g. `https://namatoko.kalcerpos.com/api/external`) |
| Auth | `Authorization: Bearer <API_KEY>` on every call. Key format `<tenantId>.<64 hex chars>`, generated by the store admin in Admin → Settings → External API access. The key, not the host, selects the store. Regenerating it invalidates the old key at once. One key per store. |
| Body | JSON. Send `Content-Type: application/json` on POST/PATCH (otherwise the body is ignored and validation fails). Max 1 MB. |
| Dates | `YYYY-MM-DD`, the store's local calendar date (store timezone, usually `Asia/Jakarta`). |
| Money | Indonesian rupiah as plain integers (`22000`), no separators, no decimals. |
| Ids | Product ids are opaque, case-sensitive Firestore ids from `GET /products`. Never derive them from names. |
| Stock | `stock >= 999` means unlimited. Recipe/combo products always report 999 (their stock lives in ingredients/component products). |
| Errors | JSON `{"error": "..."}` with a 4xx/5xx status (exceptions noted below). |
| CORS | None. Call from a server or agent runtime, not from browser JavaScript on another origin. |
| Rate limits | None enforced by the API; be reasonable. |

## Routes

| Method | Path | Purpose |
|---|---|---|
| GET | `/reports/summary?from=&to=` | Order count, gross sales, refunds, net sales, COGS, gross profit |
| GET | `/reports/by-item?from=&to=` | Qty and gross revenue per product name |
| GET | `/reports/by-payment?from=&to=` | Totals per payment method |
| GET | `/reports/by-hour?from=&to=` | Orders and revenue per hour of day (0-23), summed over the range |
| GET | `/products` | All products |
| POST | `/products` | Create a product |
| PATCH | `/products/{id}` | Update `stock`, `price`, `stockThreshold` |
| POST | `/orders` | Create an unpaid open bill (sent to kitchen/bar) |

Not available on purpose: payments / marking orders paid, deleting anything, reading a single order or an order list, customer data (PII), modifiers, bulk discounts, recipes, vouchers, editing name/category/sku/station/cogs/active of existing products.

## Recommended agent workflow

1. Reports: always pass explicit `from` and `to`. Compute "today"/"yesterday" in the store's timezone (WIB = UTC+7 for most stores), not UTC. Check `range` in the reply.
2. Before creating an order or editing a product, call `GET /products` and map the user's wording to an `id`. Ask the user when several products match.
3. Check `stock` before ordering. On `409`, tell the user the `available` amount; do not retry automatically.
4. `POST /orders` and `POST /products` are not idempotent. A repeat creates a second order/product. Retry only when the earlier call clearly did not succeed.
5. To add stock, read the current `stock`, add, and PATCH the new total (`stock` overwrites).
6. An open bill created via the API is unpaid; it only appears in reports after a cashier takes payment in the POS.

## Report rules (all four report routes)

- Query params `from`, `to`: `YYYY-MM-DD`, inclusive, matched against the order's store-local date. A missing value becomes today's date in the store's timezone. A malformed or impossible date (e.g. `2026-02-30`), or `from` after `to`, is refused with `400` (`from must be a date as YYYY-MM-DD`, `from must not be after to`).
- Only paid orders count (`paid !== false`). Unpaid open bills are excluded.
- Refunds are attributed to the original order's date, not the refund date.
- Every reply includes `range: {from, to}` (the values actually used).

### GET /reports/summary

```
curl -H "Authorization: Bearer $KEY" "https://namatoko.kalcerpos.com/api/external/reports/summary?from=2026-11-01&to=2026-11-07"
```

```json
{"range":{"from":"2026-11-01","to":"2026-11-07"},"orders":182,"grossSales":5460000,"refunds":45000,"netSales":5398000,"cogs":1910000,"grossProfit":3488000}
```

- `orders`: number of paid orders.
- `grossSales`: sum of (item price + modifier price) × qty, before voucher discounts.
- `refunds`: sum of refunded amounts on those orders.
- `netSales`: sum of order totals (after discounts, incl. QRIS unique code) minus `refunds`.
- `cogs`: sum of item cost × qty.
- `grossProfit`: `netSales - cogs`.

### GET /reports/by-item

```
curl -H "Authorization: Bearer $KEY" "https://namatoko.kalcerpos.com/api/external/reports/by-item?from=2026-11-01&to=2026-11-07"
```

```json
{"range":{"from":"2026-11-01","to":"2026-11-07"},"items":[{"name":"Es Kopi Susu","qty":64,"revenue":1408000},{"name":"Roti Bakar","qty":31,"revenue":558000}]}
```

Grouped by product name, sorted by `qty` descending. `revenue` is gross ((price + modifier price) × qty), not net of discounts or refunds.

### GET /reports/by-payment

```
curl -H "Authorization: Bearer $KEY" "https://namatoko.kalcerpos.com/api/external/reports/by-payment?from=2026-11-01&to=2026-11-07"
```

```json
{"range":{"from":"2026-11-01","to":"2026-11-07"},"byMethod":{"cash":2150000,"qris":3020000,"card":228000}}
```

Keys are lower-case method ids: `cash`, `qris`, `card` (EDC), store-defined methods `m_<id>`, and `other` for old orders without a method. Split payments count per split. Not net of refunds. Methods with no sales are omitted.

### GET /reports/by-hour

```
curl -H "Authorization: Bearer $KEY" "https://namatoko.kalcerpos.com/api/external/reports/by-hour?from=2026-11-01&to=2026-11-07"
```

```json
{"range":{"from":"2026-11-01","to":"2026-11-07"},"timezone":"Asia/Jakarta","byHour":[{"hour":0,"orders":0,"revenue":0},{"hour":12,"orders":31,"revenue":948000},{"hour":23,"orders":0,"revenue":0}]}
```

(Shortened; `byHour` always has exactly 24 entries, hours 0-23.) Hours are in the store timezone (`timezone`, from the store settings, default `Asia/Jakarta`). All days in the range are summed per hour. For one day, use the same `from` and `to`. `revenue` = order totals, not net of refunds.

## GET /products

```
curl -H "Authorization: Bearer $KEY" "https://namatoko.kalcerpos.com/api/external/products"
```

```json
{"products":[{"id":"7fQ2kLm9XbR1sT4uVw8y","sku":"KP-01","name":"Es Kopi Susu","category":"Kopi","price":22000,"stock":40,"stockThreshold":5},{"id":"a1B2c3D4e5F6g7H8i9J0","sku":"","name":"Paket Hemat","category":"Paket","price":30000,"stock":999,"stockThreshold":0}]}
```

All products in one reply (no paging), including products hidden from the cashier; the active flag is not returned. Missing text fields are `""`, missing numbers `0`.

## POST /products

```
curl -X POST -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"name":"Es Kopi Susu","price":22000,"category":"Kopi","stock":50}' \
  "https://namatoko.kalcerpos.com/api/external/products"
```

| Field | Type | Required | Default / notes |
|---|---|---|---|
| `name` | string | yes | trimmed, must be non-empty |
| `price` | number | yes | >= 0 (numeric strings are accepted) |
| `sku` | string | no | `""` |
| `category` | string | no | `"Uncategorised"` |
| `station` | `"kitchen"` or `"bar"` | no | anything other than `"kitchen"` becomes `"bar"` |
| `cogs` | number | no | `0` (cost per unit) |
| `stock` | number | no | `999` (unlimited) |
| `stockThreshold` | number | no | `0` (low-stock threshold) |
| `desc` | string | no | `""` |
| `active` | boolean | no | `true`; `false` hides it from the cashier |

Invalid or negative optional numbers are not rejected; they fall back to the default. Unknown fields are ignored. No duplicate-name check.

Reply `201`:

```json
{"ok":true,"id":"Zx81LmQp0aB2cD3eF4gH","product":{"id":"Zx81LmQp0aB2cD3eF4gH","name":"Es Kopi Susu","sku":"","category":"Kopi","station":"bar","price":22000,"cogs":0,"stock":50,"stockThreshold":0,"bulkQty":0,"bulkType":"percent","bulkValue":0,"swatch":"#a98558","desc":"","active":true,"modifiers":[],"recipe":[]}}
```

## PATCH /products/{id}

```
curl -X PATCH -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"stock":40,"price":23000}' \
  "https://namatoko.kalcerpos.com/api/external/products/7fQ2kLm9XbR1sT4uVw8y"
```

```json
{"ok":true,"id":"7fQ2kLm9XbR1sT4uVw8y","updated":{"stock":40,"price":23000}}
```

- Only `stock`, `price`, `stockThreshold` (each a number >= 0). At least one is required. Other fields and `null` values are ignored. `updated` lists what was saved.
- `stock` overwrites the value (it does not add). A stock change is logged in stock movements (`reason` `adjustment`, note `External API`) and the reply includes `stockBefore`. PATCH does not send low-stock notifications.

## POST /orders

Creates an **open bill** (unpaid, `status: "open"`), exactly like the cashier's "Save open bill".

```
curl -X POST -H "Authorization: Bearer $KEY" -H "Content-Type: application/json" \
  -d '{"table":"5","customer":"Rina","items":[{"productId":"7fQ2kLm9XbR1sT4uVw8y","qty":2,"notes":"less sugar"}]}' \
  "https://namatoko.kalcerpos.com/api/external/orders"
```

| Field | Type | Required | Default / notes |
|---|---|---|---|
| `items` | array | yes | at least one line |
| `items[].productId` | string | yes | id from `GET /products` |
| `items[].qty` | number | yes | > 0 |
| `items[].notes` | string | no | kitchen note, cut at 200 chars |
| `table` | string or number | no | `"T"`; `"5"` and `5` are both accepted, max 40 characters |
| `customer` | string | no | `"Walk-in"` |

Reply `201`:

```json
{"ok":true,"id":"Hk3PqR8sT1uV2wX4yZ5a","shortId":"K7MPX","total":44000,"items":1}
```

`id` = order id, `shortId` = 5-character code printed on tickets and shown in the POS, `total` = bill amount in rupiah, `items` = number of lines.

Side effects:

- Prices come from the current product catalog (caller cannot set prices). No modifiers, bulk discounts, vouchers, deposits or payment.
- Inactive products (hidden from the cashier) are refused: `409` with `code: "inactive"` and `productId`.
- Stock is checked for the whole order inside one transaction together with the order write and every decrement: if anything is short the reply is `409` and nothing is written, and two calls at the same moment can never both take the last unit.
- On success stock is decremented: plain products from their own stock, recipe products from their ingredients, combo/package products from their component products. Each change is logged in the store's stock movements (`reason` `sale` / `recipe_consumption`, user `external-api`).
- The order is dated today in the store timezone, stamped `cashierEmail: "external-api"`, and shows up live in the cashier's Bills list and on the kitchen/bar display.
- Kitchen, bar and waitress tickets are printed (a combo whose components span kitchen and bar prints on both) via the store's printer tablet. Tickets wait in a queue for up to 10 minutes; printing never fails the API call.
- The order only counts in reports after a cashier takes payment.

## Errors

| Status | `error` | Meaning |
|---|---|---|
| 400 | `name is required` | POST /products without a non-empty string `name` |
| 400 | `price is required and must be a non-negative number` | bad `price` |
| 400 | `invalid stock` / `invalid price` / `invalid stockThreshold` | PATCH value not a number >= 0 |
| 400 | `no valid fields to update` | PATCH with none of the allowed fields |
| 400 | `items must be a non-empty array` | POST /orders without items |
| 400 | `each item needs a productId and a positive qty` | bad order line |
| 400 | (HTML body) | request body is not valid JSON |
| 401 | `unauthorized` | missing/wrong/regenerated key, or the store is suspended |
| 403 | `External API add-on is not active for this store` | add-on off |
| 403 | body also has `"code":"trial_locked"` | free trial ended: GET routes still work, POST/PATCH are refused until the store pays |
| 404 | `product not found` / `product not found: <id>` | unknown product id |
| 404 | `combo component product not found: <id>` / `ingredient not found: <id>` | a package/recipe points at a deleted product/ingredient |
| 404 | (non-JSON) | unknown path |
| 409 | `insufficient stock: <name>` / `insufficient ingredient stock: <name>` | not enough stock; reply also has `available` and `needed` |
| 409 | `product not active: <name>` | product is hidden from the cashier; reply has `code: "inactive"` and `productId` |
| 400 | `from must be a date as YYYY-MM-DD` / `from must not be after to` | bad report date |
| 500 | `internal error` | server error, with `detail`; retry later |
| 503 | `external API not configured` | server not ready; retry later |

Examples:

```json
{"error":"insufficient stock: Es Kopi Susu","available":1,"needed":2}
```

```json
{"ok":false,"error":"Masa coba toko ini sudah habis. Data kamu aman, tapi toko hanya bisa dilihat sampai paket dibayar.","code":"trial_locked"}
```
