Saturday, March 29, 2025

How to register return sales order lines using X++ code

How to Register Return Sales Order Lines in X++

The TestSalesReturnOrderLineRegister Class in X++

The TestSalesReturnOrderLineRegister class serves as an entry point to the product registration process, specialized for the sales return order process. It handles the return disposition code and manages sales return order specifics, such as creating inventory transactions.

Code Overview



class TestSalesReturnOrderLineRegister extends TradeOrderLineRegister
{
    ReturnDispositionCodeId returnDispositionCodeId;
    DialogField dialogDispositionCodeId;
    SalesLine salesLine;
    boolean reverseInventTrans;
    boolean recreateReservationLine;
    boolean inRegistration;

    public boolean init()
    {
        boolean ret = super();
        salesLine = salesPurchLine;
        return ret;
    }

    public void run()
    {
        this.runPreSuper();
        super();
        this.runPostSuper();
    }

    public void runPostSuper()
    {
        salesLine = SalesLine::findInventTransId(salesLine.InventTransId, true);
        if (inRegistration)
        {
            if (salesLine.ReturnStatus == ReturnStatusLine::Awaiting)
            {
                if (reverseInventTrans && !salesLine.ReturnAllowReservation)
                {
                    SalesLine::changeReturnOrderType(salesLine.InventTransId, null, true);
                    salesLine = SalesLine::findInventTransId(salesLine.InventTransId, true);
                }
                if (salesLine.ReturnDispositionCodeId)
                {
                    salesLine.ReturnDispositionCodeId = '';
                    salesLine.update();
                }
            }
        }
        else 
        {
            if (salesLine.ReturnStatus == ReturnStatusLine::Registered && recreateReservationLine)
            {
                salesLine.createReturnReservationLine();
                salesLine = SalesLine::findInventTransId(salesLine.InventTransId, true);
            }
        }
    }
}
    

Calling the TestSalesReturnOrderLineRegister Class


public void registerReturnSOLine(SalesId _salesId, ReturnDispositionCodeId _dispositionCode)
{
    TradeOrderLineRegister tradeOrderlineRegister;
    TestSalesReturnOrderLineRegister salesReturnOrderLineRegister;
    InventTransWMS_Register inventTransWMS_register;
    TmpInventTransWMS TmpInventTransWMS;
    SalesLine salesLine;
    InventTrans inventTrans;
    InventTransOrigin inventTransOrigin;
    returnDispositionCode returnDispositionCode;

    Args args = new Args();
    while select forUpdate salesLine where salesLine.SalesId == _returnSOTable.SalesId
    {
        args.record(salesLine);
        tradeOrderLineRegister = TestSalesReturnOrderLineRegister::construct();
        tradeOrderLineRegister.parmArgs(args);
        tradeOrderLineRegister.init();
        salesReturnOrderLineRegister = tradeOrderLineRegister;
        salesReturnOrderLineRegister.runPreSuper();
        
        select firstOnly returnDispositionCode
            where returnDispositionCode.DispositionAction == DispositionAction::Credit;
        
        salesLine.ReturnDispositionCodeId = returnDispositionCode.DispositionCodeId;
        salesLine.update();

        select firstOnly crossCompany inventTrans
            join RecId, InventTransId from inventTransOrigin
                where inventTransOrigin.InventTransId == salesLine.InventTransId
                && inventTrans.InventTransOrigin == inventTransOrigin.RecId;

        inventTransWMS_register = inventTransWMS_register::newStandard(tmpInventTransWMS);
        tmpInventTransWMS.clear();
        tmpInventTransWMS.initFromInventTrans(inventTrans);
        tmpInventTransWMS.InventDimId = inventTrans.InventDimId;
        tmpInventTransWMS.insert();

        inventTransWMS_register.writeTmpInventTransWMS(tmpInventTransWMS, inventTrans, inventTrans.inventDim());
        if (!inventTransWMS_register.updateInvent(salesLine))
        {
            throw error("Error during registration of sales line.");
        }
    }
}
    

Wednesday, March 26, 2025

