---
# === IDENTITY ===
id: business/erp-integration/edi-integration-erp/2026
canonical_question: "How do you integrate ERP with EDI translators like SPS Commerce or TrueCommerce?"
aliases:
  - "How to connect ERP to EDI VAN or AS2 for trading partner compliance?"
  - "What is the best EDI integration approach for ERP — VAN, AS2, or API?"
  - "How do EDI document types 850, 855, 856, 810, 997 map to ERP transactions?"
  - "What are the differences between SPS Commerce, TrueCommerce, Cleo, and OpenText for EDI-ERP integration?"
entity_type: erp_integration
domain: business > erp-integration > EDI Integration with ERP
region: global
jurisdiction: global
temporal_scope: 2024-2026

# === SYSTEM PROFILE ===
# Integration playbook — covers multiple ERP systems and EDI translators/VANs
systems:
  - name: "SPS Commerce Fulfillment"
    vendor: "SPS Commerce"
    version: "2026 (cloud)"
    edition: "Full-Service EDI"
    deployment: "cloud"
    api_surface: "VAN/API/Embedded EDI"
  - name: "TrueCommerce EDI"
    vendor: "TrueCommerce"
    version: "2026 (cloud)"
    edition: "Foundry Platform"
    deployment: "cloud"
    api_surface: "VAN/SFTP/API"
  - name: "Cleo Integration Cloud"
    vendor: "Cleo"
    version: "2026 (cloud)"
    edition: "CIC"
    deployment: "cloud/hybrid"
    api_surface: "AS2/API/SFTP/VAN"
  - name: "OpenText Trading Grid"
    vendor: "OpenText"
    version: "2025"
    edition: "B2B Integration Enterprise"
    deployment: "cloud/on-premise"
    api_surface: "VAN/AS2/MFT/API"

# === VERIFICATION ===
last_verified: 2026-03-03
confidence: 0.86
version: 1.0
first_published: 2026-03-03

# === TEMPORAL VALIDITY ===
temporal_validity:
  status: evolving
  last_breaking_change: "2025 — SPS Commerce MAX AI features added; Cleo AI-powered mapping GA"
  next_review: 2026-08-30
  change_sensitivity: medium

# === CONSTRAINTS ===
constraints:
  - "VAN transaction fees are volume-based — per-kilo-character pricing can exceed $0.10/transaction at low volumes"
  - "AS2 requires digital certificate management — certificates expire (typically 1-2 years) and must be renewed with every trading partner"
  - "X12 is dominant in North America; EDIFACT in Europe/Asia — dual-standard support adds mapping complexity"
  - "EDI 997 functional acknowledgments are mandatory for most retail trading partners — missing 997s trigger compliance violations"
  - "Web EDI portals do not integrate with ERP automatically — manual data re-entry is required unless middleware bridges the gap"
  - "Trading partner maps are custom per partner — onboarding a new partner requires testing and certification of every document type"

# === SKIP CONDITIONS ===
skip_this_unit_if:
  - condition: "User needs SAP IDoc-specific EDI configuration"
    use_instead: "business/erp-integration/sap-idoc-edi-integration/2026"
  - condition: "User needs general iPaaS comparison without EDI focus"
    use_instead: "business/erp-integration/ipaas-platform-comparison/2026"
  - condition: "User needs order-to-cash process integration without EDI"
    use_instead: "business/erp-integration/order-to-cash-integration/2026"

# === AGENT HINTS ===
inputs_needed:
  - key: integration_pattern
    question: "What EDI integration approach do you need?"
    type: choice
    options:
      - "VAN-mediated (managed network, broadest partner coverage)"
      - "Direct AS2 (point-to-point, high-volume partners)"
      - "API-based (real-time, modern trading partners)"
      - "Web EDI portal (low-volume suppliers, browser-based)"
  - key: data_volume
    question: "What's your daily EDI transaction volume?"
    type: choice
    options:
      - "< 100 transactions/day"
      - "100-10,000 transactions/day"
      - "> 10,000 transactions/day"
  - key: direction
    question: "What's the primary data flow?"
    type: choice
    options:
      - "inbound (receiving POs from retailers/buyers)"
      - "outbound (sending invoices, ASNs to buyers)"
      - "bidirectional (full order-to-cash cycle)"

# === DISTRIBUTION ===
canonical_source: "https://knowledgelib.io/business/erp-integration/edi-integration-erp/2026"
suggested_citation: "Source: knowledgelib.io — AI Knowledge Library (verified 2026-03-03)"

# === RELATED UNITS ===
related_kos:
  depends_on:
    - id: "business/erp-integration/order-to-cash-integration/2026"
      label: "Order-to-Cash Integration — the business process EDI automates"
  related_to:
    - id: "business/erp-integration/sap-idoc-edi-integration/2026"
      label: "SAP IDoc EDI Integration — SAP-specific IDoc/EDI configuration"
    - id: "business/erp-integration/procure-to-pay-integration/2026"
      label: "Procure-to-Pay Integration — the buying side of EDI"
  solves:
    - id: "business/erp-integration/salesforce-netsuite-integration/2026"
      label: "Salesforce-NetSuite Integration — may use EDI for fulfillment"
  alternative_to:
    - id: "business/erp-integration/ipaas-platform-comparison/2026"
      label: "iPaaS Platform Comparison — API-first alternative to EDI"
  often_confused_with:
    - id: "business/erp-integration/sap-idoc-edi-integration/2026"
      label: "SAP IDoc EDI — IDoc is SAP's internal EDI format, not the EDI standard itself"

