Wednesday, 20 January 2016

MultiSalesOrdersLineImportfromExcel through Job in ax 2012

static void MultiSalesOrdersLineImportfromExcel(Args _args)



{

SalesTable salesTable;

SalesLine salesLine;

InventDim inventDim;

Dialog _dialog;

DialogField _file;

NumberSeq num;

SysExcelApplication application;

SysExcelWorkbooks workbooks;

SysExcelWorkbook workbook;

SysExcelWorksheets worksheets;

SysExcelWorksheet worksheet,worksheet1;

SysExcelCells cells,cells1;

COMVariantType type;

int row;



;

row++;

application = SysExcelApplication::construct();

workbooks = application.workbooks();

_dialog = new Dialog("Please select the file to load");





//_dialog.addText("Select file:");



_file = _dialog.addField(ExtendedTypeStr("FilenameOpen"));



_dialog.run();

if (_dialog.closedOK())



{

info(_file.value() );

workbooks.open(_file.value());

}

workbook = workbooks.item(1);



worksheets = workbook.worksheets();

worksheet1 = worksheets.itemFromName("Lines");



cells1 = worksheet1.cells();

salesTable = SalesTable::find("LAZ-000004");





do



{

row++;

inventDim.clear();

inventDim.InventSiteId =cells1.item(row,6).value().bStr();//int2str(real2int(cells1.item(row,4).value().double()));

inventDim.InventLocationId =cells1.item(row,7).value().bStr(); //int2str(real2int(cells1.item(row,5).value().double()));

inventDim.InventSizeId =cells1.item(row,3).value().bStr();

inventDim.InventColorId =cells1.item(row,4).value().bStr();

inventDim.InventStyleId =cells1.item(row,5).value().bStr();





//inventDim.InventLocationId =cells1.item(row,5).value().bStr();



salesLine.clear();

salesLine.initValue(salesTable.SalesType);

salesLine.initFromSalesTable(salesTable);

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

salesLine.initFromInventTable(InventTable::find(cells1.item(row, 1).value().bStr()));



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

salesLine.RetailVariantId =cells1.item(row,2).value().bStr();

salesLine.SalesQty = any2int(cells1.item(row,8).value().toString());



salesLine.RemainSalesPhysical = salesLine.SalesQty;

salesLine.SalesUnit = cells1.item(row,9).value().bStr();



salesLine.QtyOrdered = salesLine.calcQtyOrdered();

salesLine.RemainInventPhysical = salesLine.QtyOrdered;

//salesLine.setPriceDisc(InventDim::find(salesLine.InventDimId));



salesLine.PriceUnit =any2int(cells1.item(row,10).value().toString());

salesLine.LineAmount = any2int(cells1.item(row,11).value().toString());

salesLine.MRKPCommentsLoc = cells1.item(row,12).value().bStr();

salesLine.MRKPDetails = cells1.item(row,13).value().bStr();





//salesLine.deliveryDate = cells1.item(row,14).value().date();

//salesLine.DeliveryName = cells1.item(row,15).value().bStr(); //fin dimension should come here

//salesLine.MRKPDetails = cells1.item(row,16).value().bStr();



salesLine.MRKPDetails = cells1.item(row,17).value().bStr();

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

if (salesLine.validateWrite())



{

salesLine.insert();

}

}

while (type != COMVariantType::VT_EMPTY);



workbooks.close();

application.quit();

info("Done!");



}


Wednesday, 6 January 2016

Alrert for while creating Purchase Order this alert went to Original Requisitioner and po creater..in ax 2012

