A section’s finance rules

Kompass does not know how your section settles an excursion. It knows how to read a statement out of the database, how to run your rules against it, how to make the money add up and how to remember which version of the rules a statement was settled under. The rules themselves — what an allowance is, who gets it, what the participants contribute, who has to sign — are a Python package in your section’s own configuration repository.

This page is the reference for writing that package. It is the whole contract: kompass.rules is the only Kompass module a ruleset may import, and everything it offers is documented below.

Tipp

There is a directory in this repository to copy rather than start from nothing: deploy/config-template/. It holds a working ruleset, three worked cases, the mypy and ruff configuration and a CI workflow. Its README.md is the section’s half of this page.

What a ruleset is

A ruleset is a class deriving from Ruleset, instantiated once and exported as ruleset:

# rules/__init__.py
from kompass.rules import PARTICIPANTS, Ruleset, SECTION

class TownRules(Ruleset):
    name = "town"
    context_version = 1
    balance = (PARTICIPANTS, SECTION, "participant_contribution")

    ...

ruleset = TownRules()

It answers four questions about one statement, and nothing else:

inputs()

Which extra data does a person have to supply? The form is derived from these declarations, so a question is asked because a rule reads its answer.

transfers()

Who owes whom how much, and what is wrong with the statement?

checks()

What must hold before the statement may be handed in?

approval()

Who has to sign it off, and who may not?

Each one is given a RuleContext — every fact about the statement a rule is allowed to know, as frozen values.

There is a fifth method, and it matters to anyone whose questions depend on the answers already given: the live form asks relevant_inputs(), not inputs(). Its default implementation re-runs inputs against the answers so far, which is why a ruleset that branches inside inputs already works — but a ruleset that overrides relevant_inputs is overriding the method the form actually calls, while the case runner, the fuzzer and the stored declarations go through inputs. Keep the two consistent, or the question a person is asked and the answer a rule reads come apart.

How a ruleset reaches a running instance

Every Kompass instance is the stock image with one directory mounted read-only at /app/config (KOMPASS_CONFIG_DIR_PATH), the same directory settings.toml is read from. A ruleset is a package in that directory, named from the settings:

[finance]
ruleset = "rules"   # a package directory under KOMPASS_CONFIG_DIR_PATH

manage.py importruleset runs when the master container starts — one of the five the image runs, and the only one whose entrypoint imports; the SPA, the Celery worker, the beat and the LMTP containers do not — on demand from the admin, and, with [finance] ruleset_poll_minutes, from a periodic task. It reads every *.py under the package, hashes the sources together with the section’s finance parameters, and stores that as a version. An unchanged package hashes to the version that is already stored, so importing twice costs a hash and changes nothing.

A section’s workflow is therefore: pull request in the configuration repository → its own CI runs mypy, ruff and checkruleset inside the pinned image → merge → the host pulls the repository → import. No Kompass release and no container restart: workers resolve the active version per evaluation and load its sources by hash on first use.

Activation is gated on the same checks the section’s CI runs. A package that fails one of them is stored as a draft, the previous version stays active, the command exits non-zero and says so loudly — and the container still serves. A typo in a rule is not a reason to take a section’s finances offline.

A statement keeps the version it was created under: its own copy of the sources and of the parameters is snapshotted onto it, and the resolved transfers are written down as rows. Changing a rule — or a parameter, which is the same thing to the hash — never moves a figure that has already been settled.

Warnung

A section that deploys without a ruleset settles its statements under Heidelberg’s rules. When [finance] ruleset is unset, the reference ruleset that ships in the image applies, and that ruleset is the policy of the JDAV section Heidelberg: its allowance per day, its organisation fee for participants from 27, its LJP arithmetic, its single signature from the finance department.

Nothing fails and nothing warns: the statements resolve, the books add up, and the figures are somebody else’s. For any section that is not Heidelberg, writing a ruleset is not optional — it is the difference between settling your own rules and settling theirs.

The rules of the road

Six properties the engine enforces or depends on. Each of them is the reason an old statement can be re-derived years later and come out the same.

Everything is a frozen value

The context holds no model instances, no relations to follow, no names, no bank details, no other statements and no balances. A person is a Member — an id and nothing else — and the engine resolves names and bank details after evaluation, so a ruleset cannot leak them. What a rule cannot reach it cannot accidentally depend on.

A rule must not query the database

This is enforced, not asked for: while any of the four methods runs — and while the ruleset’s own module body is executed, and while the engine reads name, context_version, valid_from or permissions off it — every ordinary route to the database refuses. A query raises QueryDuringEvaluation, which comes back as an error on the statement with the traceback pointing at the line in your rules.

