Exemplo n.º 1
0
        /// <summary>
        /// Set Source Amounts
        /// </summary>
        /// <param name="C_Currency_ID">currency</param>
        /// <param name="AmtSourceDr">source amount dr</param>
        /// <param name="AmtSourceCr">source amount cr</param>
        /// <returns>true, if any if the amount is not zero</returns>
        public bool SetAmtSource(int C_Currency_ID, Decimal?AmtSourceDr, Decimal?AmtSourceCr)
        {
            SetC_Currency_ID(C_Currency_ID);
            if (AmtSourceDr != null)
            {
                SetAmtSourceDr(AmtSourceDr);
            }
            if (AmtSourceCr != null)
            {
                SetAmtSourceCr(AmtSourceCr);
            }
            //  one needs to be non zero
            if (GetAmtSourceDr().Equals(Env.ZERO) && GetAmtSourceCr().Equals(Env.ZERO))
            {
                return(false);
            }
            //	Currency Precision
            int precision = MCurrency.GetStdPrecision(GetCtx(), C_Currency_ID);

            if (AmtSourceDr != null && Env.Scale(AmtSourceDr.Value) > precision)
            {
                Decimal AmtSourceDr1 = Decimal.Round(AmtSourceDr.Value, precision, MidpointRounding.AwayFromZero);
                log.Warning("Source DR Precision " + AmtSourceDr.Value + " -> " + AmtSourceDr1);
                SetAmtSourceDr(AmtSourceDr1);
            }
            if (AmtSourceCr != null && Env.Scale(AmtSourceCr.Value) > precision)
            {
                Decimal AmtSourceCr1 = Decimal.Round(AmtSourceCr.Value, precision, MidpointRounding.AwayFromZero);
                log.Warning("Source CR Precision " + AmtSourceCr + " -> " + AmtSourceCr1);
                SetAmtSourceCr(AmtSourceCr1);
            }
            return(true);
        }
        public MCurrency Get(int id)
        {
            MCurrency currency = new MCurrency();

            currency = auctionContext.MCurrencies.Where(a => a.CurrencyID == id).FirstOrDefault();
            return(currency);
        }
