# SAP Build Process Automation with AI

> Know which AI SAP ships in its low-code process tool and Joule Studio, and build Calder's PO approval with a tested decision table and a document step.

- Course: Orchestrate, Unit 14 · AI across SAP's cloud suite
- Page: https://erpfde.com/topics/sap-build-process-automation-with-ai/
- Updated: 2026-11-23
- Reading time: Foundational 9 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 Build Process Automation** is SAP's low-code tool for business workflows. You draw a process: something starts it, a form asks a person to approve, a decision table picks who, a bot or an API call does the work. It runs on SAP's Business Technology Platform (BTP), next to S/4HANA rather than inside it.

AI shows up in two places, and the difference matters:

- **While you build.** Joule drafts processes, forms and decision tables from a sentence, and summarizes processes nobody documented. A person still checks what it drew.
- **While the process runs.** A document step reads PDFs and scans, such as a supplier's quote, and turns them into fields the process can use.

Next to it sits **Joule Studio**, where agents and, for early adopters, **n8n** workflows are built. An agent decides its own steps; a process follows the steps you drew. Most approvals want the second.

### Why it matters to the business

Approvals are where work waits. A purchase order above a limit sits in someone's inbox. A quote arrives as a PDF and a buyer retypes the price. A rule lives in a manager's head, so nobody can say why one order needed two signatures and another none.

A low-code process fixes the waiting by making the steps explicit and visible. AI then cuts two costs on top. It shortens the build, because a functional consultant can describe a rule instead of typing it. And it removes retyping, because the document step reads the quote.

Take **Calder Pumpworks**, the course's fictional pump maker. In the [fit-to-standard topic](https://erpfde.com/topics/fit-to-standard-and-extension-choices/), Calder asked for one approval rule, R05: the plant manager approves purchase orders above 25,000 USD. That was classed as configuration, using S/4HANA's own flexible workflow. Now purchasing wants more: check each PO against the supplier's quote, skip approval for orders from Calder's own German company, and keep a log the auditors can read. That is where a process tool, and its AI, earns a look.

The risks are specific:

- **A generated rule can be wrong in a way that looks right.** A boundary of "25,000 or more" instead of "above 25,000" changes who signs.
- **Extraction can misread.** A quote with an unfamiliar layout gives a wrong price, or none.
- **Approval is a control.** Auditors will ask who approved, who could have, and whether the creator approved their own order.

### How SAP does it

As of November 2026, SAP's pages describe these AI pieces for SAP Build Process Automation and its neighbors. Each has its own status and commercial terms, so read the label before you plan.

