# Bản sao từ vpcl-backend/docs/partner-api/openapi.yaml — sửa ở đó rồi chép lại.
openapi: 3.1.0
info:
  title: VPCL Partner API
  version: 1.0.0
  summary: Kết nối hệ thống đối tác với VPCL Logistics — tạo đơn, tính phí, theo dõi hành trình.
  description: |
    API dành cho đối tác (sàn TMĐT, hãng vận chuyển, doanh nghiệp) tích hợp trực tiếp với
    nền tảng vận tải **VPCL Logistics**.

    ## Môi trường

    | Môi trường | Base URL | Ghi chú |
    |---|---|---|
    | Sandbox | `https://api-dev.vpclogistics.vn/api/v1/partner` | Dữ liệu thử, không phát sinh vận chuyển thật |
    | Production | `https://api.vpclogistics.vn/api/v1/partner` | Cấp sau khi nghiệm thu sandbox |

    Mỗi môi trường có **bộ khoá riêng**. Liên hệ VPCL để được cấp `key_id`, `api_secret`
    và `webhook_secret`.

    ## Quy trình tích hợp

    1. **Đăng ký** — gửi thông tin đơn vị, đầu mối kỹ thuật và `webhook_url` sandbox.
       VPCL cấp khoá sandbox. Được tích hợp sandbox **song song** khi hợp đồng đang ký.
    2. **Tích hợp sandbox** — gọi `GET /ping` để kiểm tra chữ ký, `POST /webhooks/test` để
       kiểm tra phía nhận webhook, sau đó chạy luồng báo giá → tạo đơn → tra cứu → huỷ.
    3. **Nghiệm thu** — VPCL đối chiếu dữ liệu đơn thử và trạng thái webhook hai phía.
    4. **Production** — VPCL cấp khoá production, chạy thử vài đơn thật có giám sát rồi mở hoàn toàn.
    5. **Vận hành** — đối soát cước định kỳ theo hợp đồng; mọi thay đổi API ghi ở *Lịch sử thay đổi*.

    Mỗi phản hồi có header `X-Trace-Id`. Gửi kèm mã này khi cần hỗ trợ để tra cứu nhanh.

    ## Xác thực — chữ ký HMAC-SHA256

    Mọi request phải có 3 header:

    | Header | Giá trị |
    |---|---|
    | `X-VPCL-Key` | `key_id` được cấp |
    | `X-VPCL-Timestamp` | Unix time (giây). Lệch quá **300 giây** so với giờ máy chủ sẽ bị từ chối |
    | `X-VPCL-Signature` | `hex( HMAC_SHA256( api_secret, string_to_sign ) )` |

    `string_to_sign` gồm 4 dòng nối bằng ký tự xuống dòng `\n`:

    ```text
    {X-VPCL-Timestamp}
    {HTTP_METHOD viết hoa}
    {đường dẫn kèm query, ví dụ /api/v1/partner/orders/ORD0001}
    {hex( SHA256( raw body ) )}   ← body rỗng thì băm chuỗi rỗng
    ```

    Ví dụ Node.js:

    ```js
    import crypto from 'node:crypto';

    function sign({ secret, method, path, body = '' }) {
      const ts = Math.floor(Date.now() / 1000).toString();
      const bodyHash = crypto.createHash('sha256').update(body).digest('hex');
      const toSign = [ts, method.toUpperCase(), path, bodyHash].join('\n');
      const signature = crypto.createHmac('sha256', secret).update(toSign).digest('hex');
      return { 'X-VPCL-Timestamp': ts, 'X-VPCL-Signature': signature };
    }
    ```

    Ví dụ Python:

    ```python
    import hashlib, hmac, time

    def sign(secret: str, method: str, path: str, body: bytes = b"") -> dict:
        ts = str(int(time.time()))
        body_hash = hashlib.sha256(body).hexdigest()
        to_sign = "\n".join([ts, method.upper(), path, body_hash])
        sig = hmac.new(secret.encode(), to_sign.encode(), hashlib.sha256).hexdigest()
        return {"X-VPCL-Timestamp": ts, "X-VPCL-Signature": sig}
    ```

    Ký trên **đúng chuỗi byte** gửi đi: serialize JSON một lần, dùng chuỗi đó vừa để băm vừa làm body.

    ## Quy ước chung

    - JSON UTF-8, tên trường `snake_case`.
    - Thời gian ISO-8601 (UTC, hậu tố `Z`). Hiển thị theo giờ Việt Nam là việc của phía đối tác.
    - Tiền tệ VND, số nguyên.
    - Địa chỉ theo **mô hình 2 cấp** (tỉnh/thành → phường/xã) sau sáp nhập 2025. Lấy mã ở nhóm *Danh mục*.
    - **Chống tạo trùng:** `order_code` là mã đơn phía đối tác và là duy nhất. Gửi lại cùng
      `order_code` sẽ nhận về đúng đơn đã tạo (HTTP 200) thay vì tạo đơn mới.
    - Giới hạn: **120 request/phút** cho mỗi địa chỉ IP gọi tới. Vượt quá nhận HTTP 429.
    - Ghi chú cho tài xế đặt trong `items[].special_notes`.

    ## Lỗi

    Mọi lỗi trả cùng cấu trúc `Error` với `code` ổn định để lập trình xử lý; `message` là
    tiếng Việt cho người đọc. Xem bảng mã lỗi ở mục *Error* trong phần Schemas.

    ## Webhook

    VPCL gửi `POST` tới `webhook_url` đã đăng ký mỗi khi đơn đổi trạng thái. Xem mục
    **Webhooks** (`order.status_changed`). Webhook được ký bằng `webhook_secret`:

    ```text
    X-VPCL-Signature: t=1731139200,v1=5f2c…
    v1 = hex( HMAC_SHA256( webhook_secret, "{t}.{raw body}" ) )
    ```

    - Phản hồi **HTTP 2xx trong 10 giây** để xác nhận đã nhận.
    - Không nhận được 2xx: gửi lại tối đa **8 lần**, giãn cách 1 phút → 5 phút → 15 phút →
      1 giờ → 3 giờ → 6 giờ → 12 giờ → 24 giờ.
    - Cùng một sự kiện có thể đến **nhiều hơn một lần**: khử trùng theo `event_id`.
    - Thứ tự không đảm bảo tuyệt đối: dùng `occurred_at` để so mới/cũ.

    ## Lịch sử thay đổi

    | Phiên bản | Ngày | Nội dung |
    |---|---|---|
    | 1.0.0 | 2026-11-09 | Phát hành đầu tiên: danh mục, báo giá, đơn hàng, hành trình, webhook |
  contact:
    name: VPCL Logistics — Bộ phận tích hợp
    url: https://vpclogistics.vn/developers