Exemplo n.º 3
0
        /// <summary>
        /// GetPriceList
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public Dictionary <String, String> GetPriceList(Ctx ctx, string fields)
        {
            if (fields != null)
            {
                string[] paramValue = fields.ToString().Split(',');
                int      M_PriceList_ID;

                //Assign parameter value
                M_PriceList_ID = Util.GetValueOfInt(paramValue[0].ToString());
                //End Assign parameter value

                MPriceList prcLst = new MPriceList(ctx, M_PriceList_ID, null);
                Dictionary <String, String> retDic = new Dictionary <string, string>();
                // Reset Orig Shipment
                MCurrency crncy = new MCurrency(ctx, prcLst.GetC_Currency_ID(), null);
                //retDic["StdPrecision"] = prcLst.GetPricePrecision().ToString();
                //JID_1744  Precision should be as per currency percision
                retDic["StdPrecision"] = crncy.GetStdPrecision().ToString();
                return(retDic);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 4
0
        public void Economy_RemoveCurrencyNotExisting()
        {
            var       name     = MUtils.GetRandomString();
            ICurrency currency = new MCurrency(name);

            Assert.Throws <InvalidOperationException>(() => MEconomy.Instance.RemoveCurrency(currency));
        }
Exemplo n.º 5
0
        public void Currency_TrySpendReturnsFalse()
        {
            var       name     = MUtils.GetRandomString();
            ICurrency currency = new MCurrency(name);

            Assert.That(currency.TrySpend(1000) == false);
        }
Exemplo n.º 6
0
        public void Currency_AddNegative()
        {
            var       name     = MUtils.GetRandomString();
            ICurrency currency = new MCurrency(name);

            Assert.Throws <ArgumentException>(() => currency.Add(-1000));
            Assert.That(currency.Value == 0);
        }
Exemplo n.º 7
0
 /// <summary>
 /// Get Currency Percision
 /// </summary>
 /// <returns>precision</returns>
 private int GetStdPercision()
 {
     if (_precision == -1)
     {
         _precision = MCurrency.GetStdPrecision(GetCtx(), GetC_Currency_ID());
     }
     return(_precision);
 }
Exemplo n.º 8
0
        public void Currency_TrySpendResultsInZero()
        {
            var       name     = MUtils.GetRandomString();
            ICurrency currency = new MCurrency(name);

            currency.TrySpend(1000);

            Assert.That(currency.Value == 0);
        }
Exemplo n.º 9
0
        public void Economy_AddCurrency()
        {
            var       name     = MUtils.GetRandomString();
            ICurrency currency = new MCurrency(name);

            MEconomy.Instance.AddCurrency(currency);

            Assert.That(MEconomy.Instance[name].Name.Equals(name));
        }
Exemplo n.º 10
0
        public void Economy_AddCurrencyAlreadyExistingNonIdentical()
        {
            var       name      = MUtils.GetRandomString();
            ICurrency currency  = new MCurrency(name);
            ICurrency currency2 = new MCurrency(name);

            MEconomy.Instance.AddCurrency(currency);
            Assert.Throws <InvalidOperationException>(() => MEconomy.Instance.AddCurrency(currency2));
        }
Exemplo n.º 11
0
        public void Currency_AddValueCorrect()
        {
            var       name     = MUtils.GetRandomString();
            ICurrency currency = new MCurrency(name);

            currency.Add(1000);

            Assert.That(currency.Value == 1000);
        }
 public MCurrency AddMCurrency(MCurrency mcurrency)
 {
     if (mcurrency != null)
     {
         dbContext.MCurrencys.Add(mcurrency);
         dbContext.SaveChanges();
         return(mcurrency);
     }
     return(null);
 }
Exemplo n.º 13
0
        public void CurrencyEvent_CurrencyAdded()
        {
            var       name     = MUtils.GetRandomString();
            ICurrency currency = new MCurrency(name);

            MEvents.Add(new MEvents.EventDelegate <CurrencyAddedEvent>(e => Debug.Log(e.Currency.Name)));

            currency.Add(5);

            LogAssert.Expect(LogType.Log, name);
        }
Exemplo n.º 14
0
        public void CurrencyEvent_CurrencyInsufficient()
        {
            var       name     = MUtils.GetRandomString();
            ICurrency currency = new MCurrency(name);

            MEvents.Add(new MEvents.EventDelegate <CurrencyInsufficientEvent>((e => { Debug.Log(e.AmountAttempted); })));

            currency.Add(5);
            currency.TrySpend(7);

            LogAssert.Expect(LogType.Log, "7");
        }
Exemplo n.º 15
0
        private MCurrency ParserAddCurrency(Currency currency)
        {
            MCurrency mCurrency = new MCurrency();

            if (currency != null)
            {
                mCurrency.CurrencyID           = currency.CurrencyID;
                mCurrency.strCurrencyName      = currency.strCurrencyName ?? " ";
                mCurrency.strCurrencyShortName = currency.strCurrencyShortName ?? " ";
            }
            return(mCurrency);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Get Currency Detail
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public Dictionary <string, string> GetCurrency(Ctx ctx, string fields)
        {
            string[] paramValue = fields.Split(',');
            //Assign parameter value
            int C_Currency_ID = Util.GetValueOfInt(paramValue[0].ToString());
            //End Assign parameter
            MCurrency currency = MCurrency.Get(ctx, C_Currency_ID);
            Dictionary <string, string> result = new Dictionary <string, string>();

            result["StdPrecision"] = currency.GetStdPrecision().ToString();
            return(result);
        }
Exemplo n.º 17
0
        public void Economy_RemoveCurrency()
        {
            var       name     = MUtils.GetRandomString();
            ICurrency currency = new MCurrency(name);

            MEconomy.Instance.AddCurrency(currency);

            MEconomy.Instance.RemoveCurrency(currency);

            Assert.Throws <KeyNotFoundException>(() =>
            {
                var curr = MEconomy.Instance[name];
            });
        }
Exemplo n.º 18
0
        public MVA009OrderPaySchedule(MOrder order, MPaySchedule paySchedule)
            : base(order.GetCtx(), 0, order.Get_TrxName())
        {
            _parent = order;
            SetClientOrg(order);
            SetC_Order_ID(order.GetC_Order_ID());
            SetC_PaySchedule_ID(paySchedule.GetC_PaySchedule_ID());

            //	Amounts
            int     scale = MCurrency.GetStdPrecision(GetCtx(), order.GetC_Currency_ID());
            Decimal due   = order.GetGrandTotal();

            if (due.CompareTo(Env.ZERO) == 0)
            {
                SetDueAmt(Env.ZERO);
                SetDiscountAmt(Env.ZERO);
                //SetIsValid(false);
            }
            else
            {
                //due = due.multiply(paySchedule.getPercentage()).divide(HUNDRED, scale, Decimal.ROUND_HALF_UP);
                due = Decimal.Multiply(due, Decimal.Divide(paySchedule.GetPercentage(),
                                                           Decimal.Round(HUNDRED, scale, MidpointRounding.AwayFromZero)));
                SetDueAmt(due);
                Decimal discount = Decimal.Multiply(due, Decimal.Divide(paySchedule.GetDiscount(),
                                                                        Decimal.Round(HUNDRED, scale, MidpointRounding.AwayFromZero)));
                SetDiscountAmt(discount);
                //SetIsValid(true);
            }

            //	Dates
            DateTime dueDate = TimeUtil.AddDays(order.GetDateOrdered(), paySchedule.GetNetDays());

            SetDueDate(dueDate);
            DateTime discountDate = TimeUtil.AddDays(order.GetDateOrdered(), paySchedule.GetDiscountDays());

            SetDiscountDate(discountDate);
        }
        public bool SaveEdit(MCurrency currency)
        {
            bool status = false;

            if (currency.CurrencyID > 0)
            {
                //Edit Existing Record
                var cur = auctionContext.MCurrencies.Where(a => a.CurrencyID == currency.CurrencyID).FirstOrDefault();
                if (cur != null)
                {
                    cur.strCurrencyName      = currency.strCurrencyName;
                    cur.strCurrencyShortName = currency.strCurrencyShortName;
                }
            }
            else
            {
                //Save
                auctionContext.MCurrencies.Add(currency);
            }
            auctionContext.SaveChanges();
            status = true;
            return(status);
        }
 public MCurrency UpdateMCurrency(MCurrency mcurrency)
 {
     dbContext.Entry(mcurrency).State = EntityState.Modified;
     dbContext.SaveChanges();
     return(mcurrency);
 }
Exemplo n.º 21
0
        /// <summary>
        /// Perform Process
        /// </summary>
        /// <returns>Message (text with variables)</returns>
        protected override String DoIt()
        {
            log.Info("C_Commission_ID=" + GetRecord_ID() + ", StartDate=" + p_StartDate);
            if (p_StartDate == null)
            {
                p_StartDate = DateTime.Now;
            }
            m_com = new MCommission(GetCtx(), GetRecord_ID(), Get_Trx());
            if (m_com.Get_ID() == 0)
            {
                throw new Exception("No Commission");
            }

            //	Create Commission
            MCommissionRun comRun = new MCommissionRun(m_com);

            SetStartEndDate();
            comRun.SetStartDate(p_StartDate);
            System.Threading.Thread.CurrentThread.CurrentCulture   = Utility.Env.GetLanguage(GetCtx()).GetCulture(Utility.Env.GetLoginLanguage(GetCtx()).GetAD_Language());
            System.Threading.Thread.CurrentThread.CurrentUICulture = Utility.Env.GetLanguage(GetCtx()).GetCulture(Utility.Env.GetLoginLanguage(GetCtx()).GetAD_Language());
            //	01-Jan-2000 - 31-Jan-2001 - USD
            Classes.SimpleDateFormat format = Classes.DisplayType.GetDateFormat(Classes.DisplayType.Date);
            String description = format.Format(p_StartDate)
                                 + " - " + format.Format(m_EndDate)
                                 + " - " + MCurrency.GetISO_Code(GetCtx(), m_com.GetC_Currency_ID());

            //string description = p_StartDate
            //    + " - " + m_EndDate
            //    + " - " + MCurrency.GetISO_Code(GetCtx(), m_com.GetC_Currency_ID());

            comRun.SetDescription(description);
            System.Threading.Thread.CurrentThread.CurrentCulture   = Utility.Env.GetLanguage(GetCtx()).GetCulture(Utility.Env.GetBaseAD_Language());
            System.Threading.Thread.CurrentThread.CurrentUICulture = Utility.Env.GetLanguage(GetCtx()).GetCulture(Utility.Env.GetBaseAD_Language());

            if (!comRun.Save())
            {
                throw new Exception("Could not save Commission Run please check Organization");
            }

            MCommissionLine[] lines = m_com.GetLines();
            for (int i = 0; i < lines.Length; i++)
            {
                #region
                #endregion
                //	Amt for Line - Updated By Trigger
                MCommissionAmt comAmt = new MCommissionAmt(comRun, lines[i].GetC_CommissionLine_ID());
                if (!comAmt.Save())
                {
                    throw new SystemException("Could not save Commission Amt");
                }
                //
                StringBuilder sql = new StringBuilder();
                if (MCommission.DOCBASISTYPE_Receipt.Equals(m_com.GetDocBasisType()))
                {
                    if (m_com.IsListDetails())
                    {
                        sql.Append("SELECT h.C_Currency_ID, (l.LineNetAmt*al.Amount/h.GrandTotal) AS Amt,"
                                   + " (l.QtyInvoiced*al.Amount/h.GrandTotal) AS Qty,"
                                   + " NULL, l.C_InvoiceLine_ID, p.DocumentNo||'_'||h.DocumentNo,"
                                   + " COALESCE(prd.Value,l.Description), h.DateInvoiced "
                                   + "FROM C_Payment p"
                                   + " INNER JOIN C_AllocationLine al ON (p.C_Payment_ID=al.C_Payment_ID)"
                                   + " INNER JOIN C_Invoice h ON (al.C_Invoice_ID = h.C_Invoice_ID)"
                                   + " INNER JOIN C_InvoiceLine l ON (h.C_Invoice_ID = l.C_Invoice_ID) "
                                   + " LEFT OUTER JOIN M_Product prd ON (l.M_Product_ID = prd.M_Product_ID) "
                                   + "WHERE p.DocStatus IN ('CL','CO','RE')"
                                   + " AND h.IsSOTrx='Y'"
                                   + " AND p.AD_Client_ID = @clientid"
                                   + " AND l.IsCommissionCalculated = 'N' "
                                   + " AND p.DateTrx BETWEEN @sdate AND @edate");
                    }
                    else
                    {
                        sql.Append("SELECT h.C_Currency_ID, SUM(l.LineNetAmt*al.Amount/h.GrandTotal) AS Amt,"
                                   + " SUM(l.QtyInvoiced*al.Amount/h.GrandTotal) AS Qty,"
                                   + " NULL, NULL, NULL, NULL, MAX(h.DateInvoiced) "
                                   + "FROM C_Payment p"
                                   + " INNER JOIN C_AllocationLine al ON (p.C_Payment_ID=al.C_Payment_ID)"
                                   + " INNER JOIN C_Invoice h ON (al.C_Invoice_ID = h.C_Invoice_ID)"
                                   + " INNER JOIN C_InvoiceLine l ON (h.C_Invoice_ID = l.C_Invoice_ID) "
                                   + "WHERE p.DocStatus IN ('CL','CO','RE')"
                                   + " AND h.IsSOTrx='Y'"
                                   + " AND p.AD_Client_ID = @clientid"
                                   + " AND l.IsCommissionCalculated = 'N' "
                                   + " AND p.DateTrx BETWEEN @sdate AND @edate");
                    }
                }
                else if (MCommission.DOCBASISTYPE_Order.Equals(m_com.GetDocBasisType()))
                {
                    if (m_com.IsListDetails())
                    {
                        sql.Append("SELECT h.C_Currency_ID, l.LineNetAmt, l.QtyOrdered, "
                                   + "l.C_OrderLine_ID, NULL, h.DocumentNo,"
                                   + " COALESCE(prd.Value,l.Description),h.DateOrdered "
                                   + "FROM C_Order h"
                                   + " INNER JOIN C_OrderLine l ON (h.C_Order_ID = l.C_Order_ID)"
                                   + " LEFT OUTER JOIN M_Product prd ON (l.M_Product_ID = prd.M_Product_ID) "
                                   + "WHERE h.DocStatus IN ('CL','CO')"
                                   + " AND h.IsSOTrx='Y'"
                                   + " AND h.AD_Client_ID = @clientid"
                                   + " AND l.IsCommissionCalculated = 'N' "
                                   + " AND h.DateOrdered BETWEEN @sdate AND @edate");
                    }
                    else
                    {
                        sql.Append("SELECT h.C_Currency_ID, SUM(l.LineNetAmt) AS Amt,"
                                   + " SUM(l.QtyOrdered) AS Qty, "
                                   + "NULL, NULL, NULL, NULL, MAX(h.DateOrdered) "
                                   + "FROM C_Order h"
                                   + " INNER JOIN C_OrderLine l ON (h.C_Order_ID = l.C_Order_ID) "
                                   + "WHERE h.DocStatus IN ('CL','CO')"
                                   + " AND h.IsSOTrx='Y'"
                                   + " AND l.IsCommissionCalculated = 'N' "
                                   + " AND h.AD_Client_ID = @clientid"
                                   + " AND h.DateOrdered BETWEEN @sdate AND @edate");
                    }
                }
                else    //	Invoice Basis
                {
                    if (m_com.IsListDetails())
                    {
                        sql.Append("SELECT h.C_Currency_ID, l.LineNetAmt, l.QtyInvoiced, "
                                   + "NULL, l.C_InvoiceLine_ID, h.DocumentNo,"
                                   + " COALESCE(prd.Value,l.Description),h.DateInvoiced "
                                   + "FROM C_Invoice h"
                                   + " INNER JOIN C_InvoiceLine l ON (h.C_Invoice_ID = l.C_Invoice_ID)"
                                   + " LEFT OUTER JOIN M_Product prd ON (l.M_Product_ID = prd.M_Product_ID) "
                                   + "WHERE h.DocStatus IN ('CL','CO','RE')"
                                   + " AND h.IsSOTrx='Y'"
                                   + " AND l.IsCommissionCalculated = 'N' "
                                   + " AND h.AD_Client_ID = @clientid"
                                   + " AND h.DateInvoiced BETWEEN @sdate AND @edate");
                    }
                    else
                    {
                        sql.Append("SELECT h.C_Currency_ID, SUM(l.LineNetAmt) AS Amt,"
                                   + " SUM(l.QtyInvoiced) AS Qty, "
                                   + "NULL, NULL, NULL, NULL, MAX(h.DateInvoiced) "
                                   + "FROM C_Invoice h"
                                   + " INNER JOIN C_InvoiceLine l ON (h.C_Invoice_ID = l.C_Invoice_ID) "
                                   + "WHERE h.DocStatus IN ('CL','CO','RE')"
                                   + " AND h.IsSOTrx='Y'"
                                   + " AND l.IsCommissionCalculated = 'N' "
                                   + " AND h.AD_Client_ID = @clientid"
                                   + " AND h.DateInvoiced BETWEEN @sdate AND @edate");
                    }
                }
                //	CommissionOrders/Invoices
                if (lines[i].IsCommissionOrders())
                {
                    MUser[] users = MUser.GetOfBPartner(GetCtx(), m_com.GetC_BPartner_ID());
                    if (users == null || users.Length == 0)
                    {
                        throw new Exception("Commission Business Partner has no Users/Contact");
                    }
                    if (users.Length == 1)
                    {
                        int SalesRep_ID = users[0].GetAD_User_ID();
                        sql.Append(" AND h.SalesRep_ID=").Append(SalesRep_ID);
                    }
                    else
                    {
                        log.Warning("Not 1 User/Contact for C_BPartner_ID="
                                    + m_com.GetC_BPartner_ID() + " but " + users.Length);
                        sql.Append(" AND h.SalesRep_ID IN (SELECT AD_User_ID FROM AD_User WHERE C_BPartner_ID=")
                        .Append(m_com.GetC_BPartner_ID()).Append(")");
                    }
                }
                //added by Arpit Rai on 7-May-2016 asked & Tested by Ravikant Sir
                //To calculate Commission Amount For the Particular Agent If Not Selected in Line Tab Of Commission
                else
                {
                    MUser[] users = MUser.GetOfBPartner(GetCtx(), m_com.GetC_BPartner_ID());
                    if (users == null || users.Length == 0)
                    {
                        throw new Exception("Commission Business Partner has no Users/Contact");
                    }
                    if (users.Length == 1)
                    {
                        int SaleRepID = users[0].GetAD_User_ID();
                        sql.Append(" AND h.SalesRep_ID = ");
                        sql.Append(SaleRepID);
                    }
                    else
                    {
                        log.Warning("Not 1 User/Contact for C_BPartner_ID="
                                    + m_com.GetC_BPartner_ID() + " but " + users.Length);
                        sql.Append(" AND h.SalesRep_ID IN (SELECT AD_User_ID FROM AD_User WHERE C_BPartner_ID=")
                        .Append(m_com.GetC_BPartner_ID()).Append(")");
                    }
                }

                //	Organization
                if (lines[i].GetOrg_ID() != 0)
                {
                    sql.Append(" AND h.AD_Org_ID=").Append(lines[i].GetOrg_ID());
                }
                //	BPartner
                if (lines[i].GetC_BPartner_ID() != 0)
                {
                    sql.Append(" AND h.C_BPartner_ID=").Append(lines[i].GetC_BPartner_ID());
                }
                //	BPartner Group
                if (lines[i].GetC_BP_Group_ID() != 0)
                {
                    sql.Append(" AND h.C_BPartner_ID IN "
                               + "(SELECT C_BPartner_ID FROM C_BPartner WHERE C_BP_Group_ID=").Append(lines[i].GetC_BP_Group_ID()).Append(")");
                }
                //	Sales Region
                if (lines[i].GetC_SalesRegion_ID() != 0)
                {
                    sql.Append(" AND h.C_BPartner_Location_ID IN "
                               + "(SELECT C_BPartner_Location_ID FROM C_BPartner_Location WHERE C_SalesRegion_ID=").Append(lines[i].GetC_SalesRegion_ID()).Append(")");
                }
                //	Product
                if (lines[i].GetM_Product_ID() != 0)
                {
                    sql.Append(" AND l.M_Product_ID=").Append(lines[i].GetM_Product_ID());
                }
                //	Product Category
                if (lines[i].GetM_Product_Category_ID() != 0)
                {
                    sql.Append(" AND l.M_Product_ID IN "
                               + "(SELECT M_Product_ID FROM M_Product WHERE M_Product_Category_ID=").Append(lines[i].GetM_Product_Category_ID()).Append(")");
                }
                //	Grouping
                if (!m_com.IsListDetails())
                {
                    sql.Append(" GROUP BY h.C_Currency_ID");
                }
                //
                log.Fine("Line=" + lines[i].GetLine() + " - " + sql);
                //
                CreateDetail(sql.ToString(), comAmt);
                //comAmt.CalculateCommission();
                comAmt.CalculatecommissionwithNewLogic();
                comAmt.Save();

                int countDetails = Util.GetValueOfInt(DataBase.DB.ExecuteScalar("SELECT COUNT(*) FROM C_CommissionDetail WHERE C_CommissionAmt_ID=" + comAmt.GetC_CommissionAmt_ID(), null, Get_TrxName()));
                if (countDetails == 0)
                {
                    comAmt.Delete(true, Get_Trx());
                }
            }   //	for all commission lines

            //	comRun.updateFromAmt();
            //	comRun.save();

            //	Save Last Run
            m_com.SetDateLastRun(p_StartDate);
            m_com.Save();

            return("@C_CommissionRun_ID@ = " + comRun.GetDocumentNo()
                   + " - " + comRun.GetDescription());
        }
Exemplo n.º 22
0
 public MCurrency UpdateMCurrency(MCurrency mcurrency)
 {
     return(mcurrencyService.UpdateMCurrency(mcurrency));
 }
Exemplo n.º 23
0
 public MCurrency AddMCurrency(MCurrency mcurrency)
 {
     return(mcurrencyService.AddMCurrency(mcurrency));
 }
        /**
         *  Before Save
         *	@param newRecord new
         *	@return true
         */
        protected override bool BeforeSave(bool newRecord)
        {
            if (Is_ValueChanged("DueAmt"))
            {
                log.Fine("beforeSave");
                SetIsValid(false);
            }
            oldDueAmt = Util.GetValueOfDecimal(Get_ValueOld("DueAmt"));

            if (Env.IsModuleInstalled("VA009_"))
            {
                // get invoice currency for rounding
                MCurrency currency = MCurrency.Get(GetCtx(), GetC_Currency_ID());
                SetDueAmt(Decimal.Round(GetDueAmt(), currency.GetStdPrecision()));
                SetVA009_PaidAmntInvce(Decimal.Round(GetVA009_PaidAmntInvce(), currency.GetStdPrecision()));
                // when invoice schedule have payment reference then need to check payment mode on payment window & update here
                if (GetC_Payment_ID() > 0)
                {
                    #region for payment
                    MPayment payment = new MPayment(GetCtx(), GetC_Payment_ID(), Get_Trx());
                    SetVA009_PaymentMethod_ID(payment.GetVA009_PaymentMethod_ID());

                    // get payment method detail -- update to here
                    DataSet dsPaymentMethod = DB.ExecuteDataset(@"SELECT VA009_PaymentMode, VA009_PaymentType, VA009_PaymentTrigger FROM VA009_PaymentMethod
                                          WHERE VA009_PaymentMethod_ID = " + payment.GetVA009_PaymentMethod_ID(), null, Get_Trx());
                    if (dsPaymentMethod != null && dsPaymentMethod.Tables.Count > 0 && dsPaymentMethod.Tables[0].Rows.Count > 0)
                    {
                        if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"])))
                        {
                            SetVA009_PaymentMode(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"]));
                        }
                        if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"])))
                        {
                            SetVA009_PaymentType(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"]));
                        }
                        SetVA009_PaymentTrigger(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentTrigger"]));
                    }
                    #endregion
                }
                else if (GetC_CashLine_ID() > 0)
                {
                    #region For Cash
                    // when invoice schedule have cashline reference then need to check
                    // payment mode of "Cash" type having currency is null on "Payment Method" window & update here
                    DataSet dsPaymentMethod = (DB.ExecuteDataset(@"SELECT VA009_PaymentMethod_ID, VA009_PaymentMode, VA009_PaymentType, VA009_PaymentTrigger 
                                       FROM VA009_PaymentMethod WHERE IsActive = 'Y' 
                                       AND AD_Client_ID = " + GetAD_Client_ID() + @" AND VA009_PaymentBaseType = 'B' AND NVL(C_Currency_ID , 0) = 0", null, Get_Trx()));
                    if (dsPaymentMethod != null && dsPaymentMethod.Tables.Count > 0 && dsPaymentMethod.Tables[0].Rows.Count > 0)
                    {
                        SetVA009_PaymentMethod_ID(Util.GetValueOfInt(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMethod_ID"]));
                        if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"])))
                        {
                            SetVA009_PaymentMode(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentMode"]));
                        }
                        if (!String.IsNullOrEmpty(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"])))
                        {
                            SetVA009_PaymentType(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentType"]));
                        }
                        SetVA009_PaymentTrigger(Util.GetValueOfString(dsPaymentMethod.Tables[0].Rows[0]["VA009_PaymentTrigger"]));
                    }
                    else
                    {
                        #region when we not found record of "Cash" then we will create a new rcord on Payment Method for Cash
                        string sql     = @"SELECT AD_TABLE_ID  FROM AD_TABLE WHERE tablename LIKE 'VA009_PaymentMethod' AND IsActive = 'Y'";
                        int    tableId = Util.GetValueOfInt(DB.ExecuteScalar(sql, null, null));
                        MTable tbl     = new MTable(GetCtx(), tableId, Get_Trx());
                        PO     po      = tbl.GetPO(GetCtx(), 0, Get_Trx());
                        po.SetAD_Client_ID(GetAD_Client_ID());
                        po.SetAD_Org_ID(0); // Recod will be created in (*) Organization
                        po.Set_Value("Value", "By Cash");
                        po.Set_Value("VA009_Name", "By Cash");
                        po.Set_Value("IsActive", true);
                        po.Set_Value("VA009_PaymentBaseType", "B");
                        po.Set_Value("VA009_PaymentRule", "M");
                        po.Set_Value("VA009_PaymentMode", "C");
                        po.Set_Value("VA009_PaymentType", "S");
                        po.Set_Value("VA009_PaymentTrigger", "S");
                        po.Set_Value("C_Currency_ID", null);
                        po.Set_Value("VA009_InitiatePay", false);
                        if (!po.Save(Get_Trx()))
                        {
                            ValueNamePair pp = VLogger.RetrieveError();
                            log.Info("Error Occured when try to save record on Payment Method for Cash. Error Type : " + pp.GetValue());
                        }
                        else
                        {
                            SetVA009_PaymentMethod_ID(Util.GetValueOfInt(po.Get_Value("VA009_PaymentMethod_ID")));
                            SetVA009_PaymentMode("C");
                            SetVA009_PaymentType("S");
                            SetVA009_PaymentTrigger("S");
                        }
                        #endregion
                    }
                    #endregion
                }
            }

            return(true);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Get Commitments
        /// </summary>
        /// <param name="doc">document</param>
        /// <param name="maxQty">Qty invoiced/matched</param>
        /// <param name="C_InvoiceLine_ID">invoice line</param>
        /// <returns>commitments (order lines)</returns>
        protected static DocLine[] GetCommitments(Doc doc, Decimal maxQty, int C_InvoiceLine_ID)
        {
            int precision = -1;
            //
            List <DocLine> list = new List <DocLine>();
            String         sql  = "SELECT * FROM C_OrderLine ol "
                                  + "WHERE EXISTS "
                                  + "(SELECT * FROM C_InvoiceLine il "
                                  + "WHERE il.C_OrderLine_ID=ol.C_OrderLine_ID"
                                  + " AND il.C_InvoiceLine_ID=" + C_InvoiceLine_ID + ")"
                                  + " OR EXISTS "
                                  + "(SELECT * FROM M_MatchPO po "
                                  + "WHERE po.C_OrderLine_ID=ol.C_OrderLine_ID"
                                  + " AND po.C_InvoiceLine_ID=" + C_InvoiceLine_ID + ")";
            IDataReader idr = null;

            try
            {
                idr = DataBase.DB.ExecuteReader(sql, null, null);
                while (idr.Read())
                {
                    if (Env.Signum(maxQty) == 0)
                    {
                        continue;
                    }
                    MOrderLine line    = new MOrderLine(doc.GetCtx(), idr, null);
                    DocLine    docLine = new DocLine(line, doc);
                    //	Currency
                    if (precision == -1)
                    {
                        doc.SetC_Currency_ID(docLine.GetC_Currency_ID());
                        precision = MCurrency.GetStdPrecision(doc.GetCtx(), docLine.GetC_Currency_ID());
                    }
                    //	Qty
                    Decimal Qty = Math.Max(line.GetQtyOrdered(), maxQty);
                    docLine.SetQty(Qty, false);
                    //
                    Decimal PriceActual = line.GetPriceActual();
                    Decimal PriceCost   = line.GetPriceCost();
                    Decimal?LineNetAmt  = null;
                    if (Env.Signum(PriceCost) != 0)
                    {
                        LineNetAmt = Decimal.Multiply(Qty, PriceCost);
                    }
                    else if (Qty.Equals(maxQty))
                    {
                        LineNetAmt = line.GetLineNetAmt();
                    }
                    else
                    {
                        LineNetAmt = Decimal.Multiply(Qty, PriceActual);
                    }
                    maxQty = Decimal.Subtract(maxQty, Qty);

                    docLine.SetAmount(LineNetAmt);      //	DR
                    Decimal PriceList = line.GetPriceList();
                    int     C_Tax_ID  = docLine.GetC_Tax_ID();
                    //	Correct included Tax
                    if (C_Tax_ID != 0 && line.GetParent().IsTaxIncluded())
                    {
                        MTax tax = MTax.Get(doc.GetCtx(), C_Tax_ID);
                        if (!tax.IsZeroTax())
                        {
                            Decimal LineNetAmtTax = tax.CalculateTax(LineNetAmt.Value, true, precision);
                            _log.Fine("LineNetAmt=" + LineNetAmt + " - Tax=" + LineNetAmtTax);
                            LineNetAmt = Decimal.Subtract(LineNetAmt.Value, LineNetAmtTax);
                            Decimal PriceListTax = tax.CalculateTax(PriceList, true, precision);
                            PriceList = Decimal.Subtract(PriceList, PriceListTax);
                        }
                    }   //	correct included Tax

                    docLine.SetAmount(LineNetAmt, PriceList, Qty);
                    list.Add(docLine);
                }
                idr.Close();
            }
            catch (Exception e)
            {
                if (idr != null)
                {
                    idr.Close();
                    idr = null;
                }
                _log.Log(Level.SEVERE, sql, e);
            }


            //	Return Array
            DocLine[] dl = new DocLine[list.Count];
            dl = list.ToArray();
            return(dl);
        }
        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"));
            }
        }
Exemplo n.º 27
0
        public NDbResult SaveMCurrencies([FromBody] List <MCurrency> values)
        {
            var results = MCurrency.SaveMCurrencies(values);

            return(results);
        }
Exemplo n.º 28
0
        public NDbResult <List <MCurrency> > GetCurrencies()
        {
            var results = MCurrency.GetCurrencies();

            return(results);
        }
        protected override string DoIt()
        {
            StringBuilder          _sql       = new StringBuilder();
            MVA009Batch            batch      = new MVA009Batch(GetCtx(), GetRecord_ID(), Get_TrxName());
            MVA009PaymentMethod    _paymthd   = null;
            MVA009BatchLineDetails lineDetail = null;
            MVA009BatchLines       line       = null;

            //if (batch.GetVA009_GenerateLines()=="Y")
            //{
            //    msg = Msg.GetMsg(GetCtx(), "VA009_BatchLineAlreadyCreated");
            //    return msg;
            //}
            msg = DeleteBatchLines(_sql, batch.GetVA009_Batch_ID(), GetCtx(), Get_TrxName());
            if (!String.IsNullOrEmpty(msg))
            {
                return(msg);
            }
            MBankAccount _bankacc = new MBankAccount(GetCtx(), batch.GetC_BankAccount_ID(), Get_TrxName());

            decimal dueamt = 0;

            _sql.Clear();
            _sql.Append(@"Select cp.ad_client_id, cp.ad_org_id,CI.C_Bpartner_ID, ci.c_invoice_id, cp.c_invoicepayschedule_id, cp.duedate, 
                          cp.dueamt, cp.discountdate, cp.discountamt,cp.va009_paymentmethod_id,ci.c_currency_id , doc.DocBaseType
                          From C_Invoice CI inner join C_InvoicePaySchedule CP ON CI.c_invoice_id= CP.c_invoice_id INNER JOIN 
                          C_DocType doc ON doc.C_DocType_ID = CI.C_DocType_ID Where ci.ispaid='N' AND cp.va009_ispaid='N' AND cp.C_Payment_ID IS NULL AND
                          CI.IsActive = 'Y' and ci.docstatus in ('CO','CL') AND cp.VA009_ExecutionStatus !='Y' AND CI.AD_Client_ID = " + batch.GetAD_Client_ID()
                        + " AND CI.AD_Org_ID = " + batch.GetAD_Org_ID());

            if (_C_BPartner_ID > 0)
            {
                _sql.Append("  and CI.C_Bpartner_ID=" + _C_BPartner_ID);
            }
            if (_C_invoice_ID > 0)
            {
                _sql.Append("  and CI.C_invoice_ID=" + _C_invoice_ID);
            }
            if (_paySchedule_ID > 0)
            {
                _sql.Append(" AND CP.C_InvoicePaySchedule_ID=" + _paySchedule_ID);
            }
            if (_docType > 0)
            {
                _sql.Append(" ANd CI.C_DocType_ID=" + _docType);
            }
            else
            {
                _sql.Append(" ANd doc.DocBaseType IN ('API' , 'ARI' , 'APC' , 'ARC') ");
            }
            if (_paymentMethod > 0)
            {
                _sql.Append(" And CP.VA009_PaymentMethod_ID=" + _paymentMethod);
                _paymthd = new MVA009PaymentMethod(GetCtx(), _paymentMethod, Get_TrxName());
                _trigger = _paymthd.IsVA009_IsMandate();
            }

            if (_DateDoc_From != null && _DateDoc_To != null)
            {
                _sql.Append(" and cp.duedate BETWEEN  ");
                _sql.Append(GlobalVariable.TO_DATE(_DateDoc_From, true) + " AND ");
                _sql.Append(GlobalVariable.TO_DATE(_DateDoc_To, true));
            }
            else if (_DateDoc_From != null && _DateDoc_To == null)
            {
                _sql.Append(" and cp.duedate >=" + GlobalVariable.TO_DATE(_DateDoc_From, true));
            }
            else if (_DateDoc_From == null && _DateDoc_To != null)
            {
                _sql.Append(" and cp.duedate <=" + GlobalVariable.TO_DATE(_DateDoc_To, true));
            }
            //else if (C_ConversionType_ID > 0) //commented the conversion type because while creatring invoice against Base currency, system will set currencyconversionType_ID=0
            //{
            //    _sql.Append("  AND C_ConversionType_ID=" + C_ConversionType_ID);
            //}
            if (VA009_IsSameCurrency == true)
            {
                _sql.Append(" AND CI.C_Currency_ID =" + _bankacc.GetC_Currency_ID());
            }

            _sql.Append(" Order by CI.C_Bpartner_ID asc , doc.docbasetype ");

            DataSet ds = new DataSet();

            ds = DB.ExecuteDataset(_sql.ToString());
            if (ds.Tables != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                if (C_ConversionType_ID == 0) //to Set Default conversion Type
                {
                    C_ConversionType_ID = GetDefaultConversionType(_sql);
                }
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if ((Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["DueAmt"])) == 0)
                    {
                        continue;
                    }
                    // if invoice is of AP Invoice and AP Credit Memo then make a single Batch line
                    if (docBaseType == "API" || docBaseType == "APC")
                    {
                        if (_BPartner == Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_BPartner_ID"]) &&
                            ("API" == Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"]) || "APC" == Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"])))
                        {
                            line = new MVA009BatchLines(GetCtx(), _VA009_BatchLine_ID, Get_TrxName());
                        }
                        else
                        {
                            line = null;
                        }
                    }
                    // if invoice is of AR Invoice and AR Credit Memo then make a single Batch line
                    else if (docBaseType == "ARI" || docBaseType == "ARC")
                    {
                        if (_BPartner == Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_BPartner_ID"]) &&
                            ("ARI" == Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"]) || "ARC" == Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"])))
                        {
                            line = new MVA009BatchLines(GetCtx(), _VA009_BatchLine_ID, Get_TrxName());
                        }
                        else
                        {
                            line = null;
                        }
                    }
                    //if (_BPartner == Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_BPartner_ID"]) && docBaseType == Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"]))
                    //{
                    //    line = new MVA009BatchLines(GetCtx(), _VA009_BatchLine_ID, null);
                    //}
                    // else
                    if (line == null)
                    {
                        line = new MVA009BatchLines(GetCtx(), 0, Get_TrxName());
                        line.SetAD_Client_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["Ad_Client_ID"]));
                        line.SetAD_Org_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["Ad_Org_ID"]));
                        line.SetVA009_Batch_ID(batch.GetVA009_Batch_ID());

                        _BPartner   = Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_BPartner_ID"]);
                        docBaseType = Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"]);

                        line.SetC_BPartner_ID(_BPartner);
                        if (_trigger == true)
                        {
                            _sql.Clear();
                            _sql.Append("Select VA009_BPMandate_id from C_BPartner Where C_BPartner_ID=" + _BPartner + " AND IsActive = 'Y' AND AD_Client_ID = " + GetAD_Client_ID());
                            DataSet ds1 = new DataSet();
                            ds1 = DB.ExecuteDataset(_sql.ToString());
                            if (ds1.Tables != null && ds1.Tables.Count > 0 && ds1.Tables[0].Rows.Count > 0)
                            {
                                line.SetVA009_BPMandate_ID(Util.GetValueOfInt(ds1.Tables[0].Rows[0]["VA009_BPMandate_id"]));
                            }
                        }
                        if (line.Save(Get_TrxName()))
                        {
                            //line.SetProcessed(true);
                            line.Save(Get_TrxName());
                            _VA009_BatchLine_ID = line.GetVA009_BatchLines_ID();
                        }
                        else
                        {
                            Get_TrxName().Rollback();
                            _BPartner           = 0;
                            _VA009_BatchLine_ID = 0;
                        }
                    }
                    lineDetail = new MVA009BatchLineDetails(GetCtx(), 0, Get_TrxName());
                    lineDetail.SetAD_Client_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["Ad_Client_ID"]));
                    lineDetail.SetAD_Org_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["Ad_Org_ID"]));
                    lineDetail.SetVA009_BatchLines_ID(line.GetVA009_BatchLines_ID());
                    lineDetail.SetC_Invoice_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_Invoice_ID"]));
                    lineDetail.SetC_InvoicePaySchedule_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_InvoicePaySchedule_id"]));
                    lineDetail.SetDueDate(Util.GetValueOfDateTime(ds.Tables[0].Rows[i]["DueDate"]));
                    lineDetail.SetC_ConversionType_ID(C_ConversionType_ID);
                    dueamt = (Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["DueAmt"]));
                    Decimal DiscountAmt = Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["DiscountAmt"]);

                    bool issamme = true; decimal comvertedamt = 0;
                    if (Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_currency_id"]) == _bankacc.GetC_Currency_ID())
                    {
                        issamme = true;
                    }
                    else
                    {
                        issamme = false;
                    }
                    if (!issamme)
                    {
                        dueamt = MConversionRate.Convert(GetCtx(), dueamt, Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_currency_id"]), _bankacc.GetC_Currency_ID(), DateTime.Now, C_ConversionType_ID, GetCtx().GetAD_Client_ID(), GetCtx().GetAD_Org_ID());
                        if (DiscountAmt > 0)
                        {
                            DiscountAmt = MConversionRate.Convert(GetCtx(), DiscountAmt, Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_currency_id"]), _bankacc.GetC_Currency_ID(), DateTime.Now, C_ConversionType_ID, GetCtx().GetAD_Client_ID(), GetCtx().GetAD_Org_ID());
                            if (DiscountAmt == 0)
                            {
                                Get_TrxName().Rollback();
                                msg = Msg.GetMsg(GetCtx(), "NoCurrencyConversion");
                                MCurrency from = new MCurrency(GetCtx(), Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_currency_id"]), Get_TrxName());
                                MCurrency to   = new MCurrency(GetCtx(), Util.GetValueOfInt(_bankacc.GetC_Currency_ID()), Get_TrxName());
                                return(msg + from.GetISO_Code() + "," + to.GetISO_Code());
                            }
                        }
                        if (dueamt == 0)
                        {
                            Get_TrxName().Rollback();
                            msg = Msg.GetMsg(GetCtx(), "NoCurrencyConversion");
                            MCurrency from = new MCurrency(GetCtx(), Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_currency_id"]), Get_TrxName());
                            MCurrency to   = new MCurrency(GetCtx(), Util.GetValueOfInt(_bankacc.GetC_Currency_ID()), Get_TrxName());
                            return(msg + from.GetISO_Code() + "," + to.GetISO_Code());
                        }
                    }

                    if (Util.GetValueOfDateTime(ds.Tables[0].Rows[i]["DiscountDate"]) >= Util.GetValueOfDateTime(batch.GetVA009_DocumentDate()))
                    {
                        //dueamt = dueamt - (Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["DiscountAmt"]));
                        dueamt = dueamt - DiscountAmt;
                        //  145-2.88
                    }



                    if (Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"]) == "APC" || Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"]) == "ARC")
                    {
                        lineDetail.SetDueAmt(-1 * dueamt);
                        comvertedamt = (-1 * dueamt);
                    }
                    else
                    {
                        lineDetail.SetDueAmt(dueamt);
                        comvertedamt = (dueamt);
                    }
                    if (issamme == false)
                    {
                        comvertedamt = dueamt;
                        //comvertedamt = MConversionRate.Convert(GetCtx(), dueamt, Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_currency_id"]), _bankacc.GetC_Currency_ID(), DateTime.Now, C_ConversionType_ID, GetCtx().GetAD_Client_ID(), GetCtx().GetAD_Org_ID());
                        lineDetail.SetC_Currency_ID(_bankacc.GetC_Currency_ID());
                        if (Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"]) == "APC" || Util.GetValueOfString(ds.Tables[0].Rows[i]["DocBaseType"]) == "ARC")
                        {
                            comvertedamt = (-1 * comvertedamt);
                        }
                    }
                    else
                    {
                        lineDetail.SetC_Currency_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["c_currency_id"]));
                    }

                    lineDetail.SetVA009_ConvertedAmt(comvertedamt);
                    lineDetail.SetVA009_PaymentMethod_ID(Util.GetValueOfInt(ds.Tables[0].Rows[i]["va009_paymentmethod_id"]));


                    if (Util.GetValueOfDateTime(ds.Tables[0].Rows[i]["DiscountDate"]) < Util.GetValueOfDateTime(batch.GetVA009_DocumentDate()))
                    {
                        lineDetail.SetDiscountDate(null);
                        lineDetail.SetDiscountAmt(0);
                    }
                    else if (Util.GetValueOfDateTime(ds.Tables[0].Rows[i]["DiscountDate"]) >= Util.GetValueOfDateTime(batch.GetVA009_DocumentDate()))
                    {
                        lineDetail.SetDiscountDate(Util.GetValueOfDateTime(ds.Tables[0].Rows[i]["DiscountDate"]));
                        //lineDetail.SetDiscountAmt(Util.GetValueOfDecimal(ds.Tables[0].Rows[i]["DiscountAmt"]));
                        lineDetail.SetDiscountAmt(DiscountAmt);
                    }

                    if (!lineDetail.Save(Get_TrxName()))
                    {
                        Get_TrxName().Rollback();
                        return(Msg.GetMsg(GetCtx(), "VA009_BatchLineNotCrtd"));
                        //return"BatchLine Not Saved";
                    }
                    else
                    {
                        //lineDetail.SetProcessed(true);
                        //lineDetail.Save(Get_TrxName());
                        //MInvoicePaySchedule _invpay = new MInvoicePaySchedule(GetCtx(), Util.GetValueOfInt(ds.Tables[0].Rows[i]["C_InvoicePaySchedule_id"]), Get_TrxName());
                        //_invpay.SetVA009_ExecutionStatus("Y");
                        //_invpay.Save(Get_TrxName());
                    }
                }
                batch.SetVA009_GenerateLines("Y");
                //batch.SetProcessed(true); //Commeted by Arpit asked by Ashish Gandhi to set processed only if the Payment completion is done
                batch.Save(Get_TrxName());
                if (_paymentMethod != 0)
                {
                    //_paymthd = new MVA009PaymentMethod(GetCtx(), _paymentMethod, Get_TrxName());
                    batch.SetVA009_PaymentMethod_ID(_paymentMethod);
                    batch.SetVA009_PaymentRule(_paymthd.GetVA009_PaymentRule());
                    batch.SetVA009_PaymentTrigger(_paymthd.GetVA009_PaymentTrigger());
                    if (!batch.Save(Get_TrxName()))
                    {
                        Get_TrxName().Rollback();
                        return(Msg.GetMsg(GetCtx(), "VA009_BatchLineNotCrtd"));
                    }
                }
                return(Msg.GetMsg(GetCtx(), "VA009_BatchLineCrtd"));;
            }
            else
            {
                return(Msg.GetMsg(GetCtx(), "VA009_BatchLineNotCrtd"));
            };
        }
Exemplo n.º 30
0
        /// <summary>
        /// DB確認して、データが無ければ初期データを入れる
        /// これは1か所でやらないとダメ
        /// 外部キーを含むデータを先に登録すると、そのキーの空データが登録されてしまうので
        /// 外部キーデータの登録が先になるように登録順を工夫する必要もあることに注意
        /// </summary>
        /// <returns></returns>
        private async Task InitializeDatabaseAsync()
        {
            // DB確認して、データが無ければ初期データを入れる
            if (DbContext.MCurrencies.ToList().Count == 0)
            {
                Logger.LogInformation("通貨データがありません。初期値を登録します。");
                var array   = new List <string[]>();
                var section = Configuration.GetSection("DefaultParameters");
                section.Bind("MCurrency", array);
                foreach (var item in array)
                {
                    var data = new MCurrency
                    {
                        MCurrencyId = int.Parse(item[0]),
                        Name        = item[1],
                        DisplayName = item[2]
                    };
                    DbContext.MCurrencies.Add(data);
                }
                await DbContext.SaveChangesAsync(SystemConstants.SystemName);
            }

            if (DbContext.MBoards.ToList().Count == 0)
            {
                Logger.LogInformation("板データがありません。初期値を登録します。");
                var array   = new List <string[]>();
                var section = Configuration.GetSection("DefaultParameters");
                section.Bind("MBoard", array);
                foreach (var item in array)
                {
                    var data = new MBoard
                    {
                        MBoardId    = int.Parse(item[0]),
                        Name        = item[1],
                        DisplayName = item[2],
                        MCurrency1  = new MCurrency {
                            MCurrencyId = int.Parse(item[3])
                        },
                        MCurrency2 = new MCurrency {
                            MCurrencyId = int.Parse(item[4])
                        }
                    };
                    DbContext.MBoards.Add(data);
                }
                await DbContext.SaveChangesAsync(SystemConstants.SystemName);
            }

            if (DbContext.MTimeScales.ToList().Count == 0)
            {
                Logger.LogInformation("時間足データがありません。初期値を登録します。");
                var array   = new List <string[]>();
                var section = Configuration.GetSection("DefaultParameters");
                section.Bind("MTimeScale", array);
                foreach (var item in array)
                {
                    var data = new MTimeScale
                    {
                        Id           = int.Parse(item[0]),
                        DisplayName  = item[1],
                        SecondsValue = int.Parse(item[2])
                    };
                    DbContext.MTimeScales.Add(data);
                }
                await DbContext.SaveChangesAsync(SystemConstants.SystemName);
            }

            if (DbContext.MWebSockets.ToList().Count == 0)
            {
                Logger.LogInformation("WebSocketデータがありません。初期値を登録します。");
                var array   = new List <string[]>();
                var section = Configuration.GetSection("DefaultParameters");
                section.Bind("MWebSocket", array);
                foreach (var item in array)
                {
                    var data = new MWebSocket
                    {
                        Id     = int.Parse(item[0]),
                        MBoard = new MBoard {
                            MBoardId = int.Parse(item[1])
                        },
                        Category    = int.Parse(item[2]),
                        EndPoint    = item[3],
                        ChannelName = item[4],
                        IsEnabled   = int.Parse(item[5]) == 1
                    };
                    DbContext.MWebSockets.Add(data);
                }
                DbContext.SaveChanges(SystemConstants.SystemName);
            }
        }