Monday, May 22, 2023

How to Copy Pending Vendor Invoice Description to Vendor Transaction Descriptions in d365 using x++

 My requirement is to copy the  Pending Vendor Invoice Description to Vendor Transaction Descriptions in d365 using x++.

[ExtensionOf(classStr(PurchFormLetter_Invoice))]

internal final class DaxPurchFormLetter_Invoice_Extension

{

    protected void afterOperationEnd()

    {

        FormletterOutputContract purchFormLetterOutputContract;

        VendInvoiceJour vendInvoiceJournal;

        VendTrans updateVendTrans;

        VendInvoiceInfoTable vendInvoiceInfoTable;

          next afterOperationEnd();

          purchFormLetterOutputContract = this.getOutputContract();

        vendInvoiceJournal = purchFormLetterOutputContract.parmJournal() as VendInvoiceJour;

        if (purchFormLetterOutputContract.parmNumberOfOrdersPosted() > 0)

        {

            select vendInvoiceInfoTable where vendInvoiceInfoTable.ParmId==vendInvoiceJournal.ParmId

                    && vendInvoiceInfoTable.PurchId==vendInvoiceJournal.PurchId;

            select forupdate updateVendTrans

                 where updateVendTrans.Voucher==vendInvoiceJournal.LedgerVoucher

                && updateVendTrans.TransDate == vendInvoiceJournal.InvoiceDate

                && updateVendTrans.AccountNum == vendInvoiceJournal.InvoiceAccount;

            if (updateVendTrans.RecId)

            {

                ttsbegin;

                updateVendTrans.Txt=vendInvoiceInfoTable.Description;

                updateVendTrans.doUpdate();

                ttscommit;

            }

        }

    }

}

Account Payable à Invoice à Pending Vendor Invoice à Header à Invoice Description

Account Payable à Vendors à All Vendors à Transactions à Description





How to add fields in standard Data entity in D365 using X++

 Here my requirement is to add fields in header and line data entities. 

            ·       Warehouse work header

·       Warehouse work Lines

Add fields in entity level , vertual fields.

Add fields with same names in staging tables


Header dataentity postload method:

[ExtensionOf(tableStr(WHSWarehouseWorkHeaderEntity))]

internal final class DaxWHSWarehouseWorkHeaderEntity_Extension

{

      public void postload()

    {

        WHSWorkTable    whsWorkTable;

        WHSWorkLine     whsWorkLine;

        WHSWarehouseWorkHeaderEntity    wHSWarehouseWorkHeaderEntity = this;

        Amount qty,qtyloc;

        while  select whsWorkLine

             where whsWorkLine.WorkId == wHSWarehouseWorkHeaderEntity.WarehouseWorkId

        {

            qty += whsWorkLine.QtyWork;

            qtyloc += whsWorkLine.QtyRemain;

        }

        wHSWarehouseWorkHeaderEntity.QtyWork = qty;

        wHSWarehouseWorkHeaderEntity.QtyRemain = qtyloc;

        next postload();

    }

  }


Line Dataentity postload method :

[ExtensionOf(tableStr(WHSWarehouseWorkLineEntity))]

internal final class DaxWHSWarehouseWorkLineEntity_Extension

{

    public void postload()

    {

        Inventbatch     inventBatch;

        WHSWarehouseWorkLineEntity whsWarehouseWorkLineEntity = this;

          select inventBatch

            where inventBatch.itemId == whsWarehouseWorkLineEntity.WarehouseWorkId

            && inventBatch.inventBatchId == whsWarehouseWorkLineEntity.ItemBatchNumber;

        whsWarehouseWorkLineEntity.ExpDate = inventBatch.expDate;

        whsWarehouseWorkLineEntity.ItemName = InventTable::find(whsWarehouseWorkLineEntity.ItemNumber).itemName();

        next postload();

            }

  }




Thursday, May 18, 2023

How to export/import purchase order lines through button in D365 using x++

 Class 1 : Export Class :

internal final class DaxExportClass

{

    public static void main(Args args)

