# 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/java/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, marked `@Role`, as telling a customer is in [chapter 19](https://itinera-dev.org/book/java/19-letting-policies-act-on-the-outside-world.md):

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

```java
/** What the shop does for its policies: give an order's money back. */
@Role
interface Refunds {
  void refund(String receipt, long amount);
}

```

`HeavyParcels` now does more than turn heavy parcels away, so it becomes `FailedShipping`, named `failedShipping`. Its `on step retry` still gives up a parcel over the limit, and refunds the charge first. A second hook, marked `@OnStepFailure`, from `org.itineradev.itinera.policy`, refunds the charge of a shipping that the executor gave up. Its parameter of type `FailureCause`, from `org.itineradev.itinera.journey`, asks for why the step was given up. Both hooks ask for the receipt and the amount from the data bag, the role, and a contributor, and both call `refund`, a method of the policy's own:

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

```java
/**
 * 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")
final class FailedShipping implements ItineraStepPolicy {
  @OnStepRetry
  public OnFailure beforeRetrying(
      Optional<Reason> reason,
      @FromWorkflow String receipt,
      @FromWorkflow long amount,
      @Role Refunds refunds,
      Contributor contributor) {
    boolean overLimit = reason.map(Reason::code).filter("over-parcel-limit"::equals).isPresent();
    if (!overLimit) return keepDefault();
    refund(refunds, contributor, receipt, amount, "over-parcel-limit");
    return failWorkflow("no-carrier-can-take-it");
  }

  @OnStepFailure
  public OnFailure givenUp(
      FailureCause cause,
      @FromWorkflow String receipt,
      @FromWorkflow long amount,
      @Role Refunds refunds,
      Contributor contributor) {
    refund(refunds, contributor, receipt, amount, cause.toString());
    return keepDefault();
  }

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

```

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

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

```java
/**
 * 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. Once a journey has ended, the
 * customer is told, through the channel the shop configures.
 */
@Workflow(
    name = "orders",
    reporters = {Log.class, Desk.class},
    policies = {Notify.class})
@WithStep(
    step = Lookup.class,
    name = "lookup",
    policies = {AlreadyCompleted.class})
@WithStep(step = Price.class, name = "price")
@WithStep(
    step = Charge.class,
    name = "charge",
    rescue = RenewCard.class,
    policies = {Audit.class, Outage.class})
@WithStep(
    step = Ship.class,
    name = "ship",
    retryBudget = 1,
    policies = {FailedShipping.class})
final class Orders implements ItineraWorkflow, Messages, Refunds {
  private final String channel;

  Orders(String channel) {
    this.channel = channel;
  }

  @Override
  public void tell(String customer, String message) {
    System.out.println(channel + " to " + customer + ": " + message);
  }

  @Override
  public void refund(String receipt, long amount) {
    System.out.println("the bank gives " + amount + " back on receipt " + receipt);
  }

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

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

  /**
   * 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"})
  public Supplied parcels(@Key String key, @FromWorkflow Parcel parcel) {
    return key.equals("weight") ? supply(parcel.weight()) : fromDataBag();
  }

  /** Names each journey after its order. */
  @IdGenerator
  public String orderNumber(DataBag data) {
    String order = data.read("order", TypeToken.of(String.class)).orNull();
    if (order == null) throw new IllegalStateException("an order without a number");
    return order;
  }

  /** The order book, which has the orders completed before today. */
  @Provider(key = "orderBook")
  public Provided<OrderBook> ledger() {
    return provide(new Ledger(List.of("A-13")));
  }
}

```

