---
title: "16.5 Day-to-day: an end-of-day stock count"
url: https://una-lang.org/en/learn/memory/day-to-day-an-end-of-day-stock-count/
release: v0.4.0
edition: "0.2"
---

# 16.5 Day-to-day: an end-of-day stock count

## 16.5.1 What the program must do

Now the program from the start of the chapter. Two sites close their day. Each has the counts it opened with and the movements its tills recorded: sales, which lower a count, and deliveries, which raise it. A movement for a SKU the site does not stock, or a sale of more units than are counted, is rejected and reported, and must leave the count as it was. The sites are independent, so they are closed at the same time.

The design follows from that. One `Ledger` per site holds the running counts, and one function applies a movement to it through an `edit` parameter. When the day is done, the ledger is closed into a `Report` with `take`, and `together for` of [section 15.2](https://una-lang.org/en/learn/concurrency/building-a-list-at-the-same-time-together-for/#s15-2) closes every site at once.

## 16.5.2 The kinds

```una include="day-to-day/src/stockcount.una#L1-L27" title="day-to-day/src/stockcount.una" caption="the kinds"
module stockcount

--- One movement of stock at a site: a SKU and a change in units, negative for a sale.
pub kind Movement
  sku: Text
  change: Int

--- Why a movement could not be applied to a ledger.
pub kind CountError = UnknownSku(sku: Text) | Oversold(sku: Text, wanted: Int, left: Int)

--- The running count of one site: the units of each SKU, and how many movements it took.
pub kind Ledger
  site: Text
  counts: Map[Text, Int]
  applied: Int

--- One site's day: its opening counts and the movements its tills recorded.
pub kind Day
  site: Text
  opening: Map[Text, Int]
  movements: List[Movement]

--- What a closed day reports: a summary, one line per movement, and the closing counts.
pub kind Report
  summary: Text
  lines: List[Text]
  closing: Map[Text, Int]
```

A `Movement` holds a signed change, so a sale and a delivery are one kind. `CountError` carries what a person needs to correct the count: the SKU, and for an oversold item the units sold and counted. `Report` keeps the closing counts as a map, which [section 10.4](https://una-lang.org/en/learn/collections/maps/#s10-4) introduced.

## 16.5.3 Applying one movement

`apply` takes the ledger with `edit` and fails with `CountError`. Its `ensures` promises one more applied movement, which holds only when it returns: a rejected movement is a failure, and then the ledger is left as it was.

```una include="day-to-day/src/stockcount.una#apply" title="day-to-day/src/stockcount.una"
--- Applies one movement to the ledger. On failure the ledger is left as it was.
pub apply(edit ledger: Ledger, movement: Movement) -> Text
  ensures ledger.applied == old(ledger).applied + 1
  fails CountError
=
  let left = ledger.counts.get(key: movement.sku)
    if none fail UnknownSku(sku: movement.sku)
  let next = left + movement.change
  if next < 0
    fail Oversold(sku: movement.sku, wanted: -movement.change, left: left)
  ledger.counts = ledger.counts.with(key: movement.sku, value: next)
  ledger.applied = ledger.applied + 1
  "{movement.sku} {left} -> {next}"
```

The function changes two fields, `counts` and `applied`, and returns a line for the report, such as `LAMP-01 4 -> 3`. The checks come first, so a movement that fails changes nothing, but the guarantee does not depend on that order: a failure after the assignments would discard them too.

## 16.5.4 Replaying a day

`close_day` keeps the ledger and the report's lines in two `let edit` bindings, and replays the movements in order. A rejected movement becomes a line of its own: `if error use` gives the statement's value when the call fails, and `error` is the `CountError` that `reason` turns into words.

```una include="day-to-day/src/stockcount.una#reason..close_day" title="day-to-day/src/stockcount.una"
--- What a person reads for a movement that was not applied.
pub reason(failure: CountError) -> Text
=
  when failure
    is UnknownSku(sku) -> "no product has the SKU {sku}"
    is Oversold(sku, wanted, left) -> "{wanted} of {sku} sold, {left} counted"

--- Closes the ledger: the report keeps its counts, and nothing can update the ledger after.
pub close(take ledger: Ledger, lines: List[Text]) -> Report
=
  let rejected = lines.len - ledger.applied
  let summary = "{ledger.site}: {ledger.applied} applied, {rejected} rejected"
  Report(summary: summary, lines: lines, closing: ledger.counts)

--- Replays one site's day, movement by movement.
pub close_day(day: Day) -> Report
=
  let edit ledger = Ledger(site: day.site, counts: day.opening, applied: 0)
  let edit lines: List[Text] = []
  for movement in day.movements
    let line = apply(edit ledger, movement: movement)
      if error use "rejected: {reason(error)}"
    lines = lines.append(item: line)
  close(take ledger, lines: lines)
```

`close` takes the ledger. After `close(take ledger, lines: lines)`, no later line of `close_day` can apply another movement to a closed day: the checker would report U2017 ([Using a value after `take`](https://una-lang.org/en/learn/memory/common-mistakes/#using-a-value-after-take-u2017) shows it). The number of rejected movements is the number of lines minus the applied ones, since every movement gives one line.

## 16.5.5 Why an `edit` parameter, not a new ledger

Why an `edit` parameter, and not a function that returns a new ledger? Both would work. A function `apply(ledger: Ledger, movement: Movement) -> Ledger` would need a second result for the report's line, and every call would have to rebind the ledger by hand: `ledger = apply(ledger, …)`. Forgetting the rebinding would silently drop the movement. With `edit`, the call cannot forget, the line is the result, and the `ensures` clause can compare the ledger before and after with `old`.

`close_day` itself takes a plain `Day`. It builds its own ledger from the day's opening counts, so a caller's `Day` is never changed, and two calls with the same day give the same report. That is what lets `close_all` run the days as separate tasks.

## 16.5.6 Closing every site at once

One task per day, with `together for` as [section 15.2](https://una-lang.org/en/learn/concurrency/building-a-list-at-the-same-time-together-for/#s15-2) taught it. Each task builds its own ledger inside `close_day`, so the tasks share nothing that changes, and the reports come back in the order of `days`. This is where the rules of this chapter meet those of chapter 15: a task cannot assign a binding outside it, so a ledger that each task changes must be made inside the task.

```una include="day-to-day/src/stockcount.una#close_all" title="day-to-day/src/stockcount.una"
--- Closes every site's day at once, one task per site. The reports come back in site order.
pub close_all(days: List[Day]) -> List[Report]
=
  together for day in days
    close_day(day)
```

## 16.5.7 The sample days

`sale` and `delivery` make movements with readable names. `north_day` and `south_day` hold the sample data, and `main` prints each report.

```una include="day-to-day/src/stockcount.una#sale..main" title="day-to-day/src/stockcount.una"
--- A sale of `units` units: a negative movement.
pub sale(sku: Text, units: Int) -> Movement = Movement(sku: sku, change: -units)

--- A delivery of `units` units: a positive movement.
pub delivery(sku: Text, units: Int) -> Movement = Movement(sku: sku, change: units)

--- The north site's day, as its tills recorded it.
north_day() -> Day
=
  let opening = empty_map().with(key: "LAMP-01", value: 4).with(key: "DESK-02", value: 1)
  let movements = [sale("LAMP-01", units: 1), sale("DESK-02", units: 2), delivery("LAMP-01", units: 6)]
  Day(site: "north", opening: opening, movements: movements)

--- The south site's day.
south_day() -> Day
=
  let opening = empty_map().with(key: "LAMP-01", value: 2)
  let movements = [sale("CHAIR-09", units: 1), sale("LAMP-01", units: 2)]
  Day(site: "south", opening: opening, movements: movements)

pub main() -> Unit
  uses @console: Console[print]
=
  let reports = close_all([north_day(), south_day()])
  for report in reports
    @console.print(report.summary)
    for line in report.lines
      @console.print("  {line}")
    @console.print("  closing {report.closing}")
```

## 16.5.8 Running it

`una run .` prints the report shown in [What you'll build](https://una-lang.org/en/learn/memory/#what-youll-build). The north site rejects a sale of two desks with one counted, and the south site rejects a SKU it does not stock. Each closing map is the count after the movements that were applied, in SKU order, since a map keeps its keys in order.

Built with `una build`, the same program closes the two sites on two threads. The report is the same, line for line, because `main` prints only after `close_all` has returned every report, in site order.

## 16.5.9 The whole program

The whole file, to read in one piece or to copy:

```una include="day-to-day/src/stockcount.una" title="day-to-day/src/stockcount.una" caption="the whole program" verified="check, run, test"
module stockcount

--- One movement of stock at a site: a SKU and a change in units, negative for a sale.
pub kind Movement
  sku: Text
  change: Int

--- Why a movement could not be applied to a ledger.
pub kind CountError = UnknownSku(sku: Text) | Oversold(sku: Text, wanted: Int, left: Int)

--- The running count of one site: the units of each SKU, and how many movements it took.
pub kind Ledger
  site: Text
  counts: Map[Text, Int]
  applied: Int

--- One site's day: its opening counts and the movements its tills recorded.
pub kind Day
  site: Text
  opening: Map[Text, Int]
  movements: List[Movement]

--- What a closed day reports: a summary, one line per movement, and the closing counts.
pub kind Report
  summary: Text
  lines: List[Text]
  closing: Map[Text, Int]

--- Applies one movement to the ledger. On failure the ledger is left as it was.
pub apply(edit ledger: Ledger, movement: Movement) -> Text
  ensures ledger.applied == old(ledger).applied + 1
  fails CountError
=
  let left = ledger.counts.get(key: movement.sku)
    if none fail UnknownSku(sku: movement.sku)
  let next = left + movement.change
  if next < 0
    fail Oversold(sku: movement.sku, wanted: -movement.change, left: left)
  ledger.counts = ledger.counts.with(key: movement.sku, value: next)
  ledger.applied = ledger.applied + 1
  "{movement.sku} {left} -> {next}"

--- What a person reads for a movement that was not applied.
pub reason(failure: CountError) -> Text
=
  when failure
    is UnknownSku(sku) -> "no product has the SKU {sku}"
    is Oversold(sku, wanted, left) -> "{wanted} of {sku} sold, {left} counted"

--- Closes the ledger: the report keeps its counts, and nothing can update the ledger after.
pub close(take ledger: Ledger, lines: List[Text]) -> Report
=
  let rejected = lines.len - ledger.applied
  let summary = "{ledger.site}: {ledger.applied} applied, {rejected} rejected"
  Report(summary: summary, lines: lines, closing: ledger.counts)

--- Replays one site's day, movement by movement.
pub close_day(day: Day) -> Report
=
  let edit ledger = Ledger(site: day.site, counts: day.opening, applied: 0)
  let edit lines: List[Text] = []
  for movement in day.movements
    let line = apply(edit ledger, movement: movement)
      if error use "rejected: {reason(error)}"
    lines = lines.append(item: line)
  close(take ledger, lines: lines)

--- Closes every site's day at once, one task per site. The reports come back in site order.
pub close_all(days: List[Day]) -> List[Report]
=
  together for day in days
    close_day(day)

--- A sale of `units` units: a negative movement.
pub sale(sku: Text, units: Int) -> Movement = Movement(sku: sku, change: -units)

--- A delivery of `units` units: a positive movement.
pub delivery(sku: Text, units: Int) -> Movement = Movement(sku: sku, change: units)

--- The north site's day, as its tills recorded it.
north_day() -> Day
=
  let opening = empty_map().with(key: "LAMP-01", value: 4).with(key: "DESK-02", value: 1)
  let movements = [sale("LAMP-01", units: 1), sale("DESK-02", units: 2), delivery("LAMP-01", units: 6)]
  Day(site: "north", opening: opening, movements: movements)

--- The south site's day.
south_day() -> Day
=
  let opening = empty_map().with(key: "LAMP-01", value: 2)
  let movements = [sale("CHAIR-09", units: 1), sale("LAMP-01", units: 2)]
  Day(site: "south", opening: opening, movements: movements)

pub main() -> Unit
  uses @console: Console[print]
=
  let reports = close_all([north_day(), south_day()])
  for report in reports
    @console.print(report.summary)
    for line in report.lines
      @console.print("  {line}")
    @console.print("  closing {report.closing}")

--- A north ledger that counts `units` of LAMP-01 and nothing else, for the examples.
lamps(units: Int) -> Ledger = Ledger(site: "north", counts: empty_map().with(key: "LAMP-01", value: units), applied: 0)

--- `apply` through a copy, since a `do` line cannot pass `edit`.
applied(ledger: Ledger, movement: Movement) -> Ledger
  fails CountError
=
  let edit copy = ledger
  let receipt = apply(edit copy, movement: movement)
    if error pass
  copy

example "a sale lowers the count of its SKU"
  do applied(lamps(4), movement: sale("LAMP-01", units: 1))
  expect result.counts.get(key: "LAMP-01") == Some(3)
  expect result.applied == 1

example "selling more than is counted is Oversold"
  do applied(lamps(4), movement: sale("LAMP-01", units: 9))
  expect fails Oversold

example "a rejected movement leaves the counts as they were"
  do close_day(Day(site: "south", opening: empty_map().with(key: "LAMP-01", value: 2), movements: [sale("LAMP-01", units: 5)]))
  expect result.closing == empty_map().with(key: "LAMP-01", value: 2)
  expect result.summary == "south: 0 applied, 1 rejected"

example "closing every day at once gives the reports in site order"
  do close_all([north_day(), south_day()])
  expect result == [close_day(north_day()), close_day(south_day())]
```
