Exemple #1
0
        public HttpResponseMessage ChangePassword([FromBody] ChangePasswordModel model)
        {
            var dateStart = DateTime.Now;

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

            if (model != null)
            {
                ErrorMessage      errorMessage;
                const MessageType messageType = (int)MessageType.Critical + MessageType.OkOnly;
                if (string.IsNullOrEmpty(model.Password))
                {
                    _performancelog.Debug($"End,LoginController,ChangePassword,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
                    //MsgBox "Password Can not be Empty", vbcritical + vbOKOnly, "Empty Password"
                    var store    = CacheManager.GetStoreInfo();
                    var offSet   = store?.OffSet ?? 0;
                    var errorMsg = new InvalidLoginReponseModel
                    {
                        Error       = _resourceManager.CreateMessage(offSet, 39, 64, null, messageType),
                        ShutDownPOS = false
                    };
                    return(Request.CreateResponse(HttpStatusCode.NotAcceptable, errorMsg));
                }
                if (model.Password != model.ConfirmPassword)
                {
                    var store  = CacheManager.GetStoreInfo();
                    var offSet = store?.OffSet ?? 0;
                    // MsgBox "Re-entry Password is not matching with the Password Entry", vbCritical + vbOKOnly, "Password Entry"
                    _performancelog.Debug($"End,LoginController,ChangePassword,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
                    var errorMsg = new InvalidLoginReponseModel
                    {
                        Error       = _resourceManager.CreateMessage(offSet, 39, 65, null, messageType),
                        ShutDownPOS = false
                    };

                    return(Request.CreateResponse(HttpStatusCode.NotAcceptable, errorMsg));
                }
                var result = _loginManager.ChangePassword(model.UserName, model.Password, out errorMessage);
                _performancelog.Debug($"End,LoginController,ChangePassword,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
                var response = new ChangePasswordReponseModel
                {
                    Error   = errorMessage.MessageStyle,
                    Success = result
                };
                return(Request.CreateResponse(HttpStatusCode.OK, response));
            }
            _performancelog.Debug($"End,LoginController,ChangePassword,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
            var error = new InvalidLoginReponseModel
            {
                Error = new MessageStyle
                {
                    Message     = Resource.InvalidInformation,
                    MessageType = MessageType.OkOnly
                },
                ShutDownPOS = true
            };

            return(Request.CreateResponse(HttpStatusCode.BadRequest, error));
        }
        /// <summary>
        /// Authenitcate the POS
        /// </summary>
        /// <param name="ipAddress">Ip address</param>
        /// <param name="message">Message</param>
        /// <param name="error">Error message</param>
        /// <returns>Pos id</returns>
        public int Authenticate(string ipAddress, out string message, out ErrorMessage error)
        {
            var dateStart = DateTime.Now;

            Performancelog.Debug($"Start,LoginManager,Authenticate,{string.Empty},{DateTime.Now:hh.mm.ss.ffffff}");
            message = string.Empty;
            var posId = 0;

            if (IsValidSecurityCode(out error))
            {
                if (!string.IsNullOrEmpty(error.MessageStyle.Message))
                {
                    message = error.MessageStyle.Message;
                    error.MessageStyle.Message = string.Empty;
                }
                posId = _utilityService.GetPosId(ipAddress);
                if (posId != 0 && IsPosAllowed((byte)posId))
                {
                    Performancelog.Debug($"End,LoginManager,Authenticate,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
                    return(posId);
                }
                var offSet = _policyManager.LoadStoreInfo().OffSet;
                error.MessageStyle = _resourceManager.CreateMessage(offSet, 0, 8198, null, MessageType.OkOnly);
                error.StatusCode   = HttpStatusCode.Unauthorized;
                error.ShutDownPos  = true;
            }
            else
            {
                error.StatusCode  = HttpStatusCode.Unauthorized;
                error.ShutDownPos = true;
            }
            Performancelog.Debug($"End,LoginManager,Authenticate,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
            return(posId);
        }
        /// <summary>
        /// Method to get payout vendor
        /// </summary>
        /// <param name="error">Error</param>
        /// <returns>Vendor payout</returns>
        public VendorPayout GetPayoutVendor(out ErrorMessage error)
        {
            error = new ErrorMessage();
            var offSet = _policyManager.LoadStoreInfo().OffSet;

            if (!_policyManager.DO_PAYOUTS)
            {
                MessageType temp_VbStyle8 = (int)MessageType.Exclamation + MessageType.OkOnly;
                error.MessageStyle = _resourceManager.CreateMessage(offSet, 38, 54, null, temp_VbStyle8);
                return(null);
            }
            var vendorPayout = new VendorPayout();
            var po           = new Payout();
            var taxes        = po.Payout_Taxes;

            _taxManager.Load_Taxes(ref taxes);
            int totals = 0;

            foreach (Payout_Tax tax in taxes)
            {
                if (totals >= 4)
                {
                    MessageType temp_VbStyle = (int)MessageType.Information + MessageType.OkOnly;
                    vendorPayout.Message = _resourceManager.CreateMessage(offSet, 23, 90, null, temp_VbStyle);
                    break;
                }

                if (tax.Tax_Active)
                {
                    vendorPayout.Taxes.Add(new Tax
                    {
                        Description = _resourceManager.GetResString(offSet, 194) + tax.Tax_Name,
                        Code        = tax.Tax_Name,
                        Amount      = 0
                    });
                    totals++;
                }
            }
            var vendors = _stockService.GetAllVendors();

            foreach (var vendor in vendors)
            {
                vendorPayout.Vendors.Add(new PayoutVendor
                {
                    Code = vendor.Code,
                    Name = vendor.Name
                });
            }
            var reasons = _reasonService.GetReasons((char)ReasonType.Payouts);

            foreach (Return_Reason reason in reasons)
            {
                vendorPayout.Reasons.Add(new VendorReason
                {
                    Code        = reason.Reason,
                    Description = reason.Description
                });
            }
            return(vendorPayout);
        }
        /// <summary>
        /// Method to get cash draw buttons
        /// </summary>
        /// <returns>Cash draw buttons</returns>
        public CashBonusDrawButton GetCashBonusDrawButtons(string userCode, out ErrorMessage error)
        {
            var dateStart = DateTime.Now;

            _performancelog.Debug($"Start,CashManager,GetCashBonusDrawButtons,{string.Empty},{dateStart:hh.mm.ss.ffffff}");
            var offSet = _policyManager.LoadStoreInfo().OffSet;

            error = new ErrorMessage();
            var user = _loginManager.GetExistingUser(userCode);

            if (!Convert.ToBoolean(_policyManager.GetPol("U_TILLDRAW", user)))
            {
                MessageType temp_VbStyle3 = (int)MessageType.Exclamation + MessageType.OkOnly;
                error.MessageStyle = _resourceManager.CreateMessage(offSet, 38, 56, null, temp_VbStyle3);
                error.StatusCode   = System.Net.HttpStatusCode.Forbidden;
                _performancelog.Debug($"End,CashManager,GetCashBonusDrawButtons,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
                return(null);
            }

            var cashBonusDrawButton = new CashBonusDrawButton
            {
                Coins = _cashBonusService.GetCashBonusCoins()
            };

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

            return(cashBonusDrawButton);
        }
        public HttpResponseMessage Index(int pageIndex = 1, int pageSize = 100)
        {
            var dateStart = DateTime.Now;

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

            var sales = _returnSaleManager.GetAllSales(pageIndex, pageSize);

            if (sales.Count == 0 && (pageIndex == 1 || pageIndex == 0))
            {
                var store  = CacheManager.GetStoreInfo();
                var offSet = store?.OffSet ?? 0;
                var type   = (int)MessageType.Exclamation + MessageType.OkOnly;
                return(Request.CreateResponse(HttpStatusCode.BadRequest, new ErrorResponse
                {
                    Error = _resourceManager.CreateMessage(offSet, 40, 97, null, type)
                }));
            }

            var saleHeadModel = (from sale in sales
                                 select new SaleHeadModel
            {
                SaleNumber = sale.SaleNumber,
                TillNumber = sale.TillNumber,
                Date = sale.SaleDate,
                Time = sale.SaleTime,
                TotalAmount = Math.Round(sale.SaleAmount, 2),
                AllowCorrection = _returnSaleManager.IsAllowCorrection(sale.SaleNumber),
                AllowReason = _returnSaleManager.IsReasonAllowed(sale.SaleNumber)
            }).ToList();

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

            return(Request.CreateResponse(HttpStatusCode.OK, saleHeadModel));
        }
        /// <summary>
        /// Get a Valid GiveX Stockcode
        /// </summary>
        /// <param name="errorMessage">errorMessage</param>
        /// <returns>stock code</returns>
        public string GetValidGiveXStock(out ErrorMessage errorMessage)
        {
            var dateStart = DateTime.Now;

            Performancelog.Debug($"Start,GivexManager,GetValidGiveXStock,{string.Empty},{DateTime.Now:hh.mm.ss.ffffff}");
            errorMessage = new ErrorMessage();
            var stockCode = _givexService.GetValidGiveXStock();

            if (string.IsNullOrEmpty(stockCode))
            {
                var   store  = CacheManager.GetStoreInfo();
                short offSet = store?.OffSet ?? (short)0;
                errorMessage.MessageStyle = _resourceManager.CreateMessage(offSet, 12, 64, null, CriticalOkMessageType);
                errorMessage.StatusCode   = HttpStatusCode.NotAcceptable;
                return(null);
            }
            Performancelog.Debug($"End,GivexManager,GetValidGiveXStock,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
            return(stockCode);
        }
        public HttpResponseMessage PaymentByCoupon([FromBody] PaymentModel paymentModel)
        {
            var dateStart = DateTime.Now;

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

            ErrorMessage        errorMessage;
            string              userCode;
            HttpResponseMessage httpResponseMessage;

            if (GetUserCode(out userCode, out httpResponseMessage))
            {
                return(httpResponseMessage);
            }
            var updatedTenders = _paymentManager.ByCoupon(paymentModel.SaleNumber,
                                                          paymentModel.TillNumber, paymentModel.TransactionType, paymentModel.CouponNumber,
                                                          paymentModel.TillClose, paymentModel.TenderCode, userCode,
                                                          out errorMessage);

            //Added scenario when "Amount Cannot Exceed value of sale."
            //should be displayed and countinue to use the coupon amount
            var store        = CacheManager.GetStoreInfo();
            var offSet       = store?.OffSet ?? 0;
            var messageStyle = _resourceManager.CreateMessage(offSet, 14, 88, null, MessageType.OkOnly);
            var messages     = new List <object>();

            if (messageStyle.Message.Equals(errorMessage.MessageStyle.Message))
            {
                var msg = new
                {
                    error = messageStyle
                };
                messages.Add(msg);
            }
            else
            {
                if (!string.IsNullOrEmpty(errorMessage.MessageStyle.Message))
                {
                    return(Request.CreateResponse(errorMessage.StatusCode, new ErrorResponse
                    {
                        Error = errorMessage.MessageStyle
                    }));
                }
            }
            TenderSummaryModel tenderSummary = GetTenderSummary(updatedTenders);

            tenderSummary.Messages = messages;
            _performancelog.Debug($"End,PaymentController,PaymentByCoupon,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");

            return(Request.CreateResponse(HttpStatusCode.OK, tenderSummary));
        }
Exemple #8
0
        /// <summary>
        /// Method to read price change notification
        /// </summary>
        /// <returns>Message</returns>
        public MessageStyle ReadPricheChangeNotificationHo()
        {
            MessageStyle msg = null;

            if (_policyManager.FUELPR_HO)
            {
                if (modGlobalFunctions.BoolFuelPriceApplied)
                {
                    WriteToLogFile("Fuel price change from HeadOffice: boolFuelPriceApplied is " + System.Convert.ToString(modGlobalFunctions.BoolFuelPriceApplied) + " counter was reset to 0.");
                }
                modGlobalFunctions.BoolFuelPriceApplied = false;
                if (_fuelPumpService.IsPriceChangeFromHo())
                {
                    var offSet = _policyManager.LoadStoreInfo().OffSet;
                    msg = _resourceManager.CreateMessage(offSet, 38, 71, null, _policyManager.FPR_USER ? MessageType.YesNoCancel : MessageType.YesNo);
                }
            }
            return(msg);
        }
Exemple #9
0
        public HttpResponseMessage GetLoyaltyCustomers(int pageIndex = 1, int pageSize = 100)
        {
            var dateStart = DateTime.Now;

            _performancelog.Debug($"Start,CustomerController,GetLoyaltyCustomers,{string.Empty},{DateTime.Now:hh.mm.ss.ffffff}");
            var store     = CacheManager.GetStoreInfo();
            var offSet    = store?.OffSet ?? 0;
            var customers = _customerManager.GetLoyaltyCustomers(pageIndex, pageSize);

            if (customers.Count == 0 && (pageIndex == 1 || pageIndex == 0))
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, new ErrorResponse
                {
                    Error = _resourceManager.CreateMessage(offSet, 16, 89, null)
                }));
            }

            var listCustomerModel = GetLoyaltyCustomerResponseModels(customers);

            _performancelog.Debug($"End,CustomerController,GetLoyaltyCustomers,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
            return(Request.CreateResponse(HttpStatusCode.OK, listCustomerModel));
        }
Exemple #10
0
        /// <summary>
        /// Save Bottle return
        /// </summary>
        /// <param name="brPayment">Br payment</param>
        /// <param name="userCode">User code</param>
        /// <param name="error">Error message</param>
        /// <param name="bottleReport">Report</param>
        /// <param name="openDrawer">Open drawer or not</param>
        public Sale SaveBottleReturn(BR_Payment brPayment,
                                     out ErrorMessage error, out Report bottleReport, out bool openDrawer)
        {
            bottleReport = null;
            openDrawer   = false;
            var dateStart = DateTime.Now;

            Performancelog.Debug($"Start,BottleManager,SaveBottleReturn,{string.Empty},{DateTime.Now:hh.mm.ss.ffffff}");
            error = new ErrorMessage();
            var offSet       = _policyManager.LoadStoreInfo().OffSet;
            var userCode     = UserCode;
            var user         = _loginManager.GetExistingUser(userCode);
            var existingSale = _saleService.GetSaleByTillNumber(brPayment.TillNumber);

            if (existingSale != null && existingSale.Sale_Lines.Count > 0)
            {
                error.MessageStyle = new MessageStyle
                {
                    Message     = "Please finish current sale before bottle return.~Bottle Return",
                    MessageType = ExclamationOkMessageType
                };
                error.StatusCode = HttpStatusCode.Conflict;
                return(null);
            }
            if (!_policyManager.GetPol("U_BOTTLERTN", user))
            {
                error.MessageStyle = _resourceManager.CreateMessage(offSet, 38, 57, null, ExclamationOkMessageType);
                error.StatusCode   = HttpStatusCode.Forbidden;
                return(null);
            }

            if (brPayment.Amount != 0)
            {
                if (string.IsNullOrEmpty(Convert.ToString(_policyManager.GetPol("BASECURR", null))))
                {
                    error.MessageStyle = _resourceManager.CreateMessage(offSet, 18, 61, null, CriticalOkMessageType);
                    error.StatusCode   = HttpStatusCode.NotFound;
                    return(null);
                }

                if (brPayment.Amount > (decimal)Math.Abs(_policyManager.GetPol("U_BR_LIMIT", user)))
                {
                    // Exceed the bottle return limit, Please get an authorized user!
                    error.MessageStyle = _resourceManager.CreateMessage(offSet, 18, 62, null, CriticalOkMessageType);
                    error.StatusCode   = HttpStatusCode.Forbidden;
                    return(null);
                }

                if (_policyManager.OPEN_DRAWER == "Every Sale")
                {
                    openDrawer = true;
                }
                var sale = new Sale
                {
                    Sale_Totals = { Net = Convert.ToDecimal(brPayment.Amount) }
                };
                var saleTotals = sale.Sale_Totals;
                _saleManager.SetGross(ref saleTotals, sale.Sale_Totals.Net);
                sale.Sale_Totals.Gross        = saleTotals.Gross;
                sale.Sale_Totals.TotalLabel   = saleTotals.TotalLabel;
                sale.Sale_Totals.SummaryLabel = saleTotals.SummaryLabel;
                sale.Register    = brPayment.RegisterNumber;
                sale.Sale_Change = 0;

                sale.TillNumber  = Convert.ToByte(brPayment.TillNumber);
                sale.Sale_Date   = DateTime.Now;
                sale.Sale_Tender = 0;
                sale.Sale_Change = 0;
                sale.Sale_Amount = 0;
                if (_policyManager.GetPol("Penny_Adj", null) && brPayment.Amount != 0)
                {
                    sale.Sale_Totals.Penny_Adj = Helper.Calculate_Penny_Adj(Convert.ToDecimal(brPayment.Amount));
                }
                else
                {
                    sale.Sale_Totals.Penny_Adj = 0;
                }

                brPayment.Penny_Adj = sale.Sale_Totals.Penny_Adj;
                if (existingSale == null)
                {
                    brPayment.Sale_Num = _saleManager.GetCurrentSaleNo(brPayment.TillNumber, userCode, out error);
                }
                var tendBr = new Tenders();
                var tender = tendBr.Add(Convert.ToString(_policyManager.GetPol("BASECURR", null)),
                                        "Cash", 1, true, true, false, (short)1,
                                        Convert.ToString(_policyManager.GetPol("BASECURR", null)),
                                        false, 0, 0, 0.01, true, Convert.ToDouble(-brPayment.Amount),
                                        (short)1, true, false, "", "");
                _tenderManager.Set_Amount_Entered(ref tendBr, ref sale, tender, -brPayment.Amount);

                sale.Sale_Num  = Convert.ToInt32(brPayment.Sale_Num);
                sale.Sale_Type = "BTL RTN";
                var shiftNumber = _tillService.GetTill(brPayment.TillNumber).Shift;
                bottleReport = _receiptManager.Print_BottleReturn(brPayment, user.Name, DateTime.Today,
                                                                  DateTime.Now, sale.Register, (short)brPayment.TillNumber, shiftNumber);
                bottleReport.Copies = _policyManager.BottleReturnReceiptCopies;
                _bottleReturnService.SaveBottleReturnsToDbTrans(brPayment);
                _saleManager.SaveSale(sale, userCode, ref tendBr, null);
                CacheManager.DeleteCurrentSaleForTill(sale.TillNumber, sale.Sale_Num);
                //_saleManager.Clear_Sale(sale.Sale_Num,sale.TillNumber, userCode, "", null, true, false, false, out msg);
                sale = _saleManager.InitializeSale(brPayment.TillNumber, brPayment.RegisterNumber, userCode, out error);
                //Update Sale object in Cache
                CacheManager.AddCurrentSaleForTill(sale.TillNumber, sale.Sale_Num, sale);
                Performancelog.Debug($"End,BottleManager,SaveBottleReturn,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
                return(sale);
            }
            return(null);
        }
Exemple #11
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);
        }
Exemple #12
0
        /// <summary>
        /// Get Suspended Sale List
        /// </summary>
        /// <param name="tillNumber">Till number</param>
        /// <param name="errorMessage">Error</param>
        /// <returns>List of suspended sales</returns>
        public List <SusHead> GetSuspendedSale(int tillNumber, out ErrorMessage errorMessage)
        {
            errorMessage = new ErrorMessage();
            var dateStart = DateTime.Now;

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

            string sqlQuery;

            if (_policyManager.SHARE_SUSP)
            {
                sqlQuery = "SELECT   SusHead.Sale_No ," +
                           "         SusHead.Client ," + "SusHead.TILL " +
                           "FROM     SusHead " + "ORDER BY SusHead.Sale_No DESC";
            }
            else
            {
                sqlQuery = "SELECT   SusHead.Sale_No ," +
                           "         SusHead.Client ," + "SusHead.TILL  " +
                           "FROM     SusHead  where SusHead.TILL=" + tillNumber +
                           " ORDER BY SusHead.Sale_No DESC";
            }

            var susSale = _suspendedSaleService.GetAllSuspendedSale(sqlQuery);

            if (susSale == null || susSale.Count == 0)
            {
                var offSet = _policyManager.LoadStoreInfo().OffSet;
                errorMessage = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 11, 92, null, MessageType.OkOnly),
                    StatusCode   = HttpStatusCode.NotFound
                };
                return(null);
            }

            Performancelog.Debug($"End,SuspendedSaleManager,GetSuspendedSale,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");

            return(susSale);
        }
        /// <summary>
        /// Method to save overrlimit
        /// </summary>
        /// <param name="tillNumber">Till number</param>
        /// <param name="saleNumber">Sale number</param>
        /// <param name="userCode">User code</param>
        /// <param name="cobReason">Reason</param>
        /// <param name="txtExplanation">Explaination</param>
        /// <param name="txtLocation">Loaction</param>
        /// <param name="dtpDate">Date</param>
        /// <param name="error">Error</param>
        /// <returns>Aite response</returns>
        public AiteCardResponse DoneOverLimit(int tillNumber, int saleNumber, string userCode, string cobReason, string txtExplanation, string txtLocation, DateTime dtpDate, out ErrorMessage error)
        {
            AiteCardResponse result = new AiteCardResponse();
            var oTeSale             = CacheManager.GetTaxExemptSaleForTill(tillNumber, saleNumber);

            mPrivateGlobals.theSystem = CacheManager.GetTeSystemForTill(tillNumber, saleNumber);

            var sale = CacheManager.GetCurrentSaleForTill(tillNumber, saleNumber);

            if (!_policyManager.USE_OVERRIDE || _policyManager.TE_Type != "AITE")
            {
                error = new ErrorMessage
                {
                    MessageStyle = new MessageStyle
                    {
                        Message     = "Please select AITE Tax Exempt and enable Use override policy in BackOffice",
                        MessageType = 0
                    },
                    StatusCode = HttpStatusCode.BadRequest
                };
                return(result);
            }

            if (sale == null)
            {
                error = new ErrorMessage
                {
                    MessageStyle = new MessageStyle
                    {
                        Message     = "The request is invalid.",
                        MessageType = 0
                    },
                    StatusCode = HttpStatusCode.BadRequest
                };
                return(null);
            }
            if (oTeSale.TobaccoOverLimit)
            {
                if (!ValidExplanation(ref oTeSale, (byte)TeProductType.Tobacco, cobReason, txtExplanation, txtLocation, dtpDate))
                {
                    var offSet = _policyManager.LoadStoreInfo().OffSet;
                    error = new ErrorMessage
                    {
                        MessageStyle = _resourceManager.CreateMessage(offSet, 54, 61, null, YesNoQuestionMessageType),
                        StatusCode   = HttpStatusCode.Forbidden
                    };
                    return(null);
                }
            }

            if (oTeSale.GasOverLimit)
            {
                if (!ValidExplanation(ref oTeSale, (byte)TeProductType.Gas, cobReason, txtExplanation, txtLocation, dtpDate))
                {
                    var offSet = _policyManager.LoadStoreInfo().OffSet;
                    error = new ErrorMessage
                    {
                        MessageStyle = _resourceManager.CreateMessage(offSet, 54, 62, null, YesNoQuestionMessageType),
                        StatusCode   = HttpStatusCode.Forbidden
                    };
                    return(null);
                }
            }

            if (oTeSale.PropaneOverLimit)
            {
                if (!ValidExplanation(ref oTeSale, (byte)TeProductType.Propane, cobReason, txtExplanation, txtLocation, dtpDate))
                {
                    var offSet = _policyManager.LoadStoreInfo().OffSet;
                    error = new ErrorMessage
                    {
                        MessageStyle = _resourceManager.CreateMessage(offSet, 54, 63, null, YesNoQuestionMessageType),
                        StatusCode   = HttpStatusCode.Forbidden
                    };
                    return(null);
                }
            }

            if (oTeSale.Te_Sale_Lines.Count > 0)
            {
                foreach (TaxExemptSaleLine tempLoopVarTesl in oTeSale.Te_Sale_Lines)
                {
                    var tesl      = tempLoopVarTesl;
                    var rowNumber = tesl.Line_Num;
                    var saleLine  = sale.Sale_Lines[rowNumber];


                    if (!(tesl.Amount < 0 && saleLine.IsTaxExemptItem))
                    {
                        saleLine.IsTaxExemptItem = true;
                        _saleLineManager.SetPrice(ref saleLine, tesl.TaxFreePrice);
                        _saleLineManager.SetAmount(ref saleLine, (decimal)tesl.Amount);
                        //saleLine.price = tesl.TaxFreePrice;
                        //saleLine.Amount = (decimal)tesl.Amount;
                    }
                }
                //_saleManager.ReCompute_Totals(ref sale);
            }
            _saleManager.ReCompute_Totals(ref sale);
            var tenders = _tenderManager.GetAllTender(sale.Sale_Num, sale.TillNumber, "Sale", userCode, false, "", out error);

            result.SaleSummary = SaleSummary(sale);

            result.Tenders = tenders;
            return(result);
        }
        /// <summary>
        /// Method to close batch
        /// </summary>
        /// <param name="posId">Pos Id</param>
        /// <param name="tillNumber">Till number</param>
        /// <param name="saleNumber">Sale number</param>
        /// <param name="registerNumber">Register number</param>
        /// <param name="error">Error message</param>
        /// <returns>List of report</returns>
        public List <Report> CloseBatch(byte posId, int tillNumber, int saleNumber, byte registerNumber, out ErrorMessage error)
        {
            var   reports = new List <Report>();
            short termNos = 0;

            string[,] Terminals = new string[3, 3];
            short    i               = 0;
            string   rFileName       = "";
            DateTime batchDate       = default(DateTime);
            bool     blnNoDebitTrans = false;
            var      emvProcess      = _policyManager.EMVVersion;
            var      offSet          = _policyManager.LoadStoreInfo().OffSet;
            var      sale            = _saleManager.GetCurrentSale(saleNumber, tillNumber, registerNumber, UserCode, out error);

            if (!string.IsNullOrEmpty(error?.MessageStyle?.Message))
            {
                return(null);
            }
            var rFileNumber = (short)(FileSystem.FreeFile());

            try
            {
                if (GetConnection())
                {
                    var terminals = _maintenanceService.GetTerminalIds(posId);
                    if (terminals == null)
                    {
                        WriteToLogFile("***PROBLEM WITH CLOSE BATCH*** " + " " + _resourceManager.GetResString(offSet, 1287)); // Shiny Mar6, 2008 -EKO
                                                                                                                               //MsgBoxStyle temp_VbStyle = (int)MsgBoxStyle.Critical + MsgBoxStyle.OkOnly;
                                                                                                                               //Chaps_Main.DisplayMessage(12, (short)87, temp_VbStyle, null, (byte)0);
                        error = new ErrorMessage
                        {
                            MessageStyle = _resourceManager.CreateMessage(offSet, 12, 87, null, CriticalOkMessageType)
                        };
                        return(null);
                    }
                    //ButtonsEnabled(false);
                    rFileName = Path.GetTempPath() + "BankEod_ " + PosId + ".txt";
                    FileSystem.FileOpen(rFileNumber, rFileName, OpenMode.Append);
                    termNos = 0;
                    foreach (Terminal terminal in terminals)
                    {
                        if (string.IsNullOrEmpty(terminal.TerminalType) || string.IsNullOrEmpty(terminal.TerminalId))
                        {
                            WriteToLogFile("***PROBLEM WITH CLOSE BATCH***" + " " + _resourceManager.GetResString(offSet, 1287)); // Shiny Mar6, 2008 -EKO
                                                                                                                                  //MsgBoxStyle temp_VbStyle2 = (int)MsgBoxStyle.Critical + MsgBoxStyle.OkOnly;
                                                                                                                                  //Chaps_Main.DisplayMessage(this, (short)87, temp_VbStyle2, null, (byte)0);
                            error = new ErrorMessage
                            {
                                MessageStyle = _resourceManager.CreateMessage(offSet, 12, 87, null, CriticalOkMessageType)
                            };
                            FileSystem.FileClose(rFileNumber);
                            return(null);
                        }

                        modTPS.cc = new Credit_Card();

                        WriteToLogFile("EMVprocess:" + Convert.ToString(emvProcess));
                        SendToTps(_cardManager.GetRequestString(ref modTPS.cc, sale, "EODTerminal", terminal.TerminalType, 0, terminal.TerminalId), ref modTPS.cc, emvProcess);
                        var eodTimer = DateAndTime.Timer;
                        while (Convert.ToInt32(DateAndTime.Timer - Convert.ToDouble(eodTimer)) < 120) // shiny changed this waiting to 2 minutes- 4 is too much 240)
                        {
                            if (modTPS.cc.Response.Length > 0)
                            {
                                break;
                            }
                        }

                        if (modTPS.cc.Response.ToUpper() == "APPROVED")
                        {
                            termNos++;
                            Terminals[termNos, 1] = modTPS.cc.TerminalID;
                            Terminals[termNos, 2] = modTPS.cc.Sequence_Number;
                            FileSystem.PrintLine(rFileNumber, modTPS.cc.Report);
                            batchDate = modTPS.cc.Trans_Date;
                            WriteToLogFile("SUCCESS WITH CLOSE BATCH"); // Shiny Mar6, 2008 -EKO

                            //  - added as part of Datawire Integeration (added by Mina)
                            //#:5:TPS does handshake after sending EOD for debit. If there weren’t any debit transactions between closes batches, POS has to send special indication that there weren’t any debit transactions. Having gotten that flag, TPS doesn’t do handshake.
                            if (Strings.UCase(Convert.ToString(_policyManager.BankSystem)) == "GLOBAL")
                            {
                                blnNoDebitTrans = modTPS.cc.Report.IndexOf("No Transactions", StringComparison.Ordinal) + 1 > 0;
                            }
                            _maintenanceService.SetCloseBatchNumber(modTPS.cc);
                        }
                        else // Behrooz Jan-09
                        {
                            if (modTPS.cc.Receipt_Display.Length > 0)
                            {
                                WriteToLogFile("***PROBLEM WITH CLOSE BATCH***" + " " + modTPS.cc.Receipt_Display); // Shiny Mar6, 2008 -EKO
                                                                                                                    //Chaps_Main.DisplayMsgForm(modTPS.cc.Receipt_Display, (short)100, null, (byte)0, (byte)0, "", "", "", "");
                                error = new ErrorMessage
                                {
                                    MessageStyle = new MessageStyle
                                    {
                                        Message     = modTPS.cc.Receipt_Display,
                                        MessageType = MessageType.OkOnly
                                    }
                                };
                                FileSystem.FileClose(rFileNumber);
                                return(null);
                            }
                            else
                            {
                                WriteToLogFile("***PROBLEM WITH CLOSE BATCH***" + " " + _resourceManager.GetResString(offSet, 1284)); // Shiny Mar6, 2008 -EKO
                                                                                                                                      //Chaps_Main.DisplayMsgForm((Convert.ToDouble(12)) * 100 + 84, (short)99, null, (byte)0, (byte)0, "", "", "", "");
                                error = new ErrorMessage
                                {
                                    MessageStyle = new MessageStyle
                                    {
                                        Message     = _resourceManager.GetResString(offSet, 1284),
                                        MessageType = MessageType.OkOnly
                                    }
                                };
                                FileSystem.FileClose(rFileNumber);
                                return(null);
                            }
                        }
                        modTPS.cc = null;
                        i++;
                    }
                }
                else
                {
                    WriteToLogFile("***PROBLEM WITH CLOSE BATCH***" + " " + _resourceManager.GetResString(offSet, 1296)); // Shiny Mar6, 2008 -EKO
                                                                                                                          //Chaps_Main.DisplayMsgForm((Convert.ToDouble(12)) * 100 + 96, (short)99, null, (byte)0, (byte)0, "", "", "", "");
                    error = new ErrorMessage
                    {
                        MessageStyle = new MessageStyle
                        {
                            Message     = _resourceManager.GetResString(offSet, 1296),
                            MessageType = MessageType.OkOnly
                        }
                    };
                    //return;
                }

                FileSystem.FileClose(rFileNumber);
                if (!string.IsNullOrEmpty(rFileName))
                {
                    var stream = File.OpenRead(rFileName);
                    FileSystem.FileClose(rFileNumber);
                    var bytes = new byte[stream.Length];
                    stream.Read(bytes, 0, Convert.ToInt32(stream.Length));
                    stream.Close();
                    var content = Convert.ToBase64String(bytes);
                    reports.Add(new Report
                    {
                        ReportName    = "BankEod.txt",
                        ReportContent = content,
                        Copies        = 1
                    });
                }
                if (termNos == i)
                {
                    if (GetConnection()) //Nancy
                    {
                        //  - Datawire Integration (Added by Mina)
                        //#5: TPS does handshake after sending EOD for debit. If there weren’t any debit transactions between closes batches, POS has to send special indication that there weren’t any debit transactions. Having gotten that flag, TPS doesn’t do handshake.
                        if (Strings.UCase(Convert.ToString(_policyManager.BankSystem)) == "GLOBAL")
                        {
                            if (blnNoDebitTrans) //Added by Mina
                            {
                                SendToTps(_cardManager.GetRequestString(ref modTPS.cc, sale, "CloseBatchInside", "NoDebit", 0, ""), ref modTPS.cc, emvProcess);
                            }
                            else
                            {
                                SendToTps(_cardManager.GetRequestString(ref modTPS.cc, sale, "CloseBatchInside", "Credit", 0, ""), ref modTPS.cc, emvProcess);
                            }
                        }
                        else
                        {
                            SendToTps(_cardManager.GetRequestString(ref modTPS.cc, sale, "CloseBatchInside", "Credit", 0, ""), ref modTPS.cc, emvProcess);
                        }
                    }
                    else
                    {
                        return(null); //Call DisplayMsgForm(Me.Tag * 100 + 96, 99)
                    }
                }
                if (termNos > 0)
                {
                    //modPrint.Dump_To_Printer(RFileName, (short)1, true, true, false);
                    //FileStream fs = new FileStream(RFileName, FileMode.Open, FileAccess.Read);
                    var date      = DateTime.Parse("12:00:00 AM");
                    var eodReport = _tillCloseManager.PrintEodDetails(tillNumber, ref date, ref date, Terminals[1, 1],
                                                                      Terminals[1, 2], Terminals[2, 1], Terminals[2, 2], false, batchDate);
                    reports.Add(eodReport);
                }
                return(reports);
            }
            finally
            {
                if (!string.IsNullOrEmpty(rFileName))
                {
                    FileSystem.Kill(rFileName);
                }
            }
        }
        /// <summary>
        /// Add update tier level
        /// </summary>
        /// <param name="pumpIds"></param>
        /// <param name="tierId"></param>
        /// <param name="levelId"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public TierLevelResponse AddUpdateTierLevel(List <int> pumpIds, int tierId, int levelId, out ErrorMessage error)
        {
            error = new ErrorMessage();
            var result = new TierLevelResponse
            {
                Tiers  = GetAllTiers(),
                Levels = GetAllLevels()
            };

            object i;
            string tierLevel    = "";
            bool   pumpSelected = false;
            var    store        = CacheManager.GetStoreInfo();
            var    offSet       = store?.OffSet ?? 0;
            float  timeIn       = 0;

            for (i = 1; (int)i <= (int)Variables.gPumps.PumpsCount; i = (int)i + 1)
            {
                if (tierId == 0)
                {
                    //        MsgBox ("Please select Tier!") '21
                    //MsgBoxStyle temp_VbStyle = (int)MsgBoxStyle.OkOnly + MsgBoxStyle.Critical;
                    //Chaps_Main.DisplayMessage(this, (short)21, temp_VbStyle, null, (byte)0);
                    error = new ErrorMessage
                    {
                        MessageStyle = _resourceManager.CreateMessage(offSet, 44, 21, null, CriticalOkMessageType)
                    };
                    return(null);
                }
                if (levelId == 0)
                {
                    //        MsgBox ("Please select Level!") '22
                    //MsgBoxStyle temp_VbStyle2 = (int)MsgBoxStyle.OkOnly + MsgBoxStyle.Critical;
                    //Chaps_Main.DisplayMessage(this, (short)22, temp_VbStyle2, null, (byte)0);
                    error = new ErrorMessage
                    {
                        MessageStyle = _resourceManager.CreateMessage(offSet, 44, 22, null, CriticalOkMessageType)
                    };
                    return(null);
                }

                switch (tierId + levelId.ToString())
                {
                case "11":
                    tierLevel = "0";
                    break;

                case "12":
                    tierLevel = "1";
                    break;

                case "21":
                    tierLevel = "2";
                    break;

                case "22":
                    tierLevel = "3";
                    break;
                }

                if (pumpIds.Contains((int)i))
                {
                    pumpSelected = true;
                    //lblinformation.Caption = "Setting in Process... Please Wait..." 'Resource.DisplayCaption(lblinformation.Tag, Me.Tag, , 2) '24-4
                    //lblinformation.Text = Chaps_Main.Resource.DisplayCaption(System.Convert.ToInt16(lblinformation.Tag), System.Convert.ToInt16(this.Tag), null, (short)4); //24-4
                    result.PageCaption = _resourceManager.CreateCaption(offSet, 24, 44, null, 4);

                    if (TCPAgent.Instance.PortOpened)
                    {
                        var response  = "";
                        var strRemain = "";


                        var cmd = "STL" + Strings.Right("00" + System.Convert.ToString(i), 2) + tierLevel;
                        TCPAgent.Instance.Send_TCP(ref cmd, true);
                        if (timeIn > DateAndTime.Timer)
                        {
                            timeIn = 0; //reset on midnight
                        }
                        else
                        {
                            timeIn = (float)DateAndTime.Timer;
                        }

                        while (!(DateAndTime.Timer - timeIn > Variables.gPumps.CommunicationTimeOut))
                        {
                            var strBuffer = System.Convert.ToString(TCPAgent.Instance.NewPortReading);
                            WriteToLogFile("TCPAgent.PortReading: " + strBuffer + " from waiting STL" + Strings.Right("00" + System.Convert.ToString(i), 2));
                            if (!string.IsNullOrEmpty(strBuffer))
                            {
                                modStringPad.SplitResponse(strBuffer, "STL" + Strings.Right("00" + System.Convert.ToString(i), 2), ref response, ref strRemain); //strBuffer<>""
                                if (!string.IsNullOrEmpty(response))                                                                                             //got what we are waiting
                                {
                                    TCPAgent.Instance.PortReading = strRemain;                                                                                   //& ";" & TCPAgent.PortReading
                                    WriteToLogFile("modify TCPAgent.PortReading from Get Totalizer: " + strRemain);
                                    break;
                                }
                            }
                            Variables.Sleep(100);
                            if (DateAndTime.Timer < timeIn)
                            {
                                timeIn = (float)DateAndTime.Timer;
                            }
                        }


                        if (Strings.Left(response, 7) != "STL" + Strings.Right("00" + System.Convert.ToString(i), 2) + "OK")
                        {
                            string tempCommandRenamed = "ENDPOS";
                            TCPAgent.Instance.Send_TCP(ref tempCommandRenamed, true);
                            //  lblinformation.Caption = "Setting TierLevel failed !" 'Resource.DisplayCaption(lblinformation.Tag, Me.Tag, , 2) '24-3
                            //(System.Convert.ToInt16(lblinformation.Tag), System.Convert.ToInt16(this.Tag), null, (short)3); //24-3
                            result.PageCaption = _resourceManager.CreateCaption(offSet, 24, 44, null, 3);
                            return(result);
                        }


                        _fuelPumpService.UpdateTierLevelForPump((int)i, tierId, levelId);



                        Variables.gPumps.get_Pump(System.Convert.ToByte(i)).TierID = (byte)tierId;

                        Variables.gPumps.get_Pump(System.Convert.ToByte(i)).LevelID = (byte)levelId;


                        if (Variables.Pump[(int)i].cashUP == null)
                        {
                            Variables.Pump[(int)i].cashUP = new float[10];
                        }

                        if (Variables.Pump[(int)i].creditUP == null)
                        {
                            Variables.Pump[(int)i].creditUP = new float[10];
                        }

                        if (Variables.Pump[(int)i].Stock_Code == null)
                        {
                            Variables.Pump[(int)i].Stock_Code = new string[10];
                        }


                        short j;
                        for (j = 1; j <= Variables.gPumps.get_PositionsCount(System.Convert.ToByte(i)); j++)
                        {
                            Variables.Pump[(int)i].cashUP[j] = Variables.gPumps.get_FuelPrice(System.Convert.ToByte(Variables.gPumps.get_Assignment(System.Convert.ToByte(i), (byte)j).GradeID), (byte)(Conversion.Val(tierId)), (byte)(Conversion.Val(levelId))).CashPrice;

                            Variables.Pump[(int)i].creditUP[j] = Variables.gPumps.get_FuelPrice(System.Convert.ToByte(Variables.gPumps.get_Assignment(System.Convert.ToByte(i), (byte)j).GradeID), (byte)(Conversion.Val(tierId)), (byte)(Conversion.Val(levelId))).CreditPrice;
                        }
                    }
                    else
                    {
                        //            lblinformation.Caption = "Please select pump and corresponding Tier/Level, then press 'SET TO PUMP' button to set!"  '24-1
                        //lblinformation.Text = Chaps_Main.Resource.DisplayCaption(System.Convert.ToInt16(lblinformation.Tag), System.Convert.ToInt16(this.Tag), null, (short)1); //24-1
                        result.PageCaption    = _resourceManager.CreateCaption(offSet, 24, 44, null, 1);
                        result.PumpTierLevels = GetPumpsTierLevel();
                        //MsgBox "No TCP connection to Host !!!", vbCritical
                        //MsgBoxStyle temp_VbStyle3 = (int)MsgBoxStyle.OkOnly + MsgBoxStyle.Critical;
                        //Chaps_Main.DisplayMessage(this, (short)92, temp_VbStyle3, null, (byte)0);
                        error.MessageStyle = new MessageStyle
                        {
                            Message     = _resourceManager.GetResString(offSet, 3892),
                            MessageType = MessageType.OkOnly
                        };
                        return(result);
                    }
                }
            }

            if (!pumpSelected) //if no pump is selected
            {
                //    MsgBox ("Please select Pump!") '23
                //Chaps_Main.DisplayMessage(this, (short)23, temp_VbStyle4, null, (byte)0);
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 44, 23, null, CriticalOkMessageType)
                };
                //    lblinformation.Caption = "Please select pump and corresponding Tier/Level, then press 'SET TO PUMP' button to set!" '24-1
                //lblinformation.Text = Chaps_Main.Resource.DisplayCaption(System.Convert.ToInt16(lblinformation.Tag), System.Convert.ToInt16(this.Tag), null, (short)1); //24-1
                result.PageCaption    = _resourceManager.CreateCaption(offSet, 24, 44, null, 1);
                result.PumpTierLevels = GetPumpsTierLevel();
                return(result);
            }
            //    lblinformation.Caption = "Setting TierLevel is Done successfully !" 'Resource.DisplayCaption(lblinformation.Tag, Me.Tag, , 2) '24-2
            //lblinformation.Text = Chaps_Main.Resource.DisplayCaption(System.Convert.ToInt16(lblinformation.Tag), System.Convert.ToInt16(this.Tag), null, (short)2); //24-2
            result.PageCaption    = _resourceManager.CreateCaption(offSet, 24, 44, null, 2);
            result.PumpTierLevels = GetPumpsTierLevel();
            return(result);
        }
Exemple #16
0
        public tePurchaseList GetPurchaseList(int saleNumber, int tillNumber, string userCode, string treatyNumber, string treatyName, out ErrorMessage error)
        {
            var sale      = _saleManager.GetCurrentSale(saleNumber, tillNumber, 0, userCode, out error);
            var oTreatyNo = new teTreatyNo()
            {
                TreatyNumber = treatyNumber, Name = treatyName
            };

            var    offSet         = _policyManager.LoadStoreInfo().OffSet;
            double originalPrice  = 0;
            double taxIncldAmount = 0;

            sale.TreatyNumber = oTreatyNo.TreatyNumber;
            sale.TreatyName   = oTreatyNo.Name;

            error = null;

            var oPurchaseList = new tePurchaseList();

            oPurchaseList.Init(oTreatyNo, sale.Sale_Num, sale.TillNumber);

            var y = oPurchaseList.GetTreatyNo();

            foreach (Sale_Line tempLoopVarSl in sale.Sale_Lines)
            {
                var    sl = tempLoopVarSl;
                string strError;

                if (sl.Amount < 0 && sl.IsTaxExemptItem)
                {
                    taxIncldAmount = -1 * sl.TaxInclPrice;
                    //shiny - Dec9, 2009 - Squamish nation
                    //                OriginalPrice = sl.Regular_Price

                    if (_policyManager.TE_ByRate == false) // Regualr Site customers SITE , TE_By rate = no
                    {
                        originalPrice = sl.Regular_Price;  //  - editing the price for TE is keeping different price in purchaseitem and saleline'SL.price
                    }
                    else if (_policyManager.TE_ByRate)     //squamish SITE , TE_By rate = yes
                    {
                        originalPrice = sl.price;
                    }
                }
                else
                {
                    //shiny - Dec9, 2009 - Squamish nation
                    //                OriginalPrice = sl.Regular_Price

                    if (_policyManager.TE_ByRate == false) // Regualr Site customers SITE , TE_By rate = no
                    {
                        originalPrice = sl.Regular_Price;  //  - editing the price for TE is keeping different price in purchaseitem and saleline'SL.price
                    }
                    else if (_policyManager.TE_ByRate)     //squamish SITE , TE_By rate = yes
                    {
                        originalPrice = sl.price;
                    }
                }



                if (sl.ProductIsFuel && !sl.IsPropane)
                {
                    if (_policyManager.USE_FUEL)
                    {
                        if (Variables.gPumps == null)
                        {
                            Variables.gPumps = _fuelPumpService.InitializeGetProperty(PosId, _policyManager.TAX_EXEMPT, _policyManager.TE_ByRate, _policyManager.TE_Type, _policyManager.AuthPumpPOS);
                        }
                        string tempSProductKey = _teSystemManager.TeMakeFuelKey(sl.GradeID, Convert.ToInt16(Variables.gPumps.get_Pump(sl.pumpID).TierID), Convert.ToInt16(Variables.gPumps.get_Pump(sl.pumpID).LevelID));
                        double tempDQuantity   = sl.Quantity;
                        var    tempIRowNumberInSalesMainForm = sl.Line_Num;
                        bool   tempIsFuelItem = true;
                        string tempStockCode  = sl.Stock_Code;
                        if (!AddItem(ref oPurchaseList, ref sale, ref oTreatyNo, ref tempSProductKey, ref tempDQuantity, ref originalPrice, ref tempIRowNumberInSalesMainForm, ref tempStockCode, ref taxIncldAmount, ref tempIsFuelItem))
                        {
                            strError = oPurchaseList.GetLastError();
                            if (strError == "2")
                            {
                                //MsgBox ("Cannot load Tax Exempt price, Please set Tax Exempt Category for Grade-" & SL.GradeID & " first in the BackOffice system! ")
                                //_resourceManager.CreateMessage(offSet,this, 17, temp_VbStyle, sl.GradeID, 0);
                                error = new ErrorMessage
                                {
                                    MessageStyle = _resourceManager.CreateMessage(offSet, 11, 17, sl.GradeID, CriticalOkMessageType),
                                    StatusCode   = HttpStatusCode.Conflict
                                };
                                return(null);
                            }
                            if (!string.IsNullOrEmpty(strError) && strError.ToUpper() != "NO ERROR")
                            {
                                //MsgBox ("Error(" & strError & ") for getting Tax Exempt price, will use original price for this sale!")
                                //_resourceManager.CreateMessage(offSet,this, 18, temp_VbStyle2, strError, 0);
                                error = new ErrorMessage
                                {
                                    MessageStyle = _resourceManager.CreateMessage(offSet, 11, 18, strError, CriticalOkMessageType),
                                    StatusCode   = HttpStatusCode.Conflict
                                };
                                return(null);
                            }
                            break;
                        }
                    }
                    else
                    {
                        var    tempSProductKey2 = sl.Stock_Code;
                        double tempDQuantity2   = sl.Quantity;
                        var    tempIRowNumberInSalesMainForm2 = sl.Line_Num;
                        bool   tempIsFuelItem2 = false;
                        var    tempStockCode   = sl.Stock_Code;
                        if (!AddItem(ref oPurchaseList, ref sale, ref oTreatyNo, ref tempSProductKey2, ref tempDQuantity2, ref originalPrice, ref tempIRowNumberInSalesMainForm2, ref tempStockCode, ref taxIncldAmount, ref tempIsFuelItem2))
                        {
                            strError = oPurchaseList.GetLastError();
                            if (!string.IsNullOrEmpty(strError) && strError.ToUpper() != "NO ERROR")
                            {
                                //_resourceManager.CreateMessage(offSet,this, 18, temp_VbStyle3, strError, 0);
                                error = new ErrorMessage
                                {
                                    MessageStyle = _resourceManager.CreateMessage(offSet, 11, 18, strError, CriticalOkMessageType),
                                    StatusCode   = HttpStatusCode.Conflict
                                };
                                return(null);
                            }
                        }
                    }
                }
                else
                {
                    var    tempSProductKey3 = sl.Stock_Code;
                    double tempDQuantity3   = sl.Quantity;
                    short  tempIRowNumberInSalesMainForm3 = sl.Line_Num;
                    bool   tempIsFuelItem3 = false;
                    var    tempStockCode   = sl.Stock_Code;
                    if (!AddItem(ref oPurchaseList, ref sale, ref oTreatyNo, ref tempSProductKey3, ref tempDQuantity3, ref originalPrice, ref tempIRowNumberInSalesMainForm3, ref tempStockCode, ref taxIncldAmount, ref tempIsFuelItem3))
                    {
                        strError = oPurchaseList.GetLastError();
                        if (!string.IsNullOrEmpty(strError) && strError.ToUpper() != "NO ERROR")
                        {
                            //_resourceManager.CreateMessage(offSet,this, 18, temp_VbStyle4, strError, 0);
                            error = new ErrorMessage
                            {
                                MessageStyle = _resourceManager.CreateMessage(offSet, 11, 18, strError, CriticalOkMessageType),
                                StatusCode   = HttpStatusCode.Conflict
                            };
                            return(null);
                        }
                    }
                }
            }

            var x = oPurchaseList.GetTreatyNo();

            CacheManager.AddPurchaseListSaleForTill(tillNumber, saleNumber, oPurchaseList);
            return(oPurchaseList);
        }
        public HttpResponseMessage GetFlashReport(int tillNumber)
        {
            var dateStart = DateTime.Now;

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

            var till = _tillService.GetTill(tillNumber);

            if (till == null)
            {
                var errorMessage = new ErrorMessage
                {
                    MessageStyle = new MessageStyle
                    {
                        Message = Resource.TillNotExist
                    },
                };
                _performancelog.Debug($"End,ReportController,GetFlashReport,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");

                return(Request.CreateResponse(HttpStatusCode.NotFound, new ErrorResponse
                {
                    Error = errorMessage.MessageStyle
                }));
            }
            if (!_receiptManager.IsFlashReportAvailable(tillNumber))
            {
                var         store          = CacheManager.GetStoreInfo();
                var         offSet         = store?.OffSet ?? 0;
                MessageType temp_VbStyle11 = (int)MessageType.Exclamation + MessageType.OkOnly;
                var         errorMessage   = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 0, 5688, null, temp_VbStyle11)
                };
                _performancelog.Debug($"End,ReportController,GetFlashReport,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");

                return(Request.CreateResponse(HttpStatusCode.NotFound, new ErrorResponse
                {
                    Error = errorMessage.MessageStyle
                }));
            }
            var totals      = _receiptManager.GetTotalsForFlashReport(tillNumber);
            var departments = _receiptManager.GetDepartmentDetailsForFlashReport(tillNumber);
            var fs          = _receiptManager.PrintFlashReport(till, totals, departments);

            try
            {
                var content = Helper.CreateBytes(fs);
                FlashReportModel flashReport = CreateFlashReport(totals, departments, content);
                _performancelog.Debug($"End,ReportController,GetFlashReport,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
                return(Request.CreateResponse(HttpStatusCode.OK, flashReport));
            }
            catch
            {
                _performancelog.Debug($"End,ReportController,GetTillAuditReport,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");

                return(Request.CreateResponse(HttpStatusCode.NotFound, new ErrorResponse
                {
                    Error = new MessageStyle {
                        Message = Resource.Error, MessageType = 0
                    }
                }));
            }
        }
        /// <summary>
        /// Get Report of the Dip input values for print
        /// </summary>
        /// <param name="tillNumber">Till number</param>
        /// <param name="shiftNumber">Shift number</param>
        /// <param name="registerNumber">Register number</param>
        /// <param name="userCode">User code</param>
        /// <param name="error">Error message</param>
        /// <returns>Dip input report</returns>
        public Report PrintDipReport(int tillNumber, int shiftNumber, int registerNumber, string userCode, out ErrorMessage error)
        {
            error = new ErrorMessage();
            var user   = _loginManager.GetExistingUser(userCode);
            var report = new Report {
                ReportName = Utilities.Constants.TankDipFile, Copies = 1
            };
            var    offSet        = _policyManager.LoadStoreInfo().OffSet;
            string timeFormatHm  = string.Empty;
            string timeFormatHms = string.Empty;

            GetTimeFormats(ref timeFormatHm, ref timeFormatHms);
            var store = _policyManager.LoadStoreInfo();

            var strDate     = DateAndTime.Year(DateAndTime.Today) + Strings.Right("00" + Convert.ToString(DateAndTime.Month(DateAndTime.Today)), 2) + Strings.Right("00" + Convert.ToString(DateAndTime.Day(DateAndTime.Today)), 2);
            var strFileName = Path.GetTempPath() + "\\Dip" + $"{DateTime.Now:yyyy-MM-dd_hh-mm-ss-tt}.txt";
            var dipInputs   = _dipInputService.GetDipInputsForReport(strDate);

            if (dipInputs.Count > 0)
            {
                short sWidth = 20;
                short aWidth = 20;
                short hWidth = 40;


                var just = Strings.Left(Convert.ToString(_policyManager.REC_JUSTIFY), 1).ToUpper();

                var nH = FileSystem.FreeFile();
                FileSystem.FileOpen(nH, strFileName, OpenMode.Output, OpenAccess.Write);

                //  - store code printing should be based on policy - Gasking will enter store code as part of store name - so they don't want to see store code in the beginning
                //   If Policy.PRN_CO_NAME Then Print #nH, PadIt(Just, Store.Code & "  " & Store.Name, H_Width)

                if (_policyManager.PRN_CO_NAME)
                {
                    FileSystem.PrintLine(nH, modStringPad.PadIt(just, (_policyManager.PRN_CO_CODE ? store.Code + "  " : "") + store.Name, hWidth));
                }

                if (_policyManager.PRN_CO_ADDR)
                {
                    FileSystem.PrintLine(nH, modStringPad.PadIt(just, Convert.ToString(store.Address.Street1), hWidth));

                    if (store.Address.Street2 != "")
                    {
                        FileSystem.PrintLine(nH, modStringPad.PadIt(just, Convert.ToString(store.Address.Street2), hWidth));
                    }
                    FileSystem.PrintLine(nH, modStringPad.PadIt(just, Strings.Trim(Convert.ToString(store.Address.City)) + ", " + store.Address.ProvState, hWidth) + "\r\n" + modStringPad.PadIt(just, Convert.ToString(store.Address.PostalCode), hWidth));
                }

                if (_policyManager.PRN_CO_PHONE)
                {
                    foreach (Phone tempLoopVarPhoneRenamed in store.Address.Phones)
                    {
                        var phoneRenamed = tempLoopVarPhoneRenamed;
                        if (phoneRenamed.Number.Trim() != "")
                        {
                            FileSystem.PrintLine(nH, modStringPad.PadC(phoneRenamed.PhoneName + " " + phoneRenamed.Number, hWidth));
                        }
                    }
                }

                FileSystem.PrintLine(nH, modStringPad.PadIt(just, Strings.Trim(Convert.ToString(store.RegName)) + " " + store.RegNum, hWidth)); //& vbCrLf

                if (store.SecRegName != "")
                {
                    FileSystem.PrintLine(nH, modStringPad.PadIt(just, Strings.Trim(Convert.ToString(store.SecRegName)) + " " + store.SecRegNum, hWidth));
                }
                FileSystem.PrintLine(nH);

                FileSystem.PrintLine(nH,
                                     _policyManager.PRN_UName
                        ? modStringPad.PadIt(just,
                                             _resourceManager.GetResString(offSet, 225) + ": " + user.Name + " (" +
                                             Strings.Left(_resourceManager.GetResString(offSet, 132), 1) + Convert.ToString(registerNumber) + "/" +
                                             Strings.Left(_resourceManager.GetResString(offSet, 131), 1) + Convert.ToString(tillNumber) + "/" +
                                             Strings.Left(_resourceManager.GetResString(offSet, 346), 1) + Convert.ToString(shiftNumber) + ")",
                                             hWidth)
                        : modStringPad.PadIt(just,
                                             _resourceManager.GetResString(offSet, 225) + ": " + user.Code + " (" +
                                             Strings.Left(_resourceManager.GetResString(offSet, 132), 1) + Convert.ToString(registerNumber) + "/" +
                                             Strings.Left(_resourceManager.GetResString(offSet, 131), 1) + Convert.ToString(tillNumber) + "/" +
                                             Strings.Left(_resourceManager.GetResString(offSet, 346), 1) + Convert.ToString(shiftNumber) + ")",
                                             hWidth));
                //

                FileSystem.PrintLine(nH, modStringPad.PadIt(just, DateAndTime.Today.ToString("dd-MMM-yyyy") + _resourceManager.GetResString(offSet, 208) + DateAndTime.TimeOfDay.ToString(timeFormatHm), hWidth) + "\r\n"); //" at " '
                FileSystem.PrintLine(nH, modStringPad.PadIt(just, _resourceManager.GetResString(offSet, 3403) + " " + DateTime.Now.ToString("dd-MM-yyyy hh:mm:ss"), hWidth));                                               //"DIP READING @ "
                FileSystem.PrintLine(nH, modStringPad.PadL("=", hWidth, "=") + "\r\n");
                FileSystem.PrintLine(nH, modStringPad.PadC(_resourceManager.GetResString(offSet, 3401), sWidth) + modStringPad.PadC(_resourceManager.GetResString(offSet, 3402), aWidth));                                  //"Tank ID","DIP Value"
                FileSystem.PrintLine(nH, modStringPad.PadL("-", hWidth, "-"));                                                                                                                                              //& vbCrLf

                foreach (DipInput dipInput in dipInputs)
                {
                    FileSystem.PrintLine(nH, modStringPad.PadC(dipInput.TankId, sWidth) + modStringPad.PadC(dipInput.DipValue, aWidth));
                }

                // Advance the specified number of lines.
                short i;
                for (i = 1; i <= _policyManager.ADV_LINES; i++)
                {
                    FileSystem.PrintLine(nH);
                }
                FileSystem.FileClose(nH);
                var stream = File.OpenRead(strFileName);
                report.ReportContent = Helper.CreateBytes(stream);
                report.Copies        = 1;
                //modPrint.Dump_To_Printer((new Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase()).Info.DirectoryPath + "\\" + File_Name, 1, true, true, false);
            }
            else
            {
                //MsgBoxStyle temp_VbStyle = (int)MsgBoxStyle.Critical + MsgBoxStyle.OkOnly;
                //Chaps_Main.DisplayMessage(this, 60, temp_VbStyle, null, 0);
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 34, 60, null, CriticalOkMessageType),
                    StatusCode   = HttpStatusCode.NotFound
                };
            }

            return(report);
        }
        /// <summary>
        /// Get Sale By sale No
        /// </summary>
        /// <param name="saleNumber">Sale number</param>
        /// <param name="tillNumber">Till number</param>
        /// <param name="message">Message</param>
        /// <returns>Sale</returns>
        public Sale GetSale(int saleNumber, int tillNumber, out ErrorMessage message)
        {
            bool isSaleFound;
            bool isReturnable;
            var  sale   = _returnSaleService.GetSaleBySaleNumber(saleNumber, tillNumber, new DateTime(), _policyManager.TE_Type, _policyManager.TE_GETNAME, _policyManager.TAX_EXEMPT_GA, _policyManager.DefaultCust, _policyManager.DEF_CUST_CODE, out isSaleFound, out isReturnable);
            var  offSet = _policyManager.LoadStoreInfo().OffSet;

            if (!isSaleFound)
            {
                message = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 40, 98, null)
                };
                return(sale);
            }
            if (sale.Sale_Type == "SALE" || sale.Sale_Type == "REFUND")
            {
                var saleLines = _returnSaleService.GetSaleLineBySaleNumber(saleNumber, tillNumber, new DateTime(), sale.Customer.DiscountType, _policyManager.TE_Type, _policyManager.TAX_EXEMPT);

                foreach (Sale_Line sline in saleLines)
                {
                    sline.PRICE_DEC  = CommonUtility.GetShortValue(_policyManager.GetPol("PRICE_DEC", sline));
                    sline.QUANT_DEC  = CommonUtility.GetShortValue(_policyManager.GetPol("QUANT_DEC", sline));
                    sline.RET_REASON = _policyManager.GetPol("RET_REASON", sline);
                    sale.Sale_Lines.AddLine(sline.Line_Num, sline, "");
                }
            }
            message = new ErrorMessage();
            return(sale);
        }
        /// <summary>
        /// Get all AR Customers
        /// </summary>
        /// <param name="error"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns>list of customer</returns>
        public List <Customer> GetArCustomers(out ErrorMessage error, int pageIndex = 1, int pageSize = 100)
        {
            var dateStart = DateTime.Now;

            error = new ErrorMessage();
            Performancelog.Debug($"Start,CustomerManager,GetArCustomers,{string.Empty},{DateTime.Now:hh.mm.ss.ffffff}");
            var offSet    = _policyManager.LoadStoreInfo().OffSet;
            var customers = _customerService.GetArCustomers(pageIndex, pageSize);

            if (customers.Count == 0 && (pageIndex == 1 || pageIndex == 0))
            {
                //Chaps_Main.DisplayMessage(this, (short)91, temp_VbStyle, null, (byte)0);
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 41, 91, null, CriticalOkMessageType)
                };
                return(null);
            }

            Performancelog.Debug(
                $"End,CustomerManager,GetArCustomers,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
            return(customers);
        }
        /// <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);
        }
