привязка студента к роли при создании

This commit is contained in:
kotcheshir73 2022-03-18 20:09:15 +04:00
parent 1d3d35d106
commit 7b682e50d7
5 changed files with 167 additions and 62 deletions

View File

@ -63,7 +63,7 @@ namespace ModuleTools.BusinessLogics
continue;
}
object value = obj;
object value = null;
var customAttribute = property.GetCustomAttribute<MapConfigurationAttribute>();
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);

View File

@ -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<bool> 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<OrderSyncHistoryRecordBusinessLogic>();
_enviromentSettingLogic = DependencyManager.Instance.Resolve<EnviromentSettingBusinessLogic>();
_groupsLogic = DependencyManager.Instance.Resolve<StudentGroupBusinessLogic>();
_studentLogic = DependencyManager.Instance.Resolve<StudentBusinessLogic>();
_orderLogic = DependencyManager.Instance.Resolve<OrderBusinessLogic>();
_orderStudentRecordLogic = DependencyManager.Instance.Resolve<OrderStudentRecordBusinessLogic>();
_userLogic = DependencyManager.Instance.Resolve<UserBusinessLogic>();
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<OrderSyncHistoryRecordBusinessLogic>();
_enviromentSettingLogic = DependencyManager.Instance.Resolve<EnviromentSettingBusinessLogic>();
_groupsLogic = DependencyManager.Instance.Resolve<StudentGroupBusinessLogic>();
_studentLogic = DependencyManager.Instance.Resolve<StudentBusinessLogic>();
_orderLogic = DependencyManager.Instance.Resolve<OrderBusinessLogic>();
_orderStudentRecordLogic = DependencyManager.Instance.Resolve<OrderStudentRecordBusinessLogic>();
_userLogic = DependencyManager.Instance.Resolve<UserBusinessLogic>();
_userRoleLogic = DependencyManager.Instance.Resolve<UserRoleBusinessLogic>();
_roleLogic = DependencyManager.Instance.Resolve<RoleBusinessLogic>();
}
/// <summary>
/// Синхронизация приказов по студенту
/// </summary>
@ -286,6 +256,12 @@ namespace DepartmentBusinessLogic.BusinessLogics
var syncOrders = JsonSerializer.Deserialize<StudentOrderListSyncModel>(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<ISecurityManager>();
_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.Неопределено,
};
}

View File

@ -5,6 +5,8 @@
/// </summary>
public enum OrderType
{
Игнорировать = -2,
Неопределено = -1,
ЗачислениеСтудентов = 0,

View File

@ -7,7 +7,10 @@ namespace SecurityBusinessLogic.BindingModels
/// <summary>
/// Получение роли
/// </summary>
public class RoleGetBindingModel : GetBindingModel { }
public class RoleGetBindingModel : GetBindingModel
{
public string RoleName { get; set; }
}
/// <summary>
/// Сохранение роли

View File

@ -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<Role> IncludingWhenReading(IQueryable<Role> query) => query;
protected override IQueryable<Role> OrderingWhenReading(IQueryable<Role> 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<Role> list, RoleGetBindingModel model)
{
if (model.RoleName.IsNotEmpty())
{
return list.FirstOrDefault(x => x.RoleName == model.RoleName);
}
return base.GetSingleRecord(list, model);
}
}
}