Wednesday, November 11, 2020

Updating Sales Group Employee responable and dimension in customer

 static void GH_CustDimension_SalesGroup_Updating(Args _args)

{


    SysExcelApplication                 application;

    SysExcelWorkbooks                   workbooks;

    SysExcelWorkbook                    workbook;

    SysExcelWorksheets                  worksheets;

    SysExcelWorksheet                   worksheet;

    SysExcelCells                       cells;

    COMVariantType                      type;

    Filename                            filename;

    str                                 filePath, fileNameOnly;

    Dialog                              dialog;

    DialogField                         dialogFileName;

    int                                 row;

    container                           record, roles;


    CustTable                         _custTable;

    DimensionAttribute                _dimAttribute;

    DimensionAttributeValueSet        _dimAttributeSet;

    DimensionAttributeValueSetItem    _dimAttributeSetItem;

    DimensionAttributeValue           _dimValue;

    DimensionAttributeValueSetStorage _dimStorage;

    Common                            _dimensionValueEntry;

    CustAccount                       _custAccount;


    ;


    dialog = new Dialog();

    dialog.caption("Pick excel file");

    dialogFileName = dialog.addField(extendedTypeStr(FilenameOpen), "Enter excel file", "Browse excel file");


    if(!dialog.run())

        return;


    filename                = dialogFileName.value();

    [filePath,fileNameOnly] = fileNameSplit(filename);

    application             = SysExcelApplication::construct();

    workbooks               = application.workbooks();


    try

    {

        workbooks.open(filename);

    }

    catch (Exception::Error)

    {

        throw error(strFmt("Filename %1 cannot be blank.",filename));

    }


    workbook   = workbooks.item(1);

    worksheets = workbook.worksheets();

    worksheet  = worksheets.itemFromNum(1);

    cells      = worksheet.cells();


    row = 1;

    do

    {

        try

        {

            row++;

            _custAccount   = cells.item(row, 1).value().bStr();


            if(strLRTrim(cells.item(row, 1).value().bStr())!= "")

                {

                     select forUpdate _custTable where _custTable.AccountNum == _custAccount;

                    {

                         ttsBegin;

                         _custTable.SalesGroup           = 'TES';

                         _custTable.MainContactWorker    = 5637156776;

                         _dimStorage                     = DimensionAttributeValueSetStorage::find(_custTable.DefaultDimension);

                         _dimAttribute                   = DimensionAttribute::findByName("GH01_Salesman");

                         _dimValue                       = DimensionAttributeValue::findByDimensionAttributeAndValue(_dimAttribute, 'TES', true, true);

                         _dimStorage.addItem(_dimValue);

                         _custTable.DefaultDimension     = _dimStorage.save();

                         _custTable.doUpdate();

                        ttsCommit;

                    }

                }


            else

            {

                warning(strFmt("Row %1 not updated.", row));

            }

        }

        catch

        {

            error(strfmt("Row %1 not updated.", row));

        }

        type = cells.item(row+1, 1).value().variantType();

    }

    while (type != COMVariantType::VT_EMPTY);

    workbook.saved(true);

    application.visible(false);

    application.quit();


    info("Excel uploaded successfully");

}

Monday, November 2, 2020

Unit price non editable code

 

Sales Table Form – SalesLine DS- Active

 

//--- added for non editable unit price and netamount fileds in salesline

 

        ifcurext() == 'gh01' && !isSystemAdministrator())

        {

 

            SalesLine_ds.object(fieldNum(SalesLine, SalesPrice)).allowEdit(false);

            SalesLine_ds.object(fieldNum(SalesLine, LineAmount)).allowEdit(false);

            SalesLine_SalesPrice.allowEdit(false);

            SalesLine_LineAmount.allowEdit(false);

 

        }

        else

        {

            //if(Salestable.GOD_IsMovedToWMS)

            //{

                //SalesLine_ds.allowEdit(true);

                //allowEditFieldsOnFormDS_W(SalesLine_ds, false);

            //}

            SalesLine_ds.object(fieldNum(SalesLine, SalesPrice)).allowEdit(true);

            SalesLine_ds.object(fieldNum(SalesLine, LineAmount)).allowEdit(true);

            SalesLine_SalesPrice.allowEdit(true);

            SalesLine_LineAmount.allowEdit(true);

        }

    //----- end

 

Tuesday, October 20, 2020

Inventory Script

 SELECT T1.[ITEMID]

  , T7.[Name]

      ,CASE WHEN [ITEMTYPE] = 0 THEN 'ITEM'

WHEN [ITEMTYPE] = 2 THEN 'SERVICE'

ELSE 'ITEM' END AS ITEMTYPE