# === SOURCES ===
sources:
  - id: src1
    title: "What is EDI Integration and Why Is It Important?"
    author: SPS Commerce
    url: https://www.spscommerce.com/resources/what-is-edi-integration/
    type: vendor_resource
    published: 2025-11-15
    reliability: high
  - id: src2
    title: "EDI Document Types Explained: 850, 810, 856, & More"
    author: Aayu Technologies
    url: https://aayutechnologies.com/blog/edi-document-types-explained/
    type: technical_blog
    published: 2025-06-20
    reliability: moderate_high
  - id: src3
    title: "What is EDI Mapping? An EDI Mapping Software Guide"
    author: Cleo
    url: https://www.cleo.com/blog/knowledge-base-edi-mapping
    type: vendor_resource
    published: 2025-08-10
    reliability: high
  - id: src4
    title: "How to Choose Between AS2, VAN, and API for EDI Integration"
    author: BOLD VAN
    url: https://www.boldvan.com/blog/how-to-choose-between-as2-van-and-api-for-edi-integration-in-manufacturing
    type: technical_blog
    published: 2025-09-15
    reliability: moderate_high
  - id: src5
    title: "EDI and ERP Integration: Best Practices, Benefits & Challenges"
    author: TrueCommerce
    url: https://www.truecommerce.com/blog/edi-integration-erp/
    type: vendor_resource
    published: 2025-10-01
    reliability: high
  - id: src6
    title: "OpenText Trading Grid — EDI, API, and B2B Integration"
    author: OpenText
    url: https://www.opentext.com/products/trading-grid
    type: official_docs
    published: 2025-07-01
    reliability: authoritative
  - id: src7
    title: "EDI and ERP Integration: Best Practices, Benefits & Challenges"
    author: IBM
    url: https://www.ibm.com/think/insights/edi-erp-integration
    type: industry_report
    published: 2025-05-15
    reliability: authoritative
  - id: src8
    title: "VAN vs AS2: Which Is Best for EDI?"
    author: Aayu Technologies
    url: https://aayutechnologies.com/blog/van-vs-as2/
    type: technical_blog
    published: 2025-04-20
    reliability: moderate_high
---

# EDI Integration with ERP: SPS Commerce, TrueCommerce, Cleo & OpenText

## TL;DR

- **Bottom line**: Use a VAN-based EDI translator (SPS Commerce, TrueCommerce) for broad trading partner coverage with minimal IT overhead; use direct AS2 (Cleo, OpenText) for high-volume partnerships where per-transaction cost savings justify the setup investment.
- **Key limit**: Trading partner maps are custom per partner and per document type — onboarding each new partner requires 2-6 weeks of testing and certification. [src1]
- **Watch out for**: Web EDI portals do NOT integrate with ERP automatically — without middleware or embedded connectors, operators re-key data manually, defeating the purpose of EDI. [src5]
- **Best for**: Automating the order-to-cash cycle (PO 850 > Ack 855 > ASN 856 > Invoice 810 > FA 997) between ERP and retail/wholesale trading partners. [src2]
- **Authentication**: AS2 uses digital certificates (X.509) for signing and encryption; VAN uses account credentials with network-level security; API uses OAuth 2.0 or API keys depending on the provider. [src4]

## System Profile

This card covers the end-to-end integration between ERP systems and EDI translator/VAN platforms. It is an integration playbook, not a single-system API card. The four major EDI integration platforms compared are SPS Commerce (managed VAN/embedded EDI), TrueCommerce (VAN/API hybrid), Cleo Integration Cloud (AS2/API/VAN), and OpenText Trading Grid (enterprise VAN/AS2/MFT). On the ERP side, the patterns apply to any major ERP — SAP, Oracle, NetSuite, Dynamics 365, Epicor, Sage, Acumatica — since the EDI translation layer abstracts the ERP-specific format. [src1, src5]

| System | Role | API Surface | Direction |
|---|---|---|---|
| Any ERP (SAP, Oracle, NetSuite, D365, Epicor) | Business system of record — orders, inventory, invoicing | Native API / flat file / IDoc | Inbound + Outbound |
| SPS Commerce | Managed EDI VAN / embedded ERP connector | VAN + pre-built ERP maps | Orchestrator |
| TrueCommerce | EDI VAN / API / SFTP connector | VAN + SFTP + API | Orchestrator |
| Cleo Integration Cloud | EDI translator / AS2 gateway | AS2 + API + SFTP + VAN | Orchestrator |
| OpenText Trading Grid | Enterprise B2B integration / MFT | VAN + AS2 + MFT + API | Orchestrator |
| Trading Partners (retailers, distributors) | External buyers/sellers | X12 / EDIFACT over VAN or AS2 | Counterparty |

## API Surfaces & Capabilities

EDI integration has four distinct transport and integration surfaces. Each serves different partner volumes and technical maturity levels. [src4, src8]

| Integration Surface | Protocol | Best For | Setup Time | Per-Transaction Cost | IT Overhead | Scalability |
|---|---|---|---|---|---|---|
| VAN (Value Added Network) | Proprietary mailbox | Broad partner networks (100+), compliance-heavy industries | 1-2 weeks | $0.05-$0.25/transaction | Low | Excellent |
| AS2 (Direct) | HTTPS + S/MIME | High-volume bilateral partnerships (>10K tx/month) | 4-8 weeks per partner | Near-zero (fixed infra cost) | High | Good per partner |
| API (REST/Webhook) | HTTPS/JSON | Modern partners, real-time visibility | 2-4 weeks | Near-zero | Medium | Excellent |
| Web EDI Portal | HTTPS (browser) | Low-volume small suppliers (<50 tx/month) | 1-3 days | Included in subscription | None | Poor (manual) |

## Rate Limits & Quotas

### EDI Document Processing Limits

| Limit Type | SPS Commerce | TrueCommerce | Cleo CIC | OpenText TG |
|---|---|---|---|---|
| Documents/day | Unlimited (plan-based) | Unlimited (plan-based) | Unlimited (license-based) | Unlimited (contract-based) |
| Partner connections | Plan-dependent (25-unlimited) | Plan-dependent | License-dependent | Contract-dependent |
| Document size | 10 MB per interchange | 5 MB default (configurable) | 50 MB per document | 80 MB per file (MFT) |
| Acknowledgment SLA | 997 within 24h standard | 997 within 24h standard | Configurable per partner | Configurable per partner |
| Onboarding time | 2-4 weeks per partner | 2-6 weeks per partner | 1-4 weeks per partner | 2-8 weeks per partner |

[src1, src5, src6]

### VAN Transaction Cost Structure

