Refund Workflow Example

Real-world e-commerce refund workflow demonstrating memory-informed decision making.

Overview

This example shows:

Code

import { Workflow } from "@mdwr/sdk";

const refundWorkflow = Workflow.create("refund_v1")
  .step("evaluate_risk", async (ctx) => {
    // Query memory for similar decisions
    const insights = await ctx.memory.similar({
      situation: "refund_decision",
      context: {
        amount: ctx.input.amount,
        userTier: ctx.input.userTier,
      },
    });

    // Use historical insights to inform decision
    let decision = "approve";
    let reason = "Standard approval";
    let confidence = 0.8;

    if (insights.length > 0) {
      const bestInsight = insights[0];
      if (bestInsight.outcome && bestInsight.outcome.success) {
        decision = bestInsight.decision.decision;
        reason = `Based on similar successful decision: ${bestInsight.decision.reason}`;
        confidence = Math.min(0.95, (bestInsight.decision.confidence || 0.8) + 0.1);
      }
    }

    // Business logic
    if (ctx.input.amount > 1000) {
      decision = "manual_review";
      reason = "High amount requires manual review";
      confidence = 0.9;
    }

    return {
      decision,
      reason,
      confidence,
      metadata: {
        similarDecisions: insights.length,
        amount: ctx.input.amount,
      },
    };
  }, true)
  .step("issue_refund", async (ctx) => {
    // Only execute if previous step approved
    if (ctx.state.evaluate_risk?.decision !== "approve") {
      return {
        decision: "skip",
        reason: "Refund not approved in risk evaluation",
        confidence: 1.0,
      };
    }

    // Issue refund logic
    console.log(`Issuing refund of $${ctx.input.amount} to user ${ctx.input.userId}`);

    return {
      decision: "completed",
      reason: "Refund issued successfully",
      confidence: 1.0,
    };
  }, true);

export default refundWorkflow;

Running the Example

# Deploy the workflow
npx ts-node scripts/deploy.ts

# Execute with sample input
npx ts-node scripts/execute.ts refund_v1

Input Example

{
  "userId": "user123",
  "amount": 120,
  "userTier": "gold"
}

Key Features

Memory Integration

const insights = await ctx.memory.similar({
  situation: "refund_decision",
  context: {
    amount: ctx.input.amount,
    userTier: ctx.input.userTier
  }
});

Using Historical Insights

if (insights.length > 0) {
  const best = insights[0];
  if (best.outcome?.success) {
    decision = best.decision.decision;
    reason = `Based on similar decision: ${best.decision.reason}`;
  }
}

Conditional Execution

if (ctx.state.evaluate_risk?.decision !== "approve") {
  return { decision: "skip", reason: "...", confidence: 1.0 };
}

Next Steps