class DEVUtils
{
}
////
public static void CreateAlert(str message,
               str subject,
               UserId userId = curUserId(),
               NoYes showPopup = NoYes::Yes,
               NoYes sendEmail = NoYes::No,
               Common record = null,
               str dataSourcename = '',
               MenuFunction menuFunction = null)
 {
   EventInbox inbox;
   DictTable table;
   EventContextInformation eci;
   EventInboxData inboxData;
   Args args = new Args();
   List list;
   EventInboxId inboxId = EventInbox::nextEventId();
   FormRun formRun;
   WorkflowRecordCaptionGenerator recordCaptionGenerator;
   UserInfo userInfo;
   inboxId = EventInbox::nextEventId();
   inbox.initValue();
   inbox.ShowPopup      = showPopup;
   inbox.Subject       = subject;
   inbox.Message       = message;
   inbox.SendEmail      = sendEmail;
   inbox.EmailRecipient    = SysUserInfo::find().Email;
   inbox.UserId        = userId;
   inbox.InboxId       = inboxId;
   inbox.AlertCreatedDateTime = DateTimeUtil::getSystemDateTime();
   if (record)
   {
     table = new DictTable(record.TableId);
     eci = new EventContextInformation();
     if (!menuFunction)
     {
       menuFunction = new MenuFunction(table.formRef(),MenuItemType::Display);
       if (!menuFunction)
         throw error(strFmt("@SYS104114",table.formRef()));
     }
     //Build the data to drill down to from the notification
     args.menuItemName(menuFunction.name());
     args.menuItemType(MenuItemType::Display);
     args.name(menuFunction.object());
     eci.parmPackedArgs(args);
     eci.parmAlertBuffer(record);
     eci.parmAlertFormDsName(dataSourceName);
     //eci.parmDontUseFormRunFromMenuItem(true);
     inboxData.InboxId = inboxId;
     inboxData.DataType = EventInboxDataType::Context;
     inboxData.Data = eci.pack();
     inboxData.insert();
     inbox.AlertTableId = table.id();
     inbox.ParentTableId = table.id();
     recordCaptionGenerator = WorkflowRecordCaptionGenerator::construct(record);
     inbox.AlertedFor = recordCaptionGenerator.caption();
     list = SysDictTable::getUniqueIndexFields(table.id());
     if (list)
     {
       inbox.keyFieldList(list.pack());
       inbox.keyFieldData(SysDictTable::mapFieldIds2Values(list,record).pack());
     }
     inbox.CompanyId = record.company();
   }
   inbox.insert();
 }
//////
public static void POCreateAlert(
                //str message,
               //str subject,
               //UserId userId = curUserId(),
               //NoYes showPopup = NoYes::Yes,
               //NoYes sendEmail = NoYes::No,
               PurchTable _PurchTable,
               Common record = null,
               str dataSourcename = '',
               MenuFunction menuFunction = null)
 {
   EventInbox inbox;
   DictTable table;
   EventContextInformation eci;
   EventInboxData inboxData;
   Args args = new Args();
   List list;
   EventInboxId inboxId = EventInbox::nextEventId();
   FormRun formRun;
   WorkflowRecordCaptionGenerator recordCaptionGenerator;
   UserInfo userInfo;
    UserGroupList           groupList;
    usergroupinfo           usergroupinfo;
    ;
    select Name,generalInfo from UserInfo where UserInfo.id == curUserId();
    //while  select * from groupList where
                         //groupList.groupId ==PurchParameters::find().MRKPAlertgroupId
     //{
               inboxId = EventInbox::nextEventId();
               inbox.initValue();
               inbox.ShowPopup      = NoYes::Yes;
               inbox.Subject       = "This Alert For Purchase order creation:"+ _purchTable.PurchId;
               inbox.Message       = "New purchase order" + _purchTable.PurchId +" has been created by: " + UserInfo.name;
               inbox.SendEmail      = NoYes::No;
               inbox.EmailRecipient    = SysUserInfo::find().Email;
               inbox.UserId        = DirPersonUser::worker2UserId(_purchTable.Requester);
               inbox.InboxId       = inboxId;
               inbox.AlertCreatedDateTime = DateTimeUtil::getSystemDateTime();
               if (record)
               {
                 table = new DictTable(record.TableId);
                 eci = new EventContextInformation();
                 if (!menuFunction)
                 {
                   menuFunction = new MenuFunction(table.formRef(),MenuItemType::Display);
                   if (!menuFunction)
                     throw error(strFmt("@SYS104114",table.formRef()));
                 }
                 //Build the data to drill down to from the notification
                 args.menuItemName(menuFunction.name());
                 args.menuItemType(MenuItemType::Display);
                 args.name(menuFunction.object());
                 eci.parmPackedArgs(args);
                 eci.parmAlertBuffer(record);
                 eci.parmAlertFormDsName(dataSourceName);
                 //eci.parmDontUseFormRunFromMenuItem(true);
                 inboxData.InboxId = inboxId;
                 inboxData.DataType = EventInboxDataType::Context;
                 inboxData.Data = eci.pack();
                 inboxData.insert();
                 inbox.AlertTableId = table.id();
                 inbox.ParentTableId = table.id();
                 recordCaptionGenerator = WorkflowRecordCaptionGenerator::construct(record);
                 inbox.AlertedFor = recordCaptionGenerator.caption();
                 list = SysDictTable::getUniqueIndexFields(table.id());
                 if (list)
                 {
                   inbox.keyFieldList(list.pack());
                   inbox.keyFieldData(SysDictTable::mapFieldIds2Values(list,record).pack());
                 }
                 inbox.CompanyId = record.company();
               }
               inbox.insert();
   //  }
 }
