Friday, March 27, 2020

Create vendor pending invoices for the invoice pool - using batch job in the Accounts Payable Module.

In D365FO - Creating the vendor pending invoice using batch job:


public void process(VendPendingInvoiceContract _contract)
{
       QueryRun                queryRun;
       LedgerJournalTrans      ledgerTrans;
Query                   query = _contract.getQuery();
boolean                 hasError = false;

        query.dataSourceTable(tableNum(LedgerJournalTrans)).addRange(fieldNum(LedgerJournalTrans, AccountType)).value(queryValue(LedgerJournalACType::Vend));
        query.dataSourceTable(tableNum(LedgerJournalTable)).addRange(fieldNum(LedgerJournalTable, JournalType)).value(queryValue(LedgerJournalType::VendInvoicePool));
        query.dataSourceTable(tableNum(LedgerJournalTable)).addRange(fieldNum(LedgerJournalTable, Posted)).value(queryValue(NoYes::No));
      
        queryRun = new QueryRun(query);
       
        while (queryRun.next())
        {
            try
            {
                ttsbegin;
                ledgerTrans = queryRun.get(tableNum(LedgerJournalTrans));
                if (!ledgerTrans.hasPendingInvoice())
                {
                    this.autoApprovalJournal(ledgerTrans);
                }
                ttscommit;
            }
            catch (Exception::Error)
            {
                if(!hasError)
                {
                    error(strfmt("PendingInvoiceError"));
                    hasError = true;
                }
            }
        }
           
    }

The definition of the auotApprovalJouranl method below:



public void autoApprovalJournal(LedgerJournalTrans _ledgerJournalTrans)
{
    PurchFormLetter             purchFormLetter;
    PurchParmUpdate             purchParmUpdate;
    PurchTable                  purchTableOrig;
       
    purchTableOrig = PurchTable::find(_ledgerJournalTrans.PurchIdRange);
       
    Purchformletter = purchformletter::construct(DocumentStatus::ApproveJournal);
    purchformletter.parmParmTableNum(_ledgerJournalTrans.Invoice);
    purchFormLetter.parmSourceTable(purchTableOrig);
    Purchformletter.parmLedgerJournalTrans(_ledgerJournalTrans);
       
    purchParmUpdate = purchformletter.purchParmUpdate();
    purchParmUpdate.SumNum = _ledgerJournalTrans.Invoice;
    purchformletter.initParameters(purchParmUpdate, Printout::Current);
       
    purchformletter.sumBy(AccountOrder::None);
    purchformletter.showQueryForm(false);
    purchformletter.parmProcessAdditional(true);
    purchformletter.createFromLines(false);

    purchformletter.reArrangeNow(true);
    //purchformletter.reArrange();
    purchformletter.specQty(purchupdate::ALL);
    purchformletter.chooseLines(true);

    VendInvoiceInfoTable::moveFromActiveToSaved(VendInvoiceInfoTable::findRecId(purchformletter.parmLastParmTableRecId()));
}

I hope, you will find in some other blogs - how to create vendor pending invoice for the DocumentStatus::Invoice. I have tried but it is not working for the DocumentStatus::ApprovalJouranl. 

Both process will create pending invoice but, there code is different because they are created from different sources. 

Wednesday, April 3, 2019

D365FO Data management – CustCustomerEntity export/import financial dimensions small setup step:

When using Microsoft Dynamics 365 for Operations (D365O) Data management – CustCustomerEntity for data export/import, and when financial dimensions are involved, there is a small setup step which must be done prior to export/import.
If this step is not done, the following error is displayed when trying to export/import:
DEFAULTDIMENSIONDISPLAYVALUE screenshot of error message
“No active format for data entities has been set up. Set up an active format for each dimension format type.”

Here is how to resolve this error message:

