# The BTP account model: global accounts, directories and subaccounts

> Design an SAP BTP account structure for development, test and production, decide who administers each level, and check Calder's model before anyone creates it.

- Course: Orchestrate, Unit 21 · SAP BTP as a platform
- Page: https://erpfde.com/topics/btp-account-model/
- Updated: 2026-11-27
- Reading time: Foundational 8 min, Deep 35 min

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

## Foundational layer

### The 60-second version

Everything a company builds or subscribes to on SAP Business Technology Platform (BTP) lives somewhere in its **account model**: a tree with three kinds of node.

- The **global account** is the contract with SAP. It holds the money side: which services the company may use and how much.
- **Directories** are folders. They group subaccounts by project, team, location or anything else, and can hand out their own share of services and their own administrators.
- **Subaccounts** are where the work happens. Apps run there, services are created there, and each one sits in exactly one region of the world.

Getting the tree right is cheap before anything is built and expensive afterwards. It decides who can change what, where data is stored, which test system an app talks to, and whether finance can tell what each project costs.

### Why it matters to the business

**Isolation.** SAP's administrator guide says subaccounts are for isolation. Users, data, network connections and the trust to a company's login system are all set per subaccount. A development app that shares a subaccount with production can see production's connections.

**Data location.** A subaccount's region is fixed when it is created. If one country's data must stay in that country's region, that needs its own subaccount there.

**Cost visibility.** SAP reports usage per directory and subaccount, not per app. If finance wants AI costs apart from integration costs, the tree or its labels must make that split.

**Administration.** A global account administrator can add services, create subaccounts and, by default, make themselves administrator of any subaccount. Who holds that role is a control question, not an IT detail.

**Example:** Calder Pumpworks, the course's fictional pump maker, now runs integration flows, an order-exception agent and a distributor order-status app on BTP. All three started in one subaccount a partner set up for the integration pilot. When the agent's developers asked for access, they got the integration team's production connections too. That is the moment to design the account model.

### How SAP does it

As of November 2026, SAP documents the model in the [SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/account-model-8ed4a70.md) and gives design advice in the SAP BTP Administrator's Guide ([Setting Up Your Account Model](https://github.com/SAP-docs/btp-best-practices-guide/blob/main/docs/set-up-and-plan/setting-up-your-account-model-2db81f4.md)):

- **Start with three subaccounts.** One global account, with one subaccount each for development, test and production.
- **Grow per project.** Add a set of three for each project or team, plus shared subaccounts for services several teams use, such as SAP Integration Suite. Group them with directories and labels.
- **Add layers for the organization.** Locations or subsidiaries become top-level directories. At that size SAP recommends automating administration, for example with Terraform.
- **One global account where possible.** SAP's checklist recommends consolidating global accounts, with few exceptions: strictly separate bills, a contract with EU access, a China region, or restricting the global administrator's reach. SAP Cloud ALM always comes in its own global account, which can't be merged with the others ([Checklist](https://github.com/SAP-docs/btp-best-practices-guide/blob/main/docs/set-up-and-plan/checklist-drafting-your-account-model-7f1c318.md)).

Tools for running it: the web **cockpit**, the **btp command-line tool**, REST APIs, a Terraform provider, and, for AI-assisted administration, Joule in the cockpit and an MCP server (see the deep layer).

### Calder's account model on one page

Calder's platform team drafted this model on 26 November 2026. It groups work by **workload** at the top and separates **stages** in subaccounts below. All names and numbers are course values.

| Directory | Subaccounts | Connects to | Who administers |
| --- | --- | --- | --- |
| Platform (shared integration) | Integration Dev, Test, Prod | S/4HANA `S4D`, `S4Q`, `S4P` | BTP platform team |
| AI and agents | AI Dev, Test, Prod | `S4D`, `S4Q`, `S4P` | AI platform team, as directory administrators |
| Extensions | Ext Dev, Test, Prod | `S4D`, `S4Q`, `S4P` | BTP platform team |
| (none) | Sandbox | Nothing | BTP platform team |

How to choose a structure:

| If your main question is... | Put this at the top | Calder's answer |
| --- | --- | --- |
| Which team owns and pays for it? | Workload or project directories | Yes: three workloads with different owners |
| Which legal entity or country? | Location or subsidiary directories | Not yet: one region, one company code in BTP |
| Which stage? | Separate subaccounts, never just folders | Dev, Test and Prod subaccounts in every workload |

> **Note** **For functional consultants.** The subaccount decides which S/4HANA system an app reads. Run test cases from the Test subaccount, which connects only to `S4Q`. BTP roles are separate from S/4HANA roles: access to the AI Prod subaccount gives no right in S/4HANA, and the reverse.

### Questions to ask

- How many global accounts do we have, and is there a reason they can't be one?
- Which criterion is at the top of our directory tree, and will it still be true in three years?
- Is every production workload in its own subaccount, separate from development and test?
- Which region is each subaccount in, and which rule decided it?
- Who holds Global Account Administrator, and have we opted out of administrators adding themselves to every subaccount?
- How will finance report cost per project: by directory, by label, or not at all?
- Who owns each directory, and is there a template for requesting a new one?

### Common misconceptions

- **"Spaces are enough to separate development and production."** Cloud Foundry spaces structure work inside one subaccount. Trust, connections and data isolation are set per subaccount.
- **"More global accounts means more control."** SAP recommends one in most cases. Several global accounts split entitlements and make cost reports harder.
- **"The 'Used for production' flag protects a subaccount."** SAP says it changes no configuration. It tells your operators and SAP's which subaccounts are critical, and it blocks a forced deletion. Nothing more.
- **"We can turn beta features off later."** Once enabled on a subaccount, they can't be disabled.
- **"Directories are just folders, so make many."** Each layer adds owners, rules and paths. The tree allows at most five directory levels.

### Key terms

- **Global account:** the contract with SAP; holds entitlements, quotas, directories and subaccounts.
- **Directory:** a folder of subaccounts and other directories; can manage its own entitlements and administrators.
- **Subaccount:** where apps run and services are used; tied to one region.
- **Region:** the data center location of a subaccount, chosen when it is created.
- **Entitlement:** the right to use a service plan.
- **Quota:** how much of a service plan a directory or subaccount may use.
- **Label:** a name with values, such as `Cost object: CP10-910`, used to filter and report.
- **Role collection:** a bundle of roles assigned to users, separate at each account level.

### Check yourself

1. What does SAP mean by a global account?
   - A. A shared login for every BTP administrator in the company
   - B. The realization of the company's contract with SAP
   - C. The production subaccount that all other subaccounts copy
   - D. One data center region where all of a company's apps run

   Answer: B. SAP describes the global account as the realization of a contract. It holds entitlements and quotas and the tree of directories and subaccounts; the work itself happens in subaccounts.

2. Calder's agent developers ask to work in the integration team's production subaccount "just for now". What is the main risk?
   - A. The subaccount will run out of Cloud Foundry spaces for the new agent
   - B. The agent will be billed to a different global account than integration
   - C. They would share production's trust, connections and data access
   - D. Integration Suite stops working when a second team joins its subaccount

   Answer: C. SAP's guide says subaccounts are for isolation: trust, destinations, the Cloud Connector and data access are all per subaccount. Spaces only structure work inside it, so the developers would reach production's connections.

3. A partner suggests enabling beta features on Calder's AI production subaccount to try a new capability. What should a leader know first?
   - A. Beta features are free, so the only question is whether the team has time
   - B. SAP advises against beta in productive accounts, and the setting can't be undone
   - C. Beta features need a second global account with its own contract
   - D. The setting only applies to the trial, so it has no effect in production

   Answer: B. SAP's documentation says beta features shouldn't be used in subaccounts of productive enterprise accounts, and once enabled the setting can't be disabled. Try them in a sandbox instead.

4. Finance wants AI costs reported separately, even though AI apps also run inside other teams' directories. What fits best?
   - A. Create a second global account for AI so it gets its own bill
   - B. Ask SAP to report costs per app instead of per subaccount
   - C. Move every AI app into one Cloud Foundry space in the platform subaccount
   - D. Agree a label such as a cost object and assign it wherever AI runs

   Answer: D. SAP reports usage per directory and subaccount, not per app, and its checklist recommends labels when cost reports cut across the hierarchy. A second global account splits entitlements and is one of the cases SAP says to avoid.

5. Calder later needs an Augsburg app whose employee data must stay in the EU. What does that mean for the account model?
   - A. A separate subaccount in an EU region, because the region is set per subaccount
   - B. A separate global account, because each global account serves one country only
   - C. A new space in the existing US production subaccount with an EU label
   - D. Nothing, because the global account already covers every SAP region

   Answer: A. Each subaccount is tied to one region, chosen when it is created. SAP's checklist keeps separate global accounts for special cases such as separate bills, an EU access contract or a China region; an ordinary EU region needs only a subaccount.

