# Tables + Orders Sync API Reference

This file documents the actual backend flow between the admin `Tables` page and `Orders` page based on the current routes, controllers, and database schema in this repo.

Base API prefixes:

- `/api/tables`
- `/api/orders`
- `/api/items`
- `/api/zones`
- `/api/receipt-config`

All routes below are protected with `Authorization: Bearer <jwt>` unless noted otherwise.

---

## 1. Current Relationship Between Tables and Orders

These two modules are related in the current backend.

- `restaurant_tables` is the live POS/table source.
- `table_carts` and `table_cart_items` store the current table cart/KOT state.
- `orders` and `order_items` store the KDS/live order ticket snapshot.
- `order_status_log` stores order status history.
- `invoices` stores order checkout/payment history.
- `billing_records` stores receipt/bill history.

### Table status to order status mapping

| Table status | Order status |
|---|---|
| `Running` | `pending` |
| `RunningKOT` | `preparing` |
| `Printed` | `ready` |
| `Paid` | `served` |
| `Blank` | no direct mapped order status; used by clear/cancel/checkout reset flows |

### Auto-sync behavior already present

- `PATCH /api/tables/:id/status`
  - when status becomes `Running` or `RunningKOT`, backend auto-creates an active order if one does not already exist
  - then syncs table status to order status
  - emits `table_updated`
  - emits `order_created` if a new order was created
  - emits `order_updated` if the order status changed

---

## 2. Tables Module APIs

### Core table lifecycle

- `GET /api/tables`
  - returns active tables for the POS grid
  - includes `id`, `table_number`, `zone_id`, `status`, split flags, and `current_order_started_at`

- `POST /api/tables`
  - creates a new table

- `PATCH /api/tables/:id/status`
  - updates table status
  - allowed values: `Blank`, `Running`, `Printed`, `Paid`, `RunningKOT`
  - sets `current_order_started_at` when moving to `Running` or `RunningKOT`
  - clears `current_order_started_at` when moving to `Blank`
  - syncs order status automatically as described above

- `PUT /api/tables/:id/metadata`
  - updates `customer_name`, `customer_phone`, `waiter_id`, `pax`, `comments`
  - also updates waiter live table counts through socket event flow
  - also updates the active order header for that table

- `POST /api/tables/:id/split`
  - creates virtual split tables like `T1-A`, `T1-B`
  - clones table cart items and global discount into each split table
  - hides the original parent table by setting `has_active_splits = TRUE`
  - clears the parent table cart to avoid double billing
  - cancels the parent table's active order
  - auto-creates synced orders for the new split tables

### Table cart / KOT APIs

- `GET /api/tables/:id/orders`
  - returns current `table_cart_items`
  - returns current global discount from `table_carts`

- `POST /api/tables/:id/orders/items`
  - adds an item to the table cart
  - auto-creates a `table_carts` row if missing
  - also refreshes the active order snapshot when one already exists

- `PATCH /api/tables/:id/orders/items/:cart_item_id`
  - updates `quantity`, `is_complimentary`, `item_discount`
  - also refreshes the active order snapshot when one already exists

- `DELETE /api/tables/:id/orders/items/:cart_item_id`
  - removes one cart item from the table cart
  - also refreshes the active order snapshot when one already exists
  - cancels the active order if the cart becomes empty

- `PATCH /api/tables/:id/orders/discount`
  - updates `global_discount_type`, `global_discount_value`, `global_coupon_code`
  - also refreshes active order totals when an order already exists

### Table settlement / reset APIs

- `POST /api/tables/:id/settle`
  - settles directly from live table cart data
  - creates or refreshes the related `orders` / `order_items` snapshot
  - updates the order to `completed`
  - writes `order_status_log`
  - creates an `invoices` payment history row
  - creates a `billing_records` row unless `save_bill = false`
  - logs sales to accounting/expenses
  - resets normal tables to `Blank` and clears cart data
  - deletes virtual split tables after settlement
  - emits `order_completed`
  - emits `table_updated`

- `POST /api/tables/:id/clear`
  - force clears a table without settlement
  - resets normal tables to `Blank` and clears cart data
  - deletes virtual split tables
  - cancels any active order linked to the table
  - emits `table_updated`

### Important note

- There is currently no `DELETE /api/tables/:id` route in `src/routes/table.routes.js`.

---

## 3. Orders Module APIs

### Live KDS / tracking

- `GET /api/orders/stats/summary`
  - returns `active_orders`, `today_revenue`, `orders_completed_today`, `status_breakdown`

- `GET /api/orders/active`
  - returns all non-terminal orders
  - joins waiter and live table status
  - includes `items`

- `GET /api/orders/:orderId/live`
  - lightweight order refresh API
  - includes current `table_status`

- `GET /api/orders/:orderId`
  - full order detail API
  - includes `items`
  - includes invoice/billing details if settled
  - includes `status_log`

### Order history

- `GET /api/orders/history`
  - returns paginated terminal orders
  - filter params:
    - `page`
    - `limit`
    - `search`
    - `date`
    - `status` as `completed` or `cancelled`
  - joins `orders`, `order_items`, `invoices`, `billing_records`, `waiters`

- `GET /api/orders/history/export`
  - exports completed/cancelled order history as CSV
  - query params: `from`, `to`

### Order sync / mutation

- `POST /api/orders/sync-from-table/:tableId`
  - manual bridge from `restaurant_tables` + `table_cart_items` to `orders` + `order_items`
  - mainly fallback if auto-sync was missed

