Пример #1
0
        public string Disable(Int32 id_loc_level, Int32 Last_place, string Status)
        {
            string Result = "";

            reservation expired = new reservation();
            expired.FindOnExpired("");
            place last = mp.place.Where(x => x.id_location_level == id_loc_level & x.Status != "Was replaced").OrderByDescending(x => x.NumberPlace).FirstOrDefault();
           // bool conti = true;
           // Int32 Last_place_2 = Last_place+1;
            for (int i = Last_place + 1; i <= last.NumberPlace; i++)
            {
                place not_working_place = mp.place.Where(x => x.id_location_level == id_loc_level & x.NumberPlace == i & x.Status != "Was replaced").FirstOrDefault();
                if (not_working_place.Status == "Occupied" & Status != "Not working")
                {
                    Result = "В сокращаемом диапазоне были обнаружены занятые места, их отключение невозможно, поэтому сокращаемый диапазон частично перевелся в состояние 'not working'";
                    Status = "Not working";
                    place occ = mp.place.Where(x => x.Status == "Occupied").OrderByDescending(x => x.NumberPlace).FirstOrDefault();
                    place recurs = new place();
                    recurs.Disable(id_loc_level,occ.NumberPlace,"Disabled");
                    // occ.NumberPlace + 1;
                    break;
                }
                else if (not_working_place.Status == "Occupied" & Status == "Not working")
                {
                    Result = "В связи с тем, что одно или более транспортных мест на данный момент находится на этом уровне парковки, места были отключены не полностью...";
                    break;
                }
            }

            place last2 = mp.place.Where(x => x.id_location_level == id_loc_level & x.Status != "Was replaced").OrderByDescending(x => x.NumberPlace).FirstOrDefault();

            for (int i = Last_place + 1; i <= last2.NumberPlace; i++)
            {
                place not_working_place = mp.place.Where(x => x.id_location_level == id_loc_level & x.NumberPlace == i & x.Status != "Was replaced").FirstOrDefault();
                if (not_working_place.Status != "Occupied")
                {
                    place change = new place();
                    if (not_working_place.Status != "Disabled" & not_working_place.Status != Status)
                    {

                        if (not_working_place.Status == "In waiting visit")
                        {
                            change.ChangeStatus(Status, not_working_place.id_location_place, 0);
                            reservation res = mp.reservation.Where(x => x.Status == "Active" & (x.id_location_place == not_working_place.id_location_place || x.id_alternative_location_place == not_working_place.id_location_place)).FirstOrDefault();
                            if (res != null)
                            {
                                place findmax;
                                if (Last_place != 0)
                                {
                                    findmax = mp.place.Where(x => (x.tariffonplace.PriceForHourWithoutAbonement >= res.place.tariffonplace.PriceForHourWithoutAbonement) & x.Status == "Free").OrderBy(x => x.tariffonplace.PriceForHourWithAbonement).FirstOrDefault();
                                }
                                else
                                {
                                    findmax = mp.place.Where(x => x.id_location_level != id_loc_level & (x.tariffonplace.PriceForHourWithoutAbonement >= res.place.tariffonplace.PriceForHourWithoutAbonement) & x.Status == "Free").OrderBy(x => x.tariffonplace.PriceForHourWithAbonement).FirstOrDefault();
                                }

                                if (findmax != null)
                                {
                                    change.ChangeStatus("In waiting visit", (long)findmax.id_location_place, (int)res.place.id_tariff_on_place);
                                    res.id_alternative_location_place = (int)findmax.id_location_place;
                                    mp.Entry(res).State = EntityState.Modified;
                                    mp.SaveChanges();
                                }
                                else if (findmax == null)
                                {
                                    place findmin;
                                    if (Last_place != 0)
                                    {
                                        findmin = mp.place.Where(x => (x.tariffonplace.PriceForHourWithoutAbonement < res.place.tariffonplace.PriceForHourWithoutAbonement) & x.Status == "Free").OrderByDescending(x => x.tariffonplace.PriceForHourWithAbonement).FirstOrDefault();
                                    }
                                    else
                                    {
                                        findmin = mp.place.Where(x => x.id_location_level != id_loc_level & (x.tariffonplace.PriceForHourWithoutAbonement < res.place.tariffonplace.PriceForHourWithoutAbonement) & x.Status == "Free").OrderByDescending(x => x.tariffonplace.PriceForHourWithAbonement).FirstOrDefault();
                                    }

                                    if (findmin != null)
                                    {
                                        change.ChangeStatus("In waiting visit", (long)findmin.id_location_place, 0);
                                        res.id_alternative_location_place = (int)findmin.id_location_place;
                                        mp.Entry(res).State = EntityState.Modified;
                                        mp.SaveChanges();
                                    }
                                    else
                                    {
                                        res.id_alternative_location_place = null;
                                        mp.Entry(res).State = EntityState.Modified;
                                        mp.SaveChanges();
                                    }
                                }
                            }
                        }
                        else { change.ChangeStatus(Status, not_working_place.id_location_place, 0); }
                    }
                }
            }

            
            return Result;
        }
Пример #2
0
        public string Run_this_level(Int32 id_loc_level)
        {
            string Result = "";
            reservation expired = new reservation();
            expired.FindOnExpired("");
            int ap = mp.place.Count(x => x.id_location_level == id_loc_level & x.Status != "Was replaced" & x.Status != "Disabled");

            for (int i = 0; i <= ap; i++)
            {
                place not_working_place = mp.place.Where(x => x.id_location_level == id_loc_level & x.NumberPlace == i & x.Status == "Not working").FirstOrDefault();
                if (not_working_place != null)
                {
                    place change = new place();

                    reservation res = mp.reservation.Where(x => x.Status == "Active" & (x.id_location_place == not_working_place.id_location_place)).FirstOrDefault();
                    if (res != null)
                    {
                        if (res.id_alternative_location_place != null)
                        {
                            change.FreePlace((long)res.id_alternative_location_place);
                        }
                        res.id_alternative_location_place = (int)not_working_place.id_location_place;
                        mp.Entry(res).State = EntityState.Modified;
                        mp.SaveChanges();
                        change.ChangeStatus("In waiting visit", not_working_place.id_location_place, 0);
                    }
                    else
                    {
                        change.FreePlace((long)not_working_place.id_location_place);
                    }
                }
            }


            return Result;
        }
Пример #3
0
        public ActionResult Stop_work(Int32 id_location_level, Int32 id_loc_pl, FormCollection form)
        {
            ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");

            reservation expired = new reservation();
            expired.FindOnExpired("");

            place not_working_place = mp.place.Where(x => x.id_location_place == id_loc_pl).FirstOrDefault();



                place change = new place();

                if (not_working_place.Status != "In waiting visit")
                {
                    change.ChangeStatus("Not working", id_loc_pl, 0);
                    reservation res = mp.reservation.Where(x => x.Status == "Active" & (x.id_location_place == id_loc_pl || x.id_alternative_location_place == id_loc_pl)).FirstOrDefault();
                    if (res != null)
                    {
                        place findmax = mp.place.Where(x => (x.tariffonplace.PriceForHourWithoutAbonement >= res.place.tariffonplace.PriceForHourWithoutAbonement) & x.Status == "Free").OrderBy(x => x.tariffonplace.PriceForHourWithAbonement).FirstOrDefault();
                        if (findmax != null)
                        {
                            change.ChangeStatus("In waiting visit", (long)findmax.id_location_place, (int)res.place.id_tariff_on_place);
                            res.id_alternative_location_place = (int)findmax.id_location_place;
                            mp.Entry(res).State = EntityState.Modified;
                            mp.SaveChanges();
                        }
                        else if (findmax == null)
                        {
                            place findmin = mp.place.Where(x => (x.tariffonplace.PriceForHourWithoutAbonement < res.place.tariffonplace.PriceForHourWithoutAbonement) & x.Status == "Free").OrderByDescending(x => x.tariffonplace.PriceForHourWithAbonement).FirstOrDefault();
                            if (findmin != null)
                            {
                                change.ChangeStatus("In waiting visit", (long)findmin.id_location_place, 0);
                                res.id_alternative_location_place = (int)findmin.id_location_place;
                                mp.Entry(res).State = EntityState.Modified;
                                mp.SaveChanges();
                            }
                            else
                            {
                                res.id_alternative_location_place = null;
                                mp.Entry(res).State = EntityState.Modified;
                                mp.SaveChanges();
                            }
                        }
                    }
                }
                else { change.ChangeStatus("Not working", id_loc_pl, 0); }
            
            //& (x.Status == "Free" || x.Status == "Not working" || x.Status == "In waiting visit")
            ViewData["Reservation"] = "";
            ViewData["Zone-Level"] = "Зона №" + Convert.ToString(not_working_place.levelzone.Parking_zone) + " ; Уровень:" + Convert.ToString(not_working_place.levelzone.Level) + " ; Тип уровня: " + not_working_place.levelzone.TypeLevel;
            ViewData["ReservationPlace"] = "Место №" + not_working_place.NumberPlace + " было успешно переведено в неактивное состояние.";
            return View(mp.place.Where(x => x.id_location_level == id_location_level & (x.Status == "Free" || x.Status == "Not working" || x.Status == "In waiting visit")).OrderBy(x => x.NumberPlace).ToList());
            
        }
