Wednesday, June 22, 2022

Postman Odata request for filters and Pre request script for dates

Postman: (Get request time rely on server timezone)

Request: GET ->

https://<D365FO URL>/data/BatchJobs?$filter=Status eq Microsoft.Dynamics.DataEntities.BatchStatus'Executing' and StartDate eq {{currentdate}} and StartTime gt {{currentTime}} &cross-company=true


or

https://<D365FO URL>/data/RetailTransactions?$filter=ChannelReferenceId eq '' and CustomerAccount eq '' and TransactionDate eq 2022-08-23 &cross-company=true


Pre-Request script:

var moment = require('moment');

pm.globals.set('currentdate', moment().format(("YYYY-MM-DD")));

pm.globals.set("currentTime"new Date().setTime(new Date().getTime()-10800)); (As per postman installed machine time Zone GMT)

//setting

postman.setEnvironmentVariable("currentdate", moment().format(("YYYY-MM-DD")));


Set Global variables:

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("access_token"jsonData.access_token);

Select field list
&$select=CustomerAccount,OrganizationName

Test samples:
pm.test("Status code is 200"function () {
    pm.response.to.have.status(200);
});
var json = JSON.parse(responseBody);
tests["<Collection request name>"= !json.error && responseBody !== '' && responseBody !== '{}' && json.Id !== '';
postman.setEnvironmentVariable("<Global variable name>"json.AmountDue);

var json = JSON.parse(responseBody);
tests["<Collection request name>"= !json.error && responseBody !== '' && responseBody !== '{}' && json.CartLines !== '';
postman.setEnvironmentVariable("<Global variable name>"json.CartLines[0].LineId);

Tuesday, May 10, 2022

Create agreement header & lines and link with Sales order X++

            //Process Started


  select firstOnly agreementClassification

                where agreementClassification.AgreementRelationType == tableNum(SalesAgreementHeader);


            row =1;

            worksheetSysHeader = worksheets.itemFromName(worksheetHeader);

            cells = worksheetSysHeader.cells();

            do

            {

                row++;

                salesAgreementHeader = SalesAgreementHeader::findAgreementId(cells.item(row, 1).value().bStr());

                if(!salesAgreementHeader)

                {

                    salesAgreementHeader.clear();

                    salesAgreementHeader.initValue();

                    salesAgreementHeader.SalesNumberSequence   = cells.item(row, 1).value().bStr();

                    salesAgreementHeader.CustAccount   =  cells.item(row, 2).value().bStr();

                    salesAgreementHeader.initFromCustTable();

                    salesAgreementHeader.AgreementClassification = agreementClassification.RecId;

                    salesAgreementHeader.Currency  = cells.item(row, 9).value().bStr();

                    salesAgreementHeader.AgreementState = str2enum(agreementState, cells.item(row, 10).value().bStr());

                    salesAgreementHeader.DefaultAgreementLineEffectiveDate = str2Date(this.COMVariant2Str(cells.item(row, 5).value(), 0),213);

                    salesAgreementHeader.DefaultAgreementLineExpirationDate = str2Date(this.COMVariant2Str(cells.item(row, 6).value(), 0),213);


                    if (salesAgreementHeader.validateWrite())

                    {

                        salesAgreementHeader.insert();

                    }

                }

                else

                {

                    salesAgreementHeader.selectForUpdate(true);

                    salesAgreementHeader.Currency  = cells.item(row, 9).value().bStr();

                    salesAgreementHeader.AgreementState = str2enum(agreementState, cells.item(row, 10).value().bStr());

                    salesAgreementHeader.DefaultAgreementLineEffectiveDate = str2Date(this.COMVariant2Str(cells.item(row, 5).value(), 0),213);

                    salesAgreementHeader.DefaultAgreementLineExpirationDate = str2Date(this.COMVariant2Str(cells.item(row, 6).value(), 0),213);

                    if (salesAgreementHeader.validateWrite())

                    {

                        salesAgreementHeader.update();

                    }

                }


                if(salesAgreementHeader)

                {

                    if(!conFind(salesAgreementIds, salesAgreementHeader.SalesNumberSequence))

                    {

                        salesAgreementIds += salesAgreementHeader.SalesNumberSequence;

                    }


                    salesAgreementHeaderDefault = SalesAgreementHeaderDefault::findSalesAgreementHeader(salesAgreementHeader.RecId);

                    if(salesAgreementHeaderDefault)

                    {

                        salesAgreementHeaderDefault.selectForUpdate(true);

                        salesAgreementHeaderDefault.CustomerRequisitionNumber = cells.item(row, 12).value().bStr();

                        salesAgreementHeaderDefault.update();

                    }

                    else

                    {

                        salesAgreementHeaderDefault.clear();

                        salesAgreementHeaderDefault.initValue();

                        salesAgreementHeaderDefault.SalesAgreementHeader = salesAgreementHeader.RecId;

                        salesAgreementHeaderDefault.CustomerRequisitionNumber = cells.item(row, 12).value().bStr();

                        salesAgreementHeaderDefault.insert();

                    }


                    agreementHeaderDefault  = AgreementHeaderDefault::findAgreementHeader(salesAgreementHeader.RecId);

                    if(agreementHeaderDefault)

                    {

                        agreementHeaderDefault.selectForUpdate(true);

                        agreementHeaderDefault.DeliveryPostalAddress = CustTable::find(cells.item(row, 2).value().bStr()).postalAddress().RecId;

                        agreementHeaderDefault.DeliveryName = CustTable::find(cells.item(row, 2).value().bStr()).name();

                        agreementHeaderDefault.ContactPerson = cells.item(row, 4).value().bStr();

                        agreementHeaderDefault.ExternalReference = cells.item(row, 11).value().bStr();

                        agreementHeaderDefault.DeliveryTerm = cells.item(row, 8).value().bStr();

                        agreementHeaderDefault.PaymentTerms = cells.item(row, 7).value().bStr();

                        agreementHeaderDefault.ContactPersonDataAreaId = curext();

                        agreementHeaderDefault.PaymentTermsDataAreaId = curext();

                        agreementHeaderDefault.DeliveryTermDataAreaId = curext();

                        agreementHeaderDefault.ContactPersonDataAreaId = curext();

                        agreementHeaderDefault.update();

                    }

                    else

                    {

                        agreementHeaderDefault.clear();

                        agreementHeaderDefault.initValue();

                        agreementHeaderDefault.AgreementHeader = salesAgreementHeader.RecId;

                        agreementHeaderDefault.ContactPerson = cells.item(row, 4).value().bStr();

                        agreementHeaderDefault.ExternalReference = cells.item(row, 11).value().bStr();

                        agreementHeaderDefault.DeliveryTerm = cells.item(row, 8).value().bStr();

                        agreementHeaderDefault.PaymentTerms = cells.item(row, 7).value().bStr();

                        agreementHeaderDefault.DeliveryPostalAddress = CustTable::find(cells.item(row, 2).value().bStr()).postalAddress().RecId;

                        agreementHeaderDefault.DeliveryName = CustTable::find(cells.item(row, 2).value().bStr()).name();

                        agreementHeaderDefault.ContactPersonDataAreaId = curext();

                        agreementHeaderDefault.PaymentTermsDataAreaId = curext();

                        agreementHeaderDefault.DeliveryTermDataAreaId = curext();

                        agreementHeaderDefault.insert();

                    }

                }

                type = cells.item(row+1, 1).value().variantType();

            }

            while (type != COMVariantType::VT_EMPTY);


            row =1;

            cells = null;

            worksheetSysHeader = worksheets.itemFromName(worksheetLine);

            cells = worksheetSysHeader.cells();

            do

            {

                row++;

                salesAgreementHeader =  SalesAgreementHeader::findAgreementId(cells.item(row, 1).value().bStr());

                agreementHeader = AgreementHeader::find(salesAgreementHeader.RecId);


                agreementHeaderDefault = AgreementHeaderDefault::findAgreementHeader(agreementHeader.RecId);

                salesAgreementHeaderDefault = SalesAgreementHeaderDefault::findSalesAgreementHeader(salesAgreementHeader.RecId);

                if(salesAgreementHeader && agreementHeader)

                {

                     select firstonly agreementLineQty

                        where agreementLineQty.Agreement == agreementHeader.RecId

                            && agreementLineQty.ItemId == cells.item(row, 2).value().bStr();


                    if(!agreementLineQty)

                    {

                        agreementLineQty.clear();

                        agreementLineQty.initValue();

                        agreementLineQty.initFromAgreementHeader(agreementHeader);

                        agreementLineQty.Agreement = agreementHeader.RecId;

                        agreementLineQty.AgreementLineProduct   = AgreementLineProduct::Item;

                        agreementLineQty.AgreementLineType = CommitmentType::ProductQuantity;

                        agreementLineQty.ItemId = cells.item(row, 2).value().bStr();

                        agreementLineQty.initFromInventTable();

                        inventDim = agreementLineQty.inventDim();

                        switch (agreementLineQty.agreementModuleType())

                        {

                            case ModuleSalesPurch::Sales:

                                inventDim.initFromInventTable(agreementLineQty.inventTable(), InventItemOrderSetupType::Sales, inventDim);

                                break;


                            case ModuleSalesPurch::Purch:

                                inventDim.initFromInventTable(agreementLineQty.inventTable(), InventItemOrderSetupType::Purch, inventDim);

                                break;

                        }

                        inventDim.InventDimId = InventDim::findOrCreate(inventDim).InventDimId;

                        agreementLineQty.setInventDimId(inventDim.InventDimId);

                        agreementLineQty.InventDimDataAreaId = curext();

                        agreementLineQty.ExpirationDate = str2Date(this.COMVariant2Str(cells.item(row, 14).value(), 0),213);

                        agreementLineQty.CommitedQuantity =  str2num(this.COMVariant2Str(cells.item(row, 4).value(), 2));

                        agreementLineQty.ProductUnitOfMeasure = cells.item(row, 5).value().bStr();

                        agreementLineQty.PricePerUnit = str2num(this.COMVariant2Str(cells.item(row, 6).value(), 2));

                        agreementLineQty.LineDiscountAmount =str2num(this.COMVariant2Str(cells.item(row, 7).value(), 2));

                        agreementLineQty.LineDiscountPercent =str2num(this.COMVariant2Str(cells.item(row, 8).value(), 2));

                        agreementLineQty.LineNumber = AgreementLine::lastLineNum(agreementHeader.RecId) + 1;

                        if (agreementLineQty.validateWrite())

                        {

                            agreementLineQty.insert();

                            agreementLineQty.salesAgreementHeader().update();

                        }

                    }

                    else

                    {

                        agreementLineQty.selectForUpdate(true);

                        agreementLineQty.ExpirationDate = str2Date(this.COMVariant2Str(cells.item(row, 14).value(), 0),213);

                        agreementLineQty.CommitedQuantity =  str2num(this.COMVariant2Str(cells.item(row, 4).value(), 2));

                        agreementLineQty.ProductUnitOfMeasure = cells.item(row, 5).value().bStr();

                        agreementLineQty.PricePerUnit = str2num(this.COMVariant2Str(cells.item(row, 6).value(), 2));

                        agreementLineQty.LineDiscountAmount =str2num(this.COMVariant2Str(cells.item(row, 7).value(), 2));

                        agreementLineQty.LineDiscountPercent =str2num(this.COMVariant2Str(cells.item(row, 8).value(), 2));

                        agreementLineQty.update();


                        agreementLineQty.salesAgreementHeader().update();

                    }


                    

                    if(agreementLineQty)

                    {

                        agreementLineDefault = AgreementLineDefault::findAgreementLine(agreementLineQty.RecId);

                        if(!agreementLineDefault)

                        {

                            agreementLineDefault.clear();

                            agreementLineDefault.initValue();

                            agreementLineDefault.AgreementLine = agreementLineQty.RecId;

                            agreementLineDefault.initFromAgreementHeaderDefault(agreementHeaderDefault);

                            agreementLineDefault.initFromSalesAgreementHeaderDefault(salesAgreementHeaderDefault);

                            agreementLineDefault.insert();

                        }

                    }

                }

                else

                {

                    info(strFmt("%1 Invalid sales agreement header reference",cells.item(row, 1).value().bStr()));

                }

                type = cells.item(row+1, 1).value().variantType();

            }

            while (type != COMVariantType::VT_EMPTY);


            row =1;

            cells = null;

            worksheetSysHeader = worksheets.itemFromName(worksheetRef);

            cells = worksheetSysHeader.cells();

            do

            {

                row++;

                salesAgreementHeader.clear();

                agreementHeader.clear();

                salesAgreementHeader =  SalesAgreementHeader::findAgreementId(cells.item(row, 1).value().bStr());

                agreementHeader = AgreementHeader::find(salesAgreementHeader.RecId);

                

                agreementLine.clear();

                select firstOnly agreementLine

                    where agreementLine.Agreement == agreementHeader.RecId

                        && agreementLine.ItemId == cells.item(row, 3).value().bStr();

                

                if(agreementLine)

                {

                    salesLine.clear();

                    select firstOnly salesLine

                        where salesLine.SalesId == cells.item(row, 2).value().bStr()

                            && salesLine.ItemId == cells.item(row, 3).value().bStr(); 

                    if(salesLine)

                    {

                        salesTable = salesLine.salesTable();

                        if(salesTable)

                        {

                            salesTable.selectForUpdate(true);

                            salesTable.initFromSalesAgreementHeader(salesAgreementHeader);

                            salesTable.update();

                        }

                        SalesTableForm::createAgreementLinkServer(salesLine, agreementLine);

                    }

                    else

                    {

                        info(strFmt("%1 %2 combination of Sales order and item number doesnot exist", 

                        cells.item(row, 2).value().bStr(),

                        cells.item(row, 3).value().bStr()));

                    }

                }

                else

                {

                    info(strFmt("%1 %2 combination of Sales agreement and item number doesnot exist", 

                        cells.item(row, 1).value().bStr(),

                        cells.item(row, 3).value().bStr()));

                }

                type = cells.item(row+1, 1).value().variantType();

            }

            while (type != COMVariantType::VT_EMPTY);


            ttsCommit;

            //Process ended

Thursday, May 5, 2022

SQL script to delete all staging table data in D365FO

 declare cu cursor for SELECT [name] FROM SYSTABLEIDVIEW where [name] like '%Staging'

declare @table varchar(100)

declare @sql nvarchar(1000)

OPEN cu  

FETCH NEXT FROM cu INTO @table 

WHILE @@FETCH_STATUS = 0  

BEGIN  

    set @sql = N'delete from ' + @table

    PRINT @table

    EXEC sp_executesql @sql

    FETCH NEXT FROM cu INTO @table 

END   

CLOSE cu;  

DEALLOCATE cu;

Monday, April 25, 2022

Data management EXPORT operation using X++ in D365FO

         #DMF

        Query query;

        DMFEntityName entityName;

        boolean isGenerated = false;


        entityName = DMFEntity::findFirstByTableId(tableNum(BankPositivePayExportEntity)).EntityName;


            // Update query

            query = new Query(DMFUtil::getDefaultQueryForEntityV3(entityName));

            QueryBuildDataSource qbds = query.dataSourceTable(tableNum(BankPositivePayExportEntity));

            SysQuery::findOrCreateRange(qbds, fieldNum(BankPositivePayExportEntity, PositivePayNumber)).value(queryValue(bankPositivePayTable.PositivePayNum));


        // Export file

        DMFDefinitionGroupName definitionGroupName = strFmt('%1-%2', classStr(BankPositivePayExport), bankPositivePayTable.PositivePayNum);


        try

        {

            BankPositivePayFormat positivePayFormat = BankPositivePayFormat::findByFormatName(bankPositivePayTable.PayFormat);

            List xsltFileList = new List(Types::String);


            if (positivePayFormat.FileId != '')

            {

                xsltFileList.addEnd(this.copyTransformationFile(positivePayFormat));

            }


            DMFEntityExporter exporter = new DMFEntityExporter();

            fileId = exporter.exportToFile(

                entityName,

                definitionGroupName,

                '',

                positivePayFormat.DMFSourceName,

                #FieldGroupName_AllFields,

                query.pack(),

                curExt(),

                xsltFileList,

                true,

                false);


            if (fileId != '')

            {

                this.sendFileToDestination();

                DMFDefinitionGroup::find(definitionGroupName, true).delete();


                isGenerated = true;

            }

            else

            {

                // DMF execution failed and details were written to the execution log

                throw error("@CashManagement:DMFExportCallFailedToExecutionLog");

            }

        }

        catch

        {

            //

        }


        return isGenerated;

Tuesday, April 12, 2022

Error On data entity -> The data value violates integrity constraints in D365FO

Error: The data value violates integrity constraints

Solution:

1. Remove blank lines on sample file, If any (If in case, CSV or excel) or  Copy content alone from EXCEL or CSV, Create new workbook and paste it

2. Check all mandatory fields value filled in on input file or not and also check any index violation (duplicate values/Record) 

Thursday, March 17, 2022

ODATA Request URL D365FO - Testing postman

 POST:

https://<D365FOURL>/data/<EntityPublicCollectionName>

Body:

{
    "dataAreaId""USMF",
    "InvoiceId""USMF00000040",
    "InvoiceAmount"13110.540000,
    "Status""Sent"
}

PATCH:
https://<D365FOURL>/data/<EntityPublicCollectionName>(dataAreaId='USMF',InvoiceId='USMF00000040')?cross-company=true

Body:
{
    "Status""Paid"
}

Friday, March 11, 2022

Getting Infolog container to string in D365FO


        SysInfologEnumerator    sysInfologEnumerator;

        SysInfologMessageStruct infoMessageStruct;

        str                     logMessage;

       container logData = inputLogData;// Input 

        sysInfologEnumerator = SysInfologEnumerator::newData(logData );    

        while (sysInfologEnumerator.moveNext())

        {

            int i = 1;

            if (logMessage)

            {

                logMessage +=  '\n';

            }

            infoMessageStruct = SysInfologMessageStruct::construct(sysInfologEnumerator.currentMessage());        

            while (i <= infoMessageStruct.prefixDepth())

            {

                logMessage += infoMessageStruct.preFixTextElement(i) + '. ';                i++;

            }

            logMessage += infoMessageStruct.message();

        }

      info( logMessage);

Monday, February 28, 2022

Get SQL Table row counts

CREATE TABLE TSTRowCounts(RowCount1 BIGINT,TableName VARCHAR(128))


EXEC sp_MSForEachTable 'INSERT INTO TSTRowCounts

                        SELECT COUNT_BIG(*) AS RowCount1,

                        ''?'' as TableName FROM ?'


SELECT  top 100 TableName, RowCount1  FROM  TSTRowCounts ORDER BY RowCount1 DESC


select * from TSTRowCounts

where RowCount1 >100000

Thursday, February 17, 2022

Calculate retail price and discounts in D365FO

Reference: RetailPricingSimulator (MS Standard OOB class) 


Pre requistie:

Customer, Item Number, Retail channel, Currency

Price: Original price (Sales price - Discount)

Code:

Class declaration

using System.Reflection;

using System.Collections.Generic;

using CrtRetailAffiliationType = Microsoft.Dynamics.Commerce.Runtime.DataModel.RetailAffiliationType;

public AmountCur GetRetailPriceAndDiscounts(

            str                     _customer,

            str                     _itemId,

            RetailChannelTable      _retailChannel,

            list                    _affiliationList = null,

            Str                     _currency = Ledger::accountingCurrency(),

            str                     _orderNo = '')

    {

        Microsoft.Dynamics.Commerce.Runtime.DataModel.SalesLine                                     crtSalesLine;

        Microsoft.Dynamics.Commerce.Runtime.DataModel.SalesTransaction                              crtSalesTransaction;

        Microsoft.Dynamics.Commerce.Runtime.Services.PricingEngine.PricingEngineDiagnosticsObject   diagnosticsObjectPrices;

        Microsoft.Dynamics.Commerce.Runtime.Services.PricingEngine.PricingEngineDiagnosticsObject   diagnosticsObjectDiscounts;

        Microsoft.Dynamics.Commerce.Runtime.DataModel.SalesAffiliationLoyaltyTier                   crtSalesAffiliationList;

        Microsoft.Dynamics.Commerce.Runtime.Services.PricingEngine.IPricingDataAccessor             pricingManager;


        container                                       resultCon = conNull();

        CLRObject                                       clrSalesAffiliations;

        CLRObject                                       clrSalesLines;

        RetailCustAffiliation                           retailCustAffiliation;

        str                                             defaultSalesUnit;

        str                                             lineId;

        RetailTempOrderItem                             tempOrderItem;

        System.DateTime                                 dateTime, dateTimeUtc;

        System.DateTimeOffset                           dateTimeOffsetUtc, dateTimeOffsetChannel;

        RetailCurrencyOperations                        currencyAndRoundingHelper;

        CLRObject                                       enumeratorSalesLine;

        RetailTransactionId                             transactionIdString         = System.Guid::NewGuid().ToString('N');

        CustTable                                       custTable                   = custTable::find(_customer);

        InventTable                                     inventTable                 =InventTable::find(_itemId);

        CurrencyCode                                    channelCurrency             = _currency;

        int                                             salesLinesOrderField        = 1;

        utcDateTime                                     simulationDateTime          = DateTimeUtil::utcNow();


        const str discountOfferIdProperty = 'DiscountOfferId';

        const str discountCodeProperty = 'Code';

        const str salesTransactionCouponsProperty = 'Coupons';


        defaultSalesUnit = InventTableModule::find(_itemId, ModuleInventPurchSales::Sales).UnitId;


        crtSalesTransaction = new Microsoft.Dynamics.Commerce.Runtime.DataModel.SalesTransaction();

        crtSalesTransaction.set_Id(transactionIdString);

        clrSalesLines = crtSalesTransaction.get_SalesLines();


        crtSalesLine = new Microsoft.Dynamics.Commerce.Runtime.DataModel.SalesLine();

        crtSalesLine.set_ItemId(_itemId);

        crtSalesLine.set_InventoryDimensionId('');

        crtSalesLine.set_Quantity(1);

        crtSalesLine.set_SalesOrderUnitOfMeasure(defaultSalesUnit);

        crtSalesLine.set_OriginalSalesOrderUnitOfMeasure(defaultSalesUnit);


if (<Variant Id>)

{

    InventDimCombination    dimCombination;

    dimCombination = InventDimCombination::findVariantId(rtSalesTrans.variantId);


    crtSalesLine.set_ProductId(dimCombination.DistinctProductVariant);

    crtSalesLine.set_MasterProductId(inventTable.Product);

//Refer this method getProductVariant on class RetailPricingSimulator 

    Microsoft.Dynamics.Commerce.Runtime.DataModel.ProductVariant productVariant = this.getProductVariant(<variantId>, <itemId>, <InventDimId>);

    crtSalesLine.set_Variant(productVariant);

}


        lineId = strRFix(int2str(salesLinesOrderField), 3, '0');


        crtSalesLine.set_LineId(lineId);

        crtSalesLine.set_LineNumber(salesLinesOrderField);

        clrSalesLines.Add(crtSalesLine);


        crtSalesTransaction.set_IsTaxIncludedInPrice(_retailChannel.PriceIncludesSalesTax);

        crtSalesTransaction.set_CustomerId(_customer);


        clrSalesAffiliations = crtSalesTransaction.get_AffiliationLoyaltyTierLines();

        // Add customer retail affiliations.

        If(_affiliationList == null)

        {

            while select retailCustAffiliation

                where retailCustAffiliation.CustAccountNum == _customer

            {

                crtSalesAffiliationList = new Microsoft.Dynamics.Commerce.Runtime.DataModel.SalesAffiliationLoyaltyTier();

                crtSalesAffiliationList.set_AffiliationId(retailCustAffiliation.RetailAffiliationId);

 crtSalesAffiliationTransaction.set_AffiliationType(CrtRetailAffiliationType::General);

//crtSalesAffiliationTransaction.set_AffiliationType(CrtRetailAffiliationType::Loyalty); // in case of loyalty discount

                clrSalesAffiliations.Add(crtSalesAffiliationList);

            }

        }

        else

        {

            RetailAffiliation       retailAffiliations;

            ListEnumerator      enumerator;

            enumerator = _affiliationList.getEnumerator();

            while(enumerator.moveNext())

            {

                retailAffiliations.clear();

                retailAffiliations = RetailAffiliation::findByName(enumerator.current(), false);

                if(retailAffiliations)

                {

                    crtSalesAffiliationList = new Microsoft.Dynamics.Commerce.Runtime.DataModel.SalesAffiliationLoyaltyTier();

                    crtSalesAffiliationList.set_AffiliationId(retailAffiliations.RecId);

                    clrSalesAffiliations.Add(crtSalesAffiliationList);

                }

            }

        }


        dateTime = Global::utcDateTime2SystemDateTime(simulationDateTime);


        dateTimeUtc = new System.DateTime(dateTime.get_Ticks(), System.DateTimeKind::Utc);


        dateTimeOffsetUtc = new System.DateTimeOffset(dateTimeUtc);

        dateTimeOffsetChannel =  System.TimeZoneInfo::ConvertTimeBySystemTimeZoneId(dateTimeOffsetUtc, _retailChannel.ChannelTimeZoneInfoId);

        if(_orderNo)

        {

            //Create CRT for COUPONS

            CLRObject couponCollection;

            PropertyInfo propertyInfo = crtSalesTransaction.GetType().GetProperty(salesTransactionCouponsProperty);

            if (propertyInfo)

            {

                couponCollection = System.Activator::CreateInstance(propertyInfo.PropertyType);

                propertyInfo.SetValue(crtSalesTransaction, couponCollection);

            }

            else

            {

                throw error("@Retail:CouponsCreationError");

            }


            System.Type couponType;

            if (couponCollection)

            {

                System.Type[] argumentTypes = couponCollection.GetType().GetGenericArguments();

                if (argumentTypes && argumentTypes.Length > 0)

                {

                    couponType = argumentTypes.GetValue(0);

                }

            }


            if (couponType)

            {

                PropertyInfo discountOfferIdPropertyInfo = couponType.GetProperty(discountOfferIdProperty);

                PropertyInfo codePropertyInfo = couponType.GetProperty(discountCodeProperty);

        

                if (discountOfferIdPropertyInfo && codePropertyInfo)

                {

                    RetailCouponUsage retailCouponUsage;

                    RetailCouponCodeTable retailCouponCodeTable;

                    RetailCoupon retailCoupon;


                    while select retailCouponUsage

                    where retailCouponUsage.SalesId == _orderNo

                        join  retailCouponCodeTable

                            where retailCouponCodeTable.CouponCodeId == retailCouponUsage.CouponCodeId

                        join retailCoupon

                            where retailCoupon.CouponNumber == retailCouponCodeTable.CouponNumber

                    {

                        SalesTable salesTable = SalesTable::find(_orderNo);

                        RetailSalesTable retailSalesTable = RetailSalesTable::findSalesTable(salesTable);

                    

                        if(!retailSalesTable.RetailChannel)

                        {

                            throw error("@Retail:CouponChannelNotFound");

                        }


                        // Add coupon to list if valid.

                        if (RetailCouponHelper::validateCoupon(retailCouponCodeTable, retailSalesTable.RetailChannel)

                            && RetailCouponHelper::ValidateCouponLimits(retailCouponCodeTable.CouponCodeId, _retailChannel.RetailChannelId, _customer, _orderNo))

                        {

                            CLRObject coupon = System.Activator::CreateInstance(couponType);

                            discountOfferIdPropertyInfo.SetValue(coupon, retailCoupon.DiscountOfferId);

                            codePropertyInfo.SetValue(coupon, retailCouponCodeTable.CouponCode);

                            couponCollection.Add(coupon);

                        }

                    }

                }

            }

        }

        pricingManager = new RetailPricingDataManagerSimulator(_retailChannel.RecId, transactionIdString, false, tempOrderItem, true);        

        tempOrderItem.clear();

        tempOrderItem.itemId = _itemId;

        tempOrderItem.Product = inventTable.Product;

        tempOrderItem.insert();

        currencyAndRoundingHelper = new RetailCurrencyOperations(CompanyInfoHelper::standardCurrency());

        Microsoft.Dynamics.Commerce.Runtime.Services.PricingEngine.PricingEngine::SetCollectDiagnostics(crtSalesTransaction, true);

        // Calculate prices.

        Microsoft.Dynamics.Commerce.Runtime.Services.PricingEngine.PricingEngine::CalculatePricesForTransaction(

            crtSalesTransaction,

            pricingManager,

            currencyAndRoundingHelper,

            custTable.PriceGroup,

            channelCurrency,

            dateTimeOffsetUtc); // dateTimeOffsetChannel (error at runtime)- replace with dateTimeOffsetUtc


        diagnosticsObjectPrices = Microsoft.Dynamics.Commerce.Runtime.Services.PricingEngine.PricingEngine::GetPricingEngineDiagnosticsObject(crtSalesTransaction);


        Microsoft.Dynamics.Commerce.Runtime.Services.PricingEngine.PricingEngine::SetCollectDiagnostics(crtSalesTransaction, true);


        // Calculate discounts.

        Microsoft.Dynamics.Commerce.Runtime.Services.PricingEngine.PricingEngine::CalculateDiscountsForLines(

            pricingManager,

            crtSalesTransaction,

            currencyAndRoundingHelper,

            channelCurrency,

            custTable.LineDisc,

            custTable.MultiLineDisc,

            custTable.EndDisc,

            true,

            false,

            dateTimeOffsetUtc); // dateTimeOffsetChannel (error at runtime)- replace with dateTimeOffsetUtc


        diagnosticsObjectDiscounts =  Microsoft.Dynamics.Commerce.Runtime.Services.PricingEngine.PricingEngine::GetPricingEngineDiagnosticsObject(crtSalesTransaction);

        

        clrSalesLines = crtSalesTransaction.get_SalesLines();

        enumeratorSalesLine = clrSalesLines.GetEnumerator();


        while (enumeratorSalesLine.MoveNext())

        {

            crtSalesLine = enumeratorSalesLine.get_Current();

            resultCon += [crtSalesLine.get_Price(), crtSalesLine.get_DiscountAmount()];

        }


        return  crtSalesLine.get_Price() - crtSalesLine.get_DiscountAmount(); //Considering price - discount as original price

    }

Thursday, February 10, 2022

Export label custom content

 GRID => Properties "Export Label" => "SalesReportMexico" To get download file with custom naming.