openapi: 3.1.0
info:
  title: POSnavigator Transactions (System-Fee Tables) API
  version: "1.0.0"
  description: |-
    Admin-only v1 API for the system-fee tables in the `transactions` collection:
    the `schemefee_*`, `schemefee2_*`, `basket_*` and `marketshare_*` rows the
    price engine uses, grouped by template (`tr_template`, e.g. one bank's
    interchange/scheme-fee matrix).

    The API never writes the live table. You download a template's full table,
    edit it offline (spreadsheet or agent), and upload the **full new state** as
    a draft. An admin reviews the row-level diff and the consistency result in the
    admin UI (`/admin/transactions/drafts/{id}`) and approves it there. There is
    no approve endpoint: a leaked or buggy agent key cannot change live pricing.

    # Access

    X-Api-Key whose owner is an admin, plus `transaction:read` (GET) or
    `transaction:write` (POST, DELETE). These scopes are **not** on a default key;
    an admin grants them in the API key settings. Missing scope →
    403 INSUFFICIENT_PERMISSIONS; non-admin owner → 403 FORBIDDEN.

    # Units (read this)

    `schemefee_percentage` and `schemefee2_percentage` are **fractions**, as the
    price engine multiplies them directly: `0.000937` = 0.0937%. Writing `0.0937`
    means 9.37%, a 100× error. The consistency check warns above 0.05 (5%), and
    the admin diff flags ≥ 50% and ~100× changes. Marketshares are fractions too
    (0–1, summing to 1 per template + placement).

    # Row identity

    Rows are matched by `_id`. A row without `_id` is new. A live row whose `_id`
    is missing from the upload is deleted. An `_id` that is unknown, belongs to
    another template, or appears twice is a validation error. Editing a basket
    boundary keeps the `_id`, so it shows as a modification.

    # The happy path

    1. GET /openapi/transactions.yaml
    2. GET /api/v1/transactions/templates
    3. GET /api/v1/transactions?tr_template=RAIFFEISEN&format=csv
    4. Edit the CSV. Keep `_id`; leave it empty for new rows; drop rows to delete.
    5. POST /api/v1/transactions/drafts (multipart `file` + `tr_template`)
    6. Read `data.diffSummary` and `data.consistency`; send `data.adminUrl` to an
       admin. Optionally GET /drafts/{draftId} for the field-level diff.
    7. An admin approves in the UI. Re-uploading the same template before that
       supersedes the earlier draft (one open draft per template).

    A downloaded file re-uploaded unchanged produces a draft with 0 changes.

    # CSV format

    UTF-8, comma-separated (semicolon and decimal comma are also accepted on
    upload), header row required. Columns, in order: `_id`, `tr_template`,
    `tr_identifier`, `tr_origin`, `tr_scheme`, `tr_cardholder`, `tr_account`,
    `placement`, `marketshare_1`…`marketshare_7`, `schemefee_fixed`,
    `schemefee_percentage`, `schemefee_min`, `schemefee_max`,
    `schemefee_currency`, `schemefee_currency_sign`, the same five
    `schemefee2_*` columns plus `schemefee2_currency_sign`, `basket_from`,
    `basket_to`, `basket_currency`, `basket_currency_sign`.
    Currency columns hold the currency `_id`; on upload an unambiguous `sign`
    (e.g. `Ft`) is accepted too. `*_sign` columns are read-only and ignored on
    upload. Empty cell = field not set.

    # Drafts

    A draft is never applied automatically. Statuses: `draft` (open),
    `approved`, `discarded`, `superseded`. A draft records the fingerprint of the
    live table at upload time; if the live table changes before approval (for
    example someone edits a row in the admin UI), the draft becomes stale
    (`isStale: true`) and cannot be approved — download again and re-upload.

    # Response envelope

    Success: `{ "success": true, "data": ... }`.
    Failure: `{ "success": false, "error": { "code", "message", "details"?, "field_errors"? } }`.
    Branch on error.code, never on error.message. Validation failures (422) list
    one line per problem in `details` (first 50) and group them by row in
    `field_errors` (`row_3: ["schemefee_currency: unknown currency \"XYZ\""]`).
    Row numbers are 1-based data rows; the CSV header is not counted.

    # Error codes

    | code | status | what to do |
    | --- | --- | --- |
    | MISSING_API_KEY | 401 | add X-Api-Key; do not retry blindly |
    | INVALID_API_KEY | 401 | stop; ask a human for a new key |
    | INSUFFICIENT_PERMISSIONS | 403 | stop; ask an admin to grant transaction:read / transaction:write |
    | FORBIDDEN | 403 | stop; admin key owner required |
    | INVALID_QUERY | 400 | fix the query string |
    | INVALID_BODY | 400 | send JSON or multipart with `file` and include tr_template |
    | TEMPLATE_NOT_FOUND | 404 | check GET /api/v1/transactions/templates |
    | NOT_FOUND | 404 | the draft id does not exist |
    | DRAFT_NOT_OPEN | 409 | the draft is already approved, discarded or superseded |
    | PAYLOAD_TOO_LARGE | 413 | body over 5 MB |
    | TOO_MANY_ROWS | 413 | more than 5000 rows |
    | UNSUPPORTED_MEDIA_TYPE | 415 | use application/json or multipart/form-data |
    | VALIDATION_FAILED | 422 | fix the listed rows; no draft was created |
    | RATE_LIMIT_EXCEEDED | 429 | wait Retry-After seconds |
    | INTERNAL_ERROR | 500 | retry with backoff |

    # Rate limiting

    Every response after successful authentication carries X-RateLimit-Limit,
    X-RateLimit-Remaining and X-RateLimit-Reset. A 429 also carries Retry-After.
    Default window is 100 requests per rolling hour unless the key was configured
    otherwise.

    # Canonical host

    Use https://posnavigator.eu. Legacy .hu hosts redirect; authenticated writes
    should call .eu directly so the X-Api-Key header is not dropped.