To see the customer’s existing financial dimensions, access the customer list page https://.dynamics.com/?cmp=&mi=CustTableListPageDrill into the customer details using the Financial dimensions fast tab.
Customizing financial dimensions on customer record
In this implementation, we are using 5 financial dimensions, as shown above. Not all dimensions are required to be filled.
In order to successfully export the customer record, we need to set up the format. This is found at General ledger> Chart of accounts> Dimensions> Financial dimension configuration for integrating applications (mi=DimensionIntegrationConfiguration).
Financial dimension configuration for integrating applications
  1. Add a new default dimension format. In this case, we name it “Customer import”.
  2. Use dimension format type “Default dimension format”.
  3. Select the financial dimensions which will be exported/imported as part of the Customers data entity.
  4. To maintain simplicity, I specifically ordered the financial dimensions in the same sequence (alphabetical) as they appear on the customer details form (shown on previous image).
  5. The system will display a format example. This is comprised of the selected dimensions separated by a hyphen.
  6. Set the format “Active for type”.
Now, when exporting the customer record, we see that the financial dimension is displayed properly.
Example of successful export
Use the same format for entering data into a spreadsheet for import using Data management – CustCustomerEntity.
Important: Note that the hyphen separator is always required, even if no value is provided for a dimension (see first line, where both the first and fifth dimensions are not specified).

Tuesday, March 26, 2019

Data Management import or export error in D365FO:

Hi All,