Пример #4
0
        public ActionResult Start_work(Int32 id_location_level, Int32 id_loc_pl, FormCollection form)
        {
            ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
            reservation expired = new reservation();
            expired.FindOnExpired("");
            place not_working_place = mp.place.Where(x => x.id_location_place == id_loc_pl).FirstOrDefault();

            if (not_working_place.Status == "Not working")
            {
                place change = new place();

                reservation res = mp.reservation.Where(x => x.Status == "Active" & (x.id_location_place == id_loc_pl)).FirstOrDefault();
                if (res != null)
                {
                    if (res.id_alternative_location_place != null)
                    {
                        change.FreePlace((long)res.id_alternative_location_place);
                    }
                    res.id_alternative_location_place = id_loc_pl;
                    mp.Entry(res).State = EntityState.Modified;
                    mp.SaveChanges();
                    change.ChangeStatus("In waiting visit", id_loc_pl, 0);
                }
                else
                {
                    change.FreePlace((long)id_loc_pl);
                }
            }
            ViewData["Reservation"] = "";
            ViewData["Zone-Level"] = "Зона №" + Convert.ToString(not_working_place.levelzone.Parking_zone) + " ; Уровень:" + Convert.ToString(not_working_place.levelzone.Level) + " ; Тип уровня: " + not_working_place.levelzone.TypeLevel;           
            ViewData["ReservationPlace"] = "Место №" + not_working_place.NumberPlace + " было успешно переведено в активное состояние.";
            return View(mp.place.Where(x => x.id_location_level == id_location_level & (x.Status == "Free" || x.Status == "Not working" || x.Status == "In waiting visit")).OrderBy(x => x.NumberPlace).ToList());
        }
Пример #5
0
        public ActionResult Disabled_level(Int32 Parking_zone, Int32 id_location_level)
        {
            //Вернуть выборку по полученной зоне и значение ViewData
            ViewData["Reservation"] = "";
            ViewData["Zone"] = "Зона №" + Convert.ToString(Parking_zone);


            place dis = new place();
            ViewData["EditLevel"] = dis.Disable(id_location_level, 0,"Disabled");


            //Вернуть выборку по полученной зоне и значение ViewData
            //Из представления вынести подсчет сюда. и если роль админ то вернуть строку которая ниже. если нет, то с ограничениями
            //А именно те уровни, в которых кол-во мест не 0 по условию (!=disabled & !=Replaced)
            return View(mp.levelzone.Where(x => x.Parking_zone == Parking_zone));
        }
Пример #6
0
        public ActionResult ConnectReservation(Int32? tariff, Int32 ChoosePlace, Int32 id_location_level, FormCollection form)
        {
            ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
            reservation find = new reservation();
            find.FindOnExpired("");
            levelzone levz = mp.levelzone.Where(x => x.id_location_level == id_location_level).FirstOrDefault();
            Int32 zone = levz.Parking_zone;
            Int32 level = levz.Level;
            string type_level = levz.TypeLevel;
            ViewData["Zone-Level"] = "Зона №" + Convert.ToString(zone) + " ; Уровень:" + Convert.ToString(level) + " ; Тип уровня: " + type_level;
            ViewData["Reservation"] = "RESERVATION";

            if (User.Identity.IsAuthenticated)
            {
                string Log = User.Identity.Name.ToString();
                string Date = DateTime.Now.ToString("dd.MM.yy HH:mm");

                reservation activeres = mp.reservation.Where(x => x.Login == Log & x.Status == "Active").FirstOrDefault();
                if (activeres == null)
                {

                    reservation formedres = mp.reservation.Where(x => x.Login == Log & x.Status == "Formed").FirstOrDefault();
                    if (formedres != null)
                    {
                                ts exist = mp.ts.Where(x => x.Login == Log & x.Status == "True").FirstOrDefault();
                                if (exist != null)
                                {

                                    visit vis = mp.visit.Where(x => x.id_ts == exist.id_ts & x.DateOut == "dateout").FirstOrDefault();
                                    if (vis == null)
                                    {
                        usr us = mp.usr.Where(x => x.Login == Log).FirstOrDefault();
                        place free = mp.place.Where(x => x.id_location_place == ChoosePlace).FirstOrDefault();
                        if (us != null & free.Status == "Free")
                        {
                            if (us.Now_Balance >= 0)
                            {


                                    reservation_tariff tar = mp.reservation_tariff.Where(x => x.Status == "available" & x.id_Reservation_Tariff == formedres.id_Reservation_Tariff).FirstOrDefault();
                                    if (tar != null)
                                    {
                                        //Ниже допустимый коментируемый код
                                        tariffonplace p = mp.tariffonplace.Where(x => x.id_tariff_on_place == tariff & x.Status == "Active").FirstOrDefault();
                                        if (p != null) //до сюда
                                        {
                                            formedres.id_location_place = ChoosePlace;
                                            formedres.id_alternative_location_place = ChoosePlace;
                                            formedres.Status = "Active";
                                            formedres.Description = "Reservation connect";
                                            formedres.DateConnection = Date;
                                            DateTime mydate = Convert.ToDateTime(Date).AddHours(tar.ValidityPeriodFromTheTimeOfActivationInHour);//Согласно активному тарифу
                                            formedres.ApproximatelyDateOutFromActivity = Convert.ToString(mydate);
                                            mp.Entry(formedres).State = EntityState.Modified;
                                            mp.SaveChanges();
                                            place newplace = new place();
                                            newplace.ChangeStatus("In waiting visit", (long)formedres.id_location_place, 0);
                                        }
                                       // и соответственно противное условие тожн комментируемое
                                        else if (p==null) {
                                            formedres.id_location_place = ChoosePlace;
                                            formedres.id_alternative_location_place = ChoosePlace;
                                            mp.Entry(formedres).State = EntityState.Modified;
                                            mp.SaveChanges();

                                            ViewData["ReservationPlace"] = "Внимание, тариф для места изменился!";
                                            return View(mp.place.Where(x => x.id_location_level == id_location_level & x.Status == "Free").OrderBy(x => x.NumberPlace).ToList());
    
                                        }//Комментировать можно чтобы уменьшить время общения с автомобилистом, но и проинформировать по сути тоже надо
                                                //Подумать стоит ли делать это(комментированный примерный код) в ResController при подключении брони
                                    }
                                    else
                                    {
                                        //У формируемой брони изменился тариф.
                                        formedres.id_location_place = ChoosePlace;
                                        formedres.id_alternative_location_place = ChoosePlace;
                                        mp.Entry(formedres).State = EntityState.Modified;
                                        mp.SaveChanges();
                                        return RedirectToAction("Agreement", new { Controller = "Res" });
                                    }



                            }
                            else if (us.Now_Balance < 0)
                            {
                                ViewData["ReservationPlace"] = "Активирование брони с отрицательным балансом запрещено. Формируемая вами бронь сохранена, вы сможете подключить ее после пополнения баланса!";
                                formedres.id_location_place = ChoosePlace;
                                formedres.id_alternative_location_place = ChoosePlace;
                                mp.Entry(formedres).State = EntityState.Modified;
                                mp.SaveChanges();

                                return View(mp.place.Where(x => x.id_location_level == id_location_level & x.Status == "Free").OrderBy(x => x.NumberPlace).ToList());
                            }

                        }
                        else if (free.Status != "Free")
                        {
                            formedres.id_location_place = ChoosePlace;
                            formedres.id_alternative_location_place = ChoosePlace;
                            mp.Entry(formedres).State = EntityState.Modified;
                            mp.SaveChanges();
                            if (free.Status == "Occupied" || free.Status == "In waiting visit")
                            {
                                ViewData["ReservationPlace"] = "Место №" + free.NumberPlace + " занято!";
                            }
                            else
                            {
                                ViewData["ReservationPlace"] = "Место недоступно!";
                            }
                            return View(mp.place.Where(x => x.id_location_level == id_location_level & x.Status == "Free").OrderBy(x=>x.NumberPlace).ToList());
                        }
            }
                else
                {
                    ViewData["ReservationPlace"] = "Формиремая бронь сохранена, но Вы не можете активировать бронирование, пока одно из ваших ТС находится у нас на парковке!";
                                        formedres.id_location_place = ChoosePlace;
                        formedres.id_alternative_location_place = ChoosePlace;
                        mp.Entry(formedres).State = EntityState.Modified;
                        mp.SaveChanges();
                        return View(mp.place.Where(x => x.id_location_level == id_location_level & x.Status == "Free").OrderBy(x => x.NumberPlace).ToList());
                   
                                }
                    }
                    else
                    {
                        ViewData["ReservationPlace"] = "Активирование брони без наличия ТС запрещено. Формируемая вами бронь сохранена, вы сможете подключить ее после добавления вашего ТС!";
                        formedres.id_location_place = ChoosePlace;
                        formedres.id_alternative_location_place = ChoosePlace;
                        mp.Entry(formedres).State = EntityState.Modified;
                        mp.SaveChanges();
                        return View(mp.place.Where(x => x.id_location_level == id_location_level & x.Status == "Free").OrderBy(x => x.NumberPlace).ToList());
                    }
                    }
                    else
                    {
                        //МОЖНО СДЕЛАТЬ ПЕРЕНАПРАВЛЕНИЕ СРАЗУ НА Reservation в ResController с этим же самым сообщением. Или на принятие соглашения.
                        ViewData["ReservationPlace"] = "Система не нашла формирующейся заявки! Возможно, она была удалена вами.";
                        return View(mp.place.Where(x => x.id_location_level == id_location_level & x.Status == "Free").OrderBy(x => x.NumberPlace).ToList());
                    }





                }

                else if (activeres != null)
                {
                    ViewData["ReservationPlace"] = "Вы уже имеете активное забронированное месторасположение!";
                    return View(mp.place.Where(x => x.id_location_level == id_location_level & x.Status == "Free").ToList());
                }
                return RedirectToAction("Reservation", new { Controller = "Res" });
                //  return View(mp.place.Where(x => x.id_location_level == id_location_level).ToList());
            }
            else
            {
                return RedirectToAction("LogOn", new { Controller = "Account" });
            }
        }