-- , ISNULL(d.ITEM_STATUS, 'ACTIVE') ITEM_STATUS

  , T11.NAME [ITEM_GROUP]

      ,[PRIMARYVENDORID]

      ,[NETWEIGHT]

      ,[UNITVOLUME]

      ,[ORIGCOUNTRYREGIONID]

      ,[NAMEALIAS]

      ,[ITEMBUYERGROUPID]

      ,T12.[UNITID] SKU 

      ,[TARAWEIGHT]

      ,[GOD_ISMOVEDTOWMS]ISMOVEDTOWMS

      ,[GITL_BPCPRODUCTCATEGORY_ID]BPCPRODUCTCATEGORYID

      ,[GOD_ACTIVECHANGEDBY]ACTIVECHANGEDBY

      ,[GOD_ACTIVECHANGEDDATE]ACTIVECHANGEDDATE

      ,[GOD_AVERAGEWEIGHT]AVERAGEWEIGHT

      ,[GOD_BPCPRODUCT_SUB_CATEGORYID]BPCPRODUCT_SUB_CATEGORYID

      ,T1.[GOD_BPCPRODUCTCATEGORY_ID]BPCPRODUCTCATEGORY_ID

      ,T1.[GOD_BPCPRODUCTGROUP_ID]BPCPRODUCTGROUP_ID

      ,[GOD_BRANDCODE]BRANDCODE

      ,ISNULL(T4.[GOD_BPCBRAND_NAME],'NA') [GOD_BPCBRAND_NAME]

      ,T1.[GOD_BRANDMANAGER_ID]BRANDMANAGER_ID

      ,ISNULL(T5.[GOD_BRANDMANAGER_NAME],'NA')[GOD_BRANDMANAGER_NAME]

      ,ISNULL(T5.[GOD_BMREFERENCE],'NA')[GOD_BMREFERENCE]

      ,[GOD_CONDITION]CONDITION

      ,[GOD_CSCNT]

      ,[GOD_INACTIVE]

      ,[GOD_IPCNT]

      ,[GOD_ITEMGROUPCODE]

      ,[GOD_ITEMPACKINGTYPE]

      ,[GOD_PLCNT]

      ,[GOD_STORE]STORE

      ,[GOD_STOREAREA]STOREAREA

      ,[GOD_STOREZONE]STOREZONE

      ,[GOD_WEIGHABLE]WEIGHABLE

      ,[GOD_WMSUNIT]WMSUNIT

      ,[GOD_PROMOITEM]PROMOITEMD

      ,T1.[GOD_FAMILYCODE]FAMILYCODE

      ,ISNULL(T9.[DESCRIPTION],'NA')FAMILY

      ,[GOD_LATESTPURCHPRICE]LATESTPURCHPRICE

      ,[GOD_CNT]

      ,[GOD_TEMPERATURE]TEMPERATURE

      ,[GOD_PDSSHELFLIFE]PDSSHELFLIFE

      ,T14.EXTERNALITEMID

      ,T1.[MODIFIEDDATETIME]

      ,T1.[DEL_MODIFIEDTIME]

      ,T1.[MODIFIEDBY]

      ,T1.[CREATEDDATETIME]

      ,T1.[DEL_CREATEDTIME]

      ,T1.[CREATEDBY]

      ,T1.[DATAAREAID]

      ,T1.[RECVERSION]

      ,T1.[RECID]

      ,T15.[UNITID] PurchUnit

 FROM   [INVENTTABLE] T1

 INNER JOIN   ECORESPRODUCT T6 ON T1.PRODUCT = T6.RECID

 INNER JOIN   ECORESPRODUCTTRANSLATION T7 ON T1.PRODUCT = T7.PRODUCT AND T7.LANGUAGEID  = 'EN-US'

 INNER JOIN    INVENTITEMGROUPITEM T8 ON T8.ITEMID = T1.ITEMID AND T8.ITEMDATAAREAID = T1.DATAAREAID 

 LEFT join   inventitemgroup T11 on T11.ITEMGROUPID = T8.ITEMGROUPID and T8.ITEMDATAAREAID = T11.DATAAREAID

 LEFT JOIN   GOD_ProductCategory T2 ON T1.[GOD_BPCPRODUCTCATEGORY_ID] = T2.GOD_BPCProductCategory_ID and T1.DataareaID = T2.DataAreaID

 LEFT JOIN   GOD_ProductGroupMaster T3 on T3.[GOD_BPCPRODUCTGROUP_ID] = T1.[GOD_BPCPRODUCTGROUP_ID]     and T3.DataareaID = T1.DataAreaID

 LEFT JOIN   GOD_BRAND_SECTIONMASTER T4 on T4.[GOD_BPCBRAND_ID] = T1.[GOD_BRANDCODE] and T4.DATAAREAID = T1.DATAAREAID

 LEFT JOIN   God_BrandManagerCode T5 on T5.God_BrandManager_ID = T1.[GOD_BRANDMANAGER_ID] and  T5.DATAAREAID = T1.DATAAREAID

 LEFT JOIN   GOD_ItemFamilyMaster T9 ON T1.[GOD_FAMILYCODE] = T9.CODE AND T1.DATAAREAID = T9.DATAAREAID

 INNER JOIN   INVENTTABLEMODULE T12 ON T12.ITEMID = T1.ITEMID AND T12.DATAAREAID = T1.DATAAREAID AND T12.MODULETYPE = 0 

 INNER JOIN   INVENTTABLEMODULE T15 ON T15.ITEMID = T1.ITEMID AND T15.DATAAREAID = T1.DATAAREAID AND T15.MODULETYPE = 1 

 INNER JOIN   UNITOFMEASURE T13 ON T13.SYMBOL = T12.UNITID

 LEFT JOIN CustVendExternalItem T14 ON T14.ITEMID = T1.ITEMID AND T14.DATAAREAID = T1.DATAAREAID 

 WHERE T1.DATAAREAID = 'GH01'


