Skip to content

Core Business Primitives

The engine ships four reusable business primitives every application module leans on: units of measure, multi-currency exchange rates, attachments (the filestore), and localization (geo + locale formats). Reuse these rather than rebuilding them — they live under fullfinity/modules/core/models/ (currency rate logic lives in modules/invoicing, see below).

Two models in modules/core/models/uom.py: UoM and UoMCategory.

A UoM belongs to a UoMCategory and carries a factor (how many base units one of this unit equals) and a rounding precision. Conversion within a category always routes through the category’s base unit, so every category must have exactly one is_base_uom UoM — the model enforces this invariant on create and update, raising ValidationError if you try to add a second base UoM to a category.

class UoM(Model):
_verbose_name = "Unit of Measure"
name = Char(max_length=50, required=True)
category = ManyToOne("UoMCategory", related_name="uoms", on_delete="SET NULL")
factor = Float(default=1.0) # FROM this UoM TO base; Dozen has factor=12
rounding = Float(default=0.001, precision=6)
is_base_uom = Boolean(default=False)

All methods are on the UoM instance:

  • round_qty(qty) — round a quantity to this UoM’s rounding precision (uses round_float). Returns qty unchanged when rounding is unset/zero.
  • convert_to_base(qty, round_result=True) — qty * factor, e.g. 2 dozen -> 24 units.
  • convert_from_base(qty, round_result=True) — qty / factor, e.g. 24 units -> 2 dozen.

A factor must be greater than zero: create/update raise ValidationError for zero or a negative value, and both conversions raise UserError naming the unit if a stored factor is not positive (a zero is never read as 1).

  • await convert(qty, to_uom, round_result=True) — convert between two UoMs in the same category, routing source -> base -> target. Raises UserError if the two UoMs are not in the same category. Rounds with the target UoM’s precision.
  • await is_compatible(other_uom) — True when both are in the same category (or both have no category).
UoM = get_model("UoM")
dozen = await UoM.filter(name="Dozen").get()
gram = await UoM.filter(name="g").get()
dozen.convert_to_base(2) # 24.0 (units) — plain, not awaited
await gram.is_compatible(dozen) # False — different categories
qty = await dozen.convert(1, to_uom=units) # same category -> routed through base

convert and is_compatible are async because they fetch the related category; convert_to_base, convert_from_base, and round_qty are plain (no I/O).

The engine ships a deliberately bare Currency model in modules/core/models/currency.py. The rate logic lives in modules/invoicing/models/currency_rate.py (CurrencyRate) — rates are an accounting concern, so the engine stays minimal and invoicing adds the dated rate table and conversion API.

class Currency(Model):
_verbose_name = "Currency"
name = Char(max_length=3, required=True) # ISO code, e.g. "USD"
symbol = Char(max_length=10)
rounding = Float(default=0.01, precision=6)
active = Boolean(default=False) # currencies must be explicitly enabled
position = Selection(choices=["Before", "After"], default="Before")
plural = Char(max_length=255)

A currency says how its money is NAMED — symbol, which side of the figure it sits on, decimal places (from rounding) — and nothing about how the figure is punctuated. Separators and digit grouping belong to the reader’s Language (below), so the same amount reads €1,234.56 to an English reader and €1.234,56 to a German one. Format an amount with the |money filter or format_monetary(value, currency, locale=…); see the Translations guide.

The full ISO currency set ships inactive — because Currency has an active field it is archivable, so every currency picker (a DataCombo bound to Currency) automatically lists only the enabled ones. A currency becomes enabled either by being assigned as a company’s base currency (setting Company.currency activates it) or by being switched on directly in the Currencies management screen. Foreign-currency inputs (the currency selector and exchange-rate/gain-loss fields on invoices, payments, purchase orders, and journals) are additionally gated behind a Multi-Currency setting — author your own such gate with visible_setting: Q(enable_multi_currency=True) on a field. To offer every currency in a picker regardless of enabled state (as the base-currency field on the company form does), give it filter: Q(active__in=[True, False]) — explicitly referencing active opts the query out of the archivable default.

