# Kitchen Display System (KDS) API Reference

This document outlines the endpoints available for the Kitchen Display System (KDS) integration within the Sweet Heart Hotel POS.

---

## 1. Kitchen API (`/api/kitchen`)
These endpoints are designed for the Kitchen Display Screen and Waiter POS actions.

| Method | Full Endpoint | Description |
| :--- | :--- | :--- |
| **POST** | `/api/kitchen/kot/send` | Create a new KOT. Idempotent via `request_id`. |
| **GET** | `/api/kitchen/live` | Fetch the live queue: returns KOTs with `pending` or `preparing` status. |
| **PATCH** | `/api/kitchen/kot/:id/status` | Advance KOT lifecycle: `pending` -> `preparing` -> `ready` -> `served`. |
| **PATCH** | `/api/kitchen/item/:id/toggle` | Toggle the `is_done` flag for an individual item on a ticket. |
| **POST** | `/api/kitchen/kot/:id/print` | Mark KOT as printed and retrieve a print-formatted JSON payload. |

### Kitchen API Notes
- `POST /api/kitchen/kot/send`
  Body:
  ```json
  {
    "order_id": "ORD-1001",
    "request_id": "3d2c2ef8-6b20-4c9e-9d14-7b8ecac3ef11",
    "items": [
      {
        "id": 12,
        "name": "Paneer Butter Masala",
        "qty": 2,
        "portion": "Full",
        "modifiers": "Less spicy",
        "is_comp": false
      }
    ]
  }
  ```

- `PATCH /api/kitchen/kot/:id/status`
  Body:
  ```json
  {
    "status": "preparing"
  }
  ```

---

## 2. Admin API (`/api/admin/kitchen`)
These endpoints are for administrative monitoring, performance tracking, history, and full operational access. Admin can access both reporting APIs and live KDS action APIs.

| Method | Full Endpoint | Description |
| :--- | :--- | :--- |
| **POST** | `/api/admin/kitchen/kot/send` | Admin access to create/send a new KOT. Same behavior as kitchen/POS API. |
| **GET** | `/api/admin/kitchen/live` | Admin access to the live queue used by POS and Kitchen screens. |
| **PATCH** | `/api/admin/kitchen/kot/:id/status` | Admin access to advance the normal KOT lifecycle. |
| **PATCH** | `/api/admin/kitchen/item/:id/toggle` | Admin access to toggle an individual KOT item `is_done` state. |
| **POST** | `/api/admin/kitchen/kot/:id/print` | Admin access to print or reprint a KOT payload. |
| **GET** | `/api/admin/kitchen/all` | Paginated list of all KOTs across every status: `pending`, `preparing`, `ready`, `served`. |
| **GET** | `/api/admin/kitchen/history` | Paginated list of completed KOTs with calculated `prep_duration_seconds`. |
| **GET** | `/api/admin/kitchen/metrics` | Kitchen performance analytics: average, minimum, maximum prep times, status breakdown, and hourly throughput. |
| **GET** | `/api/admin/kitchen/order/:orderId/kots` | Retrieve all KOTs for a specific order or table session. |
| **GET** | `/api/admin/kitchen/kot/:id` | Fetch full details for a single KOT, including items and timestamps. |
| **PATCH** | `/api/admin/kitchen/kot/:id/force-close` | Admin override to forcibly mark a stuck KOT as `served` and mark pending items done. |

### Admin API Details

#### 2.1 `GET /api/admin/kitchen/live`
Returns the active kitchen queue.

- Includes KOTs with status:
  - `pending`
  - `preparing`

Example response:
```json
{
  "success": true,
  "data": [
    {
      "kot_id": 14,
      "order_id": "ORD-1001",
      "status": "pending",
      "is_printed": 0,
      "created_at": "2026-04-29T10:20:00.000Z",
      "started_at": null,
      "completed_at": null,
      "table_id": 4,
      "table_number": "T4",
      "waiter_id": "W02",
      "waiter_name": "Ramesh",
      "items": [
        {
          "id": 91,
          "kot_id": 14,
          "menu_item_id": 12,
          "name": "Paneer Butter Masala",
          "quantity": 2,
          "portion": "Full",
          "modifiers": "Less spicy",
          "is_done": 0,
          "is_complimentary": 0
        }
      ]
    }
  ],
  "total": 1
}
```

#### 2.2 `GET /api/admin/kitchen/all`
Returns all KOTs for admin with pagination and filters.

