Thursday, 11 August 2022

Workflow validation before submit x++ D365 CoC

 [ExtensionOf(classStr(CustFreeInvoiceWorkflow))]

final class XX_CustFreeInvoiceWorkflow_Extension

{

    public static void main(Args _args)

    {

        CustFreeInvoiceWorkflow custFreeInvoiceWorkflow = CustFreeInvoiceWorkflow::construct();

        CustInvoiceTable        custInvoiceTable;

        FormDataSource          custInvoiceTableDataSource;


        if (_args)

        {

            custInvoiceTable = _args.record();

            custInvoiceTableDataSource = FormDataUtil::getFormDataSource(custInvoiceTable);


            if(custInvoiceTable)

            {

                CustInvoiceLine     custInvoiceLine;

                MainAccountNum      mainAccountNum;

                MainAccount         mainAccount;

                

                while select custInvoiceLine where custInvoiceLine.ParentRecId == custInvoiceTable.RecId

                {

                    if(MainAccount::findByMainAccountId(LedgerDimensionFacade::getDisplayValueForLedgerDimension(custInvoiceLine.LedgerDimension)).XX_IsMandatory == true)

                    {

                        boolean         validated, contractCat, customers, projects, division, site;


                        contractCat =   XX_CustInvoiceLineDimension::getValidated(custInvoiceLine.DefaultDimension, "ContractCategory");

                        customers   =   XX_CustInvoiceLineDimension::getValidated(custInvoiceLine.DefaultDimension, "Customers");

                        projects    =   XX_CustInvoiceLineDimension::getValidated(custInvoiceLine.DefaultDimension, "Projects");

                        division    =   XX_CustInvoiceLineDimension::getValidated(custInvoiceLine.DefaultDimension, "Division");

                        site        =   XX_CustInvoiceLineDimension::getValidated(custInvoiceLine.DefaultDimension, "Site");


                        if(contractCat || customers || projects || division || site)

                        {

                            throw error("[ContractCategory, Customers, Projects, Division, Site] dimensions are mandatory in line to submit");

                        }

                    }

                }

            }

        }

        next main(_args);

    }


}

Dimension value by name x++

 public static boolean getValidated(RecId defaultDimension, Name dimName)

    {

        DimensionAttributeValueSetStorage   dimStorage;

        boolean                             hasValue;

        dimStorage  =       DimensionAttributeValueSetStorage::find(defaultDimension);

        hasValue    =       dimStorage.getDisplayValueByDimensionAttribute(DimensionAttribute::findByName(dimName).RecId)? false : True;

        return hasValue;

    }

Thursday, 4 August 2022

Unpack dimension x++

 public str unpackDimension(DimensionDefault _transDimension)

    {

        DimensionAttributeValueSetStorage           dimStorage;

        str                                         segmentName, segmentDescription;

        str                                         segmentValue = "";

        str                                         retProj;//retDept;

        boolean                                     isNullforSales;

        int                                         hierarchyCount, hierarchyIndex;

        DefaultDimensionView                        defaultDimensionView;

        RecId                                       defaultDimension;

        int                                         i;

        container                                   conAttribute;

        container                                   conValues;

        DimensionDefault                            result;

 

        defaultDimension    = _transDimension;

        dimStorage          = DimensionAttributeValueSetStorage::find(defaultDimension);

        for (i= 1 ; i<= dimStorage.elements() ; i++)

        {

            segmentName         = DimensionAttribute::find(dimStorage.getAttributeByIndex(i)).Name;

            segmentValue        = dimStorage.getDisplayValueByIndex(i);

            if(segmentName)

            {

                select defaultDimensionView

            where defaultDimensionView.DefaultDimension == defaultDimension

            && defaultDimensionView.Name == segmentName;

 

                segmentDescription = defaultDimensionView.dimensionDiscription();

            }

            if(segmentName != "Projects")

            {

                continue;

            }

            else

            {

                retProj =   segmentValue;

            }

        }

        return retProj;

    }

Sunday, 3 April 2022

Unpack ledger dimension x++ D365

 class FCC_TestDim

{

    /// <summary>

    /// Runs the class with the specified arguments.

    /// </summary>

    /// <param name = "_args">The specified arguments.</param>

    public static void main(Args _args)

    {

 

        // DimensionAttributeValueCombination stores the combinations of dimension values

// Any tables that uses dimension combinations for main account and dimensions

// Has a reference to this table’s recid

DimensionAttributeValueCombination dimAttrValueComb;

        //GeneralJournalAccountEntry is one such tables that refrences DimensionAttributeValueCombination

        GeneralJournalAccountEntry gjAccEntry;

        // Class Dimension storage is used to store and manipulate the values of combination

        DimensionStorage dimensionStorage;

        // Class DimensionStorageSegment will get specfic segments based on hierarchies

        DimensionStorageSegment segment;

        int segmentCount, segmentIndex;

        int hierarchyCount, hierarchyIndex;

        str segmentName, segmentDescription,segmentValue;

        LedgerJournalTrans ledgerJournalTrans;

        ;

        select ledgerJournalTrans where ledgerJournalTrans.JournalNum == "00457";

 

        dimAttrValueComb = DimensionAttributeValueCombination::find(ledgerJournalTrans.OffsetLedgerDimension);

 

        // Get dimension storage

        dimensionStorage = DimensionStorage::findById(ledgerJournalTrans.OffsetLedgerDimension);

        if (dimensionStorage == null)

        {

            throw error("@SYS83964");

        }

 

        // Get hierarchy count

        hierarchyCount = dimensionStorage.hierarchyCount();

        //Loop through hierarchies to get individual segments

        for(hierarchyIndex = 1; hierarchyIndex <= hierarchyCount; hierarchyIndex++)

        {

 

            //Get segment count for hierarchy

            segmentCount = dimensionStorage.segmentCountForHierarchy(hierarchyIndex);

 

            //Loop through segments and display required values

            for (segmentIndex = 1; segmentIndex <= segmentCount; segmentIndex++)

            {

                // Get segment

                segment = dimensionStorage.getSegmentForHierarchy(hierarchyIndex, segmentIndex);

 

                // Get the segment information

                if (segment.parmDimensionAttributeValueId() != 0)

                {

                    // Get segment name

                    segmentName = DimensionAttribute::find(DimensionAttributeValue::find(segment.parmDimensionAttributeValueId()).DimensionAttribute).Name;

                    //Get segment value (id of the dimension)

                    segmentValue = segment.parmDisplayValue();

                    segmentDescription = segment.getName();

                    if(segmentName =="BusinessUnit")            //Give the Dimension Name to that Dimension Value

                    {

                        info(strFmt("%1Value -- %2Name",segmentValue,segmentDescription));

                        //return segmentDescription;

                    }

                }

            }

        }

       // return "";

    }


}

Unpack ledger dimension x++ ax2012

 static void dimValues(Args _args)