servers:
  - url: https://api-dev.vpclogistics.vn/api/v1/partner
    description: Sandbox
  - url: https://api.vpclogistics.vn/api/v1/partner
    description: Production
security:
  - VpclKey: []
    VpclTimestamp: []
    VpclSignature: []
tags:
  - name: Kết nối
    description: Kiểm tra khoá và chữ ký.
  - name: Danh mục
    description: Tỉnh/thành, phường/xã theo mô hình địa chỉ 2 cấp.
  - name: Báo giá
    description: Tính phí trước khi tạo đơn.
  - name: Đơn hàng
    description: Tạo, tra cứu, huỷ đơn.
  - name: Hành trình
    description: Lịch sử trạng thái và sự kiện hiện trường.
  - name: Webhook
    description: Thử gửi sự kiện tới webhook đã đăng ký.

paths:
  /ping:
    get:
      tags: [Kết nối]
      operationId: ping
      summary: Kiểm tra khoá và chữ ký
      description: Dùng ở bước tích hợp đầu tiên. Trả về đối tác tương ứng với `key_id` và giờ máy chủ.
      responses:
        '200':
          description: Chữ ký hợp lệ.
          content:
            application/json:
              schema:
                type: object
                required: [partner_code, environment, server_time]
                properties:
                  partner_code: { type: string, example: DOITAC01 }
                  environment: { type: string, enum: [sandbox, production], example: sandbox }
                  server_time: { type: string, format: date-time }
        '401': { $ref: '#/components/responses/Unauthorized' }

  /locations/provinces:
    get:
      tags: [Danh mục]
      operationId: listProvinces
      summary: Danh sách 34 tỉnh/thành
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: array
                items: { $ref: '#/components/schemas/Province' }
        '401': { $ref: '#/components/responses/Unauthorized' }

  /locations/wards:
    get:
      tags: [Danh mục]
      operationId: listWards
      summary: Danh sách phường/xã/đặc khu
      parameters:
        - name: province_code
          in: query
          required: true
          schema: { type: string, pattern: '^\d{2}$' }
          example: '31'
        - name: q
          in: query
          required: false
          description: Tìm theo tên, không phân biệt hoa thường.
          schema: { type: string, maxLength: 100 }
        - name: limit
          in: query
          required: false
          schema: { type: integer, minimum: 1, maximum: 200, default: 50 }
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                type: array
                items: { $ref: '#/components/schemas/Ward' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }

  /quotes:
    post:
      tags: [Báo giá]
      operationId: createQuote
      summary: Tính phí vận chuyển
      description: |
        Không tạo đơn. Giá chỉ để tham khảo đến `valid_until`; khi tạo đơn, VPCL tính lại và
        **chốt giá tại thời điểm tạo đơn**.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/ShipmentInput' }
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Quote' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '422': { $ref: '#/components/responses/Unprocessable' }

  /orders:
    post:
      tags: [Đơn hàng]
      operationId: createOrder
      summary: Tạo đơn
      description: |
        Tạo và xác nhận đơn trong một bước. Trạng thái đầu là `CREATED`.

        **Idempotent theo `order_code`:** gửi lại cùng `order_code` trả về đơn đã có với
        HTTP 200 — an toàn để thử lại khi mất kết nối.
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/CreateOrderInput' }
      responses:
        '201':
          description: Đã tạo đơn mới.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '200':
          description: '`order_code` đã tồn tại — trả về đơn đã tạo trước đó.'
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '400': { $ref: '#/components/responses/BadRequest' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '403': { $ref: '#/components/responses/Forbidden' }
        '422': { $ref: '#/components/responses/Unprocessable' }

  /orders/{order_code}:
    parameters:
      - $ref: '#/components/parameters/OrderCode'
    get:
      tags: [Đơn hàng]
      operationId: getOrder
      summary: Tra cứu đơn
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404': { $ref: '#/components/responses/NotFound' }

  /orders/{order_code}/cancel:
    parameters:
      - $ref: '#/components/parameters/OrderCode'
    post:
      tags: [Đơn hàng]
      operationId: cancelOrder
      summary: Huỷ đơn
      description: |
        Chỉ huỷ được khi đơn ở `CREATED` (chưa giao cho tài xế). Đơn đã huỷ gọi lại vẫn trả 200.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [reason]
              properties:
                reason: { type: string, minLength: 2, maxLength: 500, example: Người bán huỷ đơn }
      responses:
        '200':
          description: Đã huỷ.
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404': { $ref: '#/components/responses/NotFound' }
        '409': { $ref: '#/components/responses/Conflict' }

  /orders/{order_code}/tracking:
    parameters:
      - $ref: '#/components/parameters/OrderCode'
    get:
      tags: [Hành trình]
      operationId: getTracking
      summary: Hành trình đơn
      description: Lịch sử trạng thái và sự kiện hiện trường (quét mã, giao nhận, bằng chứng giao hàng).
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Tracking' }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '404': { $ref: '#/components/responses/NotFound' }

  /webhooks/test:
    post:
      tags: [Webhook]
      operationId: sendTestWebhook
      summary: Gửi thử một sự kiện webhook
      description: |
        VPCL gửi ngay một sự kiện `ping` (đã ký) tới `webhook_url` đã đăng ký và trả về kết quả
        nhận được từ máy chủ của đối tác. Dùng để kiểm tra phần xác minh chữ ký.
      responses:
        '200':
          description: Kết quả lần gửi.
          content:
            application/json:
              schema:
                type: object
                required: [delivered, event_id]
                properties:
                  delivered: { type: boolean, description: Đối tác trả 2xx hay không }
                  event_id: { type: string, format: uuid }
                  http_status: { type: [integer, 'null'], example: 200 }
                  error: { type: [string, 'null'], description: Lỗi kết nối nếu có }
        '401': { $ref: '#/components/responses/Unauthorized' }
        '409': { $ref: '#/components/responses/Conflict' }

webhooks:
  order.status_changed:
    post:
      summary: Đơn đổi trạng thái
      description: |
        Gửi mỗi khi đơn chuyển trạng thái. Header kèm theo:
        `X-VPCL-Event-Id`, `X-VPCL-Event-Type`, `X-VPCL-Signature` (xem phần Webhook ở đầu tài liệu).
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: '#/components/schemas/WebhookEvent' }
      responses:
        '200':
          description: Đối tác xác nhận đã nhận. Mọi mã 2xx đều được chấp nhận.

