{
  "openapi": "3.0.3",
  "info": {
    "title": "Tavio EDI Test Harness \u2014 Public API",
    "version": "1.3.0",
    "description": "# Tavio EDI Test Harness\n\nA hosted AS2-style HTTP endpoint that accepts inbound EDI documents (X12, EDIFACT, or XML payloads) and synchronously returns a parsed result, validation report, and \u2014 for X12 with ack requested \u2014 a generated functional or implementation acknowledgment.\n\nThis API is designed for **developers building or testing EDI integrations** without needing to stand up a full AS2 server, certificates, or a trading partner agreement. It is a sandbox: there is no message encryption, no signing, and no MDN routing \u2014 the acknowledgment is returned in-band in the HTTP response body.\n\n## Quick start\n\n1. Register a partner instance through the harness UI at https://tps.taviotools.com (or reuse one you already created). You'll get back a 15-character `partner_id`.\n2. POST a raw X12 interchange to `/as2-receiver` with `AS2-From` set to your sender ID and `AS2-To` set to your harness `partner_id`.\n3. Read the JSON response. If you set `ISA14 = 1` (ack requested) and the parse succeeded, the body will contain an `acknowledgment.content` field with the X12 997 (or 999 if validation errors were found).\n4. Inspect the persisted transactions in the harness UI under **Transactions**.\n\n## Concepts\n\n- **Partner Instance** \u2014 A virtual receiver. Each instance has a unique `partner_id` (the value you put in ISA08 / `AS2-To`). Instances are auto-created on first use if `AS2-To` doesn't match an existing one.\n- **Trading Partner** \u2014 A sender (`AS2-From` / ISA06) recorded under an instance. Auto-created on first contact.\n- **Sequence Tracking** \u2014 The harness tracks the last seen ISA13 control number per (instance, trading partner, direction). Reusing or going backward triggers a duplicate-sequence validation error.\n- **Auto-Acknowledgment** \u2014 Only fires for X12 with `ISA14 = 1`. Successful parse \u2192 997. Validation errors \u2192 999 with IK3/IK4 detail.\n- **Retention** \u2014 Instances inactive for 30 days are automatically deleted along with all their transactions. Don't use this harness as a system of record.\n\n## Authentication\n\nNone. The `/as2-receiver` endpoint is intentionally unauthenticated so that any AS2 client can POST to it. Tenancy is enforced by the `AS2-To` header (or ISA08 if the header is absent), which routes the message to a specific partner instance.\n\nDo not send production data \u2014 anyone who knows a `partner_id` can post to it and read the resulting transactions through the harness UI for that instance.\n\n## Rate limits\n\nNo hard rate limits are advertised, but the endpoint is shared infrastructure. Burst-friendly use (test runs, CI suites) is fine; sustained high-volume traffic is not the intended use case.\n\n## Errors\n\n| HTTP | Meaning |\n|------|---------|\n| 200  | Parsed and stored. The body's `validationErrors` field may still be populated for non-fatal issues. |\n| 400  | Empty request body. |\n| 405  | Wrong HTTP method (only POST is accepted). |\n| 422  | Parsed and stored, but one or more `error`-level validation failures were detected. A 999 acknowledgment is included if ack was requested. |\n| 500  | Internal failure (database, parser exception, etc.). The response body will contain `{ error: string }`. |\n\n\n## S/MIME security (optional)\nInbound messages may be plain, signed, encrypted, or signed then encrypted:\n- **Encrypted**: `Content-Type: application/pkcs7-mime; smime-type=enveloped-data`, with a binary or base64 CMS body encrypted to the harness certificate (download it from the Endpoint Info page). AES-128/256-CBC and 3DES are supported.\n- **Signed**: `Content-Type: multipart/signed; protocol=\"application/pkcs7-signature\"; micalg=sha-256`, with a detached PKCS#7 signature. The harness verifies it against the partner certificate on file, or the embedded certificate if none is on file (marked untrusted).\n- **Signed MDN**: send `Disposition-Notification-Options: signed-receipt-protocol=optional, pkcs7-signature; signed-receipt-micalg=optional, sha-256`. The response becomes an RFC 4130 `multipart/signed` MDN (`multipart/report`) carrying `Received-Content-MIC`. Without this header, the JSON response is returned and includes `mdn.mic`.\n- Decryption failures return HTTP 400 with `status: processed/error: decryption-failed`.",
    "contact": {
      "name": "Tavio Training",
      "email": "training@tavio.io",
      "url": "https://tps.taviotools.com"
    },
    "license": {
      "name": "Proprietary \u2014 Test Harness",
      "url": "https://tps.taviotools.com"
    }
  },
  "servers": [
    {
      "url": "https://tps.taviotools.com/api",
      "description": "Production (branded)"
    }
  ],
  "tags": [
    {
      "name": "AS2",
      "description": "AS2-style HTTP receiver for inbound EDI documents."
    },
    {
      "name": "REST",
      "description": "JSON REST intake for ERPs that don't speak AS2."
    }
  ],
  "paths": {
    "/as2": {
      "post": {
        "tags": [
          "AS2"
        ],
        "summary": "Submit an inbound EDI document",
        "operationId": "postAs2Receiver",
        "description": "Accepts a raw EDI payload (X12, EDIFACT, or XML) over HTTP using AS2-style headers.\n\n**X12 path (most common):**\n1. Detects element separator from ISA character 4 and segment terminator from the position immediately after ISA16.\n2. Parses the ISA envelope, validates qualifiers / control numbers / usage indicator.\n3. Walks every functional group (GS\u2026GE) and every transaction set (ST\u2026SE) in the interchange.\n4. Resolves the receiver (`AS2-To` header, falling back to ISA08) to a partner instance, creating one if needed.\n5. Resolves the sender (`AS2-From`, falling back to ISA06) to a trading partner under that instance.\n6. Checks ISA13 against the per-partner sequence tracker \u2014 duplicates produce a validation error.\n7. Persists the inbound transaction.\n8. If `ISA14 = 1` and the parse produced at least one transaction set: generates and persists an outbound 997 (clean) or 999 (with IK3/IK4 details for each error).\n9. Returns a JSON envelope describing the outcome and embedding the raw X12 acknowledgment.\n\n**EDIFACT and XML payloads** are detected, stored, and reported back, but no acknowledgment is generated.\n\n**Encoding:** the request body is read as UTF-8 text. Send the X12 interchange as the raw HTTP body \u2014 do not base64-encode and do not wrap in JSON.\n\n**Idempotency:** there is none. Re-POSTing the same interchange will create a second stored transaction (and trigger a duplicate-control-number validation error if ISA13 has not advanced).\n\n**Supported inbound transaction sets** include 850 Purchase Order, 860 PO Change, 204 Load Tender and 820 Payment Order / Remittance Advice (GS01 = `RA`). An 820 is validated and acknowledged (997/999) exactly like any other X12 set.",
        "parameters": [
          {
            "name": "AS2-From",
            "in": "header",
            "required": false,
            "schema": {
              "type": "string",
              "maxLength": 128
            },
            "example": "ACME-CORP",
            "description": "Sending partner's AS2 identifier. Recorded as the trading partner under the receiving instance. If omitted, the harness falls back to ISA06 from the X12 envelope. Required in practice for non-X12 payloads."
          },
          {
            "name": "AS2-To",
            "in": "header",
            "required": false,
            "schema": {
              "type": "string",
              "maxLength": 15
            },
            "example": "TAV-A1B2C3D4E5F6",
            "description": "Receiving partner ID \u2014 the 15-character `partner_id` of a harness instance. Routes the message into that instance's transaction log. If the value doesn't match an existing instance, a new instance is auto-created with `display_name = \"Auto: <partner_id>\"`. If omitted, the harness falls back to ISA08."
          },
          {
            "name": "Message-ID",
            "in": "header",
            "required": false,
            "schema": {
              "type": "string"
            },
            "example": "<20260424T120000-abc123@example.com>",
            "description": "Unique AS2 message identifier (RFC 822 angle-bracketed form by convention). If provided, the harness echoes it back in the `Original-Message-ID` response header to support correlation."
          },
          {
            "name": "Content-Disposition",
            "in": "header",
            "required": false,
            "schema": {
              "type": "string"
            },
            "example": "attachment; filename=edi850.x12",
            "description": "Optional \u2014 preserved in logs for debugging. Not used for routing."
          },
          {
            "name": "Content-Type",
            "in": "header",
            "required": false,
            "schema": {
              "type": "string",
              "enum": [
                "application/edi-x12",
                "application/x12",
                "application/edifact",
                "application/xml",
                "text/xml",
                "application/octet-stream",
                "text/plain"
              ]
            },
            "description": "Hints the EDI type when the body's first segment is ambiguous. Detection precedence: (1) body starts with `ISA` \u2192 X12, (2) body starts with `UNA`/`UNB` \u2192 EDIFACT, (3) body starts with `<` \u2192 XML, (4) Content-Type fallback. If nothing matches, `ediType` is reported as `UNKNOWN`."
          }
        ],
        "requestBody": {
          "required": true,
          "description": "The raw EDI interchange. Send as plain text in the request body \u2014 do not JSON-wrap.",
          "content": {
            "application/edi-x12": {
              "schema": {
                "type": "string",
                "format": "binary"
              },
              "examples": {
                "minimal850": {
                  "summary": "Minimal X12 850 Purchase Order with ack requested",
                  "value": "ISA*00*          *00*          *ZZ*ACME-CORP      *ZZ*TAV-A1B2C3D4E5F6*260424*1200*^*00501*000000001*1*T*>~GS*PO*ACMEAPP*TAVAPP*20260424*1200*1*X*005010~ST*850*0001~BEG*00*NE*PO-12345**20260424~PO1*1*10*EA*25.00*BP*WIDGET-001~PID*F****Standard Widget~CTT*1~SE*7*0001~GE*1*1~IEA*1*000000001~"
                },
                "multiTransaction850": {
                  "summary": "Two ST groups in one interchange \u2014 produces one 997 covering both",
                  "value": "ISA*00*          *00*          *ZZ*ACME-CORP      *ZZ*TAV-A1B2C3D4E5F6*260424*1200*^*00501*000000002*1*T*>~GS*PO*ACMEAPP*TAVAPP*20260424*1200*2*X*005010~ST*850*0001~BEG*00*NE*PO-12345**20260424~PO1*1*10*EA*25.00*BP*WIDGET-001~CTT*1~SE*5*0001~ST*850*0002~BEG*00*NE*PO-12346**20260424~PO1*1*5*EA*50.00*BP*GADGET-002~CTT*1~SE*5*0002~GE*2*1~IEA*1*000000002~"
                }
              }
            },
            "application/edifact": {
              "schema": {
                "type": "string",
                "format": "binary"
              },
              "example": "UNB+UNOA:1+SENDER+RECEIVER+260424:1200+1++ORDERS'UNH+1+ORDERS:D:96A:UN'BGM+220+PO-12345+9'UNT+3+1'UNZ+1+1'"
            },
            "application/xml": {
              "schema": {
                "type": "string",
                "format": "binary"
              },
              "example": "<?xml version=\"1.0\"?><PurchaseOrder><Number>PO-12345</Number></PurchaseOrder>"
            },
            "application/octet-stream": {
              "schema": {
                "type": "string",
                "format": "binary"
              },
              "description": "Use when your client cannot set a more specific Content-Type. Detection then falls back to body-prefix sniffing."
            },
            "text/plain": {
              "schema": {
                "type": "string"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Document received, parsed, and stored. The acknowledgment (if any) is in `acknowledgment.content`.",
            "headers": {
              "AS2-From": {
                "schema": {
                  "type": "string"
                },
                "description": "Receiver ID \u2014 mirror of the request's `AS2-To`."
              },
              "AS2-To": {
                "schema": {
                  "type": "string"
                },
                "description": "Sender ID \u2014 mirror of the request's `AS2-From`."
              },
              "Original-Message-ID": {
                "schema": {
                  "type": "string"
                },
                "description": "Echo of the request's `Message-ID`, when supplied."
              }
            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReceiverResponse"
                },
                "examples": {
                  "cleanWithAck": {
                    "summary": "Clean 850 with auto-997",
                    "value": {
                      "status": "processed",
                      "transactionId": "550e8400-e29b-41d4-a716-446655440000",
                      "documentType": "850",
                      "ediType": "X12",
                      "acknowledgment": {
                        "type": "997",
                        "content": "ISA*00*          *00*          *ZZ*TAV-A1B2C3D4E5F6*ZZ*ACME-CORP      *260424*1200*^*00501*000000123*1*T*>~GS*FA*TAV-A1B2C3D4E5F6*ACME-CORP*20260424*1200*456789*X*005010X231A1~ST*997*0001~AK1*PO*1*005010~AK2*850*0001~AK5*A~AK9*A*1*1*1~SE*6*0001~GE*1*456789~IEA*1*000000123~"
                      }
                    }
                  },
                  "noAck": {
                    "summary": "Clean 850 with ISA14=0 (no ack requested)",
                    "value": {
                      "status": "processed",
                      "transactionId": "550e8400-e29b-41d4-a716-446655440001",
                      "documentType": "850",
                      "ediType": "X12"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Empty request body.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "Empty body"
                }
              }
            }
          },
          "405": {
            "description": "Method not allowed \u2014 only POST is accepted.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "Method not allowed"
                }
              }
            }
          },
          "422": {
            "description": "Parsed and stored, but contains validation errors. If ack was requested, `acknowledgment.type` will be `999` with full IK3/IK4 detail.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ReceiverResponse"
                },
                "example": {
                  "status": "processed/error",
                  "transactionId": "550e8400-e29b-41d4-a716-446655440002",
                  "documentType": "850",
                  "ediType": "X12",
                  "validationErrors": [
                    {
                      "level": "error",
                      "segment": "ISA",
                      "element": "ISA13",
                      "code": "025",
                      "message": "Duplicate or out-of-sequence ISA control number. Expected > 1, got 1"
                    }
                  ],
                  "acknowledgment": {
                    "type": "997",
                    "content": "ISA*00*..."
                  }
                }
              }
            }
          },
          "500": {
            "description": "Internal error \u2014 database failure, parser exception, or missing receiver routing.",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      },
      "options": {
        "tags": [
          "AS2"
        ],
        "summary": "CORS preflight",
        "description": "Returns CORS headers allowing browser-originated POSTs from any origin. Allowed headers: `authorization, x-client-info, apikey, content-type, as2-from, as2-to, message-id, content-disposition`.",
        "responses": {
          "204": {
            "description": "Preflight OK."
          }
        }
      },
      "servers": [
        {
          "url": "https://tps.taviotools.com/api",
          "description": "Primary"
        },
        {
          "url": "https://aucwoqldeyhqqupdoyzg.supabase.co/functions/v1",
          "description": "Fallback \u2014 use path /as2-receiver"
        }
      ]
    },
    "/purchase_order": {
      "post": {
        "tags": [
          "REST"
        ],
        "summary": "Create a purchase order",
        "operationId": "createPurchaseOrder",
        "description": "Creates a purchase order in the Logistics Services Provider ERP as a new inbound 850 request (tagged REST). Totals and line totals are computed server-side.",
        "security": [
          {
            "InstanceApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/PurchaseOrderInput"
              },
              "example": {
                "po_number": "PO-1001",
                "order_date": "2026-05-21",
                "supplier": {
                  "name": "Acme Corp"
                },
                "buyer": {
                  "name": "Tavio"
                },
                "shipping_address": "100 Receiving Dock, Boston, MA",
                "shipping": 15,
                "items": [
                  {
                    "sku": "WIDGET-1",
                    "description": "Blue Widget",
                    "quantity": 10,
                    "unit_price": 9.99,
                    "unit": "ea",
                    "tax_rate": 8.5
                  }
                ]
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Purchase order created",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "purchase_order": {
                      "$ref": "#/components/schemas/PurchaseOrder"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Validation error or duplicate po_number",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid X-API-Key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          },
          "405": {
            "description": "Method not allowed",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/tms/tender_response": {
      "post": {
        "tags": [
          "TMS"
        ],
        "summary": "990 Tender response (JSON)",
        "servers": [
          {
            "url": "https://tps.taviotools.com",
            "description": "Branded site root (TMS endpoints)"
          }
        ],
        "security": [
          {
            "InstanceApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "action"
                ],
                "properties": {
                  "load_id": {
                    "type": "string",
                    "example": "LD-1A2B3C4D"
                  },
                  "shipment_id": {
                    "type": "string"
                  },
                  "po_number": {
                    "type": "string"
                  },
                  "action": {
                    "type": "string",
                    "enum": [
                      "accept",
                      "decline"
                    ]
                  },
                  "carrier_scac": {
                    "type": "string"
                  },
                  "reason": {
                    "type": "string"
                  },
                  "responded_at": {
                    "type": "string"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Accepted (214)"
          },
          "201": {
            "description": "Accepted"
          },
          "400": {
            "description": "Invalid body"
          },
          "401": {
            "description": "Missing/invalid X-API-Key"
          },
          "404": {
            "description": "Unknown load"
          },
          "409": {
            "description": "Out-of-order update"
          }
        }
      }
    },
    "/tms/shipment_status": {
      "post": {
        "tags": [
          "TMS"
        ],
        "summary": "214 Shipment status (JSON)",
        "servers": [
          {
            "url": "https://tps.taviotools.com",
            "description": "Branded site root (TMS endpoints)"
          }
        ],
        "security": [
          {
            "InstanceApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "status_code"
                ],
                "properties": {
                  "load_id": {
                    "type": "string",
                    "example": "LD-1A2B3C4D"
                  },
                  "shipment_id": {
                    "type": "string"
                  },
                  "po_number": {
                    "type": "string"
                  },
                  "status_code": {
                    "type": "string",
                    "example": "X3",
                    "description": "X3 picked up, AF departed, X6 en route, X1 arrived, D1 delivered"
                  },
                  "status_label": {
                    "type": "string"
                  },
                  "location": {
                    "type": "object",
                    "properties": {
                      "city": {
                        "type": "string"
                      },
                      "state": {
                        "type": "string"
                      }
                    }
                  },
                  "occurred_at": {
                    "type": "string"
                  },
                  "pro_number": {
                    "type": "string"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Accepted (214)"
          },
          "201": {
            "description": "Accepted"
          },
          "400": {
            "description": "Invalid body"
          },
          "401": {
            "description": "Missing/invalid X-API-Key"
          },
          "404": {
            "description": "Unknown load"
          },
          "409": {
            "description": "Out-of-order update"
          }
        }
      }
    },
    "/tms/freight_invoice": {
      "post": {
        "tags": [
          "TMS"
        ],
        "summary": "210 Freight invoice (JSON)",
        "servers": [
          {
            "url": "https://tps.taviotools.com",
            "description": "Branded site root (TMS endpoints)"
          }
        ],
        "security": [
          {
            "InstanceApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "invoice_number"
                ],
                "properties": {
                  "load_id": {
                    "type": "string",
                    "example": "LD-1A2B3C4D"
                  },
                  "shipment_id": {
                    "type": "string"
                  },
                  "po_number": {
                    "type": "string"
                  },
                  "invoice_number": {
                    "type": "string"
                  },
                  "invoice_date": {
                    "type": "string"
                  },
                  "pro_number": {
                    "type": "string"
                  },
                  "charges": {
                    "type": "array",
                    "items": {
                      "type": "object",
                      "properties": {
                        "description": {
                          "type": "string"
                        },
                        "amount": {
                          "type": "number"
                        }
                      }
                    }
                  },
                  "total_amount": {
                    "type": "number"
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Accepted (214)"
          },
          "201": {
            "description": "Accepted"
          },
          "400": {
            "description": "Invalid body"
          },
          "401": {
            "description": "Missing/invalid X-API-Key"
          },
          "404": {
            "description": "Unknown load"
          },
          "409": {
            "description": "Out-of-order update"
          }
        }
      }
    },
    "/remittance": {
      "post": {
        "tags": [
          "REST"
        ],
        "summary": "Submit a remittance advice (820)",
        "operationId": "createRemittance",
        "description": "JSON equivalent of an X12 820 Payment Order / Remittance Advice. Stored in the Logistics Services Provider ERP as an inbound 820 (tagged REST) with a synthesized X12 body. Unknown payers are added as trading partners, never rejected. When the remittance references a known invoice or PO, the matching order is marked as payment-pending in the ERP until settlement is confirmed.",
        "security": [
          {
            "InstanceApiKey": []
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/RemittanceInput"
              },
              "example": {
                "remittance_number": "RA-1001",
                "payment_date": "2026-10-12",
                "payment_method": "ACH",
                "trace_number": "TRC-000555",
                "payer": {
                  "name": "Cedar Ridge Homes"
                },
                "payee": {
                  "name": "Tavio LSP"
                },
                "invoices": [
                  {
                    "invoice_number": "INV-10045",
                    "po_number": "PO-1001",
                    "invoice_amount": 1550.0,
                    "discount_amount": 29.5,
                    "amount_paid": 1520.5
                  }
                ]
              }
            }
          }
        },
        "responses": {
          "201": {
            "description": "Remittance recorded",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "success": {
                      "type": "boolean"
                    },
                    "remittance": {
                      "$ref": "#/components/schemas/Remittance"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "description": "Invalid JSON, schema violation, total mismatch, or duplicate remittance_number",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "Remittance RA-1001 already exists"
                }
              }
            }
          },
          "401": {
            "description": "Missing or invalid X-API-Key",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "Invalid X-API-Key"
                }
              }
            }
          },
          "405": {
            "description": "Only POST is accepted",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                },
                "example": {
                  "error": "Method not allowed"
                }
              }
            }
          }
        }
      },
      "options": {
        "tags": [
          "REST"
        ],
        "summary": "CORS preflight",
        "responses": {
          "204": {
            "description": "Preflight OK."
          }
        }
      }
    },
    "/customer-erp/as2": {
      "post": {
        "tags": [
          "Customer ERP"
        ],
        "summary": "Customer ERP AS2 receiver (855/856/810)",
        "description": "X12 over AS2 into the Customer ERP. AS2-To must be the ERP AS2 ID (ERP + partner ID without dashes). The document is checked (ISA envelope, receiver, increasing ISA13), matched to an ERP order by PO number, and answered with an MDN carrying a 997. The /{doc} variants reject documents whose ST01 doesn't match.",
        "parameters": [
          {
            "name": "AS2-To",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "AS2-From",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/edi-x12": {
              "schema": {
                "type": "string"
              }
            },
            "application/pkcs7-mime": {
              "schema": {
                "type": "string",
                "format": "binary"
              }
            },
            "multipart/signed": {
              "schema": {
                "type": "string"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "MDN (JSON, or signed multipart when requested)"
          },
          "404": {
            "description": "Unknown ERP AS2 ID or document path"
          }
        }
      }
    },
    "/customer-erp/as2/{doc}": {
      "post": {
        "tags": [
          "Customer ERP"
        ],
        "summary": "Customer ERP AS2 receiver (855/856/810)",
        "description": "X12 over AS2 into the Customer ERP. AS2-To must be the ERP AS2 ID (ERP + partner ID without dashes). The document is checked (ISA envelope, receiver, increasing ISA13), matched to an ERP order by PO number, and answered with an MDN carrying a 997. The /{doc} variants reject documents whose ST01 doesn't match.",
        "parameters": [
          {
            "name": "AS2-To",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "AS2-From",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "name": "doc",
            "in": "path",
            "required": true,
            "schema": {
              "type": "string",
              "enum": [
                "855",
                "856",
                "810"
              ]
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/edi-x12": {
              "schema": {
                "type": "string"
              }
            },
            "application/pkcs7-mime": {
              "schema": {
                "type": "string",
                "format": "binary"
              }
            },
            "multipart/signed": {
              "schema": {
                "type": "string"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "MDN (JSON, or signed multipart when requested)"
          },
          "404": {
            "description": "Unknown ERP AS2 ID or document path"
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "ReceiverResponse": {
        "type": "object",
        "required": [
          "status",
          "transactionId",
          "documentType",
          "ediType"
        ],
        "properties": {
          "status": {
            "type": "string",
            "enum": [
              "processed",
              "processed/error"
            ],
            "description": "MDN-style outcome. `processed` = no error-level validation failures. `processed/error` = at least one error-level finding."
          },
          "transactionId": {
            "type": "string",
            "format": "uuid",
            "description": "Primary key of the persisted inbound transaction. Use this to look it up in the harness UI."
          },
          "documentType": {
            "type": "string",
            "description": "Resolved document type. For X12 this is the ST01 (e.g. `850`, `855`, `810`, `856`, `204`, `860`). For non-X12, one of `EDIFACT`, `XML`, or `UNKNOWN`.",
            "examples": [
              "850",
              "855",
              "810",
              "856",
              "997",
              "999",
              "EDIFACT",
              "XML",
              "UNKNOWN"
            ]
          },
          "ediType": {
            "type": "string",
            "enum": [
              "X12",
              "EDIFACT",
              "XML",
              "UNKNOWN"
            ]
          },
          "validationErrors": {
            "type": "array",
            "description": "Present only when at least one validation finding was produced. Both `error` and `warning` levels are included.",
            "items": {
              "$ref": "#/components/schemas/ValidationError"
            }
          },
          "acknowledgment": {
            "type": "object",
            "description": "Present only when ISA14=1 and at least one ST was parsed.",
            "required": [
              "type",
              "content"
            ],
            "properties": {
              "type": {
                "type": "string",
                "enum": [
                  "997",
                  "999"
                ],
                "description": "`997` for clean interchanges, `999` when validation errors were detected."
              },
              "content": {
                "type": "string",
                "description": "The full raw X12 acknowledgment, ready to round-trip back to the sender."
              }
            }
          }
        }
      },
      "ValidationError": {
        "type": "object",
        "required": [
          "level",
          "segment",
          "code",
          "message"
        ],
        "properties": {
          "level": {
            "type": "string",
            "enum": [
              "error",
              "warning"
            ],
            "description": "`error` blocks acknowledgment as 997 (forces 999 instead). `warning` is informational."
          },
          "segment": {
            "type": "string",
            "description": "X12 segment that triggered the finding (e.g. `ISA`, `GS`, `ST`).",
            "example": "ISA"
          },
          "element": {
            "type": "string",
            "description": "Specific element identifier within the segment (e.g. `ISA13`). Omitted for segment-level findings.",
            "example": "ISA13"
          },
          "code": {
            "type": "string",
            "description": "Internal error code. Stable but not standardized across X12 implementations.",
            "example": "025"
          },
          "message": {
            "type": "string",
            "description": "Human-readable explanation."
          }
        }
      },
      "Error": {
        "type": "object",
        "required": [
          "error"
        ],
        "properties": {
          "error": {
            "type": "string"
          }
        }
      },
      "PurchaseOrderItemInput": {
        "type": "object",
        "required": [
          "description",
          "quantity",
          "unit_price"
        ],
        "properties": {
          "line_number": {
            "type": "integer"
          },
          "sku": {
            "type": "string",
            "nullable": true
          },
          "description": {
            "type": "string"
          },
          "quantity": {
            "type": "number"
          },
          "unit_price": {
            "type": "number"
          },
          "unit": {
            "type": "string",
            "nullable": true
          },
          "tax_rate": {
            "type": "number",
            "description": "Percent, e.g. 8.5"
          }
        }
      },
      "PurchaseOrderInput": {
        "type": "object",
        "required": [
          "supplier",
          "items"
        ],
        "properties": {
          "po_number": {
            "type": "string",
            "description": "Optional; auto-generated if omitted. Must be unique per instance."
          },
          "status": {
            "type": "string",
            "default": "pending"
          },
          "order_date": {
            "type": "string",
            "format": "date"
          },
          "expected_delivery_date": {
            "type": "string",
            "format": "date",
            "nullable": true
          },
          "supplier": {
            "type": "object",
            "required": [
              "name"
            ],
            "properties": {
              "name": {
                "type": "string"
              },
              "email": {
                "type": "string",
                "format": "email"
              },
              "phone": {
                "type": "string"
              },
              "address": {
                "type": "string"
              }
            }
          },
          "buyer": {
            "type": "object",
            "properties": {
              "name": {
                "type": "string"
              },
              "email": {
                "type": "string",
                "format": "email"
              }
            }
          },
          "shipping_address": {
            "type": "string"
          },
          "billing_address": {
            "type": "string"
          },
          "currency": {
            "type": "string",
            "default": "USD"
          },
          "shipping": {
            "type": "number",
            "default": 0
          },
          "payment_terms": {
            "type": "string"
          },
          "notes": {
            "type": "string"
          },
          "items": {
            "type": "array",
            "minItems": 1,
            "items": {
              "$ref": "#/components/schemas/PurchaseOrderItemInput"
            }
          }
        }
      },
      "PurchaseOrder": {
        "type": "object",
        "properties": {
          "po_number": {
            "type": "string"
          },
          "status": {
            "type": "string"
          },
          "supplier_name": {
            "type": "string"
          },
          "currency": {
            "type": "string"
          },
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "order_date": {
            "type": "string",
            "format": "date"
          },
          "expected_delivery_date": {
            "type": "string",
            "format": "date",
            "nullable": true
          },
          "supplier_email": {
            "type": "string",
            "nullable": true
          },
          "supplier_phone": {
            "type": "string",
            "nullable": true
          },
          "supplier_address": {
            "type": "string",
            "nullable": true
          },
          "buyer_name": {
            "type": "string",
            "nullable": true
          },
          "buyer_email": {
            "type": "string",
            "nullable": true
          },
          "shipping_address": {
            "type": "string",
            "nullable": true
          },
          "billing_address": {
            "type": "string",
            "nullable": true
          },
          "payment_terms": {
            "type": "string",
            "nullable": true
          },
          "notes": {
            "type": "string",
            "nullable": true
          },
          "subtotal": {
            "type": "number"
          },
          "tax": {
            "type": "number"
          },
          "shipping": {
            "type": "number"
          },
          "total": {
            "type": "number"
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          },
          "updated_at": {
            "type": "string",
            "format": "date-time"
          },
          "items": {
            "type": "array",
            "items": {
              "allOf": [
                {
                  "$ref": "#/components/schemas/PurchaseOrderItemInput"
                },
                {
                  "type": "object",
                  "properties": {
                    "line_total": {
                      "type": "number"
                    }
                  }
                }
              ]
            }
          }
        }
      },
      "RemittanceInvoice": {
        "type": "object",
        "required": [
          "invoice_number",
          "amount_paid"
        ],
        "properties": {
          "invoice_number": {
            "type": "string",
            "maxLength": 30,
            "example": "INV-10045"
          },
          "po_number": {
            "type": "string",
            "nullable": true,
            "maxLength": 22,
            "example": "PO-1001"
          },
          "invoice_amount": {
            "type": "number",
            "nullable": true,
            "example": 1550.0
          },
          "discount_amount": {
            "type": "number",
            "nullable": true,
            "example": 29.5
          },
          "amount_paid": {
            "type": "number",
            "example": 1520.5
          }
        }
      },
      "RemittanceInput": {
        "type": "object",
        "required": [
          "payer",
          "invoices"
        ],
        "properties": {
          "remittance_number": {
            "type": "string",
            "maxLength": 30,
            "description": "Unique per instance. Auto-generated as RA-XXXXXXXX if omitted.",
            "example": "RA-1001"
          },
          "payment_date": {
            "type": "string",
            "format": "date",
            "description": "Defaults to today."
          },
          "payment_method": {
            "type": "string",
            "enum": [
              "ACH",
              "CHK",
              "WIRE"
            ],
            "default": "ACH",
            "description": "Maps to BPR04 (ACH, CHK, FWT)."
          },
          "trace_number": {
            "type": "string",
            "maxLength": 30,
            "description": "Maps to TRN02."
          },
          "currency": {
            "type": "string",
            "minLength": 3,
            "maxLength": 3,
            "default": "USD"
          },
          "total_amount": {
            "type": "number",
            "description": "Optional. Computed from invoices[].amount_paid if omitted; if supplied it must match that sum."
          },
          "payer": {
            "type": "object",
            "required": [
              "name"
            ],
            "properties": {
              "name": {
                "type": "string",
                "maxLength": 200
              }
            }
          },
          "payee": {
            "type": "object",
            "properties": {
              "name": {
                "type": "string",
                "maxLength": 200
              }
            }
          },
          "notes": {
            "type": "string",
            "maxLength": 2000
          },
          "invoices": {
            "type": "array",
            "minItems": 1,
            "maxItems": 500,
            "items": {
              "$ref": "#/components/schemas/RemittanceInvoice"
            }
          }
        }
      },
      "Remittance": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "format": "uuid"
          },
          "remittance_number": {
            "type": "string"
          },
          "payment_date": {
            "type": "string",
            "format": "date"
          },
          "payment_method": {
            "type": "string"
          },
          "trace_number": {
            "type": "string",
            "nullable": true
          },
          "currency": {
            "type": "string"
          },
          "total_amount": {
            "type": "number"
          },
          "payer_name": {
            "type": "string"
          },
          "payee_name": {
            "type": "string",
            "nullable": true
          },
          "notes": {
            "type": "string",
            "nullable": true
          },
          "invoices": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/RemittanceInvoice"
            }
          },
          "created_at": {
            "type": "string",
            "format": "date-time"
          }
        }
      }
    },
    "securitySchemes": {
      "InstanceApiKey": {
        "type": "apiKey",
        "in": "header",
        "name": "X-API-Key",
        "description": "Your instance (partner) ID."
      }
    }
  }
}