web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Answered

Get average unit cost of an Item using X++ in D365

(0) ShareShare
ReportReport
Posted on by 758

Hi Everyone,

Need urgent help on below issue

I am trying to fetch average unit cost of Item through X code which is available on below path,

Released products > Manage costs > Cost objects

Below code I found on one of the blogs, but somehow it doesn't give perfect result for all transactions.

 public static void main(Args _args)
    {     
        ItemId                          _itemId = "2108050";
        InventSum                       inventSum;
        Amount                          avgUnitCost;
        InventDim                       inventDim;
        InventDim                       inventDimFind;
        InventCostPriceCache            inventCostPriceCache;
        UnitOfMeasureConverter_Product  productUnitConverter;
        UnitOfMeasureRecId              fromUnitMeasureRecId; 
        UnitOfMeasureRecId              toUnitMeasureRecId;
        InventTable                     inventTable;

        Amount                          costPrice, convertValue;

        select firstonly * from inventSum where inventSum.ItemId == _itemId
            join inventDim;

        if(!inventSum.InventDimId)
        {
            inventDimFind = InventDim::findDim(inventDim);
            if(inventDimFind.inventDimId)
            {
                inventSum.InventDimId = inventDimFind.inventDimId;
            }
        }

        inventCostPriceCache = InventCostPriceCache::construct();

        inventTable = inventSum.inventTable();

        fromUnitMeasureRecId    =   UnitOfMeasure::findBySymbol(inventTable.salesUnitId()).RecId;
        toUnitMeasureRecId      =   UnitOfMeasure::findBySymbol(inventTable.inventUnitId()).RecId;

        productUnitConverter  =   UnitOfMeasureConverter_Product::construct();
        
        productUnitConverter.parmProduct(inventTable.Product);
        productUnitConverter.parmFromUnitOfMeasure(fromUnitMeasureRecId);
        productUnitConverter.parmToUnitOfMeasure(toUnitMeasureRecId);
        productUnitConverter.parmRoundAbsoluteValue(NoYes::Yes);
        productUnitConverter.parmApplyRounding(NoYes::Yes);

        costPrice       = inventCostPriceCache.costPricePcs(inventSum, inventDim);
        convertValue    = productUnitConverter.convertValue(1);

        info(strFmt("costPrice %1, convertValue%2", costPrice, convertValue));


        avgUnitCost = costPrice * convertValue;

        info(strFmt("avgUnitCost %1", avgUnitCost));

        
    }

Please suggest solution on this.

I want to fetch the Average unit cost Site wise. Please refer below highlighted values.

MC_5F00_02.png

I have the same question (0)
  • Suggested answer
    Ludwig Reinhard Profile Picture
    Microsoft Employee on at

    Hi,

    If you enable the financial inventory parameter in your storage dimension groups then you can get a cost price by site.

    Have you checked this setup?

    Don't you try doing something similar?

    Best regards,

    Ludwig

  • Rhushikesh R Profile Picture
    758 on at

    Hi Ludwig,

    The setup you mentioned is already there. I can see the data Site wise but I wanted to fetch that data through my X++ code. Hence I required help on coding part.

  • udaY-ch Profile Picture
    5,133 on at

    hi

    There is no relation between inventdim and inventsum? Did you notice?

    Uday

  • Rhushikesh R Profile Picture
    758 on at

    Hi Uday,

    Even if I modify the select query with relation, it still doesn't give me the desired result. I modified the query like below,

    select firstonly * from inventSum where inventSum.ItemId == _itemId
                join inventDim
                where inventDim.inventDimId == inventSum.inventDimId
                && inventDim.inventDimId == "#12215326";
                

    But with above code as well I did not have any luck.

  • udaY-ch Profile Picture
    5,133 on at

    Try this code

    var         totalQty;
    InventSum   inventsum;
     
    totalQty = inventSum.PostedQty - abs(inventSum.Deducted)   inventSum.Received; 
    totalQty = abs(inventSum.PostedValue   inventSum.PhysicalValue) / totalQty);

  • Rhushikesh R Profile Picture
    758 on at

    Hi Uday,

    the same code which you have written has been used on InventSum data source method of form InventCostOnHandItem.

    But in that method, we get the group of records in the buffer of _inventSum and not a single record.

    Your code will give the output for only single record of inventsum however, average Unit Cost price displayed on the form InventCostOnHandItem is sum of the multiple records.

  • udaY-ch Profile Picture
    5,133 on at

    Then you need to create a x++ query and group by item and sum of these fields to get the group of inventsum for the combination of inventory dimension with aggregation in it.

  • Verified answer
    udaY-ch Profile Picture
    5,133 on at

    HI

    Try this code, this should work as you expect

    public class InventSumQuery
    {    
        static void main(Args _args)
        {
            Qty                     totalQty;
            Query                   query;
            QueryRun                queryRun;
            QueryBuildDataSource    qbdsInventDim, qbdsInventSum;
            InventSum               inventSum;
       
            query = new query();
    
            qbdsInventSum = query.addDataSource(tableNum(InventSum)); 
            qbdsInventDim = qbdsInventSum.addDataSource(tableNum(InventDim));
            qbdsInventDim.relations(true);
            qbdsInventDim.joinMode(JoinMode::InnerJoin);
            qbdsInventDim.addRange(fieldNum(InventDim, InventSiteId)).value("");
            qbdsInventDim.addRange(fieldNum(InventDim, InventLocationId)).value("");
            qbdsInventDim.addRange(fieldNum(InventDim, wmsLocationId)).value("");
            qbdsInventSum.addGroupByField(fieldNum(InventSum, ItemId));
    
            qbdsInventSum.addSelectionField(fieldNum(InventSum, PostedQty), SelectionField::Sum);
            qbdsInventSum.addSelectionField(fieldNum(InventSum, Deducted), SelectionField::Sum);
            qbdsInventSum.addSelectionField(fieldNum(InventSum, Received), SelectionField::Sum);
            qbdsInventSum.addSelectionField(fieldNum(InventSum, PostedValue), SelectionField::Sum);
            qbdsInventSum.addSelectionField(fieldNum(InventSum, PhysicalValue), SelectionField::Sum);
        
            qbdsInventSum.addRange(fieldNum(InventSum, ItemId)).value("");
    
            queryrun = new QueryRun(query);
    
            while (queryRun.next())
            {
                queryRun.changed(tableNum(InventSum));
                {
                    inventSum = queryRun.get(tableNum(InventSum));
                    totalQty = inventSum.PostedQty - abs(inventSum.Deducted)   inventSum.Received;
                    totalQty = abs(inventSum.PostedValue   inventSum.PhysicalValue) / totalQty;
                    info(strFmt("Average unit cost - %1", totalQty));
                }
            }
        }
    
    }

    Uday

  • Rhushikesh R Profile Picture
    758 on at

    Hi Uday,

    That works perfectly. Thank you for the solution. 

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Finance | Project Operations, Human Resources, AX, GP, SL

#1
Martin Dráb Profile Picture

Martin Dráb 559 Most Valuable Professional

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 464 Super User 2025 Season 2

#3
Sohaib Cheema Profile Picture

Sohaib Cheema 250 User Group Leader

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans