# Finishing a journey early

## What you want to do

Now and then the website sends an order a second time: Mia's order A-13, paid and shipped yesterday, arrives again today. You want the shop to see that the order is already done, and end its journey there, as succeeded, without charging Mia or booking her parcel a second time.

## The code

The shop keeps an order book, which says whether an order was already completed. It is a service, like the bank, so it is an interface of the shop's own:

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

```kotlin
/** The shop's order book: it says whether an order was already completed. */
interface OrderBook {
    fun completed(order: String): Boolean
}

```

A new step, the lookup, asks the order book about the order and gives back what it says, under `completed`. It decides nothing about what happens next:

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

```kotlin
/** Looks the order up in the order book, and gives back whether it was already completed. */
@Step
class Lookup(@Input private val order: String) : ItineraStep {
    fun run(@Service orderBook: OrderBook, contributor: Contributor): Outcome {
        contributor.contribute("completed", orderBook.completed(order))
        return succeed()
    }
}

```

A step policy, `alreadyCompleted`, reads that answer. Its `on step success` asks for `completed` from the step, with `@FromStep`, as the audit asks for the receipt in [chapter 15](https://itinera-dev.org/book/kotlin/15-reacting-to-what-a-step-did.md). For an order already completed, it returns `finishWorkflow()`, which `ItineraStepPolicy` gives the class beside `keepDefault()`: the lifecycle `FinishWorkflow`. Otherwise it keeps the default:

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

```kotlin
/**
 * Finishes the journey of an order that was already completed: there is nothing left to do for it.
 */
@StepPolicy(name = "alreadyCompleted")
class AlreadyCompleted : ItineraStepPolicy {
    @OnStepSuccess
    fun lookedUp(@FromStep completed: Boolean): OnSuccess =
        if (completed) finishWorkflow() else keepDefault()
}

```

The workflow runs the lookup first, with the policy attached to it. Its new provider, `ledger`, makes the order book, which in this program is faked, and holds the one order completed before today, Mia's:

Kotlin, from the program [`ch22_finishing_a_journey_early`](https://github.com/itinera-dev/book/blob/main/kotlin/examples/ch22_finishing_a_journey_early.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 = [HeavyParcels::class])
class Orders(private val channel: String) : ItineraWorkflow, Messages {
    override fun tell(customer: String, message: String) {
        println("$channel to $customer: $message")
    }

    /** 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 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, `Outage` and `HeavyParcels` 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) and the desk in [chapter 11](https://itinera-dev.org/book/kotlin/11-naming-a-journey.md). The bank's provider is [chapter 12](https://itinera-dev.org/book/kotlin/12-trying-again.md)'s, the interface `Payments` it lends [chapter 14](https://itinera-dev.org/book/kotlin/14-repairing-then-trying-once-more.md)'s, the carriers' provider [chapter 13](https://itinera-dev.org/book/kotlin/13-a-carrier-for-each-attempt.md)'s, with [chapter 12](https://itinera-dev.org/book/kotlin/12-trying-again.md)'s `Carrier`, and the input adapter [chapter 21](https://itinera-dev.org/book/kotlin/21-deciding-where-a-steps-data-comes-from.md)'s.

The log is [chapter 21](https://itinera-dev.org/book/kotlin/21-deciding-where-a-steps-data-comes-from.md)'s, with the parts that page points to, and now also says which policy finished a journey:

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

```kotlin
is JourneySucceeded ->
    when (val decidedBy = event.decidedBy) {
        is DecidingHook -> "FinishWorkflow from ${decidedBy.policy}"
        DecidedBy.Default -> null
    }
```

`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 `Order`, the output, as [chapter 19](https://itinera-dev.org/book/kotlin/19-letting-policies-act-on-the-outside-world.md) does. `main` runs two orders, Ann's and Mia's:

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

```kotlin
fun main() {
    // Each order: its number, its customer, its price, its discount if it has one, its parcel, as
    // its weight in kg and its size in cm, and the card.
    val orders =
        listOf(
            NewOrder(
                "A-1",
                "Ann",
                price = 40,
                discount = 10,
                parcel = Parcel(weight = 2, size = listOf(30, 20, 10)),
                card = "ann-2028",
            ),
            NewOrder(
                "A-13",
                "Mia",
                price = 50,
                parcel = Parcel(weight = 4, size = listOf(40, 30, 30)),
                card = "mia-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"}")
    }
}
```

It prints:

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

```text
Ann's order:
log orders A-1 #1 journey_started order, customer, price, discount, parcel, card, giftCard
log orders A-1 #2 attempt_started lookup, attempt 1
log orders A-1 #3 service_provided lookup gets orderBook from ledger, a ch22_finishing_a_journey_early.Ledger
the order book has no order A-1 yet
log orders A-1 #4 step_succeeded lookup
log orders A-1 #5 contribution_committed completed
log orders A-1 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-1 #7 attempt_started price, attempt 1
log orders A-1 #8 step_succeeded price
log orders A-1 #9 contribution_committed amount
log orders A-1 #10 attempt_started charge, attempt 1
log orders A-1 #11 service_provided charge gets payments from bank, a ch22_finishing_a_journey_early.Bank
the bank charges 30 for order A-1
log orders A-1 #12 step_succeeded charge
log orders A-1 #13 contribution_committed receipt
log orders A-1 #14 hook_called audit: on step success of charge
log orders A-1 #15 contribution_committed audit
log orders A-1 #16 attempt_started ship, attempt 1
log orders A-1 #17 input_adapter_supplied ship gets weight from parcels
log orders A-1 #18 service_provided ship gets carrier from carriers, a ch22_finishing_a_journey_early.MainCarrier
the main carrier books order A-1
log orders A-1 #19 step_info ship: the parcel leaves with receipt R-A-1
log orders A-1 #20 step_succeeded ship
log orders A-1 #21 contribution_committed tracking
log orders A-1 #22 optional_input_absent code
email to Ann: Order A-1 is on its way, tracking T-A-1.
log orders A-1 #23 hook_called notify: on workflow success
log orders A-1 #24 journey_succeeded
the journey succeeded, with receipt R-A-1 and tracking T-A-1
audit: charge took 30, receipt R-A-1
Mia's order:
log orders A-13 #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-13 #2 attempt_started lookup, attempt 1
log orders A-13 #3 service_provided lookup gets orderBook from ledger, a ch22_finishing_a_journey_early.Ledger
the order book has order A-13 completed already
log orders A-13 #4 step_succeeded lookup
log orders A-13 #5 contribution_committed completed
log orders A-13 #6 hook_called alreadyCompleted: on step success of lookup
log orders A-13 #7 optional_input_absent tracking
log orders A-13 #8 optional_input_absent code
email to Mia: Order A-13 is complete.
log orders A-13 #9 hook_called notify: on workflow success
log orders A-13 #10 journey_succeeded FinishWorkflow from alreadyCompleted
the journey succeeded, with receipt none and tracking none
audit: none
```

## How it works

1. **`FinishWorkflow` ends the journey at once, as succeeded.** It is the second lifecycle, after `FailWorkflow` in [chapter 17](https://itinera-dev.org/book/kotlin/17-giving-up-a-step-early.md). Mia's lookup succeeded and contributed `completed`, so `alreadyCompleted` finished the journey. Her price, charge and shipping never ran: her log has no attempt of theirs, and the bank and the carriers were never asked, so Mia is charged only once.
2. **The journey says who finished it.** `journey_succeeded`, a `JourneySucceeded`, carries `decidedBy`, which is one of two things, so the log's `when` on it needs no `else`: a `DecidingHook`, naming the policy whose hook returned `FinishWorkflow`, or `DecidedBy.Default`, which names none. Mia's is a `DecidingHook`, and the log prints it: `FinishWorkflow from alreadyCompleted`. Ann's journey ended by default, after its last step, so hers is `DecidedBy.Default`.
3. **Only `on step success` may finish a journey, and its type says so.** What `finishWorkflow()` returns is an `OnSuccess`, which `on step success` returns, and never an `OnFailure`, which `on step retry` and `on step abnormal termination` return. So a step that hasn't succeeded can never finish its journey.
4. **What the step contributed is kept.** The hook runs after the lookup's contributions are committed, so `completed` is in Mia's data bag, as in Ann's.
5. **The workflow's own hooks still run.** A journey finished early has succeeded, so `Notify`'s `on workflow success` tells Mia. Her data bag holds no tracking number and no gift card's code, so she reads `Order A-13 is complete.` The receipt and the tracking of yesterday's journey belong to that journey, so `main` reads none of them in this one.
6. **The step reports what it found, and the policy decides what follows.** The lookup only says whether the order was completed. Ending the journey there is a decision about the flow, so it lives in a policy. The price, the charge and the shipping could each skip an order already completed, but each of them would then need to know about the order book, and a step added later would need to know too. **A decision about the whole journey belongs in a policy, not in every step it would stop.**

The shop no longer charges an order twice. But it still keeps the money of an order it charges and never ships, such as Ned's in [chapter 17](https://itinera-dev.org/book/kotlin/17-giving-up-a-step-early.md).

## Outcomes

We have shown how a step policy finishes a journey early, as succeeded, once nothing is left to do.

| The usual way                                                                                                             | With Itinera                                                                                                    |
| ------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| A process that stops early often does so through a `return` deep in the code, and nothing records which check stopped it. | `on step success` returns `FinishWorkflow`, and `journey_succeeded` names the policy that finished the journey. |
| Skipping work for a request already handled often means a check at the top of each function that does the work.           | One policy, attached to one lookup, ends the journey, and the steps it stops know nothing about it.             |
