# Bringing Itinera into existing code

## What you want to do

The shop's first checkout, [chapter 1](https://itinera-dev.org/book/java/01-but-why-itinera.md)'s, still takes some of its orders, and it works. You want to bring it into Itinera without stopping it or rewriting it: one piece at a time, keeping the bank's client, the audit trail and the log it already has, with the checkout behaving as before after each move.

## The code

The program is [chapter 1](https://itinera-dev.org/book/java/01-but-why-itinera.md)'s checkout. Its payment, which charged the card, renewed an expired one and audited the charge inside one method, `takePayment`, is the piece moved first, into a workflow of its own, `payment`. The bank's client stays as it was: the steps ask for an interface, and a small class, `BankPayments`, implements it by calling the client's own methods:

Java, from the program [`ch41_bringing_itinera_into_existing_code`](https://github.com/itinera-dev/book/blob/main/java/examples/ch41_bringing_itinera_into_existing_code.java)

```java
/** What the payment's steps ask of the bank. */
interface Payments {
  String charge(String card, long amount) throws Declined;

  String renewedCard(String card);
}

/** The bank's client, as it was, behind the steps' interface. */
final class BankPayments implements Payments {
  private final Bank bank;

  BankPayments(Bank bank) {
    this.bank = bank;
  }

  @Override
  public String charge(String card, long amount) throws Declined {
    return bank.charge(card, amount);
  }

  @Override
  public String renewedCard(String card) {
    return bank.renewedCard(card);
  }
}

```

The charge becomes a step, and the renewal its rescue step. The charge no longer renews anything: it catches the bank's `Declined` and says why it failed.

Java, from the program [`ch41_bringing_itinera_into_existing_code`](https://github.com/itinera-dev/book/blob/main/java/examples/ch41_bringing_itinera_into_existing_code.java)

```java
/** Charges the amount to the card, and gives back the receipt. */
@Step
final class Charge implements ItineraStep {
  private final String card;
  private final long amount;

  Charge(@Input String card, @Input long amount) {
    this.card = card;
    this.amount = amount;
  }

  public Outcome run(@Service Payments payments, Contributor contributor) {
    try {
      contributor.contribute("receipt", payments.charge(card, amount));
      return succeed();
    } catch (Declined declined) {
      return switch (declined.why) {
        case EXPIRED_CARD -> fail("card-expired");
        case REFUSED -> fail("declined");
      };
    }
  }
}

/** Repairs a charge whose card had expired: it asks the bank for the card that replaced it. */
@RescueStep
final class RenewCard implements ItineraRescueStep {
  private final String card;
  private final Reason reason;

  RenewCard(@Input String card, Reason reason) {
    this.card = card;
    this.reason = reason;
  }

  public RescueOutcome run(@Service Payments payments, Contributor contributor) {
    if (!reason.code().equals("card-expired")) return fail("not-repairable");
    contributor.contribute("card", payments.renewedCard(card));
    return succeed();
  }
}

```

The audit becomes a policy, `AuditCharge`, which writes to the audit trail with the method the checkout already used:

Java, from the program [`ch41_bringing_itinera_into_existing_code`](https://github.com/itinera-dev/book/blob/main/java/examples/ch41_bringing_itinera_into_existing_code.java)

```java
/** Writes every successful charge to the shop's audit trail. */
@StepPolicy(name = "audit")
final class AuditCharge implements ItineraStepPolicy {
  @OnStepSuccess
  public OnSuccess charged(@FromWorkflow long amount, @FromStep String receipt) {
    Audit.record("charged " + amount + ", receipt " + receipt);
    return keepDefault();
  }
}

```

The log line the payment wrote becomes a reporter, `PaymentLog`, which writes with the shop's existing `Log.info`:

Java, from the program [`ch41_bringing_itinera_into_existing_code`](https://github.com/itinera-dev/book/blob/main/java/examples/ch41_bringing_itinera_into_existing_code.java)

```java
/** Writes to the shop's log when a step fails, and when a rescue step repairs it. */
final class PaymentLog implements Reporter {
  @Override
  public void report(Event event) {
    if (event instanceof StepFailed failed) {
      Log.info(
          "payment "
              + failed.journeyId()
              + ": "
              + failed.step()
              + " failed, "
              + failed.reason().code());
    } else if (event instanceof StepRescued rescued) {
      Log.info(
          "payment "
              + rescued.journeyId()
              + ": "
              + rescued.step()
              + " repaired by "
              + rescued.rescue());
    }
  }
}

```

The workflow has one step, and its provider makes the bank's client as the checkout did:

Java, from the program [`ch41_bringing_itinera_into_existing_code`](https://github.com/itinera-dev/book/blob/main/java/examples/ch41_bringing_itinera_into_existing_code.java)

```java
/** Charges an order, renewing a card that has expired, and audits the charge. */
@Workflow(
    name = "payment",
    reporters = {PaymentLog.class})
@WithStep(
    step = Charge.class,
    name = "charge",
    rescue = RenewCard.class,
    policies = {AuditCharge.class})
final class Payment implements ItineraWorkflow {
  /** Names each journey after its order. */
  @IdGenerator
  public String orderNumber(DataBag data) {
    String order = data.read("order", TypeToken.of(String.class)).orNull();
    if (order == null) throw new IllegalStateException("a payment without an order");
    return order;
  }

  /** The bank, as it is configured today. */
  @Provider(key = "payments")
  public Provided<Payments> bank() {
    return provide(new BankPayments(new Bank(2026, 1000)));
  }
}

/** What a payment starts with. */
record Due(String order, String card, long amount) {}

/** What a payment gives back. */
record Paid(String receipt) {}

```

The rest of the checkout is chapter 1's, with three changes: `Shop` no longer holds the bank; a new checked exception, `PaymentNotRun`, says that the payment did not run, and `checkout` declares it; and the line that took the payment now calls `pay`:

Java, from the program [`ch41_bringing_itinera_into_existing_code`](https://github.com/itinera-dev/book/blob/main/java/examples/ch41_bringing_itinera_into_existing_code.java)

```java
/** An order, as the shop's website hands it over. */
record Order(
    String order, String customer, String card, long price, Optional<Long> discount, long weight) {}

/** The payment workflow could not say how the payment went. */
final class PaymentNotRun extends Exception {
  private static final long serialVersionUID = 1L;

  PaymentNotRun(String why) {
    super("the payment did not run: " + why);
  }
}

/** The shop, with everything it talks to. */
final class Shop {
  private final Warehouse warehouse;
  private final Carrier main;
  private final Carrier backup;
  private final Messages messages;

  Shop(Warehouse warehouse, Carrier main, Carrier backup, Messages messages) {
    this.warehouse = warehouse;
    this.main = main;
    this.backup = backup;
    this.messages = messages;
  }

  /** Reserves, charges and ships an order, and tells the customer how it went. */
  String checkout(Order order) throws Declined, PaymentNotRun {
    Log.info("checkout " + order.order());
    try {
      String tracking = reserveChargeAndShip(order);
      messages.tell(order.customer(), "order " + order.order() + " is on its way: " + tracking);
      return tracking;
    } catch (Exception error) {
      Log.warn("checkout " + order.order() + " failed: " + error.getMessage());
      messages.tell(order.customer(), "order " + order.order() + " could not be completed");
      throw error;
    }
  }

  private String reserveChargeAndShip(Order order) throws Declined, PaymentNotRun {
    warehouse.reserve(order.order());
    long amount = order.price() - order.discount().orElse(0L);
    pay(order.order(), order.card(), amount);
    return Shipping.ship(main, backup, order.order(), order.weight())
        .orElseThrow(() -> new IllegalStateException("no carrier could take it"));
  }

```

`pay` runs the workflow, and turns how the journey ended back into the bank's `Declined`, as chapter 1's `takePayment` let it out:

Java, from the program [`ch41_bringing_itinera_into_existing_code`](https://github.com/itinera-dev/book/blob/main/java/examples/ch41_bringing_itinera_into_existing_code.java)

```java
/** Charges an order's card through the payment workflow, and gives back the receipt. */
private String pay(String order, String card, long amount) throws Declined, PaymentNotRun {
  var instance = new Payment().instance().initialData(new Due(order, card, amount)).create();
  JourneyResult result;
  try {
    result = new LocalExecutor().run(instance);
  } catch (Refusal refusal) {
    throw new PaymentNotRun(refusal.getMessage());
  }
  JourneyStatus status = result.status();
  if (status instanceof JourneyStatus.Aborted aborted) {
    throw new PaymentNotRun(aborted.abort().reason().toString());
  }
  if (status instanceof JourneyStatus.Failed failed) {
    Reason reason = failed.failure().reason();
    if (reason != null && reason.code().equals("card-expired")) {
      throw new Declined(Why.EXPIRED_CARD);
    }
    throw new Declined(Why.REFUSED);
  }
  return result.output(TypeToken.of(Paid.class)).receipt();
}

```

`main` is chapter 1's, with the same four orders, and it prints:

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

```text
INFO checkout A-1
AUDIT charged 35, receipt R-ann-card-2028-35
to Ann: order A-1 is on its way: T-A-1
A-1: shipped, T-A-1

INFO checkout A-2
INFO payment A-2: charge failed, card-expired
INFO payment A-2: charge repaired by charge_rescue
AUDIT charged 25, receipt R-ben-card-2029-25
to Ben: order A-2 is on its way: T-A-2
A-2: shipped, T-A-2

INFO checkout A-3
AUDIT charged 30, receipt R-cat-card-2027-30
WARN Rapid cannot take A-3: 30 kg is over its 20 kg limit; trying Steady
to Cat: order A-3 is on its way: B-A-3
A-3: shipped, B-A-3

INFO checkout A-4
INFO payment A-4: charge failed, card-expired
INFO payment A-4: charge repaired by charge_rescue
INFO payment A-4: charge failed, declined
WARN checkout A-4 failed: payment declined
to Dan: order A-4 could not be completed
A-4: failed, payment declined
```

## How it works

1. **The rest of the program doesn't know.** `checkout` still returns the same tracking number and lets out the same exceptions, the shipping and the messages are untouched, and each order ends as it did in chapter 1. `pay` is the only seam: it creates an instance, runs its journey and reads how it ended.
2. **Existing code is kept, behind the workflow's parts.** The bank's client is a service through the interface `BankPayments` implements, the audit trail is called from a policy, and the log from a reporter. What moves into the workflow is the decisions: when to renew a card, and when to audit. The code that talks to the outside world stays where it was.
3. **The log now says what happened.** Chapter 1's payment logged that it was renewing a card, before it tried. Now the log follows the journey's events: Ben's charge failed with `card-expired` and the rescue step repaired it, and the audit trail shows the charge then went through. Dan's was repaired too, then failed again, `declined`, which chapter 1's log never said.
4. **One piece at a time.** The shipping, with its backup carrier, and the messages to the customer are still chapter 1's code, running beside the workflow. Each can move next: the shipping as a step with a retry budget and a provider for each attempt, the messages as a policy acting through a role. Move one piece, run the program, and compare what it prints with what it printed before.
5. **Where Itinera fits, and where it doesn't.** It fits a piece of business with decisions around it: whether to try again, how to repair, what to record and whom to tell. A single call with nothing to decide around it, such as reserving the goods here, gains nothing from a workflow of its own. It stays a call, or becomes a step of a workflow that has decisions to make.

The checkout's payment is now a workflow, and the shop has one way to charge a card. It also wants a second way to sell: customers collecting their orders at the shop's counter, paying at the counter's terminal, with nothing to ship.

## Outcomes

We have shown how to bring Itinera into code that already works, one piece at a time, keeping the code that talks to the outside world.

| The usual way                                                                              | With Itinera                                                                |
| ------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------- |
| Untangling a method often means rewriting it, and its callers, in one go.                  | One piece becomes a workflow behind a method the callers already call.      |
| A client, a log or an audit trail written for the old code is often rewritten for the new. | Each stays, called from a service's implementation, a policy or a reporter. |
