public ActionResult AccrueExec(HttpPostedFileBase upload)
        {
            AccruiesViewModel model = new AccruiesViewModel()
            {
                Accruies = new List <AccrueItem>()
            };
            Dictionary <string, double>     stavki    = new Dictionary <string, double>();
            IEnumerable <UsersExchangeData> users_all = DepartmentsController.getDomainUsers();


            if (upload != null)
            {
                using (var package = new ExcelPackage(upload.InputStream))
                {
                    var Sheet   = package.Workbook.Worksheets[1];
                    int lastRow = Sheet.Dimension.End.Row;
                    int lastCol = Sheet.Dimension.End.Column;
                    int i       = 5;
                    UsersExchangeData userdata;
                    do
                    {
                        // обновляем данные
                        if (Sheet.Cells[i, 1].Value != null)
                        {
                            ApplicationUser user     = null;
                            string          username = Sheet.Cells[i, 1].Value.ToString();
                            userdata = DepartmentsController.CheckDomainUserExists(username, users_all);
                            if (userdata != null)
                            {
                                user = manager.FindByName(userdata.UserLogin);
                                if (user == null)
                                {
                                    user           = new ApplicationUser();
                                    user.UserName  = userdata.UserLogin;
                                    user.FullName  = userdata.FullName;
                                    user.Email     = "";
                                    user.ShortName = username;
                                    var res = manager.Create(user);
                                }
                                else
                                {
                                    user.ShortName = username;
                                }
                                db.SaveChanges();
                            }
                        }
                        else
                        {
                            userdata = null;
                        }

                        if (userdata != null && Sheet.Cells[i, 3].Value != null)
                        {
                            if (!String.IsNullOrEmpty(Sheet.Cells[i, 1].Value.ToString()))
                            {
                                if (!String.IsNullOrEmpty(Sheet.Cells[i, 3].Value.ToString()))
                                {
                                    double v;
                                    if (double.TryParse(Sheet.Cells[i, 3].Value.ToString(), out v))
                                    {
                                        stavki.Add(Sheet.Cells[i, 1].Value.ToString().Trim().ToUpper(), v);
                                        db.updShowSalary(manager.FindByName(userdata.UserLogin), v);
                                    }
                                }
                            }
                        }
                        i++;
                    } while (i <= lastRow);
                }
                model.RequestsIds = new List <int>();
                foreach (KeyValuePair <string, double> stavka in stavki)
                {
                    var request = db.PaymentRequests.Where(p => p.RecipientUser.ShortName.Trim().ToUpper() == stavka.Key && p.RequestState == PaymentRequestState.Confirmed).ToList();
                    //var request = (from p in db.PaymentRequests where p.RecipientUser.ShortName.Trim().ToUpper() == stavka.Key && p.RequestState == PaymentRequestState.Confirmed select p).ToList();
                    foreach (var p in request)
                    {
                        AccrueItem m = new AccrueItem()
                        {
                            RequestId     = p.PaymentRequestId,
                            UserShortName = stavka.Key,
                            ProjectName   = p.Project.Name,
                            UserId        = p.RecipientUser.Id,
                            ProjectId     = p.Project.ProjectId,
                            Sum           = p.SumType == PaymentRequestType.Times ? PaymentRequest.RoundSum(p.TimesOrSum * stavka.Value) : p.TimesOrSum,
                            Comments      = p.SumType == PaymentRequestType.Times ? "=" + p.TimesOrSum + " часов" : ""
                        };

                        bool find = false;
                        for (int l = 0; l < model.Accruies.Count; l++)
                        {
                            if (model.Accruies[l].ProjectId == m.ProjectId && model.Accruies[l].UserId == m.UserId)
                            {
                                find = true;
                                model.Accruies[l].Sum += m.Sum;
                            }
                        }

                        if (!find)
                        {
                            model.Accruies.Add(m);
                        }

                        model.RequestsIds.Add(p.PaymentRequestId);
                    }
                }
            }

            return(View(model));
        }
        public ActionResult Edit(PaymentRequestEditModel input)
        {
            if (ModelState.IsValid)
            {
                var             currentUser = manager.FindById(User.Identity.GetUserId());
                Project         prj         = db.Projects.SingleOrDefault(x => x.Name.Trim() == input.ProjectName.Trim());
                ApplicationUser recipient   = db.Users.SingleOrDefault(x => x.FullName == input.UserName);
                PaymentRequest  request     = db.PaymentRequests.Find(input.PaymentRequestId);

                if (request != null)
                {
                    string pre_fileName = !String.IsNullOrEmpty(request.AttachedFileName) ? System.IO.Path.Combine(Server.MapPath("~/App_Data/Uploads"), request.AttachedFileName) : "";

                    if ((pre_fileName != "") && input.DeleteAttachedFile)
                    {
                        System.IO.File.Delete(pre_fileName);
                    }

                    string fileName = input.File != null ? Environment.TickCount + "_" + System.IO.Path.GetFileName(input.File.FileName) : "";
                    if (fileName != "")
                    {
                        try
                        {
                            if (pre_fileName != "")
                            {
                                System.IO.File.Delete(pre_fileName);
                            }

                            var path = System.IO.Path.Combine(Server.MapPath("~/App_Data/Uploads"), fileName);
                            input.File.SaveAs(path);
                        }
                        catch (Exception e)
                        {
                            ModelState.AddModelError("", "Ошибка загрузки файла " + e.Message);
                            GenerateProjectsList();
                            return(View(input));
                        }
                    }

                    if (recipient != null)
                    {
                        if (prj == null)
                        {
                            Department dept = db.Departments.SingleOrDefault(x => x.Boss.Id == currentUser.Id);
                            if (dept == null)
                            {
                                ModelState.AddModelError("", "Пользователь не РП ");
                                GenerateProjectsList();
                                return(View(input));
                            }
                            prj = db.Projects.Add(new Project()
                            {
                                Department = dept, Name = input.ProjectName
                            });
                        }

                        request.AttachedFileName = fileName;
                        request.SumType          = input.type;
                        request.RecipientUser    = recipient;
                        request.AgreedPM         = input.AgreedPM;
                        request.TimesOrSum       = request.SumType == PaymentRequestType.Times ? input.Sum : PaymentRequest.RoundSum(input.Sum);
                        request.Project          = prj;
                        if (!manager.IsInRole(currentUser.Id, SalaryRoles.Directors))
                        {
                            request.RequestState = input.SetStateWaitConfirm ? PaymentRequestState.WaitConfirm : PaymentRequestState.InProcess;
                        }
                        else
                        {
                            request.RequestState = input.SetStateCredited ? PaymentRequestState.Confirmed : PaymentRequestState.WaitConfirm;
                        }

                        if (request.RequestState == PaymentRequestState.WaitConfirm)
                        {
                            SendMailToDirector(request.AppointedUser.ShortName, request.Project.Name);
                        }


                        if (!String.IsNullOrEmpty(input.Comments))
                        {
                            db.RequestHistories.Add(new RequestHistory()
                            {
                                WhenPosted = DateTime.Now, Comments = input.Comments, Author = currentUser, Request = request
                            });
                        }

                        db.SaveChanges();
                        return(RedirectToAction("Index"));
                    }
                }
            }
            GenerateProjectsList();
            ModelState.AddModelError("", "Ошибка ввода");
            return(View(input));
        }
        public ActionResult Create(PaymentRequestEditModel input)
        {
            if (ModelState.IsValid)
            {
                Project prj = ProjectFind(db, input.ProjectCode, input.ProjectShortName);

                if ((input.ProjectCode != null && input.ProjectShortName != null) || prj != null)
                {
                    input.ProjectName = input.ProjectCode + "_" + input.ProjectShortName;
                    var             currentUser = manager.FindById(User.Identity.GetUserId());
                    ApplicationUser recipient   = db.Users.SingleOrDefault(x => x.FullName == input.UserName);

                    bool exists = System.IO.Directory.Exists(Server.MapPath("~/App_Data"));
                    if (!exists)
                    {
                        System.IO.Directory.CreateDirectory(Server.MapPath("~/App_Data"));
                        System.IO.Directory.CreateDirectory(Server.MapPath("~/App_Data/Uploads"));
                    }
                    else
                    {
                        if (!System.IO.Directory.Exists(Server.MapPath("~/App_Data/Uploads")))
                        {
                            System.IO.Directory.CreateDirectory(Server.MapPath("~/App_Data/Uploads"));
                        }
                    }

                    string fileName = input.File != null ? Environment.TickCount + "_" + System.IO.Path.GetFileName(input.File.FileName) : "";
                    if (fileName != "")
                    {
                        try
                        {
                            var path = System.IO.Path.Combine(Server.MapPath("~/App_Data/Uploads"), fileName);
                            input.File.SaveAs(path);
                        }
                        catch (Exception e)
                        {
                            ModelState.AddModelError("", "Ошибка загрузки файла " + e.Message);
                            GenerateProjectsList();
                            return(View(input));
                        }
                    }


                    if (recipient != null)
                    {
                        if (prj == null)
                        {
                            var res = (from d in db.Departments select d);
                            if (!manager.IsInRole(currentUser.Id, SalaryRoles.Directors))
                            {
                                res = res.Where(d => d.Boss.Id == currentUser.Id || d.Assistant.Id == currentUser.Id);
                            }

                            var        depts = res.ToList();
                            Department dept  = null;
                            if (depts.Count == 0 && !manager.IsInRole(currentUser.Id, "Directors"))
                            {
                                ModelState.AddModelError("", "Пользователь не имеет прав добавлять проекты ");
                                GenerateProjectsList();
                                return(View(input));
                            }
                            else if (depts.Count == 0 && manager.IsInRole(currentUser.Id, "Directors"))
                            {
                                dept = db.Departments.SingleOrDefault(x => x.Name == "_Резерв");
                                if (dept == null)
                                {
                                    dept = db.Departments.Add(new Department {
                                        Name = "_Резерв", Boss = currentUser
                                    });
                                    db.SaveChanges();
                                    dept = db.Departments.SingleOrDefault(x => x.Name == "_Резерв");
                                }
                            }
                            else if (depts.Count > 0)
                            {
                                dept = depts.FirstOrDefault(x => x.DepartmentId == input.DepartmentId);
                                if (dept == null)
                                {
                                    ModelState.AddModelError("", "Неверно задано направление ");
                                    GenerateProjectsList();
                                    return(View(input));
                                }
                            }
                            prj = db.Projects.Add(new Project()
                            {
                                Department = dept, Name = input.ProjectName
                            });
                            db.SaveChanges();
                        }

                        PaymentRequest r = new PaymentRequest()
                        {
                            SumType          = input.type,
                            TimesOrSum       = input.type == PaymentRequestType.Times ? input.Sum : PaymentRequest.RoundSum(input.Sum),
                            AgreedPM         = input.AgreedPM,
                            Project          = prj,
                            AttachedFileName = fileName,
                            AppointedUser    = currentUser,
                            RecipientUser    = recipient,
                        };

                        if (manager.IsInRole(currentUser.Id, SalaryRoles.Managers) || manager.IsInRole(currentUser.Id, SalaryRoles.Assistant))
                        {
                            r.RequestState = input.SetStateWaitConfirm ? PaymentRequestState.WaitConfirm : PaymentRequestState.InProcess;
                            // шлем почту если надо
                            if (r.RequestState == PaymentRequestState.WaitConfirm)
                            {
                                SendMailToDirector(r.AppointedUser.ShortName, r.Project.Name);
                            }
                        }
                        else if (manager.IsInRole(currentUser.Id, "Directors"))
                        {
                            r.RequestState = input.SetStateCredited ? PaymentRequestState.Confirmed : PaymentRequestState.WaitConfirm;
                        }

                        r = db.PaymentRequests.Add(r);

                        if (!String.IsNullOrEmpty(input.Comments))
                        {
                            db.RequestHistories.Add(new RequestHistory()
                            {
                                WhenPosted = DateTime.Now, Comments = input.Comments, Author = currentUser, Request = r
                            });
                        }


                        db.SaveChanges();

                        for (int i = 0; i < input.UserName_Add.Length; i++)
                        {
                            if (!string.IsNullOrEmpty(input.UserName_Add[i]) && input.Sum_Add[i] > 0)
                            {
                                string          str        = input.UserName_Add[i];
                                ApplicationUser recipient1 = db.Users.SingleOrDefault(x => x.FullName == str);
                                if (recipient1 != null)
                                {
                                    PaymentRequest r1 = new PaymentRequest()
                                    {
                                        AgreedPM         = input.AgreedPM,
                                        Project          = r.Project,
                                        AttachedFileName = r.AttachedFileName,
                                        AppointedUser    = r.AppointedUser,
                                        RequestState     = r.RequestState,

                                        RecipientUser = recipient1,
                                        SumType       = input.type_Add[i],
                                        TimesOrSum    = input.type_Add[i] == PaymentRequestType.Times ? input.Sum_Add[i] : PaymentRequest.RoundSum(input.Sum_Add[i])
                                    };
                                    db.PaymentRequests.Add(r1);
                                    db.SaveChanges();
                                }
                            }
                        }

                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        ModelState.AddModelError("", "Сотрудник не найден или не задано поле Кому");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Не задано поле Шифр и/или Название");
                }
            }
            ModelState.AddModelError("", "Ошибка ввода");
            GenerateProjectsList();
            return(View(input));
        }