Tuesday 25 December 2018

Updating Item Batch number


static void UploadItemBatchNumber(Args _args)
{
    OGSDataImport OGSDataImport;
    INVENTITEMGROUPITEM INVENTITEMGROUPITEM; //Destination table
    InventTable  InventTable ;
    OGSITEMTYPETABLE OGSITEMTYPETABLE;
    //OGSBrandTable OGSBrandTable;
    OGSOEMTable OGSOEMTable;
    OGSSetCodeTable OGSSetCodeTable;
    OGSModelNumberTable OGSModelNumberTable;
    InventBatch InventBatch;
    int ItemExists;
    String20 BatchNumber;
    //BatchNumber ='OPN20150901';
    changeCompany('spdc')

    while select OGSDataImport
    {
        try
        {
            OGSModelNumberTable.ModelNumber = OGSDataImport.Code;
            OGSModelNumberTable.Description =OGSDataImport.Code;

            if (OGSModelNumberTable.validateWrite())
                {
                    OGSModelNumberTable.insert();
               }

        }
        catch (Exception::Error)
        {
            throw error("Error while uploading");
            continue;
        }
    }
}

Combine LedgerAccount and Default Dimension

static void USR_CombineLedgerDimAndDefaultDim(Args _args)

{

   Map         defaultDimensionSpecifiers;

   RecId       ledgerDimensionId =  5637242076;

   RecId       defaultDimensionId = 5637144576 ;

   RecId       newId;

   MapEnumerator enumerator;

   str dimStr;

   defaultDimensionSpecifiers = DimensionDefaultingEngine::getDefaultDimensionSpecifiers(defaultDimensionId);

   newId =

       DimensionDefaultingEngine::overrideLedgerDimension(ledgerDimensionId,

                                                          defaultDimensionSpecifiers);

   Enumerator = defaultDimensionSpecifiers.getEnumerator();

   while (enumerator.moveNext())

   {

       dimStr += conPeek(Enumerator.currentValue(),1);

       dimStr += ", ";

   }

   dimStr = subStr(dimStr,1,strLen(dimStr)-2);

   info(strFmt("Ledger: %1; Default: %2; New: %3",

               DimensionAttributeValueCombination::getDisplayValue(ledgerDimensionId),

               dimStr,

               DimensionAttributeValueCombination::getDisplayValue(newId)));

}

Vendor State Job

static void VendorState(Args _args)
{
    VendTable vendTable;
    DirPartyTable dirPartyTable;
    DirPartyLocation dirPartyLocation;
    LogisticsLocation logisticsLocation;
    LogisticsPostalAddress logisticsPostalAddress;
    LogisticsAddressState LogisticsAddressState;

    while select vendTable
        where vendTable.AccountNum == '5011' // Vendor
    join dirPartyTable
        where vendTable.Party == dirPartyTable.RecId
    join dirPartyLocation
        where dirPartyLocation.Party == dirPartyTable.RecId
            && dirPartyLocation.IsPostalAddress == true
    //&& dirPartyLocation.IsPrimary == true // To get primary address
    join logisticsLocation
         where logisticsLocation.RecId == dirPartyLocation.Location
            && logisticsLocation.Description == "AddressDescription" // Address description
    join logisticsPostalAddress
         where logisticsPostalAddress.Location == dirPartyLocation.Location
        {
        // Older state
            info(strFmt("State: %1", logisticsPostalAddress.State));

            // Newer state - Check on the new state
            if (LogisticsAddressState::exist(logisticsPostalAddress.CountryRegionId, "NewState"))
            {
                ttsBegin;
                logisticsPostalAddress.selectForUpdate(true);
                logisticsPostalAddress.ValidTimeStateUpdateMode (ValidTimeStateUpdate::Correction);
                logisticsPostalAddress.State = "NewState";
                logisticsPostalAddress.update();
                ttsCommit;
            }
        }

}

Voucher Credit and Debit Amount

static void VoucherBalanceCompanyWise(Args _args)
{
  VendInvoiceJour                        vendInvoiceJour;
  GeneralJournalAccountEntry    generalJournalAccountEntry;
  GeneralJournalEntry                   generalJournalEntry;
  CompanyInfo                           companyInfo;


             while select sum(AccountingCurrencyAmount) from  generalJournalAccountEntry
                    where generalJournalAccountEntry.LedgerAccount == '1211102-CENT' // debit group
                join generalJournalEntry
                    where generalJournalEntry.RecId == generalJournalAccountEntry.GeneralJournalEntry
                        && generalJournalEntry.SubledgerVoucherDataAreaId == 'CENT'
                        && generalJournalEntry.AccountingDate >= mkDate(1,4,2017)
                        && generalJournalEntry.AccountingDate <= mkDate(1,4,2017)
            {
             info(strFmt("data area ---%1 - Debit ---%2",generalJournalEntry.dataAreaId,generalJournalAccountEntry.AccountingCurrencyAmount));

            }



            while select sum(AccountingCurrencyAmount) from  generalJournalAccountEntry
                    where generalJournalAccountEntry.LedgerAccount == '2411102-CENT' // credit group
                join generalJournalEntry
                    where generalJournalEntry.RecId == generalJournalAccountEntry.GeneralJournalEntry
                        && generalJournalEntry.SubledgerVoucherDataAreaId == 'CENT'
                        && generalJournalEntry.AccountingDate >= mkDate(1,4,2017)
                        && generalJournalEntry.AccountingDate <= mkDate(1,4,2017)
            {
                info(strFmt("data area ---%1 - Credit ---%2",generalJournalEntry.dataAreaId,generalJournalAccountEntry.AccountingCurrencyAmount));

            }

}

Voucher Invoice Amount from Intercompany using Container

