# Set up for Unit 26: Integration Suite trial options and local EDI and event labs

> Know which Integration Suite trials exist in November 2026 and what they leave out, then add an EDI lab and an event broker lab to the Unit 4 tools.

- Course: Orchestrate, Unit 26 · Integration in depth
- Page: https://erpfde.com/topics/set-up-for-unit-26/
- Updated: 2026-11-30
- Reading time: Foundational 7 min, Deep 35 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

Unit 26 goes one level deeper than Unit 4 into how Calder Pumpworks, the course's fictional pump maker, connects its systems and partners: integration flows, API management, events, EDI, IDocs, RFC and the move off older middleware. It is written for architects and integration leads.

SAP's own tool for this is SAP Integration Suite. As of 29 November 2026 you can try it for free in two ways, both time-limited:

- a **30-day basic trial** on a shared tenant with sample data, without administration rights;
- **your own Integration Suite subscription** inside an SAP BTP trial account, set up with SAP's tutorial.

Neither covers everything the unit discusses. We found no trial of advanced event mesh, SAP's event broker service, and the basic trial leaves out administration. So this setup also adds two small local labs to the Unit 4 tools: one reads a distributor's EDI order file, the other runs a tiny event broker with queues. Setup takes 30 to 45 minutes and costs nothing.

### Why it matters to the business

Integration is where an SAP program's quiet risks live. A distributor's EDI order that fails a check at 2 a.m., an event that a system missed while it was down, a partner that sends the same file twice: each turns into a late shipment, a missing order or a double delivery.