    {

        #DMF

        Query query;

        DMFEntityName entityName = "Purchase order lines V2";

        DMFDefinitionGroupName definitionGroupName = 'purchase order export';

          SharedServiceUnitFileID fileId;

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

        boolean isGenerated = false;

        PurchLine   purchLine = args.record();

               // Update

 query        query = new query(dmfutil::getDefaultQueryForEntityV3(entityName,definitionGroupName));

        querybuilddatasource qbds = query.datasourcetable(tablenum(PurchPurchaseOrderLineV2Entity));

        sysquery::findorcreaterange(qbds, fieldnum(PurchPurchaseOrderLineV2Entity, PurchaseOrderNumber)).value(purchLine.PurchId);

        // Export file        // Definition group will be created if it is not existed

        try

        {

            DMFEntityExporter exporter = new DMFEntityExporter();


            //There are optional parameters also added

            fileId = exporter.exportToFile(

            entityName,//Entity label

            definitionGroupName,//Definition group to reuse

            '',//ExecutionId group to reuse,

            'EXCEL',//Source format to export in

            #FieldGroupName_AllFields,//Specify the field group fields to include in export.

            query.pack(),//Query criteria to export records

            curExt(),//Default curExt()

            null,//List of XSLT files

            true,//showErrorMessages

            false);//showSuccessMessages

            if (fileId != '')

            {

                //Get Azure blob url from guid

                str downloadUrl = DMFDataPopulation::getAzureBlobReadUrl(str2Guid(fileId));

                System.Uri uri = new System.Uri(downloadUrl);

                str fileExt;

                //Get file extension

                if (uri != null)

                {

                    fileExt = System.IO.Path::GetExtension(uri.LocalPath);

                }

                Filename filename = strFmt('PurchaseOrderlines%1',fileExt);

                System.IO.Stream stream = File::UseFileFromURL(downloadUrl);

                //Send the file to user

                File::SendFileToUser(stream, filename);

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

                isGenerated = true;

            }

            else

            {

                throw error("The file was not generated succefully. See execution log");

            }

        }

        catch

        {

                        throw error("DMF execution failed and details were written to the execution log");

        }

      }

  }

Class 2 : Import Class :

internal final class DaxImportClass

{

    private static DMFDefinitionGroup findDMFDefinitionGroup()

    {

        DMFDefinitionGroup definitionGroup;

        select firstonly definitionGroup

            where definitionGroup.DefinitionGroupName == 'Purchase order lines'; //DMF import data project

        return definitionGroup;

    }

      private static DMFDefinitionGroupEntity findDMFDefinitionGroupEntity(DMFDefinitionGroup _definitionGroup)

    {

        DMFDefinitionGroupEntity definitionGroupEntity;

        DMFEntity dmfEntity;

          select firstonly RecId, Entity from definitionGroupEntity 

exists join dmfEntity

            where definitionGroupEntity.DefinitionGroup == _definitionGroup.DefinitionGroupName

                && dmfEntity.EntityName == definitionGroupEntity.Entity

                && dmfEntity.TargetEntity == dataentityviewstr(PurchPurchaseOrderLineV2Entity);

          if (!definitionGroupEntity)

        {

            throw error(strFmt("@DMF:DMFNoEntityExists", _definitionGroup.DefinitionGroupName));

        }

        return definitionGroupEntity;

    }

      private static DMFLocalFilePath applyTransforms(SharedServiceUnitFileID _uploadedStatement,                                                                                             DMFDefinitionGroup definitionGroup)

    {

        DMFDefinitionGroupEntity    definitionGroupEntity =                             DaxImportClass::findDMFDefinitionGroupEntity(definitionGroup);

        DMFExecutionId              executionId =                                     DMFUtil::setupNewExecution(definitionGroup.DefinitionGroupName);

        DMFDefinitionGroupExecution execution = DMFDefinitionGroupExecution::find(

            definitionGroup.DefinitionGroupName,

            definitionGroupEntity.Entity,

            executionId,

            true);

        execution.IsTransformed = NoYes::No;

        DMFLocalFilePath filePath = execution.applyTransforms(_uploadedStatement);

        DMFExecution e = DMFExecution::find(executionId, true);

        e.delete();

        return filePath;

    }

      public static void main(Args _args)

