Exemplo n.º 1
0
        public ActionResult DeleteConfirmed(int id)
        {
            var vacationRecord           = _vacationRecordService.GetById(id);
            var isDeleted                = true;
            var errorRecycleToRecycleBin = string.Empty;

            if (vacationRecord != null)
            {
                var user = _userService.GetUserDataForVersion();
                var reportingPeriodForBeginDate = _reportingPeriodService.GetAll(x => x.Month == vacationRecord.VacationBeginDate.Month &&
                                                                                 x.Year == vacationRecord.VacationBeginDate.Year).FirstOrDefault();

                var reportingPeriodForEndDate = _reportingPeriodService.GetAll(x => x.Month == vacationRecord.VacationEndDate.Month &&
                                                                               x.Year == vacationRecord.VacationEndDate.Year).FirstOrDefault();
                if (reportingPeriodForEndDate != null && reportingPeriodForBeginDate != null &&
                    (reportingPeriodForBeginDate.NewTSRecordsAllowedUntilDate > DateTime.Now &&
                     reportingPeriodForEndDate.NewTSRecordsAllowedUntilDate > DateTime.Now))
                {
                    var parentHoursRecord = _tsHoursRecordService.Get(x => x.Where(t => t.ParentVacationRecordID == id).ToList());
                    if (parentHoursRecord != null && parentHoursRecord.Count > 0)
                    {
                        _tsHoursRecordService.RemoveRange(parentHoursRecord);
                    }
                    var recycleBinInDBRelationVacationRecord = _serviceService.HasRecycleBinInDBRelation(new VacationRecord()
                    {
                        ID = id
                    });
                    if (recycleBinInDBRelationVacationRecord.hasRelated == false)
                    {
                        var recycleToRecycleBinVacationRecord = _vacationRecordService.RecycleToRecycleBin(id, user.Item1, user.Item2);
                        isDeleted = recycleToRecycleBinVacationRecord.toRecycleBin;
                        errorRecycleToRecycleBin = recycleToRecycleBinVacationRecord.toRecycleBin ? string.Empty : recycleToRecycleBinVacationRecord.relatedClassId;
                    }
                    else
                    {
                        errorRecycleToRecycleBin = recycleBinInDBRelationVacationRecord.relatedInDBClassId;
                    }
                }
            }

            if (!isDeleted)
            {
                ViewBag.RecycleBinError = "Невозможно удалить, так как на удаляемый элемент ссылаются другие элементы в системе." +
                                          $"Сначала необходимо удалить элементы, которые ссылаются на данный элемент. {errorRecycleToRecycleBin}";
                return(View(vacationRecord));
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 2
0
        public ActionResult AutoHoursDataSave(int?ID, int?ProjectID, int?EmployeeID, string DayHours, string BeginDate, string EndDate, bool del = false)
        {
            TSAutoHoursRecord tsAutoHoursRecord = null;

            if (ID != null && ID.HasValue == true)
            {
                tsAutoHoursRecord = _tsAutoHoursRecordService.GetById((int)ID);
            }

            var beginDateTime = DateTime.TryParse(BeginDate, out var outBeginDateTime) ? outBeginDateTime : (DateTime)tsAutoHoursRecord.BeginDate;
            var endDateTime   = DateTime.TryParse(EndDate, out var outEndDateTime) ? outEndDateTime : (DateTime)tsAutoHoursRecord.EndDate;
            var user          = _userService.GetUserDataForVersion();
            var listUncreatedReportPeriods = GetListUncreatedReportPeriods(beginDateTime, endDateTime);

            //в данных датах нету не созданных месяцев
            if (listUncreatedReportPeriods.Count == 0)
            {
                //начало и конец отчетного периода
                var reportingPeriodForBeginDate = _reportingPeriodService
                                                  .GetAll(x => x.Month == beginDateTime.Month && x.Year == beginDateTime.Year).FirstOrDefault();
                var reportingPeriodForEndDate = _reportingPeriodService
                                                .GetAll(x => x.Month == endDateTime.Month && x.Year == endDateTime.Year).FirstOrDefault();

                if (reportingPeriodForBeginDate == null || reportingPeriodForEndDate == null)
                {
                    return(Content("Не создан отчетный период."));
                }

                //удаление записи
                if (del != false && ID != null)
                {
                    if (reportingPeriodForBeginDate != null && reportingPeriodForEndDate != null &&
                        (reportingPeriodForEndDate.NewTSRecordsAllowedUntilDate > DateTime.Now &&
                         reportingPeriodForBeginDate.NewTSRecordsAllowedUntilDate > DateTime.Now))
                    {
                        //Удаление связанных записей с таймшитом
                        var parentHoursRecords = _tsHoursRecordService.Get(x => x.Where(t => t.ParentTSAutoHoursRecordID == ID).ToList());
                        if (parentHoursRecords != null && parentHoursRecords.Count > 0)
                        {
                            _tsHoursRecordService.RemoveRange(parentHoursRecords);
                        }
                        var recycleBinInDBRelationTSAutoHoursRecord = _serviceService.HasRecycleBinInDBRelation(new TSAutoHoursRecord()
                        {
                            ID = (int)ID
                        });
                        if (recycleBinInDBRelationTSAutoHoursRecord.hasRelated == false)
                        {
                            var recycleToRecycleBinTSAutoHoursRecord = _tsAutoHoursRecordService.RecycleToRecycleBin((int)ID, user.Item1, user.Item2);
                            if (!recycleToRecycleBinTSAutoHoursRecord.toRecycleBin)
                            {
                                return(Content("Невозможно удалить, так как на удаляемый элемент ссылаются другие элементы в системе" +
                                               $".Сначала необходимо удалить элементы, которые ссылаются на данный элемент. {recycleToRecycleBinTSAutoHoursRecord.relatedClassId}"));
                            }
                        }
                        else
                        {
                            return(Content("Невозможно удалить, так как на удаляемый элемент ссылаются другие элементы в системе" +
                                           $".Сначала необходимо удалить элементы, которые ссылаются на данный элемент. {recycleBinInDBRelationTSAutoHoursRecord.relatedInDBClassId}"));
                        }

                        return(Content("true"));
                    }

                    return(Content("Отчетный период закрыт на " + reportingPeriodForBeginDate.FullName + " закрыт!"));
                }
                //обновление записей
                else
                {
                    double hours = Convert.ToDouble(DayHours.Replace(".", ","));

                    //обновление/редакрировании найденной записи
                    if (tsAutoHoursRecord != null)
                    {
                        if (beginDateTime > endDateTime)
                        {
                            return(Content("Дата начала не может быть больше даты окончания периода."));
                        }
                        var employee = _employeeService.GetById((int)EmployeeID);

                        if (tsAutoHoursRecord.EmployeeID != EmployeeID)
                        {
                            return(Content("Изменение сотрудника в созданной записи автозагрузки запрещено."));
                        }

                        if (employee.EnrollmentDate == null || employee.EnrollmentDate.HasValue == false)
                        {
                            return(Content("Сотрудник еще не принят на работу."));
                        }

                        if (employee.DismissalDate != null)
                        {
                            //Нельзя указывать дату окончания после даты принятия сотрудника на работу
                            if (endDateTime > employee.DismissalDate)
                            {
                                return(Content("Автозагрузка не может заканчиваться позже даты увольнения сотрудника."));
                            }
                        }

                        if (employee.EnrollmentDate != null)
                        {
                            //Нельзя указывать дату начала до даты принятия сотрудника на работу
                            if (beginDateTime < employee.EnrollmentDate)
                            {
                                return(Content("Автозагрузка не может начинаться ранее даты приема сотрудника"));
                            }
                        }

                        //есть ли у человек проекты
                        //отключена проверка, так как сотрудников не добавляют в РГ проекта, у кого есть автозагрузка

                        /*
                         * if (_projectMembershipService.GetProjectsForEmployee((int)tsAutoHoursRecord.EmployeeID).Count != 0)
                         * {
                         *  //работает ли этот человек не состоить в этом проекте
                         *  if (_projectMembershipService.GetProjectMembershipForEmployees(
                         *              new DateTimeRange((DateTime)tsAutoHoursRecord.BeginDate,
                         *                  (DateTime)tsAutoHoursRecord.EndDate), (int)tsAutoHoursRecord.EmployeeID)
                         *          .Count(x => x.ProjectID == ProjectID) == 0)
                         *      return Content("Данный сотрудник не состоит в проекте, либо неправильно указана дата начала или окончания действия.");
                         * }
                         * else
                         *  return Content("У данного сотрудника нету проектов.");
                         */

                        var tsAutoHoursRecordInDb = _tsAutoHoursRecordService.GetById(tsAutoHoursRecord.ID);
                        //дату начала в закрытом переоде менять нельзя
                        if (reportingPeriodForBeginDate != null && reportingPeriodForBeginDate
                            .NewTSRecordsAllowedUntilDate < DateTime.Now &&
                            tsAutoHoursRecordInDb.BeginDate != beginDateTime)
                        {
                            return(Content("Начальную дату в закрытом периоде изменять нельзя."));
                        }
                        //Дату окончания в закрытый перод менить нельзя
                        if (reportingPeriodForEndDate != null && reportingPeriodForEndDate
                            .NewTSRecordsAllowedUntilDate < DateTime.Now &&
                            endDateTime < tsAutoHoursRecordInDb.BeginDate.Value.LastDayOfMonth())
                        {
                            return(Content("Конечную дату в закрытом периоде нельзя поставить меньше последнего дня отчетного месяца."));
                        }

                        if (((reportingPeriodForBeginDate != null &&
                              reportingPeriodForBeginDate.NewTSRecordsAllowedUntilDate < DateTime.Now) ||
                             (reportingPeriodForEndDate != null &&
                              reportingPeriodForEndDate.NewTSRecordsAllowedUntilDate < DateTime.Now)) &&
                            tsAutoHoursRecordInDb.DayHours != hours)
                        {
                            return(Content("Нельзя изменить количество часов в закрытом периоде."));
                        }

                        tsAutoHoursRecord.EmployeeID = EmployeeID;
                        tsAutoHoursRecord.ProjectID  = ProjectID;
                        tsAutoHoursRecord.BeginDate  = Convert.ToDateTime(BeginDate);
                        tsAutoHoursRecord.EndDate    = Convert.ToDateTime(EndDate);
                        tsAutoHoursRecord.DayHours   = hours;

                        _tsAutoHoursRecordService.Update(tsAutoHoursRecord);
                        //TODO добавить
                        //_taskTimesheetProcessing.ProcessTSAutoHoursRecords(currentEmployee, newtsAutoHoursRecord);
                        return(Content("true"));
                    }
                    //Создание записи
                    else
                    {
                        //если начальная дата больше конечной
                        if (beginDateTime > endDateTime)
                        {
                            return(Content("Дата начала не может быть больше даты окончания периода."));
                        }

                        var employee = _employeeService.GetById((int)EmployeeID);

                        if (employee.EnrollmentDate == null || employee.EnrollmentDate.HasValue == false)
                        {
                            return(Content("Сотрудник еще не принят на работу."));
                        }

                        if (employee.DismissalDate != null)
                        {
                            //Нельзя указывать дату окончания после даты принятия сотрудника на работу
                            if (endDateTime > employee.DismissalDate)
                            {
                                return(Content("Автозагрузка не может заканчиваться позже даты увольнения сотрудника."));
                            }
                        }

                        if (employee.EnrollmentDate != null)
                        {
                            //Нельзя указывать дату начала до даты принятия сотрудника на работу
                            if (beginDateTime < employee.EnrollmentDate)
                            {
                                return(Content("Автозагрузка не может начинаться ранее даты приема сотрудника"));
                            }
                        }

                        //есть ли у человек проекты
                        //отключена проверка, так как сотрудников не добавляют в РГ проекта, у кого есть автозагрузка

                        /*
                         * if (EmployeeID != null && _projectMembershipService.GetProjectsForEmployee((int)EmployeeID).Count != 0)
                         * {
                         *  //работает ли этот человек не состоить в этом проекте
                         *  if (_projectMembershipService.GetProjectMembershipForEmployees(
                         *              new DateTimeRange(beginDateTime,
                         *                  endDateTime), (int)EmployeeID)
                         *          .Count(x => x.ProjectID == ProjectID) == 0)
                         *      return Content("Данный сотрудник не состоит в проекте, либо неправильно указана дата начала или окончания действия.");
                         * }
                         * else
                         *  return Content("У данного сотрудника нету проектов.");
                         */


                        if (reportingPeriodForBeginDate != null &&
                            reportingPeriodForBeginDate.NewTSRecordsAllowedUntilDate < DateTime.Now)
                        {
                            return(Content("Отчетный период закрыт."));
                        }
                        if (reportingPeriodForEndDate != null &&
                            reportingPeriodForEndDate.NewTSRecordsAllowedUntilDate < DateTime.Now)
                        {
                            return(Content("Отчетный период закрыт."));
                        }

                        tsAutoHoursRecord = new TSAutoHoursRecord
                        {
                            EmployeeID = EmployeeID,
                            ProjectID  = ProjectID,
                            BeginDate  = Convert.ToDateTime(BeginDate),
                            EndDate    = Convert.ToDateTime(EndDate),
                            DayHours   = hours
                        };
                        _tsAutoHoursRecordService.Add(tsAutoHoursRecord);

                        //TODO добавить
                        //_taskTimesheetProcessing.ProcessTSAutoHoursRecords(currentEmployee, tsAutoHoursRecord);

                        return(Content("true"));
                    }
                }
            }
            return(Content(CreateErroMessage(listUncreatedReportPeriods)));
        }