/// <summary>
        /// Add fee line on run tab of dunning run window.
        /// </summary>
        private void AddFees()
        {
            // Only add a fee if it contains InvoiceLines and is not a statement
            // TODO: Assumes Statement = -9999 and
            bool onlyInvoices = _level.GetDaysAfterDue().Equals(new Decimal(-9999));

            MDunningRunEntry[] entries = _run.GetEntries(true, onlyInvoices);
            if (entries != null && entries.Length > 0)
            {
                for (int i = 0; i < entries.Length; i++)
                {
                    MDunningRunLine line = new MDunningRunLine(entries[i]);
                    line.SetFee(_C_Currency_ID, _level.GetFeeAmt());
                    if (!line.Save())
                    {
                        // Change by mohit to pick error message from last error in mclass.
                        //throw new Exception(GetRetrievedError(line, "Cannot save MDunningRunLine"));
                        //throw new Exception("Cannot save MDunningRunLine");
                        ValueNamePair vp = VLogger.RetrieveError();
                        if (vp != null)
                        {
                            log.SaveError(Msg.GetMsg(GetCtx(), "NotSaveDunRunLine"), vp.GetName());
                        }
                        else
                        {
                            log.SaveError(Msg.GetMsg(GetCtx(), "NotSaveDunRunLine"), "");
                        }
                        return;
                    }
                    entries[i].SetQty(Decimal.Subtract(entries[i].GetQty(), new Decimal(1)));
                }
            }
        }
        /// <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());
        }
Exemple #3
0
        /// <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);
        }
        /// <summary>
        /// Create Invoice Line on run tab of dunning run window.
        /// </summary>
        /// <param name="C_Invoice_ID">Invoice ID.</param>
        /// <param name="C_Currency_ID">Currency ID.</param>
        /// <param name="GrandTotal">Grand Total.</param>
        /// <param name="Open">Amount.</param>
        /// <param name="DaysDue">Days Due.</param>
        /// <param name="IsInDispute">In Dispute.</param>
        /// <param name="C_BPartner_ID">Business Partner.</param>
        /// <param name="timesDunned">Number of times dunning occurred.</param>
        /// <param name="daysAfterLast">Days after last dunning.</param>
        private bool CreateInvoiceLine(int C_Invoice_ID, int C_Currency_ID,
                                       Decimal GrandTotal, Decimal Open,
                                       int DaysDue, bool IsInDispute,
                                       int C_BPartner_ID, int timesDunned, int daysAfterLast, int PaySchedule_ID)
        {
            MDunningRunEntry entry = _run.GetEntry(C_BPartner_ID, _C_Currency_ID, _SalesRep_ID);

            if (entry.Get_ID() == 0)
            {
                if (!entry.Save())
                {
                    // Change by mohit to pick error message from last error in mclass.
                    //throw new Exception(GetRetrievedError(entry, "Cannot save MDunningRunEntry"));
                    //throw new Exception("Cannot save MDunningRunEntry");
                    ValueNamePair vp = VLogger.RetrieveError();
                    if (vp != null)
                    {
                        log.SaveError(Msg.GetMsg(GetCtx(), "NotSaveDunRunEntry"), vp.GetName());
                    }
                    else
                    {
                        log.SaveError(Msg.GetMsg(GetCtx(), "NotSaveDunRunEntry"), "");
                    }
                    return(false);
                }
            }
            //
            MDunningRunLine line = new MDunningRunLine(entry);

            line.SetInvoice(C_Invoice_ID, C_Currency_ID, GrandTotal, Open,
                            new Decimal(0), DaysDue, IsInDispute, timesDunned,
                            daysAfterLast);
            line.SetC_InvoicePaySchedule_ID(PaySchedule_ID);
            if (!line.Save())
            {
                // Change by mohit to pick error message from last error in mclass.
                //throw new Exception(GetRetrievedError(line, "Cannot save MDunningRunLine"));
                //throw new Exception("Cannot save MDunningRunLine");
                ValueNamePair vp = VLogger.RetrieveError();
                if (vp != null)
                {
                    log.SaveError(Msg.GetMsg(GetCtx(), "NotSaveDunRunLine"), vp.GetName());
                }
                else
                {
                    log.SaveError(Msg.GetMsg(GetCtx(), "NotSaveDunRunLine"), "");
                }
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// Create Payment Line on run tab of dunning run window.
        /// </summary>
        /// <param name="C_Payment_ID">Payment ID.</param>
        /// <param name="C_Currency_ID">Currency ID.</param>
        /// <param name="PayAmt">Amount.</param>
        /// <param name="openAmt">Open.</param>
        /// <param name="C_BPartner_ID">Business Partner ID.</param>
        private bool CreatePaymentLine(int C_Payment_ID, int C_Currency_ID,
                                       Decimal PayAmt, Decimal openAmt, int C_BPartner_ID)
        {
            MDunningRunEntry entry = _run.GetEntry(C_BPartner_ID, _C_Currency_ID, _SalesRep_ID);

            if (entry.Get_ID() == 0)
            {
                if (!entry.Save())
                {
                    // Change by mohit to pick error message from last error in mclass.
                    //throw new Exception(GetRetrievedError(entry, "Cannot save MDunningRunEntry"));
                    //throw new Exception("Cannot save MDunningRunEntry");
                    //log.SaveError("Cannot save MDunningRunEntry", "");
                    ValueNamePair vp = VLogger.RetrieveError();
                    if (vp != null)
                    {
                        string val = vp.GetName();
                        log.SaveError(Msg.GetMsg(GetCtx(), "NotSaveDunRunEntry"), val);
                    }
                    else
                    {
                        log.SaveError(Msg.GetMsg(GetCtx(), "NotSaveDunRunEntry"), "");
                    }
                    return(false);
                }
            }
            //
            MDunningRunLine line = new MDunningRunLine(entry);

            line.SetPayment(C_Payment_ID, C_Currency_ID, PayAmt, openAmt);

            if (!line.Save())
            {
                // Change by mohit to pick error message from last error in mclass.
                //throw new Exception(GetRetrievedError(line, "Cannot save MDunningRunLine"));
                //throw new Exception("Cannot save MDunningRunLine");
                ValueNamePair vp = VLogger.RetrieveError();
                if (vp != null)
                {
                    log.SaveError(Msg.GetMsg(GetCtx(), "NotSaveDunRunLine"), vp.GetName());
                }
                else
                {
                    log.SaveError(Msg.GetMsg(GetCtx(), "NotSaveDunRunLine"), "");
                }
                return(false);
            }
            return(true);
        }
Exemple #6
0
 /// <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());
        }
Exemple #8
0
        protected override String DoIt()
        {
            //int C_Contract_ID = 0;
            String Sql = "SELECT C_OrderLine_ID FROM C_OrderLine WHERE C_Order_ID=" + orderID + " AND CreateServiceContract='N' AND IsContract='Y' AND IsActive='Y'";

            dr = DB.ExecuteReader(Sql);
            try
            {
                VAdvantage.Model.X_C_Order order = new VAdvantage.Model.X_C_Order(GetCtx(), orderID, Get_TrxName());
                string DocStatus = order.GetDocStatus();
                if (DocStatus != "CO")
                {
                    if (dr != null)
                    {
                        dr.Close();
                        dr = null;
                    }

                    return(Msg.GetMsg(GetCtx(), "FirstCompleteOrder"));
                }


                while (dr.Read())
                {
                    line = new VAdvantage.Model.X_C_OrderLine(GetCtx(), Util.GetValueOfInt(dr[0]), Get_TrxName());
                    if (line.IsContract() && line.GetC_Contract_ID() == 0)
                    {
                        contact = new VAdvantage.Model.X_C_Contract(GetCtx(), 0, Get_TrxName());
                        int M_PriceList_ID = Util.GetValueOfInt(order.GetM_PriceList_ID());

                        //Neha---Commented code because object created but not used in further class---04 Sep,2018

                        //VAdvantage.Model.MProductPricing pp = new VAdvantage.Model.MProductPricing(GetCtx().GetAD_Client_ID(), GetCtx().GetAD_Org_ID(),
                        //    line.GetM_Product_ID(), order.GetC_BPartner_ID(), line.GetQtyOrdered(), true);
                        //pp.SetM_PriceList_ID(M_PriceList_ID);
                        //VAdvantage.Model.MProduct prd = new VAdvantage.Model.MProduct(GetCtx(), line.GetM_Product_ID(), null);
                        //pp.SetC_UOM_ID(prd.GetC_UOM_ID());

                        string sql = "SELECT pl.IsTaxIncluded,pl.EnforcePriceLimit,pl.C_Currency_ID,c.StdPrecision,"
                                     + "plv.M_PriceList_Version_ID,plv.ValidFrom "
                                     + "FROM M_PriceList pl,C_Currency c,M_PriceList_Version plv "
                                     + "WHERE pl.C_Currency_ID=c.C_Currency_ID"
                                     + " AND pl.M_PriceList_ID=plv.M_PriceList_ID"
                                     + " AND pl.M_PriceList_ID=" + M_PriceList_ID                               //	1
                                     + "ORDER BY plv.ValidFrom DESC";

                        //int M_PriceList_Version_ID = 0;
                        int     C_Currency_ID = 0;
                        DataSet ds            = DB.ExecuteDataset(sql, null, Get_TrxName());
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            DataRow dr1 = ds.Tables[0].Rows[i];
                            //	Tax Included

                            isTaxIncluded = Util.GetValueOfString(ds.Tables[0].Rows[i]["IsTaxIncluded"]).Equals("Y");

                            //	Currency

                            C_Currency_ID = Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_Currency_ID"]);

                            // Std Precision
                            StdPrecision = Util.GetValueOfInt(ds.Tables[0].Rows[i]["StdPrecision"]);
                            // int prislst = Util.GetValueOfInt(dr[4].ToString());
                            //	PriceList Version
                            //M_PriceList_Version_ID = Util.GetValueOfInt(ds.Tables[0].Rows[i]["M_PriceList_Version_ID"]);
                        }
                        //int M_PriceList_Version_ID = GetCtx().GetContextAsInt(WindowNo, "M_PriceList_Version_ID");
                        //pp.SetM_PriceList_Version_ID(M_PriceList_Version_ID);
                        //Neha---Set Tenant,Organization from Sales Order---11 Sep,2018
                        contact.SetAD_Client_ID(order.GetAD_Client_ID());
                        contact.SetAD_Org_ID(order.GetAD_Org_ID());
                        //---------------------End ------------------
                        contact.SetDescription(order.GetDescription());
                        contact.SetC_Order_ID(order.GetC_Order_ID());
                        contact.SetC_OrderLine_ID(line.GetC_OrderLine_ID());
                        contact.SetStartDate(line.GetStartDate());
                        contact.SetBillStartDate(line.GetStartDate());
                        contact.SetEndDate(line.GetEndDate());
                        contact.SetC_BPartner_ID(order.GetC_BPartner_ID());
                        contact.SetBill_Location_ID(order.GetBill_Location_ID());
                        contact.SetBill_User_ID(order.GetBill_User_ID());
                        contact.SetSalesRep_ID(order.GetSalesRep_ID());
                        contact.SetC_Currency_ID(line.GetC_Currency_ID());
                        contact.SetC_ConversionType_ID(order.GetC_ConversionType_ID());
                        contact.SetC_PaymentTerm_ID(order.GetC_PaymentTerm_ID());
                        contact.SetM_PriceList_ID(order.GetM_PriceList_ID());
                        contact.SetC_Frequency_ID(line.GetC_Frequency_ID());

                        //Neha--Set List Price,Price,Unit Price,Discount from Order Line--4 Sep,2018

                        //contact.SetPriceList(pp.GetPriceList());
                        //contact.SetPriceActual(pp.GetPriceStd());
                        //contact.SetPriceEntered(pp.GetPriceStd());
                        contact.SetPriceList(line.GetPriceList());
                        contact.SetPriceActual(line.GetPriceActual());
                        contact.SetPriceEntered(line.GetPriceEntered());
                        contact.SetQtyEntered(line.GetQtyPerCycle());
                        //Decimal discount = Decimal.Round(Decimal.Divide(Decimal.Multiply(Decimal.Subtract(pp.GetPriceList(), pp.GetPriceStd()), new Decimal(100)), pp.GetPriceList()), 2);
                        contact.SetDiscount(line.GetDiscount());
                        //------------------End----------------------------

                        //contact.SetGrandTotal(
                        // invoice Count Start
                        //DateTime SDate = (DateTime)(line.GetStartDate());
                        //DateTime Edate = (DateTime)(line.GetEndDate());
                        //int frequency = Util.GetValueOfInt(line.GetC_Frequency_ID());
                        //string PSql = "Select NoOfDays from C_Frequency where C_Frequency_ID=" + frequency;
                        //int days = Util.GetValueOfInt(DB.ExecuteScalar(PSql, null, null));
                        //int totaldays = (Edate - SDate).Days;
                        //int count = totaldays / days;
                        contact.SetTotalInvoice(line.GetNoofCycle());
                        //invoice Count end
                        contact.SetC_Project_ID(order.GetC_Project_ID());
                        // contact.SetPriceList(line.GetPriceList());
                        //contact.SetPriceActual(line.GetPriceActual());
                        contact.SetC_UOM_ID(line.GetC_UOM_ID());
                        contact.SetM_Product_ID(line.GetM_Product_ID());
                        // Added by Vivek on 21/11/2017 asigned by Pradeep
                        contact.SetM_AttributeSetInstance_ID(line.GetM_AttributeSetInstance_ID());
                        // contact.SetPriceEntered(line.GetPriceEntered());
                        //contact.SetQtyEntered(line.GetQtyEntered());
                        // contact.SetDiscount(line.GetDiscount());
                        contact.SetC_Tax_ID(line.GetC_Tax_ID());
                        contact.SetC_Campaign_ID(order.GetC_Campaign_ID());

                        contact.SetLineNetAmt(Decimal.Multiply(line.GetQtyPerCycle(), line.GetPriceActual()));

                        // if Surcharge Tax is selected on Tax, then set value in Surcharge Amount
                        MTax tax = MTax.Get(GetCtx(), line.GetC_Tax_ID());
                        if (contact.Get_ColumnIndex("SurchargeAmt") > 0 && tax.GetSurcharge_Tax_ID() > 0)
                        {
                            Decimal surchargeAmt = Env.ZERO;

                            // Calculate Surcharge Amount
                            Decimal TotalRate = tax.CalculateSurcharge(contact.GetLineNetAmt(), isTaxIncluded, StdPrecision, out surchargeAmt);
                            contact.SetTaxAmt(TotalRate);
                            contact.SetSurchargeAmt(surchargeAmt);
                        }
                        else
                        {
                            sql = "SELECT Rate FROM C_Tax WHERE C_Tax_ID = " + line.GetC_Tax_ID();
                            Decimal?rate = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, Get_TrxName()));
                            //Decimal? amt = Decimal.Multiply(pp.GetPriceStd(), (Decimal.Divide(rate.Value, 100)));
                            Decimal?amt = Decimal.Multiply(line.GetPriceActual(), (Decimal.Divide(rate.Value, 100)));
                            amt = Decimal.Round(amt.Value, 2, MidpointRounding.AwayFromZero);
                            Decimal?taxAmt = Decimal.Multiply(amt.Value, line.GetQtyPerCycle());
                            contact.SetTaxAmt(taxAmt);
                        }

                        // Set Grand Total Amount
                        if (isTaxIncluded)
                        {
                            contact.SetGrandTotal(contact.GetLineNetAmt());
                        }
                        else
                        {
                            if (contact.Get_ColumnIndex("SurchargeAmt") > 0)
                            {
                                contact.SetGrandTotal(Decimal.Add(Decimal.Add(contact.GetLineNetAmt(), contact.GetTaxAmt()), contact.GetSurchargeAmt()));
                            }
                            else
                            {
                                contact.SetGrandTotal(Decimal.Add(contact.GetLineNetAmt(), contact.GetTaxAmt()));
                            }
                        }

                        //-------------------------End--------------------------
                        contact.SetDocStatus("DR");
                        contact.SetRenewContract("N");
                        if (!contact.Save())
                        {
                            //Neha----If Service Contract not saved then will show the exception---17 Sep,2018
                            ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                            if (pp != null)
                            {
                                throw new ArgumentException("Cannot save Service Contract. " + pp.GetName());
                            }
                            throw new ArgumentException("Cannot save Service Contract");
                        }
                        else
                        {
                            if (!line.Save())
                            {
                                //Neha----If Order Line not saved then will show the exception---17 Sep,2018
                                ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                                if (pp != null)
                                {
                                    throw new ArgumentException("Cannot save Order Line. " + pp.GetName());
                                }
                                throw new ArgumentException("Cannot save Order Line");
                            }
                            //Neha---Set CreateServiceContract,Order Line ID on Order Line tab---17 Sep,2018
                            String _qry = "UPDATE C_ORDERLINE SET C_CONTRACT_ID=" + contact.GetC_Contract_ID() + " ,CreateServiceContract='Y' WHERE C_ORDERLINE_ID=" + line.GetC_OrderLine_ID();
                            DB.ExecuteScalar(_qry, null, Get_TrxName());
                        }
                        //C_Contract_ID = contact.GetC_Contract_ID();
                        DocumntNo += contact.GetDocumentNo() + ",";
                    }
                }
                dr.Close();
                order.SetCreateServiceContract("Y");
                if (!order.Save())
                {
                }
                // Added Document No on Message
                return(Msg.GetMsg(GetCtx(), "ServiceContractGenerationDone") + DocumntNo.TrimEnd(','));
            }
            catch (Exception ex)
            {
                if (dr != null)
                {
                    dr.Close();
                    dr = null;
                }
                return(Msg.GetMsg(GetCtx(), ex.Message));
            }
            // return "";
        }