static void VoucherInvociedStatusIntercompany(Args _args)
{
  VendInvoiceJour               vendInvoiceJour;
  GeneralJournalAccountEntry    generalJournalAccountEntry;
  GeneralJournalEntry           generalJournalEntry;
  CompanyInfo                   companyInfo;
  container companyAccountcontainer = ['AGAP','AISI', 'ALMA','ASAB', 'ASAP', 'CENT', 'IMPB', 'IMPE', 'INDP', 'SPDC'];

   while select crossCompany : companyAccountcontainer sum(AccountingCurrencyAmount) from  generalJournalAccountEntry order by DataAreaId
         where generalJournalAccountEntry.LedgerAccount like'*2411102*'  // credit group
       join generalJournalEntry
         where  generalJournalEntry.RecId == generalJournalAccountEntry.GeneralJournalEntry
             && generalJournalEntry.SubledgerVoucherDataAreaId == companyInfo.dataArea
             && generalJournalEntry.AccountingDate >= mkDate(1,4,2017)
             && generalJournalEntry.AccountingDate <= mkDate(1,4,2017)
           {
              info(strFmt("data area ---%1 - Credit ---%2",companyInfo.DataArea,generalJournalAccountEntry.AccountingCurrencyAmount));
           }

   while select crossCompany : companyAccountcontainer sum(AccountingCurrencyAmount) from  generalJournalAccountEntry order by DataAreaId
         where generalJournalAccountEntry.LedgerAccount like '*1211102*' // debit group
      join generalJournalEntry
          where generalJournalEntry.RecId == generalJournalAccountEntry.GeneralJournalEntry
             && generalJournalEntry.SubledgerVoucherDataAreaId == companyInfo.dataArea
             && generalJournalEntry.AccountingDate >= mkDate(1,4,2017)
             && generalJournalEntry.AccountingDate <= mkDate(1,4,2017)
           {
               info(strFmt("data area ---%1 - Debit ---%2",companyInfo.DataArea,generalJournalAccountEntry.AccountingCurrencyAmount));
           }

}

Using Buf2Buf function

static void CopyData(Args _args)
{
    InventValueReportTmpLine                           sourceTable;
    Global_ASAP_InventValueReportTmpLine  copyToDestinationTable ;
    ;

    while select sourceTable
    {
        buf2Buf(sourceTable ,copyToDestinationTable );
        copyToDestinationTable.ResourceId                           = sourceTable.ResourceId;
        copyToDestinationTable.DataArea                              = sourceTable.dataAreaId;
        copyToDestinationTable.TransDate                             = sourceTable.TransDate;
        copyToDestinationTable.InventoryFinancialQty         = sourceTable.InventoryFinancialQty;
        copyToDestinationTable.InventoryFinancialAmount  = sourceTable.InventoryFinancialAmount;
        copyToDestinationTable.insert();
    }
    info("Done");
}

Printing Sticker Counting using for lookp

static void carton(Args _args)
{
        str first        = 'Kavin';
        str second   = 'Devrajan';
        int firstNo   = 1;
        int Endno    = 5;


    for(firstNo = firstNo; firstNo <= Endno; firstNo++)
    {
        info(strFmt("%1 - %2  -%3",first,second, firstNo));

    }

}

InventTable Missing Model Group and Update the values

static void InventTableUpdateMissingModelGroup(Args _args)
{
  InventTable               inventTable;
  InventModelGroupItem      modelGroup,updatemodelgroup;
  InventTableModule         updateTablemoduel;

  while select  inventTable
    notexists join modelGroup
     where modelGroup.ItemDataAreaId == inventTable.dataAreaId
        && modelGroup.ItemId  == inventTable.ItemId
    {
 
      info(strFmt("ItemId --%1 Company --%2", inventTable.ItemId,inventTable.dataAreaId));
    }

}


-----------------------------------------------------------

static void InventTableUpdateMissingModelGroup(Args _args)
{
  InventTable               inventTable;
  InventModelGroupItem      modelGroup,updatemodelgroup;
  InventTableModule         updateTablemoduel;

  while select  inventTable
    notexists join modelGroup
     where modelGroup.ItemDataAreaId == inventTable.dataAreaId
        && modelGroup.ItemId  == inventTable.ItemId
    {
    select  updatemodelgroup where updatemodelgroup.ItemId == inventTable.ItemId
        && updatemodelgroup.ItemDataAreaId == inventTable.dataAreaId;
       // if(updatemodelgroup)
        {

           // ttsBegin;
            updatemodelgroup.ModelGroupId           = "WAvgDate";
            updatemodelgroup.ItemId                 = inventTable.ItemId;
            updatemodelgroup.ItemDataAreaId         = inventTable.dataAreaId;
            updatemodelgroup.ModelGroupDataAreaId   = inventTable.dataAreaId;
            updatemodelgroup.insert();
           // ttsCommit;
            info(strFmt("ItemId --%1 Company --%2", updatemodelgroup.ItemId,updatemodelgroup.dataAreaId));
        }

     select forUpdate updateTablemoduel where updateTablemoduel.ItemId == inventTable.ItemId
     && updateTablemoduel.ModuleType != ModuleInventPurchSales::Invent;  //( updateTablemoduel.ModuleType == ModuleInventPurchSales::Purch || updateTablemoduel.ModuleType == ModuleInventPurchSales::Sales) ;
        if(updateTablemoduel)
        {
            ttsBegin;
            updateTablemoduel.TaxItemGroupId ="ITVAT";
            updateTablemoduel.update();
            ttsCommit;
            info(strFmt("ItemId --%1 ", updateTablemoduel.ItemId));
        }


      info(strFmt("ItemId --%1 Company --%2", inventTable.ItemId,inventTable.dataAreaId));
    }

}

InventTable Missing SalesTab , Purch Tab and Invent Tab Field Values