CurrencyRate stores a dated rate per currency per company. A rate is expressed as 1 unit of this currency = rate units of company currency; inverse_rate is computed and stored for convenience. The triple (currency, company, date) is unique.

class CurrencyRate(Model):
_verbose_name = "Currency Rate"
_unique_together = [("currency", "company", "date")]
currency = ManyToOne("Currency", related_name="rates", required=True, on_delete="CASCADE")
company = ManyToOne("Company", related_name="currency_rates", required=True, on_delete="CASCADE")
date = Date(required=True, default=lambda self: date.today(), index=True)
rate = Float(required=True, precision=10)
inverse_rate = Float(calculate="compute_inverse_rate", store=True, precision=10)

Both are classmethods on CurrencyRate:

  • await CurrencyRate.get_rate(currency_id, company_id, as_of_date=None, required=False) — the most recent rate on or before as_of_date (defaults to today). Rates carry forward only: a date earlier than every rate on file has no answer. Returns 1.0 for the company’s own currency. When no rate answers it returns None, or raises UserError (naming the earliest rate on file, if any) when required=True. It never substitutes 1.0 for a missing rate.
  • await CurrencyRate.convert(amount, from_currency_id, to_currency_id, company_id, as_of_date=None, required=True) — convert an amount between two currencies, going through the company currency (amount * from_rate / to_rate). Returns amount unchanged when source and target match. With the default required=True a missing rate raises UserError; with required=False it returns None when either rate is missing. Raises UserError if the target rate is zero.

Pass required=True for anything that books or values money (documents, payments, revaluation). Use required=False only where a missing rate must degrade instead of stopping, such as a list total, and handle the None.

CurrencyRate = get_model("CurrencyRate")
rate = await CurrencyRate.get_rate(eur.id, company.id, as_of_date=date(2026, 6, 26))
amount_usd = await CurrencyRate.convert(100.0, eur.id, usd.id, company.id)

A Monetary field stores a value as NUMERIC and takes its display precision from a related currency via currency_field:

amount = Monetary(currency_field="currency") # precision & symbol come from `currency.rounding`
currency = ManyToOne("Currency", related_name="...", on_delete="RESTRICT",
required=True, default=lambda self: get_company_currency(self))

The currency must always have an answer — required, defaulted, calculated or derived — or the amount renders as a bare number; see Monetary.

Monetary itself does not convert — it just stores and formats one amount in one currency. Cross-currency arithmetic (e.g. a foreign-currency invoice posted to a company-currency ledger) goes through CurrencyRate.convert / get_rate. Use round_float for sums and comparisons of monetary values. It rounds half away from zero on the decimal number a float stands for — read to the 15 significant digits a double carries — so a tax of exactly 127.095 rounds to 127.10 even though 1694.6 * 0.075 computes as 127.09499999999998. Round to the currency’s own step (rounding=currency.rounding), never a hard-coded two decimals: a dinar has three, a yen none.

“Is this invoice settled”, “is anything left on this line”, “do these two amounts agree” are one question: does the amount round to zero in its currency — is it under half that currency’s smallest unit? fullfinity.engine.utils answers it, and every accounting screen (payment status, open items, aged balances, statements, follow-ups, bank matching) asks it the same way, so they cannot disagree:

from fullfinity.engine.utils import money_is_zero, money_step, round_money
money_is_zero(0.004, bhd) # False — 4 fils are owed (BHD has three decimals)
money_is_zero(0.004, usd) # True — under half a cent
money_is_zero(0.4, jpy) # True — under half a yen
round_money(10.0049, bhd) # 10.005 — for stating an amount, e.g. in a message
money_step(None) # 0.01 — the fallback when no currency is known

Pass the currency the amount is stated in: a journal item’s residual is in the company’s currency, a document’s total_due in the document’s. Never compare money against a literal 0.005 or 0.01, and never call is_zero(amount) without a precision — both mean “two decimals” and are wrong for every other currency. (is_zero stays for non-money values: state the precision, is_zero(share, digits=6).)