Пример #7
0
        public ActionResult Run_this_zone(Int32 Parking_zone)
        {

            var levels = mp.levelzone.Where(x => x.Parking_zone == Parking_zone).ToList();
            string Mes = "";
            if (levels != null)
            {
                foreach (var lev in levels)
                {
                    if (mp.place.Where(x => x.id_location_level == lev.id_location_level).FirstOrDefault() != null)
                    {
                        place runLev = new place();
                        if (Mes == "")
                        {
                            Mes = runLev.Run_this_level((Int32)lev.id_location_level);
                        }
                        else
                        {
                            runLev.Run_this_level((Int32)lev.id_location_level);
                        }
                    }
                }
            }
                ViewData["EditZone1"] = Mes;
            return View(mp.parkingzone.ToList());
        }
Пример #8
0
        public bool Revoke(string Describe, reservation obj, string Date)
        {
            bool result = false;
            try
            {
                //format my date have view:  string d = "21.11.14 20:00";

                decimal price = 0;
                usr ur = mp.usr.Where(x => x.Login == obj.Login).FirstOrDefault();
                balance bl = new balance();
                place p = new place();

                //Можно упростить задачу. Следующим коментируемым кодом
                /*  obj.id_alternative_location_place == obj.id_location_place
                 * то есть если место уже изменено на другое, то сделать автомобилисту бесплатную бронь(т.к. нарушена его потребность)
                 * соответственно проверка на то что лучше это место или хуже не понадобится вообще.
                 * 
                 * сейчас действует схема, что бронь бесплатна если новое выданное место хуже или его нет вообще. (риск он принимал в
                 * соглашении)
                */
                if (obj.id_alternative_location_place != null) {


                    if (Describe != "Reservation was used")
                    {
                        //освобождающее место либо достанется кому-то, либо переведтся в свободное состояние
                        p.FreePlace((long)obj.id_alternative_location_place);
                    }

                    //Эта проверка может непонадобится, если обдумать описанный комментарий выше.
                    if (p.bestornot((long)obj.id_location_place, (long)obj.id_alternative_location_place) == true ||
                        obj.id_alternative_location_place == obj.id_location_place)
                        {


                long span = 0;

                if (Describe == "Reservation was expired" | Describe == "Reservation was revoke")
                {
                    span = Convert.ToDateTime(Date).Ticks - Convert.ToDateTime(obj.DateConnection).Ticks;
                }
                else if (Describe == "Reservation was used")
                {



                    DateTime mydate = Convert.ToDateTime(obj.DateConnection).AddMinutes(obj.reservation_tariff.FirstFreeTimeInMinutes);
                    if (mydate <= Convert.ToDateTime(DateTime.Now.ToString("dd.MM.yy HH:mm")))
                    {
                        span = Convert.ToDateTime(Date).Ticks - mydate.Ticks;
                    }


                }





                    decimal priceinmin = (decimal)(obj.reservation_tariff.PriceInRubForHourHightFreeTime) / 60;

                            price = (decimal)TimeSpan.FromTicks(span).TotalMinutes * priceinmin;
                            ur.Now_Balance = ur.Now_Balance - price;
                            mp.Entry(ur).State = EntityState.Modified;
                            mp.SaveChanges();
                        }

                    
                    //Да и еще, расчеты делаются точно. Но не округлить ли баланс на выходе в лучшую сторону для автомобилиста, до копейки(сотых) хотя бы.
                }

                
                bl.Operation("Debit", price, (decimal)ur.Now_Balance, ur.Login, Describe, Date);
                
                result = true;
            }
            catch
            {
                result = false;
            }
            return result;
        }
