Functional Weave
Code in TypeScript

inventory.valuation-fifo

FIFO stock valuation and cost of sales from a stock movement ledger, in exact money.

1.0.0 · published 2026-10-03 by charlie · Anterra

Pinned by 18 tests, run in TypeScript, Python and Rust.

What it does

First in, first out: each issue is costed from the oldest stock still on hand, so what remains is valued at the most recent purchase prices. This is the method IAS 2 and FRS 102 section 13 allow alongside weighted average cost (LIFO is not permitted under either).

The ledger is one item's movements in date order: receipts carry a unit cost, issues carry none and take their cost from the layers they consume. An issue that spans several receipts is costed from each in turn, oldest first, and a receipt that is partly used stays as a smaller layer. The result gives the closing quantity and value, the remaining layers, the cost of sales, and the cost of each issue in ledger order (to post each one to the ledger).

For example

  • fifoValuation(movements ×5, GBP) → closing quantity 70, closing value £385.00, cost of sales £965.00, issue costs £620.00, £345.00, layers ×1 an issue spans two receipts, a later one spans the rest of the second and a third
  • fifoValuation(movements ×3, GBP) → closing quantity 10, closing value £20.00, cost of sales £10.00, issue costs £10.00, layers ×1 an issue that exactly empties the oldest layer removes it
  • fifoValuation(movements ×3, GBP) → closing quantity 0, closing value £0.00, cost of sales £16.00, issue costs £16.00, layers issuing everything leaves no layers and nothing to value

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

export function fifoValuation(movements: readonly StockMovement[], currency: string): FifoValuation
movementsStockMovement[]the ledger for one item, in date order; same-day lines in the order they happened
currencystringthe valuation currency, so an empty ledger still has one
returnsFifoValuation

The types it declares, generated into your project

/** One line of the stock ledger. */
export interface StockMovement {
  readonly date: string;
  /** positive for a receipt, negative for an issue; never zero */
  readonly quantity: number;
  /** the cost of one unit on a receipt; null on an issue, which takes its cost from stock */
  readonly unitCost: Money | null;
}

/** Units still in stock from one receipt. */
export interface StockLayer {
  /** the date of the receipt */
  readonly date: string;
  readonly quantity: number;
  readonly unitCost: Money;
}

/** What is left, what it is worth, and what the issues cost. */
export interface FifoValuation {
  readonly closingQuantity: number;
  readonly closingValue: Money;
  /** the cost of every issue together */
  readonly costOfSales: Money;
  /** the cost of each issue, in ledger order */
  readonly issueCosts: readonly Money[];
  /** what is left, oldest first */
  readonly layers: readonly StockLayer[];
}

Your code names it in one line, in the file that uses it

import { fifoValuation } from "#fune/inventory.valuation-fifo@^1";
impl/typescript.ts · 72 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { epochDayFromIso } from "./dates_add_days.ts";  ← from dates.add-days ^1.0.0 · built alongside by fune
import { assertSameCurrency, money } from "./money_amount.ts";  ← from money.amount ^1.0.0 · built alongside by fune
import { type FifoValuation, type StockLayer, type StockMovement } from "./inventory_valuation_fifo_types.ts";

/**
 * Value stock first in, first out, and cost each issue from the oldest layers.
 *
 * Every cost is a whole quantity times a unit cost, so nothing is rounded and
 * closing value plus cost of sales always equals what was received.
 */
export function fifoValuation(movements: readonly StockMovement[], currency: string): FifoValuation {
  const zero = money(0, currency);
  const layers: { date: string; quantity: number; unitCost: StockLayer["unitCost"] }[] = [];
  const issueCosts = [];
  let costOfSales = 0;
  let previousDay: number | null = null;
  let previousDate = "";
  for (const line of movements) {
    const day = epochDayFromIso(line.date);
    if (previousDay !== null && day < previousDay) {
      throw new RangeError(`movements must be in date order: ${line.date} comes after ${previousDate}`);
    }
    previousDay = day;
    previousDate = line.date;
    if (!Number.isInteger(line.quantity) || line.quantity === 0) {
      throw new RangeError(`quantity must be a non-zero whole number, received ${line.quantity} on ${line.date}`);
    }
    if (line.quantity > 0) {
      if (line.unitCost === null || line.unitCost === undefined) {
        throw new RangeError(`a receipt needs a unitCost: ${line.quantity} on ${line.date}`);
      }
      assertSameCurrency(zero, line.unitCost);
      if (line.unitCost.minor < 0) {
        throw new RangeError(`unitCost must not be negative, received ${line.unitCost.minor} on ${line.date}`);
      }
      layers.push({ date: line.date, quantity: line.quantity, unitCost: line.unitCost });
      continue;
    }
    if (line.unitCost !== null && line.unitCost !== undefined) {
      throw new RangeError(`an issue takes its cost from stock, so its unitCost must be null: ${line.quantity} on ${line.date}`);
    }
    let wanted = -line.quantity;
    const onHand = layers.reduce((sum, layer) => sum + layer.quantity, 0);
    if (wanted > onHand) {
      throw new RangeError(`insufficient stock: an issue of ${wanted} on ${line.date} exceeds the ${onHand} on hand`);
    }
    let cost = 0;
    while (wanted > 0) {
      const oldest = layers[0];
      const used = Math.min(wanted, oldest.quantity);
      cost += used * oldest.unitCost.minor;
      oldest.quantity -= used;
      wanted -= used;
      if (oldest.quantity === 0) layers.shift();
    }
    issueCosts.push(money(cost, currency));
    costOfSales += cost;
  }
  let closingQuantity = 0;
  let closingValue = 0;
  for (const layer of layers) {
    closingQuantity += layer.quantity;
    closingValue += layer.quantity * layer.unitCost.minor;
  }
  return {
    closingQuantity,
    closingValue: money(closingValue, currency),
    costOfSales: money(costOfSales, currency),
    issueCosts,
    layers: layers.map((layer) => ({ date: layer.date, quantity: layer.quantity, unitCost: layer.unitCost })),
  };
}

