{
  "openapi": "3.1.0",
  "info": {
    "title": "SnapPar Enterprise REST API",
    "version": "1.0.0",
    "description": "Enterprise automation, ERP inventory sync, IoT scale telemetry, compliance audit logs, signed outbound webhooks, and spatial warehouse APIs. Authenticate machine requests via `X-API-Key: sk_live_...` or `Authorization: Bearer sk_live_...` (default rate limit: 120 requests/minute per key; active Fleet subscription required)."
  },
  "servers": [
    { "url": "https://snappar.app", "description": "Primary production web & API proxy" },
    { "url": "https://api.snappar.io", "description": "Direct Cloud Run API host" },
    { "url": "http://localhost:8080", "description": "Local Go API server" }
  ],
  "tags": [
    { "name": "Bins & ERP Sync", "description": "Catalog CRUD, barcode resolution, workflow transitions, ERP stock upserts, and deficit reporting." },
    { "name": "Replenishment & Requests", "description": "Reorder queue inspection, approval/denial/receiving actions, and external ERP PO linking." },
    { "name": "IoT Telemetry & Receiving", "description": "Idempotent sensor/PLC readings and supplier Advanced Shipping Notice (ASN) ingestion." },
    { "name": "Spatial Warehouse", "description": "Hierarchical facility tree, live bay stockout rollups, and dock-anchored walk sequences." },
    { "name": "Compliance & Audit", "description": "Immutable bin, workflow, and machine-token traceability records in JSON or formula-safe CSV." },
    { "name": "Outbound Webhooks", "description": "HMAC-SHA256 signed event endpoint subscriptions, synchronous ping tests, and delivery logs." },
    { "name": "API Keys (Session Only)", "description": "Interactive Admin session endpoints for minting, rotating, and revoking sk_live_ tokens." }
  ],
  "security": [{ "ApiKeyAuth": [] }, { "BearerAuth": [] }],
  "components": {
    "securitySchemes": {
      "ApiKeyAuth": {
        "type": "apiKey",
        "in": "header",
        "name": "X-API-Key",
        "description": "Scoped Enterprise machine key prefixed with `sk_live_`."
      },
      "BearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "description": "Accepts either an interactive session token (`Authorization: Bearer <jwt>`) or a machine API key (`Authorization: Bearer sk_live_...`)."
      }
    },
    "schemas": {
      "ErrorResponse": {
        "type": "object",
        "required": ["error"],
        "properties": {
          "error": { "type": "string" },
          "code": {
            "type": "string",
            "enum": [
              "INVALID_API_KEY",
              "FLEET_PLAN_REQUIRED",
              "BIN_LIMIT_REACHED",
              "SEAT_LIMIT_REACHED",
              "DOWNGRADE_BLOCKED",
              "INSUFFICIENT_SCOPE",
              "SESSION_AUTH_REQUIRED",
              "RATE_LIMIT_EXCEEDED"
            ]
          }
        },
        "example": {
          "error": "API key missing required scope: bins:write",
          "code": "INSUFFICIENT_SCOPE"
        }
      },
      "ProductMapping": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "workspace_id": { "type": "string" },
          "bin_qr_id": { "type": "string" },
          "upc_barcode": { "type": "string" },
          "alternate_barcodes": { "type": "array", "items": { "type": "string" } },
          "title": { "type": "string" },
          "category": { "type": "string" },
          "primary_vendor_url": { "type": "string", "format": "uri" },
          "secondary_vendor_fallback_url": { "type": "string", "format": "uri" },
          "default_price": { "type": "number" },
          "par_level": { "type": "integer" },
          "current_stock": { "type": "integer" },
          "active_vendor_target": { "type": "string", "enum": ["primary", "fallback"] },
          "direct_location_id": { "type": "string" },
          "bin_position": { "type": "integer" },
          "location_short_code": { "type": "string" },
          "location_display": { "type": "string" },
          "walk_sort_key": { "type": "string" },
          "status": { "type": "string", "enum": ["OK", "LOW", "OUT", "ORDERED", "SHIPPED"] },
          "updated_at": { "type": "integer" }
        },
        "example": {
          "id": "bin_bolt_m8",
          "workspace_id": "ws_acme",
          "bin_qr_id": "A01-B02-04",
          "upc_barcode": "049000028904",
          "title": "M8x25 Stainless Hex Bolt (50pk)",
          "category": "Fasteners",
          "primary_vendor_url": "https://www.mcmaster.com/91287A142",
          "default_price": 14.5,
          "par_level": 20,
          "current_stock": 4,
          "location_short_code": "A01-B02-04",
          "location_display": "North Plant > Aisle 1 > Bay 2",
          "status": "LOW"
        }
      },
      "BulkStockRequest": {
        "type": "object",
        "required": ["items"],
        "properties": {
          "workspace_id": { "type": "string" },
          "items": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "bin_id": { "type": "string" },
                "bin_qr_id": { "type": "string" },
                "upc_barcode": { "type": "string" },
                "current_stock": { "type": "integer", "minimum": 0 },
                "par_level": { "type": "integer", "minimum": 1 },
                "default_price": { "type": "number", "minimum": 0 },
                "title": { "type": "string" },
                "category": { "type": "string" },
                "primary_vendor_url": { "type": "string", "format": "uri" },
                "secondary_vendor_fallback_url": { "type": "string", "format": "uri" }
              }
            }
          }
        },
        "example": {
          "items": [
            { "bin_qr_id": "A01-B02-04", "current_stock": 0, "par_level": 24, "default_price": 15.25 }
          ]
        }
      },
      "BulkStockResult": {
        "type": "object",
        "properties": {
          "updated_bins": { "type": "array", "items": { "$ref": "#/components/schemas/ProductMapping" } },
          "updated": { "type": "integer" },
          "errors": { "type": "array", "items": { "type": "string" } }
        },
        "example": { "updated": 1, "updated_bins": [{ "id": "bin_bolt_m8", "bin_qr_id": "A01-B02-04", "current_stock": 0 }] }
      },
      "DeficitReport": {
        "type": "object",
        "properties": {
          "workspace_id": { "type": "string" },
          "generated_at": { "type": "integer" },
          "total_bins": { "type": "integer" },
          "total_deficit_units": { "type": "integer" },
          "total_estimated_cost": { "type": "number" },
          "by_supplier": { "type": "object", "additionalProperties": { "type": "integer" } },
          "items": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "bin_id": { "type": "string" },
                "bin_qr_id": { "type": "string" },
                "title": { "type": "string" },
                "location_display": { "type": "string" },
                "supplier_host": { "type": "string" },
                "active_vendor_url": { "type": "string" },
                "status": { "type": "string", "enum": ["OUT", "LOW"] },
                "current_stock": { "type": "integer" },
                "par_level": { "type": "integer" },
                "deficit_qty": { "type": "integer" },
                "unit_price": { "type": "number" },
                "estimated_cost": { "type": "number" }
              }
            }
          }
        },
        "example": {
          "workspace_id": "ws_acme",
          "generated_at": 1795300000,
          "total_bins": 1,
          "total_deficit_units": 24,
          "total_estimated_cost": 366.0,
          "by_supplier": { "mcmaster.com": 1 },
          "items": [{ "bin_qr_id": "A01-B02-04", "title": "M8x25 Hex Bolt", "status": "OUT", "deficit_qty": 24, "estimated_cost": 366.0 }]
        }
      },
      "TelemetryIngestRequest": {
        "type": "object",
        "required": ["readings"],
        "properties": {
          "workspace_id": { "type": "string" },
          "readings": {
            "type": "array",
            "items": {
              "type": "object",
              "required": ["bin_id"],
              "properties": {
                "bin_id": { "type": "string" },
                "fill_status": { "type": "string", "enum": ["Good", "Low", "Out"] },
                "measured_qty": { "type": "integer" },
                "sensor_id": { "type": "string" },
                "idempotency_key": { "type": "string" },
                "notes": { "type": "string" }
              }
            }
          }
        },
        "example": {
          "readings": [{ "bin_id": "A01-B02-04", "measured_qty": 3, "sensor_id": "scale-bay2", "idempotency_key": "scale-bay2-1795300120" }]
        }
      },
      "TelemetryIngestResult": {
        "type": "object",
        "properties": {
          "processed": { "type": "integer" },
          "deduplicated": { "type": "integer" },
          "errors": { "type": "array", "items": { "type": "string" } }
        },
        "example": { "processed": 1, "deduplicated": 0 }
      },
      "ReceivingASNRequest": {
        "type": "object",
        "required": ["items"],
        "properties": {
          "tracking_number": { "type": "string" },
          "tracking_numbers": { "type": "array", "items": { "type": "string" } },
          "po_number": { "type": "string" },
          "note": { "type": "string" },
          "items": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "bin_id": { "type": "string" },
                "bin_qr_id": { "type": "string" },
                "upc_barcode": { "type": "string" }
              }
            }
          }
        },
        "example": {
          "tracking_number": "1Z999AA10123456784",
          "po_number": "PO-2026-8841",
          "items": [{ "bin_qr_id": "A01-B02-04" }]
        }
      },
      "AuditLogEntry": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "workspace_id": { "type": "string" },
          "bin_id": { "type": "string" },
          "bin_qr_id": { "type": "string" },
          "product_title": { "type": "string" },
          "workflow": { "type": "string" },
          "action": { "type": "string" },
          "previous_status": { "type": "string" },
          "new_status": { "type": "string" },
          "previous_stock": { "type": "integer" },
          "new_stock": { "type": "integer" },
          "actor": { "type": "string" },
          "auth_type": { "type": "string" },
          "notes": { "type": "string" },
          "timestamp": { "type": "integer" }
        },
        "example": {
          "id": "aud_1795300120",
          "workspace_id": "ws_acme",
          "bin_qr_id": "A01-B02-04",
          "workflow": "bulk_stock_sync",
          "action": "updated",
          "previous_status": "LOW",
          "new_status": "OUT",
          "actor": "API Key: NetSuite ERP",
          "auth_type": "api_key",
          "timestamp": 1795300120
        }
      },
      "ReorderRequest": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "workspace_id": { "type": "string" },
          "requester_user_id": { "type": "string" },
          "product_id": { "type": "string" },
          "quantity": { "type": "integer" },
          "priority": { "type": "integer" },
          "status": { "type": "integer", "description": "1=PENDING, 2=APPROVED, 3=ORDERED, 4=DECLINED" },
          "notes": { "type": "string" },
          "created_at": { "type": "integer" }
        },
        "example": {
          "id": "req_1795300200",
          "workspace_id": "ws_acme",
          "product_id": "bin_bolt_m8",
          "quantity": 20,
          "status": 1,
          "notes": "Below par on North Aisle 1",
          "created_at": 1795300200
        }
      },
      "ExternalPORequest": {
        "type": "object",
        "required": ["po_number"],
        "properties": {
          "workspace_id": { "type": "string" },
          "po_number": { "type": "string" },
          "vendor": { "type": "string" },
          "mark_ordered": { "type": "boolean" }
        },
        "example": { "po_number": "ERP-PO-4490", "vendor": "McMaster-Carr", "mark_ordered": true }
      },
      "SiteHealthResponse": {
        "type": "object",
        "properties": {
          "site_id": { "type": "string" },
          "summary": { "type": "object", "additionalProperties": { "type": "integer" } },
          "bays": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "bay_id": { "type": "string" },
                "bay_name": { "type": "string" },
                "short_code": { "type": "string" },
                "aisle_name": { "type": "string" },
                "status": { "type": "string", "enum": ["OUT", "LOW", "TRANSIT", "OK", "EMPTY"] },
                "bin_count": { "type": "integer" },
                "deficit_qty": { "type": "integer" }
              }
            }
          }
        },
        "example": {
          "site_id": "site_north",
          "summary": { "OUT": 1, "LOW": 2, "TRANSIT": 1, "OK": 8, "EMPTY": 0 },
          "bays": [{ "bay_id": "bay_2", "bay_name": "Bay 2", "short_code": "B02", "aisle_name": "Aisle 1", "status": "OUT", "bin_count": 6, "deficit_qty": 24 }]
        }
      },
      "WalkOrderResponse": {
        "type": "object",
        "properties": {
          "site_id": { "type": "string" },
          "walk_order": { "type": "array", "items": { "type": "string" } },
          "count": { "type": "integer" }
        },
        "example": { "site_id": "site_north", "walk_order": ["bay_1", "bay_2", "bay_5"], "count": 3 }
      },
      "APIKey": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "workspace_id": { "type": "string" },
          "name": { "type": "string" },
          "prefix": { "type": "string" },
          "role": { "type": "string", "enum": ["Admin", "Manager"] },
          "scopes": { "type": "array", "items": { "type": "string" } },
          "created_by": { "type": "string" },
          "created_at": { "type": "integer" },
          "last_used_at": { "type": "integer" },
          "expires_at": { "type": "integer" },
          "revoked_at": { "type": "integer" },
          "active": { "type": "boolean" }
        },
        "example": {
          "id": "key_1795300300",
          "workspace_id": "ws_acme",
          "name": "NetSuite ERP",
          "prefix": "sk_live_4a9c2f10",
          "role": "Admin",
          "scopes": ["bins:read", "bins:write", "requests:read"],
          "active": true
        }
      },
      "CreateAPIKeyRequest": {
        "type": "object",
        "required": ["name"],
        "properties": {
          "workspace_id": { "type": "string" },
          "name": { "type": "string" },
          "role": { "type": "string", "enum": ["Admin", "Manager"] },
          "scopes": { "type": "array", "items": { "type": "string" } },
          "expires_in_days": { "type": "integer", "minimum": 0 }
        },
        "example": { "name": "NetSuite ERP", "role": "Admin", "scopes": ["bins:read", "bins:write", "requests:read"], "expires_in_days": 90 }
      },
      "WebhookEndpoint": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "workspace_id": { "type": "string" },
          "url": { "type": "string", "format": "uri" },
          "events": { "type": "array", "items": { "type": "string" } },
          "secret_prefix": { "type": "string" },
          "description": { "type": "string" },
          "active": { "type": "boolean" },
          "created_at": { "type": "integer" },
          "last_delivered_at": { "type": "integer" },
          "last_status_code": { "type": "integer" }
        },
        "example": {
          "id": "wh_1795300400",
          "workspace_id": "ws_acme",
          "url": "https://erp.acme.com/hooks/snappar",
          "events": ["bin.stock_out", "request.created"],
          "secret_prefix": "whsec_98ab12cd",
          "active": true
        }
      },
      "CreateWebhookRequest": {
        "type": "object",
        "required": ["url"],
        "properties": {
          "workspace_id": { "type": "string" },
          "url": { "type": "string", "format": "uri" },
          "description": { "type": "string" },
          "events": { "type": "array", "items": { "type": "string" } }
        },
        "example": {
          "url": "https://erp.acme.com/hooks/snappar",
          "description": "SAP Purchasing Bus",
          "events": ["bin.stock_out", "bin.stock_low", "request.created"]
        }
      },
      "WebhookDelivery": {
        "type": "object",
        "properties": {
          "id": { "type": "string" },
          "endpoint_id": { "type": "string" },
          "workspace_id": { "type": "string" },
          "event": { "type": "string" },
          "status_code": { "type": "integer" },
          "success": { "type": "boolean" },
          "error": { "type": "string" },
          "timestamp": { "type": "integer" }
        },
        "example": {
          "id": "dlv_1795300500",
          "endpoint_id": "wh_1795300400",
          "event": "webhook.test",
          "status_code": 200,
          "success": true,
          "timestamp": 1795300500
        }
      },
      "WebhookEnvelope": {
        "type": "object",
        "required": ["id", "event", "workspace_id", "timestamp", "data"],
        "properties": {
          "id": { "type": "string" },
          "event": { "type": "string" },
          "workspace_id": { "type": "string" },
          "timestamp": { "type": "integer" },
          "data": { "type": "object", "additionalProperties": true }
        },
        "example": {
          "id": "dlv_1795300500",
          "event": "bin.stock_out",
          "workspace_id": "ws_acme",
          "timestamp": 1795300500,
          "data": { "bin_id": "bin_bolt_m8", "bin_qr_id": "A01-B02-04", "current_stock": 0, "par_level": 20 }
        }
      }
    }
  },
  "paths": {
    "/api/v1/bins": {
      "get": {
        "operationId": "listBins",
        "tags": ["Bins & ERP Sync"],
        "summary": "List workspace bins",
        "description": "Returns all bins in the caller's workspace, optionally filtered by substring query `?q=`.",
        "x-required-scope": "bins:read",
        "x-plan-tier": "all",
        "parameters": [
          { "name": "q", "in": "query", "schema": { "type": "string" }, "description": "Filter by title, QR ID, or barcode." },
          { "name": "workspace_id", "in": "query", "schema": { "type": "string" }, "description": "Workspace scope (ProductAdmin only for cross-org)." }
        ],
        "responses": {
          "200": { "description": "Workspace bin catalog", "content": { "application/json": { "example": { "bins": [{ "id": "bin_bolt_m8", "bin_qr_id": "A01-B02-04", "current_stock": 4, "par_level": 20 }], "count": 1 } } } },
          "401": { "description": "Unauthorized", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "403": { "description": "Missing bins:read scope or cross-workspace denied", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } },
          "429": { "description": "Rate limit exceeded", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } }
        }
      },
      "post": {
        "operationId": "createBin",
        "tags": ["Bins & ERP Sync"],
        "summary": "Create inventory bin",
        "description": "Creates a physical bin mapping with QR code, barcode, par level, and vendor URL. Floor Scanners are blocked.",
        "x-required-scope": "bins:write",
        "x-plan-tier": "all",
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ProductMapping" } } } },
        "responses": {
          "201": { "description": "Created bin", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ProductMapping" } } } },
          "400": { "description": "Missing bin_qr_id or title" },
          "403": { "description": "Forbidden (Scanner or missing bins:write)" }
        }
      }
    },
    "/api/v1/bins/{id}": {
      "get": {
        "operationId": "getBin",
        "tags": ["Bins & ERP Sync"],
        "summary": "Fetch single bin by ID, QR ID, or UPC",
        "x-required-scope": "bins:read",
        "x-plan-tier": "all",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
        "responses": {
          "200": { "description": "Matched bin", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ProductMapping" } } } },
          "403": { "description": "Forbidden" },
          "404": { "description": "Bin not found" }
        }
      },
      "put": {
        "operationId": "updateBin",
        "tags": ["Bins & ERP Sync"],
        "summary": "Update bin configuration",
        "x-required-scope": "bins:write",
        "x-plan-tier": "all",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ProductMapping" } } } },
        "responses": {
          "200": { "description": "Updated bin", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ProductMapping" } } } },
          "400": { "description": "Invalid payload" },
          "403": { "description": "Forbidden" }
        }
      },
      "delete": {
        "operationId": "deleteBin",
        "tags": ["Bins & ERP Sync"],
        "summary": "Delete bin",
        "x-required-scope": "bins:write",
        "x-plan-tier": "all",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
        "responses": {
          "200": { "description": "Deleted", "content": { "application/json": { "example": { "deleted": true } } } },
          "403": { "description": "Forbidden" },
          "404": { "description": "Bin not found" }
        }
      }
    },
    "/api/v1/bins/bulk-stock": {
      "post": {
        "operationId": "bulkUpsertStock",
        "tags": ["Bins & ERP Sync"],
        "summary": "Batch sync stock, par levels, prices & supplier URLs",
        "description": "Synchronizes ERP stock counts, par levels, pricing, and vendor URLs in one batch. Records audit trail entries and fires `bin.stock_out`, `bin.stock_low`, or `bin.restocked` webhooks on state transitions.",
        "x-required-scope": "bins:write",
        "x-plan-tier": "fleet",
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BulkStockRequest" } } } },
        "responses": {
          "200": { "description": "Batch summary", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/BulkStockResult" } } } },
          "400": { "description": "Empty items or malformed JSON" },
          "403": { "description": "Fleet plan or bins:write scope required", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } }
        }
      }
    },
    "/api/v1/bins/locate": {
      "get": {
        "operationId": "locateBinsByBarcode",
        "tags": ["Bins & ERP Sync"],
        "summary": "Resolve UPC/case barcode to matching bins sorted by urgency",
        "x-required-scope": "bins:read",
        "x-plan-tier": "all",
        "parameters": [{ "name": "barcode", "in": "query", "required": true, "schema": { "type": "string" }, "description": "Scanned UPC, EAN, or alternate case barcode." }],
        "responses": {
          "200": { "description": "Urgency-sorted bin matches", "content": { "application/json": { "example": { "barcode": "049000028904", "bins": [{ "id": "bin_bolt_m8", "bin_qr_id": "A01-B02-04" }], "count": 1 } } } },
          "400": { "description": "Missing barcode parameter" },
          "403": { "description": "Missing bins:read scope" }
        }
      }
    },
    "/api/v1/bins/{id}/status": {
      "post": {
        "operationId": "updateBinWorkflowStatus",
        "tags": ["Bins & ERP Sync"],
        "summary": "Trigger bin workflow status update (Good, Low, Out)",
        "description": "Executes `notice_flag`, `milkman_audit`, `kanban_loop`, `receiving_reset`, or `sensor_webhook` (Fleet-gated).",
        "x-required-scope": "bins:write",
        "x-plan-tier": "all",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["fill_status"],
                "properties": {
                  "fill_status": { "type": "string", "enum": ["Good", "Low", "Out"] },
                  "workflow": { "type": "string", "enum": ["notice_flag", "milkman_audit", "kanban_loop", "receiving_reset", "sensor_webhook"] },
                  "actor": { "type": "string" },
                  "notes": { "type": "string" },
                  "current_stock": { "type": "integer", "minimum": 0 }
                }
              },
              "example": { "fill_status": "Low", "workflow": "milkman_audit", "current_stock": 5, "notes": "Morning aisle check" }
            }
          }
        },
        "responses": {
          "200": { "description": "Updated bin, generated request, and scan event" },
          "400": { "description": "Invalid status or missing bin" },
          "403": { "description": "Insufficient scope or Fleet required for sensor_webhook" }
        }
      }
    },
    "/api/v1/reports/deficits": {
      "get": {
        "operationId": "getDeficitsReport",
        "tags": ["Bins & ERP Sync"],
        "summary": "Export OUT and LOW replenishment deficits (JSON or CSV)",
        "x-required-scope": "bins:read",
        "x-plan-tier": "fleet",
        "parameters": [
          { "name": "urgency", "in": "query", "schema": { "type": "string", "enum": ["OUT", "LOW"] } },
          { "name": "supplier", "in": "query", "schema": { "type": "string" }, "description": "Filter by vendor host substring (e.g. mcmaster, amazon)." },
          { "name": "location_prefix", "in": "query", "schema": { "type": "string" } },
          { "name": "format", "in": "query", "schema": { "type": "string", "enum": ["json", "csv"] } }
        ],
        "responses": {
          "200": { "description": "Deficit report JSON or formula-safe CSV", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/DeficitReport" } } } },
          "403": { "description": "Fleet plan or bins:read scope required" }
        }
      }
    },
    "/api/v1/requests": {
      "get": {
        "operationId": "listRequests",
        "tags": ["Replenishment & Requests"],
        "summary": "List reorder requests with ?status= & ?since= filter",
        "x-required-scope": "requests:read",
        "x-plan-tier": "all",
        "parameters": [
          { "name": "status", "in": "query", "schema": { "type": "string", "enum": ["PENDING", "APPROVED", "ORDERED", "DECLINED"] } },
          { "name": "since", "in": "query", "schema": { "type": "integer" }, "description": "Unix timestamp lower bound on created_at." }
        ],
        "responses": {
          "200": { "description": "Filtered requests", "content": { "application/json": { "example": { "requests": [{ "id": "req_1795300200", "product_id": "bin_bolt_m8", "quantity": 20, "status": 1 }], "count": 1 } } } },
          "403": { "description": "Missing requests:read scope" }
        }
      },
      "post": {
        "operationId": "createRequest",
        "tags": ["Replenishment & Requests"],
        "summary": "Create replenishment request",
        "x-required-scope": "requests:write",
        "x-plan-tier": "all",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["product_id", "quantity"],
                "properties": {
                  "product_id": { "type": "string" },
                  "quantity": { "type": "integer", "minimum": 1 },
                  "notes": { "type": "string" }
                }
              },
              "example": { "product_id": "bin_bolt_m8", "quantity": 20, "notes": "Flagged at bay 2" }
            }
          }
        },
        "responses": {
          "201": { "description": "Created request", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ReorderRequest" } } } },
          "403": { "description": "Missing requests:write scope" },
          "409": { "description": "Active pending request already exists" }
        }
      }
    },
    "/api/v1/requests/{id}/approve": {
      "post": {
        "operationId": "approveRequest",
        "tags": ["Replenishment & Requests"],
        "summary": "Approve request and generate fulfillment cart link",
        "x-required-scope": "requests:write",
        "x-plan-tier": "all",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
        "responses": {
          "200": { "description": "Approved request and cart URL", "content": { "application/json": { "example": { "request": { "id": "req_1795300200", "status": 2 }, "cart_link": "https://www.mcmaster.com/91287A142" } } } },
          "403": { "description": "Scanner role or missing requests:write scope" },
          "404": { "description": "Request not found" }
        }
      }
    },
    "/api/v1/requests/{id}/deny": {
      "post": {
        "operationId": "denyRequest",
        "tags": ["Replenishment & Requests"],
        "summary": "Decline reorder request",
        "x-required-scope": "requests:write",
        "x-plan-tier": "all",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
        "responses": {
          "200": { "description": "Declined request", "content": { "application/json": { "example": { "request": { "id": "req_1795300200", "status": 4 }, "status": "declined" } } } },
          "403": { "description": "Forbidden" },
          "404": { "description": "Request not found" }
        }
      }
    },
    "/api/v1/requests/{id}/receive": {
      "post": {
        "operationId": "receiveRequest",
        "tags": ["Replenishment & Requests"],
        "summary": "Mark request received and restock target bin",
        "x-required-scope": "requests:write",
        "x-plan-tier": "all",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
        "responses": {
          "200": { "description": "Received request and updated bin stock" },
          "403": { "description": "Missing requests:write scope" },
          "404": { "description": "Request not found" }
        }
      }
    },
    "/api/v1/requests/{id}/external-po": {
      "patch": {
        "operationId": "linkExternalPO",
        "tags": ["Replenishment & Requests"],
        "summary": "Attach ERP PO number and optionally mark ORDERED",
        "x-required-scope": "requests:write",
        "x-plan-tier": "fleet",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ExternalPORequest" } } } },
        "responses": {
          "200": { "description": "Updated request with PO tag", "content": { "application/json": { "example": { "request": { "id": "req_1795300200", "status": 3, "notes": "[PO: ERP-PO-4490 · McMaster-Carr]" } } } } },
          "400": { "description": "Missing po_number" },
          "403": { "description": "Fleet plan or requests:write scope required" },
          "404": { "description": "Request not found" }
        }
      }
    },
    "/api/v1/telemetry/bins": {
      "post": {
        "operationId": "ingestTelemetry",
        "tags": ["IoT Telemetry & Receiving"],
        "summary": "Batch ingest IoT scale/RFID/PLC telemetry with idempotency",
        "description": "Ingests measured quantities or fill statuses from shop-floor scales, RFID gates, or PLCs with per-workspace idempotency deduplication.",
        "x-required-scope": "bins:write",
        "x-plan-tier": "fleet",
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/TelemetryIngestRequest" } } } },
        "responses": {
          "200": { "description": "Ingestion counts", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/TelemetryIngestResult" } } } },
          "400": { "description": "Empty readings or bad JSON" },
          "403": { "description": "Fleet plan or bins:write scope required" }
        }
      }
    },
    "/api/v1/orgs/{orgId}/receiving/asn": {
      "post": {
        "operationId": "ingestReceivingASN",
        "tags": ["IoT Telemetry & Receiving"],
        "summary": "Ingest supplier Advanced Shipping Notice & tracking numbers",
        "description": "Attaches carrier tracking numbers to one or more matching bins, logs an audit entry, and emits a `shipment.tracked` webhook.",
        "x-required-scope": "bins:write",
        "x-plan-tier": "fleet",
        "parameters": [{ "name": "orgId", "in": "path", "required": true, "schema": { "type": "string" } }],
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ReceivingASNRequest" } } } },
        "responses": {
          "200": { "description": "ASN tracking applied", "content": { "application/json": { "example": { "matched_bin_ids": ["bin_bolt_m8"], "tracking": ["1Z999AA10123456784"], "unmatched": [] } } } },
          "400": { "description": "Missing tracking number or items" },
          "403": { "description": "Fleet plan or bins:write scope required" },
          "404": { "description": "No matching bins found" }
        }
      }
    },
    "/api/v1/orgs/{orgId}/locations/tree": {
      "get": {
        "operationId": "getLocationTree",
        "tags": ["Spatial Warehouse"],
        "summary": "Fetch hierarchical warehouse tree & 2D floor plan",
        "x-required-scope": "locations:read",
        "x-plan-tier": "pro",
        "parameters": [{ "name": "orgId", "in": "path", "required": true, "schema": { "type": "string" } }],
        "responses": {
          "200": { "description": "Hierarchical location tree", "content": { "application/json": { "example": { "tree_version": 4, "roots": { "site_north": { "id": "site_north", "name": "North Plant", "type": "site" } } } } } },
          "403": { "description": "Cross-org forbidden or missing locations:read scope" }
        }
      }
    },
    "/api/v1/orgs/{orgId}/locations/{siteId}/health": {
      "get": {
        "operationId": "getSiteHealth",
        "tags": ["Spatial Warehouse"],
        "summary": "Live bay & aisle stockout rollup for a warehouse site",
        "x-required-scope": "locations:read",
        "x-plan-tier": "fleet",
        "parameters": [
          { "name": "orgId", "in": "path", "required": true, "schema": { "type": "string" } },
          { "name": "siteId", "in": "path", "required": true, "schema": { "type": "string" } }
        ],
        "responses": {
          "200": { "description": "Bay stockout summary", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/SiteHealthResponse" } } } },
          "403": { "description": "Fleet plan or locations:read scope required" },
          "404": { "description": "Site not found" }
        }
      }
    },
    "/api/v1/orgs/{orgId}/locations/{siteId}/walk-order": {
      "get": {
        "operationId": "getSiteWalkOrder",
        "tags": ["Spatial Warehouse"],
        "summary": "Ordered spatial walk-path sequence anchored to dock/door",
        "x-required-scope": "locations:read",
        "x-plan-tier": "fleet",
        "parameters": [
          { "name": "orgId", "in": "path", "required": true, "schema": { "type": "string" } },
          { "name": "siteId", "in": "path", "required": true, "schema": { "type": "string" } }
        ],
        "responses": {
          "200": { "description": "Nearest-neighbor walk sequence", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WalkOrderResponse" } } } },
          "403": { "description": "Fleet plan or locations:read scope required" },
          "404": { "description": "Site not found" }
        }
      }
    },
    "/api/v1/audit-logs": {
      "get": {
        "operationId": "queryAuditLogs",
        "tags": ["Compliance & Audit"],
        "summary": "Query paginated bin traceability audit logs (JSON or CSV)",
        "x-required-scope": "audit:read",
        "x-plan-tier": "fleet",
        "parameters": [
          { "name": "bin_id", "in": "query", "schema": { "type": "string" } },
          { "name": "workflow", "in": "query", "schema": { "type": "string" } },
          { "name": "actor", "in": "query", "schema": { "type": "string" } },
          { "name": "q", "in": "query", "schema": { "type": "string" } },
          { "name": "from", "in": "query", "schema": { "type": "integer" } },
          { "name": "to", "in": "query", "schema": { "type": "integer" } },
          { "name": "limit", "in": "query", "schema": { "type": "integer", "default": 100, "maximum": 500 } },
          { "name": "offset", "in": "query", "schema": { "type": "integer", "default": 0 } },
          { "name": "format", "in": "query", "schema": { "type": "string", "enum": ["json", "csv"] } }
        ],
        "responses": {
          "200": { "description": "Audit log entries", "content": { "application/json": { "example": { "entries": [{ "id": "aud_1795300120", "workflow": "bulk_stock_sync", "action": "updated", "actor": "API Key: NetSuite ERP" }], "total": 1, "count": 1 } } } },
          "403": { "description": "Fleet plan or audit:read scope required" }
        }
      }
    },
    "/api/v1/webhooks/endpoints": {
      "get": {
        "operationId": "listWebhookEndpoints",
        "tags": ["Outbound Webhooks"],
        "summary": "List outbound webhook subscriptions",
        "x-required-scope": "webhooks:manage",
        "x-plan-tier": "fleet",
        "responses": {
          "200": { "description": "Registered endpoints (secrets omitted)", "content": { "application/json": { "example": { "endpoints": [{ "id": "wh_1795300400", "url": "https://erp.acme.com/hooks/snappar", "events": ["bin.stock_out"] }], "count": 1 } } } },
          "403": { "description": "Admin + Fleet + webhooks:manage required" }
        }
      },
      "post": {
        "operationId": "createWebhookEndpoint",
        "tags": ["Outbound Webhooks"],
        "summary": "Register HTTPS webhook endpoint & receive whsec_ secret",
        "description": "Validates URL against HTTPS and SSRF rules (blocking internal/metadata IPs) and returns the HMAC signing secret once.",
        "x-required-scope": "webhooks:manage",
        "x-plan-tier": "fleet",
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CreateWebhookRequest" } } } },
        "responses": {
          "201": { "description": "Created endpoint with one-time signing_secret", "content": { "application/json": { "example": { "endpoint": { "id": "wh_1795300400", "secret_prefix": "whsec_98ab12cd" }, "signing_secret": "whsec_98ab12cd..." } } } },
          "400": { "description": "Invalid or blocked target URL" },
          "403": { "description": "Admin + Fleet + webhooks:manage required" }
        }
      }
    },
    "/api/v1/webhooks/endpoints/{id}": {
      "delete": {
        "operationId": "deleteWebhookEndpoint",
        "tags": ["Outbound Webhooks"],
        "summary": "Delete webhook endpoint",
        "x-required-scope": "webhooks:manage",
        "x-plan-tier": "fleet",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
        "responses": {
          "200": { "description": "Deleted", "content": { "application/json": { "example": { "deleted": true, "id": "wh_1795300400" } } } },
          "403": { "description": "Forbidden" },
          "404": { "description": "Endpoint not found" }
        }
      }
    },
    "/api/v1/webhooks/endpoints/{id}/test": {
      "post": {
        "operationId": "testWebhookEndpoint",
        "tags": ["Outbound Webhooks"],
        "summary": "Send synchronous HMAC-signed webhook.test payload",
        "x-required-scope": "webhooks:manage",
        "x-plan-tier": "fleet",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
        "responses": {
          "200": { "description": "Delivery attempt result", "content": { "application/json": { "example": { "delivery": { "id": "dlv_1795300500", "event": "webhook.test", "status_code": 200, "success": true } } } } },
          "403": { "description": "Forbidden" },
          "404": { "description": "Endpoint not found" }
        }
      }
    },
    "/api/v1/webhooks/deliveries": {
      "get": {
        "operationId": "listWebhookDeliveries",
        "tags": ["Outbound Webhooks"],
        "summary": "Inspect recent webhook delivery attempts",
        "x-required-scope": "webhooks:manage",
        "x-plan-tier": "fleet",
        "parameters": [
          { "name": "endpoint_id", "in": "query", "schema": { "type": "string" } },
          { "name": "limit", "in": "query", "schema": { "type": "integer", "default": 50, "maximum": 100 } }
        ],
        "responses": {
          "200": { "description": "Delivery attempts", "content": { "application/json": { "example": { "deliveries": [{ "id": "dlv_1795300500", "event": "webhook.test", "status_code": 200, "success": true }], "count": 1 } } } },
          "403": { "description": "Forbidden" }
        }
      }
    },
    "/api/v1/api-keys": {
      "get": {
        "operationId": "listAPIKeys",
        "tags": ["API Keys (Session Only)"],
        "summary": "List Enterprise API keys (Admin session)",
        "description": "Requires an interactive Admin browser/user session (`403 SESSION_AUTH_REQUIRED` if called with `X-API-Key`).",
        "x-required-scope": "session:admin",
        "x-plan-tier": "fleet",
        "responses": {
          "200": { "description": "Key metadata list (hashes omitted)", "content": { "application/json": { "example": { "api_keys": [{ "id": "key_1795300300", "name": "NetSuite ERP", "prefix": "sk_live_4a9c2f10", "active": true }], "count": 1 } } } },
          "403": { "description": "SESSION_AUTH_REQUIRED or FLEET_PLAN_REQUIRED", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorResponse" } } } }
        }
      },
      "post": {
        "operationId": "createAPIKey",
        "tags": ["API Keys (Session Only)"],
        "summary": "Create scoped sk_live_ API key (Admin session)",
        "x-required-scope": "session:admin",
        "x-plan-tier": "fleet",
        "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CreateAPIKeyRequest" } } } },
        "responses": {
          "201": { "description": "Created key metadata + one-time plaintext_key", "content": { "application/json": { "example": { "api_key": { "id": "key_1795300300", "prefix": "sk_live_4a9c2f10" }, "plaintext_key": "sk_live_4a9c2f10..." } } } },
          "400": { "description": "Invalid scope or missing name" },
          "403": { "description": "SESSION_AUTH_REQUIRED or non-Admin" }
        }
      }
    },
    "/api/v1/api-keys/{id}/rotate": {
      "post": {
        "operationId": "rotateAPIKey",
        "tags": ["API Keys (Session Only)"],
        "summary": "Rotate active API key secret (Admin session)",
        "x-required-scope": "session:admin",
        "x-plan-tier": "fleet",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
        "responses": {
          "200": { "description": "Updated metadata + new plaintext_key" },
          "403": { "description": "SESSION_AUTH_REQUIRED" },
          "404": { "description": "API key not found" },
          "409": { "description": "Cannot rotate an already-revoked API key" }
        }
      }
    },
    "/api/v1/api-keys/{id}": {
      "delete": {
        "operationId": "revokeAPIKey",
        "tags": ["API Keys (Session Only)"],
        "summary": "Revoke API key (Admin session)",
        "x-required-scope": "session:admin",
        "x-plan-tier": "fleet",
        "parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
        "responses": {
          "200": { "description": "Revoked key", "content": { "application/json": { "example": { "revoked": true, "api_key": { "id": "key_1795300300", "active": false } } } } },
          "403": { "description": "SESSION_AUTH_REQUIRED" },
          "404": { "description": "API key not found" }
        }
      }
    },
    "/api/v1/openapi.json": {
      "get": {
        "operationId": "getOpenAPISpec",
        "tags": ["Compliance & Audit"],
        "summary": "Fetch public OpenAPI 3.1 contract",
        "security": [],
        "x-required-scope": "public",
        "x-plan-tier": "public",
        "responses": {
          "200": { "description": "OpenAPI 3.1 JSON document" }
        }
      }
    }
  },
  "webhooks": {
    "bin.stock_out": {
      "post": {
        "summary": "Bin depleted to 0 stock",
        "description": "Includes X-SnapPar-Event, X-SnapPar-Delivery, and X-SnapPar-Signature (`t=<unix>,v1=<hmac_sha256_hex>`).",
        "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WebhookEnvelope" } } } },
        "responses": { "200": { "description": "Receiver acknowledged event" } }
      }
    },
    "bin.stock_low": {
      "post": {
        "summary": "Bin dropped at or below par level",
        "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WebhookEnvelope" } } } },
        "responses": { "200": { "description": "Receiver acknowledged event" } }
      }
    },
    "bin.restocked": {
      "post": {
        "summary": "Bin stock returned above par level",
        "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WebhookEnvelope" } } } },
        "responses": { "200": { "description": "Receiver acknowledged event" } }
      }
    },
    "bin.supplier_swapped": {
      "post": {
        "summary": "Active supplier target switched between primary and fallback",
        "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WebhookEnvelope" } } } },
        "responses": { "200": { "description": "Receiver acknowledged event" } }
      }
    },
    "request.created": {
      "post": {
        "summary": "New replenishment request queued",
        "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WebhookEnvelope" } } } },
        "responses": { "200": { "description": "Receiver acknowledged event" } }
      }
    },
    "request.approved": {
      "post": {
        "summary": "Reorder request approved by Manager or Admin",
        "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WebhookEnvelope" } } } },
        "responses": { "200": { "description": "Receiver acknowledged event" } }
      }
    },
    "request.denied": {
      "post": {
        "summary": "Reorder request declined",
        "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WebhookEnvelope" } } } },
        "responses": { "200": { "description": "Receiver acknowledged event" } }
      }
    },
    "request.received": {
      "post": {
        "summary": "Ordered request marked received and bin restocked",
        "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WebhookEnvelope" } } } },
        "responses": { "200": { "description": "Receiver acknowledged event" } }
      }
    },
    "shipment.tracked": {
      "post": {
        "summary": "Supplier ASN or carrier tracking number attached to bins",
        "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WebhookEnvelope" } } } },
        "responses": { "200": { "description": "Receiver acknowledged event" } }
      }
    },
    "webhook.test": {
      "post": {
        "summary": "Synchronous endpoint verification ping",
        "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/WebhookEnvelope" } } } },
        "responses": { "200": { "description": "Receiver acknowledged test ping" } }
      }
    }
  }
}