Exemple #9
0
        /// <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(
        }
        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"));
            }
        }
Exemple #11
0
        /// <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>
        /// Generate Contract Invoice
        /// </summary>
        /// <param name="contSchedule"></param>
        private void GenerateInvoice(VAdvantage.Model.X_C_ContractSchedule contSchedule)
        {
            if (contSchedule.IsActive())
            {
                int res = 0;
                sql.Clear();
                sql.Append(MRole.GetDefault(GetCtx()).AddAccessSQL("SELECT MIN(C_DOCTYPE_ID) FROM C_DocType WHERE DOCBASETYPE='ARI' AND ISACTIVE ='Y'", "C_DocType", true, true));
                int C_DocType_ID = Util.GetValueOfInt(DB.ExecuteScalar(sql.ToString(), null, Get_TrxName()));

                // sql = "select noofdays from c_frequency where c_frequency_id = " + cont.GetC_Frequency_ID();
                //  Decimal? days = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, null));
                Decimal?price = null;

                if (!cont.IsCancel())
                {
                    price = Decimal.Multiply(cont.GetPriceEntered(), cont.GetQtyEntered());
                }
                else
                {
                    sql.Clear();
                    sql.Append("UPDATE C_Contract SET RenewalType = NULL WHERE C_Contract_ID = " + cont.GetC_Contract_ID());
                    int res2 = Util.GetValueOfInt(DB.ExecuteQuery(sql.ToString(), null, Get_TrxName()));

                    if (contSchedule.GetEndDate() <= cont.GetCancellationDate())
                    {
                        price = Decimal.Multiply(cont.GetPriceEntered(), cont.GetQtyEntered());
                    }
                    else
                    {
                        sql.Clear();
                        sql.Append("SELECT MAX(C_ContractSchedule_ID) FROM C_ContractSchedule WHERE NVL(C_INVOICE_ID,0) > 0 AND C_Contract_ID = " + cont.GetC_Contract_ID());
                        int c_contractschedule_id = Util.GetValueOfInt(DB.ExecuteScalar(sql.ToString(), null, Get_TrxName()));
                        if (c_contractschedule_id != 0)
                        {
                            string date = cont.GetCancellationDate().Value.ToString("dd-MMM-yyyy");

                            sql.Clear();
                            sql.Append("SELECT DaysBetween('" + date + "', EndDate) FROM C_ContractSchedule WHERE C_ContractSchedule_ID = " + c_contractschedule_id);
                            Decimal?diffDays = Util.GetValueOfDecimal(DB.ExecuteScalar(sql.ToString(), null, Get_TrxName()));

                            price = Decimal.Multiply(cont.GetPriceEntered(), cont.GetQtyEntered());

                            sql.Clear();
                            sql.Append("UPDATE C_ContractSchedule SET IsActive = 'N' WHERE EndDate > '" + date + "' AND C_Contract_ID = " + cont.GetC_Contract_ID());
                            res = Util.GetValueOfInt(DB.ExecuteQuery(sql.ToString(), null, Get_TrxName()));
                        }
                        else
                        {
                            sql.Clear();
                            sql.Append("SELECT DaysBetween(CancellationDate, StartDate) FROM C_Contract WHERE C_Contract_ID = " + cont.GetC_Contract_ID());
                            Decimal?diffDays = Util.GetValueOfDecimal(DB.ExecuteScalar(sql.ToString(), null, Get_TrxName()));

                            price = Decimal.Multiply(cont.GetPriceEntered(), cont.GetQtyEntered());

                            if (diffDays > 0)
                            {
                                sql.Clear();
                                sql.Append("UPDATE C_ContractSchedule SET IsActive = 'N' WHERE C_Contract_ID = " + cont.GetC_Contract_ID());
                                res = Util.GetValueOfInt(DB.ExecuteQuery(sql.ToString(), null, Get_TrxName()));
                            }
                            else
                            {
                                sql.Clear();
                                sql.Append("UPDATE C_ContractSchedule SET IsActive = 'N' WHERE C_Contract_ID = " + cont.GetC_Contract_ID());
                                res = Util.GetValueOfInt(DB.ExecuteQuery(sql.ToString(), null, Get_TrxName()));
                            }
                        }
                    }
                }

                price = Decimal.Round(price.Value, 2, MidpointRounding.AwayFromZero);

                inv = new VAdvantage.Model.MInvoice(GetCtx(), 0, Get_TrxName());
                inv.SetAD_Client_ID(cont.GetAD_Client_ID());
                inv.SetAD_Org_ID(cont.GetAD_Org_ID());
                inv.SetC_BPartner_ID(cont.GetC_BPartner_ID());
                if (Util.GetValueOfInt(cont.GetC_Order_ID()) != 0)
                {
                    inv.SetC_Order_ID(cont.GetC_Order_ID());
                }
                // JID_0872: System has To pick the Payment Method defined with the Business Partner against whom the Invoice is getting generated.
                if (Env.IsModuleInstalled("VA009_"))
                {
                    if (bp.GetVA009_PaymentMethod_ID() > 0)
                    {
                        inv.SetVA009_PaymentMethod_ID(bp.GetVA009_PaymentMethod_ID());
                    }
                    else
                    {
                        throw new ArgumentException(Msg.GetMsg(GetCtx(), "VIS_PaymentMethodNotDefined") + " : " + bp.GetName());
                    }
                }
                inv.SetC_DocType_ID(C_DocType_ID);
                inv.SetC_DocTypeTarget_ID(C_DocType_ID);
                inv.SetC_BPartner_Location_ID(cont.GetBill_Location_ID());
                inv.SetC_Currency_ID(cont.GetC_Currency_ID());
                inv.SetC_PaymentTerm_ID(cont.GetC_PaymentTerm_ID());
                inv.SetC_Campaign_ID(cont.GetC_Campaign_ID());
                inv.SetIsSOTrx(true);
                inv.SetM_PriceList_ID(cont.GetM_PriceList_ID());
                inv.SetSalesRep_ID(cont.GetSalesRep_ID());
                inv.SetC_Contract_ID(cont.GetC_Contract_ID());
                if (!inv.Save())
                {
                    //Neha----If Invoice not saved then will show the exception---11 Sep,2018
                    ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                    if (pp != null)
                    {
                        throw new ArgumentException("Cannot save Invoice. " + pp.GetName());
                    }
                    throw new ArgumentException("Cannot save Invoice");
                }

                else
                {
                    VAdvantage.Model.MInvoiceLine invLine = new VAdvantage.Model.MInvoiceLine(GetCtx(), 0, Get_TrxName());
                    invLine.SetAD_Client_ID(inv.GetAD_Client_ID());
                    invLine.SetAD_Org_ID(inv.GetAD_Org_ID());
                    invLine.SetC_Campaign_ID(inv.GetC_Campaign_ID());
                    invLine.SetC_Invoice_ID(inv.GetC_Invoice_ID());
                    invLine.SetC_UOM_ID(cont.GetC_UOM_ID());
                    invLine.SetM_Product_ID(cont.GetM_Product_ID());
                    // Added by Vivek on 21/11/2017 asigned by Pradeep
                    invLine.SetM_AttributeSetInstance_ID(cont.GetM_AttributeSetInstance_ID());
                    if (Util.GetValueOfInt(cont.GetC_OrderLine_ID()) != 0)
                    {
                        invLine.SetC_OrderLine_ID(cont.GetC_OrderLine_ID());
                    }
                    invLine.SetC_Tax_ID(cont.GetC_Tax_ID());
                    invLine.SetQty(cont.GetQtyEntered());
                    invLine.SetQtyEntered(cont.GetQtyEntered());
                    // invLine.SetQtyInvoiced(1);
                    // invLine.SetPrice(price.Value);
                    invLine.SetPriceActual(cont.GetPriceEntered());
                    invLine.SetPriceEntered(cont.GetPriceEntered());
                    //  invLine.SetPriceLimit(price);
                    invLine.SetPriceList(cont.GetPriceEntered());
                    if (!invLine.Save())
                    {
                        //Neha----If Invoice Line not saved then will show the exception---11 Sep,2018
                        ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                        if (pp != null)
                        {
                            throw new ArgumentException("Cannot save Invoice Line. " + pp.GetName());
                        }
                        throw new ArgumentException("Cannot save Invoice Line");
                    }
                }

                string comp = inv.CompleteIt();
                //Neha---If Invoice Completed then Set Document Action, Document Status and Contract on Invoice Header---11 Sep,2018
                if (comp == "CO")
                {
                    inv.SetDocAction("CL");
                    inv.SetDocStatus("CO");
                    //Neha---Set C_Contract_ID on C_invoice table using MClass object--11 Sep,2018
                    inv.SetC_Contract_ID(cont.GetC_Contract_ID());
                    if (!inv.Save())
                    {
                        //Neha----If Invoice not saved then will show the exception---11 Sep,2018
                        ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                        if (pp != null)
                        {
                            throw new ArgumentException("Cannot save Invoice. " + pp.GetName());
                        }
                        throw new ArgumentException("Cannot save Invoice");
                    }
                }
                else
                {
                    //Neha----If Invoice not completed then will show the exception---11 Sep,2018
                    if (inv.GetProcessMsg() != null)
                    {
                        throw new ArgumentException("Cannot complete the Invoice. " + inv.GetProcessMsg());
                    }
                    throw new ArgumentException("Cannot complete the Invoice");
                }

                #region Commented Code
                //Neha---Set C_Contract_ID on C_invoice table using MClass object--11 Sep,2018

                //sql = "UPDATE c_invoice SET C_Contract_ID = " + cont.GetC_Contract_ID() + " WHERE c_invoice_id = " + inv.GetC_Invoice_ID();
                //res = Util.GetValueOfInt(DB.ExecuteQuery(sql, null, null));

                //Neha---taxAmt not used in this class----11 Sep,2018

                //sql = "SELECT SUM(taxamt) FROM c_invoicetax WHERE c_invoice_id = " + inv.GetC_Invoice_ID();
                //Decimal? taxAmt = Util.GetValueOfDecimal(DB.ExecuteScalar(sql, null, null));
                # endregion
                sql.Clear();
                sql.Append("UPDATE C_ContractSchedule SET C_Invoice_ID = " + inv.GetC_Invoice_ID() + ", Processed = 'Y' WHERE C_ContractSchedule_ID = " + contSchedule.GetC_ContractSchedule_ID());
                res = Util.GetValueOfInt(DB.ExecuteQuery(sql.ToString(), null, Get_TrxName()));
                //Neha---Append Document No. in sb----12 Sep,2018
                sb.Append(inv.GetDocumentNo() + ", ");
                //_count++;
            }
        /// <summary>
        /// Is used to create line against Income Account summary account --
        /// </summary>
        /// <param name="Profit">class object of MProfitLoss </param>
        private void InsertProfitLossLine(MProfitLoss Profit)
        {
            // get consolidated profit amount agsint Organization
            String  Sql      = @"SELECT AD_Org_ID , (SUM(AccountDebit) - SUM(AccountCredit)) AS ProfitAmt
                                    FROM C_ProfitLossLines WHERE C_ProfitAndLoss_ID > 0 AND C_ProfitLoss_ID = " + Profit.GetC_ProfitLoss_ID() + @" GROUP BY AD_Org_ID";
            DataSet dsProfit = DB.ExecuteDataset(Sql, null, Get_Trx());

            if (dsProfit != null && dsProfit.Tables.Count > 0 && dsProfit.Tables[0].Rows.Count > 0)
            {
                // get max line no
                int lineNo = Convert.ToInt32(DB.ExecuteScalar(@"SELECT NVL(MAX(Line),0)+10 AS line FROM C_ProfitLossLines WHERE C_ProfitLoss_ID = " + Profit.GetC_ProfitLoss_ID(), null, Get_Trx()));

                // get Valid Combination against Income Summary Acct  from accounting schema
                int validComID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT IncomeSummary_Acct FROM C_AcctSchema_GL WHERE C_AcctSchema_ID=" + Util.GetValueOfInt(Profit.Get_Value("C_AcctSchema_ID"))));
                // get account id
                MAccount acct = MAccount.Get(GetCtx(), validComID);

                for (int i = 0; i < dsProfit.Tables[0].Rows.Count; i++)
                {
                    Decimal profitAmt = Util.GetValueOfDecimal(dsProfit.Tables[0].Rows[i]["ProfitAmt"]);

                    // when difference of DR - CR is ZERO then not to create line
                    if (profitAmt == 0)
                    {
                        continue;
                    }
                    MProfitLossLines profitLossLines = new MProfitLossLines(GetCtx(), 0, Get_Trx());
                    profitLossLines.SetAD_Client_ID(Profit.GetAD_Client_ID());
                    profitLossLines.SetAD_Org_ID(Util.GetValueOfInt(dsProfit.Tables[0].Rows[i]["AD_Org_ID"]));
                    profitLossLines.SetC_ProfitLoss_ID(Profit.GetC_ProfitLoss_ID());
                    profitLossLines.SetLine(lineNo);
                    profitLossLines.SetC_AcctSchema_ID(Util.GetValueOfInt(Profit.Get_Value("C_AcctSchema_ID")));
                    profitLossLines.SetPostingType(Util.GetValueOfString(Profit.Get_Value("PostingType")));
                    profitLossLines.SetAccount_ID(acct.GetAccount_ID());
                    profitLossLines.Set_Value("LedgerCode", acct.GetAccount().Get_Value("Value"));
                    profitLossLines.Set_Value("LedgerName", acct.GetAccount().Get_Value("Name"));
                    if (profitAmt > 0)
                    {
                        profitLossLines.SetAccountCredit(profitAmt);
                    }
                    else
                    {
                        profitLossLines.SetAccountDebit(profitAmt);
                    }
                    if (!profitLossLines.Save(Get_Trx()))
                    {
                        ValueNamePair pp = VLogger.RetrieveError();
                        log.Fine("Failed - Profit loss line not saved for income acct summary - " + (pp != null && !String.IsNullOrEmpty(pp.GetName()) ? pp.GetName() : ""));
                    }
                    else
                    {
                        lineNo += 10;
                    }
                }
            }
        }
        /// <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);
        }
