Functional Weave
Code in Python

logistics.demurrage

Demurrage or detention charge for a container: free days, then a tiered daily rate from the carrier's tariff.

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

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

What it does

What a shipping line charges for keeping its container too long. The same arithmetic serves both charges, called with different dates:

| charge | startDate | endDate | |---|---|---| | demurrage (container full, in the terminal) | discharge from the vessel | gate-out full | | detention (container outside the terminal) | gate-out full | returned empty | | combined "D&D" tariffs | discharge | returned empty |

For example

  • demurrage(2026-03-01, 2026-03-04, 4, tiers ×3) → total days 4, free days used 4, chargeable days 0, free time ends 2026-03-04, lines , total $0.00 collected on the last free day: nothing to pay
  • demurrage(2026-03-01, 2026-03-05, 4, tiers ×3) → total days 5, free days used 4, chargeable days 1, free time ends 2026-03-04, lines ×1, total $75.00 one day over free time
  • demurrage(2026-03-01, 2026-03-20, 4, tiers ×3) → total days 20, free days used 4, chargeable days 16, free time ends 2026-03-04, lines ×3, total $3,075.00 twenty days runs through all three tiers

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.

def demurrage(start_date: str, end_date: str, free_days: int, tiers: Sequence[DemurrageTier]) -> DemurrageCharge
start_datedateday 1 of the count: discharge (demurrage) or gate-out (detention), or the day after if the tariff says so
end_datedatethe last day that counts: gate-out (demurrage) or empty return (detention), inclusive
free_daysintcalendar days free of charge from startDate, 0 or more
tiersDemurrageTier[]the tariff's daily rates by day number, in any order; they must not overlap
returnsDemurrageCharge

The types it declares, generated into your project

@dataclass(frozen=True)
class DemurrageTier:
    """One band of the tariff, by day number counted from startDate as day 1, as tariffs print them."""

    #: first day the rate applies to, 1 or more
    from_day: int
    #: last day, inclusive; null for every day after fromDay
    to_day: Optional[int]
    #: per container per day
    daily_rate: Money

@dataclass(frozen=True)
class DemurrageLine:
    """The days one tier charged."""

    from_day: int
    to_day: int
    days: int
    daily_rate: Money
    amount: Money

@dataclass(frozen=True)
class DemurrageCharge:
    """What is owed, and how the free time and each tier contributed."""

    #: startDate to endDate, both counted
    total_days: int
    #: the free days that fell inside the period
    free_days_used: int
    chargeable_days: int
    #: last free day, even if the container went back earlier; null with no free days
    free_time_ends: Optional[str]
    #: one per tier that charged anything, in day order
    lines: List[DemurrageLine]
    total: Money

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

from fune.logistics.demurrage import demurrage  # logistics.demurrage@^1
impl/python.py · 82 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.

from typing import List, Optional, Sequence

from .dates_add_days import add_days  ← from dates.add-days ^1.0.0 · built alongside by fune
from .dates_days_between import days_between  ← from dates.days-between ^1.0.0 · built alongside by fune
from .money_amount import assert_same_currency, money  ← from money.amount ^1.0.0 · built alongside by fune
from .money_sum import sum_money  ← from money.sum ^1.0.0 · built alongside by fune
from .logistics_demurrage_types import DemurrageTier, DemurrageLine, DemurrageCharge


def _whole(value: object) -> bool:
    return isinstance(value, int) and not isinstance(value, bool)


