# The big picture

## What you want to do

You want to see [chapter 1](https://itinera-dev.org/book/typescript/01-but-why-itinera.md)'s checkout written with Itinera, all at once, before learning any of it. Don't try to understand every line. The comments say what each piece is for, and answer chapter 1's questions where the code answers them. The chapters after this one teach each piece, as you need it.

## The code

Start with the workflow. Its decorators tell you at once what happens to every order: which steps run, in what order, how many times, what repairs a failure and who reacts, without reading any of the code they name. Its methods supply what the steps and policies use: the bank, the warehouse and a carrier for every attempt, for the steps, and, for the notify policy, the way the shop tells a customer something.

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

```typescript
/**
 * The shop's workflow: reserve, charge and ship, auditing the charge,
 * rescuing it when the card has expired, and telling the customer how the
 * order went.
 */
@workflow({ name: "orders", policies: [Notify], reporters: [Log] })
// The steps run in this order, and nothing reorders them.
@withStep(Reserve, { name: "reserve" })
// The charge runs at most twice: once, and once more after its rescue step
// succeeds. Every successful charge is audited.
@withStep(Charge, { name: "charge", rescue: RenewCard, policies: [Audit] })
// Shipping may be tried once more after a failure, which, for a parcel the
// carrier refused, is worth trying again.
@withStep(Ship, { name: "ship", retryBudget: 1 })
class Orders extends Workflow implements Messages {
  /** One payment client for the journey, used by the charge and its rescue. */
  @provider(PAYMENTS, { key: "payments" })
  bank(): Provided<Payments> {
    return this.provide(BANK);
  }

  /** One stock store for the journey, shared by reserve and ship. */
  @provider(STOCK_STORE, { key: "stock" })
  warehouse(): Provided<StockStore> {
    return this.provide(WAREHOUSE);
  }

  /** A carrier for every attempt: the main carrier first, the backup after. */
  @provider(CARRIER, { perAttempt: true })
  carrier(@attempt() attempt: Attempt): Provided<Carrier> {
    return this.provide(attempt.isFirst() ? MAIN_CARRIER : BACKUP_CARRIER);
  }

  /** How the shop tells a customer something, for notify: by printing it. */
  tell(customer: string, message: string): void {
    console.log(`  to ${customer}: ${message}`);
  }
}
```

The steps reach the bank, the warehouse and the carriers through services: an interface saying what each one does, and a token that stands for the interface while the program runs, which a step names, with a key, to ask for it.

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

```typescript
/** Why the bank refused a charge. */
type Declined = "expired card" | "refused";

/**
 * A payment client: it charges a card, giving back the receipt or why the bank
 * refused, and knows the card that replaced an expired one.
 */
interface Payments {
  charge(card: string, amount: number): { receipt: string } | Declined;
  renewedCard(card: string): string;
}

/** A stock store: it reserves an order's goods, then hands them over. */
interface StockStore {
  reserve(order: string): boolean;
  handOver(order: string): void;
}

/**
 * A carrier: it takes a parcel and gives back its tracking number, or
 * `undefined` when it cannot take it.
 */
interface Carrier {
  send(order: string, weight: number): string | undefined;
}

const PAYMENTS = serviceType<Payments>("Payments");
const STOCK_STORE = serviceType<StockStore>("StockStore");
const CARRIER = serviceType<Carrier>("Carrier");
```

The business rules the workflow lists are steps, one for each: reserve the goods, charge the card, renew an expired card, ship the parcel. Each is a class whose constructor takes the data it needs, and whose `run` does the work and says how it went.

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

```typescript
/** Reserves the order's goods in the stock store. */
@step()
class Reserve extends Step {
  constructor(@input("order", string) private readonly order: string) {
    super();
  }

  override run(@service("stock", STOCK_STORE) stock: StockStore): Outcome {
    if (!stock.reserve(this.order)) return this.fail("out-of-stock");
    return this.succeed();
  }
}

/**
 * Charges the card the price, less any discount. It only says how it went:
 * what happens after a declined card is not its business.
 */
@step()
class Charge extends Step {
  constructor(
    @input("card", string) private readonly card: string,
    @input("price", integer) private readonly price: number,
    @input("discount", optional(integer))
    private readonly discount: Option<number>,
  ) {
    super();
  }

  override run(
    @service("payments", PAYMENTS) payments: Payments,
    @contributor() contributor: Contributor,
  ): Outcome {
    const amount = this.price - this.discount.unwrapOr(0);
    const charged = payments.charge(this.card, amount);
    if (charged === "expired card") return this.fail("expired-card");
    if (charged === "refused") return this.fail("declined");
    contributor.contribute("charged", amount);
    contributor.contribute("receipt", charged.receipt);
    return this.succeed();
  }
}

/**
 * The charge's rescue step: asks the customer's bank for the card that
 * replaced an expired one. A charge that failed for any other reason, or
 * ended in an abnormal termination, which has no reason, cannot be repaired
 * this way.
 */
@rescueStep()
class RenewCard extends RescueStep {
  constructor(
    @input("card", string) private readonly card: string,
    @failureReason({ optional: true }) private readonly reason: Option<Reason>,
  ) {
    super();
  }

  override run(
    @service("payments", PAYMENTS) payments: Payments,
    @contributor() contributor: Contributor,
  ): RescueOutcome {
    if (this.reason.mapOr("", (reason) => reason.code) !== "expired-card") {
      return this.fail("nothing-to-renew");
    }
    contributor.contribute("card", payments.renewedCard(this.card));
    return this.succeed();
  }
}

/**
 * Ships the order through the carrier it is given, without knowing which one
 * it is. A carrier that cannot take the parcel might be replaced on another
 * try, so that failure is worth trying again.
 */
@step()
class Ship extends Step {
  constructor(
    @input("order", string) private readonly order: string,
    @input("weight", integer) private readonly weight: number,
  ) {
    super();
  }

  override run(
    @service("carrier", CARRIER) carrier: Carrier,
    @service("stock", STOCK_STORE) stock: StockStore,
    @contributor() contributor: Contributor,
  ): Outcome {
    const tracking = carrier.send(this.order, this.weight);
    if (tracking === undefined) return this.fail("parcel-refused");
    stock.handOver(this.order);
    contributor.contribute("tracking", tracking);
    return this.succeed();
  }
}
```

The policies the workflow attaches react to how things went: audit a successful charge, tell the customer at the end.

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

```typescript
/**
 * Audits every successful charge, in the journey's events, including one
 * after a rescue.
 */
@stepPolicy({ name: "audit" })
class Audit extends StepPolicy {
  @onStepSuccess()
  async audited(
    @fromStep("charged", integer) charged: number,
    @fromStep("receipt", string) receipt: string,
    @hookReporter() reporter: HookReporter,
  ): Promise<OnSuccess> {
    await reporter.info(`charged ${String(charged)}, receipt ${receipt}`);
    return this.keepDefault();
  }
}

/** A role the shop provides: telling a customer something. */
interface Messages {
  tell(customer: string, message: string): void;
}

/** Tells the customer how the order went, once, when the journey ends. */
@workflowPolicy({ name: "notify" })
class Notify extends WorkflowPolicy<Messages> {
  @onWorkflowSuccess()
  shipped(
    @fromWorkflow("customer", string) customer: string,
    @fromWorkflow("order", string) order: string,
    @fromWorkflow("tracking", string) tracking: string,
    @role<Messages>() messages: Messages,
  ): void {
    messages.tell(customer, `order ${order} is on its way: ${tracking}`);
  }

  @onWorkflowFailure()
  failed(
    @fromWorkflow("customer", string) customer: string,
    @fromWorkflow("order", string) order: string,
    @role<Messages>() messages: Messages,
  ): void {
    messages.tell(customer, `order ${order} could not be completed`);
  }
}
```

The bank, the warehouse and the carriers are faked, as in chapter 1, so the program prints the same thing every time. Before it runs anything, it prints the workflow's listing:

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

```typescript
// The workflow lists its steps, their policies, services and rescue step,
// without running anything.
for (const listed of Orders.listing()) {
  console.log(entry(listed));
}
```

Then it runs seven orders, one journey after another, each an instance of the workflow that the executor runs, and prints how each journey ended. Ann, Ben, Cat and Dan come from chapter 1, with the same data. Three more customers take the paths none of them takes: Eve's goods are out of stock, Fin's card is valid but the order is above the bank's limit of 1,000, and Gil's parcel weighs 60 kg, too heavy for both carriers.

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

```typescript
// The order, the customer, the card, the price, the discount when there is
// one, and the parcel's weight in kg.
const orders = [
  {
    order: "A-1",
    customer: "Ann",
    card: "ann-card-2028",
    price: 40,
    discount: 5,
    weight: 2,
  },
  {
    order: "A-2",
    customer: "Ben",
    card: "ben-card-2024",
    price: 25,
    weight: 1,
  },
  {
    order: "A-3",
    customer: "Cat",
    card: "cat-card-2027",
    price: 30,
    weight: 30,
  },
  {
    order: "A-4",
    customer: "Dan",
    card: "dan-card-2025",
    price: 1200,
    weight: 3,
  },
  {
    order: "A-5",
    customer: "Eve",
    card: "eve-card-2027",
    price: 20,
    weight: 2,
  },
  {
    order: "A-6",
    customer: "Fin",
    card: "fin-card-2028",
    price: 1500,
    weight: 4,
  },
  {
    order: "A-7",
    customer: "Gil",
    card: "gil-card-2029",
    price: 45,
    weight: 60,
  },
];
const executor = new LocalExecutor();
const shop = Orders.build();
for (const order of orders) {
  console.log(`${order.order}:`);
  const result = await executor.run(shop.instance(order));
  if (result.isFailed()) {
    console.log(`failed: ${why(result.status.failure)}`);
  } else {
    console.log(result.status.kind);
  }
}
```

It prints the listing, then, under each order, what the shop's log and the customer were told, and how it ended:

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

```text
1. reserve; services: stock from warehouse
2. charge, with audit; services: payments from bank; rescued by charge_rescue, services: payments from bank
3. ship; services: carrier from carrier, stock from warehouse
A-1:
  INFO audit: charged 35, receipt R-ann-card-2028-35
  to Ann: order A-1 is on its way: T-A-1
succeeded
A-2:
  WARN charge, attempt 1: expired-card
  INFO charge to be rescued by charge_rescue
  INFO audit: charged 25, receipt R-ben-card-2029-25
  to Ben: order A-2 is on its way: T-A-2
succeeded
A-3:
  INFO audit: charged 30, receipt R-cat-card-2027-30
  WARN ship, attempt 1: parcel-refused
  INFO ship tried again
  to Cat: order A-3 is on its way: B-A-3
succeeded
A-4:
  WARN charge, attempt 1: expired-card
  INFO charge to be rescued by charge_rescue
  WARN charge, attempt 2: declined
  WARN charge given up: failure
  to Dan: order A-4 could not be completed
failed: failure, declined
A-5:
  WARN reserve, attempt 1: out-of-stock
  WARN reserve given up: failure
  to Eve: order A-5 could not be completed
failed: failure, out-of-stock
A-6:
  WARN charge, attempt 1: declined
  INFO charge to be rescued by charge_rescue
  WARN charge_rescue, attempt 1: nothing-to-renew
  WARN charge_rescue given up: failure
  to Fin: order A-6 could not be completed
failed: failure, nothing-to-renew
A-7:
  INFO audit: charged 45, receipt R-gil-card-2029-45
  WARN ship, attempt 1: parcel-refused
  INFO ship tried again
  WARN ship, attempt 2: parcel-refused
  WARN ship given up: retries exhausted
  to Gil: order A-7 could not be completed
failed: retries exhausted, parcel-refused
```

## How it works

Every order follows the path the diagram draws, and the output shows which.

```mermaid
flowchart TD
  accTitle: A journey through the shop
  accDescr: The journey reserves the goods, then charges the card. A successful charge is audited, then the order is shipped. A failed charge is rescued by charge_rescue; when the rescue succeeds the charge runs once more, and when the rescue or the second charge fails the journey fails. Shipping is tried with the main carrier; when it cannot take the parcel, shipping is tried once more with the backup carrier. When shipping succeeds, notify tells the customer and the journey succeeds. Any failure that is not repaired leads notify to tell the customer, and the journey fails.
  start([The journey starts with the order]) --> reserve[reserve]
  reserve -- success --> charge[charge]
  reserve -- failure --> told_failed[notify tells the customer the order could not be completed]
  charge -- success --> audit[audit logs the charge]
  charge -- failure --> rescue[charge_rescue renews an expired card]
  rescue -- success --> again[charge runs once more]
  rescue -- failure --> told_failed
  again -- success --> audit
  again -- failure --> told_failed
  audit --> ship[ship, attempt 1, main carrier]
  ship -- success --> told_shipped[notify tells the customer the order is on its way]
  ship -- failure, retry budget left --> ship2[ship, attempt 2, backup carrier]
  ship2 -- success --> told_shipped
  ship2 -- failure --> told_failed
  told_shipped --> succeeded([The journey succeeded])
  told_failed --> failed([The journey failed])
```

The diagram shows:

1. The journey starts with the order's data and runs `reserve`. If reserving fails, as Eve's does, the journey goes to its end as failed.
2. Then `charge` runs. When it succeeds, as Ann's does, the `audit` policy logs the charge.
3. When the charge fails, the rescue step, which the listing names `charge_rescue`, runs: for an expired card it asks the bank for the new card, and for any other reason it fails, as Fin's does, and the journey goes to its end as failed.
4. When the rescue succeeds, the charge runs once more. If it succeeds, as Ben's does, `audit` logs it; if it fails, as Dan's does, the journey goes to its end as failed.
5. After the audit, `ship` makes its first attempt, with the main carrier. If it succeeds, as Ann's does, the journey goes to its end as succeeded.
6. If the first attempt fails, `ship` has a retry left, so it makes a second attempt, with the backup carrier. If that succeeds, as Cat's does, the journey goes to its end as succeeded; if it fails, as Gil's does, the journey goes to its end as failed.
7. At a successful end, `notify` tells the customer the order is on its way, and the journey succeeded.
8. At a failed end, `notify` tells the customer the order could not be completed, and the journey failed.

## Outcomes

We have shown the whole checkout as one workflow, where every question of chapter 1 is answered in one place.

| The usual way                                                                                                                      | With Itinera                                                                             |
| ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| Retries, repairs and fallbacks usually live in the functions that meet the failure, so finding them means reading those functions. | Every retry budget, rescue step and policy is in the workflow's declaration.             |
| Which services a function uses is often known only from its body or its constructor.                                               | The listing shows every step's services and where each comes from, before anything runs. |