Exemple #15
0
        /// <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);
        }
Exemple #16
0
        /// <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"));
        }
        /// <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);
            }
        }
Exemple #18
0
        /// <summary>
        /// This Method is used to Activate Product container functionlaity into Vienna System
        /// </summary>
        /// <returns>Message - Container is Applicabled or not</returns>
        protected override string DoIt()
        {
            // check container applicable or not
            if (Util.GetValueOfString(GetCtx().GetContext("#PRODUCT_CONTAINER_APPLICABLE")).Equals("N"))
            {
                // verify document is closed or not
                if (!VerifyDocumentStatus())
                {
                    return(Msg.GetMsg(GetCtx(), "VIS_NotClosedocument"));
                }

                // update container qty with current qty on all records on transaction
                int no = DB.ExecuteQuery(@"UPDATE M_TRANSACTION SET ContainerCurrentQty = CurrentQty", null, Get_Trx());
                if (no > 0)
                {
                    // delete all record from container storage
                    no = DB.ExecuteQuery(@"DELETE FROM  M_ContainerStorage", null, Get_Trx());

                    // get all data from storage having OnHandQty != 0, and create recod on container storage with locator, product and qty details
                    sql.Clear();
                    sql.Append(@"SELECT M_Transaction.AD_client_ID , M_Transaction.AD_Org_ID , M_Transaction.M_Locator_ID , M_Transaction.M_Product_ID ,
                                  NVL(M_Transaction.M_AttributeSetInstance_ID , 0) AS M_AttributeSetInstance_ID , M_Transaction.M_Transaction_ID ,
                                  M_Transaction.MovementDate , NVL(M_Transaction.MovementQty , 0) AS MovementQty , M_Transaction.CurrentQty , M_Transaction.MovementType ,
                                  CASE WHEN M_Transaction.M_InventoryLine_ID > 0
                                    AND (SELECT IsInternalUse FROM M_InventoryLine
                                      WHERE M_InventoryLine.M_InventoryLine_ID = M_Transaction.M_InventoryLine_ID ) = 'N'
                                    THEN 'Y' ELSE 'N' END AS PhysicalInventory,
                                    (SELECT MMPolicy FROM M_Product_Category WHERE M_Product_Category.M_Product_Category_ID = M_Product.M_Product_Category_ID) AS MMPolicy
                                FROM M_Transaction 
                                INNER JOIN M_Product ON M_Product.M_Product_ID = M_Transaction.M_Product_ID  
                                ORDER BY M_Transaction.AD_Client_ID , M_Transaction.M_Locator_ID , M_Transaction.M_Product_ID ,
                                M_Transaction.M_AttributeSetInstance_ID , M_Transaction.MovementDate , M_Transaction.M_Transaction_ID ASC");
                    DataSet dsStorage = DB.ExecuteDataset(sql.ToString(), null, Get_Trx());
                    if (dsStorage != null && dsStorage.Tables.Count > 0 && dsStorage.Tables[0].Rows.Count > 0)
                    {
                        X_M_ContainerStorage containerStorage = null;
                        int M_ContainerStorage_ID             = 0;
                        for (int i = 0; i < dsStorage.Tables[0].Rows.Count; i++)
                        {
                            // get dataRow from dataset
                            DataRow dr = dsStorage.Tables[0].Rows[i];

                            if (Convert.ToInt32(dr["MovementQty"]) > 0)
                            {
                                // Quantity IN
                                M_ContainerStorage_ID = GetContainerStorage(Convert.ToInt32(dr["M_Locator_ID"]), Convert.ToInt32(dr["M_Product_ID"]),
                                                                            Convert.ToInt32(dr["M_AttributeSetInstance_ID"]), Convert.ToDateTime(dr["MovementDate"]),
                                                                            Convert.ToString(dr["PhysicalInventory"]));

                                containerStorage = new X_M_ContainerStorage(GetCtx(), M_ContainerStorage_ID, Get_Trx()); // object of container storage
                                // Set or Update Values
                                containerStorage = InsertContainerStorage(containerStorage, dr);
                                if (!containerStorage.Save(Get_Trx()))
                                {
                                    Get_Trx().Rollback();
                                    ValueNamePair pp = VLogger.RetrieveError();
                                    throw new ArgumentException((Msg.GetMsg(GetCtx(), "VIS_ContainerStorageNotSave") + (pp != null && !String.IsNullOrEmpty(pp.GetName()) ? pp.GetName() : " ")));
                                }
                                else
                                {
                                    // after insertion, system will check if qty = 0 and not a physical inventory record then delete record
                                    if (containerStorage.GetQty() == 0 && !containerStorage.IsPhysicalInventory())
                                    {
                                        containerStorage.Delete(true, Get_Trx());
                                    }
                                }
                            }
                            else
                            {
                                // Quantity Out
                                ConsumeQtyFromStorage(dr);
                            }
                        }
                    }
                }
                // Update setting as Container Applicable into the system
                no = DB.ExecuteQuery("UPDATE AD_SysConfig SET VALUE = 'Y' WHERE Name='PRODUCT_CONTAINER_APPLICABLE'", null, Get_Trx());
            }
            else
            {
                return(Msg.GetMsg(GetCtx(), "VIS_AlreadyActivateContainer"));
            }
            return(Msg.GetMsg(GetCtx(), "VIS_ActivatedContainer"));
        }
Exemple #19
0
        /// <summary>
        /// This funcion is used to get record from container storage based on Material Policy
        /// </summary>
        /// <param name="dr">data row object</param>
        /// <returns>true/false</returns>
        private bool ConsumeQtyFromStorage(DataRow dr)
        {
            Decimal Qty = Math.Abs(Convert.ToDecimal(dr["MovementQty"]));
            int     no;
            String  sql = @"SELECT M_ContainerStorage_ID , Qty , IsPhysicalInventory FROM M_ContainerStorage WHERE Qty > 0 
                               AND M_Locator_ID = " + Convert.ToInt32(dr["M_Locator_ID"]) +
                          @" AND M_Product_ID = " + Convert.ToInt32(dr["M_Product_ID"]) +
                          @" AND NVL(M_AttributeSetInstance_ID , 0) = " + Convert.ToInt32(dr["M_AttributeSetInstance_ID"]);

            if (Convert.ToString(dr["MMPolicy"]).Equals(MProductCategory.MMPOLICY_LiFo))
            {
                sql += " ORDER BY MMPolicyDate  DESC , M_ContainerStorage_ID DESC";
            }
            else
            {
                sql += " ORDER BY MMPolicyDate , M_ContainerStorage_ID ASC";
            }
            DataSet ds = DB.ExecuteDataset(sql, null, Get_Trx());

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                Decimal qtyStorage = 0.0M;
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    qtyStorage = Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["Qty"]);

                    if (Qty >= qtyStorage)
                    {
                        // when consume qty is greater than current traverse row qty, then delete this record if not physical record else set qty = 0

                        if (Util.GetValueOfString(ds.Tables[0].Rows[i]["IsPhysicalInventory"]).Equals("Y"))
                        {
                            // update record - bcz it is physical inventory record
                            no = DB.ExecuteQuery("Update M_ContainerStorage SET QTY = 0 , IsPhysicalInventory = 'Y' WHERE M_ContainerStorage_ID = "
                                                 + Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["M_ContainerStorage_ID"]), null, Get_Trx());
                        }
                        else
                        {
                            // delete record
                            no = DB.ExecuteQuery("DELETE FROM  M_ContainerStorage WHERE M_ContainerStorage_ID = "
                                                 + Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["M_ContainerStorage_ID"]), null, Get_Trx());
                        }

                        // set remaining qty which is to be reduce
                        Qty = decimal.Subtract(Qty, qtyStorage);
                    }
                    else
                    {
                        // subtract qty from the current traverse record
                        no = DB.ExecuteQuery("Update M_ContainerStorage SET QTY = Qty - " + Qty + @" WHERE M_ContainerStorage_ID = "
                                             + Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["M_ContainerStorage_ID"]), null, Get_Trx());
                        Qty = 0;
                        break;
                    }
                }
            }

            // after consumption, if any qty left than need to create record there with -ve remaining qty
            if (Qty != 0)
            {
                X_M_ContainerStorage containerStorage = new X_M_ContainerStorage(GetCtx(), 0, Get_Trx()); // object of container storage
                containerStorage = InsertContainerStorage(containerStorage, dr);
                containerStorage.SetQty(Decimal.Negate(Qty));
                if (!containerStorage.Save(Get_Trx()))
                {
                    Get_Trx().Rollback();
                    ValueNamePair pp = VLogger.RetrieveError();
                    throw new ArgumentException((Msg.GetMsg(GetCtx(), "VIS_ContainerStorageNotSave") + (pp != null && !String.IsNullOrEmpty(pp.GetName()) ? pp.GetName() : " ")));
                }
            }
            return(true);
        }
Exemple #20
0
        protected override String DoIt()
        {
            VAdvantage.Model.X_C_Contract contract = new VAdvantage.Model.X_C_Contract(GetCtx(), contractID, Get_TrxName());
            DateTime start     = (DateTime)contract.GetBillStartDate();
            DateTime end       = (DateTime)contract.GetEndDate();
            int      frequency = contract.GetC_Frequency_ID();

            string Sql    = "SELECT NoofMonths FROM C_Frequency WHERE C_Frequency_ID=" + frequency;
            int    months = Util.GetValueOfInt(DB.ExecuteScalar(Sql, null, Get_TrxName()));
            int    count  = Util.GetValueOfInt(contract.GetTotalInvoice());

            for (int i = 1; i <= count; i++)
            {
                VAdvantage.Model.X_C_ContractSchedule CSchedule = new VAdvantage.Model.X_C_ContractSchedule(GetCtx(), 0, Get_TrxName());
                //Neha ---Set Tenant, Organization On Invoice Schedule when we create Invoice Schedule from Schedule Contract button on header--12 Sep,2018
                CSchedule.SetAD_Client_ID(contract.GetAD_Client_ID());
                CSchedule.SetAD_Org_ID(contract.GetAD_Org_ID());
                //-----------------------End--------------------
                CSchedule.SetC_Contract_ID(contractID);
                CSchedule.SetC_BPartner_ID(contract.GetC_BPartner_ID());
                CSchedule.SetFROMDATE(start);
                CSchedule.SetProcessed(true);
                CSchedule.SetUnitsDelivered(contract.GetQtyEntered());
                CSchedule.SetFROMDATE(start);
                DateTime toDate = start.AddMonths(months);
                toDate = toDate.AddDays(-1);
                CSchedule.SetEndDate(toDate);
                start = start.AddMonths(months);
                // if (i != count)
                // {

                // CSchedule.SetNoOfDays(days);
                // }
                // else
                // {
                //     CSchedule.SetEndDate(end);
                //     CSchedule.SetNoOfDays((end - start).Days+1);
                // }
                CSchedule.SetM_Product_ID(contract.GetM_Product_ID());
                // Added by Vivek on 21/11/2017 asigned by Pradeep
                CSchedule.SetM_AttributeSetInstance_ID(contract.GetM_AttributeSetInstance_ID());
                CSchedule.SetTotalAmt(contract.GetLineNetAmt());
                CSchedule.SetGrandTotal(contract.GetGrandTotal());
                CSchedule.SetTaxAmt(contract.GetTaxAmt());

                // if Surcharge Tax is selected on Tax, then set value in Surcharge Amount
                if (CSchedule.Get_ColumnIndex("SurchargeAmt") > 0)
                {
                    CSchedule.SetSurchargeAmt(contract.GetSurchargeAmt());
                }

                CSchedule.SetC_UOM_ID(contract.GetC_UOM_ID());
                CSchedule.SetPriceEntered(contract.GetPriceEntered());
                if (CSchedule.Save())
                {
                    contract.SetProcessed(true);
                    contract.SetScheduleContract("Y");
                    contract.Save();
                }
                else
                {
                    //Neha----If Invoice Shedule not saved then will show the exception---12 Sep,2018
                    ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                    if (pp != null)
                    {
                        throw new ArgumentException("Cannot save Invoice Schedule. " + pp.GetName());
                    }
                    throw new ArgumentException("Cannot save Invoice Schedule.");
                }
            }

            return(Msg.GetMsg(GetCtx(), "ContractScheduleDone"));
        }
