---
title: "Customer Refund"
description: "The Flow checks a customer's refund request against the order and the refund policy, waits for a manager when the amount is large, issues the refund, and emails the customer. Go also has two larger refund Flows: deterministic policy and agentic review."
canonical_url: "https://docs.superdurable.io/examples/customer-refund/"
source: "docs/content/use-cases/customer-refund.mdx"
locale: "en"
language: "python"
---

> Index of every page for AI agents: https://docs.superdurable.io/llms.txt

# Customer Refund

Code on this page is in Python. Other languages: [Go](https://docs.superdurable.io/examples/customer-refund.go.md) · [Java](https://docs.superdurable.io/examples/customer-refund.java.md) · [TypeScript](https://docs.superdurable.io/examples/customer-refund.typescript.md) · [Rust](https://docs.superdurable.io/examples/customer-refund.rust.md)

The Flow checks a customer's refund request against the order and the refund policy, waits for a manager when the amount is large, issues the refund, and emails the customer. Go also has two larger refund Flows: [deterministic policy](https://docs.superdurable.io/examples/customer-refund.md#deterministic-policy) and [agentic review](https://docs.superdurable.io/examples/customer-refund.md#agentic-review).

**SDKs:** Python · Go · TypeScript · Java · Rust

**Shows:** a manager approval through a [Channel](https://docs.superdurable.io/concepts/primitives/channel.md) and [RPCs](https://docs.superdurable.io/concepts/primitives/rpc.md), Dex Web [Actions](https://docs.superdurable.io/reference/web/dex-web.md#actions), [idempotency keys](https://docs.superdurable.io/concepts/step.md#idempotency-keys), and [Time Travel](https://docs.superdurable.io/production-operations/operate-and-debug.md#time-travel).

**Flow graph: CustomerRefundFlow**

**Steps**

1. `ReceiveRequest` (start Step): Record the refund request and the customer's email address. Next: `CheckOrder`. Writes `case-status`, `customer-email`.
2. `CheckOrder`: Look up the order in billing. Next: `CheckPolicy`.
3. `CheckPolicy`: Refund, deny, or ask a manager, by the refund policy. Next: `WriteCustomerMessage`, `RequestManagerApproval`, or `IssueRefund`. Writes `case-status`.
4. `CloseCase`: Close the case with its outcome. Next: the Flow completes. Writes `case-status`.
5. `IssueRefund`: Refund the order through billing, once per case. Next: `WriteCustomerMessage`. Writes `case-status`, `refund-id`.
6. `RequestManagerApproval`: Wait for a manager to approve or reject the refund. Next: `IssueRefund`, or `WriteCustomerMessage`. Reads `manager-decisions`; writes `case-status`.
7. `SendMessage`: Email the message to the customer, once per case. Next: `CloseCase`.
8. `WriteCustomerMessage`: Ask the model to write the customer message. Next: `SendMessage`. Writes `customer-message`.

**RPCs**

- `approve_refund`: Reads `case-status`; locks `case-status`; writes `case-status`; publishes to `manager-decisions`.
- `reject_refund`: Reads `case-status`; locks `case-status`; writes `case-status`; publishes to `manager-decisions`.

Example: [examples/python/dex_examples/products/customer_refund/refund_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/customer_refund/refund_flow.py)

<a id="refund-with-manager-approval"></a>

## Refund with manager approval

The graph is drawn from the Python source. In TypeScript, Java, and Rust, **Check policy** has one denial branch instead of two. In Go, the Flow type is `ManagerApprovalRefundFlow`, because `CustomerRefundFlow` names the deterministic Go Flow.

**Check policy** applies the refund policy. It denies a charge older than 30 days or one with no recorded outage. It sends an amount of 1,000 USD or less straight to **Issue refund** and a larger amount to **Request manager approval**. That Step waits for one message on a Channel, then refunds or denies by the manager's decision.

**Python**

```python
class CheckPolicy(Step[RefundCase]):
    def execute(self, context: Context, input: RefundCase) -> StepDecision:
        order = input.order
        if order.days_since_charge > REFUND_WINDOW_DAYS:
            CASE_STATUS.set(context, "denied")
            note = "The charge is older than our 30-day refund window."
            return go_to(WriteCustomerMessage, replace(input, outcome="denied", note=note))
        if order.outage_hours == 0:
            CASE_STATUS.set(context, "denied")
            note = "We found no service interruption on this order."
            return go_to(WriteCustomerMessage, replace(input, outcome="denied", note=note))
        if order.amount_usd > MANAGER_APPROVAL_LIMIT_USD:
            CASE_STATUS.set(context, AWAITING_MANAGER)
            return go_to(RequestManagerApproval, input)
        return go_to(IssueRefund, input)


# dex:group group-id:control group-label:"Control"
# dex:explanation text:"Wait for a manager to approve or reject the refund."
class RequestManagerApproval(Step[RefundCase]):
    def wait_for(self, context: Context, input: RefundCase) -> Wait:
        return Wait.until(MANAGER_DECISIONS.for_one())

    def execute(self, context: Context, input: RefundCase) -> StepDecision:
        decision = MANAGER_DECISIONS.results(context)[0]
        if decision.approved:
            return go_to(IssueRefund, input)
        CASE_STATUS.set(context, "denied")
        return go_to(WriteCustomerMessage, replace(input, outcome="denied", note=decision.reason))
```

Example: [examples/python/dex_examples/products/customer_refund/refund_flow.py](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/customer_refund/refund_flow.py)

An approve RPC and a reject RPC publish the manager's decision to that Channel. Each requires a reason and publishes only while `case-status` is `awaiting-manager`. In Python, Go, and TypeScript, the two RPCs are also the Dex Web Actions **Approve refund** and **Reject refund**. In every language, the example's `decide` command also approves or rejects. Java and Rust have no Actions.

The example also shows what a production refund needs:

- **Issue refund** and **Send message** pass billing and email an idempotency key built from the Flow ID: `refund-<Flow ID>` and `email-<Flow ID>`. A Step that was cut off can run again, and so can the Steps after a Time Travel point. Each fake service skips a key that its persistent records already hold. Workers must share those records; Workers with separate records would each refund.
- **Issue refund** retries a payment timeout every 5 seconds. In the `fail-then-succeed` scenario, the final **Issue refund** event in Dex Web shows that attempt 3 succeeded and keeps the details of the last failure.
- In Python, Go, and TypeScript, a payload key file makes the Worker and the Client encrypt payloads. `case-status` and `customer-email` stay plaintext, so Dex Web can show them. Dex Web evaluates the Actions' condition on `case-status`.

<a id="deterministic-policy"></a>

## Deterministic policy

`CustomerRefundFlow` in Go checks that the order exists and applies the 30-day rule. **Issue refund** builds the billing key as the case ID plus `:refund`, passes it to the payment provider, and saves it with the Step result. When the provider declines the refund, or its result is unknown, the Flow records that outcome as the case status.

**Flow graph: CustomerRefundFlow**

**Steps**

1. `ReceiveRequest` (start Step): Store the inbound refund request and start the case. Next: `CheckOrder`.
2. `CheckOrder`: Check the order and charge evidence for the refund. Next: `CheckPolicy`. Writes `case-status`, `order-age-days`, `order-lookup`.
3. `CheckPolicy`: Evaluate refund policy and choose approve or deny. Next: `NotifyCustomer`, `IssueRefund`, or `DenyRefund`. Reads `order-age-days`, `order-lookup`; writes `case-status`, `recommended-action`.
4. `CloseCase`: Close the refund case after notification. Next: the Flow completes. Reads `case-status`; writes `case-status`.
5. `DenyRefund`: Record a policy denial for the refund request. Next: `NotifyCustomer`. Writes `case-status`.
6. `IssueRefund`: Issue the refund through billing. Next: `NotifyCustomer`. Writes `billing-outcome`, `case-status`, `refund-key`.
7. `NotifyCustomer`: Notify the customer of the refund decision. Next: `CloseCase`. Reads `case-status`.

**RPCs**

- `GetDexDisplay`: Reads `billing-outcome`, `charge-reference`, `operator-note`, `order-age-days`, `order-lookup`, `recommended-action`, `refund-amount`.
- `GetDexSummary`: Reads `charge-reference`, `recommended-action`, `refund-amount`.

Example: [examples/go/products/customer-refund/deterministic/workflow.go](https://github.com/superdurable/dex/tree/main/examples/go/products/customer-refund/deterministic/workflow.go)

Its Summary shows the charge reference, requested amount, and recommendation. Its Display adds evidence, the billing outcome, and an editable operator note. It declares no Action, to show that a Flow without Actions is valid in Dex Web. Source: [`deterministic/workflow.go`](https://github.com/superdurable/dex/tree/main/examples/go/products/customer-refund/deterministic/workflow.go).

<a id="agentic-review"></a>

## Agentic review

`AgenticCustomerRefundFlow` in Go gathers evidence in a loop of Steps. A guardrail then applies the decision automatically or waits for a manager. An OpenAI Connector Step drafts the customer message, and a person confirms or rewrites it before it is sent. The Flow records the refund intent in its own Step before billing. The billing Step passes billing a key of the case ID plus `:refund`, or `:credit` for account credit, and saves it with its result. In the graph, ⚠ on a Step marks a failure route; select the Step to see where it goes.

**Flow graph: AgenticCustomerRefundFlow**

**Steps**

1. `ReceiveRequestStep` (start Step): Store the inbound refund request and open or reject the case. Next: `NotARefundStep`, or `AgentDecisionStep`. Writes `case-status`, `in-charge-ref`, `customer-email`, `in-email`, `operator-note`.
2. `GenerateCustomerMessageStep`: Generate the customer resolution message with OpenAI. Next: the Flow fails. Writes `generated-customer-message`.
3. `ApplySubscriptionStep`: Apply any subscription change required by the resolution. Next: `PrepareCustomerMessageStep`, or `SubscriptionFailedStep` if it keeps failing. Writes `subscription-applied`.
4. `AuditIntentStep`: Record the approved refund intent before billing changes. Next: `OfferAccountCreditStep`, or `IssueRefundStep`. Reads `bound-action`.
5. `BillingFailedStep`: Handle a billing failure during refund or credit. Next: `PrepareCustomerMessageStep`. Writes `billing-outcome`, `case-status`.
6. `CheckIdentityStep`: Verify the customer identity before collecting further evidence. Next: `AgentDecisionStep`. Writes `ev-identity-status`.
7. `CheckIncidentsStep`: Check for active incidents that affect refund policy. Next: `AgentDecisionStep`. Writes `evidence-state`, `ev-incident-days`, `ev-incident-status`.
8. `CloseCaseStep`: Close the refund case once resolution is final. Next: the Flow completes.
9. `ConfirmCustomerMessageStep`: Wait for a person to confirm or rewrite the customer message. Next: `SendCustomerMessageStep`. Reads `gate-request-key`, `message-approval`.
10. `AgentDecisionStep`: Choose the next capability from gathered evidence and guardrails. Next: `NonConvergenceStep`, `CheckIdentityStep`, `GetSubscriptionStep`, `GetPaymentStep`, `GetUsageStep`, `GetSupportHistoryStep`, `CheckIncidentsStep`, or `GuardrailStep`. Reads `ev-history-cancel-requested`, `decision-rounds`, `ev-history-status`, `ev-identity-status`, `ev-incident-status`, `ev-payment-status`, `ev-history-prior-refunds`, `ev-subscription-status`, `ev-usage-pct-of-allowance`, `ev-usage-status`; writes `case-status`, `decision-rounds`, `recommendation-rationale`, `recommended-action`.
11. `EmailFailedStep`: Handle a failure sending the customer resolution message. Next: `CloseCaseStep`. Writes `case-status`, `email-sent`.
12. `GetPaymentStep`: Load the payment and charge evidence for the refund. Next: `AgentDecisionStep`. Writes `ev-payment-age-days`, `ev-payment-amount`, `ev-payment-status`, `refund-amount`.
13. `GetSubscriptionStep`: Load the customer's subscription details for the case. Next: `AgentDecisionStep`. Writes `ev-subscription-status`.
14. `GetSupportHistoryStep`: Load prior support history for this customer. Next: `AgentDecisionStep`. Writes `ev-history-cancel-requested`, `ev-history-status`, `ev-history-prior-refunds`, `ev-history-tenure-years`.
15. `GetUsageStep`: Load usage signals that may support or deny a refund. Next: `AgentDecisionStep`. Writes `ev-usage-pct-of-allowance`, `ev-usage-status`.
16. `GuardrailStep`: Apply refund guardrails and set the recommended action. Next: `RequestHumanApprovalStep`, or `AuditIntentStep`. Reads `gate-entries`, `recommended-action`; writes `bound-action`, `case-status`, `gate-entries`, `gate-request-key`, `guardrail-rule`, `guardrail-verdict`.
17. `IssueRefundStep`: Issue the refund through billing. Next: `ApplySubscriptionStep`, `VerifyBillingStep`, `BillingFailedStep`, or `BillingFailedStep` if it keeps failing. Writes `billing-key`, `billing-outcome`, `case-status`.
18. `NonConvergenceStep`: Close the loop when the agent cannot converge on an action. Next: `CloseCaseStep`. Writes `case-status`.
19. `NotARefundStep`: Mark the case as not a refund request. Next: `CloseCaseStep`.
20. `OfferAccountCreditStep`: Offer account credit instead of a cash refund. Next: `BillingFailedStep`, or `ApplySubscriptionStep`. Writes `billing-key`, `billing-outcome`, `case-status`.
21. `PrepareCustomerMessageStep`: Prepare the resolution context and fallback customer message. Next: the Flow fails, or `GenerateCustomerMessageStep`. Reads `case-status`; writes `customer-message-context`.
22. `ReCheckStep`: Re-check evidence after a capability returns to the decision loop. Next: `PrepareCustomerMessageStep`, or `AuditIntentStep`. Reads `manager-verdict`; writes `bound-action`, `case-status`.
23. `RequestHumanApprovalStep`: Ask a human to approve or reject the recommended refund action. Next: `ReCheckStep`. Reads `gate-request-key`, `manager-approval`; writes `manager-verdict`.
24. `SendCustomerMessageStep`: Send the customer the message a person confirmed. Next: `CloseCaseStep`, or `EmailFailedStep` if it keeps failing. Reads `case-status`, `customer-message-draft`; writes `case-status`, `email-sent`.
25. `StoreGeneratedCustomerMessageStep`: Store the customer message generated by OpenAI and open the confirmation gate. Next: `ConfirmCustomerMessageStep`. Reads `customer-message-context`, `gate-entries`; writes `case-status`, `customer-message-draft`, `gate-entries`, `gate-request-key`.
26. `SubscriptionFailedStep`: Handle a subscription update failure after a resolution. Next: `PrepareCustomerMessageStep`. Writes `case-status`, `subscription-applied`.
27. `UseFallbackCustomerMessageStep`: Use the deterministic customer message when OpenAI cannot confirm an answer. Next: `ConfirmCustomerMessageStep`. Reads `customer-message-context`, `gate-entries`; writes `case-status`, `customer-message-draft`, `gate-entries`, `gate-request-key`.
28. `VerifyBillingStep`: Verify the billing outcome after a refund or credit. Next: `ApplySubscriptionStep`, `CloseCaseStep`, or `BillingFailedStep`. Reads `billing-key`; writes `billing-outcome`, `case-status`.

**RPCs**

- `ApproveRefund`: Reads `case-status`, `gate-request-key`; locks `case-status`, `gate-request-key`; publishes to `manager-approval`.
- `ConfirmCustomerMessage`: Reads `case-status`, `gate-request-key`; locks `case-status`, `customer-message-draft`, `gate-request-key`; writes `case-status`; publishes to `message-approval`.
- `EditCustomerMessage`: Reads `case-status`, `gate-request-key`; locks `case-status`, `customer-message-draft`, `gate-request-key`; writes `case-status`, `customer-message-draft`; publishes to `message-approval`.
- `GetDexDisplay`
- `GetDexSummary`: Reads `in-charge-ref`, `guardrail-rule`, `ev-payment-amount`, `recommended-action`.
- `RejectRefund`: Reads `case-status`, `gate-request-key`; locks `case-status`, `gate-request-key`; writes `manager-rejection-reason`; publishes to `manager-approval`.

Example: [examples/go/products/customer-refund/agentic/workflow.go](https://github.com/superdurable/dex/tree/main/examples/go/products/customer-refund/agentic/workflow.go)

Each human gate the Flow opens gets a new gate key. The `ApproveRefund` Action is a direct button with no input. `RejectRefund` asks for a reason, and `EditCustomerMessage` asks for the message to send. Those two and `ConfirmCustomerMessage` also carry the gate key in a hidden input, which Dex Web fills from the Attribute values it read when the page opened. The RPC compares it with the current gate before it publishes; if the gate has changed, it returns an error and the operator refreshes the page. Each RPC also checks the case status, because an Action's visibility condition only decides whether a button appears and authorizes no one. Source: [`agentic/workflow.go`](https://github.com/superdurable/dex/tree/main/examples/go/products/customer-refund/agentic/workflow.go).

## Run it

<a id="run-the-examples"></a>

The [Quick Start](https://docs.superdurable.io/quick-start.md) runs the manager approval Flow end to end. The example folders for [Python](https://github.com/superdurable/dex/tree/main/examples/python/dex_examples/products/customer_refund), [Go](https://github.com/superdurable/dex/tree/main/examples/go/products/customer-refund), [TypeScript](https://github.com/superdurable/dex/tree/main/examples/typescript/src/products/customer-refund), [Java](https://github.com/superdurable/dex/tree/main/examples/java/src/main/java/io/superdurable/dex/products/customerrefund), and [Rust](https://github.com/superdurable/dex/tree/main/examples/rust/src/products/customer_refund) have the commands for the other scenarios: a small refund with no manager, a denial, a refund that fails and then succeeds, and a missing billing call that Time Travel fixes. The Go folder also starts the deterministic and agentic Flows.

To start a refund over HTTP, start the examples of one language as in [Run an example from the playground](https://docs.superdurable.io/install.md#run-an-example-from-the-playground). Then open the [examples playground](https://github.com/superdurable/dex/tree/main/examples/playground) and choose **Customer refund with manager approval**.

## Next

[Production operations](https://docs.superdurable.io/production-operations.md): a Dex application runs on four components: your application, the server, the CLI, and Web.