{

    DimensionAttributeValueCombination  dimAttrValueCombination;

    DimensionStorage                    dimensionStorage;

    DimensionStorageSegment             segment;

    int                                 segmentCount, segmentIndex;

    int                                 hierarchyCount, hierarchyIndex;

    str                                 segmentName, segmentDescription;

    SysDim                              segmentValue;

    DimensionHierarchy                  dimensionHierarchy;

    LedgerDimensionAccount              ledgerDimension;

    ledgerJournalTrans                  ledgerJournalTrans;

    RefRecId                            _recid;


    //select ledgerJournalTrans where ledgerJournalTrans.JournalNum == "00457";//.LedgerDimension !=0;


    ledgerDimension = _recId;//ledgerJournalTrans.OffsetLedgerDimension;

    dimAttrValueCombination = DimensionAttributeValueCombination::find(ledgerDimension);


    dimensionStorage = DimensionStorage::findById(ledgerDimension,true);


    dimensionHierarchy = DimensionStorage::getAccountStructureFromLedgerDimension(ledgerDimension);

    hierarchyCount = dimensionStorage.hierarchyCount();

    for(hierarchyIndex = 1; hierarchyIndex <= hierarchyCount; hierarchyIndex++)

    {

        if( dimensionHierarchy.RecId == DimensionHierarchy::find(dimensionStorage.getHierarchyId(hierarchyIndex)).RecId)

        {

            segmentCount = dimensionStorage.segmentCountForHierarchy(hierarchyIndex);

            for (segmentIndex = 1; segmentIndex <= segmentCount; segmentIndex++)

            {

                segment = dimensionStorage.getSegmentForHierarchy(hierarchyIndex, segmentIndex);

                if (segment.parmDimensionAttributeValueId() != 0)

                {

                    segmentName = DimensionAttribute::find(DimensionAttributeValue::find(segment.parmDimensionAttributeValueId()).DimensionAttribute).Name;

                    segmentValue        = segment.parmDisplayValue();

                    segmentDescription  = segment.getName();

                    

                    if(segmentName == "BusinessUnit")

                    {

                        info(strFmt("%1--%2--%3", segmentName, segmentValue, segmentDescription));

                    }

                }

            }

        }

    }

}

Financial dimension unpack & create x++

 class TEST_DefaultDimensions

{

    public DimensionDefault createDimension(container _conAttr, container _conValue)

    {

        DimensionAttributeValueSetStorage   valueSetStorage = new DimensionAttributeValueSetStorage();

        DimensionDefault                    result;

        int                                 i;

        DimensionAttribute                  dimensionAttribute;

        DimensionAttributeValue             dimensionAttributeValue;

        container                           conAttr     = _conAttr;

        container                           conValue    = _conValue;

        str                                 dimValue;


        for (i = 1; i <= conLen(conAttr); i++)

        {

            dimensionAttribute = dimensionAttribute::findByName(conPeek(conAttr,i));

            if (dimensionAttribute.RecId == 0)

            {

                continue;

            }

            dimValue = conPeek(conValue,i);

            if (dimValue != "")

            {

                dimensionAttributeValue = dimensionAttributeValue::findByDimensionAttributeAndValue(dimensionAttribute,dimValue,false,true);

                valueSetStorage.addItem(dimensionAttributeValue);

            }

        }

        result = valueSetStorage.save();

        return result;

    }


    public DimensionDefault unpackDimension(CustAccount _custAccount)

    {

        DimensionAttributeValueSetStorage           dimStorage;

        str                                         segmentName, segmentValue, segmentDescription;

        boolean                                     isNullforSales;

        int                                         hierarchyCount, hierarchyIndex;

        DefaultDimensionView                        defaultDimensionView;

        RecId                                       defaultDimension;

        int                                         i;

        CustTable                                   custTable = CustTable::find(_custAccount);

        container                                   conAttribute;

        container                                   conValues;

        DimensionDefault                            result;

    

        defaultDimension    = custTable.DefaultDimension;

        dimStorage          = DimensionAttributeValueSetStorage::find(defaultDimension);

        for (i= 1 ; i<= dimStorage.elements() ; i++)

        {

            segmentName         = DimensionAttribute::find(dimStorage.getAttributeByIndex(i)).Name;

            segmentValue        = dimStorage.getDisplayValueByIndex(i);

            isNullforSales      = DimensionAttribute::find(dimStorage.getAttributeByIndex(i)).TEST_IsNULLForSales;

            if(segmentName)

            {

                select defaultDimensionView

                where defaultDimensionView.DefaultDimension == defaultDimension

                && defaultDimensionView.Name == segmentName;

    

                segmentDescription = defaultDimensionView.dimensionDiscription();

            }

    

            conAttribute = conIns(conAttribute,1, segmentName);

            if(isNullforSales == true)

            {

                segmentValue = "";

            }

            conValues    = conIns(conValues,1, segmentValue);

        }

        ttsbegin;

        result = this.createDimension(conAttribute, conValues);

        ttscommit;

        return result;

    }


}

Thursday, 24 March 2022

To get Name, Value, Description of Dimension in D365 F&O

 class TST_DimValues

{

    public static void main(Args _args)

    {       

DimensionAttributeValueCombination dimAttrValueComb;

        GeneralJournalAccountEntry gjAccEntry;

        DimensionStorage dimensionStorage;

        DimensionStorageSegment segment;

        int segmentCount, segmentIndex;

        int hierarchyCount, hierarchyIndex;

        str segmentName, segmentDescription,segmentValue;

        LedgerJournalTrans ledgerJournalTrans;

        

        select ledgerJournalTrans where ledgerJournalTrans.JournalNum == "00457";


        dimAttrValueComb = DimensionAttributeValueCombination::find(ledgerJournalTrans.OffsetLedgerDimension);

        dimensionStorage = DimensionStorage::findById(ledgerJournalTrans.OffsetLedgerDimension);

        if (dimensionStorage == null)

        {

            throw error("@SYS83964");

        }

        hierarchyCount = dimensionStorage.hierarchyCount();

        for(hierarchyIndex = 1; hierarchyIndex <= hierarchyCount; hierarchyIndex++)

        {

            segmentCount = dimensionStorage.segmentCountForHierarchy(hierarchyIndex);

            for (segmentIndex = 1; segmentIndex <= segmentCount; segmentIndex++)

            {

                segment = dimensionStorage.getSegmentForHierarchy(hierarchyIndex, segmentIndex);

                if (segment.parmDimensionAttributeValueId() != 0)

                {

                    segmentName = DimensionAttribute::find(DimensionAttributeValue::find(segment.parmDimensionAttributeValueId()).DimensionAttribute).Name;

                    segmentValue = segment.parmDisplayValue();

                    segmentDescription = segment.getName();

                    if(segmentName =="BusinessUnit")//Give the Dimension Name to that Dimension Value

                    {

                        info(strFmt("%1---%2",segmentValue,segmentDescription));

}

                }

            }

        }

    }


}