Exemple #21
0
        /// <summary>
        /// Apply Payment Term without schedule to Order
        /// </summary>
        /// <param name="order">Order</param>
        private void ApplyAdvanceTermSchedule(MOrder order)
        {
            //for(int i=0;i<_schedule.Length;i++))
            StringBuilder          _sql      = new StringBuilder();
            Decimal                remainder = order.GetGrandTotal();
            MVA009OrderPaySchedule schedule  = new MVA009OrderPaySchedule(GetCtx(), 0, Get_TrxName());
            MPaymentTerm           payterm   = new MPaymentTerm(GetCtx(), order.GetC_PaymentTerm_ID(), Get_TrxName());

            schedule.SetAD_Client_ID(order.GetAD_Client_ID());
            schedule.SetAD_Org_ID(order.GetAD_Org_ID());
            schedule.SetC_Order_ID(order.GetC_Order_ID());
            schedule.SetC_PaymentTerm_ID(order.GetC_PaymentTerm_ID());

            schedule.SetVA009_PaymentMethod_ID(order.GetVA009_PaymentMethod_ID());

            //schedule.SetDueDate(GetDueDate(order));

            // Get Next Business Day if Next Business Days check box is set to true
            DateTime?payDueDate = null;

            if (payterm.IsNextBusinessDay())
            {
                payDueDate = payterm.GetNextBusinessDate(TimeUtil.AddDays(order.GetDateOrdered(), payterm.GetNetDays()));
            }
            else
            {
                payDueDate = TimeUtil.AddDays(order.GetDateOrdered(), payterm.GetNetDays());
            }
            schedule.SetDueDate(payDueDate);

            schedule.SetDueAmt(order.GetGrandTotal());

            if (payterm.IsNextBusinessDay())
            {
                payDueDate = payterm.GetNextBusinessDate(TimeUtil.AddDays(order.GetDateOrdered(), payterm.GetDiscountDays()));
            }
            else
            {
                payDueDate = TimeUtil.AddDays(order.GetDateOrdered(), payterm.GetDiscountDays());
            }
            schedule.SetDiscountDate(payDueDate);

            //schedule.SetDiscountDate(order.GetDateOrdered().Value.AddDays(Util.GetValueOfInt(payterm.GetDiscountDays())));
            schedule.SetDiscountAmt((Util.GetValueOfDecimal((order.GetGrandTotal() * payterm.GetDiscount()) / 100)));

            if (payterm.IsNextBusinessDay())
            {
                payDueDate = payterm.GetNextBusinessDate(TimeUtil.AddDays(order.GetDateOrdered(), payterm.GetDiscountDays2()));
            }
            else
            {
                payDueDate = TimeUtil.AddDays(order.GetDateOrdered(), payterm.GetDiscountDays2());
            }
            schedule.SetDiscountDays2(payDueDate);

            //schedule.SetDiscountDays2(order.GetDateOrdered().Value.AddDays(Util.GetValueOfInt(payterm.GetDiscountDays2())));
            schedule.SetDiscount2((Util.GetValueOfDecimal((order.GetGrandTotal() * payterm.GetDiscount2()) / 100)));

            schedule.SetVA009_PlannedDueDate(GetDueDate(order));

            int BaseCurrency = GetCtx().GetContextAsInt("$C_Currency_ID");

            if (BaseCurrency != order.GetC_Currency_ID())
            {
                decimal multiplyRate = MConversionRate.GetRate(order.GetC_Currency_ID(), BaseCurrency, order.GetDateAcct(), order.GetC_ConversionType_ID(), order.GetAD_Client_ID(), order.GetAD_Org_ID());
                schedule.SetVA009_OpenAmnt(order.GetGrandTotal() * multiplyRate);
            }
            else
            {
                schedule.SetVA009_OpenAmnt(order.GetGrandTotal());
            }

            schedule.SetC_Currency_ID(order.GetC_Currency_ID());
            schedule.SetVA009_BseCurrncy(BaseCurrency);
            schedule.SetVA009_OpnAmntInvce(order.GetGrandTotal());
            schedule.SetC_BPartner_ID(order.GetC_BPartner_ID());

            MOrder _Order = new MOrder(GetCtx(), order.GetC_Order_ID(), Get_TrxName());
            //schedule.SetVA009_PaymentMethod_ID(_Order.GetVA009_PaymentMethod_ID());
            //schedule.SetC_PaymentTerm_ID(_Order.GetC_PaymentTerm_ID());

            int      _graceDay    = payterm.GetGraceDays();
            DateTime?_followUpDay = GetDueDate(order);

            schedule.SetVA009_FollowupDate(_followUpDay.Value.AddDays(_graceDay));
            _sql.Clear();
            _sql.Append("SELECT VA009_PaymentMode, VA009_PaymentType, VA009_PaymentTrigger FROM VA009_PaymentMethod WHERE VA009_PaymentMethod_ID="
                        + order.GetVA009_PaymentMethod_ID() + " AND IsActive = 'Y' AND AD_Client_ID = " + order.GetAD_Client_ID());
            DataSet ds = new DataSet();

            ds = DB.ExecuteDataset(_sql.ToString());

            if (ds != null && ds.Tables != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                schedule.SetVA009_PaymentMode(Util.GetValueOfString(ds.Tables[0].Rows[0]["VA009_PaymentMode"]));
                schedule.SetVA009_PaymentType(Util.GetValueOfString(ds.Tables[0].Rows[0]["VA009_PaymentType"]));
                schedule.SetVA009_PaymentTrigger(Util.GetValueOfString(ds.Tables[0].Rows[0]["VA009_PaymentTrigger"]));
                schedule.SetVA009_ExecutionStatus("A");
            }

            //	updateInvoice
            if (!schedule.Save())
            {
                ValueNamePair pp = VLogger.RetrieveError();
                log.Info("Error found during creation of Order Schedule against Order ID = " + order.GetC_Order_ID() +
                         " Error Name is " + pp.GetName());
            }
        }
Exemple #22
0
        }       //	doWork

        /**
         *  Process Alert
         *	@param alert alert
         *	@return true if processed
         */
        private bool ProcessAlert(MAlert alert)
        {
            if (!alert.IsValid())
            {
                log.Info("Invalid: " + alert);
                return(false);
            }
            log.Info("" + alert);
            m_recipients.Clear();

            StringBuilder message = new StringBuilder(alert.GetAlertMessage())
                                    .Append(Env.NL);
            //	Context
            Ctx ctx = alert.GetCtx();

            ctx.SetAD_Client_ID(alert.GetAD_Client_ID());
            ctx.SetAD_Org_ID(alert.GetAD_Org_ID());
            //
            bool valid     = true;
            bool processed = false;

            MAlertRule[] rules = alert.GetRules(false);
            for (int i = 0; i < rules.Length; i++)
            {
                if (i > 0)
                {
                    message.Append(Env.NL).Append("================================").Append(Env.NL);
                }
                //Trx trx = null;		//	assume r/o

                MAlertRule rule = rules[i];
                if (!rule.IsValid())
                {
                    log.Config("Invalid: " + rule);
                    continue;
                }
                log.Fine("" + rule);

                //	Pre
                String sql = rule.GetPreProcessing();
                if (sql != null && sql.Length > 0)
                {
                    int no = DB.ExecuteQuery(sql);
                    if (no == -1)
                    {
                        ValueNamePair error = VLogger.RetrieveError();
                        rule.SetErrorMsg("Pre=" + error.GetName());
                        m_errors.Append("Pre=" + error.GetName());
                        rule.SetIsValid(false);
                        rule.Save();
                        valid = false;
                        break;
                    }
                }       //	Pre

                //	The processing
                ctx.SetAD_Role_ID(0);
                ctx.SetAD_User_ID(0);
                sql = rule.GetSql();
                if (alert.IsEnforceRoleSecurity() ||
                    alert.IsEnforceClientSecurity())
                {
                    int AD_Role_ID = alert.GetFirstAD_Role_ID();
                    if (AD_Role_ID == -1)
                    {
                        AD_Role_ID = alert.GetFirstUserAD_Role_ID();
                    }
                    if (AD_Role_ID != -1)
                    {
                        String tableName      = rule.GetTableName();
                        bool   fullyQualified = MRole.SQL_FULLYQUALIFIED;
                        if (Util.IsEmpty(tableName))
                        {
                            fullyQualified = MRole.SQL_NOTQUALIFIED;
                        }
                        MRole role = MRole.Get(ctx, AD_Role_ID, 0, false);
                        sql = role.AddAccessSQL(sql, tableName,
                                                fullyQualified, MRole.SQL_RO);
                        ctx.SetAD_Role_ID(AD_Role_ID);
                    }
                    if (alert.GetFirstAD_User_ID() != -1)
                    {
                        ctx.SetAD_User_ID(alert.GetFirstAD_User_ID());
                    }
                }

                try
                {
                    String text = ListSqlSelect(sql);
                    if (text != null && text.Length > 0)
                    {
                        message.Append(text);
                        processed = true;
                        int index = text.IndexOf(":");
                        if (index > 0 && index < 5)
                        {
                            m_summary.Append(text.Substring(0, index));
                        }
                    }
                }
                catch (Exception e)
                {
                    rule.SetErrorMsg("Select=" + e.Message);
                    m_errors.Append("Select=" + e.Message);
                    rule.SetIsValid(false);
                    rule.Save();
                    valid = false;
                    break;
                }

                //	Post
                sql = rule.GetPostProcessing();
                if (sql != null && sql.Length > 0)
                {
                    int no = DB.ExecuteQuery(sql);
                    if (no == -1)
                    {
                        ValueNamePair error = VLogger.RetrieveError();
                        rule.SetErrorMsg("Post=" + error.GetName());
                        m_errors.Append("Post=" + error.GetName());
                        rule.SetIsValid(false);
                        rule.Save();
                        valid = false;
                        break;
                    }
                } //	Post
            }     //	 for all rules

            //	Update header if error
            if (!valid)
            {
                alert.SetIsValid(false);
                alert.Save();
                return(false);
            }

            //	Nothing to report
            if (!processed)
            {
                m_summary.Append(alert.GetName()).Append("=No Result - ");
                return(true);
            }

            //	Send Message
            int countRecipient = 0;

            MAlertRecipient[] recipients = alert.GetRecipients(false);
            for (int i = 0; i < recipients.Length; i++)
            {
                MAlertRecipient recipient = recipients[i];
                if (recipient.GetAD_User_ID() >= 0)             //	System == 0
                {
                    if (SendInfo(recipient.GetAD_User_ID(), alert, message.ToString()))
                    {
                        countRecipient++;
                    }
                }
                if (recipient.GetAD_Role_ID() >= 0)             //	SystemAdministrator == 0
                {
                    MUserRoles[] urs = MUserRoles.GetOfRole(GetCtx(), recipient.GetAD_Role_ID());
                    for (int j = 0; j < urs.Length; j++)
                    {
                        MUserRoles ur = urs[j];
                        if (!ur.IsActive())
                        {
                            continue;
                        }
                        if (SendInfo(ur.GetAD_User_ID(), alert, message.ToString()))
                        {
                            countRecipient++;
                        }
                    }
                }
            }

            m_summary.Append(alert.GetName()).Append(" (Recipients=").Append(countRecipient).Append(") - ");
            return(valid);
        }       //	processAlert
