openapi: 3.1.0

info:
  title: Order Template API
  version: 2.0.0
  description: |
    AutoIntel API for requesting predictive templates for given production timings & volume.
  contact:
    name: AutoIntel Platform

servers:
  - url: https://api.autointel.ai/ppm/ordering/v2
    description: Production

security:
  - apiKey: []

tags:
  - name: Templates
    description: Request and retrieve templates
  - name: Order status
    description: Report back status of orders for templates

paths:
  /templates:
    post:
      tags: [Templates]
      operationId: createTemplateRequest
      summary: Request templates for a given volume
      description: |
        Validates the request and returns immediately a unique identifier.
      parameters:
        - name: Idempotency-Key
          in: header
          required: true
          description: |
            Caller-generated key. Required to ensure the operation is performed only once
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/TemplateRequest"
      responses:
        "202":
          description: Request accepted.
          headers:
            Location:
              description: Absolute URL of the request.
              schema:
                type: string
                format: uri
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/TemplateRequestAccepted"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "409":
          description: The same `Idempotency-Key` was used for a different request body.
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/Problem"
        "429":
          $ref: "#/components/responses/TooManyRequests"

  /templates/{id}:
    parameters:
      - $ref: "#/components/parameters/TemplateRequestId"
    get:
      tags: [Templates]
      operationId: getTemplateRequest
      summary: Retrieve templates or check on a running request
      description: |
        Returns the request's status, and its templates once they are ready.

        Poll while `status` is `accepted` or `running`.

        Too many requests return 429.

        Once `status` is `succeeded` or `partially_succeeded`, the response holds either
        `templates` or `templatesUrl`.
      parameters:
        - name: modelCode
          in: query
          required: false
          description: Restrict the templates to one model. Useful for collecting a large request model by model.
          schema:
            type: string
      responses:
        "200":
          description: The request.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/TemplateRequestStatus"
              examples:
                running:
                  summary: Template request still running
                  value:
                    id: "req_01J8Z"
                    status: running
                    requestedAt: "2026-10-01T09:00:00Z"
                    startedAt: "2026-10-01T09:00:04Z"
                    models:
                      - modelCode: "26XD"
                        status: succeeded
                        requestedVolume: 40
                        generatedVolume: 40
                      - modelCode: "23FP"
                        status: running
                        requestedVolume: 25
                        generatedVolume: 11
                    totals:
                      requestedVolume: 65
                      generatedVolume: 51
                      dealers: 18
                      models: 2
                partiallySucceededInline:
                  summary: Completed, partial success
                  value:
                    id: "req_01J8Z"
                    status: partially_succeeded
                    requestedAt: "2026-10-01T09:00:00Z"
                    startedAt: "2026-10-01T09:00:04Z"
                    completedAt: "2026-10-01T09:06:41Z"
                    models:
                      - modelCode: "26XD"
                        status: succeeded
                        requestedVolume: 40
                        generatedVolume: 40
                      - modelCode: "23FP"
                        status: failed
                        requestedVolume: 25
                        generatedVolume: 0
                    totals:
                      requestedVolume: 65
                      generatedVolume: 40
                      dealers: 18
                      models: 2
                    templates:
                      - templateId: "tpl_7f21"
                        dealerId: "65775"
                        modelCode: "26XD"
                        action: submit
                        rank: 1
                        productionWeek: { year: 2026, week: 42 }
                        model_code: "26XD"
                        options: ["P0300", "S0508"]
                        templateType: predictive_template
                    errors:
                      - code: NO_CONFIGURATION_AVAILABLE
                        message: "No constructible configuration for the requested volume"
                        modelCode: "23FP"
                        requestedVolume: 25
                        generatedVolume: 0
                succeededByLink:
                  summary: Completed, templates by link
                  value:
                    id: "req_01J8Z"
                    status: succeeded
                    requestedAt: "2026-10-01T09:00:00Z"
                    completedAt: "2026-10-01T09:11:02Z"
                    models:
                      - modelCode: "26XD"
                        status: succeeded
                        requestedVolume: 4200
                        generatedVolume: 4200
                    totals:
                      requestedVolume: 4200
                      generatedVolume: 4200
                      dealers: 340
                      models: 1
                    templatesUrl:
                      url: "https://example.invalid/templates/req_01J8Z.ndjson?sig=ABC123"
                      expiresAt: "2026-10-01T10:11:02Z"
                      contentType: application/x-ndjson
                      sizeBytes: 9184223
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"

  /order-status:
    post:
      tags: [Order status]
      operationId: reportOrderStatus
      summary: Report what was ordered
      description: |
        Report what was ordered. Each entry names its `templateId`, so one call may cover
        several template requests.

        Report only the templates you acted on.

        Send one outcome at a time or in batches. A later report for a `templateId` replaces
        the earlier one.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/OrderStatusReport"
      responses:
        "202":
          description: Report accepted.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/OrderStatusAccepted"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/TooManyRequests"