////
public static void PRCreateAlert(
                //str message,
               //str subject,
               //UserId userId = curUserId(),
               //NoYes showPopup = NoYes::Yes,
               //NoYes sendEmail = NoYes::No,
               PurchReqTable _PurchReqTable,
               Common record = null,
               str dataSourcename = '',
               MenuFunction menuFunction = null)
 {
   EventInbox inbox;
   DictTable table;
   EventContextInformation eci;
   EventInboxData inboxData;
   Args args = new Args();
   List list;
   EventInboxId inboxId = EventInbox::nextEventId();
   FormRun formRun;
   WorkflowRecordCaptionGenerator recordCaptionGenerator;
   UserInfo userInfo;
    UserGroupList           groupList;
    usergroupinfo           usergroupinfo;
    ;
    select Name,generalInfo from UserInfo where UserInfo.id == curUserId();
    while  select * from groupList where
                         groupList.groupId ==PurchParameters::find().MRKPAlertgroupId
     {
               inboxId = EventInbox::nextEventId();
               inbox.initValue();
               inbox.ShowPopup      = NoYes::Yes;
               inbox.Subject       = "This Alert For Purchase requisition '"+ _purchReqTable.PurchReqId +"' requisition submitted";
               inbox.Message       = "The Purchase requisition '"+ _purchReqTable.PurchReqId +"'has been submitted by:"+ userInfo.name ;
               inbox.SendEmail      = NoYes::No;
               inbox.EmailRecipient    = SysUserInfo::find().Email;
               inbox.UserId        = groupList.userId;
               inbox.InboxId       = inboxId;
               inbox.AlertCreatedDateTime = DateTimeUtil::getSystemDateTime();
               if (record)
               {
                 table = new DictTable(record.TableId);
                 eci = new EventContextInformation();
                 if (!menuFunction)
                 {
                   menuFunction = new MenuFunction(table.formRef(),MenuItemType::Display);
                   if (!menuFunction)
                     throw error(strFmt("@SYS104114",table.formRef()));
                 }
                 //Build the data to drill down to from the notification
                 args.menuItemName(menuFunction.name());
                 args.menuItemType(MenuItemType::Display);
                 args.name(menuFunction.object());
                 eci.parmPackedArgs(args);
                 eci.parmAlertBuffer(record);
                 eci.parmAlertFormDsName(dataSourceName);
                 //eci.parmDontUseFormRunFromMenuItem(true);
                 inboxData.InboxId = inboxId;
                 inboxData.DataType = EventInboxDataType::Context;
                 inboxData.Data = eci.pack();
                 inboxData.insert();
                 inbox.AlertTableId = table.id();
                 inbox.ParentTableId = table.id();
                 recordCaptionGenerator = WorkflowRecordCaptionGenerator::construct(record);
                 inbox.AlertedFor = recordCaptionGenerator.caption();
                 list = SysDictTable::getUniqueIndexFields(table.id());
                 if (list)
                 {
                   inbox.keyFieldList(list.pack());
                   inbox.keyFieldData(SysDictTable::mapFieldIds2Values(list,record).pack());
                 }
                 inbox.CompanyId = record.company();
               }
               inbox.insert();
     }
 }
