Пример #1
0
        /// <summary>
        /// Checks whether reason allowed
        /// </summary>
        /// <param name="saleNumber">Sale number</param>
        /// <returns>List of sale lines</returns>
        public List <Sale_Line> IsReasonAllowed(int saleNumber)
        {
            List <Sale_Line> result = new List <Sale_Line>();
            var dateStart           = DateTime.Now;

            _performancelog.Debug($"Start,ReturnSaleService,IsReasonAllowed,{string.Empty},{dateStart:hh.mm.ss.ffffff}");

            var strSql = "SELECT * FROM SaleLine WHERE SALE_NO =\'" + saleNumber + "\' UNION ALL SELECT * FROM CSCTRANS.dbo.SaleLine WHERE SALE_NO =\'" + saleNumber + "\'";

            var rsSaleLines = GetRecords(strSql, DataSource.CSCTills);

            foreach (DataRow fields in rsSaleLines.Rows)
            {
                Sale_Line saleLine = new Sale_Line();
                {
                    saleLine.Stock_Code = CommonUtility.GetStringValue(fields["Stock_Code"]);
                    saleLine.Dept       = CommonUtility.GetStringValue(fields["Dept"]);
                    saleLine.Sub_Detail = CommonUtility.GetStringValue(fields["Sub_Detail"]);
                    saleLine.Sub_Dept   = CommonUtility.GetStringValue(fields["Sub_Dept"]);
                }
                result.Add(saleLine);
            }
            _performancelog.Debug($"End,ReturnSaleService,IsReasonAllowed,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
            return(result);
        }
Пример #2
0
        /// <summary>
        /// Method to adjust the discount rate
        /// </summary>
        /// <param name="saleLine">Sale line</param>
        /// <param name="discountRate">Discount rate</param>
        private void SetDiscountRate(ref Sale_Line saleLine, float discountRate)
        {
            var dateStart = DateTime.Now;

            _performancelog.Debug($"Start,ReturnSaleService,SetDiscountRate,{string.Empty},{dateStart:hh.mm.ss.ffffff}");

            saleLine.Discount_Rate = discountRate;
            if (!saleLine.No_Loading)
            {
                if (saleLine.Discount_Type == "%")
                {
                    saleLine.Line_Discount = (float)saleLine.Amount * (saleLine.Discount_Rate / 100);
                }
                else if (saleLine.Discount_Type == "$")
                {
                    if (saleLine.LINE_TYPE.ToUpper() == "LINE TOTAL")
                    {
                        saleLine.Line_Discount = saleLine.Discount_Rate;
                    }
                    else
                    {
                        saleLine.Line_Discount = saleLine.Quantity * saleLine.Discount_Rate;
                    }
                }
                else
                {
                    saleLine.Line_Discount = 0;
                }
            }

            saleLine.Net_Amount = saleLine.Amount - (decimal)Round(saleLine.Line_Discount + saleLine.Discount_Adjust, 2);
            _performancelog.Debug($"End,ReturnSaleService,SetDiscountRate,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
        }
Пример #3
0
        /// <summary>
        /// Method to add a sale line to current sale
        /// </summary>
        /// <param name="saleLine">Sale line</param>
        public void AddSaleLineToDbTill(Sale_Line saleLine)
        {
            var dateStart = DateTime.Now;

            _performancelog.Debug($"Start,SaleLineService,AddSaleLineToDbTill,{string.Empty},{DateTime.Now:hh.mm.ss.ffffff}");
            _connection = new SqlConnection(GetConnectionString(DataSource.CSCTills));
            if (_connection.State == ConnectionState.Closed)
            {
                _connection.Open();
            }
            _dataTable = new DataTable();
            _adapter   = new SqlDataAdapter("SELECT * from SALELINE where TILL_NUM=" + saleLine.Till_Num +
                                            " and SALE_NO = " + saleLine.Sale_Num +
                                            " and Line_Num = " + saleLine.Line_Num, _connection);
            _adapter.Fill(_dataTable);
            if (_dataTable.Rows.Count == 0)
            {
                var fields = _dataTable.NewRow();
                fields["PLU_Code"]      = saleLine.PLU_Code;
                fields["price"]         = saleLine.price;
                fields["SALE_NO"]       = saleLine.Sale_Num;
                fields["TILL_NUM"]      = saleLine.Till_Num;
                fields["Quantity"]      = saleLine.Quantity;
                fields["Line_Num"]      = saleLine.Line_Num;
                fields["Stock_Code"]    = saleLine.Stock_Code;
                fields["DiscountName"]  = saleLine.DiscountName;
                fields["Disc_Type"]     = saleLine.Discount_Type;
                fields["Disc_Adj"]      = saleLine.Discount_Adjust;
                fields["Disc_Code"]     = saleLine.Discount_Code;
                fields["Disc_Rate"]     = saleLine.Discount_Rate;
                fields["Amount"]        = saleLine.Amount;
                fields["PumpID"]        = saleLine.pumpID;
                fields["PositionID"]    = saleLine.PositionID;
                fields["GradeID"]       = saleLine.GradeID;
                fields["Gift_Cert"]     = saleLine.Gift_Certificate;
                fields["PromoID"]       = saleLine.PromoID;
                fields["Prepay"]        = saleLine.Prepay;
                fields["SERIAL_NO"]     = saleLine.Serial_No;
                fields["PaidByCard"]    = saleLine.PaidByCard;
                fields["Upsell"]        = saleLine.Upsell;
                fields["TaxExempt"]     = saleLine.TaxForTaxExempt;
                fields["TOTAL_AMT"]     = saleLine.Total_Amount;
                fields["Rebate"]        = saleLine.Rebate;
                fields["ScalableItem"]  = saleLine.ScalableItem;
                fields["CardProfileID"] = saleLine.CardProfileID;
                _dataTable.Rows.Add(fields);
                SqlCommandBuilder builder = new SqlCommandBuilder(_adapter);
                _adapter.InsertCommand = builder.GetInsertCommand();
                _adapter.Update(_dataTable);
                _connection.Close();
                _adapter?.Dispose();
            }
            _performancelog.Debug($"End,SaleLineService,AddSaleLineToDbTill,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
        }
        // Set the price on a line.
        /// <summary>
        /// Method to set price on line
        /// </summary>
        /// <param name="payPump">pay at pump</param>
        /// <param name="oLine">Sale line</param>
        /// <param name="price">Price</param>
        private void Line_Price(ref PayAtPump payPump, ref Sale_Line oLine, double price)
        {
            Compute_Taxes(ref payPump, oLine, -1);
            oLine.price = price;
            Compute_Taxes(ref payPump, oLine, 1);

            if (payPump.Sale_Totals.Invoice_Discount != 0)
            {
                Sale_Discount(ref payPump, payPump.Sale_Totals.Invoice_Discount, payPump.Sale_Totals.Invoice_Discount_Type);
            }
        }
        /// <summary>
        /// Get  Stock item test Data
        /// </summary>
        /// <returns></returns>
        private Sale_Line GetStockItemTestData()
        {
            var stockItem = new Sale_Line
            {
                Stock_Code  = "1",
                Description = "TestDescription",
                Stock_Type  = 'I',
                User        = string.Empty
            };

            return(stockItem);
        }
        public void SetSaleLinePolicyTest()
        {
            var saleLine = new Sale_Line();
            var expected = 1;

            _saleLineManager.SetSaleLinePolicy(ref saleLine);
            Assert.IsTrue(saleLine.GROUP_PRTY);
            Assert.IsTrue(saleLine.GC_DISCOUNT);
            Assert.AreEqual(expected, saleLine.LOYAL_PPD);
            Assert.AreEqual(expected, saleLine.NUM_PRICE);
            Assert.AreEqual(expected, saleLine.LOYAL_DISC);
            Assert.AreEqual("1", saleLine.GC_REPT);
        }
        /// <summary>
        /// Method to load tax exempt prepay
        /// </summary>
        /// <param name="saleNo">Sale number</param>
        /// <param name="sl">Sale line</param>
        /// <param name="lineNo">Line number</param>
        /// <param name="sale">Sale</param>
        /// <param name="oPurchaseList">Purchase list</param>
        /// <param name="oTreatyNo">Treaty number</param>
        /// <returns>True or false</returns>
        public bool LoadTaxExemptPrepay(int saleNo, Sale_Line sl, short lineNo, ref
                                        Sale sale, ref tePurchaseList oPurchaseList, ref teTreatyNo oTreatyNo)
        {
            var returnValue = false;

            if (!_policyManager.TAX_EXEMPT)
            {
                return(false);
            }
            var user = CacheManager.GetUser(UserCode);

            if (_policyManager.TE_Type == "SITE")
            {
                var teItem = _taxExemptSaleService.GetPurchaseItem(saleNo, lineNo);
                if (teItem != null)
                {
                    _treatyManager.Init(ref oTreatyNo, teItem.TreatyNo, false);
                    oPurchaseList.Init(oTreatyNo, sale.Sale_Num, sale.TillNumber);

                    var    tempSProductKey  = mPrivateGlobals.theSystem.teMakeFuelKey(sl.GradeID, teItem.PsTierID, teItem.PsLevelID);
                    var    tempIsFuelItem   = true;
                    var    stockCode        = string.Empty;
                    short  iRowNumberinSale = 0;
                    double tempQuantity     = 0f;
                    double org           = teItem.PdOriginalPrice;
                    double taxIncldPrice = teItem.petaxInclPrice;
                    _purchaseListManager.AddItem(ref oPurchaseList,
                                                 ref sale, ref oTreatyNo, ref tempSProductKey, ref tempQuantity, ref org, ref iRowNumberinSale, ref stockCode, ref taxIncldPrice, ref tempIsFuelItem);
                    sl.Stock_Code = stockCode;
                }
            }
            else
            {
                var oTeSale = new TaxExemptSale();

                if (_taxExemptSaleService.LoadTaxExemptForDeletePrepay(ref oTeSale,
                                                                       _policyManager.TE_Type, _tillService.GetTill(sale.TillNumber),
                                                                       user, saleNo, sale.TillNumber, lineNo, sale.Sale_Num))
                {
                    returnValue = true;
                }
                else if (_taxExemptSaleService.LoadGstExemptForDeletePrepay(ref oTeSale,
                                                                            saleNo, sale.TillNumber, DataSource.CSCTills))
                {
                    oTeSale.teCardholder.GstExempt = true;
                }
            }
            return(returnValue);
        }
Пример #8
0
        ///// <summary>
        ///// Method to get max link
        ///// </summary>
        ///// <param name="promoId"></param>
        ///// <returns>Max link</returns>
        //public short GetMaxLink(string promoId)
        //{
        //    var dateStart = DateTime.Now;
        //    _performancelog.Debug($"Start,PromoService,GetMaxLink,{string.Empty},{DateTime.Now:hh.mm.ss.ffffff}");

        //    var rsTemp = GetRecords("SELECT MAX(Link) AS MaxLink FROM PromoDetail WHERE PromoID=\'" + promoId + "\'", DataSource.CSCMaster);
        //    if (rsTemp.Rows.Count != 0)
        //    {
        //        var fields = rsTemp.Rows[0];
        //        _performancelog.Debug($"End,PromoService,GetMaxLink,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
        //        return CommonUtility.GetShortValue(fields["MaxLink"]);
        //    }
        //    _performancelog.Debug($"End,PromoService,GetMaxLink,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");

        //    return 0;
        //}

        ///// <summary>
        ///// Method to get number of links
        ///// </summary>
        ///// <param name="promoId">Promo id</param>
        ///// <returns>Number of links</returns>
        //public List<int> GetNumberOfLinks(string promoId)
        //{
        //    var dateStart = DateTime.Now;
        //    _performancelog.Debug($"Start,PromoService,GetNumberOfLinks,{string.Empty},{DateTime.Now:hh.mm.ss.ffffff}");

        //    var rsTemp = GetRecords("SELECT SUM(Link)/Link AS NrOfLinks, Link FROM PromoDetail WHERE PromoID=\'" + promoId + "\' GROUP BY Link ORDER BY Link", DataSource.CSCMaster);
        //    var links = (from DataRow fields in rsTemp.Rows select CommonUtility.GetShortValue(fields["NrOfLinks"])).Select(dummy => (int)dummy).ToList();
        //    _performancelog.Debug($"End,PromoService,GetNumberOfLinks,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");

        //    return links;
        //}

        /// <summary>
        /// Method to get all promos for today
        /// </summary>
        /// <param name="optPromoId">Promo id</param>
        /// <returns>Promo headers</returns>
        public List <Promo> GetPromoHeadersForToday(string optPromoId)
        {
            var dateStart = DateTime.Now;

            _performancelog.Debug($"Start,PromoService,GetPromoHeadersForToday,{string.Empty},{DateTime.Now:hh.mm.ss.ffffff}");
            var promos = new List <Promo>();

            _connection = new SqlConnection(GetConnectionString(DataSource.CSCMaster));
            if (_connection.State == ConnectionState.Closed)
            {
                _connection.Open();
            }
            SqlCommand cmd = new SqlCommand("GetPromoHeaders", _connection)
            {
                CommandType = CommandType.StoredProcedure
            };

            cmd.Parameters.Add(new SqlParameter {
                ParameterName = "@optPromoId", Value = optPromoId
            });
            cmd.Parameters.Add(new SqlParameter {
                ParameterName = "@dt", Value = DateTime.Now.ToString("yyyyMMdd")
            });
            var rdr = cmd.ExecuteReader();

            if (!rdr.HasRows)
            {
                return(promos);
            }
            var stockInfo = new Sale_Line();

            while (rdr.Read())
            {
                Promo promo = new Promo();
                promo.PromoID     = CommonUtility.GetStringValue(rdr["PromoID"]);
                promo.Description = CommonUtility.GetStringValue(rdr["Description"]);
                promo.DiscType    = CommonUtility.GetStringValue(rdr["DiscType"]);
                promo.Amount      = CommonUtility.GetDoubleValue(rdr["price"]);
                promo.PrType      = CommonUtility.GetStringValue(rdr["PrType"]);
                promo.MaxLink     = CommonUtility.GetShortValue(rdr["MaxLink"]);
                promo.MultiLink   = CommonUtility.GetIntergerValue(rdr["NrOfLinks"]) > 1 ? true : false;
                promos.Add(promo);
            }

            _performancelog.Debug($"End,PromoService,GetPromoHeadersForToday,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");

            return(promos);
        }
        /// <summary>
        /// Method to set quantity
        /// </summary>
        /// <param name="payPump">Pay at pump</param>
        /// <param name="oLine">Sale line</param>
        /// <param name="quantity">Quantity</param>
        /// <param name="adjust">Adjust or not</param>
        /// <returns>True or false</returns>
        private void Line_Quantity(ref PayAtPump payPump, ref Sale_Line oLine, float quantity, bool adjust = true)
        {
            Compute_Taxes(ref payPump, oLine, -1);
            oLine.Quantity = quantity;
            if (adjust)
            {
                if (!Adjust_Lines(ref payPump, ref oLine, false))
                {
                    ReCompute_Totals(ref payPump);
                }
                else
                {
                    Compute_Taxes(ref payPump, oLine, 1);
                }
            }

            if (payPump.Sale_Totals.Invoice_Discount != 0)
            {
                Sale_Discount(ref payPump, payPump.Sale_Totals.Invoice_Discount,
                              payPump.Sale_Totals.Invoice_Discount_Type);
            }
        }
Пример #10
0
        /// <summary>
        /// Method to get quantity
        /// </summary>
        /// <param name="sl"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        internal float[,] PQuantity(Sale_Line sl, float quantity)
        {
            //float[,] returnValue = default(float[,]);

            float[,] prices = new float[51, 4];

            float[,] pHold = new float[51, 4];

            const short qty = 1;
            const short pri = 2;
            const short amt = 3;

            short n;

            var   priceType = '\0';
            short m         = 0;

            var ns = (short)(quantity < 0 ? -1 : 1);

            quantity = Math.Abs((short)quantity);

            var regPrice = (decimal)sl.Regular_Price;

            priceType = sl.Price_Type;
            var priceUnits = sl.Price_Units;

            for (n = 1; n <= Information.UBound(prices, qty); n++)
            {
                prices[n, qty] = 0;
                prices[n, pri] = 0;
                prices[n, amt] = 0;
                pHold[n, qty]  = 0;
                pHold[n, pri]  = 0;
                pHold[n, amt]  = 0;
            }

            if (sl.Price_Number != 1)
            {
                // If the price number isn't 1 then none of the special pricing applies.
                prices[1, qty] = quantity * ns;
                prices[1, pri] = (float)sl.price;
                prices[1, amt] = (float)(quantity * sl.price * ns);
                m = (short)1;
            }
            else
            {
                var spPrices = _fuelService.GetPriceL(sl.Stock_Code);
                if (spPrices.Count == 0)
                {
                    // No Special Pricing defined for this item.
                    prices[1, qty] = quantity * ns;
                    prices[1, pri] = (float)regPrice;
                    prices[1, amt] = quantity * (float)regPrice * ns;
                    m = (short)1;
                }
                else
                {
                    switch (priceType)
                    {
                    case 'R':
                        // Regular Price
                        prices[1, qty] = quantity * ns;
                        prices[1, pri] = (float)regPrice;
                        prices[1, amt] = quantity * (float)regPrice * ns;
                        m = (short)1;
                        break;



                    case 'F':
                        // First Unit Pricing
                        spPrices.Reverse();
                        foreach (var spPrice in spPrices)
                        {
                            if (spPrice.FQuantity <= quantity)
                            {
                                prices[1, qty] = quantity * ns;
                                prices[1, pri] = priceUnits == '%' ? (float)(regPrice * (1 - Convert.ToInt32(Convert.ToInt32(spPrice.Price.Value) / 100))) : (spPrice.Price.Value);
                                prices[1, amt] = quantity * prices[1, pri] * ns;
                                break;
                            }
                        }
                        if (prices[1, qty] == 0)
                        {
                            prices[1, qty] = quantity * ns;
                            prices[1, pri] = (float)regPrice;
                            prices[1, amt] = quantity * (float)regPrice * ns;
                        }
                        m = (short)1;
                        break;

                    case 'X':

                        float RP_Qty = 0;
                        if (_policyManager.X_RIGOR)
                        {
                            // "X" for Pricing - RIGOROUS
                            var firstXPrice = spPrices.FirstOrDefault();
                            RP_Qty = Convert.ToSingle(firstXPrice.FQuantity - 1);
                            m      = (short)0;
                            // spPrices.Reverse();
                            int xIndex = spPrices.Count - 1;
                            if (quantity > RP_Qty)
                            {
                                while (!(xIndex != 0 || quantity <= RP_Qty))
                                {
                                    if (spPrices[xIndex].FQuantity <= quantity)
                                    {
                                        m++;
                                        prices[m, qty] = Convert.ToSingle(Convert.ToInt32(spPrices[xIndex].FQuantity) * ns);
                                        prices[m, pri] = priceUnits == '%' ? (float)(regPrice * (1 - Convert.ToInt32(Convert.ToInt32(spPrices[xIndex].Price.Value) / 100))) : (spPrices[xIndex].Price.Value);
                                        prices[m, amt] = prices[m, pri] * ns;
                                        quantity       = Convert.ToSingle(quantity - spPrices[xIndex].FQuantity);
                                        if (spPrices[xIndex].FQuantity > quantity)
                                        {
                                            xIndex--;
                                        }
                                    }
                                    else
                                    {
                                        xIndex--;
                                    }
                                }
                            }

                            if (RP_Qty > 0 & quantity > 0)
                            {
                                m++;
                                prices[m, qty] = (quantity >= RP_Qty ? RP_Qty : quantity) * ns;
                                prices[m, pri] = (float)regPrice;
                                prices[m, amt] = prices[m, qty] * (float)regPrice;
                            }
                        }
                        else
                        {
                            // X-for Pricing - NON-RIGOROUS
                            m = (short)0;
                            var lastXPrice = spPrices.LastOrDefault();
                            RP_Qty         = Convert.ToSingle(lastXPrice.FQuantity - 1);
                            prices[1, qty] = 1;
                            prices[1, pri] = (float)regPrice;
                            prices[1, amt] = (float)regPrice;
                            int index = spPrices.Count - 1;
                            // Find the best pricing available
                            while (index != 0)
                            {
                                if (spPrices[index].FQuantity <= quantity)
                                {
                                    m++;
                                    prices[m, qty] = Convert.ToSingle(spPrices[index].FQuantity * ns);
                                    prices[m, pri] = priceUnits == '%' ? (float)(regPrice * (1 - Convert.ToInt32(Convert.ToInt32(spPrices[index].Price.Value) / 100))) : (spPrices[index].Price.Value);
                                    prices[m, amt] = prices[m, pri] * ns;
                                    break;
                                }
                                index--;
                            }

                            var remainingQty = quantity;
                            if (m > 0)
                            {
                                remainingQty = quantity - prices[1, qty];
                                while (remainingQty >= prices[1, qty])
                                {
                                    m++;
                                    prices[m, qty] = prices[1, qty];
                                    prices[m, pri] = prices[1, pri];
                                    prices[m, amt] = prices[1, amt];
                                    remainingQty   = remainingQty - prices[1, qty];
                                }
                            }

                            if (remainingQty > 0)
                            {
                                m++;
                                // Compute the best price for the remaining units.
                                var   q = (prices[1, pri] / prices[1, qty]).ToString("0.000");
                                float bestPrice;
                                if (q.Substring(q.Length - 1, 1) == "0")
                                {
                                    bestPrice = (float)(Math.Round(prices[1, pri] / prices[1, qty], 2));
                                }
                                else
                                {
                                    q         = q.Substring(0, q.Length - 1);
                                    bestPrice = (float)(Conversion.Val(q) + 0.01);
                                }

                                prices[m, qty] = remainingQty * ns;
                                prices[m, pri] = bestPrice;
                                prices[m, amt] = prices[m, qty] * prices[m, pri];
                            }
                        }
                        break;


                    case 'S':
                        // Sale Pricing
                        prices[1, qty] = quantity * ns;
                        prices[1, pri] = priceUnits == '%' ? (float)(regPrice * (1 - Convert.ToInt32(Convert.ToInt32(spPrices.FirstOrDefault().Price.Value) / 100))) : (spPrices.FirstOrDefault().Price.Value);
                        prices[1, amt] = prices[1, qty] * prices[1, pri] * ns;
                        m = 1;
                        break;



                    case 'I':
                        // Incremental Pricing

                        m = 0;
                        var firstPrice = spPrices.FirstOrDefault();
                        // Sell anything below the first quantity at regular price
                        short qtyInRange = 0;
                        if (quantity < firstPrice.FQuantity)
                        {
                            qtyInRange = (short)quantity;
                            m++;
                            prices[m, qty] = qtyInRange * ns;
                            prices[m, pri] = (float)regPrice;
                            prices[m, amt] = qtyInRange * prices[m, pri] * ns;
                            quantity       = quantity - qtyInRange;
                        }

                        var lastPrice = spPrices.LastOrDefault();
                        // Sell anything above the upper limit at regular price.
                        if (lastPrice != null && quantity > lastPrice.TQuantity)
                        {
                            qtyInRange = Convert.ToInt16(quantity - lastPrice.TQuantity);
                            m++;
                            prices[m, qty] = qtyInRange * ns;
                            prices[m, pri] = (float)regPrice;
                            prices[m, amt] = qtyInRange * prices[m, pri] * ns;
                            quantity       = quantity - qtyInRange;
                        }
                        int iIndex = spPrices.Count - 1;
                        // Apply the ranges
                        while (iIndex != 0)
                        {
                            qtyInRange = (short)(Convert.ToInt32(quantity - spPrices[iIndex].FQuantity) + 1);
                            if (qtyInRange > Convert.ToInt32(Convert.ToDouble(spPrices[iIndex].TQuantity) - Convert.ToDouble(spPrices[iIndex].FQuantity) + 1))
                            {
                                qtyInRange = Convert.ToInt16(Convert.ToDouble(Convert.ToInt32(spPrices[iIndex].TQuantity) - Convert.ToDouble(spPrices[iIndex].FQuantity)) + 1);
                            }
                            if (qtyInRange > 0)
                            {
                                m++;
                                prices[m, qty] = qtyInRange * ns;
                                prices[m, pri] = priceUnits == '%' ? (float)(regPrice * (1 - Convert.ToInt32(Convert.ToInt32(spPrices[iIndex].Price.Value) / 100))) : (spPrices[iIndex].Price.Value);
                                prices[m, amt] = qtyInRange * prices[m, pri] * ns;
                                quantity       = quantity - qtyInRange;
                                if (spPrices[iIndex].FQuantity > quantity)
                                {
                                    iIndex--;
                                }
                            }
                            else
                            {
                                iIndex--;
                            }
                        }

                        if (quantity > 0)
                        {
                            m++;
                            prices[m, qty] = quantity * ns;
                            prices[m, pri] = (float)regPrice;
                            prices[m, amt] = prices[m, qty] * (float)regPrice;
                        }
                        break;
                    }
                }
            }

            // Reverse the order for cosmetic reasons
            for (n = 1; n <= m; n++)
            {
                var I = (short)(m - n + 1);
                pHold[I, qty] = prices[n, qty];
                pHold[I, pri] = prices[n, pri];
                pHold[I, amt] = prices[n, amt];
            }

            Array.Copy(pHold, prices, pHold.Length);
            return(prices);
        }
Пример #11
0
        /// <summary>
        /// Method to delete uncomplete prepay
        /// </summary>
        /// <param name="pumpId">Pump Id</param>
        /// <param name="saleNumber">Sale number</param>
        /// <param name="tillNumber">Till number</param>
        /// <param name="error">Error</param>
        /// <returns>Sale</returns>
        public Sale DeleteUnCompletePrepay(int pumpId, int saleNumber, int tillNumber, out ErrorMessage error)
        {
            var sale   = CacheManager.GetCurrentSaleForTill(tillNumber, saleNumber);
            var offSet = _policyManager.LoadStoreInfo().OffSet;

            if (sale?.Sale_Lines?.Count > 0)
            {
                //Chaps_Main.DisplayMessage(this, (short)60, temp_VbStyle, null, (byte)0);
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 36, 60, null, CriticalOkMessageType)
                };
                return(null);
            }

            sale = _saleService.GetSaleBySaleNoFromDbTill(ref sale, tillNumber, saleNumber);
            var saleLine = _saleService.GetPrepaySaleLine(saleNumber, tillNumber);

            if (sale == null || saleLine == null)
            {
                //MsgBoxStyle temp_VbStyle2 = (int)MsgBoxStyle.Critical + MsgBoxStyle.OkOnly;
                //Chaps_Main.DisplayMessage(this, (short)61, temp_VbStyle2, null, (byte)0);
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 36, 61, null, CriticalOkMessageType)
                };
                return(null);
            }
            _saleService.UpdateDiscountTender(ref sale);



            var sl = new Sale_Line
            {
                No_Loading = true,
                Dept       = saleLine.Dept,
                Sub_Dept   = saleLine.Sub_Dept,
                Stock_Code = saleLine.Stock_Code,
                Amount     = saleLine.Amount
            };

            _saleLineManager.SetSubDetail(ref sl, saleLine.Sub_Detail);
            _saleLineManager.SetPluCode(ref sale, ref sl, saleLine.PLU_Code, out error);
            _saleLineManager.SetPrice(ref sl, saleLine.price);
            _saleLineManager.SetQuantity(ref sl, saleLine.Quantity * -1);
            sl.Regular_Price = saleLine.Regular_Price;


            if (sale.Customer.GroupID != "" && _policyManager.FuelLoyalty)
            {
                if (sale.Customer.DiscountType == "%")
                {
                    _saleLineManager.SetAmount(ref sl, (saleLine.Amount - Convert.ToDecimal(saleLine.Amount * Convert.ToDecimal(sale.Customer.DiscountRate)) / 100) * (-1));
                }
                else if (sale.Customer.DiscountType == "$")
                {
                    _saleLineManager.SetAmount(ref sl, saleLine.Amount - Convert.ToDecimal(saleLine.Quantity * sale.Customer.DiscountRate) * (-1));
                }
                else
                {
                    _saleLineManager.SetAmount(ref sl, saleLine.Amount * (-1));
                }
            }
            else
            {
                _saleLineManager.SetAmount(ref sl, saleLine.Amount * (-1));
            }

            sl.pumpID     = (byte)pumpId;
            sl.PositionID = saleLine.PositionID;
            sl.GradeID    = saleLine.GradeID;

            sl.User        = UserCode;
            sl.Description = saleLine.Description;
            sale.Sale_Type = "Delete Prepay";

            _saleManager.Add_a_Line(ref sale, sl, "", tillNumber, out error, true);

            return(sale);
        }
