Tuesday, 26 June 2018

Batch Job In D365

Batch Job In D365 :

Contract Class:
[
    DataContractAttribute,
    SysOperationContractProcessingAttribute(classStr(CITCustPaymImportUIBuilder))
]
    class CITCustPaymImportContract implements SysOperationValidatable
{
    CustAccount     custAccount;
    FilePath        filePath;
    FileUpload      filepath1;
    JournalId       journalNum;
    TransDate       postingDate;
    CustGroupId     custGroup;
    [
        //DataMemberAttribute(identifierStr(Filepath)),     
        DataMemberAttribute('Filepath'),
         SysOperationLabelAttribute('Upload document'),
        SysOperationDisplayOrderAttribute('3'),
        SysOperationHelpTextAttribute(literalStr("Assign file path"))
    ]
    public FilePath parmFilePath(FilePath _filePath = filePath)
    {
        filePath = _filePath;
        return filePath;
    }

    [
        //DataMemberAttribute(identifierStr(CustAccount))
        DataMemberAttribute('CustAccount'),
        SysOperationLabelAttribute('Customer Account'),
        SysOperationDisplayOrderAttribute('1'),
        SysOperationHelpTextAttribute(literalStr("Customer Account no."))
    ]
    public CustAccount parmCustAccount(CustAccount _custAccount = custAccount)
    {
        custAccount = _custAccount;
        return custAccount;
    }

    [
        //DataMemberAttribute(identifierStr(JournalNum)),
        DataMemberAttribute('JournalNum'),
        SysOperationControlVisibilityAttribute(false),
        SysOperationDisplayOrderAttribute('4'),
        SysOperationHelpTextAttribute(literalStr("JournalNum"))
    ]
    public JournalId parmJournalNum( JournalId _journalNum = journalNum)
    {
        journalNum = _journalNum;
        return journalNum;
    }

    [
        //DataMemberAttribute(identifierStr(Postingdate)),
        DataMemberAttribute('Postingdate'),
        SysOperationLabelAttribute('Posting Date'),
        SysOperationDisplayOrderAttribute('2'),
        SysOperationHelpTextAttribute(literalStr("Posting Date"))
    ]
    public TransDate parmPostingDate(TransDate _postingDate = postingDate)
    {
        postingDate = _postingDate;
        return postingDate;
    }

    public boolean validate()
    {
        boolean isValid = true;
        if (!custAccount)
        {
            isValid = checkFailed(strFmt("@SYS84753", custAccount));
        }
        /*if (!filePath)
        {
            isValid = checkFailed(strFmt("@SYS84753", filePath));
        }*/
       
        return isValid;
    }

}
=======================================================================
Controller : 

class CITCustPaymImportController extends SysOperationServiceController
{
    Common  callerRecord;
   
 
    void new()
    {
        super();

        this.parmClassName(classStr(CITCustPaymImportService));
        this.parmMethodName(methodStr(CITCustPaymImportService, process));
        this.parmDialogCaption('Customer payments Import');
    }

    public static void main(Args _args)
    {
        CITCustPaymImportController controller;
        controller = new CITCustPaymImportController();
     
        controller.parmShowDialog(true);
        CITCustPaymImportContract contract;
        contract    =   controller.getDataContractObject();
        //contract    =   this.parmReportContract().parmRdpContract() as CITCustPaymImportContract;
        if(_args.parm())
        {
            //ledgerJournalTrans = this.parmCallerRecord() as LedgerJournalTrans;
            contract.parmJournalNum(_args.parm());
        }
        //controller.initFromCaller(); 
        controller.startOperation(); 
        //controller.refreshCallerRecord();
    }

    public LabelType parmDialogCaption(LabelType _dialogCaption = "")
    {
        LabelType caption;
        caption = "Customer payments Import";
        return caption;
    }

    public boolean canGoBatch()
     {
        return false;
     }

    public Common parmCallerRecord(Common _callerRecord = callerRecord)
    {
        callerRecord = _callerRecord;
        return callerRecord;
    }

    ///    Refreshes the calling form data source.
    protected void refreshCallerRecord()
    {
        FormDataSource callerDataSource;
        if (this.parmCallerRecord() && this.parmCallerRecord().dataSource())
        {
            callerDataSource = this.parmCallerRecord().dataSource();
            callerDataSource.research(true);
        }
     }

}
======================================================================
Service :

