# IDocs in depth: structure, partner profiles, ports, status handling and reprocessing

> Read an IDoc's control record and segments, set up partner profiles and ports, and run status handling, reprocessing and monitoring without losing orders.

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

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

## Foundational layer

### The 60-second version

An **IDoc** (intermediate document) is SAP's own format for sending a business document from one system to another: a purchase order, an order confirmation, an invoice, a customer record. It has been in SAP systems for decades and still carries a large share of the traffic between SAP and its partners, because thousands of EDI connections and SAP-to-SAP links were built on it and still work.

Every IDoc has three parts. An **envelope** says what it is, who sent it and who receives it. The **content** holds the document itself, in a fixed structure SAP defines for each type. A **diary** records every step the IDoc went through, as numbered **statuses**: "ready", "posted", "not posted", "sent". A failed IDoc doesn't disappear. It waits in the receiving system with a status that says what went wrong, until someone fixes the cause and processes it again.

That is the whole management job: someone must watch the statuses, fix causes in the right place, and never let a failed order sit unnoticed. At Calder Pumpworks, the course's fictional pump maker, every distributor order reaches S/4HANA as an IDoc today, so a missed status means a missed order.

### Why it matters to the business

- **Revenue rides on it.** Calder's distributors, such as Hallam Fluid Systems, send their orders by EDI. An EDI provider turns each one into an `ORDERS` IDoc for Calder's S/4HANA system. An IDoc stuck in "not posted" is an order nobody has entered, and a truck that leaves without it.
- **Failures are quiet.** The sender usually sees only that the message was delivered. Whether S/4HANA created the sales order is in the IDoc's status, inside Calder's system. If nobody looks, the distributor finds out first.
- **Most errors are data, not technology.** A distributor's new part number nobody mapped, a unit the system doesn't know, a new distributor nobody set up. Each needs a business owner to fix the master data, and then a person to process the IDoc again. That makes IDoc monitoring a shared job between IT and customer service, purchasing or finance.
- **They are not going away soon.** SAP keeps IDocs in S/4HANA, supports them in SAP Integration Suite, and SAP's own sample for order intake recommends the IDoc route when a customer already runs EDI order intake ([SAP-samples](https://github.com/SAP-samples/sap-btp-ai-best-practices/blob/main/use-cases/purchase-order-intake-agent/docs/ecc-integration.md)). Clean core asks you to stop adding custom code, not to tear out working IDoc interfaces, as the [integration platform topic](https://erpfde.com/topics/integration-platform-and-clean-core/) explains.

### How SAP does it