DeadStock Sql Query

 declare @DataAreaId nvarchar(4) = 'GH01',

@datePeriod int = 180

 

 

select s.DATAAREAID,s.ITEMID,i.GOD_BRANDMANAGER_ID, i.PmfProductType, i.GOD_INACTIVE,isnull(t1.lastdate,'03-01-2020') [LASTDATE],m.UNITID, sum(s.AVAILPHYSICAL) [AVAILPHYSICAL] ,sum(s.RESERVPHYSICAL) [RESERVORDERED],

          sum(s.AVAILPHYSICAL) + sum(s.RESERVPHYSICAL) [TOTALPHYSICAL]

, sum(s.PHYSICALVALUE)[PHYSICALVALUE] , sum(s.POSTEDVALUE) [POSTEDVALUE],  sum(s.PHYSICALVALUE) + sum(s.POSTEDVALUE) [TOTALCOST]

 

from INVENTSUM s

LEFT join (

          select tr.DATAAREAID, tr.ITEMID, max(tr.DATESTATUS) [LastDate]

          from INVENTTRANS tr

          inner join INVENTTRANSORIGIN o on o.RECID = tr.INVENTTRANSORIGIN

          where tr.DATAAREAID = @DataAreaId and o.REFERENCECATEGORY = 0 and tr.STATUSISSUE <> 0

          group by tr.DATAAREAID,tr.ITEMID

          ) t1 on t1.DATAAREAID = s.DATAAREAID and t1.ITEMID = s.ITEMID

          inner join INVENTTABLEMODULE m on m.DATAAREAID = s.DATAAREAID and m.ITEMID = s.ITEMID and m.MODULETYPE = 0

  inner join inventTable I on I.ITEMID = s.ITEMID and i.DATAAREAID= s.DATAAREAID

 

 

where s.DATAAREAID = @DataAreaId  and s.CLOSED = 0 and isnull(t1.LastDate,'03-01-2020') <= GETDATE() - @datePeriod



 

group by s.DATAAREAID,s.ITEMID,isnull(t1.lastdate,'03-01-2020'),m.UNITID,i.GOD_BRANDMANAGER_ID, i.GOD_INACTIVE, i.PmfProductType

Having sum(s.AVAILPHYSICAL) + sum(s.RESERVPHYSICAL) > 0


Sunday, September 27, 2020

DeadStock Items Lists

 static void DeadStock(Args _args)

{

    InventTrans         _trans,_trans1;

    InventSum           _sum;

    InventTransOrigin   _origin,_origin1;

    InventTable         _inventTable;

    TransDate           fromdate,todate ; 

    GH_DeadStockTable    deadStockTable;

    boolean             isvisible = false;


    fromdate  = mkDate(01,04,2020);

    todate    = mkDate(24,09,2020);

    

    ttsBegin;

    delete_from deadStockTable;

    ttsCommit;


    while select *  from _sum

        where   _sum.AvailPhysical   != 0

            //&&  _sum.ItemId          == 'BKK009'

    {

         select * from _trans

            join   count(RecId) from _origin

            where   _trans.DatePhysical         >= fromdate

                &&  _trans.DatePhysical         <= todate

                &&  _trans.ItemId               == _sum.ItemId

                &&  _trans.DatePhysical         != dateNull()

                &&  _trans.StatusIssue          != StatusIssue::OnOrder

                &&  _origin.RecId               == _trans.InventTransOrigin

                &&  _origin.ReferenceCategory   == InventTransType::Sales;


        if(_origin.RecId > 0)

        {

             continue;

        }

        else

        {

            deadStockTable.ItemId = _sum.ItemId;

            deadStockTable.AvailPhysical = _sum.AvailPhysical;

            deadStockTable.CostPrice = _sum.averageCostPrice();

            deadStockTable.insert();

           // info(strFmt("No transcation %1-%2-%3",_sum.ItemId,_sum.AvailPhysical,_sum.averageCostPrice()));

        }

    }

    info("Done");  


}

