# Extension patterns: a reference for in-app and side-by-side

> Pick the extension pattern for each requirement, from a custom field to an event consumer on SAP BTP, and know its editions, level and five-year cost.

- Course: Orchestrate, Unit 21 · SAP BTP as a platform
- Page: https://erpfde.com/topics/btp-extension-patterns/
- Updated: 2026-11-27
- Reading time: Foundational 8 min, Deep 36 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

Once a requirement has earned an extension, the next question is **which kind**. SAP offers many: a custom field, a piece of logic in a released hook, a new table with its own app, an ABAP Cloud program, an app on SAP BTP, a listener that reacts to events. Each is an **extension pattern**: a known shape with its own tools, editions, upgrade risk and running cost.

This topic is the catalogue. For each pattern it says when to use it, who builds it, which SAP S/4HANA editions allow it, how it behaves at upgrade, and what it costs over five years. It also gives the order of questions that picks one.

The deciding facts are few. Who uses the result: people in SAP, or outsiders? Must it act **inside** the SAP save, or after it? Is there a released API, hook or event for it? Answer those three and most requests sort themselves.

### Why it matters to the business

Calder Pumpworks (a fictional company used throughout this course) finished its fit-to-standard after Augsburg's `CP20` moved into `CP10`'s S/4HANA system. Eight requests survived as extensions or near-extensions. A partner proposed a design for them. Two of its choices would have cost money and three would have broken rules:

- A **validation** on engineered pump orders was placed in a BTP app. A BTP app can't stop an SAP save, so the check would run after the bad order was already saved.
- The **distributor order-status app** was placed inside S/4HANA. Hallam's staff would need SAP users in Calder's core system.
- A **notice to Brennock** when an order date moves was built as a BTP app that asks SAP every five minutes. SAP already publishes an event for sales order changes.

The pattern is a cost decision with a long tail. In this topic's course model, a custom field costs about 3,150 USD over five years and a side-by-side app about 24,750 USD; a program that writes into SAP tables costs about 39,600 USD, most of it in retesting at every upgrade. Those are course inputs, not SAP figures, but the ratio is the lesson: the pattern you choose sets the upgrade bill for years.

> **Note** **For functional consultants.** Key user patterns are your work: custom fields, custom logic, custom business objects, forms and queries are built in SAP Fiori apps, not in code. Expect three changes. Each one needs a test case that runs again at every upgrade. Each one moves by transport, like configuration. And a custom field is invisible to an API or a form until someone enables it there, so ask where the field must show up before it is created.

### How SAP does it

As read on SAP Learning and sap.com on 27 November 2026.

