# Undoing a charge when the shipping fails

## What you want to do

When the shop gives up an order's shipping, the customer has already paid: Ned's parcel of 90 kg is charged, then given up, as in [chapter 17](https://itinera-dev.org/book/typescript/17-giving-up-a-step-early.md), and the shop keeps his money. You want the shop to give the charge back whenever the shipping is given up, whatever gave it up.

## The code

Giving money back is something the shop does for its policies, so it is a role, as telling a customer is in [chapter 19](https://itinera-dev.org/book/typescript/19-letting-policies-act-on-the-outside-world.md): an interface of its own.

TypeScript, from the program [`ch23_undoing_a_charge_when_the_shipping_fails`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch23_undoing_a_charge_when_the_shipping_fails.ts)

```typescript
/** What the shop does for its policies: give an order's money back. */
interface Refunds {
  refund(receipt: string, amount: number): void;
}
```

`HeavyParcels` now does more than turn heavy parcels away, so it becomes `FailedShipping`, named `failedShipping`. It names the role it asks for with `StepPolicy<Refunds>`, as `Notify` does with `WorkflowPolicy<Messages>`. Its `on step retry` still gives up a parcel over the limit, and refunds the charge first. A second hook, marked `@onStepFailure()`, refunds the charge of a shipping that the executor gave up. It asks for the cause the step was given up with, as a parameter marked `@failureCause()` and typed `StepFailureCause`, both from `itinera/policy`. Both hooks ask for the receipt and the amount from the data bag, the role, and a contributor, and both call `refund`, a private method of the policy's own:

TypeScript, from the program [`ch23_undoing_a_charge_when_the_shipping_fails`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch23_undoing_a_charge_when_the_shipping_fails.ts)

```typescript
/**
 * Deals with a shipping that fails for good. It gives up a parcel over the
 * shop's limit rather than try it again, since the limit is the same on every
 * attempt, whichever carrier comes. And whatever gave the shipping up, it
 * refunds the order's charge.
 */
@stepPolicy({ name: "failedShipping" })
class FailedShipping extends StepPolicy<Refunds> {
  @onStepRetry()
  beforeRetrying(
    @failureReason({ optional: true }) reason: Option<Reason>,
    @fromWorkflow("receipt", string) receipt: string,
    @fromWorkflow("amount", integer) amount: number,
    @role<Refunds>() refunds: Refunds,
    @contributor() contributor: Contributor,
  ): OnFailure {
    if (reason.isSome() && reason.value.code === "over-parcel-limit") {
      this.refund(refunds, contributor, receipt, amount, "over-parcel-limit");
      return this.failWorkflow("no-carrier-can-take-it");
    }
    return this.keepDefault();
  }

  @onStepFailure()
  givenUp(
    @failureCause() cause: StepFailureCause,
    @fromWorkflow("receipt", string) receipt: string,
    @fromWorkflow("amount", integer) amount: number,
    @role<Refunds>() refunds: Refunds,
    @contributor() contributor: Contributor,
  ): OnFailure {
    this.refund(refunds, contributor, receipt, amount, cause);
    return this.keepDefault();
  }

  /** Gives the order's money back, and records why. */
  private refund(
    refunds: Refunds,
    contributor: Contributor,
    receipt: string,
    amount: number,
    why: string,
  ): void {
    refunds.refund(receipt, amount);
    contributor.contribute(
      "refund",
      `${String(amount)} back on ${receipt}: ${why}`,
    );
  }
}
```

The workflow attaches it to the shipping, in place of `HeavyParcels`, and implements `Refunds` next to `Messages`. Here the bank is faked, and its `refund` prints what it gives back:

TypeScript, from the program [`ch23_undoing_a_charge_when_the_shipping_fails`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch23_undoing_a_charge_when_the_shipping_fails.ts)

```typescript
/**
 * The shop's workflow: it looks the order up, and finishes an order already
 * completed. Otherwise it works out what the order costs, then charges it,
 * repairing a charge that fails and auditing one that succeeds, then ships,
 * and shipping may be tried once more, its charge refunded if it is given up.
 * Once a journey has ended, the customer is told, through the channel the shop
 * configures.
 */
@workflow({ name: "orders", reporters: [Log, Desk], policies: [Notify] })
@withStep(Lookup, { name: "lookup", policies: [AlreadyCompleted] })
@withStep(Price, { name: "price" })
@withStep(Charge, {
  name: "charge",
  rescue: RenewCard,
  policies: [Audit, Outage],
})
@withStep(Ship, { name: "ship", retryBudget: 1, policies: [FailedShipping] })
class Orders extends Workflow implements Messages, Refunds {
  constructor(private readonly channel: string) {
    super();
  }

  tell(customer: string, message: string): void {
    console.log(`${this.channel} to ${customer}: ${message}`);
  }

  refund(receipt: string, amount: number): void {
    console.log(`the bank gives ${String(amount)} back on receipt ${receipt}`);
  }

  /** Names each journey after its order. */
  @idGenerator()
  orderNumber(@dataBag() data: DataBag): string {
    return data.read("order", string).option().expect("the order's number");
  }

  /**
   * Gives the shipping the weight of the order's parcel, as the warehouse
   * describes it. Every other input of the shipping is read from the data bag.
   */
  @inputAdapter({ steps: ["ship"] })
  parcels(
    @key() key: string,
    @fromWorkflow("parcel", PARCEL) parcel: Parcel,
  ): Supplied {
    if (key !== "weight") return this.fromDataBag();
    return this.supply(parcel.weight);
  }

  /** The bank, as the payment client of the journey. */
  @provider(PAYMENTS, { key: "payments" })
  bank(): Provided<Payments> {
    return this.provide(new Bank(2026));
  }

  /**
   * A carrier for every attempt of a step: the main carrier first, the backup
   * carrier after.
   */
  @provider(CARRIER, { key: "carrier", perAttempt: true })
  carriers(@attempt() attempt: Attempt): Provided<Carrier> {
    if (attempt.isFirst()) return this.provide(new MainCarrier());
    return this.provide(new BackupCarrier());
  }

  /** The order book, which has the orders completed before today. */
  @provider(ORDER_BOOK, { key: "orderBook" })
  ledger(): Provided<OrderBook> {
    return this.provide(new Ledger(["A-13"]));
  }
}
```

The other steps, policies and reporters it names are as earlier chapters show them: the lookup, `AlreadyCompleted` and the log in [chapter 22](https://itinera-dev.org/book/typescript/22-finishing-a-journey-early.md), the pricing, the charge and the audit in [chapter 20](https://itinera-dev.org/book/typescript/20-an-optional-input.md), `RenewCard` in [chapter 14](https://itinera-dev.org/book/typescript/14-repairing-then-trying-once-more.md), the shipping and `Outage` in [chapter 17](https://itinera-dev.org/book/typescript/17-giving-up-a-step-early.md), `Notify` and the role `Messages` in [chapter 19](https://itinera-dev.org/book/typescript/19-letting-policies-act-on-the-outside-world.md) and the desk in [chapter 11](https://itinera-dev.org/book/typescript/11-naming-a-journey.md). The ledger's provider, `OrderBook` and `ORDER_BOOK` are [chapter 22](https://itinera-dev.org/book/typescript/22-finishing-a-journey-early.md)'s, the adapter with `Parcel` and `PARCEL` [chapter 21](https://itinera-dev.org/book/typescript/21-deciding-where-a-steps-data-comes-from.md)'s, and the other providers [chapter 14](https://itinera-dev.org/book/typescript/14-repairing-then-trying-once-more.md)'s, with the tokens `PAYMENTS` and `CARRIER` of [chapter 7](https://itinera-dev.org/book/typescript/07-giving-a-step-the-tools-it-needs.md); the interfaces `Payments` and `Carrier` are [chapter 14](https://itinera-dev.org/book/typescript/14-repairing-then-trying-once-more.md)'s and [chapter 12](https://itinera-dev.org/book/typescript/12-trying-again.md)'s.

The program runs three orders: Gil's, whose parcel the backup carrier takes, Ned's, and the order of a new customer, Oli. The warehouse weighed Oli's parcel as 0 kg by mistake, and the faked carriers' booking systems fail on a parcel that weighs nothing. The output now holds the refund, and the program prints it:

TypeScript, from the program [`ch23_undoing_a_charge_when_the_shipping_fails`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch23_undoing_a_charge_when_the_shipping_fails.ts)

```typescript
/**
 * What the shop reads back once the journey has ended: the type of the value
 * under each name.
 */
const orderOutput = {
  receipt: optional(string),
  tracking: optional(string),
  audit: optional(string),
  refund: optional(string),
};

const shop = Orders.build("email");
// The order, the customer, the price, the discount when there is one, the
// parcel, the card, and whether the order is a gift card.
const orders = [
  {
    order: "A-7",
    customer: "Gil",
    price: 45,
    parcel: { weight: 60, size: [120, 80, 60] },
    card: "gil-2027",
    giftCard: false,
  },
  {
    order: "A-12",
    customer: "Ned",
    price: 50,
    parcel: { weight: 90, size: [120, 80, 80] },
    card: "ned-2028",
    giftCard: false,
  },
  {
    order: "A-14",
    customer: "Oli",
    price: 20,
    parcel: { weight: 0, size: [30, 20, 20] },
    card: "oli-2029",
    giftCard: false,
  },
];
for (const order of orders) {
  console.log(`${order.customer}'s order:`);
  const result = await new LocalExecutor().run(shop.instance(order));
  const data = result.output(orderOutput);
  const receipt = data.receipt.unwrapOr("none");
  const tracking = data.tracking.unwrapOr("none");
  console.log(
    `the journey ${result.status.kind}, with receipt ${receipt} and tracking ${tracking}`,
  );
  console.log(`audit: ${data.audit.unwrapOr("none")}`);
  console.log(`refund: ${data.refund.unwrapOr("none")}`);
}
```

It prints:

What `ch23_undoing_a_charge_when_the_shipping_fails` prints, recorded in [`ch23_undoing_a_charge_when_the_shipping_fails.txt`](https://github.com/itinera-dev/book/blob/main/typescript/expected/ch23_undoing_a_charge_when_the_shipping_fails.txt)

```text
Gil's order:
log orders A-7 #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-7 #2 attempt_started lookup, attempt 1
log orders A-7 #3 service_provided lookup gets orderBook from ledger, a Ledger
the order book has no order A-7 yet
log orders A-7 #4 step_succeeded lookup
log orders A-7 #5 contribution_committed completed
log orders A-7 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-7 #7 attempt_started price, attempt 1
log orders A-7 #8 optional_input_absent discount
log orders A-7 #9 step_succeeded price
log orders A-7 #10 contribution_committed amount
log orders A-7 #11 attempt_started charge, attempt 1
log orders A-7 #12 service_provided charge gets payments from bank, a Bank
the bank charges 45 for order A-7
log orders A-7 #13 step_succeeded charge
log orders A-7 #14 contribution_committed receipt
log orders A-7 #15 hook_called audit: on step success of charge
log orders A-7 #16 contribution_committed audit
log orders A-7 #17 attempt_started ship, attempt 1
log orders A-7 #18 input_adapter_supplied ship gets weight from parcels
log orders A-7 #19 service_provided ship gets carrier from carriers, a MainCarrier
the main carrier books order A-7
log orders A-7 #20 step_failed ship: too-heavy
log orders A-7 #21 hook_called failedShipping: on step retry of ship
log orders A-7 #22 step_retrying ship
log orders A-7 #23 attempt_started ship, attempt 2
log orders A-7 #24 input_adapter_supplied ship gets weight from parcels
log orders A-7 #25 service_provided ship gets carrier from carriers, a BackupCarrier
the backup carrier books order A-7
log orders A-7 #26 step_info ship: the parcel leaves with receipt R-A-7
log orders A-7 #27 step_succeeded ship
log orders A-7 #28 contribution_committed tracking
log orders A-7 #29 optional_input_absent code
email to Gil: Order A-7 is on its way, tracking B-A-7.
log orders A-7 #30 hook_called notify: on workflow success
log orders A-7 #31 journey_succeeded
the journey succeeded, with receipt R-A-7 and tracking B-A-7
audit: charge took 45, receipt R-A-7
refund: none
Ned's order:
log orders A-12 #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-12 #2 attempt_started lookup, attempt 1
log orders A-12 #3 service_provided lookup gets orderBook from ledger, a Ledger
the order book has no order A-12 yet
log orders A-12 #4 step_succeeded lookup
log orders A-12 #5 contribution_committed completed
log orders A-12 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-12 #7 attempt_started price, attempt 1
log orders A-12 #8 optional_input_absent discount
log orders A-12 #9 step_succeeded price
log orders A-12 #10 contribution_committed amount
log orders A-12 #11 attempt_started charge, attempt 1
log orders A-12 #12 service_provided charge gets payments from bank, a Bank
the bank charges 50 for order A-12
log orders A-12 #13 step_succeeded charge
log orders A-12 #14 contribution_committed receipt
log orders A-12 #15 hook_called audit: on step success of charge
log orders A-12 #16 contribution_committed audit
log orders A-12 #17 attempt_started ship, attempt 1
log orders A-12 #18 input_adapter_supplied ship gets weight from parcels
log orders A-12 #19 service_provided ship gets carrier from carriers, a MainCarrier
log orders A-12 #20 step_failed ship: over-parcel-limit
the bank gives 50 back on receipt R-A-12
log orders A-12 #21 hook_called failedShipping: on step retry of ship
log orders A-12 #22 contribution_committed refund
log orders A-12 #23 step_given_up ship: FailWorkflow from failedShipping, no-carrier-can-take-it
email to Ned: Sorry, order A-12 could not be completed.
log orders A-12 #24 hook_called notify: on workflow failure
log orders A-12 #25 journey_failed ship
desk: order A-12 failed at ship
the journey failed, with receipt R-A-12 and tracking none
audit: charge took 50, receipt R-A-12
refund: 50 back on R-A-12: over-parcel-limit
Oli's order:
log orders A-14 #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-14 #2 attempt_started lookup, attempt 1
log orders A-14 #3 service_provided lookup gets orderBook from ledger, a Ledger
the order book has no order A-14 yet
log orders A-14 #4 step_succeeded lookup
log orders A-14 #5 contribution_committed completed
log orders A-14 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-14 #7 attempt_started price, attempt 1
log orders A-14 #8 optional_input_absent discount
log orders A-14 #9 step_succeeded price
log orders A-14 #10 contribution_committed amount
log orders A-14 #11 attempt_started charge, attempt 1
log orders A-14 #12 service_provided charge gets payments from bank, a Bank
the bank charges 20 for order A-14
log orders A-14 #13 step_succeeded charge
log orders A-14 #14 contribution_committed receipt
log orders A-14 #15 hook_called audit: on step success of charge
log orders A-14 #16 contribution_committed audit
log orders A-14 #17 attempt_started ship, attempt 1
log orders A-14 #18 input_adapter_supplied ship gets weight from parcels
log orders A-14 #19 service_provided ship gets carrier from carriers, a MainCarrier
the main carrier's booking system fails on order A-14
log orders A-14 #20 step_abnormal_termination ship: the booking system failed
log orders A-14 #21 hook_called failedShipping: on step retry of ship
log orders A-14 #22 step_retrying ship
log orders A-14 #23 attempt_started ship, attempt 2
log orders A-14 #24 input_adapter_supplied ship gets weight from parcels
log orders A-14 #25 service_provided ship gets carrier from carriers, a BackupCarrier
the backup carrier's booking system fails on order A-14
log orders A-14 #26 step_abnormal_termination ship: the booking system failed
log orders A-14 #27 step_given_up ship: retries exhausted
the bank gives 20 back on receipt R-A-14
log orders A-14 #28 hook_called failedShipping: on step failure of ship
log orders A-14 #29 contribution_committed refund
email to Oli: Sorry, order A-14 could not be completed.
log orders A-14 #30 hook_called notify: on workflow failure
log orders A-14 #31 journey_failed ship
desk: order A-14 failed at ship
the journey failed, with receipt R-A-14 and tracking none
audit: charge took 20, receipt R-A-14
refund: 20 back on R-A-14: retries exhausted
```

## How it works

1. **`on step failure` runs once the executor gives a step up by its own rule.** Oli's shipping ended in an error on both attempts, so it was given up with the cause `retries exhausted`. Then `on step failure` was called, and asked for that cause. It returns an `OnFailure`, as `on step retry` does; keeping the default, as here, lets the journey fail as it would have.
2. **A step given up by a hook never reaches `on step failure`.** Ned's shipping was given up by `on step retry`, with `FailWorkflow`, so the hook that gave it up has already decided how the journey ends, and no other hook of the shipping is called. That is why `beforeRetrying` refunds too. `on step retry` is called only when a retry is left: for Gil, it keeps the default, and his order is never refunded. That is also why `StepFailureCause` never holds `FailWorkflow`: it is one of the other causes, which [chapter 12](https://itinera-dev.org/book/typescript/12-trying-again.md) and [chapter 18](https://itinera-dev.org/book/typescript/18-doing-something-when-the-journey-ends.md) showed.
3. **A policy is a class of its own, and may hold code its hooks share.** `refund` has no hook mark, so the executor never calls it. Both hooks call it: `on step retry` when it gives the shipping up, and `on step failure` once the executor has given it up. The giving up and the undoing of the shipping live together in one policy: the shipping and the charge know nothing about refunds, and the workflow only carries out the refund the policy asks for, through its role.
4. **A hook's contributions are committed whatever the step's outcome.** The shipping failed, but `refund` is in Ned's and Oli's data, because a hook's contributor commits as soon as the hook returns. Only a failed attempt's own contributions are thrown away, as [chapter 6](https://itinera-dev.org/book/typescript/06-passing-data-on.md) showed.
5. **The undo sits with the step it undoes.** `Notify`'s `on workflow failure` runs for every failed journey, so a refund there would first have to find out whether a charge went through. Lee's journey, for one, fails without any charge, as [chapter 21](https://itinera-dev.org/book/typescript/21-deciding-where-a-steps-data-comes-from.md)'s run shows.

The shop now gives back what it can't deliver. But look at how the program runs the orders: it makes a new executor for each one, and waits for each journey to end before it starts the next.

## Outcomes

We have shown how one step policy undoes a charge, however the shipping after it is given up.

| The usual way                                                                                                          | With Itinera                                                                                                                                           |
| ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Undoing work after a failure is often written in each place that can give up, and one of them is easily forgotten.     | Whichever gave the shipping up, a hook or the executor, the hook that sees it calls the policy's own `refund`, so every shipping given up is refunded. |
| The code that undoes an order's payment often ends up inside the shipping code, which then has to know about payments. | The shipping only reports what happened, and the policy attached to it decides what to undo.                                                           |