Query params:
- `page`: default `1`
- `limit`: default `25`, max `200`
- `status`: `pending` | `preparing` | `ready` | `served`
- `date`: `YYYY-MM-DD`
- `from`: `YYYY-MM-DD`
- `to`: `YYYY-MM-DD`
- `order_id`: order reference

Example:
```http
GET /api/admin/kitchen/all?page=1&limit=25&status=ready
```

#### 2.3 `GET /api/admin/kitchen/history`
Returns completed KOT history for admin review.

Query params:
- `page`: default `1`
- `limit`: default `25`, max `200`
- `status`: `ready` | `served`
- `date`: `YYYY-MM-DD`
- `from`: `YYYY-MM-DD`
- `to`: `YYYY-MM-DD`
- `order_id`: order reference

#### 2.4 `GET /api/admin/kitchen/metrics`
Returns kitchen performance analytics for a given date.

Query params:
- `date`: `YYYY-MM-DD`

Example response fields:
- `total_kots`
- `status_breakdown`
- `completed_count`
- `avg_prep_seconds`
- `min_prep_seconds`
- `max_prep_seconds`
- `avg_wait_seconds`
- `hourly_throughput`

#### 2.5 `GET /api/admin/kitchen/order/:orderId/kots`
Returns all KOTs linked to one order, across all statuses.

#### 2.6 `GET /api/admin/kitchen/kot/:id`
Returns one KOT with:
- KOT header data
- item list
- lifecycle timestamps
- `prep_duration_seconds`
- `wait_seconds`

#### 2.7 `PATCH /api/admin/kitchen/kot/:id/status`
Admin can move KOT status forward using the same rules as kitchen:
- `pending` -> `preparing`
- `preparing` -> `ready`
- `ready` -> `served`

Body:
```json
{
  "status": "ready"
}
```

#### 2.8 `PATCH /api/admin/kitchen/item/:id/toggle`
Toggles one item between done and not done.

#### 2.9 `POST /api/admin/kitchen/kot/:id/print`
Marks the KOT as printed and returns a printer-friendly JSON payload.

#### 2.10 `PATCH /api/admin/kitchen/kot/:id/force-close`
Force closes a stuck KOT.

Body:
```json
{
  "reason": "Chef completed offline"
}
```

#### 2.11 `POST /api/admin/kitchen/kot/send`
Admin can also create/send a new KOT manually using the same payload as:
- `POST /api/kitchen/kot/send`

---

## 3. Real-time Integration (Socket.io)
The KDS system uses a dual-emission strategy to ensure that all screens (POS, Admin, and Kitchen) stay in sync regardless of their connection method.

- **Primary Namespace:** `/kitchen` (Recommended for dedicated Kitchen screens)
- **Fallback Namespace:** Root (`/`) (Common for POS and Admin dashboards)

### Events
Events are emitted to **both** namespaces simultaneously.

| Event Name | Data Payload | Description |
| :--- | :--- | :--- |
| `kot:new` | Full KOT Object | Broadcasted when a new KOT is sent to the kitchen. |
| `kot:status_sync` | `{ kot_id, status, previous_status, updated_at }` | Emitted when a KOT moves between lifecycle stages. |
| `item:status_sync` | `{ item_id, kot_id, is_done }` | Emitted when an individual item's `is_done` status is toggled. |

---

## 4. Authentication
All endpoints (both `/api/kitchen` and `/api/admin/kitchen`) require a valid JWT token in the Authorization header:
`Authorization: Bearer <token>`

The system uses the standard `authenticateJWT` middleware found in the project.

---

## 5. Implementation Status
- [x] Database Schema ([kds_schema.sql](file:///d:/Techies%20Gateway/hotel-billing-be/kds_schema.sql))
- [x] Operational KOT Logic ([kitchen.controller.js](file:///d:/Techies%20Gateway/hotel-billing-be/src/controllers/kitchen.controller.js))
- [x] Admin Analytics & Metrics ([admin.kitchen.controller.js](file:///d:/Techies%20Gateway/hotel-billing-be/src/controllers/admin.kitchen.controller.js))
- [x] Socket.io Dual-Namespace Integration ([server.js](file:///d:/Techies%20Gateway/hotel-billing-be/src/server.js))
- [x] Route Registration ([app.js](file:///d:/Techies%20Gateway/hotel-billing-be/src/app.js))
