# B2B and EDI with Trading Partner Management: profiles, agreements, guidelines and onboarding at scale

> Run partner EDI as Trading Partner Management models it, with profiles, templates, agreements, MIGs, MAGs and a B2B monitor, then onboard partners in batches.

- Course: Orchestrate, Unit 26 · Integration in depth
- Page: https://erpfde.com/topics/b2b-and-edi-integration/
- Updated: 2026-11-29
- Reading time: Foundational 8 min, Deep 40 min

Independent learning resource. Not affiliated with, sponsored by or endorsed by SAP SE. SAP and other SAP products mentioned are trademarks of SAP SE in Germany and other countries.

## Foundational layer

### The 60-second version

**EDI** (electronic data interchange) is how companies send each other business documents, such as purchase orders and invoices, in an agreed standard format. Many distributors, retailers and carmakers will only trade this way. A supplier that can't take their EDI orders doesn't get them.

The hard part of EDI isn't one partner. It is the fortieth. Each partner sends the same kind of document with its own identifiers, its own part numbers, its own reading of the standard and its own test cycle. If every partner gets a hand-built flow, the integration team spends its life copying flows and fixing one-off mistakes.

SAP's answer, as of November 2026, is **Trading Partner Management** in SAP Integration Suite. You describe each partner once in a **profile**, describe each kind of exchange once in an **agreement template**, and create an **agreement** per partner that fills in what is specific to them. SAP's generic integration flows then process every partner's messages from those agreements. The standard's details live in **message implementation guidelines** and **mapping guidelines** built in Integration Advisor.

This topic uses Calder Pumpworks, the fictional pump maker used across this course. Calder takes purchase orders from distributors such as Hallam Fluid Systems through interface `I10`. The decision for a leader: **treat partner onboarding as a repeatable process with entry rules, not as a project per partner**, and decide who owns the partner data that makes it work.

### Why it matters to the business

For Calder, distributor EDI is revenue. Hallam alone sends several orders a week. When EDI goes wrong, it goes wrong quietly:

- **Orders nobody sees.** A message from a new distributor arrives before its agreement is active. It fails before it is linked to any partner, so nobody gets an alert unless someone watches that list.
- **The wrong fix.** Hallam starts using a new part number. Retrying the message changes nothing; the fix is a mapping change in Hallam's agreement, followed by a reprocess.
- **The wrong owner.** Hallam sends a unit of measure the guideline doesn't allow. Only Hallam can fix that, by sending a corrected order. Calder's job is to tell the right person at Hallam quickly.
- **Slow onboarding.** A distributor that waits six weeks for EDI goes on emailing orders, which someone keys by hand. Each keyed order is a chance for a typo.
- **Expired certificates.** Partners that send over AS2 (a secure HTTP protocol used for EDI) sign and encrypt with certificates. One that expires on a Friday stops that partner's orders until someone notices.

Calder's integration platform decision (ADR-001 in the [integration platform topic](https://erpfde.com/topics/integration-platform-and-clean-core/)) already put Trading Partner Management in the target design. This topic is about running it well: what to set up once, what to set up per partner, and which checks stop a bad partner setup from reaching production.

### How SAP does it

As of 29 November 2026, according to SAP's Integration Suite documentation:

- **Trading Partner Management** manages partner profiles, agreement templates and agreements. It supports several protocols (SAP names AS2, SFTP and FTP) and standards (EDI, XML, JSON). When you activate an agreement, it pushes runtime settings into the **Partner Directory** of Cloud Integration, so one set of generic flows handles every partner ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/trading-partner-management-28fe3dc.md)).
- **Integration Advisor** holds a library of standards (UN/EDIFACT, ASC X12, SAP IDoc and others) and is where you build the **message implementation guideline (MIG)**, your reading of a standard message, and the **mapping guideline (MAG)**, the mapping from one MIG to another. It offers proposals from what SAP calls a crowd-based machine learning approach ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integration_Advisor/overview-of-sap-integration-advisor-f99fdaf.md)).
- **A B2B monitor** shows each interchange, its status and an error category, and lets an authorized user restart, retry or cancel ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/restart-or-retry-or-duplicate-and-retry-interchanges-8626727.md)).
- **Licensing.** SAP's [pricing page](https://www.sap.com/products/technology-platform/integration-suite/pricing.html) lists "B2B electronic interchange libraries, acknowledgment framework, and trading partner management" as a feature row across its Starter, Standard and Enhanced plans. Confirm with SAP which plan you hold includes it. The AS2 adapter's availability also depends on the service plan, per [SAP's adapter page](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/as2-adapter-d3af635.md).

### What is set up once, and what per partner

The design choice that makes EDI scale is to push as much as possible into things you set up once. This is how Calder splits it for distributor orders:

| Object | How many | What it holds for Calder | Who owns it |
| --- | --- | --- | --- |
| Company profile | One | Calder's EDI identifier `CALDERCP10`, its systems, number ranges for acknowledgments | Integration lead |
| MIG | One per standard message | Calder's reading of `ORDERS` D.96A: required segments, allowed codes and units | Integration lead with the order-to-cash team |
| MAG | One per MIG pair | How an `ORDERS` message becomes a Calder sales order | Integration developer |
| Agreement template | One per kind of exchange | Distributor order inbound: message, MIG, MAG, acknowledgment, test handling | Integration lead |
| Trading partner profile | One per partner | Name, EDI identifier, AS2 identifier and certificate, contacts for errors | Customer service with IT |
| Agreement | One per partner and exchange | The template plus the partner's customer number, sales area and part numbers | Customer service, reviewed by integration |

The more a partner's needs fit the template, the cheaper the partner. A distributor that sends Calder's own part numbers needs no part list at all. A distributor that insists on its own numbers needs a cross-reference that someone must keep current.

> **Note** **For functional consultants.** Three things change in your work. Partner part numbers become agreement data with a version history, not a table in a custom program, so changing one is a controlled change. Your test cases move into onboarding: each new partner sends a test interchange that must pass before go-live. And the customer master gates EDI: a customer with an order block or in the wrong sales area should stop onboarding, not fail at the first order.

### Questions to ask

1. Which of our partners send EDI today, through which provider, and what does each one cost us per year?
2. Which partners could send our own part numbers, so their agreement needs no cross-reference?
3. What are the entry rules for a new partner, and who checks them before an agreement is activated?
4. Who watches interchanges that fail before they are linked to any partner?
5. For each error category, who fixes it: our team or the partner? Who tells the partner?
6. Who renews AS2 certificates, and how much warning do we get?
7. Does the plan we license include Trading Partner Management and the AS2 adapter?
8. Do we let Integration Advisor's proposal service learn from our guidelines, and who decided?

### Common misconceptions

- **"EDI is a standard, so every partner sends the same thing."** The standard allows many readings. Each partner's guideline narrows it, and they differ.
- **"One flow per partner is simpler."** It is simpler for the first three. After that, every fix is copied by hand, and one copy gets forgotten.
- **"Retrying a failed order will fix it."** It fixes a receiver that was down. It never fixes a missing mapping or a wrong unit.
- **"The acknowledgment means the order was accepted."** A technical acknowledgment says the message was readable. Whether Calder can sell the parts is a different question.
- **"Onboarding is an IT task."** Most onboarding failures are business data: a blocked customer, a missing contact, an unknown part.

### Key terms

- **EDI (electronic data interchange):** business documents exchanged between companies in an agreed standard format.
- **Interchange:** one transmission between partners; it holds an envelope and one or more messages.
- **Trading partner profile:** a partner's identifiers, contacts, systems, certificates and parameters, kept once.
- **Agreement template:** the reusable definition of one kind of exchange, whose settings act as defaults.
- **Agreement:** a template applied to one partner, with that partner's own values; only an activated agreement processes messages.
- **MIG (message implementation guideline):** your organization's reading of one standard message: what is required and which codes are allowed.
- **MAG (mapping guideline):** the mapping from a source MIG to a target MIG, with code value mappings.
- **Functional acknowledgment:** a message sent back to say whether an interchange was syntactically acceptable; in UN/EDIFACT it is `CONTRL`.
- **AS2:** a protocol that sends EDI over HTTP with signing, encryption and a signed receipt.

### Check yourself

1. What makes EDI with forty partners cheaper than forty separate projects?
   - A. Asking every partner to switch to the same EDI provider as Calder
   - B. Setting up guidelines and templates once, so each partner adds only its own values
   - C. Building one flow per partner so that a change never affects anyone else
   - D. Sending each partner's orders by email until its volume justifies EDI

   Answer: B. Templates, MIGs and MAGs are set up once; an agreement per partner adds only the partner's identifiers, customer number and part numbers. One flow per partner means every fix is copied by hand.

2. Hallam starts sending a part number Calder has never mapped. What fixes the failed order?
   - A. Retrying the interchange until the order goes through
   - B. Asking Hallam to send the same interchange again
   - C. Adding the part to Hallam's agreement, then reprocessing the message
   - D. Turning off validation for Hallam's agreement for a week

   Answer: C. The mapping is Calder's data, so Calder fixes it in Hallam's agreement. A retry or a resend maps the same part again and fails the same way.

3. A new distributor's first order fails before it is linked to any partner. What is the main risk?
   - A. The distributor is charged twice for the same order
   - B. SAP deletes the message after one hour without a trace
   - C. Nobody hears about it unless someone watches that list
   - D. The order is created under the wrong customer number

   Answer: C. A message that matches no agreement isn't attached to a partner, so partner-based alerts don't fire. Someone must own the list of such interchanges.

4. Which onboarding problem is business data, not IT?
   - A. The partner's AS2 certificate is close to expiry
   - B. The customer behind the partner has an order block
   - C. The partner's test interchange has a wrong segment count
   - D. The generic flows need a newer package version

   Answer: B. An order block on the customer is a decision in the customer master, owned by sales or credit. Onboarding should stop on it instead of letting the first real order fail.

5. What does a functional acknowledgment such as CONTRL tell the partner?
   - A. That Calder has confirmed delivery dates for every line
   - B. That a person at Calder has read and approved the order
   - C. That the sales order exists in S/4HANA with its number
   - D. That the interchange was readable and syntactically acceptable

   Answer: D. CONTRL reports on syntax, not business content. A readable order can still fail later on a mapping or be blocked for credit.

6. Before planning Trading Partner Management for all distributors, what should a leader confirm?
   - A. That every distributor will send Calder's own part numbers
   - B. That the licensed plan includes it and the AS2 adapter
   - C. That SAP will build the agreements for the first partners
   - D. That Integration Advisor is switched off for all users

   Answer: B. SAP's pricing page lists trading partner management as a plan feature, and SAP says the AS2 adapter depends on the service plan. Check both before the design depends on them.

## Deep layer

### Mental model

**Configuration, not code, per partner.** A partner is a set of values: who they are on the wire, which customer they are in S/4HANA, which part numbers they use, how they connect, and whom to call. The exchange is a set of rules: which message, which guideline, which mapping, whether to acknowledge. Trading Partner Management keeps the two apart. An agreement joins them, and activation turns the joined result into runtime settings that SAP's generic flows read for each incoming message.

So a new partner is a data change with checks, not a development project. And every incoming message must answer one question first: **which agreement is this?** Everything that goes wrong in B2B traces back to one of three answers: no agreement, the wrong agreement, or the right agreement with wrong data in it.

### How it works

#### The objects

SAP's documentation describes these objects ([concepts](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/understanding-the-basic-concepts-74c068d.md)):

| Object | What it is | In Calder's lab |
| --- | --- | --- |
| Company profile | Your own company: identifiers, systems, contacts, number ranges | `tpm/company.json` |
| Trading partner profile | One partner: overview, contacts, identifiers, business context, systems, certificates, parameters, security, number ranges | `tpm/partners/HALLAMFS.json` |
| Identifier | Identification plus type system, scheme and agency; the sender or receiver ID on the wire | `HALLAMFS` in UN/EDIFACT with scheme `ZZZ` |
| Agreement template | One or more business transactions with defaults; an initiator; version 1.0 by default | `TPL_Distributor_ORDERS_Inbound` |
| Business transaction | One-way or two-way; your company is initiator or reactor | Distributor purchase order, one-way, Calder reacts |
| Agreement | A template applied to one partner, with overrides and parameters | `AGR-HALLAMFS-ORDERS` |
| MIG, MAG | Built in Integration Advisor, referenced by the transaction's interchange and mapping steps | Rules inside the template and the agreement |
| Partner Directory | Cloud Integration's per-tenant store; activation writes the agreement's runtime data there | The agreement files the lab reads |

A **business transaction step** has the parts you would expect: source system and its MIG, source protocol, source interchange, mapping, target interchange (and whether to acknowledge), target protocol, target system. A one-way transaction has one activity; a two-way transaction, such as an order with an order response, has two.

#### The runtime

Activation doesn't generate a flow per partner. SAP ships a configure-only package, **Cloud Integration - Trading Partner Management V2**, with generic flows in three steps joined by message queues ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/integration-flow-configuration-version-2-0-6d4cdd1.md)):

```mermaid
flowchart LR
  P[Partner<br/>AS2] --> S1[Step 1<br/>sender flow]
  S1 --> Q1[(inbound<br/>queue)]
  Q1 --> S2[Step 2<br/>interchange processing]
  PD[(Partner Directory<br/>from activated agreements)] -.read.-> S2
  S2 --> Q2[(outbound<br/>queue)]
  Q2 --> S3[Step 3<br/>receiver flow]
  S3 --> T[Target<br/>I10 flow, IDoc or SOAP]
  S2 -.CONTRL.-> P
```

- **Step 1** receives the interchange. SAP lists sender flows for AS2, AS2 MDN (the signed receipt), IDoc, SOAP and ProcessDirect, so another protocol such as SFTP reaches Step 1 through a custom flow you write.
- **Step 2** identifies the agreement from the message, validates it against the source MIG, maps it with the MAG and builds the target interchange. Custom pre- and post-processing flows can be plugged in over ProcessDirect.
- **Step 3** sends the result to the receiver: SOAP, AS2, IDoc or ProcessDirect.

The queues mean a down receiver doesn't lose a message, and the B2B monitor can reprocess from either side of the mapping.

#### Inside Step 2

The transaction's settings decide what Step 2 does ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/creating-b2b-transactions-e1de659.md)):

| Setting | What it does | Calder's choice |
| --- | --- | --- |
| Transaction mode | *Message* (the default) rejects only a faulty message; *Interchange* rejects the whole interchange if one message fails | *Message*: one bad order shouldn't hold back three good ones |
| Syntax validation | The EDI splitter checks the envelope and segments; on by default | On |
| Payload validation | Checks the content against the MIG; can stop processing on failure | On, stop on failure |
| Usage indicator | For UN/EDIFACT, the last element of `UNB`: `1` means test | Read on every interchange |
| Send test interchange to target | Whether test interchanges reach the receiver | No |
| Create functional acknowledgment | Builds `CONTRL` back to the partner, numbered from a number range | Yes, from Calder's range |
| Custom search attributes | Extra fields, such as the PO number, to search the monitor by | PO number |

#### The functional acknowledgment

For UN/EDIFACT, the acknowledgment is a `CONTRL` message. GS1's EANCOM guide describes it as reporting on the syntax of a received interchange, not its business content; application-level errors belong in another message ([GS1](https://www.gs1.org/sites/default/files/docs/eancom/s4/contrl.pdf)). A `UCI` segment answers for the interchange and a `UCM` segment for each message, with action code `7` for acknowledged, `4` for rejected and `8` for received only.

That limit matters for Calder. An order with an unmapped part is syntactically fine: `CONTRL` says `7` for it, and the failure shows in the B2B monitor. The person who must act on it is inside Calder, and the partner's contact must be told separately.

#### Versions and activation

Agreement templates and agreements have versions ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/versioning-in-trading-partner-management-09685b7.md)):