class CITCustPaymImportService extends SysOperationServiceBase
{
    DMFExecutionId      executionId;
    DMFDefinitionGroup  definitionGroup;
    CustAccount     custAccount;
    FilePath        filePath,filepath1;
    JournalId       journalNum;
    TransDate       postingDate;
    Map                 uniqueKeyFieldListStagingMap,stagingTargetFieldListMap, autoGenStagingMap;
    Map                 entityPermissionMap;
    guid                scopeIdentifier;
    boolean             processComposite;
    Batch           currentBatch;
FileUpload             fileUpload;
map                           mapInv;
boolean             isMapEnd;
    public void process(CITCustPaymImportContract _contract)
    {
        filePath        = _contract.parmFilePath();
        custAccount     = _contract.parmCustAccount();
        journalNum      = _contract.parmJournalNum();
        postingDate     = _contract.parmPostingDate();
        try
        {
            This.processOperations(custAccount,filePath,journalNum,postingDate);
        }
        catch (Exception::Deadlock)
        {
            retry;
        }

        catch (Exception::UpdateConflict)
        {
            if (appl.ttsLevel() == 0)
            {
                /*   if (xSession::currentRetryCount() >= #RetryNum)
                {
                throw Exception::UpdateConflictNotRecovered;
                }
                else
                {
                retry;
                }*/
            }
                else
                {
                    throw Exception::UpdateConflict;
                }
        }

        catch (Exception::Error)
        {
            error(strFmt("Error occured"));
            retry;
        }
    }

    Void processOperations(CustAccount _custAccount,FilePath  _filePath,JournalId _journalNum,TransDate _postingDate)
    {
 
        This. fileToDMStaging ();
        This. ProcessStagingData(_custAccount,_journalNum,_postingDate);
        This. stagingToTarget();
    }

    //This method execution will import the data from file to staging table
    Void fileToDMStaging()
    {
       
        DMFDefinitionGroupExecution     groupExecution;
        DMFDefinitionGroupEntity    dMFDefinitionGroupEntity;
        definitionGroup = DMFDefinitionGroup::find(CustParameters::find().CITImportProject);
        executionId             = DMFUtil::generateExecutionId(CustParameters::find().CITImportProject);
        Description description = strFmt('Execution - %1 for Definition Group - %2', executionId, CustParameters::find().CITImportProject);
        DMFDefinitionGroupExecution::insertOrDisplay(definitionGroup, executionId, description, false);
        select entity from dMFDefinitionGroupEntity where dMFDefinitionGroupEntity.DefinitionGroup == definitionGroup.DefinitionGroupName;
        ttsbegin;
        groupExecution = DMFDefinitionGroupExecution::find(definitionGroup.DefinitionGroupName,dMFDefinitionGroupEntity.Entity,executionId,true);
        groupExecution.FilePath = /*"C4PCUATTF";*/filePath;
        groupExecution.FilePath = groupExecution.applyTransforms(groupExecution.FilePath);
       
        groupExecution.ExcelLookUp =
                        DMFDefinitionGroupEntity::insertExcelLookUpValue(
                        groupExecution.DefinitionGroup,
                        groupExecution.Entity,
                        groupExecution.FilePath,
                        groupExecution.Source);
        groupExecution.update();
        ttscommit;
        DMFStagingWriterContract        contract = new DMFStagingWriterContract();
        DMFQuickImportExport::doPGImport(definitionGroup.DefinitionGroupName ,executionId);//Need to create extension of class DMFQuickImportExport to pass File path and assign it to the contract variable
    }

    public NoYes parmError(NoYes  _errorStatus = NoYes::NO)
    {
        //  errorStatus = _errorStatus;

        return  NoYes::NO;
    }

    //This method execution will process the staging data for particular execution Id
    Void processStagingdata(CustAccount _custAccount,JournalId _journalId,TransDate _postingDate)
    {
        customerPaymentJournalLineStaging       customerPaymentJournalLineStaging;
        LedgerJournalTable                      ledgerjournaltable;
        JournalTableData                        journalTableData;
        ledgerjournaltable  =   LedgerJournalTable::find(journalNum,false);
        Voucher voucher;
     
        if(ledgerjournaltable)
        {
               
            voucher     =      JournalTableData::newTable(ledgerjournaltable).journalVoucherNum().getNew(true);
           
        }
       
        Update_recordSet customerPaymentJournalLineStaging
                setting DefaultDimensionsForAccountDisplayValue= _custAccount,
                AccountDisplayValue = _custAccount,
                JournalBatchNumber = _journalId,
                TransactionDate = _postingDate,
                Voucher = voucher,
                CurrencyCode = 'USD',
                DocumentNumber = customerPaymentJournalLineStaging.MarkedInvoice
                where customerPaymentJournalLineStaging.executionId == executionId;
        select customerPaymentJournalLineStaging
                where customerPaymentJournalLineStaging.executionId == executionId;

        if (!this.isInvoiceExists(customerPaymentJournalLineStaging.MarkedInvoice))
        {
            This.assignInvoiceFromPO();
        }

        /* Else
        {
        // This.sumInvoiceId();
        }*/
    }

