# 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, with a token of its own:

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

```typescript
/** The shop's order book: it says whether an order was already completed. */
interface OrderBook {
  completed(order: string): boolean;
}

const ORDER_BOOK = serviceType<OrderBook>("OrderBook");
```

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:

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

```typescript
/**
 * Looks the order up in the order book, and gives back whether it was already
 * completed.
 */
@step()
class Lookup extends Step {
  constructor(@input("order", string) private readonly order: string) {
    super();
  }

  override run(
    @service("orderBook", ORDER_BOOK) orderBook: OrderBook,
    @contributor() contributor: Contributor,
  ): Outcome {
    contributor.contribute("completed", orderBook.completed(this.order));
    return this.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/typescript/15-reacting-to-what-a-step-did.md). For an order already completed, it returns `this.finishWorkflow()`, which is the lifecycle `FinishWorkflow`. Otherwise it keeps the default:

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

```typescript
/**
 * Finishes the journey of an order that was already completed: there is
 * nothing left to do for it.
 */
@stepPolicy({ name: "alreadyCompleted" })
class AlreadyCompleted extends StepPolicy {
  @onStepSuccess()
  lookedUp(@fromStep("completed", boolean) completed: boolean): OnSuccess {
    if (completed) return this.finishWorkflow();
    return this.keepDefault();
  }
}
```

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

TypeScript, from the program [`ch22_finishing_a_journey_early`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch22_finishing_a_journey_early.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. 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: [HeavyParcels] })
class Orders extends Workflow implements Messages {
  constructor(private readonly channel: string) {
    super();
  }

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

  /** 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 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, `Outage` and `HeavyParcels` 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 bank's and the carriers' providers are [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` [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, and the adapter with `Parcel` and `PARCEL` [chapter 21](https://itinera-dev.org/book/typescript/21-deciding-where-a-steps-data-comes-from.md)'s.

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

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

```typescript
case "journey_succeeded":
  if (event.decidedBy === "default") return undefined;
  return `FinishWorkflow from ${event.decidedBy.policy}`;
```

The rest is [chapter 21](https://itinera-dev.org/book/typescript/21-deciding-where-a-steps-data-comes-from.md)'s shop. The program runs two orders, Ann's and Mia's:

TypeScript, from the program [`ch22_finishing_a_journey_early`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch22_finishing_a_journey_early.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),
};

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-1",
    customer: "Ann",
    price: 40,
    discount: 10,
    parcel: { weight: 2, size: [30, 20, 10] },
    card: "ann-2028",
    giftCard: false,
  },
  {
    order: "A-13",
    customer: "Mia",
    price: 50,
    parcel: { weight: 4, size: [40, 30, 30] },
    card: "mia-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")}`);
}
```

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/typescript/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 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 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 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 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/typescript/17-giving-up-a-step-early.md). Mia's lookup succeeded and contributed `completed`, so `alreadyCompleted` finished the journey. Her pricing, 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` names the policy and the hook whose return was `FinishWorkflow`, as `event.decidedBy`, and the log prints it: `FinishWorkflow from alreadyCompleted`. Ann's `journey_succeeded` was decided by `"default"`, because her journey ended after its last step, so the log prints nothing more.
3. **Only `on step success` may finish a journey, and its type says so.** `this.finishWorkflow()` returns a `FinishWorkflow`, which is one of the lifecycles an `OnSuccess` may hold, and never one an `OnFailure` may hold. A method marked `@onStepRetry()` or `@onStepAbnormalTermination()` must return an `OnFailure`, as [chapter 17](https://itinera-dev.org/book/typescript/17-giving-up-a-step-early.md) showed, 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 the program 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 pricing, 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/typescript/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.             |