Tuesday, 1 February 2022

PO Partial packingslip, Invoice x++ D365

class TEST_POPackingSlip

{


    public static void main(Args _args)

    {

        PurchFormLetter             purchFormLetter, purchFormLetterInvoice;

        PurchFormletterParmData     purchFormLetterParmData;

        PurchParmUpdate             purchParmUpdate;

        PurchParmTable              purchParmTable;

        PurchParmLine               purchParmLine;

        TEST_POPartialLinesTmp      poPartialLinesTmp;

        PurchId                     purchId = 'purchaseOrderNum';

        PurchTable                  purchTable = PurchTable::find(purchId);

        PurchLine                   purchLine;

        Num                         packingSlipId = purchTable.PurchId;

        boolean                     isPackingslip = false;


        ttsBegin;

        if(purchTable.DocumentState != VersioningDocumentState::Confirmed)

        {

            purchFormLetter = PurchFormLetter::construct(DocumentStatus::PurchaseOrder);

            purchFormLetter.update(purchTable, strFmt("%1", purchTable.PurchId));

            Info(strFmt('Purchase order confirmed %1 ', purchTable.PurchId));

        }


        //partial quantity packingslip

        try

        {

            purchFormLetterParmData = PurchFormletterParmData::newData(DocumentStatus::PackingSlip,VersioningUpdateType::Initial);

            purchFormLetterParmData.parmOnlyCreateParmUpdate(true);

            purchFormLetterParmData.createData(false);

            purchParmUpdate = purchFormLetterParmData.parmParmUpdate();


            purchParmTable.clear();

            purchParmTable.TransDate                = SystemDateGet();

            purchParmTable.Ordering                 = DocumentStatus::PackingSlip;

            purchParmTable.ParmJobStatus            = ParmJobStatus::Waiting;

            purchParmTable.Num                      = packingSlipId;

            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();


            while select purchLine where purchLine.PurchId == purchId//purchTable.PurchId

            {

                select poPartialLinesTmp where poPartialLinesTmp.PurchId == purchLine.purchId && poPartialLinesTmp.ItemId == purchLine.ItemId;

                if(poPartialLinesTmp)

                {

                    purchParmLine.InitFromPurchLine(purchLine);


                    purchParmLine.ReceiveNow    = poPartialLinesTmp.Qty;

                    purchParmLine.ParmId        = purchParmTable.ParmId;

                    purchParmLine.TableRefId    = purchParmTable.TableRefId;

                    purchParmLine.setQty(DocumentStatus::PackingSlip, false, true);

                    purchParmLine.setLineAmount();

                    purchParmLine.insert();

                    isPackingslip = true;

                }

                else

                {

                    continue;

                }

                

            }

            if(isPackingslip == true)

            {

                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();

                

                Info(strFmt('Packingslip crated for purchase order %1', purchTable.PurchId));


                //for Invoice

                TEST_PurchInvoice purchInvoice = new TEST_PurchInvoice();

                purchInvoice.poInvoice(purchTable.PurchId);

            }

            ttsCommit;

        }

        catch

        {

            info(infolog.text());

        }


    }


}


---For Invoice


class TEST_PurchInvoice

{

    public static void main(Args _args)

    {

        TEST_PurchInvoice purchInvoice = new TEST_PurchInvoice();

        purchInvoice.poInvoice("purchId");

    }


    public void poInvoice(PurchId _purchId)