components:
  securitySchemes:
    VpclKey:
      type: apiKey
      in: header
      name: X-VPCL-Key
      description: '`key_id` được VPCL cấp.'
    VpclTimestamp:
      type: apiKey
      in: header
      name: X-VPCL-Timestamp
      description: Unix time (giây).
    VpclSignature:
      type: apiKey
      in: header
      name: X-VPCL-Signature
      description: HMAC-SHA256 hex của `string_to_sign` (xem phần Xác thực).

  parameters:
    OrderCode:
      name: order_code
      in: path
      required: true
      description: Mã đơn phía đối tác (đã gửi khi tạo đơn).
      schema: { $ref: '#/components/schemas/OrderCode' }

  responses:
    BadRequest:
      description: Dữ liệu không hợp lệ.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          example:
            code: VALIDATION_ERROR
            message: Dữ liệu không hợp lệ
            details: ['destination.contact_phone: Số điện thoại không hợp lệ']
            timestamp: '2026-11-09T08:00:00.000Z'
            path: /api/v1/partner/orders
    Unauthorized:
      description: Thiếu hoặc sai khoá/chữ ký/thời gian.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          example:
            code: PARTNER_SIGNATURE_INVALID
            message: Chữ ký không hợp lệ
            timestamp: '2026-11-09T08:00:00.000Z'
            path: /api/v1/partner/orders
    Forbidden:
      description: Đối tác chưa được kích hoạt dịch vụ hoặc đang bị tạm dừng.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
    NotFound:
      description: Không tìm thấy đơn với `order_code` này.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          example:
            code: PARTNER_ORDER_NOT_FOUND
            message: Không tìm thấy đơn
            timestamp: '2026-11-09T08:00:00.000Z'
            path: /api/v1/partner/orders/ORD0001
    Conflict:
      description: Thao tác không hợp lệ với trạng thái hiện tại.
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }
          example:
            code: BOOKING_NOT_CANCELLABLE
            message: Đơn đã giao cho tài xế, không thể huỷ.
            timestamp: '2026-11-09T08:00:00.000Z'
            path: /api/v1/partner/orders/ORD0001/cancel
    Unprocessable:
      description: Dữ liệu đúng định dạng nhưng không phục vụ được (tuyến chưa có giá, hàng cấm…).
      content:
        application/json:
          schema: { $ref: '#/components/schemas/Error' }

  schemas:
    OrderCode:
      type: string
      pattern: '^[A-Za-z0-9_-]{4,64}$'
      example: ORD202611090001

    Error:
      type: object
      required: [code, message, timestamp, path]
      properties:
        code:
          type: string
          description: |
            Mã lỗi ổn định. Thường gặp:

            | code | HTTP | Ý nghĩa |
            |---|---|---|
            | `PARTNER_AUTH_MISSING` | 401 | Thiếu header xác thực |
            | `PARTNER_KEY_INVALID` | 401 | `key_id` không tồn tại hoặc đã thu hồi |
            | `PARTNER_TIMESTAMP_SKEW` | 401 | Thời gian lệch quá 300 giây |
            | `PARTNER_SIGNATURE_INVALID` | 401 | Sai chữ ký |
            | `VALIDATION_ERROR` | 400 | Dữ liệu không hợp lệ (`details` liệt kê trường lỗi) |
            | `PARTNER_ORDER_NOT_FOUND` | 404 | Không có đơn với `order_code` |
            | `BOOKING_NOT_CANCELLABLE` | 409 | Đơn đã giao tài xế, không huỷ được |
            | `PARTNER_WEBHOOK_NOT_CONFIGURED` | 409 | Chưa đăng ký `webhook_url` |
            | `SERVICE_NOT_AVAILABLE_FOR_ORGANIZATION` | 403 | Dịch vụ chưa được kích hoạt cho đối tác |
            | `CARGO_CATEGORY_NOT_ALLOWED` | 422 | Loại hàng không nhận vận chuyển |
            | `TOO_MANY_REQUESTS` | 429 | Vượt giới hạn request |
          example: PARTNER_SIGNATURE_INVALID
        message: { type: string, example: Chữ ký không hợp lệ }
        details: { description: Thông tin thêm, tuỳ mã lỗi. }
        traceId: { type: string, description: Gửi kèm khi liên hệ hỗ trợ. }
        timestamp: { type: string, format: date-time }
        path: { type: string }

    Province:
      type: object
      required: [code, name]
      properties:
        code: { type: string, example: '31' }
        name: { type: string, example: Thành phố Hải Phòng }
        region_group: { type: string, description: Miền dùng để tính vùng giá., example: NORTH }

    Ward:
      type: object
      required: [code, name, province_code]
      properties:
        code: { type: string, example: '11311' }
        name: { type: string, example: Phường Hồng Bàng }
        province_code: { type: string, example: '31' }

    Address:
      type: object
      required: [contact_name, contact_phone, province_code, address_line]
      properties:
        contact_name: { type: string, minLength: 2, maxLength: 150, example: Nguyễn Văn A }
        contact_phone:
          type: string
          pattern: '^(0|\+84)[3-9][0-9]{8}$'
          example: '0912345678'
        province_code: { type: string, minLength: 2, maxLength: 2, example: '31' }
        ward_code: { type: string, minLength: 5, maxLength: 10, example: '11311' }
        address_line: { type: string, minLength: 2, maxLength: 500, example: Số 1 Hoàng Văn Thụ }
        lat: { type: number, minimum: 6, maximum: 24, description: Vĩ độ (tuỳ chọn), example: 20.8615 }
        lng: { type: number, minimum: 102, maximum: 118, description: Kinh độ (tuỳ chọn), example: 106.6822 }

    Item:
      type: object
      required: [length_cm, width_cm, height_cm, actual_weight_kg]
      properties:
        category: { type: string, maxLength: 50, description: Loại hàng, example: Hàng tiêu dùng }
        length_cm: { type: number, exclusiveMinimum: 0, example: 50 }
        width_cm: { type: number, exclusiveMinimum: 0, example: 40 }
        height_cm: { type: number, exclusiveMinimum: 0, example: 30 }
        actual_weight_kg: { type: number, exclusiveMinimum: 0, example: 12.5 }
        quantity: { type: integer, minimum: 1, default: 1 }
        special_notes: { type: string, maxLength: 500 }
        is_fragile: { type: boolean, default: false }
        is_stackable: { type: boolean, default: true }
        upright_only: { type: boolean, default: false }

    ServiceInput:
      type: object
      required: [service_code]
      properties:
        service_code:
          type: string
          enum: [INSURANCE, COD, LOADING, UNLOADING, PACKAGING]
          description: |
            - `INSURANCE` — bảo hiểm, cần `value.declared_value` (VND)
            - `COD` — thu hộ, cần `value.amount` (VND)
            - `LOADING` / `UNLOADING` — bốc / dỡ hàng
            - `PACKAGING` — đóng gói
        value:
          type: object
          additionalProperties: true
          example: { amount: 350000 }

    ShipmentInput:
      type: object
      required: [origin, destination, items]
      properties:
        origin: { $ref: '#/components/schemas/Address' }
        destination: { $ref: '#/components/schemas/Address' }
        items:
          type: array
          minItems: 1
          maxItems: 200
          items: { $ref: '#/components/schemas/Item' }
        services:
          type: array
          items: { $ref: '#/components/schemas/ServiceInput' }
        requested_pickup_at:
          type: string
          format: date-time
          description: Thời điểm mong muốn lấy hàng (tuỳ chọn).

    CreateOrderInput:
      allOf:
        - type: object
          required: [order_code]
          properties:
            order_code: { $ref: '#/components/schemas/OrderCode' }
        - $ref: '#/components/schemas/ShipmentInput'

    Fee:
      type: object
      required: [total_amount, currency]
      properties:
        chargeable_weight_kg: { type: number, description: Khối lượng tính cước (max thực tế / quy đổi), example: 12.5 }
        base_shipping_fee: { type: integer, example: 85000 }
        surcharges: { type: integer, description: Tổng phụ phí (lấy hàng xa, giao xa, cao điểm), example: 0 }
        discount: { type: integer, description: Giảm giá theo hợp đồng, example: 0 }
        services:
          type: array
          items:
            type: object
            properties:
              service_code: { type: string, example: COD }
              fee: { type: integer, example: 15000 }
        total_amount: { type: integer, example: 100000 }
        currency: { type: string, const: VND }

    Quote:
      allOf:
        - $ref: '#/components/schemas/Fee'
        - type: object
          required: [quoted_at, valid_until]
          properties:
            quoted_at: { type: string, format: date-time }
            valid_until: { type: string, format: date-time }

    OrderStatus:
      type: string
      enum: [CREATED, DRIVER_ASSIGNED, PICKED_UP, IN_TRANSIT, OUT_FOR_DELIVERY, ON_HOLD, DELIVERED, CANCELLED]
      description: |
        | status | Ý nghĩa |
        |---|---|
        | `CREATED` | Đã tạo, chờ điều phối |
        | `DRIVER_ASSIGNED` | Đã phân tài xế lấy hàng |
        | `PICKED_UP` | Đã lấy hàng |
        | `IN_TRANSIT` | Đang vận chuyển (qua kho đi, trung chuyển, kho đến) |
        | `OUT_FOR_DELIVERY` | Đang giao |
        | `ON_HOLD` | Tạm giữ chờ xác nhận (ví dụ cân lại khối lượng) |
        | `DELIVERED` | Giao thành công |
        | `CANCELLED` | Đã huỷ |

        `status_detail` cho biết bước chi tiết bên trong VPCL (ví dụ `AT_ORIGIN_HUB`,
        `LINEHAUL_IN_TRANSIT`, `AT_DESTINATION_HUB`) — dùng để hiển thị, **không** dùng để rẽ nhánh logic.

    Order:
      type: object
      required: [order_code, tracking_no, status, status_detail, created_at, origin, destination, items, packages]
      properties:
        order_code: { $ref: '#/components/schemas/OrderCode' }
        tracking_no: { type: string, description: Mã vận đơn VPCL, example: VPCL-20261109-000001 }
        service: { type: string, const: LTL }
        status: { $ref: '#/components/schemas/OrderStatus' }
        status_detail: { type: string, example: CONFIRMED }
        created_at: { type: string, format: date-time }
        updated_at: { type: string, format: date-time }
        cancel_reason: { type: [string, 'null'] }
        origin: { $ref: '#/components/schemas/Address' }
        destination: { $ref: '#/components/schemas/Address' }
        items:
          type: array
          items: { $ref: '#/components/schemas/Item' }
        services:
          type: array
          items: { $ref: '#/components/schemas/ServiceInput' }
        packages:
          type: array
          description: Mỗi kiện một mã QR dán lên hàng.
          items:
            type: object
            properties:
              package_code: { type: string, example: PKG-20261109-000001 }
              sequence_no: { type: integer, example: 1 }
        fee:
          oneOf:
            - $ref: '#/components/schemas/Fee'
            - type: 'null'

    TrackingEvent:
      type: object
      required: [occurred_at, event_type]
      properties:
        occurred_at: { type: string, format: date-time }
        event_type: { type: string, description: Loại sự kiện hiện trường (quét mã, giao, nhận…), example: DELIVERED }
        note: { type: [string, 'null'] }
        address_text: { type: [string, 'null'] }
        lat: { type: [number, 'null'] }
        lng: { type: [number, 'null'] }
        photos:
          type: array
          description: Ảnh bằng chứng (link ký, hết hạn sau 5 phút — gọi lại API để lấy link mới).
          items: { type: string, format: uri }

    Tracking:
      type: object
      required: [order_code, tracking_no, status, status_detail, history, events]
      properties:
        order_code: { $ref: '#/components/schemas/OrderCode' }
        tracking_no: { type: string }
        status: { $ref: '#/components/schemas/OrderStatus' }
        status_detail: { type: string }
        history:
          type: array
          items:
            type: object
            properties:
              status: { $ref: '#/components/schemas/OrderStatus' }
              status_detail: { type: string }
              occurred_at: { type: string, format: date-time }
              reason: { type: [string, 'null'] }
        events:
          type: array
          items: { $ref: '#/components/schemas/TrackingEvent' }

    WebhookEvent:
      type: object
      required: [event_id, event_type, occurred_at, data]
      properties:
        event_id: { type: string, format: uuid, description: Khử trùng theo trường này. }
        event_type: { type: string, enum: [order.status_changed, ping] }
        occurred_at: { type: string, format: date-time }
        data:
          type: object
          properties:
            order_code: { $ref: '#/components/schemas/OrderCode' }
            tracking_no: { type: string }
            status: { $ref: '#/components/schemas/OrderStatus' }
            status_detail: { type: string }
            previous_status: { oneOf: [{ $ref: '#/components/schemas/OrderStatus' }, { type: 'null' }] }
            reason: { type: [string, 'null'] }
      example:
        event_id: 3b1f7c2e-8a4d-4c55-9d0e-6f1a2b3c4d5e
        event_type: order.status_changed
        occurred_at: '2026-11-09T09:15:00Z'
        data:
          order_code: ORD202611090001
          tracking_no: VPCL-20261109-000001
          status: PICKED_UP
          status_detail: PICKED_UP
          previous_status: DRIVER_ASSIGNED
          reason: null
