adsenseheader

Saturday, April 4, 2020

Get packing slip id for the Posted Invoice in Dynamics AX

Hi Guys,

If you are looking for code that needs to find a Packing slip Id for the posted Customer Invoice in Dynamics AX 365 for operations.

Below is the code that helps you out!


static void getPackingSlip(Args _args)
{
    CustInvoiceJour     custInvoiceJour;
    SalesParmTable      salesParmTable;
    CustPackingSlipJour custPackingSlipJour;
    SalesParmSubLine    salesParmSubLine;
    SalesParmLine       salesParmLine;

    custInvoiceJour = CustInvoiceJour::findRecId(35637193385);
    select firstOnly salesParmTable
        where salesParmTable.ParmId == custInvoiceJour.ParmId
            && salesParmTable.Ordering == DocumentStatus::Invoice;

    //in case of mulitple packing slip selected in invoice
    while select DocumentId from salesParmSubLine
            exists join salesParmLine
            where salesParmSubLine.LineRefRecId == salesParmLine.RecId
                && salesParmLine.ParmId          == salesParmTable.ParmId
                && salesParmLine.TableRefId      == salesParmTable.TableRefId
    {
        select firstOnly custPackingSlipJour
            where custPackingSlipJour.PackingSlipId == salesParmSubLine.DocumentId
                && custPackingSlipJour.SalesId == salesParmTable.SalesId;
        info(strFmt("%1-%2-%3-%4",custPackingSlipJour.DeliveryDate,custPackingSlipJour.PackingSlipId,salesParmTable.SalesId,custInvoiceJour.InvoiceId));
    }
}

Thursday, April 2, 2020

Post Partial Purchase Order Lines through Code in AX 365 for opeartions

Hi Guys,

The below code shall help you to post the Purchase order line level Product receipt posting. Basically, its a partial Product receipt posting.

     public static void main(Args _args)
    {

                   Query        query;
                   SysQueryRun        queryRun;
                   QueryBuildDataSource qbds;


                      ttsbegin;
select firstonly1 purchLinePost
                        where purchLinePost.InventTransId == "xxxxx";

    query = new Query(QueryStr(PurchUpdatePackingSlip));
                    qbds = query.dataSourceTable(tableNum(PurchLine));
                    qbds.addRange(fieldNum(PurchLine, RecId)).value(queryValue(purchLinePost.RecId));
                    queryRun = new SysqueryRun(query);

                    purchFormLetter = PurchFormLetter::construct(DocumentStatus::PackingSlip);
                    purchFormLetter.chooseLinesQuery(queryRun);
                    purchFormLetter.update(icPurchTable,icPurchTable.PurchId);
                    ttscommit;
      }

Note: Use SysQueryRun object instead of QueryRun.

Happy Daxing!!

Regards,
Pradeep


Tuesday, February 25, 2020

Call an external webservice from AX D365 for Operations

Hi,

The below code can be used to call an external web service from AX D365 for operations.