    {

        PurchFormLetter             purchFormLetter;

        PurchTable                  purchTable = PurchTable::find(_purchId);

        PurchLine                   purchLine;

        VendPackingSlipJour         vendPackingSlipJour;

        VendPackingSlipTrans        vendPackingSlipTrans;

        VendInvoiceInfoTable        vendInvoiceInfoTable;

        VendInvoiceInfoLine         vendInvoiceInfoLine;

        VendInvoiceInfoSubTable     vendInvoiceInfoSubTable;

        VendInvoiceInfoSubLine      vendInvoiceInfoSubLine;

        InvoiceId                   invoiceId;

        TransDate                   invoiceDate;

        VendInvoiceJour             vendInvoiceJour;

        InventTrans                 inventTransQty;

        str errorLog;

        boolean isInvoiced;

        InvoiceId                   invoiceIdLocal;

        

        select vendPackingSlipJour where vendPackingSlipJour.PurchId == purchTable.PurchId;

        ttsBegin;

        if(vendPackingSlipJour.PackingSlipId)

        {

            invoiceId = strFmt("INV_%1", vendPackingSlipJour.PackingSlipId);

            invoiceDate = DateTimeUtil::getSystemDate(DateTimeUtil::getUserPreferredTimeZone());


            purchTable = vendPackingSlipJour.purchTable();

            vendInvoiceInfoTable.clear();

            vendInvoiceInfoTable.initValue();

            vendInvoiceInfoTable.initFromPurchTable(purchTable);


            vendInvoiceInfoTable.DocumentOrigin         = DocumentOrigin::Manual;

            vendInvoiceInfoTable.CurrencyCode           = purchTable.CurrencyCode;

            vendInvoiceInfoTable.DeliveryName           = purchTable.DeliveryName;

            vendInvoiceInfoTable.Num                    = invoiceId;

            vendInvoiceInfoTable.PurchName              = purchTable.PurchName;

            vendInvoiceInfoTable.VendInvoiceSaveStatus  = VendInvoiceSaveStatus::Pending;

            vendInvoiceInfoTable.TransDate              = invoiceDate;

            vendInvoiceInfoTable.DocumentDate           = invoiceDate;

            vendInvoiceInfoTable.LastMatchVariance      = LastMatchVarianceOptions::OK;

            vendInvoiceInfoTable.ParmJobStatus          = ParmJobStatus::Waiting;

            vendInvoiceInfoTable.DefaultDimension       = vendInvoiceInfoTable.copyDimension(purchTable.DefaultDimension);

            vendInvoiceInfoTable.defaultRow(purchTable);

            vendInvoiceInfoTable.insert();


            if(vendInvoiceInfoTable)

            {

                vendInvoiceInfoSubTable.clear();

                vendInvoiceInfoSubTable.initValue();

                vendInvoiceInfoSubTable.defaultRow();

                vendInvoiceInfoSubTable.ParmId      = vendInvoiceInfoTable.ParmId;

                vendInvoiceInfoSubTable.OrigPurchId = vendInvoiceInfoTable.PurchId;

                vendInvoiceInfoSubTable.PurchName   = vendInvoiceInfoTable.PurchName;

                vendInvoiceInfoSubTable.TableRefId  = vendInvoiceInfoTable.TableRefId;


                vendInvoiceInfoSubTable.insert();

            }


            while select vendPackingSlipTrans

                where vendPackingSlipTrans.PackingSlipId == vendPackingSlipJour.PackingSlipId

                && vendPackingSlipTrans.VendPackingSlipJour == vendPackingSlipJour.RecId

            {

                purchLine = vendPackingSlipTrans.purchLine();

                vendInvoiceInfoLine.clear();

                vendInvoiceInfoLine.initValue();

                vendInvoiceInfoLine.initFromPurchLine(purchLine);


                vendInvoiceInfoLine.DeliveryName    = vendInvoiceInfoTable.DeliveryName;

                vendInvoiceInfoLine.ParmId          = vendInvoiceInfoTable.ParmId;

                vendInvoiceInfoLine.TableRefId      = vendInvoiceInfoTable.TableRefId;

                vendInvoiceInfoLine.currencyCode    = vendInvoiceInfoTable.CurrencyCode;

                vendInvoiceInfoLine.LineNum         = any2int(purchLine.LineNumber);

                vendInvoiceInfoLine.InvoiceAccount  = vendInvoiceInfoTable.InvoiceAccount;

                vendInvoiceInfoLine.InventDimId     = vendPackingSlipTrans.InventDimId;

                vendInvoiceInfoLine.OrderAccount    = vendInvoiceInfoTable.OrderAccount;

                vendInvoiceInfoLine.ItemId          = vendPackingSlipTrans.ItemId;

                vendInvoiceInfoLine.InventTransId   = vendPackingSlipTrans.InventTransId;

                vendInvoiceInfoLine.PurchPrice      = purchLine.PurchPrice;

                vendInvoiceInfoLine.InventNow       = vendInvoiceInfoLine.ReceiveNow;

                vendInvoiceInfoLine.DocumentOrigin  = DocumentOrigin::Manual;

                vendInvoiceInfoLine.ReceiveNow      = vendPackingSlipTrans.Qty;

                vendInvoiceInfoLine.modifiedReceiveNow();

                if(purchLine.PurchQty != 0)

                {

                    vendInvoiceInfoLine.LineAmount = (purchLine.LineAmount / purchLine.PurchQty) * vendInvoiceInfoLine.ReceiveNow;

                }

                vendInvoiceInfoLine.DefaultDimension = purchLine.DefaultDimension;

                vendInvoiceInfoLine.insert();


                if(vendInvoiceInfoLine.RecId)

                {

                    vendInvoiceInfoSubLine.clear();

                    vendInvoiceInfoSubLine.initValue();

                    vendInvoiceInfoSubLine.defaultRow();

                    vendInvoiceInfoSubLine.ParmId               = vendInvoiceInfoTable.ParmId;

                    vendInvoiceInfoSubLine.LineRefRecId         = vendInvoiceInfoLine.RecId;

                    vendInvoiceInfoSubLine.ReceiveNow           = vendInvoiceInfoLine.ReceiveNow;

                    vendInvoiceInfoSubLine.InventNow            = vendInvoiceInfoLine.InventNow ;

                    vendInvoiceInfoSubLine.JournalRefRecId      = vendPackingSlipTrans.RecId;

                    vendInvoiceInfoSubLine.JournalRefTableId    = vendPackingSlipTrans.TableId;

                    vendInvoiceInfoSubLine.DocumentId           = vendPackingSlipTrans.PackingSlipId;

                    vendInvoiceInfoSubLine.insert();

                }

            }

            purchFormLetter = PurchFormLetter_Invoice::newFromSavedInvoice(vendInvoiceInfoTable);

            purchFormLetter.update(vendInvoiceInfoTable.purchTable(),vendInvoiceInfoTable.Num);

        }

        ttsCommit;

        PurchTable  purchTableLocal = PurchTable::find(purchTable.PurchId);

        PurchTable  purchTableUpdate;


        if (purchTableLocal.DocumentStatus == DocumentStatus::Invoice)

        {

            info(strFmt("Purchase order invoiced %1 ",purchTableLocal.PurchId));

            isInvoiced = true;

        }

        if(isInvoiced == true)

        {

            while select vendInvoiceJour where vendInvoiceJour.PurchId == purchTable.PurchId

            {

                invoiceIdLocal += vendInvoiceJour.InvoiceId+', ';

            }

            select forupdate purchTableUpdate where purchTableUpdate.PurchId == purchTableLocal.PurchId;

            if(purchTableUpdate)

            {

                ttsbegin;

                purchTableUpdate.Invoiced = invoiceIdLocal;

                purchTableUpdate.doUpdate();

                ttscommit;

            }

        }

    }


}

Tuesday, 28 December 2021

Cust Tax registration number x++ D365

 public str getCRNum(CustAccount   _custAccount)

    {

        CustTable           custTable   =   CustTable::find(_custAccount);

        DirPartyTable       dirPartyTable;

        DirPartyLocation    dirPartyLocation;

        TaxRegistration     taxRegistration;

        TaxRegistrationType taxRegistrationType;

        TaxRegistrationTypeApplicabilityRule    taxRegistrationTypeApplicabilityRule;


        select taxRegistration

            join taxRegistrationTypeApplicabilityRule

            join taxRegistrationType

            join dirPartyLocation

            join dirPartyTable

            join custTable

            where taxRegistration.DirPartyLocation  ==  dirPartyLocation.RecId

            && taxRegistration.TaxRegistrationTypeApplicabilityRule ==  taxRegistrationTypeApplicabilityRule.RecId

            && taxRegistrationTypeApplicabilityRule.TaxRegistrationType ==  taxRegistrationType.RecId

            && taxRegistrationType.TaxRegstrationType == "CR"

            && dirPartyLocation.Party   ==  dirPartyTable.RecId

            && dirPartyTable.RecId  ==  custTable.Party;

        

        return taxRegistration.RegistrationNumber;

    }

QR Text output x++

qrString        = strFmt("Supplier name: %1", CompanyInfo::findDataArea(_custInvoiceJour.DataAreaId).Name);

                qrString        += strFmt("\nSupplier VAT: %1", CompanyInfo::findDataArea(_custInvoiceJour.DataAreaId).CoRegNum);

                qrString        += strFmt("\nInvoice number: %1", _custInvoiceJour.InvoiceId);

                qrString        += strFmt("\nInvoice Date: %1", _custInvoiceJour.InvoiceDate);

                qrString        += strFmt("\nTotal amount with VAT: %1", _custInvoiceJour.InvoiceAmount);

                qrString        += strFmt("\nVAT amount: %1", _custInvoiceJour.SumTax);


public Bitmap getQR(String255 _qrString)

    {

        str                                 QrCodeBase64String;

        Microsoft.Dynamics.ApplicationSuite.QRCode.Encoder   qrCode;

        System.String                       netString;

        str                                 tempFileName;

        System.Drawing.Bitmap               netBitmap;

        Bitmap                              imageQR;

        FileIOPermission                    perm;

        BinData                             binData;

        container                           imageContainer;

        Str1260                             qrString;

        real                                taxWithoutVat;

        QRCodeGenerator qrGenerator = new QRCodeGenerator();


        qrCode          = new Microsoft.Dynamics.ApplicationSuite.QRCode.Encoder();

        

        netBitmap       = qrCode.Encode(_qrString);

        binData         = new binData();

        QrCodeBase64String  = _qrString;

        tempFileName        = qrCode.GetTempFile(QrCodeBase64String);

        perm  = new FileIOPermission(tempFileName,'RW');

        perm.assert();

        binData.loadFile(tempFileName);

        imageContainer          = binData.getData();


        return imageContainer;

    }


