Tuesday, June 27, 2023

Code to Upoload CSV file of Vendor payment journal to Azure blob storage when posted in D365 X++

 using Microsoft.WindowsAzure.Storage;

Using Microsoft.WindowsAzure.Storage.Blob;

[ExtensionOf(classStr(LedgerJournalPost))]

internal final class DaxLedgerJournalPost_Extension

{

    public static void post(Common  _record,TableId _tableId,

    NoYes _transferErrors,

            boolean _splitLargeJournal,

            boolean _suppressClientMessages,

            str _callingFormName,LedgerJournalEngine _ledgerJournalEngine,

                            boolean _skipIL_RU,LedgerJournalCheckPostResults _results_RU,boolean _progressBarHide)

    {

        LedgerJournalTable  ledgerJounralTable;

        LedgerJournalTrans  ledgerjournalTrans;

        LedgerJournalPost  post = new LedgerJournalPost();

        next post(_record, _tableId, _transferErrors, _splitLargeJournal, _suppressClientMessages, _callingFormName, _ledgerJournalEngine, _skipIL_RU, _results_RU, _progressBarHide);

        if(_record.TableId == tableNum(LedgerJournalTrans))

        {

            ledgerjournalTrans = _record;

            ledgerJounralTable = LedgerJournalTable::find(ledgerjournalTrans.JournalNum);

        }

        if(_record.TableId == tableNum(LedgerJournalTable))

        {

            ledgerJounralTable = _record;

        }

        post.csvfile(ledgerJounralTable);


    }


//Method to create CSv file and upload it to AzureBlob storage.

public void csvfile(LedgerJournalTable  ledgerJournalTable)

{

        CloudStorageAccount                                 storageAccount;

        PersonnelIntegrationStorageAccountConnectionString  azureStorageKey;

        storageAccount = CloudStorageAccount::Parse("DefaultEndpointsProtocol=https;AccountName=lohithstorageaccount123;AccountKey=C1XNEuXtv0GIB2FQ18iFEuZgafJEcMVGE/m1G3sjoTnbni9tCK1htweacZwuLZxrc/9nlksRVvLg+AStVpXnqA==;EndpointSuffix=core.windows.net"); // AccessKey connection string of storage Account.

        System.Byte[]   reportBytes = new System.Byte[0]();

        System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

        CloudBlobClient     blobClient;

        CloudBlobContainer  blobContainer;

        CloudBlockBlob      blockblob;

        CloudBlobDirectory      cbDir;

        str   ledgerDim;

        str                 containerName = "lohithcontainer", dirPath;

        dirPath = "newfolder";

        XmlDocument doc;

        commaStreamIo       iO = commaStreamIo::constructForWrite();

        Filename            filename = "MyFile.csv";

          //  Field List;

        container header = ["JournalNumber","VoucherNumber","Account number","Date","Debit","Credit"];

        iO.writeExp(header);

        header = conNull();

        LedgerJournalTrans  ledgerJournalTrans;

          while select ledgerJournalTrans

            where ledgerJournalTrans.JournalNum == ledgerJournalTable.JournalNum

        {

            ledgerDim = LedgerDimensionFacade::getDisplayValueForLedgerDimension(ledgerJournalTrans.LedgerDimension);

            container line =  [ledgerJournalTrans.JournalNum,ledgerJournalTrans.Voucher,ledgerDim,ledgerJournalTrans.TransDate,ledgerJournalTrans.AmountCurDebit,ledgerJournalTrans.AmountCurCredit];

              iO.writeExp(line);

        }

        System.IO.Stream stream = iO.getStream();

        stream.Position = 0;

        System.IO.StreamReader reader = new System.IO.StreamReader(stream);

        str  csvFileContent = reader.ReadToEnd();

        File::SendStringAsFileToUser(csvFileContent,  filename);

        info(strFmt("CSV file %1 is created", filename));

        if(storageAccount && containerName)

        {

            blobClient      = storageAccount.CreateCloudBlobClient();

            blobContainer   = blobClient.GetContainerReference(containerName);

            cbDir           = blobContainer.GetDirectoryReference(dirPath);

            blockblob       = cbDir.GetBlockBlobReference(filename);

            if (blockBlob)

            {

                if (stream)

                {

                    stream.Position = 0;

                    blockBlob.UploadFromStream(stream,null,null,null);

                    blockBlob.FetchAttributes(null, null, null);

                  }

            }

        }

    }

  }