Thursday, July 9, 2020

Updating Customer Master and Financial Dimension through Excel Upload

static void GH_CustDimension_SalesGroup_Updating(Args _args)
{
    SysExcelApplication                 application;
    SysExcelWorkbooks                   workbooks;
    SysExcelWorkbook                    workbook;
    SysExcelWorksheets                  worksheets;
    SysExcelWorksheet                   worksheet;
    SysExcelCells                       cells;
    COMVariantType                      type;
    Filename                            filename;
    str                                 filePath, fileNameOnly;
    Dialog                              dialog;
    DialogField                         dialogFileName;
    int                                 row;
    container                           record, roles;

    CustTable                         _custTable;
    DimensionAttribute                _dimAttribute;
    DimensionAttributeValueSet        _dimAttributeSet;
    DimensionAttributeValueSetItem    _dimAttributeSetItem;
    DimensionAttributeValue           _dimValue;
    DimensionAttributeValueSetStorage _dimStorage;
    Common                            _dimensionValueEntry;
    CustAccount                       _custAccount;

    ;

    dialog = new Dialog();
    dialog.caption("Pick excel file");
    dialogFileName = dialog.addField(extendedTypeStr(FilenameOpen), "Enter excel file", "Browse excel file");

    if(!dialog.run())
        return;

    filename                = dialogFileName.value();
    [filePath,fileNameOnly] = fileNameSplit(filename);
    application             = SysExcelApplication::construct();
    workbooks               = application.workbooks();

    try
    {
        workbooks.open(filename);
    }
    catch (Exception::Error)
    {
        throw error(strFmt("Filename %1 cannot be blank.",filename));
    }

    workbook   = workbooks.item(1);
    worksheets = workbook.worksheets();
    worksheet  = worksheets.itemFromNum(1);
    cells      = worksheet.cells();

    row = 1;
    do
    {
        try
        {
            row++;
            _custAccount   = cells.item(row, 1).value().bStr();

            if(strLRTrim(cells.item(row, 1).value().bStr())!= "")
                {
                     select forUpdate _custTable where _custTable.AccountNum == _custAccount;
                    {
                         ttsBegin;
                         _custTable.SalesGroup           = 'TES';
                         _custTable.MainContactWorker    = 5637156776;
                         _dimStorage                     = DimensionAttributeValueSetStorage::find(_custTable.DefaultDimension);
                         _dimAttribute                   = DimensionAttribute::findByName("GH01_Salesman");
                         _dimValue                       = DimensionAttributeValue::findByDimensionAttributeAndValue(_dimAttribute, 'TES', true, true);
                         _dimStorage.addItem(_dimValue);
                         _custTable.DefaultDimension     = _dimStorage.save();
                         _custTable.doUpdate();
                        ttsCommit;
                    }
                }

            else
            {
                warning(strFmt("Row %1 not updated.", row));
            }
        }
        catch
        {
            error(strfmt("Row %1 not updated.", row));
        }
        type = cells.item(row+1, 1).value().variantType();
    }
    while (type != COMVariantType::VT_EMPTY);
    workbook.saved(true);
    application.visible(false);
    application.quit();

    info("Excel uploaded successfully");
}


excel sheet - Header name - CustomerAccount 

Wednesday, July 8, 2020

Changing Dimension