Exemple #23
0
        /// <summary>
        /// Create Invoice Line from Order Line
        /// </summary>
        /// <param name="order">order</param>
        /// <param name="orderLine">line</param>
        /// <param name="qtyInvoiced">qty</param>
        /// <param name="qtyEntered">qty</param>
        private void CreateLine(MOrder order, MOrderLine orderLine,
                                Decimal qtyInvoiced, Decimal qtyEntered)
        {
            if (_invoice == null)
            {
                _invoice = new MInvoice(order, 0, _DateInvoiced);
                int _CountVA009 = Env.IsModuleInstalled("VA009_") ? 1 : 0;
                if (_CountVA009 > 0)
                {
                    int _PaymentMethod_ID = order.GetVA009_PaymentMethod_ID();

                    // Get Payment method from Business partner
                    int bpPamentMethod_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT " + (order.IsSOTrx() ? " VA009_PaymentMethod_ID " : " VA009_PO_PaymentMethod_ID ") +
                                                                                @" FROM C_BPartner WHERE C_BPartner_ID = " + order.GetC_BPartner_ID(), null, Get_Trx()));

                    // during consolidation, payment method need to set that is defined on selected business partner.
                    // If not defined on BP then it will set from order
                    if (_ConsolidateDocument && bpPamentMethod_ID != 0)
                    {
                        _PaymentMethod_ID = bpPamentMethod_ID;
                    }
                    if (_PaymentMethod_ID > 0)
                    {
                        _invoice.SetVA009_PaymentMethod_ID(_PaymentMethod_ID);
                    }
                }

                int _CountVA026 = Env.IsModuleInstalled("VA026_") ? 1 : 0;
                if (_CountVA026 > 0)
                {
                    _invoice.SetVA026_LCDetail_ID(order.GetVA026_LCDetail_ID());
                }

                // Added by Bharat on 29 Jan 2018 to set Inco Term from Order
                if (_invoice.Get_ColumnIndex("C_IncoTerm_ID") > 0)
                {
                    _invoice.SetC_IncoTerm_ID(order.GetC_IncoTerm_ID());
                }


                if (Env.IsModuleInstalled("VA077_"))
                {
                    //.setva077
                    _invoice.Set_Value("VA077_AdditionalAnnualCharge", order.Get_Value("VA077_AdditionalAnnualCharge"));
                    _invoice.Set_Value("VA077_ChangeStartDate", order.Get_Value("VA077_ChangeStartDate"));
                    _invoice.Set_Value("VA077_ContractCPEndDate", order.Get_Value("VA077_ContractCPEndDate"));
                    _invoice.Set_Value("VA077_ContractCPStartDate", order.Get_Value("VA077_ContractCPStartDate"));
                    _invoice.Set_Value("VA077_HistoricContractDate", order.Get_Value("VA077_HistoricContractDate"));
                    _invoice.Set_Value("VA077_IsLegalEntity", order.Get_Value("VA077_IsLegalEntity"));
                    _invoice.Set_Value("VA077_MarginPercent", order.Get_Value("VA077_MarginPercent"));
                    _invoice.Set_Value("VA077_NewAnnualContractTotal", order.Get_Value("VA077_NewAnnualContractTotal"));
                    _invoice.Set_Value("VA077_OldAnnualContractTotal", order.Get_Value("VA077_OldAnnualContractTotal"));
                    _invoice.Set_Value("VA077_PartialAmtCatchUp", order.Get_Value("VA077_PartialAmtCatchUp"));

                    _invoice.Set_Value("VA077_SalesCoWorker", order.Get_Value("VA077_SalesCoWorker"));
                    _invoice.Set_Value("VA077_SalesCoWorkerPer", order.Get_Value("VA077_SalesCoWorkerPer"));
                    _invoice.Set_Value("VA077_TotalMarginAmt", order.Get_Value("VA077_TotalMarginAmt"));
                    _invoice.Set_Value("VA077_TotalPurchaseAmt", order.Get_Value("VA077_TotalPurchaseAmt"));
                    _invoice.Set_Value("VA077_TotalSalesAmt", order.Get_Value("VA077_TotalSalesAmt"));
                }

                if (!_invoice.Save())
                {
                    ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                    if (pp != null)
                    {
                        throw new ArgumentException("Could not create Invoice (o). " + pp.GetName());
                    }
                    throw new Exception("Could not create Invoice (o)");
                }
            }
            //
            MInvoiceLine line = new MInvoiceLine(_invoice);

            line.SetOrderLine(orderLine);
            line.SetQtyInvoiced(qtyInvoiced);
            // if drop ship line true
            line.SetIsDropShip(orderLine.IsDropShip());

            log.Info("Qty Invoiced" + line.GetQtyInvoiced());
            line.SetQtyEntered(qtyEntered);
            line.SetLine(_line + orderLine.GetLine());


            if (Env.IsModuleInstalled("VA077_"))
            {
                //invoice line
                line.Set_Value("VA077_CNAutodesk", orderLine.Get_Value("VA077_CNAutodesk"));
                line.Set_Value("VA077_Duration", orderLine.Get_Value("VA077_Duration"));
                line.Set_Value("VA077_MarginAmt", orderLine.Get_Value("VA077_MarginAmt"));
                line.Set_Value("VA077_MarginPercent", orderLine.Get_Value("VA077_MarginPercent"));
                line.Set_Value("VA077_OldSN", orderLine.Get_Value("VA077_OldSN"));
                line.Set_Value("VA077_ProductInfo", orderLine.Get_Value("VA077_ProductInfo"));
                line.Set_Value("VA077_PurchasePrice", orderLine.Get_Value("VA077_PurchasePrice"));
                line.Set_Value("VA077_RegEmail", orderLine.Get_Value("VA077_RegEmail"));
                line.Set_Value("VA077_SerialNo", orderLine.Get_Value("VA077_SerialNo"));
                line.Set_Value("VA077_UpdateFromVersn", orderLine.Get_Value("VA077_UpdateFromVersn"));
                line.Set_Value("VA077_UserRef_ID", orderLine.Get_Value("VA077_UserRef_ID"));
                line.Set_Value("VA077_StartDate", orderLine.Get_Value("VA077_StartDate"));
                line.Set_Value("VA077_EndDate", orderLine.Get_Value("VA077_EndDate"));
            }

            if (!line.Save())
            {
                ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                if (pp != null)
                {
                    throw new ArgumentException("Could not create Invoice Line (o). " + pp.GetName());
                }
                throw new Exception("Could not create Invoice Line (o)");
            }
            log.Fine(line.ToString());
        }
        /// <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>
        /// Check the dunning run
        /// 1) Check for following Rule: ShowAll should produce only a record if at least one new line is found
        /// </summary>
        private void CheckDunningEntry()
        {
            // Check rule 1)
            if (_level.IsShowAllDue())
            {
                MDunningRunEntry[] entries = _run.GetEntries(true);
                if (entries != null && entries.Length > 0)
                {
                    for (int i = 0; i < entries.Length; i++)
                    {
                        // We start with saying we delete this entry as long as we don't find something new
                        bool entryDelete        = true;
                        MDunningRunLine[] lines = entries[i].GetLines(true);
                        for (int j = 0; j < lines.Length; j++)
                        {
                            if (lines[j].GetTimesDunned() < 0)
                            {
                                // We clean up the *-1 from line 255
                                lines[j].SetTimesDunned(lines[j].GetTimesDunned() * -1);
                                if (!lines[j].Save())
                                {
                                    // Change by mohit to pick error message from last error in mclass.
                                    //throw new Exception(GetRetrievedError(lines[j], "Cannot save MDunningRunLine"));
                                    ValueNamePair vp = VLogger.RetrieveError();
                                    if (vp != null)
                                    {
                                        log.SaveError(Msg.GetMsg(GetCtx(), "NotSaveDunRunLine"), vp.GetName());
                                    }
                                    else
                                    {
                                        log.SaveError(Msg.GetMsg(GetCtx(), "NotSaveDunRunLine"), "");
                                    }
                                }
                            }

                            else
                            {
                                // We found something new, so we would not save anything...
                                entryDelete = false;
                            }
                        }
                        if (entryDelete)
                        {
                            entries[i].Delete(false);
                        }
                    }
                }
            }
        }
Exemple #26
0
        /// <summary>
        /// Create Invoice Line from Shipment
        /// </summary>
        /// <param name="order">order</param>
        /// <param name="ship">shipment header</param>
        /// <param name="sLine">shipment line</param>
        private void CreateLine(MOrder order, MInOut ship, MInOutLine sLine)
        {
            if (_invoice == null)
            {
                _invoice = new MInvoice(order, 0, _DateInvoiced);
                int _CountVA009 = Env.IsModuleInstalled("VA009_") ? 1 : 0;
                if (_CountVA009 > 0)
                {
                    int _PaymentMethod_ID = order.GetVA009_PaymentMethod_ID();
                    // during consolidation, payment method need to set that is defined on selected business partner.
                    // If not defined on BP then it will set from order
                    // during sale cycle -- VA009_PaymentMethod_ID
                    // during purchase cycle -- VA009_PO_PaymentMethod_ID
                    int bpPamentMethod_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT " + (order.IsSOTrx() ? " VA009_PaymentMethod_ID " : " VA009_PO_PaymentMethod_ID ") +
                                                                                @" FROM C_BPartner WHERE C_BPartner_ID = " + order.GetC_BPartner_ID(), null, Get_Trx()));

                    if (_ConsolidateDocument && bpPamentMethod_ID != 0)
                    {
                        _PaymentMethod_ID = bpPamentMethod_ID;
                    }
                    if (_PaymentMethod_ID > 0)
                    {
                        _invoice.SetVA009_PaymentMethod_ID(_PaymentMethod_ID);
                    }
                }

                int _CountVA026 = Env.IsModuleInstalled("VA026_") ? 1 : 0;
                if (_CountVA026 > 0)
                {
                    _invoice.SetVA026_LCDetail_ID(order.GetVA026_LCDetail_ID());
                }

                // Added by Bharat on 29 Jan 2018 to set Inco Term from Order
                if (_invoice.Get_ColumnIndex("C_IncoTerm_ID") > 0)
                {
                    _invoice.SetC_IncoTerm_ID(order.GetC_IncoTerm_ID());
                }

                if (Env.IsModuleInstalled("VA077_"))
                {
                    //.setva077
                    _invoice.Set_Value("VA077_AdditionalAnnualCharge", order.Get_Value("VA077_AdditionalAnnualCharge"));
                    _invoice.Set_Value("VA077_ChangeStartDate", order.Get_Value("VA077_ChangeStartDate"));
                    _invoice.Set_Value("VA077_ContractCPEndDate", order.Get_Value("VA077_ContractCPEndDate"));
                    _invoice.Set_Value("VA077_ContractCPStartDate", order.Get_Value("VA077_ContractCPStartDate"));
                    _invoice.Set_Value("VA077_HistoricContractDate", order.Get_Value("VA077_HistoricContractDate"));
                    _invoice.Set_Value("VA077_IsLegalEntity", order.Get_Value("VA077_IsLegalEntity"));
                    _invoice.Set_Value("VA077_MarginPercent", order.Get_Value("VA077_MarginPercent"));
                    _invoice.Set_Value("VA077_NewAnnualContractTotal", order.Get_Value("VA077_NewAnnualContractTotal"));
                    _invoice.Set_Value("VA077_OldAnnualContractTotal", order.Get_Value("VA077_OldAnnualContractTotal"));
                    _invoice.Set_Value("VA077_PartialAmtCatchUp", order.Get_Value("VA077_PartialAmtCatchUp"));
                    _invoice.Set_Value("VA077_SalesCoWorker", order.Get_Value("VA077_SalesCoWorker"));
                    _invoice.Set_Value("VA077_SalesCoWorkerPer", order.Get_Value("VA077_SalesCoWorkerPer"));
                    _invoice.Set_Value("VA077_TotalMarginAmt", order.Get_Value("VA077_TotalMarginAmt"));
                    _invoice.Set_Value("VA077_TotalPurchaseAmt", order.Get_Value("VA077_TotalPurchaseAmt"));
                    _invoice.Set_Value("VA077_TotalSalesAmt", order.Get_Value("VA077_TotalSalesAmt"));
                }

                if (!_invoice.Save())
                {
                    ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                    if (pp != null)
                    {
                        throw new ArgumentException("Could not create Invoice (s). " + pp.GetName());
                    }
                    throw new Exception("Could not create Invoice (s)");
                }
            }
            #region Comment Create Shipment Comment Line
            //	Create Shipment Comment Line
            //if (_ship == null
            //    || _ship.GetM_InOut_ID() != ship.GetM_InOut_ID())
            //{
            //    MDocType dt = MDocType.Get(GetCtx(), ship.GetC_DocType_ID());
            //    if (_bp == null || _bp.GetC_BPartner_ID() != ship.GetC_BPartner_ID())
            //    {
            //        _bp = new MBPartner(GetCtx(), ship.GetC_BPartner_ID(), Get_TrxName());
            //    }

            //    //	Reference: Delivery: 12345 - 12.12.12
            //    MClient client = MClient.Get(GetCtx(), order.GetAD_Client_ID());
            //    String AD_Language = client.GetAD_Language();
            //    if (client.IsMultiLingualDocument() && _bp.GetAD_Language() != null)
            //    {
            //        AD_Language = _bp.GetAD_Language();
            //    }
            //    if (AD_Language == null)
            //    {
            //        // MessageBox.Show("Set base Language");
            //        //AD_Language = Language.getBaseAD_Language();
            //    }
            //    //java.text.SimpleDateFormat format = DisplayType.getDateFormat
            //    //    (DisplayType.Date, Language.getLanguage(AD_Language));

            //    //String reference = dt.GetPrintName(_bp.GetAD_Language())
            //    //    + ": " + ship.GetDocumentNo()
            //    //    + " - " + format.format(ship.GetMovementDate());
            //    String reference = dt.GetPrintName(_bp.GetAD_Language())
            //        + ": " + ship.GetDocumentNo()
            //        + " - " + ship.GetMovementDate();
            //    _ship = ship;
            //    //
            //    MInvoiceLine line = new MInvoiceLine(_invoice);
            //    line.SetIsDescription(true);
            //    line.SetDescription(reference);
            //    line.SetLine(_line + sLine.GetLine() - 2);
            //    if (!line.Save())
            //    {
            //        throw new Exception("Could not create Invoice Comment Line (sh)");
            //    }
            //    //	Optional Ship Address if not Bill Address
            //    if (order.GetBill_Location_ID() != ship.GetC_BPartner_Location_ID())
            //    {
            //        MLocation addr = MLocation.GetBPLocation(GetCtx(), ship.GetC_BPartner_Location_ID(), null);
            //        line = new MInvoiceLine(_invoice);
            //        line.SetIsDescription(true);
            //        line.SetDescription(addr.ToString());
            //        line.SetLine(_line + sLine.GetLine() - 1);
            //        if (!line.Save())
            //        {
            //            throw new Exception("Could not create Invoice Comment Line 2 (sh)");
            //        }
            //    }
            //}
            #endregion
            //
            MInvoiceLine line1 = new MInvoiceLine(_invoice);
            line1.SetShipLine(sLine);
            line1.SetQtyEntered(sLine.GetQtyEntered());
            line1.SetQtyInvoiced(sLine.GetMovementQty());
            line1.SetLine(_line + sLine.GetLine());
            line1.SetM_AttributeSetInstance_ID(sLine.GetM_AttributeSetInstance_ID());
            if (sLine.GetA_Asset_ID() > 0)
            {
                line1.SetA_Asset_ID(sLine.GetA_Asset_ID());
                if (line1.Get_ColumnIndex("VAFAM_AssetCost") > 0)
                {
                    int         PAcctSchema_ID = 0;
                    int         pCurrency_ID   = 0;
                    MAcctSchema as1            = MClient.Get(GetCtx(), GetAD_Client_ID()).GetAcctSchema();
                    if (as1 != null)
                    {
                        PAcctSchema_ID = as1.GetC_AcctSchema_ID();
                        pCurrency_ID   = as1.GetC_Currency_ID();
                    }
                    decimal LineNetAmt = Decimal.Multiply(line1.GetPriceActual(), line1.GetQtyEntered());
                    decimal AssetCost  = GetAssetCost(sLine.GetA_Asset_ID(), sLine.GetM_Product_ID(), PAcctSchema_ID);
                    AssetCost = Decimal.Multiply(AssetCost, line1.GetQtyEntered());
                    if (LineNetAmt > 0)
                    {
                        LineNetAmt = MConversionRate.Convert(GetCtx(), LineNetAmt, _invoice.GetC_Currency_ID(), pCurrency_ID, _invoice.GetAD_Client_ID(), _invoice.GetAD_Org_ID());
                    }
                    decimal Diff = LineNetAmt - AssetCost;
                    line1.Set_Value("VAFAM_AssetCost", AssetCost);
                    line1.Set_Value("VAFAM_Difference", Diff);
                }
            }



            if (Env.IsModuleInstalled("VA077_"))
            {
                //invoice line
                line1.Set_Value("VA077_CNAutodesk", sLine.Get_Value("VA077_CNAutodesk"));
                line1.Set_Value("VA077_Duration", sLine.Get_Value("VA077_Duration"));
                line1.Set_Value("VA077_MarginAmt", sLine.Get_Value("VA077_MarginAmt"));
                line1.Set_Value("VA077_MarginPercent", sLine.Get_Value("VA077_MarginPercent"));
                line1.Set_Value("VA077_OldSN", sLine.Get_Value("VA077_OldSN"));
                line1.Set_Value("VA077_ProductInfo", sLine.Get_Value("VA077_ProductInfo"));
                line1.Set_Value("VA077_PurchasePrice", sLine.Get_Value("VA077_PurchasePrice"));
                line1.Set_Value("VA077_RegEmail", sLine.Get_Value("VA077_RegEmail"));
                line1.Set_Value("VA077_SerialNo", sLine.Get_Value("VA077_SerialNo"));
                line1.Set_Value("VA077_UpdateFromVersn", sLine.Get_Value("VA077_UpdateFromVersn"));
                line1.Set_Value("VA077_UserRef_ID", sLine.Get_Value("VA077_UserRef_ID"));
                line1.Set_Value("VA077_EndDate", sLine.Get_Value("VA077_EndDate"));
                line1.Set_Value("VA077_StartDate", sLine.Get_Value("VA077_StartDate"));
            }



            if (!line1.Save())
            {
                ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                if (pp != null)
                {
                    throw new ArgumentException("Could not create Invoice Line (s). " + pp.GetName());
                }
                throw new Exception("Could not create Invoice Line (s)");
            }
            //	Link
            sLine.SetIsInvoiced(true);
            if (!sLine.Save())
            {
                ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                if (pp != null)
                {
                    throw new ArgumentException("Could not update Shipment Line. " + pp.GetName());
                }
                throw new Exception("Could not update Shipment Line");
            }

            log.Fine(line1.ToString());
        }
Exemple #27
0
        /// <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("");
        }
Exemple #28
0
        /// <summary>
        /// Generate Quotation
        /// </summary>
        /// <returns>Process Message</returns>
        protected override string DoIt()
        {
            // Int32 value = 0;
            string        msg = "";
            ValueNamePair vp  = null;
            MBPartner     bp  = null;
            MOrderLine    ol  = null;

            log.Info("C_Project_ID=" + _C_Project_ID);
            if (_C_Project_ID == 0)
            {
                throw new ArgumentException("C_Project_ID == 0");
            }

            MProject fromProject = new MProject(GetCtx(), _C_Project_ID, Get_TrxName());

            if (fromProject.GetGenerate_Quotation() == null)
            {
                throw new ArgumentException("No Generate Quotation found on Project.");
            }
            if (fromProject.GetGenerate_Quotation().Trim() == "Y")
            {
                throw new ArgumentException("Sales Quotation already generated");
            }

            // if Business Partner or Prospect is not selected then gives error
            if (fromProject.GetC_BPartner_ID() == 0 && fromProject.GetC_BPartnerSR_ID() == 0)
            {
                return(Msg.GetMsg(GetCtx(), "SelectBP/Prospect"));
            }

            //JID_1200: if Business Partner/Prospect Location is not selected then gives error
            if (fromProject.GetC_BPartner_Location_ID() == 0)
            {
                return(Msg.GetMsg(GetCtx(), "SelectBPLocation"));
            }

            MOrder order = new MOrder(GetCtx(), 0, Get_TrxName());

            order.SetAD_Client_ID(fromProject.GetAD_Client_ID());
            order.SetAD_Org_ID(fromProject.GetAD_Org_ID());
            C_Bpartner_id          = fromProject.GetC_BPartner_ID();
            C_Bpartner_Location_id = fromProject.GetC_BPartner_Location_ID();
            C_BPartnerSR_ID        = fromProject.GetC_BPartnerSR_ID();

            MBPartnerLocation bpartnerloc = new MBPartnerLocation(GetCtx(), C_Bpartner_Location_id, Get_TrxName());
            //String currentdate = DateTime.Now.ToString();
            String sqlprjln = "SELECT COUNT(C_ProjectLine_ID) FROM C_ProjectLine WHERE C_Project_ID=" + _C_Project_ID;

            C_ProjectLine_ID = Util.GetValueOfInt(DB.ExecuteScalar(sqlprjln, null, Get_TrxName()));
            if (C_ProjectLine_ID != 0)
            {
                order.SetDateOrdered(DateTime.Now.ToLocalTime());
                order.SetDatePromised(DateTime.Now.ToLocalTime());
                if (C_Bpartner_id != 0)
                {
                    order.SetC_BPartner_ID(fromProject.GetC_BPartner_ID());
                    if (bpartnerloc.IsShipTo() == true)
                    {
                        order.SetC_BPartner_Location_ID(fromProject.GetC_BPartner_Location_ID());
                        order.SetAD_User_ID(fromProject.GetAD_User_ID());
                    }
                    if (bpartnerloc.IsBillTo() == true)
                    {
                        order.SetBill_Location_ID(fromProject.GetC_BPartner_Location_ID());
                        order.SetBill_User_ID(fromProject.GetAD_User_ID());
                    }
                }
                if (C_BPartnerSR_ID != 0)
                {
                    order.SetC_BPartner_ID(fromProject.GetC_BPartnerSR_ID());
                    if (bpartnerloc.IsShipTo() == true)
                    {
                        order.SetC_BPartner_Location_ID(fromProject.GetC_BPartner_Location_ID());
                        order.SetAD_User_ID(fromProject.GetAD_User_ID());
                    }
                    if (bpartnerloc.IsBillTo() == true)
                    {
                        order.SetBill_Location_ID(fromProject.GetC_BPartner_Location_ID());
                        order.SetBill_User_ID(fromProject.GetAD_User_ID());
                    }
                }

                String sql = "SELECT C_DocType_ID FROM C_DocType WHERE DocBaseType = 'SOO' AND DocSubTypeSO = 'ON' AND IsReturnTrx = 'N' AND IsActive = 'Y' AND AD_Client_ID = "
                             + GetCtx().GetAD_Client_ID() + " AND AD_Org_ID IN (0, " + GetAD_Org_ID() + ") ORDER BY  AD_Org_ID DESC";
                int Doctype_id    = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, Get_TrxName()));
                int MPriceList_id = fromProject.GetM_PriceList_ID();
                order.SetM_PriceList_ID(MPriceList_id);

                order.SetC_Project_ID(GetRecord_ID());
                if (fromProject.GetSalesRep_ID() > 0)
                {
                    order.SetSalesRep_ID(fromProject.GetSalesRep_ID());
                }
                order.SetC_Currency_ID(fromProject.GetC_Currency_ID());
                if (C_Bpartner_id != 0)
                {
                    bp = new MBPartner(GetCtx(), C_Bpartner_id, Get_TrxName());
                    if (bp.GetC_Campaign_ID() == 0 && fromProject.GetC_Campaign_ID() > 0)
                    {
                        bp.SetC_Campaign_ID(fromProject.GetC_Campaign_ID());
                    }
                    //bp.SetAD_Client_ID(fromProject.GetAD_Client_ID());
                    //bp.SetAD_Org_ID(fromProject.GetAD_Org_ID());
                    if (bp.GetC_PaymentTerm_ID() != 0)
                    {
                        order.SetPaymentMethod(bp.GetPaymentRule());
                        order.SetC_PaymentTerm_ID(bp.GetC_PaymentTerm_ID());
                        order.SetVA009_PaymentMethod_ID(bp.GetVA009_PaymentMethod_ID());
                    }

                    if (!bp.Save())
                    {
                        log.SaveError("BPartnerNotSaved", "");
                        return(Msg.GetMsg(GetCtx(), "BPartnerNotSaved"));
                    }
                }
                else
                {
                    bp = new MBPartner(GetCtx(), C_BPartnerSR_ID, Get_TrxName());
                    if (bp.GetC_Campaign_ID() == 0 && fromProject.GetC_Campaign_ID() > 0)
                    {
                        bp.SetC_Campaign_ID(fromProject.GetC_Campaign_ID());
                    }
                    //bp.SetAD_Client_ID(fromProject.GetAD_Client_ID());
                    //bp.SetAD_Org_ID(fromProject.GetAD_Org_ID());
                    if (bp.GetC_PaymentTerm_ID() != 0)
                    {
                        order.SetPaymentMethod(bp.GetPaymentRule());
                        order.SetC_PaymentTerm_ID(bp.GetC_PaymentTerm_ID());
                        order.SetVA009_PaymentMethod_ID(bp.GetVA009_PaymentMethod_ID());
                    }

                    if (!bp.Save())
                    {
                        log.SaveError("BPartnerNotSaved", "");
                        return(Msg.GetMsg(GetCtx(), "BPartnerNotSaved"));
                    }
                }

                order.SetFreightCostRule("I");
                if (order.GetC_Campaign_ID() == 0 && fromProject.GetC_Campaign_ID() > 0)
                {
                    order.SetC_Campaign_ID(fromProject.GetC_Campaign_ID());
                }
                order.SetDocStatus("IP");
                order.SetC_DocType_ID(Doctype_id);
                order.SetC_DocTypeTarget_ID(Doctype_id);
                order.SetIsSOTrx(true);
                order.Set_Value("IsSalesQuotation", true);

                //Set VA077 values on header level
                if (Env.IsModuleInstalled("VA077_"))
                {
                    //Get the org count of legal entity org
                    sql = @"SELECT Count(AD_Org_ID) FROM AD_Org WHERE IsActive='Y' 
                           AND (IsProfitCenter ='Y' OR IsCostCenter ='Y') AND 
                           AD_Client_Id=" + fromProject.GetAD_Client_ID() + @" AND LegalEntityOrg = " + fromProject.GetAD_Org_ID();
                    int result = Util.GetValueOfInt(DB.ExecuteScalar(sql));
                    if (result > 0)
                    {
                        order.SetVA077_IsLegalEntity(true);
                    }
                    order.SetVA077_SalesCoWorker(fromProject.GetVA077_SalesCoWorker());
                    order.SetVA077_SalesCoWorkerPer(fromProject.GetVA077_SalesCoWorkerPer());
                    order.Set_Value("VA077_TotalMarginAmt", fromProject.Get_Value("VA077_TotalMarginAmt"));
                    order.Set_Value("VA077_TotalPurchaseAmt", fromProject.Get_Value("VA077_TotalPurchaseAmt"));
                    order.Set_Value("VA077_TotalSalesAmt", fromProject.Get_Value("VA077_TotalSalesAmt"));
                    order.Set_Value("VA077_MarginPercent", fromProject.Get_Value("VA077_MarginPercent"));
                }

                if (!order.Save())
                {
                    Get_TrxName().Rollback();
                    vp = VLogger.RetrieveError();
                    if (vp != null)
                    {
                        msg = vp.GetName();
                    }
                    else
                    {
                        msg = Msg.GetMsg(GetCtx(), "QuotationNotSaved");
                    }
                    log.SaveError("QuotationNotSaved", "");
                    return(msg);
                }

                //Order Lines
                int            count = 0;
                MProjectLine[] lines = fromProject.GetLines();
                for (int i = 0; i < lines.Length; i++)
                {
                    ol = new MOrderLine(order);
                    ol.SetLine(lines[i].GetLine());
                    ol.SetDescription(lines[i].GetDescription());
                    ol.SetM_Product_ID(lines[i].GetM_Product_ID(), true);
                    ol.SetQtyEntered(lines[i].GetPlannedQty());
                    ol.SetQtyOrdered(lines[i].GetPlannedQty());
                    ol.SetPriceEntered(lines[i].GetPlannedPrice());
                    ol.SetPriceActual(lines[i].GetPlannedPrice());
                    ol.SetPriceList(lines[i].GetPriceList());

                    //Set VA077 values on line level
                    if (Env.IsModuleInstalled("VA077_"))
                    {
                        ol.Set_Value("VA077_MarginPercent", lines[i].Get_Value("VA077_MarginPercent"));
                        ol.Set_Value("VA077_MarginAmt", lines[i].Get_Value("VA077_MarginAmt"));
                        ol.Set_Value("VA077_PurchasePrice", lines[i].Get_Value("VA077_PurchasePrice"));
                    }
                    if (ol.Save())
                    {
                        count++;
                    }
                    else
                    {
                        Get_TrxName().Rollback();
                        vp = VLogger.RetrieveError();
                        if (vp != null)
                        {
                            msg = vp.GetName();
                        }
                        else
                        {
                            msg = Msg.GetMsg(GetCtx(), "QuoteLineNotSaved");
                        }
                        log.SaveError("QuoteLineNotSaved", "");
                        return(msg);
                    }
                }

                fromProject.SetRef_Order_ID(order.GetC_Order_ID());
                fromProject.SetGenerate_Quotation("Y");
                if (!fromProject.Save())
                {
                    Get_TrxName().Rollback();
                    log.SaveError("ProjectNotSaved", "");
                    return(Msg.GetMsg(GetCtx(), "ProjectNotSaved"));
                }
                msg = Msg.GetMsg(GetCtx(), "QuotationGenerated");
            }
            else
            {
                msg = Msg.GetMsg(GetCtx(), "NoLines");
            }
            return(msg);
        }
