Skip to content
ERPForAll DocsDevelopment

    Exact units of measure

    The uom addon (erp-addon-uom) provides the internal UoM model (uom.uom), decimal precision (decimal.precision with “Product Unit”), access rules (security/ir.access.csv), and default seed data (data/uom_data.xml) for 30 standard units across dimensions (Units, Working Time, Length, Surface, Volume, Weight, and Energy).

    Installation adds uom.group_uom, an independently labelled feature classification with no implied groups or ACL grant. UoM extends res.groups._get_light_group_xmlids through ordinary super dispatch, preserving other addons’ entries. Do not replace the base list or use light-group classification as model authority. Existing base.group_user read and base.group_system CRUD access remain unchanged.

    The group’s XML identity and edited label survive ordinary upgrade through its noupdate seed. A separate, data-callable-only reclassification step runs after that XML identity is published, on install and upgrade. It removes the regular-user marker that group creation would otherwise assign before the group is identifiable as light. This helper is not exposed over RPC. No automatic user membership or UI feature switch is installed.

    conversion::Unit::new(id, root, factor) validates positive identifiers and a nonzero decimal factor. Model callers must resolve these values with caller read access; this value grants no database authority. Negative nonzero factors remain supported. Quantity conversion multiplies by the source factor and divides by the target factor; price conversion uses the inverse ratio. Both check matching roots before zero or identical-unit shortcuts.

    use erp_addon_uom::conversion::{Unit, quantity_exact, quantity_rounded};
    use erp_sdk::{Decimal, money::{Increment, RoundingMode}};
    let units = Unit::new(1, 1, Decimal::ONE)?;
    let dozen = Unit::new(2, 1, Decimal::from(12))?;
    let exact = quantity_exact(&units, &dozen, Decimal::ONE)?;
    assert_eq!(exact.to_string(), "1/12");
    let rounded = quantity_rounded(&units, &dozen, Decimal::ONE,
    &Increment::from_places(2)?, RoundingMode::AwayFromZero)?;
    assert_eq!(rounded.to_string(), "0.09");
    # Ok::<(), erp_addon_uom::error::UomError>(())

    quantity_exact and price_exact return bounded ExactRatio values. Apply a named rounding boundary explicitly with quantity_rounded. exact_decimal returns a decimal only after an exact ratio round trip; storage callers must reject an unrepresentable result. rpc_exact returns a decimal or canonical numerator/denominator strings, retaining recurring and large exact results.

    precision_compare rounds each operand independently HALF-UP. It does not round the difference. precision_is_zero tests the rounded operand. Packaging converts one pack with UP at the requested precision, rounds the pack count to an integer using the supplied mode, then multiplies. The same-unit packaging case preserves the original quantity after root validation.

    UomError distinguishes invalid identities, zero factors, incompatible roots, rounded-zero packs and bounded-number errors. Converting it to a framework error preserves its source and reports Validation. Callers must handle failure explicitly; cross-root conversion has no input-value fallback.

    Generic dynamic CRUD converts decimal values before addon create/write hooks. Unrounded numeric fields now reject digit loss with a Validation error whose source is erp_fields::convert::DecimalPrecisionExceeded; the source exposes the qualified field, original input display and maximum digit limit. Plain text is parsed exactly; scientific mantissas are limited to 28 significant digits and checked exponent shifts. Parser input is bounded to 4096 bytes. Longer inputs use the explicit diagnostic marker <decimal input exceeds 4096 bytes> rather than copying their full text. Representable fixed-scale and monetary inputs retain their declared rounding boundaries. A supplied binary float can preserve only the decimal text that float denotes. Pass decimal strings when exact source digits matter.

    The reference boundary is specified by ADR 0116 and the publication/recovery contract by ADR 0144. The implementation checkpoint is in place and acceptance is not complete; do not treat fixture coverage as delivered stock integration. Product barcode/link rules belong to the product addon; M7 owns real stock consumers and their historical backfill. Product performance evidence is deferred to milestone end under ADR 0065.

    The user-guide source docs/user/uom.md documents installed defaults, the light-group classification and backend access rights. Product integration and transactional stock consumers remain separate work.

    Installed views, actions and configuration menu

    Section titled “Installed views, actions and configuration menu”

    Installation publishes standard UI views and window action records in views/uom_views.xml:

    • List view (uom.uom_uom_view_list): renders sequence, name, relative_factor, and reference unit (relative_uom_id).
    • Form view (uom.uom_uom_view_form): defines record-mode sheet with details group for name, relative_factor, and relative_uom_id.
    • Search view (uom.uom_uom_view_search): allows search on unit name and provides an archived filter domain [('active', '=', False)].
    • Window action (uom.uom_uom_action_list): ir.actions.act_window for model uom.uom with view modes list,form linked to uom_uom_view_list and uom_uom_view_search.
    • Action views: sequences 10 (list) and 20 (form) via ir.actions.act_window.view.
    • Settings menu (menu_uom_form_action): places the “Units of Measure” menu entry under base.settings_menu restricted to base.group_system with sequence 35.

    Access rules in security/ir.access.csv grant read access (r) to base.group_user and full CRUD access (crud) to base.group_system. Feature group uom.group_uom in security/uom_security.xml provides light-group classification without granting direct model permissions.

    The model is uom.uom, declared by models::Uom. Its required translated name, active flag, direct relative_uom_id, inverse related_uom_ids and exact relative_factor describe the tree. Roots have relative factor one; all relative factors are nonzero. Stored factor and sequence are computed, and the framework maintains parent_path. Formatted display names use formatted_display_name in the environment context.

    models::load_unit(env, tx, id) loads caller-readable ancestry with explicit depth and path-size bounds, validates parent links and original relative-factor products, and checks stored factors. It returns no implicit root or factor for a missing, malformed or inaccessible record. Conversions use transaction-owned state without a global unit cache. Reading a value as system does not grant a later caller permission to use it.

    Native dispatch exposes _compute_quantity(Decimal, to_unit) and _compute_price(Decimal, to_unit) as exact-ratio services. _check_qty accepts quantity, destination id and a rounding-method name. round(Decimal), compare(Decimal, Decimal) and is_zero(Decimal) resolve current Product Unit precision through the base addon’s precision service. round defaults HALF-UP; use round_with(Decimal, String) for an explicit named mode. The pure precision_round API also accepts an explicit mode.

    convert is the registered read-only RPC method on one source unit. Its named arguments are quantity (a strict decimal string), to_unit (integer id), exact (default false) and rounding_method (default UP). Strict strings use the shared money parser: at most 64 bytes, optional minus, digits and optional fractional digits; scientific notation, binary-float transport and malformed strings are refused. Generic CRUD field admission described above has its separate decimal and scientific grammar.

    A rounded response contains value (decimal), rounding (the chosen name) and digits (current Product Unit digits). An exact request returns a representable decimal or an object containing numerator and denominator as canonical decimal strings. Supported names are HALF-UP, HALF-DOWN, HALF-EVEN, UP, DOWN, CEILING and FLOOR. Names longer than nine bytes and unknown names are errors, including on exact requests. Both source and destination, including their ancestors, must be readable even for zero amounts or equal units.

    The absolute factor is maintained by the model: create and nonempty write reject a supplied factor key, including a correct-looking value. Set relative_factor and relative_uom_id instead. Empty writes remain no-ops.

    Create and write use operation-owned savepoints and flush stored computations before success. Nonrepresentable descendant factors reject the whole mutation; error sources distinguish numeric limits. Follow the ORM’s failed-mutation transaction rules and roll back the surrounding unit of work after failure. The savepoint does not authorize replaying writes or committing a failed unit of work. No committed-reference protection is implied by these numeric guards.

    The repository fact inventory and provenance note at docs/design/uom-seed-reconstruction.md record the stable XML IDs, existing labels, archive flags, direct-parent links and finite decimal ratios. Those compatibility ratios include rounded physical conversions and an eight-hour working day. Do not silently replace them with a more precise physical constant: installed records may already be referenced. The authoring command reads only the inventory; semantic comparison against historical XML is a separate verification step. From the repository root:

    Terminal window
    python3 scripts/uom-seed-reconstruct.py \
    docs/design/evidence/uom-seed-reconstruction/compatibility-facts.json \
    addons/uom/data/uom_data.xml

    references::register(env, tx, ids) validates a bounded batch, authorizes every requested unit and its ancestry, records permanent first use and returns immutable ReferencedUnit identities in ascending unique unit order. Use those returned root/factor values for the business calculation, then write the business reference in the same transaction. A value obtained before registration is not an alternative authority. Whole-transaction or enclosing-savepoint rollback removes new markers together with the business write. Cancellation/deletion of a committed business document never removes a marker.

    use erp_sdk::prelude::*;
    use erp_addon_uom::references;
    async fn register_for_document(env: &Env, tx: &mut Transaction, ids: &[i64]) -> Result<()> {
    let units = references::register(env, tx, ids).await?;
    for unit in units {
    // The consuming addon uses these identities for its calculation and writes
    // its document in this transaction, before the caller commits it.
    let _identity = (unit.id(), unit.root(), unit.factor());
    }
    Ok(())
    }

    The native API accepts at most 4096 input identities before deduplication and 4096 graph identities; ancestry is limited to 256 levels. Empty input is a zero-SQL no-op. Invalid identities, graph limits, missing state and permission failures are errors. Environment and transaction must share the ORM lineage. Registration is native only; it is not a JSON-2 method.

    Snapshot-visible markers use compatible FOR KEY SHARE locks inside the controlled SQL function, with no singleton update. First use and topology mutations advance the database fence before authoritative graph reads. Consumers acquire this boundary after ADR 0079 class 0 and before classes 1–5. Late discovery of an earlier lock aborts the whole operation. 40001/40P01 require the framework’s whole-unit retry; 55P03 surfaces as Lock here. Never retry inside the old snapshot.

    Used units reject actual ratio or parent changes. An unused ancestor may change only when every used descendant retains its root and exact factor; an equivalent ancestor reparent can therefore be allowed. Name, sequence and archive edits retain normal access rules. Complete cascading delete closures include archived/hidden units; diagnostics do not disclose hidden names. A protected catalog alias wins over an exempt alias. _unprotected_uom_xml_ids is a native super-dispatched policy for catalog seed deletion and cannot erase transaction-reference protection.

    The internal models have no ordinary mutation API or ACL grant. Schema-owner lifecycle initializes the singleton; runtime requests never repair missing state. Future consumers must register historical unit identities in a reviewed upgrade backfill before activating their write path. A newly empty marker table is not proof that no historical consumer exists.

    A stock line stores its quantity in the product’s unit, computed with the factors and the Product Unit digits it was written with. In the plan phase of the stock unit (after the ADR 0079 prelude, before quant keys) capture them:

    let snapshot = erp_addon_uom::stock::capture(&env, &mut tx, line_unit, product_unit).await?;
    let product_qty = snapshot.product_quantity(line_qty)?; // HALF-UP, one rounding
    let up = snapshot.line_to_product(line_qty, StockRounding::Up)?; // the rule is always named

    capture registers both units as used (their factors can no longer change) and refuses units of different roots before it writes anything. A value stored with a stock row is a ProductUnitSnapshot, which only capture (or ProductUnitSnapshot::new over registered units) can build; ProductUnitPreview is the same pure calculation over plain Units for previews and tests and must not be stored. Store source_factor, target_factor and digits on the row and declare the derived column with the builder, which accepts only lowercase column names:

    let expr = erp_addon_uom::stock::product_quantity_sql("qty", "source_factor", "target_factor", "digits")?;
    // CREATE TABLE ... product_qty numeric GENERATED ALWAYS AS (<expr>) STORED

    The expression is exact (integer quotient and remainder, ties away from zero), builtins only and IMMUTABLE. tests/stock_snapshot.rs compares it with product_quantity on 10,000 seeded rows plus near-tie rows. Rules the column must meet:

    • qty, both factors and digits are NOT NULL (a NULL input stores NULL), digits is an integer from 0 to 28, and factors are nonzero (a zero target is a division error).
    • Add the NaN check on qty that ADR 0079 D6.2 requires.
    • The identifiers are quoted by the builder; pass lowercase names.
    • Where the exact result does not fit a Decimal (coefficient above 96 bits) the Rust service returns a numeric error; SQL has no such bound, so keep stored quantities inside it.
    • A rule is always named: StockRounding::Up or HalfUp, never a default.

    Product 1.3 registers units referenced by templates, additional/extra packaging sets and packaging barcode rows through the existing reference service. Its post-upgrade backfill includes archived products. Stock snapshot registration continues independently. A catalog unit replacement does not alter a protected unit’s factor or parent; changing those properties still follows ADR 0116.

    The native _is_uom_feature_enabled extension on res.groups reads the designated superuser’s effective uom.group_uom membership. It does not grant permissions or add automatic membership. See the product guide’s packaging section for the native availability methods, conditional warning and context-dependent barcode relation.