static void InventTableMissingValuesSalse_Purch_Tab(Args _args)
{
  InventTable               inventTable;

  InventTableModule         inventTableModuel;



  while select  inventTable
     join inventTableModuel
     where inventTableModuel.ItemId  == inventTable.ItemId
        && (inventTableModuel.ModuleType == ModuleInventPurchSales::Purch || inventTableModuel.ModuleType == ModuleInventPurchSales::Sales || inventTableModuel.ModuleType == ModuleInventPurchSales::Invent)
        && ( inventTableModuel.UnitId == '' || inventTableModuel.TaxItemGroupId == '' || inventTableModuel.PriceUnit != 1.00 )
    {

      info(strFmt("ItemId --%1 Type --%2 Legal Entity --%3", inventTable.ItemId,inventTableModuel.ModuleType,inventTable.dataAreaId));
    }

}

InventTable Missing ItemModel Group

static void InventTableMissingValuesItemModelGroup(Args _args)
{
  InventTable               inventTable;
  InventModelGroupItem      modelGroup;


  while select  inventTable
    notexists join modelGroup
     where modelGroup.ItemDataAreaId == inventTable.dataAreaId
        && modelGroup.ItemId  == inventTable.ItemId
    {

      info(strFmt("ItemId --%1 ItemGroup --%2 Company --%3", inventTable.ItemId,modelGroup.ModelGroupId,inventTable.dataAreaId));
    }



}

InventTable Missing Storage Dimension

static void InventTableMissingStorageDimensions(Args _args)
{
  InventTable                           inventTable;
  EcoResTrackingDimensionGroupItem      trackingGroupItem;
  EcoResStorageDimensionGroupItem       storageGroupItem;


 while select inventTable
     notexists join storageGroupItem
      where storageGroupItem.ItemDataAreaId == inventTable.dataAreaId
         && storageGroupItem.ItemId  == inventTable.ItemId
    {
        info(strFmt("ItemId --%1 Dimension --%2 Entity --%3", inventTable.ItemId, storageGroupItem.StorageDimensionGroup, inventTable.dataAreaId));
    }

}

InventTable Missing Tracking Dimension

static void InventTableMissingTrackingDimensions(Args _args)
{
  InventTable                           inventTable;
  EcoResTrackingDimensionGroupItem      trackingGroupItem;
  EcoResStorageDimensionGroupItem       storageGroupItem;


 while select inventTable
     notexists join trackingGroupItem
      where trackingGroupItem.ItemDataAreaId == inventTable.dataAreaId
         && trackingGroupItem.ItemId  == inventTable.ItemId
    {
        info(strFmt("ItemId --%1 Dimension --%2 Entity --%3", inventTable.ItemId, trackingGroupItem.TrackingDimensionGroup, inventTable.dataAreaId));
    }

}

InventTable Default Dimension

static void InventTable_defaultDimension(Args _args)
{
    InventTable                     inventTable;
    DimensionAttributeValueSet      dimAttrValueSet;
    DimensionAttributeValueSetItem  dimAttrValueSetItem;
    DimensionAttributeValue         dimAttrValue;
    DimensionAttribute              dimAttr;
    Common                          dimensionValueEntity;
    ;
    inventTable = inventTable::find('BM-60680Z-AIS');
    dimAttrValueSet = DimensionAttributeValueSet::find(inventTable.DefaultDimension);
    while select dimAttrValueSetItem
        where   dimAttrValueSetItem.DimensionAttributeValueSet   == dimAttrValueSet.RecId
    {
        dimAttrValue        = DimensionAttributeValue::find(dimAttrValueSetItem.DimensionAttributeValue);
        dimAttr             = DimensionAttribute::find(dimAttrValue.DimensionAttribute);
        info(strFmt("%1,%2,%3",dimAttr.Name, dimAttrValue.getValue(), dimAttrValue.getName()));
    }
}

VendTable Find Dimension

static void VendTable_defaultDimension(Args _args)
{
    VendTable                       vendTable;
    DimensionAttributeValueSet      dimAttrValueSet;
    DimensionAttributeValueSetItem  dimAttrValueSetItem;
    DimensionAttributeValue         dimAttrValue;
    DimensionAttribute              dimAttr;
    Common                          dimensionValueEntity;
    ;
    vendTable = VendTable::find('22222');
    dimAttrValueSet = DimensionAttributeValueSet::find(vendTable.DefaultDimension);
    while select dimAttrValueSetItem
        where   dimAttrValueSetItem.DimensionAttributeValueSet   == dimAttrValueSet.RecId
    {
        dimAttrValue        = DimensionAttributeValue::find(dimAttrValueSetItem.DimensionAttributeValue);
        dimAttr             = DimensionAttribute::find(dimAttrValue.DimensionAttribute);
        info(strFmt("%1,%2,%3",dimAttr.Name, dimAttrValue.getValue(), dimAttrValue.getName()));
    }
}

Product Master Update Fields through Excel sheet

class ASAPG_Update_ProductMasterOGS_Fields
{
    #define.firstColumnTitle("ItemId")
    #define.progressCaption("Importing Product Master Fields ")
    #define.dialogCaption("Import To ProductMaster ")