6. Which question should a CIO ask about BTP administrators?
   - A. Whether administrators can use the cockpit and the command line
   - B. Whether administrators have passed an SAP certification this year
   - C. Who holds global administration, and can they add themselves?
   - D. Whether each administrator has their own region to manage

   Answer: C. SAP documents that a global account administrator can grant themselves administration of a subaccount unless the company opts out. That makes the role a control question for the business.

## Deep layer

### Mental model

An account model is three trees laid on top of each other, and you design all three at once:

1. **The contract tree.** Entitlements and quotas flow down from the global account, optionally through a directory, to the subaccount that consumes them.
2. **The isolation tree.** Trust, users, destinations, the Cloud Connector and data stop at the subaccount boundary. Spaces and namespaces below it only structure work.
3. **The reporting tree.** Usage and cost roll up by subaccount and directory, and labels add cuts the tree doesn't have.

Every design question becomes "which tree does this belong to?" Stages belong in the isolation tree, so they are subaccounts. Owners and budgets belong in the contract tree, so they shape directories. Projects that cut across both go into labels.

```mermaid
flowchart TB
  GA[Global account<br/>contract, entitlements] --> D1[Directory<br/>optional, up to 5 levels]
  D1 --> S1[Subaccount Dev<br/>one region]
  D1 --> S2[Subaccount Prod<br/>one region]
  S1 --> O1[Cloud Foundry org<br/>spaces]
  S2 --> O2[Cloud Foundry org<br/>spaces]
  S2 --> K[Kyma clusters<br/>namespaces]
```

### How it works

#### The hierarchy and its limits

As of November 2026, SAP's documentation sets these rules ([Account Model](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/account-model-8ed4a70.md)):

| Level | What it is | Rules that shape the design |
| --- | --- | --- |
| Global account | The contract; manages subaccounts, members, entitlements and quotas | Independent of region and environment |
| Directory | Groups directories and subaccounts | Optional; at most 7 levels from global account to subaccount, so 5 directory levels |
| Subaccount | Runs apps, services and subscriptions | One region each; independent of other subaccounts |
| Cloud Foundry org | Created when Cloud Foundry is enabled | Exactly one per subaccount; spaces inside it |
| Kyma cluster | Kubernetes with Kyma | One or more per subaccount; namespaces inside |

Subaccounts in the same global account are independent of each other. SAP calls this out for security, member management, data management, migration and integration. SAP also states that global accounts and subaccounts are completely independent of user accounts.

#### Directory features

A directory can switch on two optional features ([Create a Directory](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/create-a-directory-b8ef1c4.md)):

- **Entitlement management.** The directory receives a share of the global account's entitlements and quota and hands it to its subaccounts. It can also auto-assign a set amount to each new subaccount.
- **User management.** The directory has its own administrators and viewers. It can only be used together with entitlement management on the same directory.

Only one directory in any path may have either feature. If a middle directory manages entitlements, neither its parent nor its child can. Plan where delegation happens before you build the tree.

#### Entitlements and quotas

An **entitlement** is the right to use a service plan. A **quota** is how much of it ([Entitlements and Quotas](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/entitlements-and-quotas-00aa2c2.md)). Three behaviors matter for design:

- **Fixed or unlimited.** Subscription-based contracts usually have fixed global quotas. Most services in consumption-based contracts (SAP BTPEA, CPEA, Pay-As-You-Go) have unlimited quotas, billed by use. Assigning a numeric quota to a subaccount is then a cost limit you set yourself.
- **Numeric or not.** Some plans are assigned with an amount, often a number of instances. Others, typically SaaS subscriptions, are simply allowed or not.
- **Reserved in directories.** Quota assigned to a directory shows as used even if no subaccount consumes it. Freed quota in a reserving directory stays with that directory.

Inside a subaccount, Cloud Foundry **space quota plans** can stop one space from using all of the subaccount's quota. They limit; they don't grant.

#### Subaccount properties you can't change casually

When you create a subaccount, you set ([Create a Subaccount](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/create-a-subaccount-05280a1.md)):

- **Region.** Where apps, data and services are hosted. Pick it per subaccount; it doesn't have to match where users are.
- **Subdomain.** Up to 63 characters of letters, digits and hyphens, not starting or ending with a hyphen. It must be unique across all subaccounts in the region, ignoring case. It becomes part of the URLs of subscribed apps.
- **Used for production.** A flag for your operators and SAP's. It changes no configuration, though SAP notes that such a subaccount can't be force deleted.
- **Enable beta features.** SAP says not to use beta features in productive enterprise accounts. Once enabled, it can't be disabled.
- **Labels.** Name and values for filtering and reports.

Later, SAP lets you edit the display name, description, parent directory, the production flag, labels and the beta setting ([Change Subaccount Details](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/change-subaccount-details-567d4a8.md)). Region and subdomain are not on that list, so treat them as final.

In AWS, Azure and Google Cloud regions, SAP also lets you create a subaccount from an existing one, copying its properties, labels and service plan assignments. That helps keep stage subaccounts alike.

#### Who administers what

Role collections exist separately at each level: one in the global account doesn't exist in its subaccounts ([Role Collections](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/role-collections-and-roles-in-global-accounts-directories-and-subaccounts-0039cf0.md)). The defaults include:

| Role collection | Scope | Typical holder at Calder |
| --- | --- | --- |
| Global Account Administrator | Subaccounts, entitlements, role collections, identity providers, regions | Two BTP platform administrators |
| Global Account Viewer | Read the same, including usage | Group controller, for cost |
| Directory Administrator / Viewer | One directory with user management | AI platform team for *AI and agents* |
| Subaccount Administrator / Viewer | One subaccount | Workload leads |
| Destination, Cloud Connector, Subaccount Service Administrator | Narrower subaccount tasks | Integration developers |

A global account administrator doesn't automatically administer subaccounts, but can grant themselves that right with **Add Me as Admin**. SAP lets a company opt out of this by a support request ([Add Members to Your Subaccount](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/add-members-to-your-subaccount-1e1b7b6.md)). Whoever creates a subaccount becomes its administrator.

Cloud Foundry roles (org manager, space developer and so on) are a third layer, set per org and space. Unit 21's [security model topic](https://erpfde.com/topics/btp-security-model/) covers all three layers.

#### Labels

Labels are names with up to 10 values each. The cockpit allows 10 labels per entity. Directories, subaccounts, subscriptions, service instances and environment instances can carry them. Subaccounts show the labels of every directory above them as inherited labels, and filters match them. Names and values are case-sensitive, so `Owner team` and `Owner Team` are two labels. SAP recommends avoiding such variants.

#### Subaccounts or spaces

SAP's guide compares the two ([Subaccounts or Spaces/Namespaces?](https://github.com/SAP-docs/btp-best-practices-guide/blob/main/docs/set-up-and-plan/subaccounts-or-spaces-namespaces-4cb5276.md)):

| Need | Subaccount | Cloud Foundry space |
| --- | --- | --- |
| Separate data access, connectivity, ingress | Yes | No |
| Own trust to an identity provider | Yes | No |
| Own destinations and Cloud Connector | Yes | No |
| Grant roles | Yes | Yes |
| See cost and usage in the cockpit | Yes | Per space, not per app |
| Limit resources | Quotas (required) | Space quotas |

The guide recommends at least two subaccounts for staged development, with spaces for each app, team or project inside. It also notes that exact billing exists only per global account; per-subaccount costs in a consumption contract are approximate.

#### Costs and budgets

Global account administrators and viewers see usage on the **Costs and Usage** page. In consumption-based global accounts, SAP offers **budgets**: up to 30 active budgets per global account, scoped to subaccounts and service plans, with email alerts where available ([Managing Budgets](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/managing-budgets-in-your-global-account-e115d5f.md)). A budget alerts; it doesn't stop usage. Commercial models and cost are covered in [BTP commercial models and cost control](https://erpfde.com/topics/btp-commercial-models-and-cost/).

#### Naming

SAP's naming advice ([Naming and Directory Templates](https://github.com/SAP-docs/btp-best-practices-guide/blob/main/docs/set-up-and-plan/naming-and-directory-templates-5302ea4.md)):

- Use the same pattern for a subaccount, its subdomain and its Cloud Foundry org. Include a company abbreviation in subdomains and org names.
- Use lowercase letters and hyphens; reuse space names across stages.
- Keep names short. Cloud Foundry builds routes like `{org}-{space}-{app}` as one DNS label, which allows 63 characters.
- Put no personal data in names.
- Give every new directory at least two owners, a description and a cost center.

### Build it yourself

