Showing posts with label MS Dynamics AX. Show all posts
Showing posts with label MS Dynamics AX. Show all posts

Wednesday, 16 September 2020

Multiselect lookup on dialog in UI builder class (Sysoperation) in D365 F&O

 This way of setting Multiselectlookup(Lookup that allows Multiple value selections) can be used on any module (SSRS, Service, Batch or simple server/client based service class) utilizing SysOperation framework. 

Code design would be as follows:- 

1. Data contract class: (just showing relevant parameters, there can be other parameters too). Just to note, container type parameter can also be used in place of List.

[DataContract, SysOperationContractProcessing(ClassStr(TestExpImpUIBuilder))]
class TESTEXPDC extends SysOperationServiceBaseDataContract
{
    List                department;    
    
    [DataMemberAttribute, SysOperationLabel("@SYS850"), AifCollectionTypeAttribute('return', Types::String)]
    public List parmDepartment(List _department = department)
    {
        department = _department;

        return department;
    }
}
2. UI Builder Class: This is most important to build a multi select lookup.
class TestExpImpUIBuilder extends SysOperationAutomaticUIBuilder
{
    DialogField         dialogDepartment;
    SysLookupMultiSelectCtrl    ctrlDepartment;
    
    //Override this to add dialog field
    protected DialogField addDialogField(IdentifierName _methodName, Object _dataContract = this.dataContractObject())
    {
        DialogField dialogField;;

        switch (_methodName)
        {
            case methodStr(TESTEXPDC, parmDepartment):
                dialogDepartment = this.dialog().addField(
                    extendedTypeStr(Description),
                    "@SYS850");
                dialogField = dialogDepartment;
                break;
            default:
            dialogField = super(_methodName, _dataContract);
        }
        return dialogField;
    }

    //Override this
    public void postRun()
    {
        super();
        if (this.dataContractObject() is TESTEXPDC) //if is optional, in my case i was using single UI builder for multiple tasks so required
        {
            this.lookupDepartment();
        }
    }
    
    //to populate lookup
    protected void lookupDepartment()
    {
        TableId                 multiSelectTableNum = tableNum(EcoResCategory);
        Query                   query               = new Query();
        QueryBuildDataSource    qbds                = query.addDataSource(multiSelectTableNum);

        EcoResCategoryHierarchyRole categoryRole;

        select firstonly categoryRole
            where categoryRole.NamedCategoryHierarchyRole == EcoResCategoryNamedHierarchyRole::RetailChannelNavigation;

        qbds.addRange(fieldNum(EcoResCategory, Level)).value(queryValue(3));
        qbds.addRange(fieldNum(EcoResCategory, CategoryHierarchy)).value(queryValue(categoryRole.CategoryHierarchy));
        qbds.addSelectionField(fieldNum(EcoResCategory, Code)); //needed for field display in lookup
        qbds.addSelectionField(fieldNum(EcoResCategory, Name));

        container selectedFields = [multiSelectTableNum, fieldNum(EcoResCategory, Code)]; //irrelevant for lookup but value needed for further use in method calling

        ctrlDepartment = SysLookupMultiSelectCtrl::constructWithQuery(this.dialog().dialogForm().formRun(), dialogDepartment.control(), query, false, selectedFields);
    }


    public void getFromDialog()
    {
        super();
        //keep in mind, multiselect actually brings Recid and works like reference lookup
        if (this.dataContractObject() is TESTEXPDC)
        {
            List        listDepartment  = new List(Types::String);
            container   conDeptt = ctrlDepartment.get();

            Counter conCount = 1;
            Counter conDepLength = conLen(conDeptt);

            while (conCount //use sign for less and equal here// conDepLength)
            {
                listDepartment.addEnd(EcoResCategory::find(conPeek(conDeptt, conCount)).Code);
                conCount++;
            }
            this.dataContractObject().parmDepartment(listDepartment);
            
            //whole list code not needed in case you are using container type parameter
            //this.dataContractObject().parmDepartment(ctrlDepartment.get());
        }
    }
}

3. Service class : Its optional and purely based upon requirement. No lookup code is needed here, just needed for execution type and Contract mapping to further call Task based class.

4. Task class: actual iteration of selected multiselect values would be done here.

class TESTEXPTask
{
    List                listDepartment;
    
