客户退款
查看 MarkdownFlow 根据订单和退款政策检查客户的退款申请,金额较大时等待经理审批,然后退款并给客户发邮件。Go 还有两个更大的退款 Flow:确定性策略和 agentic 审核。
SDK: Python · Go · TypeScript · Java · Rust
展示: 通过 Channel 和 RPC 完成经理审批、Dex Web Action、幂等 key,以及 Time Travel。
经理审批的退款
这张图由 Python 源码生成。在 TypeScript、Java 和 Rust 中,Check policy 只有一条拒绝分支,而不是两条。在 Go 中,Flow 类型是 ManagerApprovalRefundFlow,因为 CustomerRefundFlow 已是确定性策略的 Go Flow。
Check policy 应用退款政策。超过 30 天的扣款,或没有记录到服务中断的扣款,会被拒绝。1,000 USD 或以下的金额直接进入 Issue refund,更大的金额进入 Request manager approval。这个 Step 在一个 Channel 上等待一条消息,再按经理的决定退款或拒绝。
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))
例子: 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)
}
例子: 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);
}
}
例子: 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 });
}
}
例子: 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),
例子: examples/rust/src/products/customer_refund/refund_flow.rs
一个批准 RPC 和一个拒绝 RPC 把经理的决定发布到这个 Channel。每个 RPC 都要求填写原因,并且只在 case-status 为 awaiting-manager 时发布。在 Python、Go 和 TypeScript 中,这两个 RPC 同时是 Dex Web 的 Action:Approve refund 和 Reject refund。每种语言都能用示例的 decide 命令批准或拒绝。Java 和 Rust 没有 Action。
这个示例还展示了生产环境的退款需要什么:
- Issue refund 和 Send message 向 billing 和 email 传入由 Flow ID 生成的幂等 key:
refund-<Flow ID>和email-<Flow ID>。被中断的 Step 可能再次运行,Time Travel 点之后的 Step 也会再次运行。每个 fake 服务遇到自己持久化记录里已有的 key 就跳过。Worker 必须共用这些记录;各用一份记录的 Worker 会各退一次款。 - Issue refund 遇到支付超时,每 5 秒重试一次。在
fail-then-succeed场景中,Dex Web 里最后一个 Issue refund 事件显示第 3 次尝试成功,并保留最近一次失败的详情。 - 在 Python、Go 和 TypeScript 中,提供 payload key 文件后,Worker 和 Client 会加密 payload。
case-status和customer-email保持明文,所以 Dex Web 能显示它们。Dex Web 根据case-status判断 Action 的条件。
确定性策略
Go 中的 CustomerRefundFlow 先确认订单存在,再应用 30 天规则。Issue refund 用 case ID 加 :refund 生成 billing key,传给支付 provider,并随 Step 结果一起保存。如果 provider 拒绝退款,或者结果未知,Flow 会把这个结果记为 case 状态。
Summary 展示 charge reference、请求金额和 recommendation,Display 再加上证据、计费结果和可编辑的 operator note。它不声明任何 Action,用来说明没有 Action 的 Flow 在 Dex Web 中同样有效。源码:deterministic/workflow.go。
Agentic 审核
Go 中的 AgenticCustomerRefundFlow 在一个由 Step 组成的循环里收集证据。随后由 guardrail 自动执行决定,或等待经理审批。一个 OpenAI Connector Step 起草给客户的消息,由人确认或改写后再发送。Flow 在 billing 之前用单独的 Step 记录退款意图。billing Step 把 case ID 加 :refund(账户抵扣用 :credit)作为 key 传给 billing,并随结果一起保存。图中 Step 上的 ⚠ 表示一条失败路由;选中这个 Step 可以看到它通向哪里。
Flow 每打开一道人工 gate,都会生成新的 gate key。ApproveRefund Action 直接显示为按钮,不需要输入。RejectRefund 要求填写原因,EditCustomerMessage 要求填写要发送的消息。这两个 Action 和 ConfirmCustomerMessage 还把 gate key 放在隐藏输入里,由 Dex Web 从页面打开时读到的 Attribute 值填入。RPC 发布之前会把它与当前 gate 比较;如果 gate 已经变了,RPC 返回错误,操作员刷新页面。每个 RPC 还会检查 case 状态,因为 Action 的可见性条件只决定按钮是否出现,不做任何授权。源码:agentic/workflow.go。
运行
Quick Start 完整运行经理审批 Flow。Python、Go、TypeScript、Java 和 Rust 的示例文件夹列出了其他场景的命令:不需要经理的小额退款、拒绝、先失败后成功的退款,以及用 Time Travel 修复缺失的 billing 调用。Go 文件夹还能启动确定性和 agentic Flow。
要通过 HTTP 启动退款,先按在 playground 里运行一个示例启动一种语言的示例。然后打开示例 playground,选择 Customer refund with manager approval。
下一步
生产运维:Dex 应用运行在四个组件上:你的应用、server、CLI 和 Web。