Customer Refund
View as MarkdownThe 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.
SDKs: Python · Go · TypeScript · Java · Rust
Shows: a manager approval through a Channel and RPCs, Dex Web Actions, idempotency keys, and Time Travel.
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.
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
// dex:group group-id:evidence group-label:"Evidence"
// dex:explanation text:"Refund, deny, or ask a manager, by the refund policy."
type CheckPolicy struct {
dex.StepDefaultsNoWaitFor[RefundCase]
}
func (CheckPolicy) Execute(ctx dex.Context, input RefundCase) (*dex.StepDecision, error) {
order := input.Order
if order.DaysSinceCharge > RefundWindowDays {
return denyRefund(ctx, input, refundWindowDeniedNote)
}
if order.OutageHours == 0 {
return denyRefund(ctx, input, noInterruptionDeniedNote)
}
if order.AmountUSD > ManagerApprovalLimitUSD {
if err := CaseStatus.Set(ctx, AwaitingManager); err != nil {
return nil, err
}
return dex.GoTo(RequestManagerApproval{}, input), nil
}
return dex.GoTo(IssueRefund{}, input), nil
}
// dex:group group-id:control group-label:"Control"
// dex:explanation text:"Wait for a manager to approve or reject the refund."
type RequestManagerApproval struct {
dex.StepDefaults
}
func (RequestManagerApproval) WaitFor(dex.Context, RefundCase) (*dex.Wait, error) {
return dex.Until(managerDecisions.ForOne()), nil
}
func (RequestManagerApproval) Execute(ctx dex.Context, input RefundCase) (*dex.StepDecision, error) {
decisions, err := managerDecisions.GetConditionResults(ctx)
if err != nil {
return nil, err
}
if len(decisions) != 1 {
return nil, fmt.Errorf("expected one manager decision, got %d", len(decisions))
}
if decisions[0].Approved {
return dex.GoTo(IssueRefund{}, input), nil
}
return denyRefund(ctx, input, decisions[0].Reason)
}
Example: examples/go/products/customer-refund/managerapproval/workflow.go
final class CheckPolicy implements Step<RefundCase> {
@Override
public Class<RefundCase> getInputType() {
return RefundCase.class;
}
@Override
public StepDecision execute(final Context context, final RefundCase input) {
final Order order = input.order();
final boolean outsideWindow = order.daysSinceCharge() > REFUND_WINDOW_DAYS;
final boolean noOutage = order.outageHours() == 0;
if (outsideWindow || noOutage) {
CASE_STATUS.set(context, "denied");
final String note;
if (outsideWindow && noOutage) {
note = "The charge is outside the 30-day window and no outage was recorded.";
} else if (outsideWindow) {
note = "The charge is outside the 30-day window.";
} else {
note = "No outage was recorded for this order.";
}
return StepDecision.goTo(WriteCustomerMessage.class, input.withOutcome("denied", note));
}
if (order.amountUsd() > MANAGER_APPROVAL_LIMIT_USD) {
CASE_STATUS.set(context, AWAITING_MANAGER);
return StepDecision.goTo(RequestManagerApproval.class, input);
}
return StepDecision.goTo(IssueRefund.class, input);
}
}
Example: examples/java/src/main/java/io/superdurable/dex/products/customerrefund/CustomerRefundFlow.java
class CheckPolicy implements Step<RefundCase> {
public getStepType(): string {
return "CheckPolicy";
}
public execute(context: Context, input: RefundCase): StepDecision {
const order = input.order;
const windowExpired = order.daysSinceCharge > REFUND_WINDOW_DAYS;
const noOutage = order.outageHours === 0;
if (windowExpired || noOutage) {
caseStatus.set(context, "denied");
const notes = [
windowExpired ? WINDOW_EXPIRED_NOTE : "",
noOutage ? NO_OUTAGE_NOTE : "",
];
return goTo(WriteCustomerMessage, { ...input, outcome: "denied", note: notes.join(" ").trim() });
}
if (order.amountUsd > MANAGER_APPROVAL_LIMIT_USD) {
caseStatus.set(context, AWAITING_MANAGER);
return goTo(RequestManagerApproval, input);
}
return goTo(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 implements Step<RefundCase> {
public getStepType(): string {
return "RequestManagerApproval";
}
public waitFor(_context: Context, _input: RefundCase): Wait {
return Wait.until(managerDecisions.forOne());
}
public execute(context: Context, input: RefundCase): StepDecision {
const [decision] = managerDecisions.results(context);
if (decision.approved) {
return goTo(IssueRefund, input);
}
caseStatus.set(context, "denied");
return goTo(WriteCustomerMessage, { ...input, outcome: "denied", note: decision.reason });
}
}
Example: examples/typescript/src/products/customer-refund/refund-flow.ts
impl Step for CheckPolicy {
type Input = RefundCase;
fn execute(&self, context: &mut Context, input: Self::Input) -> HandlerResult<StepDecision> {
let order = &input.order;
let mut denial_reasons = Vec::new();
if order.days_since_charge > REFUND_WINDOW_DAYS {
denial_reasons.push("The charge is outside the 30-day refund window.");
}
if order.outage_hours == 0 {
denial_reasons.push("No service outage was recorded for this charge.");
}
if !denial_reasons.is_empty() {
CASE_STATUS.set(context, CaseStatus::Denied)?;
let note = denial_reasons.join(" ");
let denied = ResolvedCase::new(input, RefundOutcome::Denied, note);
return Ok(StepDecision::go_to(
&WriteCustomerMessage::new(&self.services),
denied,
));
}
if order.amount_cents > MANAGER_APPROVAL_LIMIT_CENTS {
CASE_STATUS.set(context, CaseStatus::AwaitingManager)?;
return Ok(StepDecision::go_to(
&RequestManagerApproval::new(&self.services),
input,
));
}
Ok(StepDecision::go_to(
&IssueRefund::new(&self.services),
Example: examples/rust/src/products/customer_refund/refund_flow.rs
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>andemail-<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-succeedscenario, 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-statusandcustomer-emailstay plaintext, so Dex Web can show them. Dex Web evaluates the Actions' condition oncase-status.
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.
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.
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.
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.
Run it
The Quick Start runs the manager approval Flow end to end. The example folders for Python, Go, TypeScript, Java, and Rust 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. Then open the examples playground and choose Customer refund with manager approval.
Next
Production operations: a Dex application runs on four components: your application, the server, the CLI, and Web.