openapi: 3.1.0

# The contract for the partner API, and the source for any published reference.
# It is hand-maintained: when you change a handler in index.ts
# or a shape in serializers.ts, change it here in the same commit. A spec that
# lies is worse than no spec, because partners write code against it.

info:
  title: Onus Delivery API
  version: "1.0.0"
  description: |
    Dispatch a courier for a restaurant order.

    Use this API when your platform already takes the order and you want Onus to
    handle the delivery: check price and availability, place the delivery, track
    it, and cancel it.

    **Authentication.** Every request sends an organization API key:

        Authorization: Bearer onus_live_...

    Keys are issued by Onus after your organization and billing are set up. A
    key belongs to one organization and may be restricted to specific stores.
    This is a server-to-server API — the key must never reach a browser or a
    mobile app, and the API deliberately sends no CORS headers.

    **Test mode.** A key beginning `onus_test_` creates orders that are never
    dispatched to a real driver, never text anyone and are never invoiced. Drive
    them through the lifecycle with `POST /v1/orders/{id}/simulate`.

    **Money** is always an integer number of cents, with an explicit currency.
    **Timestamps** are always ISO-8601 UTC.

    **Idempotency.** `POST /v1/orders` requires an `Idempotency-Key` header.
    Retrying with the same key returns the original response instead of
    dispatching a second driver.

servers:
  - url: https://api.onustech.co/functions/v1/restaurant-api/v1
    description: Production

security:
  - ApiKey: []

tags:
  - name: Locations
    description: Your store locations.
  - name: Quotes
    description: Price a delivery before placing it.
  - name: Orders
    description: Place, track and cancel deliveries.
  - name: Webhooks
    description: Receive order events instead of polling.

