Skip to main content

Import sales orders from master and details text files

The are many code snippets which you can find easily over the internet to import sales orders from a text file or from excel. The purpose of this post is to share my experience of uploading data into sales order form from two different text files.

void ImportSalesOrders()
{
    Container                  con;
    CustTable                 custTable;
    SalesTable                salesTable;
    SalesLine                  salesLine;
    Headers                    headers;
    Stock                        details;

    num                           newSalesId;
    Description                custDescription;
    
    InventTable                inventTable;
    InventDim                  inventDim;
    InventSiteId               inventSiteId;
    InventLocationId         inventLocationId;


    CustAccount             custAccount;
    real                           itemPrice;
    ItemId                       itemId;

    InventDim                  frominventDim,ToinventDim;

    int                             x,y;
    NumberSeq               num;

    SysOperationProgress progressbar = new SysOperationProgress();
    int i;
    ;

    progressbar.setCaption('Importing Journals');
    progressbar.setAnimation(filenameHeader);
    progressbar.setTotal(30000);
    for (i = 1; i <= 30000; i++)
    {
        progressbar.setText(strfmt("@SYS105740", i));
        progressbar.setCount(i, 1);
    }

    this.importData();
    ttsbegin;
    while select headers
    {
        SalesTable = SalesTable::findDocumentNumber(headers.DocumentNumber);

        if(!SalesTable)
        {
            //create sales table
            salesTable.initValue();

            num = NumberSeq::newGetNum(SalesParameters::numRefSalesId());
            newSalesId = num.num();

            if (salesTable::exist(newSalesId))
            {
                num.abort();
                throw error("@SYS23020");
            }

            salesTable.SalesId = newSalesId;
            num.used();

            if(custDescription != "")
            {
                salesTable.SalesName = custDescription;
            }

            custAccount = headers.CustAccount;

            //fetch the customer details from cust table using account no selected from drop-down list
            select * from custTable where custTable.AccountNum == custAccount;

            salesTable.CustAccount = custTable.AccountNum;
            salesTable.InvoiceAccount = custTable.InvoiceAccount;
            salesTable.SalesType = SalesType::Sales;
            salesTable.SalesStatus = SalesStatus::None;
            salesTable.CurrencyCode = custTable.Currency;

            salesTable.CustGroup = custTable.CustGroup;
            salesTable.DeliveryDateControlType = SalesDeliveryDateControlType::SalesLeadTime;

            //Set dates as systemDateTime
            salesTable.ReceiptDateRequested = systemdateget();
            salesTable.ShippingDateRequested = systemdateget();

            salesTable.LanguageId = 'en-us';
            salesTable.DlvMode = '10';

            inventSiteId = headers.InventSiteId;
            inventLocationId = headers.InventSiteId;

            salesTable.InventSiteId = inventSiteId;
            salesTable.InventLocationId = inventLocationId;
            salesTable.DocumentNumber = headers.DocumentNumber;

            //Craete Sales Order
            salesTable.insert();

            while select details
            where headers.DocumentNumber == details.DocumentNumber
            {
                salesLine.clear();

                // Create Sales Order Line
                salesLine.SalesId = salesTable.SalesId;
                salesLine.initFromSalesTable(salesTable);

                itemId = details.ItemId;

                salesLine.ItemId = itemId;
                salesLine.SalesUnit = InventTable::find(salesLine.ItemId).salesUnitId();

                select * from inventTable where inventTable.ItemId == salesLine.ItemId;
                salesLine.initFromInventTable(inventTable);

                inventDim.clear();
                inventDim.InventSiteId = inventSiteId;
                inventDim.InventLocationId = inventSiteId;

                salesLine.InventDimId = InventDim::findOrCreate(inventDim).inventDimId;

                //Set Qty as 1 by default
                salesLine.SalesQty = details.Qty;
                salesLine.ConfirmedDlv = salesTable.ShippingDateConfirmed;
                salesLine.lineNum = SalesLine::lastLineNum(salesLine.salesId) + 1.0;
                salesLine.RemainInventPhysical = 1;
                salesLine.RemainSalesPhysical = 1;
                salesLine.DlvMode = '10';
                salesLine.SalesStatus = SalesStatus::None;
                salesLine.SalesPrice = details.UnitPrice;
                salesLine.LineAmount = salesLine.SalesQty * salesLine.SalesPrice;

                //Insert sales line items
                salesLine.insert();
            }
        }
        ++x;
    }
    ttscommit;
    info(strfmt("%1 Header(s) imported with their details", x));
}