For a record filter, a journal item’s stored reconciled flag is this answer for its residual, so filter open items with Q(reconciled=False) rather than a residual threshold. ./fullfinity-server check --only money-tolerance fails on a new fixed tolerance.

A payment provider that takes integers in the currency’s minor unit converts with to_minor_units(amount, currency) / from_minor_units(minor, currency), which follow the currency’s own decimals (money_digits: cents, fils, whole yen) — never a hard-coded * 100. Where a provider documents its own table of decimals that differs from the currency’s (some treat a currency as whole units that ISO gives two decimals), that provider’s table is the authority for what it is sent.

Any model with priced lines — an order, a bill, a custom document type — gets its line figures from the Tax model (Invoicing app). Never multiply a price by a rate yourself: with a price-inclusive tax the entered price already holds the tax, and adding it again overcharges by exactly the tax.

  • await Tax.compute_line(taxes, quantity, unit_price, discount=0.0, currency=None) returns the line’s rounded {subtotal, tax, total}. It is the one answer every shipped line type gives (sales, purchase, invoices, rental, repair, field service, subscriptions, the till), so an invoice raised from your document carries the same figures. Rounding uses currency.rounding and anchors on the price as entered: a 9.99 shelf price with tax included totals 9.99. fraction taxes only part of the net (what is left after a document-level discount); from_net=True says the price is already net of tax.
  • await Tax.split_tax(taxes, net, tax, currency=None) splits a line’s tax over its taxes and their accounts, each part rounded so they add up to tax exactly. Use it to post or print a line’s tax by account.
  • await Tax.compute_breakdown([(taxes, net, tax), ...], currency=None) groups a document’s tax into the rows a form, portal page or PDF shows ([{name, amount, currency}]). Split taxes such as India’s CGST/SGST appear as separate rows, and the rows add up to the document’s total tax.
  • await Tax.price_for_net(taxes, net, currency=None) is the inverse: the price to enter so a line nets to net.

A document’s totals are the sums of its lines’ stored figures — don’t recompute tax at the document level.

@Model.calculate("quantity", "unit_price", "discount", "taxes", "currency")
async def compute_amounts(self):
Tax = get_model("Tax")
for line in self:
amounts = await Tax.compute_line(
line.taxes, line.quantity, line.unit_price, line.discount, currency=line.currency
)
line.subtotal = amounts["subtotal"]
line.total = amounts["total"]

Every stored Datetime is naive UTC. Two helpers on the engine.base star import keep your code in that shape, and check --only datetime fails the build on the alternatives:

  • utc_now() — the current time as naive UTC, to store or to compare against a column. Never datetime.now(): that is naive local time, wrong by the server’s UTC offset.
  • epoch_seconds(dt) — a datetime as Unix seconds (a token’s exp, an API’s start), reading a naive value as UTC. Never dt.timestamp(): it reads a naive value as local time, so a token built from utc_now() comes out expired, or hours too long, on any server not set to UTC.

Both mistakes look correct on a UTC machine, which is why they are gated rather than advised.

Which day it is: D('today') and company_today()

Section titled “Which day it is: D('today') and company_today()”

An instant is UTC; a date — what a document is dated, what is due or overdue — is the company’s day. Each Company has a time zone (on its form; a new company takes its creator’s). Two things to know, and they cover almost everything:

You needWrite
To compare a field with today — a search filter, a view’s filter, a visible:/readonly: rule, a _controlled_edits freeze, records.filtered(...), a job’s queryQ(due_date__lt=D('today'))
Today’s date as a value — a document’s date, a default, a computationawait company_today(record.company_id)

Both mean the same day: the record’s company’s today — or, for a record (or a model) with no company, the day of the company being acted for (the user’s current company; in a scheduled job, the main company unless the code acts for another with as_company). A company with no time zone set is on UTC.

So a job that runs for every company filters exactly as a single-company one would, with no loop over companies — each row is judged on its own company’s day:

due = await Subscription.filter(Q(state="Active") & Q(next_invoice_date__lte=D("today"))).all()

and a document’s date default is default=lambda self: company_today() (the company being acted for). D() takes every form listed under Dynamic Date Helper (D('today', days=-30), D('start_of_month', -1), …) and is a comparison (=, !=, <, <=, >, >=).

Never date.today() (the server’s date — UTC on a Cloud node) or utc_now().date(): an invoice raised on a New York evening was dated tomorrow by either, one raised before dawn in Dubai yesterday — at a month’s end, in the wrong tax period. A core test (test_company_today_gate) refuses new uses in app code — found in the syntax tree, so an alias (from datetime import date as _date) does not hide one; the ones that predate it are listed there and may only shrink.

In a test, move the clock every one of these reads with self.move_clock(days=31):

with self.move_clock(days=31):
await Contract.run_renewal_reminders() # as the nightly job sees it a month on

Patching one module’s company_today moves that module only — a query’s D() would still read the real day, and the test would quietly check nothing.

Working with timestamps (rarer): await company_now(company) is the wall-clock time where the company is; await company_day_start(day, company) the instant (UTC) a day begins there — its midnight, for a Datetime (“starts today”; datetime.combine(day, time.min) is UTC’s midnight, 7pm the evening before in New York); await company_date(moment, company) the company’s date of an instant (moment.date() is the UTC date). company is a Company or its id, by default the company being acted for.

modules/core/models/attachment.py defines Attachment — the single model behind every uploaded file. Files are content-addressed: the SHA-256 checksum of the bytes is both the dedup key and the on-disk filename.

  • Filestore layout — bytes are stored under <store_id>/ab/cd/<checksum>, fanned out by the first two byte-pairs of the checksum. The leading <store_id> is a per-database identity minted when the database is created, cloned or restored, not the database name, so a renamed or restored database keeps its files (a database created before these ids existed uses its name). Two records with identical content share one stored file. That key is relative, and it is the same string whether the backend is local disk (a path under FILESTORE_PATH) or an S3-compatible bucket (an object key) — which is why switching between them is a copy of the files and not a database migration. See Configuration.

  • SHA-256 dedup — on create/update, base64 content is decoded, hashed, written under its checksum, and the base64 column is cleared (it is never stored in the row).

  • Ref-counted, deferred delete — deleting an Attachment removes the stored file only if no other row references the same checksum, so dedup is safe. The removal happens after the transaction commits, not during it: the delete queues the checksum, and a sweep reclaims the bytes shortly afterwards. Two reasons, and both matter to you:

    • It is atomic. The queue entry is written in the same transaction as the delete, so a rollback takes it with it and the bytes are never touched. Unlinking inline meant a transaction that failed after the delete left a live row whose file was already destroyed.
    • It keeps storage off the request path. With attachments in object storage, unlinking is a network round trip; deferring it means deleting a record with many files does not wait on it, and a storage outage cannot fail the delete.

    So immediately after deleting an attachment the file may still be present. Anything asserting otherwise — a test, a cleanup script — should run the sweep first. The sweep re-checks that nothing references the checksum at the moment it deletes, so a byte-identical file uploaded in between is safe.

  • Cloned databases share, never delete — a database cloned from another reads its source’s files, so a clone dropping an inherited attachment removes its own row and leaves the bytes where its source and its siblings still see them.

class Attachment(Model):
_verbose_name = "Attachment"
name = Char(max_length=255, required=True)
checksum = Char(max_length=64, index=True)
filepath = Char(max_length=1024)
is_public = Boolean(default=False)
mimetype = Char(max_length=255)
file_size = Integer()
model = Char(max_length=255) # owning model name
record = Integer() # owning record id
field = Char(max_length=255) # owning field name
base64 = Text() # input channel only — cleared on store
url = Char(store=False, calculate="get_url")

Two classmethods cover the common targeted-file cases (one file bound to a record’s field):

  • await Attachment.create_from_file(file_content, filename, model=None, record=None, field=None, is_public=False) — decode base64 file_content, hash, store the bytes under that checksum, and create the row. When model/record/field are all given, any existing attachment on that field is deleted first (so it replaces rather than accumulates). Returns the new attachment’s id.
  • await Attachment.remove_from_attachment(model=None, record=None, field=None) — remove the attachment bound to that field; deletes the physical file when it is the last reference. Requires all three arguments (raises UserError otherwise).
Attachment = get_model("Attachment")
att_id = await Attachment.create_from_file(b64_string, "invoice.pdf",
model="FinancialDocument", record=doc.id, field="pdf")
await Attachment.remove_from_attachment(model="FinancialDocument", record=doc.id, field="pdf")

The route is GET /filestore/{action}/{attachment_id} where action is view (serves inline) or download (serves as an attachment download). A scriptable type — HTML, SVG, XML, JavaScript — is always served as a download with a sandboxing Content-Security-Policy, whichever action was asked for: its type is guessed from the uploader’s own filename, and rendered on the application’s origin it would run with the viewer’s session. An <img> ignores the disposition, so an SVG still draws where it is embedded. Access is granted when the attachment is public, the URL carries a valid signed expires/sig pair (valid only on the database that signed it), or the authenticated user can access the owning parent record. The computed url field on an attachment points at /filestore/view/<id>; signed, time-limited URLs come from GET /api/files/{attachment_id}/url. The route is the same address on either storage backend — with a bucket it answers with a short-lived redirect straight to the object rather than serving the bytes through the application, so the filename, inline/download choice and caching policy are carried into that redirect.

A model field of type File stores its value as an attachment id — it converts uploaded file data into an Attachment and clears the attachment when the field is cleared. So a File field is the model-level handle; Attachment is the storage behind it. (Binary stores raw bytes inline in the row instead, for small blobs that should live with the record.)

Geo models — modules/core/models/localization.py

Section titled “Geo models — modules/core/models/localization.py”
class Country(Model):
_verbose_name = "Country"
name = Char(max_length=255, index=True, required=True)
currency = ManyToOne("Currency", related_name="countries", on_delete="SET NULL")
code = Char(max_length=10)
flag = File(description="Flag")
class CountryState(Model):
_verbose_name = "State"
name = Char(max_length=255, index=True)
country = ManyToOne("Country", related_name="states", on_delete="CASCADE")
code = Char(max_length=10)
class CountryGroup(Model):
_verbose_name = "Country Group"
name = Char(max_length=255, index=True)
countries = ManyToMany("Country", related_name="groups", through="FKCountryGroup")
  • Country links to its default Currency (SET NULL), carries an ISO code and a flag (a File field, i.e. an attachment).
  • CountryState is the country’s subdivisions (CASCADE from country).
  • CountryGroup groups countries via an explicit ManyToMany through FKCountryGroup — handy for “EU”, “GCC”, tax zones, etc.

Language & locale formats — modules/core/models/language.py

Section titled “Language & locale formats — modules/core/models/language.py”

Language (table syslanguage) holds both the translation enablement and the locale display formats. The source language is "en" and cannot be modified; activating a language loads its i18n/*.json translations.

class Language(Model):
_verbose_name = "Language"
code = Char(max_length=10, index=True, required=True)
name = Char(max_length=255, required=True)
active = Boolean(default=False) # languages must be explicitly enabled
direction = Selection(choices=["ltr", "rtl"], default="ltr") # external standard tokens
# Locale formats
date_format = Char(max_length=20, default="DD/MM/YYYY", required=True)
time_format = Char(max_length=20, default="HH:mm")
decimal_separator = Char(max_length=5, default=".")
thousands_separator = Char(max_length=5, default=",")

The locale fields — date_format, time_format, decimal_separator, thousands_separator, and direction (RTL support) — drive how dates, times, and numbers are rendered for a user on that language. direction keeps the genuine external standard tokens ltr/rtl (an exception to the human-readable-Selection rule, like ISO weekday numbers). For the translation pipeline itself (English-text-as-key, generation, reload), see the Translations guide.