Пример #12
0
        public bool ProcessKickBack(short command_Renamed, string userCode, ref Sale sale, out ErrorMessage errorMessage)
        {
            //  var tender = new Tender();
            bool result   = true;
            var  kickback = new XML(_policyManager);
            var  store    = _policyManager.LoadStoreInfo();

            float timeIN      = 0;
            short TimeOut     = 0;
            bool  GotResponse = false;
            short Answer;
            var   KBComm = new Comm();

            object[] CapValue = new object[3];
            var      tender   = _tenderManager.GetAllTender(sale.Sale_Num, sale.TillNumber, "Sale", userCode, false,
                                                            "", out errorMessage);

            //   command 0 - GetPointStatus Request
            //   command 1 - FinalizeRewards Request - only from Exact Change button
            //   command 2 - Check Balance
            if (command_Renamed < 0 | command_Renamed > 2)
            {
                errorMessage.StatusCode           = HttpStatusCode.BadGateway;
                errorMessage.MessageStyle.Message = "Invalid loyalty card";
                return(false);
            }

            KBComm            = new Comm(); //'' KickBackComm
            KBComm.CommData  += KBComm_CommData;
            KBComm.CommError += KBComm_CommError;



            Comm.KBComm = KBComm;

            var xml      = new XML(_policyManager);
            var saleLine = new Sale_Line();
            var s        = new Sale();


            //  var sale = _saleManager.GetCurrentSale();
            var offSet = _policyManager.LoadStoreInfo().OffSet;

            // Write to log is done by KickBackXML class, POS only displays messages for the cashier

            if (!_xmlManager.Initialize("", "", "", (sale.Sale_Num).ToString(), System.Convert.ToString(store.Code), "", ref xml))
            {
                // Display the same error message on the screen because for cashier doesn't matter
                // if the connection cannot be made or the XML cannot be created.
                // But KickBackXML class writes the error in the log for debugging purposes

                _resourceManager.CreateMessage(offSet, 11, 42, null, MessageType.Exclamation);//Cannot communicate with Loyalty Server
                errorMessage.MessageStyle.Message = "Invalid loyalty card";
                errorMessage.StatusCode           = HttpStatusCode.NotAcceptable;
                return(false);
            }
            else
            {
                kickback.Sale = this.saleObj;

                if (!(tender == null))
                {
                    kickback.Tenders = tender;
                }
            }

            if (command_Renamed == 0 | command_Renamed == 2)
            {
                var a = xml.PosSequenceID;

                // if (!_xmlManager.FormatFinalizeRewardsRequestXML(sale.Customer.PointCardNum, System.Convert.ToString(sale.Customer.PointCardSwipe == "2" ? "SWIPE" : "MANUAL"), (sale.Customer.Points_Redeemed).ToString(), (sale.Sale_Totals.Gross).ToString(), "", "", "", System.Convert.ToString(store.Code), System.Convert.ToString(userCode), System.Convert.ToString(sale.TillNumber), "", "", "", "",ref xml,ref sale))
                if (!_xmlManager.FormatGetPointStatusRequestXML(sale.Customer.PointCardNum, System.Convert.ToString(sale.Customer.PointCardSwipe == "2" ? "SWIPE" : "MANUAL"), ref xml))
                {
                    // Display the same error massage on the screen because for cashier doesn't matter
                    // if the connection cannot be made or the XML cannot be created.
                    // But write the correct reason in the log for debugging purposes

                    _resourceManager.CreateMessage(offSet, 11, 42, null, MessageType.Information); //Cannot communicate to Loyalty TPS

                    return(false);
                }
                var sam1 = xml;
            }


            else if (command_Renamed == 1) // send finalize rewards only from Exact_Change Button
            {
                var points = (sale.Customer.Points_Redeemed == 0) ? 0 : (sale.Customer.Points_Redeemed / ExchangeRate);
                if (!_xmlManager.FormatFinalizeRewardsRequestXML(sale.Customer.PointCardNum, System.Convert.ToString(sale.Customer.PointCardSwipe == "2" ? "SWIPE" : "MANUAL"), points.ToString(), (sale.Sale_Totals.Gross).ToString(), "", "", "", System.Convert.ToString(store.Code), System.Convert.ToString(userCode), System.Convert.ToString(sale.TillNumber), "", "", "", "", ref xml, ref sale))
                // if (!_xmlManager.FormatFinalizeRewardsRequestXML(sale.Customer.PointCardNum, "SWIPE", (sale.Customer.Points_Redeemed * 100).ToString(), (sale.Sale_Totals.Gross).ToString(), "", "", "", System.Convert.ToString(store.Code), System.Convert.ToString(userCode), System.Convert.ToString(sale.TillNumber), "", "", "", "", ref xml, ref sale))
                {
                    //shiny end
                    // Display the same error massage on the screen because for cashier doesn't matter
                    // if the connection cannot be made or the XML cannot be created.
                    // But write the correct reason in the log for debugging purposes
                    //Chaps_Main.DisplayMessage(this, (short)42, MsgBoxStyle.Information, null, (byte)0); //Cannot communicate to Loyalty TPS
                    //shiny sept 14, 2009 - changed to use the common function, so apperstophe fix can do in one place
                    //             dbMaster.Execute "INSERT INTO KickBackQueue VALUES ('" & KickBack.GetRequestXMLstring & "')"
                    // modGlobalFunctions.InsertTo_KickBackQueue(Variables.KickBack.GetRequestXMLstring);
                    InsertTo_KickBackQueue(xml.GetRequestXMLstring);
                    //shiny end - sept14, 2009
                    return(false);
                }
            }


            KickBackBuffer = ""; //clear the response buffer

            Thread.Sleep(500);
            var timeout = _policyManager.KICKBACK_TMT;

            KickBackBuffer = socket.Connect(xml.GetRequestXMLstring, _policyManager.KICKBACK_IP, (short)Conversion.Val(_policyManager.KICKBACK_PRT), (short)Conversion.Val(timeout), out errorMessage);



            if (KickBackBuffer == "failed")
            {
                WriteTokickBackLogFile(" Cannot Send to Server: " + xml.GetRequestXMLstring);
                if (command_Renamed == 1)
                {
                    InsertTo_KickBackQueue(xml.GetRequestXMLstring);
                }
                return(false);
            }

            WriteTokickBackLogFile(" Connected to KickBack Server: " + $"{_policyManager.KICKBACK_IP}:{_policyManager.KICKBACK_PRT}");
            string kickBackTrimmedResponse = KickBackBuffer.Replace("\0", string.Empty);

            WriteTokickBackLogFile(" Received from Kickback Server:: " + kickBackTrimmedResponse.TrimEnd());
            var    sam3    = xml;
            string RespStr = "";

            Byte[] buff = new Byte[1000];

            GotResponse = false;

            TimeOut = System.Convert.ToInt16(_policyManager.KICKBACK_TMT);
            timeIN  = (float)DateAndTime.Timer;
            //    Debug.Print TimeOut & " " & timeIN
            while (!(DateAndTime.Timer - timeIN > TimeOut))
            {
                //        Debug.Print Timer
                System.Windows.Forms.Application.DoEvents();
                if (!string.IsNullOrEmpty(KickBackBuffer))
                {
                    GotResponse = true;
                    break;
                }
                if (DateAndTime.Timer < timeIN)
                {
                    timeIN = (float)DateAndTime.Timer;
                }
            }


            if (!GotResponse)
            {
                WriteTokickBackLogFile("No response from Loyalty Server.");
                if (command_Renamed == 1)
                {
                    InsertTo_KickBackQueue(xml.GetRequestXMLstring);
                }
                MessageType temp_VbStyle2 = (int)MessageType.Critical + MessageType.OkOnly;
                _resourceManager.CreateMessage(offSet, 11, 42, null, temp_VbStyle2);

                return(false);
            }
            _xmlManager.AnalyseKickBackResponse(KickBackBuffer, ref xml);

            if (command_Renamed == 0 | command_Renamed == 2)
            {
                //Analyze the response
                // Modified on Apr 03, 2009 to use two flags for invalid and non registered cards
                // If the card is not valid processing should continue without any KickBack redemtion or acumulation
                // If the card is not registered processing should continue with accumulation but without redemption
                if (!xml.GetLoyaltyIDValid)
                {
                    //Invalid Loyalty Card
                    _resourceManager.CreateMessage(offSet, 11, 45, null, MessageType.OkOnly);
                    // was 1145
                    sale.Customer.PointCardNum         = "";
                    sale.Customer.PointCardPhone       = "";
                    sale.Customer.PointCardSwipe       = "";
                    sale.Customer.Points_ExchangeRate  = 0;
                    sale.Customer.Points_Redeemed      = 0;
                    sale.Customer.PointsAwarded        = 0;
                    sale.Customer.PointCard_Registered = false;

                    errorMessage = new ErrorMessage();
                    errorMessage.MessageStyle = new MessageStyle
                    {
                        Message = "Invalid loyalty card"
                    };
                    errorMessage.StatusCode = HttpStatusCode.NotAcceptable;
                    result = false;
                }
                else if (command_Renamed == 0)
                {
                    if (xml.LoyaltyIDRegistered)
                    {
                        var allowredeem = sale.Customer.PointsCard_AllowRedemption;
                        var balance     = xml.Sale.Customer.Balance_Points;
                        //var saleline = sale.Sale_Lines;
                        //var saletotal = sale.Sale_Totals;
                        //var gross = sale.Sale_Totals.Gross;
                        //var till = sale.TillNumber;
                        //var cardno = sale.Customer.PointCardNum;
                        //var salenum = sale.Sale_Num;
                        //var entrymethod = sale.Customer.PointCardSwipe;
                        //var selectedCustomer = sale.Customer;
                        // sale = xml.Sale;
                        sale.Customer.PointCard_Registered = true;
                        // sale.Sale_Totals = saletotal;
                        // sale.Sale_Num = salenum;
                        // sale.TillNumber = till;
                        // sale.Sale_Lines = saleline;
                        //sale.Customer = selectedCustomer;
                        sale.Customer.PointsCard_AllowRedemption = allowredeem;
                        //sale.Customer.PointCardNum = cardno;
                        //sale.Customer.PointCardSwipe = entrymethod;
                        sale.Customer.Balance_Points = xml.Sale.Customer.Balance_Points;
                        result = true;
                    }
                    else
                    {
                        _resourceManager.CreateMessage(offSet, 11, 46, null, MessageType.OkOnly);

                        sale.Customer.PointCard_Registered = false;
                        sale.Customer.Points_Redeemed      = 0;
                    }
                }
                sale.Customer.Balance_Points = xml.Sale.Customer.Balance_Points;
                ExchangeRate = sale.Customer.Points_ExchangeRate = xml.Sale.Customer.Points_ExchangeRate;
                WriteUDPData(DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt") + "Inside processkickback 483 cardno value" + sale.Customer.PointCardNum);
            }
            var a10 = xml;

            CacheManager.AddCurrentSaleForTill(sale.TillNumber, sale.Sale_Num, sale);
            // _commManager.EndClass();

            //if (((string.IsNullOrEmpty(sale.Customer.CustomerCardNum) && string.IsNullOrEmpty(sale.Customer.PointCardNum))
            //    || (string.IsNullOrEmpty(sale.Customer.CustomerCardNum) && string.IsNullOrEmpty(sale.Customer.PointCardPhone)))
            //    && (string.IsNullOrEmpty(sale.Customer.PointCardNum) && string.IsNullOrEmpty(sale.Customer.LoyaltyCard)))
            //{
            //    errorMessage = new ErrorMessage();
            //    errorMessage.MessageStyle = new MessageStyle
            //    {
            //        Message = "Invalid loyalty card"

            //    };
            //    errorMessage.StatusCode = HttpStatusCode.NotAcceptable;
            //    result = false;
            //}

            //if (sale.Customer.Balance_Points == 0)
            //{
            //    errorMessage = new ErrorMessage();
            //    errorMessage.MessageStyle = new MessageStyle
            //    {
            //        Message = "Invalid loyalty card"

            //    };
            //    errorMessage.StatusCode = HttpStatusCode.NotAcceptable;
            //    result = false;
            //}
            return(result);
        }
Пример #13
0
        /// <summary>
        /// Method to set quantity
        /// </summary>
        /// <param name="saleLine">Sale line</param>
        /// <param name="isAmount">Is amount</param>
        /// <param name="propaneValue">propane value</param>
        /// <param name="error">Error message</param>
        private void SetQuantity(ref Sale_Line saleLine, bool isAmount, decimal propaneValue, out ErrorMessage
                                 error)
        {
            error = new ErrorMessage();
            var offSet = _policyManager.LoadStoreInfo().OffSet;

            if (Conversion.Val(propaneValue) != 0)
            {
                if (!isAmount)
                {
                    if (Conversion.Val(propaneValue) > MaxVolumn)
                    {
                        //MsgBoxStyle temp_VbStyle = (int)MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation;
                        //Chaps_Main.DisplayMessage(this, (short)14, temp_VbStyle, null, (byte)0);
                        error = new ErrorMessage
                        {
                            MessageStyle = _resourceManager.CreateMessage(offSet, 48, 14, null, ExclamationOkMessageType)
                        };
                        return;
                    }
                    _saleLineManager.SetQuantity(ref saleLine, (float)(Conversion.Val(propaneValue)));

                    if (saleLine.Regular_Price > 0)
                    {
                        decimal amount = System.Convert.ToDecimal(saleLine.Regular_Price) * propaneValue;
                        _saleLineManager.SetAmount(ref saleLine, amount);
                    }
                }
                else //um="$"
                {
                    if (Conversion.Val(propaneValue) > MaxAmt)
                    {
                        //MsgBoxStyle temp_VbStyle2 = (int)MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation;
                        //Chaps_Main.DisplayMessage(this, (short)13, temp_VbStyle2, null, (byte)0);
                        error = new ErrorMessage
                        {
                            MessageStyle = _resourceManager.CreateMessage(offSet, 48, 13, null, ExclamationOkMessageType)
                        };
                        return;
                    }
                    else if (saleLine.Regular_Price > 0)
                    {
                        // SL_Prop.Quantity = float.Parse((Conversion.Val(txtValue.Text) / SL_Prop.Regular_Price).ToString("#####0.000"));
                        _saleLineManager.SetQuantity(ref saleLine, float.Parse((Conversion.Val(propaneValue) / saleLine.Regular_Price).ToString("#####0.000")));
                        _saleLineManager.SetAmount(ref saleLine, (decimal)(Conversion.Val(propaneValue)));

                        //string temp_Policy_Name = "FUEL_UM";
                        //lbQuantity.Text = "(" + System.Convert.ToString(SL_Prop.Quantity) + System.Convert.ToString(modPolicy.GetPol(temp_Policy_Name, SL_Prop)) + ")";
                    }
                }
            }
            else //if change to 0
            {
                error = new ErrorMessage
                {
                    MessageStyle = new MessageStyle
                    {
                        Message     = "Please Set Amount/Volume for Prepay Sale",
                        MessageType = MessageType.Critical
                    }
                };
            }
        }
Пример #14
0
        /// <summary>
        /// Method to get volume value
        /// </summary>
        /// <param name="gradeId">Grade Id</param>
        /// <param name="pumpId">Pump Id</param>
        /// <param name="saleNumber">Sale number</param>
        /// <param name="tillNumber">Till number</param>
        /// <param name="registerNumber">Register number</param>
        /// <param name="propaneValue">Propane value</param>
        /// <param name="error">Error message</param>
        /// <returns>Volume value</returns>
        public string GetVolumeValue(int gradeId, int pumpId, int saleNumber, int tillNumber, byte registerNumber,
                                     decimal propaneValue, out ErrorMessage error)
        {
            string quantity = "";
            var    sale     = _saleManager.GetCurrentSale(saleNumber, tillNumber, registerNumber, UserCode, out error);
            var    offSet   = _policyManager.LoadStoreInfo().OffSet;

            if (!string.IsNullOrEmpty(error?.MessageStyle?.Message))
            {
                return(null);
            }

            var grades = CacheManager.GetPropaneGrades();

            if (grades == null)
            {
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 38, 76, null)
                };
                return(null);
            }
            var firstOrdDefault = grades.FirstOrDefault(p => p.Id == gradeId);

            if (firstOrdDefault == null)
            {
                error = new ErrorMessage
                {
                    MessageStyle = new MessageStyle
                    {
                        Message     = "Invalid Request",
                        MessageType = MessageType.Critical
                    }
                };
                return(null);
            }
            var pumps = _fuelPumpService.GetPumpsByPropaneGradeId(gradeId);

            if (pumps == null || !pumps.Any(p => p.Id == pumpId))
            {
                error = new ErrorMessage
                {
                    MessageStyle = new MessageStyle
                    {
                        Message     = "Invalid Request",
                        MessageType = MessageType.Critical
                    }
                };
                return(null);
            }

            var stockCode = firstOrdDefault.StockCode;


            if (sale.DeletePrepay)
            {
                // "There's no Pump set for " & Stock_Code(index) & ". Please set it in Fuel Control at first.", vbinformation+vbokonly
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 0, 1150, null, InformationOkMessageType)
                };
                return(null);
            }

            var slProp = new Sale_Line();

            _saleLineManager.SetPluCode(ref sale, ref slProp, stockCode, out error);
            slProp.GradeID = (byte)gradeId;
            if (slProp.Regular_Price == 0)
            {
                // "There's no price for " & Stock_Code(Index) & ". Please set it in BackOffice at first.", vbInformation + vbOKOnly
                //MsgBoxStyle temp_VbStyle = (int)MsgBoxStyle.Information + MsgBoxStyle.OkOnly;
                //Chaps_Main.DisplayMessage(this, (short)11, temp_VbStyle, Stock_Code[Index], (byte)0);
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 48, 11, stockCode, InformationOkMessageType)
                };
                return(null);
            }

            if (slProp.Regular_Price > 0)
            {
                quantity = (Conversion.Val(propaneValue) / slProp.Regular_Price).ToString("#####0.000");
            }
            return(quantity);
        }