- A new artifact is a **draft**. *Save as New Version* makes 1.0, then 2.0, and so on; a versioned artifact is read only.
- There is at most one draft and at most five numbered versions per artifact.
- SAP recommends creating and versioning in the development tenant and transporting to the others, never developing in parallel.
- Only one version of an agreement is active at a time. Activating one undeploys the others from the Partner Directory.

Activation has two modes: *Default* activates the agreement and its communication channels; *Full* also activates referenced identifier groups, security configurations and custom rules. A cross action activates or deactivates many agreements at once, at most 300 per run ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/activate-deactivate-agreements-e068e37.md)).

#### When things fail

The B2B monitor files failed interchanges under error categories, among them *Interchange Validation Failed*, *Interchange Mapping Failed* and *Interchange Transmission Failed*. An interchange that fails before a business document is attached, for example while its metadata is extracted, appears under **unassigned interchanges** ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/monitor-unassigned-interchanges-c86bd69.md)).

Reprocessing has three actions ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/restart-or-retry-or-duplicate-and-retry-interchanges-8626727.md)):

| Action | Starts from | Runs the mapping again | Use it when |
| --- | --- | --- | --- |
| Restart | The sender payload | Yes | You fixed a mapping or agreement and the message must be mapped again |
| Retry | The receiver payload | No | The receiver was down; the mapping was right |
| Duplicate and Retry | A completed interchange, copied | Depends on the copy | A completed message must be sent again, keeping the original's history |

Each action asks for a reason and can't be undone. The pattern to remember: **restart after a fix on your side, retry after an outage, and neither for a partner's bad data.**

### Build it yourself: run Calder's distributor EDI as profiles and agreements

You will model Calder's distributor orders the way Trading Partner Management does: a company profile, Hallam's partner profile, one agreement template and Hallam's agreement. Then you will push three interchanges through it, read the monitor, fix a mapping with a new agreement version, restart the failed order, and onboard five new distributors from a spreadsheet with entry rules.