    {

        SharedServiceUnitFileID fileId;

        //Get the file from user

        FileUploadTemporaryStorageResult result = File::GetFileFromUser() as FileUploadTemporaryStorageResult;

        if (result && result.getUploadStatus())

        {

            fileId = result.getFileId();

            DMFDefinitionGroup          definitionGroup = DaxImportClass::findDMFDefinitionGroup();

            DaxImportClass::applyTransforms(fileId, definitionGroup);

            DMFDefinitionGroupEntity    definitionGroupEntity = DaxImportClass::findDMFDefinitionGroupEntity(definitionGroup);

            DMFExecutionId              executionId = DMFUtil::setupNewExecution(definitionGroup.DefinitionGroupName);

            // Find execution

            DMFDefinitionGroupExecution execution = DMFDefinitionGroupExecution::find(definitionGroup.DefinitionGroupName, definitionGroupEntity.Entity,

                                                                                        executionId, true);

            execution.FilePath = fileId;

            execution.IsTransformed = NoYes::Yes;

            execution.update();

            // Import the file via quick import DMF

            DMFQuickImportExport::doPGImport(definitionGroup.DefinitionGroupName, executionId, true);

            //deletes file

            result.deleteResult();

        }

    }

}

Note : You need to create projects in DMF.






Tuesday, May 16, 2023

How to get one datasource cursor record in another datasource field method in d365

 

 FormDataObject formDataObject = any2Object(this) as FormDataObject;

        FormDataSource formDataSource,formdatasourceloc;

        formDataSource = formDataObject.datasource();

        formdatasourceloc = formDataSource.formRun().dataSource("WHSLoadTable");

        wHSLoadTable = formdatasourceloc.cursor();

How to Accept over delivery/under delivery percentage for new loads in d365

 Here My requirement is to accept over delivery/under delivery percentage for new loads for purchase order line.

Example : I have purchase order line with Item A0001 and the quantity is 10.

I have over delivery and under delivery fields in Item level purchase tab. The values are 50%

and 50%.

now  50% of 10 is 5. I need to throw error if quanity is below 5 and above 15.

standard is throwing error for above 10 ,based on quantity of purchline.


Path :Product Information Management >Products> Release products 



Path: Warehouse management/Setup / Load / Load template 

path : All purchase order > Warehouse tab> load planning workbench> to new load. 



Class 1:

[ExtensionOf(classStr(whsLoadTemplateAssignmentForm))]
internal final class DaxWHSLoadTemplateAssignmentClass_Extension
{
    public static WHSLoadTemplateId   wHSLoadTemplateId;
       public WHSLoadTemplateId parmWHSLoadTemplateId(WHSLoadTemplateId _WHSLoadTemplateId = wHSLoadTemplateId)
    {
        wHSLoadTemplateId = _WHSLoadTemplateId;
          return wHSLoadTemplateId;
    }
      boolean whsLoadLineQty_validate(WHSLoadLine _whsLoadLine)
    {
        real Underquantity,Overquantity;
        WHSLoadTemplate wHSLoadTemplate;
        WHSLoadTable    wHSLoadTable;
        boolean     ret;
        ret=next whsLoadLineQty_validate(_whsLoadLine);
        select wHSLoadTemplate
            where wHSLoadTemplate.LoadTemplateId == wHSLoadTemplateId;
        Underquantity = (_whsLoadLine.QtyLeftToStructure *_whsLoadLine.UnderDeliveryPct)/100;
        if(wHSLoadTemplate.DaxAcceptUnderDelivery == NoYes::Yes)
        {
            if(_whsLoadLine.Qty < Underquantity)
            {
                ret = checkFailed("The load quantity is under the deliver quantity");
            }
            return ret;
        }
        else
        {
            return ret;
        }
    }

}

Class 2 :

[ExtensionOf(formStr(WHSLoadTemplateAssignment))]
internal final class DaxWHSLoadTemplateAssignment_Extension
{
    void loadFieldData()
    {
        whsLoadTemplateAssignmentForm whsLoadTemplateAssignmentForm = new whsLoadTemplateAssignmentForm();
        next loadFieldData();
        whsLoadTemplateAssignmentForm.parmWHSLoadTemplateId(wHSLoadTable.loadTemplateId);
    }
}


Class 3:

[ExtensionOf(tableStr(WHSLoadLine))]
internal final class DaxWHSLoadLine_Extension
{
    public WHSQtyLeftToLoad qtyLeftToLoad()
    {
        whsLoadTemplateAssignmentForm   whs = new whsLoadTemplateAssignmentForm();
        WHSLoadTemplateId   loadTemplateId;
        WHSLoadLine         wHSLoadLine = this;
        WHSLoadTemplate     wHSLoadTemplate;
        InventHandlingQty   qtyLeftToLoad;
        real                qty,Overquantity;
        select wHSLoadTemplate
            where wHSLoadTemplate.LoadTemplateId == whs.parmWHSLoadTemplateId();
        qty =  next qtyLeftToLoad();
        if(wHSLoadTemplate.DaxAcceptOverDelivery == NoYes::Yes)
        {
            Overquantity = (wHSLoadLine.QtyLeftToStructure * wHSLoadLine.OverDeliveryPct)/100;
            qtyLeftToLoad = qty + Overquantity;
            return qtyLeftToLoad;
        }
        else
        {
            return qty;
        }
    }
}


 

 