| Volume Tier | Typical VAN Cost | AS2 Equivalent | Breakeven Point |
|---|---|---|---|
| < 500 tx/month | $0.10-$0.25/tx ($50-$125/mo) | ~$500/mo fixed infrastructure | ~5,000 tx/month |
| 500-5,000 tx/month | $0.05-$0.15/tx ($25-$750/mo) | ~$500/mo fixed infrastructure | ~5,000 tx/month |
| 5,000-50,000 tx/month | $0.02-$0.08/tx ($100-$4,000/mo) | ~$500-$1,500/mo fixed | Already at breakeven |
| > 50,000 tx/month | $0.01-$0.05/tx ($500+/mo) | ~$1,500/mo fixed | AS2 wins significantly |

[src4, src8]

## Authentication

| Method | Used By | Mechanism | Certificate Required? | Notes |
|---|---|---|---|---|
| X.509 Digital Certificates | AS2 direct connections | Mutual TLS + S/MIME signing/encryption | Yes (both parties) | Certificates expire every 1-2 years; renewal coordination required with each partner |
| VAN Account Credentials | SPS Commerce, TrueCommerce, OpenText | Username/password or API key to VAN portal | No | VAN handles partner-to-partner security |
| OAuth 2.0 | Cleo CIC API, SPS Commerce API | OAuth 2.0 client credentials flow | No | Used for ERP-to-translator API integration |
| SFTP Key-Based | TrueCommerce, Cleo | SSH key pair authentication | SSH keys | Used for file-based EDI exchange with ERP |

[src4, src6]

### Authentication Gotchas

- AS2 certificate expiry is the #1 cause of unplanned EDI outages — set calendar reminders 60 days before expiry for every partner certificate. [src4]
- VAN credentials are org-scoped, not user-scoped — a single compromised credential exposes all trading partner communications. [src1]
- Some retailers require specific AS2 certificate types (e.g., SHA-256 minimum) — verify partner requirements before purchasing certificates. [src8]

## Constraints
<!-- Agents: read this section before recommending any integration approach from this unit.
     These are hard constraints that must not be violated. -->

- VAN pricing is typically per-kilo-character (KC) or per-document — at high volumes (>50K tx/month), VAN costs can exceed AS2 infrastructure costs by 3-5x. [src4]
- AS2 requires bilateral certificate exchange with EVERY direct partner — this does not scale beyond 20-50 partners without dedicated PKI management. [src8]
- EDI 997 functional acknowledgments are mandatory for most retail partners (Walmart, Target, Amazon Vendor Central, Costco) — missing 997s trigger chargebacks and compliance scorecards demerits. [src2]
- X12 and EDIFACT are NOT interchangeable — a partner requiring EDIFACT ORDERS cannot accept an X12 850 without a cross-standard translation step. [src3]
- Web EDI portals have NO automation — they are browser-based manual data entry tools that do not connect to ERP; they exist only for suppliers too small to justify EDI integration. [src5]
- Trading partner certification (testing) is required for EVERY new partner AND every new document type — there is no "connect once, trade with everyone" shortcut even with VANs. [src1]
- ERP-side mapping depends on the ERP's native format: SAP uses IDocs, Oracle uses FBDI/XML, NetSuite uses CSV/SuiteTalk, Dynamics uses Data Management Framework — the EDI translator must support the specific ERP format. [src3, src5]

## Integration Pattern Decision Tree

```
START — User needs to integrate ERP with EDI trading partners
├── How many trading partners?
│   ├── 1-5 high-volume partners
│   │   ├── Budget for per-partner setup?
│   │   │   ├── YES → Direct AS2 (lowest per-tx cost at scale)
│   │   │   └── NO → VAN (faster setup, higher per-tx cost)
│   │   └── Partners require AS2 specifically? (e.g., Walmart, Amazon)
│   │       ├── YES → AS2 is mandatory — use Cleo or OpenText
│   │       └── NO → VAN or API (flexibility to choose)
│   ├── 5-50 partners
│   │   ├── Mixed protocols (some AS2, some VAN)?
│   │   │   ├── YES → Hybrid: Cleo CIC or OpenText (supports both)
│   │   │   └── NO → VAN (SPS Commerce or TrueCommerce)
│   │   └── Need AI-powered mapping / monitoring?
│   │       ├── YES → SPS Commerce MAX or Cleo CIC
│   │       └── NO → TrueCommerce or generic VAN
│   └── 50+ partners
│       └── VAN is the only scalable option → SPS Commerce or OpenText
├── Which ERP?
│   ├── SAP S/4HANA → IDoc-based integration (see sap-idoc-edi-integration)
│   ├── Oracle ERP Cloud → FBDI/XML file import or REST API
│   ├── NetSuite → CSV import via SuiteCloud or SuiteTalk API
│   ├── Dynamics 365 → Data Management Framework or OData API
│   ├── Epicor / Sage / Acumatica → Platform-specific API or flat file
│   └── No ERP (small supplier) → Web EDI portal (manual, no integration)
├── What document types?
│   ├── Core order cycle only (850/855/856/810/997) → All platforms support
│   ├── Inventory (846) + Forecasting (830) → Verify platform support
│   └── Cross-dock / drop-ship (940/945) → Verify 3PL integration
└── What's the error tolerance?
    ├── Zero-loss (retail compliance) → VAN with 997 tracking + dead letter queue
    ├── Audit trail required → VAN with archival (all provide 7-year retention)
    └── Best-effort → SFTP + scheduled reconciliation
```

## Quick Reference

### EDI Document Flow: Order-to-Cash Cycle

| Step | EDI Document | X12 Code | EDIFACT Equivalent | Direction | ERP Transaction | Trigger |
|---|---|---|---|---|---|---|
| 1. Purchase Order | Purchase Order | 850 | ORDERS | Buyer → Seller | Create Sales Order | Buyer procurement system |
| 2. PO Acknowledgment | PO Acknowledgment | 855 | ORDRSP | Seller → Buyer | SO confirmation | SO created/modified in ERP |
| 3. Advance Ship Notice | Ship Notice/Manifest | 856 | DESADV | Seller → Buyer | Shipment/delivery | Goods shipped from warehouse |
| 4. Invoice | Invoice | 810 | INVOIC | Seller → Buyer | AR Invoice | Shipment confirmed |
| 5. Functional Ack | Functional Acknowledgment | 997 | CONTRL | Receiver → Sender | (none — system-level) | Any EDI document received |
| 6. Payment Advice | Remittance Advice | 820 | REMADV | Buyer → Seller | AP payment applied | Payment processed |
| 7. Inventory Inquiry | Inventory Inquiry/Advice | 846 | INVRPT | Seller → Buyer | Inventory snapshot | Scheduled or on-demand |
| 8. Forecast | Planning Schedule | 830 | DELFOR | Buyer → Seller | Demand planning | Forecast cycle |

