# BTP commercial models and cost control

> Choose between SAP BTP's consumption-based and subscription-based models, then charge back, budget and forecast BTP spend so credits last the period.

- Course: Orchestrate, Unit 21 · SAP BTP as a platform
- Page: https://erpfde.com/topics/btp-commercial-models-and-cost/
- 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

SAP Business Technology Platform (BTP) is paid for in one of two ways, and many companies use both.

- **Consumption-based.** You get access to every service SAP has made eligible for the model and pay for what you use. It comes in three flavors. **SAP BTPEA** (SAP BTP Enterprise Agreement) and **CPEA** (Cloud Platform Enterprise Agreement) are prepaid **cloud credits** that each month's usage is deducted from. **Pay-As-You-Go** has no upfront payment and bills each month for the month before.
- **Subscription-based.** You pay a fixed price for named services for a fixed period, usually one to three years, whatever you use within the quota.

The model decides who controls the bill. With a subscription, purchasing controls it at signature. With credits, every team that creates a service instance spends from the same pot. That is why cost control on BTP is mostly a habit, not a setting: label every subaccount, set budgets, read the monthly statement and forecast the credits.

This topic shows Calder Pumpworks (the course's fictional pump maker) running out of credits on paper, finding why, and fixing it before the overage arrives.

### Why it matters to the business

- **Overage is billed at list price.** SAP's documentation says that under BTPEA and CPEA any usage beyond the credits is billed in arrears at list price, without the discount you negotiated for the credits ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/what-is-the-consumption-based-commercial-model-7047eb4.md)). Running out in month eleven costs more than buying a few more credits in month eight.
- **Unused credits are a sunk cost.** Credits are committed per period. A forecast that is too cautious buys capacity nobody uses. Check your own contract for what happens to an unused balance; this topic doesn't assume either way.
- **Nothing stops the spend automatically.** A budget on BTP sends alerts. SAP states plainly that it doesn't suspend usage when a threshold is passed ([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)). Someone has to act.
- **Shared cost needs an owner.** Calder's AI team, integration team and apps team all draw on one global account. Without a chargeback, the platform team carries the whole bill and every other team treats BTP as free.

A concrete case. Calder's ABAP development system for the test certificate archive used to sleep at night and at weekends. After a change in October nobody restored the schedule, so it ran all month. That one system tripled its cost. Nobody noticed until the monthly statement, because the apps team had no working budget alert.

### How SAP does it

As of November 2026, SAP's documentation describes these options for enterprise accounts ([Commercial Models](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/commercial-models-263d400.md)):

| Model | How you pay | Good for | Watch out for |
| --- | --- | --- | --- |
| **SAP BTPEA** (consumption) | Prepaid cloud credits for the contract, annual commitment, billed yearly in advance; minimum investment, volume discounts, top-ups at any time | Planned use cases where the mix of services will change | Overage in arrears at list price |
| **CPEA** (consumption) | The same credit mechanics as BTPEA | Existing CPEA customers: SAP's pricing page says they may continue, renew and move to BTPEA ([sap.com](https://www.sap.com/products/technology-platform/pricing.html)) | One consumption flavor per global account |
| **Pay-As-You-Go** (consumption) | Nothing upfront, no minimum, billed monthly in arrears, no discounts | Proofs of concept and unclear use cases in a productive account | List price on everything; no forecast card in the cockpit |
| **Subscription** | Fixed price for named services and quotas, typically 1 to 3 years, paid in advance | Stable, well-sized services, often in bundles | Only the subscribed services; extra usage needs a contract change |

Three more things SAP documents:

- **Mixing.** You can combine consumption and subscription in the same global account or keep them in separate ones. You can't mix two consumption flavors in one global account.
- **Free plans.** Many services offer **free tier** plans inside a consumption-based account, with community support and no SLA. **Always Free** plans are included in the contract ([Trial Accounts and Free Tier](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/trial-accounts-and-free-tier-046f127.md)). A trial account is separate, lasts 90 days, and its data can't move to an enterprise account.
- **Prices.** SAP publishes no prices on its BTP pricing page. It points to the service catalog in the SAP Discovery Center and its **SAP BTP Cost Estimator** ([SAP Learning](https://learning.sap.com/courses/becoming-an-sap-btp-solution-architect/exploring-sap-btp-commercial-models)). Your contract's rate card is what you actually pay.

In the cockpit, the global account's **Costs and Usage** page shows the monthly cost, the credit balance, budgets and recommendations such as cost spikes ([Monitoring Usage and Consumption Costs](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/monitoring-usage-and-consumption-costs-in-your-global-account-de6f0db.md)). The monthly **balance statement** in SAP for Me is the legally binding figure.

Joule Studio agents are metered in AI Units, which come with their own rules; see [pricing custom agents after the free runtime](https://erpfde.com/topics/pricing-custom-agents-after-the-free-runtime/).

### Choosing a model, and keeping it under control

| Your situation | Usual choice | The control that matters most |
| --- | --- | --- |
| First pilot, scope unclear | Pay-As-You-Go | A budget on the whole account from day one |
| Several teams, services will change over three years | SAP BTPEA | Monthly forecast of credits against the period |
| One big service sized for years (for example a large integration hub) | Subscription for that service, credits for the rest | Watch usage near the prepaid quota; beyond it is charged |
| Already on CPEA | Stay or move to BTPEA at renewal | Same as BTPEA |

A rhythm that works for most customers:

1. **Before buying:** price the solution design in the SAP Discovery Center estimator, per stage (development, test, production).
2. **At setup:** every subaccount carries an owner team and a cost object label (see [the BTP account model](https://erpfde.com/topics/btp-account-model/)).
3. **Every month:** after the balance statement, charge cost back by label, compare with the estimate and refresh the credit forecast.
4. **Every quarter:** decide top-up, reduce, or accept overage, and write the decision down.

> **Note** **For functional consultants.** Nothing changes in SAP process configuration. What changes is the project: an extension or agent you specify on BTP now has a running cost per month and per stage, and someone must own it. Ask for the estimate and the cost object before the build starts, and include "who switches it off" in the cutover and decommissioning plan.

### Questions to ask

1. Which consumption flavor are we on, and when does our current credit period end?
2. What is our credit balance today, and what does the forecast say for the end of the period?
3. Does every subaccount carry an owner and a cost object, so finance can charge cost back?
4. Which budgets exist, who receives their alerts, and who acts on them?
5. Which services do we hold by subscription, and how close is each to its prepaid quota?
6. What does our contract say about unused credits, top-ups and overage?
7. For this new project: what does the estimator say per stage, and who switches off non-production systems when they are idle?

### Common misconceptions

- **"A budget caps the spend."** It doesn't. It alerts, and only if someone turned the alerts on. Usage keeps running.
- **"The cockpit figure is the bill."** The balance statement is the bill. Cockpit figures between statements are estimates, and subaccount and directory figures are always estimates.
- **"Consumption means paying only for what production uses."** Development, test and sandbox systems consume too. An idle Kyma cluster or an ABAP system that never sleeps bills all month.
- **"Free tier means free forever for production."** Free tier plans have capacity limits, community support and no SLA. Production needs paid plans.
- **"Pay-As-You-Go is the cheap option."** It avoids commitment, not cost: every service is at list price.

### Key terms

- **Commercial model:** how SAP charges for BTP: consumption-based or subscription-based.
- **SAP BTPEA:** SAP BTP Enterprise Agreement, the consumption flavor with prepaid cloud credits.
- **CPEA:** Cloud Platform Enterprise Agreement, the older credit-based consumption flavor.
- **Pay-As-You-Go:** consumption with no commitment, billed monthly in arrears at list price.
- **Cloud credits:** the prepaid balance that monthly BTP usage is deducted from.
- **Overage:** usage beyond the credits of a period, billed at list price.
- **Balance statement:** the monthly, legally binding statement of usage and cost.
- **Budget:** a monthly amount with up to three alert thresholds, set on the Costs and Usage page.
- **Chargeback:** passing BTP cost on to the teams or cost objects that caused it.
- **Free tier plan:** a free, limited service plan in a consumption-based account.

### Check yourself

1. Calder's AI, integration and apps teams all use one consumption-based global account. Why does the platform team insist on a cost object label on every subaccount?
   - A. SAP bills each subaccount separately, so the label sets the invoice address
   - B. Finance can charge each team's cost back, so no team sees BTP as free
   - C. Without a label, SAP blocks new service instances in the subaccount
   - D. Labels unlock the volume discount on the cloud credits for that team

   Answer: B. The global account is the only billable entity; labels let you split its cost by team or cost object. Without a chargeback the platform team carries the bill and nobody else has a reason to switch things off.

2. Calder's credit forecast shows usage passing the BTPEA credits two months before the period ends. What does SAP's documentation say happens to the extra usage?
   - A. SAP suspends the global account until more credits are bought
   - B. The extra usage is moved into next period's credits at no charge
   - C. It is billed in arrears at list price, without the credit discount
   - D. It is billed at the discounted credit rate on the next annual invoice

   Answer: C. SAP documents overages under BTPEA and CPEA as billed in arrears at list price. That is why a forecast in month eight, with time to top up or cut waste, is worth more than a surprise in month eleven.

3. A project lead says the new budget on the apps subaccounts will stop spending at 3,500.00 a month. What is the right answer?
   - A. Correct, as long as the budget type is Cost rather than Charged Usage
   - B. Correct, once the 100% threshold has its email alert switched on
   - C. Only for subscription services, which SAP stops at the prepaid quota
   - D. Wrong: a budget only alerts, and someone has to act on the alert

   Answer: D. SAP states that budgets don't suspend costs or usage when a threshold is passed. A budget is a warning system; the action (switching off, resizing, topping up) is a person's job.

4. Which situation fits Pay-As-You-Go best?
   - A. A first pilot whose scope and size are still unclear
   - B. A three-year programme with several teams and a negotiated discount
   - C. One large integration hub sized for the next three years
   - D. A customer who already holds CPEA credits in the same global account

   Answer: A. Pay-As-You-Go has no commitment and no minimum, which suits unclear use cases, but every service is at list price. Planned multi-team use suits credits, a stable large service suits a subscription, and one global account can't mix two consumption flavors.

5. A controller compares the cockpit's cost for one subaccount with the monthly balance statement and finds a small difference. Which figure counts?
   - A. The cockpit, because it is updated every day from the meters
   - B. The balance statement; subaccount figures are only estimates
   - C. The SAP Discovery Center estimate made before the project started
   - D. Whichever is lower, since SAP refunds differences at the period end

   Answer: B. SAP's documentation says the balance statement is binding and that directory and subaccount figures are estimates for internal use. Use the cockpit for chargeback and trends, and the statement for the money.

6. Calder's ABAP development system ran all month in October instead of sleeping at night. Which control would have caught it soonest?
   - A. A subscription for the ABAP environment instead of consumption
   - B. A larger set of cloud credits at the next renewal
   - C. A budget on the apps subaccounts with email alerts on
   - D. Moving the development system into the trial account

   Answer: C. The cost appeared in the apps subaccounts in October; a working budget alert reaches the owners in the month itself. Changing the model or buying more credits hides the waste instead of finding it, and a trial account can't hold project work.

7. Before a new BTP extension is approved, what should a leader ask for first?
   - A. The list price of every service from SAP's public pricing page
   - B. A promise from the team that the free tier will cover production
   - C. A subscription quote, because subscriptions are always cheaper
   - D. An estimate per stage and a named owner and cost object

   Answer: D. SAP publishes prices through the Discovery Center estimator and your contract, not on its pricing page. Per-stage estimates show what development and test will cost, and an owner with a cost object makes the running cost someone's job.

## Deep layer

### Mental model

On a consumption-based contract, **the global account is a wallet and every subaccount administrator can spend from it.** SAP meters each service in its own unit (GB of memory, capacity units, compute-unit hours, API calls). Once a month SAP turns those meters into money on the balance statement and deducts it from the credits. Everything you do for cost control maps to that pipeline:

- **Before the meter:** entitlements and quotas decide who may create what, and how much.
- **At the meter:** labels decide whose cost it is.
- **After the meter:** budgets, chargeback and the credit forecast decide whether you act in time.

The commercial model changes only the last step's question. With credits you ask "will they last the period?" With a subscription you ask "are we near the prepaid quota?" With Pay-As-You-Go you ask "is this month's bill what we expected?"

### How it works

#### From meter to statement

```mermaid
flowchart LR
  E[Entitlements and quotas<br/>who may create what] --> I[Service instances<br/>in subaccounts]
  I --> M[Meters per plan<br/>GB, capacity units, hours]
  M --> S[Monthly balance statement<br/>legally binding]
  S --> C[Credits deducted<br/>or monthly invoice]
  M -. estimates .-> P[Costs and Usage page<br/>Overview, Billing, Usage, Budgets]
  P --> B[Budget thresholds<br/>email or Alert Notification event]
  S --> X[Export or Resource Consumption API<br/>chargeback, forecast]
```

SAP's documentation sets out how the figures behave ([Monitoring Usage and Consumption Costs](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/monitoring-usage-and-consumption-costs-in-your-global-account-de6f0db.md)):

- **The global account is the only billable entity.** Directory and subaccount figures are estimates for internal cost allocation.
- **Between statements, values are estimates.** The charts show them as striped bars. They aren't forecasts and may change when the month is billed.
- **Some services report only at the global account level.** They appear under a reserved entity, `REPORTED-AT-GLOBAL-ACCOUNT-LEVEL` with the ID `DEFAULT_SA`. Your chargeback needs a rule for them.
- **Costs are in the contract currency and cover all regions.** Calder's planned Augsburg subaccounts in `eu10` spend from the same credits as Rockford's in `us10`.

#### What drives cost

The runtime topic showed the units for Calder's workloads ([BTP runtimes compared](https://erpfde.com/topics/btp-runtimes-compared/)). The drivers that cause surprises are the same on every project:

| Driver | Why it surprises | Control |
| --- | --- | --- |
| Kyma cluster floor | Three nodes bill all month, even for one small workload | Share clusters; delete idle development clusters |
| ABAP environment systems | Compute units bill every hour a system runs | Hibernation for non-production; SAP says stopped systems use no ABAP compute units |
| Cloud Foundry memory | Billed on memory reserved per instance, not used | Right-size instances; numeric quotas per subaccount |
| AI services | Usage grows with adoption, not with deployments | Budgets per plan; SAP's own AI Core estimator before go-live |
| Subscription quotas | Usage beyond the prepaid quota is charged on consumption terms | Watch the prepaid quota card |
| Default quotas | Consumption accounts give each subaccount 200 GB of Cloud Foundry memory | Set lower numeric quotas, especially in sandboxes |

#### Budgets

A budget in the cockpit has a type, a scope, a monthly amount, a period and up to three thresholds ([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)). As documented in November 2026:

- **Type** is *Cost* (list-price money, any number of plans) or *Charged Usage* (the metric of exactly one service plan). You can't change the type or start date later.
- **Scope** is all subaccounts and plans by default, or the ones you pick. You can pick only services with registered usage.
- **Thresholds** are up to three percentages from 1% to 120% of the amount.
- **Alerts:** automatic email to all global account administrators, off by default and not available in every country. Every passed threshold also sends a `BudgetAlertThresholdExceeded` event to SAP Alert Notification service, a paid service you route to your own channels.
- **Limits:** up to 30 active budgets per global account. Budgets run on estimates and may alert late. Usage within a subscription's prepaid quota isn't evaluated.

#### Forecasting

The cockpit's *Show forecast* option on the BTPEA and CPEA cards projects credits for up to six months or the period end. It needs at least nine months of consistent history, leaves out the current month, isn't offered in the last month of a period, and isn't available on Pay-As-You-Go. A new global account therefore runs most of its first year without SAP's forecast. A simple run-rate forecast of your own covers the gap and adds what SAP can't know: your planned go-lives and cuts.

### Build it yourself: Calder's monthly cost review

You will run Calder's November cost review on made-up data: charge October's cost back by cost object, check the budgets, forecast the credits to March 2027, find the drivers, fix them, and write the decision record. It runs on your computer with no account.

```mermaid
flowchart LR
  I[--init] --> F[unit21/cost/<br/>contract, rates, usage,<br/>budgets, plans]
  F --> R[btp_cost.py]
  R --> O[chargeback, budgets,<br/>forecast, drivers]
  O --> X[--apply-fixes]
  X --> R
  R --> W[--write<br/>calder_btp_cost.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 **rate card** is the list of prices per unit from your contract. A **run rate** is last month's cost carried forward. A **CSV** file is a table saved as text, one row per line. **Exit code** is the number a script returns when it ends: 0 means fine, 1 here means at least one FAIL.

#### What you need

- Python and your `orchestrate-course` folder with its `.venv`.
- No account. Everything is free.
- About 40 minutes.

> **Warning** The rates in this lab are course placeholders, not SAP prices. Never quote them. For real work, replace them with your contract's rate card or the SAP Discovery Center estimator.

#### 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

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

```python
"""Calder's BTP cost control: chargeback, budgets and a credit forecast.

Built-in modules only, no randomness. Course values throughout: the rates are
placeholders, not SAP prices. Replace them with your contract's rate card or
the SAP Discovery Center estimator before you use the method on real data.
"""
import argparse
import csv
import json
import sys
from collections import defaultdict
from pathlib import Path

FOLDER = Path("unit21/cost")
CONTRACT = FOLDER / "contract.json"
RATES = FOLDER / "rate_card.json"
USAGE = FOLDER / "usage.csv"
BUDGETS = FOLDER / "budgets.json"
PLANS = FOLDER / "plans.json"
REPORT = Path("unit21/calder_btp_cost.md")

# SAP limits for budgets, as documented in the SAP BTP documentation (read 2026-11-27).
MAX_ACTIVE_BUDGETS = 30
MAX_THRESHOLDS = 3
THRESHOLD_RANGE = (1, 120)
GLOBAL_LEVEL = "REPORTED-AT-GLOBAL-ACCOUNT-LEVEL"   # SAP's reserved entity, ID DEFAULT_SA

# Course rules (not SAP's).
SPIKE_RATIO = 1.5       # this month at least 1.5 times last month ...
SPIKE_MIN = 300.00      # ... and at least 300.00 more
HEADROOM = 0.05         # keep 5% of the period's credits unspent

MONTHS = ["2026-04", "2026-05", "2026-06", "2026-07", "2026-08", "2026-09",
          "2026-10", "2026-11"]
FUTURE = ["2026-12", "2027-01", "2027-02", "2027-03"]


def sample_contract():
    def labels(stage, team, cost):
        return {"Stage": stage, "Owner team": team, "Cost object": cost}
    return {
        "as_of": "2026-11-27",
        "global_account": "Calder Pumpworks",
        "model": "SAP BTPEA (course assumption)",
        "currency": "USD",
        "credit_period": {"start": "2026-04", "end": "2027-03", "credits": 70000.00},
        "overage": "billed in arrears at list price",
        "last_balance_statement": "2026-10",
        "subscription": {"service": "SAP Integration Suite",
                         "note": "subscribed separately (course assumption); usage within "
                                 "the prepaid quota is not charged and not seen by budgets"},
        "subaccounts": {
            "calder-int-dev": labels("Dev", "Integration", "CP10-910"),
            "calder-int-test": labels("Test", "Integration", "CP10-910"),
            "calder-int-prod": labels("Prod", "Integration", "CP10-910"),
            "calder-ai-dev": labels("Dev", "AI platform", "CP10-920"),
            "calder-ai-test": labels("Test", "AI platform", "CP10-920"),
            "calder-ai-prod": labels("Prod", "AI platform", "CP10-920"),
            "calder-ext-dev": labels("Dev", "Apps", "CP10-910"),
            "calder-ext-test": labels("Test", "Apps", "CP10-910"),
            "calder-ext-prod": labels("Prod", "Apps", "CP10-910"),
            "calder-sandbox": labels("Sandbox", "BTP platform", "CP10-910"),
        },
        "cf_quota_gb": {"calder-sandbox": 200},
        "global_level_rule": "share of subaccount cost in the same month",
    }


def sample_rates():
    p = "course placeholder, not an SAP price"
    return {
        "source": "Course placeholder rates. Replace with your contract or the SAP Discovery "
                  "Center estimator.",
        "rates": {
            "Cloud Foundry runtime|standard|GB memory": {"price": 60.00, "source": p},
            "Kyma runtime|aws|capacity units": {"price": 1.10, "source": p},
            "ABAP environment|standard|ACU-hours": {"price": 1.30, "source": p},
            "ABAP environment|standard|HCU-hours": {"price": 0.60, "source": p},
            "SAP AI Core|extended|units (course metric)": {"price": 0.50, "source": p},
            "SAP Integration Suite|subscription|units (course metric)": {
                "price": 25.00, "prepaid_quota": 100, "source": p},
            "Global-level service (course example)|standard|months": {
                "price": 400.00, "source": p},
        },
    }


def sample_usage():
    rows = []

    def add(sub, service, plan, metric, values):
        for m, q in zip(MONTHS, values):
            if q:
                rows.append([m, sub, service, plan, metric, q])

    cf = ("Cloud Foundry runtime", "standard", "GB memory")
    kyma = ("Kyma runtime", "aws", "capacity units")
    acu = ("ABAP environment", "standard", "ACU-hours")
    hcu = ("ABAP environment", "standard", "HCU-hours")
    aic = ("SAP AI Core", "extended", "units (course metric)")
    ist = ("SAP Integration Suite", "subscription", "units (course metric)")
    for sub, gb in [("calder-int-dev", 1), ("calder-int-test", 1), ("calder-int-prod", 1),
                    ("calder-ai-dev", 2), ("calder-ai-test", 2), ("calder-ext-dev", 1),
                    ("calder-ext-test", 1), ("calder-ext-prod", 2), ("calder-sandbox", 1)]:
        add(sub, *cf, [gb] * 8)
    add("calder-ai-prod", *cf, [2, 2, 3, 3, 5, 5, 5, 5])
    add("calder-int-prod", *kyma, [0, 0, 0, 0, 0, 788.4, 788.4, 788.4])
    add("calder-int-dev", *kyma, [0, 0, 0, 0, 788.4, 788.4, 788.4, 788.4])
    add("calder-ext-prod", *acu, [0, 0, 730, 730, 730, 730, 730, 730])
    add("calder-ext-prod", *hcu, [0, 0, 1460, 1460, 1460, 1460, 1460, 1460])
    add("calder-ext-dev", *acu, [220, 220, 220, 220, 220, 220, 730, 730])
    add("calder-ext-dev", *hcu, [440, 440, 440, 440, 440, 440, 1460, 1460])
    add("calder-ai-dev", *aic, [300] * 8)
    add("calder-ai-test", *aic, [150] * 8)
    add("calder-ai-prod", *aic, [0, 200, 400, 600, 900, 900, 1000, 1100])
    add("calder-int-prod", *ist, [70, 74, 80, 85, 88, 92, 96, 104])
    add(GLOBAL_LEVEL, "Global-level service (course example)", "standard", "months", [1] * 8)
    return rows


def sample_budgets():
    ai = ["calder-ai-dev", "calder-ai-test", "calder-ai-prod"]
    ext = ["calder-ext-dev", "calder-ext-test", "calder-ext-prod"]
    return {"budgets": [
        {"id": "B01", "name": "AI platform monthly", "type": "Cost", "amount": 2000.00,
         "subaccounts": ai, "plans": [], "thresholds": [70, 90, 100], "email": True,
         "start": "2026-10-01", "end": None},
        {"id": "B02", "name": "Apps monthly", "type": "Cost", "amount": 3500.00,
         "subaccounts": ext, "plans": [], "thresholds": [80, 150], "email": False,
         "start": "2026-10-01", "end": None},
        {"id": "B03", "name": "AI Core units, prod", "type": "Charged Usage", "amount": 1000,
         "subaccounts": ["calder-ai-prod"],
         "plans": ["SAP AI Core|extended", "Cloud Foundry runtime|standard"],
         "thresholds": [90], "email": True, "start": "2026-10-01", "end": None},
    ]}


def sample_plans():
    return {"changes": [
        {"id": "P01", "from": "2027-01", "subaccount": "calder-int-prod",
         "service": "Kyma runtime|aws|capacity units", "delta": 700.8,
         "why": "W08 casting porosity image check: one extra node pool (Kyma runtime topic)"},
        {"id": "P02", "from": "2027-01", "subaccount": "calder-ai-prod",
         "service": "SAP AI Core|extended|units (course metric)", "delta": 400,
         "why": "invoice triage agent AGT_INV_TRIAGE in production"},
        {"id": "P03", "from": "2027-02", "subaccount": "calder-ext-prod",
         "service": "Cloud Foundry runtime|standard|GB memory", "delta": 2,
         "why": "distributor order-status app R03 scales to two more instances"},
    ]}


def write_samples():
    FOLDER.mkdir(parents=True, exist_ok=True)
    if USAGE.exists():
        sys.exit(f"{USAGE} already exists; delete the {FOLDER} folder to start again.")
    for path, data in [(CONTRACT, sample_contract()), (RATES, sample_rates()),
                       (BUDGETS, sample_budgets()), (PLANS, sample_plans())]:
        path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
    with USAGE.open("w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow(["month", "subaccount", "service", "plan", "metric", "quantity"])
        w.writerows(sample_usage())
    print(f"Wrote 5 files to {FOLDER}: contract, rate card, usage ({len(sample_usage())} rows), "
          "budgets, plans.")


def apply_fixes():
    """The fixes from the walkthrough: valid budgets, full coverage, two cuts, a sandbox quota."""
    contract, _, _, budgets, plans = load()
    if any(p["id"] == "P04" for p in plans):
        sys.exit("Fixes are already applied.")
    for b in budgets:
        if b["id"] == "B02":
            b["thresholds"], b["email"] = [80, 100], True
        if b["id"] == "B03":
            b["plans"] = ["SAP AI Core|extended"]
    budgets.append({"id": "B04", "name": "Platform and sandbox", "type": "Cost",
                    "amount": 2200.00, "subaccounts": ["calder-int-dev", "calder-int-test",
                    "calder-int-prod", "calder-sandbox"], "plans": [],
                    "thresholds": [70, 90, 100], "email": True, "start": "2026-12-01", "end": None})
    plans += [
        {"id": "P04", "from": "2026-12", "subaccount": "calder-ext-dev",
         "service": "ABAP environment|standard|ACU-hours", "delta": -510,
         "why": "hibernation schedule back on for the ABAP dev system (220 h running)"},
        {"id": "P04", "from": "2026-12", "subaccount": "calder-ext-dev",
         "service": "ABAP environment|standard|HCU-hours", "delta": -1020,
         "why": "same schedule, database side"},
        {"id": "P05", "from": "2026-12", "subaccount": "calder-int-dev",
         "service": "Kyma runtime|aws|capacity units", "delta": -788.4,
         "why": "dev cluster deleted; the MES listener's dev work moves to a local "
                "Kubernetes cluster on the developer's computer"},
    ]
    contract["cf_quota_gb"]["calder-sandbox"] = 4
    CONTRACT.write_text(json.dumps(contract, indent=2) + "\n", encoding="utf-8")
    BUDGETS.write_text(json.dumps({"budgets": budgets}, indent=2) + "\n", encoding="utf-8")
    PLANS.write_text(json.dumps({"changes": plans}, indent=2) + "\n", encoding="utf-8")
    print("Applied: B02 thresholds 80/100 and email on, B03 one plan, new budget B04, "
          "cuts P04 and P05 from 2026-12, sandbox quota 4 GB.")


def load():
    for p in (CONTRACT, RATES, USAGE, BUDGETS, PLANS):
        if not p.exists():
            sys.exit(f"{p} not found. Run: python unit21/btp_cost.py --init")
    contract = json.loads(CONTRACT.read_text(encoding="utf-8"))
    rates = json.loads(RATES.read_text(encoding="utf-8"))["rates"]
    with USAGE.open(encoding="utf-8") as f:
        usage = [r | {"quantity": float(r["quantity"])} for r in csv.DictReader(f)]
    budgets = json.loads(BUDGETS.read_text(encoding="utf-8"))["budgets"]
    plans = json.loads(PLANS.read_text(encoding="utf-8"))["changes"]
    return contract, rates, usage, budgets, plans


def charge(rates, key, qty):
    """Charged quantity and cost for one usage line under the rate card."""
    if key not in rates:
        return qty, None
    rate = rates[key]
    charged = max(0.0, qty - rate.get("prepaid_quota", 0))
    return charged, round(charged * rate["price"], 2)


def costs(rates, usage):
    """month -> subaccount -> service key -> cost; and a list of unpriced keys."""
    out = defaultdict(lambda: defaultdict(dict))
    missing = set()
    for r in usage:
        key = f"{r['service']}|{r['plan']}|{r['metric']}"
        _, c = charge(rates, key, r["quantity"])
        if c is None:
            missing.add(key)
            continue
        out[r["month"]][r["subaccount"]][key] = c
    return out, sorted(missing)


def month_total(by_sub):
    return round(sum(sum(v.values()) for v in by_sub.values()), 2)


def chargeback(contract, cost_m):
    """Cost per Cost object and owner team, global-level cost shared by subaccount cost."""
    subs = contract["subaccounts"]
    direct = {s: round(sum(v.values()), 2) for s, v in cost_m.items() if s != GLOBAL_LEVEL}
    shared = round(sum(cost_m.get(GLOBAL_LEVEL, {}).values()), 2)
    base = sum(direct.values())
    rows = defaultdict(lambda: [0.0, 0.0])
    unlabeled = []
    for s, c in sorted(direct.items()):
        lab = subs.get(s)
        if not lab or not lab.get("Cost object"):
            unlabeled.append(s)
            key = ("(no Cost object)", "(no owner)")
        else:
            key = (lab["Cost object"], lab["Owner team"])
        rows[key][0] += c
        rows[key][1] += shared * c / base if base else 0
    return rows, shared, unlabeled


def forecast(contract, rates, cost, plans):
    """Run-rate forecast: last billed month carried forward, plus planned changes."""
    period = contract["credit_period"]
    billed = contract["last_balance_statement"]
    months = [m for m in MONTHS if period["start"] <= m <= billed]
    spent = round(sum(month_total(cost[m]) for m in months), 2)
    base = month_total(cost[billed])
    out, running = [], spent
    estimate_month = MONTHS[-1]
    for m in [estimate_month] + FUTURE:
        if m > period["end"]:
            break
        extra = 0.0
        for p in plans:
            if p["from"] <= m and p["service"] in rates:
                extra += p["delta"] * rates[p["service"]]["price"]
        month_cost = round(base + extra, 2)
        running = round(running + month_cost, 2)
        out.append((m, month_cost, running))
    return spent, base, out


def check_budgets(contract, budgets, cost_m):
    findings = []
    active = [b for b in budgets if not b.get("end") or b["end"] >= contract["as_of"]]
    if len(active) > MAX_ACTIVE_BUDGETS:
        findings.append(("FAIL", "B--", f"{len(active)} active budgets; SAP allows {MAX_ACTIVE_BUDGETS}"))
    covered = set()
    status = []
    for b in active:
        th = b.get("thresholds", [])
        if len(th) > MAX_THRESHOLDS:
            findings.append(("FAIL", b["id"], f"{len(th)} thresholds; SAP allows {MAX_THRESHOLDS}"))
        bad = [t for t in th if not THRESHOLD_RANGE[0] <= t <= THRESHOLD_RANGE[1]]
        if bad:
            findings.append(("FAIL", b["id"], f"threshold {bad} outside "
                             f"{THRESHOLD_RANGE[0]}-{THRESHOLD_RANGE[1]}% of the amount"))
        if b["type"] == "Charged Usage" and len(b.get("plans", [])) != 1:
            findings.append(("FAIL", b["id"], "a Charged Usage budget needs exactly one service "
                             f"plan (has {len(b.get('plans', []))})"))
        if not b.get("email"):
            findings.append(("WARN", b["id"], "automatic email alerts are off (the default); "
                             "nobody hears about a breach"))
        subs = b.get("subaccounts") or list(contract["subaccounts"])
        covered.update(subs)
        if b["type"] == "Cost":
            spend = round(sum(sum(cost_m.get(s, {}).values()) for s in subs), 2)
            pct = 100 * spend / b["amount"]
            passed = [t for t in th if THRESHOLD_RANGE[0] <= t <= THRESHOLD_RANGE[1] and pct >= t]
            status.append((b["id"], b["name"], spend, b["amount"], pct, passed))
    objects = defaultdict(list)
    for s, lab in contract["subaccounts"].items():
        objects[lab["Cost object"]].append(s)
    for obj, subs in sorted(objects.items()):
        missing = [s for s in subs if s not in covered]
        if missing:
            findings.append(("WARN", obj, f"no budget covers {', '.join(missing)}"))
    return findings, status


def drivers(contract, cost, plans):
    """Course rules for the usual BTP cost leaks. A cut in plans.json marks one addressed."""
    cuts = {(p["subaccount"], p["service"]): p["id"] for p in plans if p["delta"] < 0}
    findings = []
    last, prev = MONTHS[-2], MONTHS[-3]          # last billed month and the one before
    for s, svc in cost[last].items():
        for key, c in svc.items():
            before = cost[prev].get(s, {}).get(key, 0)
            if before and c >= SPIKE_RATIO * before and c - before >= SPIKE_MIN:
                fix = cuts.get((s, key))
                findings.append(("OK" if fix else "WARN", s + (f" (addressed by {fix})" if fix else ""), f"{key.split('|')[0]} {key.split('|')[2]}: "
                                 f"{before:,.2f} in {prev}, {c:,.2f} in {last}"))
    for s, lab in contract["subaccounts"].items():
        svc = cost[last].get(s, {})
        kyma = "Kyma runtime|aws|capacity units"
        if lab["Stage"] != "Prod" and kyma in svc:
            fix = cuts.get((s, kyma))
            findings.append(("OK" if fix else "WARN", s + (f" (addressed by {fix})" if fix else ""), "a non-production Kyma cluster bills its 3-node floor "
                             "all month; share one or remove it when idle"))
    for s, gb in contract.get("cf_quota_gb", {}).items():
        if gb >= 200:
            findings.append(("WARN", s, f"Cloud Foundry memory quota {gb} GB is the consumption "
                             "default; set a numeric quota as a cost limit"))
    return findings


def money(x):
    return f"{x:,.2f}"


def report(contract, rates, usage, budgets, plans, month, to_file=False):
    cost, missing = costs(rates, usage)
    cur = contract["currency"]
    lines = []
    p = lines.append
    p(f"Calder Pumpworks BTP cost control, as of {contract['as_of']} (course values; "
      "rates are placeholders, not SAP prices)")
    p(f"Model: {contract['model']}. Credit period {contract['credit_period']['start']} to "
      f"{contract['credit_period']['end']}, credits {money(contract['credit_period']['credits'])} {cur}.")
    if missing:
        p("UNPRICED (add to the rate card): " + "; ".join(missing))
    p("")
    p(f"1. Chargeback for {month} (billed month)")
    rows, shared, unlabeled = chargeback(contract, cost[month])
    p(f"   {'Cost object':<12}{'Owner team':<14}{'Direct':>11}{'Shared':>10}{'Total':>11}")
    for (obj, team), (d, s) in sorted(rows.items()):
        p(f"   {obj:<12}{team:<14}{money(d):>11}{money(s):>10}{money(d + s):>11}")
    total = month_total(cost[month])
    p(f"   {'Global account total':<26}{'':>11}{money(shared):>10}{money(total):>11}")
    for s in unlabeled:
        p(f"   FAIL {s}: no Cost object label, its cost can't be charged back")
    p("")
    p(f"2. Budgets against {MONTHS[-1]} month to date (estimated values until the next "
      "balance statement)")
    bf, status = check_budgets(contract, budgets, cost[MONTHS[-1]])
    for bid, name, spend, amt, pct, passed in status:
        note = f"thresholds passed: {', '.join(f'{t}%' for t in passed)}" if passed else "below thresholds"
        p(f"   {bid} {name:<22}{money(spend):>10} of {money(amt):>9} ({pct:.0f}%)  {note}")
    p("   A budget alerts; it never stops usage.")
    for level, who, msg in bf:
        p(f"   {level} {who}: {msg}")
    p("")
    p("3. Credit forecast (run rate of the last billed month plus plans.json)")
    spent, base, fc = forecast(contract, rates, cost, plans)
    credits = contract["credit_period"]["credits"]
    p(f"   Billed {contract['credit_period']['start']} to {contract['last_balance_statement']}: "
      f"{money(spent)}; run rate {money(base)} a month")
    run_out = None
    for m, c, r in fc:
        flag = ""
        if r > credits and not run_out:
            run_out = m
            flag = "  <- credits used up"
        p(f"   {m}  {money(c):>10}  cumulative {money(r):>11}{flag}")
    end_total = fc[-1][2] if fc else spent
    if end_total > credits:
        p(f"   FAIL forecast {money(end_total)} exceeds credits by {money(end_total - credits)}: "
          f"overage {contract['overage']}")
    elif end_total > credits * (1 - HEADROOM):
        p(f"   WARN forecast {money(end_total)} leaves less than {HEADROOM:.0%} of the credits")
    else:
        p(f"   OK forecast {money(end_total)} leaves {money(credits - end_total)} unspent")
    p("")
    p(f"4. Cost drivers in {MONTHS[-2]}")
    df = drivers(contract, cost, plans)
    for level, who, msg in df:
        p(f"   {level} {who}: {msg}")
    if not df:
        p("   OK nothing flagged")
    all_f = bf + df + ([("FAIL", "forecast", "")] if end_total > credits else [])
    counts = {k: sum(1 for f in all_f if f[0] == k) for k in ("FAIL", "WARN")}
    p("")
    p(f"Result: {counts['FAIL']} FAIL, {counts['WARN']} WARN")
    text = "\n".join(lines)
    print(text)
    if to_file:
        fence = "`" * 3
        REPORT.write_text(
            f"# Calder BTP cost review ({contract['as_of']})\n\n{fence}text\n{text}\n{fence}\n\n"
            "## Decision record: closing the credit gap\n\n"
            "- **Context:** (forecast against credits; which drivers caused the gap)\n"
            "- **Options:** (1) top up credits now, (2) remove the waste and re-forecast, "
            "(3) accept overage at list price\n"
            "- **Decision:** (which option, owner, date)\n"
            "- **Consequences:** (budgets to change, what is reviewed each month)\n",
            encoding="utf-8")
        print(f"\nWrote {REPORT}. Fill in the decision record before the review.")
    return 1 if counts["FAIL"] else 0


def main():
    ap = argparse.ArgumentParser(description="Calder's BTP cost control (course values)")
    ap.add_argument("--init", action="store_true", help="write the sample files")
    ap.add_argument("--month", default="2026-10", help="billed month for the chargeback")
    ap.add_argument("--apply-fixes", action="store_true", help="apply the walkthrough's fixes")
    ap.add_argument("--write", action="store_true", help="also write the review document")
    a = ap.parse_args()
    if a.init:
        write_samples()
        return
    if a.apply_fixes:
        apply_fixes()
        return
    data = load()
    if a.month not in MONTHS[:-1]:
        sys.exit(f"--month must be a billed month: {', '.join(MONTHS[:-1])}")
    sys.exit(report(*data, month=a.month, to_file=a.write))


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

#### Step 3: Write the sample files

1. Run:

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

2. You should see:

   ```text
   Wrote 5 files to unit21/cost: contract, rate card, usage (154 rows), budgets, plans.
   ```

3. Open `unit21/cost/usage.csv`. Each row is one month of one meter in one subaccount, such as `2026-10,calder-ext-dev,ABAP environment,standard,ACU-hours,730`. The columns are the course's own, loosely shaped like the cockpit export's usage sheet.
4. Open `unit21/cost/contract.json`. Calder is on SAP BTPEA with 70,000.00 of credits from April 2026 to March 2027, a course assumption. Its integration hub is held by subscription, so usage inside the prepaid quota costs nothing extra.

> **Note** All files are made up. Calder, its subaccounts, its usage and the rates are course values; they show the method, not results from a real SAP account.

#### Step 4: Run the review

1. Run:

   ```bash
   python unit21/btp_cost.py
   ```

2. The output:

   ```text
   Calder Pumpworks BTP cost control, as of 2026-11-27 (course values; rates are placeholders, not SAP prices)
   Model: SAP BTPEA (course assumption). Credit period 2026-04 to 2027-03, credits 70,000.00 USD.

   1. Chargeback for 2026-10 (billed month)
      Cost object Owner team         Direct    Shared      Total
      CP10-910    Apps             3,890.00    218.25   4,108.25
      CP10-910    BTP platform        60.00      3.37      63.37
      CP10-910    Integration      1,914.48    107.41   2,021.89
      CP10-920    AI platform      1,265.00     70.97   1,335.97
      Global account total                     400.00   7,529.48

   2. Budgets against 2026-11 month to date (estimated values until the next balance statement)
      B01 AI platform monthly     1,315.00 of  2,000.00 (66%)  below thresholds
      B02 Apps monthly            3,890.00 of  3,500.00 (111%)  thresholds passed: 80%
      A budget alerts; it never stops usage.
      FAIL B02: threshold [150] outside 1-120% of the amount
      WARN B02: automatic email alerts are off (the default); nobody hears about a breach
      FAIL B03: a Charged Usage budget needs exactly one service plan (has 2)
      WARN CP10-910: no budget covers calder-int-dev, calder-int-test, calder-int-prod, calder-sandbox

   3. Credit forecast (run rate of the last billed month plus plans.json)
      Billed 2026-04 to 2026-10: 31,501.20; run rate 7,529.48 a month
      2026-11    7,529.48  cumulative   39,030.68
      2026-12    7,529.48  cumulative   46,560.16
      2027-01    8,500.36  cumulative   55,060.52
      2027-02    8,620.36  cumulative   63,680.88
      2027-03    8,620.36  cumulative   72,301.24  <- credits used up
      FAIL forecast 72,301.24 exceeds credits by 2,301.24: overage billed in arrears at list price

   4. Cost drivers in 2026-10
      WARN calder-ext-dev: ABAP environment ACU-hours: 286.00 in 2026-09, 949.00 in 2026-10
      WARN calder-ext-dev: ABAP environment HCU-hours: 264.00 in 2026-09, 876.00 in 2026-10
      WARN calder-int-dev: a non-production Kyma cluster bills its 3-node floor all month; share one or remove it when idle
      WARN calder-sandbox: Cloud Foundry memory quota 200 GB is the consumption default; set a numeric quota as a cost limit

   Result: 3 FAIL, 6 WARN
   ```

> **Note** Every amount above comes from synthetic data and placeholder rates. It shows the method, not a result from a real SAP account.

3. Read it section by section:
   - **Chargeback.** The 400.00 of global-level cost is shared in proportion to each team's direct cost, a rule Calder chose. Write your rule down; SAP doesn't choose one for you.
   - **Budgets.** B02 has a 150% threshold, which SAP doesn't allow, and its email alert is off. B03 is a *Charged Usage* budget on two plans, which SAP doesn't allow either. The integration and sandbox subaccounts have no budget at all.
   - **Forecast.** The credits run out in March 2027 by 2,301.24. Calder's global account is younger than nine months, so the cockpit's own forecast isn't available yet. That is why this script exists.
   - **Drivers.** The ABAP development system ran 730 hours in October instead of 220. A development Kyma cluster bills its floor all month. The sandbox keeps the 200 GB default quota.

4. Look at another billed month: `python unit21/btp_cost.py --month 2026-09`. September's total is 6,204.48, before the ABAP schedule broke.

#### Step 5: Apply the fixes and review again

1. Run:

   ```bash
   python unit21/btp_cost.py --apply-fixes
   ```

2. You should see:

   ```text
   Applied: B02 thresholds 80/100 and email on, B03 one plan, new budget B04, cuts P04 and P05 from 2026-12, sandbox quota 4 GB.
   ```

3. Open `unit21/cost/plans.json`. P04 restores the hibernation schedule from December (510 fewer ABAP compute-unit hours and 1,020 fewer database compute-unit hours a month). P05 deletes the development Kyma cluster. Each cut has a `why`, because the review asks who decided it.
4. Run the review again and write the document:

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

5. The parts that changed:

   ```text
   2. Budgets against 2026-11 month to date (estimated values until the next balance statement)
      B01 AI platform monthly     1,315.00 of  2,000.00 (66%)  below thresholds
      B02 Apps monthly            3,890.00 of  3,500.00 (111%)  thresholds passed: 80%, 100%
      B04 Platform and sandbox    2,074.48 of  2,200.00 (94%)  thresholds passed: 70%, 90%
      A budget alerts; it never stops usage.

   3. Credit forecast (run rate of the last billed month plus plans.json)
      Billed 2026-04 to 2026-10: 31,501.20; run rate 7,529.48 a month
      2026-11    7,529.48  cumulative   39,030.68
      2026-12    5,387.24  cumulative   44,417.92
      2027-01    6,358.12  cumulative   50,776.04
      2027-02    6,478.12  cumulative   57,254.16
      2027-03    6,478.12  cumulative   63,732.28
      OK forecast 63,732.28 leaves 6,267.72 unspent

   4. Cost drivers in 2026-10
      OK calder-ext-dev (addressed by P04): ABAP environment ACU-hours: 286.00 in 2026-09, 949.00 in 2026-10
      OK calder-ext-dev (addressed by P04): ABAP environment HCU-hours: 264.00 in 2026-09, 876.00 in 2026-10
      OK calder-int-dev (addressed by P05): a non-production Kyma cluster bills its 3-node floor all month; share one or remove it when idle

   Result: 0 FAIL, 0 WARN

   Wrote unit21/calder_btp_cost.md. Fill in the decision record before the review.
   ```

> **Note** Synthetic data again: the 6,267.72 left over is a course figure that shows the method.

6. Notice what didn't change. November is already spent, so B02 is still over its amount and both cuts only count from December. A budget alert in October would have saved a month.

#### Step 6: Write the decision record

1. Open `unit21/calder_btp_cost.md`.
2. Fill in the four lines under *Decision record: closing the credit gap*. Calder's choice is option 2: remove the waste and re-forecast, with a top-up only if the January review shows less than 5% headroom.
3. Save your work with Git:

   ```bash
   git add unit21/btp_cost.py unit21/cost unit21/calder_btp_cost.md
   git commit -m "Unit 21: BTP cost review"
   ```

#### Step 7 (optional, sketch): read your own figures

> **Note** **Sketch.** This needs a consumption-based enterprise global account and the Global Account Administrator or Viewer role; a trial account has no Costs and Usage page. The account setup is covered in [Set up for Unit 21](https://erpfde.com/topics/set-up-for-unit-21/) and [the BTP account model](https://erpfde.com/topics/btp-account-model/).

1. In the cockpit, open the global account and choose **Costs and Usage**.
2. Choose **Export**, then **Custom**, and add your label names (for example `Cost object`) as columns.
3. For automation, SAP documents the **Resource Consumption** APIs of the SAP Usage Data Management service ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/monitoring-usage-information-using-apis-of-the-sap-usage-data-management-service-bf2b304.md)). You create an instance of the `uas` service with plan `reporting-ga-admin` (or `reporting-directory`), take the OAuth client from its key, and call methods such as `/monthlyUsage` and `/cloudCreditsDetails`. Keep the client secret in your `.env` file, never in code.
4. Convert your export into the `usage.csv` columns and your contract's prices into `rate_card.json`, then run the script on your own data.

#### How the code works

| Part | What it does |
| --- | --- |
| `MAX_ACTIVE_BUDGETS`, `MAX_THRESHOLDS`, `THRESHOLD_RANGE` | SAP's documented budget limits |
| `SPIKE_RATIO`, `SPIKE_MIN`, `HEADROOM` | Course rules for a spike and the minimum unspent share |
| `sample_*()` | Calder's made-up contract, rates, 8 months of usage, budgets and planned changes |
| `charge()` | Applies a rate, minus any prepaid subscription quota |
| `chargeback()` | Groups a month by `Cost object` and `Owner team`, shares global-level cost by direct cost |
| `check_budgets()` | Checks SAP's budget rules, computes month-to-date spend and passed thresholds, finds cost objects without a budget |
| `forecast()` | Billed cost so far, then the last billed month carried forward plus `plans.json` |
| `drivers()` | Spikes, non-production Kyma floors and default quotas; a negative plan marks one addressed |
| `apply_fixes()` | The walkthrough's fixes, so everyone's second run matches |
| `report()` | Prints the four sections, returns exit code 1 on any FAIL, writes the document with `--write` |

#### 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 environment is off | Turn on `.venv` (Step 1); on macOS/Linux try `python3` |
| `SyntaxError` near `r | {` | Python older than 3.9 | Install the version from the course setup topic |
| `unit21/cost/contract.json not found` | Sample files not written | Run `python unit21/btp_cost.py --init` |
| `usage.csv already exists` | `--init` refuses to overwrite | Delete the `unit21/cost` folder, then run `--init` again |
| `Fixes are already applied.` | `--apply-fixes` ran before | Nothing to do; or start again from `--init` |
| `UNPRICED (add to the rate card)` | A usage line has no rate | Add the service, plan and metric key to `rate_card.json` |
| `--month must be a billed month` | November is still an estimate | Choose a month from 2026-04 to 2026-10 |
| Cockpit shows no Costs and Usage page (Step 7) | Trial or subscription-only account | Subscription-only accounts get a Usage page instead; trials have neither |
| Export or API blocked (Step 7) | Network or proxy | Ask IT to allow the SAP BTP cockpit and API hosts |

No library is installed, so there is no "missing library" case, and no key is needed outside the optional sketch.

### The SAP way

As of November 2026, SAP's tooling for each step:

- **Estimate:** the **SAP BTP Cost Estimator** in the SAP Discovery Center. SAP Learning describes naming an estimate, choosing a region and commercial model, adding services with sizing metrics, and exporting it as PDF or CSV ([SAP Learning](https://learning.sap.com/courses/becoming-an-sap-btp-solution-architect/exploring-sap-btp-commercial-models)). An SAP employee's community post lists separate estimators for SAP HANA Cloud, SAP AI Core and others, and advises comparing actual cockpit cost with the estimate ([SAP Community](https://community.sap.com/t5/technology-blog-posts-by-sap/bookmark-how-to-estimate-your-costs-using-cost-estimator-to-track-your/ba-p/14287858)).
- **Limit:** entitlements and quotas per directory and subaccount, and space quota plans in Cloud Foundry (covered in [the BTP account model](https://erpfde.com/topics/btp-account-model/)).
- **Attribute:** labels on directories and subaccounts, searchable on the Billing and Usage tabs and exportable as columns.
- **Watch:** the Costs and Usage page, its recommendations card (budget alerts, credit monitoring, cost spikes) and the prepaid quota card for mixed contracts.
- **Alert:** budgets, with email or the `BudgetAlertThresholdExceeded` event through SAP Alert Notification service.
- **Report:** the cockpit export (12, 24 or 36 months) and the Resource Consumption APIs.
- **Settle:** the balance statement in SAP for Me.

Licensing notes. Check service availability per region and per commercial model in the Discovery Center catalog: SAP says not every consumption-eligible service is available by subscription. The consumption model and budget alerts are subject to availability in your country or region ([SAP BTP documentation](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/what-is-the-consumption-based-commercial-model-7047eb4.md)).

### Build vs. SAP

| Need | SAP's tool | Build your own | Choose |
| --- | --- | --- | --- |
| Price a design before buying | Discovery Center estimator | Spreadsheet over the rate card | SAP's estimator, saved per stage |
| Alert on spend this month | Budgets | Polling the API | SAP budgets; route events to your channels |
| Forecast credits to period end | *Show forecast* (9 months of history, BTPEA and CPEA) | Run rate plus planned changes, as in this lab | Both: yours until SAP's is available, then compare |
| Charge cost to teams | Labels and export | Script over the export or API | Labels in SAP, the split rule in your script |
| Find waste | Recommendations card | Rules for floors, schedules, quotas | Both; your rules know your schedules |

### Architecture view

**Where it sits.** Cost control sits at the global account, above every subaccount in the [account model](https://erpfde.com/topics/btp-account-model/). Data flows out: the cockpit and the Resource Consumption APIs feed a chargeback job, finance's controlling system and the alert channel.

```mermaid
flowchart LR
  GA[Global account<br/>credits, budgets] --> UDM[Resource Consumption API<br/>uas reporting-ga-admin]
  GA --> ANS[Alert Notification<br/>BudgetAlertThresholdExceeded]
  UDM --> JOB[Monthly chargeback job]
  JOB --> CO[S/4HANA CP10<br/>cost centers CP10-910, CP10-920]
  ANS --> TEAM[Owner team channel]
```

**Non-functional requirements.**

| Requirement | Typical target | What breaks if missed |
| --- | --- | --- |
| Attribution | 100% of subaccount cost carries a cost object | Unowned cost lands on the platform team |
| Alert latency | Within days of a threshold; SAP warns alerts can be delayed | Waste runs a whole month |
| Forecast cadence | After every balance statement | Overage found too late to top up |
| Data retention | 36 months of export for audits and renewals | Renewal sizing on guesswork |
| Access | Viewer role for finance, admin for few | Finance can't check the bill, or too many can change budgets |

**Integration and identity.** The chargeback job calls the Resource Consumption APIs with an OAuth client from a `uas` service key; SAP notes the `subaccountUsage` method also needs the password grant with a user holding Global Account Administrator or Viewer. Store that secret like any other binding ([services and bindings](https://erpfde.com/topics/btp-services-and-bindings/)). The job posts internal allocations to Calder's controlling, which is an ordinary S/4HANA posting outside BTP.

**The decision to record.**

- **Context:** Calder's credits will run out in March 2027 at the current run rate; the gap comes from two avoidable drivers.
- **Options:** (1) top up credits now; (2) remove the waste and re-forecast monthly; (3) accept overage at list price.
- **Decision:** option 2, with a top-up if headroom falls under 5% at the January review.
- **Consequences:** every non-production ABAP system has a hibernation schedule owned by its team; development Kyma clusters need a written reason; budgets cover every cost object with alerts on.

**What a design review will ask.**

1. What is the monthly running cost per stage, and which estimate is it from?
2. Which cost object and owner carry it, and is that encoded as labels?
3. Which budget covers it, at what thresholds, and who receives the alert?
4. What scales the cost (users, documents, nodes), and what is the cost at twice the volume?
5. How is it switched off when no longer needed?

### Production concerns

- **Authorizations.** Budgets and the Costs and Usage page need Global Account Administrator or Viewer. Give finance the viewer role; keep administrators few ([BTP security model](https://erpfde.com/topics/btp-security-model/)).
- **Evaluation.** Compare each month's actuals with the estimate. A design that misses by more than your tolerance gets reviewed, not just paid.
- **Cost of the controls.** Email alerts are free; SAP Alert Notification service is paid. The chargeback job itself runs on BTP and costs a little.
- **Operations.** One person owns the monthly review. The balance statement, not the cockpit, closes the month.
- **Clean core.** Nothing here touches S/4HANA beyond posting allocations with standard interfaces.

### Where AI fits

AI changes this subject in two ways. First, **AI services are the least predictable line**: their cost grows with adoption, so they need a *Charged Usage* budget per plan and a sizing from SAP's AI Core estimator before go-live; AI Units for Joule Studio agents follow their own rules ([pricing custom agents](https://erpfde.com/topics/pricing-custom-agents-after-the-free-runtime/)). Second, **an agent can do the monthly review's legwork**: read the export, explain spikes and draft the decision record. It should only draft. Changing a quota or deleting a cluster stays a person's decision, under the same approval rules as any agent action ([AI gateways](https://erpfde.com/topics/ai-gateways-for-model-and-agent-traffic/)).

### Pitfalls

- **Treating the cockpit as the bill.** Close the month on the balance statement.
- **Budgets with alerts off.** Automatic email is off by default; check every budget.
- **A *Charged Usage* budget across several plans.** SAP allows one plan; use a *Cost* budget for groups.
- **Forgetting global-level services.** They need an allocation rule, or the platform team pays them.
- **Leaving default quotas.** 200 GB of Cloud Foundry memory per subaccount is a lot of room for a sandbox.
- **Forecasting from a flat run rate alone.** Add planned go-lives and cuts, or the forecast is wrong by design.
- **Assuming you can mix flavors.** One consumption flavor per global account; plan BTPEA moves at renewal.

### Exercise

Calder's Augsburg directory (from [the BTP account model](https://erpfde.com/topics/btp-account-model/) exercise) goes live in January 2027 with two subaccounts on cost object `CP20-910`.

1. In `unit21/cost/contract.json`, add to `subaccounts`:

   ```json
   "calder-aug-dev": {"Stage": "Dev", "Owner team": "Apps", "Cost object": "CP20-910"},
   "calder-aug-prod": {"Stage": "Prod", "Owner team": "Apps", "Cost object": "CP20-910"}
   ```

2. In `unit21/cost/plans.json`, add two changes with `"id": "P06"`, `"from": "2027-01"`, one per subaccount, service `Cloud Foundry runtime|standard|GB memory`, `"delta": 1`, and a `why`.
3. Run `python unit21/btp_cost.py`. You should see one new WARN: no budget covers the Augsburg subaccounts.
4. In `unit21/cost/budgets.json`, add budget `B05` *Augsburg apps*: type `Cost`, amount 400.00, both subaccounts, thresholds 80 and 100, email on, start `2027-01-01`.
5. Run `python unit21/btp_cost.py --write` and add the Augsburg line to the decision record's consequences.

**Done when** the review prints `Result: 0 FAIL, 0 WARN`, the forecast ends at 64,092.28 with 5,907.72 unspent, and `calder_btp_cost.md` names the Augsburg budget. The file feeds [the resilience topic](https://erpfde.com/topics/btp-resilience-and-multi-region/), where a second region changes the cost.

### Check yourself

1. Calder's global account is seven months old. Why can't the platform team use the cockpit's *Show forecast* for its BTPEA credits yet?
   - A. The forecast is only offered on Pay-As-You-Go accounts
   - B. SAP needs at least nine months of history to offer it
   - C. The forecast only works once a budget with three thresholds exists
   - D. It is offered only in the last month of each credit period

   Answer: B. SAP documents that the forecast needs at least nine months of history, covers up to six months or the period end, and isn't offered in a period's last month or on Pay-As-You-Go. Until then, a run-rate forecast of your own fills the gap.

2. In the lab, why does `chargeback()` add a "Shared" column instead of leaving the 400.00 global-level cost out?
   - A. SAP adds the shared share to each subaccount on the balance statement
   - B. The Resource Consumption API refuses to return global-level cost
   - C. Some services report only at global level and need a rule
   - D. Labels on the global account are inherited by every subaccount automatically

   Answer: C. SAP lists such services under `REPORTED-AT-GLOBAL-ACCOUNT-LEVEL` with ID `DEFAULT_SA`. Calder's course rule shares them by direct cost; without a rule, the platform team silently carries them.

3. The first review fails B03, a *Charged Usage* budget on SAP AI Core and Cloud Foundry. What is the right fix?
   - A. Raise its thresholds above 120% so it stops alerting
   - B. Switch its email alerts on so the budget becomes valid
   - C. Remove the scope so it covers every plan by default
   - D. Keep one plan, and use a *Cost* budget for the others

   Answer: D. SAP requires a *Charged Usage* budget to monitor exactly one service plan (and one metric), because it counts that plan's own unit. Groups of plans need a *Cost* budget, which sums list-price money.

4. After `--apply-fixes`, budget B02 still shows 111% for November. Why didn't the fix bring it down?
   - A. The script only re-reads budgets.json at the start of a new month
   - B. November is spent; the cuts in plans.json start in December
   - C. Budget thresholds can't be edited once they have been passed
   - D. The ABAP environment reports cost only at global account level

   Answer: B. The fixes change thresholds and future usage, not the past. P04 and P05 start in 2026-12, so they lower the forecast but not November's estimate, which is why an alert in October would have saved a month.

5. What does `charge()` do with SAP Integration Suite usage of 104 units against a prepaid quota of 100?
   - A. It charges all 104 units because consumption overrides the subscription
   - B. It charges nothing because subscription services are always prepaid
   - C. It charges the 4 units above the quota at the rate card's price
   - D. It stops with an error because a service can't have two models

   Answer: C. SAP documents that in mixed contracts usage within the prepaid quota is covered by the subscription and usage beyond it is billed on consumption terms. The lab models that with `prepaid_quota` in the rate card.

6. A developer proposes keeping the development Kyma cluster "because it is small: one workload of 2 GB". What do you tell them?
   - A. Fine, since Kyma bills only for the memory that the pods reserve
   - B. The cluster bills its three-node floor all month
   - C. Fine, since non-production clusters are free on consumption contracts
   - D. Move it to the trial account, which can host project work for free

   Answer: B. Kyma is metered by node capacity, and the cluster has a three-node floor even when idle, as the runtime topic showed. A local cluster or a shared one avoids that; trial accounts aren't for team or productive work.

7. You build the chargeback job on the Resource Consumption APIs. Where does its credential belong?
   - A. In the Python file, so the job runs without extra setup
   - B. In a label on the global account, so finance can see it
   - C. In the budget's description field, next to the threshold
   - D. In a `uas` key, with its secret in `.env` or a vault

   Answer: D. SAP's APIs are protected with OAuth from a `uas` service instance (plan `reporting-ga-admin` or `reporting-directory`). The client secret is a credential like any binding: never in code, rotated and owned.

8. Calder's January review shows 4% headroom left on the credits after the cuts. Under the decision record, what happens next?
   - A. Accept overage at list price, since cuts have already been made
   - B. Switch the global account to Pay-As-You-Go for the last quarter
   - C. Top up credits, as the record made 5% headroom the trigger
   - D. Delete budgets B01 to B05, since they no longer change anything

   Answer: C. The decision was option 2 with a top-up if headroom falls under 5%. SAP allows top-ups at any time to prevent overage; accepting overage or moving to Pay-As-You-Go would put the extra usage at list price.

## Sources

- [Commercial Models (SAP BTP documentation, SAP-docs on GitHub, repository updated 16 November 2026, read 2026-11-27)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/commercial-models-263d400.md): two models for enterprise accounts, consumption-based (flavors SAP BTPEA, CPEA, Pay-As-You-Go) and subscription-based; both can be used in separate or the same global account; never more than one consumption flavor in one global account
- [What Is the Consumption-Based Commercial Model? (SAP BTP documentation, read 2026-11-27)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/what-is-the-consumption-based-commercial-model-7047eb4.md): BTPEA and CPEA prepaid cloud credits with an annual commitment, minimum investment, volume discounts, billed annually in advance, overages in arrears at list price, top-ups; Pay-As-You-Go with no commitment, billed monthly in arrears, not discountable, transition to CPEA; default 200 GB Cloud Foundry memory quota per subaccount
- [What Is the Subscription-Based Commercial Model? (SAP BTP documentation, read 2026-11-27)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/what-is-the-subscription-based-commercial-model-239b6e0.md): fixed price and period, typically 1 to 3 years, only subscribed services, paid in advance, user or resource metrics, bundles; moving from consumption to subscription is possible but not every service is compatible
- [Monitoring Usage and Consumption Costs in Your Global Account (SAP BTP documentation, read 2026-11-27)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/monitoring-usage-and-consumption-costs-in-your-global-account-de6f0db.md): Costs and Usage page (Overview, Billing, Usage, Budgets tabs); balance statement legally binding; global account the only billable entity, subaccount and directory figures estimates; estimated values striped; forecast needs at least 9 months of history and covers 6 months or the period end; REPORTED-AT-GLOBAL-ACCOUNT-LEVEL entity; export of 12, 24 or 36 months with label columns; recommendations card including cost spikes
- [Managing Budgets in Your Global Account (SAP BTP documentation, read 2026-11-27)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/managing-budgets-in-your-global-account-e115d5f.md): Cost or Charged Usage budgets, up to 30 active, scope by subaccount and service plan, up to three thresholds from 1% to 120%, automatic email off by default, BudgetAlertThresholdExceeded event to SAP Alert Notification service (paid); budgets don't suspend usage; estimates between statements; prepaid subscription quota not evaluated
- [Monitoring Usage Information Using APIs of the SAP Usage Data Management Service (SAP BTP documentation, read 2026-11-27)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/monitoring-usage-information-using-apis-of-the-sap-usage-data-management-service-bf2b304.md): Resource Consumption APIs at /reports/v1 (cloudCreditsDetails, monthlyUsage, monthlyDirectoryUsage, subaccountUsage, monthlySubaccountsCost); uas service plans reporting-ga-admin and reporting-directory
- [Try and buy SAP Business Technology Platform (sap.com pricing page, read 2026-11-27)](https://www.sap.com/products/technology-platform/pricing.html): trial 90 days, free tier through SAP BTPEA or Pay-As-You-Go, existing CPEA customers may continue and renew and can move to SAP BTPEA, overages invoiced monthly at list price, pricing in the SAP Discovery Center service catalog; no prices shown
- [Exploring SAP BTP Commercial Models and Estimating Costs (SAP Learning, Becoming an SAP BTP Solution Architect, read 2026-11-27)](https://learning.sap.com/courses/becoming-an-sap-btp-solution-architect/exploring-sap-btp-commercial-models): Always Free versus Free Tier; the SAP BTP Cost Estimator in SAP Discovery Center (name, region, commercial model, services, sizing metrics; PDF or CSV export; shared estimates when logged in)
- [Bookmark: how to estimate your costs using the cost estimator (SAP Community, Technology Blog Posts by SAP, read 2026-11-27)](https://community.sap.com/t5/technology-blog-posts-by-sap/bookmark-how-to-estimate-your-costs-using-cost-estimator-to-track-your/ba-p/14287858): the estimator at discovery-center.cloud.sap/estimator for most services and separate estimators for SAP HANA Cloud, SAP AI Core and other services; compare actual costs in the cockpit with the estimate
- [Trial Accounts and Free Tier (SAP BTP documentation, read 2026-11-27)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/10-concepts/trial-accounts-and-free-tier-046f127.md): free tier plans get community support and no SLA; Always Free plans are included in the BTP contract; Kyma free plan once per global account for up to 30 days; trial data can't move to an enterprise account