Пример #15
0
        /// <summary>
        /// Method to update sale data
        /// </summary>
        /// <param name="sx">Sale</param>
        /// <param name="sp">Sale line</param>
        /// <param name="pennyAdj">Penny adjustment</param>
        /// <param name="change">Change</param>
        /// <param name="saleQuantity">Sale quantity</param>
        /// <param name="taxExempt">Tax exempt</param>
        /// <param name="saleAmount">Sale amount</param>
        /// <param name="unitPrice">Unit price</param>
        /// <param name="iPositionId">Position Id</param>
        /// <param name="orgPosition">Original position</param>
        /// <param name="iGradeId">Grade Id</param>
        /// <param name="fuelLoyalty">Fuel loyalty</param>
        /// <param name="newTotalAmount">Total amount</param>
        /// <param name="fullSwitch">Full switch</param>
        /// <param name="dataSource">Data source</param>
        public void UpdateSaleData(Sale sx, Sale_Line sp, decimal pennyAdj, double change, float saleQuantity,
                                   bool taxExempt, float saleAmount, float unitPrice, short iPositionId, short orgPosition, short iGradeId,
                                   bool fuelLoyalty, float newTotalAmount, bool fullSwitch, DataSource dataSource)
        {
            _connection = new SqlConnection(GetConnectionString(dataSource));
            if (_connection.State == ConnectionState.Closed)
            {
                _connection.Open();
            }


            //  -to use the object SP instead of SL( sometimes SL is changing and resetiing info in other section of code- screwing up prepy stock_code, dept etc in saleline for TE sales) to reset additional info in
            _dataTable = new DataTable();
            _adapter   = new SqlDataAdapter(" SELECT * FROM SaleHead " + " WHERE  SaleHead.Sale_No = "
                                            + Convert.ToString(sx.Sale_Num) + " and TILL=" + sx.TillNumber, _connection);
            _adapter.Fill(_dataTable);
            if (_dataTable.Rows.Count != 0)
            {
                var field = _dataTable.Rows[0];
                field["Penny_Adj"]   = pennyAdj;
                field["Sale_amt"]    = sx.Sale_Totals.Gross.ToString("##0.00");
                field["Change"]      = (Convert.ToDouble(field["Change"]) + change).ToString("##0.00");
                field["OverPayment"] = sx.OverPayment.ToString("##0.00");
                SqlCommandBuilder builder = new SqlCommandBuilder(_adapter);
                _adapter.UpdateCommand = builder.GetUpdateCommand();
                _adapter.Update(_dataTable);
            }


            _dataTable = new DataTable();
            _adapter   = new SqlDataAdapter(" SELECT * FROM SaleLine " + " WHERE SaleLine.Sale_No = "
                                            + Convert.ToString(sx.Sale_Num) + " " + " and Prepay=1", _connection);
            _adapter.Fill(_dataTable);
            if (_dataTable.Rows.Count != 0)
            {
                var field = _dataTable.Rows[0];
                field["Quantity"] = saleQuantity.ToString("##0.000");

                if (taxExempt && !string.IsNullOrEmpty(sx.TreatyNumber))
                {
                    field["Amount"] = saleAmount.ToString("##0.00");
                }
                else
                {
                    field["Amount"] = saleAmount.ToString("##0.00");
                    field["price"]  = unitPrice.ToString("##0.000");
                }


                if (iPositionId != orgPosition)
                {
                    field["PositionID"] = iPositionId;
                    field["GradeID"]    = iGradeId;
                    if (!string.IsNullOrEmpty(sp.Dept))
                    {
                        field["Dept"] = sp.Dept;
                    }
                    if (!string.IsNullOrEmpty(sp.Sub_Dept))
                    {
                        field["Sub_Dept"] = sp.Sub_Dept;
                    }
                    if (!string.IsNullOrEmpty(sp.Sub_Detail))
                    {
                        field["Sub_Detail"] = sp.Sub_Detail;
                    }
                    field["Stock_Code"] = sp.Stock_Code;
                    field["PLU_Code"]   = sp.PLU_Code;
                    field["Descript"]   = sp.Description;
                    field["price"]      = sp.price;
                    field["Reg_Price"]  = sp.Regular_Price;
                }

                field["Discount"] = sx.Sale_Lines[field["Line_Num"]].Line_Discount;
                if (fuelLoyalty && !string.IsNullOrEmpty(sx.Customer.GroupID) && sx.Customer.DiscountType == "$")
                {
                    field["Disc_Rate"] = field["Discount"];
                }

                field["Total_Amt"] = newTotalAmount;
                if (fullSwitch)
                {
                    field["Disc_adj"] = sp.Discount_Adjust;
                }
                else
                {
                    field["Disc_adj"] = 0;
                }
                SqlCommandBuilder builder = new SqlCommandBuilder(_adapter);
                _adapter.UpdateCommand = builder.GetUpdateCommand();
                _adapter.Update(_dataTable);



                Execute("Delete  From S_LineTax Where S_LineTax.Sale_No = " + Convert.ToString(sx.Sale_Num)
                        + " and Line_No=" + Convert.ToString(field["Line_Num"]), dataSource);

                _dataTable = new DataTable();
                _adapter   = new SqlDataAdapter("Select * From   S_LineTax  WHERE  S_LineTax.Sale_No = " + Convert.ToString(sx.Sale_Num), _connection);
                _adapter.Fill(_dataTable);

                if (sx.ApplyTaxes)
                {
                    if (sx.Sale_Lines.Count > 0)
                    {
                        foreach (Line_Tax tempLoopVarTx in sx.Sale_Lines[field["Line_Num"]].Line_Taxes)
                        {
                            var tx = tempLoopVarTx;
                            if (tx.Tax_Added_Amount != 0 | tx.Tax_Incl_Amount != 0)
                            {
                                var newTax = _dataTable.NewRow();

                                newTax["Till_Num"]            = sx.TillNumber;
                                newTax["sale_no"]             = sx.Sale_Num;
                                newTax["Line_No"]             = field["Line_Num"];
                                newTax["Tax_Name"]            = tx.Tax_Name;
                                newTax["Tax_Code"]            = tx.Tax_Code;
                                newTax["Tax_Rate"]            = tx.Tax_Rate;
                                newTax["Tax_Included"]        = string.Format("##0.00", tx.Tax_Included);
                                newTax["Tax_Added_Amount"]    = tx.Tax_Added_Amount.ToString("##0.00");
                                newTax["Tax_Included_Amount"] = tx.Tax_Incl_Amount.ToString("##0.00");
                                _dataTable.Rows.Add(newTax);
                                builder = new SqlCommandBuilder(_adapter);
                                _adapter.InsertCommand = builder.GetInsertCommand();
                                _adapter.Update(_dataTable);
                            }
                        }
                    }
                }
            }


            Execute("Delete  From S_SaleTax Where S_SaleTax.Sale_No = " + Convert.ToString(sx.Sale_Num) + " ", dataSource);
            _dataTable = new DataTable();
            _adapter   = new SqlDataAdapter("select * From S_SaleTax Where S_SaleTax.Sale_No = " + Convert.ToString(sx.Sale_Num), _connection);
            _adapter.Fill(_dataTable);

            foreach (Sale_Tax tempLoopVarSt in sx.Sale_Totals.Sale_Taxes)
            {
                var st = tempLoopVarSt;
                if (st.Taxable_Amount != 0 | st.Tax_Included_Amount != 0)
                {
                    var newTax = _dataTable.NewRow();
                    newTax["Till_Num"]            = sx.TillNumber;
                    newTax["sale_no"]             = sx.Sale_Num;
                    newTax["Tax_Name"]            = st.Tax_Name;
                    newTax["Tax_Code"]            = st.Tax_Code;
                    newTax["Tax_Rate"]            = st.Tax_Rate;
                    newTax["Taxable_Amount"]      = st.Taxable_Amount.ToString("##0.00");
                    newTax["Tax_Added_Amount"]    = st.Tax_Added_Amount.ToString("##0.00");
                    newTax["Tax_Included_Amount"] = st.Tax_Included_Amount.ToString("##0.00");
                    newTax["Tax_Included_Total"]  = st.Tax_Included_Total.ToString("##0.00");
                    _dataTable.Rows.Add(newTax);
                    var builder = new SqlCommandBuilder(_adapter);
                    _adapter.InsertCommand = builder.GetInsertCommand();
                    _adapter.Update(_dataTable);
                }
            }
            _adapter?.Dispose();
            _connection.Close();
        }
        /// <summary>
        /// Create Sale object
        /// </summary>
        /// <returns></returns>
        private Sale CreateSaleObjectTestData()
        {
            //dynamic flag=null;

            var sale = new Sale
            {
                Sale_Num      = 2,
                TillNumber    = 1,
                TotalTaxSaved = 10,
                ApplyTaxes    = false
            };
            var saleLineFirst = new Sale_Line
            {
                Line_Num         = 1,
                Till_Num         = 1,
                Sale_Num         = "2",
                price            = 100,
                Quantity         = 2,
                Stock_Code       = "12345",
                PLU_Code         = "12345",
                Net_Amount       = 90,
                ProductIsFuel    = true,
                TE_COLLECTTAX    = "GST",
                IncludeInLoyalty = true,
                PointsPerDollar  = 12,
                PointsPerUnit    = 5,
                Amount           = 3,
                Line_Discount    = 2,
                Discount_Type    = "%"


                                   //GC_REPT= SetPolicyforSaleLine(flag)
            };

            saleLineFirst.Line_Taxes.Add("GST", "A", 10, true, 2, 4, "");
            sale.Sale_Lines.AddLine(1, saleLineFirst, "");
            var saleLineSecond = new Sale_Line
            {
                Line_Num      = 2,
                Till_Num      = 1,
                Sale_Num      = "2",
                price         = 50,
                Quantity      = 2,
                Stock_Code    = "123",
                PLU_Code      = "123",
                Net_Amount    = 48,
                TE_COLLECTTAX = "PST",
                Discount_Type = "$"
            };

            saleLineSecond.Line_Taxes.Add("PST", "B", 2, true, 1, 1, "");

            sale.Sale_Lines.AddLine(2, saleLineFirst, "");
            sale.Sale_Totals = new Sale_Totals
            {
                SaleNumber       = 2,
                Total            = 150,
                Penny_Adj        = 10,
                Payment          = 140,
                Gross            = 160,
                Net              = 160,
                Invoice_Discount = 10
            };
            sale.Sale_Totals.Sale_Taxes.Add("GST", "A", 2, 160, 10, 20, 20, 1, 1, "GSTA");
            sale.Customer = new Customer
            {
                Code         = "A",
                Name         = "B",
                Price_Code   = 1,
                GroupID      = "1",
                DiscountName = "A",
                DiscountType = "C"
            };

            sale.Return_Reason = new Return_Reason
            {
                RType       = "D",
                Reason      = "Damaged",
                Description = "Damaged Product"
            };

            return(sale);
        }
