openapi: 3.1.0
info:
  title: Shipping Engine API
  version: '3.0'
  description: |
    The public B2B API of Shipping Engine. Look up regions and couriers, quote shipping rates, book
    and pay for shipments, track and cancel them, read your balance, and receive shipment events on
    your own webhook endpoint.

    Every response uses the same envelope: `{ "statusCode", "message", "data" }`. Errors return
    `{ "statusCode", "message", "error" }`, where `message` is a list of field errors when request
    validation fails. Unknown request fields are ignored.
servers:
  - url: https://sandbox-api.fastrac.example
    description: Sandbox (placeholder host)
  - url: https://api.fastrac.example
    description: Production (placeholder host)
security:
  - bearerAuth: []
tags:
  - name: regions
    x-displayName: Regions
    description: Look up the `subdistrictId` that every address needs. No authentication required.
  - name: couriers
    x-displayName: Couriers & catalog
    description: List couriers, their services, and the package categories you can declare.
  - name: shipping-rates
    x-displayName: Shipping rates
    description: Quote prices from one or many couriers. A quote returns a `shippingRateCode` that you use to create an order.
  - name: orders
    x-displayName: Orders
    description: Book and pay for one or more shipments in a single call, or cancel a whole order.
  - name: shipments
    x-displayName: Shipments
    description: List, inspect, track and cancel shipments. Delivery progress lives on the shipment, not the order.
  - name: balance
    x-displayName: Balance
    description: Read your balance pockets and every credit and debit that changed them.
  - name: webhooks
    x-displayName: Webhooks
    description: Register the HTTPS endpoint that receives shipment events, and check its status.
  - name: webhook-events
    x-displayName: Webhook events
    description: |
      Events that Shipping Engine sends to your registered endpoint. Every delivery is an HTTPS
      `POST` with a JSON body (no envelope) and metadata in `x-webhook-*` headers. Verify the
      signature on the raw body, answer any `2xx` within your endpoint's `timeoutMs`, and deduplicate on
      `x-webhook-id`. Events can arrive out of order. Other status changes can arrive as
      `shipment.status_updated` with the same body as the status events.