////
public static void StockChangeAlert(
                //str message,
               //str subject,
               //UserId userId = curUserId(),
               //NoYes showPopup = NoYes::Yes,
               //NoYes sendEmail = NoYes::No,
               SalesTable _SalesTable,
               Common record = null,
               str dataSourcename = '',
               MenuFunction menuFunction = null)
 {
   EventInbox inbox;
   DictTable table;
   EventContextInformation eci;
   EventInboxData inboxData;
   Args args = new Args();
   List list;
   EventInboxId inboxId = EventInbox::nextEventId();
   FormRun formRun;
   WorkflowRecordCaptionGenerator recordCaptionGenerator;
   UserInfo userInfo;
    UserGroupList           groupList;
    usergroupinfo           usergroupinfo;
    ;
    select Name,generalInfo from UserInfo where UserInfo.id == curUserId();
    //while  select * from groupList where
                         //groupList.groupId ==PurchParameters::find().MRKPAlertgroupId
     //{
               inboxId = EventInbox::nextEventId();
               inbox.initValue();
               inbox.ShowPopup      = NoYes::Yes;
               inbox.Subject       = "This Alert For manual stock change in SRP :"+ _salesTable.SalesId;
               inbox.Message       = "Stock request pool '" + _salesTable.SalesId +"'stock has been modified by: " + UserInfo.name;
               inbox.SendEmail      = NoYes::No;
               inbox.EmailRecipient    = SysUserInfo::find().Email;
               inbox.UserId        = DirPersonUser::worker2UserId(_salesTable.Requester);
               inbox.InboxId       = inboxId;
               inbox.AlertCreatedDateTime = DateTimeUtil::getSystemDateTime();
               if (record)
               {
                 table = new DictTable(record.TableId);
                 eci = new EventContextInformation();
                 if (!menuFunction)
                 {
                   menuFunction = new MenuFunction(table.formRef(),MenuItemType::Display);
                   if (!menuFunction)
                     throw error(strFmt("@SYS104114",table.formRef()));
                 }
                 //Build the data to drill down to from the notification
                 args.menuItemName(menuFunction.name());
                 args.menuItemType(MenuItemType::Display);
                 args.name(menuFunction.object());
                 eci.parmPackedArgs(args);
                 eci.parmAlertBuffer(record);
                 eci.parmAlertFormDsName(dataSourceName);
                 //eci.parmDontUseFormRunFromMenuItem(true);
                 inboxData.InboxId = inboxId;
                 inboxData.DataType = EventInboxDataType::Context;
                 inboxData.Data = eci.pack();
                 inboxData.insert();
                 inbox.AlertTableId = table.id();
                 inbox.ParentTableId = table.id();
                 recordCaptionGenerator = WorkflowRecordCaptionGenerator::construct(record);
                 inbox.AlertedFor = recordCaptionGenerator.caption();
                 list = SysDictTable::getUniqueIndexFields(table.id());
                 if (list)
                 {
                   inbox.keyFieldList(list.pack());
                   inbox.keyFieldData(SysDictTable::mapFieldIds2Values(list,record).pack());
                 }
                 inbox.CompanyId = record.company();
               }
               inbox.insert();
   //  }
 }










///
///----then method call in PURCH auto Create Class in Create Method-----///