Пример #9
0
        public ActionResult Change_level(Int32 EditPlace, Int32? ChTariffForPlaces, Int32 id_location_level, Int32 Parking_zone, string NewAmountPlaces, string AddPlaces, string Status, string TariffForAllPlace, FormCollection form)
        {
            //В случае успеха вернуть
            // return RedirectToAction("Levels", new { Parking_zone = Parking_zone });
            levelzone edit_level = mp.levelzone.Where(x => x.id_location_level == id_location_level).FirstOrDefault();

            //  ViewData["EditLevel"] = "ChTariffForPlaces: " + ChTariffForPlaces + " " + AmPlace + " " + AdPlace + " " + type.TypeLevel + " " + type.id_location_level + " " + TariffForAllPlace + " Status:" + Status;

            if (EditPlace == 1)
            {
                Int32 AmountPlace = 0;
                Int32 AddPlace = 0;
                int ap = mp.place.Count(x => x.id_location_level == id_location_level & x.Status != "Was replaced" & x.Status != "Disabled");

                    if (ChTariffForPlaces != null & NewAmountPlaces == null & AddPlaces == null & TariffForAllPlace != "True")
                    {
                        ViewData["EditLevel"] = "Выбирая тариф необходимо выбрать как его применить, а именно, либо ко всем местам уровня (поставив соответсвующую галочку), либо задать новое или добавляемое количество мест. Причем, задавая новое количество мест меньше текущего количества, выбранный тариф проигнорируется соответственно.";
                        ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
                        return View(edit_level);
                    }
                    else
                        if (ChTariffForPlaces == null & NewAmountPlaces == null & AddPlaces == null & TariffForAllPlace != "True")
                        {
                            ViewData["EditLevel"] = "Изменений не произошло.";
                            ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
                            return View(edit_level);
                        }

                    
                    if (NewAmountPlaces != null  & AddPlaces == null)
                    {
                        try
                        {
                            AmountPlace = Convert.ToInt32(NewAmountPlaces);
                            if (AmountPlace < 0) //|| AmountPlace == ap)
                            {
                                ViewData["EditLevel"] = "Неверный формат ввода. Значение должно быть положительным и целочисленным"; //+ отличаться от текущего количества мест в уровне.";
                                ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
                                return View(edit_level);
                            }
                        }
                        catch
                        {
                            ViewData["EditLevel"] = "Неверный формат ввода. Значение должно быть положительным и целочисленным"; //+ отличаться от текущего количества мест в уровне.";
                            ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
                            return View(edit_level);
                        }
                        if (AmountPlace <= ap)
                        {
                            //Если добавлять поле "Количество удаляемых мест из уровня, то в качестве параметра AmountPlace отсылать значение: ap-amount_delete_place
                            //таким образом я как бы вновь получу новое количество мест, а это значит, что и номер последнего места.
                            //ViewData["EditLevel"] = "Количество мест в уровне уменьшилось на " + Convert.ToString(ap-AmountPlace);
                            place dis = new place();
                            ViewData["EditLevel"] = dis.Disable(id_location_level, AmountPlace,"Disabled");




                        }
                        else if (AmountPlace > ap)
                        {
                            if (ChTariffForPlaces != null)
                            {
                                tariffonplace ac = mp.tariffonplace.Where(x => x.id_tariff_on_place == ChTariffForPlaces & x.Status == "Active").FirstOrDefault();
                                if (ac != null)
                                {

                                    place ad_pl = new place();
                                    string message = ad_pl.AddPlace(id_location_level, AmountPlace - ap, Status, (long)ChTariffForPlaces);
                                    if (message != "")
                                    {
                                        ViewData["EditLevel"] = message;
                                    }










                                }
                                else
                                {
                                    ViewData["EditLevel"] = "Выбранный тариф перестал быть активным";
                                    ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
                                    return View(edit_level);
                                }
                            }
                            else
                            {
                                ViewData["EditLevel"] = "Необходимо задать тариф.";
                                ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
                                return View(edit_level);
                            }
                        }


                    }
                    else if (NewAmountPlaces == null & AddPlaces != null )
                    {
                        try
                        {
                            AddPlace = Convert.ToInt32(AddPlaces);
                            if (AddPlace <= 0)
                            {
                                ViewData["EditLevel"] = "Неверный формат ввода. Значение должно быть больше нуля и целочисленным.";
                                ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
                                return View(edit_level);
                            }
                        }
                        catch
                        {
                            ViewData["EditLevel"] = "Неверный формат ввода. Значение должно быть больше нуля и целочисленным.";
                            ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
                            return View(edit_level);
                        }

                        if (ChTariffForPlaces != null)
                        {
                            tariffonplace ac = mp.tariffonplace.Where(x => x.id_tariff_on_place == ChTariffForPlaces & x.Status == "Active").FirstOrDefault();
                            if (ac != null)
                            {
                                



                                place ad_pl = new place();
                                string message = ad_pl.AddPlace(id_location_level, AddPlace, Status, (long)ChTariffForPlaces);
                                if (message != "")
                                {
                                    ViewData["EditLevel"] = message;
                                }



                            }
                            else
                            {
                                ViewData["EditLevel"] = "Выбранный тариф перестал быть активным";
                                ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
                                return View(edit_level);
                            }
                        }
                        else
                        {
                            ViewData["EditLevel"] = "Необходимо задать тариф.";
                            ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
                            return View(edit_level);
                        }

                    }



                
                if (TariffForAllPlace == "True")
                {
                    if (ChTariffForPlaces != null)
                    {
                        tariffonplace ac = mp.tariffonplace.Where(x => x.id_tariff_on_place == ChTariffForPlaces & x.Status == "Active").FirstOrDefault();
                        if (ac != null)
                        {
                            //int apo = mp.place.Count(x => x.id_location_level == id_location_level & x.Status != "Was replaced" & x.Status != "Disabled"); 
                            if (ap != 0)
                            {
                                //Тогда обновить тариф для всех мест в уровне, причем так же с учетом брони
                                var allplace = mp.place.Where(x => x.id_location_level == id_location_level & x.Status != "Was replaced" & x.Status != "Disabled").ToList();
                                if (allplace != null)
                                {
                                    string Mes = "";
                                    string Mes2 = "";
                                    foreach (var ch in allplace)
                                    {
                                        if (ch.Status != "Occupied")
                                        {
                                            reservation searchactiveres = mp.reservation.Where(x => x.id_location_place == ch.id_location_place & x.Status == "Active").FirstOrDefault();
                                            if (searchactiveres != null)
                                            {
                                                if (searchactiveres.place.id_tariff_on_place != ChTariffForPlaces)
                                                {
                                                   Mes = "Обновление тарифа для любого забронированного расположения запрещено даже если место временно не доступно.";
                                                }
                                            }
                                            else
                                            {
                                                place thplace = mp.place.Where(x => x.id_location_level == ch.id_location_level & x.NumberPlace == ch.NumberPlace & x.Status == "Was replaced" & x.id_tariff_on_place == ChTariffForPlaces).FirstOrDefault();
                                                if (thplace == null)
                                                {
                                                    if (ch.id_tariff_on_place != ChTariffForPlaces)
                                                    {
                                                        place place_new = new place();
                                                        place_new.id_location_level = ch.id_location_level;
                                                        place_new.id_tariff_on_place = (long)ChTariffForPlaces;
                                                        place_new.Status = ch.Status;
                                                        place_new.NumberPlace = ch.NumberPlace;
                                                        place_new.id_alternative_tariff_on_place = ChTariffForPlaces;
                                                        mp.place.Add(place_new);
                                                        mp.SaveChanges();

                                                        ch.Status = "Was replaced";
                                                        mp.Entry(ch).State = EntityState.Modified;
                                                        mp.SaveChanges();
                                                    }
                                                }
                                                else
                                                {
                                                    thplace.Status = ch.Status;
                                                    mp.Entry(thplace).State = EntityState.Modified;
                                                    mp.SaveChanges();

                                                    ch.Status = "Was replaced";
                                                    mp.Entry(ch).State = EntityState.Modified;
                                                    mp.SaveChanges();
                                                }

                                            }
                                        }
                                        else
                                        {
                                            Mes2 = "Обновление тарифа запрещено для расположений на которых простаивает транспортное средство.";
                                        }
                                    }
                                    if (Mes2 == "")
                                    {
                                        ViewData["EditLevel"] = Mes;
                                    }
                                    else if (Mes2 != "")
                                    {
                                        ViewData["EditLevel"] = Mes2;
                                    }
                                    if (Mes != "" & Mes2 != "")
                                    {
                                        ViewData["EditLevel"] = "Обновление выполнено частично, т.к. 1." + Mes + " 2." + Mes2;
                                    }
                                }
                                else
                                {
                                    ViewData["EditLevel"] = "Возможно, все места заняты и выполнить обновление тарифа невозможно. Рекомендуется выполнять обновление тарифа всех мест для временно недоступного уровня в целом";
                                    ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
                                    return View(edit_level);
                                }
                            }
                            else
                            {
                                ViewData["EditLevel"] = "Количество мест в этом уровне не превышает нуля. Обновление запрещено.";
                                ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
                                return View(edit_level);
                            }
                        }
                        else
                        {
                            ViewData["EditLevel"] = "Выбранный тариф перестал быть активным";
                            ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
                            return View(edit_level);
                        }
                    }
                    else
                    {
                        ViewData["EditLevel"] = "Необходимо задать тариф.";
                        ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
                        return View(edit_level);
                    }

                }

            }
            else { ViewData["EditLevel"] = "Изменений не произошло."; }
            ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
            return View(edit_level);
        }
Пример #10
0
 public ActionResult Temporarily_not_working_zone(Int32 Parking_zone)
 {
     var levels = mp.levelzone.Where(x => x.Parking_zone == Parking_zone).ToList();
     string Mes = "";
     if (levels != null)
     {
         foreach (var lev in levels)
         {
             if (mp.place.Where(x => x.id_location_level == lev.id_location_level).FirstOrDefault() != null)
             {
                 place dis = new place();
                 if (Mes == "")
                 {
                     dis.Disable((Int32)lev.id_location_level, 0, "Not working");
                 }
                 else
                 {
                     dis.Disable((Int32)lev.id_location_level, 0, "Not working");
                 }
             }
         }
     }
     if (Mes != "")
     {
         ViewData["EditZone1"] = "В связи с тем, что одно или более транспортных мест на данный момент находится на этой зоне парковки, места в уровнях на которых находятся эти ТС были отключены не полностью соответственно...";
     }
     return View(mp.parkingzone.ToList());
 }