paths:
  # ---------------------------------------------------------------- Regions
  /b2b/region/find:
    get:
      operationId: searchRegions
      tags: [regions]
      summary: Search regions
      description: |
        Free-text search over Indonesian subdistricts (kelurahan/desa). Use the returned `id` as
        `subdistrictId` in a rate request. This is the fastest way to turn an address typed by a user
        into a region.

        No authentication is required. Results are paginated: pass `nextCursor` back as `cursor` until
        it is `null`.
      security: []
      parameters:
        - name: keyword
          in: query
          required: true
          description: Any mix of subdistrict, district, city or postal code.
          schema: { type: string, example: tebet barat }
        - name: limit
          in: query
          description: Results per page. Values above 100 are capped at 100.
          schema: { type: integer, default: 20, minimum: 1, maximum: 100, example: 20 }
        - name: cursor
          in: query
          description: The `nextCursor` from the previous page. Takes precedence over `offset`.
          schema: { type: string }
        - name: offset
          in: query
          description: Number of results to skip. Ignored when `cursor` is sent; prefer `cursor`.
          schema: { type: integer, minimum: 0, default: 0 }
      responses:
        '200':
          description: Matching subdistricts, best match first.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Request successful. }
                  data:
                    type: object
                    properties:
                      regions:
                        type: array
                        items: { $ref: '#/components/schemas/RegionSearchResult' }
                      nextCursor: { type: [string, 'null'], description: '`null` on the last page.' }
              example:
                statusCode: 200
                message: Request successful.
                data:
                  regions:
                    - id: '3174091001'
                      name: Tebet Barat, Tebet, Kota Jakarta Selatan, DKI Jakarta
                      postCode: 12810
                  nextCursor: null
        '400':
          description: '`keyword` is missing, or a number parameter is not a number.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                missingKeyword:
                  summary: Missing keyword
                  value:
                    statusCode: 400
                    message: "Field 'keyword' is required."
                    error: Bad Request
                badLimit:
                  summary: Non-numeric limit
                  value:
                    statusCode: 400
                    message: "Query parameter 'limit' must be a valid number."
                    error: Bad Request

  /b2b/region/province:
    get:
      operationId: listProvinces
      tags: [regions]
      summary: List provinces
      description: |
        Returns every Indonesian province. Start here when you build a cascading address picker
        (province → city → district → subdistrict). For free-text input, **Search regions** is faster.

        No authentication is required.
      security: []
      responses:
        '200':
          description: All provinces.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Request successful. }
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Province' }
              example:
                statusCode: 200
                message: Request successful.
                data:
                  - { id: 31, name: DKI Jakarta, countryId: 1 }
                  - { id: 32, name: Jawa Barat, countryId: 1 }

  /b2b/region/city:
    get:
      operationId: listCities
      tags: [regions]
      summary: List cities
      description: |
        Returns the cities (kota) and regencies (kabupaten) of one province.

        No authentication is required. An unknown `provinceId` returns an empty list with the message
        `Request successful. data not found`.
      security: []
      parameters:
        - name: provinceId
          in: query
          required: true
          description: '`id` from **List provinces**.'
          schema: { type: integer, example: 31 }
      responses:
        '200':
          description: Cities of the province.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Request successful. }
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/City' }
              example:
                statusCode: 200
                message: Request successful.
                data:
                  - { id: 3171, name: Kota Jakarta Pusat, provinceId: 31, cityType: CITY }
                  - { id: 3174, name: Kota Jakarta Selatan, provinceId: 31, cityType: CITY }
        '400':
          $ref: '#/components/responses/RegionQueryInvalid'

  /b2b/region/district:
    get:
      operationId: listDistricts
      tags: [regions]
      summary: List districts
      description: |
        Returns the districts (kecamatan) of one city.

        No authentication is required.
      security: []
      parameters:
        - name: cityId
          in: query
          required: true
          description: '`id` from **List cities**.'
          schema: { type: integer, example: 3174 }
      responses:
        '200':
          description: Districts of the city.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Request successful. }
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/District' }
              example:
                statusCode: 200
                message: Request successful.
                data:
                  - { id: 317407, name: Mampang Prapatan, cityId: 3174 }
                  - { id: 317409, name: Tebet, cityId: 3174 }
        '400':
          $ref: '#/components/responses/RegionQueryInvalid'

  /b2b/region/subdistrict:
    get:
      operationId: listSubdistricts
      tags: [regions]
      summary: List subdistricts
      description: |
        Returns the subdistricts (kelurahan/desa) of one district. The `id` of a subdistrict is the
        `subdistrictId` you send in rate requests.

        No authentication is required.
      security: []
      parameters:
        - name: districtId
          in: query
          required: true
          description: '`id` from **List districts**.'
          schema: { type: integer, example: 317409 }
      responses:
        '200':
          description: Subdistricts of the district.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Request successful. }
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Subdistrict' }
              example:
                statusCode: 200
                message: Request successful.
                data:
                  - { id: '3174091001', name: Tebet Barat, districtId: 317409, postCode: 12810 }
                  - { id: '3174091002', name: Tebet Timur, districtId: 317409, postCode: 12820 }
        '400':
          $ref: '#/components/responses/RegionQueryInvalid'

  /b2b/region/postCode:
    get:
      operationId: lookupPostcode
      tags: [regions]
      summary: Look up a postal code
      description: |
        Returns every subdistrict that uses a postal code, with its full region hierarchy. One postal
        code often covers several subdistricts, so let the user pick one.

        No authentication is required. Note that `subdistrictId` is a **number** here; send it as a
        string in rate requests.
      security: []
      parameters:
        - name: postCode
          in: query
          required: true
          description: Five-digit Indonesian postal code.
          schema: { type: string, pattern: '^[0-9]{5}$', example: '40111' }
      responses:
        '200':
          description: Subdistricts with this postal code.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Request successful. }
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/PostCodeRegion' }
              example:
                statusCode: 200
                message: Request successful.
                data:
                  - provinceId: 32
                    provinceName: Jawa Barat
                    cityId: 3273
                    cityName: Kota Bandung
                    districtId: 327301
                    district: Sumur Bandung
                    subdistrictId: 3273011003
                    subdistrict: Braga
                    postCode: 40111
                  - provinceId: 32
                    provinceName: Jawa Barat
                    cityId: 3273
                    cityName: Kota Bandung
                    districtId: 327301
                    district: Sumur Bandung
                    subdistrictId: 3273011004
                    subdistrict: Merdeka
                    postCode: 40111
        '400':
          description: '`postCode` is missing.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                statusCode: 400
                message: "Query parameter 'postCode' is required."
                error: Bad Request

  # ---------------------------------------------------------------- Couriers & catalog
  /b2b/courier/all:
    get:
      operationId: listCouriers
      tags: [couriers]
      summary: List couriers
      description: |
        Returns the couriers you can quote, with branding for your checkout UI. Use `code` as
        `courierCode` in **Get shipping rates**. A courier is usable only when `isOperational` is
        `true` (the courier is enabled and has at least one enabled service).

        Requires the `READ_SHIPPING_RATES` permission. Results are cached for up to 15 minutes.
      parameters:
        - name: type
          in: query
          description: Only couriers that offer this type. `EXPRESS` is accepted as an alias of `REGULAR`. Case-insensitive.
          schema: { type: string, enum: [INSTANT, REGULAR, EXPRESS], example: REGULAR }
        - name: search
          in: query
          description: Filter by courier name or code.
          schema: { type: string, example: jne }
        - name: isEnabled
          in: query
          description: Only enabled (`true`, `1`) or disabled (`false`, `0`) couriers. Omit for both.
          schema: { type: string, enum: ['true', 'false', '1', '0'], example: 'true' }
      responses:
        '200':
          description: Couriers matching the filters.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Couriers retrieved successfully. }
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/Courier' }
              example:
                statusCode: 200
                message: Couriers retrieved successfully.
                data:
                  - code: JNE
                    name: JNE
                    isEnabled: true
                    hasEnabledServices: true
                    isOperational: true
                    logoUrl: https://cdn.fastrac.example/couriers/jne.png
                    logoUrlBw: https://cdn.fastrac.example/couriers/jne-bw.png
                    logoSquareUrl: https://cdn.fastrac.example/couriers/jne-square.png
                    bgColor: '#0B3C8C'
                    supportedCourierTypes: [REGULAR]
                  - code: LALAMOVE
                    name: Lalamove
                    isEnabled: true
                    hasEnabledServices: true
                    isOperational: true
                    logoUrl: https://cdn.fastrac.example/couriers/lalamove.png
                    logoUrlBw: null
                    logoSquareUrl: null
                    bgColor: '#F16622'
                    supportedCourierTypes: [INSTANT]
        '400':
          description: A filter value is not allowed.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                type:
                  summary: Unknown type
                  value:
                    statusCode: 400
                    message: 'Invalid courier type. Allowed values: INSTANT, REGULAR'
                    error: Bad Request
                isEnabled:
                  summary: Unknown isEnabled value
                  value:
                    statusCode: 400
                    message: 'Invalid isEnabled value. Allowed values: true, false, 1, 0'
                    error: Bad Request
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'

  /b2b/courier/service:
    get:
      operationId: listCourierServices
      tags: [couriers]
      summary: List courier services
      description: |
        Returns one courier and all its services (for example JNE Reguler and JNE YES), with the
        service type, vehicle, estimated delivery days and default discount. Use it to show which
        services exist before quoting; prices come only from **Get shipping rates**.

        Requires the `READ_SHIPPING_RATES` permission.
      parameters:
        - name: courier_code
          in: query
          required: true
          description: Courier `code` from **List couriers**. Case-insensitive.
          schema: { type: string, example: JNE }
      responses:
        '200':
          description: The courier and its services.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Courier services retrieved successfully. }
                  data: { $ref: '#/components/schemas/CourierWithServices' }
              example:
                statusCode: 200
                message: Courier services retrieved successfully.
                data:
                  courierCode: JNE
                  courierId: 3
                  isEnabled: true
                  supportedTypes: [REGULAR]
                  services:
                    - id: 12
                      code: REG
                      courierCode: JNE
                      courierId: 3
                      name: JNE Reguler
                      type: REGULAR
                      vehicle: null
                      defaultDiscountPercentage: 10
                      etdMinimumDay: 2
                      etdMaximumDay: 3
                      isEnabled: true
                      volumetricConversion: 6000
                      freeRts: false
                      shippingRateTtlSeconds: 900
                    - id: 13
                      code: YES
                      courierCode: JNE
                      courierId: 3
                      name: JNE YES
                      type: NEXTDAY
                      vehicle: null
                      defaultDiscountPercentage: 5
                      etdMinimumDay: 1
                      etdMaximumDay: 1
                      isEnabled: true
                      volumetricConversion: 6000
                      freeRts: false
                      shippingRateTtlSeconds: null
        '400':
          description: '`courier_code` is missing or unknown.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                missing:
                  summary: Missing courier_code
                  value:
                    statusCode: 400
                    message: '"courier_code" is not allowed to be empty'
                    error: Bad Request
                unknown:
                  summary: Unknown courier
                  value:
                    statusCode: 400
                    message: "Invalid courier_code 'XYZ'."
                    error: Bad Request
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'

  /b2b/order/category-item:
    get:
      operationId: listPackageTypes
      tags: [couriers]
      summary: List package types
      description: |
        Returns the package categories you can declare. Send the `id` (as a number) as
        `packages[].packageTypeId` in **Get shipping rates**. Some courier services refuse certain
        categories; such services are left out of the quote.

        No authentication is required.
      security: []
      responses:
        '200':
          description: All package types.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Request successful. }
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/PackageType' }
              example:
                statusCode: 200
                message: Request successful.
                data:
                  - { id: '1', category: Elektronik }
                  - { id: '2', category: Fashion }
                  - { id: '8', category: Frozen }

  # ---------------------------------------------------------------- Shipping rates
  /b2b/shipping-rate:
    post:
      operationId: createShippingRates
      tags: [shipping-rates]
      summary: Get shipping rates
      description: |
        Quotes a shipment for one courier or for every courier of a type. Each result is saved as a
        **shipping rate** with a `shippingRateCode` that is valid until `validUntil`. Pass that code to
        **Create an order** to book the shipment at the quoted price.

        Requires the `READ_SHIPPING_RATES` permission. Quoting with `codOption.isCod: true` also
        requires `USE_COD`.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ShippingRateRequest'
            examples:
              regular:
                summary: Regular courier (JNE), one package
                value:
                  origin:
                    fullAddress: Jl. Tebet Raya No. 12, Tebet Barat, Jakarta Selatan
                    subdistrictId: '3174091001'
                  destinations:
                    - fullAddress: Jl. Braga No. 8, Braga, Sumur Bandung, Kota Bandung
                      subdistrictId: '3273011003'
                  courierCode: JNE
                  insurance: true
                  packages:
                    - itemValue: 500000
                      isGlassware: false
                      weight: 1200
                      dimension: { length: 30, width: 20, height: 10 }
              allRegular:
                summary: Compare every regular courier
                value:
                  origin:
                    fullAddress: Jl. Tebet Raya No. 12, Tebet Barat, Jakarta Selatan
                    subdistrictId: '3174091001'
                  destinations:
                    - fullAddress: Jl. Braga No. 8, Braga, Sumur Bandung, Kota Bandung
                      subdistrictId: '3273011003'
                  courierCode: REGULAR
                  insurance: false
                  packages:
                    - itemValue: 250000
                      isGlassware: false
                      weight: 800
                      dimension: { length: 20, width: 15, height: 10 }
              instant:
                summary: Instant courier with a motorbike, scheduled pickup
                value:
                  origin:
                    fullAddress: Jl. Tebet Raya No. 12, Tebet Barat, Jakarta Selatan
                    subdistrictId: '3174091001'
                    coordinate: { latitude: -6.2265, longitude: 106.8521 }
                  destinations:
                    - fullAddress: Jl. Kemang Raya No. 5, Bangka, Mampang Prapatan, Jakarta Selatan
                      subdistrictId: '3174071003'
                      coordinate: { latitude: -6.2607, longitude: 106.8143 }
                  courierCode: LALAMOVE
                  vehicle: BIKE
                  scheduledAt: '2026-11-21T10:00:00+07:00'
                  packages:
                    - itemValue: 150000
                      isGlassware: false
                      weight: 2000
                      dimension: { length: 30, width: 30, height: 20 }
              cod:
                summary: Cash on delivery
                value:
                  origin:
                    fullAddress: Jl. Tebet Raya No. 12, Tebet Barat, Jakarta Selatan
                    subdistrictId: '3174091001'
                  destinations:
                    - fullAddress: Jl. Braga No. 8, Braga, Sumur Bandung, Kota Bandung
                      subdistrictId: '3273011003'
                  courierCode: JNT
                  insurance: false
                  codOption: { isCod: true }
                  packages:
                    - itemValue: 300000
                      isGlassware: false
                      weight: 1000
                      dimension: { length: 25, width: 20, height: 10 }
      responses:
        '201':
          description: One rate per courier service that can carry the shipment.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 201 }
                  message: { type: string, example: Shipping rate created successfully. }
                  data:
                    type: array
                    items: { $ref: '#/components/schemas/ShippingRate' }
              examples:
                regular:
                  $ref: '#/components/examples/RegularRatesResponse'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: No courier can carry this shipment with these parameters.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                statusCode: 404
                message: No shipping rates available for the requested route or parameters.
                error: Not Found

  /b2b/shipping-rate/{code}:
    get:
      operationId: retrieveShippingRate
      tags: [shipping-rates]
      summary: Retrieve a shipping rate
      description: |
        Returns a rate you quoted earlier, for example to re-display it before checkout. Expired rates
        are still returned; check `validUntil` before you use the code to create an order.

        Requires the `READ_SHIPPING_RATES` permission.
      parameters:
        - name: code
          in: path
          required: true
          description: The `shippingRateCode` returned by **Get shipping rates**.
          schema: { type: string, example: SR-7KQ2M9XA }
      responses:
        '200':
          description: The shipping rate.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Request successful. }
                  data: { $ref: '#/components/schemas/ShippingRate' }
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          description: No rate exists with this code.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                statusCode: 404
                message: Shipping rate with code 'SR-UNKNOWN' not found or unavailable
                error: Not Found

  # ---------------------------------------------------------------- Orders
  /b2b/orders:
    post:
      operationId: createOrder
      tags: [orders]
      summary: Create an order
      description: |
        Books one or more quoted shipments **and pays for them in the same call**. Each shipment
        references a `shippingRateCode` from **Get shipping rates**; price, courier service, insurance,
        COD and packages are taken from that rate. The courier is booked before the response returns,
        so a successful response already carries each shipment's `airwayBill` and status
        `PENDING_PICKUP` or `PENDING_DROPOFF`.

        Requires the `CREATE_ORDER` permission. Orders that use a COD rate also require `USE_COD`.

        **Payment.** Non-COD orders deduct each shipment's `priceDetail.totalPrice` from your
        `shippingCredit` balance. COD orders deduct nothing upfront, and every shipment in one order
        must be either COD or non-COD.

        **Receivers** are matched to the rate's destinations by position: send them in the same order
        as the rate's `destinations` (`stopOrder`). If you send fewer receivers than destinations, the
        last receiver is reused.

        **Fulfilment.** `shippingOptions.fulfillmentMethod` defaults to `PICKUP` for instant services
        and `DROPOFF` otherwise. A regular-courier pickup needs `sender.coordinate`. A pickup
        `schedule` must be at least 15 minutes ahead (Asia/Jakarta); omitted, it is now + 15 minutes.
        For Lalamove and Dash instant services the pickup time is fixed by the quote: send the same
        `scheduledAt` you quoted with, or omit `schedule`.

        **If payment or courier booking fails**, the response is `400` with the message
        `Payment failed, but order '<code>' was created successfully. Reason: …`. The order stays
        unpaid and any charge is refunded; quote again and create a new order. If a courier rejects one
        shipment outright, the order still succeeds and that shipment is returned as `CANCELLED` and
        refunded.

        This call is not idempotent. On a timeout, check **List shipments** (filter by `search` or
        date) before you retry.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateOrderRequest' }
            examples:
              regularDropoff:
                summary: Regular courier, drop-off at a counter
                value:
                  shipments:
                    - shippingRateCode: SR-7KQ2M9XA
                      sender:
                        name: Toko Sinar Tebet
                        email: gudang@sinartebet.co.id
                        whatsappNumber: '081211112222'
                      receivers:
                        - name: Rina Kartika
                          phoneNumber: '081298765432'
                          addressNote: Rumah pagar hijau, sebelah warung kopi
                          label: Rumah
                          stopSequence: 1
                      shippingOptions:
                        fulfillmentMethod: DROPOFF
                      packages:
                        - shippingRatePackageCode: PKG-3M8XQ1
                          packageNote: Jangan dibanting
              instantScheduledPickup:
                summary: Instant courier, scheduled pickup
                description: The rate was quoted with `courierCode` LALAMOVE, `vehicle` BIKE and `scheduledAt` 2026-11-21T10:00:00+07:00, so the order sends the same time.
                value:
                  shipments:
                    - shippingRateCode: SR-4HT8N2LC
                      sender:
                        name: Toko Sinar Tebet
                        email: gudang@sinartebet.co.id
                        phoneNumber: '081211112222'
                        coordinate: { latitude: '-6.2265', longitude: '106.8521' }
                      receivers:
                        - name: Budi Santoso
                          phoneNumber: '081377778888'
                          addressNote: Lobi kantor lantai 1, titip resepsionis
                          label: Kantor
                          stopSequence: 1
                      shippingOptions:
                        fulfillmentMethod: PICKUP
                        schedule: '2026-11-21T10:00:00+07:00'
              cod:
                summary: Cash on delivery, courier pickup
                description: Requires the `USE_COD` permission. The rate was quoted with `codOption.isCod` true.
                value:
                  shipments:
                    - shippingRateCode: SR-9PL3V6RD
                      sender:
                        name: Toko Sinar Tebet
                        email: gudang@sinartebet.co.id
                        whatsappNumber: '081211112222'
                        coordinate: { latitude: '-6.2265', longitude: '106.8521' }
                      receivers:
                        - name: Rina Kartika
                          phoneNumber: '081298765432'
                          addressNote: Bayar di tempat, siapkan uang pas
                          label: Rumah
                          stopSequence: 1
                      shippingOptions:
                        fulfillmentMethod: PICKUP
                        schedule: '2026-11-21T14:00:00+07:00'
              multiShipment:
                summary: Two shipments in one order
                description: Each shipment has its own rate code. Both are paid from your balance in one call.
                value:
                  shipments:
                    - shippingRateCode: SR-7KQ2M9XA
                      sender:
                        name: Toko Sinar Tebet
                        email: gudang@sinartebet.co.id
                        whatsappNumber: '081211112222'
                      receivers:
                        - name: Rina Kartika
                          phoneNumber: '081298765432'
                          addressNote: Rumah pagar hijau
                          label: Rumah
                          stopSequence: 1
                      shippingOptions:
                        fulfillmentMethod: DROPOFF
                    - shippingRateCode: SR-2WX5B8JN
                      sender:
                        name: Toko Sinar Tebet
                        email: gudang@sinartebet.co.id
                        whatsappNumber: '081211112222'
                      receivers:
                        - name: Dewi Lestari
                          phoneNumber: '085611223344'
                          addressNote: Kos Melati kamar 3
                          label: Kos
                          stopSequence: 1
                      shippingOptions:
                        fulfillmentMethod: DROPOFF
      responses:
        '201':
          description: The order is paid and every shipment is booked with its courier.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 201 }
                  message: { type: string, example: Resource created successfully. }
                  data: { $ref: '#/components/schemas/Order' }
              examples:
                regularDropoff:
                  $ref: '#/components/examples/OrderResponse'
        '400':
          description: |
            The request is invalid, a rate can't be ordered, or payment or courier booking failed.
            Pickup-schedule errors carry a machine-readable `code`.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                validation:
                  summary: Field validation
                  value:
                    statusCode: 400
                    message:
                      - shipments.0.shippingRateCode should not be empty
                      - shipments.0.receivers.0.phoneNumber should not be empty
                    error: Bad Request
                invalidRate:
                  summary: Unknown rate code
                  value:
                    statusCode: 400
                    message: Invalid shipping rate code provided.
                    error: Bad Request
                expiredRate:
                  summary: Rate expired
                  value:
                    statusCode: 400
                    message: Shipping rate code 'SR-7KQ2M9XA' have expired.
                    error: Bad Request
                mixedCod:
                  summary: COD and non-COD in one order
                  value:
                    statusCode: 400
                    message: All shipments in one order must be either COD or non-COD.
                    error: Bad Request
                noPickup:
                  summary: Service does not support pickup
                  value:
                    statusCode: 400
                    message: Courier service 'REG' (JNE) does not support pickup.
                    error: Bad Request
                senderCoordinate:
                  summary: Regular pickup without coordinates
                  value:
                    statusCode: 400
                    message: Pickup shipments require sender coordinates.
                    error: Bad Request
                vehicleCapacity:
                  summary: Too heavy for the vehicle
                  value:
                    statusCode: 400
                    message: Total package weight (25000g) exceeds the maximum capacity of vehicle 'Motor' (20000g).
                    error: Bad Request
                scheduleExpired:
                  summary: Pickup less than 15 minutes ahead
                  value:
                    statusCode: 400
                    code: PICKUP_SCHEDULE_EXPIRED
                    message: Pickup schedule must be at least 15 minutes ahead (Asia/Jakarta, UTC+7).
                scheduleNotQuoted:
                  summary: Pickup time differs from the quoted time (Lalamove, Dash)
                  value:
                    statusCode: 400
                    code: PICKUP_SCHEDULE_NOT_QUOTED
                    message: Jadwal pickup tidak sesuai dengan ongkir yang dipilih. Hitung ulang ongkir dengan jadwal tersebut, atau pesan tanpa jadwal untuk pickup secepatnya.
                    quotedScheduledAt: '2026-11-21T10:00:00+07:00'
                    requestedScheduledAt: '2026-11-21T11:00:00+07:00'
                paymentFailed:
                  summary: Insufficient balance
                  value:
                    statusCode: 400
                    message: "Payment failed, but order 'FSO-261120-A1B2C3' was created successfully. Reason: Insufficient balance."
                    error: Bad Request
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: Your API key's role lacks `CREATE_ORDER`, or lacks `USE_COD` for a COD rate.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                permission:
                  summary: Missing CREATE_ORDER
                  value:
                    statusCode: 403
                    message: "You're not authorized to access this resource (Missing permissions: CREATE_ORDER)."
                    error: Forbidden
                cod:
                  summary: Missing USE_COD
                  value:
                    statusCode: 403
                    message: You are not allowed to use COD for COD orders.
                    error: Forbidden

  /b2b/orders/{orderCode}/cancel:
    post:
      operationId: cancelOrder
      tags: [orders]
      summary: Cancel an order
      description: |
        Cancels every shipment of an order and refunds what was paid for each. Shipments that are
        already cancelled are skipped. Shipments not yet handed to the courier are cancelled
        immediately; for dispatched shipments the courier is asked to cancel first, and a courier
        refusal is returned as an error.

        The order is refused as a whole if any shipment is already `DELIVERED`. Shipments are cancelled
        one by one, so if an error occurs part-way, earlier shipments stay cancelled. To cancel a
        single shipment, use **Cancel a shipment**.

        Requires the `READ_ORDER` permission.
      parameters:
        - name: orderCode
          in: path
          required: true
          description: The order `code` returned by **Create an order**.
          schema: { type: string, pattern: '^FSO-[0-9]{6}-[A-Z0-9]{6}$', example: FSO-261120-A1B2C3 }
      responses:
        '200':
          description: Every shipment of the order is cancelled.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Order successfully cancelled. }
                  data: { type: 'null', description: Always empty. }
              example:
                statusCode: 200
                message: Order successfully cancelled.
        '400':
          description: The order can't be cancelled.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                delivered:
                  summary: A shipment is delivered
                  value:
                    statusCode: 400
                    message: Order 'FSO-261120-A1B2C3' cannot be cancelled because shipment 'SHP-261120-K9M2Q7' is already delivered.
                    error: Bad Request
                noShipments:
                  summary: Order has no shipments
                  value:
                    statusCode: 400
                    message: Order 'FSO-261120-A1B2C3' has no shipments to cancel.
                    error: Bad Request
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: The order belongs to another account, or your role lacks `READ_ORDER`.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                statusCode: 403
                message: You are not allowed to cancel order 'FSO-261120-A1B2C3'.
                error: Forbidden
        '404':
          description: No order exists with this code.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                statusCode: 404
                message: Order with code 'FSO-261120-ZZZZZZ' was not found.
                error: Not Found

  # ---------------------------------------------------------------- Shipments
  /b2b/shipments:
    get:
      operationId: listShipments
      tags: [shipments]
      summary: List shipments
      description: |
        Lists your shipments, newest first, with filters and per-status counts. Unpaid shipments are
        never listed. Use it for an order dashboard, or to find a shipment after a timeout.

        `data.count` covers all your shipments in the `startDate`–`endDate` range and ignores the other
        filters. `count.RTS` adds up `RTS_CONFIRMED` and `RTS_TRANSIT`.

        Requires the `READ_ORDER` permission.
      parameters:
        - name: search
          in: query
          description: Matches shipment code, airway bill, order code, or receiver name or phone (partial, case-insensitive).
          schema: { type: string, maxLength: 100, example: SHP-261120 }
        - name: orderCode
          in: query
          description: Only shipments of this order (partial match).
          schema: { type: string, maxLength: 50, example: FSO-261120-A1B2C3 }
        - name: courierCode
          in: query
          description: Only shipments with this courier. Case-insensitive.
          schema: { type: string, example: JNE }
        - name: courierServiceId
          in: query
          description: Only shipments with this courier service (`id` from **List courier services**).
          schema: { type: integer, minimum: 1, example: 12 }
        - name: status
          in: query
          description: Only shipments in this status.
          schema: { $ref: '#/components/schemas/ShipmentStatus' }
        - name: startDate
          in: query
          description: Created at or after this time. ISO 8601; include an offset, for example `2026-11-01T00:00:00+07:00`.
          schema: { type: string, format: date-time, example: '2026-11-01T00:00:00+07:00' }
        - name: endDate
          in: query
          description: Created at or before this time. ISO 8601; include an offset.
          schema: { type: string, format: date-time, example: '2026-11-30T23:59:59+07:00' }
        - name: source
          in: query
          description: Only shipments created through this channel. API orders are `B2B`; dashboard orders are `CLIENT_DASHBOARD`.
          schema: { type: string, enum: [B2B, CLIENT_DASHBOARD, WEB, ANDROID, IOS, SHOP], example: B2B }
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: One page of shipments.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Shipments retrieved. }
                  data: { $ref: '#/components/schemas/ShipmentList' }
              example:
                statusCode: 200
                message: Shipments retrieved.
                data:
                  count:
                    PENDING_PICKUP: 3
                    PENDING_DROPOFF: 1
                    IN_TRANSIT: 12
                    DELIVERED: 248
                    CANCELLED: 7
                    RTS: 2
                  shipments:
                    - id: 18452
                      code: SHP-261120-K9M2Q7
                      orderId: 9021
                      orderCode: FSO-261120-A1B2C3
                      source: B2B
                      userId: 512
                      userEmail: ops@sinartebet.co.id
                      airwayBill: CM12345678901
                      trackingUrl: null
                      courierCode: JNE
                      courierName: JNE
                      courierServiceId: 12
                      courierServiceCode: REG
                      courierServiceName: JNE Reguler
                      status: IN_TRANSIT
                      createdAt: '2026-11-20T02:05:11.000Z'
                      recipient:
                        name: Rina Kartika
                        phoneNumber: '081298765432'
                        fullAddress: Jl. Braga No. 8, Braga, Sumur Bandung, Kota Bandung
                      cursor: MTg0NTI=
                  nextCursor: MTg0NTI=
        '400':
          $ref: '#/components/responses/QueryValidation'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          $ref: '#/components/responses/InvalidDateRange'

  /b2b/shipments/{shipmentCode}/details:
    get:
      operationId: retrieveShipment
      tags: [shipments]
      summary: Retrieve a shipment
      description: |
        Returns everything about one shipment: status, courier service, airway bill, sender and
        receivers with their region names, packages (with measured weight once the courier reweighs),
        status history and driver details. This reads stored data; to ask the courier for the latest
        status, use **Track a shipment**.

        Requires the `READ_ORDER` permission. You can only read your own shipments.
      parameters:
        - $ref: '#/components/parameters/ShipmentCode'
      responses:
        '200':
          description: The shipment.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Shipment detail retrieved. }
                  data: { $ref: '#/components/schemas/ShipmentDetail' }
              examples:
                inTransit:
                  $ref: '#/components/examples/ShipmentDetailResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: The shipment belongs to another account, or your role lacks `READ_ORDER`.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                statusCode: 403
                message: You are not allowed to view this shipment.
                error: Forbidden
        '404':
          description: No shipment exists with this code.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                statusCode: 404
                message: Shipment with code SHP-261120-ZZZZZZ not found.
                error: Not Found

  /b2b/shipments/track/{trackingCode}:
    get:
      operationId: trackShipment
      tags: [shipments]
      summary: Track a shipment
      description: |
        Asks the courier for the latest tracking events and returns them merged with the stored
        history. If the courier reports a new status, the shipment is updated (and the matching webhook
        is sent) as part of this call. If the courier can't be reached, the stored history is returned.

        Pass either the shipment code or the courier's airway bill. A shipment can be tracked only
        after the courier has assigned an airway bill.

        Prefer webhooks for status changes; call this when a user opens a tracking page.

        Requires the `READ_ORDER` permission.
      parameters:
        - name: trackingCode
          in: path
          required: true
          description: A shipment `code` (`SHP-…`) or the courier's airway bill.
          schema: { type: string, example: SHP-261120-K9M2Q7 }
      responses:
        '200':
          description: Current status and full tracking history, oldest event first.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Request successful. }
                  data: { $ref: '#/components/schemas/TrackingInfo' }
              examples:
                regular:
                  summary: Regular courier in transit
                  value:
                    statusCode: 200
                    message: Request successful.
                    data:
                      currentStatus: IN_TRANSIT
                      trackingUrl: null
                      courier: JNE
                      service: JNE Reguler
                      histories:
                        - timestamp: '2026-11-20T03:12:00.000Z'
                          status: PENDING_DROPOFF
                          description: Shipment created, waiting for drop-off
                        - timestamp: '2026-11-20T08:40:00.000Z'
                          status: IN_TRANSIT
                          description: Paket diterima di counter agen
                          location: JAKARTA SELATAN
                        - timestamp: '2026-11-20T21:05:00.000Z'
                          status: IN_TRANSIT
                          description: Paket diberangkatkan ke kota tujuan
                          location: JAKARTA
                instant:
                  summary: Instant courier with a driver
                  value:
                    statusCode: 200
                    message: Request successful.
                    data:
                      currentStatus: IN_TRANSIT
                      trackingUrl: https://share.lalamove.example/t/abc123
                      courier: Lalamove
                      service: Lalamove Motor
                      driver:
                        name: Agus Prasetyo
                        phone: '081355556666'
                        licensePlate: B 3456 TKO
                      histories:
                        - timestamp: '2026-11-21T02:55:00.000Z'
                          status: PENDING_PICKUP
                          description: Driver assigned
                        - timestamp: '2026-11-21T03:10:00.000Z'
                          status: IN_TRANSIT
                          description: Picked up
        '400':
          description: The shipment has no airway bill yet.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                statusCode: 400
                message: Shipment 'SHP-261120-K9M2Q7' has not been dispatched yet.
                error: Bad Request
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: No shipment has this code or airway bill.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                statusCode: 404
                message: Shipment with code or airway bill 'CM00000000000' not found.
                error: Not Found

  /b2b/shipments/cancel/{shipmentCode}:
    post:
      operationId: cancelShipment
      tags: [shipments]
      summary: Cancel a shipment
      description: |
        Cancels one shipment and refunds what was paid for it to where the payment came from. Before
        the courier has an airway bill, the shipment is cancelled immediately. After that, the courier
        is asked to cancel first; if the courier refuses (for example because the parcel is already
        picked up), the error is returned and nothing changes.

        Calling it again on a cancelled shipment succeeds without doing anything. Delivered shipments
        and shipments already being returned to the sender can't be cancelled.

        Requires the `CANCEL_ORDER` permission. No request body.
      parameters:
        - $ref: '#/components/parameters/ShipmentCode'
      responses:
        '200':
          description: The shipment is cancelled (or already was).
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Shipment successfully cancelled. }
                  data: { type: 'null', description: Always empty. }
              example:
                statusCode: 200
                message: Shipment successfully cancelled.
        '400':
          description: The shipment is delivered, or the courier refused the cancellation.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                statusCode: 400
                message: Shipment 'SHP-261120-K9M2Q7' is delivered and cannot be cancelled.
                error: Bad Request
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          description: No shipment exists with this code.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                statusCode: 404
                message: Shipment with code 'SHP-261120-ZZZZZZ' was not found.
                error: Not Found

  /b2b/shipments/{shipmentCode}/simulate-status:
    post:
      operationId: simulateShipmentStatus
      tags: [shipments]
      summary: Simulate a status (sandbox only)
      description: |
        **Sandbox only.** Production returns `403`.

        Pretends that the courier reported an event for one of your sandbox shipments, so you can test
        your webhook handler and status logic end to end without waiting for a real courier. Use a
        shipment that already has an airway bill.

        | `status` | Webhook sent | Effect on the shipment |
        | --- | --- | --- |
        | `DRIVER_ASSIGNED` | `shipment.pending_pickup` | Sample driver details are attached |
        | `TRANSIT` | `shipment.in_transit` | Status becomes `IN_TRANSIT` |
        | `DELIVERED` | `shipment.delivered` | Status becomes `DELIVERED` |
        | `CANCELLED` | none (use **Cancel a shipment** to receive `shipment.cancelled`) | Status becomes `CANCELLED` and the shipment is refunded |
        | `RTS` | `shipment.rts_billed` if a return fee applies | Status becomes `RTS_DELIVERED` (returned to the sender) |
        | `AIRWAYBILL_UPDATED` | `shipment.airway_bill_updated` | The airway bill is replaced by a `SIM-…` number |
        | `PRICE_CHANGED` | `shipment.price_changed` | None: webhook only, sample values (Rp 10.000 → Rp 15.000) |
        | `WEIGHT_CHANGED` | `shipment.measurement_changed` | None: webhook only, sample values |
        | `RTS_BILLED` | `shipment.rts_billed` | None: webhook only, sample fee Rp 15.000 |

        Requires the `CANCEL_ORDER` permission.
      parameters:
        - $ref: '#/components/parameters/ShipmentCode'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [status]
              properties:
                status:
                  type: string
                  enum: [DRIVER_ASSIGNED, TRANSIT, DELIVERED, CANCELLED, RTS, AIRWAYBILL_UPDATED, PRICE_CHANGED, WEIGHT_CHANGED, RTS_BILLED]
                  description: The courier event to simulate. See the table above.
            examples:
              delivered:
                summary: Simulate delivery
                value: { status: DELIVERED }
              priceChanged:
                summary: Simulate a price adjustment webhook
                value: { status: PRICE_CHANGED }
      responses:
        '200':
          description: The event was processed and the webhook queued.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Shipment status simulated successfully. }
                  data: { type: 'null', description: Always empty. }
              example:
                statusCode: 200
                message: Shipment status simulated successfully.
        '400':
          description: Unknown `status` or shipment.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              examples:
                status:
                  summary: Unknown status
                  value:
                    statusCode: 400
                    message:
                      - 'status must be one of the following values: CANCELLED, DELIVERED, RTS, TRANSIT, DRIVER_ASSIGNED, PRICE_CHANGED, WEIGHT_CHANGED, AIRWAYBILL_UPDATED, RTS_BILLED'
                    error: Bad Request
                shipment:
                  summary: Unknown shipment
                  value:
                    statusCode: 400
                    message: Shipment SHP-261120-ZZZZZZ not found.
                    error: Bad Request
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          description: Called in production, or your role lacks `CANCEL_ORDER`.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                statusCode: 403
                message: Simulate shipment status is not allowed in PRODUCTION environment.
                error: Forbidden

  # ---------------------------------------------------------------- Balance
  /b2b/user-balance:
    get:
      operationId: retrieveBalance
      tags: [balance]
      summary: Retrieve your balance
      description: |
        Returns your four balance pockets in whole Rupiah. Orders are paid from `shippingCredit`;
        check it before you create orders in bulk. Top-ups are done in the Fastrac dashboard,
        not through the API.

        Any valid API key can call it; no extra permission is needed.
      responses:
        '200':
          description: Current balances.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Request successful. }
                  data: { $ref: '#/components/schemas/Balance' }
              example:
                statusCode: 200
                message: Request successful.
                data:
                  balance:
                    point: 0
                    shippingCredit: 1487016
                    payoutBalance: 325000
                    referralBalance: 0
                  timestamp: '2026-11-20T03:30:00.000Z'
        '401':
          $ref: '#/components/responses/Unauthorized'

  /b2b/user-balance/logs:
    get:
      operationId: listBalanceLogs
      tags: [balance]
      summary: List balance logs
      description: |
        Lists every credit and debit on your balance, newest first: order payments, refunds of
        cancelled shipments, price adjustments, return (RTS) fees, COD proceeds and top-ups. Use it to
        reconcile your balance with your own records.

        Any valid API key can call it; no extra permission is needed.
      parameters:
        - name: type
          in: query
          description: Only credits (money in) or debits (money out).
          schema: { type: string, enum: [CREDIT, DEBIT], example: DEBIT }
        - name: shipmentId
          in: query
          description: Text search on `description`. Pass a shipment code, order code or airway bill to find the logs that mention it.
          schema: { type: string, maxLength: 50, example: SHP-261120-K9M2Q7 }
        - name: startDate
          in: query
          description: Logs at or after this time. ISO 8601; include an offset.
          schema: { type: string, format: date-time, example: '2026-11-01T00:00:00+07:00' }
        - name: endDate
          in: query
          description: Logs at or before this time. ISO 8601; include an offset.
          schema: { type: string, format: date-time, example: '2026-11-30T23:59:59+07:00' }
        - $ref: '#/components/parameters/Limit'
        - $ref: '#/components/parameters/Cursor'
      responses:
        '200':
          description: One page of balance logs.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Request successful. }
                  data: { $ref: '#/components/schemas/BalanceLogList' }
              example:
                statusCode: 200
                message: Request successful.
                data:
                  logs:
                    - id: 77120
                      userId: 512
                      type: CREDIT
                      amount: 12984
                      description: Cancel shipment SHP-261120-P4T7W2 for order FSO-261120-D4E5F6 (wallet refund)
                      createdAt: '2026-11-20T04:10:00.000Z'
                      cursor: NzcxMjA=
                    - id: 77098
                      userId: 512
                      type: DEBIT
                      amount: 12984
                      description: Payment for order FSO-261120-A1B2C3 shipment SHP-261120-K9M2Q7
                      createdAt: '2026-11-20T02:05:12.000Z'
                      cursor: NzcwOTg=
                  nextCursor: null
        '400':
          $ref: '#/components/responses/QueryValidation'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '422':
          $ref: '#/components/responses/InvalidDateRange'

  # ---------------------------------------------------------------- Webhooks
  /b2b/webhook/info:
    get:
      operationId: retrieveWebhookEndpoint
      tags: [webhooks]
      summary: Retrieve your webhook endpoint
      description: |
        Returns your organisation's webhook endpoint, as a list with zero or one item. Check
        `verificationStatus`: events are delivered only while it is `verified` and `isEnabled` is
        `true`. `failureCount` and `backoffUntil` show whether deliveries are currently failing.

        Requires the `READ_WEBHOOKS` permission.
      responses:
        '200':
          description: Your webhook endpoint, if one is registered.
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 200 }
                  message: { type: string, example: Request successful. }
                  data:
                    type: array
                    maxItems: 1
                    items: { $ref: '#/components/schemas/WebhookEndpoint' }
              example:
                statusCode: 200
                message: Request successful.
                data:
                  - id: 41
                    name: Production events
                    url: https://hooks.sinartebet.co.id/shipping-engine
                    isEnabled: true
                    verificationStatus: verified
                    apiVersion: V3
                    timeoutMs: 10000
                    maxAttempts: 8
                    eventTypes: ['shipment.*']
                    activeSecretKeyIds: [whsec_main_2026]
                    createdAt: '2026-11-02T07:00:00.000Z'
                    updatedAt: '2026-11-18T09:30:00.000Z'
                    backoffUntil: null
                    failureCount: 0
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'

  /b2b/webhook/setWebhook:
    post:
      operationId: setWebhookEndpoint
      tags: [webhooks]
      summary: Set your webhook endpoint
      description: |
        Registers, or replaces, the single webhook endpoint of your organisation. Calling it again
        replaces the URL, secret and event types; the new secret takes effect immediately with no
        overlap, so deploy it to your endpoint first.

        **Verification challenge.** Before saving, Shipping Engine sends your URL an unsigned
        `POST` with `{"challenge":"<uuid>"}` (10-second timeout). Reply with any `2xx` and the body
        `{"challenge":"<uuid>"}` or the raw uuid.

        - Challenge passed: the endpoint is saved as `verified` and starts receiving events.
        - Challenge failed on a **new** endpoint: it is saved with `verificationStatus: failed`
          (still `201`) and **receives no events**. Fix your endpoint and call this again.
        - Challenge failed while you already have a **verified** endpoint: `422`, and the current
          endpoint stays active and unchanged.

        Always check `data.challenge.success` in the response.

        Requires the `MANAGE_WEBHOOKS` permission.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/SetWebhookEndpointRequest' }
            examples:
              allShipmentEvents:
                summary: Every shipment event
                value:
                  name: Production events
                  url: https://hooks.sinartebet.co.id/shipping-engine
                  secret: 9f2c7a1e4b8d3f6a0c5e2b7d9a1f4c8e
                  keyId: whsec_main_2026
              selectedEvents:
                summary: Only delivery and problem events, longer timeout
                value:
                  name: Delivery updates
                  url: https://hooks.sinartebet.co.id/shipping-engine
                  secret: 9f2c7a1e4b8d3f6a0c5e2b7d9a1f4c8e
                  eventTypes: [shipment.delivered, shipment.problem_detected, 'shipment.rts_*']
                  timeoutMs: 15000
                  maxAttempts: 10
      responses:
        '201':
          description: |
            The endpoint is saved. It receives events only if `challenge.success` is `true`
            (`verificationStatus: verified`).
          content:
            application/json:
              schema:
                type: object
                required: [statusCode, message, data]
                properties:
                  statusCode: { type: integer, example: 201 }
                  message: { type: string, example: Webhook endpoint registered }
                  data: { $ref: '#/components/schemas/SetWebhookEndpointResult' }
              examples:
                verified:
                  summary: Challenge passed
                  value:
                    statusCode: 201
                    message: Webhook endpoint registered
                    data:
                      id: 41
                      name: Production events
                      url: https://hooks.sinartebet.co.id/shipping-engine
                      isEnabled: true
                      verificationStatus: verified
                      apiVersion: V3
                      timeoutMs: 10000
                      maxAttempts: 8
                      eventTypes: ['shipment.*']
                      activeSecretKeyIds: [whsec_main_2026]
                      createdAt: '2026-11-20T03:00:00.000Z'
                      updatedAt: '2026-11-20T03:00:00.000Z'
                      backoffUntil: null
                      challenge: { success: true, statusCode: 200 }
                failed:
                  summary: Challenge failed on a new endpoint
                  value:
                    statusCode: 201
                    message: Webhook endpoint registered
                    data:
                      id: 41
                      name: Production events
                      url: https://hooks.sinartebet.co.id/shipping-engine
                      isEnabled: true
                      verificationStatus: failed
                      apiVersion: V3
                      timeoutMs: 10000
                      maxAttempts: 8
                      eventTypes: ['shipment.*']
                      activeSecretKeyIds: [whsec_main_2026]
                      createdAt: '2026-11-20T03:00:00.000Z'
                      updatedAt: '2026-11-20T03:00:00.000Z'
                      backoffUntil: null
                      challenge:
                        success: false
                        statusCode: 404
                        responseBody: Not Found
        '400':
          description: A field is invalid.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Error' }
              example:
                statusCode: 400
                message:
                  - Webhook URL must start with https://
                  - secret must be longer than or equal to 32 characters
                error: Bad Request
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '422':
          description: The new URL failed the challenge and your verified endpoint was kept unchanged.
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Error'
                  - type: object
                    properties:
                      challenge: { $ref: '#/components/schemas/WebhookChallengeResult' }
              example:
                statusCode: 422
                error: Unprocessable Entity
                message: The webhook URL could not be verified. The current webhook endpoint stays active and unchanged.
                challenge:
                  success: false
                  error: connect ETIMEDOUT

