diff --git a/DepartmentPortal/Common/ModuleTools/BusinessLogics/Mapper.cs b/DepartmentPortal/Common/ModuleTools/BusinessLogics/Mapper.cs index 66f6886..5607a30 100644 --- a/DepartmentPortal/Common/ModuleTools/BusinessLogics/Mapper.cs +++ b/DepartmentPortal/Common/ModuleTools/BusinessLogics/Mapper.cs @@ -63,7 +63,7 @@ namespace ModuleTools.BusinessLogics continue; } - object value = obj; + object value = null; var customAttribute = property.GetCustomAttribute(); if (customAttribute != null) { @@ -75,7 +75,7 @@ namespace ModuleTools.BusinessLogics } else { - var bindingProperty = value.GetType().GetProperty(property.Name); + var bindingProperty = typeFrom.GetProperty(property.Name); if (bindingProperty != null) { value = bindingProperty.GetValue(obj); diff --git a/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/OrderSyncHistoryBusinessLogic.cs b/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/OrderSyncHistoryBusinessLogic.cs index f4163a1..8ed8034 100644 --- a/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/OrderSyncHistoryBusinessLogic.cs +++ b/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/OrderSyncHistoryBusinessLogic.cs @@ -6,8 +6,10 @@ using DepartmentBusinessLogic.ViewModels; using ModuleTools.BusinessLogics; using ModuleTools.Enums; using ModuleTools.Extensions; +using ModuleTools.Interfaces; using SecurityBusinessLogic.BindingModels; using SecurityBusinessLogic.BusinessLogics; +using SecurityBusinessLogic.ViewModels; using System; using System.Collections.Generic; using System.Linq; @@ -34,6 +36,10 @@ namespace DepartmentBusinessLogic.BusinessLogics private UserBusinessLogic _userLogic; + private UserRoleBusinessLogic _userRoleLogic; + + private RoleBusinessLogic _roleLogic; + private OrderBusinessLogic _orderLogic; private OrderStudentRecordBusinessLogic _orderStudentRecordLogic; @@ -42,6 +48,8 @@ namespace DepartmentBusinessLogic.BusinessLogics public async Task SyncOrders() { + InitLogics(); + var history = Create(new OrderSyncHistorySetBindingModel { SyncDate = DateTime.Now }); if (history == null) { @@ -49,14 +57,6 @@ namespace DepartmentBusinessLogic.BusinessLogics return false; } - _recordLogic = DependencyManager.Instance.Resolve(); - _enviromentSettingLogic = DependencyManager.Instance.Resolve(); - _groupsLogic = DependencyManager.Instance.Resolve(); - _studentLogic = DependencyManager.Instance.Resolve(); - _orderLogic = DependencyManager.Instance.Resolve(); - _orderStudentRecordLogic = DependencyManager.Instance.Resolve(); - _userLogic = DependencyManager.Instance.Resolve(); - var address = _enviromentSettingLogic.GetList(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderIpAddress" })?.List?.FirstOrDefault(); if (address == null || address.Value.IsEmpty()) { @@ -70,40 +70,12 @@ namespace DepartmentBusinessLogic.BusinessLogics return false; } - var username = _enviromentSettingLogic.GetList(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderUserName" })?.List?.FirstOrDefault(); - if (username == null || username.Value.IsEmpty()) + var client = GetClinet(history, address); + if (client == null) { - Errors = _enviromentSettingLogic.Errors; - Errors.Add(("Ошибка получения данных", "Не удалось получить имя пользователя для получения приказов по студентам")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) - }); return false; } - var password = _enviromentSettingLogic.GetList(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderPassword" })?.List?.FirstOrDefault(); - if (password == null || password.Value.IsEmpty()) - { - Errors = _enviromentSettingLogic.Errors; - Errors.Add(("Ошибка получения данных", "Не удалось получить пароль для получения приказов по студентам")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) - }); - return false; - } - - var client = new HttpClient - { - BaseAddress = new Uri(address.Value) - }; - client.DefaultRequestHeaders.Accept.Clear(); - client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username.Value}:{password.Value}"))); - // авторизация // получение списка студентов @@ -168,7 +140,6 @@ namespace DepartmentBusinessLogic.BusinessLogics { await SyncStudentOrders(history, student, groups.List, client, address.Value); } - studentFromServer.CurrentStudentsList.Remove(studentSync); } // новые студенты и восстановленцы @@ -206,24 +177,10 @@ namespace DepartmentBusinessLogic.BusinessLogics continue; } - var userName = $"{student.lastName}{(student.firstName.IsNotEmpty() ? $" {student.firstName[0]}." : string.Empty)}{(student.patronymicName.IsNotEmpty() ? $"{student.patronymicName[0]}." : string.Empty)}"; - var user = _userLogic.GetOrCreateUser(new UserGetBindingModel - { - Login = student.recordBookName - }, userName); + var user = WorkWithUser(student, history); if (user == null) { - if (_userLogic.Errors.Count > 0) - { - var errors = _userLogic.Errors; - errors.Add(("Ошибка получения пользователя под студента", $"Не удалось получить пользователя под студента {student.lastName} {student.firstName} {student.patronymicName}")); - _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel - { - OrderSyncHistoryId = history.Id, - Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) - }); - continue; - } + continue; } var newStudent = _studentLogic.Create(new StudentSetBindingModel @@ -237,7 +194,6 @@ namespace DepartmentBusinessLogic.BusinessLogics StudentState = StudentState.Неопределен, Description = string.Empty }); - if (newStudent == null) { var errors = _studentLogic.Errors; @@ -261,6 +217,20 @@ namespace DepartmentBusinessLogic.BusinessLogics return true; } + private void InitLogics() + { + + _recordLogic = DependencyManager.Instance.Resolve(); + _enviromentSettingLogic = DependencyManager.Instance.Resolve(); + _groupsLogic = DependencyManager.Instance.Resolve(); + _studentLogic = DependencyManager.Instance.Resolve(); + _orderLogic = DependencyManager.Instance.Resolve(); + _orderStudentRecordLogic = DependencyManager.Instance.Resolve(); + _userLogic = DependencyManager.Instance.Resolve(); + _userRoleLogic = DependencyManager.Instance.Resolve(); + _roleLogic = DependencyManager.Instance.Resolve(); + } + /// /// Синхронизация приказов по студенту /// @@ -286,6 +256,12 @@ namespace DepartmentBusinessLogic.BusinessLogics var syncOrders = JsonSerializer.Deserialize(await response.Content.ReadAsStringAsync()); foreach (var syncOrder in syncOrders.StudentOrders) { + if (syncOrder.orderTypeName == "Утверждение тем курсовых работ" || + syncOrder.orderTypeName == "Утверждение тем ВКР" || + syncOrder.orderTypeName == "Назначение стипендии") + { + continue; + } if (syncOrder.markOfApprove.ToLower() != "true") { _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel @@ -316,6 +292,10 @@ namespace DepartmentBusinessLogic.BusinessLogics var orderType = GetOrderType(syncOrder.orderTypeName); // пропускаем приказы, которые нас не интересуют + if (orderType == OrderType.Игнорировать) + { + continue; + } if (orderType == OrderType.Неопределено) { if (syncOrder.orderTypeName != "Корректировка" && syncOrder.orderTypeName != "Назначение стипендии" && @@ -473,7 +453,7 @@ namespace DepartmentBusinessLogic.BusinessLogics } // ищем в приказе запись по студенту - var studentOrder = _orderStudentRecordLogic.GetElement(new OrderStudentRecordGetBindingModel + var exsistStudentOrder = _orderStudentRecordLogic.GetElement(new OrderStudentRecordGetBindingModel { OrderId = order.Id, StudentId = student.Id, @@ -481,13 +461,13 @@ namespace DepartmentBusinessLogic.BusinessLogics }); // если такой приказ по студенту уже есть, просто пропускаем - if (studentOrder != null) + if (exsistStudentOrder != null) { continue; } // создаем, если не нашли - studentOrder = _orderStudentRecordLogic.Create(new OrderStudentRecordSetBindingModel + var studentOrder = _orderStudentRecordLogic.Create(new OrderStudentRecordSetBindingModel { OrderId = order.Id, StudentId = student.Id, @@ -525,6 +505,103 @@ namespace DepartmentBusinessLogic.BusinessLogics } } + private HttpClient GetClinet(OrderSyncHistoryViewModel history, EnviromentSettingViewModel address) + { + + var username = _enviromentSettingLogic.GetList(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderUserName" })?.List?.FirstOrDefault(); + if (username == null || username.Value.IsEmpty()) + { + Errors = _enviromentSettingLogic.Errors; + Errors.Add(("Ошибка получения данных", "Не удалось получить имя пользователя для получения приказов по студентам")); + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel + { + OrderSyncHistoryId = history.Id, + Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) + }); + return null; + } + + var password = _enviromentSettingLogic.GetList(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderPassword" })?.List?.FirstOrDefault(); + if (password == null || password.Value.IsEmpty()) + { + Errors = _enviromentSettingLogic.Errors; + Errors.Add(("Ошибка получения данных", "Не удалось получить пароль для получения приказов по студентам")); + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel + { + OrderSyncHistoryId = history.Id, + Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message)) + }); + return null; + } + + var client = new HttpClient + { + BaseAddress = new Uri(address.Value) + }; + client.DefaultRequestHeaders.Accept.Clear(); + client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username.Value}:{password.Value}"))); + + return client; + } + + private UserViewModel WorkWithUser(StudentSyncModel student, OrderSyncHistoryViewModel history) + { + var userName = $"{student.lastName}{(student.firstName.IsNotEmpty() ? $" {student.firstName[0]}." : string.Empty)}{(student.patronymicName.IsNotEmpty() ? $"{student.patronymicName[0]}." : string.Empty)}"; + var user = _userLogic.GetOrCreateUser(new UserGetBindingModel + { + Login = student.recordBookName + }, userName); + if (user == null) + { + if (_userLogic.Errors.Count > 0) + { + var errors = _userLogic.Errors; + errors.Add(("Ошибка получения пользователя под студента", $"Не удалось получить пользователя под студента {student.lastName} {student.firstName} {student.patronymicName}")); + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel + { + OrderSyncHistoryId = history.Id, + Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) + }); + return null; + } + } + var role = _roleLogic.GetElement(new RoleGetBindingModel { RoleName = "Студент" }); + if (role == null) + { + if (_roleLogic.Errors.Count > 0) + { + var errors = _roleLogic.Errors; + errors.Add(("Ошибка получения роли студента", $"Не удалось получить роль студента {student.lastName} {student.firstName} {student.patronymicName}")); + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel + { + OrderSyncHistoryId = history.Id, + Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) + }); + return null; + } + } + var link = _userRoleLogic.GetElement(new UserRoleGetBindingModel { RoleId = role.Id, UserId = user.Id }); + if (link == null) + { + var manager = DependencyManager.Instance.Resolve(); + _userRoleLogic.Create(new UserRoleSetBindingModel { RoleId = role.Id, UserId = user.Id, UserIdForAccess = manager?.User }); + if (_userRoleLogic.Errors.Count > 0) + { + var errors = _userRoleLogic.Errors; + errors.Add(("Ошибка создания привязки студента к роли", $"Не удалось привязать студента {student.lastName} {student.firstName} {student.patronymicName} к роли")); + _recordLogic.Create(new OrderSyncHistoryRecordSetBindingModel + { + OrderSyncHistoryId = history.Id, + Information = string.Join(Environment.NewLine, errors.Select(x => x.Message)) + }); + return null; + } + } + + return user; + } + private static OrderType GetOrderType(string orderTitle) => orderTitle switch { "Зачисление в вуз вне приемной кампании" => OrderType.ЗачислениеСтудентов, @@ -537,8 +614,12 @@ namespace DepartmentBusinessLogic.BusinessLogics "Продление академического отпуска" => OrderType.ДвижениеСтудентов, "Восстановление из академического отпуска" => OrderType.ДвижениеСтудентов, "Отчисление" => OrderType.Отчисление, + "Отчисление (за невыполнение обязанностей по добросовестному освоению образовательной программы и выполнению учебного плана)" => OrderType.Отчисление, + "Отчисление (в связи с переводом в ___)" => OrderType.Отчисление, + "Отчисление (в связи с невыходом из академического отпуска)" => OrderType.Отчисление, "Восстановление" => OrderType.Перевод, "Выпуск" => OrderType.ДвижениеСтудентов, + "Утверждение тем ВКР" => OrderType.Игнорировать, _ => OrderType.Неопределено, }; } diff --git a/DepartmentPortal/Department/DepartmentBusinessLogic/Enums/OrderType.cs b/DepartmentPortal/Department/DepartmentBusinessLogic/Enums/OrderType.cs index fee74be..c844d64 100644 --- a/DepartmentPortal/Department/DepartmentBusinessLogic/Enums/OrderType.cs +++ b/DepartmentPortal/Department/DepartmentBusinessLogic/Enums/OrderType.cs @@ -5,6 +5,8 @@ /// public enum OrderType { + Игнорировать = -2, + Неопределено = -1, ЗачислениеСтудентов = 0, diff --git a/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/RoleBindingModels.cs b/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/RoleBindingModels.cs index 05e69bb..94dbe4f 100644 --- a/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/RoleBindingModels.cs +++ b/DepartmentPortal/Security/SecurityBusinessLogic/BindingModels/RoleBindingModels.cs @@ -7,7 +7,10 @@ namespace SecurityBusinessLogic.BindingModels /// /// Получение роли /// - public class RoleGetBindingModel : GetBindingModel { } + public class RoleGetBindingModel : GetBindingModel + { + public string RoleName { get; set; } + } /// /// Сохранение роли diff --git a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/RoleService.cs b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/RoleService.cs index b6fff9a..b0bb848 100644 --- a/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/RoleService.cs +++ b/DepartmentPortal/Security/SecurityDatabaseImplementation/Implementations/RoleService.cs @@ -2,6 +2,7 @@ using DatabaseCore.Models.Security; using Microsoft.EntityFrameworkCore; using ModuleTools.Enums; +using ModuleTools.Extensions; using ModuleTools.Models; using SecurityBusinessLogic.BindingModels; using SecurityBusinessLogic.Interfaces; @@ -49,5 +50,23 @@ namespace SecurityDatabaseImplementation.Implementations protected override IQueryable IncludingWhenReading(IQueryable query) => query; protected override IQueryable OrderingWhenReading(IQueryable query) => query.OrderBy(x => x.RoleName); + + protected override bool AdditionalCheckForSingleGet(RoleGetBindingModel model) + { + if (model.RoleName.IsNotEmpty()) + { + return true; + } + return base.AdditionalCheckForSingleGet(model); + } + + protected override Role GetSingleRecord(IQueryable list, RoleGetBindingModel model) + { + if (model.RoleName.IsNotEmpty()) + { + return list.FirstOrDefault(x => x.RoleName == model.RoleName); + } + return base.GetSingleRecord(list, model); + } } } \ No newline at end of file