servers:
  - url: https://posnavigator.eu
tags:
  - name: Discovery
  - name: Transactions
security:
  - ApiKeyAuth: []
paths:
  /openapi/transactions.yaml:
    get:
      operationId: getTransactionsOpenApiSelf
      tags: [Discovery]
      security: []
      summary: Public OpenAPI 3.1 description
      description: |-
        This document. Public: no API key, no rate limit. Fetch it first and treat
        it as the complete manual for downloading system-fee tables and uploading
        drafts. Approval is admin-UI only and is not part of this API.
      responses:
        '200':
          description: OpenAPI YAML
          content:
            application/yaml:
              schema:
                type: string
              example: 'openapi: 3.1.0'
  /api/v1/transactions/templates:
    get:
      operationId: listTransactionTemplates
      tags: [Transactions]
      summary: List templates
      description: |-
        Every tr_template that has rows in the live table, sorted by name, with its
        row count, the latest updatedAt of its rows, and the id of its open draft if
        one exists. Requires transaction:read and an admin key owner.
      responses:
        '200':
          description: Templates
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TemplateListResponse'
        '401':
          description: Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '403':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '429':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
            Retry-After:
              $ref: '#/components/headers/Retry-After'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '500':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
  /api/v1/transactions:
    get:
      operationId: exportTransactionTemplate
      tags: [Transactions]
      summary: Download a template's full table
      description: |-
        The full live table of one template with every model field and `_id`, in a
        stable column and row order (tr_identifier → placement → basket_from). This
        is exactly the file the upload expects: re-uploading it unchanged yields a
        draft with 0 changes. format=csv returns text/csv (byte-identical to the
        admin "CSV export" button) with the fingerprint in the X-Base-Fingerprint
        header; format=json (default) returns rows, currencies and baseFingerprint.
      parameters:
        - name: tr_template
          in: query
          required: true
          schema: { type: string, maxLength: 200 }
        - name: format
          in: query
          schema: { type: string, enum: [json, csv], default: json }
      responses:
        '200':
          description: Full template table
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
            X-Base-Fingerprint:
              description: SHA-256 of the live rows (csv format only)
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TemplateExportResponse'
            text/csv:
              schema:
                type: string
              example: |-
                _id,tr_template,tr_identifier,tr_origin,tr_scheme,tr_cardholder,tr_account,placement,marketshare_1,...
        '400':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '401':
          description: Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '403':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '404':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '429':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
            Retry-After:
              $ref: '#/components/headers/Retry-After'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '500':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
  /api/v1/transactions/drafts:
    get:
      operationId: listTransactionDrafts
      tags: [Transactions]
      summary: List drafts
      description: |-
        Drafts newest first, without their rows. Filter by tr_template and status
        (draft, approved, discarded, superseded). Open drafts carry isStale: true
        when the live table changed after upload; such a draft cannot be approved.
      parameters:
        - name: tr_template
          in: query
          schema: { type: string, maxLength: 200 }
        - name: status
          in: query
          schema: { type: string, enum: [draft, approved, discarded, superseded] }
        - name: limit
          in: query
          schema: { type: integer, minimum: 1, maximum: 500, default: 100 }
      responses:
        '200':
          description: Drafts
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DraftListResponse'
        '400':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '401':
          description: Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '403':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '429':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
            Retry-After:
              $ref: '#/components/headers/Retry-After'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '500':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
    post:
      operationId: createTransactionDraft
      tags: [Transactions]
      summary: Upload the full new state of a template as a draft
      description: |-
        Validates every row (enums, numbers, basket_from < basket_to, currencies,
        tr_template, _id identity), then stores a draft and returns the diff summary,
        per-field change counts, the consistency comparison against live and the
        admin URL. The live transactions collection is not modified. If any row is
        invalid, no draft is created and 422 VALIDATION_FAILED lists the rows. An
        earlier open draft of the same template becomes superseded. Accepts
        multipart/form-data (`file` = CSV, `tr_template`, optional `note`),
        or application/json `{ tr_template, rows[], note? }`. An empty row list or
        header-only CSV stages deletion of all rows for admin review.
        Limits: 5000 rows, 5 MB for the entire request body. Requires transaction:write.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required: [file, tr_template]
              properties:
                file:
                  type: string
                  format: binary
                  description: CSV in the export format
                tr_template:
                  type: string
                  maxLength: 200
                note:
                  type: string
                  maxLength: 2000
          application/json:
            schema:
              type: object
              additionalProperties: false
              required: [tr_template, rows]
              properties:
                tr_template:
                  type: string
                  maxLength: 200
                rows:
                  type: array
                  maxItems: 5000
                  items:
                    $ref: '#/components/schemas/TransactionRow'
                note:
                  type: string
                  maxLength: 2000
            example:
              tr_template: RAIFFEISEN
              note: ICC+ 2026 Q4
              rows:
                - _id: 64b7f0c2a1b2c3d4e5f60718
                  tr_template: RAIFFEISEN
                  tr_identifier: VCDCD
                  tr_origin: Domestic
                  tr_scheme: Visa
                  tr_cardholder: Consumer
                  tr_account: credit
                  placement: card present
                  marketshare_1: 0.21
                  schemefee_percentage: 0.000978
                  schemefee_fixed: 5
                  schemefee_currency: Ft
      responses:
        '201':
          description: Draft created
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DraftCreateResponse'
        '400':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '401':
          description: Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '403':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '413':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '415':
          description: Unsupported upload media type
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '422':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '429':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
            Retry-After:
              $ref: '#/components/headers/Retry-After'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '500':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
  /api/v1/transactions/drafts/{draftId}:
    get:
      operationId: getTransactionDraft
      tags: [Transactions]
      summary: Draft status and full diff
      description: |-
        Status, summary and the full field-level diff. An open draft is compared
        with the current live table (diffBase: live); an approved draft with the
        state saved right before approval (diffBase: beforeRows). Each entry lists
        type (added, modified, deleted, unchanged), before/after rows and changedFields.
      parameters:
        - name: draftId
          in: path
          required: true
          schema: { type: string, pattern: '^[a-f0-9]{24}$' }
      responses:
        '200':
          description: Draft
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DraftDetailResponse'
        '401':
          description: Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '403':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '404':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '429':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
            Retry-After:
              $ref: '#/components/headers/Retry-After'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '500':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
    delete:
      operationId: discardTransactionDraft
      tags: [Transactions]
      summary: Discard an open draft
      description: |-
        Marks an open draft as discarded. The live table is not touched. Approved,
        superseded or already discarded drafts return 409 DRAFT_NOT_OPEN. There is
        no approve operation on this API; approval needs an admin session in the UI.
      parameters:
        - name: draftId
          in: path
          required: true
          schema: { type: string, pattern: '^[a-f0-9]{24}$' }
      responses:
        '200':
          description: Discarded draft
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/DraftMetaResponse'
        '401':
          description: Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '403':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '404':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '409':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '429':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
            Retry-After:
              $ref: '#/components/headers/Retry-After'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '500':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
  /api/v1/transactions/drafts/{draftId}/consistency:
    get:
      operationId: getTransactionDraftConsistency
      tags: [Transactions]
      summary: Consistency check of the draft vs live
      description: |-
        Runs the same rule set as the admin consistency tab on the draft rows and on
        the live table, and marks each problem as new, resolved or persisting.
        newErrorCount counts new problems in error rules; warnings (e.g. a
        percentage above 5%) never block approval. An admin must explicitly
        acknowledge new errors before approving.
      parameters:
        - name: draftId
          in: path
          required: true
          schema: { type: string, pattern: '^[a-f0-9]{24}$' }
      responses:
        '200':
          description: Consistency comparison
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ConsistencyResponse'
        '401':
          description: Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '403':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '404':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '429':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
            Retry-After:
              $ref: '#/components/headers/Retry-After'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '500':
          description: Error
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/X-RateLimit-Limit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/X-RateLimit-Remaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/X-RateLimit-Reset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X-Api-Key
      description: |-
        Send `X-Api-Key: pn_...` on every data operation. Create a key at
        /user/api-keys; it is shown once. Inactive or expired keys return 401.
  headers:
    X-RateLimit-Limit:
      description: Maximum requests allowed in the current window
      schema:
        type: integer
    X-RateLimit-Remaining:
      description: Requests remaining in the current window
      schema:
        type: integer
    X-RateLimit-Reset:
      description: Unix epoch seconds when the window resets
      schema:
        type: integer
    Retry-After:
      description: Seconds to wait before retrying a 429
      schema:
        type: integer
  schemas:
    ErrorEnvelope:
      type: object
      additionalProperties: false
      required: [success, error]
      properties:
        success:
          type: boolean
          const: false
        error:
          type: object
          additionalProperties: false
          required: [code, message]
          properties:
            code:
              type: string
              maxLength: 80
              description: Stable machine code. Branch on this, never on message.
            message:
              type: string
              maxLength: 2000
            details:
              type: array
              maxItems: 50
              items:
                type: string
                maxLength: 500
            retryAfter:
              type: integer
              description: Present on RATE_LIMIT_EXCEEDED
            field_errors:
              type: object
              additionalProperties:
                type: array
                maxItems: 20
                items:
                  type: string
                  maxLength: 500
    Actor:
      type: object
      additionalProperties: false
      properties:
        apiKeyId: { type: string, maxLength: 24 }
        userId: { type: string, maxLength: 64 }
        name: { type: string, maxLength: 200 }
    TransactionRow:
      type: object
      description: |-
        One row of the transactions collection. Percentages and marketshares are
        fractions. Currency fields hold a currency _id (upload also accepts a sign).
      required: [tr_template, tr_identifier, tr_origin, tr_scheme, tr_cardholder, tr_account, placement, marketshare_1]
      properties:
        _id: { type: string, pattern: '^[a-f0-9]{24}$', description: 'Omit for a new row' }
        tr_template: { type: string, maxLength: 200 }
        tr_identifier: { type: string, maxLength: 200 }
        tr_origin: { type: string, enum: [On-us, Domestic, EU, Non-EU] }
        tr_scheme: { type: string, enum: [Visa, Mastercard, Qvik] }
        tr_cardholder: { type: string, enum: [Consumer, Corporate] }
        tr_account: { type: string, enum: [credit, debit, prepaid] }
        placement: { type: string, enum: [card present, card not present] }
        marketshare_1: { type: number, minimum: 0, maximum: 1 }
        marketshare_2: { type: number, minimum: 0, maximum: 1 }
        marketshare_3: { type: number, minimum: 0, maximum: 1 }
        marketshare_4: { type: number, minimum: 0, maximum: 1 }
        marketshare_5: { type: number, minimum: 0, maximum: 1 }
        marketshare_6: { type: number, minimum: 0, maximum: 1 }
        marketshare_7: { type: number, minimum: 0, maximum: 1 }
        schemefee_fixed: { type: number, minimum: 0 }
        schemefee_percentage: { type: number, minimum: 0, description: 'Fraction: 0.000937 = 0.0937%' }
        schemefee_min: { type: number, minimum: 0 }
        schemefee_max: { type: number, minimum: 0 }
        schemefee_currency: { type: string, maxLength: 24 }
        schemefee2_fixed: { type: number, minimum: 0 }
        schemefee2_percentage: { type: number, minimum: 0, description: 'Fraction: 0.000937 = 0.0937%' }
        schemefee2_min: { type: number, minimum: 0 }
        schemefee2_max: { type: number, minimum: 0 }
        schemefee2_currency: { type: string, maxLength: 24 }
        basket_from: { type: number, minimum: 0 }
        basket_to: { type: number, minimum: 0, description: 'Must be greater than basket_from' }
        basket_currency: { type: string, maxLength: 24 }
    Currency:
      type: object
      additionalProperties: false
      required: [_id, sign]
      properties:
        _id: { type: string, maxLength: 24 }
        sign: { type: string, maxLength: 20 }
    DiffSummary:
      type: object
      additionalProperties: false
      required: [added, modified, deleted, unchanged]
      properties:
        added: { type: integer }
        modified: { type: integer }
        deleted: { type: integer }
        unchanged: { type: integer }
    FieldChangeCounts:
      type: object
      description: Per field, the number of modified rows in which it changed
      additionalProperties: { type: integer }
    DiffEntry:
      type: object
      additionalProperties: false
      required: [type, changedFields]
      properties:
        type: { type: string, enum: [added, modified, deleted, unchanged] }
        id: { type: string, maxLength: 24, description: 'Live row _id; absent for added rows' }
        before: { $ref: '#/components/schemas/TransactionRow' }
        after: { $ref: '#/components/schemas/TransactionRow' }
        changedFields:
          type: array
          items: { type: string, maxLength: 40 }
    TemplateSummary:
      type: object
      additionalProperties: false
      required: [tr_template, rowCount]
      properties:
        tr_template: { type: string, maxLength: 200 }
        rowCount: { type: integer }
        lastModifiedAt: { type: string, maxLength: 40 }
        openDraftId: { type: string, maxLength: 24 }
    TemplateListResponse:
      type: object
      required: [success, data]
      properties:
        success: { type: boolean, const: true }
        data:
          type: array
          items: { $ref: '#/components/schemas/TemplateSummary' }
    TemplateExportResponse:
      type: object
      required: [success, data]
      properties:
        success: { type: boolean, const: true }
        data:
          type: object
          required: [tr_template, baseFingerprint, rowCount, currencies, rows]
          properties:
            tr_template: { type: string, maxLength: 200 }
            baseFingerprint: { type: string, maxLength: 64 }
            rowCount: { type: integer }
            currencies:
              type: array
              items: { $ref: '#/components/schemas/Currency' }
            rows:
              type: array
              items: { $ref: '#/components/schemas/TransactionRow' }
    DraftMeta:
      type: object
      required: [_id, tr_template, status, rowCount, baseRowCount, baseFingerprint, diffSummary, createdBy, createdAt, isStale, adminUrl]
      properties:
        _id: { type: string, maxLength: 24 }
        tr_template: { type: string, maxLength: 200 }
        status: { type: string, enum: [draft, approved, discarded, superseded] }
        note: { type: string, maxLength: 2000 }
        rowCount: { type: integer }
        baseRowCount: { type: integer }
        baseFingerprint: { type: string, maxLength: 64 }
        diffSummary: { $ref: '#/components/schemas/DiffSummary' }
        consistency:
          type: object
          properties:
            checkedAt: { type: string, maxLength: 40 }
            newErrorCount: { type: integer }
            newWarningCount: { type: integer }
            resolvedCount: { type: integer }
        createdBy: { $ref: '#/components/schemas/Actor' }
        createdAt: { type: string, maxLength: 40 }
        approvedBy: { $ref: '#/components/schemas/Actor' }
        approvedAt: { type: string, maxLength: 40 }
        discardedBy: { $ref: '#/components/schemas/Actor' }
        discardedAt: { type: string, maxLength: 40 }
        supersededAt: { type: string, maxLength: 40 }
        supersededByDraftId: { type: string, maxLength: 24 }
        restoredFromDraftId: { type: string, maxLength: 24 }
        isStale: { type: boolean, description: 'Open draft whose base no longer matches live; cannot be approved' }
        adminUrl: { type: string, maxLength: 200, description: 'Relative admin UI path for review and approval' }
    DraftListResponse:
      type: object
      required: [success, data]
      properties:
        success: { type: boolean, const: true }
        data:
          type: array
          items: { $ref: '#/components/schemas/DraftMeta' }
    DraftMetaResponse:
      type: object
      required: [success, data]
      properties:
        success: { type: boolean, const: true }
        data: { $ref: '#/components/schemas/DraftMeta' }
    DraftDetailResponse:
      type: object
      required: [success, data]
      properties:
        success: { type: boolean, const: true }
        data:
          allOf:
            - $ref: '#/components/schemas/DraftMeta'
            - type: object
              required: [diffBase, diff, currencies, hasBeforeRows]
              properties:
                diffBase: { type: string, enum: [live, beforeRows] }
                hasBeforeRows: { type: boolean }
                currencies:
                  type: array
                  items: { $ref: '#/components/schemas/Currency' }
                diff:
                  type: object
                  required: [summary, fieldChangeCounts, entries]
                  properties:
                    summary: { $ref: '#/components/schemas/DiffSummary' }
                    fieldChangeCounts: { $ref: '#/components/schemas/FieldChangeCounts' }
                    entries:
                      type: array
                      items: { $ref: '#/components/schemas/DiffEntry' }
    ConsistencyTotals:
      type: object
      required: [newErrorCount, newWarningCount, resolvedCount, liveRecordsChecked, draftRecordsChecked]
      properties:
        newErrorCount: { type: integer, description: 'New problems in error rules; approval needs explicit acknowledgement' }
        newWarningCount: { type: integer }
        resolvedCount: { type: integer }
        liveRecordsChecked: { type: integer }
        draftRecordsChecked: { type: integer }
    DraftCreateResponse:
      type: object
      required: [success, data]
      properties:
        success: { type: boolean, const: true }
        data:
          type: object
          required: [draftId, tr_template, status, rowCount, baseFingerprint, diffSummary, fieldChangeCounts, consistency, supersededDraftIds, adminUrl]
          properties:
            draftId: { type: string, maxLength: 24 }
            tr_template: { type: string, maxLength: 200 }
            status: { type: string, const: draft }
            rowCount: { type: integer }
            baseFingerprint: { type: string, maxLength: 64 }
            diffSummary: { $ref: '#/components/schemas/DiffSummary' }
            fieldChangeCounts: { $ref: '#/components/schemas/FieldChangeCounts' }
            consistency:
              allOf:
                - $ref: '#/components/schemas/ConsistencyTotals'
                - type: object
                  properties:
                    rules:
                      type: array
                      items:
                        type: object
                        properties:
                          ruleId: { type: integer }
                          name: { type: string, maxLength: 100 }
                          severity: { type: string, enum: [error, warning] }
                          newCount: { type: integer }
                          resolvedCount: { type: integer }
                          persistingCount: { type: integer }
            supersededDraftIds:
              type: array
              items: { type: string, maxLength: 24 }
            adminUrl: { type: string, maxLength: 200 }
    ConsistencyResponse:
      type: object
      required: [success, data]
      properties:
        success: { type: boolean, const: true }
        data:
          allOf:
            - $ref: '#/components/schemas/ConsistencyTotals'
            - type: object
              required: [rules, checkedAt, tr_template, draftId]
              properties:
                draftId: { type: string, maxLength: 24 }
                tr_template: { type: string, maxLength: 200 }
                checkedAt: { type: string, maxLength: 40 }
                rules:
                  type: array
                  items:
                    type: object
                    required: [ruleId, name, description, severity, passed, errors, newCount, resolvedCount, persistingCount]
                    properties:
                      ruleId: { type: integer }
                      name: { type: string, maxLength: 100 }
                      description: { type: string, maxLength: 500 }
                      severity: { type: string, enum: [error, warning] }
                      passed: { type: boolean, description: 'Result on the draft rows' }
                      newCount: { type: integer }
                      resolvedCount: { type: integer }
                      persistingCount: { type: integer }
                      errors:
                        type: array
                        items:
                          type: object
                          required: [identifier, details, status]
                          properties:
                            identifier: { type: string, maxLength: 200 }
                            placement: { type: string, maxLength: 40 }
                            rowId: { type: string, maxLength: 24 }
                            details: { type: string, maxLength: 1000 }
                            status: { type: string, enum: [new, resolved, persisting] }