**Before you start:** finish [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/). The optional Step 8 also uses your BTP trial from [Set up for Unit 18](https://erpfde.com/topics/set-up-for-unit-18/) and the btp command-line tool from [Set up for Unit 21](https://erpfde.com/topics/set-up-for-unit-21/). Everything else runs without an account.

You will turn Calder's draft account model into a file, draw it, check it against SAP's limits and Calder's rules, generate the commands that would build it, and write the deliverable: `unit21/calder_account_model.md`. The check finds three errors in the draft. You fix them in the exercise.

If you did the exercise in [Set up for Unit 21](https://erpfde.com/topics/set-up-for-unit-21/), you already drafted a flat first version in `unit21/calder_accounts_draft.json`: three stage subaccounts and an EU production subaccount, with no directories, owners or reasons. This topic grows that sketch into a model with workloads, administrators, labels and rules. Keep the old file for comparison; the new script doesn't read it.

```mermaid
flowchart LR
  I[--init] --> J[calder_account_model.json<br/>the draft]
  J --> T[--tree]
  J --> L[--labels]
  J --> C[--check<br/>R01-R14]
  J --> K[--commands<br/>cockpit + btp]
  J --> W[--write]
  W --> M[calder_account_model.md<br/>the deliverable]
```

> **Note** **New words.** A **script** is a text file of Python instructions. The **terminal** is the window where you type commands. A **command-line option** is an extra word after the command, such as `--tree`, that changes what the script does. **JSON** is a text format for structured data: names in quotes, values after a colon, lists in square brackets. An **exit code** is the number a program returns when it ends: 0 means "all fine", anything else means "needs attention".

The script talks to no SAP system. The model is a file you can review, version in Git and hand to the people who build the real account.

#### What you need

- The course folder `orchestrate-course` with its `.venv`.
- No account and no key for Steps 1 to 7. The script uses only Python's built-in modules, so `requirements.txt` doesn't change.
- For the optional Step 8: your BTP trial and the btp CLI. Free.
- Time: about 30 minutes.

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

1. Open VS Code, then **File > Open Folder** and choose `orchestrate-course`.
2. Open a terminal with **Terminal > New Terminal**.
3. Turn on the virtual environment:
   - **Windows (PowerShell):**

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

   - **macOS / Linux:**

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

4. Make the `unit21` folder if you don't have it yet (the command does nothing if it exists):
   - **Windows (PowerShell):**

     ```powershell
     New-Item -ItemType Directory -Force unit21
     ```

   - **macOS / Linux:**

     ```bash
     mkdir -p unit21
     ```

You should see `(.venv)` at the start of the prompt.

#### Step 2: Create the script

1. In VS Code, create the file `unit21/account_model.py`.
2. Paste the code below and save.

```python
"""Calder's SAP BTP account model: draw it, check it, and turn it into commands.

Usage (run from the orchestrate-course folder):
  python unit21/account_model.py --init        write the draft model to unit21/calder_account_model.json
  python unit21/account_model.py --tree        draw the global account, directories and subaccounts
  python unit21/account_model.py --labels      group subaccounts by label value (with inherited labels)
  python unit21/account_model.py --check       check the model against SAP's limits and Calder's rules
  python unit21/account_model.py --commands    print the cockpit steps and btp commands to build it
  python unit21/account_model.py --write       write unit21/calder_account_model.md (the deliverable)

Options:
  --file PATH                  read another model file in the same shape
  --shell posix|powershell     quoting for --commands (default: posix = macOS and Linux)
  --prefix TEXT                put TEXT- in front of every subdomain (for a shared trial region)
  --force                      let --init overwrite an existing model file

Built-in modules only. No account, no network. Calder Pumpworks is fictional; personnel
numbers, cost objects, mailboxes and rules R06-R14 are course labels, not SAP values.
"""
import argparse
import json
import re
import sys
from pathlib import Path

MODEL_FILE = Path("unit21/calder_account_model.json")
REPORT_FILE = Path("unit21/calder_account_model.md")
FENCE = "`" * 3       # a Markdown code fence, written so this file can sit inside one


# SAP limits, as documented in the SAP BTP documentation (read 2026-11-26).
MAX_LEVELS = 7          # global account + up to 5 directory levels + subaccount
MAX_LABELS = 10         # labels per entity in the cockpit
MAX_VALUES = 10         # values per label
MAX_DNS_LABEL = 63      # one hostname segment, e.g. {org}-{space}-{app}
SUBDOMAIN_RE = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$")

STAGE_LETTER = {"dev": "D", "test": "Q", "prod": "P"}  # course rule: last letter of a system ID


def lab(stage, team, cost, contact, **more):
    labels = {"Stage": [stage], "Owner team": [team], "Cost object": [cost], "Contacts": [contact]}
    labels.update(more)
    return labels


def draft_model():
    """The platform team's draft of 2026-11-26. It has three planted errors and one warning."""
    sa = []

    def sub(name, parent, stage, subdomain, backends, admins, labels, routes=(), ent=None,
            prod=None, beta=False, region="us10"):
        sa.append({
            "type": "subaccount", "name": name, "parent": parent, "stage": stage,
            "region": region, "subdomain": subdomain,
            "used_for_production": (stage == "prod") if prod is None else prod,
            "beta_enabled": beta, "admins": admins, "backends": backends,
            "labels": labels, "routes": [{"space": s, "app": a} for s, a in routes],
            "entitlements": ent or {},
        })

    plat, ai, ext = "Platform", "AI and agents", "Extensions"
    pmail, aimail, xmail = ("btp-platform@calder-pumpworks.example",
                            "ai-platform@calder-pumpworks.example",
                            "apps-team@calder-pumpworks.example")
    two = ["00100316", "00100317"]
    sub("Integration Dev", plat, "dev", "calder-int-dev", ["S4D"], ["00100288"],
        lab("Dev", "Integration", "CP10-910", pmail))
    sub("Integration Test", plat, "test", "calder-int-test", ["S4Q"], ["00100288"],
        lab("Test", "Integration", "CP10-910", pmail))
    sub("Integration Prod", plat, "prod", "calder-int-prod", ["S4P"], ["00100292", "00100316"],
        lab("Prod", "Integration", "CP10-910", pmail))
    sub("AI Dev", ai, "dev", "calder-ai-dev", ["S4D"], ["00100288"],
        {"Stage": ["Dev"], "Process": ["o2c", "p2p"]},
        routes=[("agents", "order-exc-agent")], ent={"SAP AI Core/extended": 1})
    sub("AI Test", ai, "test", "calder-ai-test", ["S4Q"], ["00100288"],
        {"Stage": ["Test"], "Process": ["o2c", "p2p"]},
        routes=[("agents", "order-exc-agent")], ent={"SAP AI Core/extended": 1})
    sub("AI Prod", ai, "prod", "calder-ai-prod", ["S4P"], ["00100290", "00100316"],
        {"Stage": ["Prod"], "Process": ["o2c", "p2p"]},
        routes=[("agents", "order-exc-agent")], ent={"SAP AI Core/extended": 1},
        beta=True)                                                      # planted error R05
    sub("Ext Dev", ext, "dev", "calder-ext-dev", ["S4D"], ["00100288"],
        lab("Dev", "Apps", "CP10-910", xmail),
        routes=[("distributor-portal", "distributor-order-status")])
    sub("Ext Test", ext, "test", "calder-ext-test", ["S4P"], ["00100288"],   # planted error R08
        lab("Test", "Apps", "CP10-910", xmail),
        routes=[("distributor-portal", "distributor-order-status")])
    sub("Ext Prod", ext, "prod", "calder-pumpworks-extensions-prod", ["S4P"], two,  # planted R12
        lab("Prod", "Apps", "CP10-910", xmail),
        routes=[("distributor-portal", "distributor-order-status")])
    sub("Sandbox", None, "sandbox", "calder-sandbox", [], two,          # warning: no Expires label
        lab("Sandbox", "BTP platform", "CP10-910", pmail), beta=True)

    dirs = [
        {"type": "directory", "name": plat, "parent": None, "features": [], "admins": [],
         "labels": {}, "entitlements": {}},
        {"type": "directory", "name": ai, "parent": None, "features": ["entitlements", "users"],
         "admins": ["00100290", "00100288"],
         "labels": {"Owner team": ["AI platform"], "Cost object": ["CP10-920"],
                    "Contacts": [aimail]},
         "entitlements": {"SAP AI Core/extended": 3}},
        {"type": "directory", "name": ext, "parent": None, "features": [], "admins": [],
         "labels": {}, "entitlements": {}},
    ]
    return {
        "as_of": "2026-11-26",
        "global_account": {
            "name": "Calder Pumpworks",
            "commercial_model": "consumption-based (course assumption)",
            "admins": two, "viewers": ["00100280"],
        },
        "standards": {
            "default_region": "us10",
            "required_labels": ["Stage", "Owner team", "Cost object", "Contacts"],
            "mail_domain": "calder-pumpworks.example",
        },
        "nodes": dirs + sa,
    }


# ---------------------------------------------------------------- loading and helpers

def load(path):
    if not path.exists():
        sys.exit(f"No model file {path}. Run: python unit21/account_model.py --init")
    try:
        model = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as e:
        sys.exit(f"{path} is not valid JSON (line {e.lineno}, column {e.colno}): {e.msg}")
    names = [n["name"] for n in model["nodes"]]
    dup = {n for n in names if names.count(n) > 1}
    if dup:
        sys.exit(f"Names must be unique in the model; repeated: {', '.join(sorted(dup))}")
    for n in model["nodes"]:
        if n["parent"] is not None and n["parent"] not in names:
            sys.exit(f"{n['name']}: parent '{n['parent']}' is not in the model")
    return model


def index(model):
    return {n["name"]: n for n in model["nodes"]}


def path_of(node, by_name):
    """Directories from the top down to (not including) the node."""
    out, p = [], node["parent"]
    while p is not None:
        out.insert(0, by_name[p])
        p = by_name[p]["parent"]
    return out


def effective_labels(node, by_name):
    """Labels of every directory above the node, then its own (SAP shows these as inherited)."""
    merged = {}
    for d in path_of(node, by_name) + [node]:
        for k, v in d.get("labels", {}).items():
            merged[k] = list(v)
    return merged


def subaccounts(model):
    return [n for n in model["nodes"] if n["type"] == "subaccount"]


def directories(model):
    return [n for n in model["nodes"] if n["type"] == "directory"]


def subdomain(sa, prefix):
    return f"{prefix}-{sa['subdomain']}" if prefix else sa["subdomain"]


# ---------------------------------------------------------------- the checks

def check(model, prefix=""):
    by = index(model)
    std = model["standards"]
    errors, warnings = [], []

    def err(code, who, text):
        errors.append((code, who, text))

    def warn(code, who, text):
        warnings.append((code, who, text))

    # R01 depth, R02 directory features (SAP limits)
    for n in model["nodes"]:
        levels = 1 + len(path_of(n, by)) + 1
        if n["type"] == "subaccount" and levels > MAX_LEVELS:
            err("R01", n["name"], f"{levels} levels from the global account; SAP allows {MAX_LEVELS}")
        if n["type"] == "directory":
            f = n.get("features", [])
            if "users" in f and "entitlements" not in f:
                err("R02", n["name"], "user management needs entitlement management on the same directory")
            if f:
                for d in path_of(n, by):
                    if d.get("features"):
                        err("R02", n["name"], f"'{d['name']}' above it already manages entitlements "
                                              "or users; only one directory per path may")
    # R03 subdomain syntax and uniqueness per region
    seen = {}
    for sa in subaccounts(model):
        sd = subdomain(sa, prefix)
        if not SUBDOMAIN_RE.match(sd):
            err("R03", sa["name"], f"subdomain '{sd}': letters, digits and inner hyphens only, "
                                   f"at most {MAX_DNS_LABEL} characters")
        key = (sa["region"], sd.lower())
        if key in seen:
            err("R03", sa["name"], f"subdomain '{sd}' already used by {seen[key]} in {sa['region']}")
        seen[key] = sa["name"]
    # R04 label counts (own labels)
    for n in model["nodes"]:
        labels = n.get("labels", {})
        if len(labels) > MAX_LABELS:
            err("R04", n["name"], f"{len(labels)} labels; the cockpit allows {MAX_LABELS} per entity")
        for k, v in labels.items():
            if len(v) > MAX_VALUES:
                err("R04", n["name"], f"label '{k}' has {len(v)} values; at most {MAX_VALUES}")
    all_names = {}
    for n in model["nodes"]:
        for k in n.get("labels", {}):
            all_names.setdefault(k.lower(), set()).add(k)
    for variants in all_names.values():
        if len(variants) > 1:
            warn("R04", "labels", f"same label in different casing: {', '.join(sorted(variants))}")

    for sa in subaccounts(model):
        name, stage = sa["name"], sa["stage"]
        # R05 beta in production (SAP caution; the setting can't be switched off later)
        if sa["beta_enabled"] and (stage == "prod" or sa["used_for_production"]):
            err("R05", name, "beta features enabled in a production subaccount; "
                             "once enabled it can't be disabled, so fix it before you create it")
        # R06 the production flag matches the stage (course rule)
        if sa["used_for_production"] != (stage == "prod"):
            err("R06", name, f"'Used for production' is {sa['used_for_production']} on a {stage} subaccount")
        # R08 backends match the stage (course rule: S4D/S4Q/S4P, ECD/ECQ/ECP)
        if stage in STAGE_LETTER:
            for b in sa["backends"]:
                if not b.endswith(STAGE_LETTER[stage]):
                    err("R08", name, f"{stage} subaccount connects to {b}; it needs the "
                                     f"{stage} system (ID ending in {STAGE_LETTER[stage]})")
        # R14 the sandbox never connects to a Calder system (course rule)
        if stage == "sandbox":
            if sa["backends"]:
                err("R14", name, f"sandbox connects to {', '.join(sa['backends'])}; it must connect to none")
            if "Expires" not in effective_labels(sa, by):
                warn("R14", name, "sandbox without an 'Expires' label; nobody will know when to clean it up")
        # R09 required labels, own or inherited; contacts are team mailboxes (course rule)
        eff = effective_labels(sa, by)
        missing = [k for k in std["required_labels"] if not eff.get(k)]
        if missing:
            err("R09", name, f"missing label(s): {', '.join(missing)}")
        for c in eff.get("Contacts", []):
            local, _, domain = c.partition("@")
            if domain != std["mail_domain"] or "." in local:
                err("R09", name, f"contact '{c}' is not a team mailbox on {std['mail_domain']}")
        # R10 two administrators on production (course rule)
        if stage == "prod" and len(sa["admins"]) < 2:
            err("R10", name, "a production subaccount needs at least two administrators")
        # R11 a region other than the default needs a recorded reason (course rule)
        if sa["region"] != std["default_region"] and not eff.get("Residency"):
            err("R11", name, f"region {sa['region']} without a 'Residency' label saying why")
        # R12 route length: {org}-{space}-{app} is one DNS label (org named like the subdomain)
        for r in sa.get("routes", []):
            host = f"{subdomain(sa, prefix)}-{r['space']}-{r['app']}"
            if len(host) > MAX_DNS_LABEL:
                err("R12", name, f"route '{host}' is {len(host)} characters; one DNS label "
                                 f"allows {MAX_DNS_LABEL}")

    for d in directories(model):
        # R07 a workload with production also has a non-production subaccount (course rule)
        kids = [s for s in subaccounts(model) if s["parent"] == d["name"]]
        stages = {s["stage"] for s in kids}
        if "prod" in stages and not stages & {"dev", "test"}:
            err("R07", d["name"], "production without a development or test subaccount")
        # R10 user-managed directories have two administrators (course rule)
        if "users" in d.get("features", []) and len(d.get("admins", [])) < 2:
            err("R10", d["name"], "a directory that manages its own users needs two administrators")
        # R13 entitlements reserved by the directory cover its subaccounts (SAP behavior)
        if "entitlements" in d.get("features", []):
            used = {}
            for s in kids:
                for plan, amount in s.get("entitlements", {}).items():
                    used[plan] = used.get(plan, 0) + amount
            for plan, amount in used.items():
                reserved = d["entitlements"].get(plan, 0)
                if amount > reserved:
                    err("R13", d["name"], f"{plan}: subaccounts need {amount}, directory reserves {reserved}")
    return errors, warnings


# ---------------------------------------------------------------- views

def tree(model, prefix=""):
    by = index(model)
    ga = model["global_account"]
    lines = [f"{ga['name']} (global account, {ga['commercial_model']})"]

    def walk(parent, indent):
        kids = [n for n in model["nodes"] if n["parent"] == parent]
        kids.sort(key=lambda n: (n["type"] != "directory", n["name"]))
        for i, n in enumerate(kids):
            last = i == len(kids) - 1
            branch = "`-- " if last else "|-- "
            if n["type"] == "directory":
                feats = "+".join(n.get("features", [])) or "no features"
                lines.append(f"{indent}{branch}[{n['name']}] directory, {feats}")
                walk(n["name"], indent + ("    " if last else "|   "))
            else:
                flags = []
                if n["used_for_production"]:
                    flags.append("PROD")
                if n["beta_enabled"]:
                    flags.append("BETA")
                back = ",".join(n["backends"]) or "none"
                lines.append(f"{indent}{branch}{n['name']:<17}{n['region']:<6}"
                             f"{subdomain(n, prefix):<34}-> {back:<5} {' '.join(flags)}".rstrip())
    walk(None, "")
    return "\n".join(lines)


def labels_report(model):
    by = index(model)
    out = []
    for key in model["standards"]["required_labels"] + ["Process", "Residency"]:
        groups = {}
        for sa in subaccounts(model):
            for v in effective_labels(sa, by).get(key, ["(none)"]):
                groups.setdefault(v, []).append(sa["name"])
        if key not in model["standards"]["required_labels"]:
            groups.pop("(none)", None)
        if not groups:
            continue
        out.append(f"{key}:")
        for v in sorted(groups):
            out.append(f"  {v:<40} {', '.join(groups[v])}")
    return "\n".join(out)


def commands(model, shell, prefix):
    out = ["# Build order: directories first (cockpit), then subaccounts (btp CLI).",
           "# Each subaccount command needs the ID of its directory: copy it from the",
           "# directory's overview page in the cockpit, or from: btp get accounts/global-account",
           ""]
    for d in directories(model):
        feats = d.get("features", [])
        opts = []
        if "entitlements" in feats:
            opts.append("Enable entitlement management")
        if "users" in feats:
            opts.append("Enable user management")
        parent = d["parent"] or "the global account"
        if d.get("labels"):
            opts.append("Labels " + json.dumps(d["labels"], separators=(",", ":")))
        out.append(f"# Cockpit: Account Explorer > Create > Directory > '{d['name']}', parent {parent}"
                   + (f"; under Advanced: {'; '.join(opts)}" if opts else ""))
    out.append("")
    for sa in subaccounts(model):
        own = sa.get("labels", {})
        js = json.dumps(own, separators=(",", ":"))
        if shell == "powershell":
            js = js.replace('"', '\\"')      # PowerShell: escape the inner quotes, as SAP shows
        labels = f"'{js}'"
        parts = [f'btp create accounts/subaccount --display-name "{sa["name"]}"',
                 f"--region {sa['region']}", f"--subdomain {subdomain(sa, prefix)}"]
        if sa["parent"]:
            parts.append(f'--directory "<ID of {sa["parent"]}>"')
        if own:
            parts.append(f"--labels {labels}")
        out.append(" ".join(parts))
        notes = []
        if sa["used_for_production"]:
            notes.append("then set 'Used for production' (cockpit: edit the subaccount)")
        if sa["beta_enabled"]:
            notes.append("beta features: decide in the cockpit; this can't be undone")
        for n in notes:
            out.append(f"#   {n}")
    return "\n".join(out)


def write_report(model, path, errors, warnings):
    ga = model["global_account"]
    rows = []
    for sa in subaccounts(model):
        rows.append(f"| {sa['name']} | {sa['parent'] or '(global account)'} | {sa['stage']} | "
                    f"{sa['region']} | `{sa['subdomain']}` | {'yes' if sa['used_for_production'] else 'no'} | "
                    f"{'yes' if sa['beta_enabled'] else 'no'} | {', '.join(sa['backends']) or 'none'} | "
                    f"{', '.join(sa['admins'])} |")
    drows = []
    for d in directories(model):
        ents = ", ".join(f"{k}: {v}" for k, v in d.get("entitlements", {}).items()) or "from the global account"
        drows.append(f"| {d['name']} | {', '.join(d.get('features', [])) or 'none'} | "
                     f"{', '.join(d.get('admins', [])) or '(global account admins)'} | {ents} |")
    issues = "\n".join(f"- {c} {w}: {t}" for c, w, t in errors) or "- none"
    warns = "\n".join(f"- {c} {w}: {t}" for c, w, t in warnings) or "- none"
    text = f"""# Calder Pumpworks: SAP BTP account model

As of {model['as_of']}. Calder Pumpworks is a fictional company; every value here is a course value.

### Global account

- Name: {ga['name']}
- Commercial model: {ga['commercial_model']}
- Global account administrators: {', '.join(ga['admins'])}
- Global account viewers: {', '.join(ga['viewers'])}
- Default region: {model['standards']['default_region']}

### Structure

{FENCE}text
{tree(model)}
{FENCE}

### Directories

| Directory | Features | Administrators | Entitlements reserved |
| --- | --- | --- | --- |
{chr(10).join(drows)}

### Subaccounts

| Subaccount | Directory | Stage | Region | Subdomain | Production | Beta | Connects to | Administrators |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
{chr(10).join(rows)}

### Labels (own and inherited)

{FENCE}text
{labels_report(model)}
{FENCE}

### Check result

Errors:

{issues}

Warnings:

{warns}

### Decision record

- **Context:** (why Calder needs an account model now)
- **Options:** (a) one subaccount with a space per stage; (b) stage directories at the top; (c) workload directories with stage subaccounts
- **Decision:** (your choice and reason)
- **Consequences:** (what gets easier, what gets harder)

### Open questions

- Keep or opt out of "Add Me as Admin" for global account administrators?
- Which budgets, for which subaccounts and plans?
"""
    path.write_text(text, encoding="utf-8")


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

def main():
    p = argparse.ArgumentParser(description="Calder's SAP BTP account model")
    p.add_argument("--init", action="store_true")
    p.add_argument("--force", action="store_true")
    p.add_argument("--tree", action="store_true")
    p.add_argument("--labels", action="store_true")
    p.add_argument("--check", action="store_true")
    p.add_argument("--commands", action="store_true")
    p.add_argument("--write", action="store_true")
    p.add_argument("--file", default=str(MODEL_FILE))
    p.add_argument("--shell", choices=["posix", "powershell"], default="posix")
    p.add_argument("--prefix", default="")
    a = p.parse_args()
    path = Path(a.file)

    if a.init:
        if path.exists() and not a.force:
            sys.exit(f"{path} exists; your edits would be lost. Add --force to start over.")
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(json.dumps(draft_model(), indent=2) + "\n", encoding="utf-8")
        print(f"Wrote {path}: the draft model with {len(draft_model()['nodes'])} nodes.")
        return 0
    if not any([a.tree, a.labels, a.check, a.commands, a.write]):
        p.print_help()
        return 0

    model = load(path)
    if a.prefix and not re.match(r"^[a-z0-9]{2,8}$", a.prefix):
        sys.exit("--prefix: 2 to 8 lowercase letters or digits, for example your initials")
    code = 0
    if a.tree:
        print(tree(model, a.prefix))
    if a.labels:
        print(labels_report(model))
    if a.commands:
        print(commands(model, a.shell, a.prefix))
    errors, warnings = check(model, a.prefix)
    if a.check:
        n_sa = len(subaccounts(model))
        n_dir = len(directories(model))
        print(f"Checked {n_sa} subaccounts in {n_dir} directories.")
        for c, w, t in errors:
            print(f"ERROR {c} {w}: {t}")
        for c, w, t in warnings:
            print(f"WARN  {c} {w}: {t}")
        print(f"{len(errors)} error(s), {len(warnings)} warning(s)")
        code = 1 if errors else 0
    if a.write:
        out = REPORT_FILE if path == MODEL_FILE else path.with_suffix(".md")
        write_report(model, out, errors, warnings)
        print(f"Wrote {out}")
    return code


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

#### Step 3: Write the draft model

1. Run:

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

2. You should see:

   ```text
   Wrote unit21/calder_account_model.json: the draft model with 13 nodes.
   ```

3. Open `unit21/calder_account_model.json` in VS Code and scroll through it. Each entry under `nodes` is a directory or a subaccount. `parent` says where it hangs; `null` means directly under the global account.

The file is now yours. Running `--init` again refuses to overwrite it unless you add `--force`.

#### Step 4: Draw the tree

1. Run:

   ```bash
   python unit21/account_model.py --tree
   ```

2. You should see:

   ```text
   Calder Pumpworks (global account, consumption-based (course assumption))
   |-- [AI and agents] directory, entitlements+users
   |   |-- AI Dev           us10  calder-ai-dev                     -> S4D
   |   |-- AI Prod          us10  calder-ai-prod                    -> S4P   PROD BETA
   |   `-- AI Test          us10  calder-ai-test                    -> S4Q
   |-- [Extensions] directory, no features
   |   |-- Ext Dev          us10  calder-ext-dev                    -> S4D
   |   |-- Ext Prod         us10  calder-pumpworks-extensions-prod  -> S4P   PROD
   |   `-- Ext Test         us10  calder-ext-test                   -> S4P
   |-- [Platform] directory, no features
   |   |-- Integration Dev  us10  calder-int-dev                    -> S4D
   |   |-- Integration Prod us10  calder-int-prod                   -> S4P   PROD
   |   `-- Integration Test us10  calder-int-test                   -> S4Q
   `-- Sandbox          us10  calder-sandbox                    -> none  BETA
   ```

Read each line as: name, region, subdomain, the S/4HANA system it connects to, and flags. Two lines already look wrong. Which ones?

#### Step 5: Group by label

1. Run:

   ```bash
   python unit21/account_model.py --labels
   ```

2. The first lines show the stages; further down you should see:

   ```text
   Owner team:
     AI platform                              AI Dev, AI Test, AI Prod
     Apps                                     Ext Dev, Ext Test, Ext Prod
     BTP platform                             Sandbox
     Integration                              Integration Dev, Integration Test, Integration Prod
   Cost object:
     CP10-910                                 Integration Dev, Integration Test, Integration Prod, Ext Dev, Ext Test, Ext Prod, Sandbox
     CP10-920                                 AI Dev, AI Test, AI Prod
   ```

The AI subaccounts don't carry `Owner team` or `Cost object` themselves. They inherit them from the *AI and agents* directory, the way the cockpit shows inherited labels. This is the report finance asked for: cost per owner team and cost object.

#### Step 6: Check the model

1. Run:

   ```bash
   python unit21/account_model.py --check
   ```

2. You should see:

   ```text
   Checked 10 subaccounts in 3 directories.
   ERROR R05 AI Prod: beta features enabled in a production subaccount; once enabled it can't be disabled, so fix it before you create it
   ERROR R08 Ext Test: test subaccount connects to S4P; it needs the test system (ID ending in Q)
   ERROR R12 Ext Prod: route 'calder-pumpworks-extensions-prod-distributor-portal-distributor-order-status' is 76 characters; one DNS label allows 63
   WARN  R14 Sandbox: sandbox without an 'Expires' label; nobody will know when to clean it up
   3 error(s), 1 warning(s)
   ```

3. The exit code is 1 because there are errors. That is expected: the exercise fixes them.

The rules come from two places:

| Rule | Checks | Source |
| --- | --- | --- |
| R01 | At most 7 levels from global account to subaccount | SAP limit |
| R02 | User management only with entitlement management; one such directory per path | SAP limit |
| R03 | Subdomain syntax, 63 characters, unique per region | SAP limit |
| R04 | 10 labels per entity, 10 values per label; casing variants warned | SAP limit and advice |
| R05 | No beta features in production | SAP advice |
| R06 | *Used for production* set exactly on production subaccounts | Course rule |
| R07 | A workload with production also has development or test | Course rule, after SAP's staged model |
| R08 | Each stage connects only to the same stage (`S4D`/`S4Q`/`S4P`) | Course rule |
| R09 | Required labels present; contacts are team mailboxes | Course rule (no personal data) |
| R10 | Two administrators on production and on user-managed directories | Course rule, after SAP's two-owner template |
| R11 | A region other than `us10` needs a `Residency` label | Course rule |
| R12 | `{org}-{space}-{app}` fits one DNS label | SAP naming advice |
| R13 | Subaccounts use no more than their directory reserves | SAP behavior |
| R14 | The sandbox connects to nothing and has an expiry | Course rule |

#### Step 7: Generate the build commands and write the deliverable

1. Print what an administrator would run, for your shell:
   - **Windows (PowerShell):**

     ```powershell
     python unit21/account_model.py --commands --shell powershell
     ```

   - **macOS / Linux:**

     ```bash
     python unit21/account_model.py --commands
     ```

2. The output starts with the directories, which you create in the cockpit, then one btp command per subaccount. On macOS or Linux the first one reads:

   ```text
   btp create accounts/subaccount --display-name "Integration Dev" --region us10 --subdomain calder-int-dev --directory "<ID of Platform>" --labels '{"Stage":["Dev"],"Owner team":["Integration"],"Cost object":["CP10-910"],"Contacts":["btp-platform@calder-pumpworks.example"]}'
   ```

   In PowerShell the inner quotes of `--labels` are escaped with a backslash, as SAP's documentation shows for that shell ([Passing JSON Parameters](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/passing-json-parameters-on-the-command-line-899fe34.md)).

3. Write the deliverable:

   ```bash
   python unit21/account_model.py --write
   ```

4. You should see `Wrote unit21/calder_account_model.md`. Open it: it holds the tree, a table of directories and subaccounts, the label report, the check result and an empty decision record.

> **Warning** Don't run the generated commands against a company global account. They are a plan for review. The `<ID of ...>` placeholders won't work until someone fills in real directory IDs.

#### Step 8 (optional): Build one directory in your trial

This step uses your own free trial. SAP's trial documentation says you can create directories there.

1. Open your trial cockpit and choose your global account.
2. In the left menu, open **Account Explorer**.
3. Choose **Create > Directory**.
4. Enter the display name `AI and agents`, keep the global account as the parent, and leave **Enable entitlement management** and **Enable user management** under **Advanced** off.
5. Under **Advanced > Labels**, add the label `Owner team` with the value `AI platform`. Choose **Create**.
6. In the terminal, log in and list the structure:

   ```bash
   btp login --sso
   btp get accounts/global-account
   ```

7. The output lists your global account with the new directory and your existing trial subaccount. Labels can differ in layout between btp CLI versions.
8. To tidy up, delete the directory in the **Account Explorer**. SAP only lets you delete a directory that holds no subaccounts or directories.

> **Note** We tested Steps 1 to 7 in our environment. SAP's servers weren't reachable from it, so Step 8 follows SAP's documentation and wasn't run against a live trial. Menu labels in the cockpit change from time to time; pick the closest match.

#### What the code does

| Part | What it does |
| --- | --- |
| `MAX_LEVELS`, `MAX_LABELS`, `MAX_VALUES`, `MAX_DNS_LABEL`, `SUBDOMAIN_RE` | SAP's documented limits |
| `STAGE_LETTER` | Course rule: the last letter of a system ID names its stage (`S4D`, `ECQ`, `S4P`) |
| `draft_model()` | Calder's draft: three directories, ten subaccounts, three planted errors |
| `load()` | Reads the JSON file and stops on bad JSON, repeated names or unknown parents |
| `path_of()`, `effective_labels()` | Walks up the tree; merges directory labels into the subaccount's, like inherited labels |
| `check()` | Rules R01 to R14; returns errors and warnings |
| `tree()`, `labels_report()` | The two views from Steps 4 and 5 |
| `commands()` | Cockpit steps for directories, btp commands for subaccounts, quoted for your shell |
| `write_report()` | Writes the deliverable with an empty decision record |
| `--prefix` | Adds your initials to every subdomain, since subdomains must be unique in a region |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python: command not found` or `'python' is not recognized` | Python isn't on the path, or the virtual environment is off | Turn on `.venv` (Step 1); on macOS or Linux try `python3` |
| `No model file unit21/calder_account_model.json` | Step 3 wasn't run, or you are in the wrong folder | Run `--init` from the `orchestrate-course` folder |
| `... exists; your edits would be lost` | You ran `--init` again | Keep your file, or add `--force` to start over |
| `... is not valid JSON (line 41, column 7)` | An edit left a missing comma or quote | Open the file at that line; VS Code underlines the mistake in red |
| `parent 'Augsburg' is not in the model` | A subaccount names a directory that doesn't exist | Add the directory, or fix the spelling (names are case-sensitive) |
| `ModuleNotFoundError` | A line of the script was mistyped | The script imports only built-in modules; compare the `import` lines |
| `--check` ends with `3 error(s)` and exit code 1 | Expected before the exercise | Fix them in the exercise |
| Step 8: `btp` not recognized | The btp CLI isn't installed | Install it as in [Set up for Unit 21](https://erpfde.com/topics/set-up-for-unit-21/), or skip Step 8 |
| Step 8: a network or proxy error from `btp login` | Your company network blocks the connection | Set `HTTPS_PROXY` as [Set up for Unit 21](https://erpfde.com/topics/set-up-for-unit-21/) explains, or skip Step 8 |

### The SAP way

As of November 2026, SAP offers these tools for building and running an account model:

- **SAP BTP cockpit.** The **Account Explorer** creates, moves and filters directories and subaccounts; **Entitlements** assigns plans and quotas; **Costs and Usage** shows consumption and budgets.
- **btp CLI.** Commands such as `btp create accounts/subaccount`, `btp move accounts/subaccount` and `btp assign accounts/entitlement`, with `--format json` for scripts ([btp CLI account commands](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/working-with-global-accounts-directories-and-subaccounts-using-the-btp-cli-85a683e.md)).
- **REST APIs** of the SAP Cloud Management service, for portals and self-service tools.
- **Terraform provider for SAP BTP.** SAP's guide recommends automation once the model spans locations or subsidiaries. [Automating BTP with Terraform](https://erpfde.com/topics/btp-automation-with-terraform/) turns this model into code.
- **SAP's administrator guide.** The *Set Up and Plan* chapter has the drafting checklist, naming advice, a new-directory template and governance guidance, used throughout this topic.
- **SAP Discovery Center.** Lists which services and plans exist in which region. Check it before you fix a region.
- **Joule in the cockpit and the MCP server for administration.** See *Where AI fits* below.

### Build vs. SAP

| Need | Use SAP's | Decide or build yourself | Why |
| --- | --- | --- | --- |
| Hierarchy, regions, entitlements | Cockpit, btp CLI, Terraform provider | The design itself | SAP gives the mechanics; only you know owners and rules |
| Naming and directory template | SAP's examples | Your conventions, written down | Names outlive the people who chose them |
| Cost reporting | Costs and Usage, budgets | Labels and cost objects | Reports follow your org chart, not SAP's |
| Checking a design before it exists | Nothing ready-made | A model file and a check like this topic's | Mistakes such as beta in production can't be undone after creation |
| Provisioning at scale | Terraform provider | Pipelines and reviews around it | Repeatable, reviewed changes |
| Access reviews | Role collections, audit logs | Review cadence and owners | A role nobody reviews accumulates |

### Architecture view

**Where it sits.** BTP sits beside Calder's S/4HANA landscape. Each stage subaccount connects only to the S/4HANA system of the same stage, through its own Cloud Connector tunnel and destinations. Identity comes from Calder's identity provider through SAP Cloud Identity Services.

```mermaid
flowchart LR
  subgraph GA[Global account Calder Pumpworks]
    direction TB
    subgraph P[Platform]
      ID[Integration Dev] 
      IP[Integration Prod]
    end
    subgraph A[AI and agents]
      AD[AI Dev]
      AP[AI Prod]
    end
    subgraph E[Extensions]
      ED[Ext Dev]
      EP[Ext Prod]
    end
  end
  ID --> S4D[(S4D)]
  AD --> S4D
  ED --> S4D
  IP --> S4P[(S4P)]
  AP --> S4P
  EP --> S4P
  IAS[Cloud Identity<br/>Services] -.trust per subaccount.-> GA
```

The Test subaccounts and `S4Q` follow the same pattern and are left out of the picture.

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

| Requirement | Typical target (course values) | If missed |
| --- | --- | --- |
| Isolation | No development user or connection reaches production | A test run changes production data |
| Data location | Every subaccount in its approved region, with the reason recorded | A residency breach found in an audit |
| Cost visibility | Every subaccount carries owner and cost object, own or inherited | Nobody can say what the AI programme costs |
| Administrative access | Two named administrators per production subaccount; no standing global administrator for daily work | One person can change everything, or nobody can |
| Availability | Fallback in another region means another subaccount | A disaster recovery plan that assumes one region covers two |
| Naming | Routes within 63 characters; no personal data in names | Deployments fail late; names need a privacy review |

**Integration and identity.** Each subaccount trusts the identity provider configured for it. Destinations and Cloud Connector tunnels are per subaccount, so `AI Dev` can reach only `S4D`. Service keys for SAP AI Core and other services belong to an instance in one subaccount, so an agent's development key can't call production. Account administration itself goes through the cockpit, the btp CLI, the SAP Cloud Management service APIs or Terraform, each acting with the administrator's role collections.

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

- **Context:** Three workloads with different owners share one subaccount from the integration pilot. Finance wants cost per workload; security wants development kept away from production.
- **Options:** (a) one subaccount per workload, with a Cloud Foundry space per stage; (b) stage directories at the top (Dev, Test, Prod), with a subaccount per workload inside; (c) workload directories at the top, with stage subaccounts inside.
- **Decision:** (c). Stages need subaccounts for isolation, which rules out (a). Owners and budgets follow workloads, so workloads are the most stable top-level criterion for Calder. Only the *AI and agents* directory manages its own entitlements and users, because the AI platform team needs to create its own subaccounts.
- **Consequences:** Ten subaccounts instead of one. Three teams administer their own area. Cost per workload comes from directories, cost per stage from the `Stage` label. A second location (the exercise) adds a directory, not a new tree. Beyond about fifteen subaccounts, manual creation should give way to Terraform.

**What a design review will ask**

1. Why is this the top-level criterion, and what happens to the tree if Calder reorganizes?
2. Which subaccount connects to which S/4HANA system, and how is a wrong destination detected?
3. Who holds global account administration, and has Calder opted out of administrators adding themselves to subaccounts?
4. Where is each region decision recorded, and which services in the plan exist in that region?
5. How does finance get cost per workload and per stage from this model?

### Production concerns

- **Security and authorizations.** Keep Global Account Administrator to a few named people, and give daily operators subaccount or directory roles. Decide about **Add Me as Admin** explicitly. Turn on audit logging for subaccounts with sensitive data, as SAP's checklist suggests. Review role collections at each level on a schedule.
- **Evaluation.** Keep the model file in Git and run `--check` on every change, as a pipeline step. Compare the model with reality by reading `btp --format json list accounts/subaccount` output.
- **Cost.** Use labels for cost objects from day one; adding them later means chasing owners. Set budgets for the AI subaccounts and remember they alert but don't stop spending. Numeric quotas on subaccounts are the hard limit.
- **Operations.** Publish the naming standard and the new-directory template with two owners each. A sandbox needs an expiry date and an owner who deletes it.
- **Clean core.** The account model doesn't touch S/4HANA, but it is where side-by-side extensions live. A clear model makes "build on BTP, not in the core" the easy path for project teams.

### Where AI fits

AI changes four things about the account model.

- **AI services are entitlements like any other.** SAP AI Core runs as an instance in a subaccount. As of November 2026, its *Extended* plan includes the generative AI hub, and SAP says you can't downgrade from *Extended* to *Standard* ([Service Plans](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/service-plans-c7244c6.md)). Regions vary by service, so check the Discovery Center before fixing the AI subaccounts' region. [Running AI on BTP](https://erpfde.com/topics/running-ai-on-btp/) covers the service itself.
- **Agents are consumers with identities.** An agent's service keys, destinations and technical user live in one subaccount. Keep agent development and production apart exactly as for apps, so a test agent can't act on `S4P`. See [Roles and authorization design](https://erpfde.com/topics/roles-and-authorization-design/).
- **Joule can help administer the account.** SAP documents Joule in the BTP cockpit for administration tasks and questions. A global account administrator must enable it by accepting SAP's terms for generative AI, and SAP says this version is free in non-trial global accounts ([Joule in the cockpit](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/account-administration-using-joule-in-the-cockpit-3d7626b.md)).
- **An AI client can act as the administrator.** SAP documents an MCP server for SAP BTP administration covering accounts, security, services and connectivity. SAP warns that it operates with the full scope of the user's SAP identity. If a trial uses the same email as productive accounts, the server reaches all of them ([Connect to the MCP server](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/connect-to-the-mcp-server-for-sap-btp-administration-26262f3.md)). The page states no release status. Treat it like any MCP server: register and approve it ([Registering and approving MCP servers](https://erpfde.com/topics/registering-and-approving-mcp-servers-in-ai-agent-hub/)), and connect it with a viewer or narrowly scoped identity, not a standing global administrator.

### Pitfalls

- **Stages as spaces.** Development and production in one subaccount share trust, destinations and data access.
- **Beta in production.** One checkbox, and the subaccount can never be clean again.
- **A region chosen by default.** Moving a workload to another region means a new subaccount and a migration.
- **Too many global accounts.** Each one splits entitlements and cost reports; SAP recommends consolidating.
- **Directory features in the wrong place.** Only one directory per path can manage entitlements or users, so delegating at the wrong level blocks the right one.
- **Long names.** `calder-pumpworks-extensions-prod` plus a space and an app name breaks the 63-character route limit.
- **Labels added later.** Nobody remembers which project created a subaccount two years on.
- **People's names in names.** Subdomains, labels and directory names are not the place for personal data.
- **Administrators by default.** Whoever creates a subaccount becomes its administrator, and global administrators can add themselves unless you opt out.
- **Treating the flag as protection.** *Used for production* changes no configuration; apart from blocking a forced deletion, roles and connections do the protecting.

### Exercise

Fix the draft's three errors and its warning, add Augsburg, and record the decision.

1. Open `unit21/calder_account_model.json` in VS Code.
2. In the node `"name": "AI Prod"`, change `"beta_enabled": true` to `"beta_enabled": false`.
3. In `"name": "Ext Test"`, change `"backends": ["S4P"]` to `"backends": ["S4Q"]`.
4. In `"name": "Ext Prod"`, change `"subdomain": "calder-pumpworks-extensions-prod"` to `"subdomain": "calder-ext-prod"`.
5. In `"name": "Sandbox"`, inside `"labels"`, add a line `"Expires": ["2027-03-31"],` after the opening brace.
6. Calder's (course) policy keeps employee data of Augsburg's planned shift-handover app in the EU. At the end of the `nodes` list, after the last `}` and before `]`, type a comma and paste:

   ```json
   {"type": "directory", "name": "Augsburg", "parent": null, "features": [], "admins": [],
    "labels": {"Residency": ["EU"]}, "entitlements": {}},
   {"type": "subaccount", "name": "Augsburg Dev", "parent": "Augsburg", "stage": "dev",
    "region": "eu10", "subdomain": "calder-aug-dev", "used_for_production": false,
    "beta_enabled": false, "admins": ["00100288"], "backends": ["ECD"],
    "labels": {"Stage": ["Dev"], "Owner team": ["Apps"], "Cost object": ["CP20-910"],
               "Contacts": ["apps-team@calder-pumpworks.example"]},
    "routes": [{"space": "shift-notes", "app": "shift-handover"}], "entitlements": {}},
   {"type": "subaccount", "name": "Augsburg Prod", "parent": "Augsburg", "stage": "prod",
    "region": "eu10", "subdomain": "calder-aug-prod", "used_for_production": true,
    "beta_enabled": false, "admins": ["00100316", "00100317"], "backends": ["ECP"],
    "labels": {"Stage": ["Prod"], "Owner team": ["Apps"], "Cost object": ["CP20-910"],
               "Contacts": ["apps-team@calder-pumpworks.example"]},
    "routes": [{"space": "shift-notes", "app": "shift-handover"}], "entitlements": {}}
   ```

   `eu10` is SAP's Europe (Frankfurt) region in the Cloud Foundry region list; `ECD` and `ECP` are `CP20`'s ECC systems until the July 2027 rollout.

7. Run `python unit21/account_model.py --check`. It should end with `0 error(s), 0 warning(s)` for 12 subaccounts in 4 directories.
8. Try a mistake on purpose: delete `"Residency": ["EU"]` from the Augsburg directory and run `--check` again. You should see two `R11` errors. Put the label back.
9. Run `python unit21/account_model.py --write`, open `unit21/calder_account_model.md`, and fill in the **Decision record**: context, the three options, Calder's decision and its consequences, in your own words. Answer the two open questions with a decision and a reason.
10. Commit the script, the model and the deliverable with Git.

**Done when:** `--check` reports `Checked 12 subaccounts in 4 directories.` and `0 error(s), 0 warning(s)` with exit code 0, and `unit21/calder_account_model.md` has a filled-in decision record and answers to both open questions. Keep the file: Unit 21's [connectivity](https://erpfde.com/topics/btp-connectivity/) and [security](https://erpfde.com/topics/btp-security-model/) topics build on these subaccounts, and the Architect capstone (Unit 32) collects it into Calder's target architecture.

### Check yourself

1. How many directory levels can sit between a global account and its lowest subaccount?
   - A. Three, because SAP limits a path to dev, test and production
   - B. Seven, because the limit counts only directories
   - C. Five, since the seven count the global account and subaccount
   - D. Any number, because directories are only folders for filtering

   Answer: C. SAP allows a hierarchy up to 7 levels deep, with the global account at the top and a subaccount at the bottom. That leaves at most 5 directory levels between them.

2. The *Extensions* directory has user management enabled but not entitlement management. What does `--check` report, and why?
   - A. Nothing, because the two features are independent of each other
   - B. R02, since user management needs entitlement management too
   - C. R10, because every directory needs two administrators whatever its features
   - D. R13, because the directory reserves no quota for its subaccounts

   Answer: B. SAP's documentation says the user management feature can only be enabled together with entitlement management on the same directory. R10 would add an error only if the directory also had fewer than two administrators.

3. `AI Dev` carries only `Stage` and `Process` labels of its own, yet passes R09's required-label rule. Why?
   - A. R09 skips subaccounts that sit in a directory with entitlement management
   - B. The script treats `Process` as a valid stand-in for the missing labels
   - C. R09 only checks production subaccounts, and `AI Dev` is development
   - D. `effective_labels()` adds the labels of the directory above it

   Answer: D. The script merges directory labels into each subaccount, as SAP shows inherited labels from directories in the path. The directory carries `Owner team`, `Cost object` and `Contacts`, so `AI Dev` has all four required labels.

4. Ext Prod's route `calder-pumpworks-extensions-prod-distributor-portal-distributor-order-status` fails R12. What is the cleanest fix before the subaccount exists?
   - A. Ask SAP to raise the DNS label limit for Calder's global account
   - B. Move the app into the Ext Test subaccount, which has a shorter name
   - C. Shorten the subdomain and org name, for example to `calder-ext-prod`
   - D. Split the app into two apps with shorter names in two spaces

   Answer: C. Cloud Foundry builds `{org}-{space}-{app}` as one DNS label of at most 63 characters, and SAP advises short names for subaccounts, subdomains and orgs. `calder-ext-prod` brings the route to 59 characters; a custom route would also work, but a short name avoids the problem for every app.

5. The AI directory reserves a quota of 3 for SAP AI Core's extended plan but has no subaccounts yet. What does the global account see?
   - A. The quota stays free at global account level until a subaccount uses it
   - B. The quota shows as used, reserved for that directory's subaccounts
   - C. The quota is split evenly across all existing subaccounts automatically
   - D. The quota is billed twice, once to the directory and once when used

   Answer: B. SAP's documentation says quota assigned to a directory shows as used even with no subaccounts to consume it. It is a way to reserve quota so it can't be given to other directories or subaccounts.

6. A colleague wants to connect the MCP server for SAP BTP administration to their AI coding assistant, signed in with their usual user, which holds Global Account Administrator. What do you do?
   - A. Allow it, because the server only reads account data and can't change it
   - B. Allow it, but only from the trial, since the trial is isolated by design
   - C. Block it, because SAP doesn't allow MCP clients in productive global accounts
   - D. Stop it: it acts with that user's full scope; use a narrower identity

   Answer: D. SAP warns that the server operates with the full scope of the user's SAP identity, and that a trial on the same email reaches all of that user's global accounts. Treat it as an approved MCP server and connect it with a viewer or narrowly scoped identity.

7. A security reviewer reads `"used_for_production": true` on AI Prod as proof the subaccount is locked down. What is the right reply?
   - A. The flag blocks beta features, so the subaccount stays production-grade
   - B. The flag hides the subaccount from directory administrators below the global account
   - C. The flag changes no configuration; it signals criticality to operators and SAP
   - D. The flag makes the subaccount read-only until an administrator clears it

   Answer: C. SAP's documentation says *Used for production* doesn't change the subaccount's configuration. It helps operators treat incidents there as mission-critical, and it stops a forced deletion. Access controls come from roles, trust and connections.

8. Calder sets a monthly budget for the AI subaccounts in its consumption-based global account. In week three the threshold is passed. What happens?
   - A. SAP suspends the AI services in those subaccounts until next month
   - B. Administrators get an alert where available, and usage continues until someone acts
   - C. The extra usage is moved to the Platform directory's quota automatically
   - D. The global account switches to the subscription model for the rest of the month

   Answer: B. SAP states that budgets don't suspend costs or service usage when a threshold is exceeded; acting on the alert is the customer's job. A hard limit needs numeric quotas on the subaccounts.

## Sources

- [Account Model (SAP BTP documentation, SAP-docs on GitHub, read 2026-11-26)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/account-model-8ed4a70.md): global account as the realization of a contract, region- and environment-independent; subaccounts independent of each other, one region each; Cloud Foundry org 1:1 and Kyma clusters 1:n per subaccount; up to 7 levels, 5 of them directories; directory features Manage Entitlements and Manage Authorizations; labels with up to 10 values, 10 labels per entity in the cockpit, case-sensitive, inherited from directories
- [Entitlements and Quotas (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/entitlements-and-quotas-00aa2c2.md): entitlement is the right to a service plan, quota the quantity; fixed vs unlimited global quota; numeric and non-numeric assignments; quota assigned to a directory shows as used and is reserved; auto-assignment only for new subaccounts; space quota plans in Cloud Foundry
- [Role Collections and Roles in Global Accounts, Directories, and Subaccounts (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/role-collections-and-roles-in-global-accounts-directories-and-subaccounts-0039cf0.md): Global Account Administrator and Viewer, Directory Administrator and Viewer, Subaccount Administrator and Viewer and others; role collections are specific to each account level; a global account administrator can grant themselves subaccount administration unless the global account opted out
- [Create a Directory (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/create-a-directory-b8ef1c4.md): Enable entitlement management and Enable user management under Advanced; user management only together with entitlement management; only one directory per path may have either; subaccounts inherit the directory's labels; only empty directories can be deleted
- [Create a Subaccount (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/create-a-subaccount-05280a1.md): subdomain up to 63 characters, letters, digits and inner hyphens, unique per region and case-insensitive; Used for production changes no configuration; beta features shouldn't be used in productive enterprise accounts and can't be disabled once enabled; creating a subaccount from an existing one copies labels and plan assignments
- [Setting Up Your Account Model (SAP BTP Administrator's Guide, SAP-docs on GitHub, read 2026-11-26)](https://github.com/SAP-docs/btp-best-practices-guide/blob/main/docs/set-up-and-plan/setting-up-your-account-model-2db81f4.md): start with one global account and DEV, TEST and PROD subaccounts; a set per project plus shared-service subaccounts as adoption grows; more directory layers for locations or subsidiaries, then automation with Terraform
- [Checklist: Drafting Your Account Model (SAP BTP Administrator's Guide)](https://github.com/SAP-docs/btp-best-practices-guide/blob/main/docs/set-up-and-plan/checklist-drafting-your-account-model-7f1c318.md): consolidate global accounts with few exceptions (separate bills, EU access contract, a China region, restricted global admin access); most stable criterion at the top; labels for cost reports that differ from the hierarchy; one region per subaccount; HA in another region needs another subaccount; SAP Cloud ALM in its own global account that can't be consolidated
- [Subaccounts or Spaces/Namespaces? (SAP BTP Administrator's Guide)](https://github.com/SAP-docs/btp-best-practices-guide/blob/main/docs/set-up-and-plan/subaccounts-or-spaces-namespaces-4cb5276.md): subaccounts isolate (data access, connectivity, trust, destinations, Cloud Connector, cost monitoring), spaces and namespaces structure; at least two subaccounts for staged development; billing accurate only per global account
- [Naming and Directory Templates (SAP BTP Administrator's Guide)](https://github.com/SAP-docs/btp-best-practices-guide/blob/main/docs/set-up-and-plan/naming-and-directory-templates-5302ea4.md): same name pattern for subaccount, subdomain and Cloud Foundry org; lowercase and hyphens; {org}-{space}-{app} in one DNS label of at most 63 characters; no personal data in names; a new-directory template with at least two owners
- [Connect to the MCP Server for SAP BTP Administration (SAP BTP documentation)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/connect-to-the-mcp-server-for-sap-btp-administration-26262f3.md): accounts, security, services and connectivity tools behind one endpoint for MCP clients; the server operates with the full scope of the user's SAP identity, so a trial on the same email reaches all that user's global accounts