    #define.ITEMID(1)
    #define.STOCKNUMBER(2)
    #define.PARTNUMBER(3)
    #define.CARTONQTY(4)
    #define.BOXQTY(5)
    #define.CARTYPE(6)
    #define.BRAND(7)
    #define.ITEMTYPE(8)
    #define.HSCODE(9)
    #define.VEHICLETYPE(10)
    #define.ORIGIN(11)
    #define.REFERENCE(12)
    #define.MODELNUMBER(13)
    #define.NETWEIGHT(14)
    #define.TARAWEIGHT(15)

}
-------------------
public void readFromExcel(Filename  _fileName, ecoResProductMaster _ecoResProductMaster)
{
    #AviFiles
    SysExcelApplication     xlsApplication;
    SysExcelWorkBooks       xlsWorkBooks;
    SysExcelWorkBook        xlsWorkBook;
    SysExcelWorkSheets      xlsWorkSheets;
    SysExcelWorkSheet       xlsWorkSheet;
    SysExcelRange           xlsRange;
    SysExcelCells           xlsCells;
    SysExcelCell            xlsCell;
    int                     row = 2; //nonExistitemRow;
    int                     TotalLineNum, importedLines = 0;
    SysOperationProgress    progressBar;

    OGSCTNNumber            ctnNumber;

    OGSReference            refNumber;

    ItemNetWeight           netWeight;

    ItemTaraWeight          taraWeight;

    OGSBrand                brand;

    OGSCAR                  car;

    OGSHSCode               hsCode;

    OGSItemType             itemType;

    OGSModelNumber          modelNumber;

    OGSOEMNumber            partNumber;

    OGSOrigin               origin;

    OGSVehicleType          vehicleType;

    OGSBOXNumber            boxQty;

    OGSSetCode              stockNumber;

    ItemId                  itemId;

    InventTable             inventTable;

    EcoResProductMaster     ecoResProductMaster;

    str                     _excelColumnName1,_excelColumnName2,_excelColumnName3,_excelColumnName4,_excelColumnName5;
    str                     _excelColumnName6,_excelColumnName7,_excelColumnName8,_excelColumnName9,_excelColumnName10;
    str                     _excelColumnName11,_excelColumnName12,_excelColumnName13,_excelColumnName14,_excelColumnName15;

    int                     LineNum;
    str                     excelRowNum;

    SysOperationProgress sysprogressBar = new SysOperationProgress();

    if(WinApi::fileExists(_fileName))
    {
        xlsApplication          = SysExcelApplication::construct();
        xlsWorkBooks            = xlsApplication.workbooks();
        try
        {
            xlsWorkBooks.open(_fileName,0,true);
        }
        catch (Exception::Error)
        {
            throw error("file cannot be opened");
        }

        xlsWorkBook             = xlsWorkBooks.item(1);
        xlsWorkSheets           = xlsWorkBook.worksheets();
        xlsWorkSheet            = xlsWorkSheets.itemFromNum(1);
        xlsCells                = xlsWorkSheet.cells();
      try
        {
            do
            {
                sysprogressBar.setCaption(strfmt("OGS Fields "));
                sysprogressBar.setAnimation(#aviUpdate);
                sysprogressBar.setText(strfmt("Processing %1 out of %2",row,20));

                _excelColumnName1  = xlsCells.item(1,1).value().bStr();
                _excelColumnName2  = xlsCells.item(1,2).value().bStr();
                _excelColumnName3  = xlsCells.item(1,3).value().bStr();
                _excelColumnName4  = xlsCells.item(1,4).value().bStr();
                _excelColumnName5  = xlsCells.item(1,5).value().bStr();
                _excelColumnName6  = xlsCells.item(1,6).value().bStr();
                _excelColumnName7  = xlsCells.item(1,7).value().bStr();
                _excelColumnName8  = xlsCells.item(1,8).value().bStr();
                _excelColumnName9  = xlsCells.item(1,9).value().bStr();
                _excelColumnName10 = xlsCells.item(1,10).value().bStr();
                _excelColumnName11 = xlsCells.item(1,11).value().bStr();
                _excelColumnName12 = xlsCells.item(1,12).value().bStr();
                _excelColumnName13 = xlsCells.item(1,13).value().bStr();
                _excelColumnName14 = xlsCells.item(1,14).value().bStr();
                _excelColumnName15 = xlsCells.item(1,15).value().bStr();

                LineNum++;

                ItemId            = xlsCells.item(row,1).value().bStr();

                stockNumber       = xlsCells.item(row,2).value().bStr();
                 //if(!stockNumber)
                  //{
                   //stockNumber    = int2str(real2int(xlsCells.item(row,2).value().double()));
                  //}

                partNumber        = xlsCells.item(row,3).value().bStr();
                 //if(!partNumber)
                  //{
                   //partNumber     = int2str(real2int(xlsCells.item(row,3).value().double()));
                  //}

                ctnNumber         = xlsCells.item(row,4).value().bStr();
                 //if(!ctnNumber)
                  //{
                   //ctnNumber      = int2str(real2int(xlsCells.item(row,4).value().double()));
                  //}

                boxQty            = xlsCells.item(row,5).value().bStr();
                 //if(!boxQty)
                  //{
                   //boxQty         = int2str(real2int(xlsCells.item(row,5).value().double()));
                  //}

                car               = xlsCells.item(row,6).value().bStr();
                 //if(!car)
                  //{
                   //car            = int2str(real2int(xlsCells.item(row,6).value().double()));
                  //}

                brand             = xlsCells.item(row,7).value().bStr();
                 //if(!brand)
                  //{
                   //brand          = int2str(real2int(xlsCells.item(row,7).value().double()));
                  //}

                itemType          = xlsCells.item(row,8).value().bStr();
                 //if(!itemType)
                  //{
                   //itemType       = int2str(real2int(xlsCells.item(row,8).value().double()));
                  //}

                hsCode            = xlsCells.item(row,9).value().bStr();
                 //if(!hsCode)
                  //{
                   //hsCode         = int2str(real2int(xlsCells.item(row,9).value().double()));
                  //}

                vehicleType       = xlsCells.item(row,10).value().bStr();
                 //if(!vehicleType)
                  //{
                   //vehicleType    = int2str(real2int(xlsCells.item(row,10).value().double()));
                  //}

                origin            = xlsCells.item(row,11).value().bStr();
                 //if(!origin)
                  //{
                   //origin         = int2str(real2int(xlsCells.item(row,11).value().double()));
                  //}

                refNumber         = xlsCells.item(row,12).value().bStr();
                 //if(!refNumber)
                  //{
                   //refNumber      = int2str(real2int(xlsCells.item(row,12).value().double()));
                  //}

                modelNumber       = xlsCells.item(row,13).value().bStr();
                 //if(!modelNumber)
                  //{
                   //modelNumber    = int2str(real2int(xlsCells.item(row,13).value().double()));
                  //}

                netWeight         = xlsCells.item(row,14).value().double();

                taraWeight        = xlsCells.item(row,15).value().double();


             ttsbegin;

              while select forUpdate ecoResProductMaster
                      where ecoResProductMaster.DisplayProductNumber == itemId
                if(ecoResProductMaster)
                {
                   importedLines++;
                   if(_excelColumnName2 == "STOCKNUMBER" ) //----- STOCKNUMBER
                    {
                        if(stockNumber != '')
                        {
                          ecoResProductMaster.OGSSetCode = stockNumber;
                          ecoResProductMaster.update();
                        }
                     }
                   if(_excelColumnName3 == "PARTNUMBER" ) //----- PARTNUMBER
                    {
                        if(partNumber != '')
                        {
                          ecoResProductMaster.OGSOEMNumber = partNumber;
                          ecoResProductMaster.update();
                        }
                     }
                   if(_excelColumnName4 == "CARTONQTY" ) //----- CARTONQTY
                    {
                        if(ctnNumber != '')
                        {
                          ecoResProductMaster.OGSCTNNumber = ctnNumber;
                          ecoResProductMaster.update();
                        }
                     }
                   if(_excelColumnName5 == "BOXQTY" ) //----- BOXQTY
                    {
                        if(boxQty != '')
                        {
                          ecoResProductMaster.OGSBOXQTY = boxQty;
                          ecoResProductMaster.update();
                        }
                     }
                   if(_excelColumnName6 == "CARTYPE" ) //----- CARTYPE
                    {
                        if(ctnNumber != '')
                        {
                          ecoResProductMaster.OGSCTNNumber = ctnNumber;
                          ecoResProductMaster.update();
                        }
                     }
                   if(_excelColumnName7 == "BRAND" ) //----- BRAND
                    {
                        if(brand != '')
                        {
                          ecoResProductMaster.OGSBrand = brand;
                          ecoResProductMaster.update();
                        }
                     }
                   if(_excelColumnName8 == "ITEMTYPE" ) //----- ITEMTYPE
                    {
                        if(itemType != '')
                        {
                          ecoResProductMaster.OGSItemType = itemType;
                          ecoResProductMaster.update();
                        }
                     }
                   if(_excelColumnName9 == "HSCODE" ) //----- HSCODE
                    {
                        if(hsCode != '')
                        {
                          ecoResProductMaster.OGSHSCode = hsCode;
                          ecoResProductMaster.update();
                        }
                     }
                   if(_excelColumnName10 == "VEHICLETYPE" ) //----- VEHICLETYPE
                    {
                        if(vehicleType != '')
                        {
                          ecoResProductMaster.OGSVehicleType = vehicleType;
                          ecoResProductMaster.update();
                        }
                     }
                   if(_excelColumnName11 == "ORIGIN" ) //----- ORIGIN
                    {
                        if(origin != '')
                        {
                          ecoResProductMaster.OGSOrigin = origin;
                          ecoResProductMaster.update();
                        }
                     }
                   if(_excelColumnName12 == "REFERENCE" ) //----- REFERENCE
                    {
                        if(refNumber != '')
                        {
                          ecoResProductMaster.OGSReference = refNumber;
                          ecoResProductMaster.update();
                        }
                     }
                   if(_excelColumnName13 == "MODELNUMBER" ) //----- MODELNUMBER
                    {
                        if(modelNumber != '')
                        {
                          ecoResProductMaster.OGSModelNumber = modelNumber;
                          ecoResProductMaster.update();
                        }
                     }
                   if(_excelColumnName14 == "NETWEIGHT" ) //----- NETWEIGHT
                    {
                        if(netWeight != 0.00)
                        {
                          ecoResProductMaster.OGSNetWeight = netWeight;
                          ecoResProductMaster.update();
                        }
                     }
                   if(_excelColumnName15 == "TARAWEIGHT" ) //----- TARAWEIGHT
                    {
                        if(taraWeight != 0.00)
                        {
                          ecoResProductMaster.OGSTaraWeight = taraWeight;
                          ecoResProductMaster.update();
                        }
                     }


                else if( _excelColumnName2 != "STOCKNUMBER" || _excelColumnName3 != "PARTNUMBER" || _excelColumnName4 != "CARTONQTY" || _excelColumnName5 != "BOXQTY" || _excelColumnName6 != "CARTYPE" || _excelColumnName7 != "BRAND" ||
                         _excelColumnName8 != "ITEMTYPE" || _excelColumnName9 != "HSCODE" || _excelColumnName10 != "VEHICLETYPE"  || _excelColumnName11 != "ORIGIN" || _excelColumnName12 != "REFERENCE" || _excelColumnName13 != "MODELNUMBER" ||
                         _excelColumnName14 != "NETWEIGHT" || _excelColumnName15 != "TARAWEIGHT" || _excelColumnName1 != "ITEMID")
                    {
                        checkFailed(strFmt("Header Name : %1 Not Matching1  -- %2 Not Matching2  -- %3 Not Matching3  -- %4 Not Matching4  -- %5 Not Matching5 -- %6 Not Matching6  -- %7 Not Matching7  -- %8 Not Matching8  -- %9 Not Matching9  -- %10 Not Matching10 -- %11 Not Matching11 -- %12 Not Matching12 -- %13 Not Matching13 -- %14 Not Matching14 -- %15 Not Matching15",_excelColumnName1,_excelColumnName2,_excelColumnName3,_excelColumnName4,_excelColumnName5,_excelColumnName6,_excelColumnName7,_excelColumnName8,_excelColumnName9,_excelColumnName10,_excelColumnName11,_excelColumnName12,_excelColumnName13,_excelColumnName14,_excelColumnName15));
                       // checkFailed(strFmt("Header Name : %1 Not Matching6  -- %2 Not Matching7  -- %3 Not Matching8  -- %4 Not Matching9  -- %5 Not Matching10",_excelColumnName6,_excelColumnName7,_excelColumnName8,_excelColumnName9,_excelColumnName10));
                        //checkFailed(strFmt("Header Name : %1 Not Matching11 -- %2 Not Matching12 -- %3 Not Matching13 -- %4 Not Matching14 -- %5 Not Matching15",_excelColumnName11,_excelColumnName12,_excelColumnName13,_excelColumnName14,_excelColumnName15));
                        break;
                    }
                }

                else
                {
                   info(strFmt("Item : %1 Not available",ItemId));
                }

                ttscommit;
                row++;
            }
            while(xlsCells.item(row,#ITEMID).value().bStr());
        }
        catch(Exception::Error)
        {
            error("error");
            //checkFailed(strFmt("Item %1", itemId));
        }
      }
     info(strFmt("%1 rows imported from file",importedLines));

}
-------------------
public void run(ecoResProductMaster _ecoResProductMaster)
{
    Dialog          dialog;
    DialogField     dialogFileName;
    FileName        errorFile;
    str             fileName;


    fileName = WinAPI::getOpenFileName(0,['Excel','*.xlsx'],'',' OGS Fields ','xlsx',fileName);

    if(fileName)
    {
        this.readFromExcel(fileName,_ecoResProductMaster);
    }
}
----------------------------------
public static void main(Args _args)
{
    EcoResProductMaster ecoResProductMaster;

    if (_args)
    {
         ecoResProductMaster = _args.record();
    }
    new ASAPG_Update_ProductMasterOGS_Fields().run(ecoResProductMaster);
}

Product Master Excel Template Creation

creating a class .. and in main () using dialog window to ask yes or no
-------------------------------------------------------
class ASAPG_ProductMaster_ImportTemplate extends RunBase
{

}

-------------------------------------------------------
public static void main(Args _args)
{
    SysExcelApplication excel;
    SysExcelWorkbooks   workbooks;
    SysExcelWorkbook    workbook;
    SysExcelWorksheets  worksheets;
    SysExcelWorksheet   worksheet;
    SysExcelCells       cells;

    //color and font
    SysExcelStyles      styles;
    SysExcelStyle       style;
    SysExcelFont        font;
    /// end

    COMVariantType      type;
    int                 row, column;
    Set                 set = new set(Types::Int64);
    SysExcelCell        cell;
    container           con;
    str                 delimiter="\\";
    Map                 map = new  Map(Types::String,Types::Integer);


    if (Box::yesNo("Do you want to create Product master template" ,DialogButton::Yes) == DialogButton::Yes)
    {
        excel       = SysExcelApplication::construct();
        workbooks   = excel.workbooks();
        workbook    = workbooks.add();

        styles      = workbook.styles();
        style       = styles.add("Header");
        font        = style.font();
        font.bold(true);
        font.color(255);

        worksheets  = workbook.worksheets();
        worksheet   = worksheets.itemFromNum(1);
        cells       = worksheet.cells();
        cells.range('A:A').numberFormat('@');
        row=1;

        cell = cells.item(row,1);cell.value("ITEMID");
        cell = cells.item(row,2);cell.value("STOCKNUMBER");
        cell = cells.item(row,3);cell.value("PARTNUMBER");
        cell = cells.item(row,4);cell.value("CARTONQTY");
        cell = cells.item(row,5);cell.value("BOXQTY");
        cell = cells.item(row,6);cell.value("CARTYPE");
        cell = cells.item(row,7);cell.value("BRAND");
        cell = cells.item(row,8);cell.value("ITEMTYPE");
        cell = cells.item(row,9);cell.value("HSCODE");
        cell = cells.item(row,10);cell.value("VEHICLETYPE");
        cell = cells.item(row,11);cell.value("ORIGIN");
        cell = cells.item(row,12);cell.value("REFERENCE");
        cell = cells.item(row,13);cell.value("MODELNUMBER");
        cell = cells.item(row,14);cell.value("NETWEIGHT");
        cell = cells.item(row,15);cell.value("TARAWEIGHT");


        excel.visible(true);
    }
}

----------------------------------------

Saturday 27 October 2018

PurchreqTable form Itemid lookup customization

// -- req is based on department item id lookup want to display related to the department selected


public void lookup()
{
    QueryBuildDataSource                    qbdsInventTable, qbdsEcoResCategory, qbdsEcoResProductCategoryExpanded, qbdsEcoResProcurementCategoryExpanded;
    QueryBuildRange                         qbr;
    Query                                   query   = new Query();
 
    EcoResCategory                          ecoResCategory;
    EcoResProductCategoryExpanded           ecoResProductCategoryExpanded;// view
    EcoResProcurementCategoryExpanded       ecoResProcurementCategoryExpanded;//view
    PurchReqLine                            _purchReqLine;
    Str60                                   departmentvalue , departmentText;
    DimensionAttributeValueSet              dimAttrValueSet;
    DimensionAttributeValueSetItem          dimAttrValueSetItem;
    DimensionAttributeValue                 dimAttrValue;
    DimensionAttribute                      dimAttr;
    Common                                  dimensionValueEntity;
    DimensionValue                          dimensionvalue;
    DimensionAliasName                      dimensionname;
    str                                     procurrentCategory;

      SysTablelookup              sysTableLookup  = SysTableLookup::newParameters(tablenum(InventTable), this);
 
 
     dimAttrValueSet = DimensionAttributeValueSet::find(PurchReqLine.DefaultDimension);

     while  select dimAttrValueSetItem
             where   dimAttrValueSetItem.DimensionAttributeValueSet == dimAttrValueSet.RecId
           {

                 dimAttrValue         = DimensionAttributeValue::find(dimAttrValueSetItem.DimensionAttributeValue);

                 dimAttr              = DimensionAttribute::find(dimAttrValue.DimensionAttribute);

                 dimensionValueEntity = DimensionDefaultingControllerBase::findBackingEntityInstance(curext(),dimAttr,dimAttrValue.EntityInstance);

                 if(dimAttr.Name == 'Department')
                 departmentvalue = dimAttrValue.getName();
                 //info(departmentvalue);
           }

          departmentText = departmentvalue;

    if(departmentText == 'Information and communications technology Department')
    {
             
        sysTableLookup.addLookupfield(fieldnum(InventTable, ItemId));
        sysTableLookup.addLookupfield(fieldnum(InventTable, NameAlias));
        sysTableLookup.addLookupfield(fieldnum(InventTable, ItemType));
        sysTableLookup.addLookupfield(fieldnum(InventTable, Product));

        qbdsInventTable = query.addDataSource(tableNum(InventTable));

        qbdsEcoResCategory = qbdsInventTable.addDataSource(tableNum(EcoResProductCategoryExpanded));
        qbdsEcoResCategory.relations(false);
        qbdsEcoResCategory.joinMode(joinMode::ExistsJoin);
        qbdsEcoResCategory.addLink(fieldNum(InventTable, ItemId), fieldNum(EcoResProductCategoryExpanded, ItemId));

        qbdsEcoResProcurementCategoryExpanded = qbdsEcoResCategory.addDataSource(tableNum(EcoResProcurementCategoryExpanded));
        qbdsEcoResProcurementCategoryExpanded.relations(false);
        qbdsEcoResProcurementCategoryExpanded.joinMode(joinMode::ExistsJoin);
             
        qbdsEcoResProcurementCategoryExpanded.addLink(fieldNum(EcoResProductCategoryExpanded,RecIdCategory ), fieldNum(EcoResProcurementCategoryExpanded,RecId));
     
        qbdsEcoResProcurementCategoryExpanded.addRange(fieldNum(EcoResProcurementCategoryExpanded, Name)).value("Water");

        sysTableLookup.parmQuery(query);
        sysTableLookup.performFormLookup();

    }
 
    if(departmentText == 'Laundry')
    {
             
        sysTableLookup.addLookupfield(fieldnum(InventTable, ItemId));
        sysTableLookup.addLookupfield(fieldnum(InventTable, NameAlias));
        sysTableLookup.addLookupfield(fieldnum(InventTable, ItemType));
        sysTableLookup.addLookupfield(fieldnum(InventTable, Product));

        qbdsInventTable = query.addDataSource(tableNum(InventTable));

        qbdsEcoResCategory = qbdsInventTable.addDataSource(tableNum(EcoResProductCategoryExpanded));
        qbdsEcoResCategory.relations(false);
        qbdsEcoResCategory.joinMode(joinMode::ExistsJoin);
        qbdsEcoResCategory.addLink(fieldNum(InventTable, ItemId), fieldNum(EcoResProductCategoryExpanded, ItemId));

        qbdsEcoResProcurementCategoryExpanded = qbdsEcoResCategory.addDataSource(tableNum(EcoResProcurementCategoryExpanded));
        qbdsEcoResProcurementCategoryExpanded.relations(false);
        qbdsEcoResProcurementCategoryExpanded.joinMode(joinMode::ExistsJoin);
             
        qbdsEcoResProcurementCategoryExpanded.addLink(fieldNum(EcoResProductCategoryExpanded,RecIdCategory ), fieldNum(EcoResProcurementCategoryExpanded,RecId));
     
        qbdsEcoResProcurementCategoryExpanded.addRange(fieldNum(EcoResProcurementCategoryExpanded, Name)).value("Clothes");
        qbdsEcoResProcurementCategoryExpanded.addRange(fieldNum(EcoResProcurementCategoryExpanded, Name)).value("Water");
        sysTableLookup.parmQuery(query);
        sysTableLookup.performFormLookup();

    }
}

Sunday 5 August 2018

Working with the AX 2012 EDT relation migration tool

Working with the AX 2012 EDT relation migration tool


Hi there!

This week I was faced with a couple of problems related to the relationships between tables made under an Extended Data Type (EDT). In my case, I learned that when relationships between tables exist through EDTs, they only capture a single field relationship and not necessarily a “real” relationship between tables.

A good example of this is when we assign an ItemId EDT to a custom field in a custom table. In this case, AX 2012 will ask you to create an EDT relationship, so I did. Later on the week, I was getting an error related to a violation of a primary key in the custom table I created when data was being inserted to it. 

The error was related to the relationships being defined under an EDT as the kernel was have issues defining which relationship to examine first. 

It took me a while to understand that the problem was the EDT relationship and after looking at some documentation it was easy to catch the issue as EDT relationships do not contain relationship metadata, such as cardinality and relationship type, and more often than not, they cannot be included in the relations node. 

Luckily for us, AX 2012 provides a simple way to fix the EDT relations issues fairly easy. In fact, the migration can be done both manually or using the new EDT relation migration tool. However, if the data model is not correct, there are cases where we are going to have to fix the EDT’s manually.

To begin using the EDT relation migration tool, open the form for the tool by using the navigation path Tools > Code upgrade > EDT relation migration tool as seen in the picture below. 



NOTE: Just keep in mind that if you are using this tool for the first time, AX 2012 will ask you if you want to refresh all the EDT relationships data, click yes and the EDT Migration tool will open.


When the form has opened, follow the next steps:
  1. Select a table from the Table name pane.
  2. Select each relation in the EDT relations table and choose an action from the Migration action drop-down menu for each of them.
  3. After you have set an action on all the relations for that table, click the Migrate single table button on the ribbon at the top of the form.

See Image for clarification:



What happens in the background?

  1. The migration tool attempts to find a match for the EDT relation in the existing relations in the selected table. If a match is found, the SourceEDT property on the table relation is set to the name of the EDT.
  2. However, if there is no match found in the table, the EDT migration tool will create a new table relationship only if the index (IndexType ) on the referenced table (shown by “”) is set to the correct table relationship.
  3. Finally, the tool will not create a new table relation if the matching index for the EDT field on the referenced table is set to NoIndexUniqueNonUnique.

Example: Migrating an EDT relation to a new table relation.

This example shows the case in which an EDT relation is migrated to a table where the table relation was previously not defined. The result from this example will be the creation of a new table relation.

The EDT PKTableField1 defines a relation to the PKTable.Field1 field, which is an alternate key AK1.


In addition, before the EDT migration, the FKTable.Field1 field uses the EDT PKTableField1, which makes it a foreign key into PKTable. However, there is no table relation defined on the FKTable, and the ExtendedDataType property on FKTable.Field1 is set to PKTableField1 instead. 



We choose the FKTablle and under the Migration Action, we choose Migrate.



What happens in the background?

The EDT relation migration tool performs the following actions:
  • The EDT migration tool creates the new relation to the PKTable under the Relations node of the FKTable. This relation will be of type Normal because the key is not the primary key.
  • Then, the EDT migration tool will set the EDTRelation property of the PKTable relation to Yes. This is because the tool performs the direct migration of an EDT relation to the table relation.
  • Then, the EDT migration tool creates one field link, FKTable.Field1 == PKTable.Field1, for the PKTable relation.
  • Finally, the EDT migration tool will set the SourceEDT property of the field link toPKTableField1.

What to expect the next time we use the tables?
  • All the APIs that used the EDT relation first on FKTable.Field1 will now find the same relation with the same field link under the PKTable relation by examining its SourceEDT property.
  • If a table relation that refers to PKTable already exists in FKTable, all the APIs that used those table relations will not pick up the PKTable relation because it is flagged as an EDTRelation, and the PKTable relation to the Relations node of the FKTable, with its EDTRelation property set to Yes.



In addition to the above, we can also double check the outcome of the EDT migration tool by looking at the SourceEDT property of FKTable.Field1. This should have been set to PKTableField1 to maintain a relationship with the EDT.



Let recap for a minute on what we just went over. The EDT relation migration tool can be used to automate the following actions:

  • Copy an EDT relation to all hosting tables.
  • Automatically set the EDT migration properties (markers) to reflect migration status.
  • Automatically populate relation metadata.
  • Derive cardinality from the index on the foreign key.
  • Derive the relationship type from the delete action/key composition.
  • Determine role names.
  • Report AOT objects impacted by the migration, depending on the relation used. The objects that can be affected include:
  • Queries:
  • Forms
  • Delete actions on tables
  • Data sets
  • X++ reports
Well folks, I think this is it for now. I really hope you like this article and that can help you at some point in your AX 2012 adventure. Also, I will be writing a bit more about AX 2012 Retail and Inventory and Product management in AX 2012 soon, so don’t miss it!

Labels

#veryusefulcode (1) AIF (8) AOT Maps (1) Args (1) Ax 2009 Reports (2) AX 2012 navigation (1) Ax 2012 Interview Questions (1) AX 7 (2) AX Architecture (1) Ax Backup (1) AX Workflow (2) AX2012 (1) AX2012 R2 (1) Ax2012R3 (1) AX2012R3 Dynamics Connector Step by Step Installation and Configuration (1) AX2012R3 EP Step by Step Installation and Configuration EP R3 (1) AX2012R3 HelpServer Step by Step Installation and Configuration (1) AX2012R3 Rapid Start Connector Step by Step Installation and Configuration (1) AX2012R3 Report Server and Analysis Server Step by Step Installation and Configuration (1) AX7 (1) Best practices (1) Blocking user to enter (1) Collection Classes (1) Container (1) D365FO (3) Data Migration Frame Work ax 2012R3 (1) Deleting duplicate Record from Table – Ax2012 (1) Delivery due date notification workflow in Ax 2012 (1) Development Steps EP (1) Dimensions (1) DIXF (1) DMF in Ax 2012 R3 (1) Dynamics Ax 2012 Interview Questions (1) DYNAMICS AX 2012 INTERVIEW QUESTIONS PART 2 (1) DYNAMICS AX 7 (1) EDT relation Migration Tool (1) EP AX 2012 (1) Ep Lookup (1) Error (1) Event Handler (1) F5 (1) File Handling (4) Filter on AX2012 Listpage (1) filtering (2) financial dimensions in AX 2012 (3) form (1) images (1) Installation and Configration (4) Installation and Configuration (11) Installation of Management Reporter 2012 for AX 2012 (1) Interaction class in ax 2012 (1) Interview Question (1) Interview Questions For Ax 2012 (1) Invent DIm (1) Jobs (2) license (1) List page and form menuitem enable code (1) Methods (1) microsoft Dynamics AX 365FO (1) Number Sequence Generation – AX 2012 (5) Number Sequence2012 (1) OLTP-OLAP (1) Passing Args (1) Passing form caller and menu item caller in ax 2012 (1) Passing Multiple Records Args (1) Posting in Ax 2012 (1) POSTING PURCHASE ORDER (1) Query (1) Query Filter Form (2) Query Ranges in X++ (1) Question and Answer (1) Report (1) Reports Controller class (1) RLS in ax 2009 (1) SALES ORDER IMPORT/EXPORT FRAMEWORK BY DMF (1) Security (1) security roles (1) Security Sysqueryrangeutil (1) Sharepoint 2016 (1) SQL SERVER (1) SSRS (2) SSRS Reports Controller class (2) Table collections & Virtual company (1) Time (1) TIPS AND TRICKS (1) Web service AIF (3) Web Services on IIS (AIF) Step by Step Installation and Configuration (1) workflow ax2012 (1) Workflow installation (1) Workflow Method (3) X++ (1)