Everything a rule may read is in the context it was given. If a rule needs a figure that is not there, the answer is a new context field in Kompass — an additive change with a CONTEXT_VERSION bump — and not a query.

Money is Decimal, in whole cents

Never float. Every amount a rule returns must have at most two decimal places; the engine rejects anything finer rather than rounding it silently, because how to round is the section’s decision and not the engine’s. split() and pct() are the two roundings most rules need, and quantize() is the one they are built on. A transfer whose amount is a float, or has three decimal places, is an error on the statement rather than a payout nobody can reproduce.

Rules are deterministic

There is no clock in the context and no way to read one: a call to now, today, utcnow or fromtimestamp is refused by the import check, and random and time may not be imported at all. The one value that depends on when the engine ran is age, which exists because the rules it was ported from use it; a rule that must stay reproducible prefers age_at_start.

A rule must also not read balances — neither a member’s standing with the section nor what another statement resolved to. The context deliberately has none. The only result of another rule a rule may read is the transfer list it has built itself during this evaluation, which is how the reference ruleset’s LJP contribution reads the allowance and subsidy it just produced.

balance names the residual party, and it may not be a member

A ruleset does not compute the participants‘ contributions. It declares which two parties the residue moves between (balance), and the engine appends exactly one transfer with the amount that brings the declared destination to zero. „The statement adds up“ is therefore not an assertion anybody can forget to make.

The declaration must be between the section and the participants. A member may not be a balance party: a person is a payee, not a ledger, and balancing against one makes whoever it names the sink for everything the rules did not account for — a bill nobody wrote. The engine refuses it. It also refuses a declaration that is the wrong way round, which closes nothing and leaves a 0.00 row to show for it.

A ruleset is stateless

One instance is created when a version is loaded and that instance is shared across every evaluation in the process, concurrently, for as long as the version is in use. Do not keep anything on self between calls: no caches, no counters, no „the statement I am working on“. Everything a method needs is in the context it is given, and anything stored on the instance is a figure from somebody else’s statement waiting to be used in yours.

What does not change is fine: a number read from the context (ctx.params.ALLOWANCE_PER_DAY), a module-level constant (ORG_FEE_AGE = 27), a class attribute the engine itself reads (balance), a pure helper method.

What a ruleset may import

A ruleset may import:

  • itself — relative imports inside its own package (from .travel import reimbursement),

  • kompass.rules, and nothing else from Kompass,

  • from __future__ import …, which is a compiler directive,

  • and these standard-library modules: decimal, math, dataclasses, typing, enum, fractions, itertools, functools, collections.

Everything else is refused at import time, with a file and a line. So is any mention of __import__, importlib, exec, eval, compile, open, os, sys, subprocess, socket, random, time, requests, anything under django, globals, locals, vars, getattr, setattr, delattr and dir; so are the dunder attributes that walk out of a module and into the interpreter (__class__, __globals__, __builtins__, __code__ and the rest); and so is a call to now, today, utcnow or fromtimestamp.

Third-party packages are not available. The image does not have them, and a ruleset’s import closure has to be enumerable to be hashable. A section that needs more than the list above asks for a helper in kompass.rules.

Wichtig

This is a lint plus a restricted namespace. It is not a sandbox, and nothing here should be read as one.

The check is a textual scan of the ruleset’s source, and the loader executes it with a restricted __builtins__. Neither is a boundary: four lines that mention no banned name at all reach the interpreter’s own builtins through a frame object, and frames, descriptors and __reduce__ are each one hop from the next spelling. No blacklist carries that guarantee.

What the check is worth is catching the accident early — a rule that imports half of Kompass, reads the clock or opens a file is a rule whose answer can change behind an old statement’s back — and letting your own CI say the same thing with ruff before the pull request is merged. What carries the database guarantee is the query guard, which refuses at the connection however the rule got there.

The trust boundary is unchanged by any of it: whoever can write the configuration directory already holds the database password and the secret key. Executing Python from it grants no privilege its author does not already have. A rule author is trusted exactly as far as the person who edits settings.toml.

Declaring inputs

Every answer a rule reads has to be declared by inputs(), because the statement’s form is generated from those declarations. Reading an undeclared key raises RuleError rather than returning None: a typo in a rule is a bug your cases should catch, not a silent zero in somebody’s reimbursement.

The widget vocabulary

