{
  "openapi": "3.0.3",
  "info": {
    "title": "雲管家 合作夥伴 API（門市設備狀態與控制）",
    "version": "1.4.0",
    "description": "**狀態（2026-11-16 v1.3）**：已上線。v1.3 新增營收對帳：`GET /stores/{storeId}/revenue`、`device.coins_inserted`／`device.cashbox_cleared` 事件、`revenue:read` 權限；\n錢箱歸零指令 `clear_cashbox`（`cashbox:clear` 權限）。\nv1.4（2026-11-24）新增會員：`GET /members?phone=`、`GET /members/{memberId}`、`member.balance_changed` 事件、`member:read` 權限。\n\n讓外部系統查詢「被授權門市」的設備即時狀態與營收、接收事件推播，並對設備下遠端指令。共 14 支 REST 端點（另有免金鑰的規格檔與 MCP）。\n\n## 快速開始（5 分鐘，沙盒）\n1. 拿到測試金鑰 `cmp_test_…` → `GET /ping` 確認金鑰、權限、可存取門市。\n2. `GET /actions` 看所有指令與參數；`GET /stores/sandbox/devices` 看沙盒設備。\n3. 對 `sandbox-m1`：`switch_program`（program_id=quick）→ `add_coins`（coins=10）→ `start`，看指令從 `sent` 走到 `succeeded`。\n   不先投幣就 `start`：設備不會啟動，指令 10 秒後 `expired`（not_confirmed）——這是預期行為。\n4. 用有 `webhook:manage` 的金鑰 `PUT /webhook` 設定接收網址，`POST /webhook/test` 收一筆測試事件並驗簽。\n5. 換正式金鑰 `cmp_live_…`，網址不變。\n\n## 認證與權限\n- 金鑰格式：`Authorization: Bearer cmp_live_<40 字元>`（沙盒為 `cmp_test_`）。\n- 取得方式：業主在雲管家 App「我的 → 管理 → 申請 API 串接金鑰」申請；沙盒金鑰立即可用，正式金鑰經雲管家審核後發給申請人。\n  平常金鑰以隱碼顯示，申請人要用 App 密碼或 LINE 授權重新驗證才能查看全碼（每次查看都留紀錄）。\n- 計費：免費只限業主自營的單店應用；第三方代管或多店平台屬商用，另收月租費。\n- 金鑰綁定「可存取的門市清單」與「權限範圍（scope）」；URL 帶的門市／設備不在清單內一律 `404 not_found`（不透露存在與否）。\n- scope（全功能不代表每把金鑰都給全部權限，依廠商需要勾選）：\n  - `status:read`：查門市、設備狀態、事件、指令結果、webhook 設定\n  - `machine:control`：啟動／停止／暫停／切洗程／切溫度／跳步／故障復位／暫停營業\n  - `coin:remote`：遠端投幣（等同金額，另外授權）\n  - `webhook:manage`：設定／刪除 webhook、輪替簽章密鑰、送測試事件\n  - `revenue:read`：營收對帳（現金投幣、線上付款、遠端投幣、錢箱清零）。營收資料另外授權，不含在 `status:read` 裡\n  - `cashbox:clear`：錢箱歸零（`clear_cashbox` 指令）。會改業主的帳，另外授權\n  - `member:read`：用手機查會員儲值餘額、收餘額變動推播。個資，另外授權\n- 金鑰可隨時撤銷（`401 key_revoked`）、可設到期時間（`401 key_expired`）、可綁來源 IP 白名單（單一 IP 或 CIDR，例 `203.0.113.0/24`；不在名單內 `403 ip_not_allowed`）。\n- 收費方案預留：金鑰帶方案名稱與額度設定、每天記錄請求數與指令數（`GET /ping` 的 `plan`／`usage`）。目前只記錄、不限制。\n\n## 機型能力（哪台能做什麼）\n- 每台設備的 `capabilities` 就是它現在能下的指令（已扣掉金鑰沒有的 scope）；不在清單內一律 `422 action_not_supported`。\n- 只開放現場確認過的組合；尚未確認的不出現在 `capabilities`，現場驗收通過後才陸續開放。不支援遠端啟動的機型沒有 `start`，也不會把 `start` 轉成投幣。\n- `start` 只送啟動：照設備面板**目前選定的洗程**啟動，不投幣、不補差額、不切洗程。要換洗程先 `switch_program`，要投幣用 `add_coins`。\n\n## 沙盒\n- 同一個網址，用 `cmp_test_` 金鑰即進沙盒：只能看到模擬門市 `sandbox` 的三台模擬設備，指令不會碰任何實體機台（也跟雲管家內部的 s0 實體測試機無關）；每把測試金鑰各自一份狀態。\n  - `sandbox-m1` 模擬洗脫烘：全部指令；`start` 要已投金額 ≥ 選定洗程價格才會啟動\n  - `sandbox-m2` 模擬觸控純烘：只能 `add_coins`（示範「不支援遠端啟動」的機型）\n  - `sandbox-c1` 模擬投幣洗車：`add_coins` 後依枚數計時運轉\n- 時序加速 60 倍：`start` 後 5 秒變 `running`、70 分鐘的洗程 70 秒跑完，結束變 `idle` 並發 `device.cycle_completed`。\n- 沙盒等確認的期限是 10 秒（正式 120 秒），方便測逾時處理。\n- 想測失敗路徑：`params.simulate` 帶 `offline`／`fault`／`timeout`，分別回 `409 device_offline`、指令 `failed`、指令停在 `accepted` 後 `expired`。正式金鑰帶這個欄位回 `422 invalid_params`。\n\n## 限流\n| 範圍 | 上限 | 超過時 |\n|---|---|---|\n| 每把金鑰全部請求 | 120 次／分 | `429 rate_limited` |\n| 每把金鑰下指令 | 20 次／分 | `429 rate_limited` |\n| 每個來源 IP | 300 次／分 | `429 rate_limited` |\n\n每個回應都帶 `X-RateLimit-Limit`、`X-RateLimit-Remaining`、`X-RateLimit-Reset`（秒）；429 一定帶 `Retry-After`（秒）。\n狀態建議改用 webhook 或 `GET /stores/{storeId}/events` 增量拉取；全量輪詢 `devices` 間隔請 ≥ 10 秒（每家門市快取 10 秒）。\n\n## 下指令的流程（受理 ≠ 送出 ≠ 成功）\n1. `POST /devices/{deviceId}/commands`，**必須**帶 `Idempotency-Key`（UUID）。回 `202` 與指令物件。\n2. 追結果：收 `command.updated` webhook，或輪詢 `GET /commands/{commandId}`，直到終態。\n\n| status | 意思 | 終態？ |\n|---|---|---|\n| `accepted` | 雲端已受理。設備離線或即時通道不通時會**排進佇列**，`expires_at` 是排隊期限（300 秒） | 否 |\n| `sent` | 已送到設備端（閘道已收到），還不代表設備已執行 | 可確認的指令：否；不可確認的：停在這 |\n| `succeeded` | **設備確認成功**。`confirmed_by` 說明依據：`device_state`（閘道回報的設備狀態符合預期）或 `gateway_ack`（閘道回報設備已執行寫入） | 是 |\n| `failed` | 設備或雲端拒絕執行，原因在 `error` | 是 |\n| `expired` | 期限內沒有設備回報（`not_confirmed`），或排隊超過 300 秒沒被設備取走（`queue_expired`） | 是 |\n\n- 沒有設備回報，就不會是 `succeeded`。`confirmable: false` 的指令（例如透過即時通道送出的投幣、切洗程、跳步、投幣盒子類）設備不會回報，最多到 `sent`，請以設備狀態為準。\n- `start` 確認方式：送出後 120 秒內，閘道回報該設備 `running`（且回報時間晚於下指令時間）才算成功。餘額不足、門沒關等不符合啟動條件時設備不會啟動 → `expired`（not_confirmed），**不會自動補幣**。\n- **排隊有效期**：排進佇列的指令 300 秒內沒被設備取走就作廢（`expired`／queue_expired），設備之後重新連線也**不會補執行**。\n- 設備離線時只接受 `stop`／`pause`／`pause_business`／`resume_business`（排隊，同上有效期）與 `clear_cashbox`（只記帳，立即完成），其餘回 `409 device_offline`。\n- **逾時或沒收到回應**：用**同一把** Idempotency-Key 查 `GET /commands?idempotency_key=…`，或原樣重送 POST（回原結果，不會再執行一次）。\n  **不可以換新 key 重送**——那會被當成第二道指令，可能投兩次幣。同 key 但內容不同回 `409 idempotency_conflict`。\n- 每道指令都寫進雲管家的操作紀錄（業主在 App「遠端操作紀錄」看得到是哪家廠商、帶什麼 `reference`）。\n\n## 事件推播（webhook）\n- 需要 `webhook:manage`：`PUT /webhook` 設定接收網址（必須 https、不可指向內網）與要訂的事件；回應附簽章密鑰 `whsec_…`，只顯示一次。`rotate_secret: true` 換新密鑰，舊的再保留 24 小時。\n- 雲管家送 `POST`，`Content-Type: application/json`，body 為 `WebhookEvent`。\n- **驗簽**：標頭 `X-CM-Signature: t=<unix 秒>,v1=<hex>`，`v1 = HMAC-SHA256(whsec, \"<t>.<原始 body>\")`（輪替期間會有兩個 v1，任一個對就算）。\n  請用原始 body 計算、比對用 constant-time，並拒絕 `t` 與現在差超過 300 秒的請求（防重放）。\n- 5 秒內回任何 `2xx` 視為收到；其他狀態或逾時會重送：1 分、5 分、30 分、2 小時、6 小時、24 小時，共 6 次。\n  連續 24 小時全失敗自動停用該 webhook 並通知雲管家。\n- 同一事件重送時 `event_id` 不變，請用它去重；事件不保證順序，請以 `occurred_at` 與設備 `state` 為準。\n- 漏收的事件可用 `GET /stores/{storeId}/events?cursor=…` 補拉（保留 7 天）。\n- 設備事件（`device.*`）反映的是店況頁看到的狀態；判斷「指令有沒有成功」請看指令的 `status`，不要只看設備事件。\n\n## 營收對帳（需要 `revenue:read`）\n- `GET /stores/{storeId}/revenue?from=&to=`：每台設備分三類——\n  `cash` 現金投幣（客人在現場投）、`online` 線上付款（LINE Pay、街口、會員錢包等）、`remote` 遠端投幣（App 或 API 下的投幣，附是誰按的）。\n  口徑與雲管家 App 營收報表相同；`revenue.amount`＝現金＋線上（遠端投幣沒有收錢，不算營收）。日期一律台北日期，一次最多 31 天，`granularity=day` 附每日明細。\n- 對帳以查詢結果為準；webhook 是即時通知：\n  - `device.coins_inserted`：`data.source` 為 `cash`／`online`／`remote`。remote、online 一筆操作或訂單一個事件；cash 約每分鐘彙整一次，送「這段時間新增的枚數」與「今天累計」，事件加總等於查詢結果。\n  - `device.cashbox_cleared`：業主在 App 把錢箱清零（收錢）時送出；閘道機台附清出的現金枚數。\n- 遠端投幣的 `actor.type`：`owner` 業主、`staff` 共管者、`cloudmonster` 雲管家、`partner` 合作夥伴（附 `key_prefix`，可認出是不是自己的金鑰下的）、`other`。不回個人姓名。\n- 好洗（KH）機台：遠端投幣寫的是機台設定值、不會進機台投幣累計，所以現金＝機台累計的增加量，不必再扣遠端投幣。\n- 兌幣機不列入（它的出幣是吐給客人的零錢，不是收入）。\n\n## 會員（需要 `member:read`）\n- `GET /members?phone=0912345678`：用手機號碼查一位會員。沒有列出全部會員的功能。\n- 回會員編號 `member_id`（`mem_` 開頭，同一位會員固定不變，可以存起來之後用 `GET /members/{memberId}` 查）、遮罩手機、儲值餘額；不回姓名與完整手機。\n- 錢包是「每個店家群組各一份」：`balances[]` 每筆附 `store_ids`（你的金鑰授權、屬於同一個群組的門市）。只回授權範圍內的錢包；這位會員在授權範圍內沒有錢包就查不到。\n- `member.balance_changed`：餘額一有變動就推（儲值、消費、退款、贈點、轉贈、業主手動調整），附 `previous_balance`、`balance`、`delta`、`reason`。\n  推播來自資料庫層的變動紀錄，任何管道改到餘額都會送；`reason` 對不到時為 `other`。\n- 沙盒：手機 `0900000001` 查得到一位模擬會員（餘額 500）。\n\n## AI Agent／LLM 整合\n- 機器可讀規格：`GET https://laundry-api.cloudmonster.tw/.well-known/openapi.json`（免金鑰）。\n- 工具定義：`docs/partner-api-v1-agent-tools.json`（Claude Tool Use 格式；OpenAI function calling 把 `input_schema` 改名 `parameters`）。\n- MCP（完整規劃的一部分，不影響 REST 驗收）：`https://laundry-api.cloudmonster.tw/api/partner/mcp`（Streamable HTTP，同一把 Bearer 金鑰），提供\n  `list_stores`、`list_devices`、`get_device`、`send_command`、`get_command` 五個工具；`send_command` 帶 `reference` 時重試不會重複執行。\n\n## 通用規則\n- 時間一律 RFC3339 UTC。金額單位：新台幣元；`coins` 單位：枚（每枚面額見設備 `coin_value`）。\n- 錯誤格式固定：`{ \"code\": \"...\", \"message\": \"...\", \"request_id\": \"...\" }`。回報問題請附 `request_id`（回應標頭 `X-Request-Id` 也有）。\n- 5xx：照 2／5／10／30 秒退避重試；POST 重試請沿用同一個 `Idempotency-Key`。\n- 欄位只增不減；新增欄位不另行通知，請忽略不認得的欄位與不認得的 `state`／`action` 值。\n"
  },
  "servers": [
    {
      "url": "https://laundry-api.cloudmonster.tw/api/partner/v1"
    }
  ],
  "security": [
    {
      "partnerKey": []
    }
  ],
  "tags": [
    {
      "name": "自我描述",
      "description": "確認金鑰與查詢可用指令"
    },
    {
      "name": "門市",
      "description": "這把金鑰被授權的門市"
    },
    {
      "name": "設備",
      "description": "洗衣機、烘乾機、投幣盒子等設備的即時狀態"
    },
    {
      "name": "指令",
      "description": "對設備下遠端指令並追蹤結果"
    },
    {
      "name": "營收",
      "description": "現金投幣、線上付款、遠端投幣對帳（revenue:read）"
    },
    {
      "name": "會員",
      "description": "會員儲值餘額（member:read）"
    },
    {
      "name": "事件",
      "description": "設備狀態變化的增量紀錄與 webhook 設定"
    }
  ],
  "paths": {
    "/ping": {
      "get": {
        "tags": [
          "自我描述"
        ],
        "summary": "確認金鑰有效，回傳金鑰資訊與目前限流額度",
        "operationId": "ping",
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/PingResponse"
                },
                "example": {
                  "ok": true,
                  "environment": "live",
                  "partner_name": "範例科技",
                  "key_prefix": "cmp_live_8f2c",
                  "scopes": [
                    "status:read",
                    "machine:control"
                  ],
                  "store_ids": [
                    "s3",
                    "s5"
                  ],
                  "expires_at": null,
                  "plan": {
                    "name": "standard",
                    "limits": {}
                  },
                  "usage": {
                    "today": {
                      "requests": 812,
                      "commands": 37
                    },
                    "month": {
                      "requests": 15230,
                      "commands": 640
                    }
                  },
                  "rate_limit": {
                    "limit": 120,
                    "remaining": 117,
                    "reset_sec": 41
                  },
                  "server_time": "2026-11-08T02:10:00Z"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        }
      }
    },
    "/actions": {
      "get": {
        "tags": [
          "自我描述"
        ],
        "summary": "列出所有指令、參數規格與需要的權限",
        "description": "每台設備實際可用哪些，以設備的 `capabilities` 為準；這支是全部指令的字典。",
        "operationId": "listActions",
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "actions"
                  ],
                  "properties": {
                    "actions": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/ActionSpec"
                      }
                    }
                  }
                },
                "example": {
                  "actions": [
                    {
                      "name": "start",
                      "scope": "machine:control",
                      "description": "只送啟動：照面板目前選定的洗程啟動，不投幣、不補差額、不切洗程",
                      "params": {},
                      "allowed_when_offline": false
                    },
                    {
                      "name": "switch_program",
                      "scope": "machine:control",
                      "description": "切換洗程（不投幣、不啟動）",
                      "params": {
                        "program_id": {
                          "type": "string",
                          "required": true,
                          "source": "devices[].programs[].id"
                        }
                      },
                      "allowed_when_offline": false
                    },
                    {
                      "name": "add_coins",
                      "scope": "coin:remote",
                      "description": "遠端投幣，不帶啟動。設備運轉中投入＝加到這一輪的剩餘時間；設備待機時投入只是存成額度，要再送 start 才會開始（額度留在設備上，下一位按開始的客人就會用到）",
                      "params": {
                        "coins": {
                          "type": "integer",
                          "required": true,
                          "min": 1,
                          "max": 20
                        }
                      },
                      "allowed_when_offline": false
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        }
      }
    },
    "/stores": {
      "get": {
        "tags": [
          "門市"
        ],
        "summary": "列出這把金鑰可存取的門市",
        "operationId": "listStores",
        "x-required-scope": "status:read",
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "stores"
                  ],
                  "properties": {
                    "stores": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/Store"
                      }
                    }
                  }
                },
                "example": {
                  "stores": [
                    {
                      "id": "s3",
                      "name": "為公店",
                      "suspended": false,
                      "device_count": 12
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/stores/{storeId}/devices": {
      "get": {
        "tags": [
          "設備"
        ],
        "summary": "列出門市所有設備與即時狀態",
        "description": "排序與店家 App 一致。停用中的設備 `state=maintenance`。\n狀態與客人在 LINE 店況頁看到的是同一份來源；每家門市快取 10 秒，比這更密的輪詢拿到的是同一份資料。\n",
        "operationId": "listStoreDevices",
        "x-required-scope": "status:read",
        "parameters": [
          {
            "$ref": "#/components/parameters/StoreId"
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "store_id",
                    "generated_at",
                    "devices"
                  ],
                  "properties": {
                    "store_id": {
                      "type": "string"
                    },
                    "generated_at": {
                      "type": "string",
                      "format": "date-time"
                    },
                    "devices": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/Device"
                      }
                    }
                  }
                },
                "example": {
                  "store_id": "s3",
                  "generated_at": "2026-11-02T09:30:00Z",
                  "devices": [
                    {
                      "id": "s3-m1",
                      "store_id": "s3",
                      "name": "洗脫烘 1",
                      "kind": "washer_dryer",
                      "size": "20kg",
                      "state": "running",
                      "connected": true,
                      "remain_sec": 1820,
                      "fault": false,
                      "door": "closed",
                      "program": {
                        "id": 2,
                        "name": "標準洗＋中溫烘"
                      },
                      "progress": 41,
                      "current_step": "洗滌",
                      "temperature_c": 38,
                      "last_seen": "2026-11-02T09:29:51Z",
                      "programs": [
                        {
                          "id": "1",
                          "name": "快洗",
                          "price": 60,
                          "minutes": 30
                        },
                        {
                          "id": "2",
                          "name": "標準洗＋中溫烘",
                          "price": 140,
                          "minutes": 70
                        }
                      ],
                      "capabilities": [
                        "stop",
                        "pause",
                        "fault_reset",
                        "skip_step",
                        "add_coins"
                      ]
                    },
                    {
                      "id": "s3-c1",
                      "store_id": "s3",
                      "name": "烘乾機 8",
                      "kind": "dryer",
                      "size": null,
                      "state": "idle",
                      "connected": true,
                      "remain_sec": 0,
                      "fault": false,
                      "door": null,
                      "program": null,
                      "progress": null,
                      "current_step": null,
                      "temperature_c": null,
                      "last_seen": "2026-11-02T09:29:40Z",
                      "coin_value": 10,
                      "seconds_per_coin": 360,
                      "programs": [],
                      "capabilities": [
                        "add_coins"
                      ]
                    }
                  ]
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/devices/{deviceId}": {
      "get": {
        "tags": [
          "設備"
        ],
        "summary": "查單一設備即時狀態",
        "description": "舊編號（例如換成盒子前的機台編號）會自動對應到目前的設備，回應的 `id` 是目前編號。",
        "operationId": "getDevice",
        "x-required-scope": "status:read",
        "parameters": [
          {
            "$ref": "#/components/parameters/DeviceId"
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Device"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/devices/{deviceId}/commands": {
      "post": {
        "tags": [
          "指令"
        ],
        "summary": "對設備下遠端指令",
        "description": "可用的 `action` 以該設備 `capabilities` 為準，不在清單內回 `422 action_not_supported`。\n帶了該 action 不接受的參數一律 `422 invalid_params`（例如 `start` 帶 `program_id`）。\n\n| action | 需要的 scope | params | 怎麼確認成功 |\n|---|---|---|---|\n| `start` | machine:control | 無（照面板目前選定的洗程；不投幣、不補差額） | 閘道回報 running |\n| `stop` | machine:control | — | 閘道回報不在 running |\n| `pause` | machine:control | — | 閘道回報不在 running |\n| `fault_reset` | machine:control | — | 排隊時看閘道 ack，否則停在 sent |\n| `switch_program` | machine:control | `program_id`（取自 `programs[].id`） | 同上 |\n| `switch_temp` | machine:control | `level`：`low`／`medium`／`high` | 同上 |\n| `skip_step` | machine:control | — | 同上 |\n| `pause_business` | machine:control | — （設備不接受客人投幣／付款） | 同上 |\n| `resume_business` | machine:control | — | 同上 |\n| `add_coins` | coin:remote | `coins`：1–20（運轉中＝加時；待機＝存額度，要再 `start`） | 同上（投幣盒子類停在 sent） |\n| `clear_cashbox` | cashbox:clear | —（錢箱歸零：只記帳、不對機器下指令，離線也可以） | 立即 `succeeded`（`confirmed_by: cloud`），`result` 附清出的現金枚數與金額 |\n",
        "operationId": "createCommand",
        "x-required-scope": "machine:control 或 coin:remote（依 action）",
        "parameters": [
          {
            "$ref": "#/components/parameters/DeviceId"
          },
          {
            "name": "Idempotency-Key",
            "in": "header",
            "required": true,
            "description": "每個「意圖」一把 UUID；重試請沿用同一把。",
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CommandRequest"
              },
              "examples": {
                "start": {
                  "summary": "照面板目前選定的洗程啟動（不投幣）",
                  "value": {
                    "action": "start",
                    "reference": "ORD-20261108-0042"
                  }
                },
                "switchProgram": {
                  "summary": "先切洗程",
                  "value": {
                    "action": "switch_program",
                    "params": {
                      "program_id": "2"
                    }
                  }
                },
                "addCoins": {
                  "summary": "遠端投 3 枚",
                  "value": {
                    "action": "add_coins",
                    "params": {
                      "coins": 3
                    },
                    "reference": "ORD-20261102-0043"
                  }
                },
                "stop": {
                  "summary": "停止",
                  "value": {
                    "action": "stop"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "202": {
            "description": "已受理，請輪詢指令狀態",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Command"
                },
                "example": {
                  "command_id": "cmd_01JBX7Q2M4V8K3N6P9R2T5W8Y1",
                  "device_id": "s3-m1",
                  "action": "start",
                  "params": {},
                  "reference": "ORD-20261108-0042",
                  "status": "sent",
                  "confirmable": true,
                  "confirmed_by": null,
                  "error": null,
                  "expires_at": "2026-11-08T09:33:00Z",
                  "created_at": "2026-11-08T09:31:00Z",
                  "updated_at": "2026-11-08T09:31:00Z"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "description": "設備狀態不允許：`device_offline`（離線）、`device_busy`（運轉中不能 start）、\n`device_maintenance`（停用中）、`store_suspended`（門市暫停營業）、\n`idempotency_conflict`（同一把 Idempotency-Key 但內容不同）\n",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "code": "device_offline",
                  "message": "設備離線，僅接受 stop/pause",
                  "request_id": "req_8f2c1a"
                }
              }
            }
          },
          "422": {
            "description": "`action_not_supported`／`invalid_params`",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/commands/{commandId}": {
      "get": {
        "tags": [
          "指令"
        ],
        "summary": "查指令執行結果",
        "operationId": "getCommand",
        "x-required-scope": "status:read",
        "parameters": [
          {
            "name": "commandId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Command"
                },
                "example": {
                  "command_id": "cmd_01JBX7Q2M4V8K3N6P9R2T5W8Y1",
                  "device_id": "s3-m1",
                  "action": "start",
                  "params": {},
                  "reference": "ORD-20261108-0042",
                  "status": "succeeded",
                  "confirmable": true,
                  "confirmed_by": "device_state",
                  "error": null,
                  "expires_at": null,
                  "created_at": "2026-11-08T09:31:00Z",
                  "updated_at": "2026-11-08T09:31:12Z"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/commands": {
      "get": {
        "tags": [
          "指令"
        ],
        "summary": "用 Idempotency-Key 查指令（POST 沒收到回應時用）",
        "description": "查不到＝雲端沒收到那次 POST，可以用**同一把 key** 安全重送。",
        "operationId": "findCommandByIdempotencyKey",
        "parameters": [
          {
            "name": "idempotency_key",
            "in": "query",
            "required": true,
            "schema": {
              "type": "string",
              "format": "uuid"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "找到",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Command"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/stores/{storeId}/revenue": {
      "get": {
        "tags": [
          "營收"
        ],
        "summary": "門市營收對帳（現金投幣／線上付款／遠端投幣三類）",
        "description": "日期為台北日期（`Asia/Taipei`），`from`、`to` 皆含，一次最多 31 天，不可晚於今天；今天的數字是到目前為止。\n`granularity=day` 會在每台設備附 `days[]` 每日明細（範圍越長越慢，31 天約數秒）。口徑與雲管家 App 營收報表一致。\n",
        "operationId": "getStoreRevenue",
        "x-required-scope": "revenue:read",
        "parameters": [
          {
            "$ref": "#/components/parameters/StoreId"
          },
          {
            "name": "from",
            "in": "query",
            "required": false,
            "description": "起日（預設今天）",
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2026-11-01"
            }
          },
          {
            "name": "to",
            "in": "query",
            "required": false,
            "description": "迄日（預設同 from）",
            "schema": {
              "type": "string",
              "format": "date",
              "example": "2026-11-15"
            }
          },
          {
            "name": "granularity",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "total",
                "day"
              ],
              "default": "total"
            }
          },
          {
            "name": "device_id",
            "in": "query",
            "required": false,
            "description": "只看一台",
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/StoreRevenue"
                },
                "example": {
                  "store_id": "s17",
                  "from": "2026-11-15",
                  "to": "2026-11-15",
                  "timezone": "Asia/Taipei",
                  "currency": "TWD",
                  "granularity": "total",
                  "generated_at": "2026-11-16T02:30:00Z",
                  "devices": [
                    {
                      "device_id": "s17-c1",
                      "name": "烘乾機 1",
                      "cash": {
                        "coins": 42,
                        "amount": 420
                      },
                      "online": {
                        "orders": 3,
                        "amount": 180
                      },
                      "remote": {
                        "coins": 6,
                        "amount": 60,
                        "operations": 2,
                        "by_actor": [
                          {
                            "type": "owner",
                            "coins": 2,
                            "amount": 20,
                            "operations": 1
                          },
                          {
                            "type": "partner",
                            "key_prefix": "cmp_live_8f2c",
                            "coins": 4,
                            "amount": 40,
                            "operations": 1
                          }
                        ]
                      },
                      "revenue": {
                        "amount": 600
                      }
                    }
                  ],
                  "totals": {
                    "cash": {
                      "coins": 42,
                      "amount": 420
                    },
                    "online": {
                      "orders": 3,
                      "amount": 180
                    },
                    "remote": {
                      "coins": 6,
                      "amount": 60,
                      "operations": 2
                    },
                    "revenue": {
                      "amount": 600
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "`invalid_params`：日期格式錯、from 晚於 to、晚於今天、超過 31 天",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/members": {
      "get": {
        "tags": [
          "會員"
        ],
        "summary": "用手機號碼查會員儲值餘額",
        "description": "只回這一位；沒有列出全部會員的功能。只回金鑰授權門市所屬群組的錢包，範圍內沒有錢包就回空陣列。",
        "operationId": "findMemberByPhone",
        "x-required-scope": "member:read",
        "parameters": [
          {
            "name": "phone",
            "in": "query",
            "required": true,
            "description": "09 開頭 10 碼手機號碼",
            "schema": {
              "type": "string",
              "example": "0912345678"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK（查無＝空陣列）",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "members"
                  ],
                  "properties": {
                    "members": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/Member"
                      }
                    }
                  }
                },
                "example": {
                  "members": [
                    {
                      "member_id": "mem_3f9a1c0b7d2e4f6a8b1c",
                      "phone_masked": "0912***678",
                      "balances": [
                        {
                          "store_ids": [
                            "s17"
                          ],
                          "balance": 350
                        }
                      ],
                      "total_balance": 350,
                      "currency": "TWD"
                    }
                  ]
                }
              }
            }
          },
          "400": {
            "description": "`invalid_params`：沒帶 phone 或格式錯",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/members/{memberId}": {
      "get": {
        "tags": [
          "會員"
        ],
        "summary": "用會員編號查儲值餘額",
        "operationId": "getMember",
        "x-required-scope": "member:read",
        "parameters": [
          {
            "name": "memberId",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "example": "mem_3f9a1c0b7d2e4f6a8b1c"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Member"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/stores/{storeId}/events": {
      "get": {
        "tags": [
          "事件"
        ],
        "summary": "增量拉取門市的設備事件（webhook 的備援）",
        "description": "第一次不帶 `cursor` 從 7 天前開始；之後帶上一次回應的 `next_cursor`。`has_more=true` 請立刻再拉，否則間隔 ≥ 10 秒。\n事件內容與 webhook 送出的完全相同。\n",
        "operationId": "listStoreEvents",
        "parameters": [
          {
            "$ref": "#/components/parameters/StoreId"
          },
          {
            "name": "cursor",
            "in": "query",
            "required": false,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "limit",
            "in": "query",
            "required": false,
            "schema": {
              "type": "integer",
              "minimum": 1,
              "maximum": 100,
              "default": 50
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "events",
                    "next_cursor",
                    "has_more"
                  ],
                  "properties": {
                    "events": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/WebhookEvent"
                      }
                    },
                    "next_cursor": {
                      "type": "string"
                    },
                    "has_more": {
                      "type": "boolean"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "`invalid_cursor`：cursor 錯誤或超過 7 天",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/webhook": {
      "get": {
        "tags": [
          "事件"
        ],
        "summary": "查目前的 webhook 設定與最近送達狀況",
        "x-required-scope": "status:read",
        "operationId": "getWebhook",
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookConfig"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        }
      },
      "put": {
        "tags": [
          "事件"
        ],
        "summary": "設定或更新 webhook 接收網址與訂閱事件",
        "x-required-scope": "webhook:manage",
        "description": "第一次設定，或帶 `rotate_secret` 為 true 時，回應會附新的 `secret`（只顯示這一次）；舊密鑰再保留 24 小時供切換。",
        "operationId": "putWebhook",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "url",
                  "events"
                ],
                "properties": {
                  "url": {
                    "type": "string",
                    "format": "uri",
                    "description": "必須 https"
                  },
                  "events": {
                    "type": "array",
                    "items": {
                      "$ref": "#/components/schemas/EventType"
                    }
                  },
                  "enabled": {
                    "type": "boolean",
                    "default": true
                  },
                  "rotate_secret": {
                    "type": "boolean",
                    "default": false
                  }
                }
              },
              "example": {
                "url": "https://partner.example.com/hooks/cloudmonster",
                "events": [
                  "device.cycle_completed",
                  "device.fault",
                  "device.offline",
                  "command.updated"
                ]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "已儲存",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/WebhookConfig"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "422": {
            "description": "`invalid_params`：網址不是 https、或指向私有網段",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "delete": {
        "tags": [
          "事件"
        ],
        "summary": "刪除 webhook（停止推播）",
        "x-required-scope": "webhook:manage",
        "operationId": "deleteWebhook",
        "responses": {
          "204": {
            "description": "已刪除"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          }
        }
      }
    },
    "/webhook/test": {
      "post": {
        "tags": [
          "事件"
        ],
        "summary": "送一筆 `ping` 測試事件到目前設定的網址",
        "x-required-scope": "webhook:manage",
        "description": "回應帶對方伺服器回的 HTTP 狀態與耗時，方便確認驗簽與網路。",
        "operationId": "testWebhook",
        "responses": {
          "200": {
            "description": "已送出",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "delivered": {
                      "type": "boolean"
                    },
                    "response_status": {
                      "type": "integer",
                      "nullable": true
                    },
                    "duration_ms": {
                      "type": "integer"
                    },
                    "event_id": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "409": {
            "description": "`webhook_not_configured`",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    }
  },
  "x-webhooks": {
    "deviceEvent": {
      "post": {
        "summary": "雲管家推給合作夥伴的事件",
        "operationId": "receiveDeviceEvent",
        "description": "驗簽方式見最上方「事件推播」。5 秒內回 2xx。",
        "parameters": [
          {
            "name": "X-CM-Signature",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "example": "t=1762135800,v1=5d41402abc4b2a76b9719d911017c592..."
            }
          },
          {
            "name": "X-CM-Event-Id",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/WebhookEvent"
              },
              "example": {
                "event_id": "evt_01JC2M8Q4V7K3N6P9R2T5W8Y1A",
                "type": "device.cycle_completed",
                "occurred_at": "2026-11-03T03:12:40Z",
                "environment": "live",
                "store_id": "s3",
                "device_id": "s3-m1",
                "data": {
                  "previous_state": "running",
                  "state": "idle",
                  "program": {
                    "id": 2,
                    "name": "標準洗＋中溫烘"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "收到"
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "partnerKey": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "cmp_<40 chars>"
      }
    },
    "parameters": {
      "StoreId": {
        "name": "storeId",
        "in": "path",
        "required": true,
        "description": "門市編號（取自 `GET /stores`）",
        "schema": {
          "type": "string",
          "example": "s3"
        }
      },
      "DeviceId": {
        "name": "deviceId",
        "in": "path",
        "required": true,
        "description": "設備編號（取自設備列表的 `id`）",
        "schema": {
          "type": "string",
          "example": "s3-m1"
        }
      }
    },
    "schemas": {
      "Store": {
        "type": "object",
        "required": [
          "id",
          "name",
          "suspended",
          "device_count"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "name": {
            "type": "string"
          },
          "suspended": {
            "type": "boolean",
            "description": "門市被暫停營業時為 true，此時所有控制指令回 409"
          },
          "device_count": {
            "type": "integer"
          }
        }
      },
      "Device": {
        "type": "object",
        "required": [
          "id",
          "store_id",
          "name",
          "kind",
          "state",
          "connected",
          "remain_sec",
          "fault",
          "last_seen",
          "programs",
          "capabilities"
        ],
        "properties": {
          "id": {
            "type": "string"
          },
          "store_id": {
            "type": "string"
          },
          "name": {
            "type": "string",
            "description": "店家在 App 設定的顯示名稱"
          },
          "kind": {
            "type": "string",
            "enum": [
              "washer",
              "dryer",
              "washer_dryer",
              "car_wash",
              "water_station",
              "other"
            ]
          },
          "size": {
            "type": "string",
            "nullable": true,
            "example": "20kg"
          },
          "state": {
            "type": "string",
            "description": "`idle` 待機可用／`running` 運轉中／`offline` 離線（3 分鐘沒心跳）／\n`maintenance` 店家停用／`unknown` 尚未回報。之後可能新增其他值，不認得請當 `unknown`。\n",
            "enum": [
              "idle",
              "running",
              "offline",
              "maintenance",
              "unknown"
            ]
          },
          "connected": {
            "type": "boolean"
          },
          "remain_sec": {
            "type": "integer",
            "minimum": 0,
            "description": "運轉剩餘秒數，非運轉中為 0"
          },
          "fault": {
            "type": "boolean",
            "description": "設備回報故障"
          },
          "door": {
            "type": "string",
            "nullable": true,
            "enum": [
              "open",
              "closed",
              "locked",
              null
            ],
            "description": "不支援回報門狀態的設備為 null"
          },
          "program": {
            "nullable": true,
            "type": "object",
            "properties": {
              "id": {
                "type": "integer"
              },
              "name": {
                "type": "string"
              }
            }
          },
          "progress": {
            "type": "integer",
            "nullable": true,
            "minimum": 0,
            "maximum": 100
          },
          "current_step": {
            "type": "string",
            "nullable": true
          },
          "temperature_c": {
            "type": "number",
            "nullable": true
          },
          "last_seen": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "coin_value": {
            "type": "integer",
            "nullable": true,
            "description": "每枚面額（元），投幣類設備才有"
          },
          "seconds_per_coin": {
            "type": "integer",
            "nullable": true,
            "description": "每枚可用秒數，計時類設備才有"
          },
          "programs": {
            "type": "array",
            "description": "可選洗程與定價（店家設定）",
            "items": {
              "type": "object",
              "required": [
                "id",
                "name"
              ],
              "properties": {
                "id": {
                  "type": "string"
                },
                "name": {
                  "type": "string"
                },
                "price": {
                  "type": "integer",
                  "nullable": true
                },
                "minutes": {
                  "type": "integer",
                  "nullable": true
                }
              }
            }
          },
          "capabilities": {
            "type": "array",
            "description": "這台設備目前可用的 action（已扣掉金鑰沒有的 scope）",
            "items": {
              "type": "string"
            }
          }
        }
      },
      "CommandRequest": {
        "type": "object",
        "required": [
          "action"
        ],
        "properties": {
          "action": {
            "type": "string",
            "enum": [
              "start",
              "stop",
              "pause",
              "fault_reset",
              "switch_program",
              "switch_temp",
              "skip_step",
              "pause_business",
              "resume_business",
              "add_coins",
              "clear_cashbox"
            ]
          },
          "params": {
            "type": "object",
            "additionalProperties": true,
            "properties": {
              "program_id": {
                "type": "string",
                "description": "switch_program 用，取自設備 programs[].id（start 不接受）"
              },
              "level": {
                "type": "string",
                "enum": [
                  "low",
                  "medium",
                  "high"
                ]
              },
              "coins": {
                "type": "integer",
                "minimum": 1,
                "maximum": 20
              },
              "simulate": {
                "type": "string",
                "enum": [
                  "offline",
                  "fault",
                  "timeout"
                ],
                "description": "只限沙盒金鑰，模擬失敗路徑"
              }
            }
          },
          "reference": {
            "type": "string",
            "maxLength": 64,
            "description": "合作夥伴自己的單號，會寫進雲管家操作紀錄，對帳用"
          }
        }
      },
      "Command": {
        "type": "object",
        "required": [
          "command_id",
          "device_id",
          "action",
          "status",
          "confirmable",
          "created_at",
          "updated_at"
        ],
        "properties": {
          "command_id": {
            "type": "string"
          },
          "device_id": {
            "type": "string"
          },
          "action": {
            "type": "string"
          },
          "params": {
            "type": "object",
            "additionalProperties": true
          },
          "reference": {
            "type": "string",
            "nullable": true
          },
          "status": {
            "type": "string",
            "enum": [
              "accepted",
              "sent",
              "succeeded",
              "failed",
              "expired"
            ],
            "description": "`accepted` 雲端已受理（排隊中時看 expires_at）／`sent` 已送到設備端／`succeeded` 設備確認成功（看 confirmed_by）／\n`failed` 設備或雲端拒絕執行（見 error）／`expired` 期限內沒有設備回報（not_confirmed）或排隊過期（queue_expired）\n"
          },
          "confirmable": {
            "type": "boolean",
            "description": "false＝這道指令設備不會回報結果，狀態最多到 `sent`，請以設備狀態為準"
          },
          "confirmed_by": {
            "type": "string",
            "nullable": true,
            "enum": [
              "device_state",
              "gateway_ack",
              "cloud",
              null
            ],
            "description": "只有 succeeded 才有。`device_state`＝閘道回報的設備狀態符合預期；`gateway_ack`＝閘道回報設備已執行寫入；`cloud`＝只記帳的指令（錢箱歸零）雲端已完成"
          },
          "expires_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true,
            "description": "還沒終態的期限：排隊中＝300 秒內要被設備取走，送出等確認＝120 秒（沙盒 10 秒）。終態後為 null"
          },
          "result": {
            "nullable": true,
            "type": "object",
            "description": "指令的執行結果。目前只有 clear_cashbox 有：清零時間與清出的現金（投幣盒子沒有清出枚數時為 null）",
            "properties": {
              "cleared_at": {
                "type": "string",
                "format": "date-time"
              },
              "cash_coins_collected": {
                "type": "integer",
                "nullable": true
              },
              "cash_amount_collected": {
                "type": "integer",
                "nullable": true
              }
            }
          },
          "error": {
            "nullable": true,
            "type": "object",
            "properties": {
              "code": {
                "type": "string",
                "description": "例：not_confirmed、queue_expired、device_rejected、device_offline、device_fault"
              },
              "message": {
                "type": "string"
              }
            }
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      },
      "PingResponse": {
        "type": "object",
        "required": [
          "ok",
          "environment",
          "partner_name",
          "scopes",
          "store_ids",
          "plan",
          "usage",
          "rate_limit",
          "server_time"
        ],
        "properties": {
          "ok": {
            "type": "boolean"
          },
          "environment": {
            "type": "string",
            "enum": [
              "live",
              "test"
            ]
          },
          "partner_name": {
            "type": "string"
          },
          "key_prefix": {
            "type": "string",
            "description": "金鑰前 13 碼，方便對帳是哪一把"
          },
          "scopes": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "store_ids": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "expires_at": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          },
          "plan": {
            "type": "object",
            "description": "收費方案預留（目前只記錄、不限制）",
            "properties": {
              "name": {
                "type": "string"
              },
              "limits": {
                "type": "object",
                "additionalProperties": true
              }
            }
          },
          "usage": {
            "type": "object",
            "description": "台北時間今天與本月的請求數、指令數",
            "properties": {
              "today": {
                "type": "object",
                "properties": {
                  "requests": {
                    "type": "integer"
                  },
                  "commands": {
                    "type": "integer"
                  }
                }
              },
              "month": {
                "type": "object",
                "properties": {
                  "requests": {
                    "type": "integer"
                  },
                  "commands": {
                    "type": "integer"
                  }
                }
              }
            }
          },
          "rate_limit": {
            "type": "object",
            "properties": {
              "limit": {
                "type": "integer"
              },
              "remaining": {
                "type": "integer"
              },
              "reset_sec": {
                "type": "integer"
              }
            }
          },
          "server_time": {
            "type": "string",
            "format": "date-time",
            "description": "用來校正對方時鐘（驗簽要求 300 秒內）"
          }
        }
      },
      "ActionSpec": {
        "type": "object",
        "required": [
          "name",
          "scope",
          "description",
          "params",
          "allowed_when_offline"
        ],
        "properties": {
          "name": {
            "type": "string"
          },
          "scope": {
            "type": "string"
          },
          "description": {
            "type": "string"
          },
          "params": {
            "type": "object",
            "additionalProperties": {
              "type": "object",
              "properties": {
                "type": {
                  "type": "string"
                },
                "required": {
                  "type": "boolean"
                },
                "min": {
                  "type": "integer"
                },
                "max": {
                  "type": "integer"
                },
                "enum": {
                  "type": "array",
                  "items": {
                    "type": "string"
                  }
                },
                "source": {
                  "type": "string",
                  "description": "值從哪裡取"
                }
              }
            }
          },
          "allowed_when_offline": {
            "type": "boolean"
          }
        }
      },
      "EventType": {
        "type": "string",
        "enum": [
          "device.state_changed",
          "device.cycle_started",
          "device.cycle_completed",
          "device.fault",
          "device.fault_cleared",
          "device.offline",
          "device.online",
          "command.updated",
          "ping",
          "device.coins_inserted",
          "device.cashbox_cleared",
          "member.balance_changed"
        ],
        "description": "`device.state_changed` 所有 state 變化（量最大，通常不需要）／`device.cycle_started` 開始運轉／\n`device.cycle_completed` 運轉結束（洗好、烘好）／`device.fault`、`device.fault_cleared` 故障發生與排除／\n`device.offline`、`device.online` 離線 3 分鐘與恢復／`command.updated` 指令狀態改變／`ping` 測試事件／\n`device.coins_inserted` 有錢進來（現金、線上、遠端，需 revenue:read）／`device.cashbox_cleared` 錢箱清零（需 revenue:read）／\n`member.balance_changed` 會員儲值餘額變動（需 member:read）\n"
      },
      "WebhookEvent": {
        "type": "object",
        "required": [
          "event_id",
          "type",
          "occurred_at",
          "environment",
          "data"
        ],
        "properties": {
          "event_id": {
            "type": "string",
            "description": "重送時不變，用來去重"
          },
          "type": {
            "$ref": "#/components/schemas/EventType"
          },
          "occurred_at": {
            "type": "string",
            "format": "date-time"
          },
          "environment": {
            "type": "string",
            "enum": [
              "live",
              "test"
            ]
          },
          "store_id": {
            "type": "string",
            "nullable": true
          },
          "device_id": {
            "type": "string",
            "nullable": true
          },
          "data": {
            "type": "object",
            "additionalProperties": true,
            "description": "device.* 狀態事件：`{ previous_state, state, remain_sec?, program?, fault_code? }`；\ncommand.updated：完整 `Command` 物件；\ndevice.coins_inserted：`{ source: cash|online|remote, coins, amount, coin_value?, actor?(remote), order_ref?(online), today?(cash：{ date, coins, amount }) }`；\ndevice.cashbox_cleared：`{ cash_coins_collected, cash_amount_collected, actor }`（投幣盒子沒有清出枚數時為 null）；\nmember.balance_changed：`{ member_id, phone_masked, store_ids, previous_balance, balance, delta, reason: topup|bonus|consumption|refund|transfer|adjustment|other, currency }`。\n"
          }
        }
      },
      "Member": {
        "type": "object",
        "required": [
          "member_id",
          "balances",
          "total_balance",
          "currency"
        ],
        "properties": {
          "member_id": {
            "type": "string",
            "description": "mem_ 開頭，同一位會員固定不變"
          },
          "phone_masked": {
            "type": "string",
            "nullable": true,
            "example": "0912***678"
          },
          "balances": {
            "type": "array",
            "description": "每個店家群組一份錢包；store_ids＝這把金鑰授權、屬於該群組的門市",
            "items": {
              "type": "object",
              "properties": {
                "store_ids": {
                  "type": "array",
                  "items": {
                    "type": "string"
                  }
                },
                "balance": {
                  "type": "integer",
                  "description": "儲值餘額（新台幣元）"
                }
              }
            }
          },
          "total_balance": {
            "type": "integer"
          },
          "currency": {
            "type": "string",
            "example": "TWD"
          }
        }
      },
      "MoneyBucket": {
        "type": "object",
        "required": [
          "coins",
          "amount"
        ],
        "properties": {
          "coins": {
            "type": "integer",
            "description": "枚數"
          },
          "amount": {
            "type": "integer",
            "description": "金額（新台幣元）"
          }
        }
      },
      "OnlineBucket": {
        "type": "object",
        "required": [
          "orders",
          "amount"
        ],
        "properties": {
          "orders": {
            "type": "integer",
            "description": "訂單數"
          },
          "amount": {
            "type": "integer",
            "description": "金額（扣掉部分退款）"
          }
        }
      },
      "RemoteActor": {
        "type": "object",
        "required": [
          "type"
        ],
        "properties": {
          "type": {
            "type": "string",
            "enum": [
              "owner",
              "staff",
              "cloudmonster",
              "partner",
              "other"
            ]
          },
          "key_prefix": {
            "type": "string",
            "nullable": true,
            "description": "type＝partner 時的金鑰前綴，用來認出是不是自己下的"
          }
        }
      },
      "RemoteBucket": {
        "type": "object",
        "required": [
          "coins",
          "amount",
          "operations"
        ],
        "properties": {
          "coins": {
            "type": "integer"
          },
          "amount": {
            "type": "integer"
          },
          "operations": {
            "type": "integer",
            "description": "遠端投幣次數"
          },
          "by_actor": {
            "type": "array",
            "items": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/RemoteActor"
                },
                {
                  "type": "object",
                  "properties": {
                    "coins": {
                      "type": "integer"
                    },
                    "amount": {
                      "type": "integer"
                    },
                    "operations": {
                      "type": "integer"
                    }
                  }
                }
              ]
            }
          }
        }
      },
      "RevenueRow": {
        "type": "object",
        "required": [
          "cash",
          "online",
          "remote",
          "revenue"
        ],
        "properties": {
          "cash": {
            "$ref": "#/components/schemas/MoneyBucket"
          },
          "online": {
            "$ref": "#/components/schemas/OnlineBucket"
          },
          "remote": {
            "$ref": "#/components/schemas/RemoteBucket"
          },
          "revenue": {
            "type": "object",
            "description": "營收＝現金＋線上（遠端投幣沒有收錢，不算）",
            "properties": {
              "amount": {
                "type": "integer"
              }
            }
          }
        }
      },
      "DeviceRevenue": {
        "allOf": [
          {
            "type": "object",
            "required": [
              "device_id",
              "name"
            ],
            "properties": {
              "device_id": {
                "type": "string"
              },
              "name": {
                "type": "string"
              },
              "days": {
                "type": "array",
                "description": "granularity=day 才有",
                "items": {
                  "allOf": [
                    {
                      "type": "object",
                      "properties": {
                        "date": {
                          "type": "string",
                          "format": "date"
                        }
                      }
                    },
                    {
                      "$ref": "#/components/schemas/RevenueRow"
                    }
                  ]
                }
              }
            }
          },
          {
            "$ref": "#/components/schemas/RevenueRow"
          }
        ]
      },
      "StoreRevenue": {
        "type": "object",
        "required": [
          "store_id",
          "from",
          "to",
          "timezone",
          "currency",
          "granularity",
          "generated_at",
          "devices",
          "totals"
        ],
        "properties": {
          "store_id": {
            "type": "string"
          },
          "from": {
            "type": "string",
            "format": "date"
          },
          "to": {
            "type": "string",
            "format": "date"
          },
          "timezone": {
            "type": "string",
            "example": "Asia/Taipei"
          },
          "currency": {
            "type": "string",
            "example": "TWD"
          },
          "granularity": {
            "type": "string",
            "enum": [
              "total",
              "day"
            ]
          },
          "generated_at": {
            "type": "string",
            "format": "date-time"
          },
          "devices": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/DeviceRevenue"
            }
          },
          "totals": {
            "$ref": "#/components/schemas/RevenueRow"
          }
        }
      },
      "WebhookConfig": {
        "type": "object",
        "properties": {
          "url": {
            "type": "string",
            "format": "uri",
            "nullable": true
          },
          "events": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/EventType"
            }
          },
          "enabled": {
            "type": "boolean"
          },
          "secret": {
            "type": "string",
            "nullable": true,
            "description": "只在建立或輪替時出現一次（whsec_…）"
          },
          "disabled_reason": {
            "type": "string",
            "nullable": true,
            "description": "例如連續 24 小時送達失敗"
          },
          "last_delivery": {
            "nullable": true,
            "type": "object",
            "properties": {
              "at": {
                "type": "string",
                "format": "date-time"
              },
              "response_status": {
                "type": "integer",
                "nullable": true
              },
              "success": {
                "type": "boolean"
              }
            }
          },
          "failing_since": {
            "type": "string",
            "format": "date-time",
            "nullable": true
          }
        }
      },
      "Error": {
        "type": "object",
        "required": [
          "code",
          "message",
          "request_id"
        ],
        "properties": {
          "code": {
            "type": "string"
          },
          "message": {
            "type": "string"
          },
          "request_id": {
            "type": "string"
          }
        }
      }
    },
    "responses": {
      "BadRequest": {
        "description": "`missing_idempotency_key`／`invalid_json`",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "Unauthorized": {
        "description": "`unauthorized`（沒帶或錯誤）／`key_revoked`／`key_expired`",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            },
            "example": {
              "code": "unauthorized",
              "message": "invalid api key",
              "request_id": "req_3b9e70"
            }
          }
        }
      },
      "Forbidden": {
        "description": "`insufficient_scope`：金鑰沒有這個動作需要的 scope（例如設定 webhook 要 webhook:manage）／`ip_not_allowed`：來源 IP 不在金鑰白名單",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "NotFound": {
        "description": "`not_found`：不存在或不在這把金鑰的授權範圍",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "RateLimited": {
        "description": "`rate_limited`：超過限流（見最上方限流表）",
        "headers": {
          "Retry-After": {
            "description": "幾秒後再試",
            "schema": {
              "type": "integer"
            }
          },
          "X-RateLimit-Limit": {
            "schema": {
              "type": "integer"
            }
          },
          "X-RateLimit-Remaining": {
            "schema": {
              "type": "integer"
            }
          },
          "X-RateLimit-Reset": {
            "description": "幾秒後額度重置",
            "schema": {
              "type": "integer"
            }
          }
        },
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      }
    }
  }
}