- **Inside SAP S/4HANA and SAP ECC**, IDocs are part of the standard system: partner profiles, ports, the IDoc monitor and reprocessing are all delivered. SAP's training describes the IDoc as SAP's standard format for EDI, stored as control, data and status records ([SAP Learning](https://learning.sap.com/courses/developing-integration-scenarios-using-idoc-rfc-adapter-of-sap-process-orchestration/explaining-the-integration-technology-based-on-bapis-and-idocs-basics_db458c59-a70f-480d-b139-65065be1b9e9)).
- **SAP S/4HANA Cloud Public Edition** uses IDocs only where SAP offers them through a communication scenario. An SAP knowledge base article, for example, deals with IDocs sent through scenario `SAP_COM_0277` set up in the *Communication Arrangements* app ([SAP KBA 3766365](https://userapps.support.sap.com/sap/support/knowledge/en/3766365)). Check the SAP Business Accelerator Hub for what your edition and release offers before you plan an IDoc there.
- **SAP Integration Suite** has an IDoc adapter that sends and receives IDocs over HTTP, so IDocs can travel between S/4HANA and the cloud ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Development/configure-the-idoc-receiver-adapter-018aa88.md)).
- **Monitoring beyond the system.** As of November 2026, SAP Cloud ALM's integration monitoring includes IDocs as a category, with alerts on failed IDocs and slow processing ([SAP Support Portal](https://support.sap.com/ja/alm/sap-cloud-alm/operations/expert-portal/integration-monitoring/calm-s4-onprem.html)). SAP Application Interface Framework (AIF) adds business-friendly monitoring and error handling on top of IDocs ([SAP Learning](https://learning.sap.com/courses/mastering-standard-interface-technologies-with-sap-application-interface-framework/processing-and-monitoring-inbound-idocs-with-aif)).

### A failed order, from the inbox to the fix

What happens on a Monday morning at Calder when Hallam orders a seal kit under a new part number:

| Time | What happens | Who acts | Status the IDoc shows |
| --- | --- | --- | --- |
| 07:34 | Hallam's order for 20 seal kits, part `HFS-SK-210`, arrives from the EDI provider | Nobody: it is automatic | Ready to be passed to the application |
| 07:34 | S/4HANA can't find a Calder material for `HFS-SK-210` and creates no order | Nobody yet | Application document not posted |
| 08:10 | The monitor raises an alert for an order not posted | Integration support sees it | Not posted |
| 08:20 | Customer service confirms `HFS-SK-210` is the new name of seal kit `CP-SK200` and adds the mapping | Customer service, the business owner | Not posted |
| 08:25 | Integration support processes the same IDoc again | Integration support | Application document posted: sales order created |

Three things to notice. The fix was in master data, not in the IDoc. The IDoc was processed again, not resent by the partner. And the person who owns the data and the person who reprocesses are different people, with different authorizations.

> **Note** **For functional consultants.** IDoc errors land in your area: a missing customer-material record, a unit of measure, a sales area, a partner nobody set up. Your work changes in three ways. Name a business owner for every IDoc interface in your design, and the error texts they will see. Add test cases that send a deliberately bad IDoc and check the error text and who fixes it. Treat a change to customer-material records, units or sales areas as a change that can break an EDI partner, and test it with a sample IDoc.

### Questions to ask

1. Which of our interfaces run on IDocs today, for which partners, and who owns each one on the business side?
2. Who looks at failed IDocs, how often, and how fast must an order that didn't post be fixed?
3. When an IDoc fails because of master data, who fixes the data and who processes the IDoc again? Are those separate authorizations?
4. Do we know the difference between "sent" and "received and posted"? Who confirms the partner actually got our confirmations?
5. Which IDocs use our own extensions or custom segments, and what does each cost us at upgrade time?
6. For a move to S/4HANA Cloud Public Edition or a new integration platform, which of our IDocs does SAP offer there, and what replaces the rest?
7. How long do we keep old IDocs, and do they hold personal data such as addresses or contact names?

### Common misconceptions

- **"If the partner got no error, the order is in."** The partner's EDI provider usually only knows the IDoc was delivered. Whether a sales order exists is decided in S/4HANA afterwards.
- **"A failed IDoc must be sent again."** In most cases the IDoc is already in the system. Fix the cause and process it again; a resend creates a second copy.
- **"Fixing the IDoc's content is the quick fix."** Changing the data of an IDoc hides the real cause and leaves no clean record. Fix the master data or the partner's data at the source.
- **"Status 'sent' means the partner has it."** For outbound IDocs, SAP's status says the data was passed on to the port. It says nothing about whether the partner processed it.
- **"IDocs are legacy, so clean core means replacing them."** SAP still supports and recommends IDocs in many integrations. What clean core restricts is custom code, including custom segments filled by your own code.
- **"Credit blocks are IDoc errors."** An order that is created with a credit block posted fine. It is a business hold for the credit team, not a failure for IT.

### Key terms

- **IDoc (intermediate document):** SAP's standard container for exchanging a business document between systems, with a control record, data records and status records.
- **Control record:** the IDoc's envelope: number, type, message type, sender, receiver and ports.
- **Segment:** one record of an IDoc's content, such as the order header, a partner or an item, in a hierarchy the basic type fixes.
- **Message type:** what the IDoc means in business terms, such as `ORDERS` (purchase order) or `ORDRSP` (order response).
- **Basic type:** the technical structure of segments, such as `ORDERS05`; one basic type can carry several message types.
- **Extension:** customer segments added to a basic type; it adds custom code to keep up.
- **Partner profile:** the settings that say what to do with a message type for one partner: how to process it inbound, or where and when to send it outbound.
- **Port:** the technical channel an IDoc leaves or arrives through, such as a transactional RFC connection or HTTP.
- **Status:** a two-digit code in the IDoc's history that says how far processing got, such as "posted" or "not posted".
- **Reprocessing:** running a failed IDoc again in the system after its cause is fixed, without the partner resending it.

### Check yourself

1. Hallam's order IDoc reached S/4HANA but shows "application document not posted". What does that tell a manager?
   - A. The EDI provider lost the order and Hallam must send it again
   - B. The order is in Calder's system but no sales order exists yet
   - C. The sales order exists and only its confirmation to Hallam failed
   - D. The order was refused because Hallam is above its credit limit

   Answer: B. The IDoc arrived and is stored in Calder's system, but the application step failed, so no sales order was created. A credit block is different: that order is created and held for the credit team.

2. An order IDoc failed because of a part number nobody mapped. What is the right fix?
   - A. Ask the distributor to resend the order with Calder's own part number
   - B. Edit the part number inside the IDoc and save it again
   - C. Add the mapping in master data, then process the same IDoc again
   - D. Delete the IDoc and enter the order by hand in sales order entry

   Answer: C. The cause is missing master data, so it is fixed there, and the IDoc already in the system is processed again. A resend creates a second copy, and editing the IDoc hides the cause.

3. Who should fix the master data behind a failed order IDoc at Calder?
   - A. The business owner of the data, such as customer service
   - B. The EDI provider, since it converted the order
   - C. The integration team, since the error is in an interface
   - D. Whoever first notices the alert in the monitor

   Answer: A. Most IDoc errors are data errors, so the business owner of that data fixes them. Integration support then processes the IDoc again; the two roles have different authorizations.

4. Calder's outbound order confirmation IDoc shows that its data was passed to the port. What does that prove?
   - A. Hallam has received and processed the confirmation
   - B. Hallam's EDI provider has forwarded it to Hallam
   - C. The sales order behind it can no longer be changed
   - D. Calder's system handed it to the channel, nothing more

   Answer: D. The outbound status says the data left Calder's system through the port. Whether the partner got and processed it needs a separate acknowledgment or a check with the partner.

5. Which statement about IDocs and clean core fits this topic?
   - A. IDocs break clean core and should be replaced in any upgrade
   - B. Working IDoc interfaces can stay; custom segments need a reason
   - C. IDocs are clean only when they travel through Integration Suite
   - D. IDocs are allowed in S/4HANA but only for master data

   Answer: B. SAP still supports IDocs in S/4HANA and Integration Suite. What clean core restricts is custom code, such as extensions that need your own code to fill them.

6. You plan a move to S/4HANA Cloud Public Edition. What should you check about today's IDocs?
   - A. Nothing: Public Edition offers every IDoc that ECC offered
   - B. Nothing: Public Edition has no IDocs, so all must be rebuilt
   - C. Which IDocs SAP offers there, through which communication scenario
   - D. Whether the EDI provider can convert IDocs to a newer IDoc release

   Answer: C. Public Edition offers IDocs only where SAP provides them through a communication scenario. Check the Business Accelerator Hub for your edition and release and plan a replacement for the rest.

7. Which question best tests whether IDoc monitoring is under control?
   - A. How many IDoc types does our system have installed?
   - B. Who looks at failed IDocs, how often, and how fast must they be fixed?
   - C. Which release of the IDoc basic types do we run?
   - D. Can the EDI provider see the statuses in our system?

   Answer: B. Failures are quiet: the order waits in Calder's system until someone acts. A named owner, a cadence and a target time are what keep orders from being lost.

## Deep layer

### Mental model

Think of an IDoc as **a document with an envelope and a diary**. The envelope (the control record) names the type and the partners, and the receiving system uses it to look up a **partner profile**: the rule that says what to do with this message type from this partner. The document (the data records) is a tree of segments whose shape the basic type fixes. The diary (the status records) only grows: every step adds a status, nothing is rewritten.

The one idea that makes the rest click: **once an IDoc is saved in the receiving system, that system owns it.** Errors are fixed where they arise, in master data or configuration, and the same IDoc is processed again. Resending from the partner is the exception, for when the IDoc never arrived. Almost every operational mistake with IDocs is a violation of this rule: a resend that creates a duplicate, an edited IDoc that hides a master data gap, an outbound "sent" read as "received".

### How it works

#### The three records

SAP's training describes three kinds of record, each stored in its own table: one **control record** per IDoc, the **data records** that hold the segments, and the **status records** that hold every processing status so far. The control record also carries the last status, and status records are kept apart from the IDoc's content ([SAP Learning](https://learning.sap.com/courses/developing-integration-scenarios-using-idoc-rfc-adapter-of-sap-process-orchestration/explaining-the-integration-technology-based-on-bapis-and-idocs-basics_db458c59-a70f-480d-b139-65065be1b9e9)).

When an IDoc travels as XML, as it does to and from SAP Integration Suite, the control record is the segment `EDI_DC40`. The fields below appear in SAP's own sample `ORDERS05` payload ([SAP integration recipes](https://github.com/SAP/apibusinesshub-integration-recipes/tree/master/Recipes/for/b2bintegrationfactoryordertocashscenario/IDoc/UNEDIFACT)) and in SAP's migration guide for Cloud Integration's IDoc pipeline ([SAP documentation](https://github.com/SAP-docs/btp-process-orchestration-migration-guide/blob/main/docs/70-interface-migration/generic-inbound-and-outbound-5e2fdf8.md)):

| Field | What it holds |
| --- | --- |
| `DOCNUM` | The IDoc number, unique in the system that holds it |
| `IDOCTYP` | The basic type, such as `ORDERS05` |
| `CIMTYP` | The extension, if customer segments were added; empty otherwise |
| `MESTYP` | The message type, such as `ORDERS` or `ORDRSP` |
| `SNDPOR`, `SNDPRT`, `SNDPRN` | Sender port, partner type and partner number |
| `RCVPOR`, `RCVPRT`, `RCVPRN` | The same for the receiver |
| `CREDAT`, `CRETIM` | Creation date and time |
| `STATUS` | The status when the IDoc was written |
| `TEST` | A test flag; SAP's pipeline uses it to route test IDocs to a mock receiver |

The **partner type** says what kind of partner the number is. SAP's sources use `LS` for a logical system (another SAP system or a middleware) and `KU` for a customer; SAP's ECC integration sample suggests a `KU` profile per customer or one generic logical system for Cloud Integration ([SAP-samples](https://github.com/SAP-samples/sap-btp-ai-best-practices/blob/main/use-cases/purchase-order-intake-agent/docs/ecc-integration.md)).

#### Message type, basic type and extensions

The **message type** is the business meaning; the **basic type** is the structure. They are not one to one: SAP's training gives the example of one basic type carrying both `ORDERS` (purchase order) and `ORDRSP` (order confirmation), and SAP's sample payload is an `ORDRSP` on basic type `ORDERS05`.

The data records of `ORDERS05` form a tree. The segments that matter for an inbound sales order, from SAP's ECC integration sample:

| Segment | Holds | Fields and qualifiers used |
| --- | --- | --- |
| `E1EDK01` | Header data | `CURCY` currency |
| `E1EDK14` | Organizational data, one segment per qualifier | `QUALF` `008` sales organization, `007` distribution channel, `006` division, `012` order type; value in `ORGID` |
| `E1EDK03` | Header dates | `IDDAT` `022` PO date, `002` requested delivery date |
| `E1EDK02` | Reference documents | `QUALF` `001` with `BELNR`: the customer's PO number |
| `E1EDKA1` | Partners | `PARVW` `AG` sold-to, `WE` ship-to; number in `PARTN` |
| `E1EDP01` | Item | `POSEX` item number, `MENGE` quantity, `MENEE` unit, `WERKS` plant |
| `E1EDP19` | Item object identification, under `E1EDP01` | `QUALF` `002` material number, `001` customer material number; value in `IDTNR` |
| `E1EDP20` | Schedule line | `WMENG` quantity, `EDATU` date |

Qualifiers are why IDocs are hard to read raw: the same segment means different things depending on a code. Read them with the IDoc type documentation for your release, which SAP's training shows in transaction `WE60` ([SAP Learning](https://learning.sap.com/courses/developing-integration-scenarios-using-idoc-rfc-adapter-of-sap-process-orchestration/using-the-intermediate-document-idoc-adapter-in-the-advanced-adapter-engine-aae-_edfa0134-4d73-437e-ae66-aae2f170114c)).

An **extension** adds customer segments to a basic type and is named in `CIMTYP`. In XML, the IDoc's type name then combines all three, which SAP's training writes as message type, basic type and enhancement joined by dots. An extension is cheap to define and expensive to own: the system needs your own code to fill the segment on the way out or to read it on the way in, and every partner's mapping must know it. Before adding one, check whether a standard segment, a qualifier or a text segment already carries the value.

#### Partner profiles and processing

A partner profile, in SAP's words, defines the conditions for exchanging data with a partner over the IDoc interface ([SAP Library](https://help.sap.com/saphelp_nwce10/helpdata/en/99/e7b23b94c6e54be10000000a11402f/content.htm)). It is maintained in transaction `WE20`, one per partner, with lines per message type and direction ([SAP Developers](https://developers.sap.com/tutorials/aif-idoc-monitoring-interface-create.html)):

- **Inbound lines** name the message type and a **process code**, which points to the function that posts the IDoc. For sales orders from `ORDERS`, SAP's sample uses process code `ORDE`. Processing is either triggered at once (*Trigger immediately* in SAP's tutorial) or left for a scheduled job, which suits high volumes and keeps the sender from waiting.
- **Outbound lines** name the message type, basic type and receiver port, and whether to pass each IDoc on at once or collect them for a job to send. SAP's partner profile documentation says immediate output processes every IDoc individually, with a package size of 1; the package size sets how many IDocs go in one call when a background program sends them.
- **Syntax check.** SAP's training says the syntax check is switched on or off in the partner profile, separately for inbound and outbound. Leave it on: a structure error caught at the door is cheaper than one caught by the application.

Between SAP systems, ALE (Application Link Enabling) adds a **distribution model** that says which system sends which message types to which. SAP's procedure maintains it in `BD64` (reached from the `SALE` menu) and can generate the partner profiles from it with `BD82`.

#### Ports

The port is the channel ([SAP Developers](https://developers.sap.com/tutorials/aif-idoc-monitoring-interface-create.html)):

- A **transactional RFC port**, set up in `WE21`, points to an RFC destination from `SM59`. This is the classic channel between SAP systems and to SAP PI/PO.
- An **HTTP-based port** sends IDoc-XML to a URL. This is what SAP Integration Suite needs: SAP's migration guide states that Cloud Integration supports IDoc over HTTP, so the traditional IDoc packing over RFC can't be used ([SAP documentation](https://github.com/SAP-docs/btp-process-orchestration-migration-guide/blob/main/docs/30-connectivity/standard-adapter-migration-2622c30.md)). For the inbound direction, SAP's training registers the SOAP service for IDocs with transaction `SRTIDOC`, at the path `/sap/bc/srt/idoc` ([SAP Learning](https://learning.sap.com/learning-journeys/integrate-sap-sales-cloud-and-sap-service-cloud-with-sap-s-4hana/configuring-sap-s-4hana_f4f4bfb6-923f-4b3d-9667-746daa9a00cb)).
- A **file port** writes IDocs as files. SAP's Focused Run page names tRFC and file as the techniques ALE uses underneath ([SAP Support Portal](https://support.sap.com/en/alm/sap-focused-run/expert-portal/integration-cloud-monitoring/Idoc.html)).

#### Statuses

Statuses are two-digit codes, separate for each direction. The ones this topic uses:

| Status | Direction | Meaning | Who acts |
| --- | --- | --- | --- |
| `30` | Out | Ready for dispatch: waiting for a job to send it | Nobody, unless it waits too long |
| `03` | Out | Data passed to the port: it left this system | Nobody; it doesn't prove receipt |
| `02` | Out | Error passing data to the port: the channel failed | Integration support, after the channel is back |
| `64` | In | Ready to be passed to the application | Nobody, unless the job doesn't run |
| `53` | In | Application document posted | Nobody |
| `51` | In | Application document not posted | The data owner fixes the cause; support reprocesses |
| `56` | In | IDoc added with errors, often a missing or wrong partner profile | Integration team |

Sources: SAP's knowledge base gives status 30 as "IDoc ready for dispatch (ALE service)" ([SAP KBA 3614190](https://userapps.support.sap.com/sap/support/knowledge/en/3614190)) and describes inbound IDocs left in 64 until processed by hand ([SAP KBA 3791384](https://userapps.support.sap.com/sap/support/knowledge/en/3791384)). The other meanings follow an independent diagnostics reference ([SAP IDoc status diagnostics](https://dkharlanau.github.io/atlas/diagnostics/sap-idoc-status-diagnostics/)); check them against your system's status list.

```mermaid
flowchart LR
  subgraph Inbound
    A[IDoc arrives] --> P{Partner<br/>profile?}
    P -- no --> S56[56]
    P -- yes --> S64[64 ready]
    S64 -->|now or job| APP{Posts?}
    APP -- yes --> S53[53 posted]
    APP -- no --> S51[51 not posted]
    S51 -->|fix cause,<br/>reprocess| APP
  end
  subgraph Outbound
    O[Document saved] --> S30[30 ready]
    S30 -->|now or job| PORT{Port OK?}
    PORT -- yes --> S03[03 passed]
    PORT -- no --> S02[02 error]
    S02 -->|resend| PORT
  end
```

#### Reprocessing and duplicates

**Reprocessing** runs a failed IDoc again in the system that holds it. SAP's knowledge base articles use transaction `BD87` for this, inbound and outbound, and name `RBDAGAIN` as a resend that can leave an IDoc waiting in 30 ([SAP KBA 3614190](https://userapps.support.sap.com/sap/support/knowledge/en/3614190)). Collected outbound IDocs are sent by a scheduled job; SAP's training names `RSEOUT00` among the periodic IDoc jobs ([SAP Learning](https://learning.sap.com/learning-journeys/integrate-sap-sales-cloud-and-sap-service-cloud-with-sap-s-4hana/configuring-sap-s-4hana_f4f4bfb6-923f-4b3d-9667-746daa9a00cb)). `WE19` is the IDoc test tool; SAP's tutorial uses it to push a test IDoc into inbound processing ([SAP Developers](https://developers.sap.com/tutorials/aif-idoc-monitoring-interface-create.html)). It belongs in testing, not in production fixes.

**Duplicates** come in two kinds, and they need two defenses:

- **Technical duplicates**: the same IDoc delivered twice because an acknowledgment was lost. SAP's Cloud Integration documentation says the IDoc runtime in the back end detects and ignores duplicates when the IDoc receiver adapter uses content type *Application/x-sap.idoc* and the header `SapMessageId` stays the same on every retry; content type *Text/XML* allows several IDocs per call but not exactly-once ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Development/configure-the-idoc-receiver-adapter-018aa88.md)). SAP's generic inbound pipeline adds its own duplicate check on sender partner plus IDoc number. For order, the sender adapter supports *Exactly Once In Order* through the control field `ARCKEY`, with SAP Note 3519275 applied in the sending system ([SAP documentation](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Development/configure-the-idoc-sender-adapter-bf769d6.md)).
- **Business duplicates**: the partner or its provider sends the same order again as a new message, with a new IDoc number. No transport setting catches this. The application step must check a business key, such as sold-to party plus customer PO number, which is what Calder's `I10` design asks for.

### Build it yourself: run Calder's distributor order IDocs

You will run a small stand-in for the IDoc layer of Calder's S/4HANA system `S4P`. Seven distributor order IDocs arrive from the EDI provider, as they do today on interface `I10`. You will read their control records and segments, find out why four of them didn't post, fix each cause in the right place, reprocess, and then send order responses back through a port that goes down halfway.

```mermaid
flowchart LR
  I[--init] --> F[inbox: 7 ORDERS05<br/>IDoc-XML files]
  F --> R[--run]
  R --> PP{partner<br/>profile}
  PP --> APP[post: material,<br/>unit, duplicate PO]
  APP --> ST[(state.json:<br/>statuses, orders)]
  ST --> M[--monitor, --show,<br/>--alerts]
  ST --> C[--confirm: ORDRSP]
  C --> PO[port EDIPROV]
```

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 26](https://erpfde.com/topics/set-up-for-unit-26/). Reading [B2B and EDI with Trading Partner Management](https://erpfde.com/topics/b2b-and-edi-integration/) first helps but isn't required.

> **Note** New words. **IDoc-XML** is an IDoc written as XML, with one element per segment and field, the way SAP Integration Suite exchanges IDocs. The lab's **state file** `unit26/idoc/state.json` stands in for the system's database: profiles, IDocs with their status history, and the sales orders created. The **lab clock** starts at 08:00 on Monday 30 November 2026 and moves one minute per recorded event, so your times match the samples. **Exit code** `2` from `--alerts` means something needs a person, which a scheduler can turn into a notification.

> **Warning** This is a model of the IDoc layer in a course format, not SAP's software. Status numbers are SAP's; partners, customer numbers, prices, rules and file layout are course values. Never test on a real system with a partner's live orders.

#### What you need

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

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

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

   - **Windows (PowerShell):**

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

   - **macOS / Linux:**

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

4. Make sure the `unit26` folder exists (the setup created it; this does nothing if it's there):

   - **Windows (PowerShell):**

     ```powershell
     New-Item -ItemType Directory -Force unit26 | Out-Null
     ```

   - **macOS / Linux:**

     ```bash
     mkdir -p unit26
     ```

#### Step 2: Create the script

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

```python
"""An IDoc lab for Unit 26: control records, partner profiles, ports, status records, reprocessing.

A local stand-in for the IDoc layer of Calder's S/4HANA system S4P (company code CP10).
Built-in modules only, no randomness, no network. Run from your course folder:

    python unit26/idoc_lab.py --init              # write profiles, ports, mappings and the inbox
    python unit26/idoc_lab.py --run               # take in every IDoc in the inbox
    python unit26/idoc_lab.py --monitor           # one line per IDoc: number, partner, status
    python unit26/idoc_lab.py --show DOCNUM       # control record, segments and status history
    python unit26/idoc_lab.py --job               # the background job for IDocs waiting in 64
    python unit26/idoc_lab.py --map KUNNR PART MATERIAL     # add a customer-material record
    python unit26/idoc_lab.py --profile KUNNR MODE          # add an inbound profile (MODE: now or job)
    python unit26/idoc_lab.py --reprocess DOCNUM [DOCNUM ...]  # process IDocs again after a fix
    python unit26/idoc_lab.py --close DOCNUM REASON         # stop an IDoc for good, with a reason
    python unit26/idoc_lab.py --confirm           # create order responses (ORDRSP) for posted orders
    python unit26/idoc_lab.py --port NAME up|down # simulate the provider's endpoint going down or up
    python unit26/idoc_lab.py --send              # the background job for outbound IDocs waiting in 30
    python unit26/idoc_lab.py --alerts            # IDocs that need a person, by the course rules
    python unit26/idoc_lab.py --exercise          # add Tessaly's first order to the inbox

Status numbers are the SAP statuses the topic explains; their texts here are short course wordings.
Partners, rules, numbers, the clock and the file layout are course labels, not SAP formats.
"""
import argparse
import json
import sys
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta
from pathlib import Path

HOME = Path("unit26/idoc")
INBOX = HOME / "inbox"
STATE = HOME / "state.json"
START = datetime(2026, 11, 30, 8, 0)          # Monday, the lab date

STATUS_TEXT = {                                  # the statuses this lab uses
    "64": "IDoc ready to be passed to application",
    "53": "Application document posted",
    "51": "Application document not posted",
    "56": "IDoc with errors added (partner profile check)",
    "30": "IDoc ready for dispatch (ALE service)",
    "03": "Data passed to port OK",
    "02": "Error passing data to port",
}
CLOSED = "closed"                                # course label: no further processing, with a reason

# --- the sample data written by --init --------------------------------------------------------

PROFILES = {   # partner profiles: inbound by (partner type, partner, message type); outbound likewise
    "inbound": [
        {"prt": "KU", "prn": "10000002", "name": "Hallam Fluid Systems", "mestyp": "ORDERS",
         "process_code": "ORDE", "mode": "now"},
        {"prt": "KU", "prn": "10000033", "name": "Venmoor Industrial Supply", "mestyp": "ORDERS",
         "process_code": "ORDE", "mode": "job"},
    ],
    "outbound": [
        {"prt": "KU", "prn": "10000002", "mestyp": "ORDRSP", "idoctyp": "ORDERS05",
         "port": "EDIPROV", "output": "immediately"},
        {"prt": "KU", "prn": "10000033", "mestyp": "ORDRSP", "idoctyp": "ORDERS05",
         "port": "EDIPROV", "output": "collect"},
    ],
}
PORTS = {"EDIPROV": {"kind": "XML HTTP (course stand-in)", "target": "the EDI provider", "up": True}}
CUSTOMERS = {   # sold-to party: sales area, credit exposure and limit (course values, USD)
    "10000002": {"name": "Hallam Fluid Systems", "sales_area": "CPUS/20/PU",
                 "exposure": 45326.25, "limit": 40000.00},
    "10000032": {"name": "Quillan Pump Supply", "sales_area": "CPUS/20/PU",
                 "exposure": 0.0, "limit": 25000.00},
    "10000033": {"name": "Venmoor Industrial Supply", "sales_area": "CPUS/20/PU",
                 "exposure": 0.0, "limit": 25000.00},
    "10000034": {"name": "Tessaly Flow Parts", "sales_area": "CPUS/20/PU",
                 "exposure": 0.0, "limit": 25000.00},
}
MATERIALS = {"CP-SK200": 95.00, "CP-ES200": 3555.00}        # distributor prices in CPUS/20
CUSTOMER_MATERIAL = {   # (customer, customer's part) -> Calder material
    "10000002|HFS-SK-200": "CP-SK200",
    "10000002|HFS-P200": "CP-ES200",
}
UNITS = {"PCE": "PC", "EA": "PC", "PC": "PC"}

# (docnum, partner, customer PO, [(customer part or material, quantity, unit)], minutes after 08:00)
INBOX_SPEC = [
    ("0000000000500001", "10000002", "HFS-PO-8230", [("HFS-SK-200", 60, "PCE")], 0),
    ("0000000000500002", "10000002", "HFS-PO-8231", [("HFS-P200", 4, "PCE")], 2),
    ("0000000000500003", "10000002", "HFS-PO-8232", [("HFS-SK-210", 20, "PCE")], 4),
    ("0000000000500004", "10000002", "HFS-PO-8233", [("HFS-SK-200", 3, "BX")], 6),
    ("0000000000500005", "10000032", "QPS-PO-1104", [("CP-SK200", 10, "PCE")], 8),
    ("0000000000500006", "10000002", "HFS-PO-8230", [("HFS-SK-200", 60, "PCE")], 10),
    ("0000000000500007", "10000033", "VIS-PO-0412", [("CP-SK200", 40, "PCE")], 12),
]
EXERCISE_SPEC = ("0000000000500008", "10000034", "TFP-PO-0007", [("TFP-4410", 50, "PCE")], 0)


def idoc_xml(docnum, prn, po, lines, when):
    """An inbound ORDERS05 IDoc in IDoc-XML, as an EDI provider would send it."""
    root = ET.Element("ORDERS05")
    idoc = ET.SubElement(root, "IDOC", BEGIN="1")
    dc = ET.SubElement(idoc, "EDI_DC40", SEGMENT="1")
    for tag, val in [("TABNAM", "EDI_DC40"), ("MANDT", "100"), ("DOCNUM", docnum),
                     ("IDOCTYP", "ORDERS05"), ("CIMTYP", ""), ("MESTYP", "ORDERS"),
                     ("SNDPOR", "EDIPROV"), ("SNDPRT", "KU"), ("SNDPRN", prn),
                     ("RCVPOR", "SAPS4P"), ("RCVPRT", "LS"), ("RCVPRN", "S4PCLNT100"),
                     ("CREDAT", when.strftime("%Y%m%d")), ("CRETIM", when.strftime("%H%M%S"))]:
        ET.SubElement(dc, tag).text = val
    k1 = ET.SubElement(idoc, "E1EDK01", SEGMENT="1")
    ET.SubElement(k1, "CURCY").text = "USD"
    for qualf, orgid in [("008", "CPUS"), ("007", "20"), ("006", "PU")]:
        k14 = ET.SubElement(idoc, "E1EDK14", SEGMENT="1")
        ET.SubElement(k14, "QUALF").text = qualf
        ET.SubElement(k14, "ORGID").text = orgid
    k2 = ET.SubElement(idoc, "E1EDK02", SEGMENT="1")
    ET.SubElement(k2, "QUALF").text = "001"
    ET.SubElement(k2, "BELNR").text = po
    ka = ET.SubElement(idoc, "E1EDKA1", SEGMENT="1")
    ET.SubElement(ka, "PARVW").text = "AG"
    ET.SubElement(ka, "PARTN").text = prn
    for n, (part, qty, unit) in enumerate(lines, start=1):
        p1 = ET.SubElement(idoc, "E1EDP01", SEGMENT="1")
        ET.SubElement(p1, "POSEX").text = f"{n * 10:06d}"
        ET.SubElement(p1, "MENGE").text = f"{qty:.3f}"
        ET.SubElement(p1, "MENEE").text = unit
        p19 = ET.SubElement(p1, "E1EDP19", SEGMENT="1")
        qualf = "002" if part.startswith("CP-") else "001"     # 002 material, 001 customer material
        ET.SubElement(p19, "QUALF").text = qualf
        ET.SubElement(p19, "IDTNR").text = part
    ET.indent(root)
    return ET.tostring(root, encoding="unicode") + "\n"


# --- state ------------------------------------------------------------------------------------

def load():
    if not STATE.exists():
        sys.exit("unit26/idoc/state.json not found. Run --init first, from your course folder.")
    return json.loads(STATE.read_text(encoding="utf-8"))


def save(st):
    STATE.write_text(json.dumps(st, indent=2) + "\n", encoding="utf-8")


def tick(st):
    """The lab clock: every recorded event moves it on one minute."""
    st["clock"] += 1
    return (START + timedelta(minutes=st["clock"])).strftime("%Y-%m-%d %H:%M")


def set_status(st, idoc, status, text):
    idoc["status"] = status
    idoc["history"].append({"at": tick(st), "status": status, "text": text})


def write_samples():
    INBOX.mkdir(parents=True, exist_ok=True)
    for docnum, prn, po, lines, minutes in INBOX_SPEC:
        path = INBOX / f"{docnum[-6:]}.xml"
        path.write_text(idoc_xml(docnum, prn, po, lines, START + timedelta(minutes=minutes - 30)),
                        encoding="utf-8")


def init():
    if HOME.exists():
        sys.exit("unit26/idoc/ already exists. Delete the folder only if you want to start again.")
    HOME.mkdir(parents=True)
    write_samples()
    st = {"clock": 0, "profiles": PROFILES, "ports": PORTS, "customers": CUSTOMERS,
          "materials": MATERIALS, "customer_material": CUSTOMER_MATERIAL,
          "idocs": {}, "orders": {}, "next_order": 1000701, "next_out": 900001}
    save(st)
    print(f"Wrote {len(INBOX_SPEC)} inbound IDocs to unit26/idoc/inbox/ and the lab state.")
    print("Partner profiles: inbound ORDERS from KU 10000002 (now), KU 10000033 (job).")


# --- inbound ----------------------------------------------------------------------------------

def read_idoc(path):
    root = ET.parse(path).getroot()
    idoc = root.find("IDOC")
    dc = {child.tag: (child.text or "") for child in idoc.find("EDI_DC40")}
    head = {"sales_area": "/".join(
        q.findtext("ORGID") for q in sorted(idoc.findall("E1EDK14"), key=lambda q: q.findtext("QUALF"),
                                            reverse=True)),
            "po": next((k.findtext("BELNR") for k in idoc.findall("E1EDK02")
                        if k.findtext("QUALF") == "001"), ""),
            "sold_to": next((k.findtext("PARTN") for k in idoc.findall("E1EDKA1")
                             if k.findtext("PARVW") == "AG"), "")}
    items = []
    for p1 in idoc.findall("E1EDP01"):
        p19 = p1.find("E1EDP19")
        items.append({"posex": p1.findtext("POSEX"), "qty": float(p1.findtext("MENGE")),
                      "unit": p1.findtext("MENEE"), "qualf": p19.findtext("QUALF"),
                      "part": p19.findtext("IDTNR")})
    return dc, head, items


def inbound_profile(st, prt, prn, mestyp):
    return next((p for p in st["profiles"]["inbound"]
                 if (p["prt"], p["prn"], p["mestyp"]) == (prt, prn, mestyp)), None)


def post(st, idoc):
    """The application step (process code ORDE): check the order and create it, or say why not."""
    dc, head, items = read_idoc(idoc["file"])
    cust = st["customers"].get(head["sold_to"])
    if cust is None:
        return "51", f"Sold-to party {head['sold_to']} does not exist"
    if head["sales_area"] != cust["sales_area"]:
        return "51", f"Sales area {head['sales_area']} not defined for customer {head['sold_to']}"
    for other in st["orders"].values():
        if other["sold_to"] == head["sold_to"] and other["po"] == head["po"]:
            return "51", (f"Customer PO {head['po']} already used in order {other['order']} "
                          f"(IDoc {other['docnum'][-6:]})")
    lines, value = [], 0.0
    for it in items:
        if it["qualf"] == "002":
            material = it["part"]
        else:
            material = st["customer_material"].get(f"{head['sold_to']}|{it['part']}")
            if material is None:
                return "51", f"No customer-material record for {it['part']} (customer {head['sold_to']})"
        if material not in st["materials"]:
            return "51", f"Material {material} not found"
        unit = UNITS.get(it["unit"])
        if unit is None:
            return "51", f"Unit {it['unit']} not found or not convertible (item {it['posex']})"
        lines.append({"material": material, "qty": it["qty"], "unit": unit})
        value += it["qty"] * st["materials"][material]
    number = str(st["next_order"])
    st["next_order"] += 1
    blocked = cust["exposure"] + value > cust["limit"]
    st["orders"][number] = {"order": number, "docnum": idoc["docnum"], "sold_to": head["sold_to"],
                            "po": head["po"], "lines": lines, "value": round(value, 2),
                            "credit_block": blocked}
    cust["exposure"] = round(cust["exposure"] + value, 2)
    note = ", saved with a credit block (a business hold, not an IDoc error)" if blocked else ""
    return "53", f"Sales order {number} saved ({value:,.2f} USD){note}"


def process(st, idoc):
    """From the partner profile check to posting, as the inbound IDoc layer does it."""
    if inbound_profile(st, idoc["prt"], idoc["prn"], idoc["mestyp"]) is None:
        set_status(st, idoc, "56", f"No inbound partner profile for {idoc['prt']} {idoc['prn']} "
                                   f"{idoc['mestyp']}")
        return
    profile = inbound_profile(st, idoc["prt"], idoc["prn"], idoc["mestyp"])
    if idoc["status"] != "64":
        set_status(st, idoc, "64", f"Ready; process code {profile['process_code']}, "
                                   f"{'trigger immediately' if profile['mode'] == 'now' else 'background job'}")
    if profile["mode"] == "job" and not st.get("_in_job"):
        return
    status, text = post(st, idoc)
    set_status(st, idoc, status, text)


def run():
    st = load()
    new = 0
    for path in sorted(INBOX.glob("*.xml")):
        dc, _, _ = read_idoc(path)
        if dc["DOCNUM"] in st["idocs"]:
            continue
        idoc = {"docnum": dc["DOCNUM"], "file": str(path), "direction": "inbound",
                "prt": dc["SNDPRT"], "prn": dc["SNDPRN"], "mestyp": dc["MESTYP"],
                "idoctyp": dc["IDOCTYP"], "status": "", "history": []}
        st["idocs"][dc["DOCNUM"]] = idoc
        process(st, idoc)
        new += 1
        print(line(st, idoc))
    save(st)
    print(f"{new} new IDoc(s) taken in.")


def job():
    """The stand-in for the background job that passes IDocs in 64 to the application."""
    st = load()
    st["_in_job"] = True
    done = 0
    for idoc in st["idocs"].values():
        if idoc["direction"] == "inbound" and idoc["status"] == "64":
            process(st, idoc)
            done += 1
            print(line(st, idoc))
    st.pop("_in_job")
    save(st)
    print(f"Background job: {done} IDoc(s) passed to the application.")


def reprocess(docnums):
    st = load()
    for docnum in docnums:
        idoc = find(st, docnum)
        if idoc["status"] in ("53", "03", CLOSED):
            print(f"IDoc {idoc['docnum'][-6:]} is in {idoc['status']}: nothing to reprocess.")
            continue
        if idoc["direction"] == "outbound":
            dispatch(st, idoc)
        else:
            st["_in_job"] = True              # a person reprocessing runs it now, whatever the mode
            process(st, idoc)
            st.pop("_in_job")
        print(line(st, idoc))
    save(st)


def close(docnum, reason):
    st = load()
    idoc = find(st, docnum)
    if idoc["status"] in ("53", "03", CLOSED):
        sys.exit(f"IDoc {idoc['docnum'][-6:]} is in {idoc['status']}: it can't be closed.")
    set_status(st, idoc, CLOSED, f"No further processing: {reason}")
    save(st)
    print(line(st, idoc))


# --- outbound ---------------------------------------------------------------------------------

def dispatch(st, idoc):
    port = st["ports"][idoc["port"]]
    if port["up"]:
        set_status(st, idoc, "03", f"Passed to port {idoc['port']} ({port['target']})")
    else:
        set_status(st, idoc, "02", f"Port {idoc['port']}: {port['target']} not reachable")


def confirm():
    st = load()
    made = 0
    answered = {i["order"] for i in st["idocs"].values() if i["direction"] == "outbound"}
    for order in st["orders"].values():
        if order["order"] in answered:
            continue
        prof = next((p for p in st["profiles"]["outbound"]
                     if (p["prt"], p["prn"], p["mestyp"]) == ("KU", order["sold_to"], "ORDRSP")), None)
        if prof is None:
            print(f"Order {order['order']}: no outbound profile for ORDRSP to {order['sold_to']}, "
                  "no IDoc created")
            continue
        docnum = f"{st['next_out']:016d}"
        st["next_out"] += 1
        idoc = {"docnum": docnum, "file": "", "direction": "outbound", "prt": "KU",
                "prn": order["sold_to"], "mestyp": "ORDRSP", "idoctyp": prof["idoctyp"],
                "port": prof["port"], "order": order["order"], "status": "", "history": []}
        st["idocs"][docnum] = idoc
        set_status(st, idoc, "30", f"Order response for {order['order']} ({order['po']}); "
                                   f"output mode: {prof['output']}")
        if prof["output"] == "immediately":
            dispatch(st, idoc)
        made += 1
        print(line(st, idoc))
    save(st)
    print(f"{made} order response IDoc(s) created.")


def send():
    """The stand-in for the background job that sends outbound IDocs waiting in 30."""
    st = load()
    sent = 0
    for idoc in st["idocs"].values():
        if idoc["direction"] == "outbound" and idoc["status"] == "30":
            dispatch(st, idoc)
            sent += 1
            print(line(st, idoc))
    save(st)
    print(f"Send job: {sent} IDoc(s) handed to their port.")


def port(name, state):
    st = load()
    if name not in st["ports"]:
        sys.exit(f"No port {name}. Ports: {', '.join(st['ports'])}")
    st["ports"][name]["up"] = state == "up"
    save(st)
    print(f"Port {name} is {'up' if state == 'up' else 'down'}.")


# --- monitor and alerts -----------------------------------------------------------------------

def find(st, docnum):
    hits = [i for d, i in st["idocs"].items() if d.endswith(docnum.lstrip("0") or "x")]
    if len(hits) != 1:
        sys.exit(f"IDoc {docnum} not found. Run --monitor to see the numbers.")
    return hits[0]


def line(st, idoc):
    last = idoc["history"][-1]
    arrow = "in " if idoc["direction"] == "inbound" else "out"
    return (f"{idoc['docnum'][-6:]} {arrow} {idoc['mestyp']:<6} {idoc['prt']} {idoc['prn']}  "
            f"{idoc['status']:<6} {last['text']}")


def monitor():
    st = load()
    counts = {}
    for idoc in st["idocs"].values():
        print(line(st, idoc))
        counts[idoc["status"]] = counts.get(idoc["status"], 0) + 1
    print("By status: " + ", ".join(f"{s} x{n}" for s, n in sorted(counts.items())))


def show(docnum):
    st = load()
    idoc = find(st, docnum)
    print(f"IDoc {idoc['docnum']}  {idoc['direction']}  {idoc['mestyp']} / {idoc['idoctyp']}  "
          f"partner {idoc['prt']} {idoc['prn']}")
    if idoc["file"]:
        dc, head, items = read_idoc(idoc["file"])
        print(f"  Control record: SNDPOR {dc['SNDPOR']}  SNDPRT {dc['SNDPRT']}  SNDPRN {dc['SNDPRN']}  "
              f"RCVPRN {dc['RCVPRN']}  CREDAT {dc['CREDAT']} {dc['CRETIM']}")
        print(f"  E1EDK14 sales area {head['sales_area']}  E1EDK02 PO {head['po']}  "
              f"E1EDKA1 AG {head['sold_to']}")
        for it in items:
            print(f"  E1EDP01 {it['posex']} {it['qty']:g} {it['unit']}  "
                  f"E1EDP19 {it['qualf']} {it['part']}")
    for h in idoc["history"]:
        print(f"  {h['at']}  {h['status']:<6} {h['text']}")


def alerts():
    """Course rules: 51, 56 and 02 need a person at once; 64 and 30 waiting over 15 minutes."""
    st = load()
    now = START + timedelta(minutes=st["clock"])
    found = 0
    for idoc in st["idocs"].values():
        since = datetime.strptime(idoc["history"][-1]["at"], "%Y-%m-%d %H:%M")
        waited = int((now - since).total_seconds() // 60)
        if idoc["status"] in ("51", "56", "02") or (idoc["status"] in ("64", "30") and waited > 15):
            found += 1
            print(f"ALERT {line(st, idoc)}  (waiting {waited} min)")
    print(f"{found} IDoc(s) need a person." if found else "Nothing needs a person.")
    return 2 if found else 0


def exercise():
    st = load()
    docnum, prn, po, lines, _ = EXERCISE_SPEC
    path = INBOX / f"{docnum[-6:]}.xml"
    if path.exists():
        sys.exit("The exercise IDoc is already in the inbox.")
    path.write_text(idoc_xml(docnum, prn, po, lines, START + timedelta(minutes=st["clock"])),
                    encoding="utf-8")
    print(f"Added IDoc {docnum[-6:]} from Tessaly Flow Parts (KU {prn}) to the inbox.")


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--init", action="store_true")
    ap.add_argument("--run", action="store_true")
    ap.add_argument("--monitor", action="store_true")
    ap.add_argument("--show", metavar="DOCNUM")
    ap.add_argument("--job", action="store_true")
    ap.add_argument("--map", nargs=3, metavar=("KUNNR", "PART", "MATERIAL"))
    ap.add_argument("--profile", nargs=2, metavar=("KUNNR", "MODE"))
    ap.add_argument("--reprocess", nargs="+", metavar="DOCNUM")
    ap.add_argument("--close", nargs=2, metavar=("DOCNUM", "REASON"))
    ap.add_argument("--confirm", action="store_true")
    ap.add_argument("--port", nargs=2, metavar=("NAME", "STATE"))
    ap.add_argument("--send", action="store_true")
    ap.add_argument("--alerts", action="store_true")
    ap.add_argument("--exercise", action="store_true")
    a = ap.parse_args()
    if a.init:
        init()
    elif a.run:
        run()
    elif a.monitor:
        monitor()
    elif a.show:
        show(a.show)
    elif a.job:
        job()
    elif a.map:
        st = load()
        kunnr, part, material = a.map
        if material not in st["materials"]:
            sys.exit(f"Material {material} not found. Materials: {', '.join(st['materials'])}")
        st["customer_material"][f"{kunnr}|{part}"] = material
        save(st)
        print(f"Customer-material record: {kunnr} {part} -> {material}")
    elif a.profile:
        st = load()
        kunnr, mode = a.profile
        if mode not in ("now", "job"):
            sys.exit("MODE is now (trigger immediately) or job (background job).")
        if kunnr not in st["customers"]:
            sys.exit(f"Customer {kunnr} not found.")
        if inbound_profile(st, "KU", kunnr, "ORDERS"):
            sys.exit(f"An inbound ORDERS profile for {kunnr} already exists.")
        st["profiles"]["inbound"].append({"prt": "KU", "prn": kunnr, "name": st["customers"][kunnr]["name"],
                                          "mestyp": "ORDERS", "process_code": "ORDE", "mode": mode})
        save(st)
        print(f"Inbound partner profile: KU {kunnr} ORDERS, process code ORDE, mode {mode}")
    elif a.reprocess:
        reprocess(a.reprocess)
    elif a.close:
        close(*a.close)
    elif a.confirm:
        confirm()
    elif a.port:
        if a.port[1] not in ("up", "down"):
            sys.exit("STATE is up or down.")
        port(*a.port)
    elif a.send:
        send()
    elif a.alerts:
        sys.exit(alerts())
    elif a.exercise:
        exercise()
    else:
        ap.print_help()


if __name__ == "__main__":
    main()
```

2. Check that it starts: `python unit26/idoc_lab.py --help` prints the list of options.

#### Step 3: Write the sample data and take in the inbox

1. Write Calder's partner profiles, the port, the master data and seven inbound IDocs:

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

   ```text
   Wrote 7 inbound IDocs to unit26/idoc/inbox/ and the lab state.
   Partner profiles: inbound ORDERS from KU 10000002 (now), KU 10000033 (job).
   ```

2. Open `unit26/idoc/inbox/500001.xml` in VS Code. Find the envelope `EDI_DC40` with `MESTYP` `ORDERS`, `IDOCTYP` `ORDERS05` and the sender `SNDPRT` `KU`, `SNDPRN` `10000002` (Hallam). Below it: the sales area in three `E1EDK14` segments, Hallam's PO number in `E1EDK02`, the sold-to in `E1EDKA1`, and one item `E1EDP01` with Hallam's part number in `E1EDP19` (qualifier `001`).
3. Take in the inbox:

   ```bash
   python unit26/idoc_lab.py --run
   ```

   ```text
   500001 in  ORDERS KU 10000002  53     Sales order 1000701 saved (5,700.00 USD), saved with a credit block (a business hold, not an IDoc error)
   500002 in  ORDERS KU 10000002  53     Sales order 1000702 saved (14,220.00 USD), saved with a credit block (a business hold, not an IDoc error)
   500003 in  ORDERS KU 10000002  51     No customer-material record for HFS-SK-210 (customer 10000002)
   500004 in  ORDERS KU 10000002  51     Unit BX not found or not convertible (item 000010)
   500005 in  ORDERS KU 10000032  56     No inbound partner profile for KU 10000032 ORDERS
   500006 in  ORDERS KU 10000002  51     Customer PO HFS-PO-8230 already used in order 1000701 (IDoc 500001)
   500007 in  ORDERS KU 10000033  64     Ready; process code ORDE, background job
   7 new IDoc(s) taken in.
   ```

Read it line by line. Two of Hallam's orders posted (`53`), and both carry a credit block because Hallam is over its limit: that is the credit team's work, not an interface error. Three failed in the application (`51`), each for a different reason. Quillan Pump Supply has no partner profile yet (`56`). Venmoor's order waits in `64` because its profile hands it to a background job.

> **Note** The orders, amounts and IDoc numbers are synthetic course data. They show the method, not results from a real SAP system.

#### Step 4: Ask what needs a person

```bash
python unit26/idoc_lab.py --alerts
```

```text
ALERT 500003 in  ORDERS KU 10000002  51     No customer-material record for HFS-SK-210 (customer 10000002)  (waiting 6 min)
ALERT 500004 in  ORDERS KU 10000002  51     Unit BX not found or not convertible (item 000010)  (waiting 4 min)
ALERT 500005 in  ORDERS KU 10000032  56     No inbound partner profile for KU 10000032 ORDERS  (waiting 3 min)
ALERT 500006 in  ORDERS KU 10000002  51     Customer PO HFS-PO-8230 already used in order 1000701 (IDoc 500001)  (waiting 1 min)
4 IDoc(s) need a person.
```

The course rules: `51`, `56` and `02` alert at once; `64` and `30` alert only after waiting more than 15 minutes, because waiting there is normal until a job runs. Venmoor's IDoc isn't listed yet.

#### Step 5: Fix a master data gap and reprocess

1. Look at the first failure in full:

   ```bash
   python unit26/idoc_lab.py --show 500003
   ```

   ```text
   IDoc 0000000000500003  inbound  ORDERS / ORDERS05  partner KU 10000002
     Control record: SNDPOR EDIPROV  SNDPRT KU  SNDPRN 10000002  RCVPRN S4PCLNT100  CREDAT 20261130 073400
     E1EDK14 sales area CPUS/20/PU  E1EDK02 PO HFS-PO-8232  E1EDKA1 AG 10000002
     E1EDP01 000010 20 PCE  E1EDP19 001 HFS-SK-210
     2026-11-30 08:05  64     Ready; process code ORDE, trigger immediately
     2026-11-30 08:06  51     No customer-material record for HFS-SK-210 (customer 10000002)
   ```

   The diary shows both steps: ready, then not posted. Hallam used a new part number.
2. Customer service confirms `HFS-SK-210` is Hallam's new name for seal kit `CP-SK200`. Add the customer-material record (in S/4HANA this is master data in sales, owned by customer service, not an IDoc setting):

   ```bash
   python unit26/idoc_lab.py --map 10000002 HFS-SK-210 CP-SK200
   ```

   ```text
   Customer-material record: 10000002 HFS-SK-210 -> CP-SK200
   ```

3. Process the same IDoc again:

   ```bash
   python unit26/idoc_lab.py --reprocess 500003
   ```

   ```text
   500003 in  ORDERS KU 10000002  53     Sales order 1000703 saved (1,900.00 USD), saved with a credit block (a business hold, not an IDoc error)
   ```

Run `--show 500003` again: the history now has four lines. Nothing was deleted.

#### Step 6: Close what must not be processed

Two failures should not be reprocessed at all.

- `500004` uses unit `BX` (a box), which Calder and Hallam never agreed. Reprocessing would fail the same way every time; the partner must send the order again in pieces.
- `500006` is Hallam's order `HFS-PO-8230` a second time, under a new IDoc number: the EDI provider resent the interchange. Posting it would ship 60 seal kits twice.

Close both with a reason (the quotes keep the reason together; they work the same in PowerShell):

```bash
python unit26/idoc_lab.py --close 500004 "Unit BX not agreed; Hallam asked to resend in pieces"
python unit26/idoc_lab.py --close 500006 "Duplicate of IDoc 500001 (provider resent the interchange)"
```

```text
500004 in  ORDERS KU 10000002  closed No further processing: Unit BX not agreed; Hallam asked to resend in pieces
500006 in  ORDERS KU 10000002  closed No further processing: Duplicate of IDoc 500001 (provider resent the interchange)
```

> **Note** Keep a failed IDoc's history in a real system too: end it with a final status and a recorded reason, instead of deleting it or leaving it in `51`. The lab's `closed` is a course label for that, not an SAP status number.

#### Step 7: Set up a missing partner profile

1. Quillan Pump Supply (`10000032`) signed up last week; nobody created its partner profile. Look at its IDoc:

   ```bash
   python unit26/idoc_lab.py --show 500005
   ```

   ```text
   IDoc 0000000000500005  inbound  ORDERS / ORDERS05  partner KU 10000032
     Control record: SNDPOR EDIPROV  SNDPRT KU  SNDPRN 10000032  RCVPRN S4PCLNT100  CREDAT 20261130 073800
     E1EDK14 sales area CPUS/20/PU  E1EDK02 PO QPS-PO-1104  E1EDKA1 AG 10000032
     E1EDP01 000010 10 PCE  E1EDP19 002 CP-SK200
     2026-11-30 08:09  56     No inbound partner profile for KU 10000032 ORDERS
   ```

   Quillan uses Calder's own material numbers (qualifier `002`), so no mapping is needed. The IDoc never reached the application.
2. Create the inbound profile with background processing, then reprocess:

   ```bash
   python unit26/idoc_lab.py --profile 10000032 job
   python unit26/idoc_lab.py --reprocess 500005
   ```

   ```text
   Inbound partner profile: KU 10000032 ORDERS, process code ORDE, mode job
   500005 in  ORDERS KU 10000032  53     Sales order 1000704 saved (950.00 USD)
   ```

   Reprocessing by hand runs at once, whatever the profile's mode. Future IDocs from Quillan will wait for the job.

#### Step 8: Run the background job

```bash
python unit26/idoc_lab.py --job
```

```text
500007 in  ORDERS KU 10000033  53     Sales order 1000705 saved (3,800.00 USD)
Background job: 1 IDoc(s) passed to the application.
```

Venmoor's order was never in trouble, but if the job had not been scheduled, it would have stayed in `64` forever and only the 15-minute alert would have caught it.

#### Step 9: Send order responses through a port that fails

1. Simulate the EDI provider's endpoint being down, then create order responses (`ORDRSP`) for every posted order:

   ```bash
   python unit26/idoc_lab.py --port EDIPROV down
   python unit26/idoc_lab.py --confirm
   ```

   ```text
   Port EDIPROV is down.
   900001 out ORDRSP KU 10000002  02     Port EDIPROV: the EDI provider not reachable
   900002 out ORDRSP KU 10000002  02     Port EDIPROV: the EDI provider not reachable
   900003 out ORDRSP KU 10000002  02     Port EDIPROV: the EDI provider not reachable
   Order 1000704: no outbound profile for ORDRSP to 10000032, no IDoc created
   900004 out ORDRSP KU 10000033  30     Order response for 1000705 (VIS-PO-0412); output mode: collect
   4 order response IDoc(s) created.
   ```

   Hallam's profile passes IDocs on at once, so all three hit the dead port (`02`). Venmoor's profile collects, so its IDoc waits in `30`. Quillan got no response at all: its outbound line is missing. Nothing alerts on that; you only see it here.
2. Bring the port back, resend the three, and run the send job for the collected one:

   ```bash
   python unit26/idoc_lab.py --port EDIPROV up
   python unit26/idoc_lab.py --reprocess 900001 900002 900003
   python unit26/idoc_lab.py --send
   ```

   ```text
   Port EDIPROV is up.
   900001 out ORDRSP KU 10000002  03     Passed to port EDIPROV (the EDI provider)
   900002 out ORDRSP KU 10000002  03     Passed to port EDIPROV (the EDI provider)
   900003 out ORDRSP KU 10000002  03     Passed to port EDIPROV (the EDI provider)
   900004 out ORDRSP KU 10000033  03     Passed to port EDIPROV (the EDI provider)
   Send job: 1 IDoc(s) handed to their port.
   ```

3. Check the whole picture:

   ```bash
   python unit26/idoc_lab.py --monitor
   python unit26/idoc_lab.py --alerts
   ```

   The monitor ends with `By status: 03 x4, 53 x5, closed x2` and the alerts with `Nothing needs a person.`

`03` means the response left Calder's system. Whether Hallam received it is a question for the EDI provider's acknowledgments, covered for EDI in the B2B topic.

#### Step 10: Save your work

```bash
git add unit26/idoc_lab.py unit26/idoc
git commit -m "Unit 26: IDoc lab"
```

#### How the code works

| Part | What it does |
| --- | --- |
| `PROFILES`, `PORTS`, `CUSTOMERS`, `CUSTOMER_MATERIAL` | The course's partner profiles (inbound by partner and message type, outbound with port and output mode), the port, the sold-to parties and the mapping of partner part numbers |
| `idoc_xml()` | Writes an inbound `ORDERS05` IDoc in IDoc-XML: `EDI_DC40` and the order segments `E1EDK01`, `E1EDK14`, `E1EDK02`, `E1EDKA1`, `E1EDP01` with `E1EDP19` |
| `read_idoc()` | Reads the control record, the sales area from the `E1EDK14` qualifiers, the PO from `E1EDK02` qualifier `001`, the sold-to from `E1EDKA1` `AG`, and the items |
| `process()` | The inbound path: partner profile check (`56`), ready (`64`), then posting now or by the job |
| `post()` | The application step behind process code `ORDE`: sold-to, sales area, duplicate customer PO, material mapping, unit; creates the order or returns `51` with a reason |
| `set_status()`, `tick()` | Appends a status record with the lab clock's time; history is never rewritten |
| `job()`, `send()` | Stand-ins for the scheduled jobs that pass `64` to the application and send `30` to the port |
| `reprocess()`, `close()` | Process a failed IDoc again after a fix, or end it with a reason |
| `confirm()`, `dispatch()` | Create `ORDRSP` IDocs from the outbound profiles and pass them to the port (`03`) or fail (`02`) |
| `alerts()` | The course alert rules; exit code `2` when something needs a person |

#### 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 part of it is missing | The lab needs built-in modules only; paste the whole script again |
| `AttributeError: ... has no attribute 'indent'` | Python older than 3.9 | Use the Python version from Set up your computer |
| `unit26/idoc/ already exists` | `--init` doesn't overwrite your work | Delete the `unit26/idoc` folder only if you want to start again |
| `state.json not found. Run --init first` | Wrong folder, or no `--init` yet | Run from `orchestrate-course`; run `--init` |
| `IDoc ... not found` | A typo in the number | Use the last six digits shown by `--monitor`, such as `500003` |
| Your order numbers or times differ from the samples | Commands ran in another order, or twice | Delete `unit26/idoc`, run `--init`, then follow the steps in order |
| `JSONDecodeError` after editing `state.json` by hand | A comma or quote is missing | Use the lab's options instead of editing the file; or start again |
| A company proxy blocks something | Not used here | The lab needs no network or key |

### The SAP way

What SAP provides for IDocs, as of 30 November 2026:

- **In SAP S/4HANA (on-premise and Private Edition) and SAP ECC**, the IDoc interface is standard: partner profiles in `WE20`, ports in `WE21` over RFC destinations from `SM59`, inbound process codes in `WE42`, the test tool `WE19` ([SAP Developers](https://developers.sap.com/tutorials/aif-idoc-monitoring-interface-create.html), [SAP Learning](https://learning.sap.com/courses/mastering-standard-interface-technologies-with-sap-application-interface-framework/processing-and-monitoring-inbound-idocs-with-aif)), the ALE distribution model in `BD64` with generated partner profiles from `BD82` ([SAP Library](https://help.sap.com/saphelp_nwce10/helpdata/en/99/e7b23b94c6e54be10000000a11402f/content.htm)), and reprocessing in `BD87` ([SAP KBA 3614190](https://userapps.support.sap.com/sap/support/knowledge/en/3614190)). Status numbers and process codes are delivered by SAP; texts and the details of your partner profiles are your configuration.
- **SAP Application Interface Framework (AIF)** puts IDocs into business-user monitoring and error handling. SAP's training lists five scenarios for inbound IDocs, from monitoring existing IDocs from their control and status records without touching processing, to processing the IDoc in an AIF action with its own checks, mappings and alerts. With the monitoring-only enabler, only IDocs created after it was set up are shown ([SAP Learning](https://learning.sap.com/courses/mastering-standard-interface-technologies-with-sap-application-interface-framework/processing-and-monitoring-inbound-idocs-with-aif)). SAP's tutorial for this needs SAP S/4HANA 1709 or later with AIF 4.0 ([SAP Developers](https://developers.sap.com/tutorials/aif-idoc-monitoring-interface-create.html)). Check your licence for AIF with SAP.
- **SAP Cloud ALM integration monitoring** collects IDocs from SAP S/4HANA and SAP Business Suite systems, raises events for failed IDocs (single or grouped) and for long processing times, and filters by message type, status, status group, basic type, direction, port and partner. SAP lists SAP Note 3259248 as a prerequisite for the SAP Passport correlation ([SAP Support Portal](https://support.sap.com/ja/alm/sap-cloud-alm/operations/expert-portal/integration-monitoring/calm-s4-onprem.html)).
- **SAP Integration Suite** sends and receives IDocs with the IDoc adapter over HTTP: sender with *Exactly Once* or *Exactly Once In Order*, receiver with a choice of content type and authentication including principal propagation through the Cloud Connector ([sender](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Development/configure-the-idoc-sender-adapter-bf769d6.md), [receiver](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Development/configure-the-idoc-receiver-adapter-018aa88.md)). For migrations from PI/PO, SAP's guide offers generic IDoc inbound and outbound flows in the integration packages *Cloud Integration Pipeline - Generic Inbound* and *Generic Outbound*, with a built-in duplicate check and bulk splitting ([SAP documentation](https://github.com/SAP-docs/btp-process-orchestration-migration-guide/blob/main/docs/70-interface-migration/generic-inbound-and-outbound-5e2fdf8.md)). The migration itself is covered in [Migrating from Process Integration and Process Orchestration](https://erpfde.com/topics/migrating-from-pi-po/).
- **SAP S/4HANA Cloud Public Edition** offers IDocs only through specific communication scenarios. SAP's knowledge base shows scenario `SAP_COM_0277`, set up in *Communication Arrangements*, and that changing its receiver adds a second arrangement, so IDocs go to both receivers until the old one is deleted ([SAP KBA 3766365](https://userapps.support.sap.com/sap/support/knowledge/en/3766365)). Look up the IDocs SAP publishes for your product and release on the SAP Business Accelerator Hub before designing an interface on them.

### Build vs. SAP

| Need | SAP | Hand-built | Use which |
| --- | --- | --- | --- |
| Posting an inbound order | Standard process code (`ORDE` for `ORDERS`) | A custom function module | SAP's: custom posting code is custom code in the core that you retest at every upgrade |
| A field SAP's segments lack | An extension with code to fill or read it | A text segment or qualifier the partner and you agree | Try qualifiers and text first; extend only with a named owner and a test |
| Duplicates | `SapMessageId` with *Application/x-sap.idoc*; the pipeline's partner-plus-IDoc check | A business-key check (sold-to plus customer PO) | Both: SAP for technical resends, your check for business resends |
| Monitoring for IT | IDoc monitor, Cloud ALM alerts | A script over IDoc statuses | SAP's; a script like the lab's only for a demo |
| Monitoring for business users | AIF | Emails from a custom job | AIF where licensed; otherwise Cloud ALM alerts routed to the business owner |
| A new IDoc between SAP and the cloud | IDoc adapter in Integration Suite | Direct RFC from an app | The adapter: Cloud Integration needs IDoc over HTTP anyway |
| A new interface where SAP offers an API | Released API or event | A new IDoc | The API: IDocs are for where they already work or where SAP recommends them |

### Architecture view

**Where it sits.** Calder has two IDoc interfaces in its landscape today, both in the [integration platform topic](https://erpfde.com/topics/integration-platform-and-clean-core/)'s register. `I10` brings distributor orders from an EDI provider into `CP10`'s S/4HANA system `S4P` as `ORDERS` IDocs, one `KU` partner profile per distributor. `I11` exchanges intercompany orders and invoices between `CP10` and `CP20`'s ECC system as IDoc-based EDI, and retires at the July 2027 rollout. Target design ADR-001 puts Trading Partner Management in front of `I10`, as the [B2B and EDI topic](https://erpfde.com/topics/b2b-and-edi-integration/) describes, so the IDoc becomes the last hop from Integration Suite into S/4HANA.

```mermaid
flowchart LR
  D[Distributors] -->|EDI| TPM[Integration Suite<br/>TPM and I10 flow]
  TPM -->|IDoc-XML over HTTPS<br/>Cloud Connector SCC-RK-P| S4[S4P: IDoc layer<br/>ORDERS, ORDRSP]
  S4 -->|ORDRSP| TPM
  S4 <-->|I11 IDoc EDI<br/>until July 2027| ECC[ECC CP20]
  S4 -.IDoc statuses.-> ALM[SAP Cloud ALM]
```

**Non-functional requirements.**

| Requirement | Target for `I10` | What breaks if missed |
| --- | --- | --- |
| Time to a sales order | Within 1 hour of receipt (the `I10` spec) | Orders miss picking; the distributor calls |
| Time to notice a failure | `51` and `56` alert at once; `64` and `30` after 15 minutes (course rules) | A failed order is found by the customer |
| Duplicates | Exactly once per message; one order per sold-to and customer PO | Double shipments, credit notes, lost trust |
| Volume | Peak 30 orders an hour, volume test 60 (the `I10` spec) | Jobs fall behind; IDocs pile up in `64` |
| Retention | IDocs and their statuses kept as long as disputes run, then archived or deleted under a set rule | Tables grow without end; personal data kept too long |
| Upgrade effort | No custom posting code; extensions only with an owner | Every upgrade retests your own segments and code |

**Integration and identity.** The control record identifies the partner, but nothing in it proves who sent the IDoc. Trust comes from the channel: the Cloud Connector pair `SCC-RK-P` and the technical user the IDoc adapter logs on with, limited to IDoc inbound processing for `ORDERS` in `CPUS`, as the [BTP security topic](https://erpfde.com/topics/btp-security-model/) describes for technical users. Because one technical user posts every distributor's orders, the sold-to in `E1EDKA1` must be checked against the partner the TPM agreement determined, not trusted from the payload. Changes to orders made by people go through S/4HANA's own apps, never through a test IDoc.

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

- **Context.** After ADR-001, every distributor order reaches S/4HANA through Integration Suite, not the EDI provider. Today `I10` has one `KU` partner profile per distributor, maintained by hand; Calder has 12 distributors on EDI and has signed five more.
- **Options.** A: keep a `KU` partner profile per distributor, with Integration Suite setting `SNDPRT` and `SNDPRN` per partner. B: one logical system for Integration Suite (`LS`), with the distributor carried only as the sold-to in `E1EDKA1` and checked against the TPM agreement. C: replace the IDoc with a released sales order API.
- **Decision.** B, with C reviewed when a distributor needs a synchronous answer to its order.
- **Consequences.** One inbound profile instead of seventeen, and partner onboarding stays in Trading Partner Management. Status `56` no longer catches an unknown distributor, so the sold-to check in the application step and the TPM agreement become the controls; test both. Monitoring by partner moves from the IDoc's partner fields to the sold-to, which isn't among the IDoc filters SAP lists for Cloud ALM, so the integration team adds the sold-to to its alert text.

**What a design review will ask.**

1. For each IDoc interface, who is the business owner of its errors, and how do they hear about them?
2. How do you prevent a second sales order when the provider or the partner resends?
3. What proves the sender is who the control record says?
4. Which extensions and custom segments exist, and what code fills or reads them?
5. What is the retention rule for IDocs, and do they carry personal data?

### Production concerns

- **Security and SAP authorizations.** Separate who changes partner profiles and ports (the integration team, through transports) from who reprocesses (integration support) and who fixes master data (the business owner). The technical user for inbound IDocs needs no dialog access. The SAP-samples ECC guide lists, for its BAPI route, a technical user with authorizations for the sales order authorization objects and `S_RFC` on the function groups it calls ([SAP-samples](https://github.com/SAP-samples/sap-btp-ai-best-practices/blob/main/use-cases/purchase-order-intake-agent/docs/ecc-integration.md)); design the IDoc user just as narrowly, and test it with an IDoc for another sales area.
- **Personal data.** Partner segments such as `E1EDKA1` carry names, addresses and phone numbers, as SAP's sample payload shows. Restrict who can display IDoc content, and set a retention rule with data protection.
- **Evaluation and tests.** Keep a test set of IDocs per interface: one that posts, one for each known error, one duplicate. Run it after every change to partner profiles, customer-material records, units or extensions. The `TEST` flag in the control record lets SAP's pipeline route test IDocs to a mock receiver.
- **Operations.** Schedule and monitor the jobs that process `64` and send `30`; a job that stops is invisible until something waits. Route alerts by error to the owner, as Cloud ALM's event actions allow. Decide who may close an IDoc and require a reason.
- **Cost.** IDocs cost little to run and a lot to neglect: each unposted order costs a person's time to find, fix and tell the partner. In Integration Suite, check with SAP how your contract counts IDoc messages, including bulk IDocs that a flow splits into single ones.
- **Clean core.** Standard message types, basic types and process codes are fine. Custom function modules that post IDocs, and extensions with code behind them, are custom code in the core: each needs an owner, a test and a reason, and the [extension patterns topic](https://erpfde.com/topics/btp-extension-patterns/) is where to weigh the alternatives.

> **Note** **ECC differences.** ECC has no released APIs in the S/4HANA sense, so IDocs and BAPIs are often its only standard interfaces, and `CP20`'s `I11` runs on IDocs until 2027. The IDoc interface is the same technology in both, and ALE links SAP systems of different releases, as SAP's training notes ([SAP Learning](https://learning.sap.com/courses/technical-implementation-and-operation-i-of-sap-s-4hana-and-sap-business-suite/explaining-cross-system-business-processes)), so a team's IDoc skills carry over. What changes in S/4HANA is that released APIs and events sit beside the IDocs, and Public Edition offers IDocs only through specific communication scenarios.

### Where AI fits

- **No delivered AI in the IDoc layer.** None of the SAP sources read for this topic describes an AI capability for IDoc status handling. Monitoring and alerting come from the IDoc monitor, AIF and Cloud ALM, which are rule-based.
- **An agent as a triage assistant.** A useful agent reads failed IDocs (`51`, `56`), groups them by cause, and drafts the fix for the owner: "add customer-material record `HFS-SK-210` to `CP-SK200` for Hallam, then reprocess 500003". It proposes; a person fixes master data and reprocesses. It never edits an IDoc, closes it or reprocesses on its own. The [AI in SAP Integration Suite topic](https://erpfde.com/topics/ai-in-sap-integration-suite/) covers the design-time AI features of the platform.
- **IDoc text is partner text.** Text segments and partner names in an IDoc were written outside Calder. An agent that reads them must treat them as data, never as instructions, as the [prompt injection topic](https://erpfde.com/topics/prompt-injection-and-tool-poisoning/) shows.
- **An agent as one more source of orders.** An AI order intake that reads emails can post through an IDoc, as SAP's sample shows, or through an API. If it uses the IDoc route, it inherits everything above: the duplicate check, the status handling, and a named owner for its errors.

### Pitfalls

- **Resending instead of reprocessing.** The IDoc is already there; a resend makes a second one, and a second order if no business duplicate check exists.
- **Editing an IDoc's data to make it post.** The master data gap stays, and the next order fails the same way.
- **Reading `03` as "received".** It means the data left your system. Ask the partner or its provider for an acknowledgment.
- **A job nobody scheduled.** IDocs wait in `64` or `30` without an error. Alert on age, not only on error statuses.
- **Treating credit blocks as interface errors.** The order posted; the credit team owns the block. Mixing the two buries real errors.
- **An outbound line forgotten.** Quillan's order posted, but nobody told Quillan. Check outbound profiles when you onboard a partner, not only inbound.
- **Extensions without an owner.** A custom segment outlives the project that added it, and its code is retested at every upgrade.
- **Syntax check switched off to get through a test.** It stays off in production, and structure errors reach the application.
- **Partner profiles created by hand in production.** Create and test them in development and transport them, so every system has the same settings.

### Exercise

Tessaly Flow Parts (`10000034`) sends its first EDI order. It uses its own part numbers: `TFP-4410` is Calder's seal kit `CP-SK200`. Onboard it so the order posts and Tessaly gets an order response.

1. Run `python unit26/idoc_lab.py --exercise`. It adds IDoc `500008` to the inbox.
2. Run `python unit26/idoc_lab.py --run`. Read the status and say which object is missing.
3. Create an inbound profile that processes Tessaly's orders immediately, with `--profile`.
4. Run `--reprocess 500008`. Read the new error and fix it with `--map`, as you did for Hallam.
5. Reprocess again until the IDoc is in `53` and note the sales order number.
6. Run `--confirm`. You'll see Tessaly and Quillan get no order response. In `unit26/notes.md`, write two lines: the outbound profile both partners need (message type, basic type, port, output mode), and who at Calder owns adding it.

**Done when** `python unit26/idoc_lab.py --monitor` shows `500008` in `53` with sales order `1000706`, `--alerts` prints `Nothing needs a person.`, and `notes.md` holds your two lines. The [interface monitoring and error handling topic](https://erpfde.com/topics/interface-monitoring-and-error-handling/) builds its alert routes on these statuses and owners.

> **Note** The partner, order and numbers are synthetic course data.

### Check yourself

1. An inbound order IDoc shows status 56. Where do you look first?
   - A. The partner profile for this partner and message type
   - B. The customer-material records for the order's items
   - C. The background job that processes IDocs waiting in 64
   - D. The credit limit of the sold-to party in the order

   Answer: A. Status 56 means the IDoc was added with errors before reaching the application, typically because no partner profile matches the sender and message type. Customer-material records and credit limits only matter once the application step runs.

2. Why does the lab read the sales organization from three E1EDK14 segments instead of one field?
   - A. Because ORDERS05 stores each organizational unit in its own extension
   - B. Because the EDI provider splits long values over several segments
   - C. Because E1EDK14 means a different unit for each qualifier value
   - D. Because SAP keeps old and new values of the sales area side by side

   Answer: C. E1EDK14 is one segment type whose meaning depends on QUALF: 008 sales organization, 007 distribution channel, 006 division. Qualifiers are why raw IDocs need their segment documentation to be read.

3. The EDI provider resends Hallam's order HFS-PO-8230 as a new IDoc after a timeout. What stops a second sales order?
   - A. The IDoc number, because SAP refuses an IDoc number it has seen
   - B. SapMessageId, because the adapter reuses it across all messages
   - C. The syntax check, because the partner profile has it switched on
   - D. A business check on sold-to plus customer PO in the posting step

   Answer: D. A resend as a new message gets a new IDoc number and a new message ID, so transport-level duplicate checks don't see it. Only a business key check, like the lab's sold-to plus customer PO, catches it.

4. An IDoc failed with "No customer-material record for HFS-SK-210". What is the right sequence?
   - A. Ask Hallam to resend with Calder's material number, then close the old IDoc
   - B. Have customer service add the record, then reprocess the same IDoc
   - C. Copy the IDoc in the test tool with the corrected number and post the copy
   - D. Edit the part number inside the IDoc, then reprocess it

   Answer: B. The cause is missing master data, owned by customer service; fixing it there also fixes the next order. The same IDoc is then reprocessed, so no copy or resend creates a second order and the history stays complete.

5. Venmoor's order sits in status 64 for an hour without an error. What is the likely cause?
   - A. The order is credit-blocked and waits for the credit team
   - B. The port to the EDI provider is down
   - C. Its profile leaves processing to a job that isn't running
   - D. The IDoc failed the syntax check and needs a correction

   Answer: C. Status 64 means ready to be passed to the application. With a profile set to background processing, the IDoc waits until the job runs; if the job is not scheduled, it waits with no error, which is why the lab alerts on age.

6. Calder's ORDRSP IDocs to Hallam went to status 02 while the provider was down. After it comes back, what do you do?
   - A. Create the order responses again from the sales orders
   - B. Resend the same IDocs, then confirm they reach 03
   - C. Close them and ask Hallam to call customer service
   - D. Wait: the send job picks up IDocs in 02 by itself

   Answer: B. The IDocs exist and failed at the port, so they are resent, not recreated, which would send duplicates once both copies go out. In the lab only IDocs in 30 are picked up by the send job; 02 needs an explicit resend.

7. Why does Cloud Integration's IDoc receiver adapter offer two content types?
   - A. Application/x-sap.idoc is for ECC and Text/XML for S/4HANA
   - B. Text/XML is faster but needs the Cloud Connector, the other doesn't
   - C. Application/x-sap.idoc gives exactly-once; Text/XML allows bulk IDocs
   - D. Application/x-sap.idoc is for outbound and Text/XML for inbound

   Answer: C. SAP's documentation says Application/x-sap.idoc sends one IDoc per request and supports exactly-once when SapMessageId stays the same on retry. Text/XML carries several IDocs per request but doesn't support exactly-once.

8. After ADR-001 Calder moves to one logical system for Integration Suite instead of a KU profile per distributor. What control must the team add?
   - A. A syntax check on the outbound ORDRSP profile
   - B. A separate port for each distributor in WE21
   - C. A check of the sold-to against the partner's TPM agreement
   - D. A KU profile for each new distributor as a fallback

   Answer: C. With one LS profile, status 56 no longer stops an unknown distributor, and one technical user posts for everyone. The sold-to in E1EDKA1 must be checked against the partner the TPM agreement determined, or any distributor could order on another's account.

9. An agent reads failed IDocs and finds the fix for 500003. What may it do in Calder's design?
   - A. Add the customer-material record and reprocess the IDoc
   - B. Draft the fix for the owner; a person changes data and reprocesses
   - C. Reprocess the IDoc, since reprocessing changes no master data
   - D. Close the IDoc with its own reason so the alert stops

   Answer: B. The agent proposes; master data changes and reprocessing stay with people who hold those authorizations. Reprocessing creates a sales order, so it is a change to SAP data, and closing an IDoc can lose an order.

## Sources

- [Posting alternative: IDoc ORDERS05 (SAP-samples, sap-btp-ai-best-practices, ECC integration guide, read 2026-11-30)](https://github.com/SAP-samples/sap-btp-ai-best-practices/blob/main/use-cases/purchase-order-intake-agent/docs/ecc-integration.md): message type ORDERS, basic type ORDERS05, inbound process code ORDE, partner profile of type KU per customer or a generic logical system with Cloud Integration's IDoc adapter; segments E1EDK01, E1EDK14 (qualifiers 008, 006, 007, 012), E1EDK03, E1EDK02 (QUALF 001, BELNR), E1EDKA1 (PARVW AG, WE), E1EDP01, E1EDP19 (QUALF 002, 001, IDTNR), E1EDP20; IDoc route for existing EDI order intake, BAPI route for a synchronous answer
- [Order to Cash B2B Scenario, UN/EDIFACT, IDoc sample payloads (SAP, apibusinesshub-integration-recipes, read 2026-11-30)](https://github.com/SAP/apibusinesshub-integration-recipes/tree/master/Recipes/for/b2bintegrationfactoryordertocashscenario/IDoc/UNEDIFACT): a full ORDERS05 IDoc in IDoc-XML; EDI_DC40 fields TABNAM, MANDT, DOCNUM, STATUS, IDOCTYP, CIMTYP, MESTYP (ORDRSP on basic type ORDERS05), SNDPOR, SNDPRT, SNDPRN, RCVPOR, RCVPRT, RCVPRN, CREDAT, CRETIM; segments nested under E1EDP01
- [Explaining the Integration Technology Based on BAPIs and IDocs, Basics (SAP Learning, read 2026-11-30)](https://learning.sap.com/courses/developing-integration-scenarios-using-idoc-rfc-adapter-of-sap-process-orchestration/explaining-the-integration-technology-based-on-bapis-and-idocs-basics_db458c59-a70f-480d-b139-65065be1b9e9): IDoc as SAP's standard EDI format; one basic type can carry several message types (ORDERS01 for ORDERS and ORDRSP); control, data and status records in three tables; control record holds sender, recipient, message and the last status; status records kept apart from the IDoc; syntax check switched in the partner profile, separately for inbound and outbound
- [Create a Simple IDoc Interface (SAP Developers tutorial, read 2026-11-30)](https://developers.sap.com/tutorials/aif-idoc-monitoring-interface-create.html): SM59 RFC destination of type 3; WE21 transactional RFC port; WE20 partner profile of type LS with an inbound message type, process code and processing by function module "Trigger immediately"; WE19 test tool; SAP S/4HANA 1709 or later with AIF 4.0
- [Generating Partner Profiles (SAP Library, SAP NetWeaver, read 2026-11-30)](https://help.sap.com/saphelp_nwce10/helpdata/en/99/e7b23b94c6e54be10000000a11402f/content.htm): partner profiles define the conditions for exchanging data with a partner over the IDoc interface; SALE, BD64 distribution model, BD82 generate partner profile; immediate output processes every IDoc at once with package size 1; package size sets how many IDocs go per RFC call when a background program sends
- [Configure the IDoc Sender Adapter (SAP Integration Suite documentation, SAP-docs on GitHub, read 2026-11-30)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Development/configure-the-idoc-sender-adapter-bf769d6.md): Exactly Once and Exactly Once In Order, depending on the sending system; headers from control field ARCKEY; SAP Note 3519275 for sequence; headers SapIDocType, SapIDocTransferId, SapIDocDbId; composite messages of one message type
- [Configure the IDoc Receiver Adapter (SAP Integration Suite documentation, SAP-docs on GitHub, read 2026-11-30)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ci/Development/configure-the-idoc-receiver-adapter-018aa88.md): content type Application/x-sap.idoc (one IDoc per request, sequencing, Exactly-Once; reuses SapMessageId on retry) or Text/XML (several IDocs, no Exactly-Once); proxy type On-Premise through the Cloud Connector; Basic, Client Certificate, None or Principal Propagation; default timeout 60,000 ms
- [Generic Inbound and Outbound (SAP Process Orchestration migration guide, SAP-docs on GitHub, read 2026-11-30)](https://github.com/SAP-docs/btp-process-orchestration-migration-guide/blob/main/docs/70-interface-migration/generic-inbound-and-outbound-5e2fdf8.md): generic IDoc inbound and outbound flows of the Cloud Integration pipeline; headers from control fields MESTYP, IDOCTYP, CIMTYP and TEST; duplicate check on sender partner plus IDoc number; bulk IDocs split unless KeepBulk
- [SAP Cloud ALM integration monitoring for SAP S/4HANA and SAP Business Suite (SAP Support Portal, read 2026-11-30)](https://support.sap.com/ja/alm/sap-cloud-alm/operations/expert-portal/integration-monitoring/calm-s4-onprem.html): IDoc category; events Erroneous Message(IDOC) Detected (Single, Grouped) and high processing time; filters on message type, status, status group, basic type, direction, ports and partners; SAP Note 3259248; WE05 to find segment and field names for payload search
- [SAP KBA 3614190: Manual resolution of outbound IDoc dispatch issues using BD87 (SAP Support, preview, read 2026-11-30)](https://userapps.support.sap.com/sap/support/knowledge/en/3614190): status 30 "IDoc ready for dispatch (ALE service)"; IDoc stays in 30 after a resend with RBDAGAIN and is not sent; BD87