components:
  securitySchemes:
    apiKey:
      type: apiKey
      in: header
      name: apikey

  parameters:
    TemplateRequestId:
      name: id
      in: path
      required: true
      description: Identifier returned when the request was accepted.
      schema:
        type: string

  responses:
    BadRequest:
      description: The request failed validation.
      content:
        application/problem+json:
          schema:
            $ref: "#/components/schemas/Problem"
    Unauthorized:
      description: Missing or unrecognized API key.
      content:
        application/problem+json:
          schema:
            $ref: "#/components/schemas/Problem"
    Forbidden:
      description: The key is valid, but its tenant is not served.
      content:
        application/problem+json:
          schema:
            $ref: "#/components/schemas/Problem"
    NotFound:
      description: No such request.
      content:
        application/problem+json:
          schema:
            $ref: "#/components/schemas/Problem"
    TooManyRequests:
      description: Rate limit exceeded.
      headers:
        Retry-After:
          schema:
            type: integer
      content:
        application/problem+json:
          schema:
            $ref: "#/components/schemas/Problem"

  schemas:
    TemplateRequest:
      type: object
      required: [allocationMonth, productionWeeks, dealers]
      additionalProperties: false
      description: The tenant comes from the API key.
      properties:
        allocationMonth:
          type: string
          pattern: "^[0-9]{4}-(0[1-9]|1[0-2])$"
          description: Month the volumes allocate, as YYYY-MM.
          examples: ["2026-10"]
        productionWeeks:
          type: array
          minItems: 1
          description: |
            The production weeks to select templates for.

            If counts are provided they are used when distributing templates.
          items:
            $ref: "#/components/schemas/RequestedProductionWeek"
        dealers:
          type: array
          minItems: 1
          items:
            $ref: "#/components/schemas/Dealer"
        steering:
          type: array
          description: |
            Take-rate targets, each applying to the scope its group names.
          items:
            $ref: "#/components/schemas/SteeringGroup"

    RequestedProductionWeek:
      type: object
      required: [year, week]
      additionalProperties: false
      properties:
        year:
          type: integer
        week:
          type: integer
          minimum: 1
          maximum: 53
          description: ISO week number.
        count:
          type: integer
          minimum: 1
          description: Orders to place in this week.

    ProductionWeek:
      type: object
      required: [year, week]
      additionalProperties: false
      properties:
        year:
          type: integer
        week:
          type: integer
          minimum: 1
          maximum: 53
          description: ISO week number.

    Dealer:
      type: object
      required: [dealerId, region, quotas]
      additionalProperties: false
      properties:
        dealerId:
          type: string
          maxLength: 50
        region:
          type: string
        quotas:
          type: array
          minItems: 1
          items:
            $ref: "#/components/schemas/DealerQuota"
        priceSettings:
          type: array
          description: Price steering.
          items:
            $ref: "#/components/schemas/PriceSetting"

    DealerQuota:
      type: object
      required: [modelCode, volume]
      additionalProperties: false
      properties:
        modelCode:
          type: string
        volume:
          type: integer
          minimum: 1
          description: Volume for this dealer and model.

    PriceSetting:
      type: object
      required: [modelCode, minPrice, maxPrice, targetPrice, targetQuantile]
      additionalProperties: false
      properties:
        modelCode:
          type: string
        minPrice:
          type: number
        maxPrice:
          type: number
        targetPrice:
          type: number
        targetQuantile:
          type: number
          minimum: 0
          maximum: 1
          description: |
            Shape of the price distribution around `targetPrice`. 0.5 is symmetric; above 0.5
            puts more orders below the target, below 0.5 puts more above it.

    SteeringGroup:
      type: object
      required: [scope, targets]
      additionalProperties: false
      properties:
        scope:
          $ref: "#/components/schemas/SteeringScope"
        targets:
          type: array
          minItems: 1
          items:
            $ref: "#/components/schemas/TakeRateTarget"

    SteeringScope:
      type: object
      description: |
        The population a group's targets are measured over. An empty object means the entire population.
      additionalProperties: false
      properties:
        region:
          type: string
          description: Limits the group to dealers in this region.

    TakeRateTarget:
      type: object
      required: [modelCode, optionCode, targetTakeRate]
      additionalProperties: false
      description: The desired share of a model's orders in scope that should have this option.
      properties:
        modelCode:
          type: string
        optionCode:
          type: string
        targetTakeRate:
          type: number
          minimum: 0
          maximum: 1
          description: |
            Share of the scope's orders that should have the option, as a fraction.
            0 excludes it; 1 puts it on every order.
        tolerance:
          type: number
          minimum: 0
          maximum: 1
          default: 0.05
          description: Acceptable deviation from the target, as a fraction on the same scale.

    TemplateRequestAccepted:
      type: object
      required: [id, status, requestedAt, url]
      properties:
        id:
          type: string
        status:
          const: accepted
        requestedAt:
          type: string
          format: date-time
        url:
          type: string
          format: uri
          description: Absolute URL of the request.

    TemplateRequestStatus:
      type: object
      required: [id, status, requestedAt, models, totals]
      description: |
        Once `status` is `succeeded` or `partially_succeeded`, the response holds either
        `templates` or `templatesUrl`, never both. Before then it holds neither.
      allOf:
        - if:
            properties:
              status:
                enum: [succeeded, partially_succeeded]
            required: [status]
          then:
            oneOf:
              - required: [templates]
              - required: [templatesUrl]
          else:
            not:
              anyOf:
                - required: [templates]
                - required: [templatesUrl]
      properties:
        id:
          type: string
        status:
          $ref: "#/components/schemas/RequestStatus"
        requestedAt:
          type: string
          format: date-time
        startedAt:
          type: string
          format: date-time
        completedAt:
          type: string
          format: date-time
        models:
          type: array
          items:
            $ref: "#/components/schemas/ModelProgress"
        totals:
          $ref: "#/components/schemas/RequestTotals"
        templates:
          type: array
          description: The templates, when small enough to return inline.
          items:
            $ref: "#/components/schemas/Template"
        templatesUrl:
          $ref: "#/components/schemas/TemplatesLink"
        summary:
          $ref: "#/components/schemas/TemplateSummary"
        errors:
          type: array
          items:
            $ref: "#/components/schemas/GenerationError"
        warnings:
          type: array
          description: Conditions that did not stop the request, such as a dealer absent from the brand's dealer feed.
          items:
            type: string

    RequestStatus:
      type: string
      enum: [accepted, running, succeeded, partially_succeeded, failed, cancelled]
      description: |
        `accepted` and `running` mean the request is still in flight. Every other value is terminal.

        `partially_succeeded` means some models produced templates and some did not.

    ModelProgress:
      type: object
      required: [modelCode, status, requestedVolume, generatedVolume]
      properties:
        modelCode:
          type: string
        status:
          $ref: "#/components/schemas/RequestStatus"
        requestedVolume:
          type: integer
        generatedVolume:
          type: integer

    RequestTotals:
      type: object
      required: [requestedVolume, generatedVolume, dealers, models]
      properties:
        requestedVolume:
          type: integer
        generatedVolume:
          type: integer
        dealers:
          type: integer
        models:
          type: integer

    TemplatesLink:
      type: object
      required: [url, expiresAt, contentType]
      description: Where to download the templates when they are too large to return inline.
      properties:
        url:
          type: string
          format: uri
        expiresAt:
          type: string
          format: date-time
        contentType:
          const: application/x-ndjson
          description: One `Template` per line.
        sizeBytes:
          type: integer

    TemplateSummary:
      type: object
      required: [totalTemplates, totalDealers, totalModels, byAction]
      properties:
        totalTemplates:
          type: integer
        totalDealers:
          type: integer
        totalModels:
          type: integer
        byAction:
          type: object
          required: [submit, modify]
          properties:
            submit:
              type: integer
            modify:
              type: integer

    Template:
      type: object
      required:
        - templateId
        - dealerId
        - modelCode
        - action
        - productionWeek
        - rank
        - model_code
        - options
        - templateType
      properties:
        templateId:
          type: string
          description: Identifies this template. Quote it back when reporting order status.
        productionWeek:
          $ref: "#/components/schemas/ProductionWeek"
          description: |
            The production week this template was selected for. One of the request's
            `productionWeeks`. Order the template in this week.
        dealerId:
          type: string
        modelCode:
          type: string
        action:
          type: string
          enum: [submit, modify]
        productionNumber:
          type: string
          description: The existing order to change. Required when `action` is `modify`.
        model_code:
          type: string
        options:
          type: array
          items:
            type: string
        estimatedMsrp:
          type: number
        templateType:
          type: string
          enum: [control_template, predictive_template]
          description: |
            Template classification. Determines how the OEM system handles the template.
            Pass it through unaltered.
        rank:
          type: integer
          minimum: 1
          description: Preference order within a dealer and model, best first.
      allOf:
        - if:
            properties:
              action:
                const: modify
            required: [action]
          then:
            required: [productionNumber]

    GenerationError:
      type: object
      required: [code, message]
      properties:
        code:
          type: string
          enum:
            - INVALID_MODEL
            - UNKNOWN_DEALER
            - NO_CONFIGURATION_AVAILABLE
            - CONSTRUCTABILITY_REJECTED
            - PRICE_RANGE_UNSATISFIABLE
            - CONFLICTING_TAKE_RATES
            - STEERING_UNSATISFIABLE
            - QUOTA_EXCEEDS_CAPACITY
            - UNKNOWN_ERROR
        message:
          type: string
        templateId:
          type: string
          description: |
            Present when a template existed and was then refused, as with
            `CONSTRUCTABILITY_REJECTED`. Absent when the failure stopped a template being
            produced at all.
        dealerId:
          type: string
        modelCode:
          type: string
        requestedVolume:
          type: integer
        generatedVolume:
          type: integer

    OrderStatusReport:
      type: object
      required: [reportedAt, orders]
      additionalProperties: false
      properties:
        reportedAt:
          type: string
          format: date-time
        orders:
          type: array
          minItems: 1
          description: |
            One entry per template acted on. Send a single entry as each order is placed, or
            batch them. Entries may span several template requests.
          items:
            $ref: "#/components/schemas/PlacedOrder"

    PlacedOrder:
      type: object
      required: [templateId, status]
      additionalProperties: false
      description: One outcome for a template that was acted on.
      properties:
        templateId:
          type: string
          description: The template this outcome belongs to, as returned with the templates.
        status:
          type: string
          enum: [SUCCESS, FAILURE, CANCELLED]
          description: |
            `SUCCESS`: the order was created or changed. The template's `action` says which.

            `FAILURE`: the order was attempted and refused.

            `CANCELLED`: the order was created and later removed.
        productionNumber:
          type: string
          description: |
            The order the OEM system created, changed or removed. Required for `SUCCESS` and
            `CANCELLED`, optional for `FAILURE`, where an order may not exist.
        placedAt:
          type: string
          format: date-time
        optionCodes:
          type: array
          description: Options on the order
          items:
            type: string
        reason:
          type: string
          description: Why the order failed, or why it was cancelled.
      allOf:
        - if:
            properties:
              status:
                enum: [SUCCESS, CANCELLED]
            required: [status]
          then:
            required: [productionNumber]

    OrderStatusAccepted:
      type: object
      required: [accepted]
      properties:
        accepted:
          type: integer
          description: Outcomes recorded by this report.
        rejected:
          type: array
          description: Outcomes the report could not record, each naming its template.
          items:
            type: object
            properties:
              templateId:
                type: string
              reason:
                type: string

    Problem:
      type: object
      description: Error format defined by RFC 9457.
      properties:
        type:
          type: string
          format: uri
        title:
          type: string
        status:
          type: integer
        detail:
          type: string
        instance:
          type: string
        violations:
          type: array
          description: Field-level validation failures.
          items:
            type: object
            properties:
              field:
                type: string
              message:
                type: string