In order to fix the below issue in Data Management D65FO:
when i am trying to import or export getting below error 
System.Exception: Exception from HRESULT: 0xC0000033
at Microsoft.Dynamics.AX.Framework.Tools.DMF.ServiceProxy.DmfEntitySharedTypesProxy.DoWork[T](Func`1 work)
at Dynamics.AX.Application.DMFGenerateSSISPackage.`generateFileDataV2(DMFDefinitionGroupExecution _dmfDefinitionGroupExecution, String _defGroupName, DMFFileFormat _fileFormat, DMFDelimiter _rowDelimiter, DMFDelimiter _columnDelimiter, String _codePage, String _locale, NoYes _isFirstRowHeader, NoYes _unicode, String _source, String _textQualifier, DMFXMLStyle _style, String _rootElement, String _filePath, Map _entitySyncVersion, Int32 _previewCount, Boolean @_entitySyncVersion_IsDefaultSet, Boolean @_previewCount_IsDefaultSet) in xppSource://Source/ApplicationFoundation\AxClass_DMFGenerateSSISPackage.xpp:line 1230

Solution: updated  SQL Server Licence in all AOS Machines and SQL Server Machine.  

Tuesday, March 19, 2019

How to enable access into the environment by specifying which IPs in D365:

Enable access into the environment by specifying which IPs can access the environment for a given service type.

1. Go to LCS for your project.
2. Go to Maintain - Enable access as below.

3. enter the public IP to connect to the RDP.



Saturday, March 16, 2019

How to get the User Date Sequence in Axapta2012 / D365OF:

Normally, we specify 123 or 321 sequence in str2Date(). But, in order to get the sequence randomly the below code is useful:

static int userDateSequence()
    {
        int     ds1, ds2, ds3;
        date    d = str2Date('2015/12/18', 321);
        str     s = strFmt('%1', d);


        void datepart(str strDate, str dval, int part)
        {
            if (strEndsWith(strDate, dval))
            ds3 = part;
            else if (strStartsWith(strDate, dval))
            ds1 = part;
            else
            ds2 = part;
        }

        datepart(s, '18', 1);
        datepart(s, '12', 2);
        datepart(s, '2015', 3);

        return ds1 * 100 + ds2 * 10 + ds3;
    }

How to fetch HSNCode in Ax2012 Indian GST Microsoft Hotfix:

In order to get the value of HSN code in Ax2012, we should know where exactly the HSN code is attached?
1. Normally, HSN code is attached to each item on the Item master under Foreign tab.
2. At the sales or purchase order line under Tax information-GST Tab, the HSN code can be manually selected by user.

The list of tables which has reference to other tables below:

TaxDocument has a reference to SalesTable.
TaxDocumentExtension_IN has a reference to TaxDocument.
TaxDocumentRow has  reference to SalesLine.
TaxDocumentRowTransaction has a reference to CustInvoiceTrans, CustInvoiceJour.
SalesLine_IN has a reference to SalesLine.

TaxDocumentRowTransaction_IN has the HSN code, which will have reference to TaxDocumentExtension_IN and TaxDocumentRowTransaction.

The below code is used to fetch the HSN Code:
//Normally, HSNCode if fetched from the InventTable but otherwise, it will also be fetched from salesline level.:

TaxDocumentRowTransaction       taxDocumentRowTransaction;
TaxDocumentRowTransaction_IN    taxDocumentRowTransaction_IN;
SalesTable                  salesTable;
SalesLine_IN                salesLine_IN;

salesLine_IN    = custInvoiceTrans.salesLine().salesLine_IN();
//TmpSalesPurchRegister is my buffer table.

//TmpSalesPurchRegister.Intracode     = HSNCodeTable_IN::find(InventTable::find(TmpSalesPurchRegister.ItemId).HSNCodeTable_IN).Code;
            Select RecId, TransactionJourLineRecId from taxDocumentRowTransaction
                where taxDocumentRowTransaction.TransactionJourLineRecId == custInvoiceTrans.RecId
            join HSNCode, TaxDocumentRowTransactionRecId from taxDocumentRowTransaction_IN
                where taxDocumentRowTransaction_IN.TaxDocumentRowTransactionRecId == taxDocumentRowTransaction.RecId;
            if(taxDocumentRowTransaction_IN)

            /*select * from taxTrans where taxTrans.SourceRecId == custInvoiceTrans.RecId
            join taxTrans_IN where taxTrans_IN.RefRecId == taxTrans.RecId;
            if(taxTrans_IN)*/
            {

                TmpSalesPurchRegister.Intracode = taxDocumentRowTransaction_IN.HSNCode;
                //TmpSalesPurchRegister.Intracode = HSNCodeTable_IN::find(taxTrans_IN.HSNCodeTable).Code;
            }
            else
            {
                TmpSalesPurchRegister.Intracode = HSNCodeTable_IN::find(salesLine_IN.HSNCodeTable).Code;
            }

Wednesday, October 24, 2018

Import and Export a configuration model in D365(xml file) for custom fields.

Export:

[ExtensionOf(classStr(PcModelVisitorExport))]

final class PCModelVisitorExport_Extension
{
    public void visitStart(Common _record)
    {
        next visitStart(_record);       

        if (_record is EcoResAttribute)
        {
            if ( this.writeComponent() )
            {
                EcoResAttribute ecoResAttribute = _record;

                this.writeFieldValueInt(ecoResAttribute, fieldId2name(ecoResAttribute.TableId, fieldNum(EcoResAttribute, NoPrint)), ecoResAttribute.NoPrint);
            }
        }

        if (_record is PCPriceExpressionValue)
        {
            PCPriceExpressionValue  priceExpressionValue = _record;

            this.writeFieldValue(priceExpressionValue, fieldId2name(priceExpressionValue.TableId, fieldNum(PCPriceExpressionValue, SalesOptionId)), priceExpressionValue.SalesOptionId);
        }

        if (_record is PCPriceExpressionRule)
        {
            PCPriceExpressionRule  priceExpressionRule = _record;

            this.writeFieldValue(priceExpressionRule, fieldId2name(priceExpressionRule.TableId, fieldNum(PCPriceExpressionRule, SalesOptionId)), priceExpressionRule.SalesOptionId);
        }
    }   


}

Import:

[ExtensionOf(classStr(PCImportComponentAttributeHandler))]
final class PCImportComponentAttributeHandler_Extension
{
    protected void importData()
    {
        #define.NoPrint('NoPrint')

        next importData();
               
        ttsbegin;

        attribute.Selectforupdate(true);
        attribute.NoPrint   = this.getIntFieldByName(#NoPrint);
        attribute.update();

        ttscommit;       
    }

}

[ExtensionOf(classStr(PCImportPriceExpressionRuleHandler))]
final class PCImportPriceExpressionRuleHandler_Extension
{
    protected void importData()
    {
        #define.SalesOptionId('SalesOptionId')

        next importData();

        ttsbegin;

        expressionRule.Selectforupdate(true);
        expressionRule.SalesOptionId    = this.getFieldByName(#SalesOptionId);
        expressionRule.update();

        ttscommit;
    }

}

Time and attendance-Clock-in/out(punch clock) to filter the Indirect Activities based on the Resource group attached.

[ExtensionOf(formStr(JmgRegistration))]

final class JmgRegistration_Extension
{
 
    public QueryBuildDataSource    qbdsJmgIpcActivityIndirectactivity;
    public container                           containerActivityId, conResourceGroup;
 
    public void showIPC()
    {
        WrkCtrTable                             selectedWrkCtrTable;
        WrkCtrResourceGroup             wrkCtrResourceGroup;
     
       next showIPC();

       containerActivityId  = conNull();
       conResourceGroup     = conNull();
       //Filter the data based on the resource group
        if (curWrkCtrId)
        {
            conResourceGroup += curWrkCtrId;

            selectedWrkCtrTable = WrkCtrTable::find(curWrkCtrId);

            //Checking for only resource groups but not resources in the WrkCtrTable.
            if (selectedWrkCtrTable.IsIndividualResource == NoYes::No)
            {
                this.JmgIpcActivityIndirectactivityRange();
            }
        }
        //Filter the data based on the production unit with no resource group
        if(curProdUnitId  && !curWrkCtrId)
        {
            //Fetching the list of resource group that are attached to a production unit.
            while select wrkCtrId from wrkCtrResourceGroup
                    where wrkCtrResourceGroup.ProdUnitId == curProdUnitId
            {
                conResourceGroup += wrkCtrResourceGroup.WrkCtrId;
            }
             
            this.JmgIpcActivityIndirectactivityRange();
        }

        jmgJobTable_DS.executeQuery();
    }

    //Filter the form datasource JmgJobTable_ds based on the activityID list.
    public void JmgIpcActivityIndirectactivityRange()
    {
        Query                                queryJmgIpResourceGroup, queryJmgIpActivity;
        QueryBuildDataSource    qbdsJmgIpResourceGroup, qbdsJmgIpActivity;
        QueryBuildRange             qbrJmgIpResourceGroup, qbrJmgIpActivity;
        QueryRun                         qrJmgIpResourceGroup, qrJmgIpActivity;

        WrkCtrResourceGroup             wrkCtrResourceGroup;
        JmgIpcActivity                          jmgIpActivity;
        JmgIpActivityResourceGroup   jmgIpResourceGroup;
     
        //Query to fetch the list of activityID's with the resource groups attached.
        queryJmgIpResourceGroup = new Query();
        qbdsJmgIpResourceGroup = queryJmgIpResourceGroup.addDataSource(tableNum(JmgIpActivityResourceGroup));
        qbdsJmgIpResourceGroup.addGroupByField(fieldNum(JmgIpActivityResourceGroup, Activity));
        qbdsJmgIpResourceGroup.addGroupByField(fieldNum(JmgIpActivityResourceGroup, WrkCtrId));
        qbrJmgIpResourceGroup = qbdsJmgIpResourceGroup.addRang  e(fieldNum(JmgIpActivityResourceGroup, WrkCtrId));
        qbrJmgIpResourceGroup.value(con2Str(conResourceGroup));

        qbdsJmgIpActivity = qbdsJmgIpResourceGroup.addDataSource(tableNum(JmgIpcActivity));
        qbdsJmgIpActivity.joinMode(JoinMode::ExistsJoin);
        qbdsJmgIpActivity.addLink(fieldNum(JmgIpActivityResourceGroup, Activity),fieldNum(JmgIpcActivity, Activity));

        qrJmgIpResourceGroup = new QueryRun(queryJmgIpResourceGroup);
        while (qrJmgIpResourceGroup.next())
        {
            jmgIpResourceGroup = qrJmgIpResourceGroup.get(tableNum(JmgIpActivityResourceGroup));
            containerActivityId += jmgIpResourceGroup.Activity;
        }
        //Query to fetch the list of activityID's without the resource group
        queryJmgIpActivity = new Query();
        qbdsJmgIpActivity = queryJmgIpActivity.addDataSource(tableNum(JmgIpcActivity));
        qbdsJmgIpResourceGroup = qbdsJmgIpActivity.addDataSource(tableNum(JmgIpActivityResourceGroup));
        qbdsJmgIpResourceGroup.joinMode(JoinMode::NoExistsJoin);
        qbdsJmgIpResourceGroup.addLink(fieldNum(JmgIpcActivity, Activity),fieldNum(JmgIpActivityResourceGroup, Activity));
     
        qrJmgIpActivity = new QueryRun(queryJmgIpActivity);
        while (qrJmgIpActivity.next())
        {
            jmgIpActivity = qrJmgIpActivity.get(tableNum(JmgIpcActivity));
            containerActivityId += jmgIpActivity.Activity;
        }
        //Final query to filter the data in the JmgJobTable_ds based on the activityID list.
        qbdsJmgIpcActivityIndirectactivity = qbdsJmgJobTable.addDataSource(tableNum(JmgIpcActivity));
        qbdsJmgIpcActivityIndirectactivity.joinMode(JoinMode::ExistsJoin);
        qbdsJmgIpcActivityIndirectactivity.addLink(fieldNum(JmgJobTable, JobId),fieldNum(JmgIpcActivity, JobId));
        qbdsJmgIpcActivityIndirectactivity.addRange(fieldNum(JmgIpcActivity, Activity)).value(con2Str(containerActivityId));

    }

    public void removeJmgIpcActivityIndirectactivityRange()
    {
        if (qbdsJmgIpcActivityIndirectactivity)
        {
            qbdsJmgIpcActivityIndirectactivity.enabled(false);
        }
    }

}

// To remove the newly build query when standard query being executed and thus making the datasource to work based on the standard behaviour.

class JmgRegistrationsEventHandlers
{ 
 

    [PreHandlerFor(formStr(JmgRegistration), formMethodStr(JmgRegistration, showProductionJobs))]
    public static void JmgRegistration_Pre_showProductionJobs(XppPrePostArgs args)
    {
        FormRun jmgRegistration = args.getThis();

        jmgRegistration.removeJmgIpcActivityIndirectactivityRange();
    }
 

    [PreHandlerFor(formStr(JmgRegistration), formMethodStr(JmgRegistration, showProject))]
    public static void JmgRegistration_Pre_showProject(XppPrePostArgs args)
    {
        FormRun jmgRegistration = args.getThis();

        jmgRegistration.removeJmgIpcActivityIndirectactivityRange();
    }


    [PreHandlerFor(formStr(JmgRegistration), formMethodStr(JmgRegistration, showIPC))]
    public static void JmgRegistration_Pre_showIPC(XppPrePostArgs args)
    {
        FormRun jmgRegistration = args.getThis();

        jmgRegistration.removeJmgIpcActivityIndirectactivityRange();
    }
 
}


Wednesday, June 27, 2018

What is the "Quantity Adjustment" Button in Inventory management In D365/Axapta.

It is very important to know the Quantity Adjustment through Inventory Management-Onhand Form.

It appears to create a single transaction with no Journal ID.

1. What is the purpose of this form?

Using this form for adjusting inventory quantity is basically identical to posting an counting journal for a specific item.

2. Can we add logging to it? what journal is used?

You can identify the transaction through the item transaction form but cannot open the counting journal as an ordinary user from the AX client.

3. What will be impact on costing if we adjust quantity using this form?

The impact on your costing will be that the inventory value is reduced or increased based on the number of items you specified to be on stock.

The technical information such as the trace log and classes related to this posting below:

\Data Dictionary\Tables\InventSite\Methods\changeDimension 29

\Classes\InventMov_Vir_Counting\defaultDimension                3

\Classes\InventUpdate\initInventTransPosting                    8

\Classes\InventUpdate\updateInventTransPosting                  5

\Classes\InventUpd_Physical\updateInventTransPosting            18

\Classes\InventUpd_Physical\updateNow                           69

\Classes\InventUpd_Financial\updateNow                          49

\Classes\WMSOnlineCountingServer\handleLine                     73

\Classes\WMSOnlineCountingServer\run                            19

\Classes\WMSOnlineCountingServer\validateRun                    3

\Classes\WMSOnlineCounting\validateRun                          3

\Forms\WMSOnlineCounting\Methods\canClose                       9

\Classes\FormRun\closeOk

After updating the quantity and clicking OK button the above trace log is generated.

It will update the quantity and financial dimension will update if settings exist on item or site. But, no journal number exist in counting journal.

Monday, June 25, 2018

Create a Translate button on new form in D365/Ax2012:

In standard we have translation in many places in D365. For example here I am showing in General Leger-Char of Accounts-Accounts-Main accounts.

 
 

Similarly, I have to develop the translation on another standard form called Questions as below:

Create a new table, class as below.
Table-KMQuestionTranslation. You need to write the table method. It is already there in the other standard Translation Tables.

Table properties as below:
 
Create a new class as below:
 
 
 
Write below code in Tables->KMQuestion->Insert():
 
 
 
Create a new Action Menu Item and add the menu item to the form extension as below:
 
 
 
Final project Area as below:
 
  Finally, the translation added to the Question Form.
 
 

Enjoy :)
 

User Date Sequence in D365 and Ax2012:

The below method will return the date sequence automatically.
Instead of hard coding as 123 or 213

str2Date(DateValue,123);

use the below code.


static int userDateSequence()
{
    int     ds1, ds2, ds3;
    date    d = str2Date('2015/12/18', 321);
    str     s = strFmt('%1', d);


    void datepart(str strDate, str dval, int part)
    {
        if (strEndsWith(strDate, dval))
            ds3 = part;
        else if (strStartsWith(strDate, dval))
            ds1 = part;
        else
            ds2 = part;
    }


    datepart(s, '18', 1);
    datepart(s, '12', 2);
    datepart(s, '2015', 3);

    return ds1 * 100 + ds2 * 10 + ds3;
}

Wednesday, June 6, 2018

Add new field in the Trade Agreements journal lines "Standard Price" and update item purchase price using the batch job based on the conditions.

Add new field in the Trade Agreements journal lines "Standard Price" and update the item purchase price using the batch job based on the conditions.

Procurement and sourcing > Prices and discounts > Trade agreement journals -> Create new PurchPrice trade agreement journal and go to lines.

1. Add the New field -> PriceDiscAdmTrans.Extension (Table)
2. Create a SysOperatoin - Contract class:

[DataContractAttribute]
class PurchPriceDataContract 
{
    TransDate   transDate;
    str         packedQuery;

    [DataMemberAttribute ,SysOperationLabelAttribute(literalStr("@ABC:PurchTradeAgreementLabel"))]
    public TransDate parmTransDate(TransDate _transDate = transDate)
    {
        transDate = _transDate;

        return transDate;
    }

    [DataMemberAttribute, AifQueryTypeAttribute('_packedQuery', querystr(ItemPurchPrice))]
    public str parmQuery(str _packedQuery = packedQuery)
    {
        packedQuery = _packedQuery;
        return packedQuery;
    }

    public Query getQuery()
    {
        return new Query(SysOperationHelper::base64Decode(packedQuery));
    }

    public void setQuery(Query _query)
    {
        packedQuery = SysOperationHelper::base64Encode(_query.pack());
    }

}
3. Created a Service class - 

class PurchPriceDataService 
{
    QueryRun                queryRun;
    InventTable             inventTable;
    InventTableModule       inventTableModule;
    PriceConvertFactory     priceConvertFactory;
    PriceConvert            priceConvert;
    TransDate               transDate;
    PriceDiscAdmTrans       priceDiscAdmTrans;
    PriceDiscAdmTable       priceDiscAdmTable;
    PriceCur                price;
    PriceUnit               priceUnit;
    
    //
    #ISOCountryRegionCodes
    boolean countryRegion_RU;
    //
    
    [SysEntryPointAttribute]
    public void updateItemPurchPrice(PurchPriceDataContract _purchPriceDataContract)
    {
        // Query objects
        Query                   query;
        QueryRun                queryRunpriceDiscAdmTrans;
        QueryBuildDataSource    qbdspriceDiscAdmTrans;
        QueryBuildDataSource    qbdspriceDiscAdmTable;
        QueryBuildRange         qbrpriceDiscAdmTrans;
        QueryBuildRange         qbrpriceDiscAdmTable;

        // create a new queryrun object
        queryRun = new queryRun(ItemPurchPriceDataContract.getQuery());

        // loop all results from the query
        while(queryRun.next())
        {
            inventTable = queryRun.get(tableNum(InventTable));
            transDate = _purchPriceDataContract.parmTransDate();

            if(inventTable.PrimaryVendorId)
            {
                query = new query();

                qbdspriceDiscAdmTable = query.addDataSource(tablenum(PriceDiscAdmTable));
                qbrpriceDiscAdmTable  = qbdspriceDiscAdmTable.addRange(fieldNum(PriceDiscAdmTable,DefaultRelation));
                qbrpriceDiscAdmTable.value(enum2Str(PriceType::PricePurch));

                qbrpriceDiscAdmTable  = qbdspriceDiscAdmTable.addRange(fieldNum(PriceDiscAdmTable,Posted));
                qbrpriceDiscAdmTable.value(enum2Str(NoYes::Yes));

                qbdspriceDiscAdmTrans = qbdspriceDiscAdmTable.addDataSource(tablenum(PriceDiscAdmTrans));

                qbdspriceDiscAdmTrans.addLink(fieldNum(PriceDiscAdmTable, JournalNum), fieldNum(PriceDiscAdmTrans, JournalNum));
        
                qbrpriceDiscAdmTrans = qbdspriceDiscAdmTrans.addRange(fieldNum(PriceDiscAdmTrans, Relation));
                qbrpriceDiscAdmTrans.value(enum2Str(PriceType::PricePurch));

                qbrpriceDiscAdmTrans = qbdspriceDiscAdmTrans.addRange(fieldNum(PriceDiscAdmTrans, ItemRelation));
                qbrpriceDiscAdmTrans.value(inventTable.itemId);

                qbrpriceDiscAdmTrans = qbdspriceDiscAdmTrans.addRange(fieldNum(PriceDiscAdmTrans, FromDate));
                qbrpriceDiscAdmTrans.value(SysQuery::range(transDate, dateNull()));

                qbrpriceDiscAdmTrans = qbdspriceDiscAdmTrans.addRange(fieldNum(PriceDiscAdmTrans, ToDate));
                qbrpriceDiscAdmTrans.value(SysQuery::range(dateNull(), transDate));

                // Results sorting
                qbdspriceDiscAdmTrans.addSortField(fieldNum(PriceDiscAdmTrans, StandardPurchPrice), SortOrder::Descending);
                qbdspriceDiscAdmTrans.addSortField(fieldNum(PriceDiscAdmTrans, Amount), SortOrder::Descending);
                qbdspriceDiscAdmTrans.firstOnly(true);
            
                queryRunpriceDiscAdmTrans = new QueryRun(query);
                if(queryRunpriceDiscAdmTrans.next())
                {
                    priceDiscAdmTrans = queryRunpriceDiscAdmTrans.get(tableNum(PriceDiscAdmTrans));
                    inventTableModule = InventTableModule::find(inventTable.ItemId,ModuleInventPurchSales::Purch);
                    priceConvertFactory = PriceConvertFactory::newItemPrice(priceDiscAdmTrans.ItemRelation,
                                                                        inventTableModule.UnitId,
                                                                        priceDiscAdmTrans.Amount,//inventTableModule.price(),
                                                                        inventTableModule.priceUnit(),
                                                                        inventTableModule.markup(),
                                                                        inventTableModule.priceQty(),
                                                                        '',
                                                                        countryRegion_RU ? inventTableModule.priceSecCur_RU() : 0,
                                                                        countryRegion_RU ? inventTableModule.markupSecCur_RU() : 0);

                    priceConvertFactory.parmNewCurrencyCode(priceDiscAdmTrans.Currency);
                    priceConvertFactory.parmTransDate(transDate);
                    priceConvertFactory.parmNewUnitId(priceDiscAdmTrans.UnitId);

                    priceConvert = priceConvertFactory.priceConvert();

                    price       = priceConvert.parmPrice();
                    ttsbegin;
                    inventTableModule.selectForUpdate(true);
                    inventTableModule.price = price;
                    inventTableModule.update();
                    ttscommit;
                }
            }
        }
    }

}

4. Create a AOT query for the contract class.




finally, update the price on the item purchase price where primary vendor is mentioned.

The above code will fetch the record from the trade agreements base on the dialog box itemID and date selection (which is a AOT Query) and then convert using the standard logic currency conversion, in case the company currency and trade agreements currency are different and then update the item purchase price.