How to create COC for form methods , How to get formRun , How to make control visible false on form in D365FO

How to create COC for form method in D365FO

How to create COC for form method in D365FO

Example Code

[ExtensionOf(formStr(ProjInvoiceListPage))]
final class TestProjInvoiceListPage_Extension
{
    public void init()
    {
        next init();

        FormRun formRun = this as FormRun;

        if(ProjParameters::find().TestPrintPGGDesignForProjectInvoice)
        {
            FormControl         stdViewCopyBtn   = formrun.design(0).controlName('PrintProjInvoiceCopyButton');
            FormControl         stdViewOrigBtn   = formrun.design(0).controlName('PrintProjInvoiceButton');
            stdViewCopyBtn.visible(false);
            stdViewOrigBtn.visible(false);
        }
        else
        {
            FormControl         customViewCopyBtn   = formrun.design(0).controlName('TestPSAProjInvoiceCopy');
            FormControl         customViewOrigBtn   = formrun.design(0).controlName('TestPSAProjInvoiceOriginal');

            customViewCopyBtn.visible(true);
            customViewOrigBtn.visible(true);
        }
    }
}

Thursday, February 6, 2025

Fix Dynamics 365FO Synchronization Error - Transaction Log Full

Fix Dynamics 365FO Synchronization Error - Transaction Log Full

Fix: The transaction log for database is full due to 'log_backup' - Dynamics 365FO

If you're encountering the error "The transaction log for database is full due to 'log_backup'" while working with Dynamics 365 Finance and Operations (D365FO), it means your SQL Server transaction log has reached its maximum capacity.

Solution

Follow these steps to resolve the issue:

Step 1: Check the Database Files

Run the following SQL query to check the database file details:

    SELECT * FROM sys.database_files
    

Note down the log file name from the result and use that same name in the second statement of the step 2 SQL query.

Query result screenshot:

Database files query result

Step 2: Shrink the Transaction Log

Execute the following commands to shrink the transaction log and free up space:

    ALTER DATABASE AxDB SET RECOVERY SIMPLE;
    DBCC SHRINKFILE('AxDb_New_log', 0, TRUNCATEONLY);
    ALTER DATABASE AxDB SET RECOVERY FULL;
    

Replace 'AxDb_New_log' with the actual log file name you noted earlier.

Step 3: Start DB synchronization again...this time it should work

..

Follow "Dynamics World" blog also for some other approach

Tip: Always ensure you have proper database backups before making changes to recovery models.

Wednesday, January 22, 2025

Get Description of financial dimension value from SQL DB of D365FO

Retrieve Financial Dimension Value Description using SQL Query in D365FO

How to Retrieve Financial Dimension Value Description with SQL in D365FO

In this post, we will explore how to retrieve the description of a financial dimension value in an ERP or financial management system using a specific SQL query in D365FO.

The Query


SELECT DIMATTVALUE.DISPLAYVALUE AS 'DIMENSIONVALUE',
       DIMATT.NAME AS 'FINANCIALDIMENSION',
       DIMATTVALUE.ISSUSPENDED,
       HCMWORKER.PERSONNELNUMBER AS 'OWNER',
       DimFinTag.DESCRIPTION
FROM DIMENSIONATTRIBUTEVALUE AS DIMATTVALUE
LEFT JOIN HCMWORKER ON DIMATTVALUE.OWNER = HCMWORKER.RECID
JOIN DIMENSIONATTRIBUTE AS DIMATT ON DIMATT.RECID = DIMATTVALUE.DIMENSIONATTRIBUTE
JOIN DIMENSIONATTRIBUTEDIRCATEGORY dimAttDirCategory 
ON dimAttDirCategory.DIMENSIONATTRIBUTE = DIMATTVALUE.DIMENSIONATTRIBUTE
JOIN DIMENSIONFINANCIALTAG DimFinTag ON DIMATTVALUE.DISPLAYVALUE = DimFinTag.VALUE 
AND DimFinTag.FINANCIALTAGCATEGORY = dimAttDirCategory.DIRCATEGORY
WHERE DIMATTVALUE.ISDELETED = 0
  AND DIMATTVALUE.ISSUSPENDED = 0
        

