Beispiel #1
0
        public void Execute(Message msg, IMessageSenderService sender, IBot bot)
        {
            if (!Main.Api.Users.CheckUser(msg))
            {
                var kb2 = new KeyboardBuilder(bot);
                kb2.AddButton("➕ Зарегистрироваться", "start");
                sender.Text("❌ Вы не зарегистрированы, нажмите на кнопку ниже, чтобы начать", msg.ChatId, kb2.Build());
                return;
            }

            var api  = Main.Api;
            var user = api.Users.GetUser(msg);

            if (user.Access < 6)
            {
                sender.Text("❌ Вам недоступна эта команда.", msg.ChatId);
                return;
            }

            var  array  = msg.Text.Split(" ");
            long userId = 0;

            try
            {
                userId = long.Parse(array[1]);
            }catch
            {
                sender.Text("❌ Вы ввели неверный ID пользователя.", msg.ChatId);
                return;
            }

            Car car;

            try
            {
                var carId = long.Parse(array[2]);
                car = CarsHelper.GetHelper().Cars.Single(c => c.Id == carId);
            }
            catch
            {
                sender.Text("❌ Вы ввели неверный ID автомобиля.", msg.ChatId);
                return;
            }

            var garage = api.Garages.GetGarage(userId);

            if ((garage.ParkingPlaces - garage.Cars.Length) == 0)
            {
                sender.Text("❌ У пользователя нет свободного места в гараже.", msg.ChatId);
                return;
            }

            var str = CarsHelper.GetHelper().AddCarToString(garage.Cars, car.Id);

            Main.Api.Garages.SetCars(user.Id, str);

            sender.Text($"✔ Вы выдали {car.Manufacturer} {car.Model} игроку с ID {userId}", msg.ChatId);
        }
Beispiel #2
0
        protected void Page_Load(object sender, EventArgs e)
        {
            OtherMethods.ActiveRightMenuStyleChanche("hlCars", this.Page);
            OtherMethods.ActiveRightMenuStyleChanche("hlSouls", this.Page);
            Page.Title = Page.Request.Params["id"] != null ? PagesTitles.ManagerCarEdit + BackendHelper.TagToValue("page_title_part") : PagesTitles.ManagerCarCreate + BackendHelper.TagToValue("page_title_part");

            #region Блок доступа к странице
            var userInSession = (Users)Session["userinsession"];
            var rolesList     = Application["RolesList"] as List <Roles>;
            var currentRole   = (Roles)rolesList.SingleOrDefault(u => u.Name.ToLower() == userInSession.Role.ToLower());
            if (currentRole.PageCarEdit != 1)
            {
                Response.Redirect("~/Error.aspx?id=1");
            }
            #endregion

            BackLink = CarsHelper.BackCarLinkBuilder(Page.Request.Params["aid"], Page.Request.Params["model"], Page.Request.Params["number"], Page.Request.Params["typeid"]);

            if (!IsPostBack)
            {
                ddlType.DataSource     = Cars.CarType;
                ddlType.DataTextField  = "Value";
                ddlType.DataValueField = "Key";
                ddlType.DataBind();
            }

            if (Page.Request.Params["id"] != null)
            {
                var car = new Cars {
                    ID = Convert.ToInt32(Page.Request.Params["id"])
                };
                car.GetById();
                if (String.IsNullOrEmpty(car.Model))
                {
                    Page.Response.Redirect("~/ManagerUI/Menu/Souls/CarsView.aspx?" + BackLink);
                }
                if (!IsPostBack)
                {
                    ddlType.SelectedValue = car.TypeID.ToString();
                    tbModel.Text          = car.Model;
                    tbNumber.Text         = hfNumber.Value = car.Number;

                    tbCompanyName.Text = car.CompanyName;

                    tbFirstName.Text           = car.FirstName;
                    tbLastName.Text            = car.LastName;
                    tbThirdName.Text           = car.ThirdName;
                    tbPassportSeria.Text       = car.PassportSeria;
                    tbPassportNumber.Text      = car.PassportNumber;
                    tbPersonalNumber.Text      = car.PersonalNumber;
                    tbROVD.Text                = car.ROVD;
                    tbRegistrationAddress.Text = car.RegistrationAddress;
                    tbValidity.Text            = Convert.ToDateTime(car.Validity).ToString("dd-MM-yyyy");
                    tbBirthDay.Text            = Convert.ToDateTime(car.BirthDay).ToString("dd-MM-yyyy");
                    tbDateOfIssue.Text         = Convert.ToDateTime(car.DateOfIssue).ToString("dd-MM-yyyy");
                }
            }
        }