static void changeDimensionValue(Args _args)
{
    DimensionAttributeValueSetStorage dimensionAttributeValueSetStorage;
    DimensionAttribute dimensionAttribute;
    CustTable custTable = CustTable::find("C-04958");
    DimensionValue oldDimensionValue;
    DimensionValue newDimensionValue = "GRE";
    DimensionDefault newDimensionDefault;

    #define.dimensionName("GH01_Salesman")

    DimensionValue getDimensonValue(DimensionDefault _dimensionDefault)
    {
        DefaultDimensionView defaultDimensionView;
        select firstonly DisplayValue
        from defaultDimensionView
        where defaultDimensionView.Name == #dimensionName
            && defaultDimensionView.DefaultDimension == _dimensionDefault;

        return defaultDimensionView.DisplayValue;
    }

    // Get current value
    oldDimensionValue = getDimensonValue(custTable.DefaultDimension);

    // Build DimensionAttributeValueSetStorage
    dimensionAttributeValueSetStorage = DimensionAttributeValueSetStorage::find(custTable.DefaultDimension);

    // Remove old dimension value
    dimensionAttribute = DimensionAttribute::findByName(#dimensionName);
    dimensionAttributeValueSetStorage.removeDimensionAttributeValue(
        DimensionAttributeValue::findByDimensionAttributeAndValue(dimensionAttribute, oldDimensionValue).RecId);

    // Set new dimension value
    if(newDimensionValue != "")
    {
        dimensionAttribute = DimensionAttribute::findByName(#dimensionName);
        dimensionAttributeValueSetStorage.addItem(
            DimensionAttributeValue::findByDimensionAttributeAndValue(dimensionAttribute, newDimensionValue));
    }

    newDimensionDefault = dimensionAttributeValueSetStorage.save();

    ttsbegin;
    custTable.selectForUpdate(true);
    custTable.DefaultDimension = newDimensionDefault;
    custTable.update();
    ttscommit;
}

Customer Default dimension

static void GH_CustomerDetailsUpdate(Args _args)
{
    CustTable                        _custTable;
    DimensionAttribute               _dimAttribute;
    DimensionAttributeValueSet       _dimAttributeSet;
    DimensionAttributeValueSetItem   _dimAttributeSetItem;
    DimensionAttributeValue          _dimValue;
    Common                           dimensionValueEntry;
   
   
    _custTable = CustTable::find('C-01847');
   
    _dimAttributeSet = DimensionAttributeValueSet::find(_custTable.DefaultDimension);
   
    while select _dimAttributeSetItem
        where _dimAttributeSetItem.DimensionAttributeValueSet == _dimAttributeSet.RecId
       
    {
        _dimValue = DimensionAttributeValue::find(_dimAttributeSetItem.DimensionAttributeValue);
        _dimAttribute = DimensionAttribute::find(_dimValue.DimensionAttribute);
        dimensionValueEntry = DimensionDefaultingControllerBase::findBackingEntityInstance(curext(),_dimAttribute,_dimValue.EntityInstance);
        info(strFmt("Name %1, Value %2",_dimAttribute.Name +'' + _dimValue.getName(),_dimValue.getValue()));
    }
}

Customer Default dimension update

static void GH_CustomerUpdate(Args _args)
{
    CustTable                         _custTable;
    DimensionAttribute                _dimAttribute;
    DimensionAttributeValueSet        _dimAttributeSet;
    DimensionAttributeValueSetItem    _dimAttributeSetItem;
    DimensionAttributeValue           _dimValue;
    DimensionAttributeValueSetStorage _dimStorage;
    Common                            dimensionValueEntry;
   
     select forUpdate _custTable where _custTable.AccountNum == 'C-04856';
    {
        ttsBegin;
       
         _custTable.SalesGroup           = 'GRE';
         _custTable.MainContactWorker    = 5637156776;
         _dimStorage                     = DimensionAttributeValueSetStorage::find(_custTable.DefaultDimension);
         _dimAttribute                   = DimensionAttribute::findByName("GH01_Salesman");
         _dimValue                       = DimensionAttributeValue::findByDimensionAttributeAndValue(_dimAttribute, 'GRE', true, true);
         _dimStorage.addItem(_dimValue);
         _custTable.DefaultDimension     = _dimStorage.save();
         _custTable.doUpdate();
        ttsCommit;
       
   
    }
}

Customer Excel upload

static void GH_UploadCustomerRegion(Args _args)
{

    SysExcelApplication application;
    SysExcelWorkbooks   workbooks;
    SysExcelWorkbook    workbook;
    SysExcelWorksheets  worksheets;
    SysExcelWorksheet   worksheet;
    SysExcelCells       cells;
    int                 row;
    CommaTextIO         csvFile;
    container           readCon;
    counter             icount,updated;
    Dialog              dialog;
    DialogField         dfFileName;


    FileName            fileName;
    Name                name;

    DirPartyContactInfoView   contactView;
    CustTable                 CustTable;
    DirParty                  dirParty;
    DirPartyRecId             partyRecId;

    LogisticsPostalAddress    address;
    DirPartyPostalAddressView addressView;

    updated                  = 0;

    #File

    application = SysExcelApplication::construct();
    workbooks   = application.workbooks();
    dialog      = new Dialog("Pick the file");
    dfFileName  = dialog.addField(extendedTypeStr("FilenameOpen"));
    dialog.filenameLookupFilter(["All files", #AllFiles]);


    if (dialog.run())
    {
      fileName = dfFileName.value() ;
    try
    {
      workbooks.open(filename);
    }
    catch (Exception::Error)
    {
      throw error("File cannot be opened.");
    }

    workbook   = workbooks.item(1);
    worksheets = workbook.worksheets();
    worksheet  = worksheets.itemFromNum(1);
    cells      = worksheet.cells();

    ttsBegin;
    {

    row++;
    name       = strLRTrim(cells.item(row, 2).value().bStr());
    partyRecId = DirPartyTable::createNew( DirPartyType::Organization, name).RecId;

    custTable.clear();
    custTable.initValue();
    custTable.Party         = partyRecId;
    custTable.AccountNum    = strLRTrim(cells.item(row, 1).value().bStr());
    custTable.CustGroup     = strLRTrim(cells.item(row, 3).value().bStr());
    custTable.Currency      = strLRTrim(cells.item(row, 4).value().bStr());
    custTable.DlvMode       = strLRTrim(cells.item(row, 5).value().bStr());
    custTable.PaymTermId    = strLRTrim(cells.item(row, 6).value().bStr());
    custTable.update();

    custTable               = Custtable::find(strLRTrim(cells.item(row, 1).value().bStr()));
    partyRecId              = custTable.Party;

    DirParty                = DirParty::constructFromPartyRecId(partyRecId );
    address.clear();
    //address.PostBox = strLRTrim(conPeek(readCon,13));
    address.CountryRegionId = strLRTrim(cells.item(row, 7).value().bStr());
    if( address.CountryRegionId != "")
    {
        address.State           = strLRTrim(cells.item(row, 8).value().bStr());
        address.ZipCode         = strLRTrim(cells.item(row, 9).value().bStr());
        address.Street          = strLRTrim(cells.item(row, 10).value().bStr());
        address.City            = strLRTrim(cells.item(row, 11).value().bStr());

        //address.Address = conPeek(readCon,4);

        addressView.LocationName = "Address";
        addressView.IsPrimary    = NoYes::Yes;
        addressView.Party        = partyRecId;
        addressview.initFromPostalAddress(address);


        DirParty                 = DirParty::constructFromPartyRecId(addressView.Party );
        DirParty.createOrUpdatePostalAddress(addressView);
    }

    contactView.clear();

    if(strLRTrim(cells.item(row, 12).value().bStr()) != "")
    {
        contactView.LocationName = "Phone Number";
        contactView.Locator      = strLRTrim(cells.item(row, 12).value().bStr());
        contactView.Type         = LogisticsElectronicAddressMethodType::Phone;
        contactView.Party        = partyRecId;
        contactView.IsPrimary    = NoYes::Yes;
        dirParty.createOrUpdateContactInfo(contactView);
    }

    if(strLRTrim(cells.item(row, 13).value().bStr()) != "")
    {
        contactView.LocationName = "Fax Number";
        contactView.Locator      = strLRTrim(cells.item(row, 13).value().bStr());
        contactView.Type         = LogisticsElectronicAddressMethodType::Fax;
        contactView.Party        = partyRecId;
        contactView.IsPrimary    = NoYes::Yes;
        dirParty.createOrUpdateContactInfo(contactView);
    }

    if(strLRTrim(cells.item(row, 14).value().bStr()) != "")
    {
        contactView.LocationName = "Website";
        contactView.Locator      = strLRTrim(cells.item(row, 14).value().bStr());
        contactView.Type         = LogisticsElectronicAddressMethodType::URL;
        contactView.Party        = partyRecId;
        contactView.IsPrimary    = NoYes::Yes;
        dirParty.createOrUpdateContactInfo(contactView);
    }

    if(strLRTrim(cells.item(row, 15).value().bStr())!= "")
    {
        contactView.LocationName = "Email";
        contactView.Locator      = strLRTrim(cells.item(row, 15).value().bStr());
        contactView.Type         = LogisticsElectronicAddressMethodType::Email;
        contactView.Party        = partyRecId;
        contactView.IsPrimary    = NoYes::Yes;
        dirParty.createOrUpdateContactInfo(contactView);
    }



    }
    ttsCommit;
  }
}

Tuesday, January 7, 2020

X++ code for get exchange rate

static void ExchangeRateJob(Args _args)
{

    ExchangeRate     exchangeRate;
    ExchangeRateType ExchangeRateType;
    ExchangeRateCurrencyPair exchangeRateCurrencyPair;
    Amount4decimal             exchRate;

    CurrencyCode fromCurrency  = "USD";
    CurrencyCode toCurrency    = "AED";
    TransDate    transDate     = today();


    select firstonly exchangeRateCurrencyPair
    where
        exchangeRateCurrencyPair.ExchangeRateType == 5637145326
    &&  exchangeRateCurrencyPair.FromCurrencyCode == fromCurrency
    &&  exchangeRateCurrencyPair.ToCurrencyCode   == toCurrency;
    exchRate = exchangeRate::findByDate(exchangeRateCurrencyPair.RecId,transDate).ExchangeRate;
    info(strFmt("%1",exchRate/100));

}

X++ code for Updating main contact worker in customer master

static void UpdatingCustomerMaster(Args _args)
{
 CustTable   _custTable,custMaster;
 int         updatedCount;

 updatedcount = 0;

    ttsBegin;

    while select forUpdate _custTable
        where _custTable.MainContactWorker == 0  &&
              _custTable.SalesGroup == 'RAB'//'SHI'
    {
        _custTable.MainContactWorker = 5637158830;///5637158827;
        _custTable.update();
        updatedCount++;
    }
    ttsCommit;
    info(strFmt("No Of Records Updated:%1 ",updatedCount));
    info('done');
}

X++ code for upload excel through bank account

static void BankAccountUploadExcel(Args _args)
{
    #AviFiles
    FilenameOpen filename;
    dialogField dialogFilename,DialogJournalType;
    int jounaltype;
    Dialog dialog= new Dialog("Excel Upoad");
    Container excelCont[];
    RecId           offsetledger;
        RecId   recidh;
    HcmWorkerBankAccount HcmWorkerBankAccount;
    int rowIdx;
    Counter linesImported;
    int lastRow,dimcount;
    boolean ok = true;
    str c1,c2,c3,c4,c5,c6,c7,c8,c9,c10;
    str input;
    container       accEntryPattern;
    BudgetType      budgetType;
    SysExcelApplication application;
    SysExcelWorkBooks workBooks;
    SysExcelWorkSheets workSheets;
    SysExcelWorkSheet workSheet;
    SysExcelCells cells;
    SysOperationProgress progress;
    struct      struct= new Struct();
    HcmPersonIdentificationNumber   HcmPersonIdentificationNumber;
    BankAccountType                 BankAccountType;
    #define.CurrentVersion(1)
    #localmacro.CurrentList
    filename
    #endmacro

    #Excel
    #define.Star('*')
    #define.Space(' ')


    // convert into str from excel cell value
    str COMVariant2Str(COMVariant _cv, int _decimals = 0, int _characters = 0, int _separator1 = 0, int _separator2 = 0)
    {
        switch (_cv.variantType())
        {
            case (COMVariantType::VT_BSTR):
            return _cv.bStr();

            case (COMVariantType::VT_R4):
            return num2str(_cv.float(),_characters,_decimals,_separator1,_separator2);

            case (COMVariantType::VT_R8):
            return num2str(_cv.double(),_characters,_decimals,_separator1,_separator2);

            case (COMVariantType::VT_DECIMAL):
            return num2str(_cv.decimal(),_characters,_decimals,_separator1,_separator2);

            case (COMVariantType::VT_DATE):
            return date2str(_cv.date(),213,2,1,2,1,4);

            case (COMVariantType::VT_EMPTY):
            return "";

            default:
            throw error(strfmt("@SYS26908", _cv.variantType()));
        }
        return "";
    }

    // Find last row from excel

    int findLastRow(SysExcelWorkSheet _workSheet)
    {
        SysExcelRange range;
        ;

        range = _workSheet.cells().range(#ExcelTotalRange);

        try
        {
            // Finds the row where the first contents is found.
            range = range.find(#Star, null, #xlFormulas, #xlWhole, #xlByRows, #xlPrevious);
        }
        catch (Exception::Error)
        {
            error("@SYS59926");
            return 0;
        }

        if (range)
        {
            return range.row();
        }
        else
        {
            return 0;
        }
    }


    ;


    dialogFilename = dialog.addField(extendedtypestr(FilenameOpen));
   // DialogJournalType = dialog.addField(enumstr(God_JournalToUpload),"Journal Type");
    dialog.filenameLookupFilter(["@SYS28576",#XLS,#Xlsx]);
    dialog.filenameLookupTitle("Upload from Excel");
    dialogFilename.value(filename);

    if(!dialog.run())
    return;

    filename = dialogFilename.value();

   // ttsbegin;

    application = SysExcelApplication::construct();
    workBooks = application.workbooks();
    workBooks.open(filename,0,true);

    workSheets = workBooks.item(1).worksheets();
    // this.importExcel("Sheet1");

    input = "Sheet1";
    workSheet = workSheets.itemFromNum(1);//.itemFromName(input);
    cells = workSheet.cells();
    lastRow = findLastRow(workSheet);
    rowIdx = 2;

    progress = new SysOperationProgress();
    progress.setCaption("Excel Importing");
    progress.setTotal(lastRow);
    progress.setAnimation(#AviTransfer);
    setprefix("Excel Import");

    ttsBegin;
    while (rowIdx <= lastRow)
    {

        setPrefix(strfmt("Excel Row: %1", rowIdx));

        c1 = COMVariant2Str(cells.item(rowIdx,1).value());
        c2 = COMVariant2Str(cells.item(rowIdx,2).value());
        c3 = COMVariant2Str(cells.item(rowIdx,3).value());
        c4 = COMVariant2Str(cells.item(rowIdx,4).value());
        c5 = COMVariant2Str(cells.item(rowIdx,5).value());
        c6 = COMVariant2Str(cells.item(rowIdx,6).value());
        c7 = COMVariant2Str(cells.item(rowIdx,7).value());
        c8 = COMVariant2Str(cells.item(rowIdx,8).value());
        linesImported++;
        recidh = HcmWorker::findByPersonnelNumber(c1).recid;
        if (!HcmWorkerBankAccount::findByWorkerAccount(recidh, c3))//).ReconPeek(con, 6)).RecId)
        {
            HcmWorkerBankAccount.initValue();
            HcmWorkerBankAccount.AccountId      = c4;//conPeek(con, 25);
            HcmWorkerBankAccount.BankGroupId    = c2;//conPeek(con, 26c);
            HcmWorkerBankAccount.initFromBankGroup(BankGroup::find(c2));//conPeek(con, 26)));
            HcmWorkerBankAccount.AccountNum     = c3;//conPeek(con, 28);
            HcmWorkerBankAccount.Worker         = recidh;
            HcmWorkerBankAccount.GOD_IBANNumber = c5;  //GITL::377076:28082019 field added in table and assigned in job
            HcmWorkerBankAccount.BankAccountType = str2enum(BankAccountType,c6);
            HcmWorkerBankAccount.GOD_IsSalaryAcc = NoYes::Yes;
            HcmWorkerBankAccount.insert();
        }
        rowIdx++;
    }
    ttsCommit;

    info("done");
}

X++ code for Customer Ageing through Job

static void CustomerAgeingCode(Args _args)
{
    CustAgingReportTmp          custAgingReportTmp;
    GH_CustAgingReportTmp       _ageingMaster;
    Query                       query        = new Query();
    QueryBuildDataSource        queryBuildDataSource;
    QueryBuildRange             queryBuildRange;
    int                         i;
   // CustTable                   _custTable = CustTable::find("C-00001");
    CustAgingReportController   controller   = new CustAgingReportController();
    CustAgingReportContract     rdpContract  = new CustAgingReportContract ();
    CustAgingReportDP           dataProvider = new CustAgingReportDP();
    ;
    //contract class name
     rdpContract.parmZeroDate(today()); // Balance as of
     rdpContract.parmZeroDate(today()); // Start date
     rdpContract.parmDateTransactionDuedate(DateTransactionDuedate::TransactionDate);
     rdpContract.parmDetailed(NoYes::No); // Is Detail;
     rdpContract.parmAgingBuckets("0-30-60-90-120-120 plus days" );  // Aging period
     rdpContract.parmExcludeZeroBalanceCustomer(NoYes::Yes);
     rdpContract.parmDirection(ForwardBackwardPrinting::Forward);
     rdpContract.parmPeriod(DayMonth::Day);
    //Get data contract instance.
    controller.parmReportName(ssrsReportStr(CustAgingReport, DesignWithNoDetailAndWithTransactionCur));

    query = controller.parmReportContract().parmQueryContracts().lookup('CustAgingReportDP_DynamicParameter');
    query.dataSourceNo(1).clearRanges();
   // query.dataSourceNo(1).addRange(fieldNum(CustTable, AccountNum)).Value(SysQuery::value('C-00061')); //  GIVE CUSTOMER ACCOUNT

    //parameter that you passing in contract class
    query = dataProvider.parmQuery();
    query.dataSourceNo(1).addRange(fieldNum(CustTable, AccountNum)).Value(SysQuery::value('C-00061'));
    dataProvider.parmDataContract(rdpContract);
    dataProvider.processReport();
    custAgingReportTmp = dataProvider.getCustAgingReportTmp();

    while select custAgingReportTmp
     {
        // print(custAgingReportTmp.CustAccount);
        // Just print the filed that you want see the output
        // print(custAgingReportTmp.Name);
        info(strFmt("customer         - %1", custAgingReportTmp.CustAccount));
        info(strFmt("name             - %1", custAgingReportTmp.Name));
        info(strFmt("Total Receiable  - %1", custAgingReportTmp.Balance01));
        info(strFmt("Current Balance  - %1", custAgingReportTmp.Balance02));
        info(strFmt("30days           - %1", custAgingReportTmp.Balance03));
        info(strFmt("60days           - %1", custAgingReportTmp.Balance04));
        info(strFmt("90days           - %1", custAgingReportTmp.Balance05));
        info(strFmt("120days          - %1", custAgingReportTmp.Balance06));
        info(strFmt("+120days         - %1", custAgingReportTmp.Balance07));
     }


}