[src2]

### EDI Platform Comparison

| Capability | SPS Commerce | TrueCommerce | Cleo CIC | OpenText Trading Grid |
|---|---|---|---|---|
| **Primary Model** | Managed VAN + embedded ERP connectors | VAN + API + SFTP | AS2/API/SFTP + VAN | Enterprise VAN + AS2 + MFT |
| **Pre-built ERP Maps** | 100+ ERPs (incl. NetSuite, Acumatica, SAP B1) | 20+ ERPs (D365, SAP, Oracle, Sage) | 50+ ERPs via pre-built connectors | 200+ connectors (ERP, CRM, WMS) |
| **Partner Network** | 115,000+ retail partners | 92,000+ trading partners | Variable (customer-managed) | 1,000,000+ pre-connected partners |
| **X12 Support** | Full (all transaction sets) | Full | Full | Full |
| **EDIFACT Support** | Full | Full | Full | Full |
| **AS2 Support** | Via VAN (abstracted) | Via VAN (abstracted) | Native (primary strength) | Native + VAN |
| **Web EDI** | Yes (for small suppliers) | Yes | Limited | Yes |
| **AI/ML Features** | MAX AI (2026) — anomaly detection, compliance | Basic analytics | AI-powered mapping | Analytics + MFT optimization |
| **Pricing Model** | Per-connection + transaction fees | Tiered subscription | License + per-connection | Enterprise contract (custom) |
| **Best For** | Retail/wholesale with 50+ partners | Mid-market, multi-ERP | Technical teams, high AS2 volume | Enterprise, global supply chain |

[src1, src5, src6, src3]

## Step-by-Step Integration Guide

### 1. Map Business Requirements to EDI Document Types

Identify which EDI transactions your trading partners require. Most retail partners mandate a minimum set. [src2]

```
Required by most retail partners:
  850 (Purchase Order)      — inbound to your ERP
  855 (PO Acknowledgment)   — outbound from your ERP
  856 (Advance Ship Notice)  — outbound from your ERP
  810 (Invoice)             — outbound from your ERP
  997 (Functional Ack)      — bidirectional (automatic)

Often required:
  846 (Inventory Advice)    — outbound from your ERP
  860 (PO Change Request)   — inbound to your ERP
  865 (PO Change Ack)       — outbound from your ERP
```

**Verify**: Check each trading partner's EDI implementation guide (provided during onboarding) for required document types, versions, and segment-level requirements.

### 2. Select Transport Method (VAN vs AS2 vs API)

Choose based on partner count, volume, and IT capacity. [src4, src8]

```
Decision matrix:
  Partners < 10 AND volume > 10K tx/month  → Direct AS2
  Partners < 10 AND volume < 10K tx/month  → VAN or API
  Partners 10-50                            → VAN (SPS or TrueCommerce)
  Partners 50+                              → VAN (mandatory at scale)
  Mixed (some AS2-only partners like Walmart) → Hybrid (Cleo or OpenText)
```

**Verify**: Confirm each partner's supported transport methods — some large retailers (Walmart, Amazon, Target) mandate specific protocols.

### 3. Configure ERP-to-EDI Mapping

The EDI translator converts between your ERP's native format and X12/EDIFACT standards. [src3]

```
ERP-specific outbound mapping:
  SAP S/4HANA:    IDoc (ORDERS05, INVOIC02) → X12 (850, 810)
  Oracle ERP:      XML/FBDI → X12
  NetSuite:        CSV/JSON via SuiteTalk → X12
  Dynamics 365:    XML via DMF or OData JSON → X12
  Epicor Kinetic:  BAQ/REST API JSON → X12

Mapping approach:
  1:1 Direct mapping → each partner gets custom map (simple but unscalable)
  Canonical mapping → ERP → internal canonical format → X12/EDIFACT per partner
                      (recommended for 5+ partners)
```

**Verify**: Send test transactions (EDI 850 inbound) through the full pipeline and confirm the ERP creates the correct Sales Order with all line items, prices, and shipping details.

### 4. Implement 997 Functional Acknowledgment Processing

997s confirm receipt and syntactic validity of EDI documents. They do NOT confirm business acceptance. [src2]

```
997 processing flow:
  1. Receive EDI document (e.g., 850)
  2. EDI translator validates syntax (envelope, segments, elements)
  3. If valid → generate 997 with AK9 status "A" (Accepted)
  4. If errors → generate 997 with AK9 status "R" (Rejected) + error codes
  5. Return 997 to sender within SLA (typically 24h)

Common 997 error codes:
  AK304-1:  Unrecognized segment ID
  AK304-3:  Mandatory segment missing
  AK304-5:  Segment exceeds maximum use
  AK403-1:  Mandatory data element missing
  AK403-4:  Data element too long
  AK403-7:  Invalid code value
```

**Verify**: Send a deliberately malformed test document and confirm the 997 returns status "R" with the correct error segments.

### 5. Set Up Error Monitoring and Alerting

EDI failures are silent by default — without monitoring, failed transactions go unnoticed until a trading partner complains or a compliance violation is issued. [src1, src5]

```
Monitoring checklist:
  [ ] 997 rejection alerts — email/Slack when any 997 returns "R"
  [ ] Missing 997 alerts — flag when no 997 received within SLA window
  [ ] Document stuck in queue — alert when documents pending > 4 hours
  [ ] Partner connectivity down — alert when VAN/AS2 connection fails
  [ ] ERP import failures — alert when translated documents fail ERP validation
  [ ] Compliance scorecard — weekly report of on-time ASN (856) and invoice (810) rates
```

**Verify**: Simulate a connection failure and confirm alerts fire within the configured threshold.

### 6. Test End-to-End with Trading Partner Certification

Every trading partner requires a certification cycle before going live. [src1]