Tuesday, May 9, 2023

How to create and post a journal using postman in d365

 Here my requirement is to create and post a journal using postman json format input file.

Create two tables :

1. DTT_PostingProfile

2.DTT_PostingProfileDetails

Create two forms :

1.main form

2.Details form





Classes :

1.Request Class.
2.Response Class.
3.Service Class.

1.Request Class :

Note : Parmmethod ie.,(DatamemberAttribe) names should be the same as json file input names.

Note : Untick the continous checkbox in number sequences if journal is not going to be created, ie., if you get numseq error.

[DataContractAttribute]
internal final class DTT_RequestContractClass
{
    str     LegalEntity;
    str     Process;
    date    TransactionDate;
    real    Volume;
    str     AllocationAccount;
    str     WaterAuthority;
    str     SourceTradingZone;
    str     UseTradingZone;
    str     ApplicationId;
    str     TransactionText;

    [DataMemberAttribute("LegalEntity")]
    public str parmLegalEntity(str  _legalEntity = LegalEntity)
    {
        LegalEntity = _legalEntity;
        return LegalEntity;
    }
      [DataMemberAttribute("Process")]
    public str parmProcess(str  _Process = Process)
    {
        Process = _Process;
        return Process;
    }
      [DataMemberAttribute("TransactionDate")]
    public date parmTransactionDate(date  _TransactionDate = TransactionDate)
    {
        TransactionDate = _TransactionDate;
        return TransactionDate;
    }
      [DataMemberAttribute("Volume")]
    public real parmVolume(real  _Volume = Volume)
    {
        Volume = _Volume;
        return Volume;
    }
      [DataMemberAttribute("AllocationAccount")]
    public str parmAllocationAccount(str  _AllocationAccount = AllocationAccount)
    {
        AllocationAccount = _AllocationAccount;
        return AllocationAccount;
    }
      [DataMemberAttribute("WaterAuthority/WaterCorporation")]
    public str parmWaterAuthority(str  _WaterAuthority = WaterAuthority)
    {
        WaterAuthority = _WaterAuthority;
        return WaterAuthority;
    }      
[DataMemberAttribute("SourceTradingZone")]
    public str parmSourceTradingZone(str  _SourceTradingZone = SourceTradingZone)
    {
        SourceTradingZone = _SourceTradingZone;
        return SourceTradingZone;
    }
      [DataMemberAttribute("UseTradingZone")]
    public str parmUseTradingZone(str  _UseTradingZone = UseTradingZone)
    {
        UseTradingZone = _UseTradingZone;
        return UseTradingZone;
    }
      [DataMemberAttribute("ApplicationId")]
    public str parmApplicationId(str  _ApplicationId = ApplicationId)
    {
        ApplicationId = _ApplicationId;
        return ApplicationId;
    }
      [DataMemberAttribute("TransactionText")]
    public str parmTransactionText(str  _TransactionText = TransactionText)
    {
        TransactionText = _TransactionText;
        return TransactionText;
    }
  
}

2. Response class :


