# API reference

Base URL: `https://api.armadadelivery.com`

Use an API key and secret. The SDKs handle request signing; see [Authentication](https://docs.armadadelivery.com/v2/authentication.md) for custom clients.

- **POST /v2/deliveries** — Create a delivery
- **GET /v2/deliveries/{id}** — Retrieve a delivery
- **POST /v2/deliveries/{id}/cancel** — Cancel a delivery
- **POST /v2/deliveries/estimate** — Estimate a delivery fee
- **POST /v2/deliveries/estimate/static** — Estimate a delivery fee with a fixed pickup allowance
- **GET /v2/branches** — List branches
- **POST /v2/branches** — Create a branch
- **GET /v2/branches/{id}** — Get a branch
- **PUT /v2/branches/{id}** — Update a branch
- **DELETE /v2/branches/{id}** — Delete a branch
- **GET /v2/wallet** — Get wallet balance
- **GET /v2/invoices** — List invoices
- **GET /v2/invoices/{id}** — Get an invoice

## Complete OpenAPI specification

```yaml
openapi: 3.1.0
info:
  title: Armada Automated Ordering API
  version: 2.0.0
  summary: Merchant-authenticated v2 API for creating and tracking Armada deliveries.
  description: |
    Create deliveries, manage pickup branches and read wallet and invoice records.
    Each API key belongs to one merchant. The SDK examples handle request signing.

    Start with the [quickstart](https://docs.armadadelivery.com/v2/quickstart/) or [authentication guide](https://docs.armadadelivery.com/v2/authentication/).
  contact:
    name: Armada API support
    email: support@armadadelivery.com
    url: https://docs.armadadelivery.com
  license:
    name: Proprietary
    identifier: LicenseRef-Armada-Proprietary
servers:
  - url: https://api.armadadelivery.com
    description: API for live and simulated deliveries. See /v2/test-mode/ for test key setup.

security:
  - ApiKeyAuth: []
    TimestampAuth: []
    SignatureAuth: []

tags:
  - name: Deliveries
    description: Create, track, cancel and estimate deliveries.
  - name: Branches
    description: Manage the merchant's pickup locations.
  - name: Wallet
    description: Inspect the prepaid wallet balance.
  - name: Invoices
    description: Consult generated invoices.

paths:
  /v2/deliveries:
    post:
      tags: [ Deliveries ]
      summary: Create a delivery
      description: |-
        Requires `delivery:write`.

        Each successful create request creates a new delivery, including requests
        that reuse the same reference. After a timeout, confirm the outcome before resubmitting.
        With a delivery webhook URL saved, creation waits for its initial pending
        callback response. Return 2xx promptly from the receiver.

        See [Webhooks](https://docs.armadadelivery.com/v2/webhooks.md) for receiver
        authentication and event handling.
      operationId: createDelivery
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/DeliveryRequest' }
            example:
              reference: YOUR_UNIQUE_ORDER_REFERENCE
              payment:
                amount: 4.5
                type: paid
              origin_format: branch_format
              origin:
                branch_id: YOUR_BRANCH_ID
              destination_format: location_format
              destination:
                contact_name: Test Customer
                contact_phone: "+96590000000"
                latitude: 29.3759
                longitude: 47.9774
                first_line: Salmiya, Block 5, Street 3
      responses:
        '200':
          description: Delivery created.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Delivery' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
      x-codeSamples:
        - lang: JavaScript
          label: Node SDK
          source: |
            import { ArmadaClient } from '@armada/sdk';

            const armada = new ArmadaClient({
              baseUrl: 'https://api.armadadelivery.com',
              apiKey: process.env.ARMADA_API_KEY,
              apiSecret: process.env.ARMADA_API_SECRET,
            });

            const { data } = await armada.deliveries.create({
              "reference": "YOUR_UNIQUE_ORDER_REFERENCE",
              "payment": {
                "amount": 4.5,
                "type": "paid"
              },
              "origin_format": "branch_format",
              "origin": {
                "branch_id": "YOUR_BRANCH_ID"
              },
              "destination_format": "location_format",
              "destination": {
                "contact_name": "Test Customer",
                "contact_phone": "+96590000000",
                "latitude": 29.3759,
                "longitude": 47.9774,
                "first_line": "Salmiya, Block 5, Street 3"
              }
            });
            console.log(data);

  /v2/deliveries/{id}:
    parameters:
      - { $ref: '#/components/parameters/DeliveryCode' }
    get:
      tags: [ Deliveries ]
      summary: Retrieve a delivery
      operationId: getDelivery
      responses:
        '200':
          description: OK
          content: { application/json: { schema: { $ref: '#/components/schemas/Delivery' } } }
        '404': { $ref: '#/components/responses/NotFound' }
      x-codeSamples:
        - lang: JavaScript
          label: Node SDK
          source: |
            import { ArmadaClient } from '@armada/sdk';

            const armada = new ArmadaClient({
              baseUrl: 'https://api.armadadelivery.com',
              apiKey: process.env.ARMADA_API_KEY,
              apiSecret: process.env.ARMADA_API_SECRET,
            });

            const { data } = await armada.deliveries.get('D000000001');
            console.log(data);
      description: |-
        Requires `delivery:read`.

        Retrieve a delivery created through this API using its returned code.

  /v2/deliveries/{id}/cancel:
    parameters:
      - { $ref: '#/components/parameters/DeliveryCode' }
    post:
      tags: [ Deliveries ]
      summary: Cancel a delivery
      description: |-
        Requires `delivery:cancel`.

        Use the delivery code as the path identifier. Cancellation
        depends on order and trip state and the merchant's cancellation policy.
        Simulated test deliveries can be canceled at dispatched, accepted and
        en_route. Cancellation stops the simulator for that delivery. An optional
        reason is kept on the first cancellation. Repeated cancellation of a
        canceled delivery, or cancellation of an already failed delivery, returns
        its current state. Completed deliveries return 400. A test-mode 409 means
        the delivery changed during cancellation; retrieve it before retrying.
        After a timeout or error, retrieve the delivery to confirm its current state.
      operationId: cancelDelivery
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                reason: { type: string, description: 'Optional free-text cancellation reason.' }
            example:
              reason: Customer requested cancellation
      responses:
        '200':
          description: Current delivery representation. A canceled delivery has status canceled; an already failed delivery is returned unchanged.
          content: { application/json: { schema: { $ref: '#/components/schemas/Delivery' } } }
        '404':
          description: Delivery code not found.
          content: { application/json: { schema: { type: string }, example: 'Entity not found !' } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '409':
          description: Test delivery changed during cancellation. Retrieve it and retry only if it still needs cancellation.
          content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
      x-codeSamples:
        - lang: JavaScript
          label: Node SDK
          source: |
            import { ArmadaClient } from '@armada/sdk';

            const armada = new ArmadaClient({
              baseUrl: 'https://api.armadadelivery.com',
              apiKey: process.env.ARMADA_API_KEY,
              apiSecret: process.env.ARMADA_API_SECRET,
            });

            const { data } = await armada.deliveries.cancel('D000000001', 'Customer requested cancellation');
            console.log(data);

  /v2/deliveries/estimate:
    post:
      tags: [ Deliveries ]
      summary: Estimate a delivery fee
      operationId: estimateDelivery
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/EstimateRequest' }
            example:
              origin_format: branch_format
              origin:
                branch_id: YOUR_BRANCH_ID
              destination_format: location_format
              destination:
                latitude: 29.3759
                longitude: 47.9774
      responses:
        '200':
          description: Estimate returned.
          content: { application/json: { schema: { $ref: '#/components/schemas/LiveEstimate' } } }
        '400': { $ref: '#/components/responses/BadRequest' }
      x-codeSamples:
        - lang: JavaScript
          label: Node SDK
          source: |
            import { ArmadaClient } from '@armada/sdk';

            const armada = new ArmadaClient({
              baseUrl: 'https://api.armadadelivery.com',
              apiKey: process.env.ARMADA_API_KEY,
              apiSecret: process.env.ARMADA_API_SECRET,
            });

            const { data } = await armada.deliveries.estimate({
              "origin_format": "branch_format",
              "origin": {
                "branch_id": "YOUR_BRANCH_ID"
              },
              "destination_format": "location_format",
              "destination": {
                "latitude": 29.3759,
                "longitude": 47.9774
              }
            });
            console.log(data);
      description: |-
        Requires `delivery:write`.

        Returns the fee and estimated pickup and delivery timestamps. Both timestamps
        can be null when an ETA is unavailable. The destination uses location_format;
        contact details are not required for estimates.

  /v2/deliveries/estimate/static:
    post:
      tags: [ Deliveries ]
      summary: Estimate a delivery fee with a fixed pickup allowance
      operationId: estimateDeliveryStatic
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/EstimateRequest' }
            example:
              origin_format: branch_format
              origin:
                branch_id: YOUR_BRANCH_ID
              destination_format: location_format
              destination:
                latitude: 29.3759
                longitude: 47.9774
      responses:
        '200':
          description: Estimate returned.
          content: { application/json: { schema: { $ref: '#/components/schemas/StaticEstimate' } } }
        '400': { $ref: '#/components/responses/BadRequest' }
      x-codeSamples:
        - lang: JavaScript
          label: Node SDK
          source: |
            import { ArmadaClient } from '@armada/sdk';

            const armada = new ArmadaClient({
              baseUrl: 'https://api.armadadelivery.com',
              apiKey: process.env.ARMADA_API_KEY,
              apiSecret: process.env.ARMADA_API_SECRET,
            });

            const { data } = await armada.deliveries.estimateStatic({
              "origin_format": "branch_format",
              "origin": {
                "branch_id": "YOUR_BRANCH_ID"
              },
              "destination_format": "location_format",
              "destination": {
                "latitude": 29.3759,
                "longitude": 47.9774
              }
            });
            console.log(data);
      description: |-
        Requires `delivery:write`.

        Returns durations in seconds using a fixed pickup allowance. Fee calculation
        uses the route and merchant pricing. Field names differ from the live estimate.

  /v2/branches:
    get:
      tags: [ Branches ]
      summary: List branches
      operationId: listBranches
      parameters:
        - { name: page, in: query, schema: { type: integer, minimum: 1, default: 1 } }
        - { name: limit, in: query, schema: { type: integer, minimum: 1, default: 30 } }
        - { name: sort_by, in: query, schema: { type: string, enum: [ created_at, name ], default: created_at } }
        - { name: sort_order, in: query, schema: { type: string, enum: [ asc, desc ], default: desc } }
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  branches:
                    type: array
                    items: { $ref: '#/components/schemas/Branch' }
                  page: { type: integer }
                  limit: { type: integer }
                  sort_by: { type: string }
                  sort_order: { type: string }
                  total_pages: { type: integer }
                  total_count: { type: integer }
      x-codeSamples:
        - lang: JavaScript
          label: Node SDK
          source: |
            import { ArmadaClient } from '@armada/sdk';

            const armada = new ArmadaClient({
              baseUrl: 'https://api.armadadelivery.com',
              apiKey: process.env.ARMADA_API_KEY,
              apiSecret: process.env.ARMADA_API_SECRET,
            });

            const { data } = await armada.branches.list();
            console.log(data);
      description: Requires `branch:read`.
    post:
      tags: [ Branches ]
      summary: Create a branch
      operationId: createBranch
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/BranchInput' }
            example:
              name: Main branch
              phone: "+96590000000"
              latitude: 29.3359
              longitude: 48.0758
      responses:
        '200':
          description: Branch created.
          content: { application/json: { schema: { $ref: '#/components/schemas/Branch' } } }
        '400': { $ref: '#/components/responses/BadRequest' }
      x-codeSamples:
        - lang: JavaScript
          label: Node SDK
          source: |
            import { ArmadaClient } from '@armada/sdk';

            const armada = new ArmadaClient({
              baseUrl: 'https://api.armadadelivery.com',
              apiKey: process.env.ARMADA_API_KEY,
              apiSecret: process.env.ARMADA_API_SECRET,
            });

            const { data } = await armada.branches.create({
              "name": "Main branch",
              "phone": "+96590000000",
              "latitude": 29.3359,
              "longitude": 48.0758
            });
            console.log(data);
      description: Requires `branch:write`.

  /v2/branches/{id}:
    parameters:
      - { $ref: '#/components/parameters/BranchId' }
    get:
      tags: [ Branches ]
      summary: Get a branch
      operationId: getBranch
      responses:
        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/Branch' } } } }
        '404': { $ref: '#/components/responses/NotFound' }
      x-codeSamples:
        - lang: JavaScript
          label: Node SDK
          source: |
            import { ArmadaClient } from '@armada/sdk';

            const armada = new ArmadaClient({
              baseUrl: 'https://api.armadadelivery.com',
              apiKey: process.env.ARMADA_API_KEY,
              apiSecret: process.env.ARMADA_API_SECRET,
            });

            const { data } = await armada.branches.get('YOUR_BRANCH_ID');
            console.log(data);
      description: Requires `branch:read`.
    put:
      tags: [ Branches ]
      summary: Update a branch
      description: |-
        Requires `branch:update`.

        Partial update. Send latitude and longitude together when changing coordinates;
        the address is resolved from those coordinates. Send only changed fields;
        resubmitting the current branch name returns 400.
      operationId: updateBranch
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/BranchUpdate' }, example: { name: Updated branch, latitude: 29.3359, longitude: 48.0758 } } }
      responses:
        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/Branch' } } } }
        '400': { $ref: '#/components/responses/BadRequest' }
        '404': { $ref: '#/components/responses/NotFound' }
      x-codeSamples:
        - lang: JavaScript
          label: Node SDK
          source: |
            import { ArmadaClient } from '@armada/sdk';

            const armada = new ArmadaClient({
              baseUrl: 'https://api.armadadelivery.com',
              apiKey: process.env.ARMADA_API_KEY,
              apiSecret: process.env.ARMADA_API_SECRET,
            });

            const { data } = await armada.branches.update('YOUR_BRANCH_ID', {
              "name": "Updated branch",
              "latitude": 29.3359,
              "longitude": 48.0758
            });
            console.log(data);
    delete:
      tags: [ Branches ]
      summary: Delete a branch
      operationId: deleteBranch
      responses:
        '204': { description: Deleted }
        '404': { $ref: '#/components/responses/NotFound' }
      x-codeSamples:
        - lang: JavaScript
          label: Node SDK
          source: |
            import { ArmadaClient } from '@armada/sdk';

            const armada = new ArmadaClient({
              baseUrl: 'https://api.armadadelivery.com',
              apiKey: process.env.ARMADA_API_KEY,
              apiSecret: process.env.ARMADA_API_SECRET,
            });

            const { data } = await armada.branches.delete('YOUR_BRANCH_ID');
            console.log(data);
      description: Requires `branch:delete`.

  /v2/wallet:
    get:
      tags: [ Wallet ]
      summary: Get wallet balance
      operationId: getWallet
      responses:
        '200':
          description: OK
          content: { application/json: { schema: { $ref: '#/components/schemas/Wallet' } } }
      x-codeSamples:
        - lang: JavaScript
          label: Node SDK
          source: |
            import { ArmadaClient } from '@armada/sdk';

            const armada = new ArmadaClient({
              baseUrl: 'https://api.armadadelivery.com',
              apiKey: process.env.ARMADA_API_KEY,
              apiSecret: process.env.ARMADA_API_SECRET,
            });

            const { data } = await armada.wallet.get();
            console.log(data);
      description: Requires `wallet:read`.

  /v2/invoices:
    get:
      tags: [ Invoices ]
      summary: List invoices
      operationId: listInvoices
      parameters:
        - { name: page, in: query, schema: { type: integer, minimum: 1, default: 1 } }
        - { name: perPage, in: query, schema: { type: integer, minimum: 1, maximum: 100, default: 20 } }
        - name: status
          in: query
          description: |-
            Selects a group; read each invoice's status to determine payment state.
            - unpaid: issued or sent, for regular and wallet types.
            - paid: paid or pending, for regular and wallet types.
            - topup: paid, pending, canceled or authorized, for tap_wallet invoices.
            - all (default): issued, sent, pending or paid, across invoice types.
          schema: { type: string, enum: [ unpaid, paid, topup, all ], default: all }
        - { name: periodBegin, in: query, schema: { type: string, format: date } }
        - { name: periodEnd, in: query, schema: { type: string, format: date } }
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: object
                properties:
                  page: { type: integer }
                  perPage: { type: integer }
                  total: { type: integer }
                  invoices:
                    type: array
                    items: { $ref: '#/components/schemas/Invoice' }
        '403': { $ref: '#/components/responses/Forbidden' }
      x-codeSamples:
        - lang: JavaScript
          label: Node SDK
          source: |
            import { ArmadaClient } from '@armada/sdk';

            const armada = new ArmadaClient({
              baseUrl: 'https://api.armadadelivery.com',
              apiKey: process.env.ARMADA_API_KEY,
              apiSecret: process.env.ARMADA_API_SECRET,
            });

            const { data } = await armada.invoices.list({ page: 1, perPage: 10 });
            console.log(data);
      description: |-
        Requires `invoices:read`.

        Use an invoice's _id to retrieve it. Only documented fields are part of the
        public contract; ignore additional fields.

  /v2/invoices/{id}:
    parameters:
      - name: id
        in: path
        required: true
        schema: { type: string, pattern: '^[a-f0-9]{24}$' }
    get:
      tags: [ Invoices ]
      summary: Get an invoice
      operationId: getInvoice
      responses:
        '200':
          description: OK
          content: { application/json: { schema: { $ref: '#/components/schemas/Invoice' } } }
        '404': { $ref: '#/components/responses/NotFound' }
      x-codeSamples:
        - lang: JavaScript
          label: Node SDK
          source: |
            import { ArmadaClient } from '@armada/sdk';

            const armada = new ArmadaClient({
              baseUrl: 'https://api.armadadelivery.com',
              apiKey: process.env.ARMADA_API_KEY,
              apiSecret: process.env.ARMADA_API_SECRET,
            });

            const { data } = await armada.invoices.get('YOUR_INVOICE_ID');
            console.log(data);
      description: Requires `invoices:read`.

webhooks:
  orderUpdated:
    post:
      summary: order.updated
      description: |
        Delivery status notification. Before updating your application, verify
        current state through a signed GET /v2/deliveries/{id} request. Callbacks
        are unsigned and use a single delivery attempt. Handle out-of-order arrival.
        See the [webhook guide](https://docs.armadadelivery.com/v2/webhooks.md#receiver-authentication).
      security: []
      parameters:
        - { $ref: '#/components/parameters/WebhookTopic' }
        - { $ref: '#/components/parameters/WebhookKeyId' }
        - { $ref: '#/components/parameters/WebhookId' }
        - { $ref: '#/components/parameters/WebhookTimestamp' }
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/Delivery' } } }
      responses:
        '2XX': { description: Receiver accepted the callback. Persist it before acknowledgment. }
  orderLocationUpdated:
    post:
      summary: order.location.updated
      description: Location notification while en_route. Multiple updates can share an initial webhook ID and timestamp. Verify current delivery state through a signed GET /v2/deliveries/{id} request.
      security: []
      parameters:
        - { $ref: '#/components/parameters/WebhookTopic' }
        - { $ref: '#/components/parameters/WebhookKeyId' }
        - { $ref: '#/components/parameters/WebhookId' }
        - { $ref: '#/components/parameters/WebhookTimestamp' }
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/LocationWebhook' } } }
      responses:
        '2XX': { description: Receiver accepted the callback. }
  walletBalanceLow:
    post:
      summary: wallet.balance_low
      description: Low-balance notification. The warning_balance_level uses the key's threshold when configured. Verify the current balance and wallet warning threshold through a signed GET /v2/wallet request.
      security: []
      parameters:
        - { $ref: '#/components/parameters/WebhookTopic' }
        - { $ref: '#/components/parameters/WebhookKeyId' }
        - { $ref: '#/components/parameters/WebhookId' }
        - { $ref: '#/components/parameters/WebhookTimestamp' }
      requestBody:
        required: true
        content: { application/json: { schema: { $ref: '#/components/schemas/WalletWebhook' } } }
      responses:
        '2XX': { description: Receiver accepted the callback. }

components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: Authorization
      description: |-
        `Authorization: Key <api_key_value>` combined with the timestamp and HMAC-SHA256 signature headers. See [Authentication](https://docs.armadadelivery.com/v2/authentication.md) for a complete signing example.
    TimestampAuth:
      type: apiKey
      in: header
      name: x-armada-timestamp
      description: Milliseconds since epoch as a decimal string, within 30 seconds of server time.
    SignatureAuth:
      type: apiKey
      in: header
      name: x-armada-signature
      description: Lowercase hex HMAC-SHA256 of timestamp.method.path.rawBody. Use the uppercase HTTP method, the pathname with its exact query string, and the exact UTF-8 body bytes (empty string when absent). Recompute for each API request.

  parameters:
    WebhookTopic:
      name: x-armada-webhook-topic
      in: header
      required: true
      schema: { type: string, enum: [ order.updated, order.location.updated, wallet.balance_low ] }
    WebhookKeyId:
      name: x-armada-key-id
      in: header
      required: true
      description: API key record identifier used to match a callback to your saved key configuration.
      schema: { type: string }
    WebhookId:
      name: x-armada-webhook-id
      in: header
      required: true
      description: Header identifier prefixed wh_. Location updates can share an identifier.
      schema: { type: string }
    WebhookTimestamp:
      name: x-armada-timestamp
      in: header
      required: true
      description: Header-generation time. Recurrent jobs can reuse initial headers.
      schema: { type: string, format: date-time }
    DeliveryCode:
      name: id
      in: path
      required: true
      description: Code returned when creating a delivery through this API.
      schema: { type: string, example: D000000001 }
    BranchId:
      name: id
      in: path
      required: true
      schema: { type: string, pattern: '^[a-f0-9]{24}$' }

  responses:
    BadRequest:
      description: Invalid input, unmet account requirements or an operation not allowed in the current state.
      content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    Unauthorized:
      description: Missing or invalid credentials / signature.
      content:
        application/json: { schema: { $ref: '#/components/schemas/Error' } }
        text/plain: { schema: { type: string } }
    Forbidden:
      description: API key lacks the required permission.
      content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }
    NotFound:
      description: Resource not found.
      content: { application/json: { schema: { $ref: '#/components/schemas/Error' } } }

  schemas:
    Error:
      description: Error bodies vary by operation. Check the HTTP status first; no field is present in every response.
      oneOf:
        - type: object
          properties:
            error: { type: string, description: Error code when supplied. }
            internalCode: { type: [ string, number ], description: Error code when supplied. }
            message: { type: string, description: Error description when supplied. }
            violations: { type: object, description: Validation details when supplied. }
        - type: string

    Payment:
      type: object
      required: [ amount, type ]
      properties:
        amount: { type: number, exclusiveMinimum: 0 }
        type: { type: string, enum: [ paid, cash ] }

    LocationAddress:
      type: object
      required: [ contact_name, contact_phone, latitude, longitude ]
      properties:
        contact_name: { type: string }
        contact_phone: { type: string }
        latitude: { type: number }
        longitude: { type: number }
        first_line: { type: string }
        floor: { type: string }
        apartment: { type: string }
        instructions: { type: string }

    OriginLocationAddress:
      allOf:
        - { $ref: '#/components/schemas/LocationAddress' }
        - type: object
          properties:
            branch_id:
              type: string
              pattern: '^[a-fA-F0-9]{24}$'
              description: Non-deleted branch belonging to the authenticated merchant. Required when the merchant has multiple branches; otherwise exactly one non-deleted branch must exist.

    KuwaitAddress:
      type: object
      required: [ contact_name, contact_phone, area, block, street, building ]
      properties:
        contact_name: { type: string }
        contact_phone: { type: string }
        area: { type: string }
        block: { type: string }
        street: { type: string }
        building: { type: string }
        floor: { type: string }
        apartment: { type: string }
        instructions: { type: string }

    BahrainAddress: { $ref: '#/components/schemas/KuwaitAddress' }

    KsaAddress:
      type: object
      required: [ contact_name, contact_phone, city, street, district, building ]
      properties:
        contact_name: { type: string }
        contact_phone: { type: string }
        city: { type: string }
        street: { type: string }
        district: { type: string }
        building: { type: string }
        floor: { type: string }
        apartment: { type: string }
        instructions: { type: string }

    KsaShortAddress:
      type: object
      required: [ contact_name, contact_phone, short_address ]
      properties:
        contact_name: { type: string }
        contact_phone: { type: string }
        short_address: { type: string }
        instructions: { type: string }

    BranchOrigin:
      type: object
      required: [ branch_id ]
      properties:
        branch_id: { type: string, pattern: '^[a-f0-9]{24}$' }

    DeliveryRequest:
      type: object
      required: [ reference, payment, origin_format, destination_format, origin, destination ]
      properties:
        reference: { type: string, description: 'Partner order reference. Each successful create request creates a new delivery, including requests that reuse this reference.' }
        payment: { $ref: '#/components/schemas/Payment' }
        origin_format: { type: string, enum: [ location_format, branch_format ] }
        origin:
          anyOf:
            - $ref: '#/components/schemas/BranchOrigin'
            - $ref: '#/components/schemas/OriginLocationAddress'
        destination_format: { type: string, enum: [ location_format, kuwait_format, bahrain_format, ksa_format, ksa_short_format ] }
        destination:
          anyOf:
            - $ref: '#/components/schemas/LocationAddress'
            - $ref: '#/components/schemas/KuwaitAddress'
            - $ref: '#/components/schemas/BahrainAddress'
            - $ref: '#/components/schemas/KsaAddress'
            - $ref: '#/components/schemas/KsaShortAddress'

    EstimateRequest:
      type: object
      required: [ origin_format, destination_format, origin, destination ]
      properties:
        origin_format: { type: string, enum: [ location_format, branch_format ] }
        origin:
          anyOf:
            - $ref: '#/components/schemas/BranchOrigin'
            - $ref: '#/components/schemas/EstimateLocation'
        destination_format: { type: string, enum: [ location_format ] }
        destination:
          $ref: '#/components/schemas/EstimateLocation'

    EstimateLocation:
      type: object
      required: [ latitude, longitude ]
      properties:
        latitude: { type: number }
        longitude: { type: number }

    LiveEstimate:
      type: object
      required: [ delivery_fee, estimated_pickup_at, estimated_delivery_at ]
      properties:
        delivery_fee: { type: number, description: Estimated fee in the merchant's currency. }
        estimated_pickup_at: { type: [ string, 'null' ], format: date-time }
        estimated_delivery_at: { type: [ string, 'null' ], format: date-time }

    StaticEstimate:
      type: object
      required: [ deliveryFee, durationToPickup, totalDeliveryDuration ]
      properties:
        deliveryFee: { type: number, description: Estimated fee in the merchant's currency. }
        durationToPickup: { type: number, description: Pickup allowance in seconds. }
        totalDeliveryDuration: { type: number, description: Total duration including pickup allowance in seconds. }

    Delivery:
      type: object
      properties:
        status:
          type: string
          description: Current order status. Typical progression is pending, dispatched, accepted, waiting_pack, en_route, completed. Preparation, payment and backup-driver states can also occur; handle other statuses without discarding the response.
        code: { type: string }
        test_mode: { type: boolean }
        amount: { type: number }
        created_at: { type: string, format: date-time }
        currency: { type: string }
        delivery_fee: { type: number }
        customer:
          type: object
          properties:
            name: { type: string }
            phone: { type: string }
            address: { type: string }
            latitude: { type: [ 'number', 'null' ] }
            longitude: { type: [ 'number', 'null' ] }
        driver:
          type: object
          properties:
            name: { type: string }
            phone: { type: string }
            latitude: { type: [ 'number', 'null' ] }
            longitude: { type: [ 'number', 'null' ] }
        logistics:
          type: object
          properties:
            estimated_distance: { type: number, description: Meters. }
            estimated_duration: { type: number, description: Seconds. }
            tracking_url: { type: string, format: uri }
            pickup_qr_url: { type: string, format: uri }
      example:
        code: D000000001
        status: pending
        test_mode: false
        amount: 4.5
        created_at: 2026-04-16T18:12:03.117Z
        currency: KWD
        delivery_fee: 2
        customer:
          name: Example customer
          phone: "+96590000000"
          address: Salmiya, Kuwait
          latitude: 29.3759
          longitude: 47.9774
        driver:
          name: ""
          phone: ""
          latitude: null
          longitude: null
        logistics:
          estimated_distance: 4820
          estimated_duration: 743
          tracking_url: https://example.invalid/tracking/customer-link
          pickup_qr_url: https://example.invalid/pickup/qr

    BranchInput:
      type: object
      required: [ name, phone, latitude, longitude ]
      properties:
        name: { type: string, minLength: 2, maxLength: 75 }
        phone: { type: string, pattern: '^[\d+]{7,15}$' }
        latitude: { type: number, description: Pickup latitude. Must resolve with longitude to a supported address. }
        longitude: { type: number, description: Pickup longitude. The API derives the address from the coordinates. }

    BranchUpdate:
      type: object
      dependentRequired:
        latitude: [ longitude ]
        longitude: [ latitude ]
      properties:
        name: { type: string, minLength: 2, maxLength: 75 }
        phone: { type: string, pattern: '^[\d+]{7,15}$' }
        latitude: { type: number }
        longitude: { type: number }

    Branch:
      type: object
      properties:
        id: { type: string }
        name: { type: string }
        phone: { type: string }
        address: { type: string }
        latitude: { type: [ 'number', 'null' ] }
        longitude: { type: [ 'number', 'null' ] }
        created_at: { type: string, format: date-time }

    LocationWebhook:
      type: object
      required: [ code, status, location ]
      properties:
        code: { type: string }
        status: { type: string }
        location:
          type: object
          properties:
            latitude: { type: [ number, string, 'null' ] }
            longitude: { type: [ number, string, 'null' ] }

    WalletWebhook:
      type: object
      required: [ balance, warning_balance_level, currency ]
      properties:
        balance: { type: number }
        warning_balance_level: { type: number }
        currency: { type: string }

    Wallet:
      type: object
      properties:
        balance: { type: number }
        currency: { type: string }
        warning_balance_level: { type: [ 'number', 'null' ] }

    Invoice:
      type: object
      description: Merchant invoice fields for integration use.
      properties:
        _id: { type: string, pattern: '^[a-f0-9]{24}$', description: Invoice identifier used to retrieve this invoice. }
        invoiceNo: { type: string }
        type:
          type: string
          enum: [ regular, customer_order, wallet, topup_wallet, refund_wallet, refund, tap_wallet ]
        status:
          type: string
          enum: [ issued, sent, pending, authorized, paid, canceled, validation, refunded ]
        amount: { type: number }
        currency: { type: string }
        ordersCount: { type: integer }
        deliveryTripsCount: { type: integer }
        periodBegin: { type: string, format: date-time }
        periodEnd: { type: string, format: date-time }
        dueOn: { type: string, format: date-time }
        createdAt: { type: string, format: date-time }
```