- `PATCH /api/orders/:orderId/status`
  - manual order status API
  - only allows `completed` or `cancelled`
  - blocks `pending`, `preparing`, `ready`, `served` because those are table-driven
  - on `cancelled`:
    - resets table to `Blank`
    - clears table cart
    - clears table cart items
    - writes `order_status_log`
    - emits `order_updated`
    - emits `table_updated`

- `PATCH /api/orders/:orderId/items`
  - replaces the current order snapshot items
  - recalculates `subtotal`, `tax`, `total`
  - emits `order_items_updated`

- `POST /api/orders/:orderId/checkout`
  - final order payment flow
  - creates `billing_records`
  - creates `invoices`
  - updates order to `completed`
  - writes `order_status_log`
  - logs sales to accounting/expenses
  - resets table to `Blank`
  - clears table cart and cart items
  - emits `order_completed`
  - emits `table_updated`

---

## 4. Supporting APIs Used By Tables Page

- `GET /api/items/public/menu`
  - used for POS menu/sidebar

- `GET /api/zones`
  - used to group tables by zone

- `GET /api/receipt-config`
  - used for tax and receipt config lookup during settlement/printing flows

---

## 5. Real-Time WebSocket Events

The backend uses Socket.io global events.

- `table_updated`
  - fired by table status changes, order cancellation reset, order checkout reset, table settle, and table clear
  - payload includes:
    - `id`
    - `table_number`
    - `status`
    - `current_order_started_at`

- `order_created`
  - fired when a table is auto-synced into a new order
  - also fired by manual `POST /api/orders/sync-from-table/:tableId`

- `order_updated`
  - fired on order status updates
  - payload includes:
    - `orderId`
    - `status`
    - `previousStatus`
    - `tableId`
    - `tableStatus`

- `order_items_updated`
  - fired when `PATCH /api/orders/:orderId/items` replaces order items

- `order_completed`
  - fired by `POST /api/orders/:orderId/checkout`
  - also fired by `POST /api/tables/:id/settle`

- `waiter_tables_updated`
  - fired when table assignment/reset affects waiter active table counts

---

## 6. History and Payment Effects By Action

### When table status changes

- `PATCH /api/tables/:id/status`
  - updates `restaurant_tables`
  - may create order
  - may change active order status
  - does not create invoice
  - does not create billing history by itself

### When order is cancelled

- `PATCH /api/orders/:orderId/status` with `cancelled`
  - order becomes terminal
  - `order_status_log` gets a new history row
  - table resets to `Blank`
  - cart and cart items are deleted
  - no invoice is created
  - order becomes visible in `GET /api/orders/history`

### When order is checked out

- `POST /api/orders/:orderId/checkout`
  - order becomes `completed`
  - `order_status_log` gets a new history row
  - `billing_records` gets a bill entry
  - `invoices` gets payment history
  - table resets to `Blank`
  - cart and cart items are deleted
  - order becomes visible in `GET /api/orders/history`

### When table is settled directly

- `POST /api/tables/:id/settle`
  - `orders.status` becomes `completed`
  - `order_status_log` gets a new history row
  - `invoices` gets payment history
  - `billing_records` gets a bill entry unless `save_bill = false`
  - accounting/expenses are updated
  - table resets to `Blank` or split table is deleted
  - cart and cart items are deleted for normal tables
  - emits `order_completed`
  - emits `table_updated`

### Important current sync boundary

- `POST /api/tables/:id/orders/items`
- `PATCH /api/tables/:id/orders/items/:cart_item_id`
- `DELETE /api/tables/:id/orders/items/:cart_item_id`
- `PATCH /api/tables/:id/orders/discount`
  - now update the live table cart and also refresh the active order snapshot when one exists

Remaining boundary:
- `PATCH /api/orders/:orderId/items` still updates only the order snapshot and does not push changes back into `table_cart_items`

---

## 7. Recommended Frontend Usage Flow

### Tables page

- load:
  - `GET /api/tables`
  - `GET /api/zones`
  - `GET /api/items/public/menu`
  - `GET /api/receipt-config`
- for table cart:
  - `GET /api/tables/:id/orders`
- for live updates:
  - subscribe to `table_updated`, `order_created`, `order_updated`, `order_completed`

### Orders page

- load:
  - `GET /api/orders/active`
  - `GET /api/orders/stats/summary`
- for history tab/report:
  - `GET /api/orders/history`
  - `GET /api/orders/history/export`
- for live updates:
  - subscribe to `order_created`, `order_updated`, `order_items_updated`, `order_completed`, `table_updated`
- polling fallback:
  - `GET /api/orders/:orderId/live`

---

## 8. Final API List

### Tables

- `GET /api/tables`
- `POST /api/tables`
- `PATCH /api/tables/:id/status`
- `PUT /api/tables/:id/metadata`
- `POST /api/tables/:id/split`
- `GET /api/tables/:id/orders`
- `POST /api/tables/:id/orders/items`
- `PATCH /api/tables/:id/orders/items/:cart_item_id`
- `DELETE /api/tables/:id/orders/items/:cart_item_id`
- `PATCH /api/tables/:id/orders/discount`
- `POST /api/tables/:id/settle`
- `POST /api/tables/:id/clear`

### Orders

- `GET /api/orders/stats/summary`
- `GET /api/orders/active`
- `GET /api/orders/history`
- `GET /api/orders/history/export`
- `POST /api/orders/sync-from-table/:tableId`
- `GET /api/orders/:orderId`
- `GET /api/orders/:orderId/live`
- `PATCH /api/orders/:orderId/status`
- `PATCH /api/orders/:orderId/items`
- `POST /api/orders/:orderId/checkout`

### Supporting

- `GET /api/items/public/menu`
- `GET /api/zones`
- `GET /api/receipt-config`
