{
  "openapi": "3.1.0",
  "info": {
    "title": "AI 旅客平台 PMS 標準化接口",
    "version": "1.0.0",
    "summary": "hag.workorder/v1：AI 判讀處理單位後推送工單給 PMS，PMS 回報處理狀態、同步入住退房。",
    "description": "每家旅館開通時會拿到一把 **PMS API Key**（`hag_<旅館ID>_...`），所有呼叫都帶 `Authorization: Bearer <API Key>`，金鑰決定是哪一家旅館。\n\n**開通即可使用的串接順序**\n1. `GET /api/pms/v1/ping` 確認金鑰有效。\n2. `PUT /api/pms/v1/webhook` 登記 PMS 的接收網址（https），再用 `POST /api/pms/v1/webhook/test` 送一筆簽章測試事件。無法接收 Webhook 的 PMS 改用 `GET /api/pms/v1/workorders` 定時拉取。\n3. 入住／退房時呼叫 `PUT /api/pms/v1/rooms/{room}`，取得這次住宿的旅客連結（可做成 QR）。\n4. 收到工單（Webhook `workorder.created`）後依 `department` 派工，處理後呼叫 `POST /api/pms/v1/workorders/{id}/status` 回報。\n\n**Webhook 簽章**：`X-HAG-Signature: sha256=` + HMAC-SHA256(Webhook 簽章密鑰, `{X-HAG-Timestamp}.{原始 body}`) 的 hex；時間差超過 5 分鐘應拒收。收到即回 2xx，否則平台在 10、20、40、80、160 秒後重送（共 6 次），重送帶同一個 `eventId`。\n\n**個資最小化**：推送內容不含住客姓名，只有房號。\n\n在本頁按 **Authorize** 填入 API Key 後可直接 Try it out。正式資料請小心；測試請用示範館（demo）的金鑰。"
  },
  "tags": [
    { "name": "連線", "description": "確認金鑰、登記與測試 Webhook" },
    { "name": "工單", "description": "拉取工單、回報處理狀態（接單／完成／退回轉派）" },
    { "name": "房間", "description": "入住／退房同步；新入住會讓上一位旅客的 QR 失效" }
  ],
  "security": [{ "bearerAuth": [] }],
  "paths": {
    "/api/pms/v1/ping": {
      "get": {
        "tags": ["連線"], "summary": "確認 API Key 與旅館", "operationId": "ping",
        "responses": {
          "200": { "description": "金鑰有效", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Ping" } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" }, "403": { "$ref": "#/components/responses/Suspended" }
        }
      }
    },
    "/api/pms/v1/webhook": {
      "put": {
        "tags": ["連線"], "summary": "登記 Webhook 接收網址", "operationId": "setWebhook",
        "description": "填入 https 網址後平台改為推送模式；傳空字串則改回只記錄（PMS 用拉取模式）。",
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "url": { "type": "string", "examples": ["https://pms.example.com/hag/webhook"] } }, "required": ["url"] } } } },
        "responses": {
          "200": { "description": "已更新", "content": { "application/json": { "schema": { "type": "object", "properties": { "mode": { "enum": ["webhook", "mock"] }, "url": { "type": ["string", "null"] } } } } } },
          "400": { "$ref": "#/components/responses/BadRequest" }, "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      }
    },
    "/api/pms/v1/webhook/test": {
      "post": {
        "tags": ["連線"], "summary": "送一筆簽章 ping 事件到已登記的網址", "operationId": "testWebhook",
        "description": "立即送出一次（不排入重送），回傳 PMS 端的 HTTP 狀態與耗時，用來驗證接收端與驗章程式。",
        "responses": {
          "200": { "description": "測試結果（delivered=false 時看 error）", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/TestResult" } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      }
    },
    "/api/pms/v1/workorders": {
      "get": {
        "tags": ["工單"], "summary": "拉取工單（無法接收 Webhook 時）", "operationId": "listWorkorders",
        "description": "建議每 30–60 秒拉一次 `status=new`，處理後用狀態回報 API。最多回傳 200 筆。",
        "parameters": [
          { "name": "status", "in": "query", "schema": { "enum": ["new", "accepted", "done"] } },
          { "name": "department", "in": "query", "schema": { "$ref": "#/components/schemas/Department" } },
          { "name": "since", "in": "query", "description": "只回傳此時間後有建立或狀態變動的工單（ISO 8601）", "schema": { "type": "string", "format": "date-time" } }
        ],
        "responses": {
          "200": { "description": "工單清單", "content": { "application/json": { "schema": { "type": "object", "properties": { "schema": { "const": "hag.workorder/v1" }, "hotel": { "$ref": "#/components/schemas/HotelRef" }, "workorders": { "type": "array", "items": { "$ref": "#/components/schemas/Workorder" } } } } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" }
        }
      }
    },
    "/api/pms/v1/workorders/{id}": {
      "get": {
        "tags": ["工單"], "summary": "查詢單筆工單", "operationId": "getWorkorder",
        "parameters": [{ "$ref": "#/components/parameters/WorkorderId" }],
        "responses": {
          "200": { "description": "工單", "content": { "application/json": { "schema": { "type": "object", "properties": { "schema": { "const": "hag.workorder/v1" }, "workorder": { "$ref": "#/components/schemas/Workorder" } } } } } },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/api/pms/v1/workorders/{id}/status": {
      "post": {
        "tags": ["工單"], "summary": "回報處理狀態", "operationId": "reportStatus",
        "description": "- `accepted`：已接單\n- `done`：完成，平台用旅客的語言通知旅客\n- `rejected`：退回。帶 `department` 時轉派給該單位；沒帶時升級主管重新分派\n\n同一狀態重複回報不會重複通知旅客。",
        "parameters": [{ "$ref": "#/components/parameters/WorkorderId" }],
        "requestBody": { "required": true, "content": { "application/json": {
          "schema": { "$ref": "#/components/schemas/StatusUpdate" },
          "examples": {
            "accepted": { "summary": "接單", "value": { "status": "accepted", "assignee": "房務 阿美" } },
            "done": { "summary": "完成", "value": { "status": "done", "note": "已送達" } },
            "reroute": { "summary": "錯派 → 轉工務", "value": { "status": "rejected", "department": "engineering", "note": "非房務，轉工務" } }
          } } } },
        "responses": {
          "200": { "description": "更新後的工單", "content": { "application/json": { "schema": { "type": "object", "properties": { "schema": { "const": "hag.workorder/v1" }, "workorder": { "$ref": "#/components/schemas/Workorder" } } } } } },
          "400": { "$ref": "#/components/responses/BadRequest" }, "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "description": "工單已完成，不能再改成其他狀態", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
        }
      }
    },
    "/api/pms/v1/rooms": {
      "get": {
        "tags": ["房間"], "summary": "房間與入住狀態", "operationId": "listRooms",
        "responses": { "200": { "description": "房間清單", "content": { "application/json": { "schema": { "type": "object", "properties": { "rooms": { "type": "array", "items": { "$ref": "#/components/schemas/Room" } } } } } } } }
      }
    },
    "/api/pms/v1/rooms/{room}": {
      "put": {
        "tags": ["房間"], "summary": "入住／退房同步", "operationId": "upsertRoom",
        "description": "入住：`active=true` 並帶 `checkin`，回傳這次住宿的旅客連結 `guestUrl`（做成 QR 或簡訊給旅客）。新的入住日期會讓上一位旅客的連結失效。退房：`active=false`，連結立即失效。",
        "parameters": [{ "name": "room", "in": "path", "required": true, "schema": { "type": "string", "pattern": "^[A-Za-z0-9-]{1,10}$" }, "example": "503" }],
        "requestBody": { "required": true, "content": { "application/json": {
          "schema": { "$ref": "#/components/schemas/RoomUpdate" },
          "examples": {
            "checkin": { "summary": "入住", "value": { "active": true, "checkin": "2026-10-17", "checkout": "2026-10-19", "lang": "ja", "guest": "田中様" } },
            "checkout": { "summary": "退房", "value": { "active": false } }
          } } } },
        "responses": {
          "200": { "description": "已更新", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RoomResult" } } } },
          "400": { "$ref": "#/components/responses/BadRequest" }
        }
      }
    }
  },
  "webhooks": {
    "workorder.created": {
      "post": {
        "summary": "新工單（平台 → PMS）", "description": "AI 判讀出處理單位後立即推送。PMS 依 `workorder.department` 派工。",
        "parameters": [{ "$ref": "#/components/parameters/HagEvent" }, { "$ref": "#/components/parameters/HagEventId" }, { "$ref": "#/components/parameters/HagTimestamp" }, { "$ref": "#/components/parameters/HagSignature" }],
        "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
        "responses": { "200": { "description": "收到（任何 2xx）" } }
      }
    },
    "workorder.updated": {
      "post": {
        "summary": "工單更新（平台 → PMS）", "description": "狀態、優先度（超時升級為 high）或處理單位（轉派）改變時推送。PMS 自己回報造成的變更不會再推回（避免迴圈），轉派除外。",
        "parameters": [{ "$ref": "#/components/parameters/HagEvent" }, { "$ref": "#/components/parameters/HagEventId" }, { "$ref": "#/components/parameters/HagTimestamp" }, { "$ref": "#/components/parameters/HagSignature" }],
        "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Envelope" } } } },
        "responses": { "200": { "description": "收到（任何 2xx）" } }
      }
    },
    "ping": {
      "post": {
        "summary": "測試事件（平台 → PMS）", "description": "由 `POST /api/pms/v1/webhook/test` 或旅館後台觸發，沒有 workorder 欄位。",
        "parameters": [{ "$ref": "#/components/parameters/HagEvent" }, { "$ref": "#/components/parameters/HagEventId" }, { "$ref": "#/components/parameters/HagTimestamp" }, { "$ref": "#/components/parameters/HagSignature" }],
        "requestBody": { "content": { "application/json": { "schema": { "type": "object", "properties": { "schema": { "const": "hag.workorder/v1" }, "event": { "const": "ping" }, "eventId": { "type": "string" }, "occurredAt": { "type": "string", "format": "date-time" }, "hotel": { "$ref": "#/components/schemas/HotelRef" } } } } } },
        "responses": { "200": { "description": "收到（任何 2xx）" } }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearerAuth": { "type": "http", "scheme": "bearer", "description": "每家旅館一把 PMS API Key（旅館後台或平台總覽產生，只顯示一次）" }
    },
    "parameters": {
      "WorkorderId": { "name": "id", "in": "path", "required": true, "schema": { "type": "string", "pattern": "^w\\d+$" }, "example": "w1150" },
      "HagEvent": { "name": "X-HAG-Event", "in": "header", "required": true, "schema": { "enum": ["workorder.created", "workorder.updated", "ping"] } },
      "HagEventId": { "name": "X-HAG-Event-Id", "in": "header", "required": true, "description": "同 body.eventId，用來去重", "schema": { "type": "string" } },
      "HagTimestamp": { "name": "X-HAG-Timestamp", "in": "header", "required": true, "description": "Unix 秒數", "schema": { "type": "string" } },
      "HagSignature": { "name": "X-HAG-Signature", "in": "header", "required": true, "description": "sha256=HMAC-SHA256(簽章密鑰, `{timestamp}.{原始 body}`) hex", "schema": { "type": "string" } }
    },
    "responses": {
      "Unauthorized": { "description": "API Key 錯誤", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "Suspended": { "description": "旅館已停用", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "BadRequest": { "description": "欄位錯誤", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } },
      "NotFound": { "description": "找不到", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Error" } } } }
    },
    "schemas": {
      "Error": { "type": "object", "properties": { "error": { "type": "string" } } },
      "Department": { "type": "string", "enum": ["frontdesk", "housekeeping", "engineering"], "description": "frontdesk 櫃檯（叫車、行李、退房、轉真人）· housekeeping 房務（送物、整理房間）· engineering 工務（冷氣、熱水、燈、門鎖、網路…）" },
      "HotelRef": { "type": "object", "properties": { "id": { "type": "string", "example": "demo" }, "name": { "type": "string", "example": "神御示範旅館" } } },
      "Ping": { "type": "object", "properties": { "ok": { "type": "boolean" }, "schema": { "const": "hag.workorder/v1" }, "hotel": { "$ref": "#/components/schemas/HotelRef" }, "webhook": { "type": "object", "properties": { "mode": { "enum": ["webhook", "mock"] }, "url": { "type": ["string", "null"] } } }, "serverTime": { "type": "string", "format": "date-time" } } },
      "TestResult": { "type": "object", "properties": { "delivered": { "type": "boolean" }, "httpStatus": { "type": "integer" }, "ms": { "type": "integer" }, "eventId": { "type": "string" }, "error": { "type": "string" } } },
      "Workorder": {
        "type": "object",
        "properties": {
          "id": { "type": "string", "example": "w1150" },
          "hotelId": { "type": "string", "example": "demo" },
          "room": { "type": "string", "example": "503" },
          "department": { "$ref": "#/components/schemas/Department" },
          "category": { "type": "string", "example": "房務問題" },
          "title": { "type": "string", "example": "報修：冷氣異常" },
          "detail": { "type": "string", "description": "旅客原文；語音輸入時為語音轉出的文字稿", "example": "冷氣不冷" },
          "quantity": { "type": ["integer", "null"] },
          "priority": { "enum": ["normal", "high"], "description": "超時未接單或被退回時為 high" },
          "status": { "enum": ["new", "accepted", "done"] },
          "lang": { "enum": ["zh", "en", "ja", "ko"] },
          "channel": { "enum": ["qr", "kiosk", "web", "embed"] },
          "input": { "enum": ["voice", "text"] },
          "conversationId": { "type": "string" },
          "assignee": { "type": ["string", "null"] },
          "createdAt": { "type": "string", "format": "date-time" },
          "acceptedAt": { "type": ["string", "null"], "format": "date-time" },
          "doneAt": { "type": ["string", "null"], "format": "date-time" }
        }
      },
      "Envelope": {
        "type": "object",
        "properties": {
          "schema": { "const": "hag.workorder/v1" },
          "event": { "enum": ["workorder.created", "workorder.updated"] },
          "eventId": { "type": "string", "example": "evt_3f9a1c0d2b7e4a51" },
          "occurredAt": { "type": "string", "format": "date-time" },
          "hotel": { "$ref": "#/components/schemas/HotelRef" },
          "workorder": { "$ref": "#/components/schemas/Workorder" }
        }
      },
      "StatusUpdate": {
        "type": "object", "required": ["status"],
        "properties": {
          "status": { "enum": ["accepted", "done", "rejected"] },
          "assignee": { "type": "string", "maxLength": 40 },
          "note": { "type": "string", "maxLength": 300 },
          "department": { "$ref": "#/components/schemas/Department", "description": "rejected 時指定轉派的單位" }
        }
      },
      "Room": { "type": "object", "properties": { "room": { "type": "string" }, "active": { "type": "boolean" }, "checkin": { "type": ["string", "null"], "format": "date" }, "checkout": { "type": ["string", "null"], "format": "date" }, "lang": { "enum": ["zh", "en", "ja", "ko"] } } },
      "RoomUpdate": {
        "type": "object", "required": ["active"],
        "properties": {
          "active": { "type": "boolean", "description": "true 入住中、false 已退房" },
          "checkin": { "type": "string", "format": "date", "description": "active=true 時必填" },
          "checkout": { "type": "string", "format": "date" },
          "lang": { "enum": ["zh", "en", "ja", "ko"], "description": "旅客頁預設語言" },
          "guest": { "type": "string", "maxLength": 40, "description": "選填，只用於旅客頁問候，不會推送出去" }
        }
      },
      "RoomResult": { "type": "object", "properties": { "room": { "type": "string" }, "active": { "type": "boolean" }, "checkin": { "type": ["string", "null"] }, "checkout": { "type": ["string", "null"] }, "guestUrl": { "type": ["string", "null"], "description": "這次住宿的旅客連結（簽章，退房或下一位入住即失效）" } } }
    }
  }
}