# ---------------------------------------------------------------- Outbound webhook events
webhooks:
  shipment.dispatched:
    post:
      operationId: webhookShipmentDispatched
      tags: [webhook-events]
      summary: shipment.dispatched
      description: |
        The courier accepted the booking and assigned an airway bill. For API orders this arrives
        right after **Create an order** returns.

        This event has its own **flat** body, unlike the other shipment events: `shipment_id` and
        `order_id` are numeric IDs, and `status` is `PENDING_PICKUP` or `PENDING_DROPOFF`.
      parameters:
        - $ref: '#/components/parameters/WebhookUserAgent'
        - $ref: '#/components/parameters/WebhookId'
        - $ref: '#/components/parameters/WebhookTimestamp'
        - $ref: '#/components/parameters/WebhookSignature'
        - name: x-webhook-event-type
          in: header
          required: true
          description: The event name.
          schema: { type: string, const: shipment.dispatched }
        - $ref: '#/components/parameters/WebhookSchemaVersion'
        - $ref: '#/components/parameters/WebhookAttempt'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShipmentDispatchedEvent' }
            example:
              shipment_id: 18452
              shipment_code: SHP-261120-K9M2Q7
              order_id: 9021
              status: PENDING_DROPOFF
              tracking_id: CM12345678901
              tracking_url: null
              airway_bill: CM12345678901
      responses:
        '200':
          $ref: '#/components/responses/WebhookAccepted'
        4XX:
          $ref: '#/components/responses/WebhookRejected'
        5XX:
          $ref: '#/components/responses/WebhookRetry'

  shipment.pending_pickup:
    post:
      operationId: webhookShipmentPendingPickup
      tags: [webhook-events]
      summary: shipment.pending_pickup
      description: |
        The shipment is waiting for the courier to collect it. Also sent when an instant courier
        assigns a driver: `driver_name`, `driver_phone` and `driver_license_plate` are then filled.
      parameters:
        - $ref: '#/components/parameters/WebhookUserAgent'
        - $ref: '#/components/parameters/WebhookId'
        - $ref: '#/components/parameters/WebhookTimestamp'
        - $ref: '#/components/parameters/WebhookSignature'
        - name: x-webhook-event-type
          in: header
          required: true
          description: The event name.
          schema: { type: string, const: shipment.pending_pickup }
        - $ref: '#/components/parameters/WebhookSchemaVersion'
        - $ref: '#/components/parameters/WebhookAttempt'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShipmentStatusEvent' }
            example:
              booking_id: FSO-261120-B7C8D9
              awb: LLM-260412345
              courier_code: lalamove
              shipment_code: SHP-261120-T3V6X9
              data:
                timestamp: '2026-11-21 02:55:00'
                status: PENDING_PICKUP
                desc: Driver sedang menuju lokasi penjemputan
                note: null
                mapping_code: ON_GOING
                driver_name: Agus Prasetyo
                driver_phone: '081355556666'
                driver_license_plate: B 3456 TKO
                proof_image: null
                receiver_name: null
                receiver_relation: null
                tracking_link: https://share.lalamove.example/t/abc123
      responses:
        '200':
          $ref: '#/components/responses/WebhookAccepted'
        4XX:
          $ref: '#/components/responses/WebhookRejected'
        5XX:
          $ref: '#/components/responses/WebhookRetry'

  shipment.in_transit:
    post:
      operationId: webhookShipmentInTransit
      tags: [webhook-events]
      summary: shipment.in_transit
      description: The courier has the parcel and it is on its way. Sent again for later transit scans.
      parameters:
        - $ref: '#/components/parameters/WebhookUserAgent'
        - $ref: '#/components/parameters/WebhookId'
        - $ref: '#/components/parameters/WebhookTimestamp'
        - $ref: '#/components/parameters/WebhookSignature'
        - name: x-webhook-event-type
          in: header
          required: true
          description: The event name.
          schema: { type: string, const: shipment.in_transit }
        - $ref: '#/components/parameters/WebhookSchemaVersion'
        - $ref: '#/components/parameters/WebhookAttempt'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShipmentStatusEvent' }
            example:
              booking_id: FSO-261120-A1B2C3
              awb: CM12345678901
              courier_code: jne
              shipment_code: SHP-261120-K9M2Q7
              data:
                timestamp: '2026-11-20 08:40:00'
                status: IN_TRANSIT
                desc: Paket diterima di counter agen
                note: null
                mapping_code: RC
                driver_name: null
                driver_phone: null
                driver_license_plate: null
                proof_image: null
                receiver_name: null
                receiver_relation: null
                tracking_link: null
      responses:
        '200':
          $ref: '#/components/responses/WebhookAccepted'
        4XX:
          $ref: '#/components/responses/WebhookRejected'
        5XX:
          $ref: '#/components/responses/WebhookRetry'

  shipment.delivered:
    post:
      operationId: webhookShipmentDelivered
      tags: [webhook-events]
      summary: shipment.delivered
      description: |
        The parcel reached the receiver. `DELIVERED` is final. When the courier provides them,
        `receiver_name`, `receiver_relation` and `proof_image` are filled.
      parameters:
        - $ref: '#/components/parameters/WebhookUserAgent'
        - $ref: '#/components/parameters/WebhookId'
        - $ref: '#/components/parameters/WebhookTimestamp'
        - $ref: '#/components/parameters/WebhookSignature'
        - name: x-webhook-event-type
          in: header
          required: true
          description: The event name.
          schema: { type: string, const: shipment.delivered }
        - $ref: '#/components/parameters/WebhookSchemaVersion'
        - $ref: '#/components/parameters/WebhookAttempt'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShipmentStatusEvent' }
            example:
              booking_id: FSO-261120-A1B2C3
              awb: CM12345678901
              courier_code: jne
              shipment_code: SHP-261120-K9M2Q7
              data:
                timestamp: '2026-11-22 06:18:42'
                status: DELIVERED
                desc: Paket telah diterima
                note: null
                mapping_code: D01
                driver_name: null
                driver_phone: null
                driver_license_plate: null
                proof_image: https://cdn.fastrac.example/pod/SHP-261120-K9M2Q7.jpg
                receiver_name: Rina Kartika
                receiver_relation: YBS
                tracking_link: null
      responses:
        '200':
          $ref: '#/components/responses/WebhookAccepted'
        4XX:
          $ref: '#/components/responses/WebhookRejected'
        5XX:
          $ref: '#/components/responses/WebhookRetry'

  shipment.cancelled:
    post:
      operationId: webhookShipmentCancelled
      tags: [webhook-events]
      summary: shipment.cancelled
      description: |
        The shipment was cancelled. `CANCELLED` is final. What was paid for it is refunded; see
        **List balance logs**.
      parameters:
        - $ref: '#/components/parameters/WebhookUserAgent'
        - $ref: '#/components/parameters/WebhookId'
        - $ref: '#/components/parameters/WebhookTimestamp'
        - $ref: '#/components/parameters/WebhookSignature'
        - name: x-webhook-event-type
          in: header
          required: true
          description: The event name.
          schema: { type: string, const: shipment.cancelled }
        - $ref: '#/components/parameters/WebhookSchemaVersion'
        - $ref: '#/components/parameters/WebhookAttempt'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShipmentStatusEvent' }
            example:
              booking_id: FSO-261120-A1B2C3
              awb: CM12345678901
              courier_code: jne
              shipment_code: SHP-261120-K9M2Q7
              data:
                timestamp: '2026-11-20 04:10:00'
                status: CANCELLED
                desc: Pesanan dibatalkan
                note: null
                mapping_code: null
                driver_name: null
                driver_phone: null
                driver_license_plate: null
                proof_image: null
                receiver_name: null
                receiver_relation: null
                tracking_link: null
      responses:
        '200':
          $ref: '#/components/responses/WebhookAccepted'
        4XX:
          $ref: '#/components/responses/WebhookRejected'
        5XX:
          $ref: '#/components/responses/WebhookRetry'

  shipment.problem_detected:
    post:
      operationId: webhookShipmentProblemDetected
      tags: [webhook-events]
      summary: shipment.problem_detected
      description: |
        The courier reported a problem, such as a lost or damaged parcel or a failed delivery attempt
        that needs attention. The shipment status becomes `PROBLEM_SHIPMENT`. Read `desc` and `note`,
        and contact support if the courier does not resolve it.
      parameters:
        - $ref: '#/components/parameters/WebhookUserAgent'
        - $ref: '#/components/parameters/WebhookId'
        - $ref: '#/components/parameters/WebhookTimestamp'
        - $ref: '#/components/parameters/WebhookSignature'
        - name: x-webhook-event-type
          in: header
          required: true
          description: The event name.
          schema: { type: string, const: shipment.problem_detected }
        - $ref: '#/components/parameters/WebhookSchemaVersion'
        - $ref: '#/components/parameters/WebhookAttempt'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShipmentStatusEvent' }
            example:
              booking_id: FSO-261120-A1B2C3
              awb: CM12345678901
              courier_code: jne
              shipment_code: SHP-261120-K9M2Q7
              data:
                timestamp: '2026-11-21 10:02:00'
                status: PROBLEM_SHIPMENT
                desc: Alamat penerima tidak ditemukan
                note: Nomor rumah tidak sesuai
                mapping_code: U02
                driver_name: null
                driver_phone: null
                driver_license_plate: null
                proof_image: null
                receiver_name: null
                receiver_relation: null
                tracking_link: null
      responses:
        '200':
          $ref: '#/components/responses/WebhookAccepted'
        4XX:
          $ref: '#/components/responses/WebhookRejected'
        5XX:
          $ref: '#/components/responses/WebhookRetry'

  shipment.pickup_failed:
    post:
      operationId: webhookShipmentPickupFailed
      tags: [webhook-events]
      summary: shipment.pickup_failed
      description: |
        The courier could not collect the parcel and won't retry, for example an instant order that
        expired or was rejected because no driver was found. The shipment status becomes
        `PROBLEM_SHIPMENT`. Pickup attempts the courier will retry do not send this event.
      parameters:
        - $ref: '#/components/parameters/WebhookUserAgent'
        - $ref: '#/components/parameters/WebhookId'
        - $ref: '#/components/parameters/WebhookTimestamp'
        - $ref: '#/components/parameters/WebhookSignature'
        - name: x-webhook-event-type
          in: header
          required: true
          description: The event name.
          schema: { type: string, const: shipment.pickup_failed }
        - $ref: '#/components/parameters/WebhookSchemaVersion'
        - $ref: '#/components/parameters/WebhookAttempt'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShipmentStatusEvent' }
            example:
              booking_id: FSO-261120-B7C8D9
              awb: LLM-260412345
              courier_code: lalamove
              shipment_code: SHP-261120-T3V6X9
              data:
                timestamp: '2026-11-21 03:30:00'
                status: PROBLEM_SHIPMENT
                desc: Order expired, no driver available
                note: null
                mapping_code: EXPIRED
                driver_name: null
                driver_phone: null
                driver_license_plate: null
                proof_image: null
                receiver_name: null
                receiver_relation: null
                tracking_link: null
      responses:
        '200':
          $ref: '#/components/responses/WebhookAccepted'
        4XX:
          $ref: '#/components/responses/WebhookRejected'
        5XX:
          $ref: '#/components/responses/WebhookRetry'

  shipment.rts_confirmed:
    post:
      operationId: webhookShipmentRtsConfirmed
      tags: [webhook-events]
      summary: shipment.rts_confirmed
      description: |
        The courier will return the parcel to the sender (RTS). From here the shipment only moves
        through return statuses. A return fee may follow as `shipment.rts_billed`.
      parameters:
        - $ref: '#/components/parameters/WebhookUserAgent'
        - $ref: '#/components/parameters/WebhookId'
        - $ref: '#/components/parameters/WebhookTimestamp'
        - $ref: '#/components/parameters/WebhookSignature'
        - name: x-webhook-event-type
          in: header
          required: true
          description: The event name.
          schema: { type: string, const: shipment.rts_confirmed }
        - $ref: '#/components/parameters/WebhookSchemaVersion'
        - $ref: '#/components/parameters/WebhookAttempt'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShipmentStatusEvent' }
            example:
              booking_id: FSO-261120-A1B2C3
              awb: CM12345678901
              courier_code: jne
              shipment_code: SHP-261120-K9M2Q7
              data:
                timestamp: '2026-11-23 09:00:00'
                status: RTS_CONFIRMED
                desc: Paket akan dikembalikan ke pengirim
                note: Penerima menolak paket
                mapping_code: RTS
                driver_name: null
                driver_phone: null
                driver_license_plate: null
                proof_image: null
                receiver_name: null
                receiver_relation: null
                tracking_link: null
      responses:
        '200':
          $ref: '#/components/responses/WebhookAccepted'
        4XX:
          $ref: '#/components/responses/WebhookRejected'
        5XX:
          $ref: '#/components/responses/WebhookRetry'

  shipment.rts_problem_shipment:
    post:
      operationId: webhookShipmentRtsProblemShipment
      tags: [webhook-events]
      summary: shipment.rts_problem_shipment
      description: The courier reported a problem with a parcel that is being returned to the sender.
      parameters:
        - $ref: '#/components/parameters/WebhookUserAgent'
        - $ref: '#/components/parameters/WebhookId'
        - $ref: '#/components/parameters/WebhookTimestamp'
        - $ref: '#/components/parameters/WebhookSignature'
        - name: x-webhook-event-type
          in: header
          required: true
          description: The event name.
          schema: { type: string, const: shipment.rts_problem_shipment }
        - $ref: '#/components/parameters/WebhookSchemaVersion'
        - $ref: '#/components/parameters/WebhookAttempt'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShipmentStatusEvent' }
            example:
              booking_id: FSO-261120-A1B2C3
              awb: CM12345678901
              courier_code: jne
              shipment_code: SHP-261120-K9M2Q7
              data:
                timestamp: '2026-11-24 11:20:00'
                status: RTS_PROBLEM_SHIPMENT
                desc: Alamat pengirim tidak dapat dihubungi
                note: null
                mapping_code: null
                driver_name: null
                driver_phone: null
                driver_license_plate: null
                proof_image: null
                receiver_name: null
                receiver_relation: null
                tracking_link: null
      responses:
        '200':
          $ref: '#/components/responses/WebhookAccepted'
        4XX:
          $ref: '#/components/responses/WebhookRejected'
        5XX:
          $ref: '#/components/responses/WebhookRetry'

  shipment.rts_transit:
    post:
      operationId: webhookShipmentRtsTransit
      tags: [webhook-events]
      summary: shipment.rts_transit
      description: The returned parcel is on its way back to the sender.
      parameters:
        - $ref: '#/components/parameters/WebhookUserAgent'
        - $ref: '#/components/parameters/WebhookId'
        - $ref: '#/components/parameters/WebhookTimestamp'
        - $ref: '#/components/parameters/WebhookSignature'
        - name: x-webhook-event-type
          in: header
          required: true
          description: The event name.
          schema: { type: string, const: shipment.rts_transit }
        - $ref: '#/components/parameters/WebhookSchemaVersion'
        - $ref: '#/components/parameters/WebhookAttempt'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShipmentStatusEvent' }
            example:
              booking_id: FSO-261120-A1B2C3
              awb: CM12345678901
              courier_code: jne
              shipment_code: SHP-261120-K9M2Q7
              data:
                timestamp: '2026-11-24 07:45:00'
                status: RTS_TRANSIT
                desc: Paket retur dalam perjalanan ke kota asal
                note: null
                mapping_code: null
                driver_name: null
                driver_phone: null
                driver_license_plate: null
                proof_image: null
                receiver_name: null
                receiver_relation: null
                tracking_link: null
      responses:
        '200':
          $ref: '#/components/responses/WebhookAccepted'
        4XX:
          $ref: '#/components/responses/WebhookRejected'
        5XX:
          $ref: '#/components/responses/WebhookRetry'

  shipment.rts_delivered:
    post:
      operationId: webhookShipmentRtsDelivered
      tags: [webhook-events]
      summary: shipment.rts_delivered
      description: |
        The parcel is back with the sender. `RTS_DELIVERED` is final. For a COD shipment no payment
        was collected, so no COD proceeds are paid out.
      parameters:
        - $ref: '#/components/parameters/WebhookUserAgent'
        - $ref: '#/components/parameters/WebhookId'
        - $ref: '#/components/parameters/WebhookTimestamp'
        - $ref: '#/components/parameters/WebhookSignature'
        - name: x-webhook-event-type
          in: header
          required: true
          description: The event name.
          schema: { type: string, const: shipment.rts_delivered }
        - $ref: '#/components/parameters/WebhookSchemaVersion'
        - $ref: '#/components/parameters/WebhookAttempt'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShipmentStatusEvent' }
            example:
              booking_id: FSO-261120-A1B2C3
              awb: CM12345678901
              courier_code: jne
              shipment_code: SHP-261120-K9M2Q7
              data:
                timestamp: '2026-11-25 13:05:00'
                status: RTS_DELIVERED
                desc: Paket dikembalikan ke pengirim
                note: null
                mapping_code: null
                driver_name: null
                driver_phone: null
                driver_license_plate: null
                proof_image: null
                receiver_name: Toko Sinar Tebet
                receiver_relation: null
                tracking_link: null
      responses:
        '200':
          $ref: '#/components/responses/WebhookAccepted'
        4XX:
          $ref: '#/components/responses/WebhookRejected'
        5XX:
          $ref: '#/components/responses/WebhookRetry'

  shipment.airway_bill_updated:
    post:
      operationId: webhookShipmentAirwayBillUpdated
      tags: [webhook-events]
      summary: shipment.airway_bill_updated
      description: |
        The courier replaced the airway bill. The top-level `awb` is the **new** airway bill; update
        your records and any tracking links. When known, `data.awb_before` and `data.awb_after` are
        included. The other `data` fields of status events may be absent.
      parameters:
        - $ref: '#/components/parameters/WebhookUserAgent'
        - $ref: '#/components/parameters/WebhookId'
        - $ref: '#/components/parameters/WebhookTimestamp'
        - $ref: '#/components/parameters/WebhookSignature'
        - name: x-webhook-event-type
          in: header
          required: true
          description: The event name.
          schema: { type: string, const: shipment.airway_bill_updated }
        - $ref: '#/components/parameters/WebhookSchemaVersion'
        - $ref: '#/components/parameters/WebhookAttempt'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShipmentAirwayBillUpdatedEvent' }
            example:
              booking_id: FSO-261120-A1B2C3
              awb: CM98765432109
              courier_code: jne
              shipment_code: SHP-261120-K9M2Q7
              data:
                timestamp: '2026-11-20 09:15:00'
                status: IN_TRANSIT
                desc: Nomor resi diubah oleh kurir
                awb_before: CM12345678901
                awb_after: CM98765432109
      responses:
        '200':
          $ref: '#/components/responses/WebhookAccepted'
        4XX:
          $ref: '#/components/responses/WebhookRejected'
        5XX:
          $ref: '#/components/responses/WebhookRetry'

  shipment.price_changed:
    post:
      operationId: webhookShipmentPriceChanged
      tags: [webhook-events]
      summary: shipment.price_changed
      description: |
        The courier changed the shipping price after it reweighed or remeasured the parcel. Only
        increases on non-COD shipments are charged, from your balance; decreases are not refunded.
        `payment_status` is `failed` when your balance could not cover the difference (Shipping Engine
        support follows up). A `shipment.measurement_changed` event usually accompanies it.
      parameters:
        - $ref: '#/components/parameters/WebhookUserAgent'
        - $ref: '#/components/parameters/WebhookId'
        - $ref: '#/components/parameters/WebhookTimestamp'
        - $ref: '#/components/parameters/WebhookSignature'
        - name: x-webhook-event-type
          in: header
          required: true
          description: The event name.
          schema: { type: string, const: shipment.price_changed }
        - $ref: '#/components/parameters/WebhookSchemaVersion'
        - $ref: '#/components/parameters/WebhookAttempt'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShipmentPriceChangedEvent' }
            example:
              booking_id: FSO-261120-A1B2C3
              awb: CM12345678901
              courier_code: jne
              shipment_code: SHP-261120-K9M2Q7
              data:
                timestamp: '2026-11-21 01:30:00'
                status: IN_TRANSIT
                desc: Price adjusted by courier
                price_before: 12984
                price_after: 19476
                delta: 6492
                payment_status: success
      responses:
        '200':
          $ref: '#/components/responses/WebhookAccepted'
        4XX:
          $ref: '#/components/responses/WebhookRejected'
        5XX:
          $ref: '#/components/responses/WebhookRetry'

  shipment.measurement_changed:
    post:
      operationId: webhookShipmentMeasurementChanged
      tags: [webhook-events]
      summary: shipment.measurement_changed
      description: |
        The courier measured a different weight or size than you declared. The values are display
        text. Any price effect arrives separately as `shipment.price_changed`.
      parameters:
        - $ref: '#/components/parameters/WebhookUserAgent'
        - $ref: '#/components/parameters/WebhookId'
        - $ref: '#/components/parameters/WebhookTimestamp'
        - $ref: '#/components/parameters/WebhookSignature'
        - name: x-webhook-event-type
          in: header
          required: true
          description: The event name.
          schema: { type: string, const: shipment.measurement_changed }
        - $ref: '#/components/parameters/WebhookSchemaVersion'
        - $ref: '#/components/parameters/WebhookAttempt'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShipmentMeasurementChangedEvent' }
            example:
              booking_id: FSO-261120-A1B2C3
              awb: CM12345678901
              courier_code: jne
              shipment_code: SHP-261120-K9M2Q7
              data:
                timestamp: '2026-11-21 01:30:00'
                status: IN_TRANSIT
                desc: Measurement adjusted by courier
                measurement_before: weight=1200g, dimension=30x20x10cm
                measurement_after: weight=1800g, dimension=32x22x12cm
      responses:
        '200':
          $ref: '#/components/responses/WebhookAccepted'
        4XX:
          $ref: '#/components/responses/WebhookRejected'
        5XX:
          $ref: '#/components/responses/WebhookRetry'

  shipment.rts_billed:
    post:
      operationId: webhookShipmentRtsBilled
      tags: [webhook-events]
      summary: shipment.rts_billed
      description: |
        A return-to-sender fee was charged for this shipment, from your balance. `payment_status` is
        `failed` when your balance could not cover it; the fee then stays unpaid and Shipping Engine
        support follows up.
      parameters:
        - $ref: '#/components/parameters/WebhookUserAgent'
        - $ref: '#/components/parameters/WebhookId'
        - $ref: '#/components/parameters/WebhookTimestamp'
        - $ref: '#/components/parameters/WebhookSignature'
        - name: x-webhook-event-type
          in: header
          required: true
          description: The event name.
          schema: { type: string, const: shipment.rts_billed }
        - $ref: '#/components/parameters/WebhookSchemaVersion'
        - $ref: '#/components/parameters/WebhookAttempt'
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShipmentRtsBilledEvent' }
            example:
              booking_id: FSO-261120-A1B2C3
              awb: CM12345678901
              courier_code: jne
              shipment_code: SHP-261120-K9M2Q7
              data:
                timestamp: '2026-11-25 13:10:00'
                status: RTS_DELIVERED
                desc: Tagihan retur (RTS) resi CM12345678901
                rts_fee: 9000
                payment_status: success
      responses:
        '200':
          $ref: '#/components/responses/WebhookAccepted'
        4XX:
          $ref: '#/components/responses/WebhookRejected'
        5XX:
          $ref: '#/components/responses/WebhookRetry'

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: |
        An access token from the OAuth2 client-credentials grant. Exchange your API key
        (`client_id` + `client_secret`) at the token endpoint and send
        `Authorization: Bearer <access_token>`.

  parameters:
    Limit:
      name: limit
      in: query
      description: Items per page. Values above 100 are capped at 100.
      schema: { type: integer, minimum: 1, maximum: 100, default: 25, example: 25 }
    Cursor:
      name: cursor
      in: query
      description: The `nextCursor` from the previous page. Omit for the first page.
      schema: { type: string, example: MTg0NTI= }
    ShipmentCode:
      name: shipmentCode
      in: path
      required: true
      description: The shipment `code` from **Create an order** or **List shipments**.
      schema: { type: string, pattern: '^SHP-[0-9]{6}-[A-Z0-9]{6}$', example: SHP-261120-K9M2Q7 }
    WebhookUserAgent:
      name: user-agent
      in: header
      required: true
      description: Always `Fastrac-Webhook-Client/1.0`.
      schema: { type: string, example: Fastrac-Webhook-Client/1.0 }
    WebhookId:
      name: x-webhook-id
      in: header
      required: true
      description: Unique event ID. The same on every retry of one event; use it to drop duplicates.
      schema: { type: string, format: uuid, example: 3f9b2c1e-7a4d-4e8b-9c2f-1d5e6a7b8c9d }
    WebhookTimestamp:
      name: x-webhook-timestamp
      in: header
      required: true
      description: Unix time in seconds when this attempt was sent. Part of the signed string; reject requests more than 300 seconds old.
      schema: { type: string, pattern: '^[0-9]+$', example: '1795140000' }
    WebhookSignature:
      name: x-webhook-signature
      in: header
      required: true
      description: |
        `keyId=<keyId>,sig=<hex>`, where `sig` is
        `hex(HMAC_SHA256(secret, "<x-webhook-timestamp>.<x-webhook-id>.<hex(SHA256(raw body))>"))`.
        Compute it on the raw request bytes and compare in constant time.
      schema: { type: string, example: 'keyId=whsec_main_2026,sig=5d41402abc4b2a76b9719d911017c592ae2d1f8a2b3c4d5e6f708192a3b4c5d6' }
    WebhookSchemaVersion:
      name: x-webhook-schema-version
      in: header
      required: true
      description: Version of the event body format.
      schema: { type: string, example: '2025-10-01' }
    WebhookAttempt:
      name: x-webhook-attempt
      in: header
      required: true
      description: Delivery attempt number, starting at `1`.
      schema: { type: string, pattern: '^[0-9]+$', example: '1' }

  responses:
    BadRequest:
      description: The request is invalid. `message` is an array when field validation fails.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            validation:
              summary: Field validation
              value:
                statusCode: 400
                message:
                  - packages.0.itemValue must not be less than 15000
                  - courierCode should not be empty
                error: Bad Request
            insurance:
              summary: Missing insurance flag
              value:
                statusCode: 400
                message: insurance parameter is required for regular shipments (cannot be empty)
                error: Bad Request
    QueryValidation:
      description: A query parameter is invalid. `message` lists each problem.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          example:
            statusCode: 400
            message:
              - limit must be a positive number
              - startDate must be a valid ISO 8601 date string
            error: Bad Request
    InvalidDateRange:
      description: '`startDate` is later than `endDate`, or a date can''t be read.'
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          example:
            statusCode: 422
            message: startDate cannot be later than endDate.
            error: Unprocessable Entity
    RegionQueryInvalid:
      description: The parent ID is missing or not a number.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            missing:
              summary: Missing parameter
              value:
                statusCode: 400
                message: "Query parameter 'provinceId' is required."
                error: Bad Request
            notNumber:
              summary: Not a number
              value:
                statusCode: 400
                message: "Query parameter 'provinceId' must be a valid number."
                error: Bad Request
    Unauthorized:
      description: The token is missing, expired or invalid.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          example:
            statusCode: 401
            message: Missing authorization header
            error: Unauthorized
    Forbidden:
      description: Your API key's role lacks a permission this operation requires.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          examples:
            permission:
              summary: Missing permission
              value:
                statusCode: 403
                message: "You're not authorized to access this resource (Missing permissions: READ_ORDER)."
                error: Forbidden
            cod:
              summary: COD quote without USE_COD
              value:
                statusCode: 403
                message: "You're not authorized to access this resource (Missing permissions: CREATE_ORDER)."
                error: Forbidden
    WebhookAccepted:
      description: |
        Any `2xx` within your endpoint's `timeoutMs` (default 10 seconds) marks the event delivered.
        The response body is ignored. Answer quickly and process the event asynchronously.
    WebhookRejected:
      description: |
        `408`, `409` and `429` are retried. Any other `4xx` is treated as a permanent failure and the
        event is **not** retried. Redirects (`3xx`) are not followed and not retried.
    WebhookRetry:
      description: |
        Retried with exponential backoff (1, 2, 4, 8, 16, 32, 64 seconds) up to the endpoint's
        `maxAttempts` (default 8). Timeouts and network errors are retried the same way. Events older
        than 24 hours are not retried.

  examples:
    RegularRatesResponse:
      summary: One JNE rate
      value:
        statusCode: 201
        message: Shipping rate created successfully.
        data:
          - shippingRateCode: SR-7KQ2M9XA
            validUntil: '2026-11-20T09:15:00.000Z'
            courierCode: JNE
            serviceName: JNE Reguler
            serviceType: REGULAR
            etdRange: 2 - 3 Days
            isSupportCod: true
            isSupportDropOff: true
            isSupportPickup: true
            priceDetail:
              basePrice: 10000
              fastracPrice: 9000
              discountBreakdown: { discountPercentage: 10, discountAmount: 1000 }
              insuranceBreakdown: { insurancePercent: 0.25, insuranceMinimum: 1500, insuranceAdminFee: 2000, insurance: 3500 }
              taxBreakdown: { ppnInsurance: 385, ppnShipment: 99, ppnCod: 0 }
              totalPrice: 12984
              currency: IDR
              totalPriceCalculation: fastracPrice + insurance + ppnInsurance + ppnShipment
            dimension: { length: 30, width: 20, height: 10, weight: 1200 }
            origin:
              fullAddress: Jl. Tebet Raya No. 12, Tebet Barat, Jakarta Selatan
              subdistrictId: '3174091001'
            destinations:
              - fullAddress: Jl. Braga No. 8, Braga, Sumur Bandung, Kota Bandung
                coordinate: { latitude: '', longitude: '' }
                stopOrder: 1
                packages:
                  - packageCode: PKG-3M8XQ1
                    packageTypeId: null
                    value: '500000'
                    isGlassware: false
                    length: 30
                    width: 20
                    height: 10
                    weight: 1200
                    description: null
                    packageNote: null

    OrderResponse:
      summary: JNE drop-off, paid from balance
      value:
        statusCode: 201
        message: Resource created successfully.
        data:
          id: 9021
          code: FSO-261120-A1B2C3
          userId: 512
          status: CONFIRMED
          createdAt: '2026-11-20T02:05:10.000Z'
          paidAt: '2026-11-20T02:05:12.000Z'
          dateFinished: null
          price:
            amount: 12984
            currency: IDR
            codBilled: 0
            codDisbursement: 0
          activePayment: null
          shipments:
            - id: 18452
              orderId: 9021
              shippingRateId: 66310
              code: SHP-261120-K9M2Q7
              courierCode: JNE
              courierName: JNE
              etdRange: 2 - 3 Days
              serviceName: JNE Reguler
              type: REGULAR
              status: PENDING_DROPOFF
              fulfillmentMethod: DROPOFF
              pickupSchedule: null
              isCod: false
              isInsured: true
              shippingDistanceMeter: 0
              airwayBill: CM12345678901
              trackingUrl: null
              finishedAt: null
              histories:
                - timestamp: '2026-11-20T02:05:13.000Z'
                  status: PENDING_DROPOFF
                  description: Shipment booked with courier
              priceDetail:
                basePrice: 10000
                fastracPrice: 9000
                discountBreakdown: { discountPercentage: 10, discountAmount: 1000 }
                totalPrice: 12984
                insuranceBreakdown: { insurancePercent: 0.25, insuranceMinimum: 1500, insuranceAdminFee: 2000, insurance: 3500 }
                taxBreakdown: { ppnInsurance: 385, ppnShipment: 99, ppnCod: 0 }
                currency: IDR
                totalPriceCalculation: fastracPrice + insurance + ppnInsurance + ppnShipment
              sender:
                name: Toko Sinar Tebet
                email: gudang@sinartebet.co.id
                whatsappNumber: '081211112222'
                location:
                  fullAddress: Jl. Tebet Raya No. 12, Tebet Barat, Jakarta Selatan
                  subdistrictId: '3174091001'
                createdAt: '2026-11-20T02:05:10.000Z'
              receivers:
                - shipmentId: 18452
                  name: Rina Kartika
                  phoneNumber: '081298765432'
                  addressNote: Rumah pagar hijau, sebelah warung kopi
                  label: Rumah
                  fullAddress: Jl. Braga No. 8, Braga, Sumur Bandung, Kota Bandung
                  regionMappingId: '3273011003'
                  createdAt: '2026-11-20T02:05:10.000Z'

    ShipmentDetailResponse:
      summary: Regular shipment in transit
      value:
        statusCode: 200
        message: Shipment detail retrieved.
        data:
          id: 18452
          code: SHP-261120-K9M2Q7
          orderId: 9021
          orderCode: FSO-261120-A1B2C3
          source: B2B
          userId: 512
          status: IN_TRANSIT
          type: REGULAR
          courierServiceId: 12
          courierServiceCode: REG
          courierServiceName: JNE Reguler
          courierCode: JNE
          airwayBill: CM12345678901
          trackingUrl: null
          etdRange: 2 - 3 Days
          isInsured: true
          shippingDistanceMeter: 0
          finishedAt: null
          createdAt: '2026-11-20T02:05:13.000Z'
          price: { amount: 12500, currency: IDR }
          shippingRateId: 66310
          shippingRateCode: SR-7KQ2M9XA
          sender:
            name: Toko Sinar Tebet
            email: gudang@sinartebet.co.id
            whatsappNumber: '081211112222'
            fullAddress: Jl. Tebet Raya No. 12, Tebet Barat, Jakarta Selatan
            province: DKI Jakarta
            city: Kota Jakarta Selatan
            district: Tebet
            subdistrict: Tebet Barat
            postCode: '12810'
            createdAt: '2026-11-20T02:05:10.000Z'
          receivers:
            - name: Rina Kartika
              phoneNumber: '081298765432'
              fullAddress: Jl. Braga No. 8, Braga, Sumur Bandung, Kota Bandung
              addressNote: Rumah pagar hijau, sebelah warung kopi
              label: Rumah
              province: Jawa Barat
              city: Kota Bandung
              district: Sumur Bandung
              subdistrict: Braga
              postCode: '40111'
              createdAt: '2026-11-20T02:05:10.000Z'
          histories:
            - timestamp: '2026-11-20T02:05:13.000Z'
              status: PENDING_DROPOFF
              description: Shipment booked with courier
            - timestamp: '2026-11-20T08:40:00.000Z'
              status: IN_TRANSIT
              description: Paket diterima di counter agen
          packageDetails:
            - id: 30117
              shipmentId: 18452
              shippingRatePackageDetailId: 88104
              shippingRatePackageCode: PKG-3M8XQ1
              declaredValue: 500000
              packagePhotoUrls: []
              isGlassware: false
              length: 30
              width: 20
              height: 10
              weight: 1200
              actualDimension: 0
              actualWeight: 0
              description: null
              packageNote: Jangan dibanting
          driverDetails: null

  schemas:
    # ------------------------------------------------ Regions
    RegionSearchResult:
      type: object
      properties:
        id: { type: string, description: 'Use as `subdistrictId`.', example: '3174091001' }
        name: { type: string, description: 'Subdistrict, district, city and province, comma-separated.', example: 'Tebet Barat, Tebet, Kota Jakarta Selatan, DKI Jakarta' }
        postCode: { type: [integer, 'null'], description: 'Postal code as a number, `null` when unknown.', example: 12810 }

    Province:
      type: object
      properties:
        id: { type: integer, example: 31 }
        name: { type: string, example: DKI Jakarta }
        countryId: { type: [integer, 'null'], example: 1 }

    City:
      type: object
      properties:
        id: { type: integer, example: 3174 }
        name: { type: string, example: Kota Jakarta Selatan }
        provinceId: { type: integer, example: 31 }
        cityType:
          type: string
          enum: [CITY, REGENCY]
          description: '`CITY` for a kota, `REGENCY` for a kabupaten.'

    District:
      type: object
      properties:
        id: { type: integer, example: 317409 }
        name: { type: string, example: Tebet }
        cityId: { type: integer, example: 3174 }

    Subdistrict:
      type: object
      properties:
        id: { type: string, description: 'Use as `subdistrictId`.', example: '3174091001' }
        name: { type: string, example: Tebet Barat }
        districtId: { type: integer, example: 317409 }
        postCode: { type: [integer, 'null'], example: 12810 }

    PostCodeRegion:
      type: object
      properties:
        provinceId: { type: integer, example: 32 }
        provinceName: { type: string, example: Jawa Barat }
        cityId: { type: integer, example: 3273 }
        cityName: { type: string, example: Kota Bandung }
        districtId: { type: integer, example: 327301 }
        district: { type: string, example: Sumur Bandung }
        subdistrictId: { type: integer, description: 'Send as a string `subdistrictId` in rate requests.', example: 3273011003 }
        subdistrict: { type: string, example: Braga }
        postCode: { type: [integer, 'null'], example: 40111 }

    # ------------------------------------------------ Couriers & catalog
    Courier:
      type: object
      properties:
        code: { type: string, description: 'Use as `courierCode` in rate requests.', example: JNE }
        name: { type: string, example: JNE }
        isEnabled: { type: boolean, description: The courier is switched on. }
        hasEnabledServices: { type: boolean, description: At least one of its services is switched on. }
        isOperational: { type: boolean, description: '`isEnabled` and `hasEnabledServices`: the courier can be quoted.' }
        logoUrl: { type: [string, 'null'], format: uri }
        logoUrlBw: { type: [string, 'null'], format: uri, description: Monochrome logo. }
        logoSquareUrl: { type: [string, 'null'], format: uri }
        bgColor: { type: [string, 'null'], description: Brand colour as a hex code., example: '#0B3C8C' }
        supportedCourierTypes:
          type: array
          items: { type: string, enum: [INSTANT, REGULAR] }

    CourierWithServices:
      type: object
      properties:
        courierCode: { type: string, example: JNE }
        courierId: { type: integer, example: 3 }
        isEnabled: { type: boolean }
        supportedTypes:
          type: array
          items: { type: string, enum: [INSTANT, REGULAR] }
        services:
          type: array
          items: { $ref: '#/components/schemas/CourierService' }

    CourierService:
      type: object
      properties:
        id: { type: integer, description: 'Use as `courierServiceId` when filtering shipments.', example: 12 }
        code: { type: string, example: REG }
        courierCode: { type: string, example: JNE }
        courierId: { type: integer, example: 3 }
        name: { type: string, description: 'Shown as `serviceName` in rates.', example: JNE Reguler }
        type:
          type: string
          enum: [INSTANT, SAMEDAY, NEXTDAY, REGULAR, CARGO]
        vehicle: { type: [string, 'null'], description: 'Vehicle for instant services, for example `BIKE` or `CAR`.', example: null }
        defaultDiscountPercentage: { type: number, description: 'Usual discount off the courier list price, in percent.', example: 10 }
        etdMinimumDay: { type: integer, example: 2 }
        etdMaximumDay: { type: integer, example: 3 }
        isEnabled: { type: boolean }
        volumetricConversion:
          type: number
          description: 'Divisor for volumetric weight: `length × width × height (cm) / volumetricConversion` = kg.'
          example: 6000
        freeRts: { type: boolean }
        shippingRateTtlSeconds:
          type: [integer, 'null']
          description: How long a rate from this service stays valid, in seconds. `null` uses the default.
          example: 900

    PackageType:
      type: object
      properties:
        id: { type: string, description: 'Send as a number in `packages[].packageTypeId`.', example: '8' }
        category: { type: string, example: Frozen }

    # ------------------------------------------------ Shipping rates
    Coordinate:
      type: object
      required: [latitude, longitude]
      properties:
        latitude: { type: number, minimum: -90, maximum: 90, example: -6.2265 }
        longitude: { type: number, minimum: -180, maximum: 180, example: 106.8521 }

    Location:
      type: object
      required: [fullAddress, subdistrictId]
      properties:
        fullAddress:
          type: string
          description: The full street address, as you would write it on a label.
          example: Jl. Tebet Raya No. 12, Tebet Barat, Jakarta Selatan
        subdistrictId:
          type: string
          pattern: '^[0-9]+$'
          description: Subdistrict ID from **Search regions**. Sent as a numeric string.
          example: '3174091001'
        coordinate:
          $ref: '#/components/schemas/Coordinate'
          description: Exact pin. Strongly recommended for instant couriers, and required later to book a regular **pickup**.
        googleAddress:
          type: string
          description: Google Maps formatted address, for more precise matching.

    Destination:
      allOf:
        - $ref: '#/components/schemas/Location'
        - type: object
          properties:
            stopOrder:
              type: integer
              minimum: 1
              description: Position of this stop. Required, and unique, when you send more than one destination.

    Package:
      type: object
      required: [itemValue, isGlassware, weight, dimension]
      properties:
        itemValue:
          type: integer
          minimum: 15000
          maximum: 100000000
          description: Declared value of the contents in IDR. Used for insurance and COD.
          example: 500000
        isGlassware:
          type: boolean
          description: Marks fragile contents. Send a JSON boolean, not a string.
          example: false
        weight:
          type: integer
          minimum: 0
          maximum: 100000
          description: Actual weight in **grams**.
          example: 1200
        dimension:
          type: object
          required: [length, width, height]
          description: Box size in **centimetres**. Each side is at most 250 cm.
          properties:
            length: { type: number, minimum: 0, maximum: 250, example: 30 }
            width: { type: number, minimum: 0, maximum: 250, example: 20 }
            height: { type: number, minimum: 0, maximum: 250, example: 10 }
        packageTypeId:
          type: integer
          minimum: 1
          description: Package category from **List package types**. Some courier services refuse certain categories.
        description: { type: string, description: What is inside the package. }
        packageNote: { type: string, description: Handling note for the courier. }

    ShippingRateRequest:
      type: object
      required: [origin, destinations, courierCode, packages]
      properties:
        origin:
          $ref: '#/components/schemas/Location'
        destinations:
          type: array
          minItems: 1
          items: { $ref: '#/components/schemas/Destination' }
        courierCode:
          type: string
          description: |
            A courier code such as `JNE`, `JNT`, `SPX`, `LALAMOVE`, or one of these to compare many
            couriers at once: `REGULAR` (all regular couriers), `INSTANT` (all instant couriers),
            `ALL` (everything). Case-insensitive.
          example: JNE
        vehicle:
          type: string
          description: Required when `courierCode` is `PAXEL`, `LALAMOVE`, `DASH`, `GRAB` or `INSTANT`. For example `BIKE` or `CAR`.
          example: BIKE
        packages:
          type: array
          minItems: 1
          description: Every package travels together. Multiple packages are combined into one parcel for pricing.
          items: { $ref: '#/components/schemas/Package' }
        insurance:
          type: boolean
          description: Add insurance to the price. **Required for every courier except PAXEL, LALAMOVE, DASH and GRAB.**
        scheduledAt:
          type: string
          format: date-time
          description: Pickup time to quote, ISO 8601 with offset. Omit for as soon as possible. LALAMOVE and DASH book exactly this time.
          example: '2026-11-21T10:00:00+07:00'
        codOption:
          type: object
          description: Cash on delivery. Requires the `USE_COD` permission.
          required: [isCod]
          properties:
            isCod: { type: boolean, description: Collect payment from the receiver. }
            codCustomAmount:
              type: integer
              minimum: 0
              description: Amount to collect instead of the default. Must cover `totalPrice + codFee + ppnCod`.

    ShippingRate:
      type: object
      properties:
        shippingRateCode:
          type: string
          description: Quote identifier. Pass it to **Create an order**.
          example: SR-7KQ2M9XA
        validUntil:
          type: string
          format: date-time
          description: After this time the code can no longer be used to create an order. Typically 15 minutes after the quote.
        courierCode: { type: string, example: JNE }
        serviceName: { type: string, example: JNE Reguler }
        serviceType:
          type: string
          enum: [INSTANT, SAMEDAY, NEXTDAY, REGULAR, CARGO]
        etdRange:
          type: [string, 'null']
          description: Estimated delivery time as display text, for example `2 - 3 Days`.
          example: 2 - 3 Days
        isSupportCod: { type: boolean }
        isSupportDropOff: { type: boolean, description: You can drop the parcel at a courier counter. }
        isSupportPickup: { type: boolean, description: The courier can collect the parcel from the origin. }
        priceDetail:
          $ref: '#/components/schemas/PriceDetail'
        dimension:
          type: [object, 'null']
          description: The combined parcel that was priced.
          properties:
            length: { type: number }
            width: { type: number }
            height: { type: number }
            weight: { type: number, description: grams }
        origin:
          $ref: '#/components/schemas/Location'
        destinations:
          type: array
          items:
            type: object
            properties:
              fullAddress: { type: string }
              coordinate:
                type: object
                description: Strings; empty when no coordinate was sent.
                properties:
                  latitude: { type: string }
                  longitude: { type: string }
              stopOrder: { type: integer }
              packages:
                type: array
                items:
                  type: object
                  properties:
                    packageCode: { type: string, description: Pass as `shippingRatePackageCode` when creating the order. }
                    packageTypeId: { type: [integer, 'null'] }
                    value: { type: string, description: 'Declared value in IDR, as a string.' }
                    isGlassware: { type: boolean }
                    length: { type: number }
                    width: { type: number }
                    height: { type: number }
                    weight: { type: number }
                    description: { type: [string, 'null'] }
                    packageNote: { type: [string, 'null'] }

    PriceDetail:
      type: object
      description: All amounts are whole Rupiah.
      properties:
        basePrice: { type: integer, description: Courier list price before discount. }
        fastracPrice: { type: integer, description: Shipping price after the Fastrac discount. }
        discountBreakdown:
          type: object
          properties:
            discountPercentage: { type: number }
            discountAmount: { type: integer }
        insuranceBreakdown:
          type: object
          description: All zero when `insurance` is false.
          properties:
            insurancePercent: { type: number, description: Premium as a percentage of `itemValue`. }
            insuranceMinimum: { type: integer, description: Lowest premium charged. }
            insuranceAdminFee: { type: integer, description: Fixed fee added to the premium. }
            insurance: { type: integer, description: 'Total insurance charge, admin fee included.' }
        taxBreakdown:
          type: object
          description: PPN (Indonesian VAT).
          properties:
            ppnInsurance: { type: integer, description: 11% of `insurance`. }
            ppnShipment: { type: integer, description: 1.1% of `fastracPrice`. }
            ppnCod: { type: integer, description: 11% of `codFee`. }
        totalPrice:
          type: integer
          description: What is deducted from your balance when you order. `fastracPrice + insurance + ppnInsurance + ppnShipment`.
        currency: { type: string, example: IDR }
        totalPriceCalculation: { type: string, description: 'The formula used, for display or debugging.' }
        codBreakdown:
          type: object
          description: Present only for COD rates.
          properties:
            itemValue: { type: integer }
            codBilled: { type: integer, description: Amount the courier collects from the receiver. }
            codDisbursement: { type: integer, description: Amount paid out to you after delivery. }
            codFee: { type: integer }
            codFeePercent: { type: number }
            codCustom: { type: integer }
        codCalculation: { type: string, description: The COD formula used. }

    # ------------------------------------------------ Orders
    CreateOrderRequest:
      type: object
      required: [shipments]
      properties:
        shipments:
          type: array
          minItems: 1
          description: One entry per shipping rate. All shipments must be either COD or non-COD.
          items: { $ref: '#/components/schemas/CreateOrderShipment' }

    CreateOrderShipment:
      type: object
      required: [shippingRateCode, sender, receivers]
      properties:
        shippingRateCode:
          type: string
          description: A valid (not expired) `shippingRateCode` from **Get shipping rates**.
          example: SR-7KQ2M9XA
        sender: { $ref: '#/components/schemas/OrderSender' }
        receivers:
          type: array
          minItems: 1
          description: One receiver per rate destination, in the same order as the rate's `destinations`.
          items: { $ref: '#/components/schemas/OrderReceiver' }
        shippingOptions: { $ref: '#/components/schemas/ShippingOptions' }
        packages:
          type: array
          description: Optional per-package notes. Weights, sizes and values come from the rate.
          items:
            type: object
            required: [shippingRatePackageCode]
            properties:
              shippingRatePackageCode:
                type: string
                description: '`destinations[].packages[].packageCode` from the rate.'
                example: PKG-3M8XQ1
              packageNote:
                type: string
                description: Handling note for the courier.
                example: Jangan dibanting

    OrderSender:
      type: object
      required: [name, email]
      description: 'The sender''s address comes from the rate''s `origin`. Send `whatsappNumber` or `phoneNumber` (at least one).'
      properties:
        name: { type: string, description: Sender name printed on the label., example: Toko Sinar Tebet }
        email: { type: string, format: email, example: gudang@sinartebet.co.id }
        whatsappNumber: { type: string, description: Indonesian phone number. Preferred over `phoneNumber` when both are sent., example: '081211112222' }
        phoneNumber: { type: string, description: Indonesian phone number. Used when `whatsappNumber` is absent., example: '081211112222' }
        coordinate:
          type: object
          description: |
            Exact pickup pin, as **strings**. Required for a regular-courier `PICKUP`. If omitted, the
            rate's origin coordinate is used when it has one.
          properties:
            latitude: { type: string, example: '-6.2265' }
            longitude: { type: string, example: '106.8521' }

    OrderReceiver:
      type: object
      required: [name, phoneNumber, addressNote, label, stopSequence]
      description: The receiver's address comes from the matching rate destination.
      properties:
        name: { type: string, example: Rina Kartika }
        phoneNumber: { type: string, example: '081298765432' }
        addressNote: { type: string, description: Directions for the courier., example: 'Rumah pagar hijau, sebelah warung kopi' }
        label: { type: string, description: 'Short address label, for example `Rumah` or `Kantor`.', example: Rumah }
        stopSequence: { type: number, description: Stop number; use the destination's `stopOrder`., example: 1 }

    ShippingOptions:
      type: object
      required: [fulfillmentMethod]
      properties:
        fulfillmentMethod:
          type: string
          enum: [PICKUP, DROPOFF]
          description: |
            `PICKUP`: the courier collects at the origin. `DROPOFF`: you bring the parcel to a courier
            counter. The rate's service must support it (`isSupportPickup` / `isSupportDropOff`).
            Without `shippingOptions`, instant services use `PICKUP` and others `DROPOFF`.
        schedule:
          type: string
          format: date-time
          description: |
            Pickup time, ISO 8601 with offset (`PICKUP` only). At least 15 minutes ahead in
            Asia/Jakarta time. Omitted: now + 15 minutes, or as soon as possible for Lalamove and Dash
            instant services. For Lalamove and Dash instant services it must equal the rate's `scheduledAt`.
          example: '2026-11-21T10:00:00+07:00'

    Order:
      type: object
      properties:
        id: { type: integer, example: 9021 }
        code: { type: string, description: Order code. Use it to cancel the order., example: FSO-261120-A1B2C3 }
        userId: { type: integer, example: 512 }
        status:
          type: string
          enum: [DRAFT, CONFIRMED, CANCELLED]
          description: '`CONFIRMED` once paid and booked. Track delivery on each shipment''s `status`, not here.'
        createdAt: { type: string, format: date-time }
        paidAt: { type: [string, 'null'], format: date-time }
        dateFinished: { type: [string, 'null'], format: date-time }
        price:
          type: object
          properties:
            amount: { type: integer, description: 'Total charged to your balance. `0` for COD orders.', example: 12984 }
            currency: { type: string, example: IDR }
            codBilled: { type: integer, description: Total the couriers collect from receivers (COD only). }
            codDisbursement: { type: integer, description: Total paid out to you after delivery (COD only). }
        activePayment: { type: 'null', description: Always `null` for API orders. }
        shipments:
          type: array
          items: { $ref: '#/components/schemas/OrderShipment' }

    OrderShipment:
      type: object
      properties:
        id: { type: integer, example: 18452 }
        orderId: { type: integer, example: 9021 }
        shippingRateId: { type: integer, example: 66310 }
        code: { type: string, description: 'Shipment code. Use it to track, retrieve or cancel.', example: SHP-261120-K9M2Q7 }
        courierCode: { type: string, example: JNE }
        courierName: { type: string, example: JNE }
        etdRange: { type: [string, 'null'], example: 2 - 3 Days }
        serviceName: { type: string, example: JNE Reguler }
        type: { type: string, enum: [INSTANT, SAMEDAY, NEXTDAY, REGULAR, CARGO] }
        status: { $ref: '#/components/schemas/ShipmentStatus' }
        fulfillmentMethod: { type: string, enum: [PICKUP, DROPOFF] }
        pickupSchedule:
          oneOf:
            - $ref: '#/components/schemas/PickupSchedule'
            - type: 'null'
          description: '`null` for drop-off.'
        isCod: { type: boolean }
        isInsured: { type: boolean }
        shippingDistanceMeter: { type: number, description: Route distance for instant couriers; `0` otherwise. }
        airwayBill: { type: [string, 'null'], description: The courier's tracking number (resi)., example: CM12345678901 }
        trackingUrl: { type: [string, 'null'], format: uri, description: 'Courier tracking page, when the courier provides one.' }
        finishedAt: { type: [string, 'null'], format: date-time }
        histories:
          type: array
          items: { $ref: '#/components/schemas/ShipmentHistoryEvent' }
        priceDetail: { $ref: '#/components/schemas/PriceDetail' }
        sender:
          type: object
          properties:
            name: { type: string }
            email: { type: string }
            whatsappNumber: { type: string }
            location:
              type: object
              properties:
                fullAddress: { type: string }
                googleAddress: { type: string }
                subdistrictId: { type: string }
                coordinate:
                  type: object
                  properties:
                    latitude: { type: string }
                    longitude: { type: string }
            createdAt: { type: string, format: date-time }
        receivers:
          type: array
          items:
            type: object
            properties:
              shipmentId: { type: integer }
              name: { type: string }
              phoneNumber: { type: string }
              addressNote: { type: string }
              label: { type: string }
              fullAddress: { type: string }
              googleAddress: { type: string }
              coordinate:
                type: object
                properties:
                  latitude: { type: string }
                  longitude: { type: string }
              regionMappingId: { type: [string, 'null'], description: Destination subdistrict ID. }
              createdAt: { type: string, format: date-time }

    PickupSchedule:
      type: object
      properties:
        scheduledAt:
          type: [string, 'null']
          format: date-time
          description: Pickup time in Asia/Jakarta with offset. `null` means as soon as possible.
          example: '2026-11-21T10:00:00+07:00'
        asSoonAsPossible: { type: boolean }

    ShipmentHistoryEvent:
      type: object
      properties:
        timestamp: { type: string, format: date-time }
        status: { type: string, description: 'A shipment status, for example `IN_TRANSIT`.', example: IN_TRANSIT }
        description: { type: string, description: 'Event text, often in Indonesian as the courier sent it.', example: Paket diterima di counter agen }
        location: { type: string, description: 'Scan location, when the courier provides it.', example: JAKARTA SELATAN }

    # ------------------------------------------------ Shipments
    ShipmentStatus:
      type: string
      description: |
        `WAITING_FOR_PAYMENT` → `CONFIRMED` → `PENDING_PICKUP` or `PENDING_DROPOFF` → `IN_TRANSIT` →
        `DELIVERED` (final). Side states: `PROBLEM_SHIPMENT`, `CANCELLED`. Return to sender:
        `RTS_CONFIRMED` → `RTS_TRANSIT` / `RTS_PROBLEM_SHIPMENT` → `RTS_DELIVERED` (final).
      enum:
        - WAITING_FOR_PAYMENT
        - CONFIRMED
        - PENDING_PICKUP
        - PENDING_DROPOFF
        - IN_TRANSIT
        - PROBLEM_SHIPMENT
        - DELIVERED
        - CANCELLED
        - RTS_CONFIRMED
        - RTS_TRANSIT
        - RTS_PROBLEM_SHIPMENT
        - RTS_DELIVERED
      example: IN_TRANSIT

    ShipmentList:
      type: object
      properties:
        count:
          type: object
          description: Shipments per status within the date range.
          properties:
            PENDING_PICKUP: { type: integer }
            PENDING_DROPOFF: { type: integer }
            IN_TRANSIT: { type: integer }
            DELIVERED: { type: integer }
            CANCELLED: { type: integer }
            RTS: { type: integer, description: '`RTS_CONFIRMED` + `RTS_TRANSIT`.' }
        shipments:
          type: array
          items: { $ref: '#/components/schemas/ShipmentListItem' }
        nextCursor: { type: [string, 'null'], description: Pass as `cursor` for the next page. `null` on the last page. }

    ShipmentListItem:
      type: object
      properties:
        id: { type: integer, example: 18452 }
        code: { type: string, example: SHP-261120-K9M2Q7 }
        orderId: { type: integer, example: 9021 }
        orderCode: { type: string, example: FSO-261120-A1B2C3 }
        source: { type: [string, 'null'], example: B2B }
        userId: { type: integer }
        userEmail: { type: [string, 'null'] }
        airwayBill: { type: [string, 'null'], example: CM12345678901 }
        trackingUrl: { type: [string, 'null'] }
        courierCode: { type: string, example: JNE }
        courierName: { type: string, example: JNE }
        courierServiceId: { type: integer, example: 12 }
        courierServiceCode: { type: string, example: REG }
        courierServiceName: { type: string, example: JNE Reguler }
        status: { $ref: '#/components/schemas/ShipmentStatus' }
        createdAt: { type: string, format: date-time }
        recipient:
          type: object
          description: The first receiver.
          properties:
            name: { type: [string, 'null'] }
            phoneNumber: { type: [string, 'null'] }
            fullAddress: { type: [string, 'null'] }
        cursor: { type: string, description: Cursor pointing after this item. }

    ShipmentDetail:
      type: object
      properties:
        id: { type: integer }
        code: { type: string, example: SHP-261120-K9M2Q7 }
        orderId: { type: integer }
        orderCode: { type: string, example: FSO-261120-A1B2C3 }
        source: { type: [string, 'null'], example: B2B }
        userId: { type: integer }
        status: { $ref: '#/components/schemas/ShipmentStatus' }
        type: { type: string, enum: [INSTANT, SAMEDAY, NEXTDAY, REGULAR, CARGO] }
        courierServiceId: { type: integer }
        courierServiceCode: { type: string }
        courierServiceName: { type: string }
        courierCode: { type: string }
        airwayBill: { type: [string, 'null'] }
        trackingUrl: { type: [string, 'null'] }
        etdRange: { type: [string, 'null'] }
        isInsured: { type: boolean }
        shippingDistanceMeter: { type: number }
        finishedAt: { type: [string, 'null'], format: date-time, description: When the shipment reached a final status. }
        createdAt: { type: string, format: date-time }
        price:
          type: object
          description: Shipping price stored for the shipment. The full breakdown is in the order response.
          properties:
            amount: { type: integer }
            currency: { type: string, example: IDR }
        shippingRateId: { type: [integer, 'null'] }
        shippingRateCode: { type: [string, 'null'], example: SR-7KQ2M9XA }
        sender: { $ref: '#/components/schemas/ShipmentContact' }
        receivers:
          type: array
          items: { $ref: '#/components/schemas/ShipmentContact' }
        histories:
          type: array
          items: { $ref: '#/components/schemas/ShipmentHistoryEvent' }
        packageDetails:
          type: array
          items: { $ref: '#/components/schemas/ShipmentPackageDetail' }
        driverDetails:
          type: [object, 'null']
          description: The instant-courier driver, when one is assigned.
          properties:
            name: { type: [string, 'null'] }
            licensePlate: { type: [string, 'null'] }
            phone: { type: [string, 'null'] }

    ShipmentContact:
      type: object
      description: Sender or receiver, with region names. Sender has `email` and `whatsappNumber`; receivers have `phoneNumber`, `addressNote` and `label`.
      properties:
        name: { type: string }
        phoneNumber: { type: string }
        email: { type: string }
        whatsappNumber: { type: string }
        fullAddress: { type: string }
        addressNote: { type: string }
        label: { type: string }
        province: { type: string }
        city: { type: string }
        district: { type: string }
        subdistrict: { type: string }
        postCode: { type: string }
        coordinate:
          type: object
          properties:
            latitude: { type: string }
            longitude: { type: string }
        createdAt: { type: string, format: date-time }

    ShipmentPackageDetail:
      type: object
      properties:
        id: { type: integer }
        shipmentId: { type: integer }
        shippingRatePackageDetailId: { type: [integer, 'null'] }
        shippingRatePackageCode: { type: [string, 'null'], example: PKG-3M8XQ1 }
        packageType:
          type: object
          properties:
            id: { type: integer }
            name: { type: string }
        declaredValue: { type: integer, description: Declared value in IDR. }
        packagePhotoUrls: { type: array, items: { type: string, format: uri } }
        isGlassware: { type: boolean }
        length: { type: number, description: Declared length in cm. }
        width: { type: number }
        height: { type: number }
        weight: { type: number, description: Declared weight in grams. }
        actualDimension: { type: number, description: Measured by the courier; `0` until reweighed. }
        actualWeight: { type: number, description: Measured weight in grams; `0` until reweighed. }
        description: { type: [string, 'null'] }
        packageNote: { type: [string, 'null'] }

    TrackingInfo:
      type: object
      properties:
        currentStatus: { type: string, description: 'Latest shipment status, for example `IN_TRANSIT`.' }
        description: { type: string, description: 'Latest status text, when the courier provides it.' }
        trackingUrl: { type: [string, 'null'], description: 'Courier tracking page, when available.' }
        courier: { type: string, example: JNE }
        service: { type: string, example: JNE Reguler }
        driver:
          type: object
          description: Present for couriers whose tracking includes a driver.
          properties:
            name: { type: [string, 'null'] }
            phone: { type: [string, 'null'] }
            licensePlate: { type: [string, 'null'] }
        histories:
          type: array
          items: { $ref: '#/components/schemas/ShipmentHistoryEvent' }

    # ------------------------------------------------ Balance
    Balance:
      type: object
      properties:
        balance:
          type: object
          description: Whole Rupiah.
          properties:
            shippingCredit: { type: integer, description: 'Saldo. Orders, price adjustments and return fees are paid from here.' }
            payoutBalance: { type: integer, description: 'COD proceeds and some refunds. Withdrawable from the dashboard.' }
            referralBalance: { type: integer, description: Referral earnings. }
            point: { type: integer, description: Reward points. }
        timestamp: { type: string, format: date-time, description: When the balance was read. }

    BalanceLogList:
      type: object
      properties:
        logs:
          type: array
          items: { $ref: '#/components/schemas/BalanceLog' }
        nextCursor: { type: [string, 'null'], description: Pass as `cursor` for the next page. `null` on the last page. }

    BalanceLog:
      type: object
      properties:
        id: { type: integer }
        userId: { type: integer }
        type: { type: string, enum: [CREDIT, DEBIT], description: '`CREDIT` adds money, `DEBIT` removes it.' }
        amount: { type: integer, description: Positive amount in IDR. }
        description: { type: string, description: 'Human-readable reason, mentioning order, shipment or airway bill. Some are in Indonesian.' }
        createdAt: { type: string, format: date-time }
        cursor: { type: string }

    # ------------------------------------------------ Webhook endpoint
    SetWebhookEndpointRequest:
      type: object
      required: [name, url, secret]
      properties:
        name: { type: string, maxLength: 100, description: A label for your endpoint., example: Production events }
        url:
          type: string
          format: uri
          pattern: '^https://'
          description: Public HTTPS URL with a valid certificate. Private and internal addresses are refused.
          example: https://hooks.sinartebet.co.id/shipping-engine
        secret:
          type: string
          minLength: 32
          description: A random secret you generate (at least 32 characters). Used to sign every delivery. It is never returned.
          example: 9f2c7a1e4b8d3f6a0c5e2b7d9a1f4c8e
        keyId:
          type: string
          maxLength: 64
          description: Name for this secret, sent in `x-webhook-signature` as `keyId=`. Default `whsec_` + 32 hex characters.
          example: whsec_main_2026
        eventTypes:
          type: array
          minItems: 1
          maxItems: 20
          default: ['shipment.*']
          description: 'Events to receive: exact names (`shipment.delivered`), wildcards (`shipment.*`, `*.delivered`) or `*`.'
          items: { type: string }
        timeoutMs:
          type: integer
          minimum: 1000
          maximum: 60000
          default: 10000
          description: How long to wait for your `2xx`, in milliseconds.
        maxAttempts:
          type: integer
          minimum: 1
          maximum: 50
          default: 8
          description: Delivery attempts per event, including the first.

    WebhookEndpoint:
      type: object
      properties:
        id: { type: integer, example: 41 }
        name: { type: string }
        url: { type: string, format: uri }
        isEnabled: { type: boolean, description: Deliveries are sent only while enabled. }
        verificationStatus:
          type: string
          enum: [verified, failed, unverified]
          description: Events are delivered only when `verified`.
        apiVersion: { type: string, example: V3 }
        timeoutMs: { type: integer, example: 10000 }
        maxAttempts: { type: integer, example: 8 }
        eventTypes: { type: array, items: { type: string }, example: ['shipment.*'] }
        activeSecretKeyIds: { type: array, items: { type: string }, description: The `keyId` of the secret that signs deliveries. }
        createdAt: { type: string, format: date-time }
        updatedAt: { type: string, format: date-time }
        backoffUntil:
          type: [string, 'null']
          format: date-time
          description: After repeated failures, deliveries pause until this time. Events raised during the pause are not delivered.
        failureCount: { type: integer, description: Consecutive failed deliveries. }

    WebhookChallengeResult:
      type: object
      properties:
        success: { type: boolean, description: Your endpoint echoed the challenge. }
        statusCode: { type: integer, description: HTTP status your endpoint returned. }
        responseBody: { type: string, description: 'First 256 characters of your response, when the challenge failed.' }
        error: { type: string, description: 'Why no response was received (DNS, refused connection, timeout, address not allowed).' }

    SetWebhookEndpointResult:
      allOf:
        - $ref: '#/components/schemas/WebhookEndpoint'
        - type: object
          properties:
            challenge: { $ref: '#/components/schemas/WebhookChallengeResult' }

    # ------------------------------------------------ Webhook event bodies
    ShipmentEventBase:
      type: object
      required: [booking_id, awb, courier_code, shipment_code, data]
      properties:
        booking_id: { type: string, description: The order code., example: FSO-261120-A1B2C3 }
        awb: { type: [string, 'null'], description: 'Airway bill, `null` before the courier assigns one.', example: CM12345678901 }
        courier_code: { type: string, description: 'Courier code in **lowercase**, for example `jne` or `lalamove`.', example: jne }
        shipment_code: { type: string, example: SHP-261120-K9M2Q7 }

    ShipmentEventDataCore:
      type: object
      required: [timestamp, status, desc]
      properties:
        timestamp:
          type: string
          pattern: '^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$'
          description: '`YYYY-MM-DD HH:mm:ss` in UTC, without an offset.'
          example: '2026-11-22 06:18:42'
        status: { $ref: '#/components/schemas/ShipmentStatus' }
        desc: { type: string, description: 'Event description, often the courier''s own text.' }

    ShipmentStatusEvent:
      description: Body of every shipment status event. Every `data` field is always present; unknown values are `null`.
      allOf:
        - $ref: '#/components/schemas/ShipmentEventBase'
        - type: object
          properties:
            data:
              allOf:
                - $ref: '#/components/schemas/ShipmentEventDataCore'
                - type: object
                  required: [note, mapping_code, driver_name, driver_phone, driver_license_plate, proof_image, receiver_name, receiver_relation, tracking_link]
                  properties:
                    note: { type: [string, 'null'], description: Extra remark from the courier. }
                    mapping_code: { type: [string, 'null'], description: The courier's own status code. }
                    driver_name: { type: [string, 'null'] }
                    driver_phone: { type: [string, 'null'] }
                    driver_license_plate: { type: [string, 'null'] }
                    proof_image: { type: [string, 'null'], format: uri, description: Proof-of-delivery photo. }
                    receiver_name: { type: [string, 'null'], description: Who accepted the parcel. }
                    receiver_relation: { type: [string, 'null'], description: 'Their relation to the receiver, as the courier reports it.' }
                    tracking_link: { type: [string, 'null'], format: uri, description: Live tracking link (instant couriers). }

    ShipmentAirwayBillUpdatedEvent:
      allOf:
        - $ref: '#/components/schemas/ShipmentEventBase'
        - type: object
          properties:
            awb: { type: string, description: The **new** airway bill. }
            data:
              allOf:
                - $ref: '#/components/schemas/ShipmentEventDataCore'
                - type: object
                  properties:
                    awb_before: { type: string, description: Previous airway bill. }
                    awb_after: { type: string, description: New airway bill. }

    ShipmentPriceChangedEvent:
      allOf:
        - $ref: '#/components/schemas/ShipmentEventBase'
        - type: object
          properties:
            data:
              allOf:
                - $ref: '#/components/schemas/ShipmentEventDataCore'
                - type: object
                  required: [price_before, price_after, delta, payment_status]
                  properties:
                    price_before: { type: integer, description: Previous price in IDR. }
                    price_after: { type: integer, description: New price in IDR. }
                    delta: { type: integer, description: '`price_after - price_before`. Charged only when positive and the shipment is not COD.' }
                    payment_status: { type: string, enum: [success, failed], description: Whether the difference was charged to your balance. }

    ShipmentMeasurementChangedEvent:
      allOf:
        - $ref: '#/components/schemas/ShipmentEventBase'
        - type: object
          properties:
            data:
              allOf:
                - $ref: '#/components/schemas/ShipmentEventDataCore'
                - type: object
                  required: [measurement_before, measurement_after]
                  properties:
                    measurement_before: { type: string, description: 'Declared measurement as text, for example `weight=1200g, dimension=30x20x10cm`.' }
                    measurement_after: { type: string, description: 'Measurement found by the courier, same format.' }

    ShipmentRtsBilledEvent:
      allOf:
        - $ref: '#/components/schemas/ShipmentEventBase'
        - type: object
          properties:
            data:
              allOf:
                - $ref: '#/components/schemas/ShipmentEventDataCore'
                - type: object
                  required: [rts_fee, payment_status]
                  properties:
                    rts_fee: { type: integer, description: Return fee in IDR. }
                    payment_status: { type: string, enum: [success, failed], description: Whether the fee was charged to your balance. }

    ShipmentDispatchedEvent:
      type: object
      required: [shipment_id, shipment_code, order_id, status, tracking_id, tracking_url, airway_bill]
      properties:
        shipment_id: { type: integer, description: Numeric shipment ID (the `id` in shipment responses)., example: 18452 }
        shipment_code: { type: string, example: SHP-261120-K9M2Q7 }
        order_id: { type: integer, description: 'Numeric order ID (the order `id`, not its code).', example: 9021 }
        status: { type: string, enum: [PENDING_PICKUP, PENDING_DROPOFF], example: PENDING_DROPOFF }
        tracking_id: { type: string, description: The courier's booking reference. Usually equal to `airway_bill`., example: CM12345678901 }
        tracking_url: { type: [string, 'null'], format: uri }
        airway_bill: { type: [string, 'null'], example: CM12345678901 }

    Error:
      type: object
      required: [statusCode, message]
      properties:
        statusCode: { type: integer }
        message:
          oneOf:
            - type: string
            - type: array
              items: { type: string }
          description: A sentence, or a list of field errors for validation failures.
        error: { type: string, description: Short error name. }
        code:
          type: string
          description: Machine-readable reason on some errors, for example `PICKUP_SCHEDULE_EXPIRED`.
        quotedScheduledAt:
          type: [string, 'null']
          description: With `PICKUP_SCHEDULE_NOT_QUOTED`, the pickup time the rate was quoted with (`null` = as soon as possible).
        requestedScheduledAt:
          type: [string, 'null']
          description: With `PICKUP_SCHEDULE_NOT_QUOTED`, the pickup time you sent.