type is presentation, not rule structure — money and int are both numbers, and the difference is the field the person is shown.

type

Read with

What it is, and what it reads as unanswered

money

money()

An amount, as a Decimal. Unanswered: 0.00.

int

number()

A whole number; max is its largest acceptable value. Unanswered: 0.

bool

flag()

A yes/no question. Unanswered: False.

text

text()

Free text. Unanswered: "".

choice

raw()

In the vocabulary, not yet usable — see the warning below.

member

member()

One person out of options. Unanswered: None.

member_set

members()

Several people out of options, at most max of them. Unanswered: ().

For member and member_set, the engine re-validates a submitted answer against the options the declaration offered, so an answer can never name somebody the rule did not offer. A rule cannot widen the set by returning a wider one from somewhere else either: the leaders in leaders are re-checked too.

Which keys may be declared is a separate and much tighter restriction than which types exist — see Only four input keys can be answered today.

Warnung

Do not use choice yet (#573). It is in the vocabulary and the form renders it, but there is no way to say what may be chosen: options is tuple[Member, ...] and finance/inputs.py::options_for resolves it through Member.objects.in_bulk, so a choice arrives with an empty option list and clean_value falls through to „anything else is text“ — it accepts any string at all.

Worse, the unanswered value is None while text() type-checks against str, so reading an unanswered choice with the accessor its type suggests raises RuleError — and because that happens inside transfers(), it collapses the whole evaluation into one error rather than reporting a missing answer.

Until #573, a fixed set of alternatives is a bool per alternative, or a text input whose value a check validates. If you must use choice, read it with raw() and test for None before anything else — and know that nothing validates what came in.

The section’s numbers

A figure that the section votes on rather than a rule that it writes — the allowance per day, the maximum per night, the rate per kilometre — is a parameter, read from the context as ctx.params.ALLOWANCE_PER_DAY. The values come from the section’s settings.toml, as exact decimal strings, and they are hashed into the ruleset’s version alongside its sources: changing the allowance per day is a new version, not an edit, and nothing that was settled under the old number moves.

Bemerkung

The parameter names are not free-form. Kompass copies a fixed list of settings into a version’s parameters — PARAMETER_KEYS in finance/engine/context.py, today ALLOWANCE_PER_DAY, MAX_NIGHT_COST, AID_PER_KM_TRAIN, AID_PER_KM_CAR and EXCURSION_ORG_FEE (from [finance]) plus LJP_CONTRIBUTION_PER_DAY and LJP_TAX (from [LJP]) — so ctx.params.WHATEVER_YOU_LIKE raises RuleError.

A number that is not one of those keys belongs in the ruleset as a module-level constant, where it is versioned with the rules that read it. That is arguably where a figure the section voted on belongs anyway: the hash moves when it changes, which is exactly the behaviour a parameter has.

Cases: a ruleset’s own tests

A case is one JSON file beside the rules, in rules/cases/*.json, holding a whole context and what the rules are expected to make of it. It needs no database, no fixtures and no Django, which is the point: the cases run in your own repository’s CI against the image you deploy, and the instance runs them again at import — a case that fails means the version is stored as a draft and never activated.

{
  "name": "allowance only",
  "params": {"ALLOWANCE_PER_DAY": "22"},
  "inputs": {"allowance_to": [7]},
  "excursion": {"duration": "2.0", "leaders": [7], "staff_count": 1,
                "approved_staff_count": 2},
  "expect": {
    "transfers": [
      ["SECTION", "7", "44.00", "allowance"],
      ["PARTICIPANTS", "SECTION", "44.00", "participant_contribution"]
    ],
    "errors": [],
    "checks": [true]
  }
}
  • Only the keys a case cares about have to be there. Everything else takes a quiet default: no bills, no trip, no answers, every parameter unset.

  • Money is written as a string ("42.69"), so that a case file never carries a binary float.

  • A party is "SECTION", "PARTICIPANTS" or a member id.

  • Each expected transfer is [source, destination, amount, category], in the order the rules produced them, and the engine’s balancing transfer is the last one. A case that leaves it out fails, which is deliberate: it makes the case say out loud what the participants end up contributing.

  • errors is the list of messages transfers() returned, compared exactly.

  • checks is the expected ok state of each check, in order. Leaving the key out means the case does not look at them.

  • permissions maps a codename to the ids that hold it, for a ruleset whose rules read permission_holders().

The format is implemented in jdav_web/finance/engine/cases.py, which is also where a new key would be added.

Only four input keys can be answered today

Gefahr

This is the one restriction on this page that can cost money, and it is a restriction of the running instance, not of the case runner.

A statement does not yet store its answers in one field. It has four columns, the ones the reference ruleset happens to need, and finance/engine/context.py::statement_inputs returns exactly those: night_cost, allowance_to, subsidy_to and ljp_to. A declaration under any other key has nowhere to be stored, so finance/engine/evaluation.py::_answered substitutes that type’s empty value — 0.00, 0, False, "", None or () — on every evaluation. The person is asked the question, the answer goes nowhere, and the rule reads a zero. Nothing raises and nothing warns.

raw() does not get round it: the key is present in the mapping, holding the empty value. There is nothing else to read.

A case will not catch it, which is what makes it dangerous. cases.py::_inputs coerces those same four keys and passes any other key through as JSON wrote it, so a case that answers a custom key proves something the instance will never do: the case goes green and production pays zero.

Until the answers move into one JSON field (step 3 of the refactor, #556, in flight), a rule may only read those four keys — and a section whose policy needs another number puts it in the ruleset as a module constant, where it is versioned with the rules, rather than declaring an input for it.

One consequence of the four keys being the reference ruleset’s: their types are fixed too — night_cost is money, allowance_to is member_set, subsidy_to and ljp_to are member. A declaration that reuses a key with a different type gets the column’s value, not the declared type’s.

Checking a ruleset

checkruleset runs the import check, loads the package, and runs its cases. It touches no data, so it runs anywhere the image runs:

docker run --rm -v "$PWD":/app/config:ro \
    -e KOMPASS_CONFIG_DIR_PATH=/app/config \
    ghcr.io/chrisflav/kompass:<tag> \
    python jdav_web/manage.py checkruleset /app/config/rules --fuzz 200

KOMPASS_CONFIG_DIR_PATH makes the fuzz use the numbers from the settings.toml beside the rules; the cases carry their own params. The command keeps the image’s own working directory, /app, which is where it has to run — see the warning below.

--fuzz N additionally builds N random but valid statements, asks the ruleset what to ask the person, answers those questions at random within the domains the ruleset itself declared, and checks the two things that must hold whatever the answers are: that the rules report no error, and that the books balance. It is not a proof and it is not a substitute for a case with an expected figure — it is the cheapest way to find the rule that divides by a participant count nobody checked for zero.

A section’s CI runs three commands, all three inside the image the instance runs, so that the API module and the interpreter match production. They do not share a working directory:

cd /app/config && mypy --strict rules      # reads ./pyproject.toml
cd /app/config && ruff check rules          # reads ./pyproject.toml
cd /app && python jdav_web/manage.py checkruleset /app/config/rules --fuzz 200

Warnung

The third command must not run from /app/config. Kompass pulls in Celery, whose Django fixup inserts the working directory at the front of sys.path on purpose, and a configuration directory contains a rules/ package — which is also the top-level name of django-rules, a dependency and an installed app. From /app/config the section’s own ruleset shadows it and django.setup() dies with No module named 'rules.contrib' before a single rule is read.

So checkruleset runs from /app, exactly as the container entrypoint does, and is given the package by absolute path. mypy and ruff do need /app/config as their working directory, because that is where their pyproject.toml is; neither imports Django, so neither is affected.

The exact invocation — the mount, the environment and where mypy and ruff come from, since the image carries the application’s dependencies and not a toolchain — is .github/workflows/check-rules.yml in deploy/config-template/.

mypy --strict is worth having because the accessors are typed: a Decimal + bool, a destination that is an int rather than a Member, a rule that forgot excursion may be None — all of those are a file and a line rather than an error on somebody’s statement. ruff, with the banned-import rules the template ships, reports a forbidden import as a lint failure in your own CI instead of a rejected version in the admin.

A section without CI has checkruleset by hand and the admin’s dry run. That is less, and it is stated as less.

API reference

The ruleset

class kompass.rules.Ruleset

What a section’s finance rules have to implement.

Subclass it in the section’s ruleset package and export one instance as ruleset:

ruleset = HeidelbergRules()

Everything the engine fixes is here; everything else — how many rules there are, what the categories mean, who a recipient is, whether an amount is per person or per statement — is the author’s Python.

name: str = 'unnamed'

A short name for this ruleset, used in logs and in the admin.

context_version: int = 1

The CONTEXT_VERSION this ruleset was written against. Kompass refuses to load a ruleset written against a newer context.

valid_from: str = ''

The date these rules were in force from, ISO 8601 ("2026-03-01"), empty for „from the moment Kompass is told“.

It is valid time, and it may be in the past: a section that resolved new rates in March and imports them in May says "2026-03-01", and the record then carries both when the rules applied and when Kompass learned of them. A date in the future stages a change that is already agreed. This declaration is the authority for either, which is why it lives in the ruleset package rather than in a command-line flag: the package is reviewed and committed, and it is the versioned documentation of the procedure an auditor asks for.

Backdating records; it does not re-settle. A statement is bound to the rules it was created under, and no version imported afterwards — with whatever date — changes what it settled under; settling one again under a correction is a separate, deliberate act (#561).

permissions: tuple[str, ...] = ()

Permission codenames the rules read with RuleContext.permission_holders(). The engine resolves these before evaluation, because the rules cannot query the database themselves.

balance: tuple[Member | Section | Participants, Member | Section | Participants, str] = (Participants(), Section(), 'balance')

(source, destination, category) of the one transfer the engine appends, with the amount it resolves itself: the amount that brings destination’s net position to zero. Declaring the parties and letting the engine do the arithmetic is what makes „the statement adds up“ unfalsifiable rather than asserted. When the resolved amount comes out negative the engine runs the transfer the other way round, so the direction declared here is the one that is usual for the section.

abstractmethod inputs(ctx: RuleContext) → list[Input]

Declare every answer the rules read, in the order to ask for them.

abstractmethod transfers(ctx: RuleContext) → tuple[list[Transfer], list[str]]

Resolve the statement into transfers, plus anything wrong with it.

Return (transfers, errors). An error is a sentence for the person who has to fix the statement — a covered bill with nobody to pay back — and while there is one, nothing is persisted and no money moves. Do not raise for a problem with the statement; raising is for a broken ruleset, and the engine turns it into an error with a traceback.

checks(ctx: RuleContext) → list[Check]

Preconditions for handing the statement in. Default: none.

relevant_inputs(ctx: RuleContext) → list[Input]

The questions still worth asking, given the answers so far.

The default re-runs inputs() against the answers known so far, which is enough for a ruleset whose inputs branches on them — drop the question about the price per night once „no subsidy“ has been answered, and it stops being asked.

approval(ctx: RuleContext, transfers: list[Transfer]) → tuple[list[Constraint], list[Forbid]]

Who has to sign this statement off, and who may not.

Routing runs on the transfers, after expansion, so a rule can say „nobody who receives money from this statement“ (see Forbid) or „over 1.000 € it takes the board“ without re-deriving either from the raw statement. Default: nobody, which the engine reads as „the capability check alone decides“.

kompass.rules.CONTEXT_VERSION: int = 1

The version of the context shape this Kompass offers. A ruleset declares the version it was written against in Ruleset.context_version, and Kompass refuses to load one written for a newer context. Changes are additive — a field is added, never renamed or removed — so a ruleset written against version 1 keeps working.

exception kompass.rules.RuleError

Raised when a ruleset asks the engine for something it may not have.

Rule authors do not raise this. Problems with a statement are reported by returning a message from Ruleset.transfers(); this exception is for problems with the ruleset — an input it never declared, a permission it never asked for — which are programming errors and should fail a case in the section’s own CI.

The context

class kompass.rules.RuleContext

Everything a rule may know about one statement.

Built by the engine, never by a ruleset. Each field is documented on the type it holds.

version: int

The context shape this instance was built to; compare with CONTEXT_VERSION.

params: Params

The section’s numbers (see Params).

inputs: Inputs

The answers to Ruleset.inputs() (see Inputs).

bills: tuple[Bill, ...]

Every receipt handed in, covered or not, in the order they were added.

excursion: Excursion | None

The trip, or None for a statement that settles something else.

statement: StatementInfo

The statement itself (see StatementInfo).

roles: Roles

Who holds which section role (see Roles). Resolved for Ruleset.approval(); reading it elsewhere raises rather than answering „nobody“.

permissions: Mapping[str, tuple[Member, ...]]

Who holds which permission, for the codenames the ruleset declared in Ruleset.permissions. Read it through permission_holders().

role_holders(role: str) → tuple[Member, ...]

Everybody who holds role, or () if the role is unknown.

Raises RuleError when this context did not resolve the role assignments — see Roles for why that is not silently empty.

permission_holders(codename: str) → tuple[Member, ...]

Everybody who holds codename, as of this evaluation.

The codename has to be listed in Ruleset.permissions; the engine resolves those before evaluation, because a rule cannot query the database itself. Reading an undeclared one raises RuleError.

class kompass.rules.Excursion(duration: Decimal, nights: int, kilometers: int, approach: Literal['muscle', 'public', 'car'], leaders: tuple[Member, ...], staff_count: int, approved_staff_count: int, participants: tuple[Participant, ...], ljp: LJP | None)

The trip a statement settles, when there is one.

A statement without an excursion (a purchase, a repair) has ctx.excursion is None, and every rule has to say what it does then.

duration: Decimal

Days, in half-day steps: a long single day is 1.0, a short one 0.5.

nights: int

Nights away.

kilometers: int

Kilometres travelled there and back.

approach: Literal['muscle', 'public', 'car']

How the group travelled.

leaders: tuple[Member, ...]

The excursion’s youth leaders — the people who may be named as recipients. Re-validated by the engine, so a rule cannot widen it.

staff_count: int

How many youth leaders led the trip.

approved_staff_count: int

How many of them the section’s regulations refinance.

participants: tuple[Participant, ...]

Everybody on the member list, leaders included (see Participant).

ljp: LJP | None

The Landesjugendplan proposal, or None when the trip has none.

class kompass.rules.Participant(member: Member, age: int | None, age_at_start: int | None, is_leader: bool)

Somebody on the excursion’s member list.

Youth leaders who are also on the list appear here with is_leader set, so a rule that counts „participants“ has to say whether it means the leaders too.

age: int | None

Age today, or None when the birth date is unknown.

This is the one value in the context that depends on when the engine ran, and it exists because the rules it was ported from use it. A rule that must stay reproducible should prefer age_at_start.

age_at_start: int | None

Age on the excursion’s first day, or None when the birth date is unknown. Reproducible, and usually what a regulation means.

is_leader: bool

Whether this person is also a youth leader of the excursion.

class kompass.rules.LJP(goal: Literal['qualification', 'participation', 'development', 'environment'] | None, participant_count: int, theoretic_participant_count: int, duration: Decimal)

The excursion’s Landesjugendplan proposal, if it has one.

The counts are the ones the state’s regulations define, computed by the engine: a participant is counted when they are at least 6 and under 27 on the first day, up to a fifth of the participants may fall outside that band, and youth leaders always count.

goal: Literal['qualification', 'participation', 'development', 'environment'] | None

The declared learning goal, or None when none was picked yet.

participant_count: int

The participant count under the regulations, 0 below the cutoff.

theoretic_participant_count: int

The same count without the cutoff — what the cutoff is applied to.

duration: Decimal

The number of days that count as seminar days, at most the trip’s duration.

kompass.rules.LJPGoal = Literal["qualification", "participation", "development", "environment"]

The learning goal of a Landesjugendplan proposal.

kompass.rules.TourApproach = Literal["muscle", "public", "car"]

How the group travelled: on muscle power, by public transport, or by car.

class kompass.rules.Bill(id: int, amount: Decimal, covered: bool, payer: Member | None, has_proof: bool, description: str)

One receipt handed in with the statement.

A bill is a fact, not a transfer: it says that money was spent, not that anybody is owed it. Whether the section reimburses it is covered, which the finance officer decides — and a bill that is not covered is still in the context, because it may well count towards a subsidy that is computed from the trip’s total cost.

id: int

The bill’s primary key, for error messages that name a row.

amount: Decimal

What the receipt says, cent-exact.

covered: bool

Whether the section reimburses this bill.

payer: Member | None

Who paid, if anybody was named. None is a common, reportable state.

has_proof: bool

Whether a scan of the receipt is attached.

description: str

The short description its author gave it.

class kompass.rules.StatementInfo(id: int | None, creator: Member | None, submitter: Member | None)

The statement being evaluated, stripped to what a rule may know.

id: int | None

The statement’s primary key, or None before it is first saved.

creator: Member | None

Who created it.

submitter: Member | None

Who handed it in, once somebody has.

class kompass.rules.Inputs

The answers to Ruleset.inputs(), by key.

Reading a key the ruleset did not declare raises RuleError rather than returning None: a typo in a rule is a bug the section’s own cases should catch, not a silent zero in somebody’s reimbursement. A key that was declared but never answered reads as that type’s empty value — 0.00 for money, None for a member, () for a member set.

The accessors are typed, so mypy checks the arithmetic a rule does with an answer:

nights = ctx.excursion.nights * ctx.inputs.money("night_cost")

ctx.inputs.night_cost reads the same answer untyped, for a quick look. A key that happens to be named like one of the accessors — money, member, members, number, flag, text, raw, declared — is readable through those and through raw(), but not as an attribute, where the method wins.

declared() → tuple[str, ...]

The keys that are readable, in declaration order.

raw(key: str) → object

The answer to key, untyped.

Prefer money(), member(), members(), number(), flag() or text(), which say what they expect.

money(key: str) → Decimal

A money answer, as a Decimal.

number(key: str) → int

A whole-number answer.

flag(key: str) → bool

A yes/no answer.

text(key: str) → str

A free-text answer.

member(key: str) → Member | None

A single person, or None when nobody was picked.

members(key: str) → tuple[Member, ...]

A set of people, possibly empty, in the order they were picked.

class kompass.rules.Params

The section’s numbers, as Decimals.

A ruleset’s parameters are data, versioned with it, so that changing the allowance per day is a parameter change and not a rule change. Reading one that does not exist raises RuleError.

get(key: str, default: Decimal) → Decimal

The parameter key, or default when it is not set.

as_dict() → dict[str, Decimal]

A copy of every parameter.

class kompass.rules.Roles

Who holds which section role — or a refusal to guess.

A mapping, so ctx.roles["kassenwart"] reads as one, with one difference that matters: a context built for the arithmetic does not resolve the role assignments, and reading them from there raises RuleError instead of answering ().

That asymmetry is deliberate. An empty mapping cannot distinguish „nobody holds this role“ from „nobody asked the database“, and the second one, silently, pays a treasurer nothing and balances the books around the hole. Roles are resolved for Ruleset.approval(), which is what they are for; a rule that routes money by a role has to say so, and until the engine offers that it says so by failing loudly.

get(role, default=())

The holders of role, or default when nobody holds it.

Documented here rather than inherited: the signature comes from Mapping, but the behaviour does not. The default is () rather than None, and on a context that did not resolve the role assignments this raises RuleError instead of returning the default — which is the whole point of the unresolved state, and the opposite of what Mapping.get’s own docstring says.

classmethod unresolved() → Roles

The roles of a context that did not ask for them.

property resolved: bool

Whether the role assignments were read at all.

Parties

class kompass.rules.Member(id: MemberId)

A person, by id.

Members compare and hash by id, so a rule may use them in sets and as dictionary keys ({t.destination for t in transfers}).

class kompass.rules.Section

The section itself: the party whose money is being spent.

There is one instance, SECTION.

class kompass.rules.Participants

The excursion’s participants, as one party.

There is one instance, PARTICIPANTS. It is the usual counterparty for Ruleset.balance: whatever the section pays out net is what the participants‘ contributions have to cover. It is a lump sum — no individual participant’s bank details are in scope.

kompass.rules.SECTION: Section = Section()

The section — the one instance of Section.

kompass.rules.PARTICIPANTS: Participants = Participants()

The participants as one party — the one instance of Participants.

kompass.rules.Party = Member | Section | Participants

Anything that can be one end of a Transfer.

kompass.rules.MemberId = NewType("MemberId", int)

A member’s primary key, and the only identity a rule ever sees. Names, addresses and bank details are resolved by the engine after evaluation, so that a ruleset cannot leak them.

What a ruleset returns

class kompass.rules.Transfer(source: Member | Section | Participants, destination: Member | Section | Participants, amount: Decimal, category: str, rule_id: str, label: str = '', explanation: str = '')

Money owed by one party to another, because of one rule.

A transfer is the whole output of a ruleset. Expressing a payout as a movement between two parties rather than as a number on a member makes the books add up by construction: there is no such thing as money that appears from nowhere, and the engine’s balancing transfer (see Ruleset.balance) closes whatever is left.

Signs do not appear here. A deduction — an organisation fee charged against somebody’s reimbursement — is a transfer to the section, not a negative transfer from it.

source: Member | Section | Participants

Who owes the money.

destination: Member | Section | Participants

Who receives it.

amount: Decimal

How much, with at most two decimal places. The engine rejects anything finer: how to round is the section’s decision, and split() and pct() are there to make it.

category: str

What kind of money this is — "allowance", "ljp", whatever the ruleset wants to group and label by. Free text to the engine.

rule_id: str

Which rule produced it, for provenance: the stamp that answers „which statements paid a subsidy under which version of the rule“.

label: str

A short label for a person reading the payout, e.g. the bill’s own description.

explanation: str

Room for the arithmetic, if it is worth showing: „4 Tage × 22 €“.

class kompass.rules.Input(key: str, label: str, type: Literal['money', 'int', 'bool', 'text', 'choice', 'member', 'member_set'], required: bool = True, help: str = '', options: tuple[Member, ...] = (), max: int | None = None)

One question the statement’s form has to ask.

Declaring the question beside the rule that reads the answer is what keeps the two from drifting apart: the form is generated from these, and a rule that reads an undeclared key fails loudly (see Inputs).

key: str

The key the answer is read back under.

label: str

What the person is asked, in the section’s language.

type: Literal['money', 'int', 'bool', 'text', 'choice', 'member', 'member_set']

Which widget to render (see InputType).

required: bool

Whether the statement may be handed in without an answer.

help: str

A sentence of help under the field.

options: tuple[Member, ...]

For member and member_set: who may be picked. The engine re-validates a submitted answer against this, so an answer can never name somebody the rule did not offer.

max: int | None

For member_set and int: the largest acceptable count or value.

kompass.rules.InputType = Literal["money", "int", "bool", "text", "choice", "member", "member_set"]

The widget vocabulary an Input is rendered with. It is presentation, not rule structure: see The widget vocabulary for what each one is and how its answer is read.

class kompass.rules.Check(ok: bool, message: str)

A precondition for handing the statement in.

Both states are worth showing, so a check carries its message whether or not it holds: „Für den LJP-Beitrag braucht jeder Beleg ein Bild“ is the rule either way, and whether it is satisfied is ok.

ok: bool

Whether the precondition holds.

message: str

What has to be true, phrased for the person who has to fix it.

class kompass.rules.Constraint(name: str, description: str, applicable: bool, required: int, eligible: tuple[Member, ...], anyone_permitted: bool = False)

A signature the statement needs before the money moves.

Constraints are an unordered set: no priorities, no workflow. Each one asks for required signatures out of eligible, one signature counts against every constraint it satisfies, and applicable and satisfied are separate states — a constraint that does not apply is shown as such rather than hidden.

name: str

A short name, shown in the approval list.

description: str

Why this signature is needed, in the section’s words.

applicable: bool

Whether it applies to this statement at all.

required: int

How many signatures from eligible are needed.

eligible: tuple[Member, ...]

Who may sign. Re-checked against the real permission system, so naming somebody here cannot grant them a right they do not have.

anyone_permitted: bool

What it means for eligible to come out empty.

Left False, an empty group means nobody: the constraint stands open and no signature satisfies it. That is the safe reading, and it is the one an empty group usually deserves — a role nobody holds, a filter that matched nobody, a query that returned nothing — because the alternative lets a statement pay itself out precisely when the rules could not say who should allow it.

Set True, the engine fills the group from the holders of the section’s approval capability instead, which is what Kompass did before there were constraints at all. The forbids still apply to the group it fills in, so „whoever may act, except whoever is paid“ is sayable. An empty group then still means nobody — there is no reading under which „we could not work out who“ means „anyone will do“.

class kompass.rules.Forbid(name: str, applies_to: Callable[[Member], bool])

Somebody who may not sign, whatever permits them.

Forbids are subtracted from every constraint’s eligible set before quorum is counted, and they win unconditionally: this is how a conflict of interest is expressed („nobody who receives money from this statement“).

name: str

A short name, shown when a signature is refused.

applies_to: Callable[[Member], bool]

Whether this forbid catches a given candidate.

Helpers

kompass.rules.split(amount: Decimal, n: int) → list[Decimal]

amount divided n ways, to the cent, adding back up exactly.

Each share is floored to the cent and the leftover cents are handed out one each from the top, in declaration order, so 99 cents five ways is 20, 20, 20, 20, 19 — every time, which is what makes a statement reproducible. Raises ValueError for n <= 0.

kompass.rules.pct(amount: Decimal, basis_points: int) → Decimal

basis_points ten-thousandths of amount, floored to the cent.

Basis points rather than a percentage because they are exact integers: pct(x, 9000) is 90 % of x, pct(x, 1990) is 19,9 %.

kompass.rules.quantize(amount: Decimal) → Decimal

amount floored to whole cents.

The rounding split() and pct() are built on: towards minus infinity, never away from zero, so repeatedly splitting an amount can never create money.

kompass.rules.first_of(*parties: Member | Section | Participants | None) → Member | Section | Participants | None

The first party that is not None, or None.

The fallback chain a rule needs when a deduction has to be charged to somebody and there is more than one candidate: first_of(subsidy_to, *allowance_to).

kompass.rules.CENT: Decimal = Decimal("0.01")

One cent — the resolution of every amount in a Transfer.