Пример #11
0
        public ActionResult Choose_tariff_on_place(Int32 not_working_place, Int32 choose_tariff_on_place, FormCollection form)
        {//Может вывести в качестве информации текущий тариф?? 
            reservation expired = new reservation();
            expired.FindOnExpired("");
            ViewData["Reservation"] = "";
            ViewData["ActiveTariffs"] = mp.tariffonplace.Where(x => x.Status == "Active");
            place not_working_plac = mp.place.Where(x => x.id_location_place == not_working_place & (x.Status=="Free" || x.Status=="Not working")).FirstOrDefault();
            if (not_working_plac != null)
            {
                tariffonplace choosetop = mp.tariffonplace.Where(x => x.id_tariff_on_place == choose_tariff_on_place & x.Status == "Active").FirstOrDefault();
                if (choosetop != null)
                {

                    reservation searchactiveres = mp.reservation.Where(x => x.id_location_place == not_working_place & x.Status == "Active").FirstOrDefault();
                    if (searchactiveres != null)
                    {
                        ViewData["ReservationPlace"] = "Вы не можете изменить тариф для этого места, пока в этом расположении нуждается один из участников системы";
                    }
                    else
                    {
                        place thplace = mp.place.Where(x => x.id_location_level == not_working_plac.id_location_level & x.NumberPlace == not_working_plac.NumberPlace & x.Status == "Was replaced" & x.id_tariff_on_place == choose_tariff_on_place).FirstOrDefault();
                        if (thplace == null)
                        {
                            if (not_working_plac.id_tariff_on_place != choose_tariff_on_place)
                            {
                                place place_new = new place();
                                place_new.id_location_level = not_working_plac.id_location_level;
                                place_new.id_tariff_on_place = choose_tariff_on_place;
                                place_new.Status = not_working_plac.Status;
                                place_new.NumberPlace = not_working_plac.NumberPlace;
                                place_new.id_alternative_tariff_on_place = choose_tariff_on_place;
                                mp.place.Add(place_new);
                                mp.SaveChanges();

                                not_working_plac.Status = "Was replaced";
                                mp.Entry(not_working_plac).State = EntityState.Modified;
                                mp.SaveChanges();
                                ViewData["ReservationPlace"] = "Тариф для места №" + not_working_plac.NumberPlace + " был успешно сменен.";
                            }
                            ViewData["ReservationPlace"] = "Тариф для места №" + not_working_plac.NumberPlace + " не отличался от предыдущего.";
                            //Перекинуть на представление редактирования в качестве кода сообщения выше будет txt=2, в том представлении оно определится
                        }
                        else
                        {
                            thplace.Status = not_working_plac.Status;
                            mp.Entry(thplace).State = EntityState.Modified;
                            mp.SaveChanges();

                            not_working_plac.Status = "Was replaced";
                            mp.Entry(not_working_plac).State = EntityState.Modified;
                            mp.SaveChanges();
                            ViewData["ReservationPlace"] = "Тариф для места №" + not_working_plac.NumberPlace + " был успешно сменен.";
                        }

                    }

                    //return View(mp.place.Where(x => x.id_location_level == not_working_plac.id_location_level & x.Status != "Was replaced").OrderBy(x=>x.NumberPlace).ToList());

                    ViewData["Zone-Level"] = "Зона №" + Convert.ToString(not_working_plac.levelzone.Parking_zone) + " ; Уровень:" + Convert.ToString(not_working_plac.levelzone.Level) + " ; Тип уровня: " + not_working_plac.levelzone.TypeLevel;
                    return View(mp.place.Where(x => x.id_location_level == not_working_plac.id_location_level & (x.Status == "Free" || x.Status == "Not working" || x.Status == "In waiting visit")).OrderBy(x => x.NumberPlace).ToList());
                }
                else
                {
                    return RedirectToAction("Place_tariff", new { objp = not_working_place, txt = 1 });
                }
            }
            else
            {
                ViewData["ReservationPlace"] = "Вы не можете изменить тариф для этого места, пока в этом расположении нуждается один из участников системы";
                ViewData["Zone-Level"] = "Зона №" + Convert.ToString(not_working_plac.levelzone.Parking_zone) + " ; Уровень:" + Convert.ToString(not_working_plac.levelzone.Level) + " ; Тип уровня: " + not_working_plac.levelzone.TypeLevel;
                return View(mp.place.Where(x => x.id_location_level == not_working_plac.id_location_level & (x.Status == "Free" || x.Status == "Not working" || x.Status == "In waiting visit")).OrderBy(x => x.NumberPlace).ToList());

            }
        }
Пример #12
0
        public ActionResult RegisterIn(ts numb)
        {
                if (ModelState.IsValidField("Number"))
                {
                    visitparameters vp = mp.visitparameters.Where(x => x.Status == "Active").FirstOrDefault();
                    if (vp != null)
                    {
                        reservation r = new reservation();
                        r.FindOnExpired("");
                        ts searchts = mp.ts.Where(x => x.Number == numb.Number & x.Status == "True").FirstOrDefault();
                        if (searchts != null)
                        {
                            visit nvis = new visit();
                                            visit vis = mp.visit.Where(x => x.id_ts == searchts.id_ts & x.DateOut == "dateout").FirstOrDefault();
                                            if (vis == null)
                                            {
                                                place p = new place();
                                                string Log = searchts.Login;
                                                string Date = DateTime.Now.ToString("dd.MM.yy HH:mm");
                                                reservation res = mp.reservation.Where(x => x.Login == Log & x.Status == "Active").FirstOrDefault(); //Существует ли бронь
                                                if (res != null)
                                                {
                                                    if (res.id_alternative_location_place != null)
                                                    {

                                                        nvis.RegisterIn((long)res.id_alternative_location_place, searchts.id_ts, Date, vp.id_vis_param);
                                                        res.DateOutFromActivity = Date;
                                                        res.Status = "Closed";
                                                        res.Description = "Reservation was used";
                                                        mp.Entry(res).State = EntityState.Modified;
                                                        mp.SaveChanges();
                                                        r.Revoke("Reservation was used", res, Date);
                                                        p.ChangeStatus("Occupied", (long)res.id_alternative_location_place, (Int32)res.place.id_alternative_tariff_on_place);
                                                    }
                                                    else
                                                    {
                                                        ViewData["ExceptionRegisterIn"] = "Изначально выбранное место этим ТС было закрыто, других свободных мест на данный момент нет"; //, с броней ничего не делать. Будет ждать свободных, не дождется - умрет сама.
                                                        return View("RegisterIn");
                                                    }
                                                }
                                                else
                                                {
                                                    place autoplace = mp.place.Where(x => x.Status == "Free").OrderBy(x => x.tariffonplace.PriceForHourWithoutAbonement).FirstOrDefault();
                                                    if (autoplace != null)
                                                    {
                                                        nvis.RegisterIn((long)autoplace.id_location_place, searchts.id_ts, Date, vp.id_vis_param);
                                                        p.ChangeStatus("Occupied", (long)autoplace.id_location_place, 0);
                                                    }
                                                    else
                                                    {
                                                        ViewData["ExceptionRegisterIn"] = "Свободных мест нет!";
                                                        return View("RegisterIn");
                                                    }
                                                    //Автоматический расчет мест";
                                                }
                                            }
                                            else
                                            {
                                                ViewData["ExceptionRegisterIn"] = "Возможно, Вы ошиблись при вводе регистрационного номера, т.к. указанное вами ТС уже находится на парковке.";
                                                return View("RegisterIn");
                                            }
                        }
                        else
                        {
                            ViewData["ExceptionRegisterIn"] = "TC не найдено в бд";
                            return View("RegisterIn");
                        }

                    }
                    else
                    {
                        ViewData["ExceptionRegisterIn"] = "Осутствуют параметры въезда, активной записи не найдено";
                        return View("RegisterIn");
                    }







                    return RedirectToAction("Index", new { Controller = "Home"});
                }
                else
                {
                    return View("RegisterIn");
                }
            

        }