Use bitmap to display QR (Image/bmp) 

QR base64 D365 x++

 public Bitmap hexaDecimalQRCode(Name            _companyName,

                                    VATNum          _vatNum,

                                    CustInvoiceId   _invoiceId,

                                    CreatedDateTime _transdate,

                                    AmountCurNet    _netAmt,

                                    Amount          _vatAmt)

    {

        str             hexaDecimalSellerTag,hexaDecimalVATNumberTag,hexaDecimalTimeStampTag,hexaDecimalInvoiceTotalTag,hexaDecimalVATTotalTag;

        int             hexaDecimalSellerLength,hexaDecimalVATNumberLength,hexaDecimalTimeStampLength,hexaDecimalInvoiceTotalLength,hexaDecimalVATTotalLength;

        str             hexaDecimalSellerValue,hexaDecimalVATNumberValue,hexaDecimalTimeStampValue,hexaDecimalInvoiceTotalValue,hexaDecimalVATTotalValue;

        str             hexaDecimalSeller,hexaDecimalVATNumber,hexaDecimalTimeStamp,hexaDecimalInvoiceTotal,hexaDecimalVATTotal;

        Str             Seller,VATNumber,TimeStamp,InvoiceTotal,VATTotal,hexaDecimal,tempValue,base64Text;

        System.Byte[]   byte;

        bindata         bindata;

        container       con;

        int             i;

        container       qrCode,conStore;

        Microsoft.Dynamics.ApplicationSuite.QRCode.Encoder  qrCode1 = new Microsoft.Dynamics.ApplicationSuite.QRCode.Encoder();

        System.Drawing.Bitmap bitmap;

        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();



        container      imageContainer;

        hexaDecimalSellerTag        = "01";

        hexaDecimalVATNumberTag     = "02";

        hexaDecimalTimeStampTag     = "03";

        hexaDecimalInvoiceTotalTag  = "04";

        hexaDecimalVATTotalTag      = "05";


        Seller          = _companyName;

        VATNumber       = strFmt("%1",_vatNum);

        TimeStamp       = "2021-12-22 09:26:31";//DateTimeUtil::toStr(_transdate);//"2021-11-01 11:30:28";//"3/26/2018 01:28:18";//strFmt("%1",_transdate);//"2021-11-01 21:30:00";

        InvoiceTotal    = strFmt("%1",_netAmt);

        VATTotal        = strFmt("%1",_vatAmt);


        hexaDecimalSellerLength         = strLen(Seller);

        hexaDecimalVATNumberLength      = strLen(VATNumber);

        hexaDecimalTimeStampLength      = strLen(TimeStamp);

        hexaDecimalInvoiceTotalLength   = strLen(InvoiceTotal);

        hexaDecimalVATTotalLength       = strLen(VATTotal);


        hexaDecimalSellerValue          = int2Hex(hexaDecimalSellerLength);

        hexaDecimalVATNumberValue       = int2Hex(hexaDecimalVATNumberLength);

        hexaDecimalTimeStampValue       = int2Hex(hexaDecimalTimeStampLength);

        hexaDecimalInvoiceTotalValue    = int2Hex(hexaDecimalInvoiceTotalLength);

        hexaDecimalVATTotalValue        = int2Hex(hexaDecimalVATTotalLength);



        if(strLen(hexaDecimalSellerValue) == 1)

        {

            hexaDecimalSellerValue          = "0" + hexaDecimalSellerValue;

        }

        if(strLen(hexaDecimalVATNumberValue) == 1)

        {

            hexaDecimalVATNumberValue       = "0" + hexaDecimalVATNumberValue;

        }

        if(strLen(hexaDecimalTimeStampValue) == 1)

        {

            hexaDecimalTimeStampValue       = "0" + hexaDecimalTimeStampValue;

        }

        if(strLen(hexaDecimalInvoiceTotalValue) == 1)

        {

            hexaDecimalInvoiceTotalValue    = "0" + hexaDecimalInvoiceTotalValue;

        }

        if(strLen(hexaDecimalVATTotalValue) == 1)

        {

            hexaDecimalVATTotalValue    = "0" + hexaDecimalVATTotalValue;

        }


        for (i=1;i<=hexaDecimalSellerLength ;i++)

        {

            hexaDecimalSeller    += int2Hex(char2num(Seller,i));

        }

        for (i=1;i<=hexaDecimalVATNumberLength ;i++)

        {

            hexaDecimalVATNumber    += int2Hex(char2num(VATNumber,i));

        }

        for (i=1;i<=hexaDecimalTimeStampLength ;i++)

        {

            hexaDecimalTimeStamp    += int2Hex(char2num(TimeStamp,i));

        }

        for (i=1;i<=hexaDecimalInvoiceTotalLength ;i++)

        {

            hexaDecimalInvoiceTotal    += int2Hex(char2num(InvoiceTotal,i));

        }

        for (i=1;i<=hexaDecimalVATTotalLength ;i++)

        {

            hexaDecimalVATTotal    += int2Hex(char2num(VATTotal,i));

        }


        hexaDecimal = hexaDecimalSellerTag + hexaDecimalSellerValue +hexaDecimalSeller + hexaDecimalVATNumberTag + hexaDecimalVATNumberValue +  hexaDecimalVATNumber + hexaDecimalTimeStampTag

            + hexaDecimalTimeStampValue + hexaDecimalTimeStamp + hexaDecimalInvoiceTotalTag + hexaDecimalInvoiceTotalValue + hexaDecimalInvoiceTotal + hexaDecimalVATTotalTag + hexaDecimalVATTotalValue + hexaDecimalVATTotal;



        //hexaDecimal =   "011153656465722048656164204f6666696365020f3330303034393035353231303030330313323032312d31322d32322030393a32363a3331040331313105063734342e3135";


        con         = BinData::stringToData(hexadecimal);

        bindata     = new bindata();

        bindata.setData(con);

        base64Text = bindata.base64Encode();

        //base64Text  =   "ARFTZWRlciBIZWFkIE9mZmljZQIPMzAwMDQ5MDU1MjEwMDAzAxMyMDIxLTEyLTIyIDA5OjI2OjMxBAMxMTEFBjc0NC4xNQ==";


        bitmap=qrCode1.Encode(base64Text);


        bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat::get_Jpeg());//get_Jpeg

        imageContainer=Binary::constructFromMemoryStream(memoryStream).getContainer();


        


        qrCode = imageContainer;

        return qrCode;

    }


    public bitmap qrBitMap(str _qrString)

    {

        Microsoft.Dynamics.ApplicationSuite.QRCode.Encoder  qrCode1 = new Microsoft.Dynamics.ApplicationSuite.QRCode.Encoder();

        System.Drawing.Bitmap bitmap;

        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();

        container           imageContainer;

        container           qrCode,conStore;


        bitmap=qrCode1.Encode(_qrString);


        bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat::get_Jpeg());//get_Jpeg

        imageContainer=Binary::constructFromMemoryStream(memoryStream).getContainer();


        


        qrCode = imageContainer;

        return qrCode;

    }