    public static TESTEXPTask construct()
    {
        return new TESTEXPTask();
    }
    
    public void run(TESTEXPDC _contract)
    {
        this.processDataforExport();
    }
    
    protected void processDataforExport()
    {
        try
        {
            ttsbegin;
            // any code execution
          
            //Line Creation
            this.createLinesPerDepartment();
            ttscommit;

        }
        catch (Exception::Error)
        {
            exceptionTextFallThrough();
        }
    }
    
    protected void createLinesPerDepartment()
    {
        if (listDepartment && !listDepartment.empty())
        {
            ListEnumerator listEnumerator;

            listEnumerator = listDepartment.getEnumerator();
            while (listEnumerator.moveNext())
            {
                this.methodName(listEnumerator.current());
            }
        }
        else
        {
            //call execution code
            this.methodeName();
        }
    }

and you are done. Just squeeze in your other code like additional parameters and business code and voila!!!

Keep in mind, UI builder class in anyways would be used in similar old manner (overridelookup) for conventional field lookups.

See you in next blog. Happy Daxing (Now D365ing)!!! Please drop a feedback in case of any issues or any other concerns.

Wednesday, 4 October 2017

Create Free text invoice via X++ using Templates in AX 2012 R3

Below is the code snippet to be used in X++ code editor when creating Free text invoice(FTI) using Free text invoice templates.

static void CreateFTIfromTemplate(Args _args)
{
    CustInvoiceTable    custInvoiceTable,custInvoiceTable1;
    CustInvoiceTemplate custInvoiceTemplate;
    CustInvoiceLine     custInvoiceLine;
    CustPostInvoice     custPostInvoice;
    CustTable           custtable;
    CustInvoiceLineTemplate custInvoiceLineTemplate;

    Date  invoiceDate = systemdateget();
    Date  dueDate = systemdateget()+10;


    try
    {
        custtable = Custtable::find("00001");
        custInvoiceTemplate = CustInvoiceTemplate::findByTemplateName("Dues");

        ttsBegin;
        custInvoiceTable.clear();
        custInvoiceTable.OrderAccount = custtable.AccountNum;

        custInvoiceTable.initFromCustInvoiceTemplate(
            custInvoiceTemplate,
            custtable,
            CustRecurrenceInvoiceDefaultType::InvoiceTemplate, //This can be defaulted from customer too
            invoiceDate);
        custInvoiceTable.DueDate = dueDate;
        custInvoiceTable.insert();

        // Creates a free text invoice lines by using customer free text invoice line template.
        while select custInvoiceLineTemplate
            where custInvoiceLineTemplate.CustInvoiceTemplate == custInvoiceTemplate.RecId
        {

            custInvoiceLine.clear();

            custInvoiceLine.insertFromCustInvoiceLineTemplate(custInvoiceLineTemplate,
                                                                custInvoiceTable,
                                                                custtable,
                                                                CustRecurrenceInvoiceDefaultType::InvoiceTemplate); //This can be defaulted from customer too
        }

        //just to be sure for proper distributions
        SourceDocumentProcessor::submitSourceDocumentLinesForHeader(custInvoiceTable.SourceDocumentHeader);

        //post FTI
        Select custInvoiceTable1 where custInvoiceTable1.RecId == custInvoiceTable.RecId;
        custPostInvoice = new CustPostInvoice(custInvoiceTable1);
        custPostInvoice.run();

        ttsCommit;

        info(strFmt("Invoice generated for customer %1", custtable.AccountNum));
    }
    catch
    {
        error(strFmt("Error in generating invoice for customer %1",custtable.AccountNum));
    }

}

Do share your thoughts and if you find anything incorrect here.
Thanks!

Tuesday, 15 August 2017

Free text invoice using X++ in AX 2012

Today I'll show you to create Free text invoice using X++. I have done it in Indian localization
(after GST), you can skip those steps for other localizations.
I am creating free text invoice for price adjustment to be done on previously created Customer Invoice.

    CustInvoiceJour     custinvoicejour;
    CustInvoiceTrans    custinvoicetrans;    
    CustInvoiceTable    custInvoiceTable,custInvoiceTable1;
    CustInvoiceLine     custInvoiceLine,custInvoiceLine1;
    CustPostInvoice     custPostInvoice;
    CustTable       custtable;
    SalesLine       salesLine;
    SalesLine_IN    salesLinein;
    CustInvoiceLineTaxExtensionIN custInvoiceLineTaxExtensionIN;

