openapi: 3.1.0
info:
  title: OHN-52 Paper Health Record Digitisation
  version: 1.0.0
  description: |
    Digitise patient-held paper health booklets. Every mutation needs `Idempotency-Key` (any non-empty value up to 255 characters); every request a Bearer token
    (role, jurisdiction, organization_id, purpose; subject, jurisdiction and organization are UUIDs, otherwise 401). Default deny: an unknown route is 404 after authentication, a role that is not listed for
    the route is 403 `denied_by_policy` (audited), and a purpose that is not the role's own is 403. Digitised items are never verified. Page images are kept as originals in OHN-13 (required: no original, no upload);
    recognition proposes items only when an extraction engine is configured, and every proposal needs a person's decision. Without an engine every page fails closed (`failure_reason: not_configured`) and the reviewer
    transcribes by hand (`POST /jobs/{id}/items`). 503 `not_configured` (with `dependency` and `setting`) means a required dependency or key is not configured and nothing was stored.
servers: [{ url: / }]
security: [{ bearer: [] }]
tags: [{ name: jobs }, { name: review }, { name: record }, { name: reports }, { name: ops }]
paths:
  /health/ohn-52:
    get:
      tags: [ops]
      security: []
      summary: Health, recognition engine and dependency modes
      responses:
        '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/Health' } } } }
        '503': { description: Database unavailable }
  /api/ohn/v1/digitisation/context:
    get: { tags: [ops], summary: Caller context and engine status, responses: { '200': { description: OK } } }
  /api/ohn/v1/digitisation/jobs:
    post:
      tags: [jobs]
      summary: Upload booklet pages with consent (F001, W001)
      parameters: [{ $ref: '#/components/parameters/IdempotencyKey' }]
      requestBody:
        required: true
        content:
          application/json: { schema: { $ref: '#/components/schemas/CreateJob' } }
          multipart/form-data:
            schema:
              type: object
              required: [consent, pages]
              properties:
                patient_id: { type: string, format: uuid }
                review_org_id: { type: string, format: uuid, description: 'Patient uploads only: the care site that reviews the pages (the Java service reads it; the TypeScript reference ignored this multipart field)' }
                title: { type: string, minLength: 1, maxLength: 200 }
                consent: { type: string, description: JSON-encoded Consent }
                pages: { type: array, items: { type: string, format: binary } }
      responses:
        '201': { description: Job created, content: { application/json: { schema: { $ref: '#/components/schemas/Job' } } } }
        '400': { description: Missing idempotency key or malformed body }
        '403': { description: 'patient_self_only, consent_denied (OHN-15), or role not permitted' }
        '409': { description: Idempotency key reused with another payload }
        '413': { description: Body larger than OHN52_MAX_UPLOAD_BODY }
        '422': { description: 'domain_validation_failed, consent_method_invalid, type_mismatch, page_too_large, unsupported_type, image_too_many_pixels, pdf_active_content, image_corrupt' }
        '429': { description: Rate limited }
        '503': { description: OHN-13 or OHN-15 unavailable or unconfigured; nothing stored }
    get:
      tags: [jobs]
      summary: List jobs in scope
      parameters:
        - { name: state, in: query, schema: { type: string, maxLength: 32 }, description: 'Any state name up to 32 characters; an unknown name lists nothing.' }
        - { name: patient_id, in: query, schema: { type: string, format: uuid } }
      responses: { '200': { description: OK, content: { application/json: { schema: { type: object, properties: { items: { type: array, items: { $ref: '#/components/schemas/JobSummary' } } } } } } } }
  /api/ohn/v1/digitisation/jobs/{id}:
    parameters: [{ $ref: '#/components/parameters/Id' }]
    get:
      tags: [jobs]
      summary: Job detail (patients see items only after completion, never OCR text)
      responses: { '200': { description: OK, content: { application/json: { schema: { $ref: '#/components/schemas/Job' } } } }, '404': { description: Not in scope } }
  /api/ohn/v1/digitisation/jobs/{id}/pages/{pageId}/image:
    parameters: [{ $ref: '#/components/parameters/Id' }, { name: pageId, in: path, required: true, schema: { type: string, format: uuid } }]
    get:
      tags: [jobs]
      summary: Page image (metadata stripped); viewing is audited
      responses: { '200': { description: Image, content: { image/png: {}, image/jpeg: {}, application/pdf: {} } }, '404': { description: Not in scope } }
  /api/ohn/v1/digitisation/jobs/{id}/items:
    parameters: [{ $ref: '#/components/parameters/Id' }, { $ref: '#/components/parameters/IdempotencyKey' }]
    post:
      tags: [review]
      summary: Add an item the engine missed (F003)
      requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/AddItem' } } } }
      responses: { '201': { description: Added }, '409': { description: Job not reviewable }, '422': { $ref: '#/components/responses/Invalid' } }
  /api/ohn/v1/digitisation/jobs/{id}/items/{itemId}/decision:
    parameters: [{ $ref: '#/components/parameters/Id' }, { name: itemId, in: path, required: true, schema: { type: string, format: uuid } }, { $ref: '#/components/parameters/IdempotencyKey' }]
    post:
      tags: [review]
      summary: Accept, edit or reject an item (F002, W003)
      requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/Decision' } } } }
      responses: { '200': { description: Decided }, '409': { description: Stale version or job not reviewable }, '422': { $ref: '#/components/responses/Invalid' } }
  /api/ohn/v1/digitisation/jobs/{id}/sign-off:
    parameters: [{ $ref: '#/components/parameters/Id' }, { $ref: '#/components/parameters/IdempotencyKey' }]
    post:
      tags: [review]
      summary: Sign off and write accepted items as unverified (F004, W004)
      requestBody: { required: true, content: { application/json: { schema: { $ref: '#/components/schemas/SignOff' } } } }
      responses:
        '200': { description: 'Completed; `writes` counts per write_status (written, held_no_code, refused, pending_retry, kept_in_ohn52)' }
        '403': { description: clinician_signoff_required }
        '409': { description: Stale version or job not reviewable }
        '422': { description: items_undecided }
  /api/ohn/v1/digitisation/jobs/{id}/reject:
    parameters: [{ $ref: '#/components/parameters/Id' }, { $ref: '#/components/parameters/IdempotencyKey' }]
    post:
      tags: [review]
      summary: Reject the job (F005)
      requestBody: { required: true, content: { application/json: { schema: { type: object, additionalProperties: false, required: [expected_version, reason], properties: { expected_version: { type: integer, minimum: 1 }, reason: { type: string, minLength: 10, maxLength: 2000 } } } } } }
      responses: { '200': { description: Rejected }, '409': { description: Invalid transition or stale } }
  /api/ohn/v1/digitisation/jobs/{id}/retry-writes:
    parameters: [{ $ref: '#/components/parameters/Id' }, { $ref: '#/components/parameters/IdempotencyKey' }]
    post: { tags: [review], summary: Retry pending OHN-10 writes, requestBody: { content: { application/json: { schema: { type: object, additionalProperties: false } } } }, responses: { '200': { description: Retried } } }
  /api/ohn/v1/digitisation/jobs/{id}/reprocess:
    parameters: [{ $ref: '#/components/parameters/Id' }, { $ref: '#/components/parameters/IdempotencyKey' }]
    post: { tags: [ops], summary: Recognise again before any decision (admin), requestBody: { content: { application/json: { schema: { type: object, additionalProperties: false } } } }, responses: { '200': { description: Queued }, '409': { description: Review started } } }
  /api/ohn/v1/digitisation/patients/{patientId}/digitised-items:
    parameters: [{ name: patientId, in: path, required: true, schema: { type: string, format: uuid } }]
    get:
      tags: [record]
      summary: Accepted items of signed-off jobs, each with paper provenance
      responses: { '200': { description: OK, content: { application/json: { schema: { type: object, properties: { verification_status: { const: unverified_patient_held }, items: { type: array, items: { $ref: '#/components/schemas/RecordItem' } } } } } } } }
  /api/ohn/v1/digitisation/reports:
    get: { tags: [reports], summary: Report catalogue, responses: { '200': { description: OK } } }
  /api/ohn/v1/digitisation/reports/{reportId}:
    parameters: [{ $ref: '#/components/parameters/ReportId' }, { name: days, in: query, schema: { type: integer, minimum: 1, maximum: 730, default: 90 } }]
    get: { tags: [reports], summary: Run a report, responses: { '200': { description: OK } } }
  /api/ohn/v1/digitisation/reports/{reportId}/export:
    parameters: [{ $ref: '#/components/parameters/ReportId' }, { name: days, in: query, schema: { type: integer } }]
    get:
      tags: [reports]
      summary: Signed CSV export
      responses:
        '200': { description: CSV, headers: { X-OHN52-Signature: { schema: { type: string, pattern: '^hmac-sha256=[0-9a-f]{64}$' } } }, content: { text/csv: {} } }
        '503': { description: OHN52_EXPORT_SIGNING_KEY not configured }
  /api/ohn/v1/digitisation/audit:
    get: { tags: [ops], summary: Latest audit receipts (digitisation_admin), responses: { '200': { description: OK } } }
  /api/ohn/v1/digitisation/admin/outbox/relay:
    post: { tags: [ops], summary: Relay pending events to OHN-24, parameters: [{ $ref: '#/components/parameters/IdempotencyKey' }], responses: { '200': { description: Relay result } } }
components:
  securitySchemes:
    bearer: { type: http, scheme: bearer, bearerFormat: JWT, description: 'Gateway token (ES256, iss ohn-platform-gateway, aud ohn-52) with sub, role, jurisdiction, organization_id and purpose. The TypeScript reference verified HS256 tokens (iss ohn-52-digitisation, aud ohn-52-api) and offered a development-only token route; neither is part of the Java contract.' }
  parameters:
    Id: { name: id, in: path, required: true, schema: { type: string, format: uuid } }
    IdempotencyKey: { name: Idempotency-Key, in: header, required: true, schema: { type: string, maxLength: 255 } }
    ReportId: { name: reportId, in: path, required: true, schema: { enum: [OHN-52-R001, OHN-52-R002, OHN-52-R003] } }
  responses:
    Invalid: { description: 'domain_validation_failed; details maps each top-level field to the first failing check as a zod issue code (invalid_type, too_small, too_big, invalid_string, invalid_enum_value, invalid_literal, invalid_union, custom), unknown keys under _ as unrecognized_keys; the reference returned zod flatten() (formErrors, fieldErrors) instead' }
  schemas:
    JobState: { enum: [uploaded, processing, ready_for_review, partially_reviewed, completed, rejected] }
    ItemType: { enum: [date, vaccination, diagnosis, medication, allergy, blood_group, genotype, vital_sign, visit] }
    Consent:
      type: object
      additionalProperties: false
      required: [method, statement_version, patient_agrees]
      properties:
        method: { enum: [patient_self_upload, verbal_witnessed, written_signed] }
        statement_version: { type: string, minLength: 1, maxLength: 32 }
        patient_agrees: { const: true }
        ai_processing_allowed: { type: boolean, default: false }
        witness_name: { type: string, minLength: 2, maxLength: 200, description: Required for verbal_witnessed }
    CreateJob:
      type: object
      additionalProperties: false
      required: [consent, pages]
      properties:
        patient_id: { type: string, format: uuid, description: Required for clinic capture; must be absent or own id for patients }
        review_org_id: { type: string, format: uuid, description: 'Required for patient uploads: the care site (OHN-05 facility id) whose queue reviews the pages; ignored for staff, whose job belongs to their own organization' }
        title: { type: string, minLength: 1, maxLength: 200 }
        consent: { $ref: '#/components/schemas/Consent' }
        pages:
          type: array
          minItems: 1
          maxItems: 20
          items: { type: object, additionalProperties: false, required: [media_type, content_base64], properties: { media_type: { enum: [image/jpeg, image/png, application/pdf] }, content_base64: { type: string, contentEncoding: base64 } } }
    Bbox: { type: [object, 'null'], properties: { x: { type: number }, y: { type: number }, w: { type: number }, h: { type: number } }, description: Fractions (0..1) of page width/height }
    Item:
      type: object
      properties:
        id: { type: string, format: uuid }
        page_id: { type: string, format: uuid }
        item_type: { $ref: '#/components/schemas/ItemType' }
        origin: { enum: [engine, reviewer_added] }
        source_text: { type: string }
        proposed: { type: object }
        final: { type: [object, 'null'] }
        confidence: { type: number, minimum: 0, maximum: 1 }
        low_confidence: { type: boolean }
        bbox: { $ref: '#/components/schemas/Bbox' }
        state: { enum: [proposed, accepted, edited, rejected] }
        version: { type: integer }
        verification_status: { const: unverified_patient_held }
        lab_verified: { const: false }
        target: { enum: [ohn10_problem, ohn10_medication, ohn10_allergy, ohn52_record] }
        target_gap: { type: [string, 'null'] }
        write_status: { enum: [not_applicable, written, held_no_code, refused, pending_retry, kept_in_ohn52] }
        provenance: { $ref: '#/components/schemas/Provenance' }
    Provenance:
      type: [object, 'null']
      properties:
        source: { const: digitised_from_paper }
        label_en: { type: string }
        label_fr: { type: string }
        verification_status: { const: unverified_patient_held }
        reviewer_id: { type: string, format: uuid }
        reviewed_at: { type: string, format: date-time }
        page_image_ref: { type: object, properties: { job_id: { type: string }, page_id: { type: string }, ohn13_document_id: { type: string } } }
        lab_verified: { const: false }
        transfusion_verified: { const: false, description: blood_group only }
        caveat_en: { type: string, description: 'blood_group: Reported in paper booklet, not verified for transfusion.' }
    RecordItem:
      type: object
      properties: { id: { type: string }, item_type: { $ref: '#/components/schemas/ItemType' }, value: { type: object }, write_status: { type: string }, lab_verified: { const: false }, provenance: { $ref: '#/components/schemas/Provenance' } }
    JobSummary:
      type: object
      properties: { id: { type: string }, state: { $ref: '#/components/schemas/JobState' }, source: { enum: [patient_upload, clinic_capture] }, page_count: { type: integer }, item_count: { type: integer }, open_items: { type: integer }, low_confidence_open: { type: integer }, engines: { type: array, items: { type: string } }, images_left_platform: { type: boolean }, version: { type: integer } }
    Job:
      allOf:
        - { $ref: '#/components/schemas/JobSummary' }
        - type: object
          properties:
            allowed_actions: { type: array, items: { enum: [decide_item, add_item, sign_off, reject, reprocess, retry_writes] } }
            engine_requested: { enum: [tesseract-local, anthropic-vision] }
            ai_authorisation_ref: { type: [string, 'null'] }
            pages: { type: array, items: { type: object } }
            items: { type: array, items: { $ref: '#/components/schemas/Item' } }
            history: { type: array, items: { type: object } }
            engine_runs: { type: array, items: { type: object, properties: { engine: { type: string }, model: { type: string }, left_platform: { type: boolean }, authorisation_ref: { type: [string, 'null'] }, outcome: { type: string }, duration_ms: { type: integer } } } }
            receipt: { type: object }
    AddItem:
      type: object
      additionalProperties: false
      required: [page_id, item_type, source_text, value]
      properties: { page_id: { type: string, format: uuid }, item_type: { $ref: '#/components/schemas/ItemType' }, source_text: { type: string, minLength: 1, maxLength: 1000 }, value: { type: object, maxProperties: 20, additionalProperties: { type: [string, number, boolean, 'null'] }, description: 'Values are strings of at most 500 characters, numbers, booleans or null; any key containing "verif" is dropped' } }
    Decision:
      type: object
      additionalProperties: false
      required: [expected_version, decision]
      properties: { expected_version: { type: integer, minimum: 1 }, decision: { enum: [accept, edit, reject] }, value: { type: object, maxProperties: 20, description: Required for edit }, reason: { type: string, maxLength: 2000, description: 'Required for reject (at least 3 characters)' } }
    SignOff:
      type: object
      additionalProperties: false
      required: [expected_version, attestation]
      properties: { expected_version: { type: integer, minimum: 1 }, attestation: { const: true }, note: { type: string, maxLength: 2000 } }
    Health:
      type: object
      properties:
        status: { type: string }
        module: { const: OHN-52 }
        engine: { type: object, properties: { default: { const: tesseract-local }, local_ocr_data: { enum: [present, missing] }, ai: { enum: [disabled, enabled, refused_incomplete_configuration] }, ai_model: { type: [string, 'null'] }, worker: { enum: [running, stopped] }, adapter: { enum: [none, wired], description: 'Java only: none while no OCR adapter is wired (B820); local_ocr_data is then missing' }, worker_stats: { type: object } } }
        dependencies: { type: object, additionalProperties: { enum: [live, unconfigured] } }
        writes_enabled: { type: boolean, description: False when the operator kill switch is on (every write 503 not_configured) }
        export_signing_configured: { type: boolean }
        auth_configured: { type: boolean }
        synthetic_auth: { type: boolean, description: Always false in the Java service }