Use bitmap to display QR (Image/bmp)

Tuesday, 7 December 2021

Pending/Delegated WF user x++

 public static void main(Args _args)

{

    LetterRequestTable        letterRequestTable   =    LetterRequestTable::find("ABC-000003");

    WorkflowWorkItemTable       workflowWorkItemTable;


    select workflowWorkItemTable

        where workflowWorkItemTable.RefRecId == letterRequestTable.RecId

        && workflowWorkItemTable.RefTableId == letterRequestTable.TableId

        && ((workflowWorkItemTable.Status == WorkflowWorkItemStatus::Pending) || (workflowWorkItemTable.Status == WorkflowWorkItemStatus::Delegated));


    Info(strFmt("%1", HcmWorker::find(HcmWorker::userId2Worker(workflowWorkItemTable.UserId)).name()));

}

Tuesday, 23 March 2021

Condition based company address, TRN x++

static void primaryAddresssTRN(Args _args)

{

    CompanyInfo                             companyInfo;

    LogisticsPostalAddress                  postalAddress;

    DirPartyLocation                        partyLocation;

    LogisticsLocationRole                   locationRole;

    DirPartyLocationRole                    partyLocationRole;

    TaxRegistration                         taxRegistration;

    TaxRegistrationType                     taxRegistrationType;

    TaxRegistrationTypeApplicabilityRule    taxRegRule;

    

    select companyInfo

    join partyLocation

    join postalAddress

    join partyLocationRole  

    join locationRole      

    where companyInfo.DataArea == curext()

    && partyLocation.Party == companyInfo.RecId 

    && postalAddress.Location == partyLocation.Location

    && partyLocationRole.PartyLocation == partyLocation.RecId       

    && partyLocationRole.LocationRole == locationRole.RecId       

    && locationRole.Type == LogisticsLocationRoleType::Business

    && partyLocation.IsPrimary == true;

    

    if(partyLocation)

    {

        select taxRegistration

        join taxRegRule 

        join taxRegistrationType

        where taxRegistration.DirPartyLocation == partyLocation.RecId

        && taxRegistration.TaxRegistrationTypeApplicabilityRule == taxRegRule.RecId

        && taxRegRule.CountryRegionId == LogisticsAddressCountryRegion::findByISOCode(SysCountryRegionCode::countryInfo(curext())).CountryRegionId

        && taxRegRule.TaxRegistrationType == taxRegistrationType.RecId

        && taxRegistrationType.TaxRegstrationType == 'TRN';

    }

    

    info(strFmt("%1---%2---%3---%4",locationRole.Type, partyLocation.IsPrimary, postalAddress.Address, taxRegistration.RegistrationNumber));      

}

Wednesday, 4 November 2020

query::insert_recordset x++

[SRSReportParameterAttribute(classstr(ALM_QtySaleAnalysisContract))]

class ALM_QtySaleAnalysisDp extends SRSReportDataProviderPreprocess

{

    ALM_QtySaleAnalysisContract         contract;

    ALM_QtySaleAnalysisTmp              qtySaleAnalysisTmp;

    ALM_QtySaleAnalysisStaging          qtySaleAnalysisStaging;

    TransDate                           fromDate, toDate;

    Str1260                             retailStoreIdMulti;

    Str1260                             itemGroupIdMulti;

    Str1260                             itemIdMulti;


    

    [SRSReportDataSetAttribute("ALM_QtySaleAnalysisTmp")]

    public ALM_QtySaleAnalysisTmp getALM_QtySaleAnalysisTmp()

    {

        qtySaleAnalysisTmp.setConnection(this.parmUserConnection());

        select qtySaleAnalysisTmp;

        return qtySaleAnalysisTmp;

    }


    public void processReport()

    {

        contract            =   this.parmDataContract();

        fromDate            =   contract.parmFromDate();

        toDate              =   contract.parmToDate();

        retailStoreIdMulti  =   contract.parmRetailStoreIdMulti();

        itemGroupIdMulti    =   contract.parmItemGroupIdMulti();

        itemIdMulti         =   contract.parmItemIdMulti();


        if(itemGroupIdMulti)

        {

            this.inserDataWithParm();

        }

        else

        {

            this.inserDataWithoutParm();

        }

    }


    public void insertIntoStaging()

    {

        RetailTransactionSalesTrans     retailTransactionSalesTrans;

        InventItemGroupItem             inventItemGroupItem;

        InventItemGroup                 inventItemGroup;

        InventTable                     inventTable;

        RetailStoreTable                retailStoreTable;

        RetailChannelTable              retailChannelTable;

        OMOperatingUnit                 omOperatingUnit;

        DirPartyTable                   dirPartyTable;


        ttsbegin;

        delete_from qtySaleAnalysisStaging;

        ttscommit;


        ttsBegin;

        insert_recordset qtySaleAnalysisStaging

        (

            ItemId,

            StoreCode,

            Qty,

            TransDate,

            CostAmount,

            NetAmount,

            SalesUnit,

            ItemGroupId,

            ItemGroupName,

            StoreName

        )

        select ItemId,Store,Qty,TransDate,CostAmount,NetAmount,Unit from retailTransactionSalesTrans

            where retailTransactionSalesTrans.TransDate >= fromdate && retailTransactionSalesTrans.TransDate <= toDate

            join inventTable where inventTable.ItemId == retailTransactionSalesTrans.itemId

            join ItemGroupId from inventItemGroupItem where inventItemGroupItem.ItemDataAreaId == inventTable.dataAreaId

            && inventItemGroupItem.ItemId == inventTable.ItemId

            join Name from inventItemGroup where inventItemGroup.DataAreaId == inventItemGroupItem.ItemGroupDataAreaId

            && inventItemGroup.ItemGroupId == inventItemGroupItem.ItemGroupId

            && retailTransactionSalesTrans.costAmount != 0

            join retailStoreTable where retailStoreTable.StoreNumber == retailTransactionSalesTrans.store

            join retailChannelTable where retailChannelTable.RecId == retailStoreTable.RecId

            join Name from omOperatingUnit where omOperatingUnit.RecId == retailChannelTable.OMOperatingUnitID;

        ttsCommit;


        while select forupdate qtySaleAnalysisStaging

        {

            ttsbegin;

            qtySaleAnalysisStaging.ConvertedQty = this.qtyToConvert(qtySaleAnalysisStaging.ItemId, qtySaleAnalysisStaging.Qty, qtySaleAnalysisStaging.SalesUnit);

            qtySaleAnalysisStaging.BaseUnit = this.baseUnit(qtySaleAnalysisStaging.ItemId);

            qtySaleAnalysisStaging.update();

            ttscommit;

        }


        /*ttsBegin;

        update_recordSet qtySaleAnalysisStaging

        setting StoreName = omOperatingUnit.Name

        join retailStoreTable where retailStoreTable.StoreNumber == qtySaleAnalysisStaging.StoreCode

        join retailChannelTable where retailChannelTable.RecId == retailStoreTable.RecId

        join omOperatingUnit where omOperatingUnit.RecId == retailChannelTable.OMOperatingUnitID;

        ttsCommit;*/

    }


