{
  "openapi": "3.0.3",
  "info": {
    "title": "FleetBridge Order Source API",
    "description": "Public API for external Order Sources (POS, e-commerce, marketplace, ERP, and ordering systems) to create and manage delivery orders through FleetBridge, and to receive lifecycle webhooks. This document covers exactly the endpoints available to an Order-Source-authenticated caller (X-Api-Key) — it deliberately excludes FleetBridge dashboard-only, platform-support, and inbound-provider-webhook endpoints, which are separate, internal contracts not part of this integration.",
    "version": "1.1.0",
    "x-fleetbridge-contract": {
      "apiMajor": "v1",
      "revision": "1.1.0"
    }
  },
  "servers": [
    { "url": "https://{fleetbridge-host}", "variables": { "fleetbridge-host": { "default": "api.example-fleetbridge-host" } } }
  ],
  "security": [{ "ApiKeyAuth": [] }],
  "tags": [
    { "name": "Orders", "description": "Create, update, cancel, and read orders." },
    { "name": "Webhooks", "description": "Trigger a connectivity test to your own registered webhook endpoint." }
  ],
  "paths": {
    "/api/v1/orders": {
      "post": {
        "tags": ["Orders"],
        "operationId": "createOrder",
        "summary": "Create an order",
        "parameters": [
          {
            "name": "Idempotency-Key",
            "in": "header",
            "required": false,
            "schema": { "type": "string", "maxLength": 200 },
            "description": "Strongly recommended. See the integration guide Section 13 for exact replay semantics — a repeat of the same key returns the original order unconditionally, even if the body differs."
          }
        ],
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CreateOrderRequest" } } }
        },
        "responses": {
          "201": {
            "description": "Order created (or, on an idempotent replay, the original order returned unchanged).",
            "headers": { "Location": { "schema": { "type": "string" }, "description": "/api/v1/orders/{platformOrderId}" } },
            "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CreateOrderResult" } } }
          },
          "400": { "$ref": "#/components/responses/BadRequest" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "403": { "$ref": "#/components/responses/Forbidden" },
          "429": { "$ref": "#/components/responses/TooManyRequests" }
        }
      }
    },
    "/api/v1/orders/{platformOrderId}": {
      "get": {
        "tags": ["Orders"],
        "operationId": "getOrderById",
        "summary": "Get full order detail",
        "parameters": [{ "$ref": "#/components/parameters/PlatformOrderId" }],
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/OrderDetail" } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      },
      "patch": {
        "tags": ["Orders"],
        "operationId": "updateOrder",
        "summary": "Update mutable order business data",
        "description": "A true partial update: an omitted field is left unchanged, an explicit null clears a nullable field, a value sets it. See the integration guide Section 11.",
        "parameters": [{ "$ref": "#/components/parameters/PlatformOrderId" }],
        "requestBody": {
          "required": true,
          "content": { "application/json": { "schema": { "$ref": "#/components/schemas/UpdateOrderRequest" } } }
        },
        "responses": {
          "200": { "description": "OK — per-field propagation result.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/UpdateOrderResult" } } } },
          "400": { "$ref": "#/components/responses/BadRequest" },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "$ref": "#/components/responses/Conflict" }
        }
      }
    },
    "/api/v1/orders/by-external-id/{externalOrderId}": {
      "get": {
        "tags": ["Orders"],
        "operationId": "getOrderByExternalId",
        "summary": "Look up an order by your own reference",
        "description": "Scoped to orders created by your own Order Source — an order created by a different Order Source under the same tenant is not visible here, even with an exact externalOrderId match.",
        "parameters": [
          { "name": "externalOrderId", "in": "path", "required": true, "schema": { "type": "string" } }
        ],
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/OrderDetail" } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/api/v1/orders/{platformOrderId}/status": {
      "get": {
        "tags": ["Orders"],
        "operationId": "getOrderStatus",
        "summary": "Get current order and delivery status",
        "parameters": [{ "$ref": "#/components/parameters/PlatformOrderId" }],
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/OrderStatusResponse" } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/api/v1/orders/{platformOrderId}/tracking": {
      "get": {
        "tags": ["Orders"],
        "operationId": "getOrderTracking",
        "summary": "Get the current driver/tracking snapshot",
        "parameters": [{ "$ref": "#/components/parameters/PlatformOrderId" }],
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/OrderTracking" } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/api/v1/orders/{platformOrderId}/tracking-history": {
      "get": {
        "tags": ["Orders"],
        "operationId": "getOrderTrackingHistory",
        "summary": "Get the full tracking event timeline",
        "parameters": [{ "$ref": "#/components/parameters/PlatformOrderId" }],
        "responses": {
          "200": {
            "description": "OK — an empty array (not an error) if no shipment exists yet.",
            "content": { "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/TrackingHistoryEntry" } } } }
          },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" }
        }
      }
    },
    "/api/v1/orders/{platformOrderId}/cancel": {
      "post": {
        "tags": ["Orders"],
        "operationId": "cancelOrder",
        "summary": "Cancel an order",
        "parameters": [{ "$ref": "#/components/parameters/PlatformOrderId" }],
        "requestBody": {
          "required": false,
          "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CancelOrderRequest" } } }
        },
        "responses": {
          "200": { "description": "OK", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/CancelOrderResult" } } } },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "$ref": "#/components/responses/NotFound" },
          "409": { "$ref": "#/components/responses/Conflict" }
        }
      }
    },
    "/api/v1/webhooks/test": {
      "post": {
        "tags": ["Webhooks"],
        "operationId": "sendTestWebhook",
        "summary": "Send a webhook.test event to your own registered endpoint",
        "description": "Callable directly with your Order Source API key — scoped to your own Order Source's registered webhook endpoint(s) only.",
        "responses": {
          "200": { "description": "Test webhook enqueued." },
          "401": { "$ref": "#/components/responses/Unauthorized" },
          "404": { "description": "No webhook endpoint is registered for your Order Source yet." }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "ApiKeyAuth": {
        "type": "apiKey",
        "in": "header",
        "name": "X-Api-Key",
        "description": "Format: key_ followed by 64 lowercase hex characters. See the integration guide Section 2."
      }
    },
    "parameters": {
      "PlatformOrderId": {
        "name": "platformOrderId",
        "in": "path",
        "required": true,
        "schema": { "type": "string", "format": "uuid" },
        "description": "The FleetBridge order identifier returned by Create."
      }
    },
    "responses": {
      "BadRequest": {
        "description": "Validation failure.",
        "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ProblemDetails" } } }
      },
      "Unauthorized": {
        "description": "Missing/invalid/expired/revoked API key. Empty body — not a ProblemDetails object. See the integration guide Section 2.5."
      },
      "Forbidden": {
        "description": "Authenticated, but your Order Source or Tenant cannot act right now.",
        "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ProblemDetails" } } }
      },
      "NotFound": {
        "description": "The order does not exist, or does not belong to your Order Source.",
        "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ProblemDetails" } } }
      },
      "Conflict": {
        "description": "The request is well-formed but conflicts with the order's current state.",
        "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ProblemDetails" } } }
      },
      "TooManyRequests": {
        "description": "Rate limited. Respect the Retry-After header.",
        "headers": { "Retry-After": { "schema": { "type": "integer" }, "description": "Seconds to wait before retrying." } },
        "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/ProblemDetails" } } }
      }
    },
    "schemas": {
      "ProblemDetails": {
        "type": "object",
        "properties": {
          "status": { "type": "integer" },
          "title": { "type": "string" },
          "detail": { "type": "string" },
          "errorCode": { "type": "string" },
          "details": { "type": "object", "additionalProperties": true, "nullable": true },
          "correlationId": { "type": "string", "nullable": true }
        },
        "required": ["status", "title", "detail", "errorCode"]
      },
      "PaymentMethod": { "type": "string", "enum": ["Cash", "Card", "Online", "Wallet", "Other"] },
      "OrderStatus": {
        "type": "string",
        "enum": [
          "Created", "Scheduled", "PendingRouting", "Dispatching", "InDelivery",
          "CancellationRequested", "ReturnInProgress", "Delivered", "Cancelled", "Failed",
          "NoProviderAvailable", "ManualReviewRequired"
        ]
      },
      "UnifiedDeliveryStatus": {
        "type": "string",
        "enum": [
          "SentToProvider", "ProviderAccepted", "DriverAssigned", "ArrivedAtPickup", "PickedUp",
          "OnTheWay", "Delivered", "Cancelled", "Failed", "ReturnRequested", "ReturningToOrigin",
          "ReturnedToOrigin", "ReturnFailed"
        ]
      },
      "SlaStatus": {
        "type": "string",
        "enum": ["OnTrack", "AtRisk", "Breached", "CompletedWithinSla", "CompletedBreached", "NotApplicable"]
      },
      "RoutingMode": { "type": "string", "enum": ["DefaultOnly", "ManualProvider", "PriorityFailover", "BroadcastToAll"] },
      "TrackingEventSource": { "type": "string", "enum": ["Webhook", "Polling", "Platform"] },
      "PropagationStatus": { "type": "string", "enum": ["Propagated", "NotSupportedByProvider", "PropagationFailed", "NotApplicable"] },

      "CreateOrderPickupRequest": {
        "type": "object",
        "required": ["address", "lat", "lng"],
        "properties": {
          "address": { "type": "string", "maxLength": 500 },
          "lat": { "type": "number", "format": "double", "minimum": -90, "maximum": 90 },
          "lng": { "type": "number", "format": "double", "minimum": -180, "maximum": 180 }
        }
      },
      "CreateOrderDropoffRequest": {
        "type": "object",
        "required": ["customerName", "customerPhone", "address", "lat", "lng"],
        "properties": {
          "customerName": { "type": "string", "maxLength": 200 },
          "customerPhone": { "type": "string", "maxLength": 50 },
          "customerEmail": { "type": "string", "maxLength": 320, "nullable": true },
          "address": { "type": "string", "maxLength": 500 },
          "lat": { "type": "number", "format": "double", "minimum": -90, "maximum": 90 },
          "lng": { "type": "number", "format": "double", "minimum": -180, "maximum": 180 }
        }
      },
      "CreateOrderPaymentRequest": {
        "type": "object",
        "required": ["method", "amount", "currency"],
        "properties": {
          "method": { "$ref": "#/components/schemas/PaymentMethod" },
          "methodRaw": { "type": "string", "maxLength": 100, "nullable": true },
          "amount": { "type": "number", "format": "double", "minimum": 0, "maximum": 9999999999.99 },
          "deliveryFee": { "type": "number", "format": "double", "minimum": 0, "maximum": 9999999999.99, "nullable": true },
          "currency": { "type": "string", "maxLength": 3 }
        }
      },
      "CreateOrderRequest": {
        "type": "object",
        "required": ["externalOrderId", "pickup", "dropoff", "payment", "preparationTimeMinutes"],
        "properties": {
          "externalOrderId": { "type": "string", "maxLength": 200, "description": "Technical order identifier: the correlation, lookup, and de-dup key. Unique within the Order Source." },
          "externalOrderNumber": { "type": "string", "maxLength": 200, "nullable": true, "description": "Human-readable order number for display and as the Delivery Provider's visible order reference. Not unique; never a correlation, lookup, de-dup, or idempotency key. Omitted or blank falls back to externalOrderId. Set at create only." },
          "branchId": { "type": "string", "format": "uuid", "nullable": true },
          "externalBranchId": { "type": "string", "nullable": true },
          "deliveryProviderCode": { "type": "string", "nullable": true },
          "scheduledDeliveryAt": { "type": "string", "format": "date-time", "nullable": true, "description": "ISO 8601 with an explicit UTC offset. Omit or null for an immediate order." },
          "pickup": { "$ref": "#/components/schemas/CreateOrderPickupRequest" },
          "dropoff": { "$ref": "#/components/schemas/CreateOrderDropoffRequest" },
          "payment": { "$ref": "#/components/schemas/CreateOrderPaymentRequest" },
          "preparationTimeMinutes": { "type": "integer", "minimum": 0 },
          "notes": { "type": "string", "maxLength": 2000, "nullable": true }
        }
      },
      "CreateOrderResult": {
        "type": "object",
        "properties": {
          "platformOrderId": { "type": "string", "format": "uuid" },
          "externalOrderId": { "type": "string" },
          "externalOrderNumber": { "type": "string", "description": "Display order number; equals externalOrderId when none was supplied." },
          "status": { "$ref": "#/components/schemas/OrderStatus" },
          "branchId": { "type": "string", "format": "uuid" },
          "routingMode": { "$ref": "#/components/schemas/RoutingMode" },
          "createdAt": { "type": "string", "format": "date-time" }
        }
      },

      "UpdateOrderDropoffRequest": {
        "type": "object",
        "description": "Every field is independently optional — patching the address alone does not reset lat/lng.",
        "properties": {
          "address": { "type": "string", "maxLength": 500 },
          "lat": { "type": "number", "format": "double" },
          "lng": { "type": "number", "format": "double" }
        }
      },
      "UpdateOrderRequest": {
        "type": "object",
        "description": "Every top-level field is optional. Omitted = unchanged. Explicit null on a nullable field = cleared. A value = set. See the integration guide Section 11.1.",
        "properties": {
          "customerName": { "type": "string", "maxLength": 200 },
          "customerPhone": { "type": "string", "maxLength": 50 },
          "customerEmail": { "type": "string", "maxLength": 320, "nullable": true },
          "dropoff": { "$ref": "#/components/schemas/UpdateOrderDropoffRequest" },
          "notes": { "type": "string", "maxLength": 2000, "nullable": true },
          "paymentMethod": { "$ref": "#/components/schemas/PaymentMethod" },
          "paymentMethodRaw": { "type": "string", "maxLength": 100, "nullable": true },
          "amount": { "type": "number", "format": "double" },
          "deliveryFee": { "type": "number", "format": "double", "nullable": true },
          "currency": { "type": "string", "maxLength": 3 },
          "preparationTimeMinutes": { "type": "integer" },
          "scheduledDeliveryAt": { "type": "string", "format": "date-time", "nullable": true }
        }
      },
      "UpdateOrderResult": {
        "type": "object",
        "description": "FleetBridge always persists the update on its own side first; each field below reports whether that specific field was also propagated to the active Delivery Provider.",
        "properties": {
          "orderId": { "type": "string", "format": "uuid" },
          "addressPropagation": { "$ref": "#/components/schemas/PropagationStatus" },
          "phonePropagation": { "$ref": "#/components/schemas/PropagationStatus" },
          "scheduledDeliveryPropagation": { "$ref": "#/components/schemas/PropagationStatus" },
          "notesPropagation": { "$ref": "#/components/schemas/PropagationStatus" },
          "customerNamePropagation": { "$ref": "#/components/schemas/PropagationStatus" },
          "customerEmailPropagation": { "$ref": "#/components/schemas/PropagationStatus" },
          "amountPropagation": { "$ref": "#/components/schemas/PropagationStatus" },
          "currencyPropagation": { "$ref": "#/components/schemas/PropagationStatus" },
          "paymentMethodPropagation": { "$ref": "#/components/schemas/PropagationStatus" },
          "deliveryFeePropagation": { "$ref": "#/components/schemas/PropagationStatus" },
          "preparationTimePropagation": { "$ref": "#/components/schemas/PropagationStatus" }
        }
      },

      "CancelOrderRequest": {
        "type": "object",
        "properties": { "reason": { "type": "string", "maxLength": 500, "nullable": true } }
      },
      "CancelOrderResult": {
        "type": "object",
        "properties": {
          "orderId": { "type": "string", "format": "uuid" },
          "status": { "$ref": "#/components/schemas/OrderStatus" },
          "outcome": { "type": "string", "enum": ["Cancelled", "ConfirmationPending"] }
        }
      },

      "ShipmentSummary": {
        "type": "object",
        "nullable": true,
        "properties": {
          "shipmentId": { "type": "string", "format": "uuid" },
          "platformReference": { "type": "string" },
          "deliveryProviderId": { "type": "string", "format": "uuid" },
          "providerCode": { "type": "string" },
          "unifiedStatus": { "$ref": "#/components/schemas/UnifiedDeliveryStatus" },
          "slaStatus": { "$ref": "#/components/schemas/SlaStatus" }
        }
      },
      "OrderStatusResponse": {
        "type": "object",
        "properties": {
          "platformOrderId": { "type": "string", "format": "uuid" },
          "orderStatus": { "$ref": "#/components/schemas/OrderStatus" },
          "delivery": { "$ref": "#/components/schemas/ShipmentSummary" }
        }
      },
      "OrderDetail": {
        "type": "object",
        "properties": {
          "platformOrderId": { "type": "string", "format": "uuid" },
          "externalOrderId": { "type": "string" },
          "externalOrderNumber": { "type": "string", "description": "Display order number; equals externalOrderId when none was supplied." },
          "orderSourceId": { "type": "string", "format": "uuid" },
          "branchId": { "type": "string", "format": "uuid" },
          "orderStatus": { "$ref": "#/components/schemas/OrderStatus" },
          "routingMode": { "$ref": "#/components/schemas/RoutingMode" },
          "isManualDispatch": { "type": "boolean" },
          "isTest": { "type": "boolean" },
          "customerName": { "type": "string" },
          "customerPhone": { "type": "string" },
          "customerEmail": { "type": "string", "nullable": true },
          "pickupAddress": { "type": "string" },
          "dropoffAddress": { "type": "string" },
          "paymentMethod": { "$ref": "#/components/schemas/PaymentMethod" },
          "amount": { "type": "number", "format": "double" },
          "deliveryFee": { "type": "number", "format": "double", "nullable": true },
          "currency": { "type": "string" },
          "notes": { "type": "string", "nullable": true },
          "scheduledDeliveryAt": { "type": "string", "format": "date-time", "nullable": true },
          "createdAt": { "type": "string", "format": "date-time" },
          "deliveredAt": { "type": "string", "format": "date-time", "nullable": true },
          "cancelledAt": { "type": "string", "format": "date-time", "nullable": true },
          "failedAt": { "type": "string", "format": "date-time", "nullable": true },
          "delivery": { "$ref": "#/components/schemas/ShipmentSummary" }
        }
      },
      "OrderTracking": {
        "type": "object",
        "properties": {
          "platformOrderId": { "type": "string", "format": "uuid" },
          "shipmentId": { "type": "string", "format": "uuid", "nullable": true },
          "unifiedStatus": { "$ref": "#/components/schemas/UnifiedDeliveryStatus" },
          "driverName": { "type": "string", "nullable": true },
          "driverPhone": { "type": "string", "nullable": true },
          "driverLat": { "type": "number", "format": "double", "nullable": true },
          "driverLng": { "type": "number", "format": "double", "nullable": true },
          "driverLocationUpdatedAt": { "type": "string", "format": "date-time", "nullable": true },
          "trackingUrl": { "type": "string", "nullable": true },
          "currentEta": { "type": "string", "format": "date-time", "nullable": true }
        }
      },
      "TrackingHistoryEntry": {
        "type": "object",
        "description": "providerStatus and providerCorrelationId are opaque, best-effort diagnostic text from the Delivery Provider's own raw event — not a stable contract. Build logic against `status`, never against these two fields.",
        "properties": {
          "eventTimeUtc": { "type": "string", "format": "date-time" },
          "receivedAtUtc": { "type": "string", "format": "date-time" },
          "status": { "$ref": "#/components/schemas/UnifiedDeliveryStatus" },
          "providerStatus": { "type": "string", "nullable": true },
          "source": { "$ref": "#/components/schemas/TrackingEventSource" },
          "driverName": { "type": "string", "nullable": true },
          "driverPhone": { "type": "string", "nullable": true },
          "driverLat": { "type": "number", "format": "double", "nullable": true },
          "driverLng": { "type": "number", "format": "double", "nullable": true },
          "estimatedDeliveryAtUtc": { "type": "string", "format": "date-time", "nullable": true },
          "providerCorrelationId": { "type": "string", "nullable": true }
        }
      }
    }
  }
}