def demurrage(
    start_date: str,
    end_date: str,
    free_days: int,
    tiers: Sequence[DemurrageTier],
) -> DemurrageCharge:
    """Demurrage or detention for one container: calendar days from start_date
    to end_date inclusive, the first free_days free, every later day at the
    rate of the tier whose day numbers contain it."""
    if not _whole(free_days):
        raise TypeError("freeDays must be an integer, received %r" % (free_days,))
    if free_days < 0:
        raise ValueError("freeDays must not be negative, received %d" % free_days)
    total_days = days_between(start_date, end_date) + 1
    if total_days < 1:
        raise ValueError("endDate must not be before startDate: %s to %s" % (start_date, end_date))

    if len(tiers) == 0:
        raise ValueError("tiers must not be empty")
    for tier in tiers:
        if not _whole(tier.from_day) or tier.from_day < 1:
            raise ValueError("tier fromDay must be 1 or more, received %r" % (tier.from_day,))
        if tier.to_day is not None and (not _whole(tier.to_day) or tier.to_day < tier.from_day):
            raise ValueError(
                "tier toDay must not be before fromDay, received %r to %r" % (tier.from_day, tier.to_day)
            )
        if tier.daily_rate.minor < 0:
            raise ValueError("dailyRate must not be negative, received %d" % tier.daily_rate.minor)
        assert_same_currency(tiers[0].daily_rate, tier.daily_rate)
    ordered = sorted(tiers, key=lambda t: t.from_day)
    for i in range(1, len(ordered)):
        previous = ordered[i - 1]
        if previous.to_day is None or previous.to_day >= ordered[i].from_day:
            raise ValueError("tiers overlap at day %d" % ordered[i].from_day)

    lines: List[DemurrageLine] = []
    day = free_days + 1
    for tier in ordered:
        if day > total_days:
            break
        if tier.to_day is not None and tier.to_day < day:
            continue  # wholly inside free time
        # A gap is a mistake in the tariff; charging nothing for it would hide it.
        if tier.from_day > day:
            raise ValueError("no rate for day %d: no tier covers it" % day)
        last = total_days if tier.to_day is None else min(tier.to_day, total_days)
        days = last - day + 1
        lines.append(
            DemurrageLine(
                from_day=day,
                to_day=last,
                days=days,
                daily_rate=tier.daily_rate,
                amount=money(tier.daily_rate.minor * days, tier.daily_rate.currency),
            )
        )
        day = last + 1
    if day <= total_days:
        raise ValueError("no rate for day %d: no tier covers it" % day)

    free_time_ends: Optional[str] = add_days(start_date, free_days - 1) if free_days > 0 else None
    return DemurrageCharge(
        total_days=total_days,
        free_days_used=min(free_days, total_days),
        chargeable_days=max(total_days - free_days, 0),
        free_time_ends=free_time_ends,
        lines=lines,
        total=sum_money([line.amount for line in lines], tiers[0].daily_rate.currency),
    )

Install

fune build

With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 4 dependencies, pins them in fune.lock, downloads only the Python 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 logistics.demurrage
Download for Python logistics.demurrage-1.0.0-python.fune · 19,938 bytes sha256 680b70a279415de6e12c1db7a56e51f533575e7f94bb2ea2923f716d7e5d0013

The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./logistics.demurrage-1.0.0-python.fune, or fetch it from a terminal with fune pull logistics.demurrage@1.0.0:python.

The whole function, every language, is one file too: logistics.demurrage-1.0.0.fune, 28,367 bytes, sha256 9bf7d4f8c7b4fe3c08a03715c06c0870b842933ed6581de5c71d421ae761358f. 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 logistics.demurrage

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

# fune: after logistics.demurrage

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 logistics.demurrage
# fune: replace dates.days-between in logistics.demurrage
# fune: replace money.amount in logistics.demurrage
# fune: replace money.sum in logistics.demurrage

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 logistics.demurrage --steps.