[DataContractAttribute]
internal final class DTT_ResponseContractClass
{
    str     Querystatus;
    str     JournalBatchNumber;
    str     ErrorType;
    str     ErrorDescription;
       public static DTT_ResponseContractClass construct(str _Querystatus = "",
                                                    str _JournalBatchNumber = "",
                                                    str _ErrorType = "",
                                                    str _ErrorDescription = "")
    {
        DTT_ResponseContractClass contract = new DTT_ResponseContractClass();
        contract.initialize(_Querystatus,_JournalBatchNumber,_ErrorType,_ErrorDescription);
        return contract;
    }
      private void initialize(str _Querystatus,str _JournalBatchNumber,str _ErrorType,str _ErrorDescription)
    {
        this.parmQuerystatus(_Querystatus);
        this.parmJournalBatchNumber(_JournalBatchNumber);
        this.parmErrorType(_ErrorType);
        this.parmErrorDescription(_ErrorDescription);
    }
      [DataMemberAttribute("Querystatus")]
    public str parmQuerystatus(str  _Querystatus = Querystatus)
    {
        Querystatus = _Querystatus;
        return Querystatus;
    }
      [DataMemberAttribute("JournalBatchNumber")]
    public str parmJournalBatchNumber(str  _JournalBatchNumber = JournalBatchNumber)
    {
        JournalBatchNumber = _JournalBatchNumber;
        return JournalBatchNumber;
    }
      [DataMemberAttribute("ErrorType")]
    public str parmErrorType(str  _ErrorType = ErrorType)
    {
        ErrorType = _ErrorType;
        return ErrorType;
    }
      [DataMemberAttribute("ErrorDescription")]
    public str parmErrorDescription(str  _ErrorDescription = ErrorDescription)
    {
        ErrorDescription = _ErrorDescription;
        return ErrorDescription;
    }
      public void setFailed(str _message)
    {
        this.parmErrorDescription(_message);
    }
      public void setFailedloc(str _message)
    {
        this.parmErrorType(_message);
    }
  
}

3. Service Class :