Feel free to leave a comment below if you have any questions or need further clarification on the query or its results!

Monday, January 13, 2025

Call custom service with JSON body in D365FO

Call Custom Service with JSON Body in D365FO

Call Custom Service with JSON Body in D365FO

        
FileUploadTemporaryStorageResult fileUpload = File::GetFileFromUser() as FileUploadTemporaryStorageResult;
System.IO.Stream stream = fileUpload.openResult();
str responceJson;

using (var reader = new System.IO.StreamReader(stream))
{
    responceJson = reader.ReadToEnd();

    TESTPOReceiptRequestContract contract = FormJsonSerializer::deserializeObject(
        classnum(TESTPOReceiptRequestContract), responceJson);

    new TESTPOReceiptService().processRecord(contract);
}
        
    

Friday, July 19, 2024

How to Post Partial Product Receipt in D365FO Using X++ Code

How to Post Partial Product Receipt in D365FO Using X++ Code

How to Post Partial Product Receipt in D365FO Using X++ Code

Handling partial product receipts in Microsoft Dynamics 365 for Finance and Operations (D365FO) can be crucial for businesses that receive shipments in stages. In this blog, we'll explore how to post a partial product receipt using X++ code. We'll refer to a specific code example to guide us through the process.

Introduction

Partial product receipt refers to the process of receiving a portion of the goods ordered rather than the entire quantity. This is common in scenarios where suppliers deliver products in multiple shipments. Posting partial product receipts accurately in D365FO ensures that inventory records reflect the actual quantities received.

Code Example Overview

Here's an example of X++ code that demonstrates how to post a partial product receipt. This example focuses on receiving a specific quantity of a purchase order line.


internal final class POReceiptJobTest
{
    /// 
    /// Class entry point. The system will call this method when a designated menu 
    /// is selected or when execution starts and this class is set as the startup class.
    /// 
    /// The specified arguments.
    public static void main(Args _args)
    {
       PurchTable                  purchTable;
       PurchFormLetter             purchFormLetter;
       PurchFormletterParmData     purchFormLetterParmData;
       PurchParmTable              purchParmTable;
       PurchLine                   purchLine;
       PurchParmLine               purchParmLine;

       ttsBegin;

       // Find the purchase order
       purchTable = PurchTable::find('000039');

       // Create PurchParamUpdate table
       purchFormLetterParmData = PurchFormletterParmData::newData(
                        DocumentStatus::PackingSlip,
                        VersioningUpdateType::Initial);

       purchFormLetterParmData.parmOnlyCreateParmUpdate(true);
       purchFormLetterParmData.createData(false);
       PurchParmUpdate purchParmUpdate = purchFormLetterParmData.parmParmUpdate();

       // Set PurchParmTable table
       purchParmTable.clear();
       purchParmTable.TransDate                = SystemDateGet();
       purchParmTable.Ordering                 = DocumentStatus::PackingSlip;
       purchParmTable.ParmJobStatus            = ParmJobStatus::Waiting;
       
       purchParmTable.Num                      = 'Test234567'; // PR
       purchParmTable.PurchId                  = purchTable.PurchId;
       purchParmTable.PurchName                = purchTable.PurchName;
       purchParmTable.DeliveryName             = purchTable.DeliveryName;
       purchParmTable.DeliveryPostalAddress    = purchTable.DeliveryPostalAddress;
       purchParmTable.OrderAccount             = purchTable.OrderAccount;
       purchParmTable.CurrencyCode             = purchTable.CurrencyCode;
       purchParmTable.InvoiceAccount           = purchTable.InvoiceAccount;
       purchParmTable.ParmId                   = purchParmUpdate.ParmId;
       purchParmTable.insert();

       // Set PurchParmLine table
       select purchLine
           where purchLine.PurchId     == purchTable.PurchId &&
           purchLine.LineNumber  == 1;
    
       purchParmLine.initFromPurchLine(purchLine);

       purchParmLine.ReceiveNow    = 5; // Partial quantity received
       purchParmLine.ParmId        = purchParmTable.ParmId;
       purchParmLine.TableRefId    = purchParmTable.TableRefId;
       purchParmLine.setQty(DocumentStatus::PackingSlip, false, true);
       purchParmLine.setLineAmount();
       purchParmLine.insert();

       // Post the packing slip
       purchFormLetter = PurchFormLetter::construct(DocumentStatus::PackingSlip);
       purchFormLetter.transDate(systemDateGet());
       purchFormLetter.proforma(false);
       purchFormLetter.specQty(PurchUpdate::All);
       purchFormLetter.purchTable(purchTable);
       purchFormLetter.parmParmTableNum(purchParmTable.ParmId);
       purchFormLetter.parmId(purchParmTable.ParmId);
       purchFormLetter.purchParmUpdate(purchFormLetterParmData.parmParmUpdate());
       purchFormLetter.run();

       ttsCommit;
    }
}

    