Пример #13
0
        public ActionResult RegisterOut(ts numb)
        {
            ViewData["ActiveVisit"] = mp.visit.Where(x => x.DateOut == "dateout").ToList();
            if (ModelState.IsValidField("Number"))
            {
                ts searchts = mp.ts.Where(x => x.Number == numb.Number & x.Status == "True").FirstOrDefault();
                if (searchts != null)
                {
                    usingtariffonabonementforvisit expiredabonement = new usingtariffonabonementforvisit();
                    expiredabonement.ExpiredAbonement(searchts.Login);
                    visit vis = mp.visit.Where(x => x.id_ts == searchts.id_ts & x.DateOut == "dateout").FirstOrDefault();
                    if (vis != null)
                    {
                        Int64 id_abonement_u = 0;
                        bool dual = false;
                        tariffonplace top = mp.tariffonplace.Where(x => x.id_tariff_on_place == vis.place.id_alternative_tariff_on_place).FirstOrDefault();
                        decimal PriceForPlace = 0;
                        usingtariffonabonementforvisit abontar = mp.usingtariffonabonementforvisit.Where(x => x.Login == searchts.Login & x.Status == "Active").FirstOrDefault();

                        if (abontar != null)
                        {
                            PriceForPlace = top.PriceForHourWithAbonement;
                        }
                        else
                        {
                            var searchab = mp.usingtariffonabonementforvisit.Where(x => x.Status == "Not active" & x.Login == searchts.Login).ToList();
                            
                            int count = searchab.Count();
                            int i = 0;
                            foreach (var s1 in searchab)
                            {
                                DateTime max = Convert.ToDateTime(s1.DateOutFromActivity);
                                foreach (var maxdate in searchab)
                                {
                                    if (i < count)
                                    {
                                        if (max >= Convert.ToDateTime(maxdate.DateConnection))
                                        {
                                            max = Convert.ToDateTime(maxdate.DateConnection);
                                            if (max > Convert.ToDateTime(vis.DateIn))
                                            {
                                                id_abonement_u = maxdate.id_abonement;
                                            }
                                        }
                                        i++;
                                    }
                                    else { break; }
                                }
                                break;
                            }
                            if (id_abonement_u != 0)
                            {  
                                //Осталось учесть, если абонемент который на время сдох во время стоянки.
                            //Тогда поделить на 2 части. Первая по абонементской цене до этой даты, вторая по обычной, после выхода абонемента из строя
                            //Делаю в этой ветке, т.к. автомобилист уже мог подключить новый абонемент, а эта ветка происходит если нового
                            //не было найдено
                            //Причем это пригодится только для первой попытки выезда.
                            dual = true;
                            }
                            PriceForPlace = top.PriceForHourWithoutAbonement;
                        }

                        string Date = DateTime.Now.ToString("dd.MM.yy HH:mm");
                        decimal price = 0;
                        usr ur = mp.usr.Where(x => x.Login == searchts.Login).FirstOrDefault();
                        balance bl = new balance();
                        place p = new place();

                        int y = 0;
                        if (vis.FirstAttemptGoOut == "dateout2")
                        {
                            //В минуты время простоя.
                            long span = 0;
                            DateTime timein = Convert.ToDateTime(vis.DateIn).AddMinutes(vis.visitparameters.FirstFreeTimeInMinutes);
                            if (timein < Convert.ToDateTime(Date))
                            {
                                if (dual == false)
                                {
                                    span = Convert.ToDateTime(Date).Ticks - timein.Ticks;

                                    //наличие абонемента играет роль
                                    decimal priceinmin = (decimal)(PriceForPlace) / 60;
                                    price = (decimal)TimeSpan.FromTicks(span).TotalMinutes * priceinmin;
                                    ur.Now_Balance = ur.Now_Balance - price;
                                    mp.Entry(ur).State = EntityState.Modified;
                                    mp.SaveChanges();
                                    bl.Operation("Debit", price, (decimal)ur.Now_Balance, ur.Login, "Register Out. First Attempt.", Date);
                                }
                                else
                                {
                                    usingtariffonabonementforvisit uab = mp.usingtariffonabonementforvisit.Where(x => x.id_abonement == id_abonement_u).FirstOrDefault();
                            
                                    long span2 = 0;
                                    span = Convert.ToDateTime(uab.DateOutFromActivity).Ticks - timein.Ticks;
                                    span2 = Convert.ToDateTime(Date).Ticks - Convert.ToDateTime(uab.DateOutFromActivity).Ticks;
                                    decimal priceinmin1 = (decimal)(top.PriceForHourWithoutAbonement) / 60;
                                    decimal priceinmin2 = (decimal)(top.PriceForHourWithAbonement) / 60;
                                    price = ((decimal)TimeSpan.FromTicks(span).TotalMinutes * priceinmin1) + ((decimal)TimeSpan.FromTicks(span2).TotalMinutes * priceinmin2);
                                    ur.Now_Balance = ur.Now_Balance - price;
                                    mp.Entry(ur).State = EntityState.Modified;
                                    mp.SaveChanges();
                                    bl.Operation("Debit", price, (decimal)ur.Now_Balance, ur.Login, "Register Out. First Attempt. With a both price, because your abonement was disabled during idle time", Date);
                                }
                            }
                            MyParkingEntities updout = new MyParkingEntities();
                            vis.FirstAttemptGoOut = Date;
                            mp.Entry(vis).State = EntityState.Modified;
                            mp.SaveChanges();
                            y = 1;
                        }
                        if (y == 0)
                        {
                            if (vis.FirstAttemptGoOut != "dateout2" & vis.NextAttemptGoOut == "dateout3")
                            {
                                long span = Convert.ToDateTime(Date).Ticks - Convert.ToDateTime(vis.FirstAttemptGoOut).Ticks;
                                decimal minutes = (decimal)TimeSpan.FromTicks(span).TotalMinutes - (decimal)vis.visitparameters.FirstFreeTimeOnChangeBalans;

                                if (minutes > 0)
                                {
                                    price = Math.Abs(minutes) * ((decimal)PriceForPlace / 60);
                                    ur.Now_Balance = ur.Now_Balance - price;
                                    mp.Entry(ur).State = EntityState.Modified;
                                    mp.SaveChanges();
                                    bl.Operation("Debit", price, (decimal)ur.Now_Balance, ur.Login, "Register Out. Second Attempt", Date);

                                }
                                y = 1;
                                MyParkingEntities updout = new MyParkingEntities();
                                vis.NextAttemptGoOut = Date;
                                mp.Entry(vis).State = EntityState.Modified;
                                mp.SaveChanges();
                            }

                        }
                        if (y == 0)
                        {
                            if (vis.NextAttemptGoOut != "dateout3")
                            {
                                //Сколько прошло от той попытки.
                                long span = Convert.ToDateTime(Date).Ticks - Convert.ToDateTime(vis.NextAttemptGoOut).Ticks;
                                decimal minutesnow = (decimal)TimeSpan.FromTicks(span).TotalMinutes;
                                //
                                //Для дальнейшего определения использован ли параметр бесплатного времени на покрытие брони.
                                long span2 = Convert.ToDateTime(vis.NextAttemptGoOut).Ticks - Convert.ToDateTime(vis.FirstAttemptGoOut).Ticks;
                                decimal minutes = (decimal)TimeSpan.FromTicks(span2).TotalMinutes;
                                //decimal minutes2 = (decimal)TimeSpan.FromTicks(span2).TotalMinutes - (decimal)vis.visitparameters.FirstFreeTimeOnChangeBalans;
                                if (minutes - (decimal)vis.visitparameters.FirstFreeTimeOnChangeBalans >= 0)
                                {
                                    price = Math.Abs(minutesnow) * ((decimal)PriceForPlace / 60);
                                    ur.Now_Balance = ur.Now_Balance - price;
                                    mp.Entry(ur).State = EntityState.Modified;
                                    mp.SaveChanges();
                                    bl.Operation("Debit", price, (decimal)ur.Now_Balance, ur.Login, "Register Out. Next Attempt.", Date);
                                    //y = 1;
                                    MyParkingEntities updout = new MyParkingEntities();
                                    vis.NextAttemptGoOut = Date;
                                    mp.Entry(vis).State = EntityState.Modified;
                                    mp.SaveChanges();
                                }
                                else if (minutes - (decimal)vis.visitparameters.FirstFreeTimeOnChangeBalans < 0)
                                {
                                    if ((minutes + minutesnow - (decimal)vis.visitparameters.FirstFreeTimeOnChangeBalans) < 0)
                                    {
                                        MyParkingEntities updout = new MyParkingEntities();
                                        vis.NextAttemptGoOut = Date;
                                        mp.Entry(vis).State = EntityState.Modified;
                                        mp.SaveChanges();
                                    }
                                    else if ((minutes + minutesnow - (decimal)vis.visitparameters.FirstFreeTimeOnChangeBalans) >= 0)
                                    {
                                        price = Math.Abs((minutes + minutesnow - (decimal)vis.visitparameters.FirstFreeTimeOnChangeBalans)) * ((decimal)PriceForPlace / 60);
                                        ur.Now_Balance = ur.Now_Balance - price;
                                        mp.Entry(ur).State = EntityState.Modified;
                                        mp.SaveChanges();
                                        bl.Operation("Debit", price, (decimal)ur.Now_Balance, ur.Login, "Register Out. Next Attempt.", Date);
                                        //y = 1;
                                        MyParkingEntities updout = new MyParkingEntities();
                                        vis.NextAttemptGoOut = Date;
                                        mp.Entry(vis).State = EntityState.Modified;
                                        mp.SaveChanges();
                                    }
                                }
                            }
                        }
                        if (searchts.usr.Now_Balance >= 0)
                        {
                            //Если абонемент на кол-во посещений, то прибавить единицу и проверить не истек ли и если да, то сразу здесь же закрыть.
                            vis.DateOut = Date;
                            mp.Entry(vis).State = EntityState.Modified;
                            mp.SaveChanges();
                            place fp = new place();
                            fp.FreePlace(vis.id_location_place);
                            //разделить эти изменения по методам возникает ошибка.
                          // usingtariffonabonementforvisit abontar2 = mp.usingtariffonabonementforvisit.Where(x => x.Name_tariff_on_abonement == abontar.Name_tariff_on_abonement).FirstOrDefault();

                            //MyParkingEntities forabonement = new MyParkingEntities();
                            if (abontar != null)
                            {
                                abontar.NumOfVisitsMadeWithUsingThisTariff = abontar.NumOfVisitsMadeWithUsingThisTariff + 1;
                                mp.Entry(abontar).State = EntityState.Modified;
                               mp.SaveChanges();
                                usingtariffonabonementforvisit afterupdabontar = mp.usingtariffonabonementforvisit.Where(x => x.Login == searchts.Login & x.Status == "Active").FirstOrDefault();

                                if (abontar.tariffonabonementforvisit.Max_Num_visits_in_this_tariff != null)
                                {
                                    if (abontar.tariffonabonementforvisit.Max_Num_visits_in_this_tariff == afterupdabontar.NumOfVisitsMadeWithUsingThisTariff)
                                    {
                                        abontar.Status = "Expired";
                                        abontar.DateOutFromActivity = Date;
                                        mp.Entry(abontar).State = EntityState.Modified;
                                        mp.SaveChanges();
                                    }
                                }
                            }
                        }
                        else
                        {
                            ViewData["ExceptionRegisterOut"] = "Баланс отрицателен, полный выезд невозможен";
                            return View("RegisterOut");
                        }



                    }
                    else
                    {
                        ViewData["ExceptionRegisterOut"] = "Возможно, Вы ошиблись при вводе регистрационного номера, т.к. указанное вами ТС на парковке не найдено";
                        return View("RegisterOut");
                    }
                }
                else
                {
                    ViewData["ExceptionRegisterOut"] = "Возможно, Вы ошиблись при вводе регистрационного номера, т.к. указанное вами TC не найдено в бд";
                    return View("RegisterOut");
                }
                return RedirectToAction("Index", new { Controller = "Home"});
            }
            else
            {
                return View("RegisterOut");
            }
        }