Пример #17
0
        /// <summary>
        /// Method to add a line
        /// </summary>
        /// <param name="payPump">Pay at pump</param>
        /// <param name="user">User</param>
        /// <param name="oLine">Sale line</param>
        /// <param name="adjust">Adjust or not</param>
        /// <param name="tableAdjust">Table adjust or not</param>
        /// <param name="forReprint">For reprint or not</param>
        /// <returns>True or false</returns>
        public bool Add_a_Line(ref PayAtPump payPump, User user, Sale_Line oLine,
                               bool adjust = false, bool tableAdjust = true, bool forReprint = false)
        {
            bool returnValue = false;

            //

            if (oLine.Quantity == 0)
            {
                return(false);
            }

            returnValue = true;

            oLine = Compute_Taxes(ref payPump, oLine, (short)1);

            oLine.User = Convert.ToString(user.Code);
            if (payPump.Sale_Totals.Invoice_Discount != 0)
            {
                Sale_Discount(ref payPump, payPump.Sale_Totals.Invoice_Discount, payPump.Sale_Totals.Invoice_Discount_Type);
            }

            if (adjust)
            {
                if (Adjust_Lines(ref payPump, ref oLine, true))
                {
                    if (!forReprint)
                    {
                        if (oLine.FuelRebateEligible && oLine.FuelRebate > 0 && payPump.Customer.UseFuelRebate && payPump.Customer.UseFuelRebateDiscount)
                        {
                            _saleLineManager.ApplyFuelRebate(ref oLine);
                        }
                        else
                        {
                            if (oLine.ProductIsFuel && payPump.Customer.GroupID != "" && _policyManager.FuelLoyalty)
                            {
                                if (payPump.Customer.DiscountType == "%" || payPump.Customer.DiscountType == "$")
                                {
                                    _saleLineManager.ApplyFuelLoyalty(ref oLine, payPump.Customer.DiscountType, payPump.Customer.DiscountRate, payPump.Customer.DiscountName); //
                                }
                            }
                        }
                    }
                    payPump.Sale_Lines.AddLine((short)(payPump.Sale_Lines.Count + 1), oLine, "");
                }
                else
                {
                    returnValue = false;
                }
            }
            else
            {
                if (tableAdjust)
                {
                    if (!forReprint)
                    {
                        if (oLine.FuelRebateEligible && oLine.FuelRebate > 0 && payPump.Customer.UseFuelRebate && payPump.Customer.UseFuelRebateDiscount)
                        {
                            _saleLineManager.ApplyFuelRebate(ref oLine);
                        }
                        else
                        {
                            if (oLine.ProductIsFuel && payPump.Customer.GroupID != "" && _policyManager.FuelLoyalty)
                            {
                                if (payPump.Customer.DiscountType == "%" || payPump.Customer.DiscountType == "$")
                                {
                                    _saleLineManager.ApplyFuelLoyalty(ref oLine, payPump.Customer.DiscountType, payPump.Customer.DiscountRate, payPump.Customer.DiscountName);
                                }
                            }
                        }
                    }
                    payPump.Sale_Lines.AddLine((short)(payPump.Sale_Lines.Count + 1), oLine, "");
                }
            }

            if (!forReprint)
            {
                ReCompute_Coupon(ref payPump);
            }

            ReCompute_Totals(ref payPump);
            return(returnValue);
        }