paths:
  /locations:
    get:
      tags: [Locations]
      summary: List your locations
      responses:
        "200":
          description: Your organization's locations.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/Location" }

  /locations/{external_id}:
    put:
      tags: [Locations]
      summary: Create or update a location
      description: |
        Registers one of your stores under your own identifier, so orders can
        reference it as `location_id` without repeating the address.

        The address is geocoded by Onus; the resulting point is the pickup for
        every order from this store and the origin every fare is measured from.
        If `geocode_status` comes back as anything but `ok`, the store cannot
        take orders yet.

        Safe to call repeatedly — it is an upsert on `external_id`.
      parameters:
        - name: external_id
          in: path
          required: true
          description: Your identifier for this store (1–100 characters).
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, address, city, province]
              properties:
                name: { type: string, example: "Downtown" }
                address: { type: string, example: "10180 101 St NW" }
                city: { type: string, example: "Edmonton" }
                province:
                  type: string
                  description: Two-letter province code.
                  example: "AB"
                phone: { type: string, example: "+17805551234" }
                contact_name: { type: string }
                contact_phone: { type: string }
      responses:
        "200":
          description: Location updated.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Location" }
        "201":
          description: Location created.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Location" }
        "422":
          description: The address could not be geocoded, or the province is not served.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /quotes:
    post:
      tags: [Quotes]
      summary: Price a delivery
      description: |
        Returns the delivery fee and whether Onus can serve the order right now.

        The price is **held for 15 minutes**. Pass the returned `quote_id` to
        `POST /orders` and that exact price is used — even if distances or our
        pricing change in between. A quote can be used once.

        Send `dropoff` coordinates when you have them and they must agree with
        `dropoff_address` (within 250m); omit them and Onus geocodes the address.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [location_id, dropoff_address]
              properties:
                location_id:
                  type: string
                  description: The store's `external_id`.
                dropoff_address: { type: string }
                dropoff: { $ref: "#/components/schemas/LatLng" }
                tip:
                  type: integer
                  description: Optional driver tip, in cents.
      responses:
        "200":
          description: A held price.
          content:
            application/json:
              schema:
                type: object
                properties:
                  quote_id: { type: string, format: uuid }
                  expires_at: { type: string, format: date-time }
                  fare: { $ref: "#/components/schemas/Fare" }
                  serviceable:
                    type: boolean
                    description: Whether an order placed now would be accepted.
                  reason:
                    type: [string, "null"]
                    enum: [closed, no_drivers, province_not_serviced, location_not_geocoded, null]
                  message: { type: string }
                  dropoff:
                    type: object
                    properties:
                      address: { type: string }
                      lat: { type: number }
                      lng: { type: number }
        "422":
          description: Out of range, or the location has no usable address.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /orders:
    post:
      tags: [Orders]
      summary: Place a delivery
      description: |
        Creates the delivery and starts looking for a driver immediately.

        Send either a `quote_id` (recommended — the quoted fee is then the fee
        billed) or `dropoff_address` with optional `dropoff` coordinates.

        Rejected with `service_unavailable` when Onus is closed or no driver is
        available near the store; check `serviceable` on the quote first.
      parameters:
        - name: Idempotency-Key
          in: header
          required: true
          description: |
            A unique value per order — your own order id works well. Retrying
            with the same key returns the original response rather than
            dispatching a second driver.
          schema: { type: string, maxLength: 255 }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [location_id, customer]
              properties:
                location_id: { type: string, description: The store's `external_id`. }
                quote_id: { type: string, format: uuid }
                dropoff_address: { type: string }
                dropoff: { $ref: "#/components/schemas/LatLng" }
                dropoff_unit:
                  type: string
                  description: Apartment, suite or buzzer — shown to the driver.
                customer:
                  type: object
                  required: [name, phone]
                  properties:
                    name: { type: string }
                    phone:
                      type: string
                      description: E.164, e.g. +15875551234.
                delivery_notes: { type: string }
                order_ref:
                  type: string
                  description: |
                    Your order number. Only one active delivery may carry a
                    given reference per store.
                tip: { type: integer, description: Driver tip, in cents. }
                ready_at:
                  type: string
                  format: date-time
                  description: When the food will be ready. Advisory.
      responses:
        "201":
          description: Delivery created.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Order" }
        "409":
          description: |
            Duplicate order, reused idempotency key, or an expired/used quote.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }
        "422":
          description: Not serviceable right now, or the address is unusable.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

    get:
      tags: [Orders]
      summary: List deliveries
      description: |
        Newest first. Page with `cursor`: pass the `next_cursor` from the
        previous response; a null `next_cursor` means there is no more.
      parameters:
        - name: limit
          in: query
          schema: { type: integer, default: 25, maximum: 100 }
        - name: status
          in: query
          description: Comma-separated statuses.
          schema: { type: string, example: "looking_for_driver,driver_assigned" }
        - name: location_id
          in: query
          schema: { type: string }
        - name: order_ref
          in: query
          schema: { type: string }
        - name: created_after
          in: query
          schema: { type: string, format: date-time }
        - name: created_before
          in: query
          schema: { type: string, format: date-time }
        - name: cursor
          in: query
          schema: { type: string, format: date-time }
      responses:
        "200":
          description: A page of deliveries.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/Order" }
                  next_cursor: { type: [string, "null"], format: date-time }

  /orders/{id}:
    get:
      tags: [Orders]
      summary: Retrieve a delivery
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: The delivery.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Order" }
        "404":
          description: No such delivery for this organization.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /orders/{id}/cancel:
    post:
      tags: [Orders]
      summary: Cancel a delivery
      description: |
        Cancellation fees, charged on your invoice:

        | When you cancel | Fee |
        |---|---|
        | Before a driver is assigned | none |
        | Within 5 minutes of assignment | none |
        | More than 5 minutes after assignment, driver not yet at the restaurant | $5 |
        | After the driver has reached the restaurant | the full delivery fee |

        Once the driver has collected the food the delivery can no longer be
        cancelled here; contact Onus support.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      requestBody:
        content:
          application/json:
            schema:
              type: object
              properties:
                reason: { type: string }
      responses:
        "200":
          description: Cancelled.
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string, format: uuid }
                  status: { type: string, enum: [cancelled] }
                  cancellation_fee:
                    type: integer
                    description: Fee incl. tax, in cents. 0 when free.
                  fee_reason:
                    type: string
                    enum: [no_driver_assigned, within_grace_period, after_grace_period, driver_at_pickup, test_mode]
        "409":
          description: Already terminal, or the driver already has the food.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /orders/{id}/simulate:
    post:
      tags: [Orders]
      summary: Advance a test delivery
      description: |
        **Test keys only.** Moves the delivery to the next status
        (`looking_for_driver` → `driver_assigned` → `en_route_pickup` →
        `en_route_dropoff` → `completed`) and fires the matching webhook, so you
        can build against every state without a driver.
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string, format: uuid }
      responses:
        "200":
          description: The delivery, advanced.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Order" }
        "403":
          description: Not a test key.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

  /webhook-endpoints:
    get:
      tags: [Webhooks]
      summary: List webhook endpoints
      responses:
        "200":
          description: Your endpoints.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items: { $ref: "#/components/schemas/WebhookEndpoint" }
    post:
      tags: [Webhooks]
      summary: Register a webhook endpoint
      description: |
        The signing `secret` is returned **once**, here. Verify every delivery:

            Onus-Signature: t=<unix seconds>,v1=<hex>

        where `v1` is HMAC-SHA256 of `"<t>.<raw request body>"` using the
        secret. Compare with a constant-time comparison and reject timestamps
        that are more than a few minutes old.

        Deliveries are retried on any non-2xx response (30s, 2m, 10m, 1h, 6h).
        Respond 2xx as soon as you have stored the event; do your work
        afterwards. Retries and at-least-once delivery mean you may see an event
        twice — deduplicate on `Onus-Event-Id`.

        An endpoint registered with a test key receives test-mode events only.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url]
              properties:
                url: { type: string, format: uri, description: Must be https. }
                events:
                  type: array
                  description: Empty or omitted means every event type.
                  items:
                    type: string
                    enum:
                      - order.created
                      - order.driver_assigned
                      - order.driver_arrived_pickup
                      - order.picked_up
                      - order.delivered
                      - order.cancelled
                description: { type: string }
      responses:
        "201":
          description: Endpoint registered; `secret` is shown only in this response.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: "#/components/schemas/WebhookEndpoint"
                  - type: object
                    properties:
                      secret: { type: string }

  /webhook-endpoints/{id}:
    delete:
      tags: [Webhooks]
      summary: Remove a webhook endpoint
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
      responses:
        "204": { description: Removed. }
        "404":
          description: No such endpoint.
          content:
            application/json:
              schema: { $ref: "#/components/schemas/Error" }