Пример #14
0
        public string AddPlace(Int32 id_loc_level, Int32 amount_added_place, string Status, long id_tariff_on_place)
        {
            string Result = "";
            reservation expired = new reservation();
            expired.FindOnExpired("");
            place last = mp.place.Where(x => x.id_location_level == id_loc_level & x.Status != "Was replaced" & x.Status != "Disabled").OrderByDescending(x => x.NumberPlace).FirstOrDefault();
            Int32 last_place = 0;
            if (last != null)
            {
                last_place = last.NumberPlace+1;
            }
            else { last_place = 1; }

            for (int i = last_place; i < last_place + amount_added_place; i++)
            {
                place disabled = mp.place.Where(x => x.id_location_level == id_loc_level & x.Status == "Disabled" & x.NumberPlace == i).FirstOrDefault();
                place change = new place();
                if (disabled != null)
                {
                    reservation res = mp.reservation.Where(x => x.Status == "Active" & (x.id_location_place == disabled.id_location_place)).FirstOrDefault();
                    if (res != null)
                    {

                        if (Status == "Free" & disabled.id_tariff_on_place == id_tariff_on_place)
                        {
                            if (res.id_alternative_location_place != null)
                            {
                                change.FreePlace((long)res.id_alternative_location_place);
                            }
                            res.id_alternative_location_place = (int)disabled.id_location_place;
                            mp.Entry(res).State = EntityState.Modified;
                            mp.SaveChanges();
                            change.ChangeStatus("In waiting visit", disabled.id_location_place, 0);

                            //Т.е. админ должен потом решить включить ли то место с со СТАРЫМ тарифом или ждать пока бронь кончится,
                            //а потом как доступ к изменению тарифу будет открыт(как закончится бронь) он его изменит и включит.
                            //Совпадающий тариф учитывается
                        }
                        else if (Status == "Free" & disabled.id_tariff_on_place != id_tariff_on_place)
                        {
                            change.ChangeStatus("Not working", disabled.id_location_place, 0);
                            Result = "0";
                        }
                        if (Status != "Free" & disabled.id_tariff_on_place != id_tariff_on_place)
                        {
                            if (Result != "0")
                            {
                                Result = "1";
                            }
                            change.ChangeStatus("Not working", disabled.id_location_place, 0);
                        }
                        else if (Status != "Free" & disabled.id_tariff_on_place == id_tariff_on_place)
                        {
                            change.ChangeStatus("Not working", disabled.id_location_place, 0);
                        }
                    }
                    else
                    {

                        disabled.Status = Status;
                        disabled.id_tariff_on_place = id_tariff_on_place;
                        disabled.id_alternative_tariff_on_place = (int)id_tariff_on_place;
                        mp.Entry(disabled).State = EntityState.Modified;
                        mp.SaveChanges();
                        if (Status == "Free")
                        {
                            change.FreePlace((long)disabled.id_location_place);
                        }
                    }
                }
                else
                {
                    place di = mp.place.Where(x => x.id_location_level == id_loc_level & x.Status == "Occupied" & x.NumberPlace == i).FirstOrDefault();
                    if (di == null)
                    {
                        place new_place = new place();
                        new_place.NumberPlace = i;
                        new_place.Status = Status;
                        new_place.id_tariff_on_place = id_tariff_on_place;
                        new_place.id_alternative_tariff_on_place = (int)id_tariff_on_place;
                        new_place.id_location_level = id_loc_level;
                        mp.place.Add(new_place);
                        mp.SaveChanges();
                        if (Status == "Free")
                        {
                            place new_place_search = mp.place.Where(x => x.NumberPlace == i & x.Status == Status & x.id_tariff_on_place == id_tariff_on_place & x.id_location_level == id_loc_level & x.id_alternative_tariff_on_place == (int)id_tariff_on_place).FirstOrDefault();
                            change.FreePlace((long)new_place_search.id_location_place);
                        }
                    }
                }
            }
            if (Result == "0")
            {
                Result = "К некоторым местам смена тарифа будет доступна по истечении действия активных записей бронирований, которые прикреплены к этим местам. К местам, к которым не удалось произвести смену тарифа, был присвоен статус 'Not working', их можно так же включить не меняя тариф, перейдя в просмотр мест этого уровня.";
            }
            else if (Result == "1")
            {
                Result = "К некоторым местам не удалось произвести смену тарифа, поскольку их ожидают активные записи бронирования. Смена тарифа будет доступна по истечении действия активных записей бронирований.";
            }
            return Result;
        }
Пример #15
0
        public ActionResult Run_this_level(Int32 Parking_zone, Int32 id_location_level)
        {
            //Вернуть выборку по полученной зоне и значение ViewData
            ViewData["Reservation"] = "";
            ViewData["Zone"] = "Зона №" + Convert.ToString(Parking_zone);
            //Зоны запускать и выключать так же, только в цикле подставлять id_loca_level которые ей принадлежат и запускать уже написанные методы
            
            place runLev = new place();
            ViewData["EditLevel"] = runLev.Run_this_level(id_location_level);
            //ViewData["EditLevel"] = dis.Disable(id_location_level, 0, "Not working");

            //Вернуть выборку по полученной зоне и значение ViewData
            //Из представления вынести подсчет сюда. и если роль админ то вернуть строку которая ниже. если нет, то с ограничениями
            //А именно те уровни, в которых кол-во мест не 0 по условию (!=disabled & !=Replaced)
            return View(mp.levelzone.Where(x => x.Parking_zone == Parking_zone));
        }