```
Certification steps:
  1. Receive partner's EDI implementation guide (document formats, rules)
  2. Configure maps per partner specification
  3. Exchange test documents in sandbox/test environment
  4. Partner validates: correct segments, element values, totals
  5. Fix any discrepancies (usually 2-3 rounds)
  6. Partner certifies and moves connection to production
  7. Monitor first 2 weeks of production traffic closely

Timeline: 2-6 weeks per partner (depending on partner responsiveness)
```

**Verify**: Trading partner confirms certification complete and connection status shows "Active" in both VAN portal and partner portal.

## Code Examples

### Python: Parse X12 850 Purchase Order and Create ERP Sales Order

```python
# Input:  Raw X12 850 EDI document string
# Output: Parsed purchase order dict ready for ERP API insertion
# Requires: pip install pyx12==3.0.0

import re
from datetime import datetime

def parse_x12_850(edi_content: str) -> dict:
    """Parse X12 850 Purchase Order into structured dict for ERP import."""
    segments = edi_content.replace("\n", "").split("~")
    order = {"line_items": [], "raw_segment_count": len(segments)}

    for seg in segments:
        elements = seg.strip().split("*")
        seg_id = elements[0] if elements else ""

        if seg_id == "BEG":  # Beginning segment
            order["po_number"] = elements[3] if len(elements) > 3 else ""
            order["po_date"] = elements[5] if len(elements) > 5 else ""

        elif seg_id == "N1":  # Name/entity
            qualifier = elements[1] if len(elements) > 1 else ""
            name = elements[2] if len(elements) > 2 else ""
            if qualifier == "ST":  # Ship-to
                order["ship_to_name"] = name
            elif qualifier == "BT":  # Bill-to
                order["bill_to_name"] = name

        elif seg_id == "PO1":  # Line item
            item = {
                "line_number": elements[1] if len(elements) > 1 else "",
                "quantity": int(elements[2]) if len(elements) > 2 else 0,
                "unit": elements[3] if len(elements) > 3 else "EA",
                "unit_price": float(elements[4]) if len(elements) > 4 else 0.0,
                "upc": elements[7] if len(elements) > 7 else "",
                "vendor_sku": elements[9] if len(elements) > 9 else "",
            }
            order["line_items"].append(item)

        elif seg_id == "CTT":  # Transaction totals
            order["total_line_items"] = int(elements[1]) if len(elements) > 1 else 0

    return order


def generate_x12_997(original_edi: str, accepted: bool = True) -> str:
    """Generate a 997 Functional Acknowledgment for a received document."""
    # Extract ISA/GS control numbers from original
    segments = original_edi.replace("\n", "").split("~")
    gs_control = ""
    st_control = ""
    for seg in segments:
        els = seg.strip().split("*")
        if els[0] == "GS" and len(els) > 6:
            gs_control = els[6]
        if els[0] == "ST" and len(els) > 2:
            st_control = els[2]

    status = "A" if accepted else "R"
    ack = (
        f"ST*997*0001~"
        f"AK1*PO*{gs_control}~"
        f"AK2*850*{st_control}~"
        f"AK5*{status}~"
        f"AK9*{status}*1*1*{'1' if accepted else '0'}~"
        f"SE*5*0001~"
    )
    return ack
```

### JavaScript/Node.js: Send EDI 856 ASN via AS2

```javascript
// Input:  Shipment data object from ERP
// Output: AS2 transmission result with MDN receipt
// Requires: npm install as2-lib@2.0.0 axios@1.7.0

const crypto = require('crypto');
const https = require('https');

/**
 * Build X12 856 ASN from ERP shipment data
 */
function buildASN856(shipment) {
  const date = new Date().toISOString().slice(0, 10).replace(/-/g, '');
  const time = new Date().toISOString().slice(11, 15).replace(/:/g, '');
  const controlNum = String(Date.now()).slice(-9).padStart(9, '0');

  return [
    `ISA*00*          *00*          *ZZ*SENDERID       *ZZ*RECEIVERID     *${date.slice(2)}*${time}*U*00401*${controlNum}*0*P*>`,
    `GS*SH*SENDERID*RECEIVERID*${date}*${time}*${controlNum}*X*004010`,
    `ST*856*0001`,
    `BSN*00*${shipment.shipmentId}*${date}*${time}*0001`,
    `HL*1**S`,  // Shipment level
    `TD1*CTN*${shipment.cartonCount}`,
    `TD5**2*FEDX*CC`,
    `REF*BM*${shipment.bolNumber}`,
    `DTM*011*${shipment.shipDate}`,
    `N1*ST*${shipment.shipToName}`,
    `N3*${shipment.shipToAddress}`,
    `N4*${shipment.shipToCity}*${shipment.shipToState}*${shipment.shipToZip}`,
    ...shipment.items.map((item, idx) => [
      `HL*${idx + 2}*1*I`,  // Item level
      `LIN**UP*${item.upc}*VP*${item.vendorSku}`,
      `SN1**${item.quantity}*EA`,
    ].join('~')),
    `CTT*${shipment.items.length}`,
    `SE*${12 + shipment.items.length * 3}*0001`,
    `GE*1*${controlNum}`,
    `IEA*1*${controlNum}`,
  ].join('~') + '~';
}

/**
 * Transmit EDI document via HTTPS POST (simplified AS2-like)
 * In production, use a proper AS2 library for S/MIME signing
 */
async function sendViaAS2(ediContent, partnerConfig) {
  const messageId = `<${crypto.randomUUID()}@sender.example.com>`;
  const options = {
    hostname: partnerConfig.as2Url,
    port: 443,
    path: partnerConfig.as2Path,
    method: 'POST',
    headers: {
      'Content-Type': 'application/edi-x12',
      'AS2-From': partnerConfig.senderId,
      'AS2-To': partnerConfig.receiverId,
      'Message-ID': messageId,
      'Disposition-Notification-To': partnerConfig.mdnUrl,
      'Disposition-Notification-Options':
        'signed-receipt-protocol=required,pkcs7-signature; signed-receipt-micalg=required,sha256',
    },
  };

  return new Promise((resolve, reject) => {
    const req = https.request(options, (res) => {
      let body = '';
      res.on('data', (chunk) => body += chunk);
      res.on('end', () => resolve({
        statusCode: res.statusCode,
        mdnReceived: res.statusCode === 200,
        messageId,
        body,
      }));
    });
    req.on('error', reject);
    req.write(ediContent);
    req.end();
  });
}
```