        //Assign InvoiceId based on PO number provided in file
        Boolean isInvoiceExists(InvoiceId   _invoiceid)
        {
            boolean invexists;
            CustInvoiceJour custInvoiceJour;
            select RecId from custInvoiceJour
                where custInvoiceJour.InvoiceId ==  _invoiceid;
            if(custInvoiceJour)
                invexists   =   true;
            else
                invexists   =   false;
            return invexists;
        }

        Void assignInvoiceFromPO()
        {
            CustomerPaymentJournalLineStaging   customerPaymentJournalLineStaging;
            SalesTable                          SalesTable;
            Amount                              invoiceAmount;
            CustTransOpen                       CustTransOpen;
            CustInvoiceJour                     custInvoiceJour;
            CustTrans                           custTrans;
            CustomerPaymentJournalLineStaging   customerPaymentJournalLineStagingLoc,customerPaymentJournalLineStagingins;
           
            MapEnumerator                   mapEnum;

            While select sum(CreditAmount) from customerPaymentJournalLineStaging 
                    group by markedInvoice
                    where customerPaymentJournalLineStaging.executionId == executionId
               
            {
                select SalesTable
                    where salesTable.PurchOrderFormNum==customerPaymentJournalLineStaging.MarkedInvoice;
            mapInv = new Map(Types::String, types::Real);
                While select custInvoiceJour where custInvoiceJour.SalesId == SalesTable.SalesId
        Join custTrans where custTrans.Invoice == custInvoiceJour.InvoiceId
                    && custTrans.AccountNum == custInvoiceJour.InvoiceAccount
                    && custTrans.TransDate == custInvoiceJour.InvoiceDate
                    && custTrans.Voucher == custInvoiceJour.LedgerVoucher
                join CustTransOpen where CustTransOpen.AccountNum == custTrans.AccountNum
                                    && CustTransOpen.RefRecId == custTrans.RecId
            {
                mapInv.insert(custInvoiceJour.InvoiceId,custTransOpen.amountMST);
            }
            mapEnum = new MapEnumerator(mapInv);
            isMapEnd = false;
            if(mapEnum.moveNext())
            while select forupdate customerPaymentJournalLineStagingLoc
                where customerPaymentJournalLineStagingloc.MarkedInvoice == customerPaymentJournalLineStaging.MarkedInvoice
                                && customerPaymentJournalLineStagingloc.executionId == executionId
                {
                    mapEnum = this.assignInvoice(customerPaymentJournalLineStagingloc,mapEnum);
                    if (isMapEnd)             
                        break;
                }
            }
        }

        MapEnumerator assignInvoice(customerPaymentJournalLineStaging customerPaymentJournalLineStagingLoc,MapEnumerator mapenum)
    {
        Amount invoiceAmount;
        customerPaymentJournalLineStaging   customerPaymentJournalLineStagingins;
        invoiceAmount = mapEnum.CurrentValue();
        if (invoiceAmount >= customerPaymentJournalLineStagingLoc.CreditAmount)
        {
            ttsbegin;
            customerPaymentJournalLineStagingLoc.MarkedInvoice = mapEnum.CurrentKey();
            customerPaymentJournalLineStagingLoc.update();
            ttscommit;
            /*if (!mapenum.moveNext())
            {
                isMapEnd = true;
                return mapEnum;
            }*/
           
            if(customerPaymentJournalLineStagingloc.CreditAmount == invoiceAmount)
            {
                if (!mapenum.moveNext())
                {
                    isMapEnd = true;
                    return mapEnum;
                }
            }
           
            else
            {
                mapinv.insert(mapEnum.currentKey(),invoiceAmount-customerPaymentJournalLineStagingloc.CreditAmount);
            }
        }
        else
        {
            invoiceAmount = customerPaymentJournalLineStagingLoc.CreditAmount-invoiceAmount;
            ttsbegin;
            customerPaymentJournalLineStagingLoc.selectForUpdate(true);
            customerPaymentJournalLineStagingLoc.MarkedInvoice = mapEnum.Currentkey();
            customerPaymentJournalLineStagingLoc.CreditAmount = mapEnum.CurrentValue();
            customerPaymentJournalLineStagingLoc.update();
            ttscommit;
            customerPaymentJournalLineStagingins.data(customerPaymentJournalLineStagingloc);
            customerPaymentJournalLineStagingins.LineNumber += 0.01;
            customerPaymentJournalLineStagingins.CreditAmount =   invoiceAmount;
            customerPaymentJournalLineStagingins.RecId  =   0;
            customerPaymentJournalLineStagingins.CITDiscountAmount = 0;
            customerPaymentJournalLineStagingins.MarkedInvoice = '';
            customerPaymentJournalLineStagingins.insert();
            if (!mapenum.moveNext())
            {
                isMapEnd = true;
                return mapenum;
            }
            mapenum = this.assignInvoice(customerPaymentJournalLineStagingins,MapEnum);
        }
        return mapenum;
    }

