DepartmentProject/DepartmentPortal/Department/DepartmentBusinessLogic/BusinessLogics/OrderSyncHistoryBusinessLogic.cs

263 lines
12 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using DepartmentBusinessLogic.BindingModels;
using DepartmentBusinessLogic.Enums;
using DepartmentBusinessLogic.HelperModels;
using DepartmentBusinessLogic.Interfaces;
using DepartmentBusinessLogic.ViewModels;
using ModuleTools.BusinessLogics;
using ModuleTools.Enums;
using ModuleTools.Extensions;
using SecurityBusinessLogic.BindingModels;
using SecurityBusinessLogic.BusinessLogics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace DepartmentBusinessLogic.BusinessLogics
{
/// <summary>
/// Логика работы с историями синхронизации приказов
/// </summary>
public class OrderSyncHistoryBusinessLogic : GenericBusinessLogic<OrderSyncHistoryGetBindingModel, OrderSyncHistorySetBindingModel, OrderSyncHistoryListViewModel, OrderSyncHistoryViewModel>
{
public OrderSyncHistoryBusinessLogic(IOrderSyncHistoryService service) : base(service, "Синхронизация Приказов", AccessOperation.СинхронизацияПриказов) { }
public async Task<bool> SyncOrders()
{
var history = await CreateAsync(new OrderSyncHistorySetBindingModel { SyncDate = DateTime.Now });
if (history == null)
{
Errors.Add(("Ошибка создание истории", "Не удалось создать историю"));
return false;
}
var recordLogic = DependencyManager.Instance.Resolve<OrderSyncHistoryRecordBusinessLogic>();
var enviromentSettingLogic = DependencyManager.Instance.Resolve<EnviromentSettingBusinessLogic>();
var address = (await enviromentSettingLogic.GetListAsync(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderIpAddress" }))?.List?.FirstOrDefault();
if (address == null || address.Value.IsEmpty())
{
Errors = enviromentSettingLogic.Errors;
Errors.Add(("Ошибка получения данных", "Не удалось получить адрес серверая для получения приказов по студентам"));
await recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel
{
OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message))
});
return false;
}
var username = (await enviromentSettingLogic.GetListAsync(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderUserName" }))?.List?.FirstOrDefault();
if (username == null || username.Value.IsEmpty())
{
Errors = enviromentSettingLogic.Errors;
Errors.Add(("Ошибка получения данных", "Не удалось получить имя пользователя для получения приказов по студентам"));
await recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel
{
OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message))
});
return false;
}
var password = (await enviromentSettingLogic.GetListAsync(new EnviromentSettingGetBindingModel { Key = "SyncStudentOrderPassword" }))?.List?.FirstOrDefault();
if (password == null || password.Value.IsEmpty())
{
Errors = enviromentSettingLogic.Errors;
Errors.Add(("Ошибка получения данных", "Не удалось получить пароль для получения приказов по студентам"));
await recordLogic.CreateAsync(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}")));
// авторизация
// получение списка студентов
HttpResponseMessage response = await client.GetAsync($"{address.Value}/univer_Testing/hs/Ulstu_StudentsInfo/v1/GetCurrentStudentsOfDepartment");
if (!response.IsSuccessStatusCode)
{
Errors.Add(("Ошибка получения данных", "Не удалось получить список студентов с сервера"));
await recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel
{
OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message))
});
return false;
}
var studentFromServer = JsonSerializer.Deserialize<StudentListSyncModel>(response.Content.ReadAsStringAsync().Result);
if (studentFromServer.CurrentStudentsList.Count == 0)
{
await recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel
{
OrderSyncHistoryId = history.Id,
Information = "Полученный список студентов пустой"
});
return true;
}
var groupsLogic = DependencyManager.Instance.Resolve<StudentGroupBusinessLogic>();
var groups = await groupsLogic.GetListAsync(new StudentGroupGetBindingModel());
if (groups == null || groups.List == null)
{
Errors = groupsLogic.Errors;
Errors.Add(("Ошибка получения данных", "Не удалось получить список групп"));
await recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel
{
OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message))
});
return false;
}
var studentLogic = DependencyManager.Instance.Resolve<StudentBusinessLogic>();
var userLogic = DependencyManager.Instance.Resolve<UserBusinessLogic>();
foreach (var group in groups.List)
{
var students = await studentLogic.GetListAsync(new StudentGetBindingModel { StudentGroupId = group.Id });
foreach (var student in students.List)
{
var studentSync = studentFromServer.CurrentStudentsList.FirstOrDefault(x => x.recordBookName == student.NumberOfBook);
// студент не найден, значит он ушел с кафедры, выясняем почему
if (studentSync == null)
{
await SyncStudentOrders(history, student, client, address.Value, studentSync.iduniv);
}
// перевод в другую группу
else if (group.GroupName != studentSync.groupName)
{
await SyncStudentOrders(history, student, client, address.Value, studentSync.iduniv);
}
studentFromServer.CurrentStudentsList.Remove(studentSync);
}
// новые студенты в группе
var studentSyncs = studentFromServer.CurrentStudentsList.Where(x => x.groupName == group.GroupName);
foreach (var student in studentSyncs)
{
var userName = $"{student.lastName}{(student.firstName.IsNotEmpty() ? $" {student.firstName[0]}." : string.Empty)}{(student.patronymicName.IsNotEmpty() ? $"{student.patronymicName[0]}." : string.Empty)}";
var result = await userLogic.GetListAsync(new UserGetBindingModel { UserNameForSearch = userName });
var newuser = await userLogic.CreateAsync(new UserSetBindingModel
{
Login = userName,
Password = student.recordBookName
});
if (newuser == null)
{
var errors = userLogic.Errors;
errors.Add(("Ошибка создания пользователя под студента", $"Не удалось создать пользователя под студента {student.lastName} {student.firstName} {student.patronymicName}"));
await recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel
{
OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, errors.Select(x => x.Message))
});
continue;
}
var newStudent = await studentLogic.CreateAsync(new StudentSetBindingModel
{
UserId = newuser.Id,
FirstName = student.firstName,
LastName = student.lastName,
Patronymic = student.patronymicName,
NumberOfBook = student.recordBookName,
StudentGroupId = group.Id,
StudentState = GetStudentState(student.stateName),
Description = student.presenatationOfRecordBook
});
if (newStudent == null)
{
var errors = studentLogic.Errors;
errors.Add(("Ошибка добавления студента", $"Не удалось добавить студента {student.lastName} {student.firstName} {student.patronymicName}"));
await recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel
{
OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, errors.Select(x => x.Message))
});
continue;
}
await recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel
{
OrderSyncHistoryId = history.Id,
Information = $"Добавлен студент {newStudent}"
});
await SyncStudentOrders(history, newStudent, client, address.Value, student.iduniv);
studentFromServer.CurrentStudentsList.Remove(student);
}
}
return true;
}
private static StudentState GetStudentState(string state) => state switch
{
"Является студентом" => StudentState.Учится,
"Находится в академическом отпуске" => StudentState.Академ,
_ => StudentState.Неопределен,
};
/// <summary>
/// Синхронизация приказов по студенту
/// </summary>
/// <param name="history"></param>
/// <param name="student"></param>
/// <param name="client"></param>
/// <param name="address"></param>
/// <param name="iduniv"></param>
/// <returns></returns>
private async Task SyncStudentOrders(OrderSyncHistoryViewModel history, StudentViewModel student, HttpClient client, string address, string iduniv)
{
var recordLogic = DependencyManager.Instance.Resolve<OrderSyncHistoryRecordBusinessLogic>();
var orderLogic = DependencyManager.Instance.Resolve<OrderBusinessLogic>();
HttpResponseMessage response = await client.GetAsync($"{address}/univer_Testing/hs/Ulstu_StudentsInfo/v1/GetStudentOrdersByIdAndRecordBook?iduniv={iduniv}&recordBookName={student.NumberOfBook}&allOrders=sppd");
if (!response.IsSuccessStatusCode)
{
Errors.Add(("Ошибка получения данных", "Не удалось получить список приказов по студенту"));
await recordLogic.CreateAsync(new OrderSyncHistoryRecordSetBindingModel
{
OrderSyncHistoryId = history.Id,
Information = string.Join(Environment.NewLine, Errors.Select(x => x.Message))
});
return;
}
var syncOrders = JsonSerializer.Deserialize<StudentOrderListSyncModel>(response.Content.ReadAsStringAsync().Result);
foreach(var syncOrder in syncOrders.StudentOrders)
{
var orderType = GetOrderType(syncOrder.orderSubTypeName);
if (orderType != OrderType.Неопределено)
{
var order = await orderLogic.GetListAsync(new OrderGetBindingModel { OrderNumber = syncOrder.clericNumber, OrderDate = Convert.ToDateTime(syncOrder.clericDate) });
}
}
}
private static OrderType GetOrderType(string orderTitle) => orderTitle switch
{
"Зачисление в вуз" => OrderType.ЗачислениеСтудентов,
"Распределение по группам" => OrderType.РаспределениеСтудентов,
"Перевод на следующий курс" => OrderType.ДвижениеСтудентов,
_ => OrderType.Неопределено,
};
}
}