Install

fune build

With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and its 2 dependencies, pins them in fune.lock, downloads only the TypeScript package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add inventory.valuation-fifo
Download for TypeScript inventory.valuation-fifo-1.0.0-typescript.fune · 16,290 bytes sha256 e61983ce908a318699597f04573f5f04614f2708f7cd907be4911a76f6544d62

The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./inventory.valuation-fifo-1.0.0-typescript.fune, or fetch it from a terminal with fune pull inventory.valuation-fifo@1.0.0:typescript.

The whole function, every language, is one file too: inventory.valuation-fifo-1.0.0.fune, 24,834 bytes, sha256 f514605cd88d7e8ffd9f8428614b212c31641f671a5e882c438070f9332702a0. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before inventory.valuation-fifo

after — your function gets the result and the arguments, and returns the final result.

// fune: after inventory.valuation-fifo

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

// fune: replace dates.add-days in inventory.valuation-fifo
// fune: replace money.amount in inventory.valuation-fifo

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show inventory.valuation-fifo --steps.

// fune: step inventory.valuation-fifo after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
an issue spans two receipts, a later one spans the rest of the second and a third movements ×5, GBP → closing quantity 70, closing value £385.00, cost of sales £965.00, issue costs £620.00, £345.00, layers ×1
an issue that exactly empties the oldest layer removes it movements ×3, GBP → closing quantity 10, closing value £20.00, cost of sales £10.00, issue costs £10.00, layers ×1
issuing everything leaves no layers and nothing to value movements ×3, GBP → closing quantity 0, closing value £0.00, cost of sales £16.00, issue costs £16.00, layers
receipts only: every layer is still there, oldest first movements ×2, GBP → closing quantity 5, closing value £49.99, cost of sales £0.00, issue costs , layers ×2
same-day lines are taken in ledger order: a receipt then an issue on one day movements ×4, GBP → closing quantity 2, closing value £6.00, cost of sales £16.00, issue costs £2.50, £13.50, layers ×1
a free receipt (a sample) is a layer at zero cost movements ×3, GBP → closing quantity 1, closing value £7.00, cost of sales £7.00, issue costs £7.00, layers ×1
restocking after running out starts a fresh layer movements ×4, GBP → closing quantity 3, closing value £3.90, cost of sales £7.60, issue costs £5.00, £2.60, layers ×1
an empty ledger is nothing, in the given currency , EUR → closing quantity 0, closing value €0.00, cost of sales €0.00, issue costs , layers
an issue larger than the stock on hand is an error movements ×2, GBP → error: insufficient stock: an issue of 11 on 2026-01-02 exceeds the 10 on hand
an issue before any receipt is an error movements ×1, GBP → error: insufficient stock
Show the other 8 tests
CaseArgumentsExpected
a ledger out of date order is an error movements ×2, GBP → error: movements must be in date order: 2026-01-04 comes after 2026-01-05
a receipt with no unit cost is an error movements ×1, GBP → error: a receipt needs a unitCost
an issue with a unit cost is an error movements ×2, GBP → error: its unitCost must be null
a zero quantity is an error movements ×1, GBP → error: quantity must be a non-zero whole number
a fractional quantity is an error movements ×1, GBP → error: quantity must be a non-zero whole number
a negative unit cost is an error movements ×1, GBP → error: unitCost must not be negative
a cost in another currency is an error movements ×1, GBP → error: currency mismatch
an impossible date is an error movements ×1, GBP → error: is not a real calendar date

More from the author

**Exact money.** Unit costs are `Money` in minor units and every cost is quantity times unit cost, so nothing is rounded and closing value plus cost of sales always equals the total of the receipts. A unit cost that has fractions of a penny cannot be expressed; use `inventory.valuation-weighted-average`, or cost in a smaller unit (per 100) and scale the quantities.

**Errors, not guesses.** An issue larger than the stock on hand is an error rather than negative stock: FIFO has no cost for units that were never received. So are a ledger out of date order, a zero quantity, a receipt with no unit cost or a negative one, an issue with a unit cost, and a cost in another currency. Returns to supplier and customer returns are not modelled: post a customer return as a receipt at the cost it was issued at.

Sources: IAS 2 *Inventories*, paragraphs 25-27 (IFRS Foundation); FRS 102 section 13 *Inventories*, paragraph 13.18 (Financial Reporting Council).

Files

PathBytes
README.md1,705
impl/python.py3,169
impl/rust.rs5,090
impl/typescript.ts3,072
vectors.json7,102