Orchestrate

Report an issue

Something wrong, out of date or unclear? Tell us. Corrections are prioritized over new topics. You don't need to sign in.

0 / 2000

Don't include personal or confidential company details. Reports are reviewed with AI assistance.

Connecting to SAP Business Network: S/4HANA, the managed gateway and supplier onboarding

How S/4HANA exchanges orders, confirmations, ship notices and invoices with suppliers on SAP Business Network, and how to design and run that link.

Updated Nov 30, 2026
Foundational layer · 8 min read

The 60-second version

SAP Business Network is SAP's cloud network where buyers and their trading partners exchange business documents. A buyer's S/4HANA sends purchase orders to it. Suppliers answer with order confirmations, ship notices and invoices, and those come back into S/4HANA as documents people can work with. A separate part of the network serves logistics: shippers and carriers exchange freight orders and their answers there.

Connecting to it is less about technology than it looks. SAP provides the pipe: S/4HANA's built-in integration, a gateway that SAP runs and maps for you, and standard content. What decides success is three things the buyer must design:

  1. Which systems talk to which network account. The network has a test account and a production account, and nothing else.
  2. Which suppliers join, and how. Strategic suppliers integrate their own systems. Small ones answer orders by email links or log on to the network for free.
  3. Who watches the traffic. A purchase order the network refused is a purchase order the supplier never saw.

The decision for a leader: treat supplier connectivity as a supplier program with an owner, not an IT interface. This topic uses the course's fictional company, Calder Pumpworks, and its interface I01 between SAP Business Network and S/4HANA.

Why it matters to the business

Purchasing runs on documents that cross the company boundary. When they travel by email and PDF, people retype them, and every retype is a delay and a chance for error. Using Calder (all numbers are course values):

  • The late confirmation nobody saw. In the exception trace, Orrin confirmed 20 motors for 18 November instead of 2 November. The date arrived through the network and reached the purchase order. Had it come as an email to one buyer, planning might not have seen it until the motors failed to arrive.
  • Receipts that start from the supplier's data. A ship notice becomes an inbound delivery in S/4HANA, so the receiving clerk scans what the supplier said is on the truck instead of keying it.
  • Invoices that match without typing. Network invoices refer to the order, so the three-way match in procure to pay starts with clean data.
  • Who pays. Suppliers on SAP Business Network pay nothing with a standard account. Suppliers on an enterprise account can pay a subscription and transaction fees once they pass thresholds with a buyer. A supplier who gets a bill nobody mentioned pushes back, and the program stalls.
  • Silent failures. If the connection breaks, purchase orders stop leaving and confirmations stop arriving. Nothing shouts unless someone designed the alert.

How SAP does it

As of 30 November 2026, these are the parts SAP describes:

  • SAP Business Network has a test and a production environment for each buyer, and no development environment (SAP Learning). Each buyer and supplier account has an ANID (Ariba Network ID) (SAP Learning).
  • Native integration in SAP S/4HANA Cloud. Scope item 42K, Automation of Source-to-Pay with SAP Business Network, is built into the system, with no add-on to install. SAP's course describes it for SAP S/4HANA Cloud Private Edition (SAP Learning). SAP's support notes also use 42K for SAP S/4HANA Cloud Public Edition (SAP Knowledge Base Article 3622008).
  • SAP Integration Suite, managed gateway for spend management and SAP Business Network sits between S/4HANA and the network. SAP runs it and supplies the mappings to and from cXML, the network's own document format. It used to be called SAP Ariba Cloud Integration Gateway (SAP Support).
  • For SAP ERP and on-premise S/4HANA, a managed gateway add-on provides the same connection, with settings maintained in Customizing (SAP Learning).
  • Supplier accounts. A standard account is free; an enterprise account is priced by subscription and transaction volume (SAP).
  • SAP Business Network for Logistics connects shippers and carriers. SAP says it works out of the box with SAP Transportation Management, standalone or embedded in S/4HANA (SAP Learning).

Licensing differs by contract and edition. SAP's blog on the supplier portal says it is an included entitlement for RISE with SAP S/4HANA Cloud, private edition, premium plus customers (SAP Community). Check your own order form before planning on it.

A decision guide: how each supplier joins

SAP's training sorts suppliers into groups: strategic suppliers that need full enablement, and the rest, who can join "on the fly" with standard accounts (SAP Learning). The table turns that into choices. Segment letters are a course label.

Supplier How it joins What it costs the supplier Calder example
A: strategic, high volume Enterprise account; its own system sends cXML or EDI Subscription and transaction fees above SAP's thresholds Orrin (motors), Ridgeline (seal kits)
B: regular, mid volume Standard account by the interactive order email; may integrate later Nothing on a standard account Tamsfield (castings)
C: occasional or small Standard account by the interactive order email Nothing Corvane (crane inspection), Brayford (coolant)
Carrier SAP Business Network for Logistics, invited by the shipper Set by that service Larkspur, Tallis
Supplier of a system about to retire Wait until it moves n/a Petrak, a supplier of Augsburg's ECC until July 2027

Questions to ask

  • Which S/4HANA system connects to the test account, and which to production? Is any development client connected?
  • Who owns supplier enablement: purchasing or IT? Who owns a refused document?
  • Which suppliers are strategic enough to integrate, and which stay on standard accounts?
  • Have we told enterprise-account suppliers what fees they may pay, before inviting them?
  • Which documents do we expect from each supplier: confirmations, ship notices, invoices, service entry sheets?
  • Where do we see a purchase order the network refused, and how fast?
  • Do carriers belong on this connection, or on SAP Business Network for Logistics?
  • What changes to SAP's standard mappings have we made, and are they on the cutover checklist?

Common misconceptions

  • "Connecting to the network is an IT project." The pipe takes weeks. Enabling suppliers, agreeing who pays and changing how buyers work takes much longer.
  • "Every supplier must integrate its ERP." Most suppliers can answer through the interactive order email or a free standard account. Integration pays only for high volumes.
  • "The network is free for everyone." It is free for standard accounts. Enterprise-account suppliers can pay fees once they pass SAP's thresholds with a buyer.
  • "The gateway fixes errors itself." It retries transient errors. A refused document needs a person who owns it.
  • "Carriers are suppliers, so they go on the same connection." Freight runs through SAP Business Network for Logistics, which speaks freight orders, not purchase orders.

Key terms

All course terms, A to Z, in the glossary

  • SAP Business Network: SAP's cloud network where buyers, suppliers and carriers exchange business documents.
  • ANID: Ariba Network ID, the unique identifier of an account on SAP Business Network.
  • cXML: commerce XML, the network's own document format for orders, confirmations, ship notices and invoices.
  • Managed gateway: SAP Integration Suite, managed gateway for spend management and SAP Business Network; the SAP-run service that connects ERP systems to the network.
  • Scope item 42K: SAP's prepared configuration for automating source-to-pay with SAP Business Network in SAP S/4HANA Cloud.
  • Quick Enablement: SAP's name for enabling a new supplier through the interactive purchase order email.
  • Standard account: a free supplier account for answering buyers' documents online.
  • Enterprise account: a supplier account with integration and reporting features, priced by subscription and transaction volume.
  • Trading relationship: the link between a buyer's and a supplier's accounts that lets documents flow between them.
  • System ID: the identifier of one ERP system in the buyer account, such as S4PCLNT100.
  • SAP Business Network for Logistics: the part of the network where shippers and carriers exchange freight documents.

Check yourself

Pick one answer for each question. The explanation appears after you choose.

1Calder wants its suppliers on SAP Business Network. What should a leader treat as the main work?

Answer: B. SAP provides the connection, the gateway and the mappings. What decides success is enabling suppliers, agreeing who pays and who owns a refused document.

2Corvane inspects Calder's crane once a year. How should it join the network?

Answer: D. Occasional and small suppliers join through the interactive order email on a free standard account. Integration only pays for strategic, high-volume suppliers.

3A strategic supplier receives a fee invoice from SAP after joining on an enterprise account. What should Calder have done?

Answer: C. Enterprise-account suppliers can pay fees once they pass SAP's thresholds with a buyer. Telling them first keeps the program from stalling on a surprise bill.

4Which S/4HANA system should connect to the network's test account?

Answer: B. The network has only test and production. SAP's training advises against connecting the development client, whose master data is usually incomplete.

5Larkspur hauls Calder's pumps to customers. Where should freight documents go?

Answer: B. SAP Business Network for Logistics connects shippers and carriers and works with SAP Transportation Management. Carriers tender and confirm freight orders there.

6The network refuses a purchase order with a permanent error. What matters most?

Answer: A. A refused purchase order is one the supplier never saw. Retrying a permanent error changes nothing, so an owner must hear about it at once.
Deep layer · 40 min read

Mental model