```mermaid
flowchart LR
  E[edi_lab.py<br/>from the setup] --> L[tpm_lab.py]
  I[--init] --> F[profiles, template,<br/>agreement, samples]
  F --> L
  L --> M[monitor.jsonl]
  L --> C[CONTRL and orders<br/>in tpm/out/]
  S[distributors.csv] --> O[--onboard<br/>rules O01-O08]
  O --> D[profiles and<br/>draft agreements]
  D --> T[--test, --activate-ready]
```

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 26](https://erpfde.com/topics/set-up-for-unit-26/). This lab reuses the setup's `unit26/edi_lab.py` to read EDIFACT, so it must be in your `unit26` folder. The setup's exercise is not required.

> **Note** New words. A **profile** and an **agreement** here are JSON files in a course format that mirrors SAP's objects; they are not SAP's export format. The **B2B monitor** here is a file, `tpm/monitor.jsonl`, with one line per event; the newest line for a message ID is its current status. **S4P** stands for Calder's production S/4HANA order inbound; in the lab, a delivered order is a JSON file in `tpm/out/`. **Exit code** `2` means at least one message failed, which a pipeline can use to raise an alert.

#### What you need

- Python and your `orchestrate-course` folder with its `.venv`, from the setup topics.
- No account, no network and no new libraries: the script uses Python's built-in modules only and has no randomness. Nothing to add to `requirements.txt`.
- About 40 minutes. Everything is free.

#### Step 1: Open the course folder and turn on the virtual environment

1. Open VS Code, choose **File > Open Folder**, and open `orchestrate-course`.
2. Open a terminal: **Terminal > New Terminal**.
3. If the prompt doesn't start with `(.venv)`, turn it on:

   - **Windows (PowerShell):**

     ```powershell
     .venv\Scripts\Activate.ps1
     ```

   - **macOS / Linux:**

     ```bash
     source .venv/bin/activate
     ```

4. Check that the setup's EDI lab is there:

   - **Windows (PowerShell):**

     ```powershell
     Test-Path unit26\edi_lab.py
     ```

   - **macOS / Linux:**

     ```bash
     ls unit26/edi_lab.py
     ```

   PowerShell prints `True`; macOS and Linux print the file name. If not, do Step 2 of the setup topic first.

#### Step 2: Create the script

1. In VS Code, create `unit26/tpm_lab.py`, paste the code below and save:

```python
"""A trading partner lab for Unit 26: profiles, an agreement template, agreements, a B2B monitor.

Run from your course folder (needs unit26/edi_lab.py from Set up for Unit 26):
    python unit26/tpm_lab.py --init                  # write Calder's profile, Hallam, the template, samples
    python unit26/tpm_lab.py --run FILE              # process one interchange through the active agreements
    python unit26/tpm_lab.py --monitor               # list what the B2B monitor holds
    python unit26/tpm_lab.py --map AGREEMENT PART MATERIAL   # change a part mapping in the agreement's draft
    python unit26/tpm_lab.py --version AGREEMENT     # save the draft as the next numbered version
    python unit26/tpm_lab.py --activate AGREEMENT    # activate the newest numbered version
    python unit26/tpm_lab.py --restart ID            # process a failed message again from its sender payload
    python unit26/tpm_lab.py --retry ID              # deliver a stored result again, without mapping
    python unit26/tpm_lab.py --onboard               # check the onboarding sheet, write profiles and drafts
    python unit26/tpm_lab.py --test PARTNER          # run a partner's test interchange
    python unit26/tpm_lab.py --activate-ready        # version and activate every agreement that is ready
    python unit26/tpm_lab.py --agreements            # list agreements, versions and status
    python unit26/tpm_lab.py --selftest              # check the rules in a temporary folder

Built-in Python only, no randomness, no account, no network. Calder Pumpworks and every partner are
fictional. Rules O01-O08, file layouts, names and numbers are course values that model SAP's Trading
Partner Management concepts; they are not SAP's formats or APIs.
"""
import argparse
import csv
import datetime
import importlib.util
import json
import os
import pathlib
import shutil
import sys
import tempfile

HERE = pathlib.Path(__file__).resolve().parent
LAB_DATE = datetime.date(2026, 11, 30)  # Monday at Calder; fixed so every run prints the same
MAX_VERSIONS = 5  # SAP keeps at most five numbered versions and one draft per agreement
MAX_BATCH = 300  # SAP's limit for activating agreements in one cross action

ROOT = HERE / "tpm"


def paths(root):
    return {"root": root, "company": root / "company.json", "partners": root / "partners",
            "templates": root / "templates", "agreements": root / "agreements", "inbox": root / "inbox",
            "store": root / "store", "out": root / "out", "monitor": root / "monitor.jsonl",
            "sheet": root / "onboarding" / "distributors.csv", "maps": root / "onboarding"}


def load_edi_lab():
    path = HERE / "edi_lab.py"
    if not path.exists():
        sys.exit("No unit26/edi_lab.py. Complete Set up for Unit 26 first.")
    spec = importlib.util.spec_from_file_location("edi_lab", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


EDI = load_edi_lab()

COMPANY = {
    "name": "Calder Pumpworks Inc.", "short_name": "CP10",
    "identifiers": [{"alias": "CALDER_EDI", "identification": "CALDERCP10", "type_system": "UN/EDIFACT",
                     "scheme": "ZZZ"}],
    "systems": [{"alias": "S4P_ORDERS", "purpose": "sales order inbound of CP10 (files in tpm/out/ here)"}],
    "number_ranges": {"CONTRL_CP10": 1},
}

TEMPLATE = {
    "name": "TPL_Distributor_ORDERS_Inbound", "version": "1.0", "initiator": "trading partner",
    "transaction": {
        "name": "Distributor purchase order", "pattern": "one-way", "my_company_role": "reactor",
        "sender": {"type_system": "UN/EDIFACT", "message": "ORDERS:D:96A:UN",
                   "mig": "MIG_CP_ORDERS_D96A_Distributor 1.0", "functional_ack": "required",
                   "transaction_mode": "message", "send_test_to_target": False},
        "mapping": {"mag": "MAG_CP_ORDERS_D96A_to_CalderOrder 1.0"},
        "receiver": {"system": "S4P_ORDERS", "format": "Calder order JSON (Unit 4 mock format)"}},
    "mig": {"required": ["BGM", "DTM:137", "DTM:2", "NAD:BY", "LIN", "QTY:21", "UNS", "CNT:2"],
            "codes": {"BGM": ["220"], "unit": ["PCE", "EA"]}},
    "defaults": {"sales_area": "CPUS/20/PU", "units": {"PCE": "PC", "EA": "PC"}},
}

HALLAM = {
    "id": "HALLAMFS", "name": "Hallam Fluid Systems", "customer": "10000002",
    "identifiers": [{"alias": "HALLAM_EDI", "identification": "HALLAMFS", "type_system": "UN/EDIFACT",
                     "scheme": "ZZZ"}],
    "contacts": [{"role": "EDI errors", "email": "edi@hallam-fluid.example"}],
    "communication": {"protocol": "AS2", "as2_id": "HALLAMFS-AS2", "certificate_expires": "2027-08-31"},
    "parameters": {"sales_area": "CPUS/20/PU", "part_numbers": "own"},
    "test_passed": "2026-11-23",
}

HALLAM_PARTS = {"HFS-SK-200": "CP-SK200", "HFS-P200": "CP-ES200", "HFS-BRG-6310": "CP-BRG6310"}

# Calder's customer master as the lab sees it (course values from the scenario table).
CUSTOMERS = {
    "10000002": {"name": "Hallam Fluid Systems", "sales_areas": ["CPUS/20/PU", "CPUS/30/SP"], "block": ""},
    "10000031": {"name": "Pellmark Industrial Supply", "sales_areas": ["CPUS/30/SP"], "block": "01"},
    "10000032": {"name": "Quillan Pump Supply", "sales_areas": ["CPUS/20/PU"], "block": ""},
    "10000033": {"name": "Venmoor Industrial Supply", "sales_areas": ["CPUS/20/PU"], "block": ""},
    "10000034": {"name": "Tessaly Flow Parts", "sales_areas": ["CPUS/20/PU"], "block": ""},
    "10000035": {"name": "Hallam Fluid Systems Canada Ltd.", "sales_areas": ["CPUS/20/PU"], "block": ""},
}
MATERIALS = {"CP-SK200", "CP-ES200", "CP-ES300", "CP-BRG6310", "CP-IMP200"}

SHEET = """partner_id,name,customer,sales_area,edi_id,contact_email,as2_id,certificate_expires,part_numbers
QUILLAN,Quillan Pump Supply,10000032,CPUS/20/PU,QUILLANPS,edi@quillan-pump.example,QUILLANPS-AS2,2027-09-30,calder
VENMOOR,Venmoor Industrial Supply,10000033,CPUS/20/PU,VENMOORIS,,VENMOORIS-AS2,2027-06-30,calder
TESSALY,Tessaly Flow Parts,10000034,CPUS/20/PU,TESSALYFP,edi@tessaly-flow.example,TESSALYFP-AS2,2026-12-15,own
PELLMARK,Pellmark Industrial Supply,10000031,CPUS/30/SP,PELLMARKIS,edi@pellmark-supply.example,PELLMARKIS-AS2,2027-05-31,calder
HALLAMCA,Hallam Fluid Systems Canada Ltd.,10000035,CPUS/20/PU,HALLAMFS,edi@hallam-fluid-ca.example,HALLAMCA-AS2,2027-08-31,own
"""
TESSALY_MAP = "partner_part,material\nTFP-4410,CP-SK200\nTFP-7200,CP-ES200\n"


def interchange(sender, ref, messages, test=False):
    """Build an ORDERS interchange. messages: (po, due, [(part, qty, unit)])."""
    lines = ["UNA:+.? '", f"UNB+UNOC:4+{sender}:ZZZ+CALDERCP10:ZZZ+20261130:0710+{ref}"
             + ("++++++1'" if test else "'")]
    for n, (po, due, items) in enumerate(messages, start=1):
        body = [f"UNH+{n}+ORDERS:D:96A:UN'", f"BGM+220+{po}+9'", "DTM+137:20261130:102'",
                f"DTM+2:{due}:102'", f"NAD+BY+{CUSTOMER_OF[sender]}::91'", "NAD+SU+CALDERCP10::91'"]
        for i, (part, qty, unit) in enumerate(items, start=1):
            body += [f"LIN+{i}++{part}:SA'", f"QTY+21:{qty}:{unit}'"]
        body += ["UNS+S'", f"CNT+2:{len(items)}'"]
        body.append(f"UNT+{len(body) + 1}+{n}'")
        lines += body
    lines.append(f"UNZ+{len(messages)}+{ref}'")
    return "\n".join(lines) + "\n"


CUSTOMER_OF = {"HALLAMFS": "10000002", "QUILLANPS": "10000032", "TESSALYFP": "10000034",
               "XYZTRADE": "10009999", "VENMOORIS": "10000033"}

SAMPLES = {
    "hallam_HFS000431.edi": ("HALLAMFS", "HFS000431", [
        ("HFS-PO-8210", "20261210", [("HFS-SK-210", 30, "PCE")]),
        ("HFS-PO-8211", "20261210", [("HFS-P200", 2, "BX")]),
        ("HFS-PO-8212", "20261211", [("HFS-P200", 2, "PCE"), ("HFS-SK-200", 20, "PCE")])], False),
    "hallam_HFS000437.edi": ("HALLAMFS", "HFS000437", [
        ("HFS-PO-8220", "20261214", [("HFS-BRG-6310", 12, "PCE")])], False),
    "unknown_XYZ000001.edi": ("XYZTRADE", "XYZ000001", [("XYZ-PO-0001", "20261215", [("CP-ES200", 1, "PCE")])],
                              False),
    "test_QUILLANPS_QPS000001.edi": ("QUILLANPS", "QPS000001", [
        ("QPS-PO-0001", "20261214", [("CP-ES200", 2, "PCE")])], True),
    "test_TESSALYFP_TFP000001.edi": ("TESSALYFP", "TFP000001", [
        ("TFP-PO-0001", "20261214", [("TFP-4410", 50, "PCE"), ("TFP-7200", 1, "EA")])], True),
    "test_VENMOORIS_VIS000001.edi": ("VENMOORIS", "VIS000001", [
        ("VIS-PO-0001", "20261214", [("CP-SK200", 25, "PCE")])], True),
}


def read_json(path):
    return json.loads(path.read_text(encoding="utf-8"))


def write_json(path, data):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")


def new_agreement(partner, edi_id, parts):
    """A draft agreement: the template's defaults plus what is specific to this partner."""
    return {"id": f"AGR-{edi_id}-ORDERS", "template": f"{TEMPLATE['name']} {TEMPLATE['version']}",
            "partner": partner["id"], "keys": {"sender": edi_id, "recipient": "CALDERCP10",
                                               "message": TEMPLATE["transaction"]["sender"]["message"]},
            "draft": {"customer": partner["customer"], "sales_area": partner["parameters"]["sales_area"],
                      "part_numbers": partner["parameters"]["part_numbers"], "parts": parts,
                      "units": dict(TEMPLATE["defaults"]["units"])},
            "versions": {}, "active": None, "history": []}


def init(p):
    if p["company"].exists():
        print("unit26/tpm/ already exists; delete the folder first to start again.")
        return 1
    write_json(p["company"], COMPANY)
    write_json(p["templates"] / f"{TEMPLATE['name']}.json", TEMPLATE)
    write_json(p["partners"] / "HALLAMFS.json", HALLAM)
    agreement = new_agreement(HALLAM, "HALLAMFS", dict(HALLAM_PARTS))
    agreement["versions"]["1.0"] = agreement.pop("draft")
    agreement["draft"] = None
    agreement["active"] = "1.0"
    agreement["history"].append(f"{LAB_DATE} 1.0 activated (carries the bearing from the setup exercise)")
    write_json(p["agreements"] / f"{agreement['id']}.json", agreement)
    p["inbox"].mkdir(parents=True, exist_ok=True)
    for name, (sender, ref, messages, test) in SAMPLES.items():
        (p["inbox"] / name).write_text(interchange(sender, ref, messages, test), encoding="utf-8")
    p["sheet"].parent.mkdir(parents=True, exist_ok=True)
    p["sheet"].write_text(SHEET, encoding="utf-8")
    (p["maps"] / "TESSALY_parts.csv").write_text(TESSALY_MAP, encoding="utf-8")
    for path in sorted(p["root"].rglob("*")):
        if path.is_file():
            print(f"Wrote {path.relative_to(p['root'].parent.parent).as_posix()}")
    return 0


def agreements(p):
    return {a["id"]: a for a in (read_json(f) for f in sorted(p["agreements"].glob("*.json")))}


def find_agreement(p, sender, recipient, message):
    """Agreement determination: sender identifier, recipient identifier and message type."""
    hits = [a for a in agreements(p).values()
            if a["keys"] == {"sender": sender, "recipient": recipient, "message": message}]
    return hits


def unb_usage(text):
    """Test or production: the last element of UNB, 1 meaning test (as SAP's TPM documentation reads it)."""
    syntax, raw = EDI.split_segments(text)
    tag, data = EDI.parse_segment(raw[0], syntax)
    return "test" if tag == "UNB" and len(data) > 5 and data[-1] == ["1"] else "production"


def mig_check(msg, template):
    """The message implementation guideline: required segments and code values."""
    have = set()
    for tag, data in msg["segments"]:
        have.add(tag)
        if tag in ("DTM", "NAD", "QTY", "CNT"):
            have.add(f"{tag}:{EDI.element(data, 1)}")
        if tag == "BGM" and EDI.element(data, 1) not in template["mig"]["codes"]["BGM"]:
            return f"BGM document code {EDI.element(data, 1)} is not in the MIG"
        if tag == "QTY" and EDI.element(data, 1, 2) not in template["mig"]["codes"]["unit"]:
            return f"unit {EDI.element(data, 1, 2)} is not in the MIG code list"
    missing = [r for r in template["mig"]["required"] if r not in have]
    return f"missing {', '.join(missing)}" if missing else ""


def mag_map(msg, version):
    """The mapping guideline plus the agreement's partner-specific values."""
    order = {"SoldToParty": version["customer"], "SalesArea": version["sales_area"],
             "PurchaseOrderByCustomer": "", "RequestedDeliveryDate": "", "Items": []}
    for tag, data in msg["segments"]:
        if tag == "BGM":
            order["PurchaseOrderByCustomer"] = EDI.element(data, 2)
        elif tag == "DTM" and EDI.element(data, 1) == "2":
            v = EDI.element(data, 1, 1)
            order["RequestedDeliveryDate"] = f"{v[:4]}-{v[4:6]}-{v[6:]}"
        elif tag == "NAD" and EDI.element(data, 1) == "BY" and EDI.element(data, 2) != version["customer"]:
            return None, f"buyer {EDI.element(data, 2)} is not the agreed customer {version['customer']}"
        elif tag == "LIN":
            part = EDI.element(data, 3)
            material = version["parts"].get(part) if version["part_numbers"] == "own" else part
            if material not in MATERIALS:
                return None, f"partner part {part} has no mapping in this agreement version"
            order["Items"].append({"Material": material, "PartnerPart": part})
        elif tag == "QTY":
            unit = EDI.element(data, 1, 2)
            order["Items"][-1].update({"RequestedQuantity": int(EDI.element(data, 1, 1)),
                                       "RequestedQuantityUnit": version["units"][unit]})
    return order, ""


def contrl(p, header, results, envelope_ok):
    """A CONTRL syntax report: UCI 7 or 4 for the interchange, UCM 7 or 4 per message (GS1 codes)."""
    company = read_json(p["company"])
    number = company["number_ranges"]["CONTRL_CP10"]
    company["number_ranges"]["CONTRL_CP10"] = number + 1
    write_json(p["company"], company)
    ref = f"CP{number:07d}"
    seg = [f"UNH+1+CONTRL:D:3:UN'",
           f"UCI+{header.get('reference', '')}+{header.get('sender', '')}+{header.get('recipient', '')}+"
           f"{7 if envelope_ok else 4}'"]
    for msg_ref, syntax_ok in results:
        seg.append(f"UCM+{msg_ref}+ORDERS:D:96A:UN+{7 if syntax_ok else 4}'")
    seg.append(f"UNT+{len(seg) + 1}+1'")
    sender = header.get("sender", "UNKNOWN").split(":")[0]
    text = "\n".join([f"UNB+UNOC:4+CALDERCP10:ZZZ+{sender}:ZZZ+20261130:0711+{ref}'"] + seg
                     + [f"UNZ+1+{ref}'"]) + "\n"
    p["out"].mkdir(parents=True, exist_ok=True)
    (p["out"] / f"CONTRL_{header.get('reference', ref)}.edi").write_text(text, encoding="utf-8")
    return ref


def log(p, entry):
    with p["monitor"].open("a", encoding="utf-8") as f:
        f.write(json.dumps(entry) + "\n")


def monitor_rows(p):
    if not p["monitor"].exists():
        return {}
    rows = {}
    for line in p["monitor"].read_text(encoding="utf-8").splitlines():
        entry = json.loads(line)
        rows[entry["id"]] = entry  # the newest line per ID wins
    return rows


def deliver(p, order):
    """The receiver: one file per customer and PO. A second delivery of the same order is refused."""
    path = p["out"] / f"{order['SoldToParty']}_{order['PurchaseOrderByCustomer']}.json"
    if path.exists():
        return "duplicate: the receiver already holds this order"
    write_json(path, order)
    return ""


def process(p, text, ic_id, source, receiver_down=False, only=None, quiet=False):
    """Process one interchange as a generic flow would: determine, check, map, deliver, acknowledge."""
    say = (lambda *_: None) if quiet else print
    header, messages, problems = EDI.read_interchange(text)
    sender = header.get("sender", "").split(":")[0]
    recipient = header.get("recipient", "").split(":")[0]
    usage = unb_usage(text) if not problems else "production"
    if only is None:
        say(f"{ic_id}  interchange {header.get('reference', '?')} from {sender or '?'}, {usage}, "
            f"{len(messages)} message(s)")
    if problems:
        say(f"  FAILED       envelope: {problems[0]}")
        contrl(p, header, [], envelope_ok=False)
        log(p, {"id": ic_id, "status": "Failed", "category": "envelope", "detail": problems[0], "source": source})
        return {"failed": 1}
    hits = find_agreement(p, sender, recipient, messages[0]["type"] if messages else "")
    if len(hits) != 1:
        detail = "no active agreement for these identifiers" if not hits else \
            f"{len(hits)} agreements share these identifiers"
        say(f"  UNASSIGNED   {detail}; nobody is told unless someone watches this list")
        log(p, {"id": ic_id, "status": "Failed", "category": "unassigned", "detail": detail, "source": source,
                "sender": sender})
        return {"failed": 1}
    agreement = hits[0]
    # Production uses the active version; a test runs on the draft when there is one.
    if usage == "production" or not agreement["draft"]:
        version_no = agreement["active"]
    else:
        version_no = "draft"
    version = agreement["versions"].get(version_no) if version_no != "draft" else agreement["draft"]
    if version is None:
        say(f"  UNASSIGNED   agreement {agreement['id']} has no active version")
        log(p, {"id": ic_id, "status": "Failed", "category": "unassigned", "detail": "agreement not active",
                "source": source, "sender": sender})
        return {"failed": 1}
    template = read_json(p["templates"] / f"{TEMPLATE['name']}.json")
    counts, syntax = {"completed": 0, "failed": 0}, []
    for msg in messages:
        msg_id = f"{ic_id}/{msg['ref']}"
        if only and msg_id != only:
            continue
        po = next((EDI.element(d, 2) for t, d in msg["segments"] if t == "BGM"), "?")
        unt = msg["segments"][-1][1]
        syntax_ok = EDI.element(unt, 1) == str(len(msg["segments"]))
        syntax.append((msg["ref"], syntax_ok))
        entry = {"id": msg_id, "po": po, "sender": sender, "agreement": agreement["id"],
                 "version": version_no, "usage": usage, "source": source}
        if not syntax_ok:
            status, category, detail, order = "Failed", "validation", "UNT segment count is wrong", None
        else:
            detail = mig_check(msg, template)
            category = "validation" if detail else ""
            order = None
            if not detail:
                order, detail = mag_map(msg, version)
                category = "mapping" if detail else ""
            status = "Failed" if detail else "Completed"
        if status == "Completed":
            if usage == "test" and not template["transaction"]["sender"]["send_test_to_target"]:
                detail = "test interchange: checked and mapped, not sent to S4P"
            elif receiver_down:
                status, category, detail = "Failed", "transmission", "S4P did not answer"
            else:
                detail = deliver(p, order) or "delivered to S4P"
                status, category = ("Completed", "") if detail == "delivered to S4P" else ("Failed", "duplicate")
        if order is not None:
            write_json(p["store"] / f"{msg_id.replace('/', '_')}.json", order)
        entry.update({"status": status, "category": category, "detail": detail})
        log(p, entry)
        counts["completed" if status == "Completed" else "failed"] += 1
        owner = {"validation": "partner sends a corrected order",
                 "mapping": "Calder maps it, then restart",
                 "transmission": "retry once S4P is back",
                 "duplicate": "nothing to fix: the partner sent it again"}.get(category, "")
        say(f"  {status.upper():<12} {msg_id:<10} {po:<12} {category or 'ok':<12} {detail}"
            + (f"\n{'':<15}-> {owner}" if owner else ""))
    if only is None:
        ref = contrl(p, header, syntax, envelope_ok=True)
        say(f"  CONTRL {ref} to {sender}: UCI 7, UCM " + ", ".join(f"{r}={7 if ok else 4}" for r, ok in syntax)
            + " (written to tpm/out/)")
        say(f"{counts['completed']} completed, {counts['failed']} failed (synthetic)")
    return counts


def next_ic(p):
    ids = {i.split("/")[0] for i in monitor_rows(p)}
    return f"IC-{len(ids) + 1:04d}"


def run(p, file, receiver_down=False, quiet=False):
    path = pathlib.Path(file)
    if not path.exists():
        print(f"{file} not found. Run --init first, from your course folder.")
        return {"failed": 1}
    ic_id = next_ic(p)
    p["store"].mkdir(parents=True, exist_ok=True)
    shutil.copyfile(path, p["store"] / f"{ic_id}.edi")  # keep the sender payload for a restart
    return process(p, path.read_text(encoding="utf-8"), ic_id, path.name, receiver_down, quiet=quiet)


def restart(p, msg_id):
    row = monitor_rows(p).get(msg_id)
    if not row or row["status"] != "Failed":
        print(f"{msg_id} is not a failed message in the monitor.")
        return 1
    if row["category"] == "validation":
        print(f"{msg_id} failed the MIG check. A restart maps the same wrong data again; ask the partner to "
              "send a corrected order.")
        return 1
    text = (p["store"] / f"{msg_id.split('/')[0]}.edi").read_text(encoding="utf-8")
    print(f"Restart {msg_id} from the stored sender payload, with today's active agreement version:")
    counts = process(p, text, msg_id.split("/")[0], row["source"], only=msg_id)
    return 0 if counts["failed"] == 0 else 2


def retry(p, msg_id):
    row = monitor_rows(p).get(msg_id)
    stored = p["store"] / f"{msg_id.replace('/', '_')}.json"
    if not row or row["category"] != "transmission" or not stored.exists():
        print(f"{msg_id} has no mapped result waiting for delivery. Retry only resends; use --restart "
              "after a mapping fix.")
        return 1
    detail = deliver(p, read_json(stored))
    row.update({"status": "Failed" if detail else "Completed", "category": "duplicate" if detail else "",
                "detail": detail or "delivered on retry, mapping not run again"})
    log(p, row)
    print(f"  {row['status'].upper():<12} {msg_id:<10} {row['po']:<12} {row['detail']}")
    return 0


def show_monitor(p):
    rows = monitor_rows(p)
    print(f"{'ID':<10} {'Status':<10} {'Category':<12} {'PO':<12} {'Agreement':<22} Version")
    for row in rows.values():
        print(f"{row['id']:<10} {row['status']:<10} {row['category'] or '-':<12} {row.get('po', '-'):<12} "
              f"{row.get('agreement', '-'):<22} {row.get('version', '-')}")
    failed = sum(1 for r in rows.values() if r["status"] == "Failed")
    print(f"{len(rows)} entries, {failed} failed")
    return 0


def edit_map(p, agreement_id, part, material):
    path = p["agreements"] / f"{agreement_id}.json"
    if not path.exists():
        print(f"No agreement {agreement_id}.")
        return 1
    if material not in MATERIALS:
        print(f"{material} is not a Calder material. Ask master data first.")
        return 1
    agreement = read_json(path)
    if agreement["draft"] is None:
        newest = max(agreement["versions"], key=float)
        agreement["draft"] = json.loads(json.dumps(agreement["versions"][newest]))  # copy to draft
        print(f"Copied version {newest} to a new draft.")
    agreement["draft"]["parts"][part] = material
    agreement["history"].append(f"{LAB_DATE} draft: {part} -> {material}")
    write_json(path, agreement)
    print(f"Draft of {agreement_id}: {part} -> {material}. Version and activate it before it is used.")
    return 0


def save_version(p, agreement_id, quiet=False):
    path = p["agreements"] / f"{agreement_id}.json"
    agreement = read_json(path)
    if agreement["draft"] is None:
        print(f"{agreement_id} has no draft to version.")
        return 1
    if len(agreement["versions"]) >= MAX_VERSIONS:
        print(f"{agreement_id} already has {MAX_VERSIONS} numbered versions; delete an old one first.")
        return 1
    number = f"{int(max(map(float, agreement['versions']), default=0)) + 1}.0"
    agreement["versions"][number] = agreement["draft"]
    agreement["draft"] = None
    agreement["history"].append(f"{LAB_DATE} saved as version {number}")
    write_json(path, agreement)
    if not quiet:
        print(f"{agreement_id}: saved draft as version {number} (read only from now on).")
    return 0


def activate(p, agreement_id, quiet=False):
    path = p["agreements"] / f"{agreement_id}.json"
    agreement = read_json(path)
    partner = read_json(p["partners"] / f"{agreement['partner']}.json")
    if not agreement["versions"]:
        print(f"{agreement_id}: no numbered version yet. Course rule O07: activate only a numbered version.")
        return 1
    if not partner.get("test_passed"):
        print(f"{agreement_id}: course rule O06: run --test {agreement['partner']} first.")
        return 1
    expires = datetime.date.fromisoformat(partner["communication"]["certificate_expires"])
    if (expires - LAB_DATE).days < 30:
        print(f"{agreement_id}: course rule O04: AS2 certificate expires {expires}; get the renewed one first.")
        return 1
    newest = max(agreement["versions"], key=float)
    old = agreement["active"]
    agreement["active"] = newest
    agreement["history"].append(f"{LAB_DATE} {newest} activated" + (f", {old} deactivated" if old else ""))
    write_json(path, agreement)
    if not quiet:
        print(f"{agreement_id}: version {newest} active" + (f" (was {old})." if old else "."))
    return 0


def check_partner(row, profiles, sheet_rows, p):
    """Onboarding rules O01-O05 and O08 (course rules). Returns [(rule, level, text)]."""
    found = []
    customer = CUSTOMERS.get(row["customer"])
    if not customer:
        found.append(("O01", "FAIL", f"customer {row['customer']} does not exist"))
    elif customer["block"]:
        found.append(("O01", "FAIL", f"customer {row['customer']} has order block {customer['block']}"))
    elif row["sales_area"] not in customer["sales_areas"]:
        found.append(("O01", "FAIL", f"customer {row['customer']} is not set up in {row['sales_area']}"))
    taken = {i["identification"]: pid for pid, prof in profiles.items() for i in prof["identifiers"]}
    twins = [r["partner_id"] for r in sheet_rows if r["edi_id"] == row["edi_id"] and r is not row]
    if row["edi_id"] in taken and taken[row["edi_id"]] != row["partner_id"]:
        found.append(("O02", "FAIL", f"EDI identifier {row['edi_id']} already belongs to {taken[row['edi_id']]}"))
    elif twins:
        found.append(("O02", "FAIL", f"EDI identifier {row['edi_id']} also on the sheet for {twins[0]}"))
    if not row["contact_email"]:
        found.append(("O03", "FAIL", "no contact for EDI errors"))
    expires = datetime.date.fromisoformat(row["certificate_expires"])
    if (expires - LAB_DATE).days < 30:
        found.append(("O04", "WARN", f"AS2 certificate expires {expires}, in {(expires - LAB_DATE).days} days"))
    if row["part_numbers"] == "own" and not (p["maps"] / f"{row['partner_id']}_parts.csv").exists():
        found.append(("O05", "FAIL", f"own part numbers but no {row['partner_id']}_parts.csv"))
    if row["sales_area"] != TEMPLATE["defaults"]["sales_area"]:
        found.append(("O08", "FAIL", f"sales area {row['sales_area']} is not the template's "
                                     f"{TEMPLATE['defaults']['sales_area']}"))
    return found


def onboard(p, quiet=False):
    say = (lambda *_: None) if quiet else print
    rows = list(csv.DictReader(p["sheet"].open(encoding="utf-8")))
    profiles = {f.stem: read_json(f) for f in p["partners"].glob("*.json")}
    ready = 0
    for row in rows:
        found = check_partner(row, profiles, rows, p)
        fails = [f for f in found if f[1] == "FAIL"]
        verdict = "NOT READY" if fails else ("READY, WARN" if found else "READY")
        say(f"{row['partner_id']:<9} {row['name']:<34} {verdict}")
        for rule, level, text in found:
            say(f"    {rule} {level:<4} {text}")
        if fails:
            continue
        ready += 1
        parts = {}
        if row["part_numbers"] == "own":
            with (p["maps"] / f"{row['partner_id']}_parts.csv").open(encoding="utf-8") as f:
                parts = {r["partner_part"]: r["material"] for r in csv.DictReader(f)}
        profile = {"id": row["partner_id"], "name": row["name"], "customer": row["customer"],
                   "identifiers": [{"alias": f"{row['partner_id']}_EDI", "identification": row["edi_id"],
                                    "type_system": "UN/EDIFACT", "scheme": "ZZZ"}],
                   "contacts": [{"role": "EDI errors", "email": row["contact_email"]}],
                   "communication": {"protocol": "AS2", "as2_id": row["as2_id"],
                                     "certificate_expires": row["certificate_expires"]},
                   "parameters": {"sales_area": row["sales_area"], "part_numbers": row["part_numbers"]},
                   "test_passed": profiles.get(row["partner_id"], {}).get("test_passed", "")}
        write_json(p["partners"] / f"{row['partner_id']}.json", profile)
        path = p["agreements"] / f"AGR-{row['edi_id']}-ORDERS.json"
        if not path.exists():
            write_json(path, new_agreement(profile, row["edi_id"], parts))
        profiles[row["partner_id"]] = profile
    say(f"{len(rows)} partners on the sheet: {ready} ready, {len(rows) - ready} not ready. "
        f"Profiles and draft agreements written for the ready ones.")
    return ready


def test_partner(p, partner_id, quiet=False):
    path = p["partners"] / f"{partner_id}.json"
    if not path.exists():
        print(f"No profile for {partner_id}. Run --onboard first; a NOT READY partner gets no profile.")
        return 1
    profile = read_json(path)
    edi_id = profile["identifiers"][0]["identification"]
    files = sorted(p["inbox"].glob(f"test_{edi_id}_*.edi"))
    if not files:
        print(f"No test interchange from {edi_id} in tpm/inbox/.")
        return 1
    counts = run(p, files[0], quiet=quiet)
    if counts["failed"] == 0:
        profile["test_passed"] = str(LAB_DATE)
        write_json(path, profile)
        if not quiet:
            print(f"{partner_id}: test passed on {LAB_DATE}; nothing was sent to S4P.")
        return 0
    print(f"{partner_id}: test failed; fix and run --test again.")
    return 1


def activate_ready(p, quiet=False):
    done, waiting = [], []
    for agreement in agreements(p).values():
        partner = read_json(p["partners"] / f"{agreement['partner']}.json")
        if agreement["active"] and agreement["draft"] is None:
            continue
        if not partner.get("test_passed"):
            waiting.append(f"{agreement['id']} (no passed test)")
            continue
        if len(done) >= MAX_BATCH:
            waiting.append(f"{agreement['id']} (batch full)")
            continue
        expires = datetime.date.fromisoformat(partner["communication"]["certificate_expires"])
        if (expires - LAB_DATE).days < 30:
            waiting.append(f"{agreement['id']} (certificate expires {expires})")
            continue
        if agreement["draft"] is not None:
            save_version(p, agreement["id"], quiet=True)
        activate(p, agreement["id"], quiet=True)
        done.append(agreement["id"])
    if not quiet:
        print(f"Activated {len(done)}: {', '.join(done) or '-'}")
        print(f"Waiting {len(waiting)}: {', '.join(waiting) or '-'}")
    return done


def list_agreements(p):
    print(f"{'Agreement':<24} {'Partner':<9} {'Active':<7} {'Versions':<12} {'Draft':<6} Parts")
    for a in agreements(p).values():
        current = a["versions"].get(a["active"]) if a["active"] else a["draft"]
        parts = len(current["parts"]) if current["part_numbers"] == "own" else "Calder's"
        print(f"{a['id']:<24} {a['partner']:<9} {a['active'] or '-':<7} "
              f"{', '.join(sorted(a['versions'], key=float)) or '-':<12} {'yes' if a['draft'] else 'no':<6} {parts}")
    return 0


def selftest():
    with tempfile.TemporaryDirectory() as tmp:
        p = paths(pathlib.Path(tmp) / "unit26" / "tpm")
        real_stdout = sys.stdout
        try:
            sys.stdout = open(os.devnull, "w")
            init(p)
        finally:
            sys.stdout.close()
            sys.stdout = real_stdout
        inbox = p["inbox"]
        checks = []
        c = process(p, (HERE / "edi" / "hallam_orders_HFS000417.edi").read_text(encoding="utf-8")
                    if (HERE / "edi" / "hallam_orders_HFS000417.edi").exists()
                    else interchange("HALLAMFS", "HFS000417", [("HFS-PO-8201", "20261204",
                                                               [("HFS-SK-200", 40, "PCE")])]),
                    "IC-0001", "setup sample", quiet=True)
        checks.append(("setup interchange completes", c["failed"] == 0))
        c = process(p, (inbox / "hallam_HFS000431.edi").read_text(), "IC-0002", "s", quiet=True)
        checks.append(("HFS000431: 1 completed, 2 failed", (c["completed"], c["failed"]) == (1, 2)))
        rows = monitor_rows(p)
        checks.append(("unit BX is a validation failure", rows["IC-0002/2"]["category"] == "validation"))
        checks.append(("HFS-SK-210 is a mapping failure", rows["IC-0002/1"]["category"] == "mapping"))
        c = process(p, (inbox / "unknown_XYZ000001.edi").read_text(), "IC-0003", "s", quiet=True)
        checks.append(("unknown sender is unassigned", monitor_rows(p)["IC-0003"]["category"] == "unassigned"))
        bad = (inbox / "hallam_HFS000431.edi").read_text().replace("UNT+11+1'", "UNT+10+1'")
        process(p, bad, "IC-0004", "s", quiet=True)
        checks.append(("wrong UNT count gives UCM 4", "UCM+1+ORDERS:D:96A:UN+4'" in
                       (p["out"] / "CONTRL_HFS000431.edi").read_text()))
        checks.append(("five partners: two ready", onboard(p, quiet=True) == 2))
        checks.append(("test runs on the draft, sends nothing",
                       test_partner(p, "QUILLAN", quiet=True) == 0 and
                       not (p["out"] / "10000032_QPS-PO-0001.json").exists()))
        done = activate_ready(p, quiet=True)
        test_partner(p, "TESSALY", quiet=True)
        done = done + activate_ready(p, quiet=True)
        checks.append(("tested partner activated, expiring certificate held", done == ["AGR-QUILLANPS-ORDERS"]))
    failed = [name for name, ok in checks if not ok]
    for name, ok in checks:
        print(f"  {'OK' if ok else 'FAIL':<5} {name}")
    print("Self-test passed." if not failed else f"Self-test: {len(failed)} check(s) failed.")
    return 0 if not failed else 2


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--init", action="store_true")
    parser.add_argument("--run", metavar="FILE")
    parser.add_argument("--receiver-down", action="store_true", help="with --run: S4P does not answer")
    parser.add_argument("--monitor", action="store_true")
    parser.add_argument("--map", nargs=3, metavar=("AGREEMENT", "PART", "MATERIAL"))
    parser.add_argument("--version", metavar="AGREEMENT")
    parser.add_argument("--activate", metavar="AGREEMENT")
    parser.add_argument("--restart", metavar="ID")
    parser.add_argument("--retry", metavar="ID")
    parser.add_argument("--onboard", action="store_true")
    parser.add_argument("--test", metavar="PARTNER")
    parser.add_argument("--activate-ready", action="store_true")
    parser.add_argument("--agreements", action="store_true")
    parser.add_argument("--selftest", action="store_true")
    args = parser.parse_args()
    p = paths(ROOT)
    if args.selftest:
        return selftest()
    if args.init:
        return init(p)
    if not p["company"].exists():
        print("No unit26/tpm/ yet. Run: python unit26/tpm_lab.py --init")
        return 1
    if args.run:
        counts = run(p, args.run, args.receiver_down)
        return 0 if counts["failed"] == 0 else 2
    if args.monitor:
        return show_monitor(p)
    if args.map:
        return edit_map(p, *args.map)
    if args.version:
        return save_version(p, args.version)
    if args.activate:
        return activate(p, args.activate)
    if args.restart:
        return restart(p, args.restart)
    if args.retry:
        return retry(p, args.retry)
    if args.onboard:
        onboard(p)
        return 0
    if args.test:
        return test_partner(p, args.test)
    if args.activate_ready:
        activate_ready(p)
        return 0
    if args.agreements:
        return list_agreements(p)
    parser.print_help()
    return 0


if __name__ == "__main__":
    sys.exit(main())
```

2. Check that it runs, before writing any files:

   ```bash
   python unit26/tpm_lab.py --selftest
   ```

   You should see:

   ```text
     OK    setup interchange completes
     OK    HFS000431: 1 completed, 2 failed
     OK    unit BX is a validation failure
     OK    HFS-SK-210 is a mapping failure
     OK    unknown sender is unassigned
     OK    wrong UNT count gives UCM 4
     OK    five partners: two ready
     OK    test runs on the draft, sends nothing
     OK    tested partner activated, expiring certificate held
   Self-test passed.
   ```

   The self-test builds everything in a temporary folder and deletes it, so your course folder is unchanged.

#### Step 3: Write Calder's setup

1. Run:

   ```bash
   python unit26/tpm_lab.py --init
   ```

   You should see:

   ```text
   Wrote unit26/tpm/agreements/AGR-HALLAMFS-ORDERS.json
   Wrote unit26/tpm/company.json
   Wrote unit26/tpm/inbox/hallam_HFS000431.edi
   Wrote unit26/tpm/inbox/hallam_HFS000437.edi
   Wrote unit26/tpm/inbox/test_QUILLANPS_QPS000001.edi
   Wrote unit26/tpm/inbox/test_TESSALYFP_TFP000001.edi
   Wrote unit26/tpm/inbox/test_VENMOORIS_VIS000001.edi
   Wrote unit26/tpm/inbox/unknown_XYZ000001.edi
   Wrote unit26/tpm/onboarding/TESSALY_parts.csv
   Wrote unit26/tpm/onboarding/distributors.csv
   Wrote unit26/tpm/partners/HALLAMFS.json
   Wrote unit26/tpm/templates/TPL_Distributor_ORDERS_Inbound.json
   ```

2. Open `unit26/tpm/templates/TPL_Distributor_ORDERS_Inbound.json`. This is the part set up once: the message `ORDERS:D:96A:UN`, the MIG's required segments and allowed codes, the MAG's name, transaction mode `message`, a functional acknowledgment, and `send_test_to_target: false`.
3. Open `unit26/tpm/agreements/AGR-HALLAMFS-ORDERS.json`. This is the part per partner: the keys that identify Hallam's messages (sender `HALLAMFS`, recipient `CALDERCP10`, message type), and in version `1.0` Hallam's customer `10000002`, sales area `CPUS/20/PU` and three part numbers. The third, `HFS-BRG-6310`, is the bearing the setup's exercise confirmed.
4. List the agreements:

   ```bash
   python unit26/tpm_lab.py --agreements
   ```

   ```text
   Agreement                Partner   Active  Versions     Draft  Parts
   AGR-HALLAMFS-ORDERS      HALLAMFS  1.0     1.0          no     3
   ```

#### Step 4: Process three interchanges

1. Run the setup's interchange through Hallam's agreement:

   ```bash
   python unit26/tpm_lab.py --run unit26/edi/hallam_orders_HFS000417.edi
   ```

   ```text
   IC-0001  interchange HFS000417 from HALLAMFS, production, 3 message(s)
     COMPLETED    IC-0001/1  HFS-PO-8201  ok           delivered to S4P
     COMPLETED    IC-0001/2  HFS-PO-8202  ok           delivered to S4P
     COMPLETED    IC-0001/3  HFS-PO-8203  ok           delivered to S4P
     CONTRL CP0000001 to HALLAMFS: UCI 7, UCM 1=7, 2=7, 3=7 (written to tpm/out/)
   3 completed, 0 failed (synthetic)
   ```

   All three pass, because the agreement carries the bearing. The acknowledgment's number `CP0000001` comes from Calder's number range in `company.json`.

2. Run Hallam's next interchange:

   ```bash
   python unit26/tpm_lab.py --run unit26/tpm/inbox/hallam_HFS000431.edi
   ```

   ```text
   IC-0002  interchange HFS000431 from HALLAMFS, production, 3 message(s)
     FAILED       IC-0002/1  HFS-PO-8210  mapping      partner part HFS-SK-210 has no mapping in this agreement version
                  -> Calder maps it, then restart
     FAILED       IC-0002/2  HFS-PO-8211  validation   unit BX is not in the MIG code list
                  -> partner sends a corrected order
     COMPLETED    IC-0002/3  HFS-PO-8212  ok           delivered to S4P
     CONTRL CP0000002 to HALLAMFS: UCI 7, UCM 1=7, 2=7, 3=7 (written to tpm/out/)
   1 completed, 2 failed (synthetic)
   ```

   Read the three lines carefully. The transaction mode `message` let the good order through. Two orders failed for different reasons with different owners. And `CONTRL` says `7` for all three, because all three were syntactically fine.

3. Run an interchange from a sender Calder doesn't know:

   ```bash
   python unit26/tpm_lab.py --run unit26/tpm/inbox/unknown_XYZ000001.edi
   ```

   ```text
   IC-0003  interchange XYZ000001 from XYZTRADE, production, 1 message(s)
     UNASSIGNED   no active agreement for these identifiers; nobody is told unless someone watches this list
   ```

   No agreement, so no partner, no contact and no acknowledgment.

4. Open the monitor:

   ```bash
   python unit26/tpm_lab.py --monitor
   ```

   ```text
   ID         Status     Category     PO           Agreement              Version
   IC-0001/1  Completed  -            HFS-PO-8201  AGR-HALLAMFS-ORDERS    1.0
   IC-0001/2  Completed  -            HFS-PO-8202  AGR-HALLAMFS-ORDERS    1.0
   IC-0001/3  Completed  -            HFS-PO-8203  AGR-HALLAMFS-ORDERS    1.0
   IC-0002/1  Failed     mapping      HFS-PO-8210  AGR-HALLAMFS-ORDERS    1.0
   IC-0002/2  Failed     validation   HFS-PO-8211  AGR-HALLAMFS-ORDERS    1.0
   IC-0002/3  Completed  -            HFS-PO-8212  AGR-HALLAMFS-ORDERS    1.0
   IC-0003    Failed     unassigned   -            -                      -
   7 entries, 3 failed
   ```

> **Note** These orders, failures and counts come from made-up interchanges and course rules. They show the method, not results from a real SAP system.

#### Step 5: Fix the mapping with a new agreement version, then restart

Hallam's buyer confirms that `HFS-SK-210` is their new number for Calder's seal kit `CP-SK200`.

1. First, try a restart of the unit error, to see why it is the partner's to fix:

   ```bash
   python unit26/tpm_lab.py --restart IC-0002/2
   ```

   ```text
   IC-0002/2 failed the MIG check. A restart maps the same wrong data again; ask the partner to send a corrected order.
   ```

2. Change the mapping. The agreement's version 1.0 is read only, so the lab copies it to a draft:

   ```bash
   python unit26/tpm_lab.py --map AGR-HALLAMFS-ORDERS HFS-SK-210 CP-SK200
   ```

   ```text
   Copied version 1.0 to a new draft.
   Draft of AGR-HALLAMFS-ORDERS: HFS-SK-210 -> CP-SK200. Version and activate it before it is used.
   ```

3. Restart the mapping error now:

   ```bash
   python unit26/tpm_lab.py --restart IC-0002/1
   ```

   ```text
   Restart IC-0002/1 from the stored sender payload, with today's active agreement version:
     FAILED       IC-0002/1  HFS-PO-8210  mapping      partner part HFS-SK-210 has no mapping in this agreement version
                  -> Calder maps it, then restart
   ```

   It still fails: production uses the active version, and a draft is not active.

4. Save the draft as a version and activate it:

   ```bash
   python unit26/tpm_lab.py --version AGR-HALLAMFS-ORDERS
   python unit26/tpm_lab.py --activate AGR-HALLAMFS-ORDERS
   ```

   ```text
   AGR-HALLAMFS-ORDERS: saved draft as version 2.0 (read only from now on).
   AGR-HALLAMFS-ORDERS: version 2.0 active (was 1.0).
   ```

5. Restart again:

   ```bash
   python unit26/tpm_lab.py --restart IC-0002/1
   ```

   ```text
   Restart IC-0002/1 from the stored sender payload, with today's active agreement version:
     COMPLETED    IC-0002/1  HFS-PO-8210  ok           delivered to S4P
   ```

   The restart started from the stored sender payload and ran the mapping again, as SAP's restart does.

#### Step 6: An outage, a retry and a resend

1. Process one more Hallam order while S/4HANA doesn't answer:

   ```bash
   python unit26/tpm_lab.py --run unit26/tpm/inbox/hallam_HFS000437.edi --receiver-down
   ```

   ```text
   IC-0004  interchange HFS000437 from HALLAMFS, production, 1 message(s)
     FAILED       IC-0004/1  HFS-PO-8220  transmission S4P did not answer
                  -> retry once S4P is back
     CONTRL CP0000003 to HALLAMFS: UCI 7, UCM 1=7 (written to tpm/out/)
   0 completed, 1 failed (synthetic)
   ```

2. When it is back, retry. The mapped order is resent; the mapping doesn't run:

   ```bash
   python unit26/tpm_lab.py --retry IC-0004/1
   ```

   ```text
     COMPLETED    IC-0004/1  HFS-PO-8220  delivered on retry, mapping not run again
   ```

3. Hallam's system resends last week's interchange by mistake:

   ```bash
   python unit26/tpm_lab.py --run unit26/edi/hallam_orders_HFS000417.edi
   ```

   ```text
   IC-0005  interchange HFS000417 from HALLAMFS, production, 3 message(s)
     FAILED       IC-0005/1  HFS-PO-8201  duplicate    duplicate: the receiver already holds this order
                  -> nothing to fix: the partner sent it again
     FAILED       IC-0005/2  HFS-PO-8202  duplicate    duplicate: the receiver already holds this order
                  -> nothing to fix: the partner sent it again
     FAILED       IC-0005/3  HFS-PO-8203  duplicate    duplicate: the receiver already holds this order
                  -> nothing to fix: the partner sent it again
     CONTRL CP0000004 to HALLAMFS: UCI 7, UCM 1=7, 2=7, 3=7 (written to tpm/out/)
   0 completed, 3 failed (synthetic)
   ```

   The receiver refuses each order it already holds, by customer and PO number. That is the business key from [Cloud Integration flows in depth](https://erpfde.com/topics/cloud-integration-flows-in-depth/): the receiver's own check is what stops a second shipment.

#### Step 7: Onboard five distributors from a sheet

Calder's sales team signed five more distributors. Their details are in `unit26/tpm/onboarding/distributors.csv`. Open it in VS Code: one row per partner, with the customer number, sales area, EDI identifier, error contact, AS2 identifier, certificate expiry date and whether they send their own part numbers.

1. Check the sheet against the entry rules:

   ```bash
   python unit26/tpm_lab.py --onboard
   ```

   ```text
   QUILLAN   Quillan Pump Supply                READY
   VENMOOR   Venmoor Industrial Supply          NOT READY
       O03 FAIL no contact for EDI errors
   TESSALY   Tessaly Flow Parts                 READY, WARN
       O04 WARN AS2 certificate expires 2026-12-15, in 15 days
   PELLMARK  Pellmark Industrial Supply         NOT READY
       O01 FAIL customer 10000031 has order block 01
       O08 FAIL sales area CPUS/30/SP is not the template's CPUS/20/PU
   HALLAMCA  Hallam Fluid Systems Canada Ltd.   NOT READY
       O02 FAIL EDI identifier HALLAMFS already belongs to HALLAMFS
       O05 FAIL own part numbers but no HALLAMCA_parts.csv
   5 partners on the sheet: 2 ready, 3 not ready. Profiles and draft agreements written for the ready ones.
   ```

   | Rule | Checks | Why it matters |
   | --- | --- | --- |
   | O01 | The customer exists, has no order block and is set up in the sales area | Otherwise every order fails later in S/4HANA |
   | O02 | The EDI identifier is not already someone else's | Two agreements with one identifier make agreement determination ambiguous |
   | O03 | There is a contact for EDI errors | Partner-side errors need someone to tell |
   | O04 | The AS2 certificate is valid for at least 30 more days | Warn at onboarding, block activation |
   | O05 | A partner with its own part numbers supplies a part list | Otherwise every line fails mapping |
   | O06 | A test interchange passed | Checked at activation |
   | O07 | Only a numbered version is activated | Checked at activation |
   | O08 | The sales area is the template's | Another sales area is another template, not an override |

   These rules are Calder's course rules. SAP's tool lets you activate a draft too; O07 is a stricter house rule so that what runs in production always has a version number.

   Hallam Canada's IT reused the parent's identifier `HALLAMFS`. Activating its agreement would leave two agreements answering the same messages. The fix is a separate identifier for the Canadian company, agreed with Hallam.

2. Run the ready partners' test interchanges. Their `UNB` ends with `1`, so they are test interchanges:

   ```bash
   python unit26/tpm_lab.py --test QUILLAN
   python unit26/tpm_lab.py --test TESSALY
   ```

   ```text
   IC-0006  interchange QPS000001 from QUILLANPS, test, 1 message(s)
     COMPLETED    IC-0006/1  QPS-PO-0001  ok           test interchange: checked and mapped, not sent to S4P
     CONTRL CP0000005 to QUILLANPS: UCI 7, UCM 1=7 (written to tpm/out/)
   1 completed, 0 failed (synthetic)
   QUILLAN: test passed on 2026-11-30; nothing was sent to S4P.
   IC-0007  interchange TFP000001 from TESSALYFP, test, 1 message(s)
     COMPLETED    IC-0007/1  TFP-PO-0001  ok           test interchange: checked and mapped, not sent to S4P
     CONTRL CP0000006 to TESSALYFP: UCI 7, UCM 1=7 (written to tpm/out/)
   1 completed, 0 failed (synthetic)
   TESSALY: test passed on 2026-11-30; nothing was sent to S4P.
   ```

   A test runs on the draft agreement and is mapped, but isn't sent to the target, as the template's `send_test_to_target: false` says.

3. Version and activate every ready agreement in one batch:

   ```bash
   python unit26/tpm_lab.py --activate-ready
   python unit26/tpm_lab.py --agreements
   ```

   ```text
   Activated 1: AGR-QUILLANPS-ORDERS
   Waiting 1: AGR-TESSALYFP-ORDERS (certificate expires 2026-12-15)
   Agreement                Partner   Active  Versions     Draft  Parts
   AGR-HALLAMFS-ORDERS      HALLAMFS  2.0     1.0, 2.0     no     4
   AGR-QUILLANPS-ORDERS     QUILLAN   1.0     1.0          no     Calder's
   AGR-TESSALYFP-ORDERS     TESSALY   -       -            yes    2
   ```

   The batch stops at 300, SAP's limit for one activation cross action. Tessaly waits for its renewed certificate.

> **Note** Partners, rules and results here are synthetic. They show how entry rules turn onboarding into a repeatable check; they are not SAP's onboarding checks.

#### Step 8: Save your work

```bash
git add unit26/tpm_lab.py unit26/tpm
git commit -m "Unit 26: trading partner lab"
```

#### How the code works

| Part | What it does |
| --- | --- |
| `load_edi_lab()` | Imports the setup's `edi_lab.py` and reuses its EDIFACT reader, so the two labs read interchanges the same way |
| `COMPANY`, `TEMPLATE`, `HALLAM` | The company profile, the agreement template with its MIG rules and defaults, and Hallam's partner profile |
| `new_agreement()` | Builds a draft agreement: the template's defaults plus the partner's customer, sales area and parts |
| `find_agreement()` | Agreement determination by sender, recipient and message type; none or several means unassigned |
| `unb_usage()` | Reads the usage indicator at the end of `UNB`; `1` means test |
| `mig_check()`, `mag_map()` | The guideline checks (required segments, allowed codes) and the mapping with the agreement's values |
| `process()` | One interchange through determination, syntax, MIG, MAG and delivery; writes the monitor and `CONTRL` |
| `contrl()` | A `CONTRL` with `UCI` and one `UCM` per message, numbered from the company's range |
| `restart()`, `retry()` | Restart maps again from the stored sender payload; retry resends the stored result |
| `edit_map()`, `save_version()`, `activate()` | Draft, version (at most five), activate one version; checks O04, O06 and O07 |
| `onboard()`, `check_partner()` | Reads the sheet, applies O01 to O05 and O08, writes profiles and draft agreements for ready partners |
| `activate_ready()` | Versions and activates every tested, ready agreement, up to 300 per batch |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python` is not recognized, or `command not found` | Python isn't installed, or the terminal can't find it | Repeat the Python step of Set up your computer and open a new terminal; on macOS/Linux use `python3` until `.venv` is active |
| `No unit26/edi_lab.py` | The setup's EDI lab is missing | Do Step 2 of Set up for Unit 26 |
| `No module named ...` | A different script was pasted | The lab needs built-in modules only; paste it again |
| `unit26/tpm/ already exists` | `--init` doesn't overwrite your work | Delete the `unit26/tpm` folder only if you want to start again |
| `... not found. Run --init first` | Wrong folder, or a typo in the file name | Run from `orchestrate-course`; check the name with `ls unit26/tpm/inbox` |
| Your IDs or numbers differ from the samples | Commands ran in another order, or twice | Delete `unit26/tpm`, run `--init`, then follow the steps in order |
| `JSONDecodeError` after editing a file | A comma or quote is missing | VS Code marks the line; fix it and run again |
| A company proxy blocks something | Not used here | The lab needs no network |

### The SAP way

What SAP provides for B2B, as of 29 November 2026:

- **Trading Partner Management** in SAP Integration Suite: company, trading partner and communication partner profiles, agreement templates, agreements and their versions, activation into the Partner Directory, cross actions to activate, export and import agreements in bulk (300 per run), and the B2B monitor ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/trading-partner-management-28fe3dc.md)). Type systems SAP lists for transactions include UN/EDIFACT, GS1 EANCOM, Odette and VDA EDIFACT, ASC X12, SAP IDoc, SAP SOAP, GS1 XML, Tradacoms, cXML and custom XML messages ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/creating-b2b-transactions-e1de659.md)).
- **The generic flows** in the configure-only package *Cloud Integration - Trading Partner Management V2*, copied from the *Discover* tab and configured, not edited ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/integration-flow-configuration-version-2-0-6d4cdd1.md)).
- **Integration Advisor**: the library of standards, custom type systems for your own message structures, MIGs, MAGs (graphical, overlay and XSLT), code lists and code value mappings, and proposals ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integration_Advisor/overview-of-sap-integration-advisor-f99fdaf.md)). A MIG can be started from a sample payload, with the wizard proposing type system, message and version.
- **Monitoring beyond the tenant.** Trading Partner Management can publish B2B interchange data to SAP Cloud ALM for alerting by partner or message type; SAP notes the first data can take up to 12 hours to appear and each interchange about 5 minutes to sync ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/publish-b2b-data-to-sap-cloud-alm-5ec23a5.md)). A **B2B Scenarios OData API** on the SAP Business Accelerator Hub reads business documents and orphaned interchanges ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/b2b-scenarios-56ccf98.md)).
- **Roles.** SAP's personas give the business expert (role collection `PI_Business_Expert`) monitoring, payload reading and restart, retry or cancel; the integration developer (`PI_Integration_Developer`) maintains profiles, templates and agreements and activates them ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/personas-for-trading-partner-management-d0c9a80.md)).
- **Licensing.** The [pricing page](https://www.sap.com/products/technology-platform/integration-suite/pricing.html) lists B2B libraries, the acknowledgment framework and trading partner management as a plan feature, and counts a message above 250 KB as one more message per further 250 KB. Confirm your plan with SAP; the AS2 adapter depends on the service plan per [SAP Note 2903776, referenced on the adapter page](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/as2-adapter-d3af635.md).

SAP Business Network is the other B2B route, mostly for procurement and logistics with suppliers. It is covered in [connecting to SAP Business Network](https://erpfde.com/topics/business-network-connectivity/); distributors sending Calder orders are a customer-side flow, which is why `I10` uses Trading Partner Management.

### Build vs. SAP

| Need | SAP | Hand-built or provider | Use which |
| --- | --- | --- | --- |
| Partner data and identifiers | Profiles with identifiers, contacts, certificates | A table in a custom flow | SAP's profiles: one place, versioned agreements, roles |
| A new partner | Agreement from a template, activated | A copied flow | The agreement; a copied flow is one more thing to fix |
| Standard messages | Integration Advisor's library and MIGs | XSDs written by hand | Integration Advisor, unless the partner's format is proprietary (then a custom type system) |
| Onboarding checks | Activation fails on missing referenced objects; no business entry rules | A checklist or a pipeline check like `--onboard` | Both: SAP checks configuration, your rules check business data |
| EDI for partners without AS2 | Custom sender flows into the generic Step 1 | An EDI provider (VAN) in front | A provider for the long tail of small partners, Trading Partner Management for the rest |
| Reprocessing | Restart, retry, duplicate and retry, with a reason | Re-run a script | The monitor's actions: they keep the history |

### Architecture view

**Where it sits.** Trading Partner Management and the generic flows run in Calder's production Integration Suite tenant in `calder-int-prod`. Partners reach Step 1 over AS2 on the tenant's endpoint. Step 3 hands each mapped order over ProcessDirect to a small custom flow that writes it to queue `I10_IN`, which the reviewed `I10` flow from [Cloud Integration flows in depth](https://erpfde.com/topics/cloud-integration-flows-in-depth/) reads. That flow calls `CP10`'s S/4HANA through the Cloud Connector pair `SCC-RK-P`.

```mermaid
flowchart LR
  H[Hallam and other<br/>distributors] -->|AS2| TPM[Trading Partner Management<br/>generic Steps 1-3]
  V[EDI provider<br/>small partners] -->|AS2| TPM
  TPM -->|ProcessDirect| Q[(I10_IN)]
  Q --> I10[I10 flow]
  I10 -->|Cloud Connector<br/>SCC-RK-P| S4[S/4HANA CP10]
  TPM -.CONTRL, MDN.-> H
  TPM -.interchange data.-> ALM[SAP Cloud ALM]
```

**Non-functional requirements.**

| Requirement | Target for distributor EDI | What breaks if missed |
| --- | --- | --- |
| Delay | CONTRL within 15 minutes; sales order within 1 hour (the `I10` spec) | Partners resend, creating duplicates; orders miss picking |
| Partner scale | 40 distributors on one template, onboarded in batches | One flow per partner, copied fixes |
| Identification | One identifier per partner per standard, unique | Messages land in the wrong agreement, or in none |
| Certificates | Renewed 30 days before expiry | A partner's orders stop on the expiry day |
| Retention | B2B monitor data kept as SAP states (90 days after archiving); payload archive to Calder's CMIS repository | No evidence for a disputed order |
| Volume | Messages above 250 KB count more than once | Licensing estimate too low |

**Integration and identity.** A partner is identified twice: by the AS2 identifier and certificate on the connection, and by the EDI identifier in `UNB`. Both belong to the partner profile; neither is trusted from the payload alone. Into S/4HANA, the `I10` flow posts with a technical user limited to creating sales orders in `CPUS`, as the [BTP security topic](https://erpfde.com/topics/btp-security-model/) describes. Monitor access follows SAP's personas: customer service gets the business expert role for restarts after a mapping fix; only the integration team activates agreements.

**The decision to record** (short ADR form from the [design-doc topic](https://erpfde.com/topics/writing-a-solution-design-doc/)):

- **Context.** Today `I10` runs through an EDI provider that converts distributor orders to IDoc `ORDERS`. ADR-001 targets Integration Suite. Calder has 12 distributors on EDI and has signed five more; two of the new ones can't run AS2.
- **Options.** A: keep the provider for all partners. B: move every partner to Trading Partner Management. C: Trading Partner Management for partners that can run AS2, the provider in front of it for the rest, both on the same template.
- **Decision.** C.
- **Consequences.** One template, one MIG and one MAG serve both routes. The provider becomes one communication partner instead of the place where mappings live. Calder pays for the provider only for the long tail, and owns its partners' agreements either way.

**What a design review will ask.**

1. How is each message matched to its agreement, and what happens when two agreements could match?
2. Who watches unassigned interchanges, and how fast?
3. For each error category, who fixes it, and who tells the partner?
4. How does a change to a partner's part list reach production, and who approves it?
5. Which certificates expire in the next 90 days?

### Production concerns

- **Security and authorizations.** Private keys and partner certificates live in Cloud Integration's secure store, as SAP's [stored data page](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/types-of-stored-data-c36c7c6.md) says. Contact details in profiles are personal data; SAP states the tenant's owner is responsible for handling them under laws such as GDPR. Keep payload reading to the business expert role, and keep activation to the integration team.
- **Evaluation.** Every partner sends a test interchange before activation, and every production incident becomes a new test interchange for its template. Run the onboarding checks in the pipeline that imports agreements.
- **Versions and transport.** Create and version agreements in development, then export and import them, as SAP's versioning page advises. Five numbered versions is the cap: plan to delete old ones.
- **Operations.** Watch unassigned interchanges, acknowledgment overdue and certificate dates. Decide who may restart (customer service, after a mapping fix) and who may retry (integration, after an outage). Turn on payload archiving if disputes need evidence: SAP's archiving job runs daily, archives back to 7 days before activation, and has no retry for a failed archive ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/archiving-payload-data-b927e01.md)).
- **Cost.** Size by messages, not partners. An interchange with three orders is split into three messages, and acknowledgments and receipts travel too; check with SAP how your contract counts each of them.
- **Clean core.** The target is a released inbound interface in S/4HANA, reached through the `I10` flow. Nothing in the B2B layer writes to S/4HANA tables, which keeps partner onboarding out of upgrade testing.

### Where AI fits

- **Delivered SAP capability.** Integration Advisor's proposal service suggests MIG nodes and mapping lines from a crowd-based knowledge base. SAP lists what it collects: node properties, selected codes and mapping lines, but not textual documentation or functions marked confidential. A tenant can opt out in the MIG and MAG settings, which also removes the proposals ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integration_Advisor/data-collection-for-knowledge-base-e5bd17f.md)). Decide this per tenant, on purpose. [AI in SAP Integration Suite](https://erpfde.com/topics/ai-in-sap-integration-suite/) covers the design-time AI features.
- **Proposals are drafts.** A proposed mapping goes through the same test interchanges as a hand-made one. The lab's mapping failure would have been just as real if a proposal had made it.
- **An agent as a reader of partner text.** An agent that triages failed interchanges reads text the partner wrote, such as `FTX` notes. Treat that as data, never as instructions, as the [prompt injection topic](https://erpfde.com/topics/prompt-injection-and-tool-poisoning/) shows. An agent may draft a mapping change; activating it stays with a person.
- **Where AI adds little.** Agreement determination, envelope checks and acknowledgments are deterministic rules. Plain configuration does them better than a model.

### Pitfalls

- **One flow per partner.** It works until the first fix that has to be made forty times.
- **Restarting a partner's bad data.** A unit the MIG doesn't allow fails the same way after every restart. Tell the partner.
- **Retrying after a mapping fix.** Retry skips the mapping, so the fix isn't used. Restart instead.
- **Reading `CONTRL` as an order confirmation.** It confirms syntax. Send business answers in a separate message if the partner needs them.
- **A shared identifier.** Two agreements matching the same sender and message make every message from that sender a guess.
- **Testing on production data in production.** Use the usage indicator and keep *Send test interchange to target* off.
- **Activating a draft in production.** It works, which is the problem: nobody can say which version ran.
- **Nobody watching unassigned interchanges.** Partner alerts can't fire for a message that has no partner yet.
- **Certificates in someone's calendar.** Track expiry dates in the profile and check them in the pipeline.

### Exercise

Venmoor sent the contact for its EDI errors, and Tessaly sent its renewed AS2 certificate. Onboard both.

1. Open `unit26/tpm/onboarding/distributors.csv`.
2. In Venmoor's row, put `edi@venmoor-supply.example` in the empty `contact_email` field, between `VENMOORIS,` and `,VENMOORIS-AS2`. Save.
3. In Tessaly's row, change the certificate date `2026-12-15` to `2027-12-15`. Save.
4. Run `python unit26/tpm_lab.py --onboard`. Quillan, Venmoor and Tessaly now read `READY`; Pellmark and Hallam Canada stay `NOT READY`.
5. Run `python unit26/tpm_lab.py --test VENMOOR`. It ends with `VENMOOR: test passed on 2026-11-30; nothing was sent to S4P.`
6. Run `python unit26/tpm_lab.py --activate-ready`. It prints `Activated 2: AGR-TESSALYFP-ORDERS, AGR-VENMOORIS-ORDERS`.
7. In `unit26/notes.md`, write one line each for Pellmark and Hallam Canada: what must change, and who at Calder or at the partner owns the change.

**Done when** `python unit26/tpm_lab.py --agreements` lists four agreements, each with an active version (Hallam `2.0`, the three new ones `1.0`), and `notes.md` holds your two lines. The [interface monitoring and error handling topic](https://erpfde.com/topics/interface-monitoring-and-error-handling/) builds its alert routes on these error categories.

> **Note** The partners and results are synthetic course data.

### Check yourself

1. What does activating an agreement do in Trading Partner Management?
   - A. It generates a new integration flow for that partner from the template
   - B. It pushes the agreement's runtime data into the Partner Directory
   - C. It sends the agreement to the partner for an electronic signature
   - D. It copies the template's MIG into a new MIG owned by the partner

   Answer: B. SAP's generic flows read the Partner Directory at runtime, and activation is what writes the agreement there. No flow is generated per partner.

2. In the lab, why does HFS-PO-8212 complete while two other orders in the same interchange fail?
   - A. The two failed orders were sent with a test usage indicator
   - B. The interchange's UNZ count only covers the last message
   - C. Transaction mode Message rejects only the faulty messages
   - D. Calder's MIG allows one failed message per interchange

   Answer: C. With the default transaction mode *Message*, each message is validated on its own and good ones continue. Mode *Interchange* would reject all three.

3. The CONTRL for HFS000431 shows action code 7 for all three messages. Why?
   - A. CONTRL is only created when every message is completed
   - B. CONTRL reports on syntax, and all three were syntactically fine
   - C. Action code 7 means the partner must resend the interchange
   - D. The lab sets code 7 for every message to keep the example simple

   Answer: B. GS1 describes CONTRL as a syntax report, not a check of business content. The unknown part and the wrong unit fail later, in the guideline check and the mapping.

4. Hallam's new part number is mapped in a draft, but a restart still fails. What is missing?
   - A. A retry, because restart doesn't read the agreement again
   - B. A new MIG version, because part numbers live in the MIG
   - C. A resend from Hallam, because the stored payload is now stale
   - D. Saving the draft as a version and activating it

   Answer: D. Production uses the active agreement version. The draft holds the fix but isn't active until it is versioned and activated; then the restart maps again from the sender payload.

5. S/4HANA was down when an order was mapped. Which action fits once it is back?
   - A. Retry, which resends the mapped result without mapping again
   - B. Restart, which is the only action allowed for failed interchanges
   - C. Duplicate and Retry, which keeps the failed original unchanged
   - D. Deactivate and reactivate the agreement to clear the error

   Answer: A. SAP's retry starts from the receiver payload and skips the mapping, which was right. Restart is for fixes that need the mapping to run again; Duplicate and Retry is for completed interchanges.

6. Hallam Canada's IT reuses the identifier HALLAMFS. Why does onboarding refuse it?
   - A. Identifiers must contain the partner's country code
   - B. A partner can hold only one agreement per message type
   - C. Two agreements would match the same incoming messages
   - D. The Canadian company has no customer number in CP10

   Answer: C. Agreement determination uses the sender and recipient identifiers and the message type. With a shared identifier, Calder can't tell which company an order is from.

7. A message arrives from a sender with no agreement. Where does SAP show it?
   - A. In the partner's failed interchanges, under its profile
   - B. Nowhere, because Step 1 drops messages it can't match
   - C. In the CONTRL sent back to the sender with code 4
   - D. Under unassigned interchanges in the B2B monitor

   Answer: D. SAP's B2B monitor lists interchanges without a business document as unassigned. With no agreement there is no partner contact and no acknowledgment, so someone must watch that list.

8. What should Calder decide about Integration Advisor's proposal service?
   - A. Nothing, because proposals are always switched off by default
   - B. Whether to share guideline data in exchange for proposals, per tenant
   - C. Which partner's agreements may use proposals at runtime
   - D. Whether proposals may activate mappings without a test

   Answer: B. SAP's page lists what the knowledge base collects and lets a tenant opt out, which also removes the proposals. It is a design-time choice; runtime and testing are unchanged.

## Sources

- [Trading Partner Management (SAP Integration Suite documentation, SAP-docs on GitHub, read 2026-11-29)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/trading-partner-management-28fe3dc.md): protocols such as AS2, SFTP, FTP; standards such as EDI, XML, JSON; company, trading partner and communication partner profiles; agreement templates and agreements; runtime artifacts pushed to the Partner Directory so a single integration flow processes the messages; uses Integration Advisor and Cloud Integration
- [Understanding the Basic Concepts (Trading Partner Management)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/understanding-the-basic-concepts-74c068d.md): B2B scenario, business transaction (one-way, two-way), business transaction activity, steps (source system and MIG, protocol, interchange, mapping, target interchange and functional acknowledgment); identifier with identification, type system, scheme, agency; Partner Directory; alias for transport
- [Creating an Agreement Template (Trading Partner Management)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/creating-an-agreement-template-9692cb1.md): template configurations serve as defaults reused and overridden in agreements; initiator; version 1.0 by default; company system, type system and identifiers; aliases for the partner's values
- [Creating B2B Transactions (Trading Partner Management)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/creating-b2b-transactions-e1de659.md): pattern, my company role initiator or reactor; transaction mode Message (default, only the faulty message rejected) or Interchange; MIG per interchange; usage indicator last in UNB (1 test); send test interchange to target yes or no; functional acknowledgment and number ranges; syntax and payload validation; MAG in the mapping step; custom pre- and post-processing flows over ProcessDirect; activity parameters; custom search attributes
- [Versioning in Trading Partner Management](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/versioning-in-trading-partner-management-09685b7.md): drafts and numbered versions (1.0, 2.0), read only once versioned, one draft, at most five numbered versions; develop and version in development tenants and transport; one active version per agreement, activation pushes it to the Partner Directory
- [Activate/Deactivate Agreements (Trading Partner Management)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/activate-deactivate-agreements-e068e37.md): cross action for groups of agreements; at most 300 agreements per activation; activation modes Default and Full
- [Integration Flow Configuration Version 2.0 (Trading Partner Management)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/integration-flow-configuration-version-2-0-6d4cdd1.md): configure-only package Cloud Integration - Trading Partner Management V2; Step 1 sender flows for AS2, AS2 MDN, IDoc, SOAP and ProcessDirect; Step 2 interchange processing; Step 3 receiver communication; JMS queues between steps
- [Restart or Retry, or Duplicate and Retry Interchanges (Trading Partner Management)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Trading_Partner_Management/restart-or-retry-or-duplicate-and-retry-interchanges-8626727.md): restart re-runs from the sender payload including the mapping; retry resends the receiver payload without mapping; duplicate and retry for completed interchanges; a reason is asked; generic flow 2.3.7 or later
- [Overview of SAP Integration Advisor (SAP Integration Suite documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integration_Advisor/overview-of-sap-integration-advisor-f99fdaf.md): library of type systems from standards agencies; custom type systems; message implementation guidelines (MIG) and mapping guidelines (MAG); crowd-based machine learning proposals
- [EANCOM 2002 S4 CONTRL syntax and service report message (GS1, read 2026-11-29)](https://www.gs1.org/sites/default/files/docs/eancom/s4/contrl.pdf): CONTRL reports on the syntax of a received interchange, not its business content; UCI interchange response and UCM message response; action codes 4 rejected, 7 acknowledged, 8 received