### cURL: Test VAN Connectivity and Retrieve Documents

```bash
# Test SPS Commerce API connectivity
# Input:  SPS Commerce API credentials
# Output: List of pending EDI documents in mailbox

curl -s -X GET "https://api.spscommerce.com/transactions/v2/pending" \
  -H "Authorization: Bearer $SPS_API_TOKEN" \
  -H "Content-Type: application/json" | jq '.transactions | length'

# Expected: numeric count of pending documents (0 if mailbox is empty)

# Retrieve a specific EDI document from VAN
curl -s -X GET "https://api.spscommerce.com/transactions/v2/{transaction_id}/document" \
  -H "Authorization: Bearer $SPS_API_TOKEN" \
  -H "Accept: application/edi-x12"

# Expected: raw X12 EDI content starting with ISA segment

# Submit an outbound EDI document to VAN
curl -s -X POST "https://api.spscommerce.com/transactions/v2/outbound" \
  -H "Authorization: Bearer $SPS_API_TOKEN" \
  -H "Content-Type: application/edi-x12" \
  -d @outbound_810_invoice.edi

# Expected: {"transactionId": "...", "status": "queued"}
```

## Data Mapping

### ERP-to-EDI Field Mapping: Sales Order to 850/855/856/810

| ERP Field (Generic) | X12 Segment*Element | EDIFACT Segment | Transform | Gotcha |
|---|---|---|---|---|
| PO Number | BEG*03 | BGM+220 | Direct | Max 22 chars in X12; some ERPs allow 30+ |
| PO Date | BEG*05 | DTM+137 | YYYYMMDD format | ERP may store as datetime; strip time component |
| Ship-To Name | N1*ST*02 | NAD+ST | Direct | Max 60 chars; truncate, don't reject |
| Ship-To Address | N3*01 | NAD+ST:street | Direct | Two N3 segments max; combine if ERP has 3+ lines |
| Ship-To City/State/Zip | N4*01/02/03 | NAD+ST:city/region/postal | Direct | International postal codes may exceed X12 15-char limit |
| Line Item UPC | PO1*07 (UP qualifier) | LIN+UP | Direct | Must be 12-digit GTIN; pad with leading zeros if needed |
| Line Item SKU | PO1*09 (VP qualifier) | LIN+SA | Direct | Vendor-assigned; varies by partner |
| Quantity | PO1*02 | QTY+21 | Integer | X12 allows decimals; some partners reject them |
| Unit Price | PO1*04 | PRI+AAA | Decimal, 2-4 places | Currency implied by interchange; never include currency symbol |
| Carrier Code | TD5*03 | TDT+20 | SCAC code lookup | Must use Standard Carrier Alpha Code; ERP may store carrier name instead |
| Tracking Number | REF*CN | RFF+AAR | Direct | Multiple tracking numbers = multiple REF segments |

[src2, src3]

### Data Type Gotchas

- X12 dates are ALWAYS YYYYMMDD (8 digits, no separators) — ERPs that store ISO 8601 (YYYY-MM-DD) must strip hyphens. [src2]
- X12 numeric fields do NOT include commas or currency symbols — "$1,234.56" must be transmitted as "1234.56". [src3]
- EDIFACT uses comma as decimal separator by default (UNA segment) — North American integrations must verify the UNA is set to period-as-decimal. [src3]
- GS1/UPC codes must be exactly 12 digits in X12 — if the ERP stores 13-digit EAN, strip the leading zero for US partners or use the IN qualifier for EAN. [src2]
- Ship-to addresses in X12 have a 2-line limit (N3 segments) — combine address lines 3+ into line 2 or you will get a 997 rejection. [src2]

## Error Handling & Failure Points

### Common EDI Error Codes

| Error Source | Code | Meaning | Cause | Resolution |
|---|---|---|---|---|
| 997 | AK304-1 | Unrecognized segment ID | Segment not in partner's implementation guide | Review partner's EDI spec; remove or rename segment |
| 997 | AK304-3 | Mandatory segment missing | Required segment omitted from outbound document | Add missing segment to mapping; re-send |
| 997 | AK403-1 | Mandatory element missing | Required data element blank in ERP | Fix ERP data quality; add validation before EDI generation |
| 997 | AK403-4 | Data element too long | Field exceeds max length per X12 spec | Truncate to spec length; log warning |
| 997 | AK403-7 | Invalid code value | Code not in partner's allowed value list | Map ERP code to partner's code list |
| AS2 | MDN-error | Decryption/signature failure | Certificate mismatch or expiry | Exchange updated certificates with partner |
| VAN | ENVELOPE_ERROR | ISA/GS envelope validation failed | Control numbers out of sequence or duplicate | Reset control number sequence; check for duplicate sends |
| ERP | IMPORT_FAIL | ERP rejected translated document | Validation rule failure (missing customer, invalid item) | Fix master data in ERP; add pre-validation in translator |

[src2, src3, src4]

### Failure Points in Production

- **Certificate expiry breaks all AS2 traffic silently**: AS2 connections fail with no inbound/outbound documents and no alerts unless monitoring is configured. Fix: `Set certificate expiry alerts 60 days in advance; maintain a certificate renewal calendar for every AS2 partner`. [src4]
- **Control number duplication causes 997 rejections**: X12 ISA and GS control numbers must be unique per interchange and per functional group. If the EDI translator resets or the counter file is corrupted, duplicate numbers cause immediate rejection. Fix: `Use database-backed control number sequences, not file-based counters; implement duplicate detection`. [src2]
- **ERP master data mismatch causes import failures**: A valid EDI 850 with a customer ID or item UPC not in the ERP master data will fail on import. The EDI translator accepts it (valid syntax), but the ERP rejects it (invalid business data). Fix: `Implement pre-validation in the translator that checks customer and item master data before attempting ERP import; queue failures for manual review`. [src5]
- **Timezone differences cause date mismatches**: An 850 with ship-date 20260303 processed at 23:00 PST may create an ERP order dated 2026-03-04 if the ERP server is UTC. Fix: `Standardize all EDI dates to UTC in the translator; apply timezone offset during ERP import based on business rules`. [src3]
- **GS1/UPC lookup failures on new items**: If a trading partner sends a PO with a new UPC not yet in your item master, the 850 import fails. Fix: `Create an "unknown item" queue in the translator; alert purchasing to add the item to ERP master data; retry after master data update`. [src1]
- **Partial shipment handling breaks 856 ASN generation**: If the ERP ships partially (2 of 5 items), the 856 must reflect partial quantities. Many EDI translators default to generating 856 from the original PO quantities, not the actual shipment. Fix: `Map 856 to the ERP's shipment/delivery document, NOT the sales order; verify quantities match packing list`. [src2]