        Void stagingToTarget()
        {
            DmfDefinitionGroupExecution dmfDefinitionGroupExecution;
            dmfDefinitionGroupExecution=dmfDefinitionGroupExecution::find(CustParameters::find().CITImportProject,'Customer payment journal line',executionId);
            if (dmfDefinitionGroupExecution.ExecutionId)
            {
                ttsbegin;
                DMFDefinitionGroupExecution defGroupExec;

                update_recordset defGroupExec
                setting IsSelected = NoYes::yes,
                    ExecuteTargetStep = NoYes::Yes
                where defGroupExec.ExecutionId == DMFDefinitionGroupExecution.ExecutionId;

                ttscommit;
            }

            DMFentitywriter  Dmfentitywriter = new DMFentitywriter();
            Dmfentitywriter.parmEntityTableName('CustomerPaymentJournalLineStaging');
            Dmfentitywriter.parmDMFExecution(DMFExecution::find(executionId));
            Dmfentitywriter.parmDMFDefinitionGroupExecution(dmfDefinitionGroupExecution);
            Dmfentitywriter.parmExecutionId(executionId);
            Dmfentitywriter.run();
           
        }

}
=======================================================================

UI Builder : 

class CITCustPaymImportUIBuilder extends SysOperationAutomaticUIBuilder
{
    Dialog      dlg;
    DialogField     dialogCustAcc;
    DialogField     dialogFilePath;
    DialogField     dialogPostingDate;
    DialogField     dialogJournalNum;
    str FileUploadName = 'FileUpload';
    private const str OkButtonName = 'Upload';
    str fileUrl;
    FileUploadBuild  dialogFileUpload;
    //dialogField     dialogFileUpload;


    CITCustPaymImportContract   contract;
    public void build()
    {
        DialogGroup dlgGrp;
        contract = this.dataContractObject();
       

        //get the current dialog
        dlg = this.dialog();

        dialogCustAcc = this.addDialogField(methodStr(CITCustPaymImportContract, parmCustAccount),contract);
        dialogCustAcc.value('');
        //dialogFilePath = this.addDialogField(methodStr(CITCustPaymImportContract, parmFilePath),contract);
        dialogPostingDate = this.addDialogField(methodStr(CITCustPaymImportContract, parmPostingDate),contract);
        dialogPostingDate.value(systemDateGet());
        dialogJournalNum = this.addDialogField(methodStr(CITCustPaymImportContract, parmJournalNum),contract);
        //make required modifications to the dialog
        dlgGrp = dlg.addGroup('FileUpload');
        dlgGrp.columns(2);
       
        FormBuildControl formBuildControl = dlg.formBuildDesign().control(dlgGrp.name());
       
        /*FileUploadBuild*/  dialogFileUpload = formBuildControl.addControlEx(classstr(FileUpload), FileUploadName);
        dialogFileUpload.baseFileUploadStrategyClassName(classstr(FileUploadTemporaryStorageStrategy));
        dialogFileUpload.fileNameLabel("@SYS308842");
        dialogFileUpload.resetUserSetting();
        dialogFileUpload.style(FileUploadStyle::MinimalWithFilename);
        dialogFileUpload.fileTypesAccepted('.xlsx');
    }

    public void dialogPostRun(DialogRunbase _dialog)
    {
        //super(_dialog);
        FileUpload fileUpload = this.getFormControl(_dialog, FileUploadName);
       // fileUpload.notifyUploadCompleted += eventhandler(dlg.uploadCompleted);
        //this.setDialogOkButtonEnabled(_dialog, false);
        FileUploadTemporaryStorageResult fileUploadResult = fileUpload.getFileUploadResult() as FileUploadTemporaryStorageResult;
        info(strfmt("-%1",fileUploadResult));
        if (fileUploadResult != null && fileUploadResult.getUploadStatus())
        {
            fileUrl = fileUploadResult.getDownloadUrl();
            info(strfmt("%1", fileUrl));
            contract.parmFilePath(fileUrl);
           
           
        }
    }

