public ActionResult Accept(string message, int RequestId)
        {
            try
            {
                var model = _db.Requests.Single(r => r.RequestId == RequestId);//_db.RequestFreights.Single(rf => rf.RequestId == RequestId);
                model.Status = 2;

                RequestEvent re = new RequestEvent();
                re.Status = 2;
                re.Message = message;
                re.EventDate = DateTime.Now;

                model.RequestEvents.Add(re);

                _db.SaveChanges();
                ViewBag.Message = "Заявка принята!";
            }
            catch
            {
                ViewBag.ErrMessage = @"Ошибка при ПРИНЯТИИ заявки";
                ViewBag.BackController = "Home";
                return View("Error");
            }
            return View("Signed");
        }
        public ActionResult Create(RequestCrane rc)
        {
            if (rc.Request.ApproverEmployeeId == 0)
            {
                ViewBag.ErrorMessage = "Веберите руководителя, который подпишет заявку!";
                return View(rc);
            }

            try
            {
                rc.Request.Status = 0;
                rc.Request.UserLogin = User.Identity.Name;
                rc.Request.UserFio = AccountManager.GetUserDisplayName(User.Identity.Name);
                rc.Request.PublishDate = DateTime.Now;
                rc.Request.IsDeleted = false;

                if (rc.Request.CustomerId == 0)
                    rc.Request.CustomerId = null;

                if (Utils.AccountManager.IsApprover(User.Identity.Name).Item2)
                {
                    rc.Request.Status = 1;
                    rc.Request.ApproveDate = DateTime.Now;
                    rc.Request.ApproverLogin = User.Identity.Name;
                    rc.Request.ApproverFio = Utils.AccountManager.GetUserDisplayName(User.Identity.Name);

                    RequestEvent re = new RequestEvent();
                    re.Status = 1;
                    re.EventDate = DateTime.Now;
                    rc.Request.RequestEvents.Add(re);
                }

                _db.RequestCranes.Add(rc);
                _db.SaveChanges();

                return View("Published", rc.Request.RequestId);
            }
            catch (DbEntityValidationException dbEx)
            {

                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        //TODO: Попытка удалить запись, у которой ExpDate истек
                    }
                }

                ViewBag.ErrMessage = "Ошибка при создании записи";
                ViewBag.BackController = "Home";
                return View("Error");
            }
        }
        public ActionResult Create(RequestPassenger rp)
        {
            if (ModelState.IsValid)
            {
                if (rp.Request.ApproverEmployeeId == 0)
                {
                    ViewBag.ErrorMessage = "Веберите руководителя, который подпишет заявку!";
                    return View(rp);
                }
                try
                {

                    rp.Request.Status = 0;
                    rp.Request.UserLogin = User.Identity.Name;
                    rp.Request.UserFio = AccountManager.GetUserDisplayName(User.Identity.Name);
                    rp.Request.PublishDate = DateTime.Now;
                    rp.Request.IsDeleted = false;

                    if (Utils.AccountManager.IsApprover(User.Identity.Name).Item2)
                    {
                        rp.Request.Status = 1;
                        rp.Request.ApproveDate = DateTime.Now;
                        rp.Request.ApproverLogin = User.Identity.Name;
                        rp.Request.ApproverFio = Utils.AccountManager.GetUserDisplayName(User.Identity.Name);

                        RequestEvent re = new RequestEvent();
                        re.Status = 1;
                        re.EventDate = DateTime.Now;
                        rp.Request.RequestEvents.Add(re);
                    }

                    if (rp.Request.CustomerId == 0)
                        rp.Request.CustomerId = null;

                    _db.RequestPassengers.Add(rp);
                    _db.SaveChanges();
                    return View("Published", rp.Request.RequestId);
                }
                catch
                {
                    ViewBag.ErrMessage = "Ошибка при создании записи";
                    ViewBag.BackController = "Passenger";
                    return View("Error");
                }
            }
            return View();
        }
        public ActionResult SignAll(int id)
        {
            if (!_db.RequestApprovers.Any(a => a.EmployeeId == id) && !User.IsInRole("LAN\\TR_Admins"))
            {
                ViewBag.BackController = "Home";
                return View("Denied");
            }

            try
            {
                var rqsts = _db.Requests.Where(rq => (rq.ApproverEmployeeId == id && (rq.Status == 0 || rq.Status == 3))).ToList();
                foreach (var rqst in rqsts)
                {
                    rqst.ApproveDate = DateTime.Now;
                    rqst.ApproverLogin = User.Identity.Name;
                    rqst.ApproverFio = AccountManager.GetUserDisplayName(User.Identity.Name);
                    rqst.Status = 1;

                    RequestEvent re = new RequestEvent();
                    re.Status = 1;
                    re.Message = String.Empty;
                    re.EventDate = DateTime.Now;

                    rqst.RequestEvents.Add(re);
                }
                _db.SaveChanges();
                ViewBag.Message = "Заявки подписаны!";
            }
            catch
            {
                ViewBag.Message = "Ошибка при подписи заявок, заявки не подписаны!";
            }
            return View("Signed");
        }
        public ActionResult Sign(string message, int RequestId)
        {
            if (User.IsInRole("TR_Admins") || AccountManager.IsApprover(User.Identity.Name).Item2)
            {
                try
                {
                    var model = _db.Requests.Single(r => r.RequestId == RequestId);
                    model.Status = 1;
                    model.ApproveDate = DateTime.Now;
                    model.ApproverLogin = User.Identity.Name;
                    model.ApproverFio = AccountManager.GetUserDisplayName(User.Identity.Name);

                    RequestEvent re = new RequestEvent();
                    re.Status = 1;
                    re.Message = message;
                    re.EventDate = DateTime.Now;

                    model.RequestEvents.Add(re);

                    _db.SaveChanges();
                    ViewBag.Message = "Заявка подписана!";
                    //return RedirectToAction("Details", new { id = RequestId });
                }
                catch
                {
                    ViewBag.ErrMessage = @"Ошибка при ПОДПИСИ заявки";
                    ViewBag.BackController = "Home";
                    return View("Error");
                }
                return View("Signed");
            }
            else
            {
                ViewBag.ErrMessage = "У текущего пользователя отсутствует право подписи заявок!";
                ViewBag.BackController = "Home";
                return View("Error");
            }
        }
        public ActionResult Edit(RequestCrane rc)
        {
            try
            {
                var model = _db.RequestCranes.Single(m => m.RequestId == rc.RequestId);

                model.Request.RequestDate = rc.Request.RequestDate;
                model.LicenceNumber = rc.LicenceNumber;
                model.WorkPlace = rc.WorkPlace;
                model.WorkObject = rc.WorkObject;
                model.WorkType = rc.WorkType;
                model.CraneType = rc.CraneType;
                model.PowerLineExists = rc.PowerLineExists;
                model.PowerPermission = rc.PowerPermission;
                model.Responsible = rc.Responsible;
                model.ProjectExists = rc.ProjectExists;
                model.ResponsibleOrder = rc.ResponsibleOrder;
                model.CustomerName = rc.CustomerName;
                model.Request.ApproverEmployeeId = rc.Request.ApproverEmployeeId;

                if (rc.Request.CustomerId == 0)
                    rc.Request.CustomerId = null;
                model.Request.CustomerId = rc.Request.CustomerId;

                if (model.Request.Status == 3 && User.Identity.Name.ToLower() == model.Request.UserLogin.ToLower())
                {
                    model.Request.Status = 0;
                    RequestEvent re = new RequestEvent();
                    re.Status = 0;
                    re.Message = String.Empty;
                    re.EventDate = DateTime.Now;
                    model.Request.RequestEvents.Add(re);
                }

                var modelSlingers = model.RequestCraneSlingers;
                var respSlingers = rc.RequestCraneSlingers;

                foreach (var modelSlinger in modelSlingers)
                {
                    //Существует ли такой груз в респонсе
                    bool slingerExistInResponse = false;

                    foreach (var respSlinger in respSlingers)
                    {
                        //Если обновление груза
                        if (respSlinger.SlingerId == modelSlinger.SlingerId)
                        {
                            modelSlinger.Office = respSlinger.Office;
                            modelSlinger.FIO = respSlinger.FIO;
                            modelSlinger.CertificateNumber = respSlinger.CertificateNumber;
                            modelSlinger.DateKnowledge = respSlinger.DateKnowledge;

                            slingerExistInResponse = true;
                        }
                    }

                    if (slingerExistInResponse == false)
                        modelSlinger.IsDeleted = true;
                }

                //Добавляем все новые грузы, т.е те, у которых CargoId == 0
                foreach (var respSlinger in respSlingers)
                    if (respSlinger.SlingerId == 0)
                        modelSlingers.Add(respSlinger);

                _db.SaveChanges();

                return RedirectToAction("Index", "Home");
            }
            catch
            {
                ViewBag.ErrMessage = "Ошибка при редактировании записи";
                ViewBag.BackController = "Home";
                return View("Error");
            }
        }
        public ActionResult Create(RequestFreight rf, IEnumerable<HttpPostedFileBase> files)
        {
            if (rf.Request.ApproverEmployeeId == 0)
            {
                    ViewBag.ErrorMessage = "Веберите руководителя, который подпишет заявку!";
                    return View(rf);
            }

            try
            {
                rf.Request.Status = 0;
                rf.Request.UserLogin = User.Identity.Name;
                rf.Request.UserFio = AccountManager.GetUserDisplayName(User.Identity.Name);
                rf.Request.PublishDate = DateTime.Now;
                rf.Request.IsDeleted = false;

                if (rf.Request.CustomerId == 0)
                    rf.Request.CustomerId = null;

                if (Utils.AccountManager.IsApprover(User.Identity.Name).Item2)
                {
                    rf.Request.Status = 1;
                    rf.Request.ApproveDate = DateTime.Now;
                    rf.Request.ApproverLogin = User.Identity.Name;
                    rf.Request.ApproverFio = Utils.AccountManager.GetUserDisplayName(User.Identity.Name);

                    RequestEvent re = new RequestEvent();
                    re.Status = 1;
                    re.EventDate = DateTime.Now;
                    rf.Request.RequestEvents.Add(re);
                }

                //Файлы
                if (files != null)
                {
                    foreach (var file in files)
                    {
                        if (file != null)
                        {
                            RequestAttachment attFile = new RequestAttachment();
                            attFile.Name = file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1);

                            int fl = file.ContentLength;
                            byte[] fc = new byte[fl];

                            file.InputStream.Read(fc, 0, fl);

                            attFile.Cont = fc;

                            rf.Request.RequestAttachments.Add(attFile);
                        }
                    }
                }

                _db.RequestFreights.Add(rf);
                _db.SaveChanges();

                return View("Published", rf.Request.RequestId);
            }
            catch (DbEntityValidationException dbEx)
            {

                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                        //TODO: Попытка удалить запись, у которой ExpDate истек
                    }
                }

                ViewBag.ErrMessage = "Ошибка при создании записи";
                ViewBag.BackController = "Home";
                return View("Error");
            }
        }
        public ActionResult Edit(RequestFreight rf, IEnumerable<HttpPostedFileBase> files, int[] oldFiles)
        {
            try
            {
                var model = _db.RequestFreights.Single(m => m.RequestId == rf.RequestId);
                var respCargoes = rf.RequestFreightCargoes;

                model.DestinationPoint = rf.DestinationPoint;
                model.OrderNumber = rf.OrderNumber;
                model.LoadingType = rf.LoadingType;
                model.LoadingAddress = rf.LoadingAddress;
                model.ContactName = rf.ContactName;
                model.Responsible = rf.Responsible;
                model.Request.RequestDate = rf.Request.RequestDate;
                model.Request.ApproverEmployeeId = rf.Request.ApproverEmployeeId;
                model.VehicleType = rf.VehicleType;

                if (rf.Request.CustomerId == 0)
                    rf.Request.CustomerId = null;
                model.Request.CustomerId = rf.Request.CustomerId;

                if (model.Request.Status == 3 && User.Identity.Name.ToLower() == model.Request.UserLogin.ToLower())
                {
                    model.Request.Status = 0;
                    RequestEvent re = new RequestEvent();
                    re.Status = 0;
                    re.Message = String.Empty;
                    re.EventDate = DateTime.Now;
                    model.Request.RequestEvents.Add(re);
                }

                var modelCargoes = model.RequestFreightCargoes;

                foreach (var modelCargo in modelCargoes)
                {
                    //Существует ли такой груз в респонсе
                    bool cargoExistInResponse = false;

                    foreach(var respCargo in respCargoes)
                    {
                        //Если обновление груза
                        if (respCargo.CargoId == modelCargo.CargoId)
                        {
                            modelCargo.CargoName = respCargo.CargoName;
                            modelCargo.Weight = respCargo.Weight;
                            modelCargo.Length = respCargo.Length;
                            modelCargo.Height = respCargo.Height;
                            modelCargo.Width = respCargo.Width;
                            modelCargo.Volume = respCargo.Volume;

                            cargoExistInResponse = true;
                        }
                    }

                    if (cargoExistInResponse == false)
                        modelCargo.IsDeleted = true;
                }

                //Добавляем все новые грузы, т.е те, у которых CargoId == 0
                foreach (var respCargo in respCargoes)
                    if (respCargo.CargoId == 0)
                        modelCargoes.Add(respCargo);

                //Удаляем файлы, которые пользователь отметил как удаленные
                var attForRemoving = new List<RequestAttachment>();
                if (oldFiles != null) //Если остался хоть один старый файл
                {
                    attForRemoving = model.Request.RequestAttachments.Where(a => !oldFiles.Contains(a.Id)).ToList();
                }
                else //Если пользователь удаляет все файлы
                {
                    attForRemoving = model.Request.RequestAttachments.Where(a => (a.IsDeleted == false || a.IsDeleted == null)).ToList();
                }
                foreach (var att in attForRemoving)
                {
                    att.IsDeleted = true;
                }

                //Добавляем новые файлы
                if (files != null)
                {
                    foreach (var file in files)
                    {
                        if (file != null)
                        {
                            RequestAttachment attFile = new RequestAttachment();
                            attFile.Name = file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1);

                            int fl = file.ContentLength;
                            byte[] fc = new byte[fl];

                            file.InputStream.Read(fc, 0, fl);

                            attFile.Cont = fc;
                            attFile.IsDeleted = false;

                            model.Request.RequestAttachments.Add(attFile);
                        }
                    }
                }

                _db.SaveChanges();

                return RedirectToAction("Index", "Home");
            }
            catch
            {
                ViewBag.ErrMessage = "Ошибка при редактировании записи";
                ViewBag.BackController = "Freight";
                return View("Error");
            }
        }
        public ActionResult Edit(RequestPassenger rp)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var model = _db.RequestPassengers.Single(m => m.RequestId == rp.RequestId);

                    model.DestinationPoint = rp.DestinationPoint;
                    model.PassengerAmount = rp.PassengerAmount;
                    model.ChildAmount = rp.ChildAmount;
                    model.Request.RequestDate = rp.Request.RequestDate;
                    model.OrderDate = rp.OrderDate;
                    model.OrderName = rp.OrderName;
                    model.OrderNumber = rp.OrderNumber;
                    model.TripPurpose = rp.TripPurpose;
                    model.TripDuration = rp.TripDuration;
                    model.SeatPlace = rp.SeatPlace;
                    model.SecondedPeople = rp.SecondedPeople;
                    model.Request.ApproverEmployeeId = rp.Request.ApproverEmployeeId;

                    if (rp.Request.CustomerId == 0)
                        rp.Request.CustomerId = null;

                    model.Request.CustomerId = rp.Request.CustomerId;

                    if (model.Request.Status == 3 && User.Identity.Name.ToLower() == model.Request.UserLogin.ToLower())
                    {
                        model.Request.Status = 0;
                        RequestEvent re = new RequestEvent();
                        re.Status = 0;
                        re.Message = String.Empty;
                        re.EventDate = DateTime.Now;
                        model.Request.RequestEvents.Add(re);
                    }

                    _db.SaveChanges();
                    return RedirectToAction("Index", "Home");
                }
                catch
                {
                    ViewBag.ErrMessage = "Ошибка при редактировании записи";
                    ViewBag.BackController = "Home";
                    return View("Error");
                }
            }
            return View();
        }