Пример #18
0
        //   end

        //   to build optional data string
        /// <summary>
        /// Method ro build optiona data string
        /// </summary>
        /// <param name="sale">Sale</param>
        /// <param name="card">Credit card</param>
        /// <param name="tendCard">Tend card</param>
        public void Build_OptDataString(Sale sale, ref Credit_Card card, ref TenderCard tendCard)
        {
            if (sale.EMVVersion)
            {
                if (string.IsNullOrEmpty(card.OptDataProfileIDEMV))
                {
                    card.OptDataString = "";
                    return;
                }
                tendCard = new TenderCard {
                    OptDataProfileID = card.OptDataProfileIDEMV
                };
            }
            else
            {
                if (tendCard == null)
                {
                    card.OptDataString = "";
                    return;
                }
                if (string.IsNullOrEmpty(tendCard.OptDataProfileID))
                {
                    card.OptDataString = "";
                    return;
                }
            }

            string    strData   = "";
            Sale_Line sl        = default(Sale_Line);
            var       maxIdFuel = _cardService.GetMaxFuelId(tendCard.OptDataProfileID);

            var maxIdNonFuel = _cardService.GetMaxNonFuelId(tendCard.OptDataProfileID);

            var noFuelLines = _cardService.GetTotalOptionalData(tendCard.OptDataProfileID);

            var exemptDataCode = _cardService.GetOptionalDataCode(tendCard.OptDataProfileID);

            var strExemptDept = string.IsNullOrEmpty(exemptDataCode) ? "NOT DEFINED EXEMPTION" : exemptDataCode;

            var noNonFuelLines = _cardService.GetTotalNonFuelOptionalData(tendCard.OptDataProfileID);

            var arrFuelLines       = new short[1];
            var arrNonFuelLines    = new short[1];
            var arrExemptDeptLines = new short[1];

            foreach (Sale_Line saleLine in sale.Sale_Lines)
            {
                sl = saleLine;
                if (sl.ProductIsFuel)
                {
                    Array.Resize(ref arrFuelLines, arrFuelLines.Length - 1 + 1 + 1);
                    arrFuelLines[arrFuelLines.Length - 1] = sl.Line_Num;
                }
                else if (sl.Dept != strExemptDept)
                {
                    Array.Resize(ref arrNonFuelLines, arrNonFuelLines.Length - 1 + 1 + 1);
                    arrNonFuelLines[arrNonFuelLines.Length - 1] = sl.Line_Num;
                }
                else if (sl.Dept == strExemptDept)
                {
                    Array.Resize(ref arrExemptDeptLines, arrExemptDeptLines.Length - 1 + 1 + 1);
                    arrExemptDeptLines[arrExemptDeptLines.Length - 1] = sl.Line_Num;
                }
            }

            var   optionalDatas = _cardService.GetOptionalDatas(tendCard.OptDataProfileID);
            short fuelId        = 0;
            short nonFuelId     = 0;
            var   ubFuel        = (short)(arrFuelLines.Length - 1);
            var   ubNonFuel     = (short)(arrNonFuelLines.Length - 1);

            var maxFuel    = (short)modStringPad.MinVal(ubFuel, noFuelLines);
            var maxNonFuel = (short)modStringPad.MinVal(ubNonFuel, noNonFuelLines);

            foreach (var optionalData in optionalDatas)
            {
                var      taxCode  = optionalData.Code;
                var      strValue = "";
                decimal  total    = 0;
                var      id       = Convert.ToInt32(optionalData.ID);
                Line_Tax lt;
                switch (id)
                {
                case 20:     // Exemption Dept quantity
                    foreach (Sale_Line saleLine in sale.Sale_Lines)
                    {
                        sl = saleLine;
                        if (sl.Dept == strExemptDept)
                        {
                            total = total + (decimal)sl.Quantity;
                        }
                    }
                    strValue = total.ToString(CultureInfo.InvariantCulture);
                    break;

                case 22:     // Exemption Dept amount
                    foreach (Sale_Line saleLine in sale.Sale_Lines)
                    {
                        sl = saleLine;
                        if (sl.Dept == strExemptDept)
                        {
                            total = total + sl.Amount;
                        }
                    }
                    strValue = total.ToString(CultureInfo.InvariantCulture);
                    break;

                case 24:     //  Total Transaction Amount
                    strValue = sale.Sale_Totals.Gross.ToString(CultureInfo.InvariantCulture);
                    break;

                case 101:     //  Fuel Product Code
                    if (fuelId == 0)
                    {
                        fuelId++;
                    }
                    if (fuelId <= maxFuel)
                    {
                        strValue = _cardService.Get_ProductCode(tendCard.OptDataProfileID, sale.Sale_Lines[arrFuelLines[fuelId]].Stock_Code);
                    }
                    else
                    {
                        strValue = 0.ToString();
                    }
                    break;

                case 108:     //  Fuel Price
                    if (fuelId == 0)
                    {
                        fuelId++;
                    }
                    strValue = fuelId <= maxFuel ? sale.Sale_Lines[arrFuelLines[fuelId]].price.ToString(CultureInfo.InvariantCulture) : 0.ToString();
                    break;

                case 105:     //  Fuel Extended Amount
                    if (fuelId == 0)
                    {
                        fuelId++;
                    }
                    strValue = fuelId <= maxFuel ? sale.Sale_Lines[arrFuelLines[fuelId]].Amount.ToString(CultureInfo.InvariantCulture) : 0.ToString();
                    break;

                case 107:     //  Fuel Quantity
                    if (fuelId == 0)
                    {
                        fuelId++;
                    }
                    strValue = fuelId <= maxFuel ? sale.Sale_Lines[arrFuelLines[fuelId]].Quantity.ToString(CultureInfo.InvariantCulture) : 0.ToString();
                    break;

                case 109:     // Fuel GST/HST Amount and Fuel PST Amount (Tax Code is based on Code field in OptData table)
                case 110:
                    strValue = 0.ToString();
                    if (fuelId == 0)
                    {
                        fuelId++;
                    }
                    if (fuelId <= maxFuel)
                    {
                        foreach (Line_Tax lineTax in sale.Sale_Lines[arrFuelLines[fuelId]].Line_Taxes)
                        {
                            lt = lineTax;
                            if (lt.Tax_Name == taxCode)
                            {
                                strValue = lt.Tax_Incl_Amount.ToString(CultureInfo.InvariantCulture);
                                break;
                            }
                        }
                    }
                    else
                    {
                        strValue = 0.ToString();
                    }
                    break;

                case 209:     // Accumulated Fuel GST/HST Amount and Accumulated Fuel PST Amount (Tax Code is based on Code field in OptData table)
                case 210:
                    foreach (Sale_Line saleLine in sale.Sale_Lines)
                    {
                        sl = saleLine;
                        if (sl.ProductIsFuel)
                        {
                            foreach (Line_Tax lineTax in sl.Line_Taxes)
                            {
                                lt = lineTax;
                                if (lt.Tax_Code == taxCode)
                                {
                                    total = total + (decimal)lt.Tax_Incl_Amount;
                                }
                            }
                        }
                    }
                    strValue = total.ToString(CultureInfo.InvariantCulture);
                    break;

                case 301:     //  Non-Fuel Product Code
                    if (nonFuelId == 0)
                    {
                        nonFuelId++;
                    }
                    if (nonFuelId <= maxNonFuel)
                    {
                        strValue = _cardService.Get_ProductCode(tendCard.OptDataProfileID, sale.Sale_Lines[arrNonFuelLines[nonFuelId]].Stock_Code);
                    }
                    else
                    {
                        strValue = 0.ToString();
                    }
                    break;

                case 307:     //  Non-Fuel Quantity
                    if (nonFuelId == 0)
                    {
                        nonFuelId++;
                    }
                    if (nonFuelId <= maxNonFuel)
                    {
                        strValue = sale.Sale_Lines[arrNonFuelLines[nonFuelId]].Quantity.ToString(CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        strValue = 0.ToString();
                    }
                    break;

                case 305:     //  Non-Fuel Extended Amount
                    if (nonFuelId == 0)
                    {
                        nonFuelId++;
                    }
                    if (nonFuelId <= maxNonFuel)
                    {
                        strValue = sale.Sale_Lines[arrNonFuelLines[nonFuelId]].Amount.ToString(CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        strValue = 0.ToString();
                    }
                    break;

                case 314:     //  Non-Fuel Tax Description
                    if (nonFuelId == 0)
                    {
                        nonFuelId++;
                    }
                    if (nonFuelId <= maxNonFuel)
                    {
                        strValue = sale.Sale_Lines[arrNonFuelLines[nonFuelId]].Line_Taxes.Count > 0 ? sale.Sale_Lines[arrNonFuelLines[nonFuelId]].Line_Taxes[1].Tax_Name : 0.ToString();
                    }
                    else
                    {
                        strValue = 0.ToString();
                    }
                    break;

                case 405:     // Accumulated non-fuel extended amount
                    total = 0;
                    foreach (Sale_Line saleLine in sale.Sale_Lines)
                    {
                        sl = saleLine;
                        if (!sl.ProductIsFuel)
                        {
                            total = total + sl.Amount;
                        }
                    }
                    strValue = total.ToString(CultureInfo.InvariantCulture);
                    break;

                case 415:     // Accumulated Non-Fuel Tax Amount - includes exempted dept items
                    total = 0;
                    foreach (Sale_Line saleLine in sale.Sale_Lines)
                    {
                        sl = saleLine;
                        if (!sl.ProductIsFuel)
                        {
                            foreach (Line_Tax lineTax in sl.Line_Taxes)
                            {
                                lt    = lineTax;
                                total = total + (decimal)lt.Tax_Incl_Amount + (decimal)lt.Tax_Added_Amount;
                            }
                        }
                    }
                    strValue = total.ToString(CultureInfo.InvariantCulture);
                    break;

                case 121:     //  Non Fuel Product Code
                    if (nonFuelId == 0)
                    {
                        nonFuelId++;
                    }
                    if (nonFuelId <= maxNonFuel)
                    {
                        strValue = _cardService.Get_ProductCode(tendCard.OptDataProfileID, sale.Sale_Lines[arrNonFuelLines[nonFuelId]].Stock_Code);
                    }
                    else
                    {
                        strValue = 0.ToString();
                    }
                    break;

                case 102:     //  Fuel Description
                    if (fuelId == 0)
                    {
                        fuelId++;
                    }
                    if (fuelId <= maxFuel)
                    {
                        strValue = sl.Description;
                    }
                    else
                    {
                        strValue = 0.ToString();
                    }
                    break;

                case 103:     //  Fuel Service type
                    break;

                case 2:     // Merchant Terminal Prompt Data
                    var promptSeq = _cardService.GetPromptSeq(tendCard.OptDataProfileID);
                    if (promptSeq.HasValue)
                    {
                        strValue = card.CardPrompts[promptSeq.Value].PromptAnswer;
                    }
                    else
                    {
                        strValue = 0.ToString();
                    }
                    break;

                case 3:     // Card Prompt Code
                    promptSeq = _cardService.GetPromptSeq(tendCard.OptDataProfileID);
                    strValue  = promptSeq.HasValue ? card.CardPrompts[promptSeq.Value].PromptAnswer : 0.ToString();
                    break;

                default:
                    strValue = "";
                    break;
                }
                if (Convert.ToInt32(optionalData.ID) == maxIdFuel)
                {
                    fuelId++;
                }
                if (Convert.ToInt32(optionalData.ID) == maxIdNonFuel)
                {
                    nonFuelId++;
                }
                if (Convert.ToInt32(optionalData.ID) == 29)
                {
                    strData = Convert.ToString(strData + new string(Strings.Chr(Convert.ToInt32(string.IsNullOrEmpty(optionalData.Format) ? "0" : optionalData.Format)), optionalData.Length));
                }
                else
                {
                    strData = strData +
                              Convert.ToString(Format_Value(strValue,
                                                            (short)optionalData.Length, (short)optionalData.Decimals,
                                                            string.IsNullOrEmpty(optionalData.Alignment) ? "RIGHT" : optionalData.Alignment));
                }
            }
            card.OptDataString = strData;
            //todo:
            // modStringPad.WriteToLogFile("Optional data string is " + strData)
        }
        /// <summary>
        /// Method to get suspended sale
        /// </summary>
        /// <param name="tillNumber">Till number</param>
        /// <param name="saleNumber">Sale number</param>
        /// <param name="shareSusp">Share suspended sale</param>
        /// <returns>Sale</returns>
        public Sale GetSuspendedSale(int tillNumber, int saleNumber, bool shareSusp)
        {
            var dateStart = DateTime.Now;

            _performancelog.Debug($"Start,SuspendedSaleService,GetSuspendedSale,{string.Empty},{dateStart:hh.mm.ss.ffffff}");

            var       sale = new Sale();
            DataTable uHead;
            DataTable uLine;

            if (shareSusp)
            {
                uHead = GetRecords("select * from SusHead  WHERE SALE_NO=" + Convert.ToString(saleNumber), DataSource.CSCTills);
                uLine = GetRecords("select * from SusLine WHERE SALE_NO=" + Convert.ToString(saleNumber) + " ORDER BY SusLine.Line_Num ", DataSource.CSCTills);
            }
            else
            {
                uHead = GetRecords("select * from SusHead where TILL=" + tillNumber + " AND SALE_NO=" + Convert.ToString(saleNumber), DataSource.CSCTills);
                uLine = GetRecords("select * from SusLine where TILL_NUM=" + tillNumber + " AND SALE_NO=" + Convert.ToString(saleNumber) + " ORDER BY SusLine.Line_Num ", DataSource.CSCTills);
            }

            if (uHead.Rows.Count > 0)
            {
                sale.Sale_Num             = CommonUtility.GetIntergerValue(uHead.Rows[0]["SALE_NO"]);
                sale.TillNumber           = (byte)tillNumber;
                sale.Register             = CommonUtility.GetByteValue(uHead.Rows[0]["Regist"]);
                sale.Customer.Code        = CommonUtility.GetStringValue(uHead.Rows[0]["Client"]);
                sale.Sale_Type            = CommonUtility.GetStringValue(uHead.Rows[0]["T_type"]);
                sale.Return_Reason.Reason = CommonUtility.GetStringValue(uHead.Rows[0]["Reason"]);
                sale.Return_Reason.RType  = CommonUtility.GetStringValue(uHead.Rows[0]["Reason_Type"]);
                sale.Sale_Totals.Invoice_Discount_Type = CommonUtility.GetStringValue(uHead.Rows[0]["Disc_Type"]);
                sale.Sale_Totals.Invoice_Discount      = CommonUtility.GetDecimalValue(uHead.Rows[0]["Invc_Disc"]);
                sale.Sale_Totals.Discount_Percent      = CommonUtility.GetFloatValue(uHead.Rows[0]["Discount_Percent"]);
                sale.Void_Num = CommonUtility.GetIntergerValue(uHead.Rows[0]["Void_No"]);

                sale.Customer.LoyaltyCard    = CommonUtility.GetStringValue(uHead.Rows[0]["LoyaltyCard"]);
                sale.Customer.LoyaltyExpDate = CommonUtility.GetStringValue(uHead.Rows[0]["LoyaltyExpDate"]);
                sale.CouponID = CommonUtility.GetStringValue(uHead.Rows[0]["CouponID"]);
                sale.Upsell   = CommonUtility.GetBooleanValue(uHead.Rows[0]["Upsell"]);
                var ln = (short)0;

                foreach (DataRow row in uLine.Rows)
                {
                    ln++;
                    var sl = new Sale_Line
                    {
                        Sale_Num = CommonUtility.GetStringValue(row["sale_no"]),
                        Till_Num = sale.TillNumber
                    };
                    sale.Sale_Num       = CommonUtility.GetIntergerValue(row["sale_no"]);
                    sl.Line_Num         = ln;
                    sl.PLU_Code         = CommonUtility.GetStringValue(row["PLU_Code"]);
                    sl.Quantity         = CommonUtility.GetFloatValue(row["Quantity"]);
                    sl.price            = CommonUtility.GetDoubleValue(row["price"]);
                    sl.Amount           = CommonUtility.GetDecimalValue(row["Amount"]);
                    sl.Line_Discount    = CommonUtility.GetDoubleValue(row["Discount"]);
                    sl.Discount_Type    = CommonUtility.GetStringValue(row["Disc_Type"]);
                    sl.Discount_Adjust  = CommonUtility.GetDoubleValue(row["Disc_Adj"]);
                    sl.Discount_Code    = CommonUtility.GetStringValue(row["Disc_Code"]);
                    sl.Discount_Rate    = CommonUtility.GetFloatValue(row["Disc_Rate"]);
                    sl.DiscountName     = CommonUtility.GetStringValue(row["DiscountName"]);
                    sl.Price_Type       = CommonUtility.GetCharValue(row["Price_Type"]);
                    sl.Loyalty_Save     = CommonUtility.GetFloatValue(row["Loyl_Save"]);
                    sl.Units            = CommonUtility.GetStringValue(row["Units"]);
                    sl.Serial_No        = CommonUtility.GetStringValue(row["Serial_No"]);
                    sl.User             = CommonUtility.GetStringValue(row["User"]);
                    sl.pumpID           = CommonUtility.GetByteValue(row["pumpID"]);
                    sl.PositionID       = CommonUtility.GetByteValue(row["PositionID"]);
                    sl.GradeID          = CommonUtility.GetByteValue(row["GradeID"]);
                    sl.Gift_Certificate = CommonUtility.GetBooleanValue(row["Gift_Cert"]);
                    sl.Gift_Num         = CommonUtility.GetStringValue(row["GC_Num"]);
                    sale.TillNumber     = (byte)tillNumber;
                    sl.ManualFuel       = CommonUtility.GetBooleanValue(row["ManualFuel"]);

                    sl.IsTaxExemptItem = CommonUtility.GetBooleanValue(row["TaxExempt"]);

                    var strPromo = CommonUtility.GetStringValue(row["PromoID"]);
                    if (!string.IsNullOrEmpty(strPromo))
                    {
                        sl.PromoID = strPromo;
                    }
                    sl.Upsell       = CommonUtility.GetBooleanValue(row["Upsell"]);
                    sl.ScalableItem = CommonUtility.GetBooleanValue(row["ScalableItem"]);
                    DataTable uReason;
                    if (shareSusp)
                    {
                        uReason =
                            GetRecords(
                                "select * from SusReas  WHERE SALE_NO=" + Convert.ToString(saleNumber) +
                                " AND LINE_Num = " + ln + " ORDER BY SusReas.Line_Num", DataSource.CSCTills);
                    }
                    else
                    {
                        uReason =
                            GetRecords(
                                "select * from SusReas where TILL_NUM=" + tillNumber + " AND SALE_NO=" +
                                Convert.ToString(saleNumber) + " AND LINE_Num = " + ln +
                                " ORDER BY SusReas.Line_Num", DataSource.CSCTills);
                    }
                    var returnReason = new Return_Reason();

                    foreach (DataRow dataRow in uReason.Rows)
                    {
                        if (CommonUtility.GetStringValue(dataRow["Reason"]) != "" &
                            CommonUtility.GetStringValue(dataRow["Reason_Type"]) != "")
                        {
                            returnReason.Reason = CommonUtility.GetStringValue(dataRow["Reason"]);
                            returnReason.RType  = CommonUtility.GetStringValue(dataRow["Reason_Type"]);
                        }
                        sl.Return_Reasons.Add(returnReason.Reason, returnReason.RType, ln.ToString());
                    }
                    sale.Sale_Lines.AddLine(ln, sl, "");
                }
                _performancelog.Debug($"End,SuspendedSaleService,GetSuspendedSale,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");

                return(sale);
            }
            _performancelog.Debug($"End,SuspendedSaleService,GetSuspendedSale,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");

            return(new Sale());
        }
        /// <summary>
        /// Get Stock Price details
        /// </summary>
        /// <param name="stockCode">Stock code</param>
        /// <param name="tillNumber">Till number</param>
        /// <param name="saleNumber">Sale number</param>
        /// <param name="registerNumber">Register number</param>
        /// <param name="userCode">User code</param>
        /// <param name="error">Error message</param>
        /// <returns>Stock price</returns>
        public StockPriceCheck GetStockPriceDetails(string stockCode, int tillNumber, int saleNumber, byte registerNumber, string userCode, out ErrorMessage error)
        {
            StockPriceCheck result = new StockPriceCheck {
                SpecialPriceTypes = GetSpecialPriceTypes()
            };
            Sale_Line slPrices = new Sale_Line();
            string    txtCode  = stockCode;
            var       offSet   = _policyManager.LoadStoreInfo().OffSet;
            var       sale     = _saleManager.GetCurrentSale(saleNumber, tillNumber, registerNumber, userCode, out error);

            if (!string.IsNullOrEmpty(error.MessageStyle.Message))
            {
                return(null);
            }

            slPrices.PriceCheck = true;
            //Stock_Br.Requery '  - To have the latest numbers; form
            // SLPrices.PLU_Code = cStock;
            //updated PLU setter
            _saleLineManager.SetPluCode(ref sale, ref slPrices, stockCode, out error);

            //  - For alternate codes change to the real stock code
            stockCode = slPrices.Stock_Code;

            float tePrice = 0;

            if (!string.IsNullOrEmpty(slPrices.Stock_Code))
            {
                var pd = slPrices.PRICE_DEC;
                result.IsPriceVisible = true;
                if ((slPrices.Stock_Type == 'V' || slPrices.Stock_Type == 'O') && !slPrices.ProductIsFuel)
                {
                    result.IsAvQtyVisible    = true;
                    result.AvailableQuantity = slPrices.AvailItems.ToString(CultureInfo.InvariantCulture);
                }


                var productTaxExempt = _stockService.GetProductTaxExemptByProductCode(stockCode);
                if (productTaxExempt != null)
                {
                    result.TaxExemptPrice = GetTaxFreePrice(stockCode, (float)slPrices.Regular_Price, slPrices.ProductIsFuel, ref tePrice) ? tePrice.ToString(CultureInfo.InvariantCulture) : "";
                    //
                    //                    If Policy.TE_Type = "AITE" Then ' Shiny added the if condition we are tracking separate inventory for TE product only for AITE
                    if (_policyManager.TAX_EXEMPT && _policyManager.TAX_EXEMPT && (_policyManager.TE_Type == "AITE" || (_policyManager.TE_Type != "AITE" && _policyManager.TRACK_TEINV))) //  - Only for AITE we need to track inventory separately for TE products 'If TaxExempt Then
                    {
                        if ((slPrices.Stock_Type == 'V' || slPrices.Stock_Type == 'O') && !slPrices.ProductIsFuel)
                        {
                            result.TaxExemptAvailable = productTaxExempt.Available.ToString();
                        }
                    }
                    result.IsTaxExemptVisible = true;
                }
                else
                {
                    result.IsTaxExemptVisible = false;
                }

                result.StockCode        = stockCode;
                result.Description      = slPrices.Description;
                result.RegularPriceText = slPrices.Regular_Price.ToString("#,##0." + new string('0', pd));
                var intSpPrices = (short)slPrices.SP_Prices.Count;
                if (intSpPrices != 0)
                {
                    result.FromDate = (slPrices.SP_Prices[1].FromDate).ToString("MM/dd/yyyy");
                    if (slPrices.SP_Prices[1].ToDate != System.DateTime.FromOADate(0))
                    {
                        result.IsToDateVisible  = true;
                        result.ToDate           = (slPrices.SP_Prices[1].ToDate).ToString("MM/dd/yyyy");
                        result.IsEndDateChecked = false;
                    }
                    else
                    {
                        result.IsToDateVisible  = false;
                        result.IsEndDateChecked = true;
                    }
                    if (slPrices.Price_Units == '$')
                    {
                        result.IsPerDollarChecked = true;
                    }
                    else
                    {
                        result.IsPerPercentageChecked = true;
                    }
                }
                // Get the active vendor used to pick the prices and the price type
                result.VendorId = slPrices.Vendor;

                result.IsActiveVendorPrice = _stockService.IsActiveVendorPrice(stockCode, result.VendorId);
                var type = slPrices.Price_Units == '$' ? 1 : 2;

                SP_Price sp;
                switch (slPrices.Price_Type)
                {
                case 'R':
                    result.PriceTypeText = _resourceManager.CreateCaption(offSet, 3, 39, null, 2);     // "R - Regular Price"
                    break;

                case 'S':
                    result.SalePrice = new SalePriceType {
                        Columns = 1, SalePrices = new List <PriceGrid>()
                    };
                    result.PriceTypeText        = _resourceManager.CreateCaption(offSet, 3, 39, null, 3);// "S - Sale Price"
                    result.SalePrice.ColumnText = _resourceManager.CreateCaption(offSet, 4, 39, null, (short)type);
                    foreach (SP_Price tempLoopVarSp in slPrices.SP_Prices)
                    {
                        sp = tempLoopVarSp;
                        result.SalePrice.SalePrices.Add(new PriceGrid {
                            Column1 = sp.Price.ToString("#,##0." + new string('0', pd))
                        });
                    }
                    result.IsAddButtonVisible    = false;
                    result.IsRemoveButtonVisible = false;
                    break;

                case 'F':
                    result.FirstUnitPrice = new FirstUnitPriceType {
                        Columns = 2, FirstUnitPriceGrids = new List <PriceGrid>()
                    };
                    result.PriceTypeText              = _resourceManager.CreateCaption(offSet, 3, 39, null, 4);           // "F - First Unit Price"
                    result.FirstUnitPrice.ColumnText  = _resourceManager.GetResString(offSet, 230);                       // Quantity
                    result.FirstUnitPrice.ColumnText2 = _resourceManager.CreateCaption(offSet, 4, 39, null, (short)type); // Prices


                    foreach (SP_Price tempLoopVarSp in slPrices.SP_Prices)
                    {
                        sp = tempLoopVarSp;
                        result.FirstUnitPrice.FirstUnitPriceGrids.Add(new PriceGrid {
                            Column1 = sp.From_Quantity.ToString(CultureInfo.InvariantCulture), Column2 = sp.Price.ToString("#,##0." + new string('0', pd))
                        });
                    }
                    result.IsAddButtonVisible    = true;
                    result.IsRemoveButtonVisible = true;
                    break;

                case 'I':
                    result.IncrementalPrice = new IncrementalPriceType {
                        Columns = 3, IncrementalPriceGrids = new List <PriceGrid>()
                    };

                    result.PriceTypeText = _resourceManager.CreateCaption(offSet, 3, 39, null, 5);                          // "I - Incremental Price"
                    result.IncrementalPrice.ColumnText  = _resourceManager.CreateCaption(offSet, 4, 39, null, 3);           //From
                    result.IncrementalPrice.ColumnText2 = _resourceManager.CreateCaption(offSet, 4, 39, null, 4);           // To
                    result.IncrementalPrice.ColumnText3 = _resourceManager.CreateCaption(offSet, 4, 39, null, (short)type); // Prices


                    foreach (SP_Price tempLoopVarSp in slPrices.SP_Prices)
                    {
                        sp = tempLoopVarSp;
                        result.IncrementalPrice.IncrementalPriceGrids.Add(new PriceGrid {
                            Column1 = sp.From_Quantity.ToString(CultureInfo.InvariantCulture), Column2 = sp.To_Quantity.ToString(CultureInfo.InvariantCulture), Column3 = sp.Price.ToString("#,##0." + new string('0', pd))
                        });
                    }
                    result.IsAddButtonVisible    = true;
                    result.IsRemoveButtonVisible = true;
                    break;

                case 'X':
                    result.XForPrice = new XForPriceType {
                        Columns = 2, XForPriceGrids = new List <PriceGrid>()
                    };
                    result.PriceTypeText         = _resourceManager.CreateCaption(offSet, 3, 39, null, 6);           // "X - 'X' for Price"
                    result.XForPrice.ColumnText  = _resourceManager.GetResString(offSet, 230);                       // Quantity
                    result.XForPrice.ColumnText2 = _resourceManager.CreateCaption(offSet, 4, 39, null, (short)type); // Prices


                    foreach (SP_Price tempLoopVarSp in slPrices.SP_Prices)
                    {
                        sp = tempLoopVarSp;
                        result.XForPrice.XForPriceGrids.Add(new PriceGrid {
                            Column1 = sp.From_Quantity.ToString(CultureInfo.InvariantCulture), Column2 = sp.Price.ToString("#,##0." + new string('0', pd))
                        });
                    }
                    result.IsAddButtonVisible    = true;
                    result.IsRemoveButtonVisible = true;
                    break;
                }

                if (slPrices.Group_Price == false && _policyManager.U_CHGPRICE)
                {
                    result.IsChangePriceEnable = true;
                }
                else
                {
                    result.IsChangePriceEnable = false;
                }


                result.RegularPriceText = string.Format(result.RegularPriceText, "#,##0." + new string('0', pd));
                Register register = new Register();
                _mainManager.SetRegister(ref register, registerNumber);
                if (register.Customer_Display)
                {
                    result.CustomerDisplay = _mainManager.DisplayMsgLcd(register,
                                                                        _mainManager.FormatLcdString(register, result.Description,
                                                                                                     result.RegularPriceText), System.Convert.ToString(intSpPrices != 0 ?
                                                                                                                                                       _mainManager.FormatLcdString(register, _resourceManager.GetResString(offSet, 362), "") : ""));
                }

                //  - If  sell inactive product policy is true , even if the product is inactive we can sell the same. It is only for inactive  for Purchase and ordering)
                var days = _stockService.IsStockByDayAvailable(slPrices.Stock_Code);
                if (days.Count != 0)
                {
                    // processing
                    var dayOfWeek =
                        Convert.ToString(DateAndTime.Weekday(DateAndTime.Today));
                    if (!days.Contains(dayOfWeek))
                    {
                        slPrices.Active_StockCode = true;
                        // to avoid inactive stock item message in the main screen, saleLine item is not added to the sale anyway
                        slPrices.Active_DayOfWeek = false;
                        //PM to fix the issue related to Hot Buttons on August 27, 2012
                        var msg = _resourceManager.CreateMessage(offSet, 0, 8890, txtCode.Trim());
                        result.Message             = msg.Message;
                        result.IsChangePriceEnable = false;
                        // no Else required, if it is found the product can be sold today, continue processing
                    }
                }
                else
                {
                    slPrices.Active_DayOfWeek = true; //PM on August 27, 2012
                }
                if (!slPrices.Active_StockCode || (!slPrices.Active_StockCode && !_policyManager.Sell_Inactive))
                {
                    error.MessageStyle = _resourceManager.CreateMessage(offSet, 0, 1141, txtCode.Trim());
                    error.StatusCode   = HttpStatusCode.NotFound;
                    return(null);
                }

                if (slPrices.Price_Type == 'R')
                {
                    result.IsSpecialPricingVisible = false;
                    result.IsAddButtonVisible      = false;
                    result.IsRemoveButtonVisible   = false;
                    return(result);
                }
                result.IsSpecialPricingVisible = true;
            }
            else // not a valid stock code
            {
                //Chaps_Main.DisplayMessage(this, (short)91, temp_VbStyle2, txtCode.Trim(), (byte)0);
                error.MessageStyle = _resourceManager.CreateMessage(offSet, 39, 91, txtCode.Trim());
                error.StatusCode   = HttpStatusCode.NotFound;
                return(null);
            }
            return(result);
        }
Пример #21
0
        /// <summary>
        /// Get Sale lines
        /// </summary>
        /// <param name="saleNumber"></param>
        /// <param name="tillNumber"></param>
        /// <param name="userCode"></param>
        /// <returns>List of sale lines</returns>
        public List <Sale_Line> GetSaleLinesFromDbTemp(int saleNumber, int tillNumber, string userCode)
        {
            var dateStart = DateTime.Now;

            _performancelog.Debug($"Start,SaleLineService,GetSaleLinesFromDbTemp,{string.Empty},{DateTime.Now:hh.mm.ss.ffffff}");

            var saleLines = new List <Sale_Line>();

            var   rsLine   = GetRecords("SELECT * FROM   SaleLine WHERE  SaleLine.Sale_No = " + Convert.ToString(saleNumber) + " and   SaleLine.Till_Num = " + tillNumber + " ORDER BY SaleLine.Line_Num ", DataSource.CSCCurSale);
            var   rsReason = GetRecords("SELECT * FROM SLineReason WHERE SLineReason.Sale_No = " + Convert.ToString(saleNumber) + " and   SLineReason.Till_Num = " + tillNumber + " ORDER BY SLineReason.Line_Num", DataSource.CSCCurSale);
            short ln       = 0;

            foreach (DataRow lineFields in rsLine.Rows)
            {
                ln++;

                var saleLine = new Sale_Line {
                    PLU_Code = Convert.ToString(lineFields["PLU_Code"])
                };

                if (saleLine.ProductIsFuel && !saleLine.IsPropane)
                {
                    saleLine.Regular_Price = Convert.ToDouble(lineFields["price"]);
                }
                saleLine.Line_Num         = ln;
                saleLine.User             = userCode.ToUpper();
                saleLine.Quantity         = Convert.ToSingle(lineFields["Quantity"]);
                saleLine.pumpID           = Convert.ToByte(lineFields["pumpID"]);     // Nicolette
                saleLine.PositionID       = Convert.ToByte(lineFields["PositionID"]); // Nicolette
                saleLine.GradeID          = Convert.ToByte(lineFields["GradeID"]);    // Nicolette
                saleLine.Gift_Certificate = Convert.ToBoolean(lineFields["Gift_Cert"]);
                saleLine.Gift_Num         = Convert.ToString(lineFields["GC_Num"]);
                saleLine.Serial_No        = Convert.ToString(lineFields["Serial_No"]);
                saleLine.Stock_Code       = CommonUtility.GetStringValue(lineFields["Stock_Code"]);
                saleLine.Prepay           = Convert.ToBoolean(lineFields["Prepay"]);
                saleLine.Amount           = Convert.ToDecimal(lineFields["Amount"]);
                saleLine.PositionID       = Convert.ToByte(lineFields["PositionID"]);

                saleLine.ManualFuel = Convert.ToBoolean(lineFields["ManualFuel"]);

                saleLine.IsTaxExemptItem = Convert.ToBoolean(lineFields["TaxExempt"]);

                saleLine.PaidByCard =
                    Convert.ToByte(DBNull.Value.Equals(lineFields["PaidByCard"])
                        ? 0
                        : lineFields["PaidByCard"]);


                saleLine.Upsell =
                    Convert.ToBoolean(DBNull.Value.Equals(lineFields["Upsell"])
                        ? false
                        : lineFields["Upsell"]);

                saleLine.ScalableItem =
                    Convert.ToBoolean(DBNull.Value.Equals(lineFields["ScalableItem"])
                        ? false
                        : lineFields["ScalableItem"]);
                if (saleLine.Amount < 0)
                {
                    saleLine.No_Loading = true;
                }


                saleLine.No_Loading = true;
                // Set this property here, otherwise the stock item is a mess in POS screen and no others properties like description, dept, sub_dept, etc are set
                saleLine.price =
                    Convert.ToDouble(DBNull.Value.Equals(lineFields["price"])
                        ? 0
                        : lineFields["price"]);
                saleLine.TEPrice =
                    Convert.ToDouble(DBNull.Value.Equals(lineFields["TEPrice"])
                        ? 0
                        : lineFields["TEPrice"]);
                if (saleLine.ScalableItem)
                {
                    saleLine.Regular_Price = saleLine.price;
                }

                saleLine.Quantity =
                    Convert.ToSingle(DBNull.Value.Equals(lineFields["Quantity"])
                        ? 0
                        : lineFields["Quantity"]);
                saleLine.Amount =
                    Convert.ToDecimal(DBNull.Value.Equals(lineFields["Amount"])
                        ? 0
                        : lineFields["Amount"]);
                saleLine.Total_Amount =
                    Convert.ToDecimal(-1 *
                                      Convert.ToInt32(
                                          DBNull.Value.Equals(lineFields["TOTAL_AMT"])
                                                     ? 0
                                                     : lineFields["TOTAL_AMT"]));
                saleLine.Discount_Adjust = Convert.ToDouble(lineFields["Disc_Adj"]);
                saleLine.Line_Discount   = Convert.ToDouble(lineFields["Discount"]);
                saleLine.Discount_Type   = Convert.ToString(lineFields["Disc_Type"]);
                saleLine.Discount_Code   =
                    Convert.ToString(DBNull.Value.Equals(lineFields["Disc_Code"])
                        ? ""
                        : lineFields["Disc_Code"]);
                saleLine.Discount_Rate = Convert.ToSingle(lineFields["Disc_Rate"]);
                saleLine.DiscountName  =
                    Convert.ToString(DBNull.Value.Equals(lineFields["DiscountName"])
                        ? ""
                        : lineFields["DiscountName"]);
                saleLine.CardProfileID =
                    Convert.ToString(DBNull.Value.Equals(lineFields["CardProfileID"])
                        ? 0
                        : lineFields["CardProfileID"]);
                saleLine.No_Loading = false;
                // It has to be set back to false, otherwise if the user changes the qty or price in the POS screen after unsuspend, the amount will not be right
                // Nicolette end

                var strPromo =
                    Convert.ToString(DBNull.Value.Equals(lineFields["PromoID"])
                        ? ""
                        : lineFields["PromoID"]);
                if (strPromo.Length != 0)
                {
                    saleLine.PromoID = strPromo; //
                }

                if (rsReason != null)
                {
                    foreach (DataRow reasonFields in rsReason.Rows)
                    {
                        if ((int)reasonFields["Line_Num"] == ln)
                        {
                            saleLine.Return_Reasons.Add(Convert.ToString(reasonFields["Reason"]),
                                                        Convert.ToString(reasonFields["Reason_Type"]),
                                                        Convert.ToString(reasonFields["Reason_Type"]));
                        }
                    }
                }
                else
                {
                    saleLine.Return_Reasons = new Return_Reasons();
                }

                saleLines.Add(saleLine);
            }
            _performancelog.Debug($"End,SaleLineService,GetSaleLinesFromDbTemp,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");

            return(saleLines);
        }
Пример #22
0
        /// <summary>
        /// Gets the List of Sale Lines
        /// </summary>
        /// <param name="saleNumber">Sale number</param>
        /// <param name="tillNumber">Till number</param>
        /// <param name="saleDate">Sale date</param>
        /// <param name="discountType">Discount type</param>
        /// <param name="teType">Tax exempt type</param>
        /// <param name="taxExempt">Tax exempt name</param>
        /// <returns>List of sale lines</returns>
        public List <Sale_Line> GetSaleLineBySaleNumber(int saleNumber, int tillNumber, DateTime saleDate, string discountType, string teType, bool taxExempt)
        {
            var dateStart = DateTime.Now;

            _performancelog.Debug($"Start,ReturnSaleService,GetSaleLineBySaleNumber,{string.Empty},{dateStart:hh.mm.ss.ffffff}");

            List <Sale_Line> saleLines = new List <Sale_Line>();
            DataSource       db        = DataSource.CSCTrans;

            var strSqlHead = " SELECT * FROM   SaleHead Where  SaleHead.Sale_No = " + CommonUtility.GetStringValue(saleNumber) + " AND SaleHead.TILL = " + CommonUtility.GetStringValue(tillNumber) + " AND SaleHead.T_Type IN ( \'SALE\' ,\'REFUND\', \'RUNAWAY\',\'PUMPTEST\' ) and SaleHead.SALE_AMT <> 0 ";
            var strSqlLine = " SELECT * FROM   SaleLine Where SaleLine.Sale_No = " + CommonUtility.GetStringValue(saleNumber) + " AND SaleLine.TILL_NUM = " + CommonUtility.GetStringValue(tillNumber) + "ORDER BY SaleLine.Line_Num ";

            var rsHead = GetRecords(strSqlHead, DataSource.CSCTrans);
            var rsLine = GetRecords(strSqlLine, DataSource.CSCTrans);

            // If SaleNo is not found in Trans.mdb database, then
            // look for this SaleNo in all active Tills
            if (rsHead == null || rsHead.Rows.Count == 0)
            {
                rsHead = GetRecords(strSqlHead, DataSource.CSCTills);
                rsLine = GetRecords(strSqlLine, DataSource.CSCTills);
                // If sale number is found exit for do and use this recordset
                if (rsHead != null && rsHead.Rows.Count != 0)
                {
                    db = DataSource.CSCTills;
                }
            }
            else
            {
                db = DataSource.CSCTrans;
            }
            foreach (DataRow rsLineFields in rsLine.Rows)
            {
                var saleLine = new Sale_Line
                {
                    No_Loading    = true,
                    Stock_Code    = CommonUtility.GetStringValue(rsLineFields["Stock_Code"]),
                    PLU_Code      = CommonUtility.GetStringValue(rsLineFields["PLU_Code"]),
                    Line_Num      = CommonUtility.GetShortValue(rsLineFields["Line_Num"]),
                    Price_Type    = CommonUtility.GetCharValue(rsLineFields["Price_Type"]),
                    Dept          = CommonUtility.GetStringValue(rsLineFields["Dept"]),
                    Sub_Detail    = CommonUtility.GetStringValue(rsLineFields["Sub_Detail"]),
                    Sub_Dept      = CommonUtility.GetStringValue(rsLineFields["Sub_Dept"]),
                    Quantity      = CommonUtility.GetFloatValue(rsLineFields["Quantity"]) * -1,
                    price         = CommonUtility.GetDoubleValue(rsLineFields["price"]),
                    Regular_Price = CommonUtility.GetDoubleValue(rsLineFields["Reg_Price"]),
                    Cost          = CommonUtility.GetDoubleValue(rsLineFields["Cost"]),
                    Amount        = CommonUtility.GetDecimalValue(rsLineFields["Amount"]) * -1,
                    Total_Amount  = CommonUtility.GetDecimalValue(rsLineFields["Total_Amt"]) * -1
                };

                if (!(teType == "QITE" && discountType == "D"))
                {
                    saleLine.Line_Discount = CommonUtility.GetDoubleValue(rsLineFields["Discount"]) * -1;
                }
                saleLine.Discount_Type = CommonUtility.GetStringValue(rsLineFields["Disc_Type"]);
                saleLine.Discount_Code = CommonUtility.GetStringValue(rsLineFields["Disc_Code"]);
                if (!(teType == "QITE" && discountType == "D"))
                {
                    SetDiscountRate(ref saleLine, CommonUtility.GetFloatValue(rsLineFields["Disc_Rate"]));
                }
                saleLine.Associate_Amount = CommonUtility.GetDecimalValue(rsLineFields["Assoc_Amt"]);
                saleLine.Description      = CommonUtility.GetStringValue(rsLineFields["Descript"]);
                saleLine.Loyalty_Save     = CommonUtility.GetFloatValue(rsLineFields["Loyl_Save"]);
                saleLine.Units            = CommonUtility.GetStringValue(rsLineFields["Units"]);
                saleLine.Serial_No        = CommonUtility.GetStringValue(rsLineFields["Serial_No"]);

                saleLine.Stock_Code = CommonUtility.GetStringValue(rsLineFields["Stock_Code"]);
                saleLine.pumpID     = CommonUtility.GetByteValue(rsLineFields["pumpID"]);
                saleLine.PositionID = CommonUtility.GetByteValue(rsLineFields["PositionID"]);

                saleLine.GradeID = CommonUtility.GetByteValue(rsLineFields["GradeID"]);

                saleLine.Prepay = CommonUtility.GetBooleanValue(rsLineFields["Prepay"]);

                saleLine.ManualFuel = CommonUtility.GetBooleanValue(rsLineFields["ManualFuel"]);

                saleLine.IsTaxExemptItem = CommonUtility.GetBooleanValue(rsLineFields["TaxExempt"]);

                saleLine.Gift_Num = CommonUtility.GetStringValue(rsLineFields["GC_Num"]);

                saleLine.FuelRebateEligible = CommonUtility.GetBooleanValue(rsLineFields["FuelRebateUsed"]);

                saleLine.FuelRebate = CommonUtility.GetDecimalValue(rsLineFields["RebateDiscount"]);

                saleLine.EligibleTaxEx = CommonUtility.GetBooleanValue(rsLineFields["ElgTaxExemption"]);

                saleLine.CarwashCode = CommonUtility.GetStringValue(rsLineFields["CarwashCode"]);

                if (saleLine.CarwashCode != "")
                {
                    saleLine.IsCarwashProduct = true;
                }

                if (saleLine.IsTaxExemptItem)
                {
                    if (teType == "SITE")
                    {
                        var rsPurchaseItem = GetRecords(
                            "select * from PurchaseItem Where Sale_No=" + CommonUtility.GetStringValue(saleNumber) +
                            " AND Line_No=" + CommonUtility.GetStringValue(saleLine.Line_Num), db);
                        if (rsPurchaseItem != null && rsPurchaseItem.Rows.Count != 0)
                        {
                            var rsPurchaseItemFields = rsPurchaseItem.Rows[0];

                            saleLine.OriginalPrice =
                                CommonUtility.GetFloatValue(rsPurchaseItemFields["OriginalPrice"]);
                            saleLine.TaxInclPrice = CommonUtility.GetFloatValue(rsPurchaseItemFields["Amount"]);
                        }
                        else
                        {
                            saleLine.OriginalPrice = (float)saleLine.price;
                            saleLine.TaxInclPrice  = (float)(-1 * saleLine.Amount);
                        }
                    }
                    else
                    {
                        var rsTeSaleLine = GetRecords(
                            "select * from TaxExemptSaleLine Where SALE_NO=" +
                            CommonUtility.GetStringValue(saleNumber) + " AND LINE_NUM=" +
                            CommonUtility.GetStringValue(saleLine.Line_Num), db);

                        if (rsTeSaleLine != null && rsTeSaleLine.Rows.Count != 0)
                        {
                            var rsTeSaleLineFields = rsTeSaleLine.Rows[0];

                            saleLine.OriginalPrice =
                                CommonUtility.GetFloatValue(rsTeSaleLineFields["OriginalPrice"]);

                            saleLine.TaxInclPrice =
                                CommonUtility.GetFloatValue(-1 *
                                                            CommonUtility.GetIntergerValue(
                                                                rsTeSaleLineFields["TaxIncludedAmount"]));
                        }
                        else
                        {
                            saleLine.OriginalPrice = (float)saleLine.price;
                            saleLine.TaxInclPrice  = (float)(-1 * saleLine.Amount);
                        }

                        saleLine.IsTaxExemptItem = false;
                    }
                }


                string strPromo = CommonUtility.GetStringValue(rsLineFields["PromoID"]);
                if (strPromo.Length != 0)
                {
                    saleLine.PromoID = strPromo;
                }


                saleLine.Line_Taxes = null;
                var rsLineTax =
                    GetRecords(
                        "Select * From   S_LineTax  WHERE  S_LineTax.Sale_No = " +
                        CommonUtility.GetStringValue(saleNumber) + " AND  S_LineTax.Line_No = " +
                        CommonUtility.GetStringValue(rsLineFields["Line_Num"]) + " " +
                        "Order By S_LineTax.Tax_Name ", db);
                if (rsLineTax == null || rsLineTax.Rows.Count == 0)
                {
                    if (taxExempt && (teType == "AITE" || teType == "QITE"))
                    {
                        rsLineTax =
                            GetRecords(
                                "Select * From   TaxCreditLine  WHERE  TaxCreditLine.Sale_No = " +
                                CommonUtility.GetStringValue(saleNumber) + " AND  TaxCreditLine.Line_No = " +
                                CommonUtility.GetStringValue(rsLineFields["Line_Num"]) + " " +
                                "Order By TaxCreditLine.Tax_Name ", db);
                        if (!saleLine.IsTaxExemptItem && rsLineTax.Rows.Count != 0)
                        {
                        }
                    }
                }

                foreach (DataRow rsLineTaxFields in rsLineTax.Rows)
                {
                    saleLine.Line_Taxes.Add(CommonUtility.GetStringValue(rsLineTaxFields["Tax_Name"]),
                                            CommonUtility.GetStringValue(rsLineTaxFields["Tax_Code"]),
                                            CommonUtility.GetFloatValue(rsLineTaxFields["Tax_Rate"]),
                                            CommonUtility.GetBooleanValue(rsLineTaxFields["Tax_Included"]),
                                            CommonUtility.GetFloatValue(rsLineTaxFields["Tax_Rebate_Rate"]),
                                            CommonUtility.GetDecimalValue(rsLineTaxFields["Tax_Rebate"]), "");
                }

                // Similarly, pick up the charges associated with the line.
                saleLine.Charges = null;
                var rsLineChg =
                    GetRecords(
                        "Select *  FROM   SaleChg  WHERE  SaleChg.Sale_No = " +
                        CommonUtility.GetStringValue(saleNumber) + " AND SaleChg.Line_No = " +
                        CommonUtility.GetStringValue(rsLineFields["Line_Num"]) + " Order By SaleChg.As_Code ",
                        db);
                foreach (DataRow linChrField in rsLineChg.Rows)
                {
                    var rsLcTax =
                        GetRecords(
                            "Select *  FROM   ChargeTax  WHERE  ChargeTax.Sale_No = " +
                            CommonUtility.GetStringValue(saleNumber) + " AND ChargeTax.Line_No = " +
                            CommonUtility.GetStringValue(rsLineFields["Line_Num"]) + " AND ChargeTax.As_Code = \'" +
                            CommonUtility.GetStringValue(linChrField["As_Code"]) + "\' ", db);
                    // Find any taxes that applied to those charges.
                    var lct = new Charge_Taxes();
                    foreach (DataRow rsLcTaxFields in rsLcTax.Rows)
                    {
                        lct.Add(CommonUtility.GetStringValue(rsLcTaxFields["Tax_Name"]),
                                CommonUtility.GetStringValue(rsLcTaxFields["Tax_Code"]),
                                CommonUtility.GetFloatValue(rsLcTaxFields["Tax_Rate"]),
                                CommonUtility.GetBooleanValue(rsLcTaxFields["Tax_Included"]), "");
                    }

                    saleLine.Charges.Add(CommonUtility.GetStringValue(linChrField["As_Code"]),
                                         CommonUtility.GetStringValue(linChrField["Description"]),
                                         CommonUtility.GetFloatValue(linChrField["price"]), lct, "");
                }


                saleLine.Line_Kits = GetLineKits(saleNumber,
                                                 CommonUtility.GetIntergerValue(rsLineFields["Line_Num"]), db);
                saleLines.Add(saleLine);
            }
            _performancelog.Debug($"End,ReturnSaleService,GetSaleLineBySaleNumber,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");

            return(saleLines);
        }
Пример #23
0
        /// <summary>
        /// Method to add propane sale
        /// </summary>
        /// <param name="gradeId">Grade Id</param>
        /// <param name="pumpId">Pump Id</param>
        /// <param name="saleNumber">Sale number</param>
        /// <param name="tillNumber">Till number</param>
        /// <param name="registerNumber">Register number</param>
        /// <param name="isAmount">Is amount</param>
        /// <param name="propaneValue">Propane value</param>
        /// <param name="error">Error message</param>
        /// <returns>Sale</returns>
        public Sale AddPropaneSale(int gradeId, int pumpId, int saleNumber, int tillNumber, byte registerNumber,
                                   bool isAmount, decimal propaneValue, out ErrorMessage error)
        {
            var sale   = _saleManager.GetCurrentSale(saleNumber, tillNumber, registerNumber, UserCode, out error);
            var offSet = _policyManager.LoadStoreInfo().OffSet;

            if (!string.IsNullOrEmpty(error?.MessageStyle?.Message))
            {
                return(null);
            }

            var grades = CacheManager.GetPropaneGrades();

            if (grades == null)
            {
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 38, 76, null)
                };
                return(null);
            }
            var firstOrdDefault = grades.FirstOrDefault(p => p.Id == gradeId);

            if (firstOrdDefault == null)
            {
                error = new ErrorMessage
                {
                    MessageStyle = new MessageStyle
                    {
                        Message     = "Invalid Request",
                        MessageType = MessageType.Critical
                    }
                };
                return(null);
            }
            var pumps = _fuelPumpService.GetPumpsByPropaneGradeId(gradeId);

            if (pumps == null || !pumps.Any(p => p.Id == pumpId))
            {
                error = new ErrorMessage
                {
                    MessageStyle = new MessageStyle
                    {
                        Message     = "Invalid Request",
                        MessageType = MessageType.Critical
                    }
                };
                return(null);
            }

            var stockCode = firstOrdDefault.StockCode;


            if (sale.DeletePrepay)
            {
                // "There's no Pump set for " & Stock_Code(index) & ". Please set it in Fuel Control at first.", vbinformation+vbokonly
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 0, 1150, null, InformationOkMessageType)
                };
                return(null);
            }

            var slProp = new Sale_Line();

            _saleLineManager.SetPluCode(ref sale, ref slProp, stockCode, out error);
            slProp.GradeID = (byte)gradeId;
            if (slProp.Regular_Price == 0)
            {
                // "There's no price for " & Stock_Code(Index) & ". Please set it in BackOffice at first.", vbInformation + vbOKOnly
                //MsgBoxStyle temp_VbStyle = (int)MsgBoxStyle.Information + MsgBoxStyle.OkOnly;
                //Chaps_Main.DisplayMessage(this, (short)11, temp_VbStyle, Stock_Code[Index], (byte)0);
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 48, 11, stockCode, InformationOkMessageType)
                };
                return(null);
            }

            slProp.pumpID     = (byte)pumpId;
            slProp.PositionID = (byte)_fuelPumpService.GetPositionId(pumpId, gradeId);

            SetQuantity(ref slProp, isAmount, propaneValue, out error);

            if (!string.IsNullOrEmpty(error?.MessageStyle?.Message))
            {
                return(null);
            }

            if (_policyManager.USE_CUST)
            {
                if (_policyManager.USE_LOYALTY && Strings.UCase(System.Convert.ToString(_policyManager.LOYAL_TYPE)) == "PRICES" && sale.Customer.Loyalty_Code.Length > 0 && sale.Customer.CL_Status == "A" && (!slProp.LOY_EXCLUDE))
                {
                    var loyalPricecode = System.Convert.ToInt16(_policyManager.LOYAL_PRICE);
                    if (loyalPricecode > 0)
                    {
                        _saleLineManager.SetPriceNumber(ref slProp, loyalPricecode);
                    }
                    else
                    {
                        _saleLineManager.SetPriceNumber(ref slProp, sale.Customer.Price_Code != 0 ? sale.Customer.Price_Code : (short)1);
                    }
                }
                else
                {
                    _saleLineManager.SetPriceNumber(ref slProp, sale.Customer.Price_Code != 0 ? sale.Customer.Price_Code : (short)1);
                }
            }
            else
            {
                //SL_Prop.Price_Number = (short)1;
                _saleLineManager.SetPriceNumber(ref slProp, (short)1);
            }
            _saleManager.Add_a_Line(ref sale, slProp, UserCode, sale.TillNumber, out error, true);

            CacheManager.AddCurrentSaleForTill(tillNumber, saleNumber, sale);
            return(sale);
        }