public static void main(Args _args)
    {   
        System.Net.HttpWebRequest request = null;
        System.Net.HttpWebResponse response = null;
        CLRObject webResponse;
        System.Net.WebHeaderCollection headers;
        System.IO.MemoryStream stream;
        Binary requestContent;
        str responseData;
        System.Exception ex;
        System.Net.WebException webException;
        RetailWebResponse retailWebResponse;
        int httpStatusCode;
        str contentType;
        RetailWebRequest _request;
        System.IO.Stream streamLoc;

        try
        {
            request = System.Net.WebRequest::Create("https://www.google.co.in/") as System.Net.HttpWebRequest;
            _request = RetailWebRequest::newUrl("https://www.google.co.in/");

            if (strLen(_request.parmMethod()) > 0)
            {
                request.set_Method(_request.parmMethod());
            }

            headers = request.get_Headers();
            if (strLen(_request.parmHeader()) > 0)
            {
                headers.Add(_request.parmHeader());
            }

            if (strLen(_request.parmContentType()) > 0)
            {
                request.set_ContentType(_request.parmContentType());
            }

            requestContent = _request.parmContent();
            if (requestContent)
            {
                streamLoc = requestContent.getMemoryStream();
                System.Byte[] _bytes = stream.ToArray();


                request.set_ContentLength(_bytes.get_Length());

                streamLoc = request.GetRequestStream();
                streamLoc.Write(_bytes, 0, _bytes.get_Length());
                streamLoc.Close();
            }

            webResponse = request.GetResponse();
            response = webResponse as System.Net.HttpWebResponse;
        }
        catch (Exception::CLRError)
        {
            ex = ClrInterop::getLastException();
            if (ex != null)
            {
                ex = ex.get_InnerException();
                if ((ex != null) && (ex is System.Net.WebException))
                {
                    webException = ex as System.Net.WebException;
                    webResponse = webException.get_Response();
                    response = webResponse as System.Net.HttpWebResponse;
                }
            }
        }
    }

Regards,
Pradeep

Thursday, January 30, 2020

Export to Excel in Dynamics AX 365 for operations

Hi Guys,

The below code shall take the input parameters for filtering the query and export the data to excel.

using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using OfficeOpenXml.Table;

class MOETExport
{
    VendAccount accountNum;
    TransDate fromDate, todate;
    NoYesId resetMOET;

    public VendAccount parmAccountNum(VendAccount _accountNum = accountNum)
    {
        accountNum = _accountNum;

        return accountNum;
    }

    public NoYesId parmResetMOET(NoYesId _resetMOET = resetMOET)
    {
        resetMOET = _resetMOET;

        return resetMOET;
    }

    public TransDate parmFromDate(TransDate _fromDate = fromDate)
    {
        fromDate = _fromDate;

        return fromDate;
    }