The other steps, policies and reporters it names are as earlier chapters show them: the lookup and `AlreadyCompleted` in [chapter 22](https://itinera-dev.org/book/java/22-finishing-a-journey-early.md), the pricing, the charge and the audit in [chapter 20](https://itinera-dev.org/book/java/20-an-optional-input.md), `RenewCard` in [chapter 14](https://itinera-dev.org/book/java/14-repairing-then-trying-once-more.md), the shipping and `Outage` in [chapter 17](https://itinera-dev.org/book/java/17-giving-up-a-step-early.md), `Notify` and the role `Messages` in [chapter 19](https://itinera-dev.org/book/java/19-letting-policies-act-on-the-outside-world.md), the log in [chapter 22](https://itinera-dev.org/book/java/22-finishing-a-journey-early.md), with the parts that page points to, and the desk in [chapter 11](https://itinera-dev.org/book/java/11-naming-a-journey.md). Its providers lend [chapter 14](https://itinera-dev.org/book/java/14-repairing-then-trying-once-more.md)'s `Payments`, [chapter 12](https://itinera-dev.org/book/java/12-trying-again.md)'s `Carrier` and [chapter 22](https://itinera-dev.org/book/java/22-finishing-a-journey-early.md)'s `OrderBook`, and its input adapter reads [chapter 21](https://itinera-dev.org/book/java/21-deciding-where-a-steps-data-comes-from.md)'s `Parcel`.

`main` 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. `main` also prints the refund the journey recorded:

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

```java
final class Main {
  private Main() {}

  public static void main(String[] args) throws Refusal {
    // Each order: its number, its customer, its price, its parcel, as its weight in kg and its size
    // in cm, and the card.
    var orders =
        List.of(
            new NewOrder("A-7", "Gil", 45, new Parcel(60, List.of(120L, 80L, 60L)), "gil-2027"),
            new NewOrder("A-12", "Ned", 50, new Parcel(90, List.of(120L, 80L, 80L)), "ned-2028"),
            new NewOrder("A-14", "Oli", 20, new Parcel(0, List.of(30L, 20L, 20L)), "oli-2029"));
    for (var order : orders) {
      System.out.println(order.customer() + "'s order:");
      var instance = new Orders("email").instance().initialData(order).create();
      var result = new LocalExecutor().run(instance);
      var data = result.output(TypeToken.of(Order.class));
      var ended = result.isSucceeded() ? "succeeded" : "failed";
      var receipt = data.receipt().orElse("none");
      var tracking = data.tracking().orElse("none");
      System.out.println(
          "the journey " + ended + ", with receipt " + receipt + " and tracking " + tracking);
      System.out.println("audit: " + data.audit().orElse("none"));
      System.out.println("refund: " + data.refund().orElse("none"));
    }
  }
}
```

`NewOrder` and `Parcel` are as [chapter 21](https://itinera-dev.org/book/java/21-deciding-where-a-steps-data-comes-from.md) shows them, and the output now holds the refund:

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

```java
/** What the shop reads back once the journey has ended. */
record Order(
    Optional<String> receipt,
    Optional<String> tracking,
    Optional<String> audit,
    Optional<String> refund) {}

```

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/java/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 ch23_undoing_a_charge_when_the_shipping_fails.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 ch23_undoing_a_charge_when_the_shipping_fails.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 ch23_undoing_a_charge_when_the_shipping_fails.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 ch23_undoing_a_charge_when_the_shipping_fails.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 ch23_undoing_a_charge_when_the_shipping_fails.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 ch23_undoing_a_charge_when_the_shipping_fails.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 ch23_undoing_a_charge_when_the_shipping_fails.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 ch23_undoing_a_charge_when_the_shipping_fails.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 ch23_undoing_a_charge_when_the_shipping_fails.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 ch23_undoing_a_charge_when_the_shipping_fails.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 ch23_undoing_a_charge_when_the_shipping_fails.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.** Both carriers threw `BookingFailed` for Oli's parcel, so the shipping ended in an abnormal termination on both attempts, so it was given up with the cause `retries exhausted`. Then `on step failure` was called, and asked for that cause, a `FailureCause`, which prints as the specification writes it. 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.
3. **A policy is a class of its own, and may hold code its hooks share.** `refund` is a private method with no hook annotation, 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/java/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/java/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 `main` 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.                                                           |