Exemple #22
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);
        }
        /// <summary>
        /// Method to get propane grades
        /// </summary>
        /// <param name="error">Error message</param>
        /// <returns></returns>
        public List <PropaneGrade> GetPropaneGrades(out ErrorMessage error)
        {
            var propaneGrades = _fuelPumpService.GetPropaneGrades();

            error = new ErrorMessage();
            if (propaneGrades.Count == 0)
            {
                var offSet = _policyManager.LoadStoreInfo().OffSet;
                error = new ErrorMessage
                {
                    MessageStyle = _resourceManager.CreateMessage(offSet, 38, 76, null)
                };
                return(null);
            }

            CacheManager.AddPropaneGrades(propaneGrades);
            return(propaneGrades);
        }
        /// <summary>
        /// Method to add a stock Item
        /// </summary>
        /// <param name="userName">UserCode</param>
        /// <param name="stockItem">Stock Item</param>
        /// <param name="taxCodes">List of tax codes</param>
        /// <param name="error">Error message</param>
        public void AddStockItem(string userName, StockItem stockItem, List <string> taxCodes, out ErrorMessage error)
        {
            var dateStart = DateTime.Now;

            Performancelog.Debug($"Start,StockManager,AddStockItem,{string.Empty},{DateTime.Now:hh.mm.ss.ffffff}");
            var offSet = _policyManager.LoadStoreInfo().OffSet;

            error = new ErrorMessage();
            if (!string.IsNullOrEmpty(userName) && _loginManager.GetUser(userName) != null)
            {
                //var user = _userService.GetUser(userName);
                var user = _loginManager.GetUser(userName);

                var stockCode   = stockItem.StockCode;
                var canAddStock = _policyManager.GetPol("U_AddStock", user);
                if (!Convert.ToBoolean(canAddStock))
                {
                    error.MessageStyle = _resourceManager.CreateMessage(offSet, 39, 91, stockCode, (MessageType)((int)MessageType.Critical + (int)MessageType.OkOnly));
                    error.StatusCode   = HttpStatusCode.NotFound;
                    return;
                }
                if (string.IsNullOrEmpty(stockCode))
                {
                    error.MessageStyle = new MessageStyle
                    {
                        Message     = "Stock code is required",
                        MessageType = MessageType.OkOnly
                    };
                    error.StatusCode = HttpStatusCode.NotAcceptable;
                    return;
                }
                if (string.IsNullOrEmpty(stockItem.Description))
                {
                    error.MessageStyle = new MessageStyle
                    {
                        Message     = "Description is required",
                        MessageType = MessageType.OkOnly
                    };
                    error.StatusCode = HttpStatusCode.NotAcceptable;
                    return;
                }
                if (Conversion.Val(stockItem.Price) <= 0)
                {
                    error.MessageStyle = new MessageStyle
                    {
                        Message     = "Price should be more than 0",
                        MessageType = MessageType.OkOnly
                    };
                    error.StatusCode = HttpStatusCode.NotAcceptable;
                    return;
                }
                if (SetupTaxes(taxCodes, stockCode) == false)
                {
                    error.MessageStyle = _resourceManager.CreateMessage(offSet, 39, 96, stockCode, (MessageType)((int)MessageType.Critical + (int)MessageType.OkOnly));
                    error.StatusCode   = HttpStatusCode.Conflict;
                    return;
                }
                if (_stockService.GetStockItemByCode(stockCode, true) != null)
                {
                    error.MessageStyle = _resourceManager.CreateMessage(offSet, 39, 95, stockCode, (MessageType)((int)MessageType.Critical + (int)MessageType.OkOnly));
                    error.StatusCode   = HttpStatusCode.Conflict;
                    return;
                }
                if (_stockService.GetPluMast(stockCode) != null)
                {
                    error.MessageStyle = _resourceManager.CreateMessage(offSet, 39, 95, stockCode, (MessageType)((int)MessageType.Critical + (int)MessageType.OkOnly));
                    error.StatusCode   = HttpStatusCode.Conflict;
                    return;
                }
                _stockService.AddStockItem(stockItem, _policyManager.ELG_LOY);
                _stockService.AddPluMast(stockCode);
                _stockService.AddStockBranch(stockCode);
                _stockService.AddStockPrice(stockCode, stockItem.Price);
            }
            else
            {
                error.MessageStyle = _resourceManager.CreateMessage(offSet, 10, 95, userName, (MessageType)((int)MessageType.Critical + (int)MessageType.OkOnly));
                error.StatusCode   = HttpStatusCode.Unauthorized;
            }

            Performancelog.Debug($"End,StockManager,AddStockItem,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
        }
Exemple #25
0
        /// <summary>
        /// Method to delete prepay from POS
        /// </summary>
        /// <param name="pumpId">Pump Id</param>
        /// <param name="showMessage">Show message or not</param>
        /// <param name="error">Error</param>
        /// <returns>True or false</returns>
        public bool DeletePrepayFromFc(short pumpId, bool showMessage, out ErrorMessage error)
        {
            error = new ErrorMessage();
            var store  = CacheManager.GetStoreInfo();
            var offSet = store?.OffSet ?? 0;

            if (!Variables.Pump[pumpId].IsPrepay && !Variables.Pump[pumpId].IsHoldPrepay)
            {
                return(false);
            }

            if (!TCPAgent.Instance.IsConnected)
            {
                if (showMessage)
                {
                    error = new ErrorMessage()
                    {
                        MessageStyle = _resourceManager.CreateMessage(offSet, 38, 19, null, CriticalOkMessageType)
                    };
                }
                return(false);
            }

            var response  = "";
            var strRemain = "";

            Variables.IsWaiting = true;

            var    timeIn             = (float)DateAndTime.Timer;
            string tempCommandRenamed = "Rpr" + Strings.Right("0" + Convert.ToString(pumpId), 2);

            TCPAgent.Instance.Send_TCP(ref tempCommandRenamed, true);

            while (!(DateAndTime.Timer - timeIn > Variables.gPumps.CommunicationTimeOut))
            {
                var strBuffer = Convert.ToString(TCPAgent.Instance.NewPortReading);
                WriteToLogFile("TCPAgent.PortReading: " + strBuffer + " from waiting Rpr" + Strings.Right("00" + Convert.ToString(pumpId), 2));
                if (!string.IsNullOrEmpty(strBuffer))
                {
                    modStringPad.SplitResponse(strBuffer, "Rpr" + Strings.Right("00" + Convert.ToString(pumpId), 2), ref response, ref strRemain); //strBuffer<>""
                    if (!string.IsNullOrEmpty(response))                                                                                           //got what we are waiting
                    {
                        TCPAgent.Instance.PortReading = strRemain;                                                                                 //& ";" & TCPAgent.PortReading
                        WriteToLogFile("modify PortReading from Deleting prepay: " + strRemain);
                        break;
                    }
                }
                if (DateAndTime.Timer < timeIn)
                {
                    timeIn = (float)DateAndTime.Timer;
                }
                Variables.Sleep(100);
            }

            if (Strings.Left(response, 8) == "Rpr" + Strings.Right("00" + Convert.ToString(pumpId), 2) + "ERR")
            {
                if (showMessage)
                {
                    error = new ErrorMessage()
                    {
                        MessageStyle = _resourceManager.CreateMessage(offSet, 38, 19, null, CriticalOkMessageType)
                    };
                }
                Variables.IsWaiting = false;
                return(false);
            }

            if (Strings.Left(response, 7) != "Rpr" + Strings.Right("00" + Convert.ToString(pumpId), 2) + "OK") //response is not RprERR or RprOK
            {
                if (showMessage)
                {
                    error = new ErrorMessage()
                    {
                        MessageStyle = _resourceManager.CreateMessage(offSet, 38, 19, null, CriticalOkMessageType)
                    };
                }
                string tempCommandRenamed2 = "ENDPOS";
                TCPAgent.Instance.Send_TCP(ref tempCommandRenamed2, false);
                Variables.IsWaiting = false;
                return(false);
            }
            Variables.IsWaiting = false;
            return(true);
        }
        /// <summary>
        /// Is Valid Treaty Number
        /// </summary>
        /// <param name="sTreatyNo">Treaty number</param>
        /// <param name="captureMethod">capture method</param>
        /// <param name="user">User</param>
        /// <param name="error">Error</param>
        /// <returns>True or false</returns>
        public bool IsValidTreatyNo(ref string sTreatyNo, ref short captureMethod, User user, out ErrorMessage error)
        {
            bool returnValue;

            error = new ErrorMessage();
            var offSet = _policyManager.LoadStoreInfo().OffSet;

            //   card validation for Ontario gas tax refunds e-service
            if (_policyManager.TAX_EXEMPT_FNGTR)
            {
                var rsInvalidCert = _treatyService.IsInvalidCertificate(sTreatyNo);
                if (rsInvalidCert)
                {
                    //Chaps_Main.DisplayMessage(0, (short)8800, temp_VbStyle, null, (byte)0);
                    error = new ErrorMessage
                    {
                        MessageStyle = _resourceManager.CreateMessage(offSet, 0, 8800, null, ExclamationOkMessageType),
                        StatusCode   = HttpStatusCode.BadRequest
                    };
                    return(false);
                }
                if (sTreatyNo.Length < 9 || sTreatyNo.Length > 14)
                {
                    //Chaps_Main.DisplayMessage(0, (short)8801, temp_VbStyle2, null, (byte)0);
                    error = new ErrorMessage
                    {
                        MessageStyle = _resourceManager.CreateMessage(offSet, 0, 8801, null, ExclamationOkMessageType),
                        StatusCode   = HttpStatusCode.BadRequest
                    };
                    return(false);
                }
                if (sTreatyNo.Length <= 14)
                {
                    returnValue = true;
                }
                else
                {
                    //Chaps_Main.DisplayMessage(0, (short)8801, temp_VbStyle3, null, (byte)0);
                    error = new ErrorMessage
                    {
                        MessageStyle = _resourceManager.CreateMessage(offSet, 0, 8801, null, ExclamationOkMessageType),
                        StatusCode   = HttpStatusCode.BadRequest
                    };
                    return(false);
                }
            }
            else
            {
                //   end
                returnValue = sTreatyNo.Length == _policyManager.TreatyNumDgt;
            }

            // SITE
            if (_policyManager.SITE_RTVAL)
            {
                short tillMode = user.User_Group.Code == "Trainer" ? (short)2 : (short)1;
                // SetCustomer doesn't validate the customer; RTVP dll always returns 0 (success)

                if (Variables.RTVPService == null)
                {
                    Variables.RTVPService = new Transaction();
                }
                var ret = System.Convert.ToInt16(Variables.RTVPService.SetCustomer(sTreatyNo, captureMethod));
                WriteToLogFile("Response is " + System.Convert.ToString(ret) + " from SetCustomer sent with parameters " + sTreatyNo + "," + System.Convert.ToString(captureMethod));
                ret = System.Convert.ToInt16(Variables.RTVPService.SetTillMode(tillMode));
                WriteToLogFile("Response is " + System.Convert.ToString(ret) + " from SetTillMode sent with parameter " + System.Convert.ToString(tillMode));
            }

            return(returnValue);
        }
        public HttpResponseMessage AdjustGivexCard([FromBody] AdjustGivexModel givexModel)
        {
            var dateStart = DateTime.Now;

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

            ErrorMessage        errorMessage;
            HttpResponseMessage responseMessage;

            var cardNumber = givexModel.GivexCardNumber;

            if (!ValidateGivexCard(ref cardNumber, out responseMessage))
            {
                return(responseMessage);
            }
            givexModel.GivexCardNumber = cardNumber;

            if (!ValidateStockCode(givexModel.StockCode, out responseMessage))
            {
                return(responseMessage);
            }

            string userCode;
            HttpResponseMessage httpResponseMessage;

            if (GetUserCode(out userCode, out httpResponseMessage))
            {
                return(httpResponseMessage);
            }
            if (Conversion.Val(givexModel.Amount) <= 0)
            {
                const MessageType messageType = (int)MessageType.OkOnly + MessageType.Critical;
                var offSet = _policyManager.LoadStoreInfo().OffSet;
                return(Request.CreateResponse(HttpStatusCode.NotAcceptable,
                                              new ErrorResponse
                {
                    Error = _resourceManager.CreateMessage(offSet, 32, 94, null, messageType),
                }));
            }
            Report giveReceipt;
            var    sale = _givexManager.AdjustGivexCard(givexModel.GivexCardNumber,
                                                        givexModel.Amount,
                                                        userCode,
                                                        givexModel.TillNumber,
                                                        givexModel.SaleNumber,
                                                        givexModel.StockCode,
                                                        out giveReceipt,
                                                        out errorMessage);

            if (!string.IsNullOrEmpty(errorMessage.MessageStyle.Message))
            {
                return(Request.CreateResponse(errorMessage.StatusCode, new ErrorResponse
                {
                    Error = errorMessage.MessageStyle
                }));
            }
            var editLines       = _saleManager.CheckEditOptions(sale.Sale_Lines, userCode);
            var enableButtons   = _saleManager.EnableCashButton(sale, userCode);
            var userCanWriteOff = _saleManager.EnableWriteOffButton(userCode);
            var saleModel       = SaleMapper.CreateSaleModel(sale, editLines, enableButtons, userCanWriteOff);
            var response        = new GivexResponseModel
            {
                Sale    = saleModel,
                Receipt = giveReceipt
            };

            _performancelog.Debug($"End,GivexController,AdjustGivexCard,{DateTime.Now.Subtract(dateStart).TotalMilliseconds},{DateTime.Now:hh.mm.ss.ffffff}");
            return(Request.CreateResponse(HttpStatusCode.OK, response));
        }