## Anti-Patterns

### Wrong: Using Web EDI as a Permanent Integration Strategy

```
Web EDI workflow (manual):
  1. Log into retailer's web portal
  2. View incoming PO
  3. Manually re-key PO data into ERP
  4. Process order in ERP
  5. Manually create 856/810 in web portal
  6. Copy-paste tracking numbers

Result: 15-30 minutes per order, 5-10% error rate,
        no scalability beyond 20 orders/day
```

### Correct: Automated EDI-to-ERP Integration via VAN or AS2

```
Automated EDI workflow:
  1. 850 arrives via VAN → translator auto-maps to ERP format
  2. ERP creates Sales Order automatically (< 5 seconds)
  3. Warehouse ships → ERP generates shipment record
  4. Translator auto-generates 856 ASN from shipment
  5. Translator auto-generates 810 Invoice from AR
  6. 997s exchanged automatically

Result: < 30 seconds per order, < 0.1% error rate,
        scales to thousands of orders/day
```

### Wrong: Building Custom Point-to-Point EDI Parsing

```python
# Each partner's 850 has different segment usage
# Building custom parsers per partner = maintenance nightmare
def parse_walmart_850(raw): ...   # 500 lines
def parse_target_850(raw): ...    # 400 lines
def parse_costco_850(raw): ...    # 350 lines
# Result: N partners = N parsers = N^2 maintenance burden
```

### Correct: Using Canonical Mapping Through an EDI Translator

```
Canonical mapping approach:
  Partner A (850 v4010) ──→ ┌─────────────────┐
  Partner B (850 v5010) ──→ │ Canonical Format │ ──→ ERP native format
  Partner C (ORDERS D96A) → │   (internal XML  │     (IDoc / CSV / JSON)
  Partner D (850 v4010) ──→ │    or JSON)      │
                            └─────────────────┘
  Result: N partner maps + 1 canonical-to-ERP map
          vs N custom parsers
```

### Wrong: Ignoring 997 Functional Acknowledgments

```
Common mistake:
  "We process the 850s fine — 997s are just receipts, we don't need them."

Reality:
  - Walmart: missing 997 within 24h = compliance violation = chargeback
  - Target: 997 rejection rate > 5% = vendor scorecard demerit
  - Amazon Vendor Central: no 997 = PO treated as unacknowledged
```

### Correct: Automated 997 Processing with Monitoring

```
Correct 997 implementation:
  1. Auto-generate 997 for EVERY inbound document (850, 860, 830)
  2. Track 997 SLA: must send within partner's window (usually 24h)
  3. Monitor inbound 997s for YOUR outbound documents (856, 810)
  4. Alert on: 997 rejection, 997 timeout, 997 with error segments
  5. Dashboard: 997 acceptance rate by partner (target: 99.5%+)
```

## Common Pitfalls

- **Not testing with production-volume data**: Test environments typically process 10-50 documents; production may handle 10,000+/day. Batch processing, queue depths, and ERP import throughput behave differently at scale. Fix: `Run load tests with 2x expected peak volume before go-live`. [src1]
- **Hardcoding partner-specific logic in the ERP**: Embedding partner-specific EDI rules (segment usage, code values) in ERP customizations creates unmaintainable code when partners change requirements. Fix: `Keep all partner-specific logic in the EDI translator maps; the ERP should receive a clean, standardized format`. [src3]
- **Ignoring ISA/GS envelope validation**: The ISA and GS envelope segments contain sender/receiver IDs, control numbers, and version identifiers. Mismatched envelope data causes silent routing failures at the VAN. Fix: `Validate ISA13 (interchange control number) uniqueness and GS06 (group control number) sequencing before transmission`. [src2]
- **Not planning for partner map changes**: Trading partners update their EDI implementation guides 1-2 times per year. A partner switching from X12 4010 to 5010, or adding mandatory segments, breaks existing maps. Fix: `Subscribe to partner EDI update notifications; maintain a map version matrix; schedule quarterly map reviews`. [src5]
- **Using flat-rate VAN pricing without volume analysis**: Some VANs charge per-KC (kilo-character), others per-document, others flat-rate. Choosing the wrong pricing model can cost 3-5x more than optimal. Fix: `Analyze 3 months of transaction data (document count AND size) before selecting a VAN pricing tier; renegotiate annually`. [src4]
- **Missing the AS2 MDN (Message Disposition Notification)**: AS2 requires an MDN to confirm receipt. Synchronous MDN is returned immediately; asynchronous MDN is returned later via a separate HTTP POST. Mixing these modes with a partner that expects the other causes "delivered but unacknowledged" failures. Fix: `Verify MDN mode (sync vs async) with each AS2 partner during setup; test both send and receive MDN flows`. [src4, src8]

## Diagnostic Commands

```bash
# Check VAN mailbox for pending documents (SPS Commerce API)
curl -s "https://api.spscommerce.com/transactions/v2/pending" \
  -H "Authorization: Bearer $SPS_TOKEN" | jq '.transactions | length'
# Expected: number of pending inbound documents

# Test AS2 connectivity to a partner
openssl s_client -connect partner.example.com:443 -servername partner.example.com \
  < /dev/null 2>/dev/null | openssl x509 -noout -dates
# Expected: notBefore and notAfter dates (verify cert not expired)

# Validate X12 document structure (segment count, control numbers)
grep -c "~" outbound_document.edi
# Expected: matches the SE01 segment count in the document

# Check ISA control number uniqueness in recent transmissions
grep "^ISA" transmission_log.txt | awk -F'*' '{print $14}' | sort | uniq -d
# Expected: no output (no duplicates)

# Verify 997 acknowledgment status for outbound documents
curl -s "https://api.spscommerce.com/transactions/v2/acks?status=rejected" \
  -H "Authorization: Bearer $SPS_TOKEN" | jq '.acks[]'
# Expected: empty array if all 997s accepted

# Test SFTP connectivity to EDI translator
sftp -o ConnectTimeout=10 edi_user@translator.example.com <<< "ls incoming/"
# Expected: directory listing of incoming EDI files
```