//PurchAutoCreate Class//
void  create()
{
    MRKPAlertCreate     alertCreate;
    #OCCRetryCount
    try
    {
        setprefix("@SYS28446");
        ttsbegin;
        this.setVend();
        setprefix(#PreFixField(VendTable,AccountNum));
        this.setPurchTable();
        this.createPurchTable();
        this.createLines();
        this.endUpdate();
        ttscommit;
        if (this.showInfo())
            info(strfmt("@SYS82024", purchTable.PurchId),'', SysInfoAction_TableField::newBuffer(purchTable));
        //<----------------------------------------------------added by murugan.p------------------------------------------------->
        DEVUtils::POCreateAlert(purchTable,purchTable,"PurchTable", new MenuFunction(menuitemDisplayStr(PurchTable), MenuItemType::Display));
        //<----------------------------------------------------------end---------------------------------------------------------->
    }
    catch (Exception::Deadlock)
    {
        retry;
    }
    catch (Exception::UpdateConflict)
    {
        if (appl.ttsLevel() == 0)
        {
            if (xSession::currentRetryCount() >= #RetryNum)
            {
                throw Exception::UpdateConflictNotRecovered;
            }
            else
            {
                retry;
            }
        }
        else
        {
            throw Exception::UpdateConflict;
        }
    }
}

Saturday, 19 December 2015

Inventory Movement Journals import through excel with job in ax 2012 r3

Inventory Movement Journals import through excel  with job in ax 2012 r3
-------
[Here we need to  check item having site,colour,size ,configuration if not having item these values not enter into Excel t job is working fine otherwise u get errors item is not created like that.]so what r  the fields ur mapped those filed values are there in ax level]
-----


static void InventoryMovementJournal(Args _args)//InventoryClosingImportJob(Args _args)
 {
      InventJournalTable journalTable;
     InventJournalTrans journalTrans;
     InventJournalTableData journalTableData;
     InventJournalTransData journalTransData;
     InventTable inventTable;
     InventDim locInventDim;
     Counter cnt;
     ItemId                 ItemIdstr;//, Itemid;
     InventSiteId            inventSiteId;
     InventLocationId        inventLocationId;
     InventColorTxt          inventColor;
     str           inventSize,InventStyle,Itemid;
     InventBatchId           inventBatchId;
     InventQtyJournal        qty;
     ItemCostPrice           costprice;
     LedgerDimensionDefaultAccount   mainacc;
     str                20     mainaccStr;
     str                50      Text;
     container            offSetEntryPattern;
     LedgerJournalId               JournalId;
     SysExcelApplication             application;
     SysExcelWorkbooks               workbooks;
     SysExcelWorkbook                workbook;
     SysExcelWorksheets              worksheets;
     SysExcelWorksheet               worksheet;
     SysExcelCells                   cells;
     COMVariantType                  type;
     FilenameOpen                    filename;
     dialogField                     dialogFilename;
     Dialog                          dialog;
     Integer                         row = 1;
     int     coun;
     Mainaccount     mainaccount;
     int   _mainaccountnum; //= "111200";//"202000";
     Ledger          ledger;
     CompanyInfo     companyinfo;

     str COMVariant2Str(COMVariant       _cv)
     {
         switch (_cv.variantType())
         {
             case (COMVariantType::VT_BSTR):
                 return _cv.bStr();
             case (COMVariantType::VT_R8):
               //  return _cv.toString() ;
                 return _cv.bStr() ;
             case (COMVariantType::VT_DATE):
                 return date2str(_cv.date(),123,2,1,2,1,4);
             case (COMVariantType::VT_EMPTY):
                 return '';
             default:
                 throw error(strfmt("@SYS26908", _cv.variantType()));
         }
     }
     ;
     dialog              =   new Dialog('Import Vendor Details');
     dialogFilename      =   dialog.addField(ExtendedTypeStr("FilenameOpen"));
     dialog.filenameLookupTitle('Import from excel.');
     dialog.caption('Import From Excel');
     dialogFilename.value(filename);
     if(dialog.run())
     {
         filename            =   dialogFilename.value();
         application         =   SysExcelApplication::construct();
         workbooks           =   application.workbooks();
         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();
         try
         {
             ttsbegin;
             // NOTE - JOURNAL ID MUST BE CHANGED BEFORE IMPORT
             Select journalTable Where journalTable.JournalId =="WW-000077"; //CHANGE JOURNAL ID HERE
             do
             {
                 row++;
             JournalId                               = cells.item(row, 1).value().bStr();
             inventSiteId                            = cells.item(row, 2).value().bStr();
             inventLocationId                        = cells.item(row, 3).value().bStr();
             inventSize                              = cells.item(row, 4).value().bStr();
             inventColor                             = cells.item(row, 5).value().bStr();
             inventStyle                             = cells.item(row, 6).value().bStr();
             qty                                     = cells.item(row, 7).value().double();
             costPrice                               = cells.item(row, 8).value().double();
             _mainAccountNum                         = cells.item(row, 9).value().double();
              mainAccstr                              = int2str(_mainaccountnum);
             //department                            = cells.item(row, 8).value().bStr();
             itemId                                  = cells.item(row, 10).value().bStr(); //cells.item(row, 10).value().bStr();
             //itemIdstr                                  = int2str(itemId);
             type = cells.item(row+1, 1).value().variantType();
             select recId from MainAccount where mainAccount.MainAccountId ==mainAccstr;
             locInventDim.inventBatchId              = inventBatchId;
             locInventDim.InventSiteId               = inventSiteId;
             locInventDim.InventLocationId           = inventLocationId;
             locInventDim.InventSizeId               = inventSize;
             locInventDim.InventColorId              = inventColor;
             locInventDim.InventStyleId              = inventStyle;
             locInventDim.configId                   = inventStyle; //as Config id
             journalTrans.clear();
             journalTrans.initFromInventJournalTable(journalTable);
             journalTrans.TransDate                  = cells.item(row, 8).value().date();//systemDateGet();
             journalTrans.ItemId                     = itemId;
             journalTrans.JournalId                  = journalTable.JournalId;//JournalId;//
             //Finding out the invent dim id from given value
             journalTrans.InventDimId                = InventDim::findOrCreate(locInventDim).inventDimId;
             journalTrans.PriceUnit                  = 1;
             journalTrans.Qty                        = qty;
             journalTrans.CostPrice                  = costPrice;
             journalTrans.CostAmount                 = journalTrans.Qty * journalTrans.CostPrice;
             journalTrans.LedgerDimension            = DimensionStorage::getDefaultAccountForMainAccountNum(mainAccstr);
             //Except these below two lines above things are same as like in dynamics AX 2009
             //If you want to insert the dimension value with account
             //In below code I have no dimension with main account so I just put 0, Instead I have two
             //dimension
             //write a code like “[“MainAccount”, mainAcc, 2, Dinemsion1, dimVal1, Dimension2, dimVal2)
             // offsetEntryPattern                                      = [mainAccstr,0,0];
             // journalTrans.LedgerDimension              = AxdDimensionUtil::getLedgerAccountId(offsetEntryPattern);
             //Default dimension Value either you can insert the dimension value here.
             //defaultDim                                                     = [1,"Department",department];
             //journalTrans.DefaultDimension             =        AxdDimensionUtil::getDimensionAttributeValueSetId(defaultDim);
             journalTrans.insert();
             coun++;
             print(coun);
             }
             while (type != COMVariantType::VT_EMPTY);
             info(int2str(coun));
             ttscommit;
             application.quit();
         }
         catch
         {
             throw error('Error in import.');
         }
     }
 }

Make Financial Dimensions mandatory through code for perticular Form

InventJournalMopvementForm::


InventJournalTransTable- ValidateWrite method
Description::[Here actually record getting based on JournalNameId field-Inventmovent value so goto setup see the field like JournalType  but we need to get JournalId based so we use find method then put if inthat  create buffer and JournalNameId field and type in tat again put If condition defaultDimension as 0, then write validation]


/ <MRKP-Janardhan-19122015>
    inventJournalTableLoc = InventJournalTable::find(InventJournalTrans.JournalId);
    if(InventJournalName::find(inventJournalTableLoc.JournalNameId).JournalType == InventJournalType::Movement)
    {
        if(InventJournalTrans.DefaultDimension == 0)
        {
         // isValid = checkFailed(strFmt("@MRK495"));
         //  info("Please fill the default dimension");
              throw error("Please fill the default dimensions");
        }
    }

Friday, 25 September 2015

Product Classification Updation bsaed on Product and how give the range for the Item

static void updateProductClasification(Args _args)
{
    EcoResProduct   ecoResProduct;
   
  
 while select forUpdate SearchName,DisplayProductNumber,WW_Category from ecoResProduct
     where  ecoResProduct.DisplayProductNumber >= '11001' &&  ecoResProduct.DisplayProductNumber <='11142'
  {
   
   ttsBegin;
     ecoResProduct.WW_Category = WW_Category::Stock;
     ecoResProduct.update();
   ttsCommit;  
    }
  }