    public void inserDataWithoutParm()

    {

        Query                           qr = new Query();

        QueryRun                        qRun;

        QueryBuildDataSource            qbds;

        Map                             fieldMapping;

        QueryBuildFieldList             fldList_RetailTransactionSalesTrans;

        RetailTransactionSalesTrans     retailTransactionSalesTrans;

        InventItemGroupItem             inventItemGroupItem;

        InventItemGroup                 inventItemGroup;

        InventTable                     inventTable;

        RetailStoreTable                retailStoreTable;

        RetailChannelTable              retailChannelTable;

        OMOperatingUnit                 omOperatingUnit;

        DirPartyTable                   dirPartyTable;


        ttsbegin;

        delete_from qtySaleAnalysisTmp;

        ttscommit;


        qbds = qr.addDataSource(tableNum(RetailTransactionSalesTrans));

        if(fromDate && toDate)

        {

            qbds.addRange(fieldNum(RetailTransactionSalesTrans,TransDate)).value(queryRange(fromDate, toDate));

        }

        if(retailStoreIdMulti)

        {

            qbds.addRange(fieldNum(RetailTransactionSalesTrans,Store)).value(retailStoreIdMulti);

        }

        if(itemIdMulti)

        {

            qbds.addRange(fieldNum(RetailTransactionSalesTrans,itemId)).value(itemIdMulti);

        }

        qbds.addRange(fieldNum(RetailTransactionSalesTrans,CostAmount)).value(SysQuery::valueNot(0));


        qbds.fields().clearFieldList();

        fldList_RetailTransactionSalesTrans = qbds.fields();

        fldList_RetailTransactionSalesTrans.addField(fieldNum(RetailTransactionSalesTrans, ItemId));

        fldList_RetailTransactionSalesTrans.addField(fieldNum(RetailTransactionSalesTrans, Store));

        fldList_RetailTransactionSalesTrans.addField(fieldNum(RetailTransactionSalesTrans, Qty));

        fldList_RetailTransactionSalesTrans.addField(fieldNum(RetailTransactionSalesTrans, TransDate));

        fldList_RetailTransactionSalesTrans.addField(fieldNum(RetailTransactionSalesTrans, CostAmount));

        fldList_RetailTransactionSalesTrans.addField(fieldNum(RetailTransactionSalesTrans, NetAmount));

        fldList_RetailTransactionSalesTrans.addField(fieldNum(RetailTransactionSalesTrans, Unit));

        fldList_RetailTransactionSalesTrans.dynamic(QueryFieldListDynamic::No);


        fieldMapping = new Map(Types::AnyType, Types::Container);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, ItemId), [qbds.uniqueId(), fieldStr(RetailTransactionSalesTrans, ItemId)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, StoreCode), [qbds.uniqueId(), fieldStr(RetailTransactionSalesTrans, Store)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, Qty), [qbds.uniqueId(), fieldStr(RetailTransactionSalesTrans, Qty)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, TransDate), [qbds.uniqueId(), fieldStr(RetailTransactionSalesTrans, TransDate)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, CostAmount), [qbds.uniqueId(), fieldStr(RetailTransactionSalesTrans, CostAmount)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, NetAmount), [qbds.uniqueId(), fieldStr(RetailTransactionSalesTrans, NetAmount)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, SalesUnit), [qbds.uniqueId(), fieldStr(RetailTransactionSalesTrans, Unit)]);


        query::insert_recordset(qtySaleAnalysisTmp, fieldMapping, qr);


        /*ttsBegin;

        update_recordSet qtySaleAnalysisTmp

            setting ConvertedQty = this.qtyToConvert(qtySaleAnalysisTmp.ItemId, qtySaleAnalysisTmp.Qty, qtySaleAnalysisTmp.SalesUnit)

            where qtySaleAnalysisTmp.ItemId;

        ttsCommit;*/


        while select forupdate qtySaleAnalysisTmp

        {

            ttsbegin;

            qtySaleAnalysisTmp.ConvertedQty = this.qtyToConvert(qtySaleAnalysisTmp.ItemId, qtySaleAnalysisTmp.Qty, qtySaleAnalysisTmp.SalesUnit);

            qtySaleAnalysisTmp.BaseUnit = this.baseUnit(qtySaleAnalysisTmp.ItemId);

            qtySaleAnalysisTmp.update();

            ttscommit;

        }


        ttsBegin;

        update_recordSet qtySaleAnalysisTmp

            setting StoreName = DirPartyTable.Name

            join retailStoreTable  where retailStoreTable.StoreNumber == qtySaleAnalysisTmp.StoreCode

            join retailChannelTable where retailChannelTable.RecId == retailStoreTable.RecId

            join dirPartyTable where retailChannelTable.OMOperatingUnitID == dirPartyTable.RecId;

        ttsCommit;


        ttsBegin;

        update_recordSet qtySaleAnalysisTmp

            setting ItemGroupId = inventItemGroupItem.ItemGroupId,

                    ItemGroupName = inventItemGroupItem.ItemGroupId+" - "+inventItemGroup.Name

            join inventTable where inventTable.ItemId == qtySaleAnalysisTmp.itemId

            join ItemGroupId from inventItemGroupItem where inventItemGroupItem.ItemDataAreaId == inventTable.dataAreaId

            && inventItemGroupItem.ItemId == inventTable.ItemId

            join Name from inventItemGroup where inventItemGroup.DataAreaId == inventItemGroupItem.ItemGroupDataAreaId

            && inventItemGroup.ItemGroupId == inventItemGroupItem.ItemGroupId;

        ttsCommit;


        select firstonly forupdate qtySaleAnalysisTmp;

        qtySaleAnalysisTmp.CompanyLogo = FormLetter::companyLogo();

        ttsBegin;

        qtySaleAnalysisTmp.update();

        ttsCommit;

    }


    public void inserDataWithParm()

    {

        Query                   qr = new Query();

        QueryRun                qRun;

        QueryBuildDataSource    qbds;

        Map                     fieldMapping;

        QueryBuildFieldList     fldList_ALM_QtySaleAnalysisStaging;

        InventItemGroupItem     inventItemGroupItem;

        InventItemGroup         inventItemGroup;

        InventTable             inventTable;

        RetailStoreTable        retailStoreTable;

        RetailChannelTable      retailChannelTable;

        OMOperatingUnit         omOperatingUnit;

        DirPartyTable           dirPartyTable;

    

        ttsbegin;

        delete_from qtySaleAnalysisTmp;

        ttscommit;

    

        this.insertIntoStaging();

        qbds = qr.addDataSource(tableNum(ALM_QtySaleAnalysisStaging));

        if(retailStoreIdMulti)

        {

            qbds.addRange(fieldNum(ALM_QtySaleAnalysisStaging,StoreCode)).value(retailStoreIdMulti);

        }

        if(itemIdMulti)

        {

            qbds.addRange(fieldNum(ALM_QtySaleAnalysisStaging,itemId)).value(itemIdMulti);

        }

        if(itemGroupIdMulti)

        {

            qbds.addRange(fieldNum(ALM_QtySaleAnalysisStaging,ItemGroupId)).value(itemGroupIdMulti);

        }


        qbds.fields().clearFieldList();

        fldList_ALM_QtySaleAnalysisStaging = qbds.fields();

        fldList_ALM_QtySaleAnalysisStaging.addField(fieldNum(ALM_QtySaleAnalysisStaging, ItemId));

        fldList_ALM_QtySaleAnalysisStaging.addField(fieldNum(ALM_QtySaleAnalysisStaging, ItemGroupId));

        fldList_ALM_QtySaleAnalysisStaging.addField(fieldNum(ALM_QtySaleAnalysisStaging, ItemGroupName));

        fldList_ALM_QtySaleAnalysisStaging.addField(fieldNum(ALM_QtySaleAnalysisStaging, StoreCode));

        fldList_ALM_QtySaleAnalysisStaging.addField(fieldNum(ALM_QtySaleAnalysisStaging, StoreName));

        fldList_ALM_QtySaleAnalysisStaging.addField(fieldNum(ALM_QtySaleAnalysisStaging, Qty));

        fldList_ALM_QtySaleAnalysisStaging.addField(fieldNum(ALM_QtySaleAnalysisStaging, TransDate));

        fldList_ALM_QtySaleAnalysisStaging.addField(fieldNum(ALM_QtySaleAnalysisStaging, CostAmount));

        fldList_ALM_QtySaleAnalysisStaging.addField(fieldNum(ALM_QtySaleAnalysisStaging, NetAmount));

        fldList_ALM_QtySaleAnalysisStaging.addField(fieldNum(ALM_QtySaleAnalysisStaging, SalesUnit));

        fldList_ALM_QtySaleAnalysisStaging.addField(fieldNum(ALM_QtySaleAnalysisStaging, ConvertedQty));

        fldList_ALM_QtySaleAnalysisStaging.addField(fieldNum(ALM_QtySaleAnalysisStaging, BaseUnit));

        fldList_ALM_QtySaleAnalysisStaging.dynamic(QueryFieldListDynamic::No);

    

        fieldMapping = new Map(Types::AnyType, Types::Container);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, ItemId), [qbds.uniqueId(), fieldStr(ALM_QtySaleAnalysisStaging, ItemId)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, ItemGroupId), [qbds.uniqueId(), fieldStr(ALM_QtySaleAnalysisStaging, ItemGroupId)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, ItemGroupName), [qbds.uniqueId(), fieldStr(ALM_QtySaleAnalysisStaging, ItemGroupName)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, StoreCode), [qbds.uniqueId(), fieldStr(ALM_QtySaleAnalysisStaging, StoreCode)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, StoreName), [qbds.uniqueId(), fieldStr(ALM_QtySaleAnalysisStaging, StoreName)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, Qty), [qbds.uniqueId(), fieldStr(ALM_QtySaleAnalysisStaging, Qty)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, TransDate), [qbds.uniqueId(), fieldStr(ALM_QtySaleAnalysisStaging, TransDate)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, CostAmount), [qbds.uniqueId(), fieldStr(ALM_QtySaleAnalysisStaging, CostAmount)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, NetAmount), [qbds.uniqueId(), fieldStr(ALM_QtySaleAnalysisStaging, NetAmount)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, SalesUnit), [qbds.uniqueId(), fieldStr(ALM_QtySaleAnalysisStaging, SalesUnit)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, ConvertedQty), [qbds.uniqueId(), fieldStr(ALM_QtySaleAnalysisStaging, ConvertedQty)]);

        fieldMapping.insert(fieldStr(ALM_QtySaleAnalysisTmp, BaseUnit), [qbds.uniqueId(), fieldStr(ALM_QtySaleAnalysisStaging, BaseUnit)]);

    

        query::insert_recordset(qtySaleAnalysisTmp, fieldMapping, qr);


        ttsBegin;

        update_recordSet qtySaleAnalysisTmp

            setting ItemGroupName = inventItemGroupItem.ItemGroupId+" - "+inventItemGroup.Name

            join inventTable where inventTable.ItemId == qtySaleAnalysisTmp.itemId

            join ItemGroupId from inventItemGroupItem where inventItemGroupItem.ItemDataAreaId == inventTable.dataAreaId

            && inventItemGroupItem.ItemId == inventTable.ItemId

            join Name from inventItemGroup where inventItemGroup.DataAreaId == inventItemGroupItem.ItemGroupDataAreaId

            && inventItemGroup.ItemGroupId == inventItemGroupItem.ItemGroupId;

        ttsCommit;

    

        ttsBegin;

        select firstonly forupdate qtySaleAnalysisTmp;

        qtySaleAnalysisTmp.CompanyLogo = FormLetter::companyLogo();

        qtySaleAnalysisTmp.update();

        ttsCommit;

    }


    public Qty qtyToConvert(ItemId _itemId, Qty _qty, UnitIDBase _fromUnit)

    {

        Qty                 qty;

        InventTable         inventTable;

        InventTableModule   inventTableModule;


        select firstonly inventTableModule

        where inventTableModule.ModuleType == ModuleInventPurchSales::Invent

        && inventTableModule.ItemId == _itemId;


        if(inventTableModule.UnitId)

        {

            qty =   UnitOfMeasureConverter::convert(_qty,

                    UnitOfMeasure::unitOfMeasureIdBySymbol(_fromUnit),

                    UnitOfMeasure::unitOfMeasureIdBySymbol(inventTableModule.UnitId),

                    NoYes::No,

                    InventTable::itemProduct(_itemId),

                    NoYes::No);

        }

        else

        {

            qty = _qty;

        }

        return qty;

    }


    public UnitIDBase baseUnit(ItemId _itemId)

    {

        UnitIDBase          baseUnit;

        InventTable         inventTable;

        InventTableModule   inventTableModule;


        select firstonly inventTableModule

        where inventTableModule.ModuleType == ModuleInventPurchSales::Invent

        && inventTableModule.ItemId == _itemId;

                        

        return inventTableModule.UnitId;

    }


}