Beispiel #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Title = PagesTitles.ManagerCarView + BackendHelper.TagToValue("page_title_part");
            OtherMethods.ActiveRightMenuStyleChanche("hlCars", this.Page);
            OtherMethods.ActiveRightMenuStyleChanche("hlSouls", this.Page);

            #region Блок доступа к странице
            var userInSession = (Users)Session["userinsession"];
            var rolesList     = Application["RolesList"] as List <Roles>;
            var currentRole   = (Roles)rolesList.SingleOrDefault(u => u.Name.ToLower() == userInSession.Role.ToLower());
            if (currentRole.PageCarView != 1)
            {
                Response.Redirect("~/Error.aspx?id=1");
            }
            #endregion

            if (Page.Request.Params["id"] != null)
            {
                if (!IsPostBack)
                {
                    var id  = Convert.ToInt32(Page.Request.Params["id"]);
                    var car = new Cars {
                        ID = id
                    };
                    car.GetById();
                    lblID.Text = car.ID.ToString();
                    var dm = new DataManager();
                    var driversForCarTable = dm.QueryWithReturnDataSet(String.Format("SELECT ID, FirstName, LastName, ThirdName FROM drivers WHERE CarID = {0}", id));
                    foreach (DataRow driver in driversForCarTable.Tables[0].Rows)
                    {
                        lblDrivers.Text += String.Format("<a href='DriversEdit.aspx?id={3}'>{0} {1}.{2}.</a>&nbsp; &nbsp;",
                                                         driver["FirstName"],
                                                         driver["LastName"].ToString().Remove(1, driver["LastName"].ToString().Length - 1),
                                                         driver["ThirdName"].ToString().Remove(1, driver["ThirdName"].ToString().Length - 1),
                                                         driver["ID"]);
                    }

                    lblType.Text   = CarsHelper.CarTypeToFullString(Convert.ToInt32(car.TypeID));
                    hfTypeID.Value = car.TypeID.ToString();
                    lblModel.Text  = car.Model;
                    lblNumber.Text = car.Number;

                    lblCompanyName.Text = car.CompanyName;

                    lblFirstName.Text           = car.FirstName;
                    lblLastName.Text            = car.LastName;
                    lblThirdName.Text           = car.ThirdName;
                    lblPassport.Text            = car.PassportSeria + car.PassportNumber;
                    lblPersonalNumber.Text      = car.PersonalNumber;
                    lblROVD.Text                = car.ROVD;
                    lblRegistrationAddress.Text = car.RegistrationAddress;
                    lblValidity.Text            = Convert.ToDateTime(car.Validity).ToString("dd-MM-yyyy");
                    lblBirthDay.Text            = Convert.ToDateTime(car.BirthDay).ToString("dd-MM-yyyy");
                    lblDateOfIssue.Text         = Convert.ToDateTime(car.DateOfIssue).ToString("dd-MM-yyyy");
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Title = PagesTitles.ManagerDriverViewTitle + BackendHelper.TagToValue("page_title_part");
            OtherMethods.ActiveRightMenuStyleChanche("hlDrivers", this.Page);
            OtherMethods.ActiveRightMenuStyleChanche("hlSouls", this.Page);

            #region Блок доступа к странице
            var userInSession = (Users)Session["userinsession"];
            var rolesList     = Application["RolesList"] as List <Roles>;
            var currentRole   = (Roles)rolesList.SingleOrDefault(u => u.Name.ToLower() == userInSession.Role.ToLower());
            if (currentRole.PageDriverView != 1)
            {
                Response.Redirect("~/Error.aspx?id=1");
            }
            #endregion

            if (Page.Request.Params["id"] != null)
            {
                if (!IsPostBack)
                {
                    var driver = new Drivers {
                        ID = Convert.ToInt32(Page.Request.Params["id"])
                    };
                    driver.GetById();
                    lblID.Text        = driver.ID.ToString();
                    lblStatus.Text    = DriversHelper.DriverStatusToText(Convert.ToInt32(driver.StatusID));
                    lblCar.Text       = CarsHelper.CarIdToModelName(driver.CarID.ToString());
                    hlCar.NavigateUrl = "~/ManagerUI/CarView.aspx?id=" + driver.CarID;

                    lblFIO.Text                = String.Format("{0} {1} {2}", driver.FirstName, driver.LastName, driver.ThirdName);
                    lblPhoneOne.Text           = driver.PhoneOne;
                    lblPhoneTwo.Text           = driver.PhoneTwo;
                    lblHomePhone.Text          = driver.HomePhone;
                    lblHomeAddress.Text        = driver.HomeAddress;
                    lblBirthDay.Text           = Convert.ToDateTime(driver.BirthDay).ToString("dd-MM-yyyy");
                    lblContactPersonFIO.Text   = driver.ContactPersonFIO;
                    lblContactPersonPhone.Text = driver.ContactPersonPhone;

                    lblPassportData.Text        = String.Format("{0}{1}", driver.PassportSeria, driver.PassportNumber);
                    lblPersonalNumber.Text      = driver.PersonalNumber;
                    lblROVD.Text                = driver.ROVD;
                    lblDateOfIssue.Text         = Convert.ToDateTime(driver.DateOfIssue).ToString("dd-MM-yyyy");
                    lblValidity.Text            = Convert.ToDateTime(driver.Validity).ToString("dd-MM-yyyy");
                    lblRegistrationAddress.Text = driver.RegistrationAddress;

                    lblDriverPassport.Text            = driver.DriverPassport;
                    lblDriverPassportDateOfIssue.Text = Convert.ToDateTime(driver.DriverPassportDateOfIssue).ToString("dd-MM-yyyy");
                    lblDriverPassportValidity.Text    = Convert.ToDateTime(driver.DriverPassportValidity).ToString("dd-MM-yyyy");
                    lblMedPolisDateOfIssue.Text       = Convert.ToDateTime(driver.MedPolisDateOfIssue).ToString("dd-MM-yyyy");
                    lblMedPolisValidity.Text          = Convert.ToDateTime(driver.MedPolisValidity).ToString("dd-MM-yyyy");
                }
            }
        }
Beispiel #5
0
        public void Execute(Message msg, IMessageSenderService sender, IBot bot)
        {
            if (Main.Api.Users.IsBanned(msg))
            {
                return;
            }

            if (!Main.Api.Users.CheckUser(msg))
            {
                var kb2 = new KeyboardBuilder(bot);
                kb2.AddButton("➕ Зарегистрироваться", "start");
                sender.Text("❌ Вы не зарегистрированы, нажмите на кнопку ниже, чтобы начать", msg.ChatId, kb2.Build());
                return;
            }
            long carId;

            try
            {
                carId = Int64.Parse(msg.Payload.Arguments[0]);
            }
            catch
            {
                sender.Text("❌ Эту команду можно вызывать только с клавиатуры!", msg.ChatId);
                return;
            }
            var car  = CarsHelper.GetHelper().GetCarFromId(carId);
            var text = $"🚗 Информация о автомобиле:" +
                       $"\n 🚘 Производитель: {car.Manufacturer}" +
                       $"\n 🏎 Модель: {car.Model}" +
                       $"\n ⚡ Мощность: {car.Power} л.с" +
                       $"\n 🅱 Масса: {car.Weight}" +
                       $"\n 💰 Цена: {car.Price}";

            var kb = new KeyboardBuilder(bot);

            kb.AddButton("💵 Купить автомобиль", "buycar", new List <string>()
            {
                car.Id.ToString()
            }, color: KeyboardButtonColor.Positive);
            kb.AddLine();
            kb.AddButton("↩ Назад к автомобилям", "getcars", new List <string>()
            {
                car.Manufacturer, "0"
            });

            sender.Text(text, msg.ChatId, kb.Build());
        }
Beispiel #6
0
        public void lbDelete_Click(Object sender, EventArgs e)
        {
            DeleteAccess();
            var userInSession = (Users)Session["userinsession"];

            BackLink = CarsHelper.BackCarLinkBuilder(stbAID.Text, stbModel.Text, stbNumber.Text, sddlType.SelectedValue);
            var lb     = (LinkButton)sender;
            var driver = new Drivers {
                CarID = Convert.ToInt32(lb.CommandArgument)
            };
            var ds = driver.GetAllItems("ID", "ASC", "CarID");

            if (ds.Tables[0].Rows.Count > 0)
            {
                lblError.Text =
                    "К автомобилю привязаны водители. Перед удалением отвяжите всех водителей от удаляемого автомобиля.";
                return;
            }
            var car = new Cars();

            car.Delete(Convert.ToInt32(lb.CommandArgument), userInSession.ID, OtherMethods.GetIPAddress(), "CarsView");
            Page.Response.Redirect("~/ManagerUI/Menu/Souls/CarsView.aspx?" + BackLink);
        }
Beispiel #7
0
        public void Execute(Message msg, IMessageSenderService sender, IBot bot)
        {
            if (Main.Api.Users.IsBanned(msg))
            {
                return;
            }

            if (!Main.Api.Users.CheckUser(msg))
            {
                var kb2 = new KeyboardBuilder(bot);
                kb2.AddButton("➕ Зарегистрироваться", "start");
                sender.Text("❌ Вы не зарегистрированы, нажмите на кнопку ниже, чтобы начать", msg.ChatId, kb2.Build());
                return;
            }

            var  user       = Main.Api.Users.GetUser(msg);
            var  garage     = Main.Api.Garages.GetGarage(user.Id);
            var  car        = CarsHelper.GetHelper().GetCarFromId(long.Parse(msg.Payload.Arguments[0]));
            var  text       = string.Empty;
            var  kb         = new KeyboardBuilder(bot);
            bool isAvalible = true;

            if (user.Money < car.Price)
            {
                text = $"❌ У Вас недостаточно наличных на покупку этого автомобиля." +
                       $"\n 💵 Ваш баланс: {user.Money}";
                isAvalible = false;
            }


            if ((garage.ParkingPlaces - garage.Cars.Split(";").Length - 1) <= 0)
            {
                text = $"❌ У Вас недостаточно парковочных мест в гараже. Освободите место и попробуйте ещё раз!";
                kb.AddButton("🔧 Перейти в гараж", "garage");
                kb.AddLine();
                isAvalible = false;
            }

            if (isAvalible)
            {
                Main.Api.Users.RemoveMoney(user.Id, car.Price);
                using (var db = new Database())
                {
                    car.Id = db.Cars.Count() + 1;

                    var engine = new Engine();
                    engine.Id     = db.Engines.Count() + 1;
                    engine.Name   = car.Manufacturer + " " + car.Model;
                    engine.Power  = car.Power;
                    engine.Weight = car.Weight;
                    engine.CarId  = car.Id;
                    db.Engines.Add(engine);

                    car.Engine = engine.Id;
                    car.Health = 100;
                    db.Cars.Add(car);

                    var gar = db.Garages.Single(g => g.UserId == user.Id);
                    gar.Engines = gar.Engines + $"{engine.Id};";
                    gar.Cars    = gar.Cars + $"{car.Id};";
                    db.SaveChanges();
                }
                text = $"🚗 Поздравляем с покупкой! Ваш новенький {car.Manufacturer} {car.Model} уже стоит в гараже!" +
                       $"\n ❗ Теперь укажите номер региона для автомобильного номера:";

                UsersCommandHelper.GetHelper().Add("buycarnumber", user.Id);
            }
            else
            {
                kb.AddButton("🚘 Перейти в автосалон", "autostore");
            }


            sender.Text(text, msg.ChatId, kb.Build());
        }
Beispiel #8
0
        public static string OldNewValueToRuss(string tableName, string propertyName, string value)
        {
            #region таблица заявок
            if (tableName == "tickets")
            {
                if (propertyName == "CourseRUR" ||
                    propertyName == "CourseUSD" ||
                    propertyName == "CourseEUR" ||
                    propertyName == "DeliveryCost" ||
                    propertyName == "AssessedCost" ||
                    propertyName == "AgreedCost" ||
                    propertyName == "ReceivedUSD" ||
                    propertyName == "ReceivedEUR" ||
                    propertyName == "ReceivedEUR" ||
                    propertyName == "ReceivedBLR" ||
                    propertyName == "GruzobozCost")
                {
                    return(MoneyMethods.MoneySeparator(value));
                }

                if (propertyName == "DriverID")
                {
                    return(DriversHelper.DriverIDToFioToPrint(value));
                }

                if (propertyName == "StatusIDOld" || propertyName == "StatusID")
                {
                    return(OtherMethods.TicketStatusToText(value));
                }

                if (propertyName == "CityID")
                {
                    return(CityHelper.CityIDToCityNameWithotCustom(value));
                }

                if (propertyName == "TrackIDUser")
                {
                    return(OtherMethods.TrackToText(Convert.ToInt32(value)));
                }

                if (propertyName == "DeliveryDate")
                {
                    return(value.Remove(value.Length - 8));
                }

                if (propertyName == "Comment")
                {
                    return(WebUtility.HtmlDecode(value));
                }

                if (propertyName == "PrintNakl" ||
                    propertyName == "PrintNaklInMap" ||
                    propertyName == "IsExchange" ||
                    propertyName == "WithoutMoney" ||
                    propertyName == "CheckedOut" ||
                    propertyName == "Phoned")
                {
                    return(value == "0" ? "нет" : "да");
                }

                if (propertyName == "OvDateFrom" || propertyName == "OvDateTo")
                {
                    return(String.IsNullOrEmpty(value) ? String.Empty : Convert.ToDateTime(value).ToString("HH:mm"));
                }
            }
            #endregion

            #region таблица пользователей
            if (tableName == "users")
            {
                if (propertyName == "SpecialClient" || propertyName == "IsCourse" || propertyName == "AllowApi")
                {
                    return(value == "0" ? "нет" : "да");
                }

                if (propertyName == "Status")
                {
                    return(UsersHelper.UserStatusToText(Convert.ToInt32(value)));
                }

                if (propertyName == "Role")
                {
                    return(UsersHelper.RoleToRuss(value));
                }

                if (propertyName == "Discount")
                {
                    return(String.Format("{0}%", value));
                }

                if (propertyName == "Password")
                {
                    return(String.Empty);
                }

                if (propertyName == "Validity" && value.Length >= 8)
                {
                    return(value.Remove(value.Length - 8));
                }

                if (propertyName == "BirthDay" && value.Length >= 8)
                {
                    return(value.Remove(value.Length - 8));
                }

                if (propertyName == "DateOfIssue" && value.Length >= 8)
                {
                    return(value.Remove(value.Length - 8));
                }
            }
            #endregion

            #region таблица грузов
            if (tableName == "goods")
            {
                if (propertyName == "Cost")
                {
                    return(MoneyMethods.MoneySeparator(value));
                }

                if (propertyName == "WithoutAkciza")
                {
                    return(value == "0" ? "нет" : "да");
                }
            }
            #endregion

            #region таблица профилей
            if (tableName == "usersprofiles")
            {
                if (propertyName == "StatusID")
                {
                    return(UsersProfilesHelper.UserProfileStatusToText(Convert.ToInt32(value)));
                }
            }
            #endregion

            #region таблица водителй
            if (tableName == "drivers")
            {
                if (propertyName == "StatusID" && !String.IsNullOrEmpty(value))
                {
                    return(DriversHelper.DriverStatusToText(Convert.ToInt32(value)));
                }

                if (value.Length >= 8 && (propertyName == "DateOfIssue" ||
                                          propertyName == "Validity" ||
                                          propertyName == "BirthDay" ||
                                          propertyName == "DriverPassportDateOfIssue" ||
                                          propertyName == "DriverPassportValidity" ||
                                          propertyName == "MedPolisDateOfIssue" ||
                                          propertyName == "MedPolisValidity"))
                {
                    return(value.Remove(value.Length - 8));
                }
            }
            #endregion

            #region таблица авто
            if (tableName == "cars")
            {
                if (propertyName == "TypeID" && !String.IsNullOrEmpty(value))
                {
                    return(CarsHelper.CarTypeToFullString(Convert.ToInt32(value)));
                }
            }
            #endregion

            #region таблица категорий
            if (tableName == "category")
            {
                if (propertyName == "Name")
                {
                    return(value);
                }
            }
            #endregion

            return(value);
        }
Beispiel #9
0
        static void Main(string[] args)
        {
            //string path = "b_should_be_easy.in";
            string pathC = "c_no_hurry.in";
            string pathD = "d_metropolis.in";
            string pathE = "e_high_bonus.in";

            string currentFile = pathD;

            string allFile = FileReader.ReadFile(currentFile);

            var           firstLine  = FileReader.GetFirstLine(allFile);
            List <string> otherLines = FileReader.GetOtherLines(allFile);
            Structure     structure  = Parser.ParseAll(firstLine, otherLines);

            int initialRides = structure.Rides.Count;

            List <Cart> carts = new List <Cart>();

            for (int i = 0; i < structure.Vehicles; i++)
            {
                Cart c = new Cart()
                {
                    Location = new Location()
                    {
                        Row = 0, Columm = 0
                    }
                };
                carts.Add(c);
            }


            var ridesDone  = 0;
            var totalRides = structure.Rides.Count;

            //For C
            // structure.Rides = CarsHelper.GetEarliestStart(structure.Rides);

            //For D
            structure.RemoveImpossibleRidesStart(0);
            //structure.RemoveFarRidesAndEarlyLong(3500,20000);
            //structure.RemoveRidesBetween(3000, 6000);
            //structure.RemoveFarRides(5000);
            structure.Rides = CarsHelper.GetEarliestStart3(structure.Rides);

            //structure.Rides = CarsHelper.GetByLatestStart(structure.Rides);



            for (int step = 0; step < structure.Steps; step++)
            {
                for (int cartid = 0; cartid < structure.Vehicles; cartid++)
                {
                    Cart cart = carts[cartid];
                    if (!cart.IsIdle && cart.NextEndTime == step)
                    {
                        cart.Location = cart.Ride.End;
                        structure.Rides.Remove(cart.Ride);
                        cart.RidesDone.Add(cart.Ride);
                        ridesDone++;
                        cart.Ride = null;
                    }

                    if (step % 200 == 0)
                    {
                        structure.RemoveImpossibleRides(step);
                        Console.Write($"\rStep {step} / {structure.Steps}; Rides {ridesDone}/{totalRides}");
                    }

                    if (cart.IsIdle)
                    {
                        Ride r = null;

                        //if (step == 0)
                        //{
                        //    r = structure.ChooseFirstRide(cart);
                        //}
                        //else
                        {
                            if (currentFile.Equals(pathC, StringComparison.InvariantCultureIgnoreCase))
                            {
                                r = structure.GetNextRideForC(step, cart);
                            }
                            else if (currentFile.Equals(pathD, StringComparison.InvariantCultureIgnoreCase))
                            {
                                r = structure.GetNextRide(step, cart);
                            }
                            else if (currentFile.Equals(pathE, StringComparison.InvariantCultureIgnoreCase))
                            {
                                r = structure.GetNextRide(step, cart);
                            }
                        }

                        if (r != null)
                        {
                            r.IsInUse = true;
                            cart.AssignRide(r, step);
                        }
                    }
                }
            }

            StringBuilder builder = new StringBuilder();

            totalRides = 0;

            for (int id = 0; id < carts.Count; id++)
            {
                totalRides += carts[id].RidesDone.Count;

                builder.Append(carts[id].RidesDone.Count);
                builder.Append(" ");

                var ids = carts[id].RidesDone.Select(x => x.Id).ToList();
                builder.Append(string.Join(" ", ids.ToArray()));
                builder.Append("\n");
            }

            Console.WriteLine("");
            Console.WriteLine("Rides done: " + totalRides.ToString());
            Console.WriteLine("Total rides " + initialRides.ToString());
            Console.WriteLine("Finished calculation for " + currentFile);

            File.WriteAllText("result2-" + currentFile + ".txt", builder.ToString());

            Console.ReadKey();
        }
Beispiel #10
0
        public void Execute(Message msg, IMessageSenderService sender, IBot bot)
        {
            if (Main.Api.Users.IsBanned(msg))
            {
                return;
            }

            if (!Main.Api.Users.CheckUser(msg))
            {
                var kb2 = new KeyboardBuilder(bot);
                kb2.AddButton("➕ Зарегистрироваться", "start");
                sender.Text("❌ Вы не зарегистрированы, нажмите на кнопку ниже, чтобы начать", msg.ChatId, kb2.Build());
                return;
            }
            if (msg.Payload != null)
            {
                if (msg.Payload.Arguments != null)
                {
                    var text = "🚘 Список автомобилей:\n";

                    var kb          = new KeyboardBuilder(bot);
                    var manufacture = string.Empty;
                    try
                    {
                        manufacture = msg.Payload.Arguments[0];
                    }catch
                    {
                        sender.Text("❌ Эту команду можно вызвать только с аргументом через кнопку.", msg.ChatId);
                        return;
                    }

                    List <Car> cars;
                    if (manufacture == "Rus")
                    {
                        var l1 = CarsHelper.GetHelper().Cars.Where(c => c.Manufacturer == "ВАЗ").ToList();
                        var l2 = CarsHelper.GetHelper().Cars.Where(c => c.Manufacturer == "Лада").ToList();
                        var l3 = CarsHelper.GetHelper().Cars.Where(c => c.Manufacturer == "Нива").ToList();
                        var l4 = CarsHelper.GetHelper().Cars.Where(c => c.Manufacturer == "Москвич").ToList();
                        var l5 = CarsHelper.GetHelper().Cars.Where(c => c.Manufacturer == "УАЗ").ToList();
                        cars = new List <Car>();

                        foreach (var car in l1)
                        {
                            cars.Add(car);
                        }
                        foreach (var car in l2)
                        {
                            cars.Add(car);
                        }
                        foreach (var car in l3)
                        {
                            cars.Add(car);
                        }
                        foreach (var car in l4)
                        {
                            cars.Add(car);
                        }
                        foreach (var car in l5)
                        {
                            cars.Add(car);
                        }
                    }
                    else
                    {
                        cars = CarsHelper.GetHelper().Cars.Where(c => c.Manufacturer == manufacture).ToList();
                    }

                    try
                    {
                        var offset = Int32.Parse(msg.Payload.Arguments[1]);

                        var countCars = cars.Count;

                        for (var i = 0; i < 10; i++)
                        {
                            try
                            {
                                var car = cars[i + (offset * 10)];
                                text += $"\n🚘 [{i + (offset * 10)}] {car.Manufacturer} {car.Model}" + $"| ⚡ {car.Power} лс., | ⚖ {car.Weight} кг." +
                                        $"\n💰 Цена: {car.Price} руб.\n";
                                if (sender.Platform == Fooxboy.NucleusBot.Enums.MessengerPlatform.Vkontakte)
                                {
                                    kb.AddButton($"🚗 {i + (offset * 10)}", "infocar", new List <string>()
                                    {
                                        car.Id.ToString()
                                    });
                                }
                                if (sender.Platform == Fooxboy.NucleusBot.Enums.MessengerPlatform.Telegam)
                                {
                                    kb.AddButton($"🚗 {i + (offset * 10)} [{car.Model}]", "infocar", new List <string>()
                                    {
                                        car.Id.ToString()
                                    });
                                }

                                if ((i == 3 && (countCars > 4 || countCars > 14 || countCars > 24)) || (i == 7 && (countCars > 8 || countCars > 18 || countCars > 28)))
                                {
                                    kb.AddLine();
                                }
                            }catch
                            {
                                break;
                            }
                        }

                        kb.AddLine();
                        if (offset > 0)
                        {
                            kb.AddButton($"◀ На страницу {offset - 1}", "getcars", new List <string>()
                            {
                                manufacture, $"{offset - 1}"
                            });
                        }
                        kb.AddButton("↩ Назад в автосалон", "autostore");
                        if (countCars > ((offset + 1) * 10))
                        {
                            kb.AddButton($"На страницу {offset + 1} ▶", "getcars", new List <string>()
                            {
                                manufacture, $"{offset + 1}"
                            });
                        }
                    }catch
                    {
                        for (var i = 0; i < 10; i++)
                        {
                            try
                            {
                                var car = cars[i];
                                text += $"\n🚘 [{i}] {car.Manufacturer} {car.Model}" + $"| ⚡ {car.Power} лс., | ⚖ {car.Weight} кг." +
                                        $"\n💰 Цена: {car.Price} руб.\n";
                                kb.AddButton($"🚗 {i}", "infocar", new List <string>()
                                {
                                    car.Id.ToString()
                                });
                                if (i == 4 || i == 8)
                                {
                                    kb.AddLine();
                                }
                            }
                            catch
                            {
                                break;
                            }
                        }
                        kb.AddLine();

                        kb.AddButton("↩ Назад в автомагазин", "autostore");
                        if (cars.Count > 10)
                        {
                            kb.AddButton("На страницу 2 ▶", "getcars", new List <string>()
                            {
                                manufacture, $"1"
                            });
                        }
                    }

                    if (cars.Count == 0)
                    {
                        text = "⚡ Автомобили от этого производителя скоро появятся!";
                    }
                    sender.Text(text, msg.ChatId, kb.Build());
                }
            }
        }
Beispiel #11
0
 public void Init(IBot bot, ILoggerService logger)
 {
     CarsHelper.GetHelper().InitCars(logger);
 }