When working with raw materials in Dynamics 365 Finance & Operations (D365 F&O), it’s common to encounter situations where the inventory is stored in one unit (like Liters or Packs), but needs to be viewed or calculated in Kilograms (KG) for costing, reporting, or analysis.
In this blog, we’ll walk through a practical X++ code snippet that demonstrates how to convert available inventory (AvailPhysical) into KG using D365’s standard Unit of Measure (UOM) conversion.
π Business Scenario
Suppose you have a chemical item stored in Liters, but the production or costing team needs to see its available inventory in KG.
You’ll need to:
-
Fetch the item’s
AvailPhysical
from theInventSum
table. -
Get the current unit of measure (UOM) for the item.
-
Convert that quantity into KG, based on predefined unit conversion.
π» X++ Code – Inventory Conversion to KG
Here’s the code block that does exactly that:
//******************** Avail Physical as per KG Unit conversion ********************
select sum(AvailPhysical) from inventSum
where inventSum.ItemId == this.ItemId;
select firstonly inventTable
where inventTable.ItemId == this.ItemId;
if (inventTable)
{
// Get the item's current inventory unit and the target 'KG' unit
UnitOfMeasure fromUOM = UnitOfMeasure::findBySymbol(inventTable.inventUnitId());
UnitOfMeasure toUOM = UnitOfMeasure::findBySymbol('KG'); // Change symbol if your UOM setup differs
if (fromUOM && toUOM)
{
// Find the conversion factor between item's unit and KG for the product
UnitOfMeasureConversion conversion = UnitOfMeasureConversion::findByConversion(
fromUOM.RecId,
toUOM.RecId,
inventTable.Product
);
// If a valid conversion factor is found, apply it
if (conversion)
{
this.AvailableInventory = inventSum.AvailPhysical * conversion.Factor;
}
else
{
// Fallback if no conversion found
this.AvailableInventory = inventSum.AvailPhysical;
}
}
else
{
// Fallback if UOMs are not found
this.AvailableInventory = inventSum.AvailPhysical;
}
}
else
{
// Fallback if item not found
this.AvailableInventory = inventSum.AvailPhysical;
}
π Explanation
πΈ Step 1: Fetch Available Inventory
The first select
statement grabs the total AvailPhysical
quantity from the InventSum
table for a given item.
πΈ Step 2: Get Item’s Inventory Unit
The InventTable
record gives you the default inventory unit (inventUnitId
) for the item.
πΈ Step 3: Get Unit of Measure Records
We retrieve both:
-
fromUOM
: The item's current unit (e.g., Liter) -
toUOM
: The target unit, in this case'KG'
πΈ Step 4: Apply Conversion Factor
Using the UnitOfMeasureConversion
class, we get the factor needed to convert from one unit to another — considering the specific product context.
Example: If 1 Liter = 0.9 KG for the product, and
AvailPhysical = 100
, the result will be90 KG
.
πΈ Step 5: Handle Missing Data Gracefully
Fallback logic ensures the system doesn’t break if:
-
Conversion is missing
-
UOMs are not found
-
Item is invalid
Comments
Post a Comment