# Recognising a decision in the wrong place

## What you want to do

A rule put in the wrong place often still runs, and the shop's orders all go through. You want to recognise one when you read a step or a hook, before it hides a decision the shop can no longer see.

## The code

Here is a counter-example. This charge renews an expired card itself, tells the customer, and charges the new card:

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

```typescript
/**
 * Charges an order's amount to its card through the payment client, and gives
 * back its receipt, and the gift card's code when the order is a gift card.
 * It gives every reporter the receipt as soon as the bank gives it. When the
 * card has expired, it renews it, tells the customer, and charges the new
 * card.
 */
@step()
class Charge extends Step {
  constructor(
    @input("order", string) private readonly order: string,
    @input("customer", string) private readonly customer: string,
    @input("amount", integer) private readonly amount: number,
    @input("card", string) private readonly card: string,
    @input("giftCard", boolean) private readonly giftCard: boolean,
  ) {
    super();
  }

  override async run(
    @service("payments", PAYMENTS) payments: Payments,
    @service("cards", CARDS) cards: Cards,
    @contributor() contributor: Contributor,
    @stepReporter() reporter: StepReporter,
  ): Promise<Outcome> {
    if (this.amount <= 0) return this.fail("nothing-to-charge");
    let receipt = await payments.charge(this.order, this.card, this.amount);
    if (receipt === undefined) {
      const renewed = await cards.replacement(this.card);
      if (renewed !== undefined) {
        console.log(
          `email to ${this.customer}: card ${this.card} has expired, so we charged ${renewed}.`,
        );
        receipt = await payments.charge(this.order, renewed, this.amount);
        contributor.contribute("card", renewed);
      }
    }
    if (receipt === undefined) return this.fail("card-expired");
    await reporter.setGlobalMetadata("receipt", receipt);
    contributor.contribute("receipt", receipt);
    if (this.giftCard) contributor.contribute("code", `G-${this.order}`);
    return this.succeed();
  }
}
```