Пример #24
0
        /// <summary>
        /// Method to compute taxes
        /// </summary>
        /// <param name="payPump">Pay at pump</param>
        /// <param name="oLine">Sale line</param>
        /// <param name="nSign">Signature</param>
        /// <returns>Sale lineS</returns>
        private Sale_Line Compute_Taxes(ref PayAtPump payPump, Sale_Line oLine, short nSign)
        {
            Sale_Tax stx;
            Line_Tax ltx;
            double   inclTaxes        = 0;
            double   netTaxable       = 0;
            var      key              = "";
            var      boolComputeTaxes = false;
            double   totalInclRates   = 0;
            var      strKeyLast       = "";
            double   prevTax          = 0;


            boolComputeTaxes = Convert.ToBoolean(_policyManager.TAX_COMP);

            netTaxable = (double)oLine.Net_Amount;

            foreach (Line_Tax tempLoopVarLtx in oLine.Line_Taxes)
            {
                ltx = tempLoopVarLtx;
                if (ltx.Tax_Included)
                {
                    key = ltx.Tax_Name + ltx.Tax_Code;
                    stx = payPump.Sale_Totals.Sale_Taxes[key];
                    if (boolComputeTaxes)
                    {
                        if (totalInclRates == 0)
                        {
                            totalInclRates = totalInclRates + stx.Tax_Rate;
                        }
                        else
                        {
                            totalInclRates = totalInclRates + stx.Tax_Rate + totalInclRates * stx.Tax_Rate / 100;
                        }
                    }
                    else
                    {
                        totalInclRates = totalInclRates + stx.Tax_Rate;
                    }
                    strKeyLast = key;
                }
            }

            if (totalInclRates != 0)
            {
                inclTaxes = Math.Round(netTaxable * (totalInclRates / 100) / (1 + totalInclRates / 100), 2);
            }

            // Apply Taxes to the Sale Items
            foreach (Line_Tax tempLoopVarLtx in oLine.Line_Taxes)
            {
                ltx = tempLoopVarLtx;
                key = ltx.Tax_Name + ltx.Tax_Code;
                stx = payPump.Sale_Totals.Sale_Taxes[key];
                if (ltx.Tax_Included)
                {
                    ltx.Tax_Incl_Total = (float)(oLine.Net_Amount * nSign);
                    if (key == strKeyLast)
                    {
                        if (boolComputeTaxes)
                        {
                            ltx.Tax_Incl_Amount = (float)(Math.Round(((netTaxable - inclTaxes + prevTax) * stx.Tax_Rate / 100) * nSign, 2));
                        }
                        else
                        {
                            ltx.Tax_Incl_Amount = (float)(inclTaxes - prevTax);
                        }
                    }
                    else
                    {
                        if (boolComputeTaxes)
                        {
                            ltx.Tax_Incl_Amount = (float)(Math.Round(((netTaxable - inclTaxes) * stx.Tax_Rate / 100) * nSign, 2));
                        }
                        else
                        {
                            ltx.Tax_Incl_Amount = (float)(Math.Round((inclTaxes * stx.Tax_Rate / totalInclRates) * nSign, 2));
                        }
                        prevTax = prevTax + ltx.Tax_Incl_Amount;
                    }

                    stx.Tax_Included_Total  = stx.Tax_Included_Total + (decimal)ltx.Tax_Incl_Total;
                    stx.Tax_Included_Amount = stx.Tax_Included_Amount + (decimal)ltx.Tax_Incl_Amount;

                    if (boolComputeTaxes)
                    {
                        if (key == strKeyLast)
                        {
                            stx.Taxable_Amt_ForIncluded = (decimal)(netTaxable - inclTaxes + prevTax);
                        }
                        else
                        {
                            stx.Taxable_Amt_ForIncluded = (decimal)(netTaxable - inclTaxes);
                        }
                    }
                }
                else
                {
                    ltx.Taxable_Amount   = (float)(netTaxable * nSign);
                    ltx.Tax_Added_Amount = (float)(Math.Round(ltx.Taxable_Amount * ltx.Tax_Rate / 100, 2));                   // Nicolette added to record taxes for each line in a sale
                    stx.Taxable_Amount   = (decimal)(Math.Round((double)stx.Taxable_Amount + (double)netTaxable * nSign, 2)); //
                    stx.Tax_Added_Amount = (decimal)(Math.Round((double)((float)stx.Taxable_Amount * stx.Tax_Rate / 100), 2));
                    if (boolComputeTaxes)
                    {
                        netTaxable = netTaxable + ltx.Tax_Added_Amount;
                    }
                }
            }


            payPump.Sale_Totals.Net = payPump.Sale_Totals.Net + oLine.Net_Amount * nSign;
            var returnValue = oLine;

            return(returnValue);
        }