The unit's topics ask an architect to decide how those cases are handled before go-live. Deciding on paper and in a lab is cheap. Finding out in hypercare costs a week of people reprocessing messages by hand, as the [integration lead's toolkit](https://erpfde.com/topics/the-integration-leads-toolkit/) showed for Calder's July 2027 rollout.

A trial lets the team see SAP's screens. The local labs let them break things on purpose and watch the result, which a shared trial tenant doesn't allow.

### How SAP does it

As of 29 November 2026, SAP's pages describe these entry points:

| Entry point | What you get | Limits |
| --- | --- | --- |
| [Integration Suite basic trial](https://www.sap.com/products/technology-platform/integration-suite/trial.html) | Design and test integration flows with cloud integration, API management and AI-assisted tools, on a shared tenant with sample data | 30 days; a subset of the product; no key user capabilities or administration rights |
| [Integration Suite in a BTP trial](https://developers.sap.com/tutorials/cp-starter-isuite-onboard-subscribe.html) | Your own Integration Suite tenant: you add capabilities such as building integration scenarios and managing APIs | The BTP trial's 90 days (see [Set up for Unit 21](https://erpfde.com/topics/set-up-for-unit-21/)); one Integration Suite tenant per trial account; not for productive use or team development |
| [Paid editions](https://www.sap.com/products/technology-platform/integration-suite/pricing.html) | Three base editions, each with an included monthly message volume | No free tier listed |
| [Advanced event mesh](https://www.sap.com/products/technology-platform/integration-suite/advanced-event-mesh.html) | A managed mesh of event brokers | Base plans to buy; no trial on the page |

SAP Learning lists Integration Suite's capabilities as Cloud Integration, API Management, Open Connectors, Graph, Event Mesh, Integration Advisor, Trading Partner Management, OData Provisioning, Data Space Integration, Integration Assessment and Migration Assessment ([SAP Learning](https://learning.sap.com/courses/administering-sap-integration-suite/understanding-capabilities)). Adding them needs the `Integration_Provisioner` role. Which of them a trial tenant can add is not stated on the pages we read.

Pricing counts messages. SAP's pricing page says a message larger than 250 KB counts as one more message for each 250 KB or part of it. That rule matters when Unit 26 sizes Calder's interfaces.

> **Note** **For functional consultants:** nothing in your configuration changes in this setup. The EDI lab does show the mapping table a distributor interface depends on (the partner's part numbers and units to Calder's). Keeping that table current is often a business task, not an IT one, and an unmapped part stops the whole order.

### What this unit adds

| Item | What it is | Cost | Used in |
| --- | --- | --- | --- |
| `unit26/edi_lab.py` | Reads Hallam's EDIFACT order interchange, checks its counts and maps it to Calder's order format | Free | EDI and Trading Partner Management, IDocs, interface monitoring |
| `unit26/event_lab.py` | A local event broker with topics, wildcards, queues and a dead-letter queue | Free | Event mesh, interface monitoring |
| `check_unit26.py` | Runs both labs' self-tests and counts down any trial you start | Free | Before every Unit 26 topic |
| Integration Suite basic trial (optional) | SAP's screens for integration flows and APIs | Free, 30 days | [Cloud Integration](https://erpfde.com/topics/cloud-integration-flows-in-depth/) and [API Management](https://erpfde.com/topics/api-management-in-depth/) topics |
| Integration Suite in your BTP trial (optional) | Your own tenant, where you add capabilities yourself | Free within the BTP trial | Same, plus the administration side |

Nothing new to install: both labs use only what comes with Python. The Unit 4 mock order inbox is reused if you have it.

### Time and money

- **Time:** 30 to 45 minutes for the two labs and the check. A trial adds 30 to 60 minutes of registration and onboarding.
- **Money:** nothing. Both trial routes are free. SAP's paid editions are not needed for any Unit 26 exercise.
- **Clocks:** the basic trial lasts 30 days. If your BTP trial from Unit 21 is still running, add Integration Suite to it rather than starting a new one.

### Questions to ask

Ask IT or your SAP account team before the unit's design work:

- Which Integration Suite edition do we license, and what monthly message volume is included?
- Do we already run advanced event mesh or the Event Mesh capability, and who owns the brokers?
- Which interfaces carry messages above 250 KB, such as attachments or large IDocs, and how are they counted?
- Who owns the partner mapping tables for EDI (part numbers, units, partner IDs)?
- Is there a non-production Integration Suite tenant the architecture team may use for proofs of concept?

### Common misconceptions

- **"The trial shows everything Integration Suite does."** The basic trial is a subset on a shared tenant, without administration rights.
- **"There is a free tier for Integration Suite."** SAP's pricing page, read on 29 November 2026, lists paid editions and no free tier.
- **"We can try advanced event mesh like the rest."** We found no trial for it on SAP's product page.
- **"A local lab is a toy."** The labs leave out SAP's product, not the hard parts: counts that don't match, unmapped parts, duplicates and missed events behave the same way.
- **"A trial is fine for a quick pilot with real partner files."** Trials are for non-productive use. Partner data belongs in Calder's own tenant.

### Key terms

- **SAP Integration Suite:** SAP's integration platform on SAP BTP, made of capabilities such as Cloud Integration and API Management.
- **Capability:** one part of Integration Suite that an administrator adds to a tenant.
- **EDI (electronic data interchange):** business documents exchanged between companies in an agreed standard format, such as UN/EDIFACT.
- **Interchange:** one EDI transmission, which can hold several messages, such as several purchase orders.
- **Event broker:** a service that receives events from senders and passes them to subscribers.
- **Guaranteed delivery:** a broker keeps an event on a queue until the consumer confirms it has handled it.
- **Dead-letter queue:** where a broker parks a message that failed too often, for a person to look at.

### Check yourself

1. A Calder architect wants the team to try SAP's integration tools next week at no cost. What can you offer?
   - A. A free tier of Integration Suite with no time limit
   - B. The 30-day basic trial, or Integration Suite in a BTP trial
   - C. A free advanced event mesh broker from SAP's product page
   - D. Calder's production tenant, with a separate test user

   Answer: B. SAP offers a 30-day basic trial on a shared tenant, and a tutorial for subscribing to Integration Suite in a BTP trial account. The pricing page lists no free tier, and the advanced event mesh page offers no trial.

2. Why does this setup add local labs when a trial exists?
   - A. The trial can't be opened from a company network
   - B. SAP forbids testing EDI files in its trials
   - C. Trials leave out admin rights and the event broker
   - D. The labs replace Integration Suite for Calder's rollout

   Answer: C. The basic trial has no administration rights and we found no advanced event mesh trial. The labs let learners break interfaces on purpose, which a shared trial doesn't allow; they teach the patterns, not SAP's product.

3. Calder's distributor portal sends 600 KB attachments with some orders. What should the architect check?
   - A. Whether attachments are free because they are files
   - B. Whether the trial tenant accepts files of that size
   - C. Whether EDIFACT allows attachments at all
   - D. How the larger messages count against the volume

   Answer: D. SAP's pricing page counts a message over 250 KB as one more message for each 250 KB or part of it. Large messages can use up the included volume faster than the order count suggests.

4. A partner wants to pilot Calder's new EDI flow in the basic trial with live order files. What do you say?
   - A. No: it is a shared, non-productive tenant
   - B. Yes, if the trial is restarted every 30 days
   - C. Yes, because sample data is mixed with real data
   - D. No: the trial has no integration flow design

   Answer: A. SAP describes the basic trial as a shared tenant with sample data, and trials are for non-productive use. Live partner files belong in Calder's own tenant; the trial does include integration flow design.

5. In the EDI lab, one of Hallam's orders is rejected because a part number has no mapping. Who usually fixes it?
   - A. The broker, by retrying the message until it passes
   - B. The owner of the partner mapping table, often the business
   - C. SAP support, because the mapping is part of the product
   - D. Hallam, by switching to a different EDI standard

   Answer: B. An unmapped partner part stops the order until someone adds the mapping. Retrying changes nothing, and the table is Calder's own data, so its owner must be named before go-live.

## Deep layer

### Mental model: SAP's screens from a trial, the failure cases from a lab

An architect needs two things from a setup. One is SAP's real tools, to see what a capability looks like and what it calls things. The other is a place to make failures happen on demand: a count that doesn't add up, a part nobody mapped, a consumer that was offline. A shared trial gives you the first. Only something you own gives you the second.

```mermaid
flowchart LR
  subgraph Trial[Optional trials]
    BT[Basic trial<br/>shared tenant]
    OT[Own tenant<br/>in a BTP trial]
  end
  subgraph Lab[Your laptop]
    EDI[edi_lab.py<br/>EDIFACT ORDERS] -->|orders as JSON| MOCK[Unit 4 mock<br/>order inbox]
    S4[S/4HANA-style<br/>CloudEvents] --> BRK[event_lab.py<br/>topics, queues, DLQ]
  end
  BT -.see the screens.-> CI[Cloud Integration,<br/>API Management]
  OT -.add capabilities.-> CI
  Lab -.same failure cases.-> CI
```

### How it works

#### The trial routes

The **basic trial** opens a shared tenant with sample data for 30 days. SAP says you can design and test integration flows with cloud integration, API management and AI-assisted tools, and that key user capabilities and administration rights are not offered ([sap.com](https://www.sap.com/products/technology-platform/integration-suite/trial.html)).

The **BTP trial route** gives you your own tenant. SAP's [tutorial](https://developers.sap.com/tutorials/cp-starter-isuite-onboard-subscribe.html), read on 29 November 2026, uses a trial subaccount in the **Singapore - Azure** region, subscribes to **Integration Suite** with plan **trial**, assigns the `Integration_Provisioner` role collection, then chooses **Add Capabilities** and selects **Build Integration Scenarios** and **Manage APIs**. It notes that boosters only work in Singapore subaccounts, that a trial account can hold only one Integration Suite tenant, and that trial accounts are not for productive use or team development.

| Question | Basic trial | Own tenant in a BTP trial |
| --- | --- | --- |
| Whose tenant | Shared | Yours |
| Length | 30 days | The BTP trial's 90 days |
| Administration | No | Yes, within the trial |
| Good for | A first look at flows and APIs | Adding capabilities, roles and monitoring yourself |

#### The EDI lab

> **Note** There is nothing to download. You create `edi_lab.py` in [Step 2](#d-step-2-create-the-edi-lab) below by pasting its code, and its `--init` option writes Hallam's interchange and the mapping file for you.

`edi_lab.py` reads one UN/EDIFACT interchange from Hallam Fluid Systems, Calder's fictional distributor. EDIFACT writes data as **segments** that end with an apostrophe; inside a segment, `+` separates data elements and `:` separates their parts. A `?` before one of those characters makes it plain text. An optional `UNA` segment at the start can declare other characters ([GS1](https://gs1.org/sites/gs1/files/docs/eancom/ean02s4/part1/part1_05.htm)).

```text
UNB+UNOC:4+HALLAMFS:ZZZ+CALDERCP10:ZZZ+20261123:0815+HFS000417'   interchange header
UNH+1+ORDERS:D:96A:UN'                                            message header
BGM+220+HFS-PO-8201+9'                                            the order number
LIN+1++HFS-SK-200:SA'   QTY+21:40:PCE'                            a line: part and quantity
UNT+11+1'                                                         message trailer: 11 segments
UNZ+3+HFS000417'                                                  interchange trailer: 3 messages
```

The lab checks what a receiving system checks first:

| Check | Rule | Source |
| --- | --- | --- |
| Envelope | `UNZ` repeats `UNB`'s reference and counts the messages | GS1 |
| Message | `UNT` counts every segment of its message, including `UNH` and `UNT` | GS1 |
| Content | `ORDERS` carries a message header, a beginning of message (`BGM`), dates (`DTM`), a section control (`UNS`) and a trailer; parties and line items sit in segment groups | [TrueCommerce](https://help.truecommerce.com/en/articles/16043911-edifact-orders-d-96a-purchase-order) |
| Agreement | Sender, recipient, message version, buyer, part numbers and units must be in Calder's mapping | Course rule |

Then it maps each accepted message to the JSON the [Unit 4 mock order inbox](https://erpfde.com/topics/set-up-for-unit-04/) takes, with an idempotency key made of sender, interchange reference and message number. When Hallam resends the same interchange, the keys repeat and the mock answers with the orders it already created.

The interchange's qualifier values (`220`, `9`, `137`, `2`, `21`, `91`) are the ones many ORDERS guidelines use, kept as course values here. A real partner's message guideline decides them, as TrueCommerce's page reminds its readers.

#### The event lab

> **Note** You create `event_lab.py` in [Step 5](#d-step-5-create-and-run-the-event-lab) below by pasting its code. It needs no other files.

`event_lab.py` is a broker in one file. It follows three ideas from SAP's advanced event mesh documentation:

- **Topics with levels.** An S/4HANA event topic has levels for the system, `ce`, the source, the business object, the action and the version. A subscription can use `*` for one level and `>` for everything below ([SAP tutorial](https://developers.sap.com/tutorials/pubsub-view-events.html)).
- **Direct versus guaranteed delivery.** Direct messages are not kept for a client that isn't connected and are not acknowledged. Guaranteed messages stay on a durable endpoint, such as a queue, until a client acknowledges them ([SAP documentation](https://help.pubsub.em.services.cloud.sap/Get-Started/message-delivery-modes.htm)).
- **CloudEvents envelopes.** Each event carries `id`, `source`, `specversion` (`1.0`) and `type`. A producer keeps `source` plus `id` unique per distinct event, and a re-sent duplicate may keep its `id` ([CloudEvents](https://raw.githubusercontent.com/cloudevents/spec/main/cloudevents/spec.md)). So a consumer skips duplicates by that pair.

The event types are SAP's published sales order events, `sap.s4.beh.salesorder.v1.SalesOrder.Created.v1` and `...Changed.v1`, which the [event-driven agents topic](https://erpfde.com/topics/event-driven-agents-with-sap-events/) introduced. The payload field `Version`, the queue names and the limit of three deliveries before the dead-letter queue are course values, not SAP's.

The lab runs one day at Calder. Three consumers listen: the CRM on a queue for every sales order action, the data warehouse on a queue for every S/4HANA business event, and a dashboard on direct delivery. The CRM and the dashboard go offline for a maintenance window; the CRM crashes once before acknowledging; one event arrives with a broken payload.

### Build it yourself: the EDI lab, the event lab and the Unit 26 check

You will create two lab scripts and a check, run each, break the EDI file on purpose, and optionally start a trial. Steps 1 to 6 need no account.

```mermaid
flowchart LR
  A[edi_lab.py --init] --> B[edi_lab.py]
  B --> C[edi_lab.py --deliver<br/>to the Unit 4 mock]
  D[event_lab.py] --> E[event_lab.py --direct]
  B & D --> F[check_unit26.py]
```

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/). For the `--deliver` step, also have the mock from [Set up for Unit 4](https://erpfde.com/topics/set-up-for-unit-04/). This walkthrough doesn't repeat those steps.

> **Note** New words. A **segment** is one line of an EDI message, such as a line item. An **envelope** is the header and trailer around messages that say who sent them and how many there are. A **topic** is the label an event is published under; a **queue** stores events for one consumer until it confirms them. An **acknowledgement** (ack) is that confirmation.

#### What you need

- Your course folder `orchestrate-course` with its `.venv` from the computer setup.
- About 30 to 45 minutes. Everything is free.
- Optional: an email address for an SAP trial (Step 7).

#### Step 1: Open your 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. Create the folder for this unit:

   ```bash
   mkdir unit26
   ```

Run every command from the course folder.

#### Step 2: Create the EDI lab

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

```python
"""A small UN/EDIFACT lab for Unit 26: read a distributor's ORDERS interchange, check it, map it.

Run from your course folder:
    python unit26/edi_lab.py --init       # write Hallam's sample interchange and mapping table
    python unit26/edi_lab.py              # check and map the interchange, one line per message
    python unit26/edi_lab.py --deliver    # also send the accepted orders to the Unit 4 mock, twice
    python unit26/edi_lab.py --selftest   # prove the checks catch a damaged interchange

Built-in Python only, no randomness, no account. Calder Pumpworks and Hallam Fluid Systems are
fictional. Partner IDs, part numbers, qualifier values and the mapping are course values; a real
partner's message guideline decides them. This is a teaching parser, not an EDI translator.
Exit code 0 when every message is accepted or rejected as planned, 2 when the envelope is broken.
"""
import argparse
import importlib.util
import json
import pathlib
import sys
import urllib.error
import urllib.request

HERE = pathlib.Path(__file__).resolve().parent
EDI_DIR = HERE / "edi"
SAMPLE_FILE = EDI_DIR / "hallam_orders_HFS000417.edi"
MAP_FILE = EDI_DIR / "hallam_map.json"
OUT_DIR = EDI_DIR / "out"

# One segment per line for reading; the parser ignores the line breaks (a course choice).
SAMPLE = """UNA:+.? '
UNB+UNOC:4+HALLAMFS:ZZZ+CALDERCP10:ZZZ+20261123:0815+HFS000417'
UNH+1+ORDERS:D:96A:UN'
BGM+220+HFS-PO-8201+9'
DTM+137:20261123:102'
DTM+2:20261204:102'
NAD+BY+10000002::91'
NAD+SU+CALDERCP10::91'
LIN+1++HFS-SK-200:SA'
QTY+21:40:PCE'
UNS+S'
CNT+2:1'
UNT+11+1'
UNH+2+ORDERS:D:96A:UN'
BGM+220+HFS-PO-8202+9'
DTM+137:20261123:102'
DTM+2:20261207:102'
NAD+BY+10000002::91'
NAD+SU+CALDERCP10::91'
LIN+1++HFS-P200:SA'
QTY+21:2:PCE'
LIN+2++HFS-BRG-6310:SA'
QTY+21:5:PCE'
UNS+S'
CNT+2:2'
UNT+13+2'
UNH+3+ORDERS:D:96A:UN'
BGM+220+HFS-PO-8203+9'
DTM+137:20261123:102'
DTM+2:20261211:102'
FTX+AAI+++Dock 3?: call M. Ostrander?'s desk first'
NAD+BY+10000002::91'
NAD+SU+CALDERCP10::91'
LIN+1++HFS-P200:SA'
QTY+21:2:EA'
UNS+S'
CNT+2:1'
UNT+12+3'
UNZ+3+HFS000417'
"""

MAPPING = {
    "note": "Course mapping for Hallam Fluid Systems (fictional). Values are course labels.",
    "recipient": "CALDERCP10",
    "partners": {"HALLAMFS": {"customer": "10000002", "sales_area": "CPUS/20/PU"}},
    "parts": {"HFS-SK-200": "CP-SK200", "HFS-P200": "CP-ES200"},
    "units": {"PCE": "PC", "EA": "PC"},
}


class Syntax:
    """The six service characters. Defaults apply when there is no UNA segment."""

    def __init__(self, una=None):
        chars = una[3:9] if una else ":+.? '"
        self.component, self.element, self.decimal, self.release, self.repeat, self.terminator = chars


def split_segments(text):
    """Split on the segment terminator, honouring the release character. Line breaks are ignored."""
    text = text.replace("\r", "").replace("\n", "")
    syntax = Syntax(text[:9] if text.startswith("UNA") else None)
    if text.startswith("UNA"):
        text = text[9:]
    segments, current, i = [], "", 0
    while i < len(text):
        ch = text[i]
        if ch == syntax.release and i + 1 < len(text):
            current += ch + text[i + 1]  # keep the escape; elements are split later
            i += 2
            continue
        if ch == syntax.terminator:
            segments.append(current)
            current = ""
        else:
            current += ch
        i += 1
    if current.strip():
        segments.append(current)  # a segment without its terminator: reported by the checks
    return syntax, segments


def split_on(value, sep, release):
    """Split one string on a separator, then remove release characters from each part."""
    parts, current, i = [], "", 0
    while i < len(value):
        ch = value[i]
        if ch == release and i + 1 < len(value):
            current += value[i + 1]
            i += 2
            continue
        if ch == sep:
            parts.append(current)
            current = ""
        else:
            current += ch
        i += 1
    parts.append(current)
    return parts


def parse_segment(raw, syntax):
    """'QTY+21:40:PCE' -> ('QTY', [['21', '40', 'PCE']])."""
    # Split elements first while escapes are still in place, then components.
    elements, current, i = [], "", 0
    while i < len(raw):
        ch = raw[i]
        if ch == syntax.release and i + 1 < len(raw):
            current += ch + raw[i + 1]
            i += 2
            continue
        if ch == syntax.element:
            elements.append(current)
            current = ""
        else:
            current += ch
        i += 1
    elements.append(current)
    tag = elements[0]
    return tag, [split_on(e, syntax.component, syntax.release) for e in elements[1:]]


def element(data, position, component=0, default=""):
    """Read data element `position` (1-based after the tag), component `component` (0-based)."""
    try:
        return data[position - 1][component]
    except IndexError:
        return default


def read_interchange(text):
    """Return (header, messages, envelope problems). Each message is a dict of its segments."""
    syntax, raw_segments = split_segments(text)
    segments = [parse_segment(s, syntax) for s in raw_segments]
    problems, messages, header = [], [], {}
    if not segments or segments[0][0] != "UNB":
        return header, messages, ["interchange does not start with UNB"]
    unb = segments[0][1]
    header = {"syntax": element(unb, 1), "sender": element(unb, 2), "recipient": element(unb, 3),
              "date": element(unb, 4), "time": element(unb, 4, 1), "reference": element(unb, 5)}
    current = None
    for tag, data in segments[1:]:
        if tag == "UNH":
            current = {"ref": element(data, 1), "type": ":".join(data[1]) if len(data) > 1 else "",
                       "segments": [(tag, data)]}
        elif tag == "UNZ":
            count, ref = element(data, 1), element(data, 2)
            if ref != header["reference"]:
                problems.append(f"UNZ reference {ref} does not match UNB reference {header['reference']}")
            if count != str(len(messages)):
                problems.append(f"UNZ says {count} message(s), counted {len(messages)}")
            header["unz"] = f"UNZ count {count} = messages {len(messages)}; UNZ reference {ref} = UNB"
            current = None
            break
        elif current is None:
            problems.append(f"segment {tag} outside a message")
        else:
            current["segments"].append((tag, data))
            if tag == "UNT":
                messages.append(current)
                current = None
    else:
        problems.append("no UNZ segment: the interchange is incomplete")
    if current is not None:
        problems.append(f"message {current['ref']} has no UNT segment")
    return header, messages, problems


def map_message(msg, header, mapping):
    """Check one message and map it to the Unit 4 mock's order JSON. Returns (order or None, reason)."""
    segs = msg["segments"]
    unt = segs[-1][1]
    if element(unt, 1) != str(len(segs)):
        return None, f"UNT says {element(unt, 1)} segment(s), counted {len(segs)}"
    if element(unt, 2) != msg["ref"]:
        return None, f"UNT reference {element(unt, 2)} does not match UNH {msg['ref']}"
    if msg["type"] != "ORDERS:D:96A:UN":
        return None, f"message type {msg['type']} is not in the agreement"
    partner = mapping["partners"].get(header["sender"])
    if not partner:
        return None, f"sender {header['sender']} has no agreement"
    order = {"SoldToParty": partner["customer"], "PurchaseOrderByCustomer": "", "Items": [],
             "RequestedDeliveryDate": "", "Note": ""}
    item = None
    for tag, data in segs:
        if tag == "BGM":
            order["PurchaseOrderByCustomer"] = element(data, 2)
        elif tag == "DTM" and element(data, 1) == "2":
            value = element(data, 1, 1)
            order["RequestedDeliveryDate"] = f"{value[:4]}-{value[4:6]}-{value[6:]}"
        elif tag == "FTX":
            order["Note"] = element(data, 4)
        elif tag == "NAD" and element(data, 1) == "BY" and element(data, 2) != partner["customer"]:
            return None, f"buyer {element(data, 2)} is not the customer agreed for {header['sender']}"
        elif tag == "LIN":
            part = element(data, 3)
            material = mapping["parts"].get(part)
            if not material:
                return None, f"line {element(data, 1)}: partner part {part} has no mapping"
            item = {"Material": material, "PartnerPart": part}
            order["Items"].append(item)
        elif tag == "QTY" and item is not None:
            unit = mapping["units"].get(element(data, 1, 2))
            if not unit:
                return None, f"unit {element(data, 1, 2)} has no mapping"
            item["RequestedQuantity"] = int(element(data, 1, 1))
            item["RequestedQuantityUnit"] = unit
        elif tag == "CNT" and element(data, 1) == "2" and element(data, 1, 1) != str(len(order["Items"])):
            return None, f"CNT says {element(data, 1, 1)} line(s), counted {len(order['Items'])}"
    return order, ""


def check(text, mapping, quiet=False):
    """Check and map an interchange. Returns (accepted, rejected, envelope problems)."""
    header, messages, problems = read_interchange(text)
    say = (lambda *_: None) if quiet else print
    if problems:
        for problem in problems:
            say(f"  envelope  FAIL    {problem}")
        return [], [], problems
    say(f"Interchange {header['reference']} from {header['sender']} to {header['recipient']}, "
        f"{header['date']} {header['time']}, {len(messages)} message(s)")
    if header["recipient"] != mapping["recipient"]:
        say(f"  envelope  FAIL    recipient {header['recipient']} is not us")
        return [], [], ["wrong recipient"]
    say(f"  envelope  OK      {header['unz']}")
    accepted, rejected = [], []
    for msg in messages:
        order, reason = map_message(msg, header, mapping)
        po = next((element(d, 2) for t, d in msg["segments"] if t == "BGM"), "?")
        if order:
            key = f"{header['sender']}/{header['reference']}/{msg['ref']}"
            accepted.append((key, order))
            lines = ", ".join(f"{i['Material']} {i['RequestedQuantity']} {i['RequestedQuantityUnit']}"
                              for i in order["Items"])
            note = f'; note "{order["Note"]}"' if order["Note"] else ""
            say(f"  msg {msg['ref']}     ACCEPT  {po}  {lines}, due {order['RequestedDeliveryDate']}{note}")
        else:
            rejected.append((po, reason))
            say(f"  msg {msg['ref']}     REJECT  {po}  {reason}")
    say(f"{len(accepted)} accepted, {len(rejected)} rejected (synthetic)")
    return accepted, rejected, []


def deliver(accepted):
    """Send accepted orders to the Unit 4 mock (started here, in the background), then resend."""
    mock_path = HERE.parent / "unit04" / "mock_sap.py"
    if not mock_path.exists():
        print("No unit04/mock_sap.py. Complete Set up for Unit 4 first, or run without --deliver.")
        return 1
    spec = importlib.util.spec_from_file_location("mock_sap", mock_path)
    mock = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mock)
    server, _ = mock.start(port=0)
    base = f"http://127.0.0.1:{server.server_address[1]}"
    try:
        for attempt in ("first send", "partner resends the same interchange"):
            print(f"Deliver to the Unit 4 mock ({attempt}):")
            for key, order in accepted:
                body = json.dumps(order).encode("utf-8")
                request = urllib.request.Request(base + "/calder/inbound/orders", data=body, method="POST",
                                                 headers={"Content-Type": "application/json",
                                                          "APIKey": mock.API_KEY, "Idempotency-Key": key})
                try:
                    with urllib.request.urlopen(request, timeout=5) as answer:
                        data = json.loads(answer.read())
                        replay = " (replay, no new order)" if answer.headers.get("Idempotent-Replay") else ""
                        print(f"  {answer.status}  {order['PurchaseOrderByCustomer']} -> sales order "
                              f"{data['SalesOrder']}  key {key}{replay}")
                except urllib.error.HTTPError as error:
                    try:
                        reason = json.loads(error.read()).get("error", "")
                    except ValueError:
                        reason = "no readable answer"
                    print(f"  {error.code}  {order['PurchaseOrderByCustomer']}  refused: {reason}")
    finally:
        server.shutdown()
    return 0


def selftest():
    """Damage the sample in three ways and confirm each check catches it."""
    good = SAMPLE
    cases = [
        ("sample as written", good, (2, 1, 0)),
        ("UNT count wrong in message 1", good.replace("UNT+11+1'", "UNT+10+1'"), (1, 2, 0)),
        ("UNZ reference changed", good.replace("UNZ+3+HFS000417'", "UNZ+3+HFS000418'"), (0, 0, 1)),
        ("message 3 cut off before UNT", good.replace("UNT+12+3'\n", ""), (0, 0, 1)),
    ]
    failed = 0
    for label, text, expected in cases:
        accepted, rejected, problems = check(text, MAPPING, quiet=True)
        got = (len(accepted), len(rejected), min(len(problems), 1))
        ok = got == expected
        failed += 0 if ok else 1
        print(f"  {'OK' if ok else 'FAIL':<5} {label}: {got[0]} accepted, {got[1]} rejected, "
              f"envelope {'broken' if got[2] else 'fine'}")
    print("Self-test passed." if not failed else f"Self-test: {failed} case(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", help="write the sample interchange and mapping")
    parser.add_argument("--deliver", action="store_true", help="send accepted orders to the Unit 4 mock")
    parser.add_argument("--selftest", action="store_true", help="check that damaged copies are caught")
    parser.add_argument("--file", default=str(SAMPLE_FILE), help="interchange to read")
    args = parser.parse_args()

    if args.selftest:
        return selftest()
    if args.init:
        EDI_DIR.mkdir(exist_ok=True)
        for path, content in ((SAMPLE_FILE, SAMPLE), (MAP_FILE, json.dumps(MAPPING, indent=2) + "\n")):
            if path.exists():
                print(f"{path.name} already exists; delete it first to start again.")
            else:
                path.write_text(content, encoding="utf-8")
                print(f"Wrote {path.relative_to(HERE.parent).as_posix()}")
        return 0
    path = pathlib.Path(args.file)
    if not path.exists() or not MAP_FILE.exists():
        print("No sample yet. Run: python unit26/edi_lab.py --init")
        return 1
    mapping = json.loads(MAP_FILE.read_text(encoding="utf-8"))
    accepted, _, problems = check(path.read_text(encoding="utf-8"), mapping)
    if problems:
        return 2
    OUT_DIR.mkdir(exist_ok=True)
    for _, order in accepted:
        (OUT_DIR / f"{order['PurchaseOrderByCustomer']}.json").write_text(
            json.dumps(order, indent=2) + "\n", encoding="utf-8")
    print(f"Wrote {len(accepted)} order file(s) to {OUT_DIR.relative_to(HERE.parent).as_posix()}/")
    return deliver(accepted) if args.deliver else 0


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

2. Write the sample interchange and the mapping table:

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

   You should see:

   ```text
   Wrote unit26/edi/hallam_orders_HFS000417.edi
   Wrote unit26/edi/hallam_map.json
   ```

3. Open `unit26/edi/hallam_orders_HFS000417.edi` in VS Code and read it. Three purchase orders from Hallam sit in one interchange.

#### Step 3: Check and map the interchange

1. Run the lab:

   ```bash
   python unit26/edi_lab.py
   ```

2. Compare with the expected output:

   ```text
   Interchange HFS000417 from HALLAMFS to CALDERCP10, 20261123 0815, 3 message(s)
     envelope  OK      UNZ count 3 = messages 3; UNZ reference HFS000417 = UNB
     msg 1     ACCEPT  HFS-PO-8201  CP-SK200 40 PC, due 2026-12-04
     msg 2     REJECT  HFS-PO-8202  line 2: partner part HFS-BRG-6310 has no mapping
     msg 3     ACCEPT  HFS-PO-8203  CP-ES200 2 PC, due 2026-12-11; note "Dock 3: call M. Ostrander's desk first"
   2 accepted, 1 rejected (synthetic)
   Wrote 2 order file(s) to unit26/edi/out/
   ```

   Message 3's note was written as `Dock 3?: call M. Ostrander?'s desk first`. The `?` released the colon and the apostrophe, so neither split the segment.

3. If you have the Unit 4 mock, send the accepted orders to it. The lab starts the mock in the background by itself; you don't need a second terminal:

   ```bash
   python unit26/edi_lab.py --deliver
   ```

   The last lines are:

   ```text
   Deliver to the Unit 4 mock (first send):
     201  HFS-PO-8201 -> sales order 1000201  key HALLAMFS/HFS000417/1
     201  HFS-PO-8203 -> sales order 1000202  key HALLAMFS/HFS000417/3
   Deliver to the Unit 4 mock (partner resends the same interchange):
     201  HFS-PO-8201 -> sales order 1000201  key HALLAMFS/HFS000417/1 (replay, no new order)
     201  HFS-PO-8203 -> sales order 1000202  key HALLAMFS/HFS000417/3 (replay, no new order)
   ```

   Without `unit04/mock_sap.py` you see a message saying so; Steps 4 to 6 still work.

> **Note** These orders, partners and part numbers are synthetic. Calder and Hallam are fictional, and the mapping is a course table, not SAP configuration.

#### Step 4: Break the interchange on purpose

1. Open `unit26/edi/hallam_orders_HFS000417.edi`.
2. Change the line `UNT+11+1'` to `UNT+10+1'` and save.
3. Run `python unit26/edi_lab.py` again. Message 1 is now rejected:

   ```text
     msg 1     REJECT  HFS-PO-8201  UNT says 10 segment(s), counted 11
   ```

4. Change it back to `UNT+11+1'`, save and rerun. The lab's own `--selftest` tries this and two more breakages:

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

   ```text
     OK    sample as written: 2 accepted, 1 rejected, envelope fine
     OK    UNT count wrong in message 1: 1 accepted, 2 rejected, envelope fine
     OK    UNZ reference changed: 0 accepted, 0 rejected, envelope broken
     OK    message 3 cut off before UNT: 0 accepted, 0 rejected, envelope broken
   Self-test passed.
   ```

   A broken envelope rejects the whole interchange, because the lab can no longer trust what is inside it.

#### Step 5: Create and run the event lab

1. Create `unit26/event_lab.py`, paste the code below and save:

```python
"""A local event broker for Unit 26: topics, wildcards, queues, direct versus guaranteed delivery.

Run from your course folder:
    python unit26/event_lab.py              # run Calder's sales order event day, one line per step
    python unit26/event_lab.py --direct     # the same day with the CRM on direct delivery (no queue)
    python unit26/event_lab.py --match TOPIC PATTERN   # test one subscription against one topic
    python unit26/event_lab.py --selftest   # prove the wildcard rules and the day's results

Built-in Python only, no randomness, no network. This is a teaching stand-in for an event broker,
not SAP Integration Suite, advanced event mesh. The event types follow SAP's published S/4HANA sales
order events; topics, IDs, queue names and the redelivery limit are course labels. Calder Pumpworks
is fictional. Events use the CloudEvents attributes id, source, specversion and type.
"""
import argparse
import json
import sys

SOURCE = "/default/sap.s4/S4P"          # course value for Calder's production S/4HANA (CP10)
TOPIC_ROOT = "default/sap.s4/S4P/ce/sap/s4/beh/salesorder/v1/SalesOrder"
MAX_DELIVERIES = 3                      # course rule: after 3 failed deliveries, to the dead-letter queue


def matches(pattern, topic):
    """Subscription matching: '*' is one level (or a prefix such as 'Chan*'); '>' at the end is one or more."""
    p_levels, t_levels = pattern.split("/"), topic.split("/")
    for i, p in enumerate(p_levels):
        if p == ">" and i == len(p_levels) - 1:
            return len(t_levels) > i        # at least one more level
        if i >= len(t_levels):
            return False
        if p == "*":
            continue
        if p.endswith("*") and t_levels[i].startswith(p[:-1]):
            continue
        if p != t_levels[i]:
            return False
    return len(p_levels) == len(t_levels)


def event(eid, action, order, version, payload=None):
    """One CloudEvents envelope. 'data' is what a consumer reads; the rest is the envelope."""
    return {"specversion": "1.0", "id": eid, "source": SOURCE,
            "type": f"sap.s4.beh.salesorder.v1.SalesOrder.{action}.v1",
            "time": "2026-11-23T08:00:00Z", "datacontenttype": "application/json",
            "data": payload if payload is not None else {"SalesOrder": order, "Version": version},
            "_topic": f"{TOPIC_ROOT}/{action}/v1"}


class Broker:
    """Queues keep guaranteed messages until a consumer acknowledges them; direct subscribers don't."""

    def __init__(self):
        self.queues = {}     # name -> {"subs": [...], "messages": [[event, deliveries]], "dlq": name}
        self.direct = {}     # client -> {"subs": [...], "online": bool, "received": [...]}
        self.log = []

    def add_queue(self, name, subscriptions, dlq=None):
        self.queues[name] = {"subs": subscriptions, "messages": [], "dlq": dlq}

    def add_direct(self, client, subscriptions):
        self.direct[client] = {"subs": subscriptions, "online": True, "received": []}

    def publish(self, evt):
        topic, copies = evt["_topic"], []
        for name, q in self.queues.items():
            if any(matches(s, topic) for s in q["subs"]):
                q["messages"].append([evt, 0])
                copies.append(name)
        for client, d in self.direct.items():
            if any(matches(s, topic) for s in d["subs"]):
                if d["online"]:
                    d["received"].append(evt["id"])
                    copies.append(f"{client} (direct)")
                else:
                    copies.append(f"{client} (direct, offline: lost)")
        return copies


class Consumer:
    """Reads its queue, skips duplicates by source + id, ignores older versions, acks what it handled."""

    def __init__(self, name, broker, queue):
        self.name, self.broker, self.queue = name, broker, queue
        self.seen, self.orders, self.applied = set(), {}, []
        self.crash_before_ack = set()   # event IDs where the process dies after work, before the ack

    def handle(self, evt):
        key = (evt["source"], evt["id"])
        if key in self.seen:
            return "duplicate, already applied"
        data = evt.get("data")
        if not isinstance(data, dict) or "SalesOrder" not in data:
            raise ValueError("data has no SalesOrder")
        order, version = data["SalesOrder"], data.get("Version", 0)
        self.seen.add(key)
        if version <= self.orders.get(order, 0):
            return f"order {order} v{version} older than v{self.orders[order]}, ignored"
        self.orders[order] = version
        self.applied.append(evt["id"])
        return f"applied order {order} v{version}"

    def drain(self, say):
        q = self.broker.queues[self.queue]
        while q["messages"]:
            entry = q["messages"][0]
            evt = entry[0]
            entry[1] += 1
            try:
                result = self.handle(evt)
            except ValueError as error:
                if entry[1] >= MAX_DELIVERIES:
                    q["messages"].pop(0)
                    self.broker.queues[q["dlq"]]["messages"].append([evt, entry[1]])
                    say(f"  {self.name:<4} {evt['id']}  delivery {entry[1]}: {error}; moved to {q['dlq']}")
                else:
                    say(f"  {self.name:<4} {evt['id']}  delivery {entry[1]}: {error}; not acknowledged")
                continue
            if evt["id"] in self.crash_before_ack:
                self.crash_before_ack.discard(evt["id"])
                say(f"  {self.name:<4} {evt['id']}  delivery {entry[1]}: {result}; crashed before the ack")
                return
            q["messages"].pop(0)
            say(f"  {self.name:<4} {evt['id']}  delivery {entry[1]}: {result}; acknowledged")


def run_day(direct_crm=False, quiet=False):
    """Calder's sales order events on 2026-11-23. Returns a summary dictionary."""
    say = (lambda *_: None) if quiet else print
    broker = Broker()
    broker.add_queue("q/crm/dlq", [])
    broker.add_queue("q/dw/dlq", [])
    if direct_crm:
        broker.add_direct("CRM", [f"{TOPIC_ROOT}/*/v1"])
    else:
        broker.add_queue("q/crm/salesorder", [f"{TOPIC_ROOT}/*/v1"], dlq="q/crm/dlq")
    broker.add_queue("q/dw/s4", ["default/sap.s4/S4P/ce/sap/s4/beh/>"], dlq="q/dw/dlq")
    broker.add_direct("DASH", [f"{TOPIC_ROOT}/Changed/v1"])
    crm = None if direct_crm else Consumer("CRM", broker, "q/crm/salesorder")
    dw = Consumer("DW", broker, "q/dw/s4")

    day = [
        ("publish", event("evt-0001", "Changed", "1000011", 1)),
        ("drain", None),
        ("offline", None),
        ("publish", event("evt-0002", "Changed", "1000011", 2)),
        ("publish", event("evt-0004", "Created", "1000012", 1)),
        ("publish", event("evt-0003", "Changed", "1000011", 3)),
        ("publish", event("evt-0009", "Changed", "1000011", 0, payload="NOT JSON")),
        ("online", None),
        ("drain", None),
        ("drain", None),
    ]
    if crm:
        crm.crash_before_ack.add("evt-0003")
    mode = "direct (no queue)" if direct_crm else "guaranteed, queue q/crm/salesorder"
    say(f"Calder sales order events, 2026-11-23 (synthetic). CRM on {mode}.")
    for step, evt in day:
        if step == "publish":
            copies = broker.publish(evt)
            say(f"  pub  {evt['id']}  {evt['type'].split('.')[-2]:<7} -> {', '.join(copies)}")
        elif step == "offline":
            say("  ---  CRM and the dashboard go offline (maintenance window)")
            if "CRM" in broker.direct:
                broker.direct["CRM"]["online"] = False
            broker.direct["DASH"]["online"] = False
        elif step == "online":
            say("  ---  CRM and the dashboard are back")
            if "CRM" in broker.direct:
                broker.direct["CRM"]["online"] = True
            broker.direct["DASH"]["online"] = True
        elif step == "drain":
            for consumer in (crm, dw):
                if consumer:
                    consumer.drain(say)

    crm_applied = crm.applied if crm else broker.direct["CRM"]["received"]
    summary = {
        "crm_applied": crm_applied,
        "crm_latest_1000011": crm.orders.get("1000011") if crm else None,
        "dw_applied": dw.applied,
        "dashboard_received": broker.direct["DASH"]["received"],
        "crm_dlq": [e["id"] for e, _ in broker.queues["q/crm/dlq"]["messages"]],
        "dw_dlq": [e["id"] for e, _ in broker.queues["q/dw/dlq"]["messages"]],
    }
    say("Result:")
    say(f"  CRM applied {crm_applied}" + (f", order 1000011 at v{summary['crm_latest_1000011']}" if crm else
                                         " (direct: no acks, nothing kept while offline)"))
    say(f"  DW applied {dw.applied}")
    say(f"  dashboard received {summary['dashboard_received']} (direct: missed what was sent while offline)")
    say(f"  dead-letter queues: q/crm/dlq {summary['crm_dlq']}, q/dw/dlq {summary['dw_dlq']}")
    return summary


def selftest():
    root = TOPIC_ROOT
    cases = [
        (f"{root}/*/v1", f"{root}/Changed/v1", True),
        (f"{root}/*/v1", f"{root}/Changed/v2", False),
        (f"{root}/Chan*/v1", f"{root}/Changed/v1", True),
        ("default/sap.s4/S4P/ce/sap/s4/beh/>", f"{root}/Created/v1", True),
        ("default/sap.s4/S4P/ce/sap/s4/beh/>", "default/sap.s4/S4P/ce/sap/s4/beh", False),
        ("default/sap.s4/S4Q/ce/>", f"{root}/Created/v1", False),
    ]
    failed = 0
    for pattern, topic, expected in cases:
        ok = matches(pattern, topic) == expected
        failed += 0 if ok else 1
        print(f"  {'OK' if ok else 'FAIL':<5} {pattern.replace(root, '<root>')}  vs  "
              f"{topic.replace(root, '<root>')}: {'match' if expected else 'no match'}")
    guaranteed, direct = run_day(quiet=True), run_day(direct_crm=True, quiet=True)
    checks = [
        ("queue: CRM applied every good event once", guaranteed["crm_applied"] == ["evt-0001", "evt-0002", "evt-0004", "evt-0003"]),
        ("queue: poison event parked after 3 deliveries", guaranteed["crm_dlq"] == ["evt-0009"]),
        ("direct: CRM lost the events sent while offline", direct["crm_applied"] == ["evt-0001"]),
        ("dashboard missed evt-0002 and evt-0003", guaranteed["dashboard_received"] == ["evt-0001"]),
    ]
    for label, ok in checks:
        failed += 0 if ok else 1
        print(f"  {'OK' if ok else 'FAIL':<5} {label}")
    print("Self-test passed." if not failed else f"Self-test: {failed} case(s) failed.")
    return 0 if not failed else 2


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("--direct", action="store_true", help="run the CRM on direct delivery")
    parser.add_argument("--match", nargs=2, metavar=("TOPIC", "PATTERN"), help="test one subscription")
    parser.add_argument("--selftest", action="store_true", help="check the wildcard rules and the day")
    parser.add_argument("--show", metavar="ID", help="print one event envelope as JSON, e.g. evt-0002")
    args = parser.parse_args()
    if args.selftest:
        return selftest()
    if args.match:
        topic, pattern = args.match
        print("match" if matches(pattern, topic) else "no match")
        return 0
    if args.show:
        number = int(args.show.split("-")[-1]) if args.show.startswith("evt-") else 0
        known = {1: ("Changed", "1000011", 1), 2: ("Changed", "1000011", 2), 3: ("Changed", "1000011", 3),
                 4: ("Created", "1000012", 1)}
        if number not in known:
            print("Known events: evt-0001, evt-0002, evt-0003, evt-0004")
            return 1
        evt = event(args.show, *known[number])
        print(f"topic: {evt.pop('_topic')}")
        print(json.dumps(evt, indent=2))
        return 0
    run_day(direct_crm=args.direct)
    return 0


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

2. Run Calder's event day:

   ```bash
   python unit26/event_lab.py
   ```

3. Compare with the expected output:

   ```text
   Calder sales order events, 2026-11-23 (synthetic). CRM on guaranteed, queue q/crm/salesorder.
     pub  evt-0001  Changed -> q/crm/salesorder, q/dw/s4, DASH (direct)
     CRM  evt-0001  delivery 1: applied order 1000011 v1; acknowledged
     DW   evt-0001  delivery 1: applied order 1000011 v1; acknowledged
     ---  CRM and the dashboard go offline (maintenance window)
     pub  evt-0002  Changed -> q/crm/salesorder, q/dw/s4, DASH (direct, offline: lost)
     pub  evt-0004  Created -> q/crm/salesorder, q/dw/s4
     pub  evt-0003  Changed -> q/crm/salesorder, q/dw/s4, DASH (direct, offline: lost)
     pub  evt-0009  Changed -> q/crm/salesorder, q/dw/s4, DASH (direct, offline: lost)
     ---  CRM and the dashboard are back
     CRM  evt-0002  delivery 1: applied order 1000011 v2; acknowledged
     CRM  evt-0004  delivery 1: applied order 1000012 v1; acknowledged
     CRM  evt-0003  delivery 1: applied order 1000011 v3; crashed before the ack
     DW   evt-0002  delivery 1: applied order 1000011 v2; acknowledged
     DW   evt-0004  delivery 1: applied order 1000012 v1; acknowledged
     DW   evt-0003  delivery 1: applied order 1000011 v3; acknowledged
     DW   evt-0009  delivery 1: data has no SalesOrder; not acknowledged
     DW   evt-0009  delivery 2: data has no SalesOrder; not acknowledged
     DW   evt-0009  delivery 3: data has no SalesOrder; moved to q/dw/dlq
     CRM  evt-0003  delivery 2: duplicate, already applied; acknowledged
     CRM  evt-0009  delivery 1: data has no SalesOrder; not acknowledged
     CRM  evt-0009  delivery 2: data has no SalesOrder; not acknowledged
     CRM  evt-0009  delivery 3: data has no SalesOrder; moved to q/crm/dlq
   Result:
     CRM applied ['evt-0001', 'evt-0002', 'evt-0004', 'evt-0003'], order 1000011 at v3
     DW applied ['evt-0001', 'evt-0002', 'evt-0004', 'evt-0003']
     dashboard received ['evt-0001'] (direct: missed what was sent while offline)
     dead-letter queues: q/crm/dlq ['evt-0009'], q/dw/dlq ['evt-0009']
   ```

   Read three things in it. The queue kept `evt-0002` to `evt-0009` while the CRM was away. The CRM's crash meant `evt-0003` came twice, and the second time was skipped as a duplicate. The broken `evt-0009` was parked, not retried forever.

4. Run the same day with the CRM on direct delivery:

   ```bash
   python unit26/event_lab.py --direct
   ```

   The result line now reads `CRM applied ['evt-0001'] (direct: no acks, nothing kept while offline)`. Order `1000011` never reaches version 3 in the CRM.

5. Look at one envelope and test one subscription:

   ```bash
   python unit26/event_lab.py --show evt-0002
   python unit26/event_lab.py --match default/sap.s4/S4P/ce/sap/s4/beh/salesorder/v1/SalesOrder/Created/v1 "default/sap.s4/S4P/ce/sap/s4/beh/salesorder/v1/SalesOrder/*/v1"
   ```

   The first prints the topic and a CloudEvents JSON with `"specversion": "1.0"`. The second prints `match`. Keep the quotes around the pattern: without them, the terminal may expand the `*` itself.

> **Note** The event day is synthetic: the order numbers come from Calder's fictional order-to-cash scenario, and the source `/default/sap.s4/S4P` and the `Version` field are course values. Real S/4HANA event payloads differ; check the event's definition on the SAP Business Accelerator Hub.

#### Step 6: Run the Unit 26 check

This unit adds no Python libraries, so `requirements.txt` doesn't change.

1. In the course folder (not in `unit26`), create `check_unit26.py`, paste the code below and save:

```python
"""Check that your course folder is ready for Unit 26 (integration in depth).

Run it from your course folder:  python check_unit26.py
Built-in Python only. It runs the two Unit 26 labs' self-tests and reads trial dates from .env;
it calls no SAP service and changes nothing.
"""
import datetime
import os
import subprocess
import sys

problems = 0
TRIALS = {  # .env name: (what it is, length in days as SAP states it)
    "INTEGRATION_SUITE_TRIAL_START": ("Integration Suite basic trial", 30),
    "BTP_TRIAL_START": ("SAP BTP trial (Integration Suite in your own trial account)", 90),
}


def report(ok: bool, label: str, fix: str = "", optional: bool = False) -> None:
    """Print one line: OK, MISSING (must fix) or LATER (optional for now)."""
    global problems
    if ok:
        print(f"  OK       {label}")
    elif optional:
        print(f"  LATER    {label}  ->  {fix}")
    else:
        problems += 1
        print(f"  MISSING  {label}  ->  {fix}")


def env_value(name: str) -> str:
    """Read one line NAME=value from .env without extra libraries."""
    if not os.path.exists(".env"):
        return ""
    with open(".env", encoding="utf-8") as handle:
        for line in handle:
            if line.strip().startswith(name + "="):
                return line.split("=", 1)[1].strip().strip('"').strip("'")
    return ""


def selftest(script: str) -> str:
    """Run a lab's --selftest and return its last line, or '' if it failed."""
    done = subprocess.run([sys.executable, script, "--selftest"], capture_output=True, text=True, timeout=60)
    last = (done.stdout.strip().splitlines() or ["no output"])[-1]
    return last if done.returncode == 0 else ""


def main() -> int:
    today = datetime.date.today()
    print(f"Unit 26 check, {today.isoformat()}")

    report(sys.version_info >= (3, 10), f"Python {sys.version.split()[0]}", "install Python 3.10 or newer")
    report(os.path.isdir("unit26"), "folder unit26/", "run this from orchestrate-course, then: mkdir unit26")
    report(os.path.exists(os.path.join("unit04", "mock_sap.py")), "unit04/mock_sap.py (for --deliver)",
           "optional; complete Set up for Unit 4 to deliver EDI orders to the mock", optional=True)

    for name in ("edi_lab.py", "event_lab.py"):
        script = os.path.join("unit26", name)
        if not os.path.exists(script):
            report(False, f"unit26/{name}", "create it in the walkthrough")
            continue
        last = selftest(script)
        report(bool(last), f"{name} self-test: {last or 'failed'}", f"run: python unit26/{name} --selftest")

    sample = os.path.join("unit26", "edi", "hallam_orders_HFS000417.edi")
    report(os.path.exists(sample), "unit26/edi/ sample interchange", "run: python unit26/edi_lab.py --init")

    for name, (label, days) in TRIALS.items():
        value = env_value(name)
        if not value:
            report(False, label, f"optional; add {name}=YYYY-MM-DD to .env when you start it", optional=True)
            continue
        try:
            start = datetime.date.fromisoformat(value)
        except ValueError:
            report(False, f"{label} date '{value}'", "use the form YYYY-MM-DD")
            continue
        left = days - (today - start).days
        if left > 0:
            report(True, f"{label}: {left} day(s) left of {days}")
        else:
            report(False, f"{label} ended {-left} day(s) ago", "register again only when a topic needs it",
                   optional=True)

    print("Ready for Unit 26." if problems == 0 else f"{problems} item(s) to fix before Unit 26.")
    return 0 if problems == 0 else 1


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

2. Run it:

   ```bash
   python check_unit26.py
   ```

3. Before any trial, the output looks like this (your date and Python version differ):

   ```text
   Unit 26 check, 2026-11-29
     OK       Python 3.12.7
     OK       folder unit26/
     OK       unit04/mock_sap.py (for --deliver)
     OK       edi_lab.py self-test: Self-test passed.
     OK       event_lab.py self-test: Self-test passed.
     OK       unit26/edi/ sample interchange
     LATER    Integration Suite basic trial  ->  optional; add INTEGRATION_SUITE_TRIAL_START=YYYY-MM-DD to .env when you start it
     LATER    SAP BTP trial (Integration Suite in your own trial account)  ->  optional; add BTP_TRIAL_START=YYYY-MM-DD to .env when you start it
   Ready for Unit 26.
   ```

   `LATER` lines are fine. If you skipped Unit 4, the mock line shows `LATER` too.

#### Step 7: Start a trial (optional)

Pick one route. Each is personal and non-productive; never load Calder's or your company's real partner files into it.

**Basic trial (a shared tenant, 30 days)**

1. Open `https://www.sap.com/products/technology-platform/integration-suite/trial.html`.
2. Follow the registration form on the page and the email SAP sends.
3. Add one line with today's date to `.env`:

   ```text
   INTEGRATION_SUITE_TRIAL_START=2026-11-29
   ```

**Your own tenant in a BTP trial**

1. Open `https://developers.sap.com/tutorials/cp-starter-isuite-onboard-subscribe.html` and follow it. In short, as the tutorial stood on 29 November 2026: go to your trial account, use a subaccount in the **Singapore - Azure** region, open **Services > Instances and Subscriptions**, choose **Create**, pick **Integration Suite** with plan **trial**, then assign the **Integration_Provisioner** role collection under **Security**.
2. Open Integration Suite, choose **Add Capabilities**, and select **Build Integration Scenarios** and **Manage APIs**. Wait until the tiles appear.
3. If your BTP trial date isn't in `.env` yet from Unit 21, add it:

   ```text
   BTP_TRIAL_START=2026-11-29
   ```

Rerun `python check_unit26.py`. A trial you started now shows `OK` with the days left.

> **Warning** Trial user names and passwords are secrets. Keep them in a password manager, not in `.env`, a script or Git.

#### Step 8: Save your work in Git

```bash
git add unit26 check_unit26.py
git commit -m "Unit 26 setup: EDI lab, event lab and check"
```

`unit26/edi/out/` holds generated files; commit them or add the folder to `.gitignore`, as you prefer.

#### How the code works

| Part | What it does |
| --- | --- |
| `split_segments()` | Splits the interchange on the segment terminator, skipping any character after the release character `?` |
| `parse_segment()`, `split_on()` | Split a segment into data elements on `+`, then into components on `:`, and remove release characters |
| `read_interchange()` | Groups segments into messages between `UNH` and `UNT`, then checks `UNZ` against `UNB` and the message count |
| `map_message()` | Checks `UNT`'s count, the message version and the buyer, and maps parts and units with `hallam_map.json` |
| `deliver()` | Loads the Unit 4 mock from its file, starts it on a free port and posts each order twice with the same idempotency key |
| `matches()` | The wildcard rules: `*` is one level or a prefix within a level, `>` at the end is one or more levels |
| `Broker.publish()` | Copies an event to every queue whose subscription matches; direct subscribers get it only while online |
| `Consumer.drain()` | Delivers from the queue head, acknowledges on success, counts failed deliveries and parks after three |
| `Consumer.handle()` | Skips a repeated `source` and `id`, ignores an older version, and applies the rest |
| `check_unit26.py` | Runs both self-tests, checks the sample file and counts down trial dates from `.env` |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python: command not found` or `'python' is not recognized` | Python isn't on your PATH, or the virtual environment is off | Turn on `.venv` (Step 1); on macOS/Linux try `python3` |
| `No sample yet` | `--init` hasn't run | Run `python unit26/edi_lab.py --init` |
| `already exists; delete it first` | `--init` won't overwrite your edits | Delete the file only if you want the sample back |
| `envelope FAIL` on every run | An edit broke `UNB`, `UNZ` or a `UNT` line | Undo the edit, or delete `unit26/edi` and run `--init` |
| `No unit04/mock_sap.py` | The Unit 4 mock isn't in your course folder | Complete Set up for Unit 4, or skip `--deliver` |
| `Address already in use` | Unlikely here: `--deliver` picks a free port | Close other mock windows and rerun |
| `--match` prints `no match` for a pattern with `*` | The terminal expanded the `*` | Put the pattern in double quotes |
| A trial page won't load or the form fails | A company proxy or firewall blocks sap.com sign-ups | Use a personal network, or skip the trial; no Unit 26 exercise needs it |
| `ModuleNotFoundError` | You ran another unit's script by mistake | These scripts use built-in modules only; check the file name |

### Where this shows up in SAP

Each lab rule has a home in SAP's tools, which later Unit 26 topics open up:

- **EDI checks and mapping.** Trading Partner Management and Integration Advisor, both in SAP Learning's capability list ([SAP Learning](https://learning.sap.com/courses/administering-sap-integration-suite/understanding-capabilities)), are the B2B side of Integration Suite; [B2B and EDI with Trading Partner Management](https://erpfde.com/topics/b2b-and-edi-integration/) opens them up. The [how SAP systems talk](https://erpfde.com/topics/how-sap-systems-talk/) topic showed where a partner's message lands on the SAP side, as an IDoc or an API call.
- **Queues and dead-letters.** Advanced event mesh keeps guaranteed messages on durable endpoints until a client acknowledges them ([SAP documentation](https://help.pubsub.em.services.cloud.sap/Get-Started/message-delivery-modes.htm)). The lab's `q/crm/dlq` stands for the place a broker parks what can't be delivered; the exact settings are in [event mesh and event-driven architecture](https://erpfde.com/topics/event-mesh-and-event-driven-architecture/).
- **Topic design.** SAP's tutorial shows S/4HANA topics with the system, source, object, action and version as levels ([SAP tutorial](https://developers.sap.com/tutorials/pubsub-view-events.html)). The lab's subscriptions use the same shape so the wildcards behave the same way.

### Where AI fits

The basic trial page names AI-assisted tools for designing integration flows ([sap.com](https://www.sap.com/products/technology-platform/integration-suite/trial.html)). The [AI in SAP Integration Suite](https://erpfde.com/topics/ai-in-sap-integration-suite/) topic covers what they do; [Cloud Integration flows in depth](https://erpfde.com/topics/cloud-integration-flows-in-depth/) reviews a flow against design rules, whoever wrote it. Two of the labs' cases are also where agents add risk. An agent that consumes events must skip duplicates by `source` and `id` like any other consumer. And an agent that reads partner free text, such as message 3's delivery note, reads text a partner wrote, not an instruction from Calder.

### Production concerns

- **Trials are not pilots.** Both routes are non-productive. Proofs of concept with partner files belong in a non-production tenant Calder owns.
- **Name the owners.** The mapping table and each dead-letter queue need an owner and a daily check, as the [integration lead's toolkit](https://erpfde.com/topics/the-integration-leads-toolkit/) set out for `I10`.
- **Count what you pay for.** Message volume is the pricing unit; large messages count more than once.
- **Keep the labs' labels out of designs.** Queue names, the three-delivery limit, the `Version` field and the qualifier values are course values.

### Pitfalls

- Starting the 30-day trial on day one and losing it before the flow and API topics.
- Reading the basic trial's missing admin screens as missing features.
- Retrying an EDI message that failed a mapping: it fails the same way every time.
- Putting a consumer that must not miss events on direct delivery.
- Skipping duplicates by order number alone: two different changes to one order would look like one event.
- Copying trial passwords into `.env` or a script.

### Exercise: fix the mapping, then meet the next failure

Hallam's buyer confirms that `HFS-BRG-6310` is their number for Calder's spare bearing `CP-BRG6310`.

1. Open `unit26/edi/hallam_map.json`.
2. In `parts`, add `"HFS-BRG-6310": "CP-BRG6310"` after the last entry. Mind the comma on the line before. Save.
3. Run `python unit26/edi_lab.py`. You now get `3 accepted, 0 rejected (synthetic)`.
4. Run `python unit26/edi_lab.py --deliver`. `HFS-PO-8202` is now refused by the mock:

   ```text
     400  HFS-PO-8202  refused: Product CP-BRG6310 does not exist
   ```

   The EDI mapping is right; the receiving system doesn't sell bearings yet. That is a master data problem, not an interface problem.
5. In `unit26/notes.md`, write three sentences: who at Calder owns the mapping table, who owns the missing product, and what the dead letter for `HFS-PO-8202` should say so the right person picks it up.

**Done when** the lab prints `3 accepted, 0 rejected (synthetic)`, `--deliver` shows two `201` lines and one `400` for `HFS-PO-8202` on each send, and `notes.md` holds your three sentences. [B2B and EDI with Trading Partner Management](https://erpfde.com/topics/b2b-and-edi-integration/) builds its partner agreement on this mapping.

### Check yourself

1. You need to show the team who adds Integration Suite capabilities and how. Which trial route fits?
   - A. The basic trial, because it has every capability enabled
   - B. Your own tenant in a BTP trial, set up with SAP's tutorial
   - C. An advanced event mesh trial from SAP's product page
   - D. Either; both include administration rights in the same way

   Answer: B. The basic trial is a shared tenant without administration rights. In your own tenant you assign Integration_Provisioner and choose Add Capabilities yourself, as SAP's tutorial shows.

2. In `edi_lab.py`, why is a broken `UNZ` reference handled differently from an unmapped part?
   - A. A broken envelope means nothing inside it can be trusted
   - B. An unmapped part can be fixed by retrying the message
   - C. UNZ is optional in EDIFACT, so the lab only warns about it
   - D. The UNZ check runs after mapping, so it only affects one order

   Answer: A. The envelope says who sent what and how many messages; if it doesn't add up, the lab rejects the whole interchange. An unmapped part rejects only its own message, and a retry won't fix it either.

3. Hallam's EDI provider resends interchange `HFS000417` after a network error. Why doesn't Calder get two sets of orders?
   - A. The mock rejects any order from Hallam it has seen this week
   - B. EDIFACT forbids a sender from reusing an interchange reference
   - C. The broker deletes the second copy before it reaches the mock
   - D. Each order's key repeats, so the mock replays its first answer

   Answer: D. `deliver()` builds the idempotency key from sender, interchange reference and message number. The resend produces the same keys, so the Unit 4 mock returns the stored sales orders with a replay header instead of creating new ones.

4. The CRM crashed after applying `evt-0003` but before acknowledging it. What happens next in the lab?
   - A. The event is lost, because it was taken off the queue
   - B. The event goes straight to the dead-letter queue
   - C. It is delivered again and skipped by source and id
   - D. The CRM applies it a second time and order 1000011 reaches v4

   Answer: C. A guaranteed message stays on the queue until it is acknowledged, so the broker delivers it again. The consumer has already recorded that `source` and `id`, so it skips the work and acknowledges, as CloudEvents' uniqueness rule allows.

5. What does `--direct` show about the CRM, and what follows for Calder's design?
   - A. Direct is faster, so the CRM ends at version 3 sooner
   - B. Direct keeps events while the CRM is offline, like a queue
   - C. Events sent while it was offline are lost; it needs a queue
   - D. Direct sends duplicates, so the CRM needs a dead-letter queue

   Answer: C. Direct messages are not kept for a disconnected client and are not acknowledged, so the CRM applies only `evt-0001`. A consumer that must not miss sales order changes belongs on guaranteed delivery with a durable queue.

6. Does the subscription `default/sap.s4/S4P/ce/sap/s4/beh/>` receive an event on `default/sap.s4/S4P/ce/sap/s4/beh` itself?
   - A. Yes, because `>` matches zero or more levels
   - B. No, because `>` needs at least one more level
   - C. Yes, but only when the event uses guaranteed delivery
   - D. No, because `>` may only be used in the first level

   Answer: B. In the lab, as in SAP's examples, `>` at the last level stands for one or more levels below the prefix. A topic that ends at the prefix has nothing below it, so it doesn't match.

7. Why does the event lab park `evt-0009` after three deliveries instead of retrying it forever?
   - A. Brokers delete any event that is older than three minutes
   - B. Three is the limit SAP sets for every advanced event mesh queue
   - C. A retry would change the event's id and break duplicate checks
   - D. A broken payload fails every time and blocks the queue behind it

   Answer: D. The payload has no `SalesOrder`, so no number of retries helps, and while it sits at the head of the queue later events wait. Parking it lets them flow and puts it in front of a person; the limit of three is a course value, not SAP's.

## Sources

- [Start your free trial of SAP Integration Suite (sap.com, read 2026-11-29)](https://www.sap.com/products/technology-platform/integration-suite/trial.html): 30-day basic trial on a shared tenant with sample data; a selected subset of functionality; design and test integration flows with cloud integration, API management and AI-assisted tools; no key user capabilities or administration rights
- [Set Up Integration Suite Trial (SAP Developers tutorial, read 2026-11-29)](https://developers.sap.com/tutorials/cp-starter-isuite-onboard-subscribe.html): BTP trial in the Singapore - Azure region; subscribe to Integration Suite with plan trial; assign Integration_Provisioner; Add Capabilities, Build Integration Scenarios and Manage APIs; boosters only in Singapore; one Integration Suite tenant per trial account; not for productive usage or team development
- [SAP Integration Suite pricing (sap.com, read 2026-11-29)](https://www.sap.com/products/technology-platform/integration-suite/pricing.html): three paid base editions, each with one or more tenants and an included monthly message volume; no free tier listed; a message over 250 KB counts as one more message per 250 KB or part of it; feature rows include Edge integration cell and MCP Gateway
- [Understanding Capabilities (SAP Learning, Administering SAP Integration Suite, read 2026-11-29)](https://learning.sap.com/courses/administering-sap-integration-suite/understanding-capabilities): capabilities Cloud Integration, API Management, Open Connectors, Graph, Event Mesh, Integration Advisor, Trading Partner Management, OData Provisioning, Data Space Integration, Integration Assessment, Migration Assessment; Integration_Provisioner role to add and manage capabilities
- [SAP Integration Suite, advanced event mesh (sap.com, read 2026-11-29)](https://www.sap.com/products/technology-platform/integration-suite/advanced-event-mesh.html): managed service for event-driven architectures, a mesh of event brokers across regions; base plans with Buy Now; no trial offered on the page
- [Message Delivery Modes (SAP Integration Suite, advanced event mesh documentation, read 2026-11-29)](https://help.pubsub.em.services.cloud.sap/Get-Started/message-delivery-modes.htm): direct messaging not retained for disconnected clients and not acknowledged; guaranteed messaging kept on a durable endpoint until a client acknowledges it; subscriptions tied to the endpoint
- [View Events in SAP Integration Suite, advanced event mesh (SAP Developers tutorial, read 2026-11-29)](https://developers.sap.com/tutorials/pubsub-view-events.html): S/4HANA event topic levels (system, ce, source, business object path, action, version); wildcard examples with * for one level and > for everything below; Try Me! with direct and persistent modes
- [CloudEvents specification (CNCF, main branch, read 2026-11-29)](https://raw.githubusercontent.com/cloudevents/spec/main/cloudevents/spec.md): required attributes id, source, specversion, type; specversion 1.0; source plus id unique per distinct event, a re-sent duplicate may keep its id; optional subject, time, datacontenttype, dataschema
- [EANCOM syntax and service segments (GS1, read 2026-11-29)](https://gs1.org/sites/gs1/files/docs/eancom/ean02s4/part1/part1_05.htm): default separators apostrophe, plus, colon, question mark as release character; UNA service string advice before UNB; UNB to UNZ and UNH to UNT mandatory; UNT segment count includes UNH and UNT; UNZ counts messages
- [EDIFACT ORDERS D.96A Purchase Order (TrueCommerce help, revised 2026-07-22, read 2026-11-29)](https://help.truecommerce.com/en/articles/16043911-edifact-orders-d-96a-purchase-order): required segments UNH message header, BGM beginning of message, DTM date/time/period, UNS section control, UNT message trailer; segment groups for parties and line items; summary with CNT; not a substitute for a partner's specification