components:
  securitySchemes:
    ApiKey:
      type: http
      scheme: bearer
      description: Your Onus API key, `onus_live_…` or `onus_test_…`.

  schemas:
    LatLng:
      type: object
      required: [lat, lng]
      properties:
        lat: { type: number }
        lng: { type: number }

    Fare:
      type: object
      properties:
        currency: { type: string, example: CAD }
        total: { type: integer, description: Everything, in cents. }
        delivery_fee: { type: integer, description: Pre-tax delivery fee, in cents. }
        tax: { type: integer }
        tip: { type: integer }
        distance_km: { type: number }
        federal_tax: { type: integer }
        provincial_tax: { type: integer }

    Location:
      type: object
      properties:
        id: { type: string, description: Your `external_id` for the store. }
        external_id: { type: [string, "null"] }
        name: { type: string }
        address: { type: string }
        city: { type: string }
        phone: { type: [string, "null"] }
        geocode_status:
          type: string
          enum: [pending, ok, failed]
          description: Only `ok` locations can take orders.
        lat: { type: [number, "null"] }
        lng: { type: [number, "null"] }
        created_at: { type: string, format: date-time }

    Order:
      type: object
      properties:
        id: { type: string, format: uuid }
        status:
          type: string
          enum: [looking_for_driver, driver_assigned, en_route_pickup, en_route_dropoff, completed, cancelled]
          description: |
            `en_route_pickup` means the driver has reached the restaurant;
            `en_route_dropoff` means they have the food and are on the way.
        order_ref: { type: [string, "null"] }
        is_test: { type: boolean }
        location:
          type: object
          properties:
            id: { type: string }
            name: { type: [string, "null"] }
        customer:
          type: object
          properties:
            name: { type: string }
            phone: { type: string }
        pickup:
          type: object
          properties:
            address: { type: string }
            lat: { type: [number, "null"] }
            lng: { type: [number, "null"] }
        dropoff:
          type: object
          properties:
            address: { type: string }
            unit: { type: [string, "null"] }
            lat: { type: [number, "null"] }
            lng: { type: [number, "null"] }
            notes: { type: [string, "null"] }
        ready_at: { type: [string, "null"], format: date-time }
        fare: { $ref: "#/components/schemas/Fare" }
        cancellation:
          type: [object, "null"]
          properties:
            reason: { type: [string, "null"] }
            cancelled_by:
              type: string
              enum: [restaurant, partner, onus, system]
            fee: { type: integer, description: Incl. tax, in cents. }
        driver:
          type: [object, "null"]
          description: Present once a driver is assigned.
          properties:
            first_name: { type: string }
            location:
              type: [object, "null"]
              description: Live position; null once the delivery ends.
              properties:
                lat: { type: number }
                lng: { type: number }
                at: { type: [string, "null"], format: date-time }
        eta:
          type: "null"
          description: Reserved; always null today.
        proof_of_delivery_url:
          type: "null"
          description: Reserved; always null today.
        timeline:
          type: object
          properties:
            created_at: { type: string, format: date-time }
            driver_assigned_at: { type: [string, "null"], format: date-time }
            driver_arrived_pickup_at: { type: [string, "null"], format: date-time }
            picked_up_at: { type: [string, "null"], format: date-time }
            driver_arrived_dropoff_at: { type: [string, "null"], format: date-time }
            delivered_at: { type: [string, "null"], format: date-time }
            cancelled_at: { type: [string, "null"], format: date-time }
        tracking_url:
          type: [string, "null"]
          description: Public page your customer can watch. Asks for the last 4 digits of their phone number.

    WebhookEndpoint:
      type: object
      properties:
        id: { type: string }
        url: { type: string }
        events:
          type: array
          items: { type: string }
        environment: { type: string, enum: [live, test] }
        description: { type: [string, "null"] }
        disabled_at:
          type: [string, "null"]
          format: date-time
          description: Set after repeated delivery failures.
        last_success_at: { type: [string, "null"], format: date-time }
        last_failure_at: { type: [string, "null"], format: date-time }
        created_at: { type: string, format: date-time }

    Error:
      type: object
      properties:
        error:
          type: object
          properties:
            code:
              type: string
              description: |
                Stable machine-readable code. Branch on this, not on `message`.

                Common codes: `unauthenticated`, `ip_not_allowed`,
                `rate_limited`, `daily_cap_reached`, `validation_error`,
                `idempotency_key_required`, `idempotency_key_reused`,
                `idempotency_conflict`, `duplicate_order`, `quote_expired`,
                `quote_already_used`, `quote_mismatch`, `address_mismatch`,
                `address_not_found`, `service_unavailable`, `out_of_range`,
                `not_found`, `invalid_state`, `too_late_to_cancel`,
                `test_mode_only`, `internal_error`.
            message:
              type: string
              description: Human-readable, for your logs. May change.
            request_id:
              type: string
              description: Quote this to Onus support.