Пример #25
0
        /// <summary>
        /// Method to adjust lines
        /// </summary>
        /// <param name="payPump">Pay at pump</param>
        /// <param name="thisLine">Sale line</param>
        /// <param name="newLine">New line</param>
        /// <param name="remove">Remove or not</param>
        /// <returns>True or false</returns>
        internal bool Adjust_Lines(ref PayAtPump payPump, ref Sale_Line thisLine, bool
                                   newLine, bool remove = false)
        {
            bool returnValue = false;

            // Get the pricing for that many products
            float[,] spr = null;
            Sale_Line ss       = default(Sale_Line);
            float     saleQty  = 0;
            short     saleLin  = 0;
            Sale_Line New_Line = default(Sale_Line);
            short     n        = 0;
            short     m;
            short     nDel = 0;
            bool      Fd;
            bool      Can_Combine  = false;
            bool      Combined     = false;
            short     Lines_Needed = 0;
            short     ns;
            short     nL;
            bool      Combine_Policy = false;



            Combine_Policy = Convert.ToBoolean(_policyManager.COMBINE_LINE);


            returnValue = true;

            // If the incoming line is New then include it's quantity in the count. If it isn't
            // then the quantity will be included in the following loop.
            saleQty = Convert.ToSingle(newLine ? thisLine.Quantity : 0);
            if (remove)
            {
                saleQty = Convert.ToSingle(-thisLine.Quantity);
            }
            saleLin = Convert.ToInt16(newLine ? 1 : 0);

            // Compute the total quantity of the item in the sale and the number of lines
            // on which it appears.
            foreach (Sale_Line tempLoopVarSLine in payPump.Sale_Lines)
            {
                var sLine = tempLoopVarSLine;
                if (thisLine.Stock_Code != sLine.Stock_Code)
                {
                    continue;
                }
                saleQty = saleQty + sLine.Quantity;
                saleLin++;
            }
            ns = (short)(saleQty < 0 ? -1 : 1);

            // Call 'PQuantity' to build the array of prices and quantities to be used for this
            // item.


            spr     = PQuantity(thisLine, saleQty);
            saleQty = Math.Abs((short)saleQty);

            if (thisLine.Price_Number > 1)
            {
                // If Price_Number > 1 then it is NOT regular price.
                if (newLine)
                {
                    foreach (Sale_Line tempLoopVarSs in payPump.Sale_Lines)
                    {
                        ss = tempLoopVarSs;
                        if (ss.Stock_Code == thisLine.Stock_Code)
                        {
                            string temp_Policy_Name = "COMBINE_LINE";
                            Can_Combine = Combine_Policy && _policyManager.GetPol(temp_Policy_Name, thisLine) && (!thisLine.Gift_Certificate) && ss.price == thisLine.price & ss.Quantity > 0 & thisLine.Quantity > 0 & ss.Discount_Rate == thisLine.Discount_Rate && ss.Serial_No == "" && thisLine.Serial_No == "" && ss.Discount_Type == thisLine.Discount_Type;


                            if (!Can_Combine)
                            {
                                continue;
                            }
                            ss.Quantity = ss.Quantity + thisLine.Quantity;
                            ss.Amount   = (decimal)(ss.Quantity * ss.price);
                            returnValue = false;
                            break;
                        }
                    }
                }
                else
                {
                    thisLine.Amount = (decimal)(thisLine.Quantity * thisLine.price);
                }
            }
            else
            {
                // Price_Code = 1 means that this is based on regular price.
                if (thisLine.Price_Type == 'R')
                {
                    if (newLine)
                    {
                        foreach (Sale_Line tempLoopVarSs in payPump.Sale_Lines)
                        {
                            ss = tempLoopVarSs;
                            if (ss.Stock_Code == thisLine.Stock_Code)
                            {
                                var temp_Policy_Name2 = "COMBINE_LINE";
                                Can_Combine = Combine_Policy && _policyManager.GetPol(temp_Policy_Name2, thisLine) && (!thisLine.Gift_Certificate) && ss.price == thisLine.price & ss.Quantity > 0 & thisLine.Quantity > 0 & ss.Discount_Rate == thisLine.Discount_Rate && ss.Serial_No == "" && thisLine.Serial_No == "" && ss.Discount_Type == thisLine.Discount_Type;


                                if (!Can_Combine)
                                {
                                    continue;
                                }
                                ss.Quantity = ss.Quantity + thisLine.Quantity;
                                ss.Amount   = (decimal)(ss.Quantity * ss.price);
                                returnValue = false;
                                break;
                            }
                        }
                    }
                    else
                    {
                        thisLine.Amount = (decimal)(thisLine.Quantity * thisLine.price);
                    }
                }
                else if (thisLine.Price_Type == 'F')
                {
                    // "F" - First Unit Pricing
                    if (newLine)
                    {
                        foreach (Sale_Line tempLoopVarSs in payPump.Sale_Lines)
                        {
                            ss = tempLoopVarSs;
                            // Assign the computed prices to each item in the sale.
                            if (ss.Stock_Code == thisLine.Stock_Code)
                            {
                                Line_Price(ref payPump, ref ss, (double)(Convert.ToDecimal(spr[1, 2])));
                                ss.Amount = (decimal)(ss.Quantity * ss.price);
                            }
                        }

                        foreach (Sale_Line tempLoopVarSs in payPump.Sale_Lines)
                        {
                            ss = tempLoopVarSs;

                            if (ss.Stock_Code == thisLine.Stock_Code)
                            {
                                var temp_Policy_Name3 = "COMBINE_LINE";
                                Can_Combine = Combine_Policy && _policyManager.GetPol(temp_Policy_Name3, thisLine) && (!thisLine.Gift_Certificate) && (decimal)ss.price == Convert.ToDecimal(spr[1, 2]) && ss.Quantity > 0 & thisLine.Quantity > 0 & ss.Discount_Rate == thisLine.Discount_Rate && ss.Serial_No == "" && thisLine.Serial_No == "" && ss.Discount_Type == thisLine.Discount_Type;

                                Line_Price(ref payPump, ref ss, (double)(Convert.ToDecimal(spr[1, 2])));
                                if (Can_Combine && !Combined)
                                {
                                    Line_Quantity(ref payPump, ref ss, ss.Quantity + thisLine.Quantity, false);
                                    Combined = true;
                                }
                                ss.Amount = (decimal)(ss.Quantity * ss.price);
                            }
                        }

                        if (Combined)
                        {
                            returnValue = false;
                        }
                        else
                        {
                            thisLine.price  = (double)(Convert.ToDecimal(spr[1, 2]));
                            thisLine.Amount = (decimal)(thisLine.Quantity * thisLine.price);
                        }
                    }
                    else
                    {
                        if (thisLine.Price_Number == 1)
                        {
                            thisLine.price = (double)(Convert.ToDecimal(spr[1, 2]));
                        }
                        thisLine.Amount = (decimal)(thisLine.Quantity * thisLine.price);
                    }
                }
                else if (thisLine.Price_Type == 'S')
                {
                    // "S" - Sale Pricing
                    if (newLine)
                    {
                        Combined = false;
                        foreach (Sale_Line tempLoopVarSs in payPump.Sale_Lines)
                        {
                            ss = tempLoopVarSs;

                            if (ss.Stock_Code == thisLine.Stock_Code)
                            {
                                var temp_Policy_Name4 = "COMBINE_LINE";
                                Can_Combine = Combine_Policy && _policyManager.GetPol(temp_Policy_Name4, thisLine) && (!thisLine.Gift_Certificate) && (decimal)ss.price == Convert.ToDecimal(spr[1, 2]) && ss.Quantity > 0 & thisLine.Quantity > 0 & ss.Discount_Rate == thisLine.Discount_Rate && ss.Serial_No == "" && thisLine.Serial_No == "" && ss.Discount_Type == thisLine.Discount_Type;



                                Line_Price(ref payPump, ref ss, (double)(Convert.ToDecimal(spr[1, 2])));
                                if (Can_Combine && !Combined)
                                {
                                    Line_Quantity(ref payPump, ref ss, ss.Quantity + thisLine.Quantity, false);
                                    Combined = true;
                                }
                                ss.Amount = (decimal)(ss.Quantity * ss.price);
                            }
                        }

                        if (Combined)
                        {
                            returnValue = false;
                        }
                        else
                        {
                            thisLine.price  = (double)(Convert.ToDecimal(spr[1, 2]));
                            thisLine.Amount = (decimal)(thisLine.Quantity * thisLine.price);
                        }
                    }
                    else
                    {
                        if (thisLine.Price_Number == 1)
                        {
                            thisLine.price = (double)(Convert.ToDecimal(spr[1, 2]));
                        }
                        thisLine.Amount = (decimal)(thisLine.Quantity * thisLine.price);
                    }
                }
                else if (thisLine.Price_Type == 'X' || thisLine.Price_Type == 'I')
                {
                    // "X" - X for Pricing;      "I" - Incremental Pricing

                    // Compute how many lines are needed by counting the number of prices
                    // that the 'PQuantity' routine set.
                    Lines_Needed = (short)0;
                    for (n = 1; n <= (spr.Length - 1); n++)
                    {
                        if (spr[n, 1] != 0)
                        {
                            Lines_Needed++;
                        }
                        else
                        {
                            break;
                        }
                    }

                    nDel = (short)0;

                    // Remove Lines if there are more than we need ...
                    if (Lines_Needed < saleLin)
                    {
                        if (newLine)
                        {
                            // Don't add the incoming line. That reduces the number we need to
                            // delete by 1.
                            nDel = (short)1;
                        }
                        if (nDel < saleLin - Lines_Needed)
                        {
                            foreach (Sale_Line tempLoopVarSs in payPump.Sale_Lines)
                            {
                                ss = tempLoopVarSs;
                                if (ss.Stock_Code == thisLine.Stock_Code)
                                {
                                    //Me.Remove_a_Line SS.Line_Num, False
                                    nDel++;
                                    if (nDel == saleLin - Lines_Needed)
                                    {
                                        break;
                                    }
                                }
                            }
                        }

                        // Add lines if there are not enough.
                    }
                    else if (Lines_Needed > saleLin)
                    {
                        for (n = saleLin; n <= Lines_Needed - 1; n++)
                        {
                            nDel++;
                            New_Line = new Sale_Line
                            {
                                PLU_Code      = thisLine.PLU_Code,
                                Discount_Type = thisLine.Discount_Type,
                                Discount_Rate = thisLine.Discount_Rate,
                                Line_Num      = (short)(payPump.Sale_Lines.Count + 1)
                            };
                            var user = _loginManager.GetExistingUser(payPump.UserCode);
                            Add_a_Line(ref payPump, user, New_Line, false);
                        }
                    }

                    // Set the pricing on each line
                    n = (short)0;
                    foreach (Sale_Line tempLoopVarSs in payPump.Sale_Lines)
                    {
                        ss = tempLoopVarSs;
                        if (ss.Stock_Code == thisLine.Stock_Code)
                        {
                            n++;

                            Line_Price(ref payPump, ref ss, (double)(Convert.ToDecimal(spr[n, 2])));
                            Line_Quantity(ref payPump, ref ss, Convert.ToInt16(spr[n, 1]), false);
                            ss.Amount = Convert.ToDecimal(spr[n, 3]);
                            saleQty   = saleQty - System.Math.Abs(Convert.ToInt16(spr[n, 1]));
                        }
                    }

                    // Set the quantity on the new line
                    if (saleQty != 0)
                    {
                        n++;
                        thisLine.Quantity = saleQty;

                        thisLine.price = (double)(Convert.ToDecimal(spr[n, 2]));

                        thisLine.Amount = Convert.ToDecimal(spr[n, 3]);
                        returnValue     = true;
                    }
                    else
                    {
                        returnValue = false;
                    }
                }
            }

            return(returnValue);
        }