## Version History & Compatibility

| Standard/Platform | Version | Status | Key Changes | Notes |
|---|---|---|---|---|
| ANSI X12 Version 4010 | 2000 | Widely supported | — | Most common in US retail; still the default for many partners |
| ANSI X12 Version 5010 | 2009 | Current standard | Additional segments, HIPAA alignment | Required for healthcare; increasingly adopted in retail |
| ANSI X12 Version 8030 | 2023 | Emerging | JSON/XML hybrid support | Limited adoption; most partners still on 4010/5010 |
| UN/EDIFACT D.96A-D.22A | Ongoing | Current | Annual directory releases | European/global standard; version specified per message |
| SPS Commerce Platform | 2026 | Current | MAX AI features (anomaly detection, compliance) | Largest US retail EDI network |
| TrueCommerce Foundry | 2026 | Current | Enhanced API integration | Multi-ERP cloud platform |
| Cleo Integration Cloud | 2026 | Current | AI-powered mapping GA | Hybrid AS2/API/VAN |
| OpenText Trading Grid | 2025 | Current | 200+ pre-built connectors | Largest global B2B network (1M+ partners) |

[src1, src2, src3, src6]

### Deprecation Policy

X12 versions are not formally deprecated — trading partners dictate which version they accept, and most US retail partners still accept version 4010 (released 2000). However, HIPAA mandates version 5010 for healthcare EDI. EDIFACT issues annual directory releases but maintains backward compatibility. EDI platform vendors (SPS, TrueCommerce, Cleo, OpenText) maintain backward compatibility indefinitely since their business depends on supporting legacy partner connections. [src2]

## When to Use / When Not to Use

| Use When | Don't Use When | Use Instead |
|---|---|---|
| Trading partners mandate EDI (retail, wholesale, automotive, healthcare) | Partners offer modern API-based integration | REST API direct integration |
| Need to comply with retailer scorecards (Walmart, Target, Amazon Vendor Central) | Only 1-2 partners with low volume (<10 tx/month) | Email + manual processing |
| Processing >100 orders/day across multiple partners | Internal system-to-system integration (no external partners) | iPaaS or native API (see ipaas-platform-comparison) |
| Need automated order-to-cash cycle (850→855→856→810) | Real-time, sub-second integration required | Direct API or webhook integration |
| Industry requires EDI compliance (HIPAA 837/835, automotive AIAG) | Partner supports CSV/flat file exchange only | SFTP + file-based integration |

## Cross-System Comparison

| Capability | SPS Commerce | TrueCommerce | Cleo CIC | OpenText Trading Grid |
|---|---|---|---|---|
| **Setup Complexity** | Low (managed service) | Low-Medium | Medium-High | High (enterprise) |
| **IT Staff Required** | Minimal (0.5 FTE) | Low (0.5-1 FTE) | Medium (1-2 FTE) | High (2+ FTE) |
| **Partner Onboarding** | 2-4 weeks (pre-mapped) | 2-6 weeks | 1-4 weeks | 2-8 weeks |
| **ERP Connectors** | 100+ pre-built | 20+ pre-built | 50+ pre-built | 200+ pre-built |
| **AS2 Native** | No (via VAN) | No (via VAN) | Yes (primary) | Yes |
| **API Integration** | REST API available | SFTP + API | REST + webhook | REST + MFT |
| **AI/ML Features** | MAX AI (2026) | Basic | AI mapping (2025) | Analytics |
| **Global EDIFACT** | Supported | Supported | Supported | Primary strength |
| **Pricing Transparency** | Published tiers | Quote-based | Quote-based | Enterprise contract |
| **Best For** | US retail mid-market | Multi-ERP, Sage/D365 | Technical teams, AS2-heavy | Global enterprise |
| **Typical Annual Cost** | $5K-$50K | $3K-$30K | $10K-$100K+ | $50K-$500K+ |
| **Free Trial** | Demo only | Demo only | POC available | POC available |

[src1, src3, src5, src6]

## Important Caveats

- EDI translator pricing varies dramatically — SPS Commerce publishes tiered pricing, but TrueCommerce, Cleo, and OpenText require custom quotes. Always get quotes from at least 3 providers before committing. [src4]
- "Full-service EDI" means different things to different vendors — SPS Commerce includes map creation and partner onboarding in their managed service; Cleo expects your team to build and maintain maps (but provides tools). Clarify scope before signing. [src1, src3]
- VAN transaction costs are declining as API-based alternatives grow, but VANs remain essential for partners that only support VAN-based EDI (many large retailers). [src8]
- HIPAA-regulated EDI (healthcare claims 837, remittance 835) has additional compliance requirements not covered in this card — consult industry-specific guidance. [src2]
- This card covers the integration architecture and platform comparison — for ERP-specific configuration (SAP IDoc setup, NetSuite SuiteCloud connector, D365 DMF), see the related system-specific cards. [src5]
- AI-powered EDI mapping (SPS MAX, Cleo AI) is newly GA as of 2025-2026 — evaluate carefully as these features are still maturing. [src1, src3]

## Related Units

- [Order-to-Cash Integration](/business/erp-integration/order-to-cash-integration/2026) — the business process EDI automates
- [SAP IDoc EDI Integration](/business/erp-integration/sap-idoc-edi-integration/2026) — SAP-specific IDoc/EDI configuration
- [Procure-to-Pay Integration](/business/erp-integration/procure-to-pay-integration/2026) — the buying side of EDI
- [iPaaS Platform Comparison](/business/erp-integration/ipaas-platform-comparison/2026) — API-first alternative to EDI
- [Error Handling & Dead Letter Queues](/business/erp-integration/error-handling-dead-letter-queues/2026) — error handling patterns for failed EDI transactions