void importData()
{
    Container               con;
    // I created these two table headers and details to make the import process fast I had huge data files to import
    Headers                 headers;
    Stock                   details;

    TextBuffer              tbHeader = new TextBuffer();
    TextBuffer              tbDetails = new TextBuffer();

    int                     cntHeader, cntDetails;
    int                     numLinesHeader, numLinesDetails;
    container               inLineHeader, inLineDetails;

    int i;
    ;

    tbHeader.fromFile(filenameHeader);
    tbDetails.fromFile(filenameDetail);

    numLinesHeader = tbHeader.numLines();
    numLinesDetails = tbDetails.numLines();

    delete_from headers;
    delete_from details;

    if(numLinesHeader)
    {
        ttsbegin;
        inLineHeader = str2Con(tbHeader.nextToken(true));


        for(cntHeader = 1; cntHeader < numLinesHeader; ++cntHeader)
        {
            inLineHeader = str2Con(tbHeader.nextToken(true));

            headers.DocumentNumber = conpeek(inLineHeader, 1);
            headers.CustAccount = conpeek(inLineHeader, 2);
            headers.insert();
        }

        inLineDetails = str2Con(tbDetails.nextToken(true));

        for(cntDetails = 1; cntDetails < numLinesDetails; ++cntDetails)
        {
            inLineDetails = str2Con(tbDetails.nextToken(true));

            details.DocumentNumber = conpeek(inLineDetails, 1);
            details.ItemId = conpeek(inLineDetails, 2);
            details.Qty = conpeek(inLineDetails, 3);
            details.UnitPrice = conpeek(inLineDetails, 4);
            details.Discount = conpeek(inLineDetails, 5);
            details.UnitDiscount = conpeek(inLineDetails, 6);
            details.insert();
        }

        ttscommit;
    }
}

Comments

  1. Hello Fareed,

    If I understand it right - are you using Headers and details tables are your Temp tables and then loading the data into Salestable, Salesline tables.

    Thanks,

    ReplyDelete
  2. Hi, You don't need to use temp tables rather then using sales order and sales line table. I used temp tables for some customized requirement.

    ReplyDelete
  3. Hi,

    Do you have an example for upload ONE file to table Header-detail in AX 2012?

    Thanks.

    ReplyDelete
  4. Hi Joicehelena,

    I haven't updated this code for AX 2012 but I am sure it will not be that much tough to update it. If you have some specific requirement I would be nice to discuss it with you.

    ReplyDelete
  5. how does it handle with item dimensions.

    ReplyDelete
  6. and inventTransId..?

    ReplyDelete

Post a Comment

I will appreciate your comments !

Popular posts from this blog

D365O - How to add financial dimension in grid

This post outlines the steps; how to add financial dimensions (segmented control) in a grid in D365O. Let's assume we are adding new table and form for below explanation; New table contains two fields  AccountType and  LedgerDimension with relation to DimensionAttributeValueCombination table  Form looks like this; Set properties for segmented control under form design; - Auto declaration = Yes - Account type field = AccountType - Controller class = DimensionDynamicAccountController - Filter expression = %1 1. Override modified method for LedgerDimension field under form's datasource 2. Override lookup and checkUserCustomLookup method on ledger dimension segmented control in form desgin Datasource | D365O_FinancialDimension | LedgerDimension | modified [DataSource]     class D365O_FinancialDimension     { ...

The Dual Write implementation - Part 1 - Understand and Setup

What is Dual-write? Tightly couples – complete at one transaction level Near real time Bi-directional Master data and business documents – Customer records you are creating and modifying and at this document we are talking about sales orders or quotes and invoice. Master data could be reference data e.g. customer groups and tax information Why Dual-write and why not Data Integrator? Data Integrator is Manual or Scheduled One directional Now, Let's deep dive and understand what is required for Dual-write setup and from where to start. First thing first, check you have access to https://make.powerapps.com/ Choose right environment of CDS (CE) Make sure you have access to the environment too, click on gear icon and Admin Center  Look for required environment and Open it, you must have access as going forward you are going to configure dual write steps in the environment user the same user you are logged in now. Now, go back to power platform admin center and...

Another step closer - Finance Operations data in Power Platform - Virtual Entities

This post focuses on the integration technologies available to have the Microsoft Dynamics 365 Finance Operations data available in Dataverse/Common Data Services/CDS. What could be better then having The biggest ERP system's data in Power Platform. You can Power Portals, Power Apps, Power BI analytical reports, use power virtual agents for inventory closing and year end closing processes, manage expenses and employee/contractors time entry processes, most of these processes can be even without logging to MS ERP (Dynamics 365 Finance Operation) so can safe on license cost too.  Let's see what options are available to integrate F&O data with Power Platform however, this post is dedicated to Virtual Entities.  3 Options available out-the-box to integrate F&O data with Power Platform; 👉  Data Integrator  - Click on link to read more 👉  Dual-Write  -  Click on link to read more 👉  Virtual Entities - MS Tech Talk on Virtual entities   ...