Exemple #1
0
        public async Task Create(DepartmentLoad model)
        {
            try
            {
                _logger.LogInformation("Trying to execute sql create department load query");
                model.Id = await QuerySingleOrDefaultAsync <int>(@"
                        insert into DepartmentLoad (
                            DepartmentId,
                            StudyYear,
                            Total
                        ) values (
                            @DepartmentId,
                            @StudyYear,
                            @Total
                        );
                        select SCOPE_IDENTITY();
                ", model);

                _logger.LogInformation("Sql create department load query successfully executed");
            }
            catch (Exception exception)
            {
                _logger.LogError(exception.Message);
                throw exception;
            }
        }
        private void GetTotalLoad(DepartmentLoad departmentLoad, ISheet loadSheet)
        {
            int?firstLoadRowIndex = GetFirstRowIndex(loadSheet);

            if (!firstLoadRowIndex.HasValue)
            {
                throw new ApplicationException("Ошибка формата файла.");
            }
            int?lastLoadRowIndex = GetLastRowIndex(loadSheet, firstLoadRowIndex.Value);

            if (!lastLoadRowIndex.HasValue)
            {
                throw new ApplicationException("Ошибка формата файла.");
            }

            for (int i = lastLoadRowIndex.Value; i < loadSheet.LastRowNum; i++)
            {
                var          row              = loadSheet.GetRow(i);
                const int    totalColumn      = 29;
                const string totalStringValue = "Всего часов";

                if (row != null && row.Cells.Any(o => o.StringCellValue == totalStringValue))
                {
                    var totalCell = row.GetCell(totalColumn);
                    departmentLoad.Total = totalCell.NumericCellValue;
                    return;
                }
            }
        }
        public async Task <DepartmentLoad> Update(DepartmentLoad model)
        {
            await _dao.Update(model);

            if (model.GroupDisciplineLoad != null)
            {
                await UpdateGroupDisciplineLoad(model.Id, model.GroupDisciplineLoad);
            }
            return(model);
        }
Exemple #4
0
        public async Task Update(DepartmentLoad model)
        {
            try
            {
                _logger.LogInformation("Trying to execute sql update department load query");
                await ExecuteAsync(@"
                    update DepartmentLoad set
                        DepartmentId = @DepartmentId,
                        StudyYear = @StudyYear,
                        Total = @Total
                    from DepartmentLoad
                    where Id = @Id
                ", model);

                _logger.LogInformation("Sql update department load query successfully executed");
            }
            catch (Exception exception)
            {
                _logger.LogError(exception.Message);
                throw exception;
            }
        }
        private void GetStudyYearFromSheet(DepartmentLoad departmentLoad, ISheet loadSheet)
        {
            for (int i = 0; i < loadSheet.LastRowNum; i++)
            {
                var row = loadSheet.GetRow(i);
                CheckRow(row);

                for (int j = 0; j < row.LastCellNum; j++)
                {
                    var cell = row.GetCell(j);

                    if (cell != null && cell.StringCellValue.ToLower().Contains("уч.год:"))
                    {
                        var    studyYears     = cell.StringCellValue.ToLower().Replace("уч.год: ", "").Replace(" ", "").Split('-');
                        string startYear      = studyYears.FirstOrDefault();
                        string endYear        = studyYears.LastOrDefault();
                        string currentCentury = DateTime.Now.Year.ToString("").Substring(0, 2);
                        endYear = currentCentury + endYear;
                        departmentLoad.StudyYear = startYear + "-" + endYear;
                        return;
                    }
                }
            }
        }
 public async Task <DepartmentLoad> Generate(DepartmentLoadGenerateOptions options, DepartmentLoad model)
 {
     return(await _membersFactory().GenerateExtensions(options, model));
 }
        public static async Task <DepartmentLoad> GenerateExtensions(this IEnumerable <IGenerateStrategy> members, DepartmentLoadGenerateOptions options, DepartmentLoad model)
        {
            List <GenerateRatio> generateRatios = new List <GenerateRatio>();

            var membersList = members.ToList();

            if (membersList != null)
            {
                for (int i = 0; i < membersList.Count; i++)
                {
                    model = await membersList[i].Generate(options, model, generateRatios);
                }
            }
            else
            {
                foreach (var member in members)
                {
                    model = await member.Generate(options, model, generateRatios);
                }
            }

            return(model);
        }
        ///<summary> Распределение коэффициентов по ученым степеням для распределения нагрузки </summary>
        public async Task <DepartmentLoad> Generate(DepartmentLoadGenerateOptions options, DepartmentLoad model, List <GenerateRatio> generateRatios)
        {
            // Если не указан флаг использовать закрепленные дисциплины при распределении нагрузки
            if (!options.UseGraduateDegrees.HasValue || !options.UseGraduateDegrees.Value)
            {
                return(model);
            }

            var users = await _userService.Get(new UserGetOptions { DepartmentId = model.DepartmentId });

            var loads = model.GroupDisciplineLoad;

            foreach (var load in loads)
            {
                foreach (var studyLoad in load.StudyLoad)
                {
                    var generateRatio = generateRatios.FirstOrDefault(o => o.StudyLoadId == studyLoad.Id);
                    var ratios        = users
                                        .ToDictionary(o => o,
                                                      o => o.GraduateDegrees.Any(gd => gd.GraduateDegree == GraduateDegree.DoctorOfSciences)
                                ? doctorOfSciencesRatioValue
                                : candidatOfSciencesRatioValue
                                                      );

                    if (generateRatio == null)
                    {
                        generateRatios.Add(new GenerateRatio
                        {
                            StudyLoadId = studyLoad.Id,
                            Ratios      = ratios
                        });
                    }
                    else
                    {
                        foreach (var userRatio in ratios)
                        {
                            var existedUserRatio = generateRatio.Ratios.FirstOrDefault(o => o.Key.Id == userRatio.Key.Id);
                            if (existedUserRatio.Key != null)
                            {
                                double newRatioValue = existedUserRatio.Value
                                                       + (existedUserRatio.Key.GraduateDegrees
                                                          .Any(gd => gd.GraduateDegree == GraduateDegree.DoctorOfSciences)
                                            ? doctorOfSciencesRatioValue
                                            : candidatOfSciencesRatioValue
                                                          );
                                existedUserRatio = new KeyValuePair <User, double>(existedUserRatio.Key, newRatioValue);
                            }
                            generateRatio.Ratios.Add(userRatio.Key, userRatio.Value);
                        }
                    }
                }
            }

            return(model);
        }
        private async Task <DepartmentLoad> CalculateRatios(DepartmentLoad model, List <GenerateRatio> generateRatios)
        {
            try
            {
                var groupDisciplineLoads = model.GroupDisciplineLoad
                                           .Where(o => o.StudyLoad.Any(sl => generateRatios.Any(gr => gr.StudyLoadId == sl.Id)))
                                           .ToList();

                IEnumerable <int> usersIds = generateRatios.SelectMany(o => o.Ratios.Select(r => r.Key.Id)).Distinct();

                var usersRolesInDepartment = await _userRoleInDepartmentService.Get(new UserRoleInDepartmentGetOptions
                {
                    DepartmentId = model.DepartmentId,
                    UserIds      = usersIds.ToList()
                });

                var roles = await _roleService.Get(new RoleGetOptions
                {
                    Ids = usersRolesInDepartment.Select(o => o.RoleId).ToList()
                });

                foreach (var groupDisciplineLoad in groupDisciplineLoads)
                {
                    var studyLoads = groupDisciplineLoad.StudyLoad
                                     .Where(o => generateRatios.Any(gr => gr.StudyLoadId == o.Id))
                                     .ToList();

                    foreach (var studyLoad in groupDisciplineLoad.StudyLoad)
                    {
                        var studyLoadRatio = generateRatios.Find(o => o.StudyLoadId == studyLoad.Id);
                        if (studyLoadRatio == null || studyLoadRatio.Ratios.Count == 0)
                        {
                            continue;
                        }

                        User user          = null;
                        var  orderedRatios = studyLoadRatio.Ratios.OrderBy(o => o.Value).ToList();
                        for (int i = 0; i < orderedRatios.Count; i++)
                        {
                            var    supposedUser          = orderedRatios[i].Key;
                            var    userRolesInDepartment = usersRolesInDepartment.Where(o => o.UserId == supposedUser.Id).ToList();
                            var    role        = roles.FirstOrDefault(o => userRolesInDepartment.Any(urd => urd.RoleId == o.Id) && o.CanTeach);
                            double userLoadSum = groupDisciplineLoads
                                                 .Where(o => o.StudyLoad.Any(sl => sl.UsersLoad.Any(ul => ul.UserId == supposedUser.Id)))
                                                 .SelectMany(o => o.StudyLoad)
                                                 .Sum(o => o.Value);

                            double supposedUserLoadSum = userLoadSum + studyLoad.Value;

                            if (role != null && role.MaxLoad > supposedUserLoadSum)
                            {
                                user = supposedUser;
                                break;
                            }
                        }

                        if (user != null)
                        {
                            studyLoad.UsersLoad.Add(new UserLoad
                            {
                                StudentsCount = groupDisciplineLoad.StudentGroup.StudentsCount,
                                StudyLoadId   = studyLoad.Id,
                                UserId        = user.Id,
                                User          = user
                            });
                        }
                    }
                }

                return(model);
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }
        public async Task <DepartmentLoad> Generate(DepartmentLoadGenerateOptions options, DepartmentLoad model, List <GenerateRatio> generateRatios)
        {
            await CalculateRatios(model, generateRatios);

            return(model);
        }
        ///<summary> Распределение коэффициентов по закрепленным дисициплинам для распределения нагрузки </summary>
        public async Task <DepartmentLoad> Generate(DepartmentLoadGenerateOptions options, DepartmentLoad model, List <GenerateRatio> generateRatios)
        {
            // Если не указан флаг использовать закрепленные дисциплины при распределении нагрузки
            if (!options.UsePinnedDisciplines.HasValue || !options.UsePinnedDisciplines.Value)
            {
                return(model);
            }

            var users = await _userService.Get(new UserGetOptions { DepartmentId = model.DepartmentId, OnlyWithPinnedDisciplines = true });

            var allPinnedDisciplines = users.SelectMany(u => u.PinnedDisciplines).ToList();

            var loads = model.GroupDisciplineLoad
                        .Where(o => allPinnedDisciplines.Any(pd => pd.DisciplineTitleId == o.DisciplineTitleId))
                        .Select(o => new KeyValuePair <int, List <StudyLoad> >(
                                    o.DisciplineTitleId,
                                    o.StudyLoad.Where(sl => allPinnedDisciplines.Any(pd => pd.ProjectType == sl.ProjectType)).ToList()
                                    )
                                )
                        .ToList();

            foreach (var load in loads)
            {
                var userPinnedDiscipline = users.Where(o => o.PinnedDisciplines.Any(o => o.DisciplineTitleId == load.Key));
                foreach (var studyLoad in load.Value)
                {
                    var generateRatio = generateRatios.FirstOrDefault(o => o.StudyLoadId == studyLoad.Id);
                    var ratios        = userPinnedDiscipline
                                        .Where(o => o.PinnedDisciplines.Any(pd => pd.ProjectType == studyLoad.ProjectType))
                                        .ToDictionary(o => o, o => ratioValue);

                    if (generateRatio == null)
                    {
                        generateRatios.Add(new GenerateRatio
                        {
                            StudyLoadId = studyLoad.Id,
                            Ratios      = ratios
                        });
                    }
                    else
                    {
                        foreach (var userRatio in ratios)
                        {
                            var existedUserRatio = generateRatio.Ratios.FirstOrDefault(o => o.Key.Id == userRatio.Key.Id);
                            if (existedUserRatio.Key != null)
                            {
                                existedUserRatio = new KeyValuePair <User, double>(existedUserRatio.Key, existedUserRatio.Value + ratioValue);
                            }
                            generateRatio.Ratios.Add(userRatio.Key, userRatio.Value);
                        }
                    }
                }
            }

            return(model);
        }
        private void GetLoadFromSheet(
            DepartmentLoad departmentLoad,
            ISheet loadSheet,
            List <StudyDirection> studyDirections,
            List <Department> faculties,
            List <DisciplineTitle> disciplinesTitles,
            List <StudentGroup> studentGroups
            )
        {
            #region Define columns numbers
            const int disciplineTitleColumn       = 1;
            const int semesterColumn              = 2;
            const int studyDirectionColumn        = 3;
            const int facultyColumn               = 4;
            const int courseColumn                = 5;
            const int studentGroupColumn          = 6;
            const int studentsCountColumn         = 7;
            const int groupsInStreamColumn        = 8;
            const int studyWeeksColumn            = 9;
            const int lectionsColumn              = 10;
            const int practicalLessonsColumn      = 11;
            const int laboratoryLessonsColumn     = 12;
            const int thematicalDiscussionsColumn = 13;
            const int consultasionsColumn         = 14;
            const int examsColumn                = 15;
            const int offsetsColumn              = 16;
            const int otherColumn                = 17;
            const int abstractsColumn            = 18;
            const int esTestPapersColumn         = 19;
            const int stateExamsColumn           = 20;
            const int postgraduateExamsColumn    = 21;
            const int practicesColumn            = 22;
            const int departmentManagementColumn = 23;
            const int studentReserachWorkColumn  = 24;
            const int courseWorksColumn          = 25;
            const int graduationQualificationManagementColumn = 26;
            const int masterProgramManagementColumn           = 27;
            const int postgraduateProgramManagementColumn     = 28;
            const int amountColumn = 29;
            #endregion

            int?firstRowIndex = GetFirstRowIndex(loadSheet);
            if (!firstRowIndex.HasValue)
            {
                throw new ApplicationException("Ошибка формата файла.");
            }
            int?lastRowIndex = GetLastRowIndex(loadSheet, firstRowIndex.Value);
            if (!lastRowIndex.HasValue)
            {
                throw new ApplicationException("Ошибка формата файла.");
            }
            int firstRow = firstRowIndex.Value + 1;

            for (int i = firstRow; i < lastRowIndex; i++)
            {
                var row = loadSheet.GetRow(i);
                CheckRow(row);

                #region Define required cells
                var disciplineTitleCell       = row.GetCell(disciplineTitleColumn);
                var semesterCell              = row.GetCell(semesterColumn);
                var studyDirectionCell        = row.GetCell(studyDirectionColumn);
                var facultyCell               = row.GetCell(facultyColumn);
                var courseCell                = row.GetCell(courseColumn);
                var studentGroupCell          = row.GetCell(studentGroupColumn);
                var studentsCountCell         = row.GetCell(studentsCountColumn);
                var groupsInStreamCell        = row.GetCell(groupsInStreamColumn);
                var studyWeeksCell            = row.GetCell(studyWeeksColumn);
                var lectionsCell              = row.GetCell(lectionsColumn);
                var practicalLessonsCell      = row.GetCell(practicalLessonsColumn);
                var laboratoryLessonsCell     = row.GetCell(laboratoryLessonsColumn);
                var thematicalDiscussionsCell = row.GetCell(thematicalDiscussionsColumn);
                var consultasionsCell         = row.GetCell(consultasionsColumn);
                var examsCell                = row.GetCell(examsColumn);
                var offsetsCell              = row.GetCell(offsetsColumn);
                var otherCell                = row.GetCell(otherColumn);
                var abstractCell             = row.GetCell(abstractsColumn);
                var esTestPapersCell         = row.GetCell(esTestPapersColumn);
                var stateExamsCell           = row.GetCell(stateExamsColumn);
                var postgraduateExamsCell    = row.GetCell(postgraduateExamsColumn);
                var practicesCell            = row.GetCell(practicesColumn);
                var departmentManagementCell = row.GetCell(departmentManagementColumn);
                var studentReserachWorkCell  = row.GetCell(studentReserachWorkColumn);
                var courseWorksCell          = row.GetCell(courseWorksColumn);
                var graduationQualificationManagementCell = row.GetCell(graduationQualificationManagementColumn);
                var masterProgramManagementCell           = row.GetCell(masterProgramManagementColumn);
                var postgraduateProgramManagementCell     = row.GetCell(postgraduateProgramManagementColumn);
                var amountCell = row.GetCell(amountColumn);
                #endregion

                #region Check required cells
                CheckCell(disciplineTitleCell);
                CheckCell(semesterCell);
                CheckCell(studyDirectionCell);
                CheckCell(facultyCell);
                CheckCell(courseCell);
                CheckCell(studentGroupCell);
                CheckCell(studentsCountCell);
                CheckCell(groupsInStreamCell);
                CheckCell(studyWeeksCell);
                #endregion

                #region Get values from cells
                string tempStartYear = Regex.Match(studentGroupCell.StringCellValue, @"[а-я,А-Я]\d{2}").Value;
                int    startYear     = int.Parse(Regex.Match(tempStartYear, @"\d{2}").Value);
                string directionCode = Regex.Match(studyDirectionCell.StringCellValue, @"\d{2}.\d{2}.\d{2}").Value;

                var studyDirection = studyDirections.Find(o => directionCode == o.Code);

                var title = new DisciplineTitle
                {
                    DepartmentId = departmentLoad.DepartmentId,
                    Name         = disciplineTitleCell.StringCellValue,
                    Shortname    = disciplineTitleCell.StringCellValue.GetShortening()
                };

                if (!disciplinesTitles.Any(o => o.Name == title.Name))
                {
                    disciplinesTitles.Add(title);
                }

                if (studyDirection != null)
                {
                    var group = new StudentGroup
                    {
                        CurrentCourse    = Convert.ToInt32(courseCell.NumericCellValue),
                        Name             = studentGroupCell.StringCellValue,
                        StartYear        = startYear,
                        StudentsCount    = Convert.ToInt32(studentsCountCell.NumericCellValue),
                        StudyDirection   = studyDirection,
                        StudyDirectionId = studyDirection.Id
                    };
                    if (!studentGroups.Any(o => o.Name == group.Name))
                    {
                        studentGroups.Add(group);
                    }

                    int    semesterNumber  = Convert.ToInt32(semesterCell.NumericCellValue);
                    int    studyWeeksCount = Convert.ToInt32(studyWeeksCell.NumericCellValue);
                    double amount          = amountCell.NumericCellValue;

                    var groupDisciplineLoad = new GroupDisciplineLoad
                    {
                        DisciplineTitle   = title,
                        DisciplineTitleId = title.Id,
                        FacultyName       = facultyCell.StringCellValue,
                        SemesterNumber    = semesterNumber,
                        StudentGroup      = group,
                        StudentGroupId    = group.Id,
                        StudyWeeksCount   = studyWeeksCount,
                        StudyLoad         = new List <StudyLoad>(),
                        Amount            = amount
                    };

                    if (lectionsCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(lectionsCell),
                            ShownValue  = GetShownValueFromCell(lectionsCell),
                            ProjectType = ProjectType.Lection
                        });
                    }
                    if (practicalLessonsCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(practicalLessonsCell),
                            ShownValue  = GetShownValueFromCell(practicalLessonsCell),
                            ProjectType = ProjectType.PracticalLesson
                        });
                    }
                    if (laboratoryLessonsCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(laboratoryLessonsCell),
                            ShownValue  = GetShownValueFromCell(laboratoryLessonsCell),
                            ProjectType = ProjectType.LaboratoryLesson
                        });
                    }
                    if (thematicalDiscussionsCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(thematicalDiscussionsCell),
                            ShownValue  = GetShownValueFromCell(thematicalDiscussionsCell),
                            ProjectType = ProjectType.ThematicalDiscussion
                        });
                    }
                    if (consultasionsCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(consultasionsCell),
                            ShownValue  = GetShownValueFromCell(consultasionsCell),
                            ProjectType = ProjectType.Consultation
                        });
                    }
                    if (examsCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(examsCell),
                            ShownValue  = GetShownValueFromCell(examsCell),
                            ProjectType = ProjectType.Exam
                        });
                    }
                    if (offsetsCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(offsetsCell),
                            ShownValue  = GetShownValueFromCell(offsetsCell),
                            ProjectType = ProjectType.Offest
                        });
                    }
                    if (otherCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(otherCell),
                            ShownValue  = GetShownValueFromCell(otherCell),
                            ProjectType = ProjectType.Other
                        });
                    }
                    if (abstractCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(abstractCell),
                            ShownValue  = GetShownValueFromCell(abstractCell),
                            ProjectType = ProjectType.Abstract
                        });
                    }
                    if (esTestPapersCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(esTestPapersCell),
                            ShownValue  = GetShownValueFromCell(esTestPapersCell),
                            ProjectType = ProjectType.EsTestPapers
                        });
                    }
                    if (stateExamsCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(stateExamsCell),
                            ShownValue  = GetShownValueFromCell(stateExamsCell),
                            ProjectType = ProjectType.StateExam
                        });
                    }
                    if (postgraduateExamsCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(postgraduateExamsCell),
                            ShownValue  = GetShownValueFromCell(postgraduateExamsCell),
                            ProjectType = ProjectType.PostgraduateEntranceExam
                        });
                    }
                    if (practicesCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(practicesCell),
                            ShownValue  = GetShownValueFromCell(practicesCell),
                            ProjectType = ProjectType.Practice
                        });
                    }
                    if (departmentManagementCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(departmentManagementCell),
                            ShownValue  = GetShownValueFromCell(departmentManagementCell),
                            ProjectType = ProjectType.DepartmentManagement
                        });
                    }
                    if (studentReserachWorkCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(studentReserachWorkCell),
                            ShownValue  = GetShownValueFromCell(studentReserachWorkCell),
                            ProjectType = ProjectType.StudentResearchWork
                        });
                    }
                    if (courseWorksCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(courseWorksCell),
                            ShownValue  = GetShownValueFromCell(courseWorksCell),
                            ProjectType = ProjectType.CourseWork
                        });
                    }
                    if (graduationQualificationManagementCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(graduationQualificationManagementCell),
                            ShownValue  = GetShownValueFromCell(graduationQualificationManagementCell),
                            ProjectType = ProjectType.GraduationQualificationManagement
                        });
                    }
                    if (masterProgramManagementCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(masterProgramManagementCell),
                            ShownValue  = GetShownValueFromCell(masterProgramManagementCell),
                            ProjectType = ProjectType.MasterProgramManagement
                        });
                    }
                    if (postgraduateProgramManagementCell != null)
                    {
                        groupDisciplineLoad.StudyLoad.Add(new StudyLoad
                        {
                            Value       = GetValueFromCell(postgraduateProgramManagementCell),
                            ShownValue  = GetShownValueFromCell(postgraduateProgramManagementCell),
                            ProjectType = ProjectType.PostgraduateProgramManagement
                        });
                    }

                    departmentLoad.GroupDisciplineLoad.Add(groupDisciplineLoad);
                }
                #endregion
            }
        }
        public async Task <DepartmentLoad> Import(DepartmentLoadImportOptions options)
        {
            try
            {
                if (!options.DepartmentId.HasValue)
                {
                    throw new ApplicationException("Не удалось найти кафедру.");
                }

                DepartmentLoad departmentLoad = new DepartmentLoad
                {
                    DepartmentId = options.DepartmentId.Value
                };
                var departments = await _departmentService.Get(new DepartmentGetOptions { Id = options.DepartmentId });

                var department = departments.FirstOrDefault();
                List <DisciplineTitle>       disciplinesTitles = new List <DisciplineTitle>();
                List <StudentGroup>          studentGroups     = new List <StudentGroup>();
                IEnumerable <StudyDirection> studyDirections   = await _studyDirectionService.Get(new StudyDirectionGetOptions());

                IEnumerable <Department> faculties = await _departmentService.Get(new DepartmentGetOptions
                {
                    Type = DepartmentType.Faculty
                });

                using (var fileStream = await _fileService.PrepareFile(options.FileName))
                {
                    IWorkbook workbook  = WorkbookFactory.Create(fileStream);
                    ISheet    loadSheet = null;
                    for (int i = 0; i < workbook.NumberOfSheets; i++)
                    {
                        var sheet = workbook.GetSheetAt(i);
                        if (sheet.SheetName.ToLower().Contains(department.Name.ToLower()) ||
                            sheet.SheetName.ToLower().Contains(department.FullName.ToLower()))
                        {
                            loadSheet = sheet;
                            break;
                        }
                    }

                    if (loadSheet == null)
                    {
                        throw new ApplicationException("Не удалось найти лист с нагрузкой кафедры");
                    }

                    GetStudyYearFromSheet(departmentLoad, loadSheet);
                    GetLoadFromSheet(
                        departmentLoad,
                        loadSheet,
                        studyDirections.ToList(),
                        faculties.ToList(),
                        disciplinesTitles,
                        studentGroups
                        );
                    GetTotalLoad(departmentLoad, loadSheet);
                }

                if (options.UpdateStudentsGroups)
                {
                    var enabledGroups = studentGroups.Where(o => o.StudyDirectionId != 0 && o.StudyDirection != null).ToList();

                    var departmentsIds = studentGroups.Select(o => o.StudyDirection.DepartmentId).Distinct().ToList();
                    foreach (int departmentId in departmentsIds)
                    {
                        var departmentGroups = enabledGroups.Where(o => o.StudyDirection.DepartmentId == departmentId).ToList();
                        await _departmentService.UpdateDepartmentStudentsGroups(departmentId, departmentGroups);
                    }
                }

                if (options.UpdateDisciplinesTitles)
                {
                    await _departmentService.UpdateDepartmentDisciplinesTitles(options.DepartmentId.Value, disciplinesTitles);
                }

                var newGroups = await _studentGroupService.Get(new StudentGroupGetOptions());

                var newTitles = await _disciplineTitleService.Get(new DisciplineTitleGetOptions());

                foreach (var load in departmentLoad.GroupDisciplineLoad)
                {
                    var title = newTitles.FirstOrDefault(o => o.Name == load.DisciplineTitle.Name);
                    if (title != null)
                    {
                        load.DisciplineTitleId = title.Id;
                    }
                    else
                    {
                        _logger.LogError("Discipline title not found");
                    }

                    var group = newGroups.FirstOrDefault(o => o.Name == load.StudentGroup.Name);
                    if (group != null)
                    {
                        load.StudentGroupId = group.Id;
                    }
                    else
                    {
                        _logger.LogError("Student group not found");
                    }

                    load.StudyLoad.ForEach(o => o.UsersLoad = new List <UserLoad>());
                }

                departmentLoad.GroupDisciplineLoad = departmentLoad.GroupDisciplineLoad
                                                     .Where(o =>
                                                            newGroups.Any(g => g.Id == o.StudentGroupId) &&
                                                            newTitles.Any(t => t.Id == o.DisciplineTitleId)
                                                            ).ToList();
                await Create(departmentLoad);

                return(departmentLoad);
            }
            catch (Exception exception)
            {
                _logger.LogError(exception.Message);
                throw exception;
            }
            finally
            {
                _fileService.RemoveFile(options.FileName);
            }
        }
 public async Task <IActionResult> Patch([FromBody] DepartmentLoad model)
 {
     return(Ok(await _service.Update(model)));
 }