A connection to SAP Business Network is three links in a chain, and each has a different owner:

  1. System to account. One S/4HANA system talks to one network account through the managed gateway. Its identity is the system ID and the gateway project. IT owns it.
  2. Account to supplier. A trading relationship links Calder's account to each supplier's account. The supplier's account type decides what it can do and what it pays. Purchasing owns it.
  3. Document to document. Each S/4HANA document becomes a cXML document and back: a purchase order an OrderRequest, a ship notice an inbound delivery. Mappings and output rules decide which, and process owners own the result.

Most connection problems are a broken link that someone thought belonged to someone else: a system ID typed differently in two places, a supplier with no email address, a refused order that only IT can see.

How it works

The parts

flowchart LR
  subgraph Calder
    S4Q[S/4HANA S4Q<br/>quality]
    S4P[S/4HANA S4P<br/>production]
    SCC[Cloud Connector<br/>SCC-RK-NP / SCC-RK-P]
  end
  subgraph SAP
    GW[Managed gateway<br/>one account, test + production]
    T[Network test account]
    P[Network production account]
  end
  S4Q -- SOAP out --> GW
  S4P -- SOAP out --> GW
  GW -- inbound calls --> SCC --> S4Q
  SCC --> S4P
  GW <--> T
  GW <--> P
  P <--> SUP[Suppliers' accounts]

SAP's course names four components: SAP Business Network, S/4HANA, the managed gateway and the Cloud Connector (SAP Learning). What each does:

  • The network keeps a test and a production environment per buyer. There is no development environment.
  • The managed gateway is integration as a service on SAP BTP, run by SAP in regional data centers. It maps S/4HANA's messages to cXML with standard content. One gateway account serves test and production.
  • The Cloud Connector carries calls from the gateway into S/4HANA through a tunnel that Calder's administrator controls. In the source-to-pay scenario, SAP's course says it is used only for these inbound calls. The course also mentions a mediated setup with your own Cloud Integration tenant in the middle.
  • S/4HANA sends and receives SOAP web services, configured in SOAMANAGER, and monitored in SRT_MONI (SAP Learning).

Identities that must match

Three identifiers tie the chain together, and they must agree everywhere:

Identifier Where it lives What breaks when it doesn't match
ANID of each account The network; assigned to a business system entry in S/4HANA Documents go to no account
System ID (S4QCLNT100, S4PCLNT100) The buyer account's Business Application IDs, the gateway's basic data, S/4HANA SAP's course says a mismatch typically leads to failed connections
Vendor ID (Calder's supplier number) The purchase order, and the supplier's relationship in the buyer account A document can't be routed to the supplier

The buyer account holds one system ID for the quality system in the test account, and one for production in the production account, with one marked as the default endpoint (SAP Learning). In Public Edition, an SAP support note adds that communication arrangements take a business partner number, not a supplier number, and recommends giving both the same number (SAP Knowledge Base Article 3622008).

Setup in three steps

Scope item 42K is set up in three steps (SAP Learning):

  1. Communication setup (once): the Cloud Connector, the business system and SOAMANAGER in S/4HANA, the system IDs in the buyer account, and the gateway project.
  2. Business process configuration (once): number ranges, output, texts, invoice settings.
  3. Supplier setup (again for every supplier): Quick Enablement.

The gateway's own setup has five steps: basic data with the system ID, a project covering the quality and production systems, connections to S/4HANA with the endpoint URL and credentials, testing, and deployment to production (SAP Learning).

For the Cloud Connector, SAP's course asks for separate subaccounts for test and production with the same location ID, virtual host and virtual port in both, backend type ABAP System, HTTPS, the internal host and port from transaction SMICM, no underscores in the virtual host, and the resource path /sap/ (SAP Learning). The BTP connectivity topic explains location IDs and virtual hosts.

Which documents flow

A purchase order leaves S/4HANA and arrives at the network as a cXML OrderRequest. SAP lists standard, blanket, scheduling agreement, service, subcontracting, returns and consignment orders, with changes and cancellations (SAP Learning). A 2022 SAP blog on Public Edition lists the documents of scope item 42K at the time: request for quotation, purchase order, advance ship notice, goods receipt, invoice, invoice status update and payment advice, plus service entry sheets sent by the supplier.

sequenceDiagram
  participant S as S/4HANA S4P
  participant G as Managed gateway
  participant N as Network
  participant V as Supplier (Orrin)
  S->>G: purchase order (SOAP)
  G->>N: cXML OrderRequest
  N-->>G: 2xx accepted
  N->>V: order in Orrin's account or system
  V->>N: order confirmation: 18 Nov
  N->>G: confirmation
  G->>S: via Cloud Connector: confirmation on the PO item
  V->>N: ship notice
  G->>S: inbound delivery
  S->>G: goods receipt
  V->>N: invoice
  G->>S: supplier invoice
  S->>G: invoice status, payment remittance

Which documents go out is decided by output in S/4HANA. SAP's course names two mechanisms: message control (NACE), and output control with output parameter determination (OPD) in BRFplus, recommended for new implementations. Rules run in order, and a row without a supplier acts as a wildcard, so it must come last (SAP Learning). A wildcard row that sends through the network would send every other supplier's orders there too.

Answers and retries

The network answers each cXML request at once. SAP's course describes three outcomes: a 2xx answer means accepted; a 4xx answer is a permanent error that the gateway logs; a 5xx answer is a temporary error, and the gateway sends the document again with the same payload ID, a set number of times (SAP Learning). The same payload ID is what lets the receiver recognize a repeat, the same idea as the message key in Cloud Integration flows. A flow that gives each retry a new ID can create a second order. A flow that retries a 4xx fails every time and hides the problem.

Enabling a supplier

Quick Enablement, also called the interactive purchase order flow, is how SAP's course enables a supplier with no account yet (SAP Learning):

  1. Calder sends a purchase order to a supplier with no trading relationship.
  2. The network creates a private ANID for the supplier, recording Calder's vendor ID and the sending system ID in the buyer account.
  3. The supplier gets an email with a Process Order button.
  4. The supplier creates an account (the private ANID becomes public) or links an existing one.
  5. The trading relationship is confirmed automatically by default, or by the supplier.
  6. The supplier confirms the order or turns it into an invoice.

The supplier master record must have an email address, and the vendor ID must be on the order. Without the email, there is no one to invite.

Account types. A standard account is free, with unlimited documents (SAP). SAP's training describes it as an email-based way to answer a buyer's order, without reporting or cXML and EDI integration. An account becomes an enterprise account when the supplier receives a non-standard trading relationship request, or upgrades itself (SAP Learning).

Fees. SAP's fee lesson, as read on 30 November 2026, says an enterprise-account supplier becomes chargeable after passing both 5 documents and 50,000 USD with one buyer in a rolling 12 months. The transaction fee is 0.155% of the volume with that buyer, or 0.35% when service entry sheets are used, capped at 20,000 USD per relationship a year. A subscription level depends on the document count, and the lesson says the Silver level (25 to 99 documents a year) is required for cXML and EDI. Some US suppliers are exempt (SAP Learning). SAP's pricing page lists five subscription levels while the lesson's table differs, so treat any estimate as a conversation starter and point suppliers to SAP's current fee schedule.

Carriers: a different network

Freight is a different conversation. SAP Business Network for Logistics offers out-of-the-box connectivity with SAP Transportation Management, standalone or embedded in S/4HANA, and carriers are invited by a shipper they work with (SAP Learning). An SAP blog on freight collaboration shows the link: the carrier's network ID is added to the carrier's business partner in TM with ID type LBN001, the freight order goes out as TransportationOrderRequest_Out, and the carrier's acceptance comes back as TransportationOrderConfirmation_In, both visible in SRT_MONI (SAP Community). At Calder, carriers are interface I06, today by email and portals; the warehouse and transportation topic covers tendering.

Changing SAP's standard

Two kinds of change are possible. A change to what suppliers see on the network is a UI customization that SAP's implementation services apply. A change to what travels is a mapping change in the gateway's mapping tool, which a buyer can make. Hiding schedule lines in the UI alone leaves them in the cXML; removing them needs the mapping. Both kinds belong on the cutover checklist, and mapping changes are activated in test before they are published to production (SAP Learning).

Monitoring

Errors can sit in three places, so each needs an owner:

  • S/4HANA: SRT_MONI shows web service messages, with restart from the Actions menu for some errors.
  • The gateway: the Transaction Tracker shows source and target payloads and attachments, and lets you reprocess. It keeps transaction documents for 30 days from creation (SAP Learning).
  • SAP Cloud ALM: the gateway writes status messages that Cloud ALM's Integration Monitoring collects, once an OAuth client from the SAP Ariba developer portal is linked to the buyer's ANID (SAP Support). The interface monitoring topic builds the alert routes.

Build it yourself: review Calder's network connection

You will run a lab with three parts. Review checks a connection design for I01 against twelve course rules. Replay sends six documents through the design and shows what happens to each. Fees estimates what each supplier may pay for Calder's share of its volume.

flowchart LR
  I[--init] --> D[design_draft.json]
  I --> V[design_reviewed.json]
  D --> R[review: BN01-BN12]
  V --> R
  D --> P[replay E1-E6]
  V --> P
  V --> F[fees per supplier]

Before you start: complete Set up your computer for this course and Set up for Unit 26. This walkthrough needs none of the setup's trials.

The design is a partner's first draft for I01, the interface from the exception trace that carries purchase orders, confirmations and ship notices between SAP Business Network and CP10's S/4HANA.

What you need

  • Python and your orchestrate-course folder with its .venv, from the setup topic.
  • No account, no network and no extra libraries. The script uses built-in modules only and has no randomness, so your output matches the samples exactly.
  • 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):

      .venv\Scripts\Activate.ps1
    • macOS / Linux:

      source .venv/bin/activate
  4. Create the unit folder if it doesn't exist yet:

    • Windows (PowerShell):

      New-Item -ItemType Directory -Force unit26
    • macOS / Linux:

      mkdir -p unit26

Step 2: Create the script

  1. In VS Code, create a new file unit26/bn_lab.py.
  2. Paste the code below and save.
"""Review a connection to SAP Business Network, replay messages, preview supplier fees.

Course lab for Unit 26, "Connecting to SAP Business Network".
Built-in modules only, no randomness, no network, no SAP system.

  python unit26/bn_lab.py --init                  write the draft and reviewed designs
  python unit26/bn_lab.py review                  review unit26/network/design_draft.json
  python unit26/bn_lab.py review --file unit26/network/design_reviewed.json
  python unit26/bn_lab.py replay                  replay six messages through the draft
  python unit26/bn_lab.py replay --file unit26/network/design_reviewed.json
  python unit26/bn_lab.py fees --file unit26/network/design_reviewed.json
  python unit26/bn_lab.py --self-test             check the built-in samples

Rule IDs BN01 to BN12, account IDs, segments, owners and volumes are course
labels for the fictional Calder Pumpworks. The stand-in network and gateway
only imitate behavior described in the topic; they are not SAP software. Fee
figures follow SAP Learning's supplier fee lesson as read on 2026-11-30 and
are an estimate of Calder's share only: check SAP's current fee schedule.
"""

import argparse
import copy
import json
import sys
from pathlib import Path

FOLDER = Path("unit26/network")
AS_OF = "2026-11-30"
ROLLOUT = "2027-07-05"  # CP20 moves into CP10's S/4HANA system

# ------------------------------------------------------------- the designs

DRAFT = {
    "interface": "I01",
    "as_of": AS_OF,
    "route": "own-tenant",  # partner's own flow on calder-int-prod
    "network_accounts": {"test": "AN-CALDER-TEST", "production": "AN-CALDER-PROD"},
    "systems": [
        {"sid": "S4D", "stage": "development", "account": "test", "system_id": "S4DCLNT100"},
        {"sid": "S4Q", "stage": "quality", "account": "test", "system_id": "S4QCLNT100"},
        {"sid": "S4P", "stage": "production", "account": "production", "system_id": "S4PCLNT100"},
    ],
    "gateway_system_ids": ["S4Q100", "S4PCLNT100"],
    "cloud_connector": [
        {"account": "test", "connector": "SCC-RK-NP", "location_id": "RK",
         "virtual_host": "s4q_api", "port": 443, "protocol": "HTTPS", "path": "/sap/"},
        {"account": "production", "connector": "SCC-RK-P", "location_id": "RK1",
         "virtual_host": "s4p-api", "port": 443, "protocol": "HTTP", "path": "/"},
    ],
    "connector_location_ids": {"SCC-RK-NP": "RK", "SCC-RK-P": "RK"},
    "output_rules": [
        {"supplier": "", "channel": "EDI"},
        {"supplier": "20000001", "channel": "EDI"},
        {"supplier": "20000003", "channel": "EDI"},
    ],
    "retry": {"on": ["4xx", "5xx"], "same_payload_id": False, "max_tries": 4},
    "monitoring": {"technical_owner": "", "business_owner": "", "cloud_alm": False,
                   "evidence": "transaction tracker"},
    "mapping_changes": [
        {"id": "M1", "change": "hide schedule lines from suppliers", "where": "network UI only",
         "tested_in_test": False, "on_cutover_list": False},
    ],
    "suppliers": [
        {"bp": "20000001", "name": "Orrin Motor Works", "segment": "A", "account": "enterprise",
         "method": "cXML", "email": "orders@orrin-motor.example", "contact": "",
         "documents": ["PO", "order confirmation", "ship notice", "invoice"],
         "docs_year": 192, "volume_usd": 1086000.00, "service_sheets": False,
         "system": "S4P", "fee_preview_sent": False, "kind": "goods"},
        {"bp": "20000002", "name": "Tamsfield Foundry", "segment": "B", "account": "standard",
         "method": "interactive email", "email": "sales@tamsfield-foundry.example", "contact": "",
         "documents": ["PO", "order confirmation", "invoice"],
         "docs_year": 96, "volume_usd": 402000.00, "service_sheets": False,
         "system": "S4P", "fee_preview_sent": False, "kind": "goods"},
        {"bp": "20000003", "name": "Ridgeline Bearing Supply", "segment": "A", "account": "enterprise",
         "method": "cXML", "email": "orders@ridgeline-bearing.example", "contact": "edi@ridgeline-bearing.example",
         "documents": ["PO", "order confirmation", "ship notice", "invoice"],
         "docs_year": 72, "volume_usd": 172800.00, "service_sheets": False,
         "system": "S4P", "fee_preview_sent": False, "kind": "goods"},
        {"bp": "20000004", "name": "Corvane Lifting Services", "segment": "C", "account": "standard",
         "method": "interactive email", "email": "", "contact": "",
         "documents": ["PO", "service entry sheet", "invoice"],
         "docs_year": 16, "volume_usd": 14800.00, "service_sheets": True,
         "system": "S4P", "fee_preview_sent": False, "kind": "services"},
        {"bp": "20000005", "name": "Larkspur Freight Lines", "segment": "B", "account": "standard",
         "method": "interactive email", "email": "dispatch@larkspur-freight.example", "contact": "",
         "documents": ["PO", "invoice"],
         "docs_year": 300, "volume_usd": 189000.00, "service_sheets": False,
         "system": "S4P", "fee_preview_sent": False, "kind": "carrier"},
        {"bp": "20000011", "name": "Petrak Stahlhandel GmbH", "segment": "B", "account": "standard",
         "method": "interactive email", "email": "auftrag@petrak-stahl.example", "contact": "",
         "documents": ["PO", "order confirmation", "invoice"],
         "docs_year": 24, "volume_usd": 52000.00, "service_sheets": False,
         "system": "ECP", "fee_preview_sent": False, "kind": "goods"},
        {"bp": "20000014", "name": "Brayford Process Fluids", "segment": "C", "account": "enterprise",
         "method": "cXML", "email": "orders@brayford-fluids.example", "contact": "",
         "documents": ["PO", "invoice"],
         "docs_year": 12, "volume_usd": 2064.00, "service_sheets": False,
         "system": "S4P", "fee_preview_sent": False, "kind": "goods"},
    ],
}


def reviewed_design():
    d = copy.deepcopy(DRAFT)
    d["route"] = "managed-gateway"
    d["systems"] = [
        {"sid": "S4D", "stage": "development", "account": "", "system_id": ""},
        {"sid": "S4Q", "stage": "quality", "account": "test", "system_id": "S4QCLNT100"},
        {"sid": "S4P", "stage": "production", "account": "production", "system_id": "S4PCLNT100"},
    ]
    d["gateway_system_ids"] = ["S4QCLNT100", "S4PCLNT100"]
    d["cloud_connector"] = [
        {"account": "test", "connector": "SCC-RK-NP", "location_id": "RK",
         "virtual_host": "s4-bn", "port": 443, "protocol": "HTTPS", "path": "/sap/"},
        {"account": "production", "connector": "SCC-RK-P", "location_id": "RK",
         "virtual_host": "s4-bn", "port": 443, "protocol": "HTTPS", "path": "/sap/"},
    ]
    d["output_rules"] = [
        {"supplier": "20000001", "channel": "EDI"},
        {"supplier": "20000002", "channel": "EDI"},
        {"supplier": "20000003", "channel": "EDI"},
        {"supplier": "20000004", "channel": "EDI"},
        {"supplier": "20000014", "channel": "EDI"},
        {"supplier": "", "channel": "EMAIL"},
    ]
    d["retry"] = {"on": ["5xx"], "same_payload_id": True, "max_tries": 4}
    d["monitoring"] = {"technical_owner": "00100292", "business_owner": "00100211",
                       "cloud_alm": True, "evidence": "Cloud ALM integration monitoring"}
    d["mapping_changes"] = [
        {"id": "M1", "change": "remove schedule lines from the OrderRequest mapping and hide them in the UI",
         "where": "gateway mapping and network UI", "tested_in_test": True, "on_cutover_list": True},
    ]
    sup = {s["bp"]: s for s in d["suppliers"]}
    sup["20000001"]["contact"] = "edi@orrin-motor.example"
    for bp in ("20000001", "20000003"):
        sup[bp]["fee_preview_sent"] = True
    sup["20000004"]["email"] = "service@corvane-lifting.example"
    sup["20000005"].update({"kind": "carrier", "documents": [], "account": "",
                            "method": "freight collaboration (I06)"})
    sup["20000011"]["enable_from"] = ROLLOUT
    sup["20000014"].update({"account": "standard", "method": "interactive email"})
    return d


# ------------------------------------------------------------------ rules

RULES = {
    "BN01": "Each network account connects to one S/4HANA system; production to production only; no development client",
    "BN02": "System IDs match in the buyer account, the gateway's basic data and S/4HANA",
    "BN03": "Cloud Connector: HTTPS, path /sap/, no underscore in the virtual host, same location ID, host and port for test and production",
    "BN04": "The location ID in each mapping is the one its Cloud Connector uses",
    "BN05": "Output rules: supplier rows first, at most one wildcard row, last, and not EDI",
    "BN06": "Segment A: enterprise account, integrated method, named technical contact; B and C: standard account by interactive email",
    "BN07": "Every supplier sent orders by interactive email has an email address",
    "BN08": "Retries: only transient 5xx answers, with the same payload ID",
    "BN09": "Monitoring: a technical and a business owner, Cloud ALM connected, evidence kept beyond the tracker's 30 days",
    "BN10": "Gateway mapping and UI changes tested in the test account and on the cutover list",
    "BN11": "Carriers are connected through SAP Business Network for Logistics, not procurement",
    "BN12": "Enterprise-account suppliers get a fee preview before the invitation; suppliers on a system that retires wait",
}


def check(d):
    """Return a list of (status, rule, text)."""
    out = []

    def add(status, rule, text):
        out.append((status, rule, text))

    # BN01
    seen = {}
    for s in d["systems"]:
        if not s["account"]:
            add("OK", "BN01", f"{s['sid']} not connected")
            continue
        if s["stage"] == "development":
            add("FAIL", "BN01", f"{s['sid']} (development) connected to the {s['account']} account")
        elif s["stage"] == "production" and s["account"] != "production":
            add("FAIL", "BN01", f"{s['sid']} (production) connected to the {s['account']} account")
        elif s["stage"] != "production" and s["account"] == "production":
            add("FAIL", "BN01", f"{s['sid']} ({s['stage']}) connected to the production account")
        else:
            add("OK", "BN01", f"{s['sid']} -> {s['account']} account")
        seen.setdefault(s["account"], []).append(s["sid"])
    for acct, sids in seen.items():
        if len(sids) > 1:
            add("WARN", "BN01", f"{acct} account receives from {', '.join(sids)}: answers go to one default endpoint")
    # BN02
    gw = set(d["gateway_system_ids"])
    for s in d["systems"]:
        if s["account"] and s["stage"] != "development":
            if s["system_id"] in gw:
                add("OK", "BN02", f"{s['system_id']} known to the gateway")
            else:
                add("FAIL", "BN02", f"{s['system_id']} not in the gateway's basic data ({', '.join(sorted(gw))})")
    # BN03 and BN04
    cc = d["cloud_connector"]
    for m in cc:
        problems = []
        if m["protocol"] != "HTTPS":
            problems.append(f"protocol {m['protocol']}")
        if m["path"] != "/sap/":
            problems.append(f"path {m['path']}")
        if "_" in m["virtual_host"]:
            problems.append(f"underscore in {m['virtual_host']}")
        if problems:
            add("FAIL", "BN03", f"{m['account']} mapping: " + ", ".join(problems))
        else:
            add("OK", "BN03", f"{m['account']} mapping {m['virtual_host']}:{m['port']} {m['protocol']} {m['path']}")
        real = d["connector_location_ids"].get(m["connector"])
        if real == m["location_id"]:
            add("OK", "BN04", f"{m['account']} uses location ID {real} of {m['connector']}")
        else:
            add("FAIL", "BN04", f"{m['account']} names location ID {m['location_id']}, {m['connector']} uses {real}")
    keys = {(m["location_id"], m["virtual_host"], m["port"]) for m in cc}
    if len(keys) > 1:
        add("FAIL", "BN03", "test and production differ in location ID, virtual host or port")
    # BN05
    rules = d["output_rules"]
    wild = [i for i, r in enumerate(rules) if not r["supplier"]]
    if not wild:
        add("WARN", "BN05", "no wildcard row: suppliers without a row get no output")
    elif len(wild) > 1 or wild[0] != len(rules) - 1:
        add("FAIL", "BN05", f"wildcard row at position {wild[0] + 1} of {len(rules)}: it catches every supplier below it")
    elif rules[-1]["channel"] == "EDI":
        add("FAIL", "BN05", "wildcard row sends every other supplier's orders to the network")
    else:
        add("OK", "BN05", f"{len(rules) - 1} supplier rows, wildcard last ({rules[-1]['channel']})")
    routed = {r["supplier"] for r in rules if r["supplier"] and r["channel"] == "EDI"}
    on_network = [s for s in d["suppliers"] if s["kind"] != "carrier" and s["system"] != "ECP"
                  and not s.get("enable_from")]
    for s in on_network:
        if s["bp"] not in routed and not (wild and rules[wild[-1]]["channel"] == "EDI"):
            add("WARN", "BN05", f"{s['bp']} {s['name']}: on the network but no EDI output row")
    # suppliers
    for s in d["suppliers"]:
        who = f"{s['bp']} {s['name']}"
        if s["kind"] == "carrier":
            if s["documents"]:
                add("FAIL", "BN11", f"{who}: carrier sent procurement documents ({', '.join(s['documents'])})")
            else:
                add("OK", "BN11", f"{who}: {s['method']}")
            continue
        # BN12: retiring system first
        if s["system"] == "ECP" and not s.get("enable_from"):
            add("FAIL", "BN12", f"{who}: on ECC ECP, which retires {ROLLOUT}; enable after the rollout")
            continue
        if s.get("enable_from"):
            add("OK", "BN12", f"{who}: enable from {s['enable_from']}")
            continue
        # BN06
        if s["segment"] == "A":
            gaps = []
            if s["account"] != "enterprise":
                gaps.append("standard account")
            if s["method"] not in ("cXML", "EDI"):
                gaps.append(f"method {s['method']}")
            if not s["contact"]:
                gaps.append("no technical contact")
            if gaps:
                add("FAIL" if len(gaps) > 1 or "standard account" in gaps else "WARN",
                    "BN06", f"{who}: segment A with " + ", ".join(gaps))
            else:
                add("OK", "BN06", f"{who}: A, enterprise, {s['method']}")
        else:
            if s["account"] == "enterprise":
                add("WARN", "BN06", f"{who}: segment {s['segment']} pushed to an enterprise account and {s['method']}")
            else:
                add("OK", "BN06", f"{who}: {s['segment']}, standard account by interactive email")
        # BN07
        if s["method"] == "interactive email":
            if s["email"]:
                add("OK", "BN07", f"{who}: {s['email']}")
            else:
                add("FAIL", "BN07", f"{who}: no email, the interactive order can't be sent")
        # BN12: fee preview
        if s["account"] == "enterprise":
            if s["fee_preview_sent"]:
                add("OK", "BN12", f"{who}: fee preview sent")
            else:
                f = fee(s)
                status = "WARN" if f["chargeable"] else "OK"
                add(status, "BN12", f"{who}: no fee preview; estimate {f['fee']:,.2f} USD a year"
                    if f["chargeable"] else f"{who}: not chargeable on Calder's volume")
    # BN08
    r = d["retry"]
    if "4xx" in r["on"]:
        add("FAIL", "BN08", "retries permanent 4xx errors: they fail every time and hide the problem")
    if not r["same_payload_id"]:
        add("FAIL", "BN08", "each retry gets a new payload ID: the network can't spot the repeat")
    if "4xx" not in r["on"] and r["same_payload_id"]:
        add("OK", "BN08", f"5xx retried up to {r['max_tries']} tries with the same payload ID")
    # BN09
    m = d["monitoring"]
    for k, label in (("technical_owner", "technical owner"), ("business_owner", "business owner")):
        add("OK" if m[k] else "FAIL", "BN09", f"{label} {m[k]}" if m[k] else f"no {label}")
    add("OK" if m["cloud_alm"] else "WARN", "BN09",
        "gateway connected to Cloud ALM integration monitoring" if m["cloud_alm"]
        else "gateway not in Cloud ALM: errors seen only by whoever opens the tracker")
    if m["evidence"] == "transaction tracker":
        add("WARN", "BN09", "evidence only in the transaction tracker, which keeps 30 days")
    # BN10
    for c in d["mapping_changes"]:
        gaps = []
        if c["where"] == "network UI only":
            gaps.append("UI only: the data still travels in the cXML")
        if not c["tested_in_test"]:
            gaps.append("not tested in the test account")
        if not c["on_cutover_list"]:
            gaps.append("not on the cutover list")
        add("FAIL" if gaps else "OK", "BN10", f"{c['id']} {c['change']}: " + ("; ".join(gaps) if gaps else "tested, on the cutover list"))
    order = {k: i for i, k in enumerate(RULES)}
    out.sort(key=lambda x: order[x[1]])
    return out


def load(path):
    p = Path(path)
    if not p.exists():
        sys.exit(f"{p} not found. Run: python unit26/bn_lab.py --init")
    try:
        return json.loads(p.read_text(encoding="utf-8"))
    except json.JSONDecodeError as e:
        sys.exit(f"{p} is not valid JSON (line {e.lineno}): {e.msg}")


def review(path, show=True):
    d = load(path)
    lines = check(d)
    totals = {"OK": 0, "WARN": 0, "FAIL": 0}
    for status, rule, text in lines:
        totals[status] += 1
        if show and status != "OK":
            print(f"  {status:<4} {rule}  {text}")
    if show:
        print(f"{d['interface']} route {d['route']}: {totals['OK']} OK, {totals['WARN']} WARN, {totals['FAIL']} FAIL")
        if totals["FAIL"]:
            print("Rules: " + ", ".join(sorted({r for s, r, _ in lines if s == 'FAIL'})) + " (see --rules)")
    return totals


# ------------------------------------------------------------------- fees
# SAP Learning, supplier fee lesson (read 2026-11-30): chargeable once a supplier
# passes 5 documents AND 50,000 USD with one buyer in 12 months; 0.155 % of volume,
# 0.35 % when service entry sheets are used; cap 20,000 USD per relationship a year.

LEVELS = [(0, 4, "Enterprise (no cost)"), (5, 24, "Bronze"), (25, 99, "Silver"),
          (100, 499, "Gold"), (500, 10 ** 9, "Platinum")]


def cents_half_up(amount_usd, rate_per_100000):
    # amount in cents times rate in 1/100000 (0.155 % = 155), rounded half up
    num = round(amount_usd * 100) * rate_per_100000
    return (num + 50000) // 100000


def fee(s):
    docs, vol = s["docs_year"], s["volume_usd"]
    level = next(n for lo, hi, n in LEVELS if lo <= docs <= hi)
    rate = 350 if s["service_sheets"] else 155
    chargeable = docs >= 5 and vol >= 50000
    cents = cents_half_up(vol, rate) if chargeable else 0
    cents = min(cents, 2000000)
    return {"level": level, "rate": rate / 1000, "chargeable": chargeable, "fee": cents / 100}


def fees(path):
    d = load(path)
    print(f"{'Supplier':<34}{'Acct':<11}{'Docs':>5}{'Volume USD':>14}  {'Level':<21}{'Rate':>7}  {'If enterprise':>13}  {'Estimate':>9}")
    total = 0.0
    for s in d["suppliers"]:
        if s["kind"] == "carrier":
            continue
        f = fee(s)
        est = f["fee"] if s["account"] == "enterprise" else 0.0
        total += est
        acct = s["account"] or "-"
        print(f"{s['bp'] + ' ' + s['name'][:24]:<34}{acct:<11}{s['docs_year']:>5}{s['volume_usd']:>14,.2f}  "
              f"{f['level']:<21}{f['rate']:>6.3f}%  {f['fee']:>13,.2f}  {est:>9,.2f}")
    print(f"Estimated fees for suppliers on enterprise accounts: {total:,.2f} USD a year (Calder's share only)")
    return total


# ----------------------------------------------------------------- replay

EVENTS = [
    {"id": "E1", "dir": "out", "doc": "PO 4500000015", "bp": "20000001",
     "text": "30 CP-MTR15 at 905.00", "answers": ["timeout", 200]},
    {"id": "E2", "dir": "out", "doc": "PO 4500000017", "bp": "20000003",
     "text": "100 CP-SK200 at 48.00", "answers": [400, 400, 400, 400]},
    {"id": "E3", "dir": "out", "doc": "PO 4500000007", "bp": "20000004",
     "text": "crane inspection, first order to Corvane", "answers": [200]},
    {"id": "E4", "dir": "out", "doc": "PO 4500000021", "bp": "20000005",
     "text": "freight Rockford to Brennock", "answers": [200]},
    {"id": "E5", "dir": "in", "doc": "order confirmation on PO 4500000002", "bp": "20000001",
     "text": "20 CP-MTR15 on 2026-11-18", "result": "confirmation stored on the PO item"},
    {"id": "E6", "dir": "in", "doc": "ship notice on PO 4500000003", "bp": "20000003",
     "text": "seal kits in HU 1000000031", "result": "inbound delivery 180000003 created"},
]


def plural(n):
    return f"{n} try" if n == 1 else f"{n} tries"


def replay(path):
    d = load(path)
    sup = {s["bp"]: s for s in d["suppliers"]}
    r = d["retry"]
    reach = {}
    for m in d["cloud_connector"]:
        ok = (d["connector_location_ids"].get(m["connector"]) == m["location_id"]
              and "_" not in m["virtual_host"] and m["protocol"] == "HTTPS" and m["path"] == "/sap/")
        reach[m["account"]] = ok
    stats = {"documents at suppliers": 0, "duplicates": 0, "wasted calls": 0,
             "inbound posted": 0, "alerts to an owner": 0}
    payload = 0
    for e in EVENTS:
        s = sup[e["bp"]]
        head = f"{e['id']} {e['doc']} ({s['name']}, {e['text']})"
        if e["dir"] == "out":
            if s["kind"] == "carrier" and not s["documents"]:
                print(f"{head}\n   not sent: carriers get freight orders through I06, not purchase orders")
                continue
            if s["kind"] == "carrier":
                stats["documents at suppliers"] += 1
                print(f"{head}\n   200 accepted: a freight job arrives as a purchase order the carrier can't tender back")
                continue
            if s["method"] == "interactive email" and not s["email"]:
                note = "alert to " + d["monitoring"]["business_owner"] if d["monitoring"]["business_owner"] else "seen only in the tracker"
                if d["monitoring"]["business_owner"]:
                    stats["alerts to an owner"] += 1
                print(f"{head}\n   400 refused: no email for a new supplier ({note})")
                continue
            sent, stored = [], set()
            payload += 1
            final = None
            for ans in e["answers"]:
                if sent and not r["same_payload_id"]:
                    payload += 1
                pid = f"PL-{payload:04d}"
                sent.append(pid)
                if ans in (200, "timeout"):  # stand-in: a timed-out call was stored
                    stored.add(pid)
                if ans == 200:
                    final = 200
                    break
                kind = "5xx" if ans == "timeout" or ans >= 500 else "4xx"
                if kind not in r["on"] or len(sent) >= r["max_tries"]:
                    final = ans
                    break
            tries = len(sent)
            if final == 200:
                stats["documents at suppliers"] += len(stored)
                stats["duplicates"] += len(stored) - 1
                how = "interactive order email" if s["method"] == "interactive email" else s["method"]
                dup = f", {len(stored)} copies at the supplier" if len(stored) > 1 else ", 1 document at the supplier"
                ids = ", ".join(dict.fromkeys(sent))
                same = " (same ID on every try)" if tries > 1 and len(set(sent)) == 1 else ""
                print(f"{head}\n   {plural(tries)}, payload ID {ids}{same}: accepted by {how}{dup}")
            else:
                stats["wasted calls"] += tries - 1
                if d["monitoring"]["business_owner"]:
                    stats["alerts to an owner"] += 1
                    note = "alert to " + d["monitoring"]["business_owner"]
                else:
                    note = "seen only in the tracker"
                print(f"{head}\n   {plural(tries)}, last answer {final}: permanent error, {note}")
        else:
            acct = "production"
            if reach.get(acct):
                stats["inbound posted"] += 1
                print(f"{head}\n   gateway -> Cloud Connector -> S4P: {e['result']}")
            else:
                print(f"{head}\n   gateway can't reach S4P through the Cloud Connector; waits in the tracker")
    print("Summary: " + ", ".join(f"{k} {v}" for k, v in stats.items()))
    return stats


# ------------------------------------------------------------------- main

def init():
    FOLDER.mkdir(parents=True, exist_ok=True)
    for name, data in (("design_draft.json", DRAFT), ("design_reviewed.json", reviewed_design())):
        p = FOLDER / name
        if p.exists():
            print(f"{p} already exists; delete it first to get the sample back")
            continue
        p.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
        print(f"Wrote {p}")


def self_test():
    results = []

    def t(name, cond):
        results.append(cond)
        if not cond:
            print(f"FAILED: {name}")

    def counts(d):
        c = {"OK": 0, "WARN": 0, "FAIL": 0}
        for s, _, _ in check(d):
            c[s] += 1
        return c

    dc, rc = counts(DRAFT), counts(reviewed_design())
    t("draft totals", (dc["OK"], dc["WARN"], dc["FAIL"]) == SAMPLE_DRAFT)
    t("reviewed totals", (rc["OK"], rc["WARN"], rc["FAIL"]) == SAMPLE_REVIEWED)
    t("reviewed has no FAIL", rc["FAIL"] == 0)
    orrin = next(s for s in DRAFT["suppliers"] if s["bp"] == "20000001")
    f = fee(orrin)
    t("Orrin fee", (f["level"], f["fee"], f["chargeable"]) == ("Gold", 1683.30, True))
    corv = next(s for s in DRAFT["suppliers"] if s["bp"] == "20000004")
    t("Corvane not chargeable", fee(corv)["chargeable"] is False and fee(corv)["rate"] == 0.35)
    big = dict(orrin, volume_usd=20000000.00)
    t("cap", fee(big)["fee"] == 20000.00)
    t("rounding", cents_half_up(172800.00, 155) == 26784)
    import contextlib
    import io
    import tempfile
    with tempfile.TemporaryDirectory() as tmp:
        for name, data, want in (("d.json", DRAFT, (3, 1, 3, 0, 0)),
                                 ("r.json", reviewed_design(), (2, 0, 0, 2, 1))):
            f = Path(tmp) / name
            f.write_text(json.dumps(data), encoding="utf-8")
            with contextlib.redirect_stdout(io.StringIO()):
                st = replay(f)
                total = fees(f)
            t(f"replay {name}", tuple(st.values()) == want)
            t(f"fees {name}", round(total, 2) == 1951.14)
    print(f"{sum(results)} of {len(results)} self-test checks passed")
    return all(results)


SAMPLE_DRAFT = (9, 7, 15)
SAMPLE_REVIEWED = (27, 0, 0)


def main():
    ap = argparse.ArgumentParser(description="Review and replay Calder's SAP Business Network connection.")
    ap.add_argument("command", nargs="?", choices=["review", "replay", "fees"])
    ap.add_argument("--file", default=str(FOLDER / "design_draft.json"))
    ap.add_argument("--init", action="store_true", help="write the sample designs")
    ap.add_argument("--rules", action="store_true", help="list the rules")
    ap.add_argument("--self-test", action="store_true", help="check the built-in samples")
    a = ap.parse_args()
    if a.init:
        init()
    elif a.rules:
        for k, v in RULES.items():
            print(f"{k}  {v}")
    elif a.self_test:
        sys.exit(0 if self_test() else 1)
    elif a.command == "review":
        totals = review(a.file)
        sys.exit(2 if totals["FAIL"] else 0)
    elif a.command == "replay":
        replay(a.file)
    elif a.command == "fees":
        fees(a.file)
    else:
        ap.print_help()


if __name__ == "__main__":
    main()

Step 3: Write the sample designs and check them

  1. Write the two designs:

    python unit26/bn_lab.py --init
    Wrote unit26/network/design_draft.json
    Wrote unit26/network/design_reviewed.json
  2. Run the self-test:

    python unit26/bn_lab.py --self-test
    11 of 11 self-test checks passed
  3. Open unit26/network/design_draft.json in VS Code. It has the systems and their network accounts, the system IDs in the gateway, the two Cloud Connector mappings, the output rules, the retry policy, monitoring, one mapping change and seven suppliers.

Step 4: Review the partner's draft

  1. Run the review:

    python unit26/bn_lab.py review
      FAIL BN01  S4D (development) connected to the test account
      WARN BN01  test account receives from S4D, S4Q: answers go to one default endpoint
      FAIL BN02  S4QCLNT100 not in the gateway's basic data (S4PCLNT100, S4Q100)
      FAIL BN03  test mapping: underscore in s4q_api
      FAIL BN03  production mapping: protocol HTTP, path /
      FAIL BN03  test and production differ in location ID, virtual host or port
      FAIL BN04  production names location ID RK1, SCC-RK-P uses RK
      FAIL BN05  wildcard row at position 1 of 3: it catches every supplier below it
      WARN BN06  20000001 Orrin Motor Works: segment A with no technical contact
      WARN BN06  20000014 Brayford Process Fluids: segment C pushed to an enterprise account and cXML
      FAIL BN07  20000004 Corvane Lifting Services: no email, the interactive order can't be sent
      FAIL BN08  retries permanent 4xx errors: they fail every time and hide the problem
      FAIL BN08  each retry gets a new payload ID: the network can't spot the repeat
      FAIL BN09  no technical owner
      FAIL BN09  no business owner
      WARN BN09  gateway not in Cloud ALM: errors seen only by whoever opens the tracker
      WARN BN09  evidence only in the transaction tracker, which keeps 30 days
      FAIL BN10  M1 hide schedule lines from suppliers: UI only: the data still travels in the cXML; not tested in the test account; not on the cutover list
      FAIL BN11  20000005 Larkspur Freight Lines: carrier sent procurement documents (PO, invoice)
      WARN BN12  20000001 Orrin Motor Works: no fee preview; estimate 1,683.30 USD a year
      WARN BN12  20000003 Ridgeline Bearing Supply: no fee preview; estimate 267.84 USD a year
      FAIL BN12  20000011 Petrak Stahlhandel GmbH: on ECC ECP, which retires 2027-07-05; enable after the rollout
    I01 route own-tenant: 9 OK, 7 WARN, 15 FAIL
    Rules: BN01, BN02, BN03, BN04, BN05, BN07, BN08, BN09, BN10, BN11, BN12 (see --rules)

    The exit code is 2 because something failed. Only WARN and FAIL lines are printed; the OK checks are counted.

  2. List the rules with python unit26/bn_lab.py --rules. Where each comes from:

    Rule Checks Source
    BN01 Systems to accounts; no development client SAP Learning (components)
    BN02 System IDs match in buyer account, gateway and S/4HANA SAP Learning (gateway steps, buyer account)
    BN03 Cloud Connector mapping: HTTPS, /sap/, no underscore, same host, port and location ID for test and production SAP Learning (Cloud Connector)
    BN04 Location ID in the mapping is the connector's BTP connectivity topic
    BN05 Wildcard output row last and not to the network SAP Learning (output); "not EDI" is a course rule
    BN06 Segment A integrated on an enterprise account; B and C standard SAP Learning (account types); segments are course labels
    BN07 An email for every interactive order SAP Learning (Quick Enablement)
    BN08 Retry only 5xx, with the same payload ID SAP Learning (purchase orders)
    BN09 Owners, Cloud ALM, evidence beyond 30 days SAP Learning (tracker), SAP Support (Cloud ALM); owners are a course rule
    BN10 Mapping and UI changes tested and on the cutover list SAP Learning (use cases)
    BN11 Carriers through SAP Business Network for Logistics SAP Learning (logistics); course rule
    BN12 Fee preview before inviting; wait for a retiring system Course rules, fees from SAP Learning

Step 5: Replay six documents through the draft

  1. Run the replay:

    python unit26/bn_lab.py replay
    E1 PO 4500000015 (Orrin Motor Works, 30 CP-MTR15 at 905.00)
       2 tries, payload ID PL-0001, PL-0002: accepted by cXML, 2 copies at the supplier
    E2 PO 4500000017 (Ridgeline Bearing Supply, 100 CP-SK200 at 48.00)
       4 tries, last answer 400: permanent error, seen only in the tracker
    E3 PO 4500000007 (Corvane Lifting Services, crane inspection, first order to Corvane)
       400 refused: no email for a new supplier (seen only in the tracker)
    E4 PO 4500000021 (Larkspur Freight Lines, freight Rockford to Brennock)
       200 accepted: a freight job arrives as a purchase order the carrier can't tender back
    E5 order confirmation on PO 4500000002 (Orrin Motor Works, 20 CP-MTR15 on 2026-11-18)
       gateway can't reach S4P through the Cloud Connector; waits in the tracker
    E6 ship notice on PO 4500000003 (Ridgeline Bearing Supply, seal kits in HU 1000000031)
       gateway can't reach S4P through the Cloud Connector; waits in the tracker
    Summary: documents at suppliers 3, duplicates 1, wasted calls 3, inbound posted 0, alerts to an owner 0
  2. Read it line by line:

    • E1 timed out on the first try, but the stand-in network had stored it. The partner's flow gave the retry a new payload ID, so Orrin now has two orders for 30 motors. This is why BN08 asks for the same ID.
    • E2 has a data error the network refuses with 400 (in the lab it always does). Retrying it three more times changed nothing, and no one was told. Ridgeline never got the order.
    • E3 is Corvane's first order. With no email address, there is no one to invite (BN07).
    • E4 sent freight as a purchase order (BN11).
    • E5 and E6 never arrive, because the production mapping names location ID RK1 while the connector uses RK (BN04). Orrin's late date is exactly the confirmation planning needed.

Step 6: Review and replay the corrected design

  1. Review the corrected design:

    python unit26/bn_lab.py review --file unit26/network/design_reviewed.json
    I01 route managed-gateway: 27 OK, 0 WARN, 0 FAIL
  2. Replay it:

    python unit26/bn_lab.py replay --file unit26/network/design_reviewed.json
    E1 PO 4500000015 (Orrin Motor Works, 30 CP-MTR15 at 905.00)
       2 tries, payload ID PL-0001 (same ID on every try): accepted by cXML, 1 document at the supplier
    E2 PO 4500000017 (Ridgeline Bearing Supply, 100 CP-SK200 at 48.00)
       1 try, last answer 400: permanent error, alert to 00100211
    E3 PO 4500000007 (Corvane Lifting Services, crane inspection, first order to Corvane)
       1 try, payload ID PL-0003: accepted by interactive order email, 1 document at the supplier
    E4 PO 4500000021 (Larkspur Freight Lines, freight Rockford to Brennock)
       not sent: carriers get freight orders through I06, not purchase orders
    E5 order confirmation on PO 4500000002 (Orrin Motor Works, 20 CP-MTR15 on 2026-11-18)
       gateway -> Cloud Connector -> S4P: confirmation stored on the PO item
    E6 ship notice on PO 4500000003 (Ridgeline Bearing Supply, seal kits in HU 1000000031)
       gateway -> Cloud Connector -> S4P: inbound delivery 180000003 created
    Summary: documents at suppliers 2, duplicates 0, wasted calls 0, inbound posted 2, alerts to an owner 1
  3. Compare the two designs in VS Code. What changed: the managed gateway instead of the partner's own flow; S4D disconnected; matching system IDs; one virtual host s4-bn:443 on location ID RK for both stages; supplier output rows first with an email wildcard last; retries on 5xx only with the same ID; buyer 00100211 and integration lead 00100292 as owners, with Cloud ALM; the mapping change in the gateway and on the cutover list; Corvane's email; Brayford on a standard account; Larkspur moved to I06; Petrak waiting for 5 July 2027.

Step 7: Preview supplier fees

  1. Run the fee preview on the corrected design:

    python unit26/bn_lab.py fees --file unit26/network/design_reviewed.json
    Supplier                          Acct        Docs    Volume USD  Level                   Rate  If enterprise   Estimate
    20000001 Orrin Motor Works        enterprise   192  1,086,000.00  Gold                  0.155%       1,683.30   1,683.30
    20000002 Tamsfield Foundry        standard      96    402,000.00  Silver                0.155%         623.10       0.00
    20000003 Ridgeline Bearing Supply enterprise    72    172,800.00  Silver                0.155%         267.84     267.84
    20000004 Corvane Lifting Services standard      16     14,800.00  Bronze                0.350%           0.00       0.00
    20000011 Petrak Stahlhandel GmbH  standard      24     52,000.00  Bronze                0.155%          80.60       0.00
    20000014 Brayford Process Fluids  standard      12      2,064.00  Bronze                0.155%           0.00       0.00
    Estimated fees for suppliers on enterprise accounts: 1,951.14 USD a year (Calder's share only)
  2. Read the columns. Level is the subscription level by document count; If enterprise is the transaction fee if the supplier were on an enterprise account; Estimate is what applies to its actual account. Corvane uses service entry sheets, so its rate is 0.35%, but its volume with Calder is below 50,000 USD. Standard accounts pay nothing.

Step 8 (sketch): Check a real connection

  1. In the buyer account, open Manage Profile, then Business Application IDs, and copy the system IDs into the JSON.
  2. In the managed gateway, copy the system IDs from the basic data and the connections from the project.
  3. In the Cloud Connector, copy each subaccount's location ID and the virtual host, port, protocol and path of the S/4HANA mapping.
  4. In S/4HANA, export the output parameter determination rules for purchase orders.
  5. From purchasing, add each supplier's segment, account type, method, email, contact and last year's documents and volume.
  6. Run the review and the fee preview.

Step 9: Save your work

git add unit26/bn_lab.py unit26/network
git commit -m "Unit 26: SAP Business Network connection review for Calder"

How the code works

Part What it does
DRAFT, reviewed_design() The partner's design and the corrected one, written to JSON by --init
RULES, check() The twelve rules, applied to one design; each finding is OK, WARN or FAIL
review() Prints WARN and FAIL lines and the totals; exit code 2 on any FAIL
LEVELS, fee(), cents_half_up() Subscription level by documents, chargeability, rate and capped fee, in cents rounded half up
EVENTS, replay() Six documents sent through a stand-in gateway and network that follow the design's retry policy, output and Cloud Connector settings
self_test() Eleven checks on the built-in samples, so you can tell a broken copy from an edited file

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 module named ... A different script was pasted, or an import was added The script needs built-in modules only; paste it again from Step 2
design_draft.json not found Step 3 hasn't run, or you are in another folder Run python unit26/bn_lab.py --init from orchestrate-course
already exists; delete it first --init doesn't overwrite your edits Delete the file only if you want the sample back
is not valid JSON (line N) A comma or bracket is missing after an edit VS Code marks the line; fix it and run again
KeyError: 'kind' or another field A supplier you added lacks a field Copy an existing supplier and change its values
Your counts differ from the samples The JSON files or the script were edited Run --self-test, then --init in a fresh folder
A company proxy blocks downloads Not used here The lab needs no network

The SAP way

What SAP provides, as of 30 November 2026:

  • SAP S/4HANA Cloud, scope item 42K, Automation of Source-to-Pay with SAP Business Network: native integration, no add-on, with Quick Enablement for suppliers (SAP Learning). Public Edition uses communication arrangements with business partners (SAP Knowledge Base Article 3622008); Private Edition uses SOAMANAGER and the Cloud Connector.
  • SAP ERP and on-premise S/4HANA: the managed gateway add-on, with parameters such as ORDER_ENABLED and HANDLING_UNITS in Customizing, and cXML or IDoc integration (SAP Learning).
  • SAP Integration Suite, managed gateway for spend management and SAP Business Network: SAP-run mapping and routing, a mapping tool for buyer-side changes, the Transaction Tracker, and Cloud ALM integration monitoring (SAP Support).
  • SAP Business Network supplier accounts: standard (free) and enterprise (subscription and transaction fees) (SAP).
  • SAP Business Network for Logistics: freight collaboration with SAP TM, carrier onboarding by the shipper, dock appointment APIs (SAP Learning).
  • Licensing note. SAP's marketing page says SAP Business Network is "already included" in an organization's S/4HANA deployment (SAP); what that covers for your edition, and whether the supplier portal entitlement applies, is a question for your contract. Supplier fees are the supplier's, not the buyer's.

Build vs. SAP

Need SAP Your own Use which
Connect S/4HANA to the network Native integration with the managed gateway Your own Cloud Integration flows and mappings to cXML SAP's: standard content, SAP keeps it current
Map a document differently The gateway's mapping tool A custom flow in front of the gateway The mapping tool; only add a flow for logic it can't hold
Enable small suppliers Quick Enablement, standard accounts Your own supplier portal SAP's, unless the network can't reach those suppliers
Connect distributors who send you orders Not this network's main job Trading Partner Management, as in the B2B topic TPM for customer-side EDI
Connect carriers SAP Business Network for Logistics Email, portals, carrier EDI The network where carriers will join it
Monitor SRT_MONI, Transaction Tracker, Cloud ALM Your own dashboards SAP's tools, with your owners and routes

Architecture view

Where it sits. I01 crosses from Calder's private network connection to RISE, through SAP's gateway, to the network and the suppliers' own systems.

flowchart LR
  S4P[S/4HANA S4P<br/>CP10, RISE] -- POs, GR, invoice status --> GW[Managed gateway]
  GW -- confirmations, ship notices, invoices --> SCC[Cloud Connector SCC-RK-P<br/>s4-bn:443 @ RK] --> S4P
  GW <--> BN[SAP Business Network<br/>AN-CALDER-PROD]
  BN <--> O[Orrin: cXML]
  BN <--> R[Ridgeline: cXML]
  BN <--> T[Tamsfield, Corvane, Brayford:<br/>standard accounts]
  GW -. status .-> ALM[SAP Cloud ALM<br/>Integration Monitoring]
  TM[TM in S4P] -. I06 later .-> LBN[SAP Business Network<br/>for Logistics] -.-> C[Larkspur, Tallis]

Non-functional requirements.

Requirement Typical target What breaks if missed
Delivery Every PO at the supplier once; no duplicates Double deliveries, or orders the supplier never saw
Timeliness Confirmations in S/4HANA within minutes of the supplier sending MRP plans on a date the supplier already changed
Availability Inbound path through a high-availability Cloud Connector pair Confirmations and ship notices queue in the gateway
Error handling A refused document reaches its owner the same day Orders silently missing at suppliers
Evidence Message history kept beyond the tracker's 30 days No proof of what a supplier received
Security HTTPS, credentials held in the gateway and the connector, one technical user per direction Exposed credentials, documents read on the way
Supplier cost Fee preview before each enterprise invitation Suppliers refuse to join or leave

Integration and identity. S/4HANA calls the gateway with SOAP services set up in SOAMANAGER; the gateway calls back through the Cloud Connector with the credentials its connection holds. Use a dedicated technical user in S/4HANA with only the inbound services it needs, never a person's account. Business identity travels in the documents: the system ID names Calder's system, the vendor ID names the supplier, the ANID names the account. Integration security goes deeper on credentials and certificates; BTP connectivity covers the Cloud Connector.

The decision to record (short ADR form from the design-doc topic):

  • Context. Calder's integration platform decision, ADR-001 in the integration platform topic, sends SAP-to-SAP standard integrations direct. The partner proposed building I01 as Calder's own Cloud Integration flows to cXML, so all traffic would be in one monitor.
  • Options. A: managed gateway with SAP's standard content. B: Calder's own flows on calder-int-prod. C: managed gateway, with an own flow only where a mapping can't express a rule.
  • Decision. A. The gateway is SAP-run, maps with SAP's content and handles retries with the same payload ID. Monitoring comes into Cloud ALM, which Calder already uses, so one monitor is still possible. C stays available if a later need can't be met in the mapping tool.
  • Consequences. Mapping changes go through the gateway's mapping tool and the cutover list. The gateway's 30-day tracker isn't Calder's evidence store; Cloud ALM and S/4HANA are. Purchasing owns supplier enablement; the integration lead owns the connection.

What a design review will ask.

  1. Which S/4HANA system talks to which network account, and how do we know the system IDs match?
  2. What happens to a purchase order the network refuses, and who hears about it?
  3. Can a retry create a second order at the supplier?
  4. How does each supplier join, and has every enterprise-account supplier seen a fee estimate?
  5. Where do carriers and customer-side EDI go, if not through this connection?

Production concerns

  • Security and authorizations. One technical user for inbound calls, with only the needed services; credentials held in the gateway and the Cloud Connector, rotated on a calendar. Gateway configuration roles go to named people. Buyers' roles in S/4HANA decide who can send and change orders, as in the roles topic.
  • Evaluation. Before go-live, test each document type with real suppliers in the test account: an order, a change, a cancellation, a confirmation with a new date, a partial ship notice, an invoice above tolerance. Repeat for every mapping change.
  • Cost. The connection's cost is mostly people: supplier enablement waves, buyer training, and answering suppliers' questions. Suppliers' fees are theirs, but they shape who joins.
  • Operations. Owners for SRT_MONI, the tracker and Cloud ALM alerts; a run book for the common refusals; a weekly report of suppliers with orders unconfirmed after the agreed time.
  • Clean core. Native integration and standard mappings keep the core clean. Extensions to the documents go into the gateway's mapping, not into modified SAP code.

Where AI fits

  • Delivered by SAP. Nothing in this connection's setup uses AI today. SAP has announced planned Joule assistants for supply chain and procurement work; the exception trace lists the plans as published, with dates. Check each one's status, edition and license before a design depends on it.
  • An agent as one more consumer. Confirmations and ship notices land in S/4HANA as ordinary data, so an agent reads them through released APIs, like the supply watch agent in the exception trace. It proposes; a buyer changes the order. An agent never writes to the network directly.
  • Suppliers who stay off the network. PDF invoices from them are an extraction case, as in the procure-to-pay ADR; the procurement AI topic maps what SAP offers.
  • A new risk. Supplier-written text in comments and attachments is untrusted input for any agent that reads it.

Pitfalls

  • Connecting the development client. Its incomplete master data produces errors that look like integration bugs.
  • System IDs typed three ways. The buyer account, the gateway and S/4HANA must agree exactly.
  • A wildcard output row first. It catches every supplier, including those not on the network.
  • Retrying everything. Retrying a 4xx hides a data error; a new payload ID per retry can double an order.
  • No email on the supplier record. Quick Enablement has no one to invite.
  • Inviting a supplier without talking about fees. The supplier finds out from SAP's invoice.
  • Hiding data in the UI only. It still travels in the cXML.
  • Treating the tracker as an archive. It keeps 30 days.
  • Carriers on the procurement connection. Freight orders need the logistics network.

Exercise

Calder decides Tamsfield should integrate: castings volume is growing, and receiving wants ship notices from every strategic supplier. Extend the lab to enforce that.

  1. Open unit26/network/design_reviewed.json and change Tamsfield (20000002): "segment": "A", "account": "enterprise", "method": "cXML", "contact": "edi@tamsfield-foundry.example".

  2. In unit26/bn_lab.py, add a rule to RULES, after BN12:

    "BN13": "Segment A suppliers send ship notices, so receiving works from inbound deliveries",
  3. In check(), find the line # BN07 (inside the loop over suppliers) and add this block just above it:

            # BN13 (exercise)
            if s["segment"] == "A":
                if "ship notice" in s["documents"]:
                    add("OK", "BN13", f"{who}: sends ship notices")
                else:
                    add("FAIL", "BN13", f"{who}: segment A without ship notices")

    Keep the indentation: # BN13 starts in the same column as # BN07.

  4. Run python unit26/bn_lab.py review --file unit26/network/design_reviewed.json. You should see:

      WARN BN12  20000002 Tamsfield Foundry: no fee preview; estimate 623.10 USD a year
      FAIL BN13  20000002 Tamsfield Foundry: segment A without ship notices
    I01 route managed-gateway: 28 OK, 1 WARN, 1 FAIL
  5. Fix both: set Tamsfield's "documents" to ["PO", "order confirmation", "ship notice", "invoice"] and "fee_preview_sent": true. Run the review and the fee preview again.

  6. The self-test now reports two failed checks, because the rule changed the built-in totals. Update the sample constants in the script to SAMPLE_DRAFT = (11, 7, 15) and SAMPLE_REVIEWED = (29, 0, 0).

Done when the review prints I01 route managed-gateway: 30 OK, 0 WARN, 0 FAIL, the fee preview ends with Estimated fees for suppliers on enterprise accounts: 2,574.24 USD a year (Calder's share only), and --self-test passes 11 of 11. Keep the design file: the architect capstone's integration pack lists I01 with its owners and rules.

Check yourself

Pick one answer for each question. The explanation appears after you choose.

1Which three identifiers must agree for a document to reach the right supplier from the right system?

Answer: A. The ANID names the account, the system ID names Calder's S/4HANA system in the buyer account and gateway, and the vendor ID names the supplier. A mismatch in any one stops routing.

2Calder's gateway gets a 400 answer for a purchase order to Ridgeline. What should happen?

Answer: D. SAP's course treats 4xx as a permanent error that is logged. Only a person fixing the order or its data changes the outcome, so the alert matters more than any retry.

3In the replay, why did Orrin end up with two copies of PO 4500000015?

Answer: B. The first call was stored before it timed out. A repeat with the same payload ID is recognizably the same document; the draft's flow gave the retry a new ID, so it counted as a second order.

4Orrin's confirmation never reaches S4P, though the gateway accepted it. What do you check first?

Answer: D. Inbound documents travel from the gateway through the Cloud Connector into S/4HANA. A location ID that doesn't match the connector, as in the draft, leaves them waiting in the tracker.

5The output rule table starts with a row with no supplier, sending through the network. What goes wrong?

Answer: C. Rules run in order, and a row without a supplier is a wildcard. Placed first, it catches every supplier, so it belongs last and, at Calder, sends email.

6Purchasing wants suppliers not to see schedule lines and asks to hide them on the network's screens. What do you say?

Answer: D. A UI customization changes the display only. Removing data from what travels is a mapping change, tested in the test account and put on the cutover list.

7Corvane has no email address in its supplier record. What happens to its first order through the network?

Answer: C. Quick Enablement invites a new supplier through an interactive order email. Without an address on the supplier record there is no invitation, so the order goes nowhere.

8Why does the corrected design keep evidence in Cloud ALM and S/4HANA, not the Transaction Tracker?

Answer: D. SAP's course says the tracker keeps transaction documents for 30 days from creation. It is a working tool, so proof of what a supplier received must live elsewhere.
Next · Unit 27 · Security, identity and complianceSet up for Unit 27: Calder's security sample pack and an optional Identity Services trialBuild a week of Calder's sign-in, audit and read access logs on your laptop, read them against eight rules, and know what the free identity trial offers.

Sources

Sign in to track your progress

We'll email you a one-time sign-in link. No password needed.

or

Tell us a little about you

Optional, every field. It helps us pitch answers to your questions at the right level and decide which topics to write next. It is never shown publicly, and you can change or clear it anytime from the account menu.

SAP areas you work in