    protected FormControl getFormControl(DialogRunbase _dialog, str _controlName)
    {
        return _dialog.formRun().control(_dialog.formRun().controlId( _controlName));
    }

    private void setDialogOkButtonEnabled(DialogRunbase _dialog, boolean _isEnabled)
    {
        FormControl okButtonControl = this.getFormControl(_dialog, OkButtonName);

        if (okButtonControl)
        {
            okButtonControl.enabled(_isEnabled);
        }
    }

    public void run()
    {
       
        try
        {
            ttsbegin;
            FileUpload fileUploadControl = this.getFormControl(dlg, FileUploadName);
            FileUploadTemporaryStorageResult fileUploadResult = fileUploadControl.getFileUploadResult() as FileUploadTemporaryStorageResult;
            info(strfmt("-%1",fileUploadResult));
            if (fileUploadResult != null && fileUploadResult.getUploadStatus())
            {
                fileUrl = fileUploadResult.getDownloadUrl();
                info(strfmt("%1", fileUrl));
           
           
            }
            ttscommit;
        }
        catch (Exception::Deadlock)
        {
            retry;
        }
    }

    public void postBuild()
    {
        contract            =   this.dataContractObject();
        dialogCustAcc = this.bindInfo().getDialogField(
        this.dataContractObject(), methodStr(CITCustPaymImportContract, parmCustAccount));
        dialogFilePath = this.bindInfo().getDialogField(
        this.dataContractObject(), methodStr(CITCustPaymImportContract, parmFilePath));
        dialogPostingDate = this.bindInfo().getDialogField(
        this.dataContractObject(), methodStr(CITCustPaymImportContract, parmPostingDate));
        dialogJournalNum = this.bindInfo().getDialogField(
        this.dataContractObject(), methodStr(CITCustPaymImportContract, parmJournalNum));
       
    }

    private void custAccLookup(FormStringControl custAcclookup)
    {
        Query query = new Query();
        QueryBuildDataSource qbds_CustTable;
        QueryBuildRange         qbrBlocked;
        SysTableLookup sysTableLookup;

        // Create an instance of SysTableLookup with the current calling form control.
        sysTableLookup = SysTableLookup::newParameters(tableNum(CustTable), custAcclookup);
        // Add fields to be shown in the lookup form.
        sysTableLookup.addLookupfield(fieldNum(CustTable,AccountNum));
        //sysTableLookup.addLookupfield(fieldNum(CustTable,Name));
        qbds_CustTable = query.addDataSource(tableNum(CustTable));
        //this.query().dataSourceTable(tablenum(PurchTable)).addRange(fieldnum(PurchTable, PurchStatus)).value(strfmt('!%1,!%2',enum2str(PurchStatus::Canceled),enum2str(purchstatus::Invoiced)));
        //qbds_CustTable.addRange(fieldNum(CustTable, Blocked)).value(enum2str(CustVendorBlocked::All),enum2str(CustVendorBlocked::Payment));
        qbds_CustTable.addRange(fieldNum(CustTable, Blocked)).value(strfmt('!%1,!%2',enum2str(CustVendorBlocked::All),enum2str(CustVendorBlocked::Payment)));
        sysTableLookup.parmQuery(query);
        // Perform the lookup
        sysTableLookup.performFormLookup();
    }

    public void postRun()
    {
        super();

        //Register overrides for form control events
        dialogCustAcc.registerOverrideMethod(
        methodstr(FormStringControl, lookup),
        methodstr(CITCustPaymImportUIBuilder, custAccLookup),
        this);
    }

    /// <summary>
    ///
    /// </summary>
    public void getFromDialog()
    {
       
        FileUpload fileUploadControl = dlg.formRun().control(dlg.formRun().controlId(FileUploadName));
         
        FileUploadTemporaryStorageResult fileUploadResult = fileUploadControl.getFileUploadResult() as FileUploadTemporaryStorageResult;
        if (fileUploadResult != null && fileUploadResult.getUploadStatus())
        {
            fileUrl = fileUploadResult.getFileId();
        }
        contract.parmFilePath(fileUrl);
        super();
    }


}
======================================================================

No comments:

Post a Comment