# 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/kotlin/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/kotlin/19-letting-policies-act-on-the-outside-world.md):

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

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

```

`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:

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

```kotlin
/**
 * 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 : ItineraStepPolicy {
    @OnStepRetry
    fun beforeRetrying(
        reason: Reason?,
        @FromWorkflow receipt: String,
        @FromWorkflow amount: Long,
        @Role refunds: Refunds,
        contributor: Contributor,
    ): OnFailure {
        if (reason?.code != "over-parcel-limit") return keepDefault()
        refund(refunds, contributor, receipt, amount, "over-parcel-limit")
        return failWorkflow("no-carrier-can-take-it")
    }

    @OnStepFailure
    fun givenUp(
        cause: FailureCause,
        @FromWorkflow receipt: String,
        @FromWorkflow amount: Long,
        @Role refunds: Refunds,
        contributor: Contributor,
    ): OnFailure {
        refund(refunds, contributor, receipt, amount, "$cause")
        return keepDefault()
    }

    /** Gives the order's money back, and records why. */
    private fun refund(
        refunds: Refunds,
        contributor: Contributor,
        receipt: String,
        amount: Long,
        why: String,
    ) {
        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:

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

```kotlin
/**
 * 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(Lookup::class, name = "lookup", policies = [AlreadyCompleted::class])
@WithStep(Price::class, name = "price")
@WithStep(
    Charge::class,
    name = "charge",
    rescue = RenewCard::class,
    policies = [Audit::class, Outage::class],
)
@WithStep(Ship::class, name = "ship", retryBudget = 1, policies = [FailedShipping::class])
class Orders(private val channel: String) : ItineraWorkflow, Messages, Refunds {
    override fun tell(customer: String, message: String) {
        println("$channel to $customer: $message")
    }

    override fun refund(receipt: String, amount: Long) {
        println("the bank gives $amount back on receipt $receipt")
    }

    /** The bank, as the payment client of the journey. */
    @Provider(key = "payments") fun bank(): Provided<Payments> = provide(Bank(thisYear = 2026))

    /** A carrier for every attempt of a step: the main carrier first, the backup carrier after. */
    @Provider(perAttempt = true, key = "carrier")
    fun carriers(attempt: Attempt): Provided<Carrier> =
        if (attempt.isFirst) provide(MainCarrier()) else provide(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"])
    fun parcels(@Key key: String, @FromWorkflow parcel: Parcel): Supplied =
        if (key == "weight") supply(parcel.weight) else fromDataBag()

    /** Names each journey after its order. */
    @IdGenerator
    fun orderNumber(data: DataBag): String =
        data.read<String>("order").orNull() ?: error("an order without a number")

    /** The order book, which has the orders completed before today. */
    @Provider(key = "orderBook") fun ledger(): Provided<OrderBook> = provide(Ledger(listOf("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/kotlin/22-finishing-a-journey-early.md), the pricing, the charge and the audit in [chapter 20](https://itinera-dev.org/book/kotlin/20-an-optional-input.md), `RenewCard` in [chapter 14](https://itinera-dev.org/book/kotlin/14-repairing-then-trying-once-more.md), the shipping and `Outage` in [chapter 17](https://itinera-dev.org/book/kotlin/17-giving-up-a-step-early.md), `Notify` and the role `Messages` in [chapter 19](https://itinera-dev.org/book/kotlin/19-letting-policies-act-on-the-outside-world.md), the log in [chapter 22](https://itinera-dev.org/book/kotlin/22-finishing-a-journey-early.md), with the parts that page points to, and the desk in [chapter 11](https://itinera-dev.org/book/kotlin/11-naming-a-journey.md). Its providers lend [chapter 14](https://itinera-dev.org/book/kotlin/14-repairing-then-trying-once-more.md)'s `Payments`, [chapter 12](https://itinera-dev.org/book/kotlin/12-trying-again.md)'s `Carrier` and [chapter 22](https://itinera-dev.org/book/kotlin/22-finishing-a-journey-early.md)'s `OrderBook`, and its input adapter reads [chapter 21](https://itinera-dev.org/book/kotlin/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:

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

```kotlin
fun main() {
    // Each order: its number, its customer, its price, its parcel, as its weight in kg and its size
    // in cm, and the card.
    val orders =
        listOf(
            NewOrder(
                "A-7",
                "Gil",
                price = 45,
                parcel = Parcel(weight = 60, size = listOf(120, 80, 60)),
                card = "gil-2027",
            ),
            NewOrder(
                "A-12",
                "Ned",
                price = 50,
                parcel = Parcel(weight = 90, size = listOf(120, 80, 80)),
                card = "ned-2028",
            ),
            NewOrder(
                "A-14",
                "Oli",
                price = 20,
                parcel = Parcel(weight = 0, size = listOf(30, 20, 20)),
                card = "oli-2029",
            ),
        )
    for (order in orders) {
        println("${order.customer}'s order:")
        val instance = Orders(channel = "email").instance().initialData(order).create()
        val result = LocalExecutor().run(instance)
        val data = result.output<Order>()
        val ended = if (result.isSucceeded) "succeeded" else "failed"
        val receipt = data.receipt ?: "none"
        val tracking = data.tracking ?: "none"
        println("the journey $ended, with receipt $receipt and tracking $tracking")
        println("audit: ${data.audit ?: "none"}")
        println("refund: ${data.refund ?: "none"}")
    }
}
```

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

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

```kotlin
/** What the shop reads back once the journey has ended. */
data class Order(
    val receipt: String?,
    val tracking: String?,
    val audit: String?,
    val refund: String?,
)

```

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/kotlin/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/kotlin/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/kotlin/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.                                                           |