If you have any questions or need further assistance, feel free to leave a comment below!

Monday, July 15, 2024

How to Return Date Difference in Dynamics 365 Finance and Operations (D365FO) Computed Column

How to Return Date Difference in Dynamics 365 Finance and Operations (D365FO) Computed Column

In Dynamics 365 Finance and Operations (D365FO), computed columns can dynamically calculate and display values derived from other fields or system values. This guide will show you how to create a computed column that calculates the difference in days between a record's creation date and the current date.

Steps to Create a Computed Column and Method

1. Define the Computed Column in the AOT

  1. Open Visual Studio and navigate to the Application Object Tree (AOT).
  2. Expand the Data Dictionary node.
  3. Right-click on Views and select the custom view / Extension of standad view, where you want to add the computed column (e.g., AllPOLinesView).
  4. Click on New > Computed Column.
  5. Name your computed column (e.g., ApprovalDays).
  6. Set the ComputedColumnExpression property to the method you will define for calculating the date difference (e.g., AllPOLinesView::compColumnApprovalDays()).

2. Implement the Computed Column Method (compColumnApprovalDays)

Add the following method to your view's code to calculate the date difference:

private static server str compColumnApprovalDays()
{
    return SysComputedColumn::getDateDiff(
                SysComputedColumn::returnField(tableStr(AllPOLinesView), identifierStr(PurchLine),
                                        fieldId2name(tableNum(PurchLine), fieldNum(PurchLine, CreatedDateTime))),
                SysComputedColumn::getCurrentUtcDate(),
                SysComputedColumnDatePart::Day);
}
    

Explanation of the Method:

  • SysComputedColumn::returnField(tableStr(AllPOLinesView), identifierStr(PurchLine), fieldId2name(tableNum(PurchLine), fieldNum(PurchLine, CreatedDateTime))): Retrieves the CreatedDateTime field from the PurchLine data source in the AllPOLinesView.
  • SysComputedColumn::getCurrentUtcDate(): Gets the current UTC date.
  • SysComputedColumn::getDateDiff(...): Computes the difference in days between the CreatedDateTime field and the current UTC date.
  • SysComputedColumnDatePart::Day: Specifies that the date difference should be calculated in days.

3. Compile and Synchronize

  • Compile your changes in Visual Studio.
  • Synchronize your database to reflect the changes in D365FO.

Using the Computed Column

After setting up the computed column, it will automatically calculate and display the approval days based on the creation date (CreatedDateTime field) for each record in the AllPOLinesView.

Example Usage

Here’s how you can use the computed column in a form or report:

  1. Navigate to the form or report that displays the AllPOLinesView, also make sure ApprovalDays is added on report/Form.
  2. The ApprovalDays computed column will show the number of days between the creation date and the current date for each purchase order line.

Summary

By following these steps, you can create a computed column in D365FO to calculate date differences dynamically. This method enhances data presentation and provides valuable insights based on the computed values. Computed columns like this one can automate calculations and streamline your business processes in D365FO.

Update Values During Data Entity Import in D365FO

Update Values During Data Entity Import in D365FO Updating Field Values During Data Entity Import in Dynamics 365 Finance ...