It asks for [chapter 35](https://itinera-dev.org/book/typescript/35-giving-the-rescue-step-a-service-of-its-own.md)'s `Payments` and `Cards`, with their tokens `PAYMENTS`, from [chapter 7](https://itinera-dev.org/book/typescript/07-giving-a-step-the-tools-it-needs.md), and `CARDS`.

Since the charge renews the card itself, the workflow gives it no rescue step, and the card registry's provider serves the charge itself rather than a rescue step:

TypeScript, from the program [`ch40_counter_example`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch40_counter_example.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,
 * which renews an expired card itself, auditing a charge 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", policies: [Audit, Outage] })
@withStep(Ship, { name: "ship", retryBudget: 1, policies: [FailedShipping] })
class Orders extends Workflow implements Messages, Refunds {
  constructor(private readonly channel: string) {
    super();
  }

  async tell(customer: string, message: string): Promise<void> {
    await network();
    console.log(`${this.channel} to ${customer}: ${message}`);
  }

  async refund(receipt: string, amount: number): Promise<void> {
    await network();
    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 bank's card registry in Europe, for the charge only. */
  @provider(CARDS, { key: "cards", steps: ["charge"] })
  cards(): Provided<Cards> {
    return this.provide(cardRegistry("eu"), "eu");
  }

  /** 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"]));
  }
}
```

Its methods are as [chapter 39](https://itinera-dev.org/book/typescript/39-deciding-where-a-decision-belongs.md) shows them, but for the card registry's provider, which now names `charge`. What it names is as earlier chapters show it: the token `CARRIER` in [chapter 7](https://itinera-dev.org/book/typescript/07-giving-a-step-the-tools-it-needs.md), the lookup, `AlreadyCompleted`, `OrderBook`, `ORDER_BOOK` and `Ledger` in [chapter 22](https://itinera-dev.org/book/typescript/22-finishing-a-journey-early.md), the pricing in [chapter 20](https://itinera-dev.org/book/typescript/20-an-optional-input.md), `Audit` and `Outage` in [chapter 34](https://itinera-dev.org/book/typescript/34-saying-which-attempt-took-the-money.md), the shipping, `Notify`, `FailedShipping`, `Carrier`, `Messages`, `Refunds` and `network` in [chapter 26](https://itinera-dev.org/book/typescript/26-running-async-journeys-while-others-wait.md), `cardRegistry` in [chapter 35](https://itinera-dev.org/book/typescript/35-giving-the-rescue-step-a-service-of-its-own.md), `Parcel` and `PARCEL` in [chapter 21](https://itinera-dev.org/book/typescript/21-deciding-where-a-steps-data-comes-from.md), the log in [chapter 33](https://itinera-dev.org/book/typescript/33-giving-every-reporter-what-it-needs.md), [chapter 35](https://itinera-dev.org/book/typescript/35-giving-the-rescue-step-a-service-of-its-own.md) and [chapter 36](https://itinera-dev.org/book/typescript/36-orders-refused-before-they-start.md), and the desk in [chapter 11](https://itinera-dev.org/book/typescript/11-naming-a-journey.md). The program runs Jo's order, whose card has expired, with `followUp` as [chapter 34](https://itinera-dev.org/book/typescript/34-saying-which-attempt-took-the-money.md) shows it, and prints:

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

```text
log orders A-8 for Jo #1 journey_started order, customer, price, parcel, card, giftCard
log orders A-8 for Jo #2 attempt_started lookup, attempt 1
log orders A-8 for Jo #3 service_provided lookup gets orderBook from ledger, a Ledger
the order book has no order A-8 yet
log orders A-8 for Jo #4 step_succeeded lookup
log orders A-8 for Jo #5 contribution_committed completed
log orders A-8 for Jo #6 hook_called alreadyCompleted: on step success of lookup
log orders A-8 for Jo #7 attempt_started price, attempt 1
log orders A-8 for Jo #8 optional_input_absent discount
log orders A-8 for Jo #9 step_succeeded price
log orders A-8 for Jo #10 contribution_committed amount
log orders A-8 for Jo #11 attempt_started charge, attempt 1
log orders A-8 for Jo #12 service_provided charge gets payments from bank, a Bank
log orders A-8 for Jo #13 service_provided charge gets cards from cards, a Cards, with eu
the bank declines card jo-2024: it has expired
the card registry in eu says card jo-2024 was replaced by jo-2029
email to Jo: card jo-2024 has expired, so we charged jo-2029.
the bank charges 30 for order A-8
log orders A-8 for Jo, receipt R-A-8 #14 global_metadata_set receipt
log orders A-8 for Jo, receipt R-A-8 #15 step_succeeded charge
log orders A-8 for Jo, receipt R-A-8 #16 contribution_committed card
log orders A-8 for Jo, receipt R-A-8 #17 data_overwritten card
log orders A-8 for Jo, receipt R-A-8 #18 contribution_committed receipt
log orders A-8 for Jo, receipt R-A-8 #19 hook_called audit: on step success of charge
log orders A-8 for Jo, receipt R-A-8 #20 contribution_committed audit
log orders A-8 for Jo, receipt R-A-8 #21 attempt_started ship, attempt 1
log orders A-8 for Jo, receipt R-A-8 #22 input_adapter_supplied ship gets weight from parcels
log orders A-8 for Jo, receipt R-A-8 #23 service_provided ship gets carrier from carriers, a MainCarrier
the main carrier books order A-8
log orders A-8 for Jo, receipt R-A-8 #24 step_info ship: the parcel leaves with receipt R-A-8
log orders A-8 for Jo, receipt R-A-8 #25 step_succeeded ship
log orders A-8 for Jo, receipt R-A-8 #26 contribution_committed tracking
log orders A-8 for Jo, receipt R-A-8 #27 optional_input_absent code
email to Jo: Order A-8 is on its way, tracking T-A-8.
log orders A-8 for Jo, receipt R-A-8 #28 hook_called notify: on workflow success
log orders A-8 for Jo, receipt R-A-8 #29 journey_succeeded
the journey succeeded, with receipt R-A-8 and tracking T-A-8
audit: A-8: charge took 30 on attempt 1, receipt R-A-8
```

## How it works

What the counter-example shows:

1. **It works, and its journey records none of it.** Jo's order is charged and shipped. But the log says the charge succeeded on its first attempt, events 11 and 15, and that the card was overwritten, event 17. Nothing says the card had expired, that the registry renewed it, or that Jo was told: the email came from inside the step, as a `console.log` the journey never sees.
2. **It holds three decisions where one belongs.** Charging is the step's. Renewing the card is a repair, which the rescue step made visible as `step_rescuing` and `step_rescued` in [chapter 14](https://itinera-dev.org/book/typescript/14-repairing-then-trying-once-more.md). Telling the customer is a reaction, which belongs to a policy, through a role, as [chapter 19](https://itinera-dev.org/book/typescript/19-letting-policies-act-on-the-outside-world.md) showed. **A step does one thing of the business, and says how it went.**
3. **Back in their places, the journey records them.** With the renewal in the rescue step `charge_rescue`, as [chapter 35](https://itinera-dev.org/book/typescript/35-giving-the-rescue-step-a-service-of-its-own.md) gave it its own card registry, the charge fails with the reason `card-expired` when the card has expired, the one failure the rescue step knows how to repair, and the journey records the repair as `step_rescuing` and `step_rescued`. With the message in a policy acting through a role, as `notify` does in [chapter 19](https://itinera-dev.org/book/typescript/19-letting-policies-act-on-the-outside-world.md), the journey records the hook it ran as `hook_called`.
4. **The places it doesn't belong are recognisable.** A step that tries its work again in a loop, calls a second service when the first fails, or tells anyone anything has taken a decision that isn't its own. A hook that works out a price, or judges whether a card is good enough, has taken one of the business's. **When a step or a hook takes a decision the journey doesn't record, such as a repair, a retry or a message, that decision is out of its place.**

Now you can tell a decision in its place from one out of it. But the shop's first checkout, [chapter 1](https://itinera-dev.org/book/typescript/01-but-why-itinera.md)'s, still runs beside the workflow, and moving a system like it is rarely done in one go.

## Outcomes

We have shown how to recognise a decision in the wrong place, and where to move it.

| The usual way                                                                   | With Itinera                                                                                  |
| ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| A rule put in the wrong place often goes unnoticed, since the code still works. | A rule in the wrong place is spotted from the journey, which records none of what it decided. |