| Capability | What SAP describes | Status and terms on SAP's page |
| --- | --- | --- |
| Joule for developers in SAP Build | Generates processes, forms, decisions and scripts from natural language, and summarizes artefacts ([features](https://www.sap.com/uk/products/technology-platform/process-automation/features.html)) | Design time only; enabled from the SAP Build lobby by accepting the SAP AI Terms; offered free ([Joule for developers](https://www.sap.com/products/artificial-intelligence/joule-for-developers.html)) |
| Decision generation | Creates decision artifacts from a plain description of the rules ([SAP page](https://www.sap.com/spain/products/technology-platform/build-process-automation-decision-generation.html)) | AI Units not currently required, "subject to change" |
| Process summarization | Writes business summaries of undocumented process models ([SAP page](https://www.sap.com/products/technology-platform/build-process-automation-process-summarization.html)) | AI Units currently required |
| Document data extraction | Reads scanned PDFs and images, with or without templates; template-free extraction uses LLMs through SAP Document AI ([SAP page](https://www.sap.com/uk/products/technology-platform/build-process-automation-document-data-extraction.html)) | AI Units not currently required; price on request; the features page ties LLM extraction to the premium edition of Document Information Extraction |
| Agents and n8n in Joule Studio | No-code and pro-code tools to build and extend agents; n8n workflows for customers in the Joule Studio early adopter program ([SAP News, 27 October 2026](https://news.sap.com/2026/10/sap-teched-ai-developers-build-what-matters-autonomous-execution/)) | n8n "broader availability to follow"; runtime free through December 2026 for select customers |

SAP's pricing page lists **Advanced user** (a builder) and **Standard user** (someone who starts or takes part in workflows) plans, attended automation, and add-ons such as unattended automations at USD 590.00 a month per connection ([pricing](https://www.sap.com/products/technology-platform/process-automation/pricing.html)). It lists no AI items, so AI terms come from each AI feature's own page.

> **Note** **For functional consultants.** This is the low-code tool aimed at you. You can draw the process, write the decision table and design the form. Three things change in your work. Your rule now needs **test cases**, written before you trust a table Joule drafted. Your test plan gains a **document step**: quotes in every layout your suppliers send. And your role design gains **process roles** on BTP next to the S/4HANA ones. Connections to S/4HANA (destinations, Cloud Connector, Integration Suite) usually need a BTP administrator.

### A decision guide: which tool for an approval?

| Situation | Start with | Why |
| --- | --- | --- |
| One approval on one S/4HANA document, rules on its own fields (amount, plant, purchasing group) | S/4HANA flexible workflow | Configuration, no extra platform; Calder's R05 alone lands here |
| Approval that needs a document read, a second system, or a custom form | SAP Build Process Automation | Forms, decision tables and document steps in one process |
| Steps that change with the case, where judgment picks the next tool | A Joule Studio agent, with the process as one of its tools | An agent plans; the process keeps the approval fixed |
| Gluing many SaaS tools together, event by event | n8n in Joule Studio, once it is available to you | Early adopter only as of November 2026 |
| A rule nobody can state in one sentence | Neither yet | Write the policy first; AI can't generate a rule nobody agrees on |

### Questions to ask

1. Which AI features in our SAP Build tenant are on, and which need AI Units or another edition?
2. Who reviews a decision table Joule drafted, and where are the test cases stored?
3. Which supplier documents will the extraction see, and what happens when a field is missing?
4. Who can approve their own purchase orders today, in S/4HANA and in the new process?
5. Is this approval better as flexible workflow inside S/4HANA? What does the process add?
6. Who runs the process after go-live: who watches failed steps, and who changes a rule?
7. If Joule Studio's free runtime promotion applies to us, what happens to our costs in January 2027?

### Common misconceptions

- **"AI builds the process for us."** Joule drafts; a person tests and owns the result. A decision table is a control, and the owner of the control signs it off.
- **"Low-code means no IT."** Drawing the process is low-code. Connecting it to S/4HANA, with destinations, roles and a cloud connector, is BTP administration.
- **"Document extraction is always right."** It is often right. The process must say what happens when it isn't: a task to a person, never a silent guess.
- **"An agent is a better workflow."** For a fixed approval, an agent adds risk. Use the agent where steps vary; let it hand fixed approvals to a process.
- **"SAP templates are production-ready."** SAP's own guide for a requisition approval template says its learning content is for demo and reference ([guide](https://hub.sap.com/odata/1.0/catalog.svc/Files('a8bd337e-9ffc-4c13-9072-399e57ed3693_Configuration_and_User_Guide_for_Purchase_Requisition_Line_Item_Approval_and_Release')/$value)). Treat a template as a start.

### Key terms

- **SAP Build Process Automation:** SAP's low-code tool on BTP for workflows, forms, decision tables, bots and document steps.
- **Process:** the drawn sequence of steps, started by a trigger such as an event, an API call or a form.
- **Decision table:** a business rule written as rows of conditions and results, such as amount ranges and approvers.
- **Approval form:** a task a person sees in their inbox, with buttons such as Approve and Reject that the process branches on.
- **Document step:** a process step that extracts fields from a PDF or image, with or without a template.
- **Joule for developers:** design-time AI in SAP Build that drafts processes, forms, decisions and scripts.
- **Joule Studio:** SAP's environment for building and extending agents, and for early adopters, n8n workflows.
- **Flexible workflow:** S/4HANA's built-in, configurable approval for documents such as purchase orders.
- **Touchless rate:** the share of cases that finish without any person touching them.

### Check yourself

1. Calder needs only R05: the plant manager approves POs above 25,000 USD. What should it start with?
   - A. An SAP Build process with a document step and a decision table
   - B. S/4HANA flexible workflow, configured on the PO's own fields
   - C. A Joule Studio agent that decides who should approve each PO
   - D. An n8n workflow that watches new POs and emails the plant manager

   Answer: B. One approval on one S/4HANA document, ruled by its own fields, is configuration. A process tool earns its place when the approval needs a document read, a second system or a custom form.

2. Joule drafts a decision table from Calder's approval policy. What must happen before it goes live?
   - A. Nothing, because Joule generates the table from the policy text itself
   - B. An administrator checks that AI Units are available for the table
   - C. The rule owner tests it against cases written from the policy
   - D. The table is summarized by Joule so the approvers can read it

   Answer: C. A generated table can look right and still be wrong at a boundary. Test cases written from the policy catch that, and the rule owner signs off the control.

3. Which statement about AI terms in SAP Build Process Automation matches SAP's pages in November 2026?
   - A. Every AI feature is included in the Advanced user plan
   - B. Every AI feature needs AI Units before it can be used
   - C. Terms differ by feature, so each feature's page must be read
   - D. AI features are only offered in the 30-day basic trial

   Answer: C. SAP's pages say decision generation does not currently need AI Units, while process summarization does. The pricing page lists no AI items, so each feature's own page is the reference.

4. A supplier sends quotes in a layout the extraction has never seen. What should the process do?
   - A. Use the PO price, because the buyer already typed it
   - B. Create a task for a person to check the quote against the PO
   - C. Approve the PO, because extraction is only an extra check
   - D. Reject the PO and ask the supplier to resend the quote

   Answer: B. Extraction can miss fields on an unfamiliar layout. The process must route the case to a person, not guess or skip the check.

5. Where does an agent fit next to an approval process?
   - A. It replaces the approval, because agents can reason about amounts
   - B. It approves on the manager's behalf when the manager is away
   - C. It handles varying steps and hands fixed approvals to the process
   - D. It replaces the decision table, because it can read the policy

   Answer: C. An agent plans its own steps, which suits varying cases. A fixed approval is a control; it stays in a process where the steps and approvers are known.

6. What is the status of n8n workflows in Joule Studio as SAP described it in October 2026?
   - A. Generally available to every SAP Build customer
   - B. Planned for 2027 with no customers using it yet
   - C. For customers in the Joule Studio early adopter program
   - D. Included in the SAP Build basic trial for everyone

   Answer: C. SAP's TechEd press release says early adopter customers can design and run n8n workflows, with broader availability to follow. Plan with that label, not a general release.

## Deep layer

### Mental model

Treat a low-code process as **a fixed route with gates**, and AI as **two helpers outside the gates**. The route is drawn: trigger, checks, decision, approvals, action. The gates are where a person or a rule must say yes. One AI helper works at design time and drafts the route. The other works at run time and reads documents into fields.

Neither helper opens a gate. Joule's draft becomes a gate only after tests prove it matches the policy. The extraction feeds a gate; when it is unsure, the case goes to a person. Keep that picture and most design questions answer themselves.

### How it works

An SAP Build Process Automation project holds a few kinds of artifact. SAP's guide for a purchase requisition approval template shows them all together ([guide](https://hub.sap.com/odata/1.0/catalog.svc/Files('a8bd337e-9ffc-4c13-9072-399e57ed3693_Configuration_and_User_Guide_for_Purchase_Requisition_Line_Item_Approval_and_Release')/$value)):

- **Processes**: the main flow and sub-processes, such as validate, approve, rework and release.
- **Decisions**: business rules, such as "Determine Line Item Approvers" and "Validate Purchase Requisition Line Item".
- **Forms**: the task screens for approval, rework and errors.
- **Actions**: calls to APIs, such as reading and releasing the requisition in S/4HANA.
- **Destinations**: named connections on BTP that say where an action's API lives and how to sign in.

```mermaid
flowchart LR
  T[Trigger<br/>PO created] --> X[Document step<br/>read the quote]
  X -->|fields unsure| C[Form: buyer<br/>checks the quote]
  X -->|price above quote| R[Form: buyer<br/>reworks the PO]
  X -->|fields match| D[Decision table<br/>who approves]
  C --> D
  D -->|nobody| A[Action<br/>release request]
  D -->|approvers| F[Approval forms<br/>one per step]
  F -->|all approved| A
  F -->|rejected| R
```

Where AI enters:

| Moment | AI piece | What it produces | What checks it |
| --- | --- | --- | --- |
| Design | Joule for developers, decision generation | A draft process, form or decision table | The builder's review and the rule tests |
| Design | Process or decision summarization | A plain-language description of an existing artifact | A reader who knows the process |
| Run | Document data extraction | Fields from a PDF or image, with or without a template | Comparison with the PO, and a person when unsure |
| Run, outside the process | A Joule Studio agent | A plan and tool calls for a varying case | The process it hands approvals to |

In SAP's requisition template the flow is: validate the line item with a decision; if it fails, the requester fixes or deletes it; cost center owners approve in sequence; a rejection goes back to the requester; the approved item is released in S/4HANA; and if the release fails, IT support gets a task. The release calls `BAPI_REQUISITION_RELEASE`, exposed as OData through Integration Suite and a Cloud Connector. The same shape, with a document step added, is what you build below.

### Build it yourself: Calder's PO approval with a tested rule and a document step

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 14](https://erpfde.com/topics/set-up-for-unit-14/). No SAP account is needed.

You will build a local stand-in for the process in the diagram above. One script keeps every part as a plain file you can open: purchase orders, supplier quotes, a decision table, test cases, an inbox of tasks and a process log. Two things are the point. First, the decision table starts as an **AI draft** that looks right and isn't; you test it and fix it. Second, the document step reads quotes with a template and sends anything unsure to a person.

> **Note** New words. A **stand-in** is a small local program that behaves like the real service in the ways this lesson needs, so you can learn without an account. **JSON** is a text format for structured data; you will edit one JSON file by pasting. A **first-match** table checks rows from the top and uses the first row whose conditions all hold. That is how this lab's tables work; check the hit policy your SAP tool uses before you copy a table across.

> **Note** The draft table is written by the course to look like something an assistant would produce from Calder's policy sentence. It does not come from Joule. The lesson is the habit, not the tool: test every generated rule against cases you wrote yourself.

#### What you need

- The course folder with its `.venv`. Python's built-in modules only, nothing to install.
- Cost: free. Time: about 40 minutes.

#### Step 1: Open your 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. Check that the `unit14` folder exists from the setup topic. If it doesn't, create it:

   ```bash
   mkdir unit14
   ```

#### Step 2: Create the script

1. In VS Code, create the file `unit14/po_approval_lab.py`.
2. Paste this code and save:

```python
"""Calder PO approval lab: a local stand-in for a low-code approval process with AI steps.

It copies the parts of an SAP Build Process Automation project (a trigger, a
document step, a decision table, approval forms in an inbox, an action at the
end) as plain files, so you can see how they fit and where AI helps or hurts.
Nothing here calls SAP. Built-in modules only, no randomness.

  python unit14/po_approval_lab.py init          write the sample files to unit14/bpa/
  python unit14/po_approval_lab.py test-rules    test the approver table against the policy
  python unit14/po_approval_lab.py run           send the new purchase orders through the process
  python unit14/po_approval_lab.py inbox --as 00100253           tasks for one user
  python unit14/po_approval_lab.py decide TASK-0001 --as 00100253 --approve
  python unit14/po_approval_lab.py status        where every purchase order stands
  python unit14/po_approval_lab.py reset         clear the run history and start again

All people, suppliers, numbers and rules are fictional course values.
"""
import argparse
import json
import re
import sys
from pathlib import Path

LAB = Path("unit14") / "bpa"
TODAY = "2026-11-23"

POLICY = ("Purchase orders from an intercompany supplier need no approval. "
          "Other purchase orders up to 10,000.00 USD need no approval; above 10,000.00 "
          "up to 25,000.00 USD the purchasing manager approves; above 25,000.00 USD the "
          "purchasing manager approves, then the plant manager.")

ROLES = {"PURCH_MGR": "00100253", "PLANT_MGR": "00100301"}

SUPPLIERS = {
    "20000001": {"name": "Orrin Motor Works", "intercompany": False},
    "20000002": {"name": "Tamsfield Foundry", "intercompany": False},
    "20000003": {"name": "Ridgeline Bearing Supply", "intercompany": False},
    "20000010": {"name": "Calder Pumpworks GmbH", "intercompany": True},
}

PURCHASE_ORDERS = [
    {"po": "4500000015", "supplier": "20000001", "material": "CP-MTR15", "qty": 30,
     "price": 905.00, "quote": "ORR-Q-2611", "created_by": "00100211"},
    {"po": "4500000016", "supplier": "20000002", "material": "CP-IMP200", "qty": 60,
     "price": 335.00, "quote": "TF-Q-0912", "created_by": "00100211"},
    {"po": "4500000017", "supplier": "20000003", "material": "CP-SK200", "qty": 100,
     "price": 48.00, "quote": "RBS-Q-0451", "created_by": "00100211"},
    {"po": "4500000018", "supplier": "20000010", "material": "CP-IMP200", "qty": 80,
     "price": 335.00, "quote": None, "created_by": "00100211"},
    {"po": "4500000019", "supplier": "20000001", "material": "CP-MTR15", "qty": 26,
     "price": 950.00, "quote": "ORR-Q-2617", "created_by": "00100211"},
    {"po": "4500000020", "supplier": "20000001", "material": "CP-MTR15", "qty": 120,
     "price": 905.00, "quote": "ORR-Q-2620", "created_by": "00100211"},
]

# The text a scanner or PDF reader would give you for each supplier quote.
QUOTES = {
    "ORR-Q-2611": "ORRIN MOTOR WORKS\nQuotation: ORR-Q-2611\nDate: 2026-11-12\n"
                  "Valid until: 2026-12-31\nMaterial: CP-MTR15 Motor 15 kW\n"
                  "Unit price: USD 905.00\nQuantity: 30\n",
    "ORR-Q-2617": "ORRIN MOTOR WORKS\nQuotation: ORR-Q-2617\nDate: 2026-11-16\n"
                  "Valid until: 2026-12-31\nMaterial: CP-MTR15 Motor 15 kW\n"
                  "Unit price: USD 905.00\nQuantity: 26\n",
    "ORR-Q-2620": "ORRIN MOTOR WORKS\nQuotation: ORR-Q-2620\nDate: 2026-11-20\n"
                  "Valid until: 2027-01-31\nMaterial: CP-MTR15 Motor 15 kW\n"
                  "Unit price: USD 905.00\nQuantity: 120\n",
    "TF-Q-0912": "Tamsfield Foundry - Offer\nOffer no. TF-Q-0912 of 13 Nov 2026\n"
                 "Impeller CP-IMP200, 60 pcs\nPrice per piece 335.00 US dollars\n"
                 "Offer binding for 30 days\n",
    "RBS-Q-0451": "RIDGELINE BEARING SUPPLY\nQuotation: RBS-Q-0451\nDate: 2026-11-18\n"
                  "Valid until: 2026-12-18\nMaterial: CP-SK200 Seal kit\n"
                  "Unit price: USD 48.00\nQuantity: 100\n",
}

# What an assistant drafted from the policy sentence. It looks right. Test it.
AI_DRAFT = {
    "name": "Determine PO approvers (CP10)",
    "hit_policy": "first match",
    "drafted_from": POLICY,
    "rows": [
        {"id": "R1", "intercompany": None, "amount_above": None, "amount_up_to": 10000.00,
         "approvers": []},
        {"id": "R2", "intercompany": None, "amount_above": 10000.00, "amount_up_to": 24999.99,
         "approvers": ["PURCH_MGR"]},
        {"id": "R3", "intercompany": None, "amount_above": 24999.99, "amount_up_to": None,
         "approvers": ["PURCH_MGR", "PLANT_MGR"]},
        {"id": "R4", "intercompany": True, "amount_above": None, "amount_up_to": None,
         "approvers": []},
    ],
}

RULE_TESTS = [
    {"id": "T01", "intercompany": False, "amount": 4800.00, "expect": []},
    {"id": "T02", "intercompany": False, "amount": 10000.00, "expect": []},
    {"id": "T03", "intercompany": False, "amount": 10000.01, "expect": ["PURCH_MGR"]},
    {"id": "T04", "intercompany": False, "amount": 25000.00, "expect": ["PURCH_MGR"]},
    {"id": "T05", "intercompany": False, "amount": 25000.01, "expect": ["PURCH_MGR", "PLANT_MGR"]},
    {"id": "T06", "intercompany": True, "amount": 26800.00, "expect": []},
    {"id": "T07", "intercompany": True, "amount": 4800.00, "expect": []},
    {"id": "T08", "intercompany": False, "amount": 27150.00, "expect": ["PURCH_MGR", "PLANT_MGR"]},
]

FIELDS = {  # the extraction template: one pattern per field
    "quote_no": r"Quotation:\s*(\S+)",
    "valid_until": r"Valid until:\s*(\d{4}-\d{2}-\d{2})",
    "unit_price": r"Unit price:\s*USD\s*([\d,]+\.\d{2})",
}


def path(name):
    return LAB / name


def load(name, default=None):
    p = path(name)
    if not p.exists():
        if default is not None:
            return default
        sys.exit(f"Missing {p}. Run: python unit14/po_approval_lab.py init")
    return json.loads(p.read_text(encoding="utf-8"))


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


def log(event):
    with path("process_log.jsonl").open("a", encoding="utf-8") as f:
        f.write(json.dumps(event) + "\n")


def cmd_init(args):
    """Write the sample files. Files you edit are kept unless you add --force."""
    (LAB / "quotes").mkdir(parents=True, exist_ok=True)
    yours = {"policy.json": {"policy": POLICY, "roles": ROLES},
             "rule_tests.json": RULE_TESTS, "approvers.json": AI_DRAFT}
    for name, data in yours.items():
        if args.force or not path(name).exists():
            save(name, data)
        else:
            print(f"Kept your {path(name)} (add --force to start again)")
    save("suppliers.json", SUPPLIERS)
    save("purchase_orders.json", PURCHASE_ORDERS)
    save("approvers_ai_draft.json", AI_DRAFT)
    for quote, text in QUOTES.items():
        (LAB / "quotes" / f"{quote}.txt").write_text(text, encoding="utf-8")
    cmd_reset(args, quiet=True)
    print(f"Sample files written to {LAB}")
    print("approvers.json starts as the AI draft. Test it before you trust it:")
    print("  python unit14/po_approval_lab.py test-rules")


def cmd_reset(args, quiet=False):
    """Forget every run: tasks, state, log and release requests."""
    for name in ("tasks.json", "process_log.jsonl", "release_requests.jsonl", "state.json"):
        if path(name).exists():
            path(name).unlink()
    if not quiet:
        print("Run history cleared. The next run starts every purchase order again.")
    return 0


def decide_approvers(table, intercompany, amount):
    """First row whose conditions all hold wins. Returns (row id, approver roles)."""
    for row in table["rows"]:
        if row.get("intercompany") is not None and row["intercompany"] != intercompany:
            continue
        if row.get("amount_above") is not None and not amount > row["amount_above"]:
            continue
        if row.get("amount_up_to") is not None and not amount <= row["amount_up_to"]:
            continue
        return row["id"], list(row["approvers"])
    return None, None


def show(roles):
    return "none" if not roles else ">".join(roles)


def run_tests(table, tests, quiet=False):
    failed = 0
    for t in tests:
        row, got = decide_approvers(table, t["intercompany"], t["amount"])
        ok = got == t["expect"]
        failed += 0 if ok else 1
        if not quiet:
            kind = "intercompany" if t["intercompany"] else "external"
            print(f"{t['id']}  {kind:<12} {t['amount']:>10,.2f}  expect {show(t['expect']):<19}"
                  f"  got {show(got):<19}  {row}  {'PASS' if ok else 'FAIL'}")
    return failed


def cmd_test_rules(args):
    table = load(args.table) if args.table else load("approvers.json")
    tests = load("rule_tests.json")
    print(f"Table: {table['name']} ({table['hit_policy']})")
    failed = run_tests(table, tests)
    print(f"{len(tests) - failed} of {len(tests)} tests pass.")
    if failed:
        print("Do not deploy this table. Fix approvers.json and test again.")
        return 1
    print("The table matches the policy on every test case.")
    return 0


def extract(text):
    """Template extraction: each field has one pattern. Returns fields and confidence."""
    found = {}
    for field, pattern in FIELDS.items():
        m = re.search(pattern, text)
        if m:
            found[field] = m.group(1).replace(",", "")
    return found, len(found) / len(FIELDS)


def new_task(tasks, po, kind, user, text):
    task = {"task": f"TASK-{len(tasks) + 1:04d}", "po": po, "kind": kind, "user": user,
            "text": text, "status": "open"}
    tasks.append(task)
    log({"date": TODAY, "po": po, "event": "task created", "task": task["task"],
         "kind": kind, "user": user})
    return task


def next_step(po, state, tasks, table, roles):
    """Create the next approval task, or write the release request when none is left."""
    s = state[po["po"]]
    if s["steps"]:
        role = s["steps"][0]
        new_task(tasks, po["po"], "APPROVE", roles[role],
                 f"Approve PO {po['po']} ({po['net']:,.2f} USD) as {role}")
        s["status"] = f"waiting for {role}"
    else:
        s["status"] = "approved, release requested"
        with path("release_requests.jsonl").open("a", encoding="utf-8") as f:
            f.write(json.dumps({"po": po["po"], "date": TODAY, "approvals": s["approvals"],
                                "note": "stand-in: a real process would call the release API"}) + "\n")
        log({"date": TODAY, "po": po["po"], "event": "release requested"})


def cmd_run(args):
    table = load("approvers.json")
    if run_tests(table, load("rule_tests.json"), quiet=True):
        print("Refused: approvers.json fails its rule tests. Run test-rules first.")
        return 1
    roles = load("policy.json")["roles"]
    suppliers = load("suppliers.json")
    state = load("state.json", {})
    tasks = load("tasks.json", [])
    for po in load("purchase_orders.json"):
        if po["po"] in state:
            continue
        po["net"] = round(po["qty"] * po["price"], 2)
        ic = suppliers[po["supplier"]]["intercompany"]
        row, steps = decide_approvers(table, ic, po["net"])
        state[po["po"]] = {"net": po["net"], "row": row, "steps": steps or [],
                           "approvals": [], "status": "new"}
        log({"date": TODAY, "po": po["po"], "event": "started", "net": po["net"], "row": row})
        if po["quote"]:
            text = (LAB / "quotes" / f"{po['quote']}.txt").read_text(encoding="utf-8")
            fields, conf = extract(text)
            log({"date": TODAY, "po": po["po"], "event": "extracted", "fields": fields,
                 "confidence": round(conf, 2)})
            if conf < 1.0:
                new_task(tasks, po["po"], "CHECK_QUOTE", po["created_by"],
                         f"Extraction found {len(fields)} of {len(FIELDS)} fields in "
                         f"{po['quote']}. Check the quote against the PO.")
                state[po["po"]]["status"] = "waiting for quote check"
                continue
            if float(fields["unit_price"]) < po["price"]:
                new_task(tasks, po["po"], "REWORK", po["created_by"],
                         f"PO price {po['price']:.2f} is above quote price "
                         f"{float(fields['unit_price']):.2f} in {po['quote']}. Fix the PO.")
                state[po["po"]]["status"] = "back to buyer"
                continue
            if fields["valid_until"] < TODAY:
                new_task(tasks, po["po"], "REWORK", po["created_by"],
                         f"Quote {po['quote']} expired on {fields['valid_until']}.")
                state[po["po"]]["status"] = "back to buyer"
                continue
        next_step(po, state, tasks, table, roles)
    save("state.json", state)
    save("tasks.json", tasks)
    return cmd_status(args)


def cmd_inbox(args):
    mine = [t for t in load("tasks.json", []) if t["user"] == args.user and t["status"] == "open"]
    if not mine:
        print(f"No open tasks for {args.user}.")
    for t in mine:
        print(f"{t['task']}  {t['kind']:<12} PO {t['po']}  {t['text']}")
    return 0


def cmd_decide(args):
    tasks = load("tasks.json", [])
    state = load("state.json", {})
    pos = {p["po"]: p for p in load("purchase_orders.json")}
    task = next((t for t in tasks if t["task"] == args.task), None)
    if task is None or task["status"] != "open":
        print(f"Refused: {args.task} is not an open task.")
        return 1
    if args.user != task["user"]:
        print(f"Refused: {args.task} is assigned to {task['user']}, not {args.user}.")
        return 1
    po = pos[task["po"]]
    po["net"] = state[po["po"]]["net"]
    if task["kind"] == "APPROVE" and args.user == po["created_by"]:
        print("Refused: the person who created a PO cannot approve it.")
        return 1
    task["status"] = "approved" if args.approve else "rejected"
    log({"date": TODAY, "po": po["po"], "event": f"task {task['status']}", "task": task["task"],
         "user": args.user, "note": args.note})
    s = state[po["po"]]
    if task["kind"] == "APPROVE":
        if args.approve:
            s["approvals"].append({"role": s["steps"].pop(0), "user": args.user})
            next_step(po, state, tasks, load("approvers.json"), load("policy.json")["roles"])
        else:
            s["status"] = "rejected, back to buyer"
    elif task["kind"] == "CHECK_QUOTE":
        if args.approve:
            next_step(po, state, tasks, load("approvers.json"), load("policy.json")["roles"])
        else:
            s["status"] = "quote rejected, back to buyer"
    else:
        s["status"] = ("buyer will change the PO and send it again" if args.approve
                       else "cancelled by buyer")
    save("tasks.json", tasks)
    save("state.json", state)
    print(f"{task['task']} {task['status']} by {args.user}. PO {po['po']}: {s['status']}")
    return 0


def cmd_status(args):
    state = load("state.json", {})
    if not state:
        print("Nothing has run yet. Run: python unit14/po_approval_lab.py run")
        return 0
    print(f"{'PO':<11} {'Net USD':>11}  {'Row':<4} Status")
    for po, s in state.items():
        print(f"{po:<11} {s['net']:>11,.2f}  {s['row'] or '-':<4} {s['status']}")
    done = sum(1 for s in state.values() if s["status"] == "approved, release requested"
               and not s["approvals"])
    print(f"Touchless: {done} of {len(state)} purchase orders needed no person.")
    return 0


def main():
    p = argparse.ArgumentParser(description="Calder PO approval lab (course stand-in)")
    sub = p.add_subparsers(dest="cmd", required=True)
    i = sub.add_parser("init")
    i.add_argument("--force", action="store_true", help="overwrite your policy, tests and table")
    t = sub.add_parser("test-rules")
    t.add_argument("--table", help="file in unit14/bpa/ to test instead of approvers.json")
    sub.add_parser("run")
    b = sub.add_parser("inbox")
    b.add_argument("--as", dest="user", required=True)
    d = sub.add_parser("decide")
    d.add_argument("task")
    d.add_argument("--as", dest="user", required=True)
    g = d.add_mutually_exclusive_group(required=True)
    g.add_argument("--approve", action="store_true")
    g.add_argument("--reject", action="store_true")
    d.add_argument("--note", default="")
    sub.add_parser("status")
    sub.add_parser("reset")
    args = p.parse_args()
    handlers = {"init": cmd_init, "test-rules": cmd_test_rules, "run": cmd_run,
                "inbox": cmd_inbox, "decide": cmd_decide, "status": cmd_status, "reset": cmd_reset}
    return handlers[args.cmd](args)


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

#### Step 3: Write the sample files

1. Run:

   ```bash
   python unit14/po_approval_lab.py init
   ```

2. You should see:

   ```text
   Sample files written to unit14/bpa
   approvers.json starts as the AI draft. Test it before you trust it:
     python unit14/po_approval_lab.py test-rules
   ```

3. Open `unit14/bpa/policy.json`. It holds Calder's approval policy as one sentence and two course roles: purchasing manager `00100253` and plant manager `00100301`. The policy: intercompany POs need no approval; other POs up to 10,000.00 USD need none; above 10,000.00 up to 25,000.00 the purchasing manager approves; above 25,000.00 the purchasing manager and then the plant manager.
4. Open `unit14/bpa/purchase_orders.json`. Six new POs from buyer `00100211` in `CP10`, from Orrin (motors), Tamsfield (impellers), Ridgeline (seal kits) and Calder's German company `20000010`.

#### Step 4: Test the AI draft before you trust it

1. Run:

   ```bash
   python unit14/po_approval_lab.py test-rules
   ```

2. You should see two failures:

   ```text
   Table: Determine PO approvers (CP10) (first match)
   T01  external       4,800.00  expect none                 got none                 R1  PASS
   T02  external      10,000.00  expect none                 got none                 R1  PASS
   T03  external      10,000.01  expect PURCH_MGR            got PURCH_MGR            R2  PASS
   T04  external      25,000.00  expect PURCH_MGR            got PURCH_MGR>PLANT_MGR  R3  FAIL
   T05  external      25,000.01  expect PURCH_MGR>PLANT_MGR  got PURCH_MGR>PLANT_MGR  R3  PASS
   T06  intercompany  26,800.00  expect none                 got PURCH_MGR>PLANT_MGR  R3  FAIL
   T07  intercompany   4,800.00  expect none                 got none                 R1  PASS
   T08  external      27,150.00  expect PURCH_MGR>PLANT_MGR  got PURCH_MGR>PLANT_MGR  R3  PASS
   6 of 8 tests pass.
   Do not deploy this table. Fix approvers.json and test again.
   ```

3. Read the two failures:
   - **T04:** the draft's row R3 starts "above 24,999.99", so a PO of exactly 25,000.00 gets the plant manager too. The policy says "above 25,000.00".
   - **T06:** the intercompany row R4 is last. In a first-match table, R3 matches every large PO first, so R4 is never reached for them. **T07** passes only by luck: R1 happens to give the same answer.
4. Try to run the process anyway:

   ```bash
   python unit14/po_approval_lab.py run
   ```

   ```text
   Refused: approvers.json fails its rule tests. Run test-rules first.
   ```

   That refusal is the gate. A table that fails its tests never reaches a PO.

#### Step 5: Fix the table

1. Open `unit14/bpa/approvers.json`, select everything, and replace it with this. It moves the intercompany row to the top and sets both boundaries at exactly 25,000.00:

   ```json
   {
     "name": "Determine PO approvers (CP10)",
     "hit_policy": "first match",
     "reviewed_by": "your name",
     "rows": [
       {"id": "R4", "intercompany": true, "amount_above": null, "amount_up_to": null,
        "approvers": []},
       {"id": "R1", "intercompany": null, "amount_above": null, "amount_up_to": 10000.00,
        "approvers": []},
       {"id": "R2", "intercompany": null, "amount_above": 10000.00, "amount_up_to": 25000.00,
        "approvers": ["PURCH_MGR"]},
       {"id": "R3", "intercompany": null, "amount_above": 25000.00, "amount_up_to": null,
        "approvers": ["PURCH_MGR", "PLANT_MGR"]}
     ]
   }
   ```

2. Put your own name in `reviewed_by` and save.
3. Test again:

   ```bash
   python unit14/po_approval_lab.py test-rules
   ```

4. The last two lines should read:

   ```text
   8 of 8 tests pass.
   The table matches the policy on every test case.
   ```

#### Step 6: Run the process

1. Run:

   ```bash
   python unit14/po_approval_lab.py run
   ```

2. You should see:

   ```text
   PO              Net USD  Row  Status
   4500000015    27,150.00  R3   waiting for PURCH_MGR
   4500000016    20,100.00  R2   waiting for quote check
   4500000017     4,800.00  R1   approved, release requested
   4500000018    26,800.00  R4   approved, release requested
   4500000019    24,700.00  R2   back to buyer
   4500000020   108,600.00  R3   waiting for PURCH_MGR
   Touchless: 2 of 6 purchase orders needed no person.
   ```

3. What happened to each PO:
   - `4500000015` (30 motors at 905.00): the quote `ORR-Q-2611` matched, so it waits for two approvals.
   - `4500000016` (60 impellers): Tamsfield's quote uses its own labels ("Offer no.", "Price per piece"). The template found none of its three fields, so the buyer gets a task to check it.
   - `4500000017` (seal kits) and `4500000018` (intercompany impellers) needed nobody.
   - `4500000019` (26 motors at 950.00): Orrin's quote `ORR-Q-2617` says 905.00, so the PO goes back to the buyer before anyone approves it.
4. Open `unit14/bpa/process_log.jsonl`. Each line is one event: started, extracted (with the fields and a confidence), task created. This is the audit trail.

> **Note** These counts come from six made-up purchase orders. They show the method, not a touchless rate from a real SAP system.

#### Step 7: Work the inboxes

1. See the purchasing manager's tasks:

   ```bash
   python unit14/po_approval_lab.py inbox --as 00100253
   ```

   ```text
   TASK-0001  APPROVE      PO 4500000015  Approve PO 4500000015 (27,150.00 USD) as PURCH_MGR
   TASK-0004  APPROVE      PO 4500000020  Approve PO 4500000020 (108,600.00 USD) as PURCH_MGR
   ```

2. Try to approve as the buyer, who created the PO:

   ```bash
   python unit14/po_approval_lab.py decide TASK-0001 --as 00100211 --approve
   ```

   ```text
   Refused: TASK-0001 is assigned to 00100253, not 00100211.
   ```

3. Approve as the purchasing manager, then as the plant manager:

   ```bash
   python unit14/po_approval_lab.py decide TASK-0001 --as 00100253 --approve --note "Motors for the December ES-200 builds"
   python unit14/po_approval_lab.py decide TASK-0005 --as 00100301 --approve
   ```

   ```text
   TASK-0001 approved by 00100253. PO 4500000015: waiting for PLANT_MGR
   TASK-0005 approved by 00100301. PO 4500000015: approved, release requested
   ```

4. Let the buyer confirm the Tamsfield quote, which sends that PO on to the purchasing manager:

   ```bash
   python unit14/po_approval_lab.py decide TASK-0002 --as 00100211 --approve --note "Quote TF-Q-0912 checked: 335.00"
   ```

   ```text
   TASK-0002 approved by 00100211. PO 4500000016: waiting for PURCH_MGR
   ```

5. Open `unit14/bpa/release_requests.jsonl`. The last line holds `4500000015` with both approvals and who gave them. A real process would now call S/4HANA's release API; the stand-in only writes the request.
6. To start again at any point, run `python unit14/po_approval_lab.py reset` and then `run`.

#### Step 8: Save your work in Git

```bash
git add unit14/po_approval_lab.py unit14/bpa
git commit -m "Unit 14: PO approval lab with tested decision table"
```

#### What each part of the code does

| Part | What it does |
| --- | --- |
| `POLICY`, `ROLES` | Calder's approval rule as one sentence, and which person holds each course role |
| `AI_DRAFT` | The decision table as an assistant might draft it, with two hidden faults |
| `RULE_TESTS` | Eight cases written from the policy, including both boundaries and intercompany |
| `decide_approvers` | Reads the table top to bottom and returns the first row that matches |
| `cmd_test_rules`, `run_tests` | Compares every test case with the table's answer |
| `FIELDS`, `extract` | The extraction template: one pattern per field, and the share of fields found |
| `cmd_run` | The process: refuse an untested table, read the quote, compare it with the PO, decide, create tasks |
| `cmd_decide` | The approval form: only the assigned person decides, and a PO's creator never approves it |
| `next_step` | Creates the next approval task, or writes the release request when none is left |
| `log` | Appends every event to `process_log.jsonl` |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python: command not found` or `'python' is not recognized` | Python is not on your path | Follow [Set up your computer](https://erpfde.com/topics/set-up-your-computer/); on macOS or Linux try `python3` |
| `ModuleNotFoundError` | The script imports something it shouldn't, so a line was pasted wrongly | Paste the whole script again; it uses built-in modules only |
| `Missing unit14/bpa/... Run: ... init` | The sample files aren't there | Run `python unit14/po_approval_lab.py init` from the course folder, not from `unit14` |
| `json.decoder.JSONDecodeError` | `approvers.json` has a typo, often a missing comma or bracket | Paste the table from Step 5 again, or run `init --force` to start from the draft |
| `Refused: approvers.json fails its rule tests` | Your table still fails a test | Run `test-rules` and read the `FAIL` lines |
| `Refused: ... is assigned to` | The wrong user is deciding | Check the task's user with `inbox --as` |
| Different task numbers from the ones shown | You ran `decide` in another order, or ran `run` twice | Run `reset`, then `run`, and follow the steps in order |
| A network or proxy error | Not expected: the script never goes online | Check you are running this script and not another one |

### The SAP way

As of November 2026, this is how the same ideas map to SAP's services. Statuses and terms come from the pages listed; check them again before you plan.

**The process.** SAP Build Process Automation offers a no-code process builder with generative AI assistance, forms, decisions and automations ([features](https://www.sap.com/uk/products/technology-platform/process-automation/features.html)). Builders hold an **Advanced user** plan; people who start or take part in workflows hold a **Standard user** plan ([pricing](https://www.sap.com/products/technology-platform/process-automation/pricing.html)). SAP's get-started page describes a BTP free tier without time limits, up to a capacity limit the page doesn't quantify ([get started](https://www.sap.com/products/technology-platform/process-automation/get-started.html)).

**Design-time AI.** Joule for developers generates processes, forms, decisions and scripts from natural language and summarizes artefacts. SAP describes it as design-time only, enabled from the SAP Build lobby by accepting the SAP AI Terms, and offered free ([Joule for developers](https://www.sap.com/products/artificial-intelligence/joule-for-developers.html)). Decision generation creates decision artifacts from a description of the rules, and SAP's page says AI Units are not currently required, subject to change ([decision generation](https://www.sap.com/spain/products/technology-platform/build-process-automation-decision-generation.html)). Process summarization, by contrast, says AI Units are currently required ([process summarization](https://www.sap.com/products/technology-platform/build-process-automation-process-summarization.html)).

**The document step.** SAP describes extraction from scanned PDFs and images, with or without templates, for document types such as invoices, purchase orders and payment advices. Template-free extraction uses LLMs through SAP Document AI on BTP ([document data extraction](https://www.sap.com/uk/products/technology-platform/build-process-automation-document-data-extraction.html)). The features page ties LLM-based extraction to the premium edition of Document Information Extraction through the AI consumption model. That is exactly the Tamsfield case: a template misses a new layout; template-free extraction may read it. The [Document AI topic](https://erpfde.com/topics/document-ai-and-sap/) covers the service itself.

**The connection to S/4HANA.** SAP's requisition approval template shows what a real build needs ([guide](https://hub.sap.com/odata/1.0/catalog.svc/Files('a8bd337e-9ffc-4c13-9072-399e57ed3693_Configuration_and_User_Guide_for_Purchase_Requisition_Line_Item_Approval_and_Release')/$value)): S/4HANA Cloud Private Edition 2023 onwards or on-premise; an Integration Suite package that exposes BAPIs such as `BAPI_REQUISITION_RELEASE` as OData; a Cloud Connector for on-premise; BTP destinations; and roles such as `ProcessAutomationParticipant` and `ProcessAutomationAdmin`. It is used together with SAP's Procure to Order package, which supplies the start screen. The guide's version 1.0.1 is dated 7 August 2025, and it says its learning content is for demo and reference.

**Agents and n8n.** Joule Studio offers no-code and pro-code tools to build and extend agents. SAP's TechEd release of 27 October 2026 says customers in the Joule Studio early adopter program can also design and run n8n workflows, "with broader availability to follow". Running custom agents on the SAP-managed runtime is free through December 2026 for select customers, and design-time tooling stays free under fair-use limits ([SAP News](https://news.sap.com/2026/10/sap-teched-ai-developers-build-what-matters-autonomous-execution/)). How agents call processes as tools is covered in [the order exception agent three ways](https://erpfde.com/topics/order-exception-agent-three-ways/), and the platform in [Joule and Joule Studio](https://erpfde.com/topics/joule-and-joule-studio/).

**What you can try.** The SAP Build basic trial runs 30 days at no cost on a shared tenant with sample data. It includes a workbook to extend S/4HANA Cloud Public Edition and one to create a custom AI agent in Joule Studio, classic edition. Key user and administration rights, agent deployment and integration are not offered ([SAP Build trial](https://www.sap.com/products/technology-platform/build/trial.html)). So the trial shows the builder; it can't show Calder's S/4HANA connection.

> **Note** None of the pages opened for this topic gives the hit policies of SAP Build decision tables, or the confidence values its extraction returns. The lab's first-match rule and its "share of fields found" are course choices. Check both in SAP's documentation for your tenant before you design around them.

### Build vs. SAP

| Need | Build it yourself | SAP Build Process Automation | S/4HANA flexible workflow |
| --- | --- | --- | --- |
| One approval on PO fields | Overkill | Possible | Best fit |
| Read a supplier quote | Your own extraction code | Document step, template or template-free | Not in scope |
| Rule owned by a functional team | Code that a developer changes | Decision table a consultant edits | Configured conditions |
| Audit trail | You write it | Process instances and task history on BTP | Workflow records in S/4HANA |
| Who runs it | Your team | BTP operations, with SAP's runtime | The S/4HANA team |
| Cost | Your time and hosting | User plans, add-ons, AI feature terms | Included in S/4HANA |

### Architecture view

**Where it sits.** The process runs on BTP. S/4HANA for `CP10` creates the PO and receives the release. Quotes arrive by email or from the supplier portal. People decide in an inbox. A Joule Studio agent, if Calder adds one, calls the process; it never releases a PO itself.

```mermaid
flowchart LR
  S4[S/4HANA CP10<br/>purchase orders] -->|event: PO created| BPA[SAP Build<br/>Process Automation]
  POR[Supplier portal<br/>and mailbox] -->|quote PDF| BPA
  BPA -->|document step| DOC[SAP Document AI]
  BPA -->|tasks| INB[Approver inbox]
  BPA -->|release via<br/>Integration Suite| S4
  AG[Joule Studio agent] -->|starts or reads| BPA
```

**Non-functional requirements.**

| Requirement | Typical target | What breaks if missed |
| --- | --- | --- |
| Segregation of duties | No one approves a PO they created; checked in the process and in S/4HANA roles | An audit finding on purchasing |
| Latency | A PO reaches the first approver within minutes of creation | Buyers bypass the process to chase approvals |
| Availability | When BTP is down, POs wait and resume; nothing is released unapproved | Orders released without a check, or lost |
| Extraction quality | Every missing field goes to a person | A wrong price is approved silently |
| Cost | User plans, unattended bots and AI features budgeted per year | A pilot that can't be paid for at scale |

**Integration and identity.** The PO reaches the process as an event or an API call; the release goes back through a released API or, as in SAP's template, a BAPI exposed through Integration Suite. Approvers sign in through the customer's identity service, so the process knows who decided. The release call runs under a technical user that can release only POs the process has approved; check its roles with the [roles and authorization design topic](https://erpfde.com/topics/roles-and-authorization-design/).

**The decision to record.**

- **Context:** R05 needs plant manager approval above 25,000 USD; purchasing also wants quote checks and an intercompany exception.
- **Options:** 1 flexible workflow only; 2 flexible workflow for R05 now, SAP Build Process Automation for the quote check later; 3 one SAP Build process for all of it.
- **Decision:** option 2. R05 goes live with the `CP20` rollout as configuration; the quote check is piloted in SAP Build with tested decision tables.
- **Consequences:** two places hold approval logic for a time, so the decision table copies R05's thresholds and is tested against the same cases; the PO's release stays in S/4HANA.

**What a design review will ask.**

1. Which system is the single source of the approval thresholds?
2. What stops the release user from releasing a PO the process didn't approve?
3. What happens to open tasks when an approver leaves Calder?
4. Which AI features are switched on, under which terms, and who reviewed the generated artifacts?
5. How is a failed release noticed and fixed?

### Production concerns

- **Authorizations.** Approval rights live in two places: process roles on BTP and release rights in S/4HANA. Design them together, and test that a buyer can't approve their own PO in either.
- **Evaluation.** Keep the rule tests with the table, and run them in the transport or release pipeline. Keep a set of real quote layouts, one per supplier, and measure how many fields the extraction gets right.
- **Change.** A threshold change is a change to a control. Version the table, record who approved the change, and rerun the tests.
- **Operations.** Someone watches failed steps daily: extraction errors, release errors, tasks past their due date.
- **Cost.** Count Advanced users (builders) and Standard users (participants), unattended bots and AI features separately; the AI terms differ by feature.
- **Clean core.** The process sits outside S/4HANA and talks through released APIs or integration content; nothing is modified inside the core.

### Where AI fits, and where it doesn't

| Step | Pattern | Verdict |
| --- | --- | --- |
| Draft the process, form or decision table | Generate | Useful, then test |
| Read the supplier quote | Extract | Useful, with a person on low confidence |
| Decide who approves | Plain rules | No AI at run time: a decision table is enough |
| Approve | A person | Never AI |
| Release the PO | Plain automation | An API call after approval |
| Explain an old, undocumented process | Summarize | Useful as a start, checked by its owner |

### Pitfalls

- **Trusting a generated table because it reads well.** Test the boundaries and every exception row.
- **Row order in first-match tables.** An exception row below a broad row is never reached.
- **Silent extraction failure.** A missing price must create a task, not default to the PO price.
- **Approval logic in two places without one source.** Thresholds drift between S/4HANA and BTP.
- **Building an agent for a fixed approval.** It adds variation where the auditor wants none.
- **Treating a template as finished.** SAP labels its learning content as demo and reference.
- **Planning around a free promotion.** Joule Studio's free runtime for select customers ends in December 2026.

### Exercise

Calder's finance team adds a third signature: purchase orders above 100,000.00 USD also need the CFO, course user `00100302`.

1. In `unit14/bpa/policy.json`, add `"CFO": "00100302"` to `roles` (mind the comma after the line above it).
2. In `unit14/bpa/rule_tests.json`, add two cases before the closing `]`: `T09` external 100,000.00 expecting `["PURCH_MGR", "PLANT_MGR"]`, and `T10` external 100,000.01 expecting `["PURCH_MGR", "PLANT_MGR", "CFO"]`. Copy the shape of `T08`.
3. Run `test-rules`. `T10` should fail: write the test first and watch it fail.
4. In `approvers.json`, add row `R5` with `amount_above` 100000.00 and approvers `["PURCH_MGR", "PLANT_MGR", "CFO"]`. Decide where it must go in a first-match table, and put it there.
5. Run `test-rules`, then `reset` and `run`.

**Done when:** `test-rules` shows 10 of 10, and after `run` the status shows `4500000020` on row `R5`, waiting for `PURCH_MGR`. Keep the folder: the finance close topic in this unit and the capstone reuse approval rules with their tests.

### Check yourself

1. In the mental model, what is the role of Joule's draft decision table?
   - A. It opens the approval gate once the policy sentence is loaded
   - B. It becomes a gate only after tests prove it matches the policy
   - C. It replaces the approvers for POs below the highest threshold
   - D. It runs at run time to pick the approver for every new PO

   Answer: B. Joule drafts at design time. The table becomes a control only once test cases written from the policy pass, which is what the lab's run command enforces.

2. The draft's intercompany row R4 sat at the bottom of a first-match table. What went wrong?
   - A. R4 had the wrong approvers, so intercompany POs went to nobody
   - B. R4 was skipped because the intercompany flag was spelled wrongly
   - C. Large intercompany POs matched R3 first, so R4 was never reached
   - D. Small intercompany POs failed, because R1 checks the supplier first

   Answer: C. First match uses the first row whose conditions hold. R3 matched every large PO, so the exception below it never applied; T07 passed only because R1 happened to give the same answer.

3. Tamsfield's quote used labels the template didn't know. What did the lab do, and why?
   - A. It created a check task for the buyer, so no price is guessed
   - B. It used the PO price, because the buyer had already typed it
   - C. It skipped the quote check, because Tamsfield is a known supplier
   - D. It rejected the PO, because the supplier must resend a new quote

   Answer: A. The template found none of its fields, so confidence was zero. A missing field must reach a person; SAP's template-free extraction may read such layouts, but the process still needs that route.

4. Which control stops a buyer from approving their own PO in the lab?
   - A. The decision table, because it never lists the buyer as an approver
   - B. The process log, because it records who created every PO
   - C. The release request, because it checks the approvals afterwards
   - D. The decide command, which checks the assignee and the PO creator

   Answer: D. cmd_decide refuses anyone but the assigned user, and refuses a PO's creator for approval tasks. The same rule must also hold in the S/4HANA roles of the release user.

5. What does SAP's requisition approval template need to release a requisition in S/4HANA?
   - A. A Joule Studio agent with write access to purchasing data
   - B. Integration Suite content exposing a BAPI, with destinations on BTP
   - C. An n8n workflow that calls the S/4HANA user interface
   - D. A direct database update from SAP Build Process Automation

   Answer: B. SAP's guide releases via BAPI_REQUISITION_RELEASE exposed as OData through Integration Suite, with a Cloud Connector for on-premise and BTP destinations. Nothing writes to S/4HANA directly.

6. Purchasing asks you to rebuild the PO approval as a Joule Studio agent "because it is smarter". What do you recommend?
   - A. Rebuild it, because agents follow written policy more strictly
   - B. Rebuild it in n8n instead, because it is generally available
   - C. Keep the fixed approval in a process, and let an agent call it
   - D. Remove approvals, because an agent can judge each PO itself

   Answer: C. A fixed approval is a control, and an agent's varying steps add risk to it. An agent can still start or read the process; n8n is early adopter only as of October 2026.

7. Which statement about AI terms is accurate for this topic's SAP pages?
   - A. Decision generation and process summarization both need AI Units
   - B. The pricing page lists AI Units for every AI feature
   - C. Process summarization needs AI Units; decision generation doesn't yet
   - D. Template-free extraction is included in the Standard user plan

   Answer: C. SAP's pages say process summarization currently requires AI Units, while decision generation does not, subject to change. The pricing page lists no AI items.

8. In the recorded decision, why does Calder put R05 in flexible workflow first?
   - A. Because SAP Build Process Automation cannot route by amount
   - B. Because it is configuration on PO fields, live with the rollout
   - C. Because flexible workflow can read the suppliers' quote PDFs
   - D. Because AI features are not allowed on purchase orders

   Answer: B. R05 is one approval on the PO's own fields, which S/4HANA configures. The quote check needs a document step, so it is piloted in SAP Build, with the thresholds tested against the same cases.

## Sources

- [SAP Build Process Automation features (sap.com)](https://www.sap.com/uk/products/technology-platform/process-automation/features.html): Read 2026-11-23. No-code process builder with generative AI assistance; template-based intelligent document processing; LLM-based document information extraction without templates, 'powered by the premium edition of Document Information Extraction available through the AI consumption model'; other SAP BTP AI services and third-party LLMs through API connections; design-time Joule for developers generates processes, forms, decisions and scripts and summarizes artefacts
- [SAP Build Process Automation, document data extraction (sap.com)](https://www.sap.com/uk/products/technology-platform/build-process-automation-document-data-extraction.html): Read 2026-11-23. Extracts data from scanned PDFs and images with or without templates, standard SAP document types such as invoices, purchase orders and payment advices; template-free extraction with LLMs powered by SAP Document AI through SAP BTP; 'AI Feature'; AI Units not currently required, subject to change; price upon request; the UK page showed the solution as not available in that region
- [SAP Build Process Automation, decision generation (sap.com, Spain)](https://www.sap.com/spain/products/technology-platform/build-process-automation-decision-generation.html): Read 2026-11-23. AI-assisted decision generation creates decision artifacts from natural-language descriptions of the rules; AI Feature; AI Units not currently required, subject to change; flat fee, price upon request; vendor effort claims without a source
- [SAP Build Process Automation, process summarization (sap.com)](https://www.sap.com/products/technology-platform/build-process-automation-process-summarization.html): Read 2026-11-23. Generates business summaries for undocumented process models; AI Feature; 'AI Units are currently required to use this AI offering'; 'Activate with AI Units'
- [SAP Build Process Automation pricing (sap.com)](https://www.sap.com/products/technology-platform/process-automation/pricing.html): Read 2026-11-23. Base plans Advanced user (builder) and Standard user (participant), attended automation; add-ons: additional API calls USD 5.90 a month per 10,000, storage USD 2.95 a month per GB, unattended automations USD 590.00 a month per connection; Pay-As-You-Go for SAP BTP or BTP Enterprise Agreement; no AI items listed
- [SAP Build Process Automation get started (sap.com)](https://www.sap.com/products/technology-platform/process-automation/get-started.html): Read 2026-11-23. Free tier model for SAP BTP services without time limits, up to a capacity limit not quantified on the page; switch to a paid plan without losing work; content store with process flows, forms, business rules and bot templates
- [Start your free trial of SAP Build (sap.com)](https://www.sap.com/products/technology-platform/build/trial.html): Read 2026-11-23. 30-day basic trial at no cost on a shared tenant with sample data; workbooks include extending S/4HANA Cloud Public Edition and 'Create a custom AI agent in Joule Studio, classic edition'; key user, administration, agent deployment and integration not offered; trial Joule skills cannot go to production
- [Joule for developers (sap.com)](https://www.sap.com/products/artificial-intelligence/joule-for-developers.html): Read 2026-11-23. Embedded design-time AI for SAP Build and ABAP; excludes runtime and end-user AI such as SAP Document AI; enabled for SAP Build from the SAP Build lobby by accepting the SAP AI Terms; free access, the only requirement being the SAP AI Terms
- [SAP Empowers AI Developers to Build What Matters for Autonomous Execution (SAP News, 27 October 2026)](https://news.sap.com/2026/10/sap-teched-ai-developers-build-what-matters-autonomous-execution/): Read 2026-11-23. Joule Studio no-code and pro-code tools to build and extend agents, more than 70 models; customers in the Joule Studio early adopter program can design and run n8n workflows, broader availability to follow; custom agents on the SAP-managed runtime free through December 2026 for select customers; design-time tooling free under fair-use limits
- [Purchase Requisition Line Item Approval and Release: Configuration and User Guide (SAP Business Accelerator Hub)](https://hub.sap.com/odata/1.0/catalog.svc/Files('a8bd337e-9ffc-4c13-9072-399e57ed3693_Configuration_and_User_Guide_for_Purchase_Requisition_Line_Item_Approval_and_Release')/$value): Read 2026-11-23. Store template for SAP Build Process Automation, used with the Procure to Order package; S/4HANA Cloud Private Edition 2023 onwards and on-premise; decisions Determine Line Item Approvers, Validate Purchase Requisition Line Item; approval and rework forms; release via BAPI_REQUISITION_RELEASE exposed through Integration Suite and Cloud Connector; destinations; version 1.0.1 of 7 August 2025; learning content for demo and reference only
