# Letting policies act on the outside world

## What you want to do

The message for each customer is written, but nobody sends it. You want the notify policy to send it, while how it is sent, by email today and perhaps by text message tomorrow, stays the shop's business: the policy should only say "tell this customer this".

## The code

What the policy needs from the shop is an interface of its own, with one operation: tell a customer something.

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

```typescript
/** What the shop does for its policies: tell a customer something. */
interface Messages {
  tell(customer: string, message: string): void;
}
```

The notify policy now names it as the role it asks for, with `WorkflowPolicy<Messages>`. Its two hooks ask for it, as a parameter marked `@role<Messages>()`, from `itinera/policy`, and for the customer's name from the data bag, and tell the customer instead of contributing the message:

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

```typescript
/** Tells the customer how their order went, once its journey has ended. */
@workflowPolicy({ name: "notify" })
class Notify extends WorkflowPolicy<Messages> {
  @onWorkflowSuccess()
  succeeded(
    @fromWorkflow("customer", string) customer: string,
    @fromWorkflow("order", string) order: string,
    @fromWorkflow("tracking", optional(string)) tracking: Option<string>,
    @fromWorkflow("code", optional(string)) code: Option<string>,
    @role<Messages>() messages: Messages,
  ): void {
    let message = `Order ${order} is complete.`;
    if (tracking.isSome()) {
      message = `Order ${order} is on its way, tracking ${tracking.value}.`;
    } else if (code.isSome()) {
      message = `Order ${order} is paid: your gift card's code is ${code.value}.`;
    }
    messages.tell(customer, message);
  }

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

The workflow class implements the interface, with `implements Messages`, and sends through the channel it is configured with, a field its constructor sets. Here the channel is faked, and prints what it sends.

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