internal final class DTT_ServiceClass
{
    DTT_PostingProfile          dTT_PostingProfile;
    DTT_PostingProfileDetails   dTT_PostingProfileDetails;
    LedgerJournalTable  ledgerJournaltable;
    LedgerJournalTrans  ledgerJournalTrans;
    LedgerJournalName   ledgerJournalname;
         public DTT_ResponseContractClass exampleReturnJson(DTT_RequestContractClass _request)
       {
           DTT_ResponseContractClass contract = DTT_ResponseContractClass::construct();
           DTT_Process dTT_Process;
           container   con;
            LedgerJournalCheckPost jourPost;
           NumberSeq   numberSeq;
           str     process= _request.parmProcess();
           dTT_Process = str2Enum(dTT_Process,process);
           try
           {
                          select crosscompany dTT_PostingProfile
                where dTT_PostingProfile.DTT_Process == dTT_Process
                && dTT_PostingProfile.DataAreaId == _request.parmLegalEntity();
            select crosscompany dTT_PostingProfileDetails
                where dTT_PostingProfileDetails.DTT_Process == dTT_PostingProfile.DTT_Process;
            select crosscompany ledgerJournaltable
                 where ledgerJournaltable.JournalName == dTT_PostingProfile.DTT_JournalName
                 && ledgerJournaltable.DataAreaId == _request.parmLegalEntity();
            changecompany(_request.parmLegalEntity())
            {
                ledgerJournalTable.clear();
                ledgerJournalTable.initFromLedgerJournalName( dTT_PostingProfile.DTT_JournalName);
                ledgerJournaltable.JournalNum = JournalTableData::newTable(ledgerJournalTable).nextJournalId();
                if (ledgerJournalTable.validateWrite())
                {
                    ledgerJournalTable.insert();
                }
                                      ledgerJournalTrans.clear();
                ledgerJournalTrans.initValue();
                ledgerjournalTrans.JournalNum = ledgerJournalTable.JournalNum;
                ledgerjournalTrans.TransDate = _request.parmTransactionDate();
                ledgerjournalTrans.Company = _request.parmLegalEntity();
                ledgerjournalTrans.AccountType = LedgerJournalACType::Ledger;
                con = DTT_ServiceClass::getLedgerDim(dTT_PostingProfileDetails);
                ledgerJournalTrans.LedgerDimension =  conPeek(con,1);
                ledgerJournalTrans.OffsetLedgerDimension = conPeek(con,2);
                ledgerjournalTrans.Txt = _request.parmTransactionText();
                if(dTT_PostingProfileDetails.DTT_DebitCreaditProposal == DTT_DebitCreaditProposal::Debit)
                {
                    ledgerjournalTrans.AmountCurDebit = _request.parmVolume();
                }
                else if(dTT_PostingProfileDetails.DTT_DebitCreaditProposal == DTT_DebitCreaditProposal::Credit)
                {
                    ledgerjournalTrans.AmountCurCredit = _request.parmVolume();
                }
                ledgerjournalTrans.OffsetAccountType = LedgerJournalACType::Ledger;
                ledgerjournalTrans.OffsetTxt = _request.parmTransactionText();
                ledgerjournalTrans.Approved = NoYes::Yes;
                ledgerjournalTrans.defaultRow(); // remove this line if u get continous error
                if (ledgerJournalTrans.validateWrite())
                {
                    ledgerjournalTrans.insert();
                }
                 jourPost = LedgerJournalCheckPost::newLedgerJournalTable(ledgerJournalTable, NoYes::Yes);
                jourPost.runOperation();
            }
            if(_request.parmAllocationAccount() == null)
            {
                contract.setFailedloc("ApplicationAccount is empty");
                contract.setFailed("ApplicationAccount cannot be blank");
            }
            else if(_request.parmVolume() ==0)
            {
                contract.setFailedloc("Volume is empty");
                contract.setFailed("volume cannot be blank");
            }
            else if(_request.parmLegalEntity() ==null)
            {
                 contract.setFailedloc("LegalEntity is empty");
                contract.setFailed("LegalEntity cannot be blank");
            }
            else if(_request.parmProcess() == null)
            {
                contract.setFailedloc("Process is empty");
                contract.setFailed("Process cannot be blank");
            }
            else if(_request.parmSourceTradingZone() == null)
            {
                contract.setFailedloc("SourceTradingZone is empty");
                contract.setFailed("SourceTradingZone cannot be blank");
            }
            else if(_request.parmTransactionDate()== dateNull())
            {
                contract.setFailedloc("TransactionDate is empty");
                contract.setFailed("TransactionDate cannot be blank");
            }
            else if(_request.parmTransactionText() == null)
            {
                contract.setFailedloc("TransactionText is empty");
                contract.setFailed("TransactionText cannot be blank");
            }
            else  if(_request.parmUseTradingZone() == null)
            {
                contract.setFailedloc("UseTradingZone is empty");
                contract.setFailed("UseTradingZone cannot be blank");
            }
            else if(_request.parmWaterAuthority() == null)
            {
                contract.setFailedloc("WaterAuthority is empty");
                contract.setFailed("WaterAuthority cannot be blank");
            }
            else
            {
                contract.parmQuerystatus("0");
                contract.parmJournalBatchNumber(ledgerjournalTrans.Voucher);
                contract.parmErrorType("Test");
                contract.parmErrorDescription("Test");
            }
            return     contract;
            }
             catch (Exception::Error) 
           {
                contract.parmQuerystatus("1");
                contract.parmJournalBatchNumber("Test");
                contract.parmErrorType("Test");
                contract.parmErrorDescription("Test");
            }
            return contract;
            }
      static container getLedgerDim(DTT_PostingProfileDetails   dTT_PostingProfileDetails)
    {
        DimensionDynamicAccount ledgerDim;
        LedgerRecId             ledgerRecId;
        MainAccountnum          mainAccount,mainAccountloc;
        DimensionAttributeValueCombination      dimensionAttributeValueCombination;
        DimensionStorage        dimStorage;
        container               con,conloc;
        int64                   value,valueloc;
        int                     i;
        // mainAccount = MainAccount::findByMainAccountId("110115");
        //mainAccountloc = MainAccount::findByMainAccountId("110130");
        mainAccount = dTT_PostingProfileDetails.DTT_MainAccount;
        mainAccountloc = dTT_PostingProfileDetails.DTT_OffsetAccount;
        con = [mainAccount,mainAccountloc];
        for (i = 1; i <= conLen(con); i++)
        {
            //value =any2Int64(conPeek(con,i));
            DimensionServiceProvider DimensionServiceProvider = new DimensionServiceProvider();
            LedgerAccountContract LedgerAccountContract = new LedgerAccountContract();
            DimensionAttributeValueContract ValueContract;
            List ListValueContract = new List(Types::Class);
            LedgerAccountContract.parmMainAccount(conPeek(con,i));
            LedgerAccountContract.parmValues(ListValueContract);
            dimStorage = DimensionServiceProvider::buildDimensionStorageForLedgerAccount(LedgerAccountContract);
            dimensionAttributeValueCombination = DimensionAttributeValueCombination::find(dimStorage.save());
            if(dimensionAttributeValueCombination.RecId)
            {
                ledgerRecId = dimensionAttributeValueCombination.RecId;
            }
            conloc += ledgerRecId;
        }
        return  conloc;
    }

}


Json input file :
{
    "_request" :
    {
   "LegalEntity" : "USMF",
   "Process"   :    "Trade Application refused",
   "TransactionDate" : "02/01/2023",
   "Volume"    :   "10",
   "AllocationAccount" : "1",
   "WaterAuthority/WaterCorporation" : "111",
   "SourceTradingZone" : "12",
   "UseTradingZone" : "12",
   "ApplicationId" : "ap11",
   "TransactionText" : "Trade application processed"
    }
}

