/// <summary> /// function to create window /// </summary> /// <param name="DisplayName">name of window</param> /// <returns>int (Window ID)</returns> private int CreateVerWindow(string DisplayName, string TabName) { // create new version window MWindow verWnd = new MWindow(GetCtx(), 0, Get_TrxName()); verWnd.SetName(DisplayName + "_" + TabName); verWnd.SetDisplayName(DisplayName); // set window as Query Only verWnd.SetWindowType("Q"); verWnd.SetDescription("Display version data"); verWnd.SetHelp("The window allows you to view past data versioning and future updation versions (if any)."); if (!verWnd.Save()) { ValueNamePair vnp = VLogger.RetrieveError(); string error = ""; if (vnp != null) { error = vnp.GetName(); if (error == "" && vnp.GetValue() != null) { error = vnp.GetValue(); } } if (error == "") { error = "Error in creating Version Window"; } log.Log(Level.SEVERE, "Version Window not Created :: " + DisplayName + " :: " + error); Get_TrxName().Rollback(); return(0); } // Return Window ID return(verWnd.GetAD_Window_ID()); }
/// <summary> /// Create default columns for Master Data Version Table /// e.g. Processed, Processing, IsApproved etc. /// </summary> /// <param name="Ver_AD_Table_ID"></param> /// <returns></returns> private string CreateDefaultVerCols(int Ver_AD_Table_ID) { for (int i = 0; i < listDefVerCols.Count; i++) { MColumn colVer = new MColumn(GetCtx(), 0, _trx); colVer.SetExport_ID(null); colVer.SetAD_Table_ID(Ver_AD_Table_ID); colVer.SetColumnName(listDefVerCols[i]); colVer.SetAD_Element_ID(_listDefVerElements[i]); colVer.SetAD_Reference_ID(listDefVerRef[i]); //if (listDefVerCols[i] == "VersionValidFrom") // colVer.SetIsParent(true); if (listDefVerRef[i] == 10) { colVer.SetFieldLength(10); } if (listDefVerRef[i] == 14) { colVer.SetFieldLength(2000); } if (listDefVerRef[i] == 13) { colVer.SetIsKey(true); colVer.SetIsMandatory(true); colVer.SetIsMandatoryUI(true); } if (!colVer.Save()) { ValueNamePair vnp = VLogger.RetrieveError(); string error = ""; if (vnp != null) { error = vnp.GetName(); if (error == "" && vnp.GetValue() != null) { error = vnp.GetValue(); } } if (error == "") { error = "Error in creating Version Column " + listDefVerCols[i]; } log.Log(Level.SEVERE, "Version Column not created :: " + listDefVerCols[i] + " :: " + error); _trx.Rollback(); return(Msg.GetMsg(GetCtx(), "VersionColNotCreated")); } } return(""); }
/// <summary> /// function to create tab against Version Window /// </summary> /// <param name="tab">Object of MTab</param> /// <param name="ver_AD_Window_ID">Version Window ID</param> /// <param name="Ver_AD_Table_ID">Version Table ID</param> /// <returns>int (Version Tab ID)</returns> private int CreateVerTab(MTab tab, int ver_AD_Window_ID, int Ver_AD_Table_ID) { MTab verTab = new MTab(GetCtx(), 0, Get_TrxName()); // copy Master table tab to Version tab tab.CopyTo(verTab); verTab.SetAD_Window_ID(ver_AD_Window_ID); verTab.SetAD_Table_ID(Ver_AD_Table_ID); verTab.SetIsReadOnly(false); verTab.SetIsInsertRecord(false); verTab.SetIsSingleRow(true); verTab.SetWhereClause(null); verTab.SetSeqNo(10); verTab.SetAD_Column_ID(0); verTab.SetTabLevel(0); verTab.SetExport_ID(null); verTab.SetDescription("Version tab for " + tab.GetName()); verTab.SetHelp("Version tab for " + tab.GetName() + ", to display versions for current record"); // set order by on Version Window's tab on "Version Valid From column" verTab.SetOrderByClause("VersionValidFrom DESC, RecordVersion DESC"); if (!verTab.Save()) { ValueNamePair vnp = VLogger.RetrieveError(); string error = ""; if (vnp != null) { error = vnp.GetName(); if (error == "" && vnp.GetValue() != null) { error = vnp.GetValue(); } } if (error == "") { error = "Error in creating Version Tab"; } log.Log(Level.SEVERE, "Version Tab not Created :: " + tab.GetName() + " :: " + error); Get_TrxName().Rollback(); return(0); } else { CreateVerTabPanel(verTab); } return(verTab.GetAD_Tab_ID()); }
/// <summary> /// Save New User and organization accesses provided to it. /// </summary> /// <param name="Name"></param> /// <param name="Email"></param> /// <param name="Value"></param> /// <param name="password"></param> /// <param name="mobile"></param> /// <param name="OrgID"></param> /// <returns></returns> public String SaveNewUser(string Name, string Email, string Value, string password, string mobile, List <int> OrgID) { string msg; string info = ""; MUser user = new MUser(ctx, 0, null); user.SetName(Name); user.SetIsLoginUser(true); user.SetEMail(Email); if (!string.IsNullOrEmpty(password)) { string key = ctx.GetSecureKey(); password = SecureEngineBridge.DecryptByClientKey(password, key); user.SetPassword(password); } if (!String.IsNullOrEmpty(mobile)) { user.SetMobile(mobile); } if (!string.IsNullOrEmpty(Value)) { user.SetValue(Value); } if (user.Save()) { if (OrgID != null) { for (int i = 0; i < OrgID.Count; i++) { MOrg org = new MOrg(ctx, OrgID[i], null); MUserOrgAccess roles = new MUserOrgAccess(org, user.GetAD_User_ID()); roles.SetAD_Client_ID(ctx.GetAD_Client_ID()); roles.SetAD_Org_ID(OrgID[i]); roles.SetIsReadOnly(false); roles.Save(); } } } else { ValueNamePair ppE = VAdvantage.Logging.VLogger.RetrieveError(); if (ppE != null) { msg = ppE.GetValue(); info = ppE.GetName(); } } return(info); }
protected override string DoIt() { try { _log.Info("Foreign Cost Calculation start at : " + DateTime.Now); // Calculate Foreign Cost for Average Invoice sql = @"SELECT i.c_invoice_id , il.c_invoiceline_id FROM c_invoice i INNER JOIN c_invoiceline il ON i.c_invoice_id = il.c_invoice_id WHERE il.isactive = 'Y' AND il.isfuturecostcalculated = 'N' AND i.isfuturecostcalculated = 'N' AND docstatus IN ('CO' , 'CL') AND i.issotrx = 'N' AND i.isreturntrx = 'N' AND NVL(il.m_inoutline_ID , 0) <> 0 ORDER BY i.c_invoice_id ASC"; ds = DB.ExecuteDataset(sql, null, null); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { _log.Info("Foreign Cost Calculation : Average Invoice Record : " + ds.Tables[0].Rows.Count); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { try { invoice = new MInvoice(GetCtx(), Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_invoice_id"]), Get_Trx()); invoiceLine = new MInvoiceLine(GetCtx(), Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_invoiceline_id"]), Get_Trx()); if (!MCostForeignCurrency.InsertForeignCostAverageInvoice(GetCtx(), invoice, invoiceLine, Get_Trx())) { Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); _log.Info("Error found for calcualting Av. Invoice Foreign Cost for this record ID = " + invoice.GetDocumentNo() + " Error Name is " + pp.GetName() + " And Error Value is " + pp.GetValue()); continue; } else { if (Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(*) FROM C_InvoiceLine WHERE IsFutureCostCalculated = 'N' AND C_Invoice_ID = " + invoice.GetC_Invoice_ID(), null, Get_Trx())) <= 0) { int no = Util.GetValueOfInt(DB.ExecuteQuery("UPDATE C_Invoice Set IsFutureCostCalculated = 'Y' WHERE C_Invoice_ID = " + invoice.GetC_Invoice_ID(), null, Get_Trx())); } Get_Trx().Commit(); } } catch (Exception ex1) { } } } // Calculate Foriegn Cost for Average PO sql = @"SELECT i.m_inout_id , il.m_inoutline_id , il.c_orderline_id FROM m_inout i INNER JOIN m_inoutline il ON i.m_inout_id = il.m_inout_id WHERE il.isactive = 'Y' AND il.isfuturecostcalculated = 'N' AND i.isfuturecostcalculated = 'N' AND docstatus IN ('CO' , 'CL') AND i.issotrx = 'N' AND i.isreturntrx = 'N' AND NVL(il.c_orderline_ID , 0) <> 0 ORDER BY i.m_inout_id ASC"; ds = DB.ExecuteDataset(sql, null, null); if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { _log.Info("Foreign Cost Calculation : Average PO Record : " + ds.Tables[0].Rows.Count); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { try { orderLine = new MOrderLine(GetCtx(), Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_orderline_id"]), Get_Trx()); order = new MOrder(GetCtx(), orderLine.GetC_Order_ID(), Get_Trx()); inoutLine = new MInOutLine(GetCtx(), Util.GetValueOfInt(ds.Tables[0].Rows[i]["m_inoutline_id"]), Get_Trx()); if (!MCostForeignCurrency.InsertForeignCostAveragePO(GetCtx(), order, orderLine, inoutLine, Get_Trx())) { Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); _log.Info("Error found for calcualting Av. PO Foreign Cost for this record ID = " + inoutLine.GetM_InOut_ID() + " Error Name is " + pp.GetName() + " And Error Value is " + pp.GetValue()); continue; } else { if (Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(*) FROM M_InoutLine WHERE IsFutureCostCalculated = 'N' AND M_InOut_ID = " + inoutLine.GetM_InOut_ID(), null, Get_Trx())) <= 0) { int no = Util.GetValueOfInt(DB.ExecuteQuery("UPDATE M_Inout Set IsFutureCostCalculated = 'Y' WHERE M_Inout_ID = " + inoutLine.GetM_InOut_ID(), null, Get_Trx())); } Get_Trx().Commit(); } } catch (Exception ex2) { } } } } catch (Exception ex) { } _log.Info("Foreign Cost Calculation End : " + DateTime.Now); return(Msg.GetMsg(GetCtx(), "SuccessFullyCompleted")); }
/// <summary> /// Insert data in Version table against multikey Master table /// </summary> /// <param name="baseTbl"></param> /// <param name="keyCols"></param> /// <param name="tblVer"></param> /// <returns></returns> private string InsertMKVersionData(MTable baseTbl, string[] keyCols, MTable tblVer) { string retMsg = ""; // Get data from Master table DataSet dsRecs = DB.ExecuteDataset("SELECT * FROM " + baseTbl.GetTableName(), null, _trx); // check if there are any records in master table if (dsRecs != null && dsRecs.Tables[0].Rows.Count > 0) { // loop through all records and insert in Version table for (int i = 0; i < dsRecs.Tables[0].Rows.Count; i++) { // get where Clause for Master table against multiple key columns GetMKWhereClause(dsRecs.Tables[0].Rows[i], keyCols); if (MKWhereClause.Length > 0) { int count = Util.GetValueOfInt(DB.ExecuteScalar("SELECT COUNT(" + tblVer.GetTableName() + "_ID) FROM " + tblVer.GetTableName() + " WHERE " + MKWhereClause.ToString(), null, _trx)); if (count > 0) { continue; } } // create PO object of source table (Master table) PO sPO = baseTbl.GetPO(GetCtx(), dsRecs.Tables[0].Rows[i], _trx); // create PO object of destination table (Version table) PO dPO = tblVer.GetPO(GetCtx(), 0, _trx); sPO.CopyTo(dPO); dPO.SetAD_Client_ID(sPO.GetAD_Client_ID()); dPO.SetAD_Org_ID(sPO.GetAD_Org_ID()); dPO.Set_Value("RecordVersion", "1"); dPO.Set_ValueNoCheck("VersionValidFrom", sPO.Get_Value("Created")); dPO.Set_ValueNoCheck("IsVersionApproved", true); dPO.Set_ValueNoCheck("Processed", true); dPO.Set_ValueNoCheck("ProcessedVersion", true); for (int j = 0; j < keyCols.Length; j++) { dPO.Set_ValueNoCheck(keyCols[j], sPO.Get_Value(keyCols[j])); } dPO.Set_Value("Export_ID", null); if (!dPO.Save()) { ValueNamePair vnp = VLogger.RetrieveError(); string error = ""; if (vnp != null) { error = vnp.GetName(); if (error == "" && vnp.GetValue() != null) { error = vnp.GetValue(); } } if (error == "") { error = "Error in saving data in Version table"; } return(retMsg); } } } return(retMsg); }
/// <summary> /// Create version table and window based on the parent table \ /// where Maintain Version field is marked as true /// </summary> /// <returns> Message (String) </returns> public string CreateVersionInfo(int AD_Column_ID, int AD_Table_ID, Trx trx) { _trx = trx; _AD_Table_ID = AD_Table_ID; _AD_Column_ID = AD_Column_ID; bool hasMainVerCol = Util.GetValueOfInt(DB.ExecuteScalar("SELECT AD_Column_ID FROM AD_Column WHERE AD_Table_ID = " + _AD_Table_ID + " AND IsActive ='Y' AND IsMaintainVersions = 'Y'", null, _trx)) > 0; if (!hasMainVerCol) { hasMainVerCol = Util.GetValueOfString(DB.ExecuteScalar("SELECT IsMaintainVersions FROM AD_Table WHERE AD_Table_ID = " + _AD_Table_ID, null, _trx)) == "Y"; } // check whether there are any columns in the table // marked as "Maintain Versions", then proceed else return if (hasMainVerCol) { MTable tbl = new MTable(GetCtx(), _AD_Table_ID, _trx); string VerTblName = tbl.GetTableName() + "_Ver"; // Create/Get System Elements for Version Table Columns string retMsg = GetSystemElements(VerTblName); if (retMsg != "") { return(retMsg); } int Ver_AD_Table_ID = Util.GetValueOfInt(DB.ExecuteScalar("SELECT AD_Table_ID FROM AD_Table WHERE TableName = '" + VerTblName + "'", null, _trx)); // check whether version table is already present in system // if not present then create table MTable tblVer = null; if (Ver_AD_Table_ID <= 0) { string tableName = tbl.GetTableName(); // create new Version table for parent table tblVer = new MTable(GetCtx(), 0, _trx); tbl.CopyTo(tblVer); tblVer.SetTableName(tableName + "_Ver"); tblVer.SetName(tableName + " Ver"); tblVer.Set_Value("Export_ID", null); tblVer.Set_Value("AD_Window_ID", null); tblVer.SetIsDeleteable(true); tblVer.SetDescription("Table for maintaining versions of " + tableName); tblVer.SetHelp("Table for maintaining versions of " + tableName); tblVer.SetIsMaintainVersions(false); //tblVer.SetAD_Window_ID(Ver_AD_Window_ID); if (!tblVer.Save()) { ValueNamePair vnp = VLogger.RetrieveError(); string error = ""; if (vnp != null) { error = vnp.GetName(); if (error == "" && vnp.GetValue() != null) { error = vnp.GetValue(); } } if (error == "") { error = "Error in creating Version Table"; } log.Log(Level.SEVERE, "Version table not created :: " + error); _trx.Rollback(); return(Msg.GetMsg(GetCtx(), "VersionTblNotCreated")); } else { Ver_AD_Table_ID = tblVer.GetAD_Table_ID(); // Create Default Version Columns retMsg = CreateDefaultVerCols(Ver_AD_Table_ID); if (retMsg != "") { return(retMsg); } } } else { tblVer = new MTable(GetCtx(), Ver_AD_Table_ID, _trx); // Create Default Version Columns retMsg = CreateDefaultVerCols(Ver_AD_Table_ID); if (retMsg != "") { return(retMsg); } } int VerTableColID = 0; // if Version table successfully created, then check columns, if not found then create new if (Ver_AD_Table_ID > 0) { // Get all columns from Version Table int[] ColIDs = MColumn.GetAllIDs("AD_Column", "AD_Table_ID = " + _AD_Table_ID, _trx); bool hasCols = false; DataSet dsDestCols = DB.ExecuteDataset("SELECT ColumnName, AD_Column_ID FROM AD_Column WHERE AD_Table_ID = " + Ver_AD_Table_ID, null, _trx); if (dsDestCols != null && dsDestCols.Tables[0].Rows.Count > 0) { hasCols = true; } // loop through all columns foreach (int columnID in ColIDs) { bool createNew = true; // object of Column from source table (Master Table) MColumn sCol = new MColumn(GetCtx(), columnID, _trx); // check if source column is not Virtual Column, proceed in that case only if (!sCol.IsVirtualColumn()) { DataRow[] dr = null; if (hasCols) { dr = dsDestCols.Tables[0].Select("ColumnName = '" + sCol.GetColumnName() + "'"); if (dr.Length > 0) { createNew = false; } } // Version Column object MColumn colVer = null; int AD_Col_ID = 0; // if column not present in Version table then create new if (createNew) { colVer = new MColumn(GetCtx(), AD_Col_ID, _trx); } // if column already present and user pressed sync button on same column of Master table // then create object of existing column (in case of change in any column fields) else if (!createNew && (_AD_Column_ID == columnID)) { AD_Col_ID = Util.GetValueOfInt(dr[0]["AD_Column_ID"]); colVer = new MColumn(GetCtx(), Util.GetValueOfInt(dr[0]["AD_Column_ID"]), _trx); } if (colVer != null) { sCol.CopyTo(colVer); if (AD_Col_ID > 0) { colVer.SetAD_Column_ID(AD_Col_ID); } colVer.SetExport_ID(null); colVer.SetAD_Table_ID(Ver_AD_Table_ID); // set key column to false colVer.SetIsKey(false); // check if source column is key column // then set Restrict Constraint and set Reference as Table Direct if (sCol.IsKey()) { colVer.SetConstraintType("R"); colVer.SetAD_Reference_ID(19); } //if (sCol.IsKey()) // colVer.SetIsParent(true); //else colVer.SetIsParent(false); colVer.SetIsMaintainVersions(false); colVer.SetIsMandatory(false); colVer.SetIsMandatoryUI(false); if (!colVer.Save()) { ValueNamePair vnp = VLogger.RetrieveError(); string error = ""; if (vnp != null) { error = vnp.GetName(); if (error == "" && vnp.GetValue() != null) { error = vnp.GetValue(); } } if (error == "") { error = "Version Column not created"; } log.Log(Level.SEVERE, "Version Column not created :: " + sCol.GetColumnName() + " :: " + error); _trx.Rollback(); return(Msg.GetMsg(GetCtx(), "VersionColNotCreated")); } else { VerTableColID = colVer.GetAD_Column_ID(); } } } } // Get one column to sync table in database from Version Table if (VerTableColID <= 0) { VerTableColID = Util.GetValueOfInt(DB.ExecuteScalar("SELECT AD_Column_ID FROM AD_Column WHERE AD_Table_ID = " + Ver_AD_Table_ID, null, _trx)); } // Get newly Created Column if (oldVerCol > 0) { VerTableColID = oldVerCol; } // Sync Version table in database bool success = true; retMsg = SyncVersionTable(tblVer, VerTableColID, out success); // if any error and there is message in return then return and rollback transaction if (!success && retMsg != "") { log.Log(Level.SEVERE, "Column not sync :: " + retMsg); _trx.Rollback(); return(Msg.GetMsg(GetCtx(), "ColumnNotSync")); } else { // if table has single key if (tbl.IsSingleKey()) { // get column names from parent table string colNameStrings = GetColumnNameString(tbl.GetAD_Table_ID()); // get default columns string from Version Table columns list string defColString = GetDefaultColString(colNameStrings); // Insert data in version table from Master table InsertVersionData(colNameStrings, defColString, tblVer.GetTableName()); } // Cases where single key is not present in Master table else { // Insert data in version table against Master Table retMsg = InsertMKVersionData(tbl, tbl.GetKeyColumns(), tblVer); if (retMsg != "") { log.Log(Level.SEVERE, "Data not Inserted :: " + retMsg); _trx.Rollback(); return(Msg.GetMsg(GetCtx(), "DataInsertionErrorMultikey")); } } } } } return(Msg.GetMsg(GetCtx(), "ProcessCompletedSuccessfully")); }
// Method added by mohit to get reports as byteArray. 19 April 2019 /// <summary> /// Method to get byte array of report. /// </summary> /// <param name="ctx">Current Context.</param> /// <param name="AD_Process_ID">Process ID.</param> /// <param name="Name">Name of process.</param> /// <param name="AD_Table_ID">Table id for fetching report.</param> /// <param name="Record_ID">Record id.</param> /// <param name="WindowNo">Window Number if process fired from window.</param> /// <param name="recIDs">String of record id's/</param> /// <param name="fileType">Report type.</param> /// <param name="report">Out parameter to get byte array.</param> /// <returns>Returns Process Info list and report byte array.</returns> public Dictionary <string, object> GetReport(Ctx ctx, int AD_Process_ID, string Name, int AD_Table_ID, int Record_ID, int WindowNo, string recIDs, string fileType, out byte[] report, out string rptFilePath) { Dictionary <string, object> d = null; report = null; rptFilePath = null; // Create PInstance MPInstance instance = null; try { instance = new MPInstance(ctx, AD_Process_ID, Record_ID); } catch (Exception e) { VLogger.Get().SaveError("GetReport-Instance Save", e.Message); return(d); } if (!instance.Save()) { ValueNamePair vp = VLogger.RetrieveError(); if (vp != null) { VLogger.Get().SaveError("GetReport-Instance Save", vp.Name ?? vp.GetValue()); } else { VLogger.Get().SaveError("GetReport-Instance Save", "PInstanceNotSaved"); } return(d); } // Culture. string lang = ctx.GetAD_Language().Replace("_", "-"); System.Globalization.CultureInfo original = System.Threading.Thread.CurrentThread.CurrentCulture; System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(lang); System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(lang); // Process info ProcessInfo pi = new ProcessInfo(Name, AD_Process_ID, AD_Table_ID, Record_ID, recIDs); pi.SetFileType(fileType); TryPrintFromDocType(pi); try { pi.SetAD_User_ID(ctx.GetAD_User_ID()); pi.SetAD_Client_ID(ctx.GetAD_Client_ID()); pi.SetAD_PInstance_ID(instance.GetAD_PInstance_ID()); ProcessCtl ctl = new ProcessCtl(); d = new Dictionary <string, object>(); d = ctl.Process(pi, ctx, out report, out rptFilePath); ctl.ReportString = null; } catch (Exception e) { VLogger.Get().SaveError("GetReport", e.Message); report = null; } return(d); }
protected override String DoIt() { MInvoice obj = new MInvoice(GetCtx(), GetRecord_ID(), Get_Trx()); // get Precision for rounding MCurrency currency = new MCurrency(GetCtx(), obj.GetC_Currency_ID(), Get_Trx()); precision = currency.GetStdPrecision(); MInvoiceLine[] lines = obj.GetLines(); if (_IsCLearDiscount == "N") { if (_DiscountAmt == 0 && _DiscountPercent == 0) { return(Msg.GetMsg(GetCtx(), "PlsSelAtlstOneField")); } if (_DiscountAmt != 0 && _DiscountPercent != 0) { return(Msg.GetMsg(GetCtx(), "PlsSelOneField")); } // get amount on which we have to apply discount subTotal = obj.GetTotalLines(); // when we are giving discount in terms of amount, then we have to calculate discount in term of percentage discountPercentageOnTotalAmount = GetDiscountPercentageOnTotal(subTotal, _DiscountAmt, precision); for (int i = 0; i < lines.Length; i++) { MInvoiceLine ln = lines[i]; // this value represent discount on line net amount discountAmountOnTotal = GetDiscountAmountOnTotal(ln.GetLineNetAmt(), discountPercentageOnTotalAmount != 0 ? discountPercentageOnTotalAmount : _DiscountPercent); // this value represent discount on unit price of 1 qty discountAmountOnTotal = Decimal.Round(Decimal.Divide(discountAmountOnTotal, ln.GetQtyEntered()), precision); ln.SetAmountAfterApplyDiscount(Decimal.Add(ln.GetAmountAfterApplyDiscount(), discountAmountOnTotal)); ln.SetPriceActual(Decimal.Round(Decimal.Subtract(ln.GetPriceActual(), discountAmountOnTotal), precision)); ln.SetPriceEntered(Decimal.Round(Decimal.Subtract(ln.GetPriceEntered(), discountAmountOnTotal), precision)); // set tax amount as 0, so that on before save we calculate tax again on discounted price ln.SetTaxAmt(0); if (!ln.Save(Get_TrxName())) { Rollback(); ValueNamePair pp = VLogger.RetrieveError(); log.Info("ApplyDiscountInvoiceVendor : Not Saved. Error Value : " + pp.GetValue() + " , Error Name : " + pp.GetName()); throw new Exception(Msg.GetMsg(GetCtx(), "DiscNotApplied")); } } return(Msg.GetMsg(GetCtx(), "DiscAppliedSuccess")); } else { for (int i = 0; i < lines.Length; i++) { MInvoiceLine ln = lines[i]; ln.SetPriceEntered(Decimal.Add(ln.GetPriceEntered(), ln.GetAmountAfterApplyDiscount())); ln.SetPriceActual(Decimal.Add(ln.GetPriceActual(), ln.GetAmountAfterApplyDiscount())); ln.SetAmountAfterApplyDiscount(0); ln.SetTaxAmt(0); if (!ln.Save(Get_TrxName())) { Rollback(); ValueNamePair pp = VLogger.RetrieveError(); log.Info("ApplyDiscountInvoiceVendor : Not Saved. Error Value : " + pp.GetValue() + " , Error Name : " + pp.GetName()); throw new Exception(Msg.GetMsg(GetCtx(), "DiscNotCleared")); } } return(Msg.GetMsg(GetCtx(), "DiscClearedSuccessfully")); } }
/// <summary> /// Is used to do a reverse entry of "Production Record" into the system /// </summary> /// <returns>message successfuly created or not</returns> protected override string DoIt() { if (M_Production_ID > 0) { //Copy Production Header X_M_Production production = new X_M_Production(GetCtx(), M_Production_ID, Get_Trx()); //check production is Reversed or not, if Reversed then not to do anything if (production.IsReversed()) { return(Msg.GetMsg(GetCtx(), "AlreadyReversed")); } //Get data from Production Plan dsProductionPlan = DB.ExecuteDataset(@"SELECT AD_CLIENT_ID , AD_ORG_ID , DESCRIPTION , LINE , M_LOCATOR_ID , M_PRODUCT_ID , M_PRODUCTIONPLAN_ID , M_PRODUCTION_ID , PROCESSED , PRODUCTIONQTY M_WAREHOUSE_ID FROM M_ProductionPlan WHERE IsActive = 'Y' AND M_PRODUCTION_ID = " + M_Production_ID, null, Get_Trx()); //get data from production Line dsProductionLine = DB.ExecuteDataset(@"SELECT AD_CLIENT_ID , AD_ORG_ID , DESCRIPTION , LINE , M_ATTRIBUTESETINSTANCE_ID , M_LOCATOR_ID , M_PRODUCT_ID , M_PRODUCTIONLINE_ID, M_PRODUCTIONPLAN_ID , M_PRODUCTION_ID , PROCESSED , MOVEMENTQTY , C_UOM_ID , PLANNEDQTY , M_WAREHOUSE_ID FROM M_ProductionLine WHERE IsActive = 'Y' AND M_PRODUCTION_ID = " + M_Production_ID, null, Get_Trx()); // Create New record of Production Header with Reverse Entry X_M_Production productionTo = new X_M_Production(production.GetCtx(), 0, production.Get_Trx()); try { productionTo.Set_TrxName(production.Get_Trx()); PO.CopyValues(production, productionTo, production.GetAD_Client_ID(), production.GetAD_Org_ID()); productionTo.SetName("{->" + productionTo.GetName() + ")"); if (production.Get_ColumnIndex("DocumentNo") > 0) { productionTo.Set_Value("DocumentNo", ("{->" + productionTo.Get_Value("DocumentNo") + ")")); } productionTo.SetMovementDate(production.GetMovementDate()); //SI_0662 : not to create reverse record in current date, it should be created with the same date. productionTo.SetProcessed(false); if (!productionTo.Save(production.Get_Trx())) { production.Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); _log.Log(Level.SEVERE, "Could Not create Production reverse entry. ERRor Value : " + pp.GetValue() + "ERROR NAME : " + pp.GetName()); throw new Exception("Could not create Production reverse entry"); } else { #region create new record of Production Plan if (dsProductionPlan != null && dsProductionPlan.Tables.Count > 0 && dsProductionPlan.Tables[0].Rows.Count > 0) { for (int i = 0; i < dsProductionPlan.Tables[0].Rows.Count; i++) { //Original Line fromProdPlan = new X_M_ProductionPlan(GetCtx(), Util.GetValueOfInt(dsProductionPlan.Tables[0].Rows[i]["M_PRODUCTIONPLAN_ID"]), Get_Trx()); // Create New record of Production Plan with Reverse Entry toProdPlan = new X_M_ProductionPlan(production.GetCtx(), 0, production.Get_Trx()); try { toProdPlan.Set_TrxName(production.Get_Trx()); PO.CopyValues(fromProdPlan, toProdPlan, fromProdPlan.GetAD_Client_ID(), fromProdPlan.GetAD_Org_ID()); toProdPlan.SetProductionQty(Decimal.Negate(toProdPlan.GetProductionQty())); toProdPlan.SetM_Production_ID(productionTo.GetM_Production_ID()); toProdPlan.SetProcessed(false); if (!toProdPlan.Save(production.Get_Trx())) { production.Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); _log.Log(Level.SEVERE, "Could Not create Production Plan reverse entry. ERRor Value : " + pp.GetValue() + "ERROR NAME : " + pp.GetName()); throw new Exception("Could not create Production Plan reverse entry"); } else { #region check record exist on production line if (dsProductionLine != null && dsProductionLine.Tables.Count > 0 && dsProductionLine.Tables[0].Rows.Count > 0) { //check record exist on production line against production plan drProductionLine = dsProductionLine.Tables[0].Select("M_ProductionPlan_ID = " + fromProdPlan.GetM_ProductionPlan_ID()); if (drProductionLine.Length > 0) { for (int j = 0; j < drProductionLine.Length; j++) { //Original Line fromProdline = new X_M_ProductionLine(GetCtx(), Util.GetValueOfInt(drProductionLine[j]["M_PRODUCTIONLINE_ID"]), Get_Trx()); // Create New record of Production line with Reverse Entry toProdline = new X_M_ProductionLine(production.GetCtx(), 0, production.Get_Trx()); try { toProdline.Set_TrxName(production.Get_Trx()); PO.CopyValues(fromProdline, toProdline, fromProdPlan.GetAD_Client_ID(), fromProdPlan.GetAD_Org_ID()); toProdline.SetMovementQty(Decimal.Negate(toProdline.GetMovementQty())); toProdline.SetPlannedQty(Decimal.Negate(toProdline.GetPlannedQty())); toProdline.SetM_Production_ID(productionTo.GetM_Production_ID()); toProdline.SetM_ProductionPlan_ID(toProdPlan.GetM_ProductionPlan_ID()); toProdline.SetReversalDoc_ID(fromProdline.GetM_ProductionLine_ID()); //maintain refernce of Orignal record on reversed record toProdline.SetProcessed(false); if (!CheckQtyAvailablity(GetCtx(), toProdline.GetM_Warehouse_ID(), toProdline.GetM_Locator_ID(), toProdline.GetM_Product_ID(), toProdline.GetM_AttributeSetInstance_ID(), toProdline.GetMovementQty(), Get_Trx())) { production.Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); if (!string.IsNullOrEmpty(pp.GetName())) { throw new Exception("Could not create Production line reverse entry, " + pp.GetName()); } else { throw new Exception("Could not create Production line reverse entry"); } } if (!toProdline.Save(production.Get_Trx())) { production.Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); _log.Log(Level.SEVERE, "Could Not create Production Line reverse entry. ERRor Value : " + pp.GetValue() + "ERROR NAME : " + pp.GetName()); throw new Exception("Could not create Production line reverse entry"); } } catch (Exception ex) { _log.Info("Error Occured during Production Reverse " + ex.ToString()); if (dsProductionLine != null) { dsProductionLine.Dispose(); } if (dsProductionPlan != null) { dsProductionPlan.Dispose(); } return(Msg.GetMsg(GetCtx(), "DocumentNotReversed" + result)); } } } } #endregion } } catch (Exception ex) { _log.Info("Error Occured during Production Reverse " + ex.ToString()); if (dsProductionLine != null) { dsProductionLine.Dispose(); } if (dsProductionPlan != null) { dsProductionPlan.Dispose(); } return(Msg.GetMsg(GetCtx(), "DocumentNotReversed" + result)); } } } #endregion result = productionTo.GetName(); } //set Reversed as True productionTo.SetIsReversed(true); if (!productionTo.Save(production.Get_Trx())) { production.Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); _log.Log(Level.SEVERE, "Could Not create Production reverse entry. ERRor Value : " + pp.GetValue() + "ERROR NAME : " + pp.GetName()); throw new Exception("Could not create Production reverse entry"); } //Set reversed as true, Reverse Refernce on Orignal Document production.SetIsReversed(true); production.SetM_Ref_Production(productionTo.GetM_Production_ID()); if (!production.Save(production.Get_Trx())) { production.Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); _log.Log(Level.SEVERE, "Could Not create Production reverse entry. ERRor Value : " + pp.GetValue() + "ERROR NAME : " + pp.GetName()); throw new Exception("Could not create Production reverse entry"); } } catch (Exception ex) { _log.Info("Error Occured during Production Reverse " + ex.ToString()); if (dsProductionLine != null) { dsProductionLine.Dispose(); } if (dsProductionPlan != null) { dsProductionPlan.Dispose(); } return(Msg.GetMsg(GetCtx(), "DocumentNotReversed" + result)); } } return(Msg.GetMsg(GetCtx(), "DocumentReversedSuccessfully" + result)); }
/// <summary> /// Create actual Payment /// </summary> /// <param name="C_Invoice_ID">invoice</param> /// <param name="C_BPartner_ID">partner ignored when invoice exists</param> /// <param name="C_Currency_ID">currency</param> /// <param name="stmtAmt">statement amount</param> /// <param name="trxAmt">transaction amt</param> /// <param name="C_BankAccount_ID">bank account</param> /// <param name="dateTrx">transaction date</param> /// <param name="dateAcct">accounting date</param> /// <param name="description">description</param> /// <param name="AD_Org_ID"></param> /// <param name="C_ConversionType_ID">C_ConversionType_ID</param> /// <param name="C_Order_ID">C_Order_ID</param> /// <returns>payment</returns> private MPayment CreatePayment(int C_Invoice_ID, int C_BPartner_ID, int C_Currency_ID, Decimal stmtAmt, Decimal trxAmt, int C_BankAccount_ID, DateTime?dateTrx, DateTime?dateAcct, String description, int AD_Org_ID, int C_ConversionType_ID, int C_Order_ID) { // Trx Amount = Payment overwrites Statement Amount if defined Decimal payAmt = trxAmt; if (Env.ZERO.CompareTo(payAmt) == 0) { payAmt = stmtAmt; } if (C_Invoice_ID == 0 && C_Order_ID == 0 && (Env.ZERO.CompareTo(payAmt) == 0)) { throw new Exception("@PayAmt@ = 0"); } //if (payAmt == null) //{ // payAmt = Env.ZERO; //} // MPayment payment = new MPayment(GetCtx(), 0, Get_Trx()); payment.SetAD_Org_ID(AD_Org_ID); payment.SetC_BankAccount_ID(C_BankAccount_ID); //payment.SetTenderType(MPayment.TENDERTYPE_Check);//not required it will update on MPayment class //Get the C_ConversionType_ID from BankStatementLine and Set C_ConversionType_ID for Payment payment.SetC_ConversionType_ID(C_ConversionType_ID); if (dateTrx != null) { payment.SetDateTrx(dateTrx); } else if (dateAcct != null) { payment.SetDateTrx(dateAcct); } if (dateAcct != null) { payment.SetDateAcct(dateAcct); } else { payment.SetDateAcct(payment.GetDateTrx()); } payment.SetDescription(description); // if (C_Invoice_ID != 0) { MInvoice invoice = new MInvoice(GetCtx(), C_Invoice_ID, Get_Trx()); //Used Trx payment.SetC_DocType_ID(invoice.IsSOTrx()); // Receipt payment.SetC_BPartner_ID(invoice.GetC_BPartner_ID()); //set the BPartner Location from the Invoice payment.SetC_BPartner_Location_ID(invoice.GetC_BPartner_Location_ID()); //set the PaymentMethod by the reference of Invoice payment.SetVA009_PaymentMethod_ID(invoice.GetVA009_PaymentMethod_ID()); payment.SetC_Currency_ID(invoice.GetC_Currency_ID()); decimal _dueAmt = 0; string _sql = "SELECT * FROM C_InvoicePaySchedule WHERE VA009_PAIDAMNT IS NULL AND VA009_IsPaid = 'N' AND IsActive = 'Y' AND C_Invoice_ID =" + invoice.GetC_Invoice_ID(); DataSet _ds = DB.ExecuteDataset(_sql, null, Get_Trx()); if (_ds != null && _ds.Tables[0].Rows.Count == 1) { payment.SetC_Invoice_ID(invoice.GetC_Invoice_ID());//set Invoice Reference payment.SetC_InvoicePaySchedule_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[0]["C_INVOICEPAYSCHEDULE_ID"])); _dueAmt = Util.GetValueOfDecimal(_ds.Tables[0].Rows[0]["DUEAMT"]); //Set PayAmt -ve sign Incase of DocBaseType APC or ARC - IsReturnTrx is true //Set PayAmt +ve sign Incase of DocBaseType API or ARI - IsReturnTrx is false if (!invoice.IsReturnTrx()) { payment.SetPayAmt(_dueAmt); } else // payment is likely to be negative { payment.SetPayAmt(Decimal.Negate(_dueAmt)); } if (!payment.Save(Get_Trx())) { Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); //to get Exact Error Message first get Value from GetName() else GetValue() string error = pp != null?pp.GetName() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.GetValue() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.ToString() : ""; } } _message = !string.IsNullOrEmpty(error) ? error : "VA012_PaymentNotSaved"; return(null); } } else if (_ds != null && _ds.Tables[0].Rows.Count > 1) { if (!payment.Save(Get_Trx())) { Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); //to get Exact Error Message first get Value from GetName() else GetValue() string error = pp != null?pp.GetName() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.GetValue() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.ToString() : ""; } } _message = !string.IsNullOrEmpty(error) ? error : "VA012_PaymentNotSaved"; return(null); } else { //Initialize the Object for MPaymentAllocate class MPaymentAllocate PayAlocate = null; for (int i = 0; _ds.Tables[0].Rows.Count > i; i++) { //Create the Object for MPaymentAllocate class for every Iteration PayAlocate = new MPaymentAllocate(GetCtx(), 0, Get_Trx()); PayAlocate.SetC_Payment_ID(payment.GetC_Payment_ID()); PayAlocate.SetAD_Client_ID(payment.GetAD_Client_ID()); //set Organization with the reference of Bank Account PayAlocate.SetAD_Org_ID(payment.GetAD_Org_ID());//set Org_ID from the Header PayAlocate.SetC_Invoice_ID(invoice.GetC_Invoice_ID()); PayAlocate.SetC_InvoicePaySchedule_ID(Util.GetValueOfInt(_ds.Tables[0].Rows[i]["C_INVOICEPAYSCHEDULE_ID"])); //Set PayAmt -ve sign Incase of DocBaseType APC or ARC - IsReturnTrx is true //Set PayAmt +ve sign Incase of DocBaseType API or ARI - IsReturnTrx is false if (!invoice.IsReturnTrx()) { PayAlocate.SetInvoiceAmt(Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["DUEAMT"])); PayAlocate.SetAmount(Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["DUEAMT"])); } else { PayAlocate.SetInvoiceAmt(-1 * Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["DUEAMT"])); PayAlocate.SetAmount(-1 * Util.GetValueOfDecimal(_ds.Tables[0].Rows[i]["DUEAMT"])); } if (!PayAlocate.Save(Get_Trx())) { Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); //to get Exact Error Message first get Value from GetName() else GetValue() string error = pp != null?pp.GetName() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.GetValue() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.ToString() : ""; } } _message = !string.IsNullOrEmpty(error) ? error : "VA012_PaymentNotSaved"; return(null); } } } } } else if (C_Order_ID > 0 && C_BPartner_ID > 0) // Create Payment for prePayOrder reference { MOrder order = new MOrder(GetCtx(), C_Order_ID, Get_Trx()); payment.SetC_Order_ID(C_Order_ID); payment.SetC_DocType_ID(order.IsSOTrx()); // Receipt payment.SetC_BPartner_ID(order.GetC_BPartner_ID()); payment.SetC_BPartner_Location_ID(order.GetC_BPartner_Location_ID()); payment.SetC_Currency_ID(order.GetC_Currency_ID()); payment.SetVA009_PaymentMethod_ID(order.GetVA009_PaymentMethod_ID()); payment.SetPayAmt(order.GetGrandTotal()); if (!payment.Save(Get_Trx())) { Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); //to get Exact Error Message first get Value from GetName() else GetValue() string error = pp != null?pp.GetName() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.GetValue() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.ToString() : ""; } } _message = !string.IsNullOrEmpty(error) ? error : "VA012_PaymentNotSaved"; return(null); } } else { _message = "VA012_ReferenceNotfoundtoCreatePayment"; return(null); } //Commit the Transaction Get_Trx().Commit(); //Call Complete Method to Complete the Record //149 is AD_Process_ID for C_Payment_Process _message = CompletePayment(GetCtx(), payment.GetC_Payment_ID(), 149, MPayment.DOCACTION_Complete); if (!string.IsNullOrEmpty(_message)) { return(null); } return(payment); }
/// <summary> /// Create PO From SO /// </summary> /// <param name="so">sales order</param> /// <returns>number of POs created</returns> private int CreatePOFromSO(MOrder so) { StringBuilder sql = new StringBuilder(); StringBuilder sqlErrorMessage = new StringBuilder(); sqlErrorMessage.Clear(); string _Dropship = ""; log.Info(so.ToString()); MOrderLine[] soLines = so.GetLines(true, null); if (soLines == null || soLines.Length == 0) { log.Warning("No Lines - " + so); return(0); } // int counter = 0; // Order Lines with a Product which has a current vendor sql.Append(@"SELECT DISTINCT po.C_BPartner_ID, po.M_Product_ID ,ol.Isdropship, po.PriceList , po.PricePO , po.C_Currency_ID FROM M_Product_PO po INNER JOIN M_Product prd ON po.M_Product_ID=prd.M_Product_ID INNER JOIN C_OrderLine ol ON (po.M_Product_ID=ol.M_Product_ID "); // changes done by bharat on 26 June 2018 If purchased Checkbox is false on Finished Good Product, System should not generate Purchase Order. sqlErrorMessage.Append(@"SELECT DISTINCT po.C_BPartner_ID, bp.name AS BPName, ol.M_Product_ID , p.Name, ol.Isdropship, po.C_Currency_ID, bp.PO_PaymentTerm_ID, bp.PO_PriceList_ID FROM C_OrderLine ol INNER JOIN m_product p ON (p.M_Product_ID =ol.M_Product_ID) LEFT JOIN M_Product_PO po ON (po.M_Product_ID=ol.M_Product_ID AND po.isactive = 'Y' AND po.IsCurrentVendor = 'Y' ) LEFT JOIN c_bpartner bp ON (bp.c_bpartner_id = po.c_bpartner_id "); // Added by Vivek on 20/09/2017 Assigned By Pradeep for drop shipment // if drop ship parameter is true then get all records true drop ship lines if (_IsDropShip == "Y") { sql.Append(@"AND Ol.Isdropship='Y' "); sqlErrorMessage.Append(@"AND Ol.Isdropship='Y' "); } // if drop ship parameter is false then get all records false drop ship lines else if (_IsDropShip == "N") { sql.Append(@"AND Ol.Isdropship='N' "); sqlErrorMessage.Append(@"AND Ol.Isdropship='N' "); } // changes don eby Bharat on 26 June 2018 to handle If purchased Checkbox is false on Finished Good Product, System should not generate Purchase Order. sql.Append(@") WHERE ol.C_Order_ID=" + so.GetC_Order_ID() + @" AND po.IsCurrentVendor='Y' AND prd.IsPurchased='Y'"); sqlErrorMessage.Append(@") WHERE ol.C_Order_ID=" + so.GetC_Order_ID()); if (_Vendor_ID > 0) { sql.Append(@" AND po.C_BPartner_ID = " + _Vendor_ID); sqlErrorMessage.Append(@" AND po.C_BPartner_ID = " + _Vendor_ID); } sql.Append(@" ORDER BY po.c_bpartner_id,ol.Isdropship "); sqlErrorMessage.Append(@" ORDER BY po.c_bpartner_id,ol.Isdropship "); // get error or setting message GetErrorOrSetting(sqlErrorMessage.ToString(), Get_TrxName()); IDataReader idr = null; MOrder po = null; ConsolidatePO consolidatePO = null; //ConsolidatePOLine consolidatePOLine = null; try { idr = DataBase.DB.ExecuteReader(sql.ToString(), null, Get_TrxName()); while (idr.Read()) { // New Order int C_BPartner_ID = Utility.Util.GetValueOfInt(idr[0]);//.getInt(1); // Code Commented by Vivek Kumar on 20/09/2017 Assigned By Pradeep for drop shipment //if (po == null || po.GetBill_BPartner_ID() != C_BPartner_ID) //{ // po = CreatePOForVendor(Utility.Util.GetValueOfInt(idr[0]), so); // AddLog(0, null, null, po.GetDocumentNo()); // counter++; // // check ANY PO created with same Business Partnet and Drop Shipment if (_IsConsolidatedPO && listConsolidatePO.Count > 0) { ConsolidatePO poRecord; if (listConsolidatePO.Exists(x => (x.C_BPartner_ID == C_BPartner_ID) && (x.IsDropShip == Utility.Util.GetValueOfString(idr[2])))) { poRecord = listConsolidatePO.Find(x => (x.C_BPartner_ID == C_BPartner_ID) && (x.IsDropShip == Utility.Util.GetValueOfString(idr[2]))); if (poRecord != null) { po = new MOrder(GetCtx(), poRecord.C_Order_ID, Get_Trx()); _Dropship = po.IsDropShip() ? "Y" : "N"; } } } // Drop Shipment fucntionality added by Vivek on 20/09/2017 Assigned By Pradeep if (po == null || po.GetBill_BPartner_ID() != C_BPartner_ID || _Dropship != Utility.Util.GetValueOfString(idr[2])) { po = CreatePOForVendor(Utility.Util.GetValueOfInt(idr[0]), so, Utility.Util.GetValueOfString(idr[2])); if (po == null) { return(counter); } // AddLog(0, null, null, po.GetDocumentNo()); counter++; // maintain list if (po != null && po.GetC_Order_ID() > 0) { consolidatePO = new ConsolidatePO(); consolidatePO.C_Order_ID = po.GetC_Order_ID(); consolidatePO.C_BPartner_ID = C_BPartner_ID; consolidatePO.IsDropShip = Utility.Util.GetValueOfString(idr[2]); listConsolidatePO.Add(consolidatePO); } } _Dropship = Utility.Util.GetValueOfString(idr[2]); // Line int M_Product_ID = Utility.Util.GetValueOfInt(idr[1]);//.getInt(2); for (int i = 0; i < soLines.Length; i++) { // When Drop ship parameter is yes but SO line does not contains any drop shipment product if (_IsDropShip == "Y" && Util.GetValueOfBool(soLines[i].IsDropShip()) == false) { continue; } // When Drop ship parameter is NO but SO line contains drop shipment product then it also does not generate any else if (_IsDropShip == "N" && Util.GetValueOfBool(soLines[i].IsDropShip()) == true) { continue; } //When Drop ship parameter is yes and SO line also contains drop shipment product else { String _Drop = "N"; if (Util.GetValueOfBool(soLines[i].IsDropShip())) { _Drop = "Y"; } if (soLines[i].GetM_Product_ID() == M_Product_ID && _Drop == _Dropship) { MOrderLine poLine = new MOrderLine(po); poLine.SetRef_OrderLine_ID(soLines[i].GetC_OrderLine_ID()); poLine.SetM_Product_ID(soLines[i].GetM_Product_ID()); poLine.SetM_AttributeSetInstance_ID(soLines[i].GetM_AttributeSetInstance_ID()); poLine.SetC_UOM_ID(soLines[i].GetC_UOM_ID()); poLine.SetQtyEntered(soLines[i].GetQtyEntered()); poLine.SetQtyOrdered(soLines[i].GetQtyOrdered()); poLine.SetDescription(soLines[i].GetDescription()); poLine.SetDatePromised(soLines[i].GetDatePromised()); poLine.SetIsDropShip(soLines[i].IsDropShip()); poLine.SetPrice(); // Set value in Property From Process to check on Before Save. poLine.SetFromProcess(true); if (!poLine.Save()) { ValueNamePair pp = VLogger.RetrieveError(); log.Info("CreatePOfromSO : Not Saved. Error Value : " + pp.GetValue() + " , Error Name : " + pp.GetName()); } //else //{ // if (poLine != null && poLine.GetC_OrderLine_ID() > 0) // { // consolidatePOLine = new ConsolidatePOLine(); // consolidatePOLine.C_Order_ID = poLine.GetC_Order_ID(); // consolidatePOLine.C_OrderLine_ID = poLine.GetC_OrderLine_ID(); // consolidatePOLine.M_Product_ID = poLine.GetM_Product_ID(); // consolidatePOLine.M_AttributeSetInstance_ID = poLine.GetM_AttributeSetInstance_ID(); // consolidatePOLine.C_UOM_ID = poLine.GetC_UOM_ID(); // consolidatePOLine.IsDropShip = soLines[i].IsDropShip() ? "Y" : "N"; // listConsolidatePOLine.Add(consolidatePOLine); // } //} } } } } idr.Close(); } catch (Exception e) { if (idr != null) { idr.Close(); } log.Log(Level.SEVERE, sql.ToString(), e); } // Set Reference to PO if (po != null) { so.SetRef_Order_ID(po.GetC_Order_ID()); so.Save(); } return(counter); }
/// <summary> /// Function to update data in Master Table based on the versions saved /// </summary> /// <param name="dsRec">All Records which need to be updated</param> /// <param name="TableName">Version Table Name</param> /// <param name="VerTableID">Version Table ID</param> /// <returns>True/False based on the Updation of data in parent table</returns> private bool UpdateRecords(DataSet dsRec, string TableName, int VerTableID) { // Get Master table name from Version table string BaseTblName = TableName; if (TableName.EndsWith("_Ver")) { BaseTblName = BaseTblName.Substring(0, TableName.Length - 4); } // Master Table ID from Table name int BaseTableID = Util.GetValueOfInt(DB.ExecuteScalar("SELECT AD_Table_ID FROM AD_Table WHERE TableName = '" + BaseTblName + "'")); // Get Column information of Master Table DataSet dsDBColNames = DB.ExecuteDataset("SELECT ColumnName, AD_Reference_ID, IsUpdateable, IsAlwaysUpdateable FROM AD_Column WHERE AD_Table_ID = " + BaseTableID); if (dsDBColNames != null && dsDBColNames.Tables[0].Rows.Count > 0) { log.Info("Processing for " + TableName + " :: "); StringBuilder sqlSB = new StringBuilder(""); bool recordProcessed = false; // create object of Master Table MTable tbl = new MTable(GetCtx(), BaseTableID, null); // create object of Version table MTable tblVer = new MTable(GetCtx(), VerTableID, null); // check whether master table has Single key bool isSingleKey = tbl.IsSingleKey(); // List of records which were not processed by process in case of any error List <string> keys = new List <string>(); StringBuilder sbKey = new StringBuilder(""); // Loop through the records which need to be updated on Master Table for (int i = 0; i < dsRec.Tables[0].Rows.Count; i++) { DataRow dr = dsRec.Tables[0].Rows[i]; sbKey.Clear(); PO poDest = null; PO poSource = tblVer.GetPO(GetCtx(), dr, null); // if table has single key if (isSingleKey) { // Create object of PO Class from TableName and Record ID poDest = MTable.GetPO(GetCtx(), BaseTblName, Util.GetValueOfInt(dr[BaseTblName + "_ID"]), null); sbKey.Append(Util.GetValueOfInt(dr[BaseTblName + "_ID"])); } else { // Create object of PO Class from combination of key columns string[] keyCols = tbl.GetKeyColumns(); StringBuilder whereCond = new StringBuilder(""); for (int w = 0; w < keyCols.Length; w++) { if (w == 0) { if (keyCols[w] != null) { whereCond.Append(keyCols[w] + " = " + poSource.Get_Value(keyCols[w])); } else { whereCond.Append(" NVL(" + keyCols[w] + ",0) = 0"); } } else { if (keyCols[w] != null) { whereCond.Append(" AND " + keyCols[w] + " = " + poSource.Get_Value(keyCols[w])); } else { whereCond.Append(" AND NVL(" + keyCols[w] + ",0) = 0"); } } } poDest = tbl.GetPO(GetCtx(), whereCond.ToString(), null); sbKey.Append(whereCond); } // check if there is any error in processing record, then continue and do not process next versions if (keys.Contains(sbKey.ToString())) { continue; } // Check whether Master Table contains "Processing" Column if (poDest.Get_ColumnIndex("Processing") >= 0) { // if "Processing" column found then return, do not update in Master Table, // because transaction might be in approval process if (Util.GetValueOfString(poSource.Get_Value("Processing")) == "Y") { keys.Add(sbKey.ToString()); continue; } } // Check whether Master Table contains "Processed" Column if (poDest.Get_ColumnIndex("Processed") >= 0) { if (Util.GetValueOfString(poSource.Get_Value("Processed")) == "Y") { recordProcessed = true; } } // set client and Organization ID from Version table to Master // as copy PO set these ID's as 0 poDest.SetAD_Client_ID(poSource.GetAD_Client_ID()); poDest.SetAD_Org_ID(poSource.GetAD_Org_ID()); StringBuilder sbColName = new StringBuilder(""); // Loop through all the columns in Master Table for (int j = 0; j < dsDBColNames.Tables[0].Rows.Count; j++) { sbColName.Clear(); // Get Name of Column sbColName.Append(dsDBColNames.Tables[0].Rows[j]["ColumnName"]); // check if column exist in Default columns list, in that case do not update and continue to next column if (defcolNames.Contains(sbColName.ToString())) { continue; } // No need to update Primary key column, continue to next column if (sbColName.ToString().Equals(BaseTblName + "_ID")) { continue; } // if column is of "Yes-No" type i.e. Reference ID is 20 (Fixed) then set True/False if (Util.GetValueOfInt(dsDBColNames.Tables[0].Rows[j]["AD_Reference_ID"]) == 20) { Object val = false; if (poSource.Get_Value(sbColName.ToString()) != null) { val = poSource.Get_Value(sbColName.ToString()); } poDest.Set_Value(sbColName.ToString(), val); } else { poDest.Set_ValueNoCheck(sbColName.ToString(), poSource.Get_Value(sbColName.ToString())); } // Check if Master record is Processed and Always Updatable is false then check whether any value updated in such column // if value updated then return false, can't change data in Processed record if it's not Always Updatable if (recordProcessed && Util.GetValueOfString(dsDBColNames.Tables[0].Rows[j]["IsAlwaysUpdateable"]) == "N") { bool upd = poDest.Is_ValueChanged(sbColName.ToString()); if (upd) { msg.Append("Can't update " + sbColName.ToString() + " in " + TableName); log.SaveError("ERROR", "Can not update processed record for column ==>> " + sbColName.ToString()); // Add record to the list of unprocessed records keys.Add(sbKey.ToString()); continue; } } } // Save Master Record if (!poDest.Save()) { // Add record to the list of unprocessed records keys.Add(sbKey.ToString()); // Check for Errors ValueNamePair vnp = VLogger.RetrieveError(); string error = ""; if (vnp != null) { error = vnp.GetName(); if (error == "" && vnp.GetValue() != null) { error = vnp.GetValue(); } } if (error == "") { error = "Error in updating Version"; } msg.Append("Save error in " + TableName + " ==>> " + error); log.SaveError("ERROR", error); sqlSB.Clear(); sqlSB.Append("UPDATE " + TableName + " SET VersionLog = '" + error + "' WHERE " + TableName + "_ID = " + dr[TableName + "_ID"]); int count = DB.ExecuteQuery(sqlSB.ToString(), null, null); continue; } else { // Update Version table, Set "ProcessedVersion" to "Y", so that it don't consider when process runs next time sqlSB.Clear(); // Update against record id in case of Single key, and update Key column in version table as well in case of new record if (isSingleKey) { sqlSB.Append("UPDATE " + TableName + " SET ProcessedVersion = 'Y', " + BaseTblName + "_ID = " + poDest.Get_ID() + " WHERE " + TableName + "_ID = " + dr[TableName + "_ID"]); } // else else { sqlSB.Append("UPDATE " + TableName + " SET ProcessedVersion = 'Y' WHERE " + TableName + "_ID = " + dr[TableName + "_ID"]); } int count = DB.ExecuteQuery(sqlSB.ToString(), null, null); if (count <= 0) { log.Info(TableName + " not updated ==>> " + sqlSB.ToString()); } } } } return(true); }
/** * Before Save * @param newRecord new * @return true */ protected override bool BeforeSave(bool newRecord) { if (Is_ValueChanged("DueAmt")) { log.Fine("beforeSave"); SetIsValid(false); } oldDueAmt = Util.GetValueOfDecimal(Get_ValueOld("DueAmt")); if (Env.IsModuleInstalled("VA009_")) { // get invoice currency for rounding MCurrency currency = MCurrency.Get(GetCtx(), GetC_Currency_ID()); SetDueAmt(Decimal.Round(GetDueAmt(), currency.GetStdPrecision())); SetVA009_PaidAmntInvce(Decimal.Round(GetVA009_PaidAmntInvce(), currency.GetStdPrecision())); // when invoice schedule have payment reference then need to check payment mode on payment window & update here if (GetC_Payment_ID() > 0) { #region for payment MPayment payment = new MPayment(GetCtx(), GetC_Payment_ID(), Get_Trx()); SetVA009_PaymentMethod_ID(payment.GetVA009_PaymentMethod_ID()); // get payment method detail -- update to here DataSet dsPaymentMethod = DB.ExecuteDataset(@"SELECT VA009_PaymentMode, VA009_PaymentType, VA009_PaymentTrigger FROM VA009_PaymentMethod WHERE VA009_PaymentMethod_ID = " + payment.GetVA009_PaymentMethod_ID(), null, Get_Trx()); if (dsPaymentMethod != null && dsPaymentMethod.Tables.Count > 0 && dsPaymentMethod.Tables[0].Rows.Count > 0) { if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"]))) { SetVA009_PaymentMode(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"])); } if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"]))) { SetVA009_PaymentType(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"])); } SetVA009_PaymentTrigger(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentTrigger"])); } #endregion } else if (GetC_CashLine_ID() > 0) { #region For Cash // when invoice schedule have cashline reference then need to check // payment mode of "Cash" type having currency is null on "Payment Method" window & update here DataSet dsPaymentMethod = (DB.ExecuteDataset(@"SELECT VA009_PaymentMethod_ID, VA009_PaymentMode, VA009_PaymentType, VA009_PaymentTrigger FROM VA009_PaymentMethod WHERE IsActive = 'Y' AND AD_Client_ID = " + GetAD_Client_ID() + @" AND VA009_PaymentBaseType = 'B' AND NVL(C_Currency_ID , 0) = 0", null, Get_Trx())); if (dsPaymentMethod != null && dsPaymentMethod.Tables.Count > 0 && dsPaymentMethod.Tables[0].Rows.Count > 0) { SetVA009_PaymentMethod_ID(Util.GetValueOfInt(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMethod_ID"])); if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"]))) { SetVA009_PaymentMode(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"])); } if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"]))) { SetVA009_PaymentType(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"])); } SetVA009_PaymentTrigger(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentTrigger"])); } else { #region when we not found record of "Cash" then we will create a new rcord on Payment Method for Cash string sql = @"SELECT AD_TABLE_ID FROM AD_TABLE WHERE tablename LIKE 'VA009_PaymentMethod' AND IsActive = 'Y'"; int tableId = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null)); MTable tbl = new MTable(GetCtx(), tableId, Get_Trx()); PO po = tbl.GetPO(GetCtx(), 0, Get_Trx()); po.SetAD_Client_ID(GetAD_Client_ID()); po.SetAD_Org_ID(0); // Recod will be created in (*) Organization po.Set_Value("Value", "By Cash"); po.Set_Value("VA009_Name", "By Cash"); po.Set_Value("IsActive", true); po.Set_Value("VA009_PaymentBaseType", "B"); po.Set_Value("VA009_PaymentRule", "M"); po.Set_Value("VA009_PaymentMode", "C"); po.Set_Value("VA009_PaymentType", "S"); po.Set_Value("VA009_PaymentTrigger", "S"); po.Set_Value("C_Currency_ID", null); po.Set_Value("VA009_InitiatePay", false); if (!po.Save(Get_Trx())) { ValueNamePair pp = VLogger.RetrieveError(); log.Info("Error Occured when try to save record on Payment Method for Cash. Error Type : " + pp.GetValue()); } else { SetVA009_PaymentMethod_ID(Util.GetValueOfInt(po.Get_Value("VA009_PaymentMethod_ID"))); SetVA009_PaymentMode("C"); SetVA009_PaymentType("S"); SetVA009_PaymentTrigger("S"); } #endregion } #endregion } } return(true); }
/// <summary> /// Is used to do a reverse entry of "Production Record" into the system /// </summary> /// <returns>message successfuly created or not</returns> protected override string DoIt() { if (M_Production_ID > 0) { //Copy Production Header ViennaAdvantage.Model.X_M_Production production = new ViennaAdvantage.Model.X_M_Production(GetCtx(), M_Production_ID, Get_Trx()); string cnt = "Select count(*) from m_production pro where pro.movementdate >" + GlobalVariable.TO_DATE(production.GetMovementDate(), true) + " and pro.processed='Y' "; int trncnt = Util.GetValueOfInt(DB.ExecuteScalar(cnt)); if (trncnt > 0) { production.SetGOM01_IsRecordAvail(true); production.Save(Get_TrxName()); return(Msg.GetMsg(GetCtx(), "Please Check some transaction already availble in future")); } else { production.SetGOM01_IsRecordAvail(false); production.Save(Get_TrxName()); } //check production is Reversed or not, if Reversed then not to do anything if (production.IsReversed()) { return(Msg.GetMsg(GetCtx(), "AlreadyReversed")); } //Get data from Production Plan dsProductionPlan = DB.ExecuteDataset(@"SELECT AD_CLIENT_ID , AD_ORG_ID , DESCRIPTION , LINE , M_LOCATOR_ID , M_PRODUCT_ID , M_PRODUCTIONPLAN_ID , M_PRODUCTION_ID , PROCESSED , PRODUCTIONQTY M_WAREHOUSE_ID FROM M_ProductionPlan WHERE IsActive = 'Y' AND M_PRODUCTION_ID = " + M_Production_ID, null, Get_Trx()); //get data from production Line dsProductionLine = DB.ExecuteDataset(@"SELECT AD_CLIENT_ID , AD_ORG_ID , DESCRIPTION , LINE , M_ATTRIBUTESETINSTANCE_ID , M_LOCATOR_ID , M_PRODUCT_ID , M_PRODUCTIONLINE_ID, M_PRODUCTIONPLAN_ID , M_PRODUCTION_ID , PROCESSED , MOVEMENTQTY , C_UOM_ID , PLANNEDQTY , M_WAREHOUSE_ID FROM M_ProductionLine WHERE IsActive = 'Y' AND M_PRODUCTION_ID = " + M_Production_ID, null, Get_Trx()); // Create New record of Production Header with Reverse Entry X_M_Production productionTo = new X_M_Production(production.GetCtx(), 0, production.Get_Trx()); try { productionTo.Set_TrxName(production.Get_Trx()); PO.CopyValues(production, productionTo, production.GetAD_Client_ID(), production.GetAD_Org_ID()); productionTo.SetName("{->" + productionTo.GetName() + ")"); if (production.Get_ColumnIndex("DocumentNo") > 0) { productionTo.Set_Value("DocumentNo", ("{->" + productionTo.Get_Value("DocumentNo") + ")")); } productionTo.SetMovementDate(production.GetMovementDate()); //SI_0662 : not to create reverse record in current date, it should be created with the same date. productionTo.SetProcessed(false); if (!productionTo.Save(production.Get_Trx())) { production.Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); _log.Log(Level.SEVERE, "Could Not create Production reverse entry. ERRor Value : " + pp.GetValue() + "ERROR NAME : " + pp.GetName()); throw new Exception("Could not create Production reverse entry"); } else { #region create new record of Production Plan if (dsProductionPlan != null && dsProductionPlan.Tables.Count > 0 && dsProductionPlan.Tables[0].Rows.Count > 0) { for (int i = 0; i < dsProductionPlan.Tables[0].Rows.Count; i++) { //Original Line fromProdPlan = new X_M_ProductionPlan(GetCtx(), Util.GetValueOfInt(dsProductionPlan.Tables[0].Rows[i]["M_PRODUCTIONPLAN_ID"]), Get_Trx()); // Create New record of Production Plan with Reverse Entry toProdPlan = new X_M_ProductionPlan(production.GetCtx(), 0, production.Get_Trx()); try { toProdPlan.Set_TrxName(production.Get_Trx()); PO.CopyValues(fromProdPlan, toProdPlan, fromProdPlan.GetAD_Client_ID(), fromProdPlan.GetAD_Org_ID()); toProdPlan.SetProductionQty(Decimal.Negate(toProdPlan.GetProductionQty())); toProdPlan.SetM_Production_ID(productionTo.GetM_Production_ID()); toProdPlan.SetProcessed(false); if (!toProdPlan.Save(production.Get_Trx())) { production.Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); _log.Log(Level.SEVERE, "Could Not create Production Plan reverse entry. ERRor Value : " + pp.GetValue() + "ERROR NAME : " + pp.GetName()); throw new Exception("Could not create Production Plan reverse entry"); } else { #region check record exist on production line if (dsProductionLine != null && dsProductionLine.Tables.Count > 0 && dsProductionLine.Tables[0].Rows.Count > 0) { //check record exist on production line against production plan drProductionLine = dsProductionLine.Tables[0].Select("M_ProductionPlan_ID = " + fromProdPlan.GetM_ProductionPlan_ID()); if (drProductionLine.Length > 0) { for (int j = 0; j < drProductionLine.Length; j++) { //Original Line fromProdline = new X_M_ProductionLine(GetCtx(), Util.GetValueOfInt(drProductionLine[j]["M_PRODUCTIONLINE_ID"]), Get_Trx()); // Create New record of Production line with Reverse Entry toProdline = new X_M_ProductionLine(production.GetCtx(), 0, production.Get_Trx()); try { toProdline.Set_TrxName(production.Get_Trx()); PO.CopyValues(fromProdline, toProdline, fromProdPlan.GetAD_Client_ID(), fromProdPlan.GetAD_Org_ID()); toProdline.SetMovementQty(Decimal.Negate(toProdline.GetMovementQty())); toProdline.SetPlannedQty(Decimal.Negate(toProdline.GetPlannedQty())); toProdline.SetM_Production_ID(productionTo.GetM_Production_ID()); toProdline.SetM_ProductionPlan_ID(toProdPlan.GetM_ProductionPlan_ID()); toProdline.SetReversalDoc_ID(fromProdline.GetM_ProductionLine_ID()); //maintain refernce of Orignal record on reversed record toProdline.SetProcessed(false); // if (!CheckQtyAvailablity(GetCtx(), toProdline.GetM_Warehouse_ID(), toProdline.GetM_Locator_ID(), toProdline.GetM_ProductContainer_ID(), toProdline.GetM_Product_ID(), toProdline.GetM_AttributeSetInstance_ID(), toProdline.GetMovementQty(), Get_Trx())) if (!CheckQtyAvailablity(GetCtx(), toProdline.GetM_Warehouse_ID(), toProdline.GetM_Locator_ID(), 0, toProdline.GetM_Product_ID(), toProdline.GetM_AttributeSetInstance_ID(), toProdline.GetMovementQty(), Get_Trx())) { production.Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); if (!string.IsNullOrEmpty(pp.GetName())) { throw new Exception("Could not create Production line reverse entry, " + pp.GetName()); } else { throw new Exception("Could not create Production line reverse entry"); } } if (!toProdline.Save(production.Get_Trx())) { production.Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); _log.Log(Level.SEVERE, "Could Not create Production Line reverse entry. ERRor Value : " + pp.GetValue() + "ERROR NAME : " + pp.GetName()); throw new Exception("Could not create Production line reverse entry"); } else { // Create New record of Production line Policy (Material Policy) with Reverse Entry sql.Clear(); sql.Append(@"INSERT INTO M_ProductionLineMA ( AD_CLIENT_ID, AD_ORG_ID , CREATED , CREATEDBY , ISACTIVE , UPDATED , UPDATEDBY , M_PRODUCTIONLINE_ID , M_ATTRIBUTESETINSTANCE_ID , MMPOLICYDATE , M_PRODUCTCONTAINER_ID, MOVEMENTQTY ) (SELECT AD_CLIENT_ID, AD_ORG_ID , sysdate , CREATEDBY , ISACTIVE , sysdate , UPDATEDBY , " + toProdline.GetM_ProductionLine_ID() + @" , M_ATTRIBUTESETINSTANCE_ID , MMPOLICYDATE , M_PRODUCTCONTAINER_ID, -1 * MOVEMENTQTY FROM M_ProductionLineMA WHERE M_ProductionLine_ID = " + fromProdline.GetM_ProductionLine_ID() + @" ) "); int no = DB.ExecuteQuery(sql.ToString(), null, Get_Trx()); _log.Info("No of records saved on Meterial Policy against Production line ID : " + toProdline.GetM_ProductionLine_ID() + " are : " + no); } } catch (Exception ex) { _log.Info("Error Occured during Production Reverse " + ex.ToString()); if (dsProductionLine != null) { dsProductionLine.Dispose(); } if (dsProductionPlan != null) { dsProductionPlan.Dispose(); } return(Msg.GetMsg(GetCtx(), "DocumentNotReversed" + result)); } } } } #endregion } } catch (Exception ex) { _log.Info("Error Occured during Production Reverse " + ex.ToString()); if (dsProductionLine != null) { dsProductionLine.Dispose(); } if (dsProductionPlan != null) { dsProductionPlan.Dispose(); } return(Msg.GetMsg(GetCtx(), "DocumentNotReversed" + result)); } } } #endregion result = productionTo.GetName(); } //set Reversed as True productionTo.SetIsReversed(true); if (!productionTo.Save(production.Get_Trx())) { production.Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); _log.Log(Level.SEVERE, "Could Not create Production reverse entry. ERRor Value : " + pp.GetValue() + "ERROR NAME : " + pp.GetName()); throw new Exception("Could not create Production reverse entry"); } //Set reversed as true, Reverse Refernce on Orignal Document production.SetIsReversed(true); production.SetM_Ref_Production(productionTo.GetM_Production_ID()); if (!production.Save(production.Get_Trx())) { production.Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); _log.Log(Level.SEVERE, "Could Not create Production reverse entry. ERRor Value : " + pp.GetValue() + "ERROR NAME : " + pp.GetName()); throw new Exception("Could not create Production reverse entry"); } } catch (Exception ex) { _log.Info("Error Occured during Production Reverse " + ex.ToString()); if (dsProductionLine != null) { dsProductionLine.Dispose(); } if (dsProductionPlan != null) { dsProductionPlan.Dispose(); } return(Msg.GetMsg(GetCtx(), "DocumentNotReversed" + result)); } } return(Msg.GetMsg(GetCtx(), "DocumentReversedSuccessfully" + result)); }
/// <summary> /// Process /// </summary> /// <returns></returns> protected override string DoIt() { try { MRevenueRecognitionPlan revenueRecognitionPlan = null; MInvoiceLine invoiceLine = null; MInvoice invoice = null; MRevenueRecognition mRevenueRecognition = new MRevenueRecognition(GetCtx(), _RevenueRecognition_ID, Get_Trx()); // Count of previous date's RevenueRecognition_Run whose journal is not created string sql = "SELECT COUNT(C_RevenueRecognition_Run_ID) FROM C_RevenueRecognition_Run run " + "INNER JOIN C_RevenueRecognition_Plan pl ON pl.C_RevenueRecognition_Plan_ID = run.C_RevenueRecognition_Plan_ID WHERE "; if (C_InvoiceLine_ID > 0) { sql += "pl.C_invoiceLine_ID = " + C_InvoiceLine_ID + " AND "; } sql += "pl.C_RevenueRecognition_ID = " + _RevenueRecognition_ID + " AND NVL(GL_Journal_ID, 0)<=0 AND run.RECOGNITIONDATE < " + GlobalVariable.TO_DATE(DateTime.Now, true); if (Util.GetValueOfInt(DB.ExecuteScalar(sql)) == 0) { MRevenueRecognitionPlan[] revenueRecognitionPlans = MRevenueRecognitionPlan.GetRecognitionPlans(mRevenueRecognition, C_InvoiceLine_ID, _orgId); journal_ID = new int[revenueRecognitionPlans.Length]; if (ReversalType == "P") { for (int i = 0; i < revenueRecognitionPlans.Length; i++) { revenueRecognitionPlan = revenueRecognitionPlans[i]; invoiceLine = new MInvoiceLine(GetCtx(), revenueRecognitionPlan.GetC_InvoiceLine_ID(), Get_Trx()); invoice = new MInvoice(GetCtx(), invoiceLine.GetC_Invoice_ID(), Get_Trx()); //get Sum of Amount Whose journal is not yet created sql = "SELECT SUM(run.Recognizedamt) AS TotalRecognizedAmt FROM C_RevenueRecognition_Run run WHERE " + "C_RevenueRecognition_Plan_ID = " + revenueRecognitionPlan.GetC_RevenueRecognition_Plan_ID() + " AND NVL(GL_Journal_ID,0) <= 0"; totalAmt = Util.GetValueOfInt(DB.ExecuteScalar(sql)); if (totalAmt != 0) { //if totalAmount is not 0 then only create Journal if (revenueRecognitionPlan.GetC_AcctSchema_ID() != _AcctSchema_ID || revenueRecognitionPlan.GetC_Currency_ID() != _Currency_ID) { if (journal != null) { if (DocNo == null) { DocNo = journal.GetDocumentNo(); } else { DocNo += "," + journal.GetDocumentNo(); } journal_ID[i - 1] = journal.GetGL_Journal_ID(); } journal = new MJournal(GetCtx(), 0, Get_Trx()); journal.SetC_DocType_ID(_DocType); journal = CreateJournalHDR(revenueRecognitionPlan); if (journal.Save(Get_TrxName())) { _AcctSchema_ID = journal.GetC_AcctSchema_ID(); _Currency_ID = journal.GetC_Currency_ID(); lineno = Util.GetValueOfInt(DB.ExecuteScalar("SELECT NVL(MAX(Line), 0)+10 AS DefaultValue FROM GL_JournalLine WHERE GL_Journal_ID=" + journal.GetGL_Journal_ID(), null, invoice.Get_Trx())); } else { pp = VLogger.RetrieveError(); if (pp != null) { errorMsg = pp.GetName(); if (errorMsg == "") { errorMsg = pp.GetValue(); } } if (errorMsg == "") { errorMsg = Msg.GetMsg(GetCtx(), "GLJournalNotCreated"); } Get_TrxName().Rollback(); return(errorMsg); } } revenueRecognitionPlan.SetRecognizedAmt(totalAmt + revenueRecognitionPlan.GetRecognizedAmt()); if (!revenueRecognitionPlan.Save()) { pp = VLogger.RetrieveError(); if (pp != null) { errorMsg = pp.GetName(); if (errorMsg == "") { errorMsg = pp.GetValue(); } } if (errorMsg == "") { errorMsg = Msg.GetMsg(GetCtx(), "GLJournalNotCreated"); } Get_TrxName().Rollback(); return(errorMsg); } for (int k = 0; k < 2; k++) { journalLine = new MJournalLine(journal); journalLine = GenerateJounalLine(journal, invoice, invoiceLine, revenueRecognitionPlan, totalAmt, mRevenueRecognition.GetRecognitionType(), k); if (journalLine.Save(Get_TrxName())) { lineno += 10; } else { pp = VLogger.RetrieveError(); if (pp != null) { errorMsg = pp.GetName(); if (errorMsg == "") { errorMsg = pp.GetValue(); } } if (errorMsg == "") { errorMsg = Msg.GetMsg(GetCtx(), "GLJournalNotCreated"); } Get_TrxName().Rollback(); return(errorMsg); } } sql = "UPDATE C_RevenueRecognition_Run set Gl_Journal_ID= " + journal.GetGL_Journal_ID() + " WHERE C_RevenueRecognition_Plan_ID= " + revenueRecognitionPlan.GetC_RevenueRecognition_Plan_ID() + "AND NVL(Gl_Journal_ID,0)=0"; int count = DB.ExecuteQuery(sql, null, Get_Trx()); log.Log(Level.INFO, (Msg.GetMsg(GetCtx(), "RevenueRecognitionRunUpdated") + count)); } } if (journal != null) { if (DocNo == null) { DocNo = journal.GetDocumentNo(); } else { DocNo += "," + journal.GetDocumentNo(); } journal_ID[journal_ID.Length - 1] = journal.GetGL_Journal_ID(); } } #region Existing Reversal Type //else if (ReversalType == "E") //{ // for (int i = 0; i < revenueRecognitionPlans.Length; i++) // { // MRevenueRecognitionPlan revenueRecognitionPlan = revenueRecognitionPlans[i]; // MInvoiceLine invoiceLine = new MInvoiceLine(GetCtx(), revenueRecognitionPlan.GetC_InvoiceLine_ID(), Get_Trx()); // MInvoice invoice = new MInvoice(GetCtx(), invoiceLine.GetC_Invoice_ID(), Get_Trx()); // sql = "Select Distinct round(SUM(recognizedamt),5) as RecognizedAmt from C_RevenueRecognition_Run Where C_RevenueRecognition_Plan_ID = " + revenueRecognitionPlan.GetC_RevenueRecognition_Plan_ID() + " And NVL(GL_Journal_ID,0) > 0 "; // DataSet ds = new DataSet(); // ds = DB.ExecuteDataset(sql); // if (ds != null && ds.Tables[0].Rows.Count > 0) // { // decimal Amt = Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["RecognizedAmt"]); // string sql1 = "Select GL_Journal_ID from C_RevenueRecognition_Run Where C_RevenueRecognition_Plan_ID = " + revenueRecognitionPlan.GetC_RevenueRecognition_Plan_ID() + " And NVL(GL_Journal_ID,0) > 0 AND RowNum=1"; // int GL_Journal_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql1)); // MJournal journal = new MJournal(GetCtx(), GL_Journal_ID, Get_TrxName()); // log.Info(ToString()); // // Journal // MJournal reverse = new MJournal(journal); // reverse.SetDateDoc(DateTime.Now); // reverse.SetC_Period_ID(journal.GetC_Period_ID()); // int Period_ID = MPeriod.GetC_Period_ID(GetCtx(), DateTime.Now); // reverse.SetDateAcct(DateTime.Now); // if (reverse.Save()) // { // MJournalLine[] journalLines = journal.GetLines(false); // if (journalLines.Length > 0) // { // for (int j = 0; j < journalLines.Length; j++) // { // MJournalLine journalLine = journalLines[j]; // MJournalLine newjournalLine = new MJournalLine(GetCtx(), 0, Get_TrxName()); // PO.CopyValues(journalLine, newjournalLine, GetAD_Client_ID(), GetAD_Org_ID()); // newjournalLine.SetGL_Journal_ID(reverse.GetGL_Journal_ID()); // newjournalLine.SetDateAcct(DateTime.Now); // // Amounts // if (newjournalLine.GetAmtAcctCr() > 0) // { // newjournalLine.SetAmtAcctDr(0); // newjournalLine.SetAmtSourceDr(0); // newjournalLine.SetAmtSourceCr(Decimal.Negate(Amt)); // newjournalLine.SetAmtAcctCr(Decimal.Negate(Amt)); // } // else // { // newjournalLine.SetAmtAcctDr(Decimal.Negate(Amt)); // newjournalLine.SetAmtSourceDr(Decimal.Negate(Amt)); // newjournalLine.SetAmtSourceCr(0); // newjournalLine.SetAmtAcctCr(0); // } // newjournalLine.SetIsGenerated(true); // newjournalLine.SetProcessed(false); // newjournalLine.Save(); // if (j == 1) // { // break; // } // } // } // } // if (reverse != null && reverse.GetDocStatus() != "CO") // { // reverse.CompleteIt(); // reverse.SetProcessed(true); // reverse.SetDocStatus("CO"); // reverse.SetDocAction("CL"); // reverse.Save(Get_TrxName()); // if (DocNo == null) // { // DocNo = reverse.GetDocumentNo(); // } // int count = Util.GetValueOfInt(DB.ExecuteQuery("Update C_RevenueRecognition_Run Set GL_Journal_ID=null WHere C_RevenueRecognition_Plan_ID=" + revenueRecognitionPlan.GetC_RevenueRecognition_Plan_ID())); // int count1 = Util.GetValueOfInt(DB.ExecuteQuery("Update C_RevenueRecognition_Plan Set RecognizedAmt=RecognizedAmt - " + Amt + " WHere C_RevenueRecognition_Plan_ID=" + revenueRecognitionPlan.GetC_RevenueRecognition_Plan_ID())); // } // } // } //} #endregion Get_TrxName().Commit(); if (journal_ID != null) { for (int i = 0; i < journal_ID.Length; i++) { if (journal_ID[i] > 0) { string result = RevenueRun.CompleteOrReverse(GetCtx(), journal_ID[i], 169, "CO"); if (!String.IsNullOrEmpty(result)) { journalIDS += ", " + journal_ID[i] + " " + result; } } } } if (DocNo == null) { return(Msg.GetMsg(GetCtx(), "FoundNoRevenueRecognitionPlan")); } } else { return(Msg.GetMsg(GetCtx(), "NotRecoganized")); } } catch (Exception ex) { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "GLJournalnotallocateddueto") + ex.Message); Get_TrxName().Rollback(); return(ex.Message); } if (!String.IsNullOrEmpty(journalIDS)) { return(Msg.GetMsg(GetCtx(), "GLJournalCreated") + DocNo + ", " + Msg.GetMsg(GetCtx(), "GLJournalNotCompleted") + journalIDS); } else { return(Msg.GetMsg(GetCtx(), "GLJournalCreated") + DocNo); } }
/// <summary> /// Create Payment for BankStatement /// </summary> /// <param name="bsl">bank statement Line</param> /// <returns>Message</returns> private String CreatePayment(MBankStatementLine bsl) { if (bsl == null || bsl.GetC_Payment_ID() != 0) { return("--"); } log.Fine(bsl.ToString()); if (bsl.GetC_Invoice_ID() == 0 && bsl.GetC_BPartner_ID() == 0) { throw new Exception("@NotFound@ @C_Invoice_ID@ / @C_BPartner_ID@"); } // MBankStatement bs = new MBankStatement(GetCtx(), bsl.GetC_BankStatement_ID(), Get_Trx()); // //Check the Column Exists or not then Pass the Colums as parameters for CreatePayment method int conversionType = bsl.Get_ColumnIndex("C_ConversionType_ID") > 0 ? bsl.Get_ValueAsInt("C_ConversionType_ID") : 0; int _order_Id = bsl.Get_ColumnIndex("C_Order_ID") > 0 ? bsl.Get_ValueAsInt("C_Order_ID") : 0; MPayment payment = CreatePayment(bsl.GetC_Invoice_ID(), bsl.GetC_BPartner_ID(), bsl.GetC_Currency_ID(), bsl.GetStmtAmt(), bsl.GetTrxAmt(), bs.GetC_BankAccount_ID(), bsl.GetStatementLineDate(), bsl.GetDateAcct(), bsl.GetDescription(), bsl.GetAD_Org_ID(), conversionType, _order_Id); if (payment == null && !string.IsNullOrEmpty(_message)) { return(_message); } //Update Bank StatementLine //Created new Object for Payment to get Updated Payment Record MPayment mPayment = new MPayment(GetCtx(), payment.GetC_Payment_ID(), payment.Get_Trx()); _message = bsl.SetPayments(mPayment); if (string.IsNullOrEmpty(_message)) { if (!bsl.Save(Get_Trx())) { Get_Trx().Rollback(); ValueNamePair pp = VLogger.RetrieveError(); //to get Exact Error Message first get Value from GetName() else GetValue() string error = pp != null?pp.GetName() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.GetValue() : ""; if (string.IsNullOrEmpty(error)) { error = pp != null?pp.ToString() : ""; } } return(!string.IsNullOrEmpty(error) ? error : "DatanotSaved"); } else { String retString = "@C_Payment_ID@ = " + mPayment.GetDocumentNo(); if (Env.Signum(payment.GetOverUnderAmt()) != 0) { retString += " - @OverUnderAmt@=" + mPayment.GetOverUnderAmt(); } Get_Trx().Commit(); return(retString); } } else { Get_Trx().Rollback(); return(_message); } }
/// <SUMmary> /// Oppportunity Products /// </SUMmary> /// <returns>No of Lines created</returns> private int OnlyOpportunityProducts() { if (!Env.IsModuleInstalled("VA073_")) { //sql = " SELECT distinct(pl.m_product_id) FROM c_projectline pl INNER JOIN c_project p ON p.c_project_id = pl.c_project_id WHERE p.c_order_id IS NULL" // + " AND p.ref_order_id IS ANDNULL pl.m_product_id NOT IN (SELECT DISTINCT(M_Product_ID) FROM c_forecastline fl " // + " INNER JOIN c_forecast f ON (fl.c_forecast_id = f.c_forecast_id) WHERE f.c_period_id = " + C_Period_ID // + " AND f.ad_client_id = " + GetCtx().GetAD_Client_ID() + " AND fl.isactive = 'Y')"; sql = " SELECT DISTINCT(pl.m_product_id) FROM c_projectline pl INNER JOIN c_project p ON p.c_project_id = pl.c_project_id WHERE p.c_order_id IS NULL" + " AND p.ref_order_id IS NULL AND pl.m_product_id NOT IN (SELECT m_product_id FROM c_masterforecastline WHERE isactive = 'Y' AND c_masterforecast_id = " + GetRecord_ID() + ")"; IDataReader idr = null; try { idr = DB.ExecuteReader(sql, null, mf.Get_Trx()); while (idr.Read()) { Decimal?totalQtyOpp = 0; Decimal?totalPriceOpp = 0; sql = "SELECT SUM(nvl(pl.plannedqty,0)) AS Quantity ,SUM(NVL(pl.plannedqty,0) * NVL(pl.plannedprice,0)) AS Price, p.C_Currency_ID,pl.C_UOM_ID" + " FROM c_projectline pl INNER JOIN c_project p ON (p.c_project_id = pl.c_project_id) " + " WHERE " + "pl.planneddate BETWEEN (SELECT startdate FROM c_period WHERE c_period_id = " + C_Period_ID + ") " + " AND (SELECT enddate FROM c_period WHERE c_period_id = " + C_Period_ID + ") " + "AND pl.m_product_id = " + Util.GetValueOfInt(idr[0]) + " AND p.c_order_id IS NULL AND p.ref_order_id IS NULL AND pl.isactive = 'Y'" + " GROUP BY C_Currency_ID,pl.C_UOM_ID"; // totalQtyOpp = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, null)); //sql = " SELECT SUM(NVL(pl.plannedqty,0) * NVL(pl.plannedprice,0)) FROM c_projectline pl INNER JOIN c_project p ON (p.c_project_id = pl.c_project_id) " // + " WHERE " + //"pl.planneddate BETWEEN (SELECT startdate FROM c_period WHERE c_period_id = " + C_Period_ID + ") " //+ " AND (SELECT enddate FROM c_period WHERE c_period_id = " + C_Period_ID + ") " + //" AND pl.m_product_id = " + Util.GetValueOfInt(idr[0]) + " AND p.c_order_id IS NULL AND p.ref_order_id IS NULL AND pl.isactive = 'Y'"; //totalPriceOpp = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, null)); dsOpp = DB.ExecuteDataset(sql, null, mf.Get_Trx()); if (dsOpp != null && dsOpp.Tables[0].Rows.Count > 0) { //Conversion from Project to MasterForecast Currency totalPriceOpp = MConversionRate.Convert(mf.GetCtx(), Util.GetValueOfDecimal(dsOpp.Tables[0].Rows[0]["Price"]), Util.GetValueOfInt(dsOpp.Tables[0].Rows[0]["C_Currency_ID"]), Currency, Util.GetValueOfDateTime(mf.Get_Value("TRXDATE")), Util.GetValueOfInt(mf.Get_Value("C_ConversionType_ID")), mf.GetAD_Client_ID(), mf.GetAD_Org_ID()); //Conversion from BaseUOM to UOM on Project Line totalQtyOpp = MUOMConversion.ConvertProductFrom(mf.GetCtx(), Util.GetValueOfInt(idr[0]), Util.GetValueOfInt(dsOpp.Tables[0].Rows[0]["C_UOM_ID"]), Util.GetValueOfDecimal(dsOpp.Tables[0].Rows[0]["Quantity"])); } if (totalQtyOpp.Value > 0) { Decimal?avgPrice = Decimal.Divide(totalPriceOpp.Value, totalQtyOpp.Value); avgPrice = Decimal.Round(avgPrice.Value, 2, MidpointRounding.AwayFromZero); mfLine = GenerateMasterForecast(Util.GetValueOfInt(idr[0]), 0, Util.GetValueOfDecimal(Decimal.Zero), totalQtyOpp, avgPrice); if (!mfLine.Save()) { ValueNamePair vp = VLogger.RetrieveError(); if (vp != null) { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved") + vp.GetValue() + " - " + vp.GetName()); } else { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved")); } } } } if (idr != null) { idr.Close(); idr = null; } } catch { if (idr != null) { idr.Close(); idr = null; } } } else { //VA073_ Module is Installed sql = "SELECT pl.m_product_id, p.c_project_id,p.C_Currency_ID,pl.c_projectline_id, pl.plannedqty,pl.C_UOM_ID," + "(NVL(pl.plannedqty,0) * NVL(pl.plannedprice,0)) AS Price,pl.M_AttributeSetInstance_ID " + " FROM C_Project p " + "INNER JOIN C_ProjectLine pl ON p.C_Project_ID = pl.C_Project_ID" + " WHERE p.c_order_id IS NULL AND p.ref_order_id IS NULL AND c_period_id = " + C_Period_ID + " AND p.AD_Org_ID = " + mf.GetAD_Org_ID() + " AND C_ProjectLine_ID NOT IN (SELECT C_ProjectLine_ID FROM va073_masterforecastlinedetail WHERE " + "AD_Org_ID = " + mf.GetAD_Org_ID() + " AND C_Period_ID=" + C_Period_ID + ") AND NVL(pl.M_Product_ID,0)>0 "; sql = MRole.GetDefault(GetCtx()).AddAccessSQL(sql, "C_Project", true, true); // fully qualified - RO dsOpp = new DataSet(); dsOpp = DB.ExecuteDataset(sql, null, mf.Get_Trx()); if (dsOpp != null && dsOpp.Tables[0].Rows.Count > 0) { for (int i = 0; i < dsOpp.Tables[0].Rows.Count; i++) { //Create MasterForecastline mfLine = GenerateMasterForecast(Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["M_Product_ID"]), Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]), 0, 0, 0); if (!mfLine.Save()) { ValueNamePair vp = VLogger.RetrieveError(); if (vp != null) { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved") + vp.GetValue() + " - " + vp.GetName()); } else { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved")); } } else { LineNo = Util.GetValueOfInt(DB.ExecuteScalar("SELECT NVL(MAX(LineNo), 0)+10 FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID(), null, mf.Get_Trx())); //Conversion from BaseUOM to UOM on Project Line OppQty = MUOMConversion.ConvertProductFrom(mf.GetCtx(), Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["M_Product_ID"]), Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["C_UOM_ID"]), Util.GetValueOfDecimal(dsOpp.Tables[0].Rows[i]["plannedqty"])); if (OppQty == null) { OppQty = Util.GetValueOfDecimal(dsOpp.Tables[0].Rows[i]["plannedqty"]); } //Convert Line Amount as per Currency Defined ON Master Forecast ConvertedAmt = MConversionRate.Convert(mf.GetCtx(), Util.GetValueOfDecimal(dsOpp.Tables[0].Rows[i]["Price"]), Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["C_Currency_ID"]), Currency, Util.GetValueOfDateTime(mf.Get_Value("TRXDATE")), Util.GetValueOfInt(mf.Get_Value("C_ConversionType_ID")), mf.GetAD_Client_ID(), mf.GetAD_Org_ID()); //Create Product Line Details po = GenerateProductLineDetails(mfLine, LineNo, 0, 0, Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["C_Project_ID"]), Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["C_ProjectLine_ID"]), 0, 0, C_Period_ID, Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["C_UOM_ID"]), Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["M_Product_ID"]), OppQty, ConvertedAmt, Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["M_AttributeSetInstance_ID"])); if (!po.Save()) { ValueNamePair vp = VLogger.RetrieveError(); if (vp != null) { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "ProductLineDetailNotSaved") + " for ProjectLine " + Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["C_ProjectLine_ID"]) + vp.GetValue() + " - " + vp.GetName()); } else { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "ProductLineDetailNotSaved") + " for ProjectLine " + Util.GetValueOfInt(dsOpp.Tables[0].Rows[i]["C_ProjectLine_ID"])); } } else { Count++; LineNo += 10; //Update quantities AND price at Product line sql = "UPDATE c_masterforecastline SET " + "ForcastQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Forecast_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " + "OppQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Project_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " + "VA073_SalesOrderQty =(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Order_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " + "TotalQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + ") , " + "Price= (Round((SELECT NVL(SUM(price),0)/ NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " + StdPrecision + ")), " + "PlannedRevenue =(ROUND((SELECT SUM(price) FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID() + ")," + StdPrecision + "))" + " WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID(); DB.ExecuteQuery(sql, null, mf.Get_Trx()); } } } } else { log.Log(Level.INFO, Msg.GetMsg(GetCtx(), "NoRecordFoundOpportunity")); } } return(Count); }
/// <summary> /// Complete the Payment Record /// </summary> /// <param name="ctx">Context</param> /// <param name="Record_ID">C_Payment_ID</param> /// <param name="Process_ID">AD_Process_ID</param> /// <param name="DocAction">Documnet Action</param> /// <returns>return message</returns> public string CompletePayment(Ctx ctx, int Record_ID, int Process_ID, string DocAction) { string result = ""; MRole role = MRole.Get(ctx, ctx.GetAD_Role_ID()); if (Util.GetValueOfBool(role.GetProcessAccess(Process_ID))) { DB.ExecuteQuery("UPDATE C_Payment SET DocAction = '" + DocAction + "' WHERE C_Payment_ID = " + Record_ID); MProcess proc = new MProcess(ctx, Process_ID, null); MPInstance pin = new MPInstance(proc, Record_ID); if (!pin.Save()) { ValueNamePair vnp = VLogger.RetrieveError(); string errorMsg = ""; if (vnp != null) { errorMsg = vnp.GetName(); if (errorMsg == "") { errorMsg = vnp.GetValue(); } } if (errorMsg == "") { result = Msg.GetMsg(ctx, "DocNotCompleted"); } return(result); } MPInstancePara para = new MPInstancePara(pin, 20); para.setParameter("DocAction", DocAction); if (!para.Save()) { //String msg = "No DocAction Parameter added"; // not translated } ProcessInfo pi = new ProcessInfo("WF", Process_ID); pi.SetAD_User_ID(ctx.GetAD_User_ID()); pi.SetAD_Client_ID(ctx.GetAD_Client_ID()); pi.SetAD_PInstance_ID(pin.GetAD_PInstance_ID()); pi.SetRecord_ID(Record_ID); pi.SetTable_ID(335); //AD_Table_ID=335 for C_Payment ProcessCtl worker = new ProcessCtl(ctx, null, pi, null); worker.Run(); if (pi.IsError()) { ValueNamePair vnp = VLogger.RetrieveError(); string errorMsg = ""; if (vnp != null) { errorMsg = vnp.GetName(); if (errorMsg == "") { errorMsg = vnp.GetValue(); } } if (errorMsg == "") { errorMsg = pi.GetSummary(); } if (errorMsg == "") { errorMsg = Msg.GetMsg(ctx, "DocNotCompleted"); } result = errorMsg; return(result); } else { result = ""; } } else { result = Msg.GetMsg(ctx, "NoAccess"); return(result); } return(result); }
/// <SUMmary> /// Sales Order Products /// </SUMmary> /// <returns>No of lines created</returns> private int SalesOrderProducts() { sql = "SELECT ol.m_product_id,ol.QtyOrdered,M_AttributeSetInstance_ID,ol.C_UOM_ID," + " ol.C_OrderLine_ID,o.C_Order_ID,(NVL(PriceEntered,0) * NVL(QtyEntered,0)) AS Price,o.C_Currency_ID FROM C_Order o " + " INNER JOIN C_OrderLine ol ON o.C_Order_ID = ol.C_Order_ID " + " INNER JOIN C_Doctype d ON o.c_DocTypeTarget_ID = d.C_Doctype_ID " + " WHERE d.DocBaseType='" + MDocBaseType.DOCBASETYPE_SALESORDER + "' " + " AND d.DocSubTypeSo NOT IN ('" + MDocType.DOCSUBTYPESO_BlanketOrder + "','" + MDocType.DOCSUBTYPESO_Proposal + "')" + " AND o.IsSOTrx='Y' AND o.IsReturnTrx='N' AND o.AD_Org_ID = " + mf.GetAD_Org_ID() + " AND o.DateOrdered BETWEEN (SELECT startdate FROM C_Period WHERE C_Period_ID = " + C_Period_ID + ") " + " AND (SELECT enddate FROM C_Period WHERE C_Period_ID = " + C_Period_ID + ") AND ol.QtyOrdered > ol.QtyDelivered " + " AND ol.C_OrderLine_ID NOT IN (SELECT C_OrderLine_ID FROM va073_masterforecastlinedetail WHERE " + "AD_Org_ID = " + mf.GetAD_Org_ID() + " AND C_Period_ID=" + C_Period_ID + ") AND NVL(ol.M_Product_ID,0)>0 AND o.DocStatus IN('CO','CL') "; sql = MRole.GetDefault(GetCtx()).AddAccessSQL(sql, "C_Order", true, true); // fully qualified - RO dsOrder = new DataSet(); dsOrder = DB.ExecuteDataset(sql, null, mf.Get_Trx()); if (dsOrder != null && dsOrder.Tables[0].Rows.Count > 0) { for (int i = 0; i < dsOrder.Tables[0].Rows.Count; i++) { //create MasterForecastLine mfLine = GenerateMasterForecast(Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["M_Product_ID"]), Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]), 0, 0, 0); if (!mfLine.Save()) { ValueNamePair vp = VLogger.RetrieveError(); if (vp != null) { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved") + vp.GetValue() + " - " + vp.GetName()); } else { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved")); } } else { LineNo = Util.GetValueOfInt(DB.ExecuteScalar("SELECT NVL(MAX(LineNo), 0)+10 FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID(), null, mf.Get_Trx())); //Convert Line Amount as per Currency Defined ON Master Forecast ConvertedAmt = MConversionRate.Convert(mf.GetCtx(), Util.GetValueOfDecimal(dsOrder.Tables[0].Rows[i]["Price"]), Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["C_Currency_ID"]), Currency, Util.GetValueOfDateTime(mf.Get_Value("TRXDATE")), Util.GetValueOfInt(mf.Get_Value("C_ConversionType_ID")), mf.GetAD_Client_ID(), mf.GetAD_Org_ID()); //Create Product Line Details po = GenerateProductLineDetails(mfLine, LineNo, Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["C_Order_ID"]), Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["C_OrderLine_ID"]), 0, 0, 0, 0, C_Period_ID, Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["C_UOM_ID"]), Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["M_Product_ID"]), Util.GetValueOfDecimal(dsOrder.Tables[0].Rows[i]["QtyOrdered"]), ConvertedAmt, Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["M_AttributeSetInstance_ID"])); if (!po.Save()) { ValueNamePair vp = VLogger.RetrieveError(); if (vp != null) { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "ProductLineDetailNotSaved") + "for OrderLine" + Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["C_OrderLine_ID"]) + vp.GetValue() + " - " + vp.GetName()); } else { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "ProductLineDetailNotSaved") + "for OrderLine" + Util.GetValueOfInt(dsOrder.Tables[0].Rows[i]["C_OrderLine_ID"])); } } else { Count++; LineNo += 10; //Update quantities AND price at Product line sql = "UPDATE c_masterforecastline SET " + "ForcastQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Forecast_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " + "OppQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Project_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " + "VA073_SalesOrderQty =(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Order_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " + "TotalQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + ") , " + "Price= (Round((SELECT NVL(SUM(price),0)/ NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " + StdPrecision + ")), " + "PlannedRevenue =(ROUND((SELECT SUM(price) FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID() + ")," + StdPrecision + "))" + " WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID(); DB.ExecuteQuery(sql, null, mf.Get_Trx()); } } } } else { log.Log(Level.INFO, Msg.GetMsg(GetCtx(), "NoRecordFoundSalesOrder")); } return(Count); }
//Thread worker = null; /// <summary> /// Start Workflow and Wait for completion. /// </summary> /// <param name="pi">process info with Record_ID record for the workflow</param> /// <returns>process</returns> public MWFProcess StartWait(ProcessInfo pi) { const int SLEEP = 500; // 1/2 sec const int MAXLOOPS = 160; // 50;// 30; // 15 sec // MWFProcess process = Start(pi); if (process == null) { return(null); } //Causes the currently executing thread object to temporarily pause //and allow other threads to execute. //Thread.yield(); Thread.Sleep(0); StateEngine state = process.GetState(); //worker = new Thread(new ThreadStart(process.Run)); //worker.Start(); int loops = 0; while (!state.IsClosed() && !state.IsSuspended() && !state.IsBackground()) { if (loops > MAXLOOPS) { // MessageBox.Show("Timeout after sec " + ((SLEEP * MAXLOOPS) / 1000)); pi.SetSummary(Msg.GetMsg(GetCtx(), "ProcessRunning", true)); pi.SetIsTimeout(true); return(process); } try { Thread.Sleep(SLEEP); loops++; } catch (Exception e) { log.Log(Level.SEVERE, "Interrupted", e); pi.SetSummary("Interrupted"); return(process); } //Thread.yield(); Thread.Sleep(0); state = process.GetState(); } String summary = process.GetProcessMsg(); // Change to get the Error Message and Display the Message ValueNamePair vp = VLogger.RetrieveAdvDocNoError(); if (vp != null) { summary = vp.GetValue(); } // Change to get the Error Message and Display the Message if (summary == null || summary.Trim().Length == 0) { // in case of Suspend (User Approval) show the workflow node on which it is suspended for approval if (state != null && state.GetState() == StateEngine.STATE_SUSPENDED) { string node = Util.GetValueOfString(DB.ExecuteScalar(@"SELECT n.Name FROM AD_WF_Activity ac INNER JOIN AD_WF_Node n ON ac.AD_WF_Node_ID = n.AD_WF_Node_ID WHERE ac.AD_WF_Process_ID = " + process.Get_ID() + " AND ac.WFState = '" + StateEngine.STATE_SUSPENDED + "'")); if (!String.IsNullOrEmpty(node)) { summary = state.ToString() + " " + Msg.GetMsg(GetCtx(), "For") + " " + node; } } else { summary = state.ToString(); } } pi.SetSummary(summary, state.IsTerminated() || state.IsAborted()); log.Fine(summary); return(process); }
/// <SUMmary> /// Team Forecast Products /// </SUMmary> /// <returns>No of lines created</returns> private int TeamForecastProduct() { sql = @"SELECT fl.M_Product_ID,fl.M_AttributeSetInstance_ID,fl.qtyentered,fl.BaseQty,f.C_Forecast_ID, C_ForecastLine_ID,f.C_Period_ID,fl.C_UOM_ID,NVL(pricestd,0) AS Price,f.C_Currency_ID FROM C_Forecast f " + " INNER JOIN C_Forecastline fl ON fl.c_forecast_id = f.c_forecast_id " + " WHERE f.c_period_id = " + C_Period_ID + " AND f.AD_Org_ID = " + mf.GetAD_Org_ID() + " AND f.isactive = 'Y' AND f.processed = 'Y'" + " AND C_ForecastLine_ID NOT IN (SELECT C_ForecastLine_ID FROM VA073_MasterForecastlinedetail WHERE " + "AD_Org_ID = " + mf.GetAD_Org_ID() + " AND C_Period_ID=" + C_Period_ID + ") AND NVL(fl.M_Product_ID,0)>0 "; sql = MRole.GetDefault(mf.GetCtx()).AddAccessSQL(sql, "C_Forecast", true, true); // fully qualified - RO dsForecast = new DataSet(); dsForecast = DB.ExecuteDataset(sql, null, mf.Get_Trx()); if (dsForecast != null && dsForecast.Tables[0].Rows.Count > 0) { for (int i = 0; i < dsForecast.Tables[0].Rows.Count; i++) { //Create MasterForecastLine mfLine = GenerateMasterForecast(Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["M_Product_ID"]), Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["M_AttributeSetInstance_ID"]), 0, 0, 0); if (!mfLine.Save()) { ValueNamePair vp = VLogger.RetrieveError(); if (vp != null) { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved") + vp.GetValue() + " - " + vp.GetName()); } else { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved")); } } else { LineNo = Util.GetValueOfInt(DB.ExecuteScalar("SELECT NVL(MAX(LineNo), 0)+10 FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID(), null, mf.Get_Trx())); //Convert Line Amount as per Currency Defined ON Master Forecast ConvertedAmt = MConversionRate.Convert(mf.GetCtx(), Util.GetValueOfDecimal(dsForecast.Tables[0].Rows[i]["Price"]), Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["C_Currency_ID"]), Currency, Util.GetValueOfDateTime(mf.Get_Value("TRXDATE")), Util.GetValueOfInt(mf.Get_Value("C_ConversionType_ID")), mf.GetAD_Client_ID(), mf.GetAD_Org_ID()); //Create Product Line Details po = GenerateProductLineDetails(mfLine, LineNo, 0, 0, 0, 0, Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["C_Forecast_ID"]), Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["C_ForecastLine_ID"]), Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["C_Period_ID"]), mfLine.GetC_UOM_ID(), Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["M_Product_ID"]), Util.GetValueOfDecimal(dsForecast.Tables[0].Rows[i]["qtyentered"]), ConvertedAmt, Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["M_AttributeSetInstance_ID"])); if (!po.Save()) { ValueNamePair vp = VLogger.RetrieveError(); if (vp != null) { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "ProductLineDetailNotSaved") + " for ForecastLine " + Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["C_ForecastLine_ID"]) + " " + vp.GetValue() + " - " + vp.GetName()); } else { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "ProductLineDetailNotSaved") + " for ForecastLine " + Util.GetValueOfInt(dsForecast.Tables[0].Rows[i]["C_ForecastLine_ID"])); } } else { //Update quantities AND Price at Product line Count++; LineNo += 10; sql = "UPDATE c_masterforecastline SET " + "ForcastQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Forecast_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " + "OppQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Project_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " + "VA073_SalesOrderQty =(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE NVL(C_Order_ID,0)>0 AND c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " + "TotalQty=(SELECT NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE c_masterforecastline_ID=" + mfLine.GetC_MasterForecastLine_ID() + ") , " + "Price= (Round((SELECT NVL(SUM(price),0)/ NVL(SUM(QtyEntered),0) FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID() + "), " + StdPrecision + ")), " + "PlannedRevenue =(ROUND((SELECT SUM(price) FROM VA073_MasterForecastLineDetail WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID() + ")," + StdPrecision + "))" + " WHERE C_MasterForecastLine_ID=" + mfLine.GetC_MasterForecastLine_ID(); DB.ExecuteQuery(sql, null, mf.Get_Trx()); } } } } else { log.Log(Level.INFO, Msg.GetMsg(GetCtx(), "NoRecordFoundForecast")); } return(Count); }
/// <summary> /// Create New Role /// </summary> /// <param name="Name"></param> /// <param name="userLevel"></param> /// <param name="OrgID"></param> /// <returns></returns> public String AddNewRole(string Name, string userLevel, List <int> OrgID) { string info = ""; string msg; int AD_Role_Table_ID = Convert.ToInt32(DB.ExecuteScalar("SELECT AD_Table_ID FROM AD_Table WHERE TableName='AD_Role'", null, null)); try { string sql = @"SELECT AD_Column_ID,ColumnName, defaultvalue FROM AD_Column WHERE AD_Table_ID =" + AD_Role_Table_ID + @" AND isActive ='Y' AND defaultvalue IS NOT NULL"; DataSet ds = DB.ExecuteDataset(sql); // Get Default Values if (ds == null || ds.Tables[0].Rows.Count == 0) { return(VAdvantage.Utility.Msg.GetMsg(ctx, "DefaultValueNotFound")); } MRole role = new MRole(ctx, 0, null); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) // Setting Default Values { string value = ds.Tables[0].Rows[i]["DefaultValue"].ToString(); if (value.StartsWith("@")) { value = value.Substring(0, value.Length - 1); string columnName = value.Substring(value.IndexOf("@") + 1); value = ctx.GetContext(columnName); // get global context } role.Set_Value(ds.Tables[0].Rows[i]["ColumnName"].ToString(), value); } role.SetIsManual(true); role.SetName(Name); role.SetUserLevel(userLevel); if (role.Save()) { if (OrgID != null) { for (int i = 0; i < OrgID.Count; i++) // Assigning org access to role { MOrg org = new MOrg(ctx, OrgID[i], null); MRoleOrgAccess roles = new MRoleOrgAccess(org, role.GetAD_Role_ID()); roles.SetAD_Client_ID(ctx.GetAD_Client_ID()); roles.SetAD_Org_ID(OrgID[i]); roles.SetIsReadOnly(false); roles.Save(); } } } else { ValueNamePair ppE = VAdvantage.Logging.VLogger.RetrieveError(); if (ppE != null) { msg = ppE.GetValue(); info = ppE.GetName(); } } return(info); } catch (Exception ex) { return(ex.Message); } //rr.Set_Value( }
/// <SUMmary> /// Consolidate Data FROM sales order , Team Forecast, Opportunity /// </SUMmary> /// <returns>Info</returns> protected override string DoIt() { mf = new X_C_MasterForecast(GetCtx(), GetRecord_ID(), Get_Trx()); if (Util.GetValueOfInt(mf.Get_Value("M_PriceList_ID")) == 0) { return(Msg.GetMsg(mf.GetCtx(), "CreatelinesManually")); } C_Period_ID = mf.GetC_Period_ID(); Currency = Util.GetValueOfInt(mf.Get_Value("C_Currency_ID")); StdPrecision = Util.GetValueOfInt(DB.ExecuteScalar("SELECT StdPrecision FROM C_Currency WHERE C_Currency_ID=" + Currency, null, null)); //Get Table_Id to create PO Object // sql = @"SELECT AD_TABLE_ID FROM AD_TABLE WHERE tablename LIKE 'VA073_MasterForecastLineDetail' AND IsActive = 'Y'"; // tableId = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null)); // tbl = new MTable(GetCtx(), tableId, null); tbl = MTable.Get(GetCtx(), "VA073_MasterForecastLineDetail"); // sql = "delete FROM c_masterforecastline WHERE c_masterforecast_id = " + mf.GetC_MasterForecast_ID(); // int count = DB.ExecuteQuery(sql, null, null); if (C_Period_ID != 0) { sql = "SELECT COUNT(C_MasterForecastLine_ID) FROM c_masterforecastline WHERE c_masterforecast_id = " + GetRecord_ID(); int count = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null)); if (count > 0) { sql = "UPDATE c_masterforecastline set Processed = 'Y' WHERE c_masterforecast_id = " + GetRecord_ID(); int res = Util.GetValueOfInt(DB.ExecuteQuery(sql, null, null)); sql = "UPDATE c_masterforecast set Processed = 'Y' WHERE c_masterforecast_id = " + GetRecord_ID(); res = Util.GetValueOfInt(DB.ExecuteQuery(sql, null, null)); msg = Msg.GetMsg(GetCtx(), "RecordsProcessed"); return(msg); } if (!Env.IsModuleInstalled("VA073_")) { sql = "SELECT DISTINCT(M_Product_ID) FROM c_forecastline fl INNER JOIN c_forecast f ON (fl.c_forecast_id = f.c_forecast_id) WHERE f.c_period_id = " + C_Period_ID + " AND f.ad_client_id = " + GetCtx().GetAD_Client_ID() + " AND f.isactive = 'Y' AND f.processed = 'Y'"; IDataReader idr = null; try { idr = DB.ExecuteReader(sql, null, mf.Get_Trx()); while (idr.Read()) { Decimal?totalQtyTeam = 0; Decimal?totalPriceTeam = 0; Decimal?totalQtyOpp = 0; Decimal?totalPriceOpp = 0; sql = "SELECT SUM(nvl(qtyentered,0)) AS Quantity,SUM(nvl(pricestd,0)) AS Price,f.C_Currency_ID FROM c_forecastline fl" + " INNER JOIN C_Forecast f ON f.C_Forecast_ID = fl.C_Forecast_ID " + " WHERE fl.m_product_id = " + Util.GetValueOfInt(idr[0]) + " AND f.Processed = 'Y' AND f.isactive = 'Y'" + " GROUP BY f.C_Currency_ID"; //totalQtyTeam = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, null)); //// sql = "SELECT SUM(nvl(qtyentered,0) * nvl(pricestd,0)) FROM c_forecastline WHERE m_product_id = " + Util.GetValueOfInt(idr[0]) + " AND Processed = 'Y'"; //sql = "SELECT SUM(nvl(pricestd,0)) FROM c_forecastline WHERE m_product_id = " + Util.GetValueOfInt(idr[0]) + " AND Processed = 'Y' AND isactive = 'Y'"; //totalPriceTeam = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, Get_Trx())); dsForecast = DB.ExecuteDataset(sql, null, mf.Get_Trx()); if (dsForecast != null && dsForecast.Tables[0].Rows.Count > 0) { totalPriceTeam = MConversionRate.Convert(mf.GetCtx(), Util.GetValueOfDecimal(dsForecast.Tables[0].Rows[0]["Price"]), Util.GetValueOfInt(dsForecast.Tables[0].Rows[0]["C_Currency_ID"]), Currency, Util.GetValueOfDateTime(mf.Get_Value("TRXDATE")), Util.GetValueOfInt(mf.Get_Value("C_ConversionType_ID")), mf.GetAD_Client_ID(), mf.GetAD_Org_ID()); totalQtyTeam = Util.GetValueOfDecimal(dsForecast.Tables[0].Rows[0]["Quantity"]); } if (mf.IsIncludeOpp()) { sql = "SELECT SUM(NVL(pl.plannedqty,0)) AS Quantity ,SUM(NVL(pl.plannedqty,0) * NVL(pl.plannedprice,0)) AS Price, p.C_Currency_ID,pl.C_UOM_ID" + " FROM c_projectline pl INNER JOIN c_project p ON (p.c_project_id = pl.c_project_id) " + " WHERE " + "pl.planneddate BETWEEN (SELECT startdate FROM c_period WHERE c_period_id = " + C_Period_ID + ") " + " AND (SELECT enddate FROM c_period WHERE c_period_id = " + C_Period_ID + ") " + "AND pl.m_product_id = " + Util.GetValueOfInt(idr[0]) + " AND p.c_order_id IS NULL AND p.ref_order_id IS NULL AND pl.isactive = 'Y'" + " GROUP BY C_Currency_ID,pl.C_UOM_ID"; //totalQtyOpp = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, Get_Trx())); //sql = " SELECT SUM(NVL(pl.plannedqty,0) * NVL(pl.plannedprice,0)) FROM c_projectline pl INNER JOIN c_project p ON (p.c_project_id = pl.c_project_id) " // + " WHERE " + // " pl.planneddate BETWEEN (SELECT startdate FROM c_period WHERE c_period_id = " + C_Period_ID + ") " // + " AND (SELECT enddate FROM c_period WHERE c_period_id = " + C_Period_ID + ") " + // " AND pl.m_product_id = " + Util.GetValueOfInt(idr[0]) + // " AND p.c_order_id IS NULL AND p.ref_order_id IS NULL AND pl.isactive = 'Y' AND p.ad_client_id = " + mf.GetAD_Client_ID(); dsOpp = DB.ExecuteDataset(sql, null, mf.Get_Trx()); if (dsOpp != null && dsOpp.Tables[0].Rows.Count > 0) { //Conversion from Project to MasterForecast Currency totalPriceOpp = MConversionRate.Convert(mf.GetCtx(), Util.GetValueOfDecimal(dsOpp.Tables[0].Rows[0]["Price"]), Util.GetValueOfInt(dsOpp.Tables[0].Rows[0]["C_Currency_ID"]), Currency, Util.GetValueOfDateTime(mf.Get_Value("TRXDATE")), Util.GetValueOfInt(mf.Get_Value("C_ConversionType_ID")), mf.GetAD_Client_ID(), mf.GetAD_Org_ID()); //Conversion from BaseUOM to UOM on Project Line totalQtyOpp = MUOMConversion.ConvertProductFrom(mf.GetCtx(), Util.GetValueOfInt(idr[0]), Util.GetValueOfInt(dsOpp.Tables[0].Rows[0]["C_UOM_ID"]), Util.GetValueOfDecimal(dsOpp.Tables[0].Rows[0]["Quantity"])); } } Decimal?totalPrice = Decimal.Add(totalPriceTeam.Value, totalPriceOpp.Value); Decimal?totalQty = Decimal.Add(totalQtyTeam.Value, totalQtyOpp.Value); if (totalQty.Value > 0) { Decimal?avgPrice = Decimal.Divide(totalPrice.Value, totalQty.Value); avgPrice = Decimal.Round(avgPrice.Value, 2, MidpointRounding.AwayFromZero); mfLine = GenerateMasterForecast(Util.GetValueOfInt(idr[0]), 0, totalQtyTeam, totalQtyOpp, avgPrice); if (!mfLine.Save()) { ValueNamePair vp = VLogger.RetrieveError(); if (vp != null) { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved") + vp.GetValue() + " - " + vp.GetName()); } else { log.Log(Level.SEVERE, Msg.GetMsg(GetCtx(), "MasterForecastLineNotSaved")); } } } } if (idr != null) { idr.Close(); idr = null; } } catch { if (idr != null) { idr.Close(); idr = null; } } if (mf.IsIncludeOpp()) { OnlyOpportunityProducts(); } mf.SetCurrentVersion(true); mf.SetProcessed(true); if (!mf.Save()) { log.SaveError("MasterForecastNotSaved", "MasterForecastNotSaved"); return(GetRetrievedError(mf, "MasterForecastNotSaved")); } msg = Msg.GetMsg(GetCtx(), "ProcessCompleted"); } else { //VA073 module installed -- Consolidate FROM Sales order , opportunity , Team Forecast TeamForecastProduct(); if (mf.IsIncludeOpp()) { OnlyOpportunityProducts(); } if (Util.GetValueOfBool(mf.Get_Value("VA073_IsIncludeOpenSO"))) { SalesOrderProducts(); } if (Count == 0) { mf.Get_Trx().Rollback(); } else { //UPDATE Master forecast Line Set processed to true sql = "UPDATE C_MasterForecastLine SET Processed='Y' WHERE C_MasterForecast_ID=" + GetRecord_ID(); DB.ExecuteQuery(sql, null, mf.Get_Trx()); //UPDATE Master forecast Set processed to true sql = "UPDATE C_MasterForecast SET Processed='Y' WHERE C_MasterForecast_ID=" + GetRecord_ID(); DB.ExecuteQuery(sql, null, mf.Get_Trx()); } msg = Msg.GetMsg(mf.GetCtx(), "ProductLinesDetailCreated") + Count; } } return(msg); }
public byte[] GenerateCrystalReport() { string reportPath = System.IO.Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "CReports\\Reports"); string reportImagePath = System.IO.Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "CReports\\Images"); //string _ReportImagePath = ""; //string _ReportPath = ""; string path = reportPath; //_ReportImagePath = reportImagePath; if (String.IsNullOrEmpty(path)) { throw new MissingFieldException("CrystalReportPathNotSet"); } if (reportName.IndexOf(":") < 0) { reportPath = path + "\\" + reportName; } else { reportPath = reportName; } ReportDocument rptBurndown = new ReportDocument(); if (File.Exists(reportPath)) //Check if the crystal report file exists in a specified location. { try { rptBurndown.Load(reportPath); //Set Connection Info ConnectionInfo.Get().SetAttributes(System.Configuration.ConfigurationManager.AppSettings["oracleConnectionString"]); //Application will pick database info from the property file. CrystalDecisions.Shared.ConnectionInfo crDbConnection = new CrystalDecisions.Shared.ConnectionInfo(); crDbConnection.IntegratedSecurity = false; crDbConnection.DatabaseName = ConnectionInfo.Get().Db_name; crDbConnection.UserID = ConnectionInfo.Get().Db_uid; crDbConnection.Password = ConnectionInfo.Get().Db_pwd; //crDbConnection.Type = ConnectionInfoType.Unknown; crDbConnection.ServerName = ConnectionInfo.Get().Db_host; CrystalDecisions.CrystalReports.Engine.Database crDatabase = rptBurndown.Database; CrystalDecisions.Shared.TableLogOnInfo oCrTableLoginInfo; foreach (CrystalDecisions.CrystalReports.Engine.Table oCrTable in crDatabase.Tables) { crDbConnection.IntegratedSecurity = false; crDbConnection.DatabaseName = ConnectionInfo.Get().Db_name; crDbConnection.UserID = ConnectionInfo.Get().Db_uid; crDbConnection.Password = ConnectionInfo.Get().Db_pwd; //crDbConnection.Type = ConnectionInfoType.Unknown; crDbConnection.ServerName = ConnectionInfo.Get().Db_host; oCrTableLoginInfo = oCrTable.LogOnInfo; oCrTableLoginInfo.ConnectionInfo = crDbConnection; oCrTable.ApplyLogOnInfo(oCrTableLoginInfo); } //Create Parameter query string sql = SqlQuery; StringBuilder sb = new StringBuilder(" WHERE "); if (_pi.GetRecord_ID() > 0 && _pi.GetTable_ID() > 0) { string tableName = DB.ExecuteScalar("SELECT TableName FROM AD_Table WHERE AD_TABLE_ID =" + _pi.GetTable_ID()).ToString(); sb.Append(tableName).Append("_ID = ").Append(_pi.GetRecord_ID()); } else { ProcessInfoUtil.SetParameterFromDB(_pi); ProcessInfoParameter[] parameters = _pi.GetParameter(); if (parameters.Count() > 0) { int loopCount = 0; for (int para = 0; para <= parameters.Count() - 1; para++) { string sInfo = parameters[para].GetInfo(); string sInfoTo = parameters[para].GetInfo_To(); if ((String.IsNullOrEmpty(sInfo) && String.IsNullOrEmpty(sInfoTo)) || sInfo == "NULL") { continue; } if (loopCount > 0) { sb.Append(" AND "); } string paramName = parameters[para].GetParameterName(); object paramValue = parameters[para].GetParameter(); object paramValueTo = parameters[para].GetParameter_To(); if (paramValue is DateTime) { sb.Append(paramName).Append(" BETWEEN ").Append(GlobalVariable.TO_DATE((DateTime)paramValue, true)); if (paramValueTo != null && paramValueTo.ToString() != String.Empty) { sb.Append(" AND ").Append(GlobalVariable.TO_DATE(((DateTime)paramValueTo).AddDays(1), true)); } else { sb.Append(" AND ").Append(GlobalVariable.TO_DATE(((DateTime)paramValue).AddDays(1), true)); } } else if (paramValue != null && paramValue.ToString().Contains(',')) { sb.Append(paramName).Append(" IN (") .Append(paramValue.ToString()).Append(")"); } else { sb.Append("Upper(").Append(paramName).Append(")").Append(" = Upper(") .Append(GlobalVariable.TO_STRING(paramValue.ToString()) + ")"); } loopCount++; } } } if (sb.Length > 7) { sql = sql + sb.ToString(); } //if (form.IsIncludeProcedure()) //{ // bool result = StartDBProcess(form.GetProcedureName(), parameters); //} DataSet ds = DB.ExecuteDataset(sql); if (ds == null) { ValueNamePair error = VLogger.RetrieveError(); throw new Exception(error.GetValue() + "BlankReportWillOpen"); } bool imageError = false; if (isIncludeImage) { for (int i_img = 0; i_img <= ds.Tables[0].Rows.Count - 1; i_img++) { String ImagePath = ""; String ImageField = ""; if (ds.Tables[0].Rows[i_img][imagePathField] != null) { ImagePath = ds.Tables[0].Rows[i_img][imagePathField].ToString(); ImageField = imageField; if (ds.Tables[0].Columns.Contains(ImageField)) { if (File.Exists(reportImagePath + "\\" + ImagePath)) { byte[] b = StreamFile(reportImagePath + "\\" + ImagePath); ds.Tables[0].Rows[i_img][ImageField] = b; } else { //ds.Tables[0].Rows.RemoveAt(i_img); imageError = true; } } else { imageError = true; } } else { imageError = true; } } } if (imageError) { // ShowMessage.Error("ErrorLoadingSomeImages", true); } //crystalReportViewer1.ReportSource = rptBurndown; //crystalReportViewer1.Refresh(); System.IO.Stream oStream; byte[] byteArray = null; rptBurndown.SetDataSource(ds.Tables[0]); //By karan approveed by lokesh...... //rptBurndown.PrintOptions.ApplyPageMargins(new CrystalDecisions.Shared.PageMargins(100, 360, 100, 360)); oStream = rptBurndown.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat); byteArray = new byte[oStream.Length]; oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length)); return(byteArray); //if (form.IsDirectPrint()) //{ // // rptBurndown.PrintOptions.PrinterName = Env.GetCtx().GetPrinterName(); // //rptBurndown.PrintToPrinter(1, false, 0, 0); //} } catch (Exception ex) { throw ex; } } else { throw new MissingFieldException("CouldNotFindTheCrystalReport"); } }
/// <summary> /// Create version fields against version tab /// </summary> /// <param name="tab"> Object of MTab </param> /// <param name="Ver_AD_Tab_ID"> Tab ID of Version window </param> /// <param name="Ver_AD_Table_ID"> Table ID of Version </param> /// <returns>string (Message)</returns> private string CreateVerFields(MTab tab, int Ver_AD_Tab_ID, int Ver_AD_Table_ID) { // Get all fields from Master Tab int[] fields = MTable.GetAllIDs("AD_Field", "AD_Tab_ID = " + tab.GetAD_Tab_ID(), Get_TrxName()); bool hasOrigCols = false; bool hasVerFields = false; bool hasVerCols = false; // Get columns from Master table DataSet origColDS = DB.ExecuteDataset("SELECT AD_Column_ID, Name,ColumnSql, ColumnName FROM AD_Column WHERE AD_Table_ID = " + tab.GetAD_Table_ID(), null, Get_TrxName()); if (origColDS != null && origColDS.Tables[0].Rows.Count > 0) { hasOrigCols = true; } // Get fields from Version Tab DataSet verFieldDS = DB.ExecuteDataset("SELECT f.AD_Column_ID, f.Name, f.AD_Field_ID, (SELECT c.AD_Element_ID FROM AD_Column c WHERE c.AD_Column_ID = f.AD_Column_ID) AS AD_Element_ID FROM AD_Field f WHERE f.AD_Tab_ID = " + Ver_AD_Tab_ID, null, Get_TrxName()); if (verFieldDS != null && verFieldDS.Tables[0].Rows.Count > 0) { hasVerFields = true; } // Get Columns from Version Table DataSet verColumnsDS = DB.ExecuteDataset("SELECT AD_Column_ID, Name, ColumnName FROM AD_Column WHERE AD_Table_ID = " + Ver_AD_Table_ID, null, Get_TrxName()); if (verColumnsDS != null && verColumnsDS.Tables[0].Rows.Count > 0) { hasVerCols = true; } StringBuilder sbColName = new StringBuilder(""); foreach (int fld in fields) { bool createNew = true; MField origFld = new MField(GetCtx(), fld, Get_TrxName()); // check if Field already exist for Version Tab else create new if (hasVerFields) { DataRow[] drFld = verFieldDS.Tables[0].Select("Name = '" + origFld.GetName() + "'"); if (drFld.Length > 0) { createNew = false; } } // if Field do not exist on Version tab if (createNew) { sbColName.Clear(); int VerColID = 0; // Get column Info from Column ID of Master Table DataRow[] drOrigColName = origColDS.Tables[0].Select("AD_Column_ID = " + origFld.GetAD_Column_ID()); if (drOrigColName.Length > 0) { if (Util.GetValueOfString(drOrigColName[0]["ColumnSQL"]).Trim() != "") { continue; } sbColName.Append(Util.GetValueOfString(drOrigColName[0]["ColumnName"])); // check whether Column exist in Version table with column name of Master Table // if column not found return with Message DataRow[] drVerCol = verColumnsDS.Tables[0].Select("ColumnName = '" + sbColName.ToString() + "'"); if (drVerCol.Length > 0) { VerColID = Util.GetValueOfInt(drVerCol[0]["AD_Column_ID"]); } else { log.Log(Level.SEVERE, "Version Column Not Found :: " + sbColName.ToString()); Get_TrxName().Rollback(); return(Msg.GetMsg(GetCtx(), "ColumnNameNotFound") + " :: " + sbColName.ToString()); } } else { log.Log(Level.SEVERE, "Column ID not found in Original table :: " + origFld.GetAD_Column_ID()); Get_TrxName().Rollback(); return(Msg.GetMsg(GetCtx(), "ColumnNameNotFound") + " :: " + origFld.GetAD_Column_ID()); } // Only create Version Field if Version Column found if (VerColID > 0) { // check if field is already created with column // else skip creating field int fldID = Util.GetValueOfInt(DB.ExecuteScalar("SELECT AD_Field_ID FROM AD_Field WHERE AD_Column_ID = " + VerColID + " AND AD_Tab_ID = " + Ver_AD_Tab_ID, null, Get_TrxName())); if (fldID <= 0) { // Create Field for Column, copy field from Master tables Field tab on Version Field against Version Tab MField verFld = new MField(GetCtx(), 0, Get_TrxName()); origFld.CopyTo(verFld); verFld.SetAD_Tab_ID(Ver_AD_Tab_ID); verFld.SetAD_Column_ID(VerColID); verFld.SetExport_ID(null); if (!verFld.Save()) { ValueNamePair vnp = VLogger.RetrieveError(); string error = ""; if (vnp != null) { error = vnp.GetName(); if (error == "" && vnp.GetValue() != null) { error = vnp.GetValue(); } } if (error == "") { error = "Error in creating Version Field"; } log.Log(Level.SEVERE, "Version Field not saved :: " + verFld.GetName() + " :: " + error); Get_TrxName().Rollback(); return(Msg.GetMsg(GetCtx(), "FieldNotSaved") + " :: " + verFld.GetName()); } } } } } // Fill Dataset again from Version Field verFieldDS = DB.ExecuteDataset("SELECT f.AD_Column_ID, f.Name, f.AD_Field_ID, (SELECT c.AD_Element_ID FROM AD_Column c WHERE c.AD_Column_ID = f.AD_Column_ID) AS AD_Element_ID FROM AD_Field f WHERE f.AD_Tab_ID = " + Ver_AD_Tab_ID, null, Get_TrxName()); // Create Default Fields against default Columns for Version tab string retMsg = CreateDefaultFields(Ver_AD_Tab_ID, verFieldDS, hasVerFields, verColumnsDS, Ver_AD_Table_ID); if (retMsg != "") { Get_TrxName().Rollback(); return(retMsg); } return(""); }
/// <summary> /// Get System Elements for Default Columns /// </summary> /// <param name="VerTblName">Table Name</param> public string GetSystemElements(string VerTblName) { // check if count in list is equal to default version columns if (_listDefVerElements.Count == listDefVerCols.Count) { return(""); } // Clear values from list _listDefVerElements.Clear(); // check if Primary key column is present in Columns list, if not present then add Primary Key column if (!listDefVerCols.Contains(VerTblName + "_ID")) { listDefVerCols.Add(VerTblName + "_ID"); } // Create comma separated string of all default version columns string DefSysEle = string.Join(",", listDefVerCols .Select(x => string.Format("'{0}'", x))); // Get System Elements and Column Names for all Version table columns DataSet dsDefVerCols = DB.ExecuteDataset("SELECT AD_Element_ID, ColumnName FROM AD_Element WHERE ColumnName IN (" + DefSysEle + ")", null, _trx); if (dsDefVerCols != null && dsDefVerCols.Tables[0].Rows.Count > 0) { // loop through all columns of version table to get System Elements // if not found then create new for (int i = 0; i < listDefVerCols.Count; i++) { DataRow[] drSysEle = dsDefVerCols.Tables[0].Select("ColumnName='" + listDefVerCols[i] + "'"); if (drSysEle.Length > 0) { if (!_listDefVerElements.Contains(Util.GetValueOfInt(drSysEle[0]["AD_Element_ID"]))) { _listDefVerElements.Add(Util.GetValueOfInt(drSysEle[0]["AD_Element_ID"])); } if (listDefVerCols[i] == VerTblName + "_ID") { listDefVerRef.Add(13); } } else { M_Element ele = new M_Element(GetCtx(), 0, _trx); ele.SetAD_Client_ID(0); ele.SetAD_Org_ID(0); ele.SetName(listDefVerCols[i]); ele.SetColumnName(listDefVerCols[i]); ele.SetPrintName(listDefVerCols[i]); if (!ele.Save()) { ValueNamePair vnp = VLogger.RetrieveError(); string error = ""; if (vnp != null) { error = vnp.GetName(); if (error == "" && vnp.GetValue() != null) { error = vnp.GetValue(); } } if (error == "") { error = "Error in creating System Element"; } log.Log(Level.SEVERE, error); _trx.Rollback(); return(Msg.GetMsg(GetCtx(), "ElementNotSaved")); } else { _listDefVerElements.Add(ele.GetAD_Element_ID()); if (ele.GetColumnName() == VerTblName + "_ID") { listDefVerRef.Add(13); } } } } } return(""); }
//Thread worker = null; /// <summary> /// Start Workflow and Wait for completion. /// </summary> /// <param name="pi">process info with Record_ID record for the workflow</param> /// <returns>process</returns> public MWFProcess StartWait(ProcessInfo pi) { const int SLEEP = 500; // 1/2 sec const int MAXLOOPS = 160; // 50;// 30; // 15 sec // MWFProcess process = Start(pi); if (process == null) { return(null); } //Causes the currently executing thread object to temporarily pause //and allow other threads to execute. //Thread.yield(); Thread.Sleep(0); StateEngine state = process.GetState(); //worker = new Thread(new ThreadStart(process.Run)); //worker.Start(); int loops = 0; while (!state.IsClosed() && !state.IsSuspended()) { if (loops > MAXLOOPS) { // MessageBox.Show("Timeout after sec " + ((SLEEP * MAXLOOPS) / 1000)); pi.SetSummary(Msg.GetMsg(GetCtx(), "ProcessRunning", true)); pi.SetIsTimeout(true); return(process); } try { Thread.Sleep(SLEEP); loops++; } catch (Exception e) { log.Log(Level.SEVERE, "Interrupted", e); pi.SetSummary("Interrupted"); return(process); } //Thread.yield(); Thread.Sleep(0); state = process.GetState(); } String summary = process.GetProcessMsg(); // Change to get the Error Message and Display the Message ValueNamePair vp = VLogger.RetrieveAdvDocNoError(); if (vp != null) { summary = vp.GetValue(); } // Change to get the Error Message and Display the Message if (summary == null || summary.Trim().Length == 0) { summary = state.ToString(); } pi.SetSummary(summary, state.IsTerminated() || state.IsAborted()); log.Fine(summary); return(process); }
/// <summary> /// Create default columns for Master Data Version Table /// e.g. Processed, Processing, IsApproved etc. /// </summary> /// <param name="Ver_AD_Table_ID"></param> /// <returns></returns> private string CreateDefaultVerCols(int Ver_AD_Table_ID) { DataSet dstblCols = DB.ExecuteDataset("SELECT ColumnName FROM AD_Column WHERE AD_Table_ID = " + Ver_AD_Table_ID, null, null); for (int i = 0; i < listDefVerCols.Count; i++) { bool hasCol = false; if (dstblCols != null && dstblCols.Tables[0].Rows.Count > 0) { DataRow[] dr = dstblCols.Tables[0].Select("ColumnName = '" + listDefVerCols[i] + "'"); if (dr != null && dr.Length > 0) { hasCol = true; } } if (hasCol) { continue; } MColumn colVer = new MColumn(GetCtx(), 0, _trx); colVer.SetExport_ID(null); colVer.SetAD_Table_ID(Ver_AD_Table_ID); colVer.SetColumnName(listDefVerCols[i]); colVer.SetAD_Element_ID(_listDefVerElements[i]); colVer.SetAD_Reference_ID(listDefVerRef[i]); //if (listDefVerCols[i] == "VersionValidFrom") // colVer.SetIsParent(true); if (listDefVerRef[i] == 10) { colVer.SetFieldLength(10); } if (listDefVerRef[i] == 14) { colVer.SetFieldLength(2000); } if (listDefVerRef[i] == 13) { colVer.SetIsKey(true); colVer.SetIsMandatory(true); colVer.SetIsMandatoryUI(true); } if (!colVer.Save()) { ValueNamePair vnp = VLogger.RetrieveError(); string error = ""; if (vnp != null) { error = vnp.GetName(); if (error == "" && vnp.GetValue() != null) { error = vnp.GetValue(); } } if (error == "") { error = "Error in creating Version Column " + listDefVerCols[i]; } log.Log(Level.SEVERE, "Version Column not created :: " + listDefVerCols[i] + " :: " + error); _trx.Rollback(); return(Msg.GetMsg(GetCtx(), "VersionColNotCreated")); } else { oldVerCol = colVer.GetAD_Column_ID(); } } return(""); }
} // doIt /// <summary> /// Process Expense Line /// </summary> /// <param name="te">header</param> /// <param name="tel">line</param> /// <param name="bp">bp</param> private void ProcessLine(MTimeExpense te, MTimeExpenseLine tel, MBPartner bp) { if (_order == null) { log.Info("New Order for " + bp + ", Project=" + tel.GetC_Project_ID()); _order = new MOrder(GetCtx(), 0, Get_TrxName()); _order.SetAD_Org_ID(tel.GetAD_Org_ID()); _order.SetC_DocTypeTarget_ID(MOrder.DocSubTypeSO_Standard); // _order.SetBPartner(bp); if (_order.GetC_BPartner_Location_ID() == 0) { log.Log(Level.SEVERE, "No BP Location: " + bp); AddLog(0, te.GetDateReport(), null, "No Location: " + te.GetDocumentNo() + " " + bp.GetName()); _order = null; return; } _order.SetM_Warehouse_ID(te.GetM_Warehouse_ID()); //Bhupendra: Add payment term // to check for if payment term is null if (bp.GetC_PaymentTerm_ID() == 0) { // set the default payment method as check int payTerm = GetPaymentTerm(); if (payTerm <= 0) { message = Msg.GetMsg(GetCtx(), "IsActivePaymentTerm"); return; } else { _order.SetC_PaymentTerm_ID(payTerm); } } else { //check weather paymentterm is active or not if (Util.GetValueOfString(DB.ExecuteScalar("SELECT IsActive FROM C_PaymentTerm WHERE C_PaymentTerm_ID=" + bp.GetC_PaymentTerm_ID(), null, Get_Trx())).Equals("Y")) { _order.SetC_PaymentTerm_ID(bp.GetC_PaymentTerm_ID()); } else { message = Msg.GetMsg(GetCtx(), "IsActivePaymentTerm"); return; } } // Bhupendra: added a cond to check for payment method if null // Added by mohit - to set payment method and sales rep id. if (bp.GetVA009_PaymentMethod_ID() == 0) { // set the default payment method as check int paymethod = GetPaymentMethod(); if (paymethod <= 0) { message = Msg.GetMsg(GetCtx(), "IsActivePaymentMethod"); return; } else { _order.SetVA009_PaymentMethod_ID(paymethod); } } else { //check weather the PaymentMethod is active or not if (Util.GetValueOfString(DB.ExecuteScalar("SELECT IsActive FROM VA009_PaymentMethod WHERE VA009_PaymentMethod_ID=" + bp.GetVA009_PaymentMethod_ID(), null, Get_Trx())).Equals("Y")) { _order.SetVA009_PaymentMethod_ID(bp.GetVA009_PaymentMethod_ID()); } else { message = Msg.GetMsg(GetCtx(), "IsActivePaymentMethod"); return; } } _order.SetSalesRep_ID(te.GetDoc_User_ID()); ////Added By Arpit asked by Surya Sir..................29-12-2015 //_order.SetSalesRep_ID(GetCtx().GetAD_User_ID()); //End if (tel.GetC_Activity_ID() != 0) { _order.SetC_Activity_ID(tel.GetC_Activity_ID()); } if (tel.GetC_Campaign_ID() != 0) { _order.SetC_Campaign_ID(tel.GetC_Campaign_ID()); } if (tel.GetC_Project_ID() != 0) { _order.SetC_Project_ID(tel.GetC_Project_ID()); // Optionally Overwrite BP Price list from Project MProject project = new MProject(GetCtx(), tel.GetC_Project_ID(), Get_TrxName()); if (project.GetM_PriceList_ID() != 0) { //check weather the PriceList is active or not if (Util.GetValueOfString(DB.ExecuteScalar("SELECT IsActive FROM M_PriceList WHERE M_PriceList_ID=" + project.GetM_PriceList_ID(), null, Get_Trx())).Equals("Y")) { _order.SetM_PriceList_ID(project.GetM_PriceList_ID()); } else { message = Msg.GetMsg(GetCtx(), "IsActivePriceList"); return; } } } else { if (bp.GetM_PriceList_ID() != 0) { if (Util.GetValueOfString(DB.ExecuteScalar("SELECT IsActive FROM M_PriceList WHERE M_PriceList_ID=" + bp.GetM_PriceList_ID(), null, Get_Trx())).Equals("Y")) { _order.SetM_PriceList_ID(bp.GetM_PriceList_ID()); } else { message = Msg.GetMsg(GetCtx(), "IsActivePriceList"); return; } } } _order.SetSalesRep_ID(te.GetDoc_User_ID()); // if (!_order.Save()) { Rollback(); ValueNamePair pp = VLogger.RetrieveError(); if (pp != null) { message = pp.GetName(); //if GetName is Empty then it will check GetValue if (string.IsNullOrEmpty(message)) { message = Msg.GetMsg("", pp.GetValue()); } } if (string.IsNullOrEmpty(message)) { message = Msg.GetMsg(GetCtx(), "CantSaveOrder"); } return; //throw new Exception("Cannot save Order"); } } else { // Update Header info if (tel.GetC_Activity_ID() != 0 && tel.GetC_Activity_ID() != _order.GetC_Activity_ID()) { _order.SetC_Activity_ID(tel.GetC_Activity_ID()); } if (tel.GetC_Campaign_ID() != 0 && tel.GetC_Campaign_ID() != _order.GetC_Campaign_ID()) { _order.SetC_Campaign_ID(tel.GetC_Campaign_ID()); } if (!_order.Save()) { Rollback(); //get error message from ValueNamePair ValueNamePair pp = VLogger.RetrieveError(); if (pp != null) { message = pp.GetName(); //if GetName is Empty then it will check GetValue if (string.IsNullOrEmpty(message)) { message = Msg.GetMsg("", pp.GetValue()); } } //it will check message is null or not if (string.IsNullOrEmpty(message)) { message = Msg.GetMsg(GetCtx(), "CantSaveOrder"); } return; //new Exception("Cannot save Order"); } } // OrderLine MOrderLine ol = new MOrderLine(_order); // if (tel.GetM_Product_ID() != 0) { ol.SetM_Product_ID(tel.GetM_Product_ID(), tel.GetC_UOM_ID()); } if (tel.GetS_ResourceAssignment_ID() != 0) { ol.SetS_ResourceAssignment_ID(tel.GetS_ResourceAssignment_ID()); } // Set charge ID if (tel.GetC_Charge_ID() != 0) { ol.SetC_Charge_ID(tel.GetC_Charge_ID()); ol.SetPriceActual(tel.GetExpenseAmt()); ol.SetQty(tel.GetQty()); } ol.SetQty(tel.GetQtyInvoiced()); // ol.SetDescription(tel.GetDescription()); // ol.SetC_Project_ID(tel.GetC_Project_ID()); ol.SetC_ProjectPhase_ID(tel.GetC_ProjectPhase_ID()); ol.SetC_ProjectTask_ID(tel.GetC_ProjectTask_ID()); ol.SetC_Activity_ID(tel.GetC_Activity_ID()); ol.SetC_Campaign_ID(tel.GetC_Campaign_ID()); // Decimal price = tel.GetPriceInvoiced(); // if (price.CompareTo(Env.ZERO) != 0) { if (tel.GetC_Currency_ID() != _order.GetC_Currency_ID()) { price = MConversionRate.Convert(GetCtx(), price, tel.GetC_Currency_ID(), _order.GetC_Currency_ID(), _order.GetAD_Client_ID(), _order.GetAD_Org_ID()); } ol.SetPrice(price); // added by Bhupendra to set the entered price ol.SetPriceEntered(price); } else { ol.SetPrice(); } if (tel.GetC_UOM_ID() != 0 && ol.GetC_UOM_ID() == 0) { ol.SetC_UOM_ID(tel.GetC_UOM_ID()); } ol.SetTax(); if (!ol.Save()) { Rollback(); //get error message from ValueNamePair ValueNamePair pp = VLogger.RetrieveError(); if (pp != null) { message = pp.GetName(); //if GetName is Empty then it will check GetValue if (string.IsNullOrEmpty(message)) { message = Msg.GetMsg("", pp.GetValue()); } } //it will check message is null or not if (string.IsNullOrEmpty(message)) { message = Msg.GetMsg(GetCtx(), "CantSaveOrderLine"); } return; //throw new Exception("Cannot save Order Line"); } // Update TimeExpense Line tel.SetC_OrderLine_ID(ol.GetC_OrderLine_ID()); if (tel.Save()) { log.Fine("Updated " + tel + " with C_OrderLine_ID"); } else { log.Log(Level.SEVERE, "Not Updated " + tel + " with C_OrderLine_ID"); } } // processLine