Exemple #29
0
        /// <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("");
        }
        /// <summary>
        /// Create Invoice.
        /// </summary>
        /// <returns>document no</returns>
        protected override String DoIt()
        {
            StringBuilder invDocumentNo  = new StringBuilder();
            int           count          = Util.GetValueOfInt(DB.ExecuteScalar(" SELECT  Count(*)  FROM M_Inout WHERE  ISSOTRX='Y' AND  M_Inout_ID=" + GetRecord_ID()));
            MInOut        ship           = null;
            bool          isAllownonItem = Util.GetValueOfString(GetCtx().GetContext("$AllowNonItem")).Equals("Y");

            if (count > 0)
            {
                if (_M_InOut_ID == 0)
                {
                    throw new ArgumentException("No Shipment");
                }
                //
                ship = new MInOut(GetCtx(), _M_InOut_ID, Get_Trx());
                if (ship.Get_ID() == 0)
                {
                    throw new ArgumentException("Shipment not found");
                }
                if (!MInOut.DOCSTATUS_Completed.Equals(ship.GetDocStatus()))
                {
                    // JID_0750: done by Bharat on 05 Feb 2019 if Customer Return document and status is not complete it should give message "Customer Return Not Completed".
                    if (ship.IsReturnTrx())
                    {
                        throw new ArgumentException("Customer Return Not Completed");
                    }
                    else
                    {
                        throw new ArgumentException("Shipment Not Completed");
                    }
                }
            }
            else
            {
                if (_M_InOut_ID == 0)
                {
                    throw new ArgumentException("No Material Receipt");
                }
                //
                ship = new MInOut(GetCtx(), _M_InOut_ID, Get_Trx());
                if (ship.Get_ID() == 0)
                {
                    throw new ArgumentException("Material Receipt not found");
                }
                if (!MInOut.DOCSTATUS_Completed.Equals(ship.GetDocStatus()))
                {
                    // JID_0750: done by Bharat on 05 Feb 2019 if Return to vendor document and status is not complete it should give message "Return To Vendor Not Completed".
                    if (ship.IsReturnTrx())
                    {
                        throw new ArgumentException("Return To Vendor Not Completed");
                    }
                    else
                    {
                        throw new ArgumentException("Material Receipt Not Completed");
                    }
                }
            }

            // When record contain more than single order and order having different Payment term or Price List then not to generate invoices
            // JID_0976 - For conversion Type
            if (ship.GetC_Order_ID() > 0 && Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT  COUNT(DISTINCT  c_order.m_pricelist_id) +  count(distinct c_order.c_paymentterm_id) + count(distinct COALESCE( c_order.C_ConversionType_ID , " + MConversionType.GetDefault(GetAD_Client_ID()) + @"))  as recordcount
                            FROM m_inoutline INNER JOIN c_orderline ON m_inoutline.c_orderline_id = c_orderline.c_orderline_id
                            INNER JOIN c_order ON c_order.c_order_id = c_orderline.c_order_id
                            WHERE m_inoutline.m_inout_id = " + _M_InOut_ID + @"  GROUP BY   m_inoutline.m_inout_id ", null, Get_Trx())) > 3)
            {
                if (ship.IsSOTrx())
                {
                    //Different Payment Terms, Price list found against the selected orders, use "Generate Invoice" process to create multiple invoices.
                    throw new ArgumentException(Msg.GetMsg(GetCtx(), "VIS_SoDifferentPayAndPrice"));
                }
                else
                {
                    //Different Payment Terms, Price list found against the selected orders
                    throw new ArgumentException(Msg.GetMsg(GetCtx(), "VIS_DifferentPayAndPrice"));
                }
            }

            // Create Invoice Header
            MInvoice invoice = new MInvoice(ship, null);

            //Payment Management
            int _CountVA009 = Env.IsModuleInstalled("VA009_") ? 1 : 0;

            // Amortization
            int _CountVA038 = Env.IsModuleInstalled("VA038_") ? 1 : 0;

            if (_CountVA009 > 0)
            {
                int _PaymentMethod_ID = Util.GetValueOfInt(DB.ExecuteScalar("Select VA009_PaymentMethod_ID From C_Order Where C_Order_ID=" + ship.GetC_Order_ID(), null, Get_Trx()));

                // during consolidation, payment method need to set that is defined on selected business partner.
                // If not defined on BP then it will set from order
                int bpPamentMethod_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT " + (ship.IsSOTrx() ? " VA009_PaymentMethod_ID " : " VA009_PO_PaymentMethod_ID ") +
                                                                            @" FROM C_BPartner WHERE C_BPartner_ID = " + ship.GetC_BPartner_ID(), null, Get_Trx()));

                if (bpPamentMethod_ID != 0)
                {
                    _PaymentMethod_ID = bpPamentMethod_ID;
                }
                if (_PaymentMethod_ID > 0)
                {
                    invoice.SetVA009_PaymentMethod_ID(_PaymentMethod_ID);
                }
            }

            // Letter Of Credit
            int _CountVA026 = Env.IsModuleInstalled("VA026_") ? 1 : 0;

            if (_CountVA026 > 0)
            {
                int VA026_LCDetail_ID = Util.GetValueOfInt(DB.ExecuteScalar("Select VA026_LCDetail_ID From C_Order Where C_Order_ID=" + ship.GetC_Order_ID(), null, Get_Trx()));
                if (VA026_LCDetail_ID > 0)
                {
                    invoice.SetVA026_LCDetail_ID(VA026_LCDetail_ID);
                }
            }
            //end

            if (ship.IsReturnTrx())
            {
                if (!ship.IsSOTrx())
                {
                    // Purchase Return
                    // set target document from documnet type window -- based on documnet type available on material receipt / return to vendor

                    // JID_0779: Create AP Credit memo if we run the Generate TO process from Returm to Vendor window.

                    //if (invoice.GetC_DocTypeTarget_ID() == 0)
                    //{
                    if (_C_DocType_ID > 0)
                    {
                        invoice.SetC_DocTypeTarget_ID(_C_DocType_ID);
                    }
                    else
                    {
                        int C_DocTypeTarget_ID = DB.GetSQLValue(null, "SELECT C_DocTypeInvoice_ID FROM C_DocType WHERE C_DocType_ID=@param1", ship.GetC_DocType_ID());
                        if (C_DocTypeTarget_ID > 0)
                        {
                            invoice.SetC_DocTypeTarget_ID(C_DocTypeTarget_ID);
                        }
                        else
                        {
                            invoice.SetC_DocTypeTarget_ID(ship.IsSOTrx() ? MDocBaseType.DOCBASETYPE_ARCREDITMEMO : MDocBaseType.DOCBASETYPE_APCREDITMEMO);
                        }
                    }
                    invoice.SetIsReturnTrx(ship.IsReturnTrx());
                    invoice.SetIsSOTrx(ship.IsSOTrx());
                }
                else
                {
                    // Sales Return
                    if (_C_DocType_ID > 0)
                    {
                        invoice.SetC_DocTypeTarget_ID(_C_DocType_ID);
                    }
                    else
                    {
                        if (ship.GetC_Order_ID() >= 0)
                        {
                            int      C_DocType_ID = Util.GetValueOfInt(DB.ExecuteScalar("Select C_DocType_ID From C_Order Where C_Order_ID=" + ship.GetC_Order_ID(), null, Get_Trx()));
                            MDocType dt           = MDocType.Get(GetCtx(), C_DocType_ID);
                            if (dt.GetC_DocTypeInvoice_ID() != 0)
                            {
                                invoice.SetC_DocTypeTarget_ID(dt.GetC_DocTypeInvoice_ID(), true);
                            }
                            else
                            {
                                invoice.SetC_DocTypeTarget_ID(ship.IsSOTrx() ? MDocBaseType.DOCBASETYPE_ARCREDITMEMO : MDocBaseType.DOCBASETYPE_APCREDITMEMO);
                            }
                        }
                        else
                        {
                            invoice.SetC_DocTypeTarget_ID(ship.IsSOTrx() ? MDocBaseType.DOCBASETYPE_ARCREDITMEMO : MDocBaseType.DOCBASETYPE_APCREDITMEMO);
                        }
                    }
                }
            }
            if (_M_PriceList_ID != 0)
            {
                invoice.SetM_PriceList_ID(_M_PriceList_ID);
            }
            //Set InvoiceDocumentNo to InvoiceReference
            if (_InvoiceDocumentNo != null && _InvoiceDocumentNo.Length > 0)
            {
                invoice.Set_Value("InvoiceReference", _InvoiceDocumentNo);
            }
            //Set TargetDoctype
            if (_C_DocType_ID > 0 && !ship.IsReturnTrx())
            {
                invoice.Set_Value("C_DocTypeTarget_ID", _C_DocType_ID);
            }

            // Added by Bharat on 30 Jan 2018 to set Inco Term from Order
            if (invoice.Get_ColumnIndex("C_IncoTerm_ID") > 0)
            {
                invoice.SetC_IncoTerm_ID(ship.GetC_IncoTerm_ID());
            }
            //To get Payment Rule and set the Payment method
            if (invoice.GetPaymentRule() != "")
            {
                invoice.SetPaymentMethod(invoice.GetPaymentRule());
            }
            if (!invoice.Save())
            {
                //SI_0708 - message was not upto the mark
                ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                if (pp != null)
                {
                    throw new ArgumentException("Cannot save Invoice. " + pp.GetName());
                }
                throw new ArgumentException("Cannot save Invoice");
            }
            MInOutLine[] shipLines      = ship.GetLines(false);
            DateTime?    AmortStartDate = null;
            DateTime?    AmortEndDate   = null;

            count = 0;
            DataSet ds    = null;
            DataSet dsDoc = null;

            for (int i = 0; i < shipLines.Length; i++)
            {
                MInOutLine sLine = shipLines[i];
                // Changes done by Bharat on 06 July 2017 restrict to create invoice if Invoice already created against that for same quantity
                string sql = @"SELECT ml.QtyEntered - SUM(COALESCE(li.QtyEntered,0)) as QtyEntered, ml.MovementQty- SUM(COALESCE(li.QtyInvoiced, 0)) as QtyInvoiced" +
                             " FROM M_InOutLine ml INNER JOIN C_InvoiceLine li ON li.M_InOutLine_ID = ml.M_InOutLine_ID INNER JOIN C_Invoice ci ON ci.C_Invoice_ID = li.C_Invoice_ID " +
                             " WHERE ci.DocStatus NOT IN ('VO', 'RE') AND ml.M_InOutLine_ID =" + sLine.GetM_InOutLine_ID() + " GROUP BY ml.MovementQty, ml.QtyEntered";
                ds = DB.ExecuteDataset(sql, null, Get_Trx());
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    decimal qtyEntered  = Util.GetValueOfDecimal(ds.Tables[0].Rows[0]["QtyEntered"]);
                    decimal qtyInvoiced = Util.GetValueOfDecimal(ds.Tables[0].Rows[0]["QtyInvoiced"]);
                    if (qtyEntered <= 0)
                    {
                        // Getting document number Count if Invoice already generated for Material Receipt
                        string StrSql = "SELECT ci.DocumentNo,li.M_InOutLine_ID FROM C_InvoiceLine li INNER JOIN C_Invoice ci ON ci.C_Invoice_ID = li.C_Invoice_ID " +
                                        "  WHERE ci.DocStatus NOT IN ('VO', 'RE') AND li.M_InOutLine_ID = " + sLine.GetM_InOutLine_ID();
                        dsDoc = DB.ExecuteDataset(StrSql, null, Get_Trx());
                        if (dsDoc != null && dsDoc.Tables[0].Rows.Count > 0)
                        {
                            for (int j = 0; j < dsDoc.Tables[0].Rows.Count; j++)
                            {
                                // JID_1358: Need to show document number in message if Invoice already generated for Material Receipt
                                string no = invDocumentNo.ToString();
                                if (invDocumentNo.Length > 0 && no != Util.GetValueOfString(dsDoc.Tables[0].Rows[j]["DocumentNo"]))
                                {
                                    invDocumentNo.Append(", " + Util.GetValueOfString(dsDoc.Tables[0].Rows[j]["DocumentNo"]));
                                }
                                else
                                {
                                    invDocumentNo.Clear();
                                    invDocumentNo.Append(Util.GetValueOfString(dsDoc.Tables[0].Rows[j]["DocumentNo"]));
                                }
                                ds.Dispose();
                                log.Info("Invoice Line already exist for Receipt Line ID - " + sLine.GetM_InOutLine_ID());
                                continue;
                            }
                            dsDoc.Dispose();
                        }
                    }
                    else
                    {
                        MInvoiceLine line = new MInvoiceLine(invoice);
                        line.SetShipLine(sLine);
                        line.SetQtyEntered(qtyEntered);
                        line.SetQtyInvoiced(qtyInvoiced);
                        // Change By Mohit Amortization process -------------
                        if (_CountVA038 > 0)
                        {
                            if (line.GetM_Product_ID() > 0)
                            {
                                //MProduct pro = new MProduct(GetCtx(), sLine.GetM_Product_ID(), Get_TrxName());
                                int VA038_AmortizationTemplate_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT VA038_AmortizationTemplate_ID 
                                     FROM M_Product WHERE M_Product_ID = " + sLine.GetM_Product_ID(), null, Get_Trx()));
                                if (VA038_AmortizationTemplate_ID > 0)
                                {
                                    line.Set_Value("VA038_AmortizationTemplate_ID", VA038_AmortizationTemplate_ID);
                                    DataSet amrtDS = DB.ExecuteDataset("SELECT VA038_AmortizationType,VA038_AmortizationPeriod,VA038_TermSource,VA038_PeriodType,Name FROM VA038_AmortizationTemplate WHERE IsActive='Y' AND VA038_AMORTIZATIONTEMPLATE_ID=" + VA038_AmortizationTemplate_ID);
                                    AmortStartDate = null;
                                    AmortEndDate   = null;
                                    if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "A")
                                    {
                                        AmortStartDate = invoice.GetDateAcct();
                                    }
                                    if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "T")
                                    {
                                        AmortStartDate = invoice.GetDateInvoiced();
                                    }

                                    if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "M")
                                    {
                                        AmortEndDate = AmortStartDate.Value.AddMonths(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"]));
                                    }
                                    if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "Y")
                                    {
                                        AmortEndDate = AmortStartDate.Value.AddYears(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"]));
                                    }
                                    line.Set_Value("FROMDATE", AmortStartDate);
                                    line.Set_Value("EndDate", AmortEndDate);
                                    if (amrtDS != null)
                                    {
                                        amrtDS.Dispose();
                                    }
                                }
                            }
                            if (line.GetC_Charge_ID() > 0)
                            {
                                //MCharge charge = new MCharge(GetCtx(), sLine.GetC_Charge_ID(), Get_TrxName());
                                int VA038_AmortizationTemplate_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT VA038_AmortizationTemplate_ID 
                                     FROM C_Charge WHERE C_Charge_ID = " + sLine.GetC_Charge_ID(), null, Get_Trx()));
                                if (VA038_AmortizationTemplate_ID > 0)
                                {
                                    line.Set_Value("VA038_AmortizationTemplate_ID", VA038_AmortizationTemplate_ID);
                                    DataSet amrtDS = DB.ExecuteDataset("SELECT VA038_AmortizationType,VA038_AmortizationPeriod,VA038_TermSource,VA038_PeriodType,Name FROM VA038_AmortizationTemplate WHERE IsActive='Y' AND VA038_AMORTIZATIONTEMPLATE_ID=" + VA038_AmortizationTemplate_ID);
                                    AmortStartDate = null;
                                    AmortEndDate   = null;
                                    if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "A")
                                    {
                                        AmortStartDate = invoice.GetDateAcct();
                                    }
                                    if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "T")
                                    {
                                        AmortStartDate = invoice.GetDateInvoiced();
                                    }

                                    if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "M")
                                    {
                                        AmortEndDate = AmortStartDate.Value.AddMonths(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"]));
                                    }
                                    if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "Y")
                                    {
                                        AmortEndDate = AmortStartDate.Value.AddYears(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"]));
                                    }
                                    line.Set_Value("FROMDATE", AmortStartDate);
                                    line.Set_Value("EndDate", AmortEndDate);
                                    if (amrtDS != null)
                                    {
                                        amrtDS.Dispose();
                                    }
                                }
                            }
                        }
                        // End Change Amortization process--------------
                        if (!line.Save())
                        {
                            //SI_0708 - message was not upto the mark
                            ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                            if (pp != null)
                            {
                                throw new ArgumentException("Cannot save Invoice Line. " + pp.GetName());
                            }
                            throw new ArgumentException("Cannot save Invoice Line");
                        }
                        count++;
                    }
                    ds.Dispose();
                }
                else
                {
                    MInvoiceLine line = new MInvoiceLine(invoice);
                    // JID_1850 Avoid the duplicate charge line
                    if (sLine.GetC_Charge_ID() > 0 && (!isAllownonItem || _GenerateCharges))
                    {
                        continue;
                    }
                    line.SetShipLine(sLine);
                    line.SetQtyEntered(sLine.GetQtyEntered());
                    line.SetQtyInvoiced(sLine.GetMovementQty());
                    line.Set_ValueNoCheck("IsDropShip", sLine.Get_Value("IsDropShip")); //Arpit Rai 20-Sept-2017

                    // Change By Mohit Amortization process -------------
                    if (_CountVA038 > 0)
                    {
                        if (line.GetM_Product_ID() > 0)
                        {
                            //MProduct pro = new MProduct(GetCtx(), sLine.GetM_Product_ID(), Get_TrxName());
                            int VA038_AmortizationTemplate_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT VA038_AmortizationTemplate_ID 
                                     FROM M_Product WHERE M_Product_ID = " + sLine.GetM_Product_ID(), null, Get_Trx()));
                            if (VA038_AmortizationTemplate_ID > 0)
                            {
                                line.Set_Value("VA038_AmortizationTemplate_ID", VA038_AmortizationTemplate_ID);
                                DataSet amrtDS = DB.ExecuteDataset("SELECT VA038_AmortizationType,VA038_AmortizationPeriod,VA038_TermSource,VA038_PeriodType,Name FROM VA038_AmortizationTemplate WHERE IsActive='Y' AND VA038_AMORTIZATIONTEMPLATE_ID=" + VA038_AmortizationTemplate_ID);
                                AmortStartDate = null;
                                AmortEndDate   = null;
                                if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "A")
                                {
                                    AmortStartDate = invoice.GetDateAcct();
                                }
                                if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "T")
                                {
                                    AmortStartDate = invoice.GetDateInvoiced();
                                }

                                if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "M")
                                {
                                    AmortEndDate = AmortStartDate.Value.AddMonths(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"]));
                                }
                                if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "Y")
                                {
                                    AmortEndDate = AmortStartDate.Value.AddYears(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"]));
                                }
                                line.Set_Value("FROMDATE", AmortStartDate);
                                line.Set_Value("EndDate", AmortEndDate);
                                if (amrtDS != null)
                                {
                                    amrtDS.Dispose();
                                }
                            }
                        }
                        if (line.GetC_Charge_ID() > 0)
                        {
                            //MCharge charge = new MCharge(GetCtx(), sLine.GetC_Charge_ID(), Get_TrxName());
                            int VA038_AmortizationTemplate_ID = Util.GetValueOfInt(DB.ExecuteScalar(@"SELECT VA038_AmortizationTemplate_ID 
                                     FROM C_Charge WHERE C_Charge_ID = " + sLine.GetC_Charge_ID(), null, Get_Trx()));
                            if (VA038_AmortizationTemplate_ID > 0)
                            {
                                line.Set_Value("VA038_AmortizationTemplate_ID", VA038_AmortizationTemplate_ID);
                                DataSet amrtDS = DB.ExecuteDataset("SELECT VA038_AmortizationType,VA038_AmortizationPeriod,VA038_TermSource,VA038_PeriodType,Name FROM VA038_AmortizationTemplate WHERE IsActive='Y' AND VA038_AMORTIZATIONTEMPLATE_ID=" + VA038_AmortizationTemplate_ID);
                                AmortStartDate = null;
                                AmortEndDate   = null;
                                if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "A")
                                {
                                    AmortStartDate = invoice.GetDateAcct();
                                }
                                if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "T")
                                {
                                    AmortStartDate = invoice.GetDateInvoiced();
                                }

                                if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "M")
                                {
                                    AmortEndDate = AmortStartDate.Value.AddMonths(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"]));
                                }
                                if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "Y")
                                {
                                    AmortEndDate = AmortStartDate.Value.AddYears(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"]));
                                }
                                line.Set_Value("FROMDATE", AmortStartDate);
                                line.Set_Value("EndDate", AmortEndDate);
                                if (amrtDS != null)
                                {
                                    amrtDS.Dispose();
                                }
                            }
                        }
                    }
                    // End Change Amortization process--------------
                    if (!line.Save())
                    {
                        //SI_0708 - message was not upto the mark
                        ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                        if (pp != null)
                        {
                            throw new ArgumentException("Cannot save Invoice Line. " + pp.GetName());
                        }
                        throw new ArgumentException("Cannot save Invoice Line");
                    }
                    count++;
                }
            }


            #region [Enhancement for Charges Distribution/Generation by Sukhwinder on 13 December 2017]

            if (_GenerateCharges && count > 0)
            {
                StringBuilder OrderSql = new StringBuilder();
                OrderSql.Append("   SELECT CO.C_ORDER_ID,                    "
                                + "      SUM(ML.QTYENTERED) AS MRLINEQTY,     "
                                + "      SUM(OL.QTYENTERED) AS ORDERQTY       "
                                + "  FROM M_INOUTLINE ML                      "
                                + "  INNER JOIN C_ORDERLINE OL                "
                                + "  ON OL.C_ORDERLINE_ID = ML.C_ORDERLINE_ID "
                                + " INNER JOIN C_ORDER CO                     "
                                + " ON CO.C_ORDER_ID     = OL.C_ORDER_ID      "
                                + " WHERE ML.M_INOUT_ID  = " + _M_InOut_ID
                                + " AND (OL.C_CHARGE_ID IS NULL               "
                                + " OR OL.C_CHARGE_ID    = 0)                 "
                                + " GROUP BY CO.C_ORDER_ID                    ");

                DataSet OrderDS = DB.ExecuteDataset(OrderSql.ToString(), null, Get_Trx());

                if (OrderDS != null && OrderDS.Tables[0].Rows.Count > 0)
                {
                    StringBuilder ChargesSql = new StringBuilder();
                    for (int index = 0; index < OrderDS.Tables[0].Rows.Count; index++)
                    {
                        ds = null;
                        ChargesSql.Clear();
                        ChargesSql.Append(" SELECT C_CHARGE_ID,                                             "
                                          + "   C_ORDERLINE_ID,                                                      "
                                          + "   C_ORDER_ID,                                                          "
                                          + "   C_CURRENCY_ID,                                                       "
                                          + "   PRICEENTERED,                                                        "
                                          + "   PRICEACTUAL,                                                         "
                                          + "   LINENETAMT,                                                          "
                                          + "   QTYENTERED,                                                          "
                                          + "   C_UOM_ID,                                                            "
                                          + "   C_Tax_ID,                                                            "
                                          + "   IsDropShip                                                           "
                                          + " FROM C_ORDERLINE                                                       "
                                          + " WHERE C_ORDER_ID IN                                                    "
                                          + "   ( " + Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["C_ORDER_ID"])
                                          + "   )                                                                    "
                                          + " AND C_CHARGE_ID IS NOT NULL                                            "
                                          + " AND C_CHARGE_ID  > 0                                                   ");


                        ds = DB.ExecuteDataset(ChargesSql.ToString(), null, Get_Trx());

                        if (ds != null && ds.Tables[0].Rows.Count > 0)
                        {
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                MInvoiceLine line = new MInvoiceLine(invoice);
                                line.SetQty(1);
                                line.SetQtyEntered(1);
                                line.SetQtyInvoiced(1);
                                line.SetOrderLine(new MOrderLine(GetCtx(), Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_ORDERLINE_ID"]), Get_Trx()));
                                line.SetC_Charge_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_CHARGE_ID"]));
                                line.SetC_UOM_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_UOM_ID"]));
                                line.SetC_Tax_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_TAX_ID"]));

                                decimal SumOfQty = 0;
                                if (Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["ORDERQTY"]) == 0)
                                {
                                    SumOfQty = 1;
                                }
                                else
                                {
                                    SumOfQty = Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["ORDERQTY"]);
                                }
                                decimal amt = (Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["LINENETAMT"]) / SumOfQty) * Util.GetValueOfInt(OrderDS.Tables[0].Rows[index]["MRLINEQTY"]);

                                line.SetPrice(Decimal.Round(amt, 3));
                                line.SetPriceActual(Decimal.Round(amt, 3));
                                line.SetPriceEntered(Decimal.Round(amt, 3));
                                line.SetLineNetAmt(Decimal.Round(amt, 3));

                                line.Set_ValueNoCheck("IsDropShip", Util.GetValueOfString(ds.Tables[0].Rows[i]["ISDROPSHIP"]));

                                if (_CountVA038 > 0)
                                {
                                    if (line.GetC_Charge_ID() > 0)
                                    {
                                        MCharge charge = new MCharge(GetCtx(), line.GetC_Charge_ID(), Get_TrxName());
                                        if (Util.GetValueOfInt(charge.Get_Value("VA038_AmortizationTemplate_ID")) > 0)
                                        {
                                            line.Set_Value("VA038_AmortizationTemplate_ID", Util.GetValueOfInt(charge.Get_Value("VA038_AmortizationTemplate_ID")));
                                            DataSet amrtDS = DB.ExecuteDataset("SELECT VA038_AmortizationType,VA038_AmortizationPeriod,VA038_TermSource,VA038_PeriodType,Name FROM VA038_AmortizationTemplate WHERE IsActive='Y' AND VA038_AMORTIZATIONTEMPLATE_ID=" + Util.GetValueOfInt(charge.Get_Value("VA038_AmortizationTemplate_ID")));
                                            AmortStartDate = null;
                                            AmortEndDate   = null;
                                            if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "A")
                                            {
                                                AmortStartDate = invoice.GetDateAcct();
                                            }
                                            if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_TermSource"]) == "T")
                                            {
                                                AmortStartDate = invoice.GetDateInvoiced();
                                            }

                                            if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "M")
                                            {
                                                AmortEndDate = AmortStartDate.Value.AddMonths(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"]));
                                            }
                                            if (Util.GetValueOfString(amrtDS.Tables[0].Rows[0]["VA038_PeriodType"]) == "Y")
                                            {
                                                AmortEndDate = AmortStartDate.Value.AddYears(Util.GetValueOfInt(amrtDS.Tables[0].Rows[0]["VA038_AmortizationPeriod"]));
                                            }
                                            line.Set_Value("FROMDATE", AmortStartDate);
                                            line.Set_Value("EndDate", AmortEndDate);
                                            if (amrtDS != null)
                                            {
                                                amrtDS.Dispose();
                                            }
                                        }
                                    }
                                }

                                if (!line.Save())
                                {
                                    //SI_0708 - message was not upto the mark
                                    ValueNamePair pp = VAdvantage.Logging.VLogger.RetrieveError();
                                    if (pp != null)
                                    {
                                        throw new ArgumentException("Cannot save Invoice Line. " + pp.GetName());
                                    }
                                    throw new ArgumentException("Cannot save Invoice Line");
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            if (count > 0)
            {
                return(invoice.GetDocumentNo());
            }
            else
            {
                //Get_Trx().Rollback();
                throw new ArgumentException(Msg.GetMsg(GetCtx(), "InvoiceExist") + ": " + invDocumentNo.ToString());
            }
        }