Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/docs/business-logic-patterns.md
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
business-logic-patterns.md · 11.5 KB · 209 lines

Business Logic Patterns — Where Every Rule Goes

Every business rule has one correct home in the primitive stack. This page is the placement guide: the decision procedure, the map, and four worked examples (sales tax, payment aging, dunning, refunds) that most systems get wrong. The placement decisions and their reasons accumulate in logic-decisions.md, the way UI behavior accumulates in ui-decisions.md.

The method behind all of it (see logic-decisions #4): build each module's rules concretely in the cheapest correct primitive — a hook is three lines of real code — and only promote a pattern to a declarative schema key after it has repeated in two or three real modules. Concrete → pattern → primitive, never primitive-first. Systems that build the workflow/rules engine first die when reality doesn't fit it; ours extracts engines from reality.

Where does this rule go?

flowchart TD
    Q["a business rule"] --> D1{"Derivable from<br/>stored data?"}
    D1 -->|same record| F["formula field"]
    D1 -->|child records| R["rollup field"]
    D1 -->|no| D2{"Does it GATE<br/>a write?"}
    D2 -->|shape / bounds / FK| V["schema validation"]
    D2 -->|legal state moves + who| T["transitions + when guards"]
    D2 -->|cross-record or computed gate| H["pre-write hook<br/>(reject or stamp)"]
    D2 -->|no| D3{"Does TIME<br/>cause it?"}
    D3 -->|yes| DM["daemon: scheduled pass /<br/>auto-transition"]
    D3 -->|no| D4{"Is it a REACTION<br/>to a change?"}
    D4 -->|notify / email| N["notify_rules (after write)"]
    D4 -->|run code| TR["trigger → target object"]
    D4 -->|external system| C["connector<br/>(desired state + reconcile)"]
    D4 -->|no| O["plain object<br/>(page / API / worker)"]

The placement map

Kind of rulePrimitiveLives inExample
Shape, type, bounds, enum, FK-existsschema validationobject_records write pathamount is integer cents; project must exist
Same-record derivationformula (materialized)object_computed via object_recordstax_cents = amount_cents * tax_rate
Aggregation over childrenrollup (materialized, live)sameinvoice.paid_cents = sum(payments)
Legal state moves, and who may movetransitions + whenobject_recordsdraft → posted, owner only
Cross-record gate, computed gate, point-in-time stamppre-write hookhooks.before_write → object_server write pathjournal must balance; stamp tax_rate
Time-driven statedaemon scheduled pass / after_hours auto-transitionobject_daemonsent → overdue when past due
Reaction: notify, emailnotify_rulesdaemon, after the writedunning email on overdue
Reaction: run codetrigger → target objectdaemonrecompute, follow-on records
External side effectconnectordesired-state records + reconcilepayment-provider refund call
Correction to money / inventoryappend-only compensating recordstorage: append collectionsrefunds, stock moves, journal reversals
Everything elsea plain objectanywherebespoke report, integration, one-off page

Two hard boundaries hold the map together:

  • Gates before the write; reactions after. A hook may reject or stamp but

never send email or call out — a gate with side effects leaks that a write was attempted and couples saves to SMTP. A reaction may notify or spawn work but never block the write that already happened. (event-hooks-decisions.md)

  • Derived values are non-authoritative; gates are authoritative. A broken

formula stores "" and the write succeeds; a broken hook fails closed and the write is rejected. Never let a gate read only a derived value it could recompute — the journal-balance hook sums the lines itself even though rollup totals exist.

Worked example 1: sales tax (the one everyone leaves out)

Why it's left out: it hides a doctrine most systems never articulate — stamp point-in-time facts; derive live facts (logic-decisions #1). The tax rate is a fact about the transaction moment: rates change, and the invoice must forever carry the rate it was issued under.

  1. Rates are data: a tax_rates collection — region, category,

rate, valid_from. Editable like any records; history visible.

  1. Stamping is a hook: hooks.before_write on invoice lines looks up the

applicable rate and stamps tax_rate onto the line — same posture as the server stamping owner_id. The client never supplies it; later rate changes never rewrite history.

  1. Amounts are formulas/rollups: `line.tax_cents = amount_cents *

tax_rate (formula); invoice.tax_total_cents` (rollup). Materialized, so they appear on every list/detail/report and update live.

Worked example 2: payment aging (time makes the state)

The trap: an invoice becomes overdue with no write happening — time did it. Any system that computes "is it late?" ad hoc in the UI grows a dozen disagreeing copies of that check.

  1. balance_cents is a rollup (total_cents minus sum(payments)).
  2. sent → overdue is a daemon scheduled pass through the ordinary

transition machinery, when due_date < today and balance_cents > 0 — so the state is stored, permission-checked, realtime-pushed, and every surface agrees (logic-decisions #2: time-driven state belongs to the daemon, never to read-time checks).

  1. Aging buckets (30/60/90) are a rollup/report over stored state.

Worked example 3: dunning (reactions compose on state)

Dunning is nothing new — it is the composition of the two layers above:

  1. The daemon flips the state (overdue, later overdue_30, …).
  2. notify_rules reacts: state change → email template to the invoice's

contact. The rule is data; the daemon delivers after the write.

  1. Escalation ("again at 30 days unless paid") is more time-driven state,

not a special notification feature — each escalation step is a transition the daemon makes, each with its own notify rule.

Worked example 4: refunds (money moves, never mutates)

Money never mutates; it moves (logic-decisions #3). A refund is not an edit to a payment — it is a new, append-only compensating record, exactly like a stock move or a journal reversal.

  1. refunds is an storage: append collection pointing at the payment.
  2. The invariant is a hook: refund ≤ payment − prior refunds — a

cross-record gate, summed from the records themselves.

  1. payment.refunded_cents / net_cents are rollup/formula — display

truth, derived.

  1. "Correctly credited" is the balanced journal entry the refund composes —

enforced by the journal-balance hook that already ships. The chain closes: append-only record → hook invariant → rollup display → balanced books.

Worked example 5: inventory shrinkage (the events nobody codes for)

Waste, breakage, theft, expiry, damage, disaster: systems are easy to build when quantities just flow buy → stock → sell; real usage is losses. Naming them is the point — "adjustment" is the euphemism that hides exactly what operators and auditors need to see.

  1. Losses are movements (logic-decisions #3): a loss is an append-only

stock move with a loss reason, out of a location, to nowhere — never an edit to an on-hand number (levels stay derived).

  1. The hook stamps and gates: unit_cost_cents is stamped from the

product at the moment of movement (#1 — tomorrow's cost edit must not reprice yesterday's loss); a loss must leave a real location and can have no destination.

  1. The composer books the shadow: a loss move composes a posted journal —

DR shrinkage-expense / CR inventory-asset — with per-reason account overrides as settings (theft to its own account for the insurance claim).

  1. Count reconciliation is the same machinery: a physical count writes

one compensating adjustment move for the variance (out for shortage, in for overage) plus the mirror journal. The count is an event, not an edit.

This was also the composer pattern's third repeat, which triggered the doctrine-#4 extraction: every generated journal now goes through object_finance.compose_posted_journal (idempotent by generated_from, verify-then-post), and the payment/refund/recurring/reversal composers shrank onto it.

Worked example 6: bank reconciliation (evidence, not data entry)

Comparing the books to a bank statement is the strongest practical control a small business has, and the reason is not arithmetic — it is that the bank's copy was written by someone with no stake in our numbers. Every design choice follows from protecting that independence (logic-decisions #8).

  1. Imported lines are append-only and keep their original text in raw;

parsed fields are a view of it. A pre-write hook makes the factual fields immutable on update — corrections come from re-importing a corrected statement, never from editing a line to agree with the books.

  1. The statement checks itself. Opening + lines = closing (tie-out), and

this opening = the last statement's closing (continuity). Both run at import and set the import's status; a truncated or edited file fails arithmetic. The flags record which checks ran, so a balance-less CSV never reads as trustworthy as a verified one.

  1. Reading a bank's format is data, not code: a saved column map,

authored once with AI help and executed deterministically thereafter. AI at configuration time, code at run time — a control cannot be nondeterministic.

  1. The matcher proposes; a person disposes. Suggestions are derived and

non-authoritative; confirming is an ordinary attributed update, so the change log names who reconciled what. Only a two-signal match (reference and amount) is auto-confirmable, and even that is configurable to off.

  1. The unmatched tail is where the business logic lives: fees, interest,

own-account transfers, NSF bounces — each a resolution verb composing a posted journal through the shared composer, stamped with the line's id so resolving twice books once. These are exactly the entries small books never record, which is why their cash balance drifts until they stop reconciling at all.

State-dependent behavior generally

transitions + when guards define the machine; the board's drag is its UI; hooks gate specific moves with computed conditions (the balance check gates draft → posted); the daemon makes time-based moves. The known missing declarative is "state freezes fields" (a posted invoice's amounts are immutable). Per the method: express it in each module's hook first; promote it to a schema key (locked_when) only after the shape repeats (logic-decisions #5).

What this implies we build next

The examples above want one substrate piece that doesn't exist yet: a payments collection (plain records — provider integration is a connector later). It unblocks aging, dunning, and refunds at once. Then: tax_rates + the stamping hook; then a delay/repeat notion for notify_rules if escalation schedules outgrow "each step is its own transition."

Related

reference for each primitive (validation table, hooks contract, formulas/rollups, the automation substrate).

decisions and doctrines.

substrate for money-moves.