- **Three places to extend.** SAP's training names key user (in-app), developer and side-by-side extensibility ([SAP Learning](https://learning.sap.com/courses/building-transactional-apps-with-the-abap-restful-application-programming-model/exploring-extensibility-options)). Key user and developer extensions are **on-stack**: they run inside S/4HANA. Side-by-side extensions run on **SAP BTP** and reach S/4HANA through remote APIs ([SAP Learning](https://learning.sap.com/courses/practicing-clean-core-extensibility-for-sap-s-4hana-cloud/explaining-side-by-side-extensibility_a01bb1ac-1acb-434d-8458-7a36cf2bcb3b)).
- **Key user tools.** Web-based SAP Fiori apps available in all SAP S/4HANA deployment options: UI adaptation, Custom Fields, Custom Business Logic, Custom Business Objects, Custom CDS Views, Custom Analytical Queries, KPIs and Custom Forms ([SAP Learning](https://learning.sap.com/courses/practicing-clean-core-extensibility-for-sap-s-4hana-cloud/explaining-key-user-extensibility_c7f6cbcb-ed54-4f1d-8e76-4a6e311e3cfa)).
- **Developer tools.** ABAP Cloud in ABAP development tools for Eclipse, on released interfaces only. SAP's course cites over 125 business object interfaces and over 800 BAdIs (released hooks) open to customers ([SAP Learning](https://learning.sap.com/courses/practicing-clean-core-extensibility-for-sap-s-4hana-cloud/explaining-developer-extensibility_f2683861-d69e-4a59-9e3e-01e3cc20fb0f)).
- **Coupling decides on-stack versus side-by-side.** SAP's architect training puts on-stack extensions on close coupling and side-by-side on looser coupling, and says extensions must never duplicate standard functionality ([SAP Learning](https://learning.sap.com/courses/sap-enterprise-architects/exploring-how-to-make-extensions-clean-core-compliant)).
- **Levels.** SAP rates every extension from level A (released APIs) to level D (not clean). An extension takes the level of the lowest technique it uses ([SAP Learning](https://learning.sap.com/courses/sap-enterprise-architects/exploring-how-to-make-extensions-clean-core-compliant-1)). How levels are measured is in [Fit-to-standard and extension choices](https://erpfde.com/topics/fit-to-standard-and-extension-choices/).
- **Events.** SAP's Architecture Center describes BTP extension apps that consume events from SAP cloud applications "while adhering to the clean core concept", with SAP's business events listed on the SAP Business Accelerator Hub ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/196eba), last updated 10 October 2025).
- **A method for the choice.** The SAP Application Extension Methodology breaks a use case into extension tasks (a UI change, an API call, an event to consume, new persistence) and maps each to a building block on-stack or side-by-side ([SAP Learning](https://learning.sap.com/courses/becoming-an-sap-btp-solution-architect/adopting-the-sap-application-extension-methodology)).

### The catalogue on one page

Pattern IDs are course labels. Editions: PE is SAP S/4HANA Cloud Public Edition, PCE is Private Edition, OP is on-premise. Five-year cost uses the course model in the deep layer.

| Pattern | Use it when | Who builds | Editions | Level | 5-year cost (course) |
| --- | --- | --- | --- | --- | ---: |
| KU-UI UI adaptation | Hide, rename or move fields on an SAP screen | Key user | PE, PCE, OP | A | 2,700 |
| KU-FLD Custom field | A field SAP doesn't have, on screens, forms, reports or APIs | Key user | PE, PCE, OP | A | 3,150 |
| KU-LOG Custom logic | A check or default inside the save, where a released BAdI exists | Key user | PE, PCE, OP | A | 4,050 |
| KU-CBO Custom business object | Your own small table with an app and an API | Key user | PE, PCE, OP | A | 4,950 |
| KU-RPT, KU-OUT | A query, a KPI, a form or email template | Key user | PE, PCE, OP | A | 4,050 |
| DV-RAPX RAP extension | Logic or fields on an SAP business object beyond key user reach | Developer | see note | A | 5,850 |
| DV-APP ABAP Cloud app or job | A program working on core data in the same transaction | Developer | see note | A | 7,650 |
| DV-WRAP Released wrapper | No released API yet; wrap a classic one until SAP releases it | Developer | PCE, OP | B | 9,450 |
| SB-APP Side-by-side app | Users outside SAP, own lifecycle, own UI | BTP team | PE, PCE, OP | A | 24,750 |
| SB-EVT Event consumer | React after a change in SAP, often for outsiders | BTP team | PE, PCE, OP | A | 11,250 |
| CL-MOD Modification | Never for new work; legacy only, with board approval | Developer | PCE, OP | D | 39,600 |

> **Note** Developer extensibility with ABAP Cloud is available in Public Edition and, per SAP's ABAP Cloud training, in every S/4HANA deployment option from release 2022. One SAP Learning page read today still lists developer extensibility as Public Edition only; check your release with SAP. ECC has none of the key user or ABAP Cloud patterns.

### Questions to ask

- For each extension: who uses it, and are any of them outside our company?
- Does it have to stop or change the SAP save, or can it run after the save?
- Which released API, BAdI or event does it use? Where is that listed for our release?
- What is its clean core level, and who approved anything below A?
- What does it cost to retest at each upgrade, and who runs it?
- Could a key user pattern do this before we pay a developer?
- When will we delete it? What standard feature would replace it?

### Common misconceptions

- **"Side-by-side is always cleaner."** It is cleaner only for what can run outside the save. A check that must block a bad order belongs on-stack.
- **"Key user means toy."** Custom fields, custom logic and custom business objects are SAP's first choice for last-mile needs, and they are level A.
- **"A custom field shows up everywhere."** It shows up only where it is enabled: screens, forms, reports or APIs.
- **"Polling is simpler than events."** Polling is easier to start and costs more to run; where SAP publishes an event, use it.
- **"A wrapper is a clean API."** A wrapper around a classic API is level B and needs an exit date; on Public Edition it isn't an option at all.

### Key terms

- **Extension pattern:** a known shape of extension, with its own tools, editions, level and cost.
- **On-stack:** runs inside S/4HANA, under SAP's transaction and roles (key user and developer extensions).
- **Side-by-side:** runs on SAP BTP and reaches S/4HANA through released APIs and events.
- **BAdI:** Business Add-In, a hook where SAP lets customers add logic; released BAdIs are stable across upgrades.
- **RAP business object extension:** fields, checks, actions or nodes added to an SAP business object built with the ABAP RESTful application programming model.
- **Wrapper:** a customer-released object that calls a classic or internal SAP object, used until SAP releases an API.
- **Event consumer:** a program that receives SAP business events and acts on them after the change.

### Check yourself

1. Which three facts sort most extension requests into a pattern?
   - A. Budget, project deadline and the partner's preferred build tool
   - B. Who uses it, whether it acts inside the save, what SAP releases
   - C. Module, number of users and the SAP release date
   - D. Data volume, screen count and the number of reports

   Answer: B. Users outside SAP point side-by-side, logic that must act inside the save points on-stack, and the released API, BAdI or event decides the concrete pattern. Budget and tools follow from that, not the other way round.

2. A partner puts a check that must block bad EP-900 orders into a BTP app. What is wrong?
   - A. BTP apps can't read sales orders at all
   - B. The check would need a licence for each order
   - C. A BTP app can't stop an SAP save; the check must be on-stack
   - D. BTP apps are only allowed for analytics, never for any checks

   Answer: C. Side-by-side apps call SAP through remote APIs after or around the transaction. A check that must stop the save belongs inside it, as key user custom logic or a RAP extension.

3. Hallam's staff need to see their own order status. Where does that belong?
   - A. In S/4HANA, with an SAP user for every Hallam employee
   - B. In a side-by-side app on SAP BTP that reads released APIs
   - C. In a custom field on the sales order, made visible to Hallam
   - D. In a modification of the standard order display program

   Answer: B. Outsiders and an own lifecycle point to side-by-side. Giving distributors SAP users in the core system widens access to Calder's ERP for no gain.

4. Why does the pattern choice matter to the budget years after go-live?
   - A. Its level sets how much retesting every upgrade costs
   - B. SAP charges a yearly fee for each custom field created
   - C. Patterns expire and must be rebuilt every two years
   - D. The partner's support fee depends on the pattern

   Answer: A. In the course model most of a modification's five-year cost is retesting at each upgrade. Level A patterns carry little of that tail; level D patterns carry the most.

5. A key user creates a custom field for the test certificate number. Why might the CRM still not see it?
   - A. Custom fields can only appear on printed forms
   - B. The CRM must be restarted after every new field
   - C. Custom fields are deleted again at every following upgrade
   - D. The field shows only where it was enabled, such as an API

   Answer: D. A custom field is made available to apps, reports, forms or APIs one by one. Ask where it must show up before it is built, and test each place.

6. When is a wrapper around a classic API acceptable at Calder?
   - A. Always, because a wrapper makes any API released
   - B. Only on Public Edition, where classic APIs are missing anyway
   - C. On Private Edition, with a release request and an exit date
   - D. Never, because wrappers are level D by definition

   Answer: C. SAP's training describes the released wrapper for private edition and on-premise, removed once SAP releases an API. Wrapping a classic API is level B, so it needs a planned exit.

## Deep layer

### Mental model

Think of the core as a building with **marked sockets**. SAP marks them: released APIs, released BAdIs, extensible RAP business objects, published events. Every clean extension pattern plugs into one of those sockets, from inside the building (on-stack) or from outside (side-by-side). The pattern you choose is mostly a choice of socket.

Three questions pick the socket:

1. **Who is on the other end?** People outside SAP, or a system with its own release cycle, point outside: side-by-side.
2. **When must it act?** Inside the save (block, default, derive in the same transaction) points inside: on-stack. After the save (notify, sync, start a process) points to an event.
3. **What does SAP mark for it?** A field, a BAdI, an extensible business object, an API, an event. If nothing is marked, you are either asking SAP to release something, wrapping a classic object for a while, or redesigning.

Cost follows from the socket. A marked socket has a stability contract, so the extension survives upgrades with little retesting. An unmarked one (a table written directly, an implicit enhancement) has none, and you pay at every upgrade.

### How it works

#### The selection order

```mermaid
flowchart TD
  R[Request with evidence] --> FG{Fit-to-standard says<br/>extension?}
  FG -- no --> N[No pattern:<br/>config, process, standard]
  FG -- yes --> O{Users outside SAP?}
  O -- yes --> RE{Reacts to a<br/>change in SAP?}
  RE -- yes --> SBE[SB-EVT event consumer]
  RE -- no --> SBA[SB-APP side-by-side app]
  O -- no --> AF{Must act inside<br/>the save?}
  AF -- no --> SBE
  AF -- yes --> K{What is needed?}
  K -- field / UI / form / query --> KU[Key user pattern]
  K -- check or default --> B{Released BAdI<br/>for key users?}
  B -- yes --> KL[KU-LOG custom logic]
  B -- no --> RX[DV-RAPX RAP extension]
  K -- own table and app --> CB[KU-CBO custom BO]
  K -- program or job --> DA[DV-APP ABAP Cloud]
  K -- no released API --> W{Public Edition?}
  W -- no --> WR[DV-WRAP wrapper,<br/>level B, with exit]
  W -- yes --> ASK[Ask SAP to release,<br/>or redesign]
```

The order matters. Outsiders are tested first because no on-stack pattern serves them well. "Inside the save" is tested next because it rules out every side-by-side pattern. Only then does the concrete need pick among on-stack patterns, starting with the cheapest (key user). SAP's own advice runs the same way: exhaust key user options, then move to more complex extensions ([Fit-to-standard](https://erpfde.com/topics/fit-to-standard-and-extension-choices/) has the sources).

#### Key user patterns (on-stack, level A)

Built in SAP Fiori apps by a key user with the *Administrator* or *Extensibility Specialist* business role, collected in the development system's customizing tenant and moved by transport ([SAP Learning](https://learning.sap.com/courses/implementing-sap-s-4hana-cloud-private-edition/using-the-key-user-in-app-extensibility-tools-in-sap-s-4hana-cloud-private-edition_bfd97d11-03ce-46d1-87d4-6118b5fff695), read 27 November 2026). The *Extensibility Inventory* app lists them.

| Pattern | SAP app | What you get | Watch out for |
| --- | --- | --- | --- |
| KU-UI | Adapt UI (runtime authoring) | Fields hidden, renamed, moved, added to a screen | Changes per app; test each app variant |
| KU-FLD | Custom Fields | A field on SAP tables, CDS views or OData services, enabled per app, report, form template or API | Publishing is a background job of up to 30 minutes; the course page says custom fields get no read-access logging, can't be marked relevant for data protection blocking and can't be deleted, so never put personal data in one |
| KU-LOG | Custom Logic | ABAP in a released BAdI, written in a web editor with syntax checks | Only where SAP offers a BAdI for key users; unsupported statements are blocked on save |
| KU-CBO | Custom Business Objects | A table, a generated service (API) and optionally a UI | Small, simple data only; no complex behavior |
| KU-RPT | Custom CDS Views, Custom Analytical Queries, KPIs | A query or tile over SAP and custom data | Reads only; heavy analytics belong in [the data layer](https://erpfde.com/topics/reporting-and-analytics-architecture/) |
| KU-OUT | Maintain Form Templates, Maintain Email Templates | Output based on CDS views and OData services | The course page says only print forms are supported in S/4HANA itself |

#### Developer patterns (on-stack, ABAP Cloud)

Built in ABAP development tools for Eclipse with ABAP Cloud, in a separate development, test and production landscape. SAP's training lists the use cases: frequent or complex SQL on core data, running in the same logical unit of work (LUW, one database transaction) as SAP's applications, and serving as a remote API for side-by-side apps ([SAP Learning](https://learning.sap.com/courses/practicing-clean-core-extensibility-for-sap-s-4hana-cloud/explaining-developer-extensibility_f2683861-d69e-4a59-9e3e-01e3cc20fb0f)).

| Pattern | What it adds | Rule of the socket |
| --- | --- | --- |
| DV-RAPX RAP business object extension | Fields, determinations, validations, actions, an additional save, new nodes, an extended service | SAP must have enabled the object for extension; there is no implicit enhancement, and an extension only adds, it can't remove or overwrite ([SAP Learning](https://learning.sap.com/courses/building-transactional-apps-with-the-abap-restful-application-programming-model/exploring-extensibility-options)) |
| DV-BADI Released BAdI in ABAP Cloud | Logic in a hook, with the full ABAP Cloud language | SAP's course says updates won't affect BAdI implementations, because BAdIs are separate from the object they extend |
| DV-APP Own ABAP Cloud app or job | A RAP app or an application job working on core data through released objects | Released objects only, enforced by the syntax check |
| DV-EVT Custom RAP business event | An event raised by your business object, for side-by-side consumers | Raised in the save phase; external consumers need an event binding |
| DV-WRAP Released wrapper | A customer object, released for ABAP Cloud, that calls a classic or internal SAP object | Private edition and on-premise only; request the release from SAP through the Customer Influence Tool and delete the wrapper once SAP releases an API ([SAP Learning](https://learning.sap.com/courses/sap-enterprise-architects/exploring-how-to-make-extensions-clean-core-compliant)) |

SAP's training describes the wrapper under its older three-tier model. Under the level model, an extension takes the level of its lowest technique ([SAP Learning](https://learning.sap.com/courses/sap-enterprise-architects/exploring-how-to-make-extensions-clean-core-compliant-1)), so a wrapper around a classic BAPI is level B and one around an internal object is level C. That is why this catalogue gives DV-WRAP level B and an exit rule.

How to build RAP apps and extensions is in [ABAP Cloud and RAP for AI](https://erpfde.com/topics/abap-cloud-and-rap-for-ai/).

#### Side-by-side patterns (SAP BTP)

Side-by-side extensions run on SAP BTP in Java, Node.js or the SAP BTP, ABAP environment, and suit an app that needs S/4HANA data but not its runtime ([SAP Learning](https://learning.sap.com/courses/practicing-clean-core-extensibility-for-sap-s-4hana-cloud/explaining-side-by-side-extensibility_a01bb1ac-1acb-434d-8458-7a36cf2bcb3b)).

| Pattern | Typical build | Taught in |
| --- | --- | --- |
| SB-APP App on released APIs | CAP app with Fiori elements, or an ABAP environment app | [CAP and side-by-side extensions](https://erpfde.com/topics/cap-and-side-by-side-extensions/), [CAP in depth for architects](https://erpfde.com/topics/cap-for-architects/) |
| SB-EVT Event consumer | A small service subscribed to an event broker, then reading details through an API | [Event-driven agents with SAP events](https://erpfde.com/topics/event-driven-agents-with-sap-events/) |
| SB-PROC Process extension | A workflow with forms and approvals | [SAP Build Process Automation for architects](https://erpfde.com/topics/sap-build-process-automation/) |
| SB-LC Low-code app | A small app for a team | [SAP Build Apps](https://erpfde.com/topics/sap-build-apps/) |

Which runtime each app lands on is in [BTP runtimes compared](https://erpfde.com/topics/btp-runtimes-compared/).

#### Events: the after-the-save socket

An event consumer is the pattern for "when X changes in SAP, do Y elsewhere". SAP's Architecture Center lists the brokers: **SAP Cloud Application Event Hub**, **SAP Integration Suite, advanced event mesh** for large, multi-broker landscapes, and the **event mesh capability** of SAP Integration Suite for starter or small-volume scenarios ([SAP Architecture Center](https://architecture.learning.sap.com/docs/ref-arch/196eba)). SAP's training on event sources says S/4HANA offers around 600 standard notification events documented on the Business Accelerator Hub, and that a custom-event-only approach doesn't scale ([SAP Learning](https://learning.sap.com/courses/discovering-event-driven-integration-with-sap-integration-suite-advanved-event-mesh/presenting-event-sources_e4194f4f-a986-418d-9c3b-ee71bb4ed101)). The sales order change event Calder uses is the one in [Event-driven agents with SAP events](https://erpfde.com/topics/event-driven-agents-with-sap-events/).

```mermaid
sequenceDiagram
  participant U as Order clerk
  participant S as S/4HANA CP10
  participant B as Event broker
  participant C as Consumer on BTP
  participant M as Brennock project team
  U->>S: Change EP-900 order, save
  S-->>B: Sales order changed (after commit)
  B-->>C: Deliver event
  C->>S: Read order through released API
  C->>C: Confirmed date moved?
  C->>M: Email with old and new date
```

The event arrives after the commit, so it can't block anything. That is its strength for notifications and its limit for checks.

#### The classic pattern, for completeness

CL-MOD covers modifications, direct writes into SAP tables and implicit enhancements: level D in SAP's white paper, which also lists objects marked `noAPI` there ([SAP white paper](https://www.sap.com/uk/documents/2024/09/20aece06-d87e-0010-bca6-c68f7e60039b.html)). It exists on private edition and on-premise. It is in the catalogue so a review can name it, not so a design can choose it.

### Build it yourself: Calder's pattern picker and design review

You will write a Python script that holds the catalogue above, picks a pattern for each of Calder's eight requests in the order of the flowchart, and reviews a partner's design against eight rules. It writes a register you can hand to an architecture board. It runs on your computer with no account and no SAP system.

```mermaid
flowchart LR
  I[--init] --> F[patterns/<br/>requests.json<br/>design_draft.json<br/>design_reviewed.json]
  F --> S[extension_patterns.py<br/>catalogue + rules X01-X08]
  S --> P[--pick<br/>pattern per request]
  S --> V[--review<br/>OK / WARN / FAIL, exit 2]
  S --> RP[--report<br/>calder_extension_patterns.md]
```

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 21](https://erpfde.com/topics/set-up-for-unit-21/). This walkthrough doesn't repeat their steps.

> **Note** New words. A **request** here is one surviving requirement from Calder's fit-to-standard, E01 to E08. A **design** is a file that names one pattern per request. A **rule** is one of Calder's checks, X01 to X08 (course rules). A **verdict** is OK, WARN (fix soon) or FAIL (breaks a rule). **JSON** is a text format for data, used here for the request and design files. An **exit code** is the number a program returns when it ends; this one returns 2 when any rule fails, so a pipeline can stop on it.

#### What you need

- Python and your `orchestrate-course` folder with its `.venv`.
- No account, no network. Free.
- About 30 minutes.

#### 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. The `unit21` folder exists from the setup topic. If it doesn't, create it with `mkdir unit21`.

#### Step 2: Create the script

Create `unit21/extension_patterns.py` and paste this in. It uses only Python's built-in modules, so there is nothing to install.

```python
"""Calder's extension pattern catalogue: pick a pattern per request and review a design.

Course script for Orchestrate, Unit 21 (Extension patterns). Built-in modules only,
no randomness, no network. Pattern IDs, build days, run costs, rules and requests are
course values, not SAP figures. Calder Pumpworks is fictional.

  python unit21/extension_patterns.py --init              write the sample files
  python unit21/extension_patterns.py --catalog           print the pattern catalogue
  python unit21/extension_patterns.py --pick              pick a pattern for each request
  python unit21/extension_patterns.py --review FILE       check a proposed design (exit 2 on FAIL)
  python unit21/extension_patterns.py --report FILE       write calder_extension_patterns.md
"""
import argparse
import json
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent
DATA = HERE / "patterns"

DAY_RATE = 900          # USD per person-day (course input from the fit-gap scenario)
YEARS = 5               # horizon of the cost comparison
UPGRADES_PER_YEAR = 1   # upgrade events a year (course input)
RETEST_DAYS = {"A": 0.5, "B": 1.5, "C": 4, "D": 8}  # per upgrade, by clean core level

ALL = ["PE", "PCE", "OP"]   # Public Edition, Private Edition, on-premise S/4HANA
NO_PE = ["PCE", "OP"]

# id: name, where, who builds, tool, editions, level, build days, run USD/month, kind
PATTERNS = {
    "KU-UI":   ("UI adaptation", "on-stack", "key user", "Adapt UI", ALL, "A", 0.5, 0, "ui"),
    "KU-FLD":  ("Custom field", "on-stack", "key user", "Custom Fields app", ALL, "A", 1, 0, "field"),
    "KU-LOG":  ("Custom logic in a released BAdI", "on-stack", "key user", "Custom Logic app", ALL, "A", 2, 0, "check"),
    "KU-CBO":  ("Custom business object", "on-stack", "key user", "Custom Business Objects app", ALL, "A", 3, 0, "table"),
    "KU-RPT":  ("Custom CDS view or analytical query", "on-stack", "key user", "Custom CDS Views app", ALL, "A", 2, 0, "report"),
    "KU-OUT":  ("Custom form or email template", "on-stack", "key user", "Maintain Form Templates", ALL, "A", 2, 0, "form"),
    "DV-RAPX": ("RAP business object extension", "on-stack", "developer", "ABAP Cloud in ADT", ALL, "A", 4, 0, "check"),
    "DV-BADI": ("Released BAdI in ABAP Cloud", "on-stack", "developer", "ABAP Cloud in ADT", ALL, "A", 3, 0, "check"),
    "DV-APP":  ("Own ABAP Cloud app or job", "on-stack", "developer", "ABAP Cloud in ADT", ALL, "A", 6, 0, "job"),
    "DV-EVT":  ("Custom RAP business event", "on-stack", "developer", "ABAP Cloud in ADT", ALL, "A", 3, 0, "raise"),
    "DV-WRAP": ("Released wrapper around a classic API", "on-stack", "developer", "ABAP in ADT", NO_PE, "B", 3, 0, "classic-api"),
    "SB-APP":  ("Side-by-side app on released APIs", "side-by-side", "BTP team", "CAP or ABAP environment", ALL, "A", 15, 150, "app"),
    "SB-EVT":  ("Event consumer on SAP BTP", "side-by-side", "BTP team", "CAP + event broker", ALL, "A", 6, 60, "react"),
    "SB-PROC": ("Process extension", "side-by-side", "BTP team", "SAP Build Process Automation", ALL, "A", 5, 100, "process"),
    "SB-LC":   ("Low-code app", "side-by-side", "citizen developer", "SAP Build Apps", ALL, "A", 4, 80, "lowcode"),
    "CL-MOD":  ("Modification or direct table write", "on-stack", "developer", "classic ABAP", NO_PE, "D", 4, 0, "classic"),
}

KIND_TO_PATTERN = {"ui": "KU-UI", "field": "KU-FLD", "table": "KU-CBO", "report": "KU-RPT",
                   "form": "KU-OUT", "job": "DV-APP", "raise": "DV-EVT", "process": "SB-PROC"}

REQUESTS = [
    {"id": "E01", "title": "Pump test certificate number on order item, delivery note and order API (R02)",
     "target": "PCE", "fit_gap": "extension", "need": "field", "same_luw": True, "outsiders": False},
    {"id": "E02", "title": "EP-900 order item: requested date at least 15 days out, checked on save",
     "target": "PCE", "fit_gap": "extension", "need": "check", "same_luw": True, "outsiders": False,
     "released_badi": True},
    {"id": "E03", "title": "Monthly intercompany price for CP-IMP200 at cost plus 8% (R08)",
     "target": "PCE", "fit_gap": "extension", "need": "job", "same_luw": True, "outsiders": False},
    {"id": "E04", "title": "Distributor order-status app for Hallam and others (R03)",
     "target": "PCE", "fit_gap": "extension", "need": "app", "same_luw": False, "outsiders": True},
    {"id": "E05", "title": "Tell Brennock's project team when an EP-900 order's confirmed date moves",
     "target": "PCE", "fit_gap": "extension", "need": "react", "same_luw": False, "outsiders": True,
     "event_available": True},
    {"id": "E06", "title": "Test bench readings per pump serial, with an app for test technicians",
     "target": "PCE", "fit_gap": "extension", "need": "table", "same_luw": True, "outsiders": False},
    {"id": "E07", "title": "Augsburg program writing delivery dates into PO items (R07)",
     "target": "PCE", "fit_gap": "process change", "need": "job", "same_luw": True, "outsiders": False},
    {"id": "E08", "title": "Engineering change check that needs a classic BAPI with no released successor",
     "target": "PCE", "fit_gap": "extension", "need": "classic-api", "same_luw": True, "outsiders": False},
]

DESIGN_DRAFT = {"name": "Partner draft", "items": [
    {"request": "E01", "pattern": "DV-RAPX"},
    {"request": "E02", "pattern": "SB-APP"},
    {"request": "E03", "pattern": "DV-APP"},
    {"request": "E04", "pattern": "DV-APP"},
    {"request": "E05", "pattern": "SB-APP", "polling": True},
    {"request": "E06", "pattern": "KU-CBO"},
    {"request": "E07", "pattern": "CL-MOD"},
    {"request": "E08", "pattern": "DV-WRAP"},
]}

DESIGN_REVIEWED = {"name": "Reviewed design", "items": [
    {"request": "E01", "pattern": "KU-FLD"},
    {"request": "E02", "pattern": "KU-LOG"},
    {"request": "E03", "pattern": "DV-APP"},
    {"request": "E04", "pattern": "SB-APP"},
    {"request": "E05", "pattern": "SB-EVT"},
    {"request": "E06", "pattern": "KU-CBO"},
    {"request": "E07", "pattern": "NONE"},
    {"request": "E08", "pattern": "DV-WRAP", "release_request": "INF-0042",
     "exit": "remove when SAP releases a successor; review 2027-06-30"},
]}

RANK = {"OK": 0, "WARN": 1, "FAIL": 2}


def cost(pid):
    """Five-year cost in USD: build + retests at each upgrade + running cost."""
    if pid == "NONE":
        return 0
    p = PATTERNS[pid]
    level, build, run = p[5], p[6], p[7]
    retest = YEARS * UPGRADES_PER_YEAR * RETEST_DAYS[level] * DAY_RATE
    return round(build * DAY_RATE + retest + run * 12 * YEARS)


def pick(req):
    """Return (pattern id, reason) for one request, in a fixed order of questions."""
    if req["fit_gap"] != "extension":
        return "NONE", f"fit-to-standard decided '{req['fit_gap']}': no extension"
    need = req["need"]
    if req.get("outsiders"):
        if need == "react":
            return "SB-EVT", "users outside SAP, triggered by a change in SAP: consume an event on BTP"
        return "SB-APP", "users outside SAP: side-by-side app on released APIs"
    if need == "react":
        return "SB-EVT", "reacts to a change in SAP after the save: consume an event"
    if need == "check":
        if req.get("released_badi"):
            return "KU-LOG", "check inside the save, released BAdI exists: key user custom logic"
        return "DV-RAPX", "check inside the save, no key user BAdI: RAP business object extension"
    if need == "classic-api":
        if req["target"] == "PE":
            return "NONE", "no released API and Public Edition allows no wrapper: ask SAP to release one"
        return "DV-WRAP", "no released API yet: released wrapper (level B) with an exit"
    if need == "app":
        return "SB-APP", "own lifecycle and UI: side-by-side app"
    pid = KIND_TO_PATTERN.get(need)
    if pid is None:
        return "NONE", f"no pattern for need '{need}'"
    return pid, f"need '{need}' maps to {PATTERNS[pid][0].lower()}"


def review(design, requests):
    """Check each design item against rules X01-X08. Returns rows and counts."""
    by_id = {r["id"]: r for r in requests}
    rows = []
    for item in design["items"]:
        req = by_id.get(item["request"])
        if req is None:
            rows.append((item["request"], item["pattern"], "FAIL", ["X00 unknown request"]))
            continue
        pid = item["pattern"]
        best, _ = pick(req)
        findings = []
        if pid != "NONE" and pid not in PATTERNS:
            rows.append((req["id"], pid, "FAIL", ["X00 unknown pattern"]))
            continue
        # X08 the design must follow the fit-to-standard decision
        if req["fit_gap"] != "extension" and pid != "NONE":
            findings.append(("FAIL", f"X08 fit-to-standard decided '{req['fit_gap']}', not an extension"))
        if req["fit_gap"] == "extension" and pid == "NONE" and best != "NONE":
            findings.append(("FAIL", "X08 the request needs an extension; none designed"))
        if pid != "NONE":
            name, where, _, _, editions, level = PATTERNS[pid][:6]
            # X01 the pattern must exist on the target edition
            if req["target"] not in editions:
                findings.append(("FAIL", f"X01 {pid} is not available on {req['target']}"))
            # X02 clean core level
            if level in ("C", "D") and not item.get("board_approved"):
                findings.append(("FAIL", f"X02 level {level} without board approval"))
            elif level == "B":
                findings.append(("WARN", "X02 level B: retested at every upgrade, needs an exit"))
            # X03 users outside SAP never get an on-stack pattern
            if req.get("outsiders") and where == "on-stack":
                findings.append(("FAIL", "X03 users outside SAP on an on-stack pattern"))
            # X04 logic that must act inside the save can't run side-by-side
            if req.get("same_luw") and where == "side-by-side":
                findings.append(("FAIL", "X04 must act inside the SAP save; side-by-side can't"))
            # X05 a wrapper needs a release request and an exit
            if pid == "DV-WRAP" and not (item.get("release_request") and item.get("exit")):
                findings.append(("FAIL", "X05 wrapper without a release request and an exit"))
            # X06 polling where SAP publishes an event
            if item.get("polling") and req.get("event_available"):
                findings.append(("WARN", "X06 polls the API although a standard event exists"))
            # X07 heavier than needed
            if best != "NONE" and cost(pid) > 1.5 * cost(best):
                findings.append(("WARN", f"X07 five-year cost {cost(pid):,} USD vs {cost(best):,} for {best}"))
        verdict = max((f[0] for f in findings), key=RANK.get, default="OK")
        rows.append((req["id"], pid, verdict, [f[1] for f in findings]))
    counts = {v: sum(1 for r in rows if r[2] == v) for v in RANK}
    return rows, counts


def load(path):
    with open(path, encoding="utf-8") as f:
        return json.load(f)


def requests_file():
    path = DATA / "requests.json"
    if not path.exists():
        sys.exit(f"{path} not found. Run: python unit21/extension_patterns.py --init")
    return load(path)


def cmd_init(force):
    DATA.mkdir(exist_ok=True)
    files = {"requests.json": REQUESTS, "design_draft.json": DESIGN_DRAFT,
             "design_reviewed.json": DESIGN_REVIEWED}
    for name, content in files.items():
        path = DATA / name
        if path.exists() and not force:
            print(f"kept    {path.relative_to(HERE.parent)} (use --force to overwrite)")
            continue
        path.write_text(json.dumps(content, indent=2) + "\n", encoding="utf-8")
        print(f"wrote   {path.relative_to(HERE.parent)}")


def cmd_catalog():
    print(f"{'ID':8} {'Pattern':40} {'Where':13} {'Level':5} {'Editions':12} {'5-yr USD':>9}")
    for pid, p in PATTERNS.items():
        print(f"{pid:8} {p[0]:40} {p[1]:13} {p[5]:5} {'/'.join(p[4]):12} {cost(pid):>9,}")


def cmd_pick():
    for req in requests_file():
        pid, reason = pick(req)
        print(f"{req['id']}  {pid:8} {cost(pid):>7,} USD  {reason}")


def cmd_review(path):
    design = load(path)
    rows, counts = review(design, requests_file())
    print(f"Design: {design.get('name', path)}")
    for rid, pid, verdict, findings in rows:
        print(f"{verdict:5} {rid}  {pid:8} " + ("; ".join(findings) if findings else "matches the catalogue"))
    print(f"Summary: {counts['OK']} OK, {counts['WARN']} WARN, {counts['FAIL']} FAIL")
    return 2 if counts["FAIL"] else 0


def cmd_report(path):
    design = load(path)
    reqs = requests_file()
    rows, counts = review(design, reqs)
    by_row = {r[0]: r for r in rows}
    lines = [f"# Calder extension register: {design.get('name', path)}", "",
             "Course values; Calder Pumpworks is fictional.", "",
             "| Request | Title | Pattern | Level | Where | 5-yr USD | Verdict | Findings |",
             "| --- | --- | --- | --- | --- | ---: | --- | --- |"]
    total = 0
    for req in reqs:
        rid, pid, verdict, findings = by_row.get(req["id"], (req["id"], "-", "-", ["not in design"]))
        p = PATTERNS.get(pid)
        level, where = (p[5], p[1]) if p else ("-", "-")
        c = cost(pid) if pid in PATTERNS or pid == "NONE" else 0
        total += c
        lines.append(f"| {rid} | {req['title']} | {pid} | {level} | {where} | {c:,} | {verdict} | "
                     + ("; ".join(findings) or "-") + " |")
    lines += ["", f"Five-year cost of the design: {total:,} USD. "
              f"Verdicts: {counts['OK']} OK, {counts['WARN']} WARN, {counts['FAIL']} FAIL.", ""]
    out = HERE / "calder_extension_patterns.md"
    out.write_text("\n".join(lines), encoding="utf-8")
    print(f"wrote   {out.relative_to(HERE.parent)} (five-year cost {total:,} USD)")


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--init", action="store_true", help="write the sample files")
    ap.add_argument("--force", action="store_true", help="with --init, overwrite existing files")
    ap.add_argument("--catalog", action="store_true", help="print the pattern catalogue")
    ap.add_argument("--pick", action="store_true", help="pick a pattern for each request")
    ap.add_argument("--review", metavar="FILE", help="check a design file")
    ap.add_argument("--report", metavar="FILE", help="write the register for a design file")
    args = ap.parse_args()
    if args.init:
        cmd_init(args.force)
    if args.catalog:
        cmd_catalog()
    if args.pick:
        cmd_pick()
    code = 0
    if args.review:
        code = cmd_review(args.review)
    if args.report:
        cmd_report(args.report)
    if not any([args.init, args.catalog, args.pick, args.review, args.report]):
        ap.print_help()
    return code


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

#### Step 3: Write the sample files and print the catalogue

1. Write the request and design files:

   ```bash
   python unit21/extension_patterns.py --init
   ```

   ```text
   wrote   unit21/patterns/requests.json
   wrote   unit21/patterns/design_draft.json
   wrote   unit21/patterns/design_reviewed.json
   ```

2. Print the catalogue:

   ```bash
   python unit21/extension_patterns.py --catalog
   ```

   ```text
   ID       Pattern                                  Where         Level Editions      5-yr USD
   KU-UI    UI adaptation                            on-stack      A     PE/PCE/OP        2,700
   KU-FLD   Custom field                             on-stack      A     PE/PCE/OP        3,150
   KU-LOG   Custom logic in a released BAdI          on-stack      A     PE/PCE/OP        4,050
   KU-CBO   Custom business object                   on-stack      A     PE/PCE/OP        4,950
   KU-RPT   Custom CDS view or analytical query      on-stack      A     PE/PCE/OP        4,050
   KU-OUT   Custom form or email template            on-stack      A     PE/PCE/OP        4,050
   DV-RAPX  RAP business object extension            on-stack      A     PE/PCE/OP        5,850
   DV-BADI  Released BAdI in ABAP Cloud              on-stack      A     PE/PCE/OP        4,950
   DV-APP   Own ABAP Cloud app or job                on-stack      A     PE/PCE/OP        7,650
   DV-EVT   Custom RAP business event                on-stack      A     PE/PCE/OP        4,950
   DV-WRAP  Released wrapper around a classic API    on-stack      B     PCE/OP           9,450
   SB-APP   Side-by-side app on released APIs        side-by-side  A     PE/PCE/OP       24,750
   SB-EVT   Event consumer on SAP BTP                side-by-side  A     PE/PCE/OP       11,250
   SB-PROC  Process extension                        side-by-side  A     PE/PCE/OP       12,750
   SB-LC    Low-code app                             side-by-side  A     PE/PCE/OP       10,650
   CL-MOD   Modification or direct table write       on-stack      D     PCE/OP          39,600
   ```

> **Note** These costs are synthetic. They come from course inputs (900 USD a day, one upgrade a year, retest days of 0.5, 1.5, 4 and 8 by level A to D, and made-up build days and running costs per pattern). They show the method, not prices from SAP or a real project. Running `--init` again keeps your files; add `--force` to restore the originals.

#### Step 4: Pick a pattern for each request

```bash
python unit21/extension_patterns.py --pick
```

```text
E01  KU-FLD     3,150 USD  need 'field' maps to custom field
E02  KU-LOG     4,050 USD  check inside the save, released BAdI exists: key user custom logic
E03  DV-APP     7,650 USD  need 'job' maps to own abap cloud app or job
E04  SB-APP    24,750 USD  users outside SAP: side-by-side app on released APIs
E05  SB-EVT    11,250 USD  users outside SAP, triggered by a change in SAP: consume an event on BTP
E06  KU-CBO     4,950 USD  need 'table' maps to custom business object
E07  NONE           0 USD  fit-to-standard decided 'process change': no extension
E08  DV-WRAP    9,450 USD  no released API yet: released wrapper (level B) with an exit
```

Read E07 first: the Augsburg delivery-date program was a **process change** in fit-to-standard, so it gets no pattern at all. E02 and E08 rest on course assumptions: that a released BAdI for key users covers the sales order item check, and that the engineering change check needs a classic BAPI with no released successor in Calder's release. On a real project you would confirm both in the SAP Business Accelerator Hub and the Cloudification Repository for your release.

#### Step 5: Review the partner's draft

```bash
python unit21/extension_patterns.py --review unit21/patterns/design_draft.json
```

```text
Design: Partner draft
WARN  E01  DV-RAPX  X07 five-year cost 5,850 USD vs 3,150 for KU-FLD
FAIL  E02  SB-APP   X04 must act inside the SAP save; side-by-side can't; X07 five-year cost 24,750 USD vs 4,050 for KU-LOG
OK    E03  DV-APP   matches the catalogue
FAIL  E04  DV-APP   X03 users outside SAP on an on-stack pattern
WARN  E05  SB-APP   X06 polls the API although a standard event exists; X07 five-year cost 24,750 USD vs 11,250 for SB-EVT
OK    E06  KU-CBO   matches the catalogue
FAIL  E07  CL-MOD   X08 fit-to-standard decided 'process change', not an extension; X02 level D without board approval
FAIL  E08  DV-WRAP  X02 level B: retested at every upgrade, needs an exit; X05 wrapper without a release request and an exit
Summary: 2 OK, 2 WARN, 4 FAIL
```

The script ends with exit code 2. What each rule protects:

| Rule | Checks | Why |
| --- | --- | --- |
| X01 | The pattern exists on the target edition | Wrappers and modifications don't exist on Public Edition |
| X02 | Level B warns; C or D fails without board approval | Lower levels carry the upgrade bill |
| X03 | No on-stack pattern for users outside SAP | Outsiders would need users in the core system |
| X04 | No side-by-side pattern for logic inside the save | A remote app can't stop or change a save |
| X05 | A wrapper names a release request and an exit | Otherwise level B becomes permanent |
| X06 | No polling where a standard event exists | Polling costs runs and misses changes between polls |
| X07 | No pattern over 1.5 times the cost of the picked one | Heavier than needed is money spent at every upgrade |
| X08 | The design follows the fit-to-standard decision | Extensions must not reopen settled decisions |

#### Step 6: Review the corrected design and write the register

1. Review it:

   ```bash
   python unit21/extension_patterns.py --review unit21/patterns/design_reviewed.json
   ```

   ```text
   Design: Reviewed design
   OK    E01  KU-FLD   matches the catalogue
   OK    E02  KU-LOG   matches the catalogue
   OK    E03  DV-APP   matches the catalogue
   OK    E04  SB-APP   matches the catalogue
   OK    E05  SB-EVT   matches the catalogue
   OK    E06  KU-CBO   matches the catalogue
   OK    E07  NONE     matches the catalogue
   WARN  E08  DV-WRAP  X02 level B: retested at every upgrade, needs an exit
   Summary: 7 OK, 1 WARN, 0 FAIL
   ```

   The remaining warning is intended. Calder accepts the wrapper with request `INF-0042` and a review date of 2027-06-30 (course labels), and the warning keeps it visible until SAP releases an API.

2. Write the register:

   ```bash
   python unit21/extension_patterns.py --report unit21/patterns/design_reviewed.json
   ```

   ```text
   wrote   unit21/calder_extension_patterns.md (five-year cost 65,250 USD)
   ```

   The same command on the draft gives 124,650 USD.

> **Note** Both totals are synthetic course numbers: they show that the draft's choices roughly doubled the five-year cost, not what a real Calder project would spend.

#### Step 7: Save your work

```bash
git add unit21/extension_patterns.py unit21/patterns unit21/calder_extension_patterns.md
git commit -m "Unit 21: extension pattern picker and design review"
```

#### How the code works

| Part | What it does |
| --- | --- |
| `PATTERNS` | The catalogue: name, on-stack or side-by-side, builder, tool, editions, level, build days, running cost a month |
| `cost()` | Five-year cost: build days times the day rate, plus retests at each upgrade by level, plus 60 months of running cost |
| `pick()` | Asks the flowchart's questions in order: fit-to-standard decision, outsiders, react after the save, then the kind of need |
| `review()` | Compares each design item with the picked pattern and applies rules X01 to X08; the worst finding sets the verdict |
| `REQUESTS`, `DESIGN_DRAFT`, `DESIGN_REVIEWED` | The sample data, written to `unit21/patterns/` by `--init` so you can edit it as JSON |
| `cmd_report()` | Writes the register as a markdown table with the total five-year cost |
| `main()` | Returns exit code 2 when a review finds any FAIL |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python: command not found` or `Python was not found` | Python isn't on your path, or the virtual environment is off | Turn on `.venv` (Step 1); on macOS or Linux try `python3` |
| `requests.json not found` | You skipped `--init` | Run `python unit21/extension_patterns.py --init` |
| `json.decoder.JSONDecodeError` | A JSON file you edited has a typo, often a missing comma or quote | Fix the file, or run `--init --force` to restore the samples |
| `X00 unknown pattern` | A design names a pattern ID that isn't in `PATTERNS` | Use an ID from `--catalog` |
| Output differs from the expected text | You edited the sample files | Run `--init --force` and try again |
| Anything about a proxy or network | Not from this script | It never goes online and needs no key |

### The SAP way

As read on SAP's pages on 27 November 2026.

- **Key user extensibility** in all S/4HANA deployment options: UI adaptation, Custom Fields, Custom Business Logic, Custom Business Objects, Custom CDS Views, Custom Analytical Queries, KPIs, Custom Forms ([SAP Learning](https://learning.sap.com/courses/practicing-clean-core-extensibility-for-sap-s-4hana-cloud/explaining-key-user-extensibility_c7f6cbcb-ed54-4f1d-8e76-4a6e311e3cfa)). The private edition course adds the app names and the transport path ([SAP Learning](https://learning.sap.com/courses/implementing-sap-s-4hana-cloud-private-edition/using-the-key-user-in-app-extensibility-tools-in-sap-s-4hana-cloud-private-edition_bfd97d11-03ce-46d1-87d4-6118b5fff695)).
- **Developer extensibility**: RAP business object extensions and BAdIs in ABAP Cloud. SAP does the extensibility enablement of its objects; the customer does the provisioning ([SAP Learning](https://learning.sap.com/courses/practicing-clean-core-extensibility-for-sap-s-4hana-cloud/explaining-developer-extensibility_f2683861-d69e-4a59-9e3e-01e3cc20fb0f)). In practice: you can extend only what SAP has opened, so check the object's extensibility before you promise a design.
- **Side-by-side extensibility** on SAP BTP with CAP, SAP Build or the SAP BTP, ABAP environment ([SAP Learning](https://learning.sap.com/courses/practicing-clean-core-extensibility-for-sap-s-4hana-cloud/explaining-side-by-side-extensibility_a01bb1ac-1acb-434d-8458-7a36cf2bcb3b)). SAP's white paper calls its overall line "SAP BTP first", with level A as the target ([SAP white paper](https://www.sap.com/uk/documents/2024/09/20aece06-d87e-0010-bca6-c68f7e60039b.html)).
- **Governance**: ABAP test cockpit checks on transport release with an exemption process, a Solution Standardization Board for deviations, and the SAP Application Extension Methodology for design ([SAP Learning](https://learning.sap.com/courses/sap-enterprise-architects/exploring-how-to-make-extensions-clean-core-compliant-1)).
- **Finding the sockets**: business events, APIs and BAdIs are listed on the SAP Business Accelerator Hub; the SAP Application Extension Methodology names the SAP Extensibility Explorer, SAP Discovery Center missions and Architecture Center reference architectures as decision aids ([SAP Learning](https://learning.sap.com/courses/becoming-an-sap-btp-solution-architect/adopting-the-sap-application-extension-methodology)).
- **Licensing.** Key user and developer extensibility are part of S/4HANA. Side-by-side patterns need SAP BTP services (runtime, event broker, process automation), billed under your BTP contract; check the current terms with SAP before you size a design, as in [BTP runtimes compared](https://erpfde.com/topics/btp-runtimes-compared/).

### Build vs. SAP

| Situation | Choose | Why |
| --- | --- | --- |
| A partner app in the SAP Store already covers it | The partner solution | SAP's training says to check the SAP Store and certified solutions before building ([Fit-to-standard](https://erpfde.com/topics/fit-to-standard-and-extension-choices/)) |
| A standard feature in a later release covers it | Wait, or a temporary key user pattern with a delete date | The cheapest extension is the one you remove |
| Last-mile field, check, form or query | Key user pattern | Level A, built by the people who know the process |
| Logic beyond key user reach, inside the transaction | ABAP Cloud developer pattern | Level A with the full language |
| Outsiders, own lifecycle, AI services, several systems | Side-by-side on BTP | Decoupled from upgrades; own release cycle |
| Nothing released and no time to wait | Wrapper with a release request (private edition) | Level B with an exit, instead of level C or D for good |

### Architecture view

**Where it sits.** Calder's reviewed design puts five extensions inside `CP10` and two on BTP:

```mermaid
flowchart LR
  subgraph S4[CP10 S/4HANA Private Edition]
    E01[E01 custom field]
    E02[E02 custom logic]
    E03[E03 ABAP Cloud job]
    E06[E06 custom BO]
    E08[E08 wrapper, level B]
  end
  subgraph BTP[SAP BTP, Extensions directory]
    E04[E04 distributor app]
    E05[E05 event consumer]
  end
  EB[Event broker] --> E05
  S4 -->|sales order event| EB
  E04 -->|released APIs| S4
  E05 -->|released API| S4
  H[Hallam staff] --> E04
  E05 --> BR[Brennock team email]
```

**Non-functional requirements that decide the pattern**

| Requirement | Typical target at Calder | What breaks if missed |
| --- | --- | --- |
| Transactional integrity | Checks that must block a save run on-stack | Bad orders saved, then "corrected" later |
| Upgrade effort | New extensions at level A; level B only with an exit date | Each upgrade turns into a retest project |
| Access for outsiders | Partners reach only side-by-side apps with row filters | Partners hold users in the core ERP |
| Latency of reactions | Event consumers act within minutes of the commit | Polling delays and extra load |
| Cost | Five-year cost in the register for each extension | Running costs surprise the budget |

**Integration and identity.** On-stack patterns run under the SAP user's own roles; authorization comes from [roles and authorization design](https://erpfde.com/topics/roles-and-authorization-design/). The distributor app (E04) signs in Hallam's users through BTP and filters by the customer taken from their identity, as in [CAP in depth for architects](https://erpfde.com/topics/cap-for-architects/). The event consumer (E05) receives the event, then reads the order through a released API with a narrowly scoped technical user, because no person is behind the event; connections run through destinations from [BTP connectivity](https://erpfde.com/topics/btp-connectivity/).

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

- **Context:** Brennock's project team wants an email when the confirmed date of an EP-900 order moves (E05). The partner built a BTP app that reads all open orders every five minutes.
- **Options:** A) poll the sales order API every five minutes; B) consume SAP's standard sales order change event and read the order only when it changed; C) key user custom logic that sends mail during the save.
- **Decision:** B.
- **Consequences:** one event broker subscription and a small consumer on BTP; the consumer must ignore events where the confirmed date didn't change, and handle repeats safely; C was rejected because mail from inside the save would delay the clerk and fire even if the save fails later.

**What a design review will ask**

1. For each extension, which released API, BAdI, object or event does it plug into, and where is that listed for our release?
2. Which logic must act inside the save, and is any of it side-by-side?
3. Which extensions are below level A, who approved them, and when do they end?
4. Who outside Calder reaches which app, and how is their data filtered?
5. What does each extension cost to run and to retest each year?

### Production concerns

- **Security and SAP authorizations.** Restrict the *Extensibility Specialist* role to a few named key users in development. Side-by-side apps get their own roles and never a broad technical user ([Agent permissions and SAP authorizations](https://erpfde.com/topics/agent-permissions-and-sap-authorizations/)). Keep personal data out of custom fields, given the logging and blocking limits SAP's course states.
- **Evaluation.** Count extensions by pattern and level each quarter, and run every pattern's test case at each upgrade. A rising share of DV and SB patterns where KU would do is a governance signal.
- **Cost.** Record build, run and retest cost per extension; re-check them after each upgrade with the actual effort.
- **Operations.** Every extension has an owner, a test and a retirement trigger. Event consumers need a dead-letter queue and monitoring, covered in [Event-driven agents with SAP events](https://erpfde.com/topics/event-driven-agents-with-sap-events/).
- **Clean core.** ATC checks block new level C and D code on transport release. Wrappers carry their release request and review date in the register.

### Where AI fits

- **A delivered SAP capability.** Joule for developers generates RAP and CAP code; generated code follows the same patterns and the same review, as in [SAP Build Code and AI-assisted development](https://erpfde.com/topics/sap-build-code/).
- **An agent as one more consumer.** An agent sees only what an API exposes. A custom field the agent needs must be enabled for the API (KU-FLD), and an agent that reacts to changes is an event consumer (SB-EVT) like any other.
- **AI features are extensions too.** An AI step in a side-by-side app calls the generative AI hub from BTP ([CAP and side-by-side extensions](https://erpfde.com/topics/cap-and-side-by-side-extensions/)); an AI step inside the transaction uses the ABAP AI SDK ([Generative AI in ABAP Cloud](https://erpfde.com/topics/generative-ai-in-abap-cloud-with-the-ai-sdk-and-islm/)). Joule agents have their own extension points ([Agent extensions](https://erpfde.com/topics/agent-extensions-for-sap-base-agents/)).
- **A new risk.** An agent writing through a wrapper or a modified program bypasses the checks a released API enforces. Agents get level A sockets only.

### Pitfalls

- **Choosing by team skill.** A BTP team builds everything side-by-side; an ABAP team builds everything on-stack. Let the three questions choose.
- **Checks after the fact.** Validations in an event consumer or a BTP app arrive after the save. Bad data is already in.
- **Fields created without their places.** A custom field not enabled for the API or the form looks done and isn't.
- **Wrappers without an exit.** Without a release request and a review date, a level B wrapper stays for years.
- **Polling by default.** It works in the demo and costs at scale, and it misses short-lived states between polls.
- **Extending what SAP hasn't opened.** RAP extensions need an object SAP enabled for extension; promise nothing before checking.
- **Duplicating the standard.** SAP's training is explicit that extensions must never duplicate standard functionality.

### Exercise

Extend Calder's register with a new request and test an edition change.

1. Open `unit21/patterns/requests.json` and add a request at the end of the list (mind the comma after the previous entry):

   ```json
   {"id": "E09", "title": "End customer on distributor orders, also shown in the distributor app",
    "target": "PCE", "fit_gap": "extension", "need": "field", "same_luw": true, "outsiders": false}
   ```

2. Run `python unit21/extension_patterns.py --pick` and check that E09 gets `KU-FLD`.
3. Add `{"request": "E09", "pattern": "KU-FLD"}` to the `items` list in `design_reviewed.json`.
4. Run the review and the report on the reviewed design.
5. Now suppose `CP10` were on Public Edition for E08: change E08's `"target"` to `"PE"` and run `--pick` and `--review` again. Write two sentences in a new file `unit21/e08_public_edition.md` on what Calder would do instead of the wrapper.
6. Change E08 back to `"PCE"`, run `--report` on the reviewed design again, and commit.

**Done when** the reviewed design shows `Summary: 8 OK, 1 WARN, 0 FAIL` with a five-year cost of 68,400 USD, the Public Edition run shows E08 as `NONE` in `--pick` and as `FAIL` with `X01` in the review, and your two sentences are in `unit21/e08_public_edition.md`. The register feeds the architect capstone's extension inventory.

### Check yourself

1. In the picker, why is "users outside SAP?" asked before "must it act inside the save?"
   - A. Because outsiders always need the cheapest pattern available
   - B. Because no on-stack pattern serves outsiders, which settles it
   - C. Because SAP requires partner apps to be checked before key user ones
   - D. Because side-by-side apps can block the save for outsiders

   Answer: B. Outsiders point to side-by-side regardless of the rest. Asking it first avoids designing an on-stack pattern and then discovering Hallam's staff can't use it.

2. The partner's E02 check gets X04. What does the rule protect against?
   - A. A check that costs more than 1.5 times the pattern the picker chose
   - B. A check built on an object SAP hasn't enabled for extension
   - C. A check that runs on an edition where it isn't available
   - D. A check placed outside the transaction it was meant to stop

   Answer: D. E02 must block a bad EP-900 order on save. A side-by-side app sees the order only through remote APIs, so the order is saved first. X07 also fires, but X04 is the reason it fails.

3. A RAP extension is proposed on an SAP business object. What must you check before promising it?
   - A. That the object's tables can be written to directly
   - B. That SAP enabled the object for extension in your release
   - C. That an implicit enhancement point exists in the object
   - D. That the extension can overwrite the object's existing checks

   Answer: B. RAP has no implicit enhancement; extensibility must be enabled by SAP, and extensions only add, never remove or overwrite. Writing tables directly would make it level D.

4. Why is DV-WRAP level B in this catalogue, and not A?
   - A. Because SAP charges extra for every customer-released object
   - B. Because wrappers can only be built by key users in Fiori apps
   - C. Because it takes the level of the classic API it calls
   - D. Because wrappers always write into SAP tables directly

   Answer: C. An extension takes the level of its lowest technique. The wrapper itself is released, but it calls a classic BAPI, so it is level B; around an internal object it would be level C.

5. What does the event consumer for E05 do after it receives the sales order event?
   - A. It blocks the order until Brennock confirms the new date
   - B. It writes the new date into the order item table
   - C. It asks the broker to resend every open order for a comparison
   - D. It reads the order through a released API and checks the date

   Answer: D. The event arrives after the commit and says the order changed. The consumer reads the details through an API and mails only when the confirmed date moved, ignoring other changes and repeats.

6. You must design E08 for a Public Edition system with no released API. What do you do?
   - A. Ask SAP to release an API, or redesign the requirement
   - B. Build the wrapper anyway and record a board exemption
   - C. Use a modification with a planned removal after go-live
   - D. Move the check into an event consumer on SAP BTP

   Answer: A. Public Edition allows neither wrappers nor modifications, so the picker returns no pattern and the review fails on X01. An event consumer can't replace a check that must act in the transaction.

7. An agent needs a custom field that a key user created on the sales order. What decides whether it can read it?
   - A. Whether the agent runs on SAP BTP or on another cloud
   - B. Whether the field was created by a developer in ABAP Cloud
   - C. Whether the field was enabled for the API the agent calls
   - D. Whether the field is shown on the sales order screen

   Answer: C. An agent sees only what an API exposes. Custom fields are enabled per app, report, form or API, so the field must be enabled for the API the agent uses.

## Sources

- [Explaining Key User Extensibility (SAP Learning, read 2026-11-27)](https://learning.sap.com/courses/practicing-clean-core-extensibility-for-sap-s-4hana-cloud/explaining-key-user-extensibility_c7f6cbcb-ed54-4f1d-8e76-4a6e311e3cfa): web-based SAP Fiori apps available in all SAP S/4HANA deployment options and consistent with clean core; UI adaptation at runtime, Custom Fields, Custom Business Logic, Custom Business Objects (tables and a CRUD API), Custom CDS Views, Custom Analytical Queries, KPIs, Custom Forms
- [Using the Key-User In-App Extensibility Tools in SAP S/4HANA Cloud Private Edition (SAP Learning, read 2026-11-27)](https://learning.sap.com/courses/implementing-sap-s-4hana-cloud-private-edition/using-the-key-user-in-app-extensibility-tools-in-sap-s-4hana-cloud-private-edition_bfd97d11-03ce-46d1-87d4-6118b5fff695): Custom Fields app; a field can be made available to related apps, reports, email and form templates and APIs; publishing is a background job of up to 30 minutes; no read-access logging, not relevant for data protection blocking, can't be deleted; Custom Logic app on released BAdIs; Custom Business Objects app generates tables, services and UIs; Extensibility Inventory app; Administrator or Extensibility Specialist role
- [Explaining Developer Extensibility (SAP Learning, read 2026-11-27)](https://learning.sap.com/courses/practicing-clean-core-extensibility-for-sap-s-4hana-cloud/explaining-developer-extensibility_f2683861-d69e-4a59-9e3e-01e3cc20fb0f): ABAP Cloud with ABAP development tools for Eclipse and released interfaces; use cases frequent SQL access, same LUW as SAP applications, remote API for side-by-side apps; RAP extensibility and BAdIs; over 125 business object interfaces and over 800 BAdIs; SAP does extensibility enablement, the customer provisioning; separate development, test and production tenants
- [Exploring Extensibility Options (SAP Learning, RAP course, read 2026-11-27)](https://learning.sap.com/courses/building-transactional-apps-with-the-abap-restful-application-programming-model/exploring-extensibility-options): in-app (key user), developer and side-by-side extensibility; RAP extensions add fields, determinations, validations, actions, an additional save and nodes; no implicit enhancement, extensibility must be enabled by the original developer, extensions only add and cannot remove or overwrite
- [Explaining Side-By-Side Extensibility (SAP Learning, read 2026-11-27)](https://learning.sap.com/courses/practicing-clean-core-extensibility-for-sap-s-4hana-cloud/explaining-side-by-side-extensibility_a01bb1ac-1acb-434d-8458-7a36cf2bcb3b): side-by-side runs on SAP BTP and calls remote APIs; Java, Node.js or SAP BTP, ABAP environment; fits an app that needs S/4HANA data but not its runtime; use cases BTP services such as AI, apps across several systems, partner SaaS
- [Exploring How to Make Extensions Clean Core Compliant (SAP Learning, enterprise architects, read 2026-11-27)](https://learning.sap.com/courses/sap-enterprise-architects/exploring-how-to-make-extensions-clean-core-compliant-1): levels A (released APIs only, the only level for SAP Cloud ERP public) to D (not clean); use A to C in that order; a class mixing level A and B calls is level B; ATC checks on transport release with an exemption process; Solution Standardization Board; SAP Application Extension Methodology
- [Decouple Extensions from Standard (SAP Learning, enterprise architects, read 2026-11-27)](https://learning.sap.com/courses/sap-enterprise-architects/exploring-how-to-make-extensions-clean-core-compliant): on-stack key user and developer extensions for close coupling, side-by-side for looser coupling; released wrapper around an unreleased object for private edition and on-premise, release requested through the Customer Influence Tool, wrapper removed once SAP releases the API; extensions must never duplicate standard functionality
- [Clean core extensibility for SAP S/4HANA Cloud (SAP white paper, read 2026-11-27)](https://www.sap.com/uk/documents/2024/09/20aece06-d87e-0010-bca6-c68f7e60039b.html): on-stack (ABAP Cloud or classic) and side-by-side (SAP Build on SAP BTP); level A on released interfaces with stability contracts; level D covers noAPI objects, modifications, write access to SAP tables and implicit enhancements; SAP BTP first; read only the first pages
- [Designing Event-Driven Applications on SAP BTP (SAP Architecture Center, last updated 2025-10-10, read 2026-11-27)](https://architecture.learning.sap.com/docs/ref-arch/196eba): SAP Cloud Application Event Hub, SAP Integration Suite advanced event mesh, event mesh capability for starter or small-volume scenarios; extension apps on BTP consume events from SAP cloud apps while adhering to clean core; business events on SAP Business Accelerator Hub; RAP for custom events
- [Exploring SAP Application Extension Methodology (SAP Learning, BTP solution architect, read 2026-11-27)](https://learning.sap.com/courses/becoming-an-sap-btp-solution-architect/adopting-the-sap-application-extension-methodology): three phases (assess the use case, assess the extension technology, define the target solution); extension tasks mapped to building blocks in a core solution extension domain and a side-by-side extension domain; sample tasks such as UI extension, consume API, consume event, create persistence; SAP Extensibility Explorer and reference architectures as decision aids