    public TransDate parmToDate(TransDate _todate = todate)
    {
        todate = _todate;

        return todate;
    }

public void run()
    {
#define.Standard('Standard')
        #define.Student('Student')
        #define.STD('STD')
        #define.STU('STU')


PurchLine purchLine;
        Query query = new Query();
        QueryBuildDataSource qbdsPurchTable;
        QueryBuildDataSource qbdsTransDetails;
        QueryBuildDataSource qbds;
        QueryRun qr;
        TransDetails transDetails;
        DictRelation            dictRelation;
        MemoryStream memoryStream = new MemoryStream();

        try
        {
            accountNum = this.parmAccountNum();
            fromDate = this.parmFromDate() ? this.parmFromDate() : dateNull();
            todate = this.parmToDate() ? this.parmToDate() : dateMax();
            resetMOET = this.parmResetMOET();

            if (fromDate > todate)
            {
                throw Error("@SYS120590");
            }

            qbdsPurchTable = query.addDataSource(tableNum(PurchTable));
            qbds = qbdsPurchTable.addDataSource(tableNum(PurchLine));
            qbds.relations(true);

            qbdsTransDetails = qbds.addDataSource(tableNum(TransDetails));
            dictRelation = new DictRelation(tableNum(TransDetails));
            dictRelation.loadTableRelation(tableNum(PurchLine));
            qbdsTransDetails.addRelation(dictRelation);

            if (accountNum)
            {
                qbdsPurchTable.addRange(fieldNum(PurchTable, OrderAccount)).value(accountNum);
            }

            if (fromDate && todate)
            {
                qbdsPurchTable.addRange(fieldNum(PurchTable, CreatedDateTime)).value(queryRange(fromDate,todate));
            }

            if (resetMOET)
            {
                qbdsTransDetails.addRange(fieldNum(TransDetails, MOETExported)).value(queryValue(NoYes::Yes));

                qr = new QueryRun(query);
 
                while (qr.next())
                {
                    purchLine = qr.get(tableNum(PurchLine));

                    transDetails = TransDetails::findfromPurchLine(purchLine.RecId,true);

                    ttsbegin;
                    transDetails.MOETExported = NoYes::No;
                    transDetails.doUpdate();
                    ttscommit;
                }

                qbdsTransDetails.clearRanges();
            }

            qbdsTransDetails.addRange(fieldNum(TransDetails, MOETExported)).value(queryValue(NoYes::No));

            qr = new QueryRun(query);

            using (var package = new ExcelPackage(memoryStream))
            {
                var currentRow = 1;
                var worksheets = package.get_Workbook().get_Worksheets();
                var MOETWorksheet = worksheets.Add("ExportMOET");
                var cells = MOETWorksheet.get_Cells();
                OfficeOpenXml.ExcelRange cell = cells.get_Item(currentRow, 1);

                System.String value = fieldPName(PurchLine,DeliveryName);
                cell.set_Value(value);
                cell = null;

                value = fieldPName(PurchLine,PurchId);
                cell = cells.get_Item(currentRow, 2);
                cell.set_Value(value);

                value = "UsageDate";
                cell = cells.get_Item(currentRow, 3);
                cell.set_Value(value);

                value = "UsageMonth";
                cell = cells.get_Item(currentRow, 4);
                cell.set_Value(value);

                value = "UsageYear";
                cell = cells.get_Item(currentRow, 5);
                cell.set_Value(value);

                value = fieldPName(TransDetails,AgreementNumber);
                cell = cells.get_Item(currentRow, 6);
                cell.set_Value(value);

                value = "@SYS9367";
                cell = cells.get_Item(currentRow, 7);
                cell.set_Value(value);

                value = fieldPName(TransDetails,ProductSKU);
                cell = cells.get_Item(currentRow, 8);
                cell.set_Value(value);

                value = fieldPName(purchLine,QtyOrdered);
                cell = cells.get_Item(currentRow, 9);
                cell.set_Value(value);

                value = "@SYS319915";
                cell = cells.get_Item(currentRow, 10);
                cell.set_Value(value);

                value = fieldPName(TransDetails,BillingOption);
                cell = cells.get_Item(currentRow, 11);
                cell.set_Value(value);

                value = "OfferingType";
                cell = cells.get_Item(currentRow, 12);
                cell.set_Value(value);

                value = fieldPName(TransDetails,UsageCountry);
                cell = cells.get_Item(currentRow, 13);
                cell.set_Value(value);

                value = fieldPName(PurchLine,CustPurchaseOrderFormNum);
                cell = cells.get_Item(currentRow, 14);
                cell.set_Value(value);
 
                while (qr.next())
                {
                    currentRow ++;
                    NameAlias offeringVal;

                    purchLine = qr.get(tableNum(PurchLine));

                    transDetails = TransDetails::findfromPurchLine(purchLine.RecId,true);

                    if (!transDetails.MOETExported)
                    {
                        if (transDetails.Offering == #Standard)
                        {
                            offeringVal = #STD;
                        }

                        else if (transDetails.Offering == #Student)
                        {
                            offeringVal = #STU;
                        }

                        else
                        {
                            offeringVal = transDetails.Offering;
                        }

                        cell = null;
                        cell = cells.get_Item(currentRow, 1);
                        cell.set_Value(purchLine.DeliveryName);
                         
cell = null;
                        cell = cells.get_Item(currentRow, 2);
                        cell.set_Value(purchLine.PurchId);

                        cell = null;
                        cell = cells.get_Item(currentRow, 3);
                        cell.set_Value(DateTimeUtil::day(transDetails.UsageDate));

                        cell = null;
                        cell = cells.get_Item(currentRow, 4);
                        cell.set_Value(DateTimeUtil::month(transDetails.UsageDate));

                        cell = null;
                        cell = cells.get_Item(currentRow, 5);
                        cell.set_Value(DateTimeUtil::year(transDetails.UsageDate));

                        cell = null;
                        cell = cells.get_Item(currentRow, 6);
                        cell.set_Value(transDetails.AgreementNumber);

                        cell = null;
                        cell = cells.get_Item(currentRow, 7);
                        cell.set_Value(PurchLine.LineNumber);

                        cell = null;
                        cell = cells.get_Item(currentRow, 8);
                        cell.set_Value(transDetails.ProductSKU);

                        cell = null;
                        cell = cells.get_Item(currentRow, 9);
                        cell.set_Value(purchLine.QtyOrdered);

                        cell = null;
                        cell = cells.get_Item(currentRow, 10);
                        cell.set_Value(purchLine.itemName());

                        cell = null;
                        cell = cells.get_Item(currentRow, 11);
                        cell.set_Value(transDetails.BillingOption);

                        cell = null;
                        cell = cells.get_Item(currentRow, 12);
                        cell.set_Value(offeringVal);

                        cell = null;
                        cell = cells.get_Item(currentRow, 13);
                        cell.set_Value(transDetails.usageCountry);

                        cell = null;
                        cell = cells.get_Item(currentRow, 14);
cell.set_Value(purchLine.CustPurchaseOrderFormNum);
                    }
                        ttsbegin;
                        transDetails.MOETExported = NoYes::Yes;
                        transDetails.doUpdate();
                        ttscommit;
                }
                package.Save();
                file::SendFileToUser(memoryStream, 'MOETExport.xlsx');
            }

}
        catch (Exception::Error)
        {
            throw Exception::Error;
        }
    }

public static void main(Args _args)
    {
        Dialog dialog = new Dialog("@SCM:PurchPurchaseOrderLineEntityExport");
        DialogGroup dialogGroup;
        DialogField dialogAccountId;
        DialogField dialogFromDate;
        DialogField dialogToDate;
        DialogField dialogResetMOET;
        MOETExport moetExport = new MOETExport();

        dialogGroup = dialog.addGroup("@SYS8079");
        dialogAccountId = dialog.addField(extendedTypeStr(VendAccount));

        dialogGroup = dialog.addGroup("@SYS41297");
        dialogGroup.columns(2);
        dialogFromDate = dialog.addField(extendedTypeStr(FromDate));
        dialogToDate   = dialog.addField(extendedTypeStr(ToDate));

        dialogGroup = dialog.addGroup("ResetMOET");
        dialogGroup.columns(1);
        dialogResetMOET = dialog.addField(extendedTypeStr(NoYesId));
        dialogResetMOET.helpText("ResetMOETHelpTxt");

        if (dialog.run())
        {
            moetExport.parmAccountNum(dialogAccountId.value());
            moetExport.parmFromDate(dialogFromDate.value());
            moetExport.parmToDate(dialogToDate.value());
            moetExport.parmResetMOET(dialogResetMOET.value());
            moetExport.run();
        }
    }

}

Regards,
Pradeep

Thursday, December 12, 2019

AOD flush in D365 for operations

HI,

Below post shall help you in clearing the AOD flush

// Class to clear the cache, build a URL to call it:

https://[AOS NAME].cloudax.dynamics.com/?mi=SysClassRunner&cls=SysFlushAOD

or

https://[AOS NAME].cloudax.dynamics.com/?mi=action:SysFlushAOD

Regards,
Pradeep

Monday, November 18, 2019

Create Ledger dimension only with MainAccount in AX 365 for operations

HI,

The below code shall help you to create a Ledger Dimension through MainAccountNum in 365 for operations.


LedgerDimensionFacade::serviceCreateLedgerDimension(
            LedgerDefaultAccountHelper::getDefaultAccountFromMainAccountRecId(
                MainAccount::findByMainAccountId(_mainAccountId).RecId),
            0);

Regards,
Pradeep

Monday, November 4, 2019

Additional voucher creation for an Procurement item, Correct and Cancel Product receipt for Purchase Order in D365 for opeartions

Hi Guys,

Below code shall help in  creating additional Vouchers for a Procurement item and also correcting and canceling the Product receipt.

Distributes amount based on the Accounting distribution setup on the Purchase order line


[ExtensionOf(classStr(PurchPackingSlipJournalPost))]
final class ABC_PurchPackingSlipJournalPost_Extension
{
    protected void postSingleLine(boolean _countryRegion_RU,
                                  boolean _hasQualityOrder,
                                  boolean _isExciseEnableIN,
                                  boolean _isVATEnableIN,
                                  boolean _isCustomsEnableIN,
                                  boolean _isConfigurationkeyRetailEnabled)
    {
        LedgerDimensionAccount          ledgerDimensionId;
        AccountingDistribution          accountingDistribution;
        LedgerDimensionDefaultAccount   ledgerDefaultAccount;
        LedgerDimensionDefaultAccount   ledgerDefaultAccountOffset;
        DimensionDefault                defaultDim;
        Amount                          gstAmount;
        Amount                          creditAmount;
        Amount                          debitAmount;
        LedgerVoucher                   ledgerVoucher;
        LedgerVoucherTransObject        ledgerVoucherTransObject;
        CurrencyCode                    standardCurrencyCode;
        LedgerVoucherObject             ledgerVoucherObject;
        CurrencyExchangeHelper          currencyExchHelper;

        xyz_POItemFeeTable              POItemFeeTable;
        PurchLine                       purchLineLocal = this.sourceLine();

        next postSingleline (_countryRegion_RU,     _hasQualityOrder, _isExciseEnableIN, _isVATEnableIN, _isCustomsEnableIN,  _isConfigurationkeyRetailEnabled);

        PurchParmLine                   purchParmLine = this.purchParmLine;
        PurchParmLine                   purchParmLineloc = this.purchParmLine;
        SourceDocumentLine              sourceDocumentLine;
        Qty                             res = purchParmLineloc.purchQtyCorrection();
        AccountingDistribution          accDist;
        AccountingDistribution          revAccDist;
        SourceDocumentLine              sourceDocLine;
        PurchTable                      purchTable = PurchTable::find(purchline.PurchId);
        AllocationFactor                allocationFactor;

        while select forupdate RecId from sourceDocLine
                where
                    sourceDocLine.SourceDocumentHeader == purchTable.SourceDocumentHeader
            join forupdate accDist
                where
                    accDist.SourceDocumentLine == sourceDocLine.RecId &&
                    accDist.ReferenceRole != AccountingDistributionReferenceRole::Reversing
            notexists join revAccDist
                where
                    (   revAccDist.ReferenceDistribution == accDist.RecId &&
                        revAccDist.SourceDocumentLine == sourceDocLine.RecId &&
                        revAccDist.ReferenceRole == AccountingDistributionReferenceRole::Reversing
                    )
                    ||
                    (
                        revAccDist.ReferenceDistribution == accDist.RecId &&
                        revAccDist.SourceDocumentLine == sourceDocLine.RecId &&
                        revAccDist.ReferenceRole == AccountingDistributionReferenceRole::Adjusting
                    )
        {
            if (accDist.AllocationFactor == 1.0)
            {
                continue;
            }

            allocationFactor += accDist.AllocationFactor;
         
            if (purchLineLocal.ProcCatRecoverable_xyz== NoYes::Yes)
            {
                Amount exclGst =   xyz_ItemFeeTable::findByPurchLine(purchLineLocal.recId).RecoveryAmountExclGST;
                if (this.versioningUpdateType == VersioningUpdateType::Correction)
                {
                    gstAmount = ((exclGst /purchLineLocal.PurchQty ) * res) * accDist.AllocationFactor;
                    creditAmount = -decRound(gstAmount,2);
                    debitAmount  = creditAmount * -1;
                }

                else if (this.versioningUpdateType == VersioningUpdateType::Cancel)
                {
                    gstAmount = xyz_ItemFeeTable::findByPurchLine(purchLineLocal.recId).RecoveryAmountExclGST / purchLineLocal.PurchQty;
                    creditAmount = -(gstAmount * res) * accDist.AllocationFactor;
                    creditAmount = decRound(creditAmount,2);
                    debitAmount  = creditAmount * -1;
                }
                else
                {
                    gstAmount = 0 ;
                    creditAmount = ((xyz_ItemFeeTable::findByPurchLine(purchLineLocal.recId).RecoveryAmountExclGST /purchLineLocal.PurchQty ) * purchParmLineloc.ReceiveNow) * accDist.AllocationFactor  ;
                    creditAmount = decRound(creditAmount,2);
                    debitAmount  = -creditAmount;
                }
         

                ledgerDefaultAccount = InventPosting::accountItemLedgerDimensionFromParameters(InventPostingAccountItemLedgerDimensionParameters::newFromParameters(
                                                                                        InventAccountType::RevenueAccrual_xyz,
                                                                                        purchLineLocal.ItemId,
                                                                                        purchLineLocal.inventTable().itemGroupId(),
                                                                                        purchLineLocal.ProcurementCategory,
                                                                                        purchLineLocal.VendAccount,
                                                                                        purchLineLocal.VendGroup,
                                                                                        purchLineLocal.TaxGroup
                                                                                        ));
                ledgerDimensionId = LedgerDimensionFacade::serviceCreateLedgerDimension(ledgerDefaultAccount);

                ledgerVoucher = this.ledgerVoucher;
         
                ledgerVoucherObject = this.findOrCreateLedgerVoucherObject(this.getVoucher(), this.updateDate());
         
                standardCurrencyCode = CompanyInfoHelper::standardCurrency();
                currencyExchHelper = CurrencyExchangeHelper::newExchangeDate(Ledger::current(), systemDateGet());

                ledgerVoucherTransObject =  LedgerVoucherTransObject::newTransactionAmountDefault(ledgerVoucherObject  ,
                                                                                                    LedgerPostingType::RevenueAccrual_xyz,
                                                                                                    ledgerDimensionId,
                                                                                                    standardCurrencyCode,
                                                                                                    debitAmount,
                                                                                                    currencyExchHelper);

                ledgerVoucher.addTrans(ledgerVoucherTransObject);

                //for credit account
                ledgerDefaultAccount = InventPosting::accountItemLedgerDimensionFromParameters(InventPostingAccountItemLedgerDimensionParameters::newFromParameters(
                                                                                        InventAccountType::RevenuePurchReceipt_xyz,
                                                                                        purchLineLocal.ItemId,
                                                                                        purchLineLocal.inventTable().itemGroupId(),
                                                                                        purchLineLocal.ProcurementCategory,
                                                                                        purchLineLocal.VendAccount,
                                                                                        purchLineLocal.VendGroup,
                                                                                        purchLineLocal.TaxGroup
                                                                                        ));

                defaultDim = LedgerDimensionFacade::getDefaultDimensionFromLedgerDimension(accDist.ledgerdimension);

                ledgerDimensionId = LedgerDimensionFacade::serviceCreateLedgerDimension(ledgerDefaultAccount);
                ledgerDefaultAccountOffset = LedgerDimensionFacade::serviceMergeLedgerDimensions(ledgerDimensionId,accDist.ledgerdimension);
                ledgerVoucherTransObject =  LedgerVoucherTransObject::newTransactionAmountDefault(ledgerVoucherObject,
                                                                                                    LedgerPostingType::RevenuePurchReceipt_xyz,
                                                                                                    ledgerDefaultAccountOffset,
                                                                                                    standardCurrencyCode,
                                                                                                    creditAmount,
                                                                                                    currencyExchHelper);
                ledgerVoucherObject.addTrans(ledgerVoucherTransObject);
                ledgerVoucherObject.parmVoucherCheck(false);
            }

            if (allocationFactor == 1.0)
            {
                break ;
            }
        }
    }

}


Thanks,
Pradeep