    container   offsetDimensions;
    LineNum     lineNum;
    Query   q;
    QueryBuildDataSource    qbds;
    QueryRun    qr;

    q = new Query();

    qbds = q.addDataSource(tableNum(CustInvoiceJour));
    qbds.addRange(fieldNum(CustInvoiceJour, Invoiceaccount)).value("Cust1");
    qbds.addRange(fieldNum(CustInvoiceJour, InvoiceId)).value("TestInvoice1");
    qbds.addRange(fieldNum(CustInvoiceJour, InvoiceId)).value("TestInvoice2");

    qr = new QueryRun(q);

    while(qr.next())
    {
        custinvoicejour = qr.get(tableNum(CustInvoiceJour));
         //info(strFmt("%1, %2",custinvoicejour.InvoiceAccount, custinvoicejour.InvoiceDate));

        ttsBegin;

        custtable = CustTable::find(custinvoicejour.InvoiceAccount);
        custInvoiceTable.clear();
        custInvoiceTable.initFromCustTable(custtable);
        //custInvoiceTable.InvoiceDate = custinvoicejour.InvoiceDate;

        custInvoiceTable.insert();

        lineNum = 0;
        while select custinvoicetrans       
            where custinvoicetrans.InvoiceId == custinvoicejour.InvoiceId
            && custinvoicetrans.InvoiceDate == custinvoicejour.InvoiceDate
        {
            custInvoiceLine.clear();
            custInvoiceLine.initValue();
            
            //setup main account as required 
            offsetDimensions = ["999999","999999", 0, "", ""]; // you can set a Main Account with multiple financial dimensions

            custInvoiceLine.LedgerDimension = AxdDimensionUtil::getLedgerAccountId(offsetDimensions);
            custInvoiceLine.initFromCustInvoiceTable(custInvoiceTable);
            custInvoiceLine.ItemId = "001234"; //custom field     

           
            custInvoiceLine.Quantity = custinvoicetrans.Qty;
            custInvoiceLine.UnitPrice = 2.0 ;
            custInvoiceLine.modifiedField(fieldNum(CustInvoiceLine, UnitPrice));
            custInvoiceLine.Description = custinvoicetrans.itemName();

            //to get HSN code used in original invoice
            select salesLine
                where salesLine.SalesId == custinvoicetrans.SalesId
                && salesLine.ItemId == custinvoicetrans.ItemId;

            select salesLinein
                where salesLinein.SalesLine == salesLine.RecId;

            //Instead of HSNCode, you need to specify Taxgroup and Itemtaxgroup in case of other localizations
            custInvoiceLine.HSNCodeTable_IN = salesLinein.HSNCodeTable;

            custInvoiceLine.ParentRecId = custInvoiceTable.RecId;
            if(!lineNum)
            {
                lineNum = CustInvoiceLine::lastLineNum_W(custInvoiceLine.ParentRecId);
            }

            lineNum += 1;
            custInvoiceLine.LineNum = lineNum;
            custInvoiceLine.InvoiceTxt = custinvoicetrans.InvoiceId+"\n"+date2StrXpp(custinvoicetrans.InvoiceDate);//change it as per need

            custInvoiceLine.insert();
            
            //Specific to Indian localization, not required for other localizations
            custInvoiceLineTaxExtensionIN.CustInvoiceLine = custInvoiceLine.RecId;
            custInvoiceLineTaxExtensionIN.TaxInformation_IN = TaxInformation_IN::findDefaultbyLocation(DirPartyTable::find(CompanyInfo::findDataArea(curext()).PartyNumber).PrimaryAddressLocation).RecId;
            custInvoiceLineTaxExtensionIN.initValue();
            custInvoiceLineTaxExtensionIN.insert();

        }

        //Post free text invoice
        if(lineNum)
        {
            Select custInvoiceTable1 where custInvoiceTable1.RecId == custInvoiceTable.RecId;

            custPostInvoice = new CustPostInvoice(custInvoiceTable1);
            custPostInvoice.run();

            ttsCommit;

        }
        else
        {
            ttsAbort;
        }

    }
}

This is it. Share your ideas and thoughts if any.