Correct multilevel bill-of-materials calculation scales quantities by the output denominator along every valid assembly path, then combines endpoints with matching units and explosion boundaries. Neither deduplicating material identities nor silently switching to the latest child recipe is sufficient. This article addresses traceable gross-demand calculation for manufacturing data, integration and analytics teams, rather than complete materials planning or production scheduling.
The output is gross demand, not a purchase order or actual cost
A bill of materials, or BOM, specifies components and quantities required to manufacture an item. Components may themselves have BOMs. Odoo 18’s multilevel documentation separates subassembly production from replenishment and describes dependencies across manufacturing levels.[1] Finding all descendants is therefore only the starting point. The calculation also needs to decide which levels will be manufactured and which subassemblies will be issued from stock or purchased as complete items.
The output here is theoretical gross demand for a specific order under a fixed structure, with an optional materials estimate. It does not deduct available inventory, incoming purchases or reservations, or schedule lead times, minimum order quantities, production batches or losses. Gross demand is not automatically a purchasing recommendation. A materials estimate is not actual manufacturing cost, which also requires actual issues and returns, labor, operations, overhead and accounting definitions.
Inputs are authorized read-only order quantities, BOM headers and lines, unit conversions and an explosion policy. The example follows PostgreSQL 18 recursive-query and numeric semantics and provides an implementable data contract and procedure. Arithmetic was independently checked; no performance experiment on a target database was run. ERP documentation supplies public modeling examples, not evidence that an IDENIFE product includes these fields or manufacturing-planning capabilities.
The organizational hierarchy rollup method already distinguished node deduplication from path quantities. This article addresses conditions omitted from its simplified materials counterexample: a BOM need not describe one output unit, child references must identify a specific revision, expansion can stop at a subassembly, and quantity precision must align with valuation boundaries. These conditions define the query’s meaning; DISTINCT is not a repair to apply after a total looks wrong.
Represent output denominators, line identity and child revisions explicitly
A useful header contract contains tenant_id, bom_id, parent_item, output_qty, output_uom, release_state and a content revision. Within a tenant, bom_id identifies an immutable approved BOM. output_qty specifies the output represented by that recipe and must be positive with an explicit unit. If a recipe makes twenty finished units, its component quantities are not inherently per-unit requirements.
Each line needs at least bom_id, line_id, component_item, component_qty, component_uom, child_bom_id and an explosion policy. line_id distinguishes assembly positions: the same material can legitimately occur in two positions, so parent item plus child item is not a sufficient unique key. Reimporting the same source line is a different case and must be recognized. ERPNext also distinguishes legitimate repeated-item lines from explosion settings.[2]
A child reference should point to an approved child_bom_id, not select the “latest default” by component name during execution. When a component has no child BOM, distinguish an intentional purchasing endpoint from an item that should be manufactured but lacks a recipe. The former is a valid termination; the latter is missing evidence. Treating every item without descendants as a leaf disguises incomplete data as usable output.
Unit rules record source and target units, applicable item, conversion numerator and denominator, and rule revision. Convert parent demand into the header’s output unit, then convert component demand into its bound child BOM’s output unit or final stock unit. Kilograms and grams can have a defined general relationship; a component’s “box” requires item and packaging conditions. Unit names alone do not establish a universal multiplier.
Freeze tenant, root BOM, order quantity, all child references, unit-rule revision and explosion-policy revision for each run, and assign a run identifier. A structural owner confirms recipes and manufacturing boundaries, a data owner confirms source rows and types, and a business owner approves the output’s use. Retain the relationship snapshot and quantities: a final aggregate alone cannot explain why a later run differs.
Expand ten finished units into 110 components
Construct order O1 for ten units of P. BOM P1 describes output of twenty P: line 10 consumes thirty A, line 20 consumes twenty B and line 30 consumes forty X. A binds to A1 and B to B1. A1 makes five A using twenty X and 500 grams of adhesive G. B1 makes two B using six X and 600 grams of G. X is a purchased endpoint and G is aggregated in kilograms. All BOMs are approved and losses are excluded.
The root scaling factor is 10/20=0.5, giving fifteen A, ten B and twenty direct X. The A branch scales by 15/5=3, contributing sixty X and 1,500 grams of G. The B branch scales by 10/2=5, contributing thirty X and 3,000 grams of G. Endpoint totals are X=20+60+30=110 and G=4,500 grams=4.5 kilograms.
The path worksheet retains three X contributions: O1/P1/30 contributes twenty; the X line under O1/P1/10/A1 contributes sixty; and the X line under O1/P1/20/B1 contributes thirty. The two G paths contribute 1.5 and 3 kilograms. An implementation uses actual line identifiers, not merely the letter X, in the path key. “X line” is shorthand here, not permission to merge component-line identities across A1 and B1.
If an approved single materials-price snapshot values X at RMB 2 each and G at RMB 10 per kilogram, the estimate is 110×2+4.5×10=RMB 265, or RMB 26.5 per finished unit. These are constructed prices with one currency and a common valuation boundary, not supplier quotations. A and B are not additionally valued as subassemblies because their contents are already included. Adding their prices would count embedded materials again.
An independent calculation must retain every parent’s output denominator. Multiplying P1’s line quantities directly by ten would produce A=300, B=200 and direct X=400, treating a twenty-unit recipe as a one-unit recipe. Even with the correct root factor, omitting division by five on A or by two on B inflates lower-level quantities. RMB 265 alone does not localize the fault; check fifteen, ten and twenty at the first level and every downstream contribution.
Carry quantity and termination reasons through recursion
PostgreSQL 18’s recursive example uses UNION ALL to retain paths, multiplies along edges and sums by component.[3] Under this contract, a step is more precisely: child demand = current parent demand / current BOM output quantity × line component quantity × unit-conversion factor. Parent demand and output quantity must first share a unit. The conversion factor handles only the component unit’s transition to the next level or endpoint, without converting twice.
The initial state contains order O1, item P, BOM P1, ten units of demand, an empty line path and an initial visited chain. Each step reads valid lines of that BOM, calculates child demand, and appends the line identifier and child revision reference. Recurse when expansion is permitted and child_bom_id is valid. Emit approved purchasing or stock-issue endpoints with their termination reason. Emit faults separately rather than mixing them into normal endpoints.
A concrete intermediate record contains run identifier, root order, parent BOM, parent quantity and unit, line identifier, output denominator, multiplier, child BOM, child quantity, path, depth and state. Produce path results before aggregating by root order, material, endpoint stock unit and any required lot or specification. Different units or noninterchangeable specifications must not collapse into one row merely because item names match.
Use numeric for quantities rather than prematurely casting ratios to integers. PostgreSQL supports exact decimal calculations, but a declared scale rounds values to that scale.[4] Exact types do not retain recurring decimals indefinitely. Define intermediate precision, allowed error and final rounding points; preserve original quantities, numerators, denominators and conversion evidence instead of retaining only rounded outputs.
G becomes exactly 4.5 kilograms in the example. Rounding each path upward to whole kilograms first changes 1.5 and 3 into 2 and 3, totaling 5. That may implement a particular issue-packaging rule, but it is not the original theoretical gross demand. If procurement requires whole bags, report a separate purchasing-pack result and specify whether rounding follows consolidation by order, warehouse or supplier. Do not overwrite 4.5.
Cycle checks apply to complete BOM identities on the current path. Revisiting the same BOM through another legitimate path is not a cycle. PostgreSQL supports CYCLE or explicit path arrays for detecting repeated visits.[3] Any cycle, missing revision, unit conflict or resource truncation makes the complete run incomplete. Dropping a faulty branch and returning a plausible subtotal would falsely imply that material demand is fully known.
Stopping at a subassembly and changing a child revision require different evidence
Keep the ten-unit order and original structure but explicitly change the policy: B is purchased or issued as a complete subassembly, so B1 is not expanded; A remains manufactured. The result becomes eighty X from the A branch plus direct usage, 1.5 kilograms of G, and ten B. ERPNext’s Do Not Explode documentation illustrates a subassembly stopping boundary.[2] It is a modeling example here; the selected configuration’s actual behavior still needs verification.
If a separately approved materials-estimate price for B is RMB 8 each, the estimate becomes 80×2+1.5×10+10×8=RMB 255. Comparing 255 with 265 covers only materials under these assumptions. It does not prove buying B is cheaper because transport, processing, lead time, quality and inventory risks remain outside the calculation. Nor may the same purchasing scope contain both ten B and their thirty X and three kilograms of G.
Restore full explosion and create A2 only: twenty X per five A becomes twenty-five, while G remains 500 grams. A new root revision P2 explicitly references A2 and otherwise preserves the original conditions. For ten P, the A branch now needs seventy-five X; total X is 20+75+30=125, G remains 4.5 kilograms, and materials value becomes RMB 295. Relative to P1, the difference is fifteen X and RMB 30.
An old order bound to P1 and A1 should still reproduce 110 X and RMB 265. ERPNext’s multilevel maintenance documentation warns that changing a lower-level BOM does not automatically update a parent still referencing the old child BOM.[5] A revised subassembly and an order that actually selected the revised structure are separate pieces of evidence. The system’s current default cannot substitute for the order’s binding.
If the business approves changing an old order to P2, create a new calculation revision with the approval, old and new demand, and their difference. Then decide how purchasing and production should respond. If 110 X are already on order, new gross demand of 125 does not imply buying another 125. Incremental procurement also requires existing commitments and available inventory. This article stops at the gross-demand difference instead of turning a structural revision into an unchecked business write.
On-demand and pre-exploded calculations have different maintenance costs
Option one recursively reads fixed direct relationships on demand. It suits frequent revisions and manageable reachable structures, and directly preserves quantities and line paths at each step. Design basic indexes around tenant, bom_id and line_id, narrow to revisions reachable from the chosen root, and then expand. Repeated high-frequency requests repeat work; a short query is not evidence of a particular response time.
Option two precomputes quantities from one unit of a root product to endpoint materials, then multiplies by order quantity. It suits repeated use of the same revisions and policy with linear quantity rules. Under P1’s full explosion, each P needs eleven X and 0.45 kilograms of G. Under P1 with B stopped, each P needs eight X, 0.15 kilograms of G and one B. These results need different policy identities; a cache keyed only by root item is insufficient.
A pre-explosion key should cover root revision, reachable child revisions, unit rules, explosion policy and calculation-program version, with evidence linking aggregates back to contributing paths. Changing A1 to A2 requires locating affected new derived results, not just refreshing A itself. Old approved versions remain reproducible. Build a new derived version, validate control samples, then switch the read entry point. On failure, preserve the previous accepted version.
Per-unit coefficients have a clear limitation. Fixed inputs per production batch, minimum manufacturing batches, piecewise losses or intermediate rounding can break linear scaling. If starting a batch requires an additional 100 grams of adhesive, both one and ten finished units incur that amount once. Multiplying a one-unit result by ten counts the fixed component ten times. Retain a dedicated calculation step for such rules instead of forcing them into one coefficient.
For purely linear rules with identical revisions, units and policy, demand reaching the same child BOM can be aggregated before propagation to reduce repeated work, provided source contributions remain traceable. Path-specific stopping, lot or specification conditions invalidate that early merge. Compare update amplification, rebuilding, evidence storage and peak workload, rather than only a single warm-cache query.
Six failure tests must check both the result and blocking evidence
Test one covers denominators and units. Change A1’s output_qty to zero: expect an invalid-BOM error and no certified demand. Change G’s unit to an unregistered “drum”: expect an unknown conversion, not an assumed kilogram per drum. Evidence consists of the original header and line plus rule-match counts. After approving the denominator or factor, recheck X=110, G=4.5 and every contribution path.
Test two separates duplicate input from legitimate repeated lines. Replay P1 line 30: expect idempotent ingestion or an explicit duplicate rejection, not doubled direct X. Then add a genuinely different line_id consuming another forty X per twenty P at another approved assembly position. Ten finished units should now require 130 X. Source-row identity and business approval distinguish the cases; material DISTINCT must not remove the new position.
Test three covers revision mismatch. Keep P1 bound to A1 but change A’s default to A2. The old order must still return 110 X, while P2 returns 125. If both return 125, inspect whether recursion chooses defaults by item. Repair the explicit revision references, then test the old order, new order and repeated runs together to establish that bindings do not drift with default settings.
Test four covers stopping. The stop-B policy must return X=80, G=1.5 and B=10; full explosion must return X=110 and G=4.5 without an endpoint B. Inspect policy identity, endpoint reasons and whether B1 was visited. After correcting cache keys or filters, alternate the policies to detect contamination from whichever result was computed first.
Test five covers missing structures and cycles. Remove the referenced A1 target: expect a missing manufactured-recipe error, not an automatic purchasing leaf of fifteen A. Then create a path from A1 back to P1: expect retained cycle evidence and blocking of a complete result. Restore valid references and repeat. Legitimately reaching A1 through another assembly path must still accumulate; a global “already visited, skip it” set would incorrectly remove demand.
Test six covers resources and valuation. Set a test depth limit of one while A and B still have components: expect truncation, not completed direct-only usage. Change G’s price unit to per gram while retaining the per-kilogram numeric rate: expect rejection of the valuation contract. Inspect depth, unexpanded nodes, price units and price snapshot. Restore the agreed scope and price, then recalculate quantities and RMB 265, rather than merely checking that the query ends without an error.
Preserve path evidence and budget the calculation
An acyclic structure can still generate rapidly growing path counts through shared subassemblies. Capacity assessment needs reachable BOM count, valid-line count, maximum depth, expanded paths and endpoints, with measurements for cold caches, typical orders and the most complex approved structure. Set execution-time, memory and row budgets with cancellation. No universal safe threshold is supplied here; determine it from the environment and worst relevant workload.
Each result should retain run identity, input manifest, quantity definitions, state, exceptional paths, endpoint aggregates and calculation version. Distinguish complete results, deliberately restricted business scope and technical incompleteness. If permissions prevent reading a manufactured child BOM, report restricted coverage without revealing protected content or treating the missing branch as zero. Purchasing and costing users need the limitation visible.
Maintenance triggers include BOM revisions, unit changes, make-or-buy boundaries, calculation precision and price snapshots. Structural changes require quantity regression; a price-only change with unchanged structure requires valuation regression; combined changes require both. Compare inputs and paths before totals, rather than manually adjusting usage to make a total match. Frozen historical revisions remain intact; corrections create a new revision and an explicit relationship.
The reusable delivery card has six sections: order and approved purpose; root-to-child revision chain; output denominators and units; explosion and rounding policy; normal, revision, duplicate, missing-data and resource tests; and owners, retest dates and exit conditions. For this example, deliver the 110-X and 4.5-kilogram path worksheet, the separate stop-B result, and the P2 difference. Explaining why all three differ is the foundation for entrusting materials relationships to automated queries.
References
- [1] Odoo 18.0: Multilevel BoMs (accessed 2026-11-25)
- [2] ERPNext: Bill Of Materials, repeated item lines and Do Not Explode (online documentation, accessed 2026-11-25)
- [3] PostgreSQL 18: WITH Queries, recursion and cycle detection (accessed 2026-11-25)
- [4] PostgreSQL 18: Numeric Types (accessed 2026-11-25)
- [5] ERPNext: Managing Multi-level BOM (online documentation, accessed 2026-11-25)