Respone :

 "$id""1",
    "Querystatus""0",
    "JournalBatchNumber""GNJL000804",
    "ErrorType""Test",
    "ErrorDescription""Test"



Monday, April 17, 2023

How to update purchline vendor tax information based on selected location in header.

 My requirement is to add a tab page on purchase order header same as like punchline vendor tax information. Instead of updating vendor tax in each punchline , if i update in header it should update to all the punchlines at a time.

Add Fields and relations in purchtable :




Add Controls in PurchTable Form:


Code to get lookup for location:

[FormControlEventHandler(formControlStr(PurchTable, VendorLocation), FormControlEventType::Lookup)] 
public static void VendorLocation_OnLookup(FormControl sender, FormControlEventArgs e)    
{        
DirPartyTable               dirPartyTable;
        VendTable                   VendTable;
        LogisticsLocationRoleType  _roleType = LogisticsLocationRoleType::None;
        PurchTable                  purchTable = sender.dataSourceObject().cursor();
        select * from dirPartyTable
         join vendTable
           where dirPartyTable.RecId  == VendTable.Party
           &&   VendTable.AccountNum == purchTable.OrderAccount;
        TaxInformation_IN::locationLookup(sender,dirPartyTable.RecId,_roleType);
        FormControlCancelableSuperEventArgs cancelableSuperEventArgs = e as FormControlCancelableSuperEventArgs;
        cancelableSuperEventArgs.CancelSuperCall();
}

Code to get Tax lookup :

[FormControlEventHandler(formControlStr(PurchTable, VendorTaxInfo), FormControlEventType::Lookup)]
public static void VendorTaxInfo_OnLookup(FormControl sender, FormControlEventArgs e)    
{        
PurchTable purchTable = sender.dataSourceObject().cursor();
        TaxInformation_IN::lookup(sender,purchTable.vendorLocation);
        FormControlCancelableSuperEventArgs cancelableSuperEventArgs = e as FormControlCancelableSuperEventArgs;
        cancelableSuperEventArgs.CancelSuperCall();  
}

Code for Modifying location :

[FormControlEventHandler(formControlStr(PurchTable, VendorLocation), FormControlEventType::Modified)]    
public static void VendorLocation_OnModified(FormControl sender, FormControlEventArgs e)
{         
VendTable               vendTable;
        PurchTable              purchTable;
        TaxInformation_IN       taxInformation_IN;
        LogisticsLocation       logisticsLocation;
        DirPartyTable           dirPartyTable;
        LogisticsPostalAddress  logisticsPostalAddress;
        Query           query = new Query();
        QueryBuildDataSource    queryBuildDataSource;
        QueryBuildRange         queryBuildRange;
        TransTaxInformation     transTaxInformation;
        FormRun                 formRun;
          formRun = sender.formRun();
        FormDataSource purchtable_ds =  formRun.dataSource();
        purchTable     = formRun.dataSource().cursor();
        select logisticsLocation where logisticsLocation.RecId == purchTable.VendorLocation;
        select logisticsPostalAddress where logisticsPostalAddress.Location == logisticsLocation.RecId;
        select taxInformation_IN
             where taxInformation_IN.RegistrationLocation == logisticsLocation.RecId
            && taxInformation_IN.IsPrimary == NoYes::Yes;
          ttsbegin;
        purchTable.Address = logisticsPostalAddress.Address;
        purchTable.VendorTaxInformation = taxInformation_IN.RecId;
        purchTable.selectForUpdate(true);
        purchTable.update();
        ttscommit; 
}

Code for JumpRef of Location and Tax fields:

[ExtensionOf(formStr(PurchTable))]
internal  final class DaxPurchTableForm_Extension
{   
public TransTaxInformation  transTaxInformationloc;
    private void initControls()    
{        
List              list = new List(Types::Class);
        #ISOCountryRegionCodes
        TransTaxInformationVendorTaxInfoCtrl_IN     transTaxInformationVendorTaxInfoCtrl = new TransTaxInformationVendorTaxInfoCtrl_IN();        transTaxInformationVendorTaxInfoCtrl.parmVendorTaxInformation(VendorTaxInformation);
        transTaxInformationVendorTaxInfoCtrl.parmVendorTaxInfo(VendorTaxInfo);
        transTaxInformationVendorTaxInfoCtrl.parmVendorLocation(VendorLocation);
        list.addEnd(transTaxInformationVendorTaxInfoCtrl);
    }
      public void  init()
    {
        PurchTable          purchTable;
        VendTable           vendTable;
        DirPartyTable       dirPartyTable;
        LogisticsLocation   logisticLocation;
        TaxInformation_IN   taxInformation_IN;
        TransTaxInformation transTaxInformation;
        List                list = new List(Types::Class);
          TransTaxInformationVendorTaxInfoCtrl_IN     transTaxInformationVendorTaxInfoCtrl = new TransTaxInformationVendorTaxInfoCtrl_IN();
        TransTaxInformationUIController     transTaxInformationUIController;
        next init();
                FormDataSource fds = this.dataSource(formDataSourceStr(PurchTable,PurchTable));
                  this.initControls();
         fds.object(fieldNum(PurchTable, VendorLocation)).registerOverrideMethod(methodStr(FormReferenceGroupControl, jumpRef),methodStr(TransTaxInformationUIController, jumpRefOfVendorLocation), this);
        fds.object(fieldNum(PurchTable, VendorTaxInformation)).registerOverrideMethod(methodstr(FormReferenceGroupControl, jumpRef), FormmethodStr(PurchTable, jumpRefOfVendTaxInfo), this);
    }
      protected void jumpRefOfVendorLocation(FormReferenceObject _formReferenceObject)
    {
        FormDataSource fds = this.dataSource(formDataSourceStr(PurchTable,PurchTable));
        TaxInformation_IN::jumpRefLocationAddressForm(purchTable.VendorLocation, fds.formRun());
    }
      protected void jumpRefOfVendTaxInfo(FormReferenceObject _formReferenceObject)
    {
        TaxInformation_IN::jumpRef(purchTable.VendorTaxInformation, _formReferenceObject);
    }
  }

Code in Validatewrite of purchtable form :

[ExtensionOf(FormDataSourcestr(PurchTable,PurchTable))]
internal final class DaxPurchTableFormDatasource_Extension
{
    public boolean Validatewrite()
    {
        boolean             ret;
        PurchTable          purchTable,purchTableloc;
        PurchLine           purchLine;
        VendTable           vendTable;
        TaxInformation_IN   taxInformation_IN;
        Dialog              dialog;
        TransTaxInformation transTaxInformationloc;
        DialogField         field;
        DialogButton        copyTaxGroupToMarkupTrans;
        PurchTable2LineUpdatePrompt     purchTable2LineUpdatePrompt;
        LogisticsLocation   logisticsLocation;
            FormDataSource purchTable_ds = this.formRun().dataSource();
              purchTable = this.formRun().dataSource().cursor();
           vendTable = VendTable::find(purchTable.OrderAccount);
        ret =next Validatewrite();
        purchTable2LineUpdatePrompt = PurchTable2LineUpdatePrompt::newExecuteExtendedPrompt(purchTable, copyTaxGroupToMarkupTrans);
        if(ret)
        {
            if (purchTable.VendorLocation != purchTable.VendorLocationCopy1)
            {
            dialog = new Dialog("My Dialog");
            dialog.addText("Do you want to transfer the vendor tax information to lines ?");
            dialog.run();
            if (dialog.closedOk())
                {
                    while select purchLine where purchLine.PurchId == purchTable.PurchId
                    {
                                transTaxInformationloc = TransTaxInformationHelper::findOrCreateTransTaxInformation(purchLine.TableId,purchLine.RecId);
                        select logisticsLocation where logisticsLocation.RecId == purchTable.VendorLocation;
                        select taxInformation_IN where taxInformation_IN.RecId == purchTable.VendorTaxInformation;
                            ttsbegin;
                            transTaxInformationloc.selectForUpdate(true);
                            transTaxInformationloc.VendorLocation = logisticsLocation.RecId;
                            transTaxInformationloc.VendorTaxInformation = taxInformation_IN.RecId;
                            transTaxInformationloc.Update();
                            purchTable.VendorLocationCopy1 = purchTable.VendorLocation;//I need to open dialog form when location is modified and saved ,so created a dummy field for storing.
                            purchTable.selectForUpdate(true);
                            ttscommit;
                    }
                }
            }
        }
        return ret;
      }
 }