Пример #16
0
        //Нужен для регистрации выезда, так же сойдет для отката(и истечения) брони:   
         //Можно попробовать задействовать при включении места. Мое место  включить и сразу все обновить, а альтернативное
        //уже не нужное отправить сюда
        public bool FreePlace(long free_id_loc_place)
        {
            
            bool res = true;
            place fp = mp.place.Where(x => x.id_location_place == free_id_loc_place).FirstOrDefault();
            var obj = mp.reservation.Where(x => x.Status == "Active" & x.id_alternative_location_place == null).ToList();
            int count = obj.Count();
            place pl = new place();
            if (count > 0)
            {
                long id_user_reserv = 0;
                int i = 0;
                foreach (var search in obj)
                {
                    DateTime min = Convert.ToDateTime(search.DateConnection);
                    foreach (var mindate in obj)
                    {
                        if (i < count)
                        {
                            if (min <= Convert.ToDateTime(mindate.DateConnection))
                            {
                                min = Convert.ToDateTime(mindate.DateConnection);
                                id_user_reserv = mindate.id_reservation_user;
                            }
                            i++;
                        }
                        else { break; }
                    }
                    break;
                }
                reservation myfind = mp.reservation.Where(x => x.id_reservation_user == id_user_reserv).FirstOrDefault();
                myfind.id_alternative_location_place = (int)free_id_loc_place;
                mp.Entry(myfind).State = EntityState.Modified;
                mp.SaveChanges();
                //Если освобождающееся место лучше или такое же
                if (pl.bestornot((long)myfind.id_location_place, free_id_loc_place) == true)
                {
                    pl.ChangeStatus("In waiting visit", free_id_loc_place, (int)myfind.place.id_tariff_on_place);
                }
                //если нет
                else
                {
                    pl.ChangeStatus("In waiting visit", free_id_loc_place, 0);
                }

               res = true;
            }
            else
            {
                int newfr = 0;
                var eq = mp.reservation.Where(x =>  x.Status == "Active" & x.id_alternative_location_place != x.id_location_place & x.id_alternative_location_place != free_id_loc_place).ToList();
               int e = eq.Count();
                //long id_u_r = 0;
               // int coun = 0;

                if (e > 0)
                {
                    foreach (var s1 in eq)
                    {
                        place fineq = mp.place.Where(x => x.id_location_place == s1.id_alternative_location_place).FirstOrDefault();

                            if ((fp.tariffonplace.PriceForHourWithoutAbonement > fineq.tariffonplace.PriceForHourWithoutAbonement) &
                             (fp.tariffonplace.PriceForHourWithoutAbonement <= s1.place.tariffonplace.PriceForHourWithoutAbonement))
                                //alt<new<=first 
                            {
                                //Можно модернизировать путем определения ранней даты. Кто раньше забронировался, тому и получше достанется
                                //присвоить и получить
                                newfr = (int)s1.id_alternative_location_place;
                                s1.id_alternative_location_place = (int)free_id_loc_place;
                                mp.Entry(s1).State = EntityState.Modified;
                                mp.SaveChanges();
                               pl.ChangeStatus("In waiting visit", free_id_loc_place, (int)fp.id_tariff_on_place);          
                               break;
                            }

                            
                        
                    }//Разъединил. Сначала те, кто могут подняться к лучшему, потом те, кто могут отпустить более лучшее место, потом
                    //те, кто могут из худшего перейти в лучшее сразу. Может быть удалить первую часть, оставив только 3-ю вместо нее?
                    if (newfr == 0)//последнее добавленное
                    {
                        foreach (var s1 in eq)
                        {
                            place fineq = mp.place.Where(x => x.id_location_place == s1.id_alternative_location_place).FirstOrDefault();
                            if ((fp.tariffonplace.PriceForHourWithoutAbonement >= s1.place.tariffonplace.PriceForHourWithoutAbonement) &
                            (fp.tariffonplace.PriceForHourWithoutAbonement < fineq.tariffonplace.PriceForHourWithoutAbonement))
                            {//alt>new>=first
                                newfr = (int)s1.id_alternative_location_place;
                                s1.id_alternative_location_place = (int)free_id_loc_place;
                                mp.Entry(s1).State = EntityState.Modified;
                                mp.SaveChanges();
                                pl.ChangeStatus("In waiting visit", free_id_loc_place, (int)s1.place.id_tariff_on_place);
                            break;
                            }
                            
                        }
                    }


                    if (newfr == 0)//последнее добавленное
                    {
                        foreach (var s1 in eq)
                        {// alt<first<=new
                            place fineq = mp.place.Where(x => x.id_location_place == s1.id_alternative_location_place).FirstOrDefault();
                            if (((s1.place.tariffonplace.PriceForHourWithoutAbonement > fineq.tariffonplace.PriceForHourWithoutAbonement) &
                                 (fp.tariffonplace.PriceForHourWithoutAbonement >= s1.place.tariffonplace.PriceForHourWithoutAbonement)))
                            {
                                newfr = (int)s1.id_alternative_location_place;
                                s1.id_alternative_location_place = (int)free_id_loc_place;
                                mp.Entry(s1).State = EntityState.Modified;
                                mp.SaveChanges();
                                pl.ChangeStatus("In waiting visit", free_id_loc_place, (int)fp.id_tariff_on_place);
                                break;
                            }
                        }
                    }
                }
                    if (newfr != 0)
                    {
                        pl.FreePlace((long)newfr);
                    }
                    else
                    {
                        pl.ChangeStatus("Free", free_id_loc_place, 0);
                        res = false ;
                    }
            }
            return res;
        }
Пример #17
0
        public ActionResult Connect()
        {
            reservation find = new reservation();
            find.FindOnExpired("");
            if (User.Identity.IsAuthenticated)
            {
                string Log = User.Identity.Name.ToString();
                string Date = DateTime.Now.ToString("dd.MM.yy HH:mm");
                reservation formedres = mp.reservation.Where(x => x.Login == Log & x.Status == "Formed").FirstOrDefault();


                            ts exist = mp.ts.Where(x => x.Login == Log & x.Status == "True").FirstOrDefault();
                            if (exist != null)
                            {

                visit vis = mp.visit.Where(x => x.id_ts == exist.id_ts & x.DateOut == "dateout").FirstOrDefault();
                if (vis == null)
                {

                usr us = mp.usr.Where(x => x.Login == Log).FirstOrDefault();
                if (formedres.id_location_place != null)
                {
                    place free = mp.place.Where(x => x.id_location_place == formedres.id_location_place).FirstOrDefault();
                    if (us != null & free.Status == "Free")
                    {
                        if (us.Now_Balance >= 0)
                        {


                                reservation_tariff tar = mp.reservation_tariff.Where(x => x.Status == "available" & x.id_Reservation_Tariff == formedres.id_Reservation_Tariff).FirstOrDefault();
                                if (tar != null)
                                {
                                    formedres.Status = "Active";
                                    formedres.Description = "Reservation connect";
                                    formedres.DateConnection = Date;
                                    DateTime mydate = Convert.ToDateTime(Date).AddHours(tar.ValidityPeriodFromTheTimeOfActivationInHour);//Согласно активному тарифу
                                    formedres.ApproximatelyDateOutFromActivity = Convert.ToString(mydate);
                                    mp.Entry(formedres).State = EntityState.Modified;
                                    mp.SaveChanges();
                                    place newplace = new place();
                                    newplace.ChangeStatus("In waiting visit", (long)formedres.id_location_place,0);
                                }
                                else
                                {
                                    ViewData["AnswerFromReservation"] = "Данный тариф бронирования не активен. Пожалуйста, переформируйте заявку!";
                                }

                        }
                        else if (us.Now_Balance < 0)
                        {
                            ViewData["AnswerFromReservation"] = "У Вас отрицательный баланс, активирование бронирования запрещено!";
                        }
                    }

                    else if (free.Status != "Free")
                    {
                        if (free.Status == "Occupied" || free.Status == "In waiting visit")
                        {
                            ViewData["AnswerFromReservation"] = "Месторасположение занято!";
                        }
                        else
                        {
                            ViewData["AnswerFromReservation"] = "Место недоступно!";
                        }
                        
                    }
                }
                else if (formedres.id_location_place == null)
                {
                    ViewData["AnswerFromReservation"] = "Месторасположение не задано!";
                }
            }
                else
                {
                    ViewData["AnswerFromReservation"] = "Формиремая бронь сохранена, но Вы не можете активировать бронирование, пока хотя бы одно из ваших ТС находится у нас на парковке!";
                }
                            }
                            else
                            {
                                ViewData["AnswerFromReservation"] = "Активирование бронирования без наличия ТС запрещено!";
                            }

                ViewData["ReservationTariff"] = mp.reservation_tariff.Where(x => x.Status == "available").ToList();
                return View(mp.reservation.Where(x => x.Login == Log & (x.Status == "Formed" || x.Status == "Active")).ToList());
            }
            else
            {
                return RedirectToAction("LogOn", new { Controller = "Account" });
            }
        }