# fune: step logistics.demurrage 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
collected on the last free day: nothing to pay 2026-03-01, 2026-03-04, 4, tiers ×3 → total days 4, free days used 4, chargeable days 0, free time ends 2026-03-04, lines , total $0.00
one day over free time 2026-03-01, 2026-03-05, 4, tiers ×3 → total days 5, free days used 4, chargeable days 1, free time ends 2026-03-04, lines ×1, total $75.00
twenty days runs through all three tiers 2026-03-01, 2026-03-20, 4, tiers ×3 → total days 20, free days used 4, chargeable days 16, free time ends 2026-03-04, lines ×3, total $3,075.00
tiers given out of order give the same answer 2026-03-01, 2026-03-20, 4, tiers ×3 → total days 20, free days used 4, chargeable days 16, free time ends 2026-03-04, lines ×3, total $3,075.00
extended free time swallows the first tier and part of the second 2026-03-01, 2026-03-20, 10, tiers ×3 → total days 20, free days used 10, chargeable days 10, free time ends 2026-03-10, lines ×2, total $2,400.00
free time runs through 29 February in a leap year 2028-02-27, 2028-03-02, 4, tiers ×1 → total days 5, free days used 4, chargeable days 1, free time ends 2028-03-01, lines ×1, total €90.00
returned early: free time still ends where it would have 2026-12-30, 2026-12-31, 4, tiers ×1 → total days 2, free days used 2, chargeable days 0, free time ends 2027-01-02, lines , total €0.00
no free time, a single day at a flat rate 2026-06-15, 2026-06-15, 0, tiers ×1 → total days 1, free days used 0, chargeable days 1, free time ends —, lines ×1, total £50.00
a zero-rate tier charges nothing but still appears 2026-06-01, 2026-06-10, 2, tiers ×2 → total days 10, free days used 2, chargeable days 8, free time ends 2026-06-02, lines ×2, total £200.00
no free time with a tariff that starts at day 5 leaves days uncovered 2026-03-01, 2026-03-06, 0, tiers ×1 → error: no rate for day 1
Show the other 12 tests
CaseArgumentsExpected
a gap in the tariff is an error, not a free day 2026-03-01, 2026-03-10, 4, tiers ×2 → error: no rate for day 8
a closed last tier leaves later days uncovered 2026-03-01, 2026-03-10, 4, tiers ×1 → error: no rate for day 8
overlapping tiers 2026-03-01, 2026-03-10, 4, tiers ×2 → error: tiers overlap at day 8
an open tier followed by another overlaps 2026-03-01, 2026-03-10, 4, tiers ×2 → error: tiers overlap at day 10
a tier running backwards 2026-03-01, 2026-03-10, 4, tiers ×1 → error: tier toDay must not be before fromDay
a tier starting at day 0 2026-03-01, 2026-03-10, 4, tiers ×1 → error: tier fromDay must be 1 or more
a negative daily rate 2026-03-01, 2026-03-10, 4, tiers ×1 → error: dailyRate must not be negative
tiers in two currencies 2026-03-01, 2026-03-10, 4, tiers ×2 → error: currency mismatch
no tiers at all 2026-03-01, 2026-03-02, 4, → error: tiers must not be empty
negative free days 2026-03-01, 2026-03-10, -1, tiers ×1 → error: freeDays must not be negative
end before start 2026-03-10, 2026-03-09, 4, tiers ×1 → error: endDate must not be before startDate
an impossible date 2026-02-30, 2026-03-09, 4, tiers ×1 → error: 2026-02-30

More from the author

## Counting days

Days are calendar days and both ends count: a container discharged on 1 March and collected on 5 March has been there 5 days. Tariffs differ on whether the discharge day is day 1; if yours starts counting the next day, pass the next day as `startDate`. Free time in working days (some carriers exclude weekends and holidays) is not handled here.

Days 1 to `freeDays` are free. Every later day is charged at the rate of the tier whose `fromDay`..`toDay` contains it, and the tiers use the same day numbers as the tariff prints ("days 5-7 USD 75, days 8-14 USD 150, day 15 onwards USD 300"). With extended free time the free days simply swallow the early tiers: 10 free days on that tariff charges days 11-14 at USD 150 and then USD 300. If your contract restarts the tiers after extended free time, renumber them before calling.

`freeTimeEnds` is the last free day (`startDate + freeDays - 1`), reported even when the container went back earlier, because that is the date operations plan against. It is correct across month ends and 29 February.

## Errors

A chargeable day that no tier covers is an error naming the day, not a free day: a gap in a tariff table is a data mistake, and charging nothing for it would hide it. Overlapping tiers, a tier running backwards, a negative rate, mixed currencies, no tiers at all, negative free days and an end before the start are errors too.

## Money

Each line is `days x dailyRate` in integer minor units, exactly; there is no rounding anywhere. The rate is per container: multiply for several.

Files

PathBytes
README.md1,995
impl/python.py3,503
impl/rust.rs4,964
impl/typescript.ts3,169
vectors.json8,968