```typescript
/**
 * The shop's workflow: it charges, 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(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");
  }

  /** 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 steps, policies and reporters it names are as earlier chapters show them: the charge and the audit in [chapter 15](https://itinera-dev.org/book/typescript/15-reacting-to-what-a-step-did.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), the log in [chapter 18](https://itinera-dev.org/book/typescript/18-doing-something-when-the-journey-ends.md) and the desk in [chapter 11](https://itinera-dev.org/book/typescript/11-naming-a-journey.md). The 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` are [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.

The workflow object is made with the channel, `Orders.build("email")`. Each order's initial data now holds its customer's name, so each order is given whole to its instance, and the output no longer holds a message:

TypeScript, from the program [`ch19_letting_policies_act_on_the_outside_world`](https://github.com/itinera-dev/book/blob/main/typescript/examples/ch19_letting_policies_act_on_the_outside_world.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 parcel's weight in kg, the card, and
// whether the order is a gift card.
const orders = [
  {
    order: "A-1",
    customer: "Ann",
    price: 40,
    weight: 2,
    card: "ann-2028",
    giftCard: false,
  },
  {
    order: "A-7",
    customer: "Gil",
    price: 45,
    weight: 60,
    card: "gil-2027",
    giftCard: false,
  },
  {
    order: "A-8",
    customer: "Jo",
    price: 30,
    weight: 1,
    card: "jo-2024",
    giftCard: false,
  },
  {
    order: "A-9",
    customer: "Kim",
    price: 25,
    weight: 0,
    card: "kim-2027",
    giftCard: true,
  },
  {
    order: "A-10",
    customer: "Lee",
    price: 35,
    weight: 3,
    card: "lee-2019",
    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")}`);
}
```

The rest is [chapter 18](https://itinera-dev.org/book/typescript/18-doing-something-when-the-journey-ends.md)'s shop, and it runs the same five orders. It prints:

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

```text
Ann's order:
log orders A-1 #1 journey_started order, customer, price, weight, card, giftCard
log orders A-1 #2 attempt_started charge, attempt 1
log orders A-1 #3 service_provided charge gets payments from bank, a Bank
the bank charges 40 for order A-1
log orders A-1 #4 step_succeeded charge
log orders A-1 #5 contribution_committed receipt
log orders A-1 #6 hook_called audit: on step success of charge
log orders A-1 #7 contribution_committed audit
log orders A-1 #8 attempt_started ship, attempt 1
log orders A-1 #9 service_provided ship gets carrier from carriers, a MainCarrier
the main carrier books order A-1
log orders A-1 #10 step_info ship: the parcel leaves with receipt R-A-1
log orders A-1 #11 step_succeeded ship
log orders A-1 #12 contribution_committed tracking
log orders A-1 #13 optional_input_absent code
email to Ann: Order A-1 is on its way, tracking T-A-1.
log orders A-1 #14 hook_called notify: on workflow success
log orders A-1 #15 journey_succeeded
the journey succeeded, with receipt R-A-1 and tracking T-A-1
audit: charge took 40, receipt R-A-1
Gil's order:
log orders A-7 #1 journey_started order, customer, price, weight, card, giftCard
log orders A-7 #2 attempt_started charge, attempt 1
log orders A-7 #3 service_provided charge gets payments from bank, a Bank
the bank charges 45 for order A-7
log orders A-7 #4 step_succeeded charge
log orders A-7 #5 contribution_committed receipt
log orders A-7 #6 hook_called audit: on step success of charge
log orders A-7 #7 contribution_committed audit
log orders A-7 #8 attempt_started ship, attempt 1
log orders A-7 #9 service_provided ship gets carrier from carriers, a MainCarrier
the main carrier books order A-7
log orders A-7 #10 step_failed ship: too-heavy
log orders A-7 #11 hook_called heavyParcels: on step retry of ship
log orders A-7 #12 step_retrying ship
log orders A-7 #13 attempt_started ship, attempt 2
log orders A-7 #14 service_provided ship gets carrier from carriers, a BackupCarrier
the backup carrier books order A-7
log orders A-7 #15 step_info ship: the parcel leaves with receipt R-A-7
log orders A-7 #16 step_succeeded ship
log orders A-7 #17 contribution_committed tracking
log orders A-7 #18 optional_input_absent code
email to Gil: Order A-7 is on its way, tracking B-A-7.
log orders A-7 #19 hook_called notify: on workflow success
log orders A-7 #20 journey_succeeded
the journey succeeded, with receipt R-A-7 and tracking B-A-7
audit: charge took 45, receipt R-A-7
Jo's order:
log orders A-8 #1 journey_started order, customer, price, weight, card, giftCard
log orders A-8 #2 attempt_started charge, attempt 1
log orders A-8 #3 service_provided charge gets payments from bank, a Bank
the bank declines card jo-2024: it has expired
log orders A-8 #4 step_failed charge: card-expired
log orders A-8 #5 step_rescuing charge: failure, rescued by charge_rescue
log orders A-8 #6 attempt_started charge_rescue, attempt 1
the bank says card jo-2024 was replaced by jo-2029
log orders A-8 #7 step_succeeded charge_rescue
log orders A-8 #8 contribution_committed card
log orders A-8 #9 data_overwritten card
log orders A-8 #10 step_rescued charge by charge_rescue
log orders A-8 #11 attempt_started charge, attempt 2
the bank charges 30 for order A-8
log orders A-8 #12 step_succeeded charge
log orders A-8 #13 contribution_committed receipt
log orders A-8 #14 hook_called audit: on step success of charge
log orders A-8 #15 contribution_committed audit
log orders A-8 #16 attempt_started ship, attempt 1
log orders A-8 #17 service_provided ship gets carrier from carriers, a MainCarrier
the main carrier books order A-8
log orders A-8 #18 step_info ship: the parcel leaves with receipt R-A-8
log orders A-8 #19 step_succeeded ship
log orders A-8 #20 contribution_committed tracking
log orders A-8 #21 optional_input_absent code
email to Jo: Order A-8 is on its way, tracking T-A-8.
log orders A-8 #22 hook_called notify: on workflow success
log orders A-8 #23 journey_succeeded
the journey succeeded, with receipt R-A-8 and tracking T-A-8
audit: charge took 30, receipt R-A-8
Kim's order:
log orders A-9 #1 journey_started order, customer, price, weight, card, giftCard
log orders A-9 #2 attempt_started charge, attempt 1
log orders A-9 #3 service_provided charge gets payments from bank, a Bank
the bank charges 25 for order A-9
log orders A-9 #4 step_succeeded charge
log orders A-9 #5 contribution_committed receipt
log orders A-9 #6 contribution_committed code
log orders A-9 #7 hook_called audit: on step success of charge
log orders A-9 #8 contribution_committed audit
log orders A-9 #9 attempt_started ship, attempt 1
log orders A-9 #10 service_provided ship gets carrier from carriers, a MainCarrier
log orders A-9 #11 step_skipped ship: nothing-to-ship
log orders A-9 #12 contributions_discarded ship
log orders A-9 #13 optional_input_absent tracking
email to Kim: Order A-9 is paid: your gift card's code is G-A-9.
log orders A-9 #14 hook_called notify: on workflow success
log orders A-9 #15 journey_succeeded
the journey succeeded, with receipt R-A-9 and tracking none
audit: charge took 25, receipt R-A-9
Lee's order:
log orders A-10 #1 journey_started order, customer, price, weight, card, giftCard
log orders A-10 #2 attempt_started charge, attempt 1
log orders A-10 #3 service_provided charge gets payments from bank, a Bank
the bank declines card lee-2019: it has expired
log orders A-10 #4 step_failed charge: card-expired
log orders A-10 #5 step_rescuing charge: failure, rescued by charge_rescue
log orders A-10 #6 attempt_started charge_rescue, attempt 1
the bank says nothing replaced card lee-2019
log orders A-10 #7 step_failed charge_rescue: not-replaced
log orders A-10 #8 step_given_up charge_rescue: failure
email to Lee: Sorry, order A-10 could not be completed.
log orders A-10 #9 hook_called notify: on workflow failure
log orders A-10 #10 journey_failed charge_rescue
desk: order A-10 failed at charge_rescue
the journey failed, with receipt none and tracking none
audit: none
```

## How it works

1. **A role is what a workflow offers its policies.** It is a set of operations the workflow's own code carries out, such as "tell a customer". A policy that needs to act on the outside world asks for a role, never for the workflow itself. In TypeScript, a role is an interface the workflow class implements, and a hook's parameter marked `@role<Messages>()` is given the workflow object, seen only as a `Messages`.
2. **A policy says which roles it needs.** `WorkflowPolicy<Messages>` names them, so a hook of `Notify` can ask for `Messages`, and a workflow that lists `Notify` must implement `Messages`: TypeScript checks it where `@workflow(...)` lists the policy.
3. **A role carries operations, never data.** The customer's name and the order come to the hook as data from the workflow, from the data bag. The role only does something with them.
4. **A workflow's fields are its configuration.** `channel` is given to the workflow's constructor, through `Orders.build("email")`, and is never in the data bag, so no step or hook can read it as data. `Orders.build` takes what the constructor takes, so the shop can't make the workflow object without a channel.
5. **The policy knows only the role.** `Notify` tells a customer through whatever `Messages` it is given, so sending by text message would change the workflow's `tell`, and no policy. **A policy acts on the outside world only through the roles its workflow offers.**
6. **Only policies ask for roles.** Steps never do: a step does its business with its inputs and its services, and never reaches the workflow.
7. **A role's work is the workflow's business.** The executor doesn't record what a role does: the log shows `hook_called` once the hook has returned, after the email was sent, and nothing in between.

So every customer is told how their order went. The charge, though, still charges the full price of every order, while the shop gives some customers a discount that nothing in the shop applies.

## Outcomes

We have shown how a policy acts on the outside world through a role its workflow offers.

| The usual way                                                                                                         | With Itinera                                                                                           |
| --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| Code that sends a message usually holds the mail client itself, so changing how customers are told changes that code. | The policy asks for a role, and only the workflow, which implements it, knows how the message is sent. |