Accounts Payable>Payments>Vendor Payment Journal.


Storage Account > Bob >Container > New Folder> file.







Code to display the value of Ledger dimension in d365 X++

     public static void main(Args _args)

    {

        str         ledgerAccount;

        int64    dimension = 68719705755;

        ledgerAccount = LedgerDimensionFacade::getDisplayValueForLedgerDimension(dimension);

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

    }

Output :


Other way :

DimensionAttributeLevelValueAllView






Monday, June 26, 2023

Code to export all vendors to XML file using X++ in D365

 public static void main(Args _args)

    {

        VendAccount vendAcc;

        XmlDocument doc;

        XmlElement nodeXml,Audit; //Main nodes.

        XmlElement nodeTable,BusinessUnit,AlternateId,VendorCustomFields; //Sub nodes

        XmlElement  nodeAccount,name,name2,StreetAddress1,

                    City,State,PostalCode,Country,ContactName,

                    ContactPhone,ContactFax,ContactEmail,BusinessUnitID,BusinessUnitName,

                    Status,PaymentMethod,PaymentTerm,AlternateType,AlternateIDNbr,

                    CFNbr,Value,Description,VendorCount;

        XmlElement nodeName;

        int x = 0;      

        VendTable    vendTable;

        DirPartyLocation    dirpartylocation;

        DirPartyTable    dirPartyTable,dir;

        LogisticsPostalAddress  logisticsPostalAddress,logisticsPostalAddressloc;

        LogisticsLocation    logisticsLocation;

        LogisticsElectronicAddress  logisticsElectronicAddress,logisticsFax,logisticsEmail;

        CompanyInfo company;

        #define.filename(@'C:\Temp\accountsloc.xml')  //creates a file in Temp folder of c drive.

        doc = XmlDocument::newBlank();

        nodeXml = doc.createElement('xml');     //creates a new node. Starting point = xml

        doc.appendChild(nodeXml);

        while select vendTable

             where vendTable.Blocked == CustVendorBlocked::No

        {

            vendAcc = vendTable.AccountNum;

            select dirPartyTable

                where dirPartyTable.RecId == vendTable.Party;

            select logisticsPostalAddress

                 where logisticsPostalAddress.Location == dirPartyTable.PrimaryAddressLocation;

           select logisticsLocation

                where logisticsLocation.RecId == dirPartyTable.PrimaryAddressLocation;

            x++; //To get count of vendor.

            company = CompanyInfo::find();

            dir = DirPartyTable::findRec(vendtable.Party);

            logisticsElectronicAddress = LogisticsElectronicAddress::findRecId(dir.PrimaryContactPhone,true);


            logisticsFax   =   LogisticsElectronicAddress::findRecId(dir.PrimaryContactFax);

            logisticsEmail = LogisticsElectronicAddress::findRecId(dir.PrimaryContactEmail);

            nodeTable = doc.createElement("vendor");   // create a subnmode to xml node as Vendor inside xml


            nodeXml.appendChild(nodeTable);

            nodeAccount = doc.createElement("CustomersVendorNbr");

            nodeAccount.appendChild(doc.createTextNode(vendTable.AccountNum));


            nodeTable.appendChild(nodeAccount);

            name = doc.createElement("Name");

            name.appendChild(doc.createTextNode(dirPartyTable.Name));

            nodeTable.appendChild(name);


            StreetAddress1 = doc.createElement("StreetAddress1");

            StreetAddress1.appendChild(doc.createTextNode(logisticsPostalAddress.Street));

            nodeTable.appendChild(StreetAddress1);


            City = doc.createElement("City");

            City.appendChild(doc.createTextNode(logisticsPostalAddress.City));

            nodeTable.appendChild(City);


            State = doc.createElement("State-Region");

            State.appendChild(doc.createTextNode(logisticsPostalAddress.state));

            nodeTable.appendChild(State);


            PostalCode = doc.createElement("PostalCode");

            PostalCode.appendChild(doc.createTextNode(logisticsPostalAddress.ZipCode));

            nodeTable.appendChild(PostalCode);


            Country = doc.createElement("Country");

            Country.appendChild(doc.createTextNode(logisticsPostalAddress.County));

            nodeTable.appendChild(Country);


            ContactName = doc.createElement("ContactName");

            ContactName.appendChild(doc.createTextNode(logisticsElectronicAddress.Description)); 

            nodeTable.appendChild(ContactName);


            ContactPhone = doc.createElement("ContactPhone");

            ContactPhone.appendChild(doc.createTextNode(logisticsElectronicAddress.locator)); 

            nodeTable.appendChild(ContactPhone);


            ContactFax = doc.createElement("ContactFax");

            ContactFax.appendChild(doc.createTextNode(logisticsFax.locator));

            nodeTable.appendChild(ContactFax);


            ContactEmail = doc.createElement("ContactEmail");

            ContactEmail.appendChild(doc.createTextNode(logisticsEmail.locator));

            nodeTable.appendChild(ContactEmail); 


            BusinessUnit = doc.createElement("BusinessUnit"); // create a node as business unit inside of vendor.

            nodeTable.appendChild(BusinessUnit);

            BusinessUnitID = doc.createElement("BusinessUnitID"); // To get Company Id eg:usmf 

            BusinessUnitID.appendChild(doc.createTextNode(vendTable.DataAreaId));

            BusinessUnit.appendChild(BusinessUnitID);


            BusinessUnitName = doc.createElement("BusinessUnitName"); // To get Company name.

            BusinessUnitName.appendChild(doc.createTextNode(company.Name));

            BusinessUnit.appendChild(BusinessUnitName);


            PaymentMethod = doc.createElement("PaymentMethod");

            PaymentMethod.appendChild(doc.createTextNode(vendTable.PaymMode));

            BusinessUnit.appendChild(PaymentMethod);


            PaymentTerm = doc.createElement("PaymentTerm");

            PaymentTerm.appendChild(doc.createTextNode(vendTable.PaymTermId));

            BusinessUnit.appendChild(PaymentTerm);


            AlternateID = doc.createElement("AlternateID"); //It is subnode of BusinessUnit. it is inside of Business unit as alternateId.

            BusinessUnit.appendChild(AlternateID);

            AlternateType = doc.createElement("AlternateType");

            AlternateType.appendChild(doc.createTextNode("ALT"));

            AlternateID.appendChild(AlternateType);

            AlternateIDNbr = doc.createElement("AlternateIDNbr"); // To get tax federal tax amount

            AlternateIDNbr.appendChild(doc.createTextNode(vendTable.Tax1099RegNum));

            AlternateID.appendChild(AlternateIDNbr);


            VendorCustomFields = doc.createElement("VendorCustomFields"); //It is subnode of BusinessUnit.it is inside of Business unit as VendorCustomFields .

            BusinessUnit.appendChild(VendorCustomFields);

            boolean values = false;

                         //loop to get address of vendor if purpose is Remit to only.

            while select dirpartylocation

                where dirpartylocation.Party == vendtable.Party

                && dirpartylocation.PostalAddressRoles == enum2Str(LogisticsLocationRoleType::RemitTo)

            {

                values = true;

                    select logisticsPostalAddressloc

                         where logisticsPostalAddressloc.Location == dirpartylocation.Location;

                    CFNbr = doc.createElement("CFNbr");

                    CFNbr.appendChild(doc.createTextNode("1"));

                    VendorCustomFields.appendChild(CFNbr);

                    Value = doc.createElement("Value");

                    Value.appendChild(doc.createTextNode(logisticsPostalAddressloc.Address));

                    VendorCustomFields.appendChild(Value);

                    Description = doc.createElement("Description");

                    Description.appendChild(doc.createTextNode(logisticsPostalAddressloc.Address));

                    VendorCustomFields.appendChild(Description);

            }

            if(!values)

            {

                CFNbr = doc.createElement("CFNbr");

                CFNbr.appendChild(doc.createTextNode("1"));

                VendorCustomFields.appendChild(CFNbr);


                Value = doc.createElement("Value");

                VendorCustomFields.appendChild(Value);


                Description = doc.createElement("Description");

                VendorCustomFields.appendChild(Description);

            }

                }

        Audit = doc.createElement("Audit");

        nodeXml.appendChild(Audit);

        VendorCount = doc.createElement("VendorCount");

        VendorCount.appendChild(doc.createTextNode(int2Str(x))); //To get the count of loop. vendors

        Audit.appendChild(VendorCount);

        doc.save(#filename);

        Info(strFmt("file created"));

    }


Output :



Wednesday, June 21, 2023

Code to open TransTaxinformation form from purcheditlines form in D365 X++

 [ExtensionOf(formcontrolstr(PurchEditLines,TaxInformation))]

internal final class Dax_PurchEditLInes_TaxInformation_Extension

{

    public void clicked()

    {

        Args            args;

        FormRun         formRun,formrunloca,formrunpurchtable;

        PurchLine       purchline;

        FormControl     formcontrol ;

        PurchParmLine   purchparmline;

        next clicked();

        formcontrol = any2Object(this);

        formrunloca = formcontrol.formRun();

        purchparmline = formrunloca.dataSource().cursor();

        select * from purchline

            where purchline.PurchId == purchparmline.OrigPurchId

            && purchline.ItemId     == purchparmline.ItemId;

        args = new Args();

        args.name(formStr(PurchTable));

        formrunpurchtable = new FormRun(args);

        formrunpurchtable.init();

        formrunpurchtable.run();

        formrunpurchtable.close();

        args.name(formStr(TransTaxInformation));

        args.record(purchline);

        args.caller(formrunpurchtable);

        formRun = New FormRun(args);

        formRun.init();

        formRun.run();

        formRun.wait();

     }

  }

Thursday, June 15, 2023

Code to get Opening balance for Ledgerdimension in D365

     public static void main(Args _args)

    {

        LedgerBalanceDimAttrValueComboAmounts   ledgerBalance;

        AmountMst                               opSum;

        DimensionAttributeValueCombination      dim;

        select dim where dim.RecId ==  68719651020; // recid of (110110-001-022)

        date dateTime,datetimeloc,fromdate,todate;

        fromdate = mkDate(01,01,2017);

        todate = mkDate(31,12,2017);

        dateTime = any2Date(DateTimeUtil::addYears(fromdate , -1));

        datetimeloc = any2Date(DateTimeUtil::addYears(todate , -1));

        ledgerBalance = LedgerBalanceDimAttrValueComboAmounts::construct();

        ledgerBalance.parmIncludeRegularPeriod(true);

        ledgerBalance.parmIncludeOpeningPeriod(true);

        ledgerBalance.parmIncludeClosingPeriod(false);

        ledgerBalance.parmAccountingDateRange(dateTime, datetimeloc);

        ledgerBalance.calculateBalance(dim);

        opSum = ledgerBalance.getAccountingCurrencyBalance();

        Info(strFmt("opening balance : %1 ",opSum));

     }

....................

Other Way:

       LedgerTrialBalanceDP        ledgerTrialBalanceDP;

       LedgerTrialBalanceContract  ledgerTrialBalanceContract;

       LedgerTrialBalanceTmp       ledgerTrialBalanceTmp,ledgerTrialBalanceTmpLoc;

       LedgerTrialBalanceTmp       ledgerTrialBalanceTmpCustom;

       DimensionHierarchy          dimensionHierarchy;

       List                        postingLayer;

       ledgerTrialBalanceDP        = new LedgerTrialBalanceDP();

       ledgerTrialBalanceContract  = new LedgerTrialBalanceContract();

       postingLayer                = new List(Types::Enum);

       dimensionHierarchy          = DimensionHierarchy::getMainAccountFocus();

       postingLayer.addEnd(CurrentOperationsTax::Current);

       ledgerTrialBalanceContract.parmFromDate(mkDate(01,01,2017));

       ledgerTrialBalanceContract.parmToDate(mkDate(31,12,2017));

       ledgerTrialBalanceContract.parmIncludeOpening(false);

       ledgerTrialBalanceContract.parmIncludeClosing(false);

       ledgerTrialBalanceContract.parmPostingLayers(postingLayer);

       ledgerTrialBalanceContract.parmPrimaryDimensionFocus("MA+BU+DEPT");

       ledgerTrialBalanceContract.parmIncludeClosingAdjustments(false);

       ledgerTrialBalanceContract.parmIncludeClosingTransactions(false);

       ledgerTrialBalanceContract.parmDisplayMainAccountCategory(false);

       ledgerTrialBalanceDP.parmDataContract(ledgerTrialBalanceContract);

       ledgerTrialBalanceDP.setTrialBalanceTmpTable(ledgerTrialBalanceTmp);

       ledgerTrialBalanceDP.processReport();

       ledgerTrialBalanceTmp = ledgerTrialBalanceDP.getLedgerTrialBalanceTmp();

       while  select ledgerTrialBalanceTmp

              where ledgerTrialBalanceTmp.DimensionValues[1]=="110110"

               &&ledgerTrialBalanceTmp.DimensionValues[2]=="001" //businessunit

              &&ledgerTrialBalanceTmp.DimensionValues[3]=="022" //department

       {

           Info(strFmt("%1",ledgerTrialBalanceTmp.OpeningBalance));

       }







Code to get opening balance and closing balance for Ledger Main account in D365

Code to get Opening balance for  MainAccount :

2017 year opening balance will be the closing balance of year 2016.

    public static void main(Args _args)

    {

        date dateTime,datetimeloc,fromdate,todate;

        fromdate = mkDate(01,01,2017);

        todate = mkDate(31,12,2017);

        LedgerBalanceMainAccountAmounts ledgerBalance,ledgerBalanceloc;

        AmountMst  opSum,closingbalance;

        dateTime = any2Date(DateTimeUtil::addYears(fromdate , -1));

        datetimeloc = any2Date(DateTimeUtil::addYears(todate , -1));

        ledgerBalance = LedgerBalanceMainAccountAmounts::construct();

        ledgerBalance.parmIncludeRegularPeriod(true);

        ledgerBalance.parmIncludeOpeningPeriod(true);

        ledgerBalance.parmIncludeClosingPeriod(false);

        ledgerBalance.parmAccountingDateRange(dateTime, datetimeloc);

        ledgerBalance.calculateBalance(MainAccount::findByMainAccountId('202300'));

        opSum = ledgerBalance.getAccountingCurrencyBalance();


        ledgerBalanceloc = LedgerBalanceMainAccountAmounts::construct();

        ledgerBalanceloc.parmIncludeRegularPeriod(true);

        ledgerBalanceloc.parmIncludeOpeningPeriod(true);

        ledgerBalanceloc.parmIncludeClosingPeriod(false);

        ledgerBalanceloc.parmAccountingDateRange(fromdate, todate);

        ledgerBalanceloc.calculateBalance(MainAccount::findByMainAccountId('202300'));

        closingbalance = ledgerBalanceloc.getAccountingCurrencyBalance();

        info(strFmt("Opening balance : %1",opSum));

        info(strfmt("Closing balance : %1", closingbalance));

     }




Reference blog : https://msdynamicsxx2012.blogspot.com/2018/02/code-to-get-opening-balance-for-ledger.html







Code to create ledger dimension from mainaccount in d365 X++

 public void main(Args args)

{

DimensionAttributeValueCombination      dimensionAttributeValueCombination;

DimensionServiceProvider DimensionServiceProvider = new DimensionServiceProvider();

LedgerAccountContract LedgerAccountContract = new LedgerAccountContract();

DimensionAttributeValueContract ValueContract;

DimensionStorage        dimStorage;

List ListValueContract = new List(Types::Class);


LedgerAccountContract.parmMainAccount("110110");

LedgerAccountContract.parmValues(ListValueContract);

dimStorage = DimensionServiceProvider::buildDimensionStorageForLedgerAccount(LedgerAccountContract);

dimensionAttributeValueCombination = DimensionAttributeValueCombination::find(dimStorage.save());

info(strfmt("Ledger dimension %1",dimensionAttributeValueCombination.Recid));

}

How to create a default dimension from financial dimensions in d365 X++

 public DimensionDefault createDefaultDimension()

{

    DimensionAttributeValueSetStorage   valueSetStorage = new DimensionAttributeValueSetStorage();

    DimensionDefault                    result;

    int                     i;

    DimensionAttribute      dimensionAttribute;

    DimensionAttributeValue dimensionAttributeValue; 

    container               conAttr = ["BusinessUnit","Costcentre","Department"];    

    container               conValue = ["001","007","022"];    

    str                     dimValue;    

    for (i = 1; i <= conLen(conAttr); i++)

    {

        dimensionAttribute = dimensionAttribute::findByName(conPeek(conAttr,i));

        if (dimensionAttribute.RecId == 0)

        {

            continue;

        }

        dimValue = conPeek(conValue,i);

        if (dimValue != "")

        {

            dimensionAttributeValue = dimensionAttributeValue::findByDimensionAttributeAndValue(dimensionAttribute,dimValue,false,true);

            valueSetStorage.addItem(dimensionAttributeValue);

        }

    }    

    result = valueSetStorage.save();

    return result;

}


How to get opening balance for ledger dimension in D365 X++

                         LedgerBalanceDimAttrValueComboAmounts   ledgerBalance;

                         AmountMST   opSum ;

DimensoinAttributevalueCombination dim;

select dim where dim.RecId == 68719651018;

                        ledgerBalance = LedgerBalanceDimAttrValueComboAmounts::construct();

                        ledgerBalance.parmIncludeRegularPeriod(true);

                        ledgerBalance.parmIncludeOpeningPeriod(true);

                        ledgerBalance.parmIncludeClosingPeriod(false);

                        ledgerBalance.parmAccountingDateRange(mkdate(01,01,2017), mkdate(31,12,2017));

                        ledgerBalance.calculateBalance(dim);

                        opSum = ledgerBalance.getAccountingCurrencyBalance();

info(strfmt("Opening Balance %1", opSum));

How to get lookup for individual financial dimension values in d365 X++

 public void lookup()

        {

            FormStringControl   ctrl = this as FormStringControl;

            Args                args;

            FormRun             formRun;

            DimensionAttribute  dimensionAttribute;

            select dimensionAttribute

                where dimensionAttribute.Name == 'BusinessUnit'; //mention the required dimension name.

            args = new Args();

            args.record(dimensionAttribute);

            args.caller(this);

            args.name(formstr(DimensionLookup));

            formRun = classfactory.formRunClass(args);

            formRun.init();

            ctrl.performFormLookup(formRun);

            super();

        }


How to create a ledger dimension from mainaccount and financial dimension values in d365 X++

 public static void main(Args args)

 { 

DimensionAttributeValueSetStorage valueSetStorage = new DimensionAttributeValueSetStorage();

            DimensionDefault result;

            int i;

         ledgerRecid    Recid;

            DimensionAttribute dimensionAttribute;

            DimensionAttributeValue dimensionAttributeValue;

                   DimensionServiceProvider DimensionServiceProvider = new DimensionServiceProvider();

            LedgerAccountContract LedgerAccountContract = new LedgerAccountContract();

            DimensionAttributeValueContract ValueContract;

            List ListValueContract = new List(Types::Class);

            str dimValue;

            MainAccountnum          mainAccount;

            DimensionAttributeValueCombination      dimensionAttributeValueCombination;

            DimensionStorage        dimStorage;          

                container conAttr = ["BusinessUnit", "Department"];

                container conValue = ["001","022"];

                mainAccount = "110110";

                for (i = 1; i <= conLen(conAttr); i++)

                {

                    dimensionAttribute = dimensionAttribute::findByName(conPeek(conAttr,i));

                    if (dimensionAttribute.RecId == 0)

                    {

                        continue;

                    }

                    dimValue = conPeek(conValue,i);

                    if (dimValue != "")

                    {

                        // The last parameter is “true”. A dimensionAttributeValue record will be created if not //found.

                        dimensionAttributeValue =dimensionAttributeValue::findByDimensionAttributeAndValue(dimensionAttribute,dimValue,false,true);

                        // Add the dimensionAttibuteValue to the default dimension

                        valueSetStorage.addItem(dimensionAttributeValue);

                    }

                         result = valueSetStorage.save();

                LedgerAccountContract.parmMainAccount(mainAccount);

                LedgerAccountContract.parmValues(ListValueContract);

                dimStorage = DimensionServiceProvider::buildDimensionStorageForLedgerAccount(LedgerAccountContract);

                dimensionAttributeValueCombination = DimensionAttributeValueCombination::find(dimStorage.save());

                Recid = LedgerDimensionFacade::ServiceCreateLedgerDimension(dimensionAttributeValueCombination.RecId, result);

    info(strfmt("Ledger dimension : %1", Recid));

            }


OutPut : 68719651020.



Monday, June 5, 2023

How to create and post pending vendor invoice through X++ code in D365FO

 Job:

Note : Purchase order must be complete product reciept.

   public static void main(Args _args)

    {

        VendInvoiceInfoTable    vendInvoiceInfoTable,vendInvoiceInfoTableloc;

        VendInvoiceInfoSubTable     vendInvoiceInfoSubTable;

        VendInvoiceInfoLine         vendInvoiceInfoLine;

        VendPackingSlipTrans        vendPackingSlipTrans;

        VendInvoiceInfoSubLine      vendInvoiceInfoSubLine;

        PurchLine                   purchLine;

        VendTable                   vendTable;

        PurchTable                  purchTable;

        PurchFormLetter         purchFormLetter;

        purchtable = purchtable::find("000036");

        vendInvoiceInfoTable.clear();

        vendInvoiceInfoTable.initValue();

        vendInvoiceInfoTable.initFromPurchTable(purchTable);


        vendInvoiceInfoTable.DocumentOrigin    = DocumentOrigin::Manual;

        vendInvoiceInfoTable.CurrencyCode      = purchTable.CurrencyCode;

        vendInvoiceInfoTable.DeliveryName      = purchTable.DeliveryName;

        vendInvoiceInfoTable.Num               = "LM-036";

        vendInvoiceInfoTable.PurchName         = purchTable.PurchName;

        vendInvoiceInfoTable.VendInvoiceSaveStatus = VendInvoiceSaveStatus::Pending;

        vendInvoiceInfoTable.TransDate         = DateTimeUtil::getSystemDate(DateTimeUtil::getUserPreferredTimeZone());

        vendInvoiceInfoTable.DocumentDate      = DateTimeUtil::getSystemDate(DateTimeUtil::getUserPreferredTimeZone());

        vendInvoiceInfoTable.LastMatchVariance = LastMatchVarianceOptions::OK;

        vendInvoiceInfoTable.ParmJobStatus     = ParmJobStatus::Waiting;

        vendInvoiceInfoTable.DefaultDimension  = vendInvoiceInfoTable.copyDimension(purchTable.DefaultDimension);

        vendInvoiceInfoTable.defaultRow(purchTable);

        vendInvoiceInfoTable.insert();

        if(vendInvoiceInfoTable)

        {

            vendInvoiceInfoSubTable.clear();

            vendInvoiceInfoSubTable.initValue();

            vendInvoiceInfoSubTable.defaultRow();

            vendInvoiceInfoSubTable.ParmId      = vendInvoiceInfoTable.ParmId;

            vendInvoiceInfoSubTable.OrigPurchId = vendInvoiceInfoTable.PurchId;

            vendInvoiceInfoSubTable.PurchName   = vendInvoiceInfoTable.PurchName;

            vendInvoiceInfoSubTable.TableRefId  = vendInvoiceInfoTable.TableRefId;

            vendInvoiceInfoSubTable.insert();

        }

          while  select purchline

           where purchline.PurchId == purchtable.PurchId

        {

            select * from VendPackingSlipTrans

               where VendPackingSlipTrans.OrigPurchid ==  purchtable.PurchId

               &&    VendPackingSlipTrans.PackingSlipId == vendPackingSlipTrans.PackingSlipId

               && VendPackingSlipTrans.ItemId == purchline.ItemId ;

            vendInvoiceInfoLine.clear();

            vendInvoiceInfoLine.initValue();

            vendInvoiceInfoLine.initFromPurchLine(purchLine);

            vendInvoiceInfoLine.DeliveryName   = vendInvoiceInfoTable.DeliveryName;

            vendInvoiceInfoLine.ParmId         = vendInvoiceInfoTable.ParmId;

            vendInvoiceInfoLine.TableRefId     = vendInvoiceInfoTable.TableRefId;

            vendInvoiceInfoLine.currencyCode   = vendInvoiceInfoTable.CurrencyCode;

            vendInvoiceInfoLine.LineNum        = any2int(purchLine.LineNumber);

            vendInvoiceInfoLine.InvoiceAccount = vendInvoiceInfoTable.InvoiceAccount;

            vendInvoiceInfoLine.InventDimId    = vendPackingSlipTrans.InventDimId;

            vendInvoiceInfoLine.OrderAccount   = vendInvoiceInfoTable.OrderAccount;

            vendInvoiceInfoLine.ItemId         = vendPackingSlipTrans.ItemId;

            vendInvoiceInfoLine.InventTransId  = vendPackingSlipTrans.InventTransId;

            vendInvoiceInfoLine.DocumentOrigin = DocumentOrigin::Manual; 

           vendInvoiceInfoLine.ReceiveNow     = 1;

            vendInvoiceInfoLine.modifiedReceiveNow();

            vendInvoiceInfoLine.PurchPrice     = purchLine.PurchPrice;

            vendInvoiceInfoLine.InventNow      = vendInvoiceInfoLine.ReceiveNow;

            vendInvoiceInfoLine.LineAmount   = (purchLine.LineAmount / purchLine.PurchQty) * vendInvoiceInfoLine.ReceiveNow;

            vendInvoiceInfoLine.DefaultDimension = purchLine.DefaultDimension; 

           vendInvoiceInfoLine.insert();

              if(vendInvoiceInfoLine)

            {

                vendInvoiceInfoSubLine.clear();

                vendInvoiceInfoSubLine.initValue();

                vendInvoiceInfoSubLine.defaultRow();

                vendInvoiceInfoSubLine.ParmId            = vendInvoiceInfoTable.ParmId;

                vendInvoiceInfoSubLine.LineRefRecId      = vendInvoiceInfoLine.RecId;

                vendInvoiceInfoSubLine.ReceiveNow        = vendInvoiceInfoLine.ReceiveNow;

                vendInvoiceInfoSubLine.InventNow         = vendInvoiceInfoLine.InventNow ;

                vendInvoiceInfoSubLine.JournalRefRecId   = vendPackingSlipTrans.RecId;

                vendInvoiceInfoSubLine.JournalRefTableId = vendPackingSlipTrans.TableId;

                vendInvoiceInfoSubLine.DocumentId        = vendPackingSlipTrans.PackingSlipId;

                vendInvoiceInfoSubLine.insert();

            }

          }

        select vendInvoiceInfoTableloc

             where vendInvoiceInfoTableloc.Num == vendInvoiceInfoTable.Num;

        purchFormLetter = PurchFormLetter_Invoice::newFromSavedInvoice(vendInvoiceInfoTableloc);

        purchFormLetter.update(vendInvoiceInfoTableloc.purchTable(), vendInvoiceInfoTableloc.Num);

    }




Friday, June 2, 2023

How to Update Sales Totals in D365 by X++

 My requirement is to update the sales totals based on custom fields data.

·       Create two separate fields in Sales order header.

o   Total Discount in Amount

o   Total Discount %


·       The user can enter either Total discount % or Total discount amount, if the user has entered the discount %, the total discount amount need to be calculated and show.

·       If the user has entered the total discount amount, then system need to calculate the total discount % and show.

·       Need to calculate the total discount after the line discount calculation.

·       The calculated total discount value need to push it to on the Sales total form. (Standard field).

·           Once it is pushed to standard field (Total discount), the system will take care of postings.

[    ExtensionOf(tableStr(SalesTable))]

    final class DaxSalesTable_Extension

{

    public void modifiedField(FieldId _fieldId)

    {

        SalesLine   salesLine;

        select sum(LineAmount) from salesLine

where salesLine.SalesId == this.SalesId;

      next modifiedField(_fieldId);

            switch (_fieldId)

            {

                case fieldnum(SalesTable, TotalDiscountAmount):

                  this.TotalDiscountPercentage = this.TotalDiscountAmount/salesLine.LineAmount*100;

                    break;

                  case fieldnum(SalesTable, TotalDiscountPercentage):

                  this.TotalDiscountAmount = (this.TotalDiscountPercentage/100)*salesLine.LineAmount;

                    break;

            }

        }

     [ExtensionOf(classStr(TradeTotals))]

internal final class DaxTradetotals_Extension

{

    public DiscAmount  totalEndDisc()

    {

           real oldvalue;

        SalesTable  salesTableloc = orderTable;

        oldvalue = next totalEndDisc();

        endDisc =  salesTableloc.TotalDiscountAmount;

        if(salesTableloc.SalesStatus == SalesStatus::Invoiced)

        {

            oldvalue = 0;

            return oldvalue;

        }

        else

        {

            return endDisc;

        }

      }

}

}

      Open Order Totals:

     Confirmation Totals :
     

     Picking List Tots :
     

      Posting  Invoice  Totals: