diff --git a/School/School.sln b/School/School.sln new file mode 100644 index 0000000..dcab06b --- /dev/null +++ b/School/School.sln @@ -0,0 +1,43 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.3.32922.545 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SchoolDataModels", "School\SchoolDataModels.csproj", "{6C8CCA43-D189-445E-B430-C341745F6761}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SchoolDataBaseImplement", "SchoolDataBaseImplement\SchoolDataBaseImplement.csproj", "{D9840F4F-BFA0-4EF9-9EBB-EB9723CB2BAE}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SchoolContracts", "SchoolContracts\SchoolContracts.csproj", "{9DA05BF2-D735-4C58-B5CC-41442B46FB97}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SchoolBusinessLogics", "SchoolBusinessLogics\SchoolBusinessLogics.csproj", "{39948F72-26CF-490B-A152-9AEB5597D360}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {6C8CCA43-D189-445E-B430-C341745F6761}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6C8CCA43-D189-445E-B430-C341745F6761}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6C8CCA43-D189-445E-B430-C341745F6761}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6C8CCA43-D189-445E-B430-C341745F6761}.Release|Any CPU.Build.0 = Release|Any CPU + {D9840F4F-BFA0-4EF9-9EBB-EB9723CB2BAE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D9840F4F-BFA0-4EF9-9EBB-EB9723CB2BAE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D9840F4F-BFA0-4EF9-9EBB-EB9723CB2BAE}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D9840F4F-BFA0-4EF9-9EBB-EB9723CB2BAE}.Release|Any CPU.Build.0 = Release|Any CPU + {9DA05BF2-D735-4C58-B5CC-41442B46FB97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9DA05BF2-D735-4C58-B5CC-41442B46FB97}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9DA05BF2-D735-4C58-B5CC-41442B46FB97}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9DA05BF2-D735-4C58-B5CC-41442B46FB97}.Release|Any CPU.Build.0 = Release|Any CPU + {39948F72-26CF-490B-A152-9AEB5597D360}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {39948F72-26CF-490B-A152-9AEB5597D360}.Debug|Any CPU.Build.0 = Debug|Any CPU + {39948F72-26CF-490B-A152-9AEB5597D360}.Release|Any CPU.ActiveCfg = Release|Any CPU + {39948F72-26CF-490B-A152-9AEB5597D360}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {7B0FE67E-8DCA-49AC-8D92-C7F538B6F05D} + EndGlobalSection +EndGlobal diff --git a/School/School/IAccountModel.cs b/School/School/IAccountModel.cs new file mode 100644 index 0000000..25c27d4 --- /dev/null +++ b/School/School/IAccountModel.cs @@ -0,0 +1,10 @@ +using SchoolDataModels.Interfaces; + +namespace SchoolDataModels +{ + public interface IAccountModel: IId + { + int StudentByDisciplineId { get; } + double Price { get; } + } +} diff --git a/School/School/IDisciplineModel.cs b/School/School/IDisciplineModel.cs new file mode 100644 index 0000000..549838c --- /dev/null +++ b/School/School/IDisciplineModel.cs @@ -0,0 +1,15 @@ +using SchoolDataModels; + +namespace SchoolContracts.BindingModels +{ + public class AccountBindingModel : IAccountModel + { + public int StudentByDisciplineId { get; set; } + + public DateOnly DateOfAccount { get; set; } = DateOnly.FromDateTime(DateTime.Now); + + public double Price { get; set; } + + public int Id { get; set; } + } +} \ No newline at end of file diff --git a/School/School/IExecutorModel.cs b/School/School/IExecutorModel.cs new file mode 100644 index 0000000..349b77b --- /dev/null +++ b/School/School/IExecutorModel.cs @@ -0,0 +1,8 @@ +using SchoolDataModels.Interfaces; + +namespace SchoolDataModels +{ + public interface IExecutorModel : IUser + { + } +} diff --git a/School/School/IImplementerModel.cs b/School/School/IImplementerModel.cs new file mode 100644 index 0000000..b3c9813 --- /dev/null +++ b/School/School/IImplementerModel.cs @@ -0,0 +1,8 @@ +using SchoolDataModels.Interfaces; + +namespace SchoolDataModels +{ + public interface IImplementerModel : IUser + { + } +} diff --git a/School/School/IRequirementModel.cs b/School/School/IRequirementModel.cs new file mode 100644 index 0000000..0208daa --- /dev/null +++ b/School/School/IRequirementModel.cs @@ -0,0 +1,14 @@ +using SchoolDataModels.Interfaces; +using SchoolDataModels.Models; + +namespace SchoolDataModels +{ + public interface IRequirementModel : IId + { + int ExecutorId { get; } + string NameOfRequirement { get; } + double Price { get; } + + Dictionary DisciplinesModels { get; } + } +} diff --git a/School/School/IStudentModel.cs b/School/School/IStudentModel.cs new file mode 100644 index 0000000..0ab6aa9 --- /dev/null +++ b/School/School/IStudentModel.cs @@ -0,0 +1,11 @@ +using SchoolDataModels.Interfaces; + +namespace SchoolDataModels +{ + public interface IStudentModel : IId + { + int ExecutorId { get; } + string Name { get; } + int Course { get; } + } +} diff --git a/School/School/Interfaces/IId.cs b/School/School/Interfaces/IId.cs new file mode 100644 index 0000000..0c025d4 --- /dev/null +++ b/School/School/Interfaces/IId.cs @@ -0,0 +1,7 @@ +namespace SchoolDataModels.Interfaces +{ + public interface IId + { + int Id { get; } + } +} diff --git a/School/School/Interfaces/IUser.cs b/School/School/Interfaces/IUser.cs new file mode 100644 index 0000000..2c7380a --- /dev/null +++ b/School/School/Interfaces/IUser.cs @@ -0,0 +1,14 @@ +namespace SchoolDataModels.Interfaces +{ + public interface IUser : IId + { + string FirstName { get; } + string LastName { get; } + + string Login { get; } + + string Password { get; } + + string PhoneNumber { get; } + } +} diff --git a/School/School/Models/RequirementByDisciplineModel.cs b/School/School/Models/RequirementByDisciplineModel.cs new file mode 100644 index 0000000..b0188fb --- /dev/null +++ b/School/School/Models/RequirementByDisciplineModel.cs @@ -0,0 +1,14 @@ +using SchoolDataModels.Interfaces; + +namespace SchoolDataModels.Models +{ + public class RequirementByDisciplineModel : IId + { + public virtual int Id { get; set; } + + public virtual int RequirementId { get; set; } + public virtual int DisciplineId { get; set; } + + public virtual int Count { get; set; } + } +} diff --git a/School/School/Models/StudentByDisciplinModel.cs b/School/School/Models/StudentByDisciplinModel.cs new file mode 100644 index 0000000..59c44c4 --- /dev/null +++ b/School/School/Models/StudentByDisciplinModel.cs @@ -0,0 +1,11 @@ +namespace SchoolDataModels.Models +{ + public class StudentByDisciplineModel + { + public virtual int Id { get; set; } + public virtual int StudentId { get; set; } + public virtual int DisciplineId { get; set; } + + public virtual DateTime DateOfStudent { get; set; } + } +} diff --git a/School/School/SchoolDataModels.csproj b/School/School/SchoolDataModels.csproj new file mode 100644 index 0000000..8b2bcde --- /dev/null +++ b/School/School/SchoolDataModels.csproj @@ -0,0 +1,15 @@ + + + + WinExe + net6.0-windows + enable + true + enable + + + + + + + \ No newline at end of file diff --git a/School/SchoolBusinessLogics/BusinessLogics/AccountLogic.cs b/School/SchoolBusinessLogics/BusinessLogics/AccountLogic.cs new file mode 100644 index 0000000..8591a92 --- /dev/null +++ b/School/SchoolBusinessLogics/BusinessLogics/AccountLogic.cs @@ -0,0 +1,116 @@ +using SchoolContracts.BusinessLogicContracts; +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.ViewModels; +using Microsoft.Extensions.Logging; +using SchoolContracts.StoragesContracts; + +namespace SchoolBusinessLogics.BusinessLogics +{ + public class AccountLogic : IAccountLogic + { + private readonly ILogger _logger; + private readonly IAccountStorage _accountStorage; + private readonly IDisciplineLogic _disciplineStorage; + + public AccountLogic(ILogger logger, IAccountStorage accountStorage, IDisciplineLogic disciplineStorage) + { + _logger = logger; + _accountStorage = accountStorage; + _disciplineStorage = disciplineStorage; + } + public List ReadList(AccountSearchModel? model) + { + try + { + var results = model != null ? _accountStorage.GetFilteredList(model) : _accountStorage.GetFullList(); + _logger.LogDebug("Список полученных счетов: {@accounts}", results); + _logger.LogInformation("Извлечение списка в количестве {Count} c счетовой по модели: {@AccountSearchModel}", results.Count, model); + return results; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки получить список по модели: {@AccountSearchModel}", model); + throw; + } + } + public AccountViewModel ReadElement(AccountSearchModel model) + { + try + { + var result = _accountStorage.GetElement(model); + if (result == null) + { + throw new ArgumentNullException($"Результат получения элемента с айди {model.Id} оказался нулевым"); + } + _logger.LogInformation("Извлечение счета {@AccountViewModel} по модели: {@AccountSearchModel}", result, model); + return result; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки получить элемент по модели: {@AccountSearchModel}", model); + throw; + } + } + public bool Create(AccountBindingModel model) + { + try + { + CheckModel(model); + var result = _accountStorage.Insert(model); + if (result == null) + { + throw new ArgumentNullException($"Результат создания счета оказался нулевым"); + } + _logger.LogInformation("Была создана сущность: {@AccountViewModel}", result); + return true; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки создать элемент по модели: {@AccountBindingModel}", model); + throw; + } + } + private void CheckModel(AccountBindingModel model, bool withParams = true) + { + const string txt = "Произошла ошибка на уровне проверки AccountBindingModel."; + if (model == null) + { + throw new ArgumentNullException(nameof(model), txt); + } + if (!withParams) + { + return; + } + if (model.Price < 0) + { + throw new ArgumentNullException(nameof(model.Price), txt + "Оплаченная стоимость не может быть отрицательной"); + } + } + public bool GetAccountInfo(AccountSearchModel model, + out double currentBalance, + out double paidPrice) + { + try + { + var accounts = ReadList(model); // Вызываем метод из бизнес логики, чтобы залогировать доп информацию + paidPrice = 0; + if (accounts == null || accounts.Count == 0) + { + currentBalance = 0; + return true; + } + currentBalance = accounts.Sum(x => x.Price); + _logger.LogInformation( + "По дисциплине({Id}) и клиенту({Id}) получена полная стоимостиь {fullPrice} и оплаченная стоимость {paidPrice}", + model.DisciplineId, model.ClientId, currentBalance, paidPrice); + return true; + } + catch (Exception e) + { + _logger.LogError(e, "При попытке получения счетов по {@searchModel} произошла ошибка", model); + throw; + } + } + } +} diff --git a/School/SchoolBusinessLogics/BusinessLogics/DisciplineLogic.cs b/School/SchoolBusinessLogics/BusinessLogics/DisciplineLogic.cs new file mode 100644 index 0000000..3b3b6d7 --- /dev/null +++ b/School/SchoolBusinessLogics/BusinessLogics/DisciplineLogic.cs @@ -0,0 +1,131 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.BusinessLogicContracts; +using SchoolContracts.SearchModels; +using SchoolContracts.StoragesContracts; +using SchoolContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace SchoolBusinessLogics.BusinessLogics +{ + public class DisciplineLogic : IDisciplineLogic + { + private readonly ILogger _logger; + private readonly IDisciplineStorage _disciplineStorage; + + public DisciplineLogic(ILogger logger, IDisciplineStorage disciplineStorage) + { + _logger = logger; + _disciplineStorage = disciplineStorage; + } + + public void CheckModel(DisciplineBindingModel model, bool checkParams = true) + { + const string txt = "Произошла ошибка на уровне проверки DisciplineBindingModel."; + if (model == null) + { + throw new ArgumentNullException(nameof(model), txt); + } + if (checkParams is false) + { + return; + } + } + + public List ReadList(DisciplineSearchModel? model) + { + try + { + var results = model != null ? _disciplineStorage.GetFilteredList(model) : _disciplineStorage.GetFullList(); + _logger.LogDebug("Список полученных дисциплин на посещение: {@disciplinesVisit}", results); + _logger.LogInformation("Извлечение списка в количестве {Count} c дисциплин на посещение по модели: {@DisciplineSearchModel}", results.Count, model); + return results; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки получить список по модели: {@DisciplineSearchModel}", model); + throw; + } + } + + public DisciplineViewModel ReadElement(DisciplineSearchModel model) + { + try + { + var result = _disciplineStorage.GetElement(model); + if (result == null) + { + throw new ArgumentNullException($"Результат получения элемента с айди {model.Id} оказался нулевым"); + } + _logger.LogInformation("Извлечение элемента {@DisciplineViewModel} c дисциплин на посещение по модели: {@DisciplineSearchModel}", result, model); + return result; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки получить элемент по модели: {@DisciplineSearchModel}", model); + throw; + } + } + + public bool Create(DisciplineBindingModel model) + { + try + { + CheckModel(model); + var result = _disciplineStorage.Insert(model); + if (result == null) + { + throw new ArgumentNullException($"Результат создания дисциплины на посещение оказался нулевым"); + } + _logger.LogInformation("Была создана сущность: {@DisciplineViewModel}", result); + return true; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки создать элемент по модели: {@DisciplineBindingModel}", model); + throw; + } + } + + public bool Update(DisciplineBindingModel model) + { + try + { + CheckModel(model); + var result = _disciplineStorage.Update(model); + if (result == null) + { + throw new ArgumentNullException($"Результат обновления дисциплины на посещение оказался нулевым"); + } + _logger.LogInformation("Была обновлена сущность на: {@DisciplineViewModel}", result); + return true; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки обновить элемент по модели: {@DisciplineBindingModel}", model); + throw; + } + } + + public bool Delete(DisciplineBindingModel model) + { + try + { + CheckModel(model, false); + var result = _disciplineStorage.Delete(model); + if (result == null) + { + throw new ArgumentNullException($"Результат удаления дисциплины на посещение оказался нулевым"); + } + _logger.LogInformation("Была удалена сущность: {@DisciplineViewModel}", result); + return true; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки удалить элемент по модели: {@DisciplineBindingModel}", model); + throw; + } + } + } +} + + diff --git a/School/SchoolBusinessLogics/BusinessLogics/ExecutorLogic.cs b/School/SchoolBusinessLogics/BusinessLogics/ExecutorLogic.cs new file mode 100644 index 0000000..b72c1c2 --- /dev/null +++ b/School/SchoolBusinessLogics/BusinessLogics/ExecutorLogic.cs @@ -0,0 +1,105 @@ +using SchoolContracts.BusinessLogicContracts; +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.ViewModels; +using Microsoft.Extensions.Logging; +using SchoolContracts.StoragesContracts; +using System.Text.RegularExpressions; + +namespace SchoolBusinessLogics.BusinessLogics +{ + public class ExecutorLogic : IExecutorLogic + { + private readonly ILogger _logger; + private readonly IExecutorStorage _employeeStorage; + public ExecutorLogic(ILogger logger, IExecutorStorage employeeStorage) + { + _logger = logger; + _employeeStorage = employeeStorage; + } + + public bool Create(ExecutorBindingModel model) + { + try + { + CheckModel(model); + var result = _employeeStorage.Insert(model); + if (result == null) + { + throw new ArgumentNullException($"Результат создания работника оказался нулевым"); + } + _logger.LogInformation("Была создана сущность: {@ExecutorViewModel}", result); + return true; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки создать элемент по модели: {@ExecutorBindingModel}", model); + throw; + } + } + + public ExecutorViewModel ReadElement(ExecutorSearchModel model) + { + try + { + var result = _employeeStorage.GetElement(model); + if (result == null) + { + throw new ArgumentNullException($"Результат получения элемента с айди {model.Id} оказался нулевым"); + } + _logger.LogInformation("Извлечение элемента {@DirectorViewModel} c работника по модели: {@ExecutorSearchModel}", result, model); + return result; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки получить элемент по модели: {@ExecutorSearchModel}", model); + throw; + } + } + + private void CheckModel(ExecutorBindingModel model, bool withParams = true) + { + const string txt = "Произошла ошибка на уровне проверки ExecutorBindingModel."; + if (model == null) + { + throw new ArgumentNullException(nameof(model), txt); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.Login)) + { + throw new ArgumentNullException(nameof(model.Login), txt + "Нет логина работника"); + } + if (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException(nameof(model.Password), txt + "Нет пароля работника"); + } + if (model.Login.Length is < 5 or > 50) + { + throw new ArgumentException("Логин пользователя должен быть от 5 до 50 символом", nameof(model.Login)); + } + + if (model.Password.Length < 5) + { + throw new ArgumentException("Пароль пользователя должен быть не менее 5 символов", nameof(model.Password)); + } + if (!Regex.IsMatch(model.Password, "[0-9]+")) + { + throw new ArgumentException("Пароль пользователя должен содержать хотя бы одну цифру", + nameof(model.Password)); + } + _logger.LogDebug("{level} Проверка логина пользователя на уникальность {@Executor}", txt, model); + var element = _employeeStorage.GetElement(new ExecutorSearchModel + { + Login = model.Login, + }); + if (element != null && element.Id != model.Id) + { + _logger.LogWarning("С логином: {login}, уже есть пользователь: {@ExistExecutor}", model.Login, element); + throw new InvalidOperationException($"Работник с таким логином \"{model.Login}\" уже есть"); + } + } + } +} diff --git a/School/SchoolBusinessLogics/BusinessLogics/ImplementerLogic.cs b/School/SchoolBusinessLogics/BusinessLogics/ImplementerLogic.cs new file mode 100644 index 0000000..5d013dc --- /dev/null +++ b/School/SchoolBusinessLogics/BusinessLogics/ImplementerLogic.cs @@ -0,0 +1,106 @@ +using System.Text.RegularExpressions; +using SchoolContracts.BusinessLogicContracts; +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.ViewModels; +using Microsoft.Extensions.Logging; +using SchoolContracts.StoragesContracts; + +namespace SchoolBusinessLogics.BusinessLogics +{ + public class ImplementerLogic : IImplementerLogic + { + private readonly ILogger _logger; + private readonly IImplementerStorage _storage; + public ImplementerLogic(ILogger logger, IImplementerStorage implementerStorage) + { + _logger = logger; + _storage = implementerStorage; + } + + public bool Create(ImplementerBindingModel model) + { + try + { + CheckModel(model); + var result = _storage.Insert(model); + if (result == null) + { + throw new ArgumentNullException($"Результат создания клиента оказался нулевым"); + } + _logger.LogInformation("Была создана сущность: {@StudentViewModel}", result); + return true; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки создать элемент по модели: {@StudentBindingModel}", model); + throw; + } + } + + public ImplementerViewModel ReadElement(ImplementerSearchModel model) + { + try + { + var result = _storage.GetElement(model); + if (result == null) + { + throw new ArgumentNullException($"Результат получения элемента с айди {model.Id} оказался нулевым"); + } + _logger.LogInformation("Извлечение элемента {@StudentViewModel} c клиента по модели: {@StudentSearchModel}", result, model); + return result; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки получить элемент по модели: {@StudentSearchModel}", model); + throw; + } + } + + private void CheckModel(ImplementerBindingModel model, bool withParams = true) + { + const string txt = "Произошла ошибка на уровне проверки StudentBindingModel."; + if (model == null) + { + throw new ArgumentNullException(nameof(model), txt); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.Login)) + { + throw new ArgumentNullException(nameof(model.Login), txt + "Нет логина клиента"); + } + if (string.IsNullOrEmpty(model.Password)) + { + throw new ArgumentNullException(nameof(model.Password), txt + "Нет пароля клиента"); + } + if (model.Login.Length is < 5 or > 20) + { + throw new ArgumentException(nameof(model.Login), "Логин пользователя должен быть от 5 до 20 символом"); + } + + if (model.Password.Length < 5) + { + throw new ArgumentException(nameof(model.Password), + "Пароль пользователя должен быть не менее 5 символов"); + } + if (!Regex.IsMatch(model.Password, "[0-9]+")) + { + throw new ArgumentException(nameof(model.Password), + "Пароль пользователя должен содержать хотя бы одну цифру"); + } + _logger.LogDebug("{level} Проверка логина пользователя на уникальность {@Student}", txt, model); + var element = _storage.GetElement(new ImplementerSearchModel + { + Login = model.Login, + }); + if (element != null && element.Id != model.Id) + { + _logger.LogWarning("С логином: {login}, уже есть пользователь: {@ExistStudent}", model.Login, element); + throw new InvalidOperationException($"Клиент с таким логином \"{model.Login}\" уже есть"); + } + } + } +} diff --git a/School/SchoolBusinessLogics/BusinessLogics/ReportLogic.cs b/School/SchoolBusinessLogics/BusinessLogics/ReportLogic.cs new file mode 100644 index 0000000..badd5a1 --- /dev/null +++ b/School/SchoolBusinessLogics/BusinessLogics/ReportLogic.cs @@ -0,0 +1,119 @@ +using SchoolBusinessLogics.OfficePackage; +using SchoolContracts.BindingModels; +using SchoolContracts.BusinessLogicContracts; +using SchoolContracts.StoragesContracts; + +namespace SchoolBusinessLogics.BusinessLogics; + +public class ReportLogic : IReportLogic +{ + private readonly AbstractSaveToWord _saveToWord; + private readonly IDisciplineStorage _disciplineStorage; + private readonly IStudentStorage _studentStorage; + private readonly AbstractSaveToExcel _saveToExcel; + private readonly IAccountStorage _accountStorage; + private readonly AbstractSaveToPdf _saveToPdf; + + public ReportLogic(AbstractSaveToWord saveToWord, IDisciplineStorage disciplineStorage, AbstractSaveToExcel saveToExcel, + IAccountStorage accountStorage, AbstractSaveToPdf saveToPdf, IStudentStorage studentStorage) + { + _accountStorage = accountStorage; + _saveToExcel = saveToExcel; + _saveToWord = saveToWord; + _disciplineStorage = disciplineStorage; + _saveToPdf = saveToPdf; + _studentStorage = studentStorage; + } + + public void SaveDisciplinesToWord(ReportBindingModel option) + { + _saveToWord.CreateDoc(new() + { + FileName = option.FileName, + Stream = option.Stream, + Title = "Список дисциплин вместе с клиентами", + ReportObjects = _disciplineStorage.GetFilteredList(new() { ClientsIds = option.Ids?.ToList() }) + .Select(x => (object)x).ToList(), + }); + } + + public void SaveDisciplinesToExcel(ReportBindingModel option) + { + var ids = option.Ids?.ToList(); + _saveToExcel.CreateReportDisciplines(new() + { + FileName = option.FileName, + Stream = option.Stream, + Title = "Список дисциплин вместе с клиентами", + ReportObjects = _disciplineStorage.GetFilteredList(new() { StudentsIds = ids }) + .Select(x => (object)x).ToList(), + Headers = new() { "Дисциплина", "Дата создания", "Дата прохождения" } + }); + } + + public void SendAccountsToEmail(ReportDateRangeBindingModel option, string email) + { + var accounts = _accountStorage.GetFilteredList(new() + { + DateFrom = option.DateFrom, + DateTo = option.DateTo, + }); + option.Stream = new MemoryStream(); + _saveToPdf.CreateDocForAccounts(new() + { + DateFrom = option.DateFrom, + DateTo = option.DateTo, + Stream = option.Stream, + Title = "Данные по клиентом с накопительными счетами за период", + ReportObjects = accounts.Select(x => (object)x).ToList() + }); + + + } + + public void SaveClientsToWord(ReportBindingModel option) + { + _saveToWord.CreateDoc(new() + { + FileName = option.FileName, + Stream = option.Stream, + Title = "Список клиентов вместе с их дисциплинами", + ReportObjects = _clientStorage.GetFilteredList(new() { DisciplinesIds = option.Ids?.ToList() }) + .Select(x => (object)x).ToList(), + }); + } + + public void SaveClientsToExcel(ReportBindingModel option) + { + _saveToExcel.CreateReportClients(new() + { + FileName = option.FileName, + Stream = option.Stream, + + Title = "Список клиентов вместе с их дисциплинами", + ReportObjects = _clientStorage.GetFilteredList(new() { DisciplinesIds = option.Ids?.ToList() }) + .Select(x => (object)x).ToList(), + Headers = new() { "Клиент", "Дата", "Дисциплина", "Курс" } + }); + } + + public void SendRequirementsToEmail(ReportDateRangeBindingModel option, string email) + { + var dicscipline = _disciplineStorage.GetFilteredList(new() + { + DateFrom = option.DateFrom, + DateTo = option.DateTo, + }); + option.Stream = new MemoryStream(); + _saveToPdf.CreateDocForDisciplines(new() + { + DateFrom = option.DateFrom, + DateTo = option.DateTo, + Stream = option.Stream, + Title = "Данные по дисциплинам с требованиями за период", + ReportObjects = dicscipline.Select(x => (object)x).ToList() + }); + + + } +} \ No newline at end of file diff --git a/School/SchoolBusinessLogics/BusinessLogics/RequirementLogic.cs b/School/SchoolBusinessLogics/BusinessLogics/RequirementLogic.cs new file mode 100644 index 0000000..bdeaa5c --- /dev/null +++ b/School/SchoolBusinessLogics/BusinessLogics/RequirementLogic.cs @@ -0,0 +1,139 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.BusinessLogicContracts; +using SchoolContracts.SearchModels; +using SchoolContracts.StoragesContracts; +using SchoolContracts.ViewModels; +using Microsoft.Extensions.Logging; + +namespace SchoolBusinessLogics.BusinessLogics +{ + public class RequirementLogic : IRequirementLogic + { + private readonly ILogger _logger; + private readonly IRequirementStorage _requirementStorage; + + public RequirementLogic(ILogger logger, IRequirementStorage requirementStorage) + { + _logger = logger; + _requirementStorage = requirementStorage; + } + + public void CheckModel(RequirementBindingModel model, bool checkParams = true) + { + const string txt = "Произошла ошибка на уровне проверки RequirementBindingModel."; + if (model == null) + { + throw new ArgumentNullException(nameof(model), txt); + } + if (checkParams is false) + { + return; + } + + if (string.IsNullOrEmpty(model.NameOfRequirement)) + { + throw new ArgumentNullException(txt + $"Имя требованийы не должно быть нулевым или пустым. Полученное имя: \"{model.NameOfRequirement}\""); + } + + if (model.Price <= 0) + { + throw new ArgumentException(txt + $"Стоимость требованийы (Price={model.Price}) должна быть больше 0"); + } + } + + public List ReadList(RequirementSearchModel? model) + { + try + { + var results = model != null ? _requirementStorage.GetFilteredList(model) : _requirementStorage.GetFullList(); + _logger.LogDebug("Список полученных статей требований: {@requirements}", results); + _logger.LogInformation("Извлечение списка в количестве {Count} c требований по модели: {@RequirementSearchModel}", results.Count, model); + return results; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки получить список по модели: {@RequirementSearchModel}", model); + throw; + } + } + + public RequirementViewModel ReadElement(RequirementSearchModel model) + { + try + { + var result = _requirementStorage.GetElement(model); + if (result == null) + { + throw new ArgumentNullException($"Результат получения элемента с айди {model.Id} оказался нулевым"); + } + _logger.LogInformation("Извлечение элемента {@RequirementViewModel} c требований по модели: {@RequirementSearchModel}", result, model); + return result; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки получить элемент по модели: {@RequirementSearchModel}", model); + throw; + } + } + + public bool Create(RequirementBindingModel model) + { + try + { + CheckModel(model); + var result = _requirementStorage.Insert(model); + if (result == null) + { + throw new ArgumentNullException($"Результат создания требований оказался нулевым"); + } + _logger.LogInformation("Была создана сущность: {@RequirementViewModel}", result); + return true; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки создать элемент по модели: {@RequirementBindingModel}", model); + throw; + } + } + + public bool Update(RequirementBindingModel model) + { + try + { + CheckModel(model, false); + var result = _requirementStorage.Update(model); + if (result == null) + { + throw new ArgumentNullException($"Результат обновления требований оказался нулевым"); + } + _logger.LogInformation("Была обновлена сущность на: {@RequirementViewModel}", result); + return true; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки обновить элемент по модели: {@RequirementBindingModel}", model); + throw; + } + } + + public bool Delete(RequirementBindingModel model) + { + try + { + CheckModel(model, false); + var result = _requirementStorage.Delete(model); + if (result == null) + { + throw new ArgumentNullException($"Результат удаления требований оказался нулевым"); + } + _logger.LogInformation("Была удалена сущность: {@RequirementViewModel}", result); + return true; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки удалить элемент по модели: {@RequirementBindingModel}", model); + throw; + } + } + } +} diff --git a/School/SchoolBusinessLogics/BusinessLogics/StudentLogic.cs b/School/SchoolBusinessLogics/BusinessLogics/StudentLogic.cs new file mode 100644 index 0000000..d65ef5b --- /dev/null +++ b/School/SchoolBusinessLogics/BusinessLogics/StudentLogic.cs @@ -0,0 +1,147 @@ +using Microsoft.Extensions.Logging; +using SchoolContracts.BindingModels; +using SchoolContracts.BusinessLogicContracts; +using SchoolContracts.SearchModels; +using SchoolContracts.StoragesContracts; +using SchoolContracts.ViewModels; +using static System.Net.Mime.MediaTypeNames; + +namespace SchoolBusinessLogics.BusinessLogics +{ + public class StudentLogic : IStudentLogic + { + private readonly ILogger _logger; + private readonly IStudentStorage _studentStorage; + private const string ErrorString = "Произошла ошибка на уровне проверки StudentBindingModel."; + + public StudentLogic(ILogger logger, IStudentStorage studentStorage) + { + _logger = logger; + _studentStorage = studentStorage; + } + + private void CheckOnlyModel(StudentBindingModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model), ErrorString); + } + } + + private void CheckUpdateModel(StudentBindingModel model) + { + CheckOnlyModel(model); + + if (model.Course <= 0) + { + throw new ArgumentException(ErrorString + $"Курс (Course={model.Course}) должна быть больше 0"); + } + } + + public void CheckFullModel(StudentBindingModel model) + { + CheckOnlyModel(model); + CheckUpdateModel(model); + if (string.IsNullOrEmpty(model.Name)) + { + throw new ArgumentNullException(ErrorString + $"Имя клиента не должно быть нулевым или пустым. Полученное имя: \"{model.Name}\""); + } + } + + public List ReadList(StudentSearchModel? model) + { + try + { + var results = model != null ? _studentStorage.GetFilteredList(model) : _studentStorage.GetFullList(); + _logger.LogDebug("Список полученных клиентов: {@students}", results); + _logger.LogInformation("Извлечение списка в количестве {Count} c клиентов по модели: {@StudentSearchModel}", results.Count, model); + return results; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки получить список по модели: {@StudentSearchModel}", model); + throw; + } + } + + public StudentViewModel ReadElement(StudentSearchModel model) + { + try + { + var result = _studentStorage.GetElement(model); + if (result == null) + { + throw new ArgumentNullException($"Результат получения элемента с айди {model.Id} оказался нулевым"); + } + _logger.LogInformation("Извлечение элемента {@StudentViewModel} c клиентов по модели: {@StudentSearchModel}", result, model); + return result; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки получить элемент по модели: {@StudentSearchModel}", model); + throw; + } + } + + public bool Create(StudentBindingModel model) + { + try + { + CheckFullModel(model); + var result = _studentStorage.Insert(model); + if (result == null) + { + throw new ArgumentNullException($"Результат создания клиентов оказался нулевым"); + } + _logger.LogInformation("Была создана сущность: {@StudentViewModel}", result); + return true; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки создать элемент по модели: {@StudentBindingModel}", model); + throw; + } + } + + public bool Update(StudentBindingModel model) + { + try + { + CheckUpdateModel(model); + var result = _studentStorage.Update(model); + if (result == null) + { + throw new ArgumentNullException($"Результат обновления клиентов оказался нулевым"); + } + _logger.LogInformation("Была обновлена сущность на: {@StudentViewModel}", result); + return true; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки обновить элемент по модели: {@StudentBindingModel}", model); + throw; + } + } + + public bool Delete(StudentBindingModel model) + { + try + { + CheckOnlyModel(model); + var result = _studentStorage.Delete(model); + if (result == null) + { + throw new ArgumentNullException($"Результат удаления клиентов оказался нулевым"); + } + _logger.LogInformation("Была удалена сущность: {@StudentViewModel}", result); + return true; + } + catch (Exception e) + { + _logger.LogError(e, "Произошла ошибка при попытки удалить элемент по модели: {@StudentBindingModel}", model); + throw; + } + } + } +} + diff --git a/School/SchoolBusinessLogics/OfficePackage/AbstractSaveToExcel.cs b/School/SchoolBusinessLogics/OfficePackage/AbstractSaveToExcel.cs new file mode 100644 index 0000000..7c7cd73 --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/AbstractSaveToExcel.cs @@ -0,0 +1,164 @@ +using SchoolBusinessLogics.OfficePackage.HelperEnums; +using SchoolBusinessLogics.OfficePackage.HelperModels; +using SchoolContracts.ViewModels; + +namespace SchoolBusinessLogics.OfficePackage +{ + public abstract class AbstractSaveToExcel + { + private void CreateHeaders(ExcelInfo info) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = 1, + Text = info.Title, + StyleInfo = ExcelStyleInfoType.Title + }); + + MergeCells(new ExcelMergeParameters + { + CellFromName = "A1", + CellToName = "G1" + }); + + for (var i = 0; i < info.Headers.Count; i++) + { + InsertCellInWorksheet(new ExcelCellParameters() + { + ColumnName = ((char)('A' + i)).ToString(), + RowIndex = 2, + Text = info.Headers[i], + StyleInfo = ExcelStyleInfoType.Text + }); + } + } + + /// + /// Создание отчета + /// + /// + public void CreateReportDisciplines(ExcelInfo info) + { + CreateExcel(info); + CreateHeaders(info); + + uint rowIndex = 3; + foreach (var pc in info.ReportObjects) + { + var discipline = pc as DisciplineViewModel; + if (discipline == null) + { + throw new ArgumentException($"Передан некорректный тип в отчет: " + + $"ожидается DisciplineViewModel; Получен объект типа: {pc.GetType()}", nameof(info)); + } + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = discipline.Name, + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = discipline.DateOfReceipt.ToShortDateString(), + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = discipline.DateOfPassage.ToShortDateString(), + StyleInfo = ExcelStyleInfoType.Text + }); + + for (var i = 0; i < discipline.ClientViewModels.Count; i++) + { + var client = discipline.ClientViewModels[i]; + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = ((char)('D' + i)).ToString(), + RowIndex = rowIndex, + Text = $"{client.Name} на {discipline.ClientsModel[client.Id].DateOfClient.ToShortDateString()}", + StyleInfo = ExcelStyleInfoType.TextWithBroder + }); + } + rowIndex++; + } + SaveExcel(info); + } + + public void CreateReportClients(ExcelInfo info) + { + CreateExcel(info); + CreateHeaders(info); + + uint rowIndex = 3; + foreach (var pc in info.ReportObjects) + { + var student = pc as StudentViewModel; + if (student == null) + { + throw new ArgumentException($"Передан некорректный тип в отчет: " + + $"ожидается StudentViewModel; Получен объект типа: {pc.GetType()}", nameof(info)); + } + foreach (var discipline in student.Disciplines) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = student.Name, + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = discipline.StudentsModel[student.Id].DateOfStudent.ToShortDateString(), + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = discipline.Name, + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "D", + RowIndex = rowIndex, + Text = student.Course.ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + } + rowIndex++; + } + SaveExcel(info); + } + /// + /// Создание excel-файла + /// + /// + protected abstract void CreateExcel(ExcelInfo info); + + /// + /// Добавляем новую ячейку в лист + /// + protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams); + + /// + /// Объединение ячеек + /// + protected abstract void MergeCells(ExcelMergeParameters excelParams); + + /// + /// Сохранение файла + /// + /// + protected abstract void SaveExcel(ExcelInfo info); + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/AbstractSaveToPdf.cs b/School/SchoolBusinessLogics/OfficePackage/AbstractSaveToPdf.cs new file mode 100644 index 0000000..67e2e41 --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/AbstractSaveToPdf.cs @@ -0,0 +1,135 @@ +using SchoolBusinessLogics.OfficePackage.HelperEnums; +using SchoolBusinessLogics.OfficePackage.HelperModels; +using SchoolContracts.ViewModels; + +namespace SchoolBusinessLogics.OfficePackage +{ + public abstract class AbstractSaveToPdf + { + public void CreateDocForAccounts(PdfInfo info) + { + CreatePdf(info); + CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + CreateParagraph(new PdfParagraph { + Text = $"с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}", Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Center }); + + CreateTable(new List { "5cm", "6cm", "3cm", "3cm"}); + + CreateRow(new PdfRowParameters + { + Texts = new List { "Ученик", "Занятие", "Дата получения занятия", "Пополнение счета" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + var sumPaidPrice = 0.0; + foreach (var pc in info.ReportObjects) + { + if (pc is not AccountViewModel account) + { + throw new ArgumentException($"Передан некорректный тип в отчет: " + + $"ожидается Account; Получен объект типа: {pc.GetType()}", nameof(info)); + } + + if (account.Student == null || account.ClientByDiscipline == null) + { + throw new ArgumentNullException(nameof(account), $"Получена модель счета c нулевыми полями"); + } + sumPaidPrice += account.Price; + CreateRow(new PdfRowParameters + { + Texts = new List + { + account.Student.Name, + account.Discipline?.Name ?? string.Empty, + account.StudentByDiscipline.DateOfStudent.ToShortDateString(), + account.Price.ToString(), + }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + CreateParagraph(new PdfParagraph { Text = $"Итого оплачено : {sumPaidPrice}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Rigth }); + + SavePdf(info); + } + + public void CreateDocForDisciplines(PdfInfo info) + { + CreatePdf(info); + CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + CreateParagraph(new PdfParagraph + { + Text = $"с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}", + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + CreateTable(new List { "4cm", "5cm", "5cm", "3cm", }); + + CreateRow(new PdfRowParameters + { + Texts = new List { "Дата получения", "Занятие", "Требование", "Сумма требования" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + foreach (var pc in info.ReportObjects) + { + if (pc is not DisciplineViewModel discipline) + { + throw new ArgumentException($"Передан некорректный тип в отчет: " + + $"ожидается Discipline; Получен объект типа: {pc.GetType()}", nameof(info)); + } + + if (discipline.RequirementViewModels == null) + { + throw new ArgumentNullException($"Получена модель требований c нулевыми полями"); + } + foreach(var requirement in discipline.RequirementViewModels) + { + CreateRow(new PdfRowParameters + { + Texts = new List + { + discipline.DateOfPassage.ToShortDateString(), + discipline.Name, + requirement.NameOfRequirement, + requirement.Price.ToString(), + }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + } + SavePdf(info); + } + + /// + /// Создание doc-файла + /// + /// + protected abstract void CreatePdf(PdfInfo info); + + /// + /// Создание параграфа с текстом + /// + protected abstract void CreateParagraph(PdfParagraph paragraph); + + /// + /// Создание таблицы + /// + protected abstract void CreateTable(List columns); + + /// + /// Создание и заполнение строки + /// + /// + protected abstract void CreateRow(PdfRowParameters rowParameters); + + /// + /// Сохранение файла + /// + /// + protected abstract void SavePdf(PdfInfo info); + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/AbstractSaveToWord.cs b/School/SchoolBusinessLogics/OfficePackage/AbstractSaveToWord.cs new file mode 100644 index 0000000..dd3fcdc --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/AbstractSaveToWord.cs @@ -0,0 +1,59 @@ +using SchoolBusinessLogics.OfficePackage.HelperEnums; +using SchoolBusinessLogics.OfficePackage.HelperModels; + +namespace SchoolBusinessLogics.OfficePackage +{ + public abstract class AbstractSaveToWord + { + public void CreateDoc(WordInfo info) + { + CreateWord(info); + + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + + foreach (var text in info.ReportObjects.SelectMany(reportObject => reportObject.ToString()?.Split("\n") ?? new string[]{})) + { + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> + { + (text, new WordTextProperties { Size = "24" }) + }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Both + } + }); + } + SaveWord(info); + } + + /// + /// Создание doc-файла + /// + /// + protected abstract void CreateWord(WordInfo info); + + /// + /// Создание абзаца с текстом + /// + /// + /// + protected abstract void CreateParagraph(WordParagraph paragraph); + + /// + /// Сохранение файла + /// + /// + protected abstract void SaveWord(WordInfo info); + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/HelperEnums/ExcelStyleInfoType.cs b/School/SchoolBusinessLogics/OfficePackage/HelperEnums/ExcelStyleInfoType.cs new file mode 100644 index 0000000..d7711d5 --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/HelperEnums/ExcelStyleInfoType.cs @@ -0,0 +1,9 @@ +namespace SchoolBusinessLogics.OfficePackage.HelperEnums +{ + public enum ExcelStyleInfoType + { + Title, + Text, + TextWithBroder + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs b/School/SchoolBusinessLogics/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs new file mode 100644 index 0000000..21f5737 --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs @@ -0,0 +1,9 @@ +namespace SchoolBusinessLogics.OfficePackage.HelperEnums +{ + public enum PdfParagraphAlignmentType + { + Center, + Left, + Rigth + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/HelperEnums/WordJustificationType.cs b/School/SchoolBusinessLogics/OfficePackage/HelperEnums/WordJustificationType.cs new file mode 100644 index 0000000..02a49de --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/HelperEnums/WordJustificationType.cs @@ -0,0 +1,8 @@ +namespace SchoolBusinessLogics.OfficePackage.HelperEnums +{ + public enum WordJustificationType + { + Center, + Both + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/HelperModels/ExcelCellParameters.cs b/School/SchoolBusinessLogics/OfficePackage/HelperModels/ExcelCellParameters.cs new file mode 100644 index 0000000..d917a96 --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/HelperModels/ExcelCellParameters.cs @@ -0,0 +1,13 @@ +using SchoolBusinessLogics.OfficePackage.HelperEnums; + +namespace SchoolBusinessLogics.OfficePackage.HelperModels +{ + public class ExcelCellParameters + { + public string ColumnName { get; set; } = string.Empty; + public uint RowIndex { get; set; } + public string Text { get; set; } = string.Empty; + public string CellReference => $"{ColumnName}{RowIndex}"; + public ExcelStyleInfoType StyleInfo { get; set; } + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/HelperModels/ExcelInfo.cs b/School/SchoolBusinessLogics/OfficePackage/HelperModels/ExcelInfo.cs new file mode 100644 index 0000000..593e726 --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/HelperModels/ExcelInfo.cs @@ -0,0 +1,18 @@ +namespace SchoolBusinessLogics.OfficePackage.HelperModels +{ + public class ExcelInfo + { + public string? FileName { get; set; } + + public Stream? Stream { get; set; } + + public string Title { get; set; } = string.Empty; + public List ReportObjects + { + get; + set; + } = new(); + + public List Headers { get; set; } = new(); + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/HelperModels/ExcelMergeParameters.cs b/School/SchoolBusinessLogics/OfficePackage/HelperModels/ExcelMergeParameters.cs new file mode 100644 index 0000000..ed8aab4 --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/HelperModels/ExcelMergeParameters.cs @@ -0,0 +1,9 @@ +namespace SchoolBusinessLogics.OfficePackage.HelperModels +{ + public class ExcelMergeParameters + { + public string CellFromName { get; set; } = string.Empty; + public string CellToName { get; set; } = string.Empty; + public string Merge => $"{CellFromName}:{CellToName}"; + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/HelperModels/PdfInfo.cs b/School/SchoolBusinessLogics/OfficePackage/HelperModels/PdfInfo.cs new file mode 100644 index 0000000..c9321d9 --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/HelperModels/PdfInfo.cs @@ -0,0 +1,13 @@ +namespace SchoolBusinessLogics.OfficePackage.HelperModels +{ + public class PdfInfo + { + public string? FileName { get; set; } + public Stream? Stream { get; set; } + + public string Title { get; set; } = string.Empty; + public DateOnly DateFrom { get; set; } + public DateOnly DateTo { get; set; } + public List ReportObjects { get; set; } = new(); + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/HelperModels/PdfParagraph.cs b/School/SchoolBusinessLogics/OfficePackage/HelperModels/PdfParagraph.cs new file mode 100644 index 0000000..d4df81c --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/HelperModels/PdfParagraph.cs @@ -0,0 +1,11 @@ +using UniversityBusinessLogics.OfficePackage.HelperEnums; + +namespace UniversityBusinessLogics.OfficePackage.HelperModels +{ + public class PdfParagraph + { + public string Text { get; set; } = string.Empty; + public string Style { get; set; } = string.Empty; + public PdfParagraphAlignmentType ParagraphAlignment { get; set; } + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/HelperModels/PdfRowParameters.cs b/School/SchoolBusinessLogics/OfficePackage/HelperModels/PdfRowParameters.cs new file mode 100644 index 0000000..23deb3f --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/HelperModels/PdfRowParameters.cs @@ -0,0 +1,11 @@ +using SchoolBusinessLogics.OfficePackage.HelperEnums; + +namespace UniversityBusinessLogics.OfficePackage.HelperModels +{ + public class PdfRowParameters + { + public List Texts { get; set; } = new(); + public string Style { get; set; } = string.Empty; + public PdfParagraphAlignmentType ParagraphAlignment { get; set; } + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/HelperModels/WordInfo.cs b/School/SchoolBusinessLogics/OfficePackage/HelperModels/WordInfo.cs new file mode 100644 index 0000000..c7405f9 --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/HelperModels/WordInfo.cs @@ -0,0 +1,11 @@ +namespace SchoolBusinessLogics.OfficePackage.HelperModels +{ + public class WordInfo + { + public string? FileName { get; set; } + public Stream? Stream { get; set; } + + public string Title { get; set; } = string.Empty; + public List ReportObjects { get; set; } = new(); + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/HelperModels/WordParagraph.cs b/School/SchoolBusinessLogics/OfficePackage/HelperModels/WordParagraph.cs new file mode 100644 index 0000000..48725c0 --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/HelperModels/WordParagraph.cs @@ -0,0 +1,8 @@ +namespace SchoolBusinessLogics.OfficePackage.HelperModels +{ + public class WordParagraph + { + public List<(string, WordTextProperties)> Texts { get; set; } = new(); + public WordTextProperties? TextProperties { get; set; } + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/HelperModels/WordTextProperties.cs b/School/SchoolBusinessLogics/OfficePackage/HelperModels/WordTextProperties.cs new file mode 100644 index 0000000..f4932aa --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/HelperModels/WordTextProperties.cs @@ -0,0 +1,11 @@ +using SchoolBusinessLogics.OfficePackage.HelperEnums; + +namespace SchoolBusinessLogics.OfficePackage.HelperModels +{ + public class WordTextProperties + { + public string Size { get; set; } = string.Empty; + public bool Bold { get; set; } + public WordJustificationType JustificationType { get; set; } + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/Implements/SaveToExcel.cs b/School/SchoolBusinessLogics/OfficePackage/Implements/SaveToExcel.cs new file mode 100644 index 0000000..6d210d1 --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/Implements/SaveToExcel.cs @@ -0,0 +1,304 @@ +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Office2010.Excel; +using DocumentFormat.OpenXml.Office2013.Excel; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using SchoolBusinessLogics.OfficePackage.HelperEnums; +using SchoolBusinessLogics.OfficePackage.HelperModels; + +namespace SchoolBusinessLogics.OfficePackage.Implements +{ + public class SaveToExcel : AbstractSaveToExcel + { + private SpreadsheetDocument? _spreadsheetDocument; + + private SharedStringTablePart? _shareStringPart; + + private Worksheet? _worksheet; + + /// + /// Настройка стилей для файла + /// + /// + private static void CreateStyles(WorkbookPart workbookpart) + { + var sp = workbookpart.AddNewPart(); + sp.Stylesheet = new Stylesheet(); + + var fonts = new Fonts() { Count = 2U, KnownFonts = true }; + + var fontUsual = new Font(); + fontUsual.Append(new FontSize() { Val = 12D }); + fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U }); + fontUsual.Append(new FontName() { Val = "Times New Roman" }); + fontUsual.Append(new FontFamilyNumbering() { Val = 2 }); + fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor }); + + var fontTitle = new Font(); + fontTitle.Append(new Bold()); + fontTitle.Append(new FontSize() { Val = 14D }); + fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U }); + fontTitle.Append(new FontName() { Val = "Times New Roman" }); + fontTitle.Append(new FontFamilyNumbering() { Val = 2 }); + fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor }); + + fonts.Append(fontUsual); + fonts.Append(fontTitle); + + var fills = new Fills() { Count = 2U }; + + var fill1 = new Fill(); + fill1.Append(new PatternFill() { PatternType = PatternValues.None }); + + var fill2 = new Fill(); + fill2.Append(new PatternFill() { PatternType = PatternValues.Gray125 }); + + fills.Append(fill1); + fills.Append(fill2); + + var borders = new Borders() { Count = 2U }; + + var borderNoBorder = new Border(); + borderNoBorder.Append(new LeftBorder()); + borderNoBorder.Append(new RightBorder()); + borderNoBorder.Append(new TopBorder()); + borderNoBorder.Append(new BottomBorder()); + borderNoBorder.Append(new DiagonalBorder()); + + var borderThin = new Border(); + + var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin }; + leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); + + var rightBorder = new RightBorder() { Style = BorderStyleValues.Thin }; + rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); + + var topBorder = new TopBorder() { Style = BorderStyleValues.Thin }; + topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); + + var bottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin }; + bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); + + borderThin.Append(leftBorder); + borderThin.Append(rightBorder); + borderThin.Append(topBorder); + borderThin.Append(bottomBorder); + borderThin.Append(new DiagonalBorder()); + + borders.Append(borderNoBorder); + borders.Append(borderThin); + + var cellStyleFormats = new CellStyleFormats() { Count = 1U }; + var cellFormatStyle = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U }; + + cellStyleFormats.Append(cellFormatStyle); + + var cellFormats = new CellFormats() { Count = 3U }; + var cellFormatFont = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U, FormatId = 0U, ApplyFont = true }; + var cellFormatFontAndBorder = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 1U, FormatId = 0U, ApplyFont = true, ApplyBorder = true }; + var cellFormatTitle = new CellFormat() { NumberFormatId = 0U, FontId = 1U, FillId = 0U, BorderId = 0U, FormatId = 0U, Alignment = new Alignment() { Vertical = VerticalAlignmentValues.Center, WrapText = true, Horizontal = HorizontalAlignmentValues.Center }, ApplyFont = true }; + + cellFormats.Append(cellFormatFont); + cellFormats.Append(cellFormatFontAndBorder); + cellFormats.Append(cellFormatTitle); + + var cellStyles = new CellStyles() { Count = 1U }; + + cellStyles.Append(new CellStyle() { Name = "Normal", FormatId = 0U, BuiltinId = 0U }); + + var differentialFormats = new DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats() { Count = 0U }; + + var tableStyles = new TableStyles() { Count = 0U, DefaultTableStyle = "TableStyleMedium2", DefaultPivotStyle = "PivotStyleLight16" }; + + var stylesheetExtensionList = new StylesheetExtensionList(); + + var stylesheetExtension1 = new StylesheetExtension() { Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" }; + stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"); + stylesheetExtension1.Append(new SlicerStyles() { DefaultSlicerStyle = "SlicerStyleLight1" }); + + var stylesheetExtension2 = new StylesheetExtension() { Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}" }; + stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"); + stylesheetExtension2.Append(new TimelineStyles() { DefaultTimelineStyle = "TimeSlicerStyleLight1" }); + + stylesheetExtensionList.Append(stylesheetExtension1); + stylesheetExtensionList.Append(stylesheetExtension2); + + sp.Stylesheet.Append(fonts); + sp.Stylesheet.Append(fills); + sp.Stylesheet.Append(borders); + sp.Stylesheet.Append(cellStyleFormats); + sp.Stylesheet.Append(cellFormats); + sp.Stylesheet.Append(cellStyles); + sp.Stylesheet.Append(differentialFormats); + sp.Stylesheet.Append(tableStyles); + sp.Stylesheet.Append(stylesheetExtensionList); + } + + /// + /// Получение номера стиля из типа + /// + /// + /// + private static uint GetStyleValue(ExcelStyleInfoType styleInfo) + { + return styleInfo switch + { + ExcelStyleInfoType.Title => 2U, + ExcelStyleInfoType.TextWithBroder => 1U, + ExcelStyleInfoType.Text => 0U, + _ => 0U, + }; + } + + protected override void CreateExcel(ExcelInfo info) + { + if (info.Stream != null) + { + _spreadsheetDocument = SpreadsheetDocument.Create(info.Stream, SpreadsheetDocumentType.Workbook); + } + else if (info.FileName != null) + { + _spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook); + } + else + { + throw new ArgumentException("Книга не может быть создана поскольку не было указано ни имя файла, ни поток, куда файл сохранится", nameof(info)); + + } + // Создаем книгу (в ней хранятся листы) + var workbookpart = _spreadsheetDocument.AddWorkbookPart(); + workbookpart.Workbook = new Workbook(); + + CreateStyles(workbookpart); + + // Получаем/создаем хранилище текстов для книги + _shareStringPart = _spreadsheetDocument.WorkbookPart!.GetPartsOfType().Any() + ? _spreadsheetDocument.WorkbookPart.GetPartsOfType().First() + : _spreadsheetDocument.WorkbookPart.AddNewPart(); + + // Создаем SharedStringTable, если его нет + if (_shareStringPart.SharedStringTable == null) + { + _shareStringPart.SharedStringTable = new SharedStringTable(); + } + + // Создаем лист в книгу + var worksheetPart = workbookpart.AddNewPart(); + worksheetPart.Worksheet = new Worksheet(new SheetData()); + + // Добавляем лист в книгу + var sheets = _spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets()); + var sheet = new Sheet() + { + Id = _spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), + SheetId = 1, + Name = "Лист" + }; + sheets.Append(sheet); + + _worksheet = worksheetPart.Worksheet; + } + + protected override void InsertCellInWorksheet(ExcelCellParameters excelParams) + { + if (_worksheet == null || _shareStringPart == null) + { + return; + } + var sheetData = _worksheet.GetFirstChild(); + if (sheetData == null) + { + return; + } + + // Ищем строку, либо добавляем ее + Row row; + if (sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).Any()) + { + row = sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).First(); + } + else + { + row = new Row() { RowIndex = excelParams.RowIndex }; + sheetData.Append(row); + } + + // Ищем нужную ячейку + Cell cell; + if (row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).Any()) + { + cell = row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).First(); + } + else + { + // Все ячейки должны быть последовательно друг за другом расположены + // нужно определить, после какой вставлять + Cell? refCell = null; + foreach (Cell rowCell in row.Elements()) + { + if (string.Compare(rowCell.CellReference!.Value, excelParams.CellReference, true) > 0) + { + refCell = rowCell; + break; + } + } + + var newCell = new Cell() { CellReference = excelParams.CellReference }; + row.InsertBefore(newCell, refCell); + + cell = newCell; + } + + // вставляем новый текст + _shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(excelParams.Text))); + _shareStringPart.SharedStringTable.Save(); + + cell.CellValue = new CellValue((_shareStringPart.SharedStringTable.Elements().Count() - 1).ToString()); + cell.DataType = new EnumValue(CellValues.SharedString); + cell.StyleIndex = GetStyleValue(excelParams.StyleInfo); + } + + protected override void MergeCells(ExcelMergeParameters excelParams) + { + if (_worksheet == null) + { + return; + } + MergeCells mergeCells; + + if (_worksheet.Elements().Any()) + { + mergeCells = _worksheet.Elements().First(); + } + else + { + mergeCells = new MergeCells(); + + if (_worksheet.Elements().Any()) + { + _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); + } + else + { + _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); + } + } + + var mergeCell = new MergeCell() + { + Reference = new StringValue(excelParams.Merge) + }; + mergeCells.Append(mergeCell); + } + + protected override void SaveExcel(ExcelInfo info) + { + if (_spreadsheetDocument == null) + { + return; + } + _spreadsheetDocument.WorkbookPart!.Workbook.Save(); + _spreadsheetDocument.Close(); + } + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/Implements/SaveToPdf.cs b/School/SchoolBusinessLogics/OfficePackage/Implements/SaveToPdf.cs new file mode 100644 index 0000000..e183e9d --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/Implements/SaveToPdf.cs @@ -0,0 +1,129 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml; +using SchoolBusinessLogics.OfficePackage.HelperEnums; +using SchoolBusinessLogics.OfficePackage.HelperModels; +using MigraDoc.DocumentObjectModel; +using MigraDoc.DocumentObjectModel.Tables; +using MigraDoc.Rendering; + +namespace SchoolBusinessLogics.OfficePackage.Implements +{ + public class SaveToPdf : AbstractSaveToPdf + { + private Document? _document; + + private Section? _section; + + private Table? _table; + + private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type) + { + return type switch + { + PdfParagraphAlignmentType.Center => ParagraphAlignment.Center, + PdfParagraphAlignmentType.Left => ParagraphAlignment.Left, + PdfParagraphAlignmentType.Rigth => ParagraphAlignment.Right, + _ => ParagraphAlignment.Justify, + }; + } + + /// + /// Создание стилей для документа + /// + /// + private static void DefineStyles(Document document) + { + var style = document.Styles["Normal"]; + style.Font.Name = "Times New Roman"; + style.Font.Size = 14; + + style = document.Styles.AddStyle("NormalTitle", "Normal"); + style.Font.Bold = true; + } + + protected override void CreatePdf(PdfInfo info) + { + _document = new Document(); + DefineStyles(_document); + + _section = _document.AddSection(); + } + + protected override void CreateParagraph(PdfParagraph pdfParagraph) + { + if (_section == null) + { + return; + } + var paragraph = _section.AddParagraph(pdfParagraph.Text); + paragraph.Format.SpaceAfter = "1cm"; + paragraph.Format.Alignment = GetParagraphAlignment(pdfParagraph.ParagraphAlignment); + paragraph.Style = pdfParagraph.Style; + } + + protected override void CreateTable(List columns) + { + if (_document == null) + { + return; + } + _table = _document.LastSection.AddTable(); + + foreach (var elem in columns) + { + _table.AddColumn(elem); + } + } + + protected override void CreateRow(PdfRowParameters rowParameters) + { + if (_table == null) + { + return; + } + var row = _table.AddRow(); + for (int i = 0; i < rowParameters.Texts.Count; ++i) + { + row.Cells[i].AddParagraph(rowParameters.Texts[i]); + + if (!string.IsNullOrEmpty(rowParameters.Style)) + { + row.Cells[i].Style = rowParameters.Style; + } + + Unit borderWidth = 0.5; + + row.Cells[i].Borders.Left.Width = borderWidth; + row.Cells[i].Borders.Right.Width = borderWidth; + row.Cells[i].Borders.Top.Width = borderWidth; + row.Cells[i].Borders.Bottom.Width = borderWidth; + + row.Cells[i].Format.Alignment = GetParagraphAlignment(rowParameters.ParagraphAlignment); + row.Cells[i].VerticalAlignment = VerticalAlignment.Center; + } + } + + protected override void SavePdf(PdfInfo info) + { + System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); + var renderer = new PdfDocumentRenderer(true) + { + Document = _document + }; + renderer.RenderDocument(); + if (info.Stream != null) + { + renderer.PdfDocument.Save(info.Stream); + } + else if (info.FileName != null) + { + renderer.PdfDocument.Save(info.FileName); + } + else + { + throw new ArgumentException("Книга не может быть создана поскольку не было указано ни имя файла, ни поток, куда файл сохранится", nameof(info)); + + } + } + } +} diff --git a/School/SchoolBusinessLogics/OfficePackage/Implements/SaveToWord.cs b/School/SchoolBusinessLogics/OfficePackage/Implements/SaveToWord.cs new file mode 100644 index 0000000..965285a --- /dev/null +++ b/School/SchoolBusinessLogics/OfficePackage/Implements/SaveToWord.cs @@ -0,0 +1,145 @@ +using SchoolBusinessLogics.OfficePackage.HelperEnums; +using SchoolBusinessLogics.OfficePackage.HelperModels; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; + +namespace SchoolBusinessLogics.OfficePackage.Implements; + +public class SaveToWord : AbstractSaveToWord +{ + private WordprocessingDocument? _wordDocument; + + private Body? _docBody; + + /// + /// Получение типа выравнивания + /// + /// + /// + private static JustificationValues GetJustificationValues(WordJustificationType type) + { + return type switch + { + WordJustificationType.Both => JustificationValues.Both, + WordJustificationType.Center => JustificationValues.Center, + _ => JustificationValues.Left, + }; + } + + /// + /// Настройки страницы + /// + /// + private static SectionProperties CreateSectionProperties() + { + var properties = new SectionProperties(); + + var pageSize = new PageSize + { + Orient = PageOrientationValues.Portrait + }; + + properties.AppendChild(pageSize); + + return properties; + } + + /// + /// Задание форматирования для абзаца + /// + /// + /// + private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties) + { + if (paragraphProperties == null) + { + return null; + } + + var properties = new ParagraphProperties(); + + properties.AppendChild(new Justification() + { + Val = GetJustificationValues(paragraphProperties.JustificationType) + }); + + properties.AppendChild(new SpacingBetweenLines + { + LineRule = LineSpacingRuleValues.Auto + }); + + properties.AppendChild(new Indentation()); + + var paragraphMarkRunProperties = new ParagraphMarkRunProperties(); + if (!string.IsNullOrEmpty(paragraphProperties.Size)) + { + paragraphMarkRunProperties.AppendChild(new FontSize { Val = paragraphProperties.Size }); + } + properties.AppendChild(paragraphMarkRunProperties); + + return properties; + } + + protected override void CreateWord(WordInfo info) + { + if (info.FileName != null) + { + _wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document); + } + else if (info.Stream != null) + { + _wordDocument = WordprocessingDocument.Create(info.Stream, WordprocessingDocumentType.Document); + } + else + { + throw new ArgumentException("Документ не может быть создан поскольку не был указан ни имя файла, ни поток, куда файл сохранится", nameof(info)); + } + MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart(); + mainPart.Document = new Document(); + _docBody = mainPart.Document.AppendChild(new Body()); + } + + protected override void CreateParagraph(WordParagraph paragraph) + { + if (_docBody == null || paragraph == null) + { + return; + } + var docParagraph = new Paragraph(); + + docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties)); + + foreach (var run in paragraph.Texts) + { + var docRun = new Run(); + + var properties = new RunProperties(); + properties.AppendChild(new FontSize { Val = run.Item2.Size }); + if (run.Item2.Bold) + { + properties.AppendChild(new Bold()); + } + docRun.AppendChild(properties); + + docRun.AppendChild(new Text { Text = run.Item1, Space = SpaceProcessingModeValues.Preserve }); + + docParagraph.AppendChild(docRun); + } + + _docBody.AppendChild(docParagraph); + } + + protected override void SaveWord(WordInfo info) + { + if (_docBody == null || _wordDocument == null) + { + return; + } + _docBody.AppendChild(CreateSectionProperties()); + + _wordDocument.MainDocumentPart!.Document.Save(); + + _wordDocument.Close(); + } +} diff --git a/School/SchoolBusinessLogics/SchoolBusinessLogics.csproj b/School/SchoolBusinessLogics/SchoolBusinessLogics.csproj new file mode 100644 index 0000000..d6a74bb --- /dev/null +++ b/School/SchoolBusinessLogics/SchoolBusinessLogics.csproj @@ -0,0 +1,21 @@ + + + + WinExe + net6.0-windows + enable + true + enable + + + + + + + + + + + + + \ No newline at end of file diff --git a/School/SchoolContracts/BindingModels/AccountBindingModel.cs b/School/SchoolContracts/BindingModels/AccountBindingModel.cs new file mode 100644 index 0000000..8d2ca4d --- /dev/null +++ b/School/SchoolContracts/BindingModels/AccountBindingModel.cs @@ -0,0 +1,15 @@ +using SchoolDataModels; + +namespace SchoolContracts.BindingModels +{ + public class AccountBindingModel : IAccountModel + { + public int StudentByDisciplineId { get; set; } + + public DateOnly DateOfAccount { get; set; } = DateOnly.FromDateTime(DateTime.Now); + + public double Price { get; set; } + + public int Id { get; set; } + } +} diff --git a/School/SchoolContracts/BindingModels/DisciplineBindingModel.cs b/School/SchoolContracts/BindingModels/DisciplineBindingModel.cs new file mode 100644 index 0000000..1f5929c --- /dev/null +++ b/School/SchoolContracts/BindingModels/DisciplineBindingModel.cs @@ -0,0 +1,21 @@ +using System.ComponentModel; +using SchoolDataModels; +using SchoolDataModels.Models; + +namespace SchoolContracts.BindingModels +{ + public class DisciplineBindingModel : IDisciplineModel + { + public int ImplementerId { get; set; } + public string Name { get; set; } = string.Empty; + public double Price { get; set; } + + public DateOnly DateOfReceipt { get; set; } = DateOnly.FromDateTime(DateTime.Now); + public DateOnly DateOfPassage { get; set; } = DateOnly.FromDateTime(DateTime.Now); + + public Dictionary StudentsModel { get; set; } = new(); + public List RequirementsModel { get; set; } = new(); + + public int Id { get; set; } + } +} diff --git a/School/SchoolContracts/BindingModels/ExecutorBindingModel.cs b/School/SchoolContracts/BindingModels/ExecutorBindingModel.cs new file mode 100644 index 0000000..7040229 --- /dev/null +++ b/School/SchoolContracts/BindingModels/ExecutorBindingModel.cs @@ -0,0 +1,17 @@ +using SchoolDataModels; + +namespace SchoolContracts.BindingModels +{ + public class ExecutorBindingModel : IExecutorModel + { + public string FirstName { get; set; } = string.Empty; + + public string LastName { get; set; } = string.Empty; + + public string Login { get; set; } = string.Empty; + + public string Password { get; set; } = string.Empty; + public string PhoneNumber { get; set; } = string.Empty; + public int Id { get; set; } + } +} diff --git a/School/SchoolContracts/BindingModels/ImplementerBindingModel.cs b/School/SchoolContracts/BindingModels/ImplementerBindingModel.cs new file mode 100644 index 0000000..08e500c --- /dev/null +++ b/School/SchoolContracts/BindingModels/ImplementerBindingModel.cs @@ -0,0 +1,14 @@ +using SchoolDataModels; + +namespace SchoolContracts.BindingModels +{ + public class ImplementerBindingModel : IImplementerModel + { + public int Id { get; set; } + public string FirstName { get; set; } = string.Empty; + public string LastName { get; set; } = string.Empty; + public string Login { get; set; } = string.Empty; + public string Password { get; set; } = string.Empty; + public string PhoneNumber { get; set; } = string.Empty; + } +} diff --git a/School/SchoolContracts/BindingModels/ReportBindingModel.cs b/School/SchoolContracts/BindingModels/ReportBindingModel.cs new file mode 100644 index 0000000..3d7954f --- /dev/null +++ b/School/SchoolContracts/BindingModels/ReportBindingModel.cs @@ -0,0 +1,8 @@ +namespace SchoolContracts.BindingModels; + +public class ReportBindingModel +{ + public string? FileName { get; set; } + public Stream? Stream { get; set; } + public int[]? Ids { get; set; } +} \ No newline at end of file diff --git a/School/SchoolContracts/BindingModels/ReportDateRangeBindingModel.cs b/School/SchoolContracts/BindingModels/ReportDateRangeBindingModel.cs new file mode 100644 index 0000000..ea9c448 --- /dev/null +++ b/School/SchoolContracts/BindingModels/ReportDateRangeBindingModel.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SchoolContracts.BindingModels +{ + public class ReportDateRangeBindingModel + { + public string? FileName { get; set; } + public Stream? Stream { get; set; } + + public DateOnly DateFrom { get; set; } + public DateOnly DateTo { get; set; } + } +} diff --git a/School/SchoolContracts/BindingModels/RequirementBindingModel.cs b/School/SchoolContracts/BindingModels/RequirementBindingModel.cs new file mode 100644 index 0000000..dc5febf --- /dev/null +++ b/School/SchoolContracts/BindingModels/RequirementBindingModel.cs @@ -0,0 +1,17 @@ +using SchoolDataModels; +using SchoolDataModels.Models; + +namespace SchoolContracts.BindingModels +{ + public class RequirementBindingModel : IRequirementModel + { + public int ExecutorId { get; set; } + + public string NameOfRequirement { get; set; } = string.Empty; + + public double Price { get; set; } + public Dictionary DisciplinesModels { get; set; } = new(); + + public int Id { get; set; } + } +} diff --git a/School/SchoolContracts/BindingModels/StudentBindingModel.cs b/School/SchoolContracts/BindingModels/StudentBindingModel.cs new file mode 100644 index 0000000..58ebe34 --- /dev/null +++ b/School/SchoolContracts/BindingModels/StudentBindingModel.cs @@ -0,0 +1,17 @@ +using SchoolDataModels; + +namespace SchoolContracts.BindingModels +{ + public class StudentBindingModel : IStudentModel + { + public int DirectorId { get; set; } + + public string Name { get; set; } = string.Empty; + + public double Price { get; set; } + + public int Course { get; set; } + + public int Id { get; set; } + } +} diff --git a/School/SchoolContracts/BusinessLogicContracts/IAccountLogic.cs b/School/SchoolContracts/BusinessLogicContracts/IAccountLogic.cs new file mode 100644 index 0000000..5ff2603 --- /dev/null +++ b/School/SchoolContracts/BusinessLogicContracts/IAccountLogic.cs @@ -0,0 +1,14 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.ViewModels; + +namespace SchoolContracts.BusinessLogicContracts +{ + public interface IAccountLogic + { + List ReadList(AccountSearchModel model); + AccountViewModel ReadElement(AccountSearchModel model); + bool Create(AccountBindingModel model); + bool GetAccountInfo(AccountSearchModel model, out double fullPrice, out double paidPrice); + } +} diff --git a/School/SchoolContracts/BusinessLogicContracts/IDisciplineLogic.cs b/School/SchoolContracts/BusinessLogicContracts/IDisciplineLogic.cs new file mode 100644 index 0000000..ab3c739 --- /dev/null +++ b/School/SchoolContracts/BusinessLogicContracts/IDisciplineLogic.cs @@ -0,0 +1,16 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.ViewModels; + + +namespace SchoolContracts.BusinessLogicContracts +{ + public interface IDisciplineLogic + { + List ReadList(DisciplineSearchModel? model = null); + DisciplineViewModel ReadElement(DisciplineSearchModel model); + bool Create(DisciplineBindingModel model); + bool Update(DisciplineBindingModel model); + bool Delete(DisciplineBindingModel model); + } +} diff --git a/School/SchoolContracts/BusinessLogicContracts/IExecutorLogic.cs b/School/SchoolContracts/BusinessLogicContracts/IExecutorLogic.cs new file mode 100644 index 0000000..8c1fc3d --- /dev/null +++ b/School/SchoolContracts/BusinessLogicContracts/IExecutorLogic.cs @@ -0,0 +1,12 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.ViewModels; + +namespace SchoolContracts.BusinessLogicContracts +{ + public interface IExecutorLogic + { + ExecutorViewModel ReadElement(ExecutorSearchModel model); + bool Create(ExecutorrBindingModel model); + } +} diff --git a/School/SchoolContracts/BusinessLogicContracts/IImplementerLogic.cs b/School/SchoolContracts/BusinessLogicContracts/IImplementerLogic.cs new file mode 100644 index 0000000..7f2f352 --- /dev/null +++ b/School/SchoolContracts/BusinessLogicContracts/IImplementerLogic.cs @@ -0,0 +1,12 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.ViewModels; + +namespace SchoolContracts.BusinessLogicContracts +{ + public interface IImplementerLogic + { + ImplementerViewModel ReadElement(ImplementerSearchModel model); + bool Create(ImplementerBindingModel model); + } +} \ No newline at end of file diff --git a/School/SchoolContracts/BusinessLogicContracts/IReportLogic.cs b/School/SchoolContracts/BusinessLogicContracts/IReportLogic.cs new file mode 100644 index 0000000..d77fc20 --- /dev/null +++ b/School/SchoolContracts/BusinessLogicContracts/IReportLogic.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SchoolContracts.BindingModels; + +namespace SchoolContracts.BusinessLogicContracts +{ + public interface IReportLogic + { + void SaveDisciplinesToWord(ReportBindingModel option); + + void SaveDisciplinesToExcel(ReportBindingModel option); + + void SendAccountsToEmail(ReportDateRangeBindingModel option, string email); + void SaveStudentsToWord(ReportBindingModel option); + + void SaveStudentsToExcel(ReportBindingModel option); + + void SendRequirementsToEmail(ReportDateRangeBindingModel option, string email); + } +} diff --git a/School/SchoolContracts/BusinessLogicContracts/IRequirementLogic.cs b/School/SchoolContracts/BusinessLogicContracts/IRequirementLogic.cs new file mode 100644 index 0000000..259edcd --- /dev/null +++ b/School/SchoolContracts/BusinessLogicContracts/IRequirementLogic.cs @@ -0,0 +1,15 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.ViewModels; + +namespace SchoolContracts.BusinessLogicContracts +{ + public interface IRequirementLogic + { + List ReadList(RequirementSearchModel? model = null); + RequirementViewModel ReadElement(RequirementSearchModel model); + bool Create(RequirementBindingModel model); + bool Update(RequirementBindingModel model); + bool Delete(RequirementBindingModel model); + } +} diff --git a/School/SchoolContracts/BusinessLogicContracts/IStudentLogic.cs b/School/SchoolContracts/BusinessLogicContracts/IStudentLogic.cs new file mode 100644 index 0000000..187c26e --- /dev/null +++ b/School/SchoolContracts/BusinessLogicContracts/IStudentLogic.cs @@ -0,0 +1,15 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.ViewModels; + +namespace SchoolContracts.BusinessLogicContracts +{ + public interface IStudentLogic + { + List ReadList(StudentSearchModel? model = null); + StudentViewModel ReadElement(StudentSearchModel model); + bool Create(StudentBindingModel model); + bool Update(StudentBindingModel model); + bool Delete(StudentBindingModel model); + } +} diff --git a/School/SchoolContracts/Extensions/ExtensionsCast.cs b/School/SchoolContracts/Extensions/ExtensionsCast.cs new file mode 100644 index 0000000..0e756f4 --- /dev/null +++ b/School/SchoolContracts/Extensions/ExtensionsCast.cs @@ -0,0 +1,23 @@ +namespace SchoolContracts.Extensions +{ + public static class ExtensionCast + { + public static TO CastWithCommonProperties(this TFrom fromObject) + where TO : class, new() + where TFrom : class, new() + { + TO result = new(); + foreach (var propFrom in typeof(TFrom).GetProperties()) + { + foreach (var propTo in typeof(TO).GetProperties()) + { + if (propFrom.Name == propTo.Name && propFrom.PropertyType == propTo.PropertyType && propTo.CanWrite) + { + propTo.SetValue(result, propFrom.GetValue(fromObject)); + } + } + } + return result; + } + } +} diff --git a/School/SchoolContracts/SchoolContracts.csproj b/School/SchoolContracts/SchoolContracts.csproj new file mode 100644 index 0000000..8b2bcde --- /dev/null +++ b/School/SchoolContracts/SchoolContracts.csproj @@ -0,0 +1,15 @@ + + + + WinExe + net6.0-windows + enable + true + enable + + + + + + + \ No newline at end of file diff --git a/School/SchoolContracts/SearchModels/AccountSearchModels.cs b/School/SchoolContracts/SearchModels/AccountSearchModels.cs new file mode 100644 index 0000000..ed15379 --- /dev/null +++ b/School/SchoolContracts/SearchModels/AccountSearchModels.cs @@ -0,0 +1,13 @@ +namespace SchoolContracts.SearchModels +{ + public class AccountSearchModel + { + public int? Id { get; set; } + + public int? StudentId { get; set; } + public int? DisciplineId { get; set; } + + public DateOnly? DateFrom { get; set; } + public DateOnly? DateTo { get; set; } + } +} diff --git a/School/SchoolContracts/SearchModels/DisciplineSearchModel.cs b/School/SchoolContracts/SearchModels/DisciplineSearchModel.cs new file mode 100644 index 0000000..e8f8d14 --- /dev/null +++ b/School/SchoolContracts/SearchModels/DisciplineSearchModel.cs @@ -0,0 +1,13 @@ +namespace SchoolContracts.SearchModels +{ + public class DisciplineSearchModel + { + public int? Id { get; set; } + public DateOnly? DateFrom { get; set; } + public DateOnly? DateTo { get; set; } + + public List? StudentsIds { get; set; } + + public int? ImplementerId { get; set; } + } +} diff --git a/School/SchoolContracts/SearchModels/ExecutorSearchModel.cs b/School/SchoolContracts/SearchModels/ExecutorSearchModel.cs new file mode 100644 index 0000000..bcf27ae --- /dev/null +++ b/School/SchoolContracts/SearchModels/ExecutorSearchModel.cs @@ -0,0 +1,9 @@ +namespace SchoolContracts.SearchModels +{ + public class ExecutorSearchModel + { + public int? Id { get; set; } + public string? Login { get; set; } + public string? Password { get; set; } + } +} diff --git a/School/SchoolContracts/SearchModels/ImplementerSearchModel.cs b/School/SchoolContracts/SearchModels/ImplementerSearchModel.cs new file mode 100644 index 0000000..524bf97 --- /dev/null +++ b/School/SchoolContracts/SearchModels/ImplementerSearchModel.cs @@ -0,0 +1,9 @@ +namespace SchoolContracts.SearchModels +{ + public class ImplementerSearchModel + { + public int? Id { get; set; } + public string? Login { get; set; } + public string? Password { get; set; } + } +} diff --git a/School/SchoolContracts/SearchModels/RequirementSearchModel.cs b/School/SchoolContracts/SearchModels/RequirementSearchModel.cs new file mode 100644 index 0000000..4dceadc --- /dev/null +++ b/School/SchoolContracts/SearchModels/RequirementSearchModel.cs @@ -0,0 +1,9 @@ +namespace SchoolContracts.SearchModels +{ + public class RequirementSearchModel + { + public int? Id { get; set; } + + public int? ExecutorId { get; set; } + } +} diff --git a/School/SchoolContracts/SearchModels/StudentSearchModel.cs b/School/SchoolContracts/SearchModels/StudentSearchModel.cs new file mode 100644 index 0000000..bcfc4e7 --- /dev/null +++ b/School/SchoolContracts/SearchModels/StudentSearchModel.cs @@ -0,0 +1,11 @@ +namespace SchoolContracts.SearchModels +{ + public class StudentSearchModel + { + public int? Id { get; set; } + + public int? ExecutorId { get; set; } + + public List? DisciplinesIds { get; set; } + } +} diff --git a/School/SchoolContracts/StoragesContracts/IAccountStorage.cs b/School/SchoolContracts/StoragesContracts/IAccountStorage.cs new file mode 100644 index 0000000..7edb636 --- /dev/null +++ b/School/SchoolContracts/StoragesContracts/IAccountStorage.cs @@ -0,0 +1,14 @@ +using SchoolContracts.SearchModels; +using SchoolContracts.BindingModels; +using SchoolContracts.ViewModels; + +namespace SchoolContracts.StoragesContracts +{ + public interface IAccountStorage + { + List GetFullList(); + List GetFilteredList(AccountSearchModel model); + AccountViewModel? GetElement(AccountSearchModel model); + AccountViewModel? Insert(AccountBindingModel model); + } +} diff --git a/School/SchoolContracts/StoragesContracts/IDisciplineStorage.cs b/School/SchoolContracts/StoragesContracts/IDisciplineStorage.cs new file mode 100644 index 0000000..d4c603d --- /dev/null +++ b/School/SchoolContracts/StoragesContracts/IDisciplineStorage.cs @@ -0,0 +1,18 @@ +using SchoolContracts.SearchModels; +using SchoolContracts.BindingModels; +using SchoolContracts.ViewModels; + +namespace SchoolContracts.StoragesContracts +{ + public interface IDisciplineStorage + { + List GetFullList(); + List GetFilteredList(DisciplineSearchModel model); + DisciplineViewModel? GetElement(DisciplineSearchModel model); + DisciplineViewModel? Insert(DisciplineBindingModel model); + DisciplineViewModel? Update(DisciplineBindingModel model); + DisciplineViewModel? Delete(DisciplineBindingModel model); + + List GetAccountsFromDisciplineAndClient(DisciplineSearchModel modelDiscipline, ClientSearchModel modelClient); + } +} diff --git a/School/SchoolContracts/StoragesContracts/IExecutorStorage.cs b/School/SchoolContracts/StoragesContracts/IExecutorStorage.cs new file mode 100644 index 0000000..5347d08 --- /dev/null +++ b/School/SchoolContracts/StoragesContracts/IExecutorStorage.cs @@ -0,0 +1,12 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.ViewModels; + +namespace SchoolContracts.StoragesContracts +{ + public interface IExecutorStorage + { + ExecutorViewModel? GetElement(ExecutorSearchModel model); + ExecutorViewModel? Insert(ExecutorBindingModel model); + } +} diff --git a/School/SchoolContracts/StoragesContracts/IImplementerStorage.cs b/School/SchoolContracts/StoragesContracts/IImplementerStorage.cs new file mode 100644 index 0000000..a30116b --- /dev/null +++ b/School/SchoolContracts/StoragesContracts/IImplementerStorage.cs @@ -0,0 +1,12 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.ViewModels; + +namespace SchoolContracts.StoragesContracts +{ + public interface IImplementerStorage + { + ImplementerViewModel? GetElement(ImplementerSearchModel model); + ImplementerViewModel? Insert(ImplementerBindingModel model); + } +} diff --git a/School/SchoolContracts/StoragesContracts/IRequirementStorage.cs b/School/SchoolContracts/StoragesContracts/IRequirementStorage.cs new file mode 100644 index 0000000..12b157f --- /dev/null +++ b/School/SchoolContracts/StoragesContracts/IRequirementStorage.cs @@ -0,0 +1,16 @@ +using SchoolContracts.SearchModels; +using SchoolContracts.BindingModels; +using SchoolContracts.ViewModels; + +namespace SchoolContracts.StoragesContracts +{ + public interface IRequirementStorage + { + List GetFullList(); + List GetFilteredList(RequirementSearchModel model); + RequirementViewModel? GetElement(RequirementSearchModel model); + RequirementViewModel? Insert(RequirementBindingModel model); + RequirementViewModel? Update(RequirementBindingModel model); + RequirementViewModel? Delete(RequirementBindingModel model); + } +} diff --git a/School/SchoolContracts/StoragesContracts/IStudentStorage.cs b/School/SchoolContracts/StoragesContracts/IStudentStorage.cs new file mode 100644 index 0000000..0bd3e73 --- /dev/null +++ b/School/SchoolContracts/StoragesContracts/IStudentStorage.cs @@ -0,0 +1,16 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.ViewModels; + +namespace SchoolContracts.StoragesContracts +{ + public interface IStudentStorage + { + List GetFullList(); + List GetFilteredList(StudentSearchModel model); + StudentViewModel? GetElement(StudentSearchModel model); + StudentViewModel? Insert(StudentSearchModel model); + StudentViewModel? Update(StudentSearchModel model); + StudentViewModel? Delete(StudentSearchModel model); + } +} diff --git a/School/SchoolContracts/ViewModels/DisciplineViewModel.cs b/School/SchoolContracts/ViewModels/DisciplineViewModel.cs new file mode 100644 index 0000000..6a00745 --- /dev/null +++ b/School/SchoolContracts/ViewModels/DisciplineViewModel.cs @@ -0,0 +1,41 @@ +using SchoolDataModels; +using System.ComponentModel; +using System.Text; +using SchoolDataModels.Models; + +namespace SchoolContracts.ViewModels +{ + public class DisciplineViewModel : IDisciplineModel + { + public int Id { get; set; } + public int ImplementerId { get; set; } + public string Name { get; set; } = string.Empty; + public double Price { get; set; } + + [DisplayName("Логин ученика")] + public string ExecutorLogin { get; set; } = string.Empty; + [DisplayName("Дата получения")] + public DateOnly DateOfReceipt { get; set; } = DateOnly.FromDateTime(DateTime.Now); + [DisplayName("Дата прохождения")] + public DateOnly DateOfPassage { get; set; } = DateOnly.FromDateTime(DateTime.Now); + + public Dictionary StudentsModel { get; set; } = new(); + public List RequirementViewModels { get; set; } = new(); + + public List StudentViewModels { get; set; } = new(); + + public override string ToString() + { + var result = new StringBuilder( + $"Занятие {Name}, созданная {DateOfReceipt}, " + + $"дата обучения {DateOfPassage}, включает в себя группу учеников:"); + for (int i = 0; i < StudentViewModels.Count; i++) + { + var discipline = StudentViewModels[i]; + result.Append($"\n\t{i + 1}. {discipline.Name} на " + + $"{StudentsModel[discipline.Id].DateOfStudent.ToShortDateString()}"); + } + return result.ToString(); + } + } +} diff --git a/School/SchoolContracts/ViewModels/ExecutorViewModel.cs b/School/SchoolContracts/ViewModels/ExecutorViewModel.cs new file mode 100644 index 0000000..b9397b8 --- /dev/null +++ b/School/SchoolContracts/ViewModels/ExecutorViewModel.cs @@ -0,0 +1,19 @@ +using SchoolDataModels; +using System.ComponentModel; + +namespace SchoolContracts.ViewModels +{ + public class ExecutorViewModel : IExecutorModel + { + public int Id { get; set; } + [DisplayName("Фамилия")] + public string LastName { get; set; } = string.Empty; + [DisplayName("Имя")] + public string FirstName { get; set; } = string.Empty; + public string Login { get; set; } = string.Empty; + [DisplayName("Пароль")] + public string Password { get; set; } = string.Empty; + + public string PhoneNumber { get; set; } = string.Empty; + } +} diff --git a/School/SchoolContracts/ViewModels/IAccountModel.cs b/School/SchoolContracts/ViewModels/IAccountModel.cs new file mode 100644 index 0000000..b33fd75 --- /dev/null +++ b/School/SchoolContracts/ViewModels/IAccountModel.cs @@ -0,0 +1,21 @@ +using SchoolDataModels; +using System.ComponentModel; +using SchoolDataModels.Models; + +namespace SchoolContracts.ViewModels +{ + public class AccountViewModel : IAccountModel + { + public int Id { get; set; } + public int StudentByDisciplineId { get; set; } + public DateOnly DateOfAccount { get; set; } = DateOnly.FromDateTime(DateTime.Now); + + public double Price { get; set; } + + public StudentByDisciplineModel StudentByDiscipline { get; set; } + + public StudentViewModel? Student { get; set; } + + public DisciplineViewModel? Discipline { get; set; } + } +} diff --git a/School/SchoolContracts/ViewModels/ImplementerViewModel.cs b/School/SchoolContracts/ViewModels/ImplementerViewModel.cs new file mode 100644 index 0000000..67951e2 --- /dev/null +++ b/School/SchoolContracts/ViewModels/ImplementerViewModel.cs @@ -0,0 +1,16 @@ +using SchoolDataModels; +using System.ComponentModel; + +namespace SchoolContracts.ViewModels +{ + public class ImplementerViewModel : IImplementerModel + { + public int Id { get; set; } + public string LastName { get; set; } = string.Empty; + public string FirstName { get; set; } = string.Empty; + public string Login { get; set; } = string.Empty; + public string Password { get; set; } = string.Empty; + + public string PhoneNumber { get; set; } = string.Empty; + } +} diff --git a/School/SchoolContracts/ViewModels/RequirementViewModel.cs b/School/SchoolContracts/ViewModels/RequirementViewModel.cs new file mode 100644 index 0000000..969aeae --- /dev/null +++ b/School/SchoolContracts/ViewModels/RequirementViewModel.cs @@ -0,0 +1,20 @@ +using SchoolDataModels; +using System.ComponentModel; +using SchoolDataModels.ProxyModels; + +namespace SchoolContracts.ViewModels +{ + public class RequirementViewModel : IRequirementModel + { + public int Id { get; set; } + public int ExecutorId { get; set; } + [DisplayName("Логин сотрудника")] + public string DirectorLogin { get; set; } = string.Empty; + [DisplayName("Наименование")] + public string NameOfRequirement { get; set; } = string.Empty; + [DisplayName("Стоимость")] + public double Price { get; set; } + + public Dictionary DisciplinesModels { get; set; } = new(); + } +} diff --git a/School/SchoolContracts/ViewModels/StudentViewModel.cs b/School/SchoolContracts/ViewModels/StudentViewModel.cs new file mode 100644 index 0000000..ef9f623 --- /dev/null +++ b/School/SchoolContracts/ViewModels/StudentViewModel.cs @@ -0,0 +1,29 @@ +using SchoolDataModels; +using System.ComponentModel; +using System.Text; +using System.Text.Json.Serialization; + +namespace SchoolContracts.ViewModels +{ + public class StudentViewModel : IStudentModel + { + public int Id { get; set; } + public int ExecutorId { get; set; } + public string ExecutorLogin { get; set; } = string.Empty; + public string Name { get; set; } = string.Empty; + public int Course { get; set; } + + [JsonIgnore] + public List Disciplines { get; set; } = new(); + public override string ToString() + { + var result = new StringBuilder(); + foreach (var discipline in Disciplines) + { + result.Append($"Ученик {Name} {Course} класса, записанный {discipline.StudentModel[Id].DateOfStudent.ToShortDateString()}, " + + $"на занятие {discipline.Name}.\n"); + } + return result.ToString(); + } + } +} diff --git a/School/SchoolDataBaseImplement/Implements/AccountStorage.cs b/School/SchoolDataBaseImplement/Implements/AccountStorage.cs new file mode 100644 index 0000000..31612f6 --- /dev/null +++ b/School/SchoolDataBaseImplement/Implements/AccountStorage.cs @@ -0,0 +1,82 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.StoragesContracts; +using SchoolContracts.ViewModels; +using SchoolDatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; +using Microsoft.EntityFrameworkCore.Query; + +namespace SchoolDatabaseImplement.Implements +{ + public class AccountStorage : IAccountStorage + { + private static IIncludableQueryable Accounts(SchoolDB context) + => context.Accounts + .Include(x => x.StudentByDiscipline).ThenInclude(x => x.Discipline) + .Include(x => x.StudentByDiscipline).ThenInclude(x => x.Student); + + public List GetFullList() + { + using var context = new SchoolDB(); + return Accounts(context) + .Select(x => (AccountViewModel)x) + .ToList(); + } + + public List GetFilteredList(AccountSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model), "Получена пустая поисковая модель"); + } + + if (model.DateFrom.HasValue && !model.DateTo.HasValue || model.DateTo.HasValue && !model.DateFrom.HasValue) + { + throw new ArgumentException("Получена поисковая модель только с началом или концом периода"); + } + if (!model.DateFrom.HasValue && !model.StudentId.HasValue) + { + throw new ArgumentNullException(nameof(model.StudentId), "Получена поисковая модель без StudentId"); + + } + if (!model.DateFrom.HasValue && !model.DisciplineId.HasValue) + { + throw new ArgumentNullException(nameof(model.DisciplineId), "Получена поисковая модель без DisciplineId"); + } + using var context = new SchoolDB(); + if (model.DateFrom.HasValue) + { + return Accounts(context) + .Where(x => model.DateFrom.Value <= x.DateOfAccount && x.DateOfAccount <= model.DateTo.Value) + .Select(x => (AccountViewModel)x) + .ToList(); + } + + return Accounts(context) + .Where(x => x.SchoolByDiscipline != null && + x.SchoolByDiscipline.StudentId == model.StudentId && + x.SchoolByDiscipline.DisciplineId == model.DisciplineId) + .Select(x => (AccountViewModel)x) + .ToList(); + } + public AccountViewModel? GetElement(AccountSearchModel model) + { + using var context = new SchoolDB(); + return Accounts(context) + .FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id)); + } + public AccountViewModel? Insert(AccountBindingModel model) + { + if (model == null) + { + return null; + } + var newAccount = Account.Create(model); + using var context = new SchoolDB(); + context.Accounts.Add(newAccount); + context.SaveChanges(); + return newAccount; + } + } +} diff --git a/School/SchoolDataBaseImplement/Implements/DisciplineStorage.cs b/School/SchoolDataBaseImplement/Implements/DisciplineStorage.cs new file mode 100644 index 0000000..47b839f --- /dev/null +++ b/School/SchoolDataBaseImplement/Implements/DisciplineStorage.cs @@ -0,0 +1,152 @@ +using System.Security.Cryptography.X509Certificates; +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.StoragesContracts; +using SchoolContracts.ViewModels; +using SchoolDatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; + +namespace SchoolDatabaseImplement.Implements +{ + public class DisciplineStorage : IDisciplineStorage + { + private void CheckSearchModel(DisciplineSearchModel model) + { + if (model == null) + throw new ArgumentNullException("Передаваемая модель для поиска равна нулю", nameof(model)); + if (!model.Id.HasValue && !model.ImplementerId.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue && model.ClientsIds == null) + throw new ArgumentException("Все передаваемые поля поисковой модели оказались пусты или равны null"); + if (model.DateFrom.HasValue != model.DateTo.HasValue) + throw new ArgumentException($"Не указано начало {model.DateFrom} или конец {model.DateTo} периода для поиска по дате."); + } + public DisciplineViewModel? Delete(DisciplineBindingModel model) + { + using var context = new SchoolDB(); + var element = context.Disciplines.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + context.Disciplines.Remove(element); + context.SaveChanges(); + return element; + } + return null; + } + + /// + /// Получение списка счетов по клиенту и дисциплине, для получения полной и оплаченной стоимости в бизнес логике + /// + public List GetAccountsFromDisciplineAndClient(DisciplineSearchModel modelDiscipline, StudentSearchModel modelStudent) + { + if (!modelDiscipline.Id.HasValue) + { + throw new ArgumentNullException(nameof(modelDiscipline), "Получена поисковая модель без Id"); + } + if (!modelStudent.Id.HasValue) + { + throw new ArgumentNullException(nameof(modelStudent), "Получена поисковая модель без Id"); + } + using var context = new SchoolDB(); + var studentByDiscipline = context.StudentsByDisciplines + .Include(x => x.Accounts) + .FirstOrDefault(x => x.ClientId == modelStudent.Id && x.DisciplineId == modelDiscipline.Id); + if (studentByDiscipline?.Accounts == null) + { + throw new InvalidOperationException( + $"Не существует связи между данным учеников(Id={modelStudent.Id}) и (Id={modelDiscipline.Id})"); + } + return studentByDiscipline.Accounts.Select(account => (AccountViewModel)account).ToList(); + } + + public DisciplineViewModel? GetElement(DisciplineSearchModel model) + { + using var context = new SchoolDB(); + if (!model.Id.HasValue) + { + return null; + } + return context.Disciplines + .Include(x => x.Student) + .Include(x => x.Students) + .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id); + } + + public List GetFilteredList(DisciplineSearchModel model) + { + CheckSearchModel(model); + if (model.Id.HasValue) + { + var res = GetElement(model); + return res != null ? new() { res } : new(); + } + + using var context = new SchoolDB(); + + var query = context.Disciplines.Include(x => x.Student); + IQueryable? resultQuery = null; + if (model.ImplementerId.HasValue) + { + return query + .Where(x => model.ImplementerId == x.ImplementerId) + .Select(x => (DisciplineViewModel)x) + .ToList(); + } + + if (model.DateTo.HasValue) + resultQuery = query + .Include(x => x.Students) + .ThenInclude(x => x.Student) + .Include(x => x.Requirements) + .ThenInclude(x => x.Requirement) + .Where(x => model.DateFrom <= x.DateOfReceipt && x.DateOfReceipt <= model.DateTo); + + else if (model.StudentsIds != null) + resultQuery = query + .Include(x => x.Students) + .ThenInclude(x => x.Student) + .Where(x => x.Clients.Any(x => model.StudentsIds.Contains(x.StudentId))); + + return resultQuery? + .Select(x => (DisciplineViewModel)x) + .ToList() ?? new(); + } + + public List GetFullList() + { + using var context = new SchoolDB(); + return context.Disciplines + .Include(x => x.Student) + .Include(x => x.Students) + .Select(x => (DisciplineViewModel)x) + .ToList(); + } + + public DisciplineViewModel? Insert(DisciplineBindingModel model) + { + var newDiscipline = Discipline.Create(model); + if (newDiscipline == null) + { + return null; + } + using var context = new SchoolDB(); + context.Disciplines.Add(newDiscipline); + context.SaveChanges(); + newDiscipline.UpdateClients(context, model); + context.SaveChanges(); + return newDiscipline; + } + + public DisciplineViewModel? Update(DisciplineBindingModel model) + { + using var context = new SchoolDB(); + var disciplinevisit = context.Disciplines.FirstOrDefault(x => x.Id == model.Id); + if (disciplinevisit == null) + { + return null; + } + disciplinevisit.Update(model); + disciplinevisit.UpdateClients(context, model); + context.SaveChanges(); + return disciplinevisit; + } + } +} diff --git a/School/SchoolDataBaseImplement/Implements/ExecutorStorage.cs b/School/SchoolDataBaseImplement/Implements/ExecutorStorage.cs new file mode 100644 index 0000000..71bf9d3 --- /dev/null +++ b/School/SchoolDataBaseImplement/Implements/ExecutorStorage.cs @@ -0,0 +1,39 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.StoragesContracts; +using SchoolContracts.ViewModels; +using SchoolDatabaseImplement.Models; + +namespace SchoolDatabaseImplement.Implements +{ + public class ExecutorStorage : IExecutorStorage + { + private void CheckSearchModel(DirectorSearchModel model) + { + if (model == null) + throw new ArgumentNullException("Передаваемая модель для поиска равна нулю", nameof(model)); + if (!model.Id.HasValue && string.IsNullOrEmpty(model.Login) && string.IsNullOrEmpty(model.Password)) + throw new ArgumentException("Все передаваемые поля поисковой модели оказались пусты или равны null"); + } + public ExecutorViewModel? GetElement(ExecutorSearchModel model) + { + CheckSearchModel(model); + using var context = new SchoolDB(); + // возможность поиска только по логину для проверки на уникальность, или поиска по логина и паролю + return context.Executors + .FirstOrDefault(x => x.Login.Equals(model.Login) && (string.IsNullOrEmpty(model.Password) || x.Password.Equals(model.Password))); + } + public ExecutorViewModel? Insert(ExecutorBindingModel model) + { + if (model == null) + { + return null; + } + var newExecutor = Executor.Create(model); + using var context = new SchoolDB(); + context.Executors.Add(newExecutor); + context.SaveChanges(); + return newExecutor; + } + } +} diff --git a/School/SchoolDataBaseImplement/Implements/ImplementerStorage.cs b/School/SchoolDataBaseImplement/Implements/ImplementerStorage.cs new file mode 100644 index 0000000..b9e7b44 --- /dev/null +++ b/School/SchoolDataBaseImplement/Implements/ImplementerStorage.cs @@ -0,0 +1,39 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.StoragesContracts; +using SchoolContracts.ViewModels; +using SchoolDatabaseImplement.Models; + +namespace SchoolDatabaseImplement.Implements +{ + public class ImplementerStorage : IImplementerStorage + { + private void CheckSearchModel(ImplementerSearchModel model) + { + if (model == null) + throw new ArgumentNullException("Передаваемая модель для поиска равна нулю", nameof(model)); + if (!model.Id.HasValue && string.IsNullOrEmpty(model.Login) && string.IsNullOrEmpty(model.Password)) + throw new ArgumentException("Все передаваемые поля поисковой модели оказались пусты или равны null"); + } + public ImplementerViewModel? GetElement(ImplementerSearchModel model) + { + CheckSearchModel(model); + using var context = new SchoolDB(); + // возможность поиска только по логину для проверки на уникальность, или поиска по логина и паролю + return context.Implementers + .FirstOrDefault(x => x.Login.Equals(model.Login) && (string.IsNullOrEmpty(model.Password) || x.Password.Equals(model.Password))); + } + public ImplementerViewModel? Insert(ImplementerBindingModel model) + { + if (model == null) + { + return null; + } + var newStudent = Implementer.Create(model); + using var context = new SchoolDB(); + context.Implementers.Add(newStudent); + context.SaveChanges(); + return newStudent; + } + } +} diff --git a/School/SchoolDataBaseImplement/Implements/RequirementStorage.cs b/School/SchoolDataBaseImplement/Implements/RequirementStorage.cs new file mode 100644 index 0000000..8cab313 --- /dev/null +++ b/School/SchoolDataBaseImplement/Implements/RequirementStorage.cs @@ -0,0 +1,95 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.StoragesContracts; +using SchoolContracts.ViewModels; +using SchoolDatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; + +namespace SchoolDatabaseImplement.Implements +{ + public class RequirementStorage : IRequirementStorage + { + private void CheckSearchModel(RequirementSearchModel model) + { + if (model == null) + throw new ArgumentNullException("Передаваемая модель для поиска равна нулю", nameof(model)); + if (!model.Id.HasValue && !model.DirectorId.HasValue) + throw new ArgumentException("Все передаваемые поля поисковой модели оказались пусты или равны null"); + } + public RequirementViewModel? Delete(RequirementBindingModel model) + { + using var context = new SchoolDB(); + var element = context.Requirements.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + context.Requirements.Remove(element); + context.SaveChanges(); + return element; + } + return null; + } + + public RequirementViewModel? GetElement(RequirementSearchModel model) + { + CheckSearchModel(model); + using var context = new SchoolDB(); + if (!model.Id.HasValue) + { + return null; + } + return context.Requirements + .Include(requirement => requirement.Executor) + .Include(requirement => requirement.Disciplines).ThenInclude(requirementByDiscipline => requirementByDiscipline.Discipline) + .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id); + } + + public List GetFilteredList(RequirementSearchModel model) + { + CheckSearchModel(model); + using var context = new SchoolDB(); + return context.Requirements + .Include(requirement => requirement.Executor) + .Include(requirement => requirement.Disciplines).ThenInclude(requirementByDiscipline => requirementByDiscipline.Discipline) + .Where(x => x.DirectorId == model.ExecutorId) + .Select(x => (RequirementViewModel)x) + .ToList(); + } + + public List GetFullList() + { + using var context = new SchoolDB(); + return context.Requirements + .Include(requirement => requirement.Executor) + .Include(requirement => requirement.Disciplines).ThenInclude(requirementByDiscipline => requirementByDiscipline.Discipline) + .Select(x => (RequirementViewModel)x) + .ToList(); + } + + public RequirementViewModel? Insert(RequirementBindingModel model) + { + var newRequirement = Requirement.Create(model); + if (newRequirement == null) + { + return null; + } + using var context = new SchoolDB(); + context.Requirements.Add(newRequirement); + context.SaveChanges(); + return newRequirement; + } + public RequirementViewModel? Update(RequirementBindingModel model) + { + using var context = new SchoolDB(); + var requirement = context.Requirements.FirstOrDefault(x => x.Id == model.Id); + if (requirement == null) + { + return null; + } + requirement.Update(model); + context.SaveChanges(); + requirement.UpdateDisciplines(context, model); + context.SaveChanges(); + return requirement; + } + } +} diff --git a/School/SchoolDataBaseImplement/Implements/StudentStorage.cs b/School/SchoolDataBaseImplement/Implements/StudentStorage.cs new file mode 100644 index 0000000..1bcfead --- /dev/null +++ b/School/SchoolDataBaseImplement/Implements/StudentStorage.cs @@ -0,0 +1,110 @@ +using System.Security.Cryptography.X509Certificates; +using SchoolContracts.BindingModels; +using SchoolContracts.SearchModels; +using SchoolContracts.StoragesContracts; +using SchoolContracts.ViewModels; +using SchoolDatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; + +namespace SchoolDatabaseImplement.Implements +{ + public class StudentStorage : IStudentStorage + { + private void CheckSearchModel(StudentSearchModel model) + { + if (model == null) + throw new ArgumentNullException("Передаваемая модель для поиска равна нулю", nameof(model)); + if (!model.Id.HasValue && !model.DirectorId.HasValue && model.DisciplinesIds == null) + throw new ArgumentException("Все передаваемые поля поисковой модели оказались пусты или равны null"); + } + + public StudentViewModel? Delete(StudentBindingModel model) + { + using var context = new SchoolDB(); + var element = context.Students.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + context.Studentss.Remove(element); + context.SaveChanges(); + return element; + } + return null; + } + + public StudentViewModel? GetElement(StudentSearchModel model) + { + CheckSearchModel(model); + if (!model.Id.HasValue) + { + return null; + } + using var context = new SchoolDB(); + return context.Students + .Include(x => x.Executor) + .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id); + } + + public List GetFilteredList(StudentSearchModel model) + { + CheckSearchModel(model); + if (model.Id.HasValue) + { + var res = GetElement(model); + return res != null ? new() { res } : new(); + } + using var context = new SchoolDB(); + var query = context.Students.Include(x => x.Executor); + if (model.DirectorId.HasValue) + { + return query + .Where(x => model.DirectorId == x.DirectorId) + .Select(x => (StudentViewModel)x) + .ToList(); + } + + if (model.DisciplinesIds != null) + return query + .Include(x => x.Disciplines)! + .ThenInclude(x => x.Discipline) + .ThenInclude(x => x.Student) + .Where(x => x.Disciplines.Any(y => model.DisciplinesIds.Contains(y.DisciplineId))) + .Select(x => (StudentViewModel)x) + .ToList(); + return new(); + } + + public List GetFullList() + { + using var context = new SchoolDB(); + return context.Students.Include(x => x.Executor) + .Select(x => (StudentViewModel)x) + .ToList(); + } + + public StudentViewModel? Insert(StudentBindingModel model) + { + var newStudent = Student.Create(model); + if (newStudent == null) + { + return null; + } + using var context = new SchoolDB(); + context.Students.Add(newStudent); + context.SaveChanges(); + return newStudent; + } + + public StudentViewModel? Update(StudentBindingModel model) + { + using var context = new SchoolDB(); + var Student = context.Students.FirstOrDefault(x => x.Id == model.Id); + if (Student == null) + { + return null; + } + Student.Update(model); + context.SaveChanges(); + return Student; + } + } +} diff --git a/School/SchoolDataBaseImplement/Migrations/20230515153721_Init.Designer.cs b/School/SchoolDataBaseImplement/Migrations/20230515153721_Init.Designer.cs new file mode 100644 index 0000000..e3b259d --- /dev/null +++ b/School/SchoolDataBaseImplement/Migrations/20230515153721_Init.Designer.cs @@ -0,0 +1,372 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using UniversityDatabaseImplement; + +#nullable disable + +namespace UniversityDatabaseImplement.Migrations +{ + [DbContext(typeof(UniversityDB))] + [Migration("20230515153721_Init")] + partial class Init + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.4") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.Account", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientByDisciplineId") + .HasColumnType("integer"); + + b.Property("DateOfAccount") + .HasColumnType("date"); + + b.Property("Price") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.HasIndex("ClientByDisciplineId"); + + b.ToTable("Accounts"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Course") + .HasColumnType("integer"); + + b.Property("DirectorId") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("Price") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.HasIndex("DirectorId"); + + b.ToTable("Clients"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.ClientByDiscipline", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("integer"); + + b.Property("DateOfClient") + .HasColumnType("timestamp with time zone"); + + b.Property("DisciplineId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("DisciplineId"); + + b.ToTable("ClientsByDisciplines"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.Director", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("text"); + + b.Property("LastName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Login") + .IsRequired() + .HasColumnType("text"); + + b.Property("Password") + .IsRequired() + .HasColumnType("text"); + + b.Property("PhoneNumber") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Directors"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.Discipline", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DateOfPassage") + .HasColumnType("date"); + + b.Property("DateOfReceipt") + .HasColumnType("date"); + + b.Property("ImplementerId") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("Price") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.HasIndex("ImplementerId"); + + b.ToTable("Disciplines"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("text"); + + b.Property("LastName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Login") + .IsRequired() + .HasColumnType("text"); + + b.Property("Password") + .IsRequired() + .HasColumnType("text"); + + b.Property("PhoneNumber") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.Requirement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DirectorId") + .HasColumnType("integer"); + + b.Property("NameOfRequirement") + .IsRequired() + .HasColumnType("text"); + + b.Property("Price") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.HasIndex("DirectorId"); + + b.ToTable("Requirements"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.RequirementByDiscipline", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("DisciplineId") + .HasColumnType("integer"); + + b.Property("RequirementId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DisciplineId"); + + b.HasIndex("RequirementId"); + + b.ToTable("RequirementByDisciplines"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.Account", b => + { + b.HasOne("UniversityDatabaseImplement.Models.ClientByDiscipline", "ClientByDiscipline") + .WithMany("Accounts") + .HasForeignKey("ClientByDisciplineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ClientByDiscipline"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.Client", b => + { + b.HasOne("UniversityDatabaseImplement.Models.Director", "Director") + .WithMany("Clients") + .HasForeignKey("DirectorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Director"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.ClientByDiscipline", b => + { + b.HasOne("UniversityDatabaseImplement.Models.Client", "Client") + .WithMany("Disciplines") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("UniversityDatabaseImplement.Models.Discipline", "Discipline") + .WithMany("Clients") + .HasForeignKey("DisciplineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Discipline"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.Discipline", b => + { + b.HasOne("UniversityDatabaseImplement.Models.Implementer", "Client") + .WithMany("Disciplines") + .HasForeignKey("ImplementerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.Requirement", b => + { + b.HasOne("UniversityDatabaseImplement.Models.Director", "Director") + .WithMany("Requirements") + .HasForeignKey("DirectorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Director"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.RequirementByDiscipline", b => + { + b.HasOne("UniversityDatabaseImplement.Models.Discipline", "Discipline") + .WithMany("Requirements") + .HasForeignKey("DisciplineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("UniversityDatabaseImplement.Models.Requirement", "Requirement") + .WithMany("Disciplines") + .HasForeignKey("RequirementId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Discipline"); + + b.Navigation("Requirement"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.Client", b => + { + b.Navigation("Disciplines"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.ClientByDiscipline", b => + { + b.Navigation("Accounts"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.Director", b => + { + b.Navigation("Clients"); + + b.Navigation("Requirements"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.Discipline", b => + { + b.Navigation("Clients"); + + b.Navigation("Requirements"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Disciplines"); + }); + + modelBuilder.Entity("UniversityDatabaseImplement.Models.Requirement", b => + { + b.Navigation("Disciplines"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/School/SchoolDataBaseImplement/Migrations/20230515153721_Init.cs b/School/SchoolDataBaseImplement/Migrations/20230515153721_Init.cs new file mode 100644 index 0000000..c5e98b4 --- /dev/null +++ b/School/SchoolDataBaseImplement/Migrations/20230515153721_Init.cs @@ -0,0 +1,259 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace SchoolDatabaseImplement.Migrations +{ + /// + public partial class Init : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Executors", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + FirstName = table.Column(type: "text", nullable: false), + LastName = table.Column(type: "text", nullable: false), + Login = table.Column(type: "text", nullable: false), + Password = table.Column(type: "text", nullable: false), + PhoneNumber = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Executors", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Implementers", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + FirstName = table.Column(type: "text", nullable: false), + LastName = table.Column(type: "text", nullable: false), + Login = table.Column(type: "text", nullable: false), + Password = table.Column(type: "text", nullable: false), + PhoneNumber = table.Column(type: "text", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Implementers", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Students", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ExecutorId = table.Column(type: "integer", nullable: false), + Name = table.Column(type: "text", nullable: false), + Price = table.Column(type: "double precision", nullable: false), + Course = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Students", x => x.Id); + table.ForeignKey( + name: "FK_Students_Executors_ExecutorId", + column: x => x.ExecutorId, + principalTable: "Executors", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Requirements", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ExecutorId = table.Column(type: "integer", nullable: false), + NameOfRequirement = table.Column(type: "text", nullable: false), + Price = table.Column(type: "double precision", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Requirements", x => x.Id); + table.ForeignKey( + name: "FK_Requirements_Executors_ExecutorId", + column: x => x.ExecutorId, + principalTable: "Executors", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Disciplines", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + ImplementerId = table.Column(type: "integer", nullable: false), + Name = table.Column(type: "text", nullable: false), + Price = table.Column(type: "double precision", nullable: false), + DateOfReceipt = table.Column(type: "date", nullable: false), + DateOfPassage = table.Column(type: "date", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Disciplines", x => x.Id); + table.ForeignKey( + name: "FK_Disciplines_Implementers_ImplementerId", + column: x => x.ImplementerId, + principalTable: "Implementers", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "StudentsByDisciplines", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + StudentId = table.Column(type: "integer", nullable: false), + DisciplineId = table.Column(type: "integer", nullable: false), + DateOfStudent = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_StudentsByDisciplines", x => x.Id); + table.ForeignKey( + name: "FK_StudentsByDisciplines_Students_StudentId", + column: x => x.ClientId, + principalTable: "Students", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_StudentsByDisciplines_Disciplines_DisciplineId", + column: x => x.DisciplineId, + principalTable: "Disciplines", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "RequirementByDisciplines", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + RequirementId = table.Column(type: "integer", nullable: false), + DisciplineId = table.Column(type: "integer", nullable: false), + Count = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_RequirementByDisciplines", x => x.Id); + table.ForeignKey( + name: "FK_RequirementByDisciplines_Disciplines_DisciplineId", + column: x => x.DisciplineId, + principalTable: "Disciplines", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_RequirementByDisciplines_Requirements_RequirementId", + column: x => x.RequirementId, + principalTable: "Requirements", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "Accounts", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + StudentByDisciplineId = table.Column(type: "integer", nullable: false), + DateOfAccount = table.Column(type: "date", nullable: false), + Price = table.Column(type: "double precision", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Accounts", x => x.Id); + table.ForeignKey( + name: "FK_Accounts_StudentsByDisciplines_StudentByDisciplineId", + column: x => x.StudentByDisciplineId, + principalTable: "StudentsByDisciplines", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Accounts_StudentByDisciplineId", + table: "Accounts", + column: "StudentByDisciplineId"); + + migrationBuilder.CreateIndex( + name: "IX_Students_DirectorId", + table: "Students", + column: "ExecutorId"); + + migrationBuilder.CreateIndex( + name: "IX_StudentsByDisciplines_StudentId", + table: "StudentsByDisciplines", + column: "StudentId"); + + migrationBuilder.CreateIndex( + name: "IX_StudentsByDisciplines_DisciplineId", + table: "StudentsByDisciplines", + column: "DisciplineId"); + + migrationBuilder.CreateIndex( + name: "IX_Disciplines_ImplementerId", + table: "Disciplines", + column: "ImplementerId"); + + migrationBuilder.CreateIndex( + name: "IX_RequirementByDisciplines_DisciplineId", + table: "RequirementByDisciplines", + column: "DisciplineId"); + + migrationBuilder.CreateIndex( + name: "IX_RequirementByDisciplines_RequirementId", + table: "RequirementByDisciplines", + column: "RequirementId"); + + migrationBuilder.CreateIndex( + name: "IX_Requirements_ExecutorId", + table: "Requirements", + column: "ExecutorId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Accounts"); + + migrationBuilder.DropTable( + name: "RequirementByDisciplines"); + + migrationBuilder.DropTable( + name: "StudentsByDisciplines"); + + migrationBuilder.DropTable( + name: "Requirements"); + + migrationBuilder.DropTable( + name: "Students"); + + migrationBuilder.DropTable( + name: "Disciplines"); + + migrationBuilder.DropTable( + name: "Executors"); + + migrationBuilder.DropTable( + name: "Implementers"); + } + } +} diff --git a/School/SchoolDataBaseImplement/Migrations/SchoolDBModelSnapshot.cs b/School/SchoolDataBaseImplement/Migrations/SchoolDBModelSnapshot.cs new file mode 100644 index 0000000..d49d34c --- /dev/null +++ b/School/SchoolDataBaseImplement/Migrations/SchoolDBModelSnapshot.cs @@ -0,0 +1,369 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using SchoolDatabaseImplement; + +#nullable disable + +namespace UniversityDatabaseImplement.Migrations +{ + [DbContext(typeof(SchoolDB))] + partial class SchoolDBModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.4") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.Account", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("StudentByDisciplineId") + .HasColumnType("integer"); + + b.Property("DateOfAccount") + .HasColumnType("date"); + + b.Property("Price") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.HasIndex("StudentByDisciplineId"); + + b.ToTable("Accounts"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.Student", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Course") + .HasColumnType("integer"); + + b.Property("ExecutorId") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("Price") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.HasIndex("ExecutorId"); + + b.ToTable("Students"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.StudentByDiscipline", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("StudentId") + .HasColumnType("integer"); + + b.Property("DateOfStudent") + .HasColumnType("timestamp with time zone"); + + b.Property("DisciplineId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("StudentId"); + + b.HasIndex("DisciplineId"); + + b.ToTable("StudentsByDisciplines"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.Executor", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("text"); + + b.Property("LastName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Login") + .IsRequired() + .HasColumnType("text"); + + b.Property("Password") + .IsRequired() + .HasColumnType("text"); + + b.Property("PhoneNumber") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Executors"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.Discipline", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("DateOfPassage") + .HasColumnType("date"); + + b.Property("DateOfReceipt") + .HasColumnType("date"); + + b.Property("ImplementerId") + .HasColumnType("integer"); + + b.Property("Name") + .IsRequired() + .HasColumnType("text"); + + b.Property("Price") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.HasIndex("ImplementerId"); + + b.ToTable("Disciplines"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.Implementer", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("FirstName") + .IsRequired() + .HasColumnType("text"); + + b.Property("LastName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Login") + .IsRequired() + .HasColumnType("text"); + + b.Property("Password") + .IsRequired() + .HasColumnType("text"); + + b.Property("PhoneNumber") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Implementers"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.Requirement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ExecutorId") + .HasColumnType("integer"); + + b.Property("NameOfRequirement") + .IsRequired() + .HasColumnType("text"); + + b.Property("Price") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.HasIndex("ExecutorId"); + + b.ToTable("Requirements"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.RequirementByDiscipline", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("DisciplineId") + .HasColumnType("integer"); + + b.Property("RequirementId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("DisciplineId"); + + b.HasIndex("RequirementId"); + + b.ToTable("RequirementByDisciplines"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.Account", b => + { + b.HasOne("UniversityDatabaseImplement.Models.StudentByDiscipline", "StudentByDiscipline") + .WithMany("Accounts") + .HasForeignKey("StudentByDisciplineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("StudentByDiscipline"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.Student", b => + { + b.HasOne("UniversityDatabaseImplement.Models.Executor", "Executor") + .WithMany("Students") + .HasForeignKey("ExecutorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Executor"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.StudentByDiscipline", b => + { + b.HasOne("SchoolDatabaseImplement.Models.Student", "Student") + .WithMany("Disciplines") + .HasForeignKey("StudentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SchoolDatabaseImplement.Models.Discipline", "Discipline") + .WithMany("Students") + .HasForeignKey("DisciplineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Student"); + + b.Navigation("Discipline"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.Discipline", b => + { + b.HasOne("UniversityDatabaseImplement.Models.Implementer", "Student") + .WithMany("Disciplines") + .HasForeignKey("ImplementerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Student"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.Requirement", b => + { + b.HasOne("UniversityDatabaseImplement.Models.Executor", "Executor") + .WithMany("Requirements") + .HasForeignKey("ExecutorId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Executor"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.RequirementByDiscipline", b => + { + b.HasOne("UniversityDatabaseImplement.Models.Discipline", "Discipline") + .WithMany("Requirements") + .HasForeignKey("DisciplineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("UniversityDatabaseImplement.Models.Requirement", "Requirement") + .WithMany("Disciplines") + .HasForeignKey("RequirementId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Discipline"); + + b.Navigation("Requirement"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.Student", b => + { + b.Navigation("Disciplines"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.StudentByDiscipline", b => + { + b.Navigation("Accounts"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.Executor", b => + { + b.Navigation("Students"); + + b.Navigation("Requirements"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.Discipline", b => + { + b.Navigation("Students"); + + b.Navigation("Requirements"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.Implementer", b => + { + b.Navigation("Disciplines"); + }); + + modelBuilder.Entity("SchoolDatabaseImplement.Models.Requirement", b => + { + b.Navigation("Disciplines"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/School/SchoolDataBaseImplement/Models/Account.cs b/School/SchoolDataBaseImplement/Models/Account.cs new file mode 100644 index 0000000..885df19 --- /dev/null +++ b/School/SchoolDataBaseImplement/Models/Account.cs @@ -0,0 +1,40 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.Extensions; +using SchoolContracts.ViewModels; +using SchoolDataModels; +using System.ComponentModel.DataAnnotations; + +namespace SchoolDatabaseImplement.Models +{ + public class Account : IAccountModel + { + [Required] + public int StudentByDisciplineId { get; private set; } + + [Required] + public DateOnly DateOfAccount { get; private set; } + + [Required] + public double Price { get; private set; } + + public int Id { get; private set; } + + [Required] + public StudentByDisciplineId? StudentByDisciplineId { get; private set; } + + public static Account Create(AccountBindingModel model) => model.CastWithCommonProperties(); + + public static implicit operator AccountViewModel(Account? model) + { + if (model == null) + { + throw new ArgumentNullException("Возникла ошибка при попытки получить View-модель из null-объекта", nameof(model)); + } + var res = model.CastWithCommonProperties(); + res.StudentByDisciplineId = model.StudentByDisciplineId; + res.Student = model.StudentByDisciplineId?.Student; + res.Discipline = model.StudentByDisciplineId?.Discipline; + return res; + } + } +} diff --git a/School/SchoolDataBaseImplement/Models/Discipline.cs b/School/SchoolDataBaseImplement/Models/Discipline.cs new file mode 100644 index 0000000..0355d41 --- /dev/null +++ b/School/SchoolDataBaseImplement/Models/Discipline.cs @@ -0,0 +1,98 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.Extensions; +using SchoolContracts.ViewModels; +using SchoolDataModels; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq.Expressions; +using SchoolDataModels.Models; + +namespace SchoolDatabaseImplement.Models +{ + public class Discipline : IDisciplineModel + { + public int ImplementerId { get; private set; } + public string Name { get; private set; } = string.Empty; + public double Price { get; set; } + + public DateOnly DateOfReceipt { get; private set; } + + public DateOnly DateOfPassage { get; private set; } + + + private Dictionary? _cachedClients = null; + [NotMapped] + public Dictionary StudentsModel => + _cachedClients ??= Students.Select(x => (StudentByDisciplineModel)x).ToDictionary(x => x.StudentId, x => x); + + public int Id { get; private set; } + + [Required] + public Implementer? Student { get; private set; } + [Required] + public List Students { get; private set; } = new(); + + [Required] + public List Requirements { get; private set; } = new(); + + public static Discipline Create(DisciplineBindingModel model) => + model.CastWithCommonProperties(); + + public static implicit operator DisciplineViewModel?(Discipline? model) + { + if (model == null) + { + return null; + } + + model._cachedClients = null; + var res = model.CastWithCommonProperties(); + res.DirectorLogin = model.Student?.Login ?? string.Empty; + res.RequirementViewModels = model.Requirements? + .Select(x => (RequirementViewModel)x.Requirement) + .ToList() ?? new(); + foreach (var studentByDiscipline in model.Students) + { + if (studentByDiscipline.Student != null) + { + res.StudenttViewModels.Add(studentByDiscipline.Student.GetViewModel()); + } + else + { + res.StudentViewModels = new(); + break; + } + } + return res; + } + + public void Update(DisciplineBindingModel model) + { + Price = model.Price; + DateOfPassage = model.DateOfPassage; + } + + public void UpdateClients(SchoolDB context, DisciplineBindingModel model) + { + var oldStudents = context.StudentsByDisciplines.Where(x => x.DisciplineId == model.Id).ToDictionary(x => x.StudentId, x => x); + var newStudents = model.StudentsModel.ToDictionary( + x => x.Key, + x => + { + var res = x.Value.CastWithCommonProperties(); + res.StudentId = x.Key; + res.DisciplineId = Id; + return res; + }); + context.RemoveRange(oldStudents.Where(x => !newStudents.ContainsKey(x.Key)).Select(x => x.Value)); + context.SaveChanges(); + context.AddRange (newStudents.Where(x => !oldStudents.ContainsKey(x.Key)).Select(x => x.Value)); + oldStudents + .Where(x => newStudents.ContainsKey(x.Key)) + .Select(x => x.Value).ToList() + .ForEach(x => x.DateOfClient = newStudents[x.StudentId].DateOfStudent); + context.SaveChanges(); + _cachedClients = null; + } + } +} diff --git a/School/SchoolDataBaseImplement/Models/Executor.cs b/School/SchoolDataBaseImplement/Models/Executor.cs new file mode 100644 index 0000000..d36d287 --- /dev/null +++ b/School/SchoolDataBaseImplement/Models/Executor.cs @@ -0,0 +1,32 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.ViewModels; +using SchoolDataModels; +using System.ComponentModel.DataAnnotations; +using SchoolContracts.Extensions; + +namespace SchoolDatabaseImplement.Models +{ + public class Executor : IExecutorModel + { + public int Id { get; private set; } + [Required] + public string FirstName { get; private set; } = string.Empty; + [Required] + public string LastName { get; private set; } = string.Empty; + [Required] + public string Login { get; private set; } = string.Empty; + [Required] + public string Password { get; private set; } = string.Empty; + + public string PhoneNumber { get; set; } = string.Empty; + + [Required] + public List? Students { get; private set; } + [Required] + public List? Requirements { get; private set; } + + public static Executor Create(ExecutorBindingModel model) => model.CastWithCommonProperties(); + + public static implicit operator ExecutorViewModel?(Executor? model) => model?.CastWithCommonProperties(); + } +} diff --git a/School/SchoolDataBaseImplement/Models/Implementer.cs b/School/SchoolDataBaseImplement/Models/Implementer.cs new file mode 100644 index 0000000..4f45276 --- /dev/null +++ b/School/SchoolDataBaseImplement/Models/Implementer.cs @@ -0,0 +1,34 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.Extensions; +using SchoolContracts.ViewModels; +using SchoolDataModels; +using System.ComponentModel.DataAnnotations; + +namespace SchoolDatabaseImplement.Models +{ + public class Implementer : IImplementerModel + { + public int Id { get; set; } + [Required] + public string FirstName { get; private set; } = string.Empty; + [Required] + public string LastName { get; private set; } = string.Empty; + + [Required] + public string Login { get; private set; } = string.Empty; + [Required] + public string Password { get; private set; } = string.Empty; + + public string PhoneNumber { get; set; } = string.Empty; + + [Required] + public List? Disciplines { get; private set; } + + public static Implementer Create(ImplementerBindingModel model) + { + return model.CastWithCommonProperties(); + } + + public static implicit operator ImplementerViewModel?(Implementer? model) => model?.CastWithCommonProperties(); + } +} diff --git a/School/SchoolDataBaseImplement/Models/Requirement.cs b/School/SchoolDataBaseImplement/Models/Requirement.cs new file mode 100644 index 0000000..99f8dc4 --- /dev/null +++ b/School/SchoolDataBaseImplement/Models/Requirement.cs @@ -0,0 +1,78 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.Extensions; +using SchoolContracts.ViewModels; +using SchoolDataModels; +using System.ComponentModel.DataAnnotations; +using SchoolDataModels.Models; + +namespace SchoolDatabaseImplement.Models +{ + public class Requirement : IRequirementModel + { + [Required] + public int ExecutorId { get; private set; } + + [Required] + public string NameOfRequirement { get; private set; } = string.Empty; + + public int Id { get; private set; } + + [Required] + public double Price { get; private set; } + + private Dictionary? _cachedDisciplines; + + public Dictionary DisciplinesModels => + _cachedDisciplines ??= Disciplines.Select(x => (RequirementByDisciplineModel)x).ToDictionary(x => x.DisciplineId, x => x); + + [Required] + public Executor? Executor { get; private set; } + + [Required] + public List Disciplines { get; private set; } = new(); + + public static Requirement Create(RequirementBindingModel model) => model.CastWithCommonProperties(); + + public static implicit operator RequirementViewModel(Requirement? model) + { + if (model == null) + { + throw new ArgumentNullException("Возникла ошибка при попытки получить View-модель из null-объекта", nameof(model)); + } + model._cachedDisciplines = null; + var result = model.CastWithCommonProperties(); + result.ExecutorLogin = model.Executor?.Login ?? string.Empty; + return result; + } + + public void Update(RequirementBindingModel model) + { + Price = model.Price; + } + + /// + /// Привязка требований к дисциплиным + /// + public void UpdateDisciplines(SchoolDB context, RequirementBindingModel model) + { + var oldDisciplines = context.RequirementByDisciplines.Where(x => x.DisciplineId == model.Id).ToDictionary(x => x.DisciplineId, x => x); + var newDisciplines = model.DisciplinesModels.ToDictionary( + x => x.Key, + x => + { + var res = x.Value.CastWithCommonProperties(); + res.RequirementId = model.Id; + res.DisciplineId = x.Key; + return res; + }); + context.RemoveRange(oldDisciplines.Where(x => !newDisciplines.ContainsKey(x.Key)).Select(x => x.Value)); + context.SaveChanges(); + context.AddRange (newDisciplines.Where(x => !oldDisciplines.ContainsKey(x.Key)).Select(x => x.Value)); + oldDisciplines.Where(x => newDisciplines.ContainsKey(x.Key)) + .Select(x => x.Value).ToList() + .ForEach(x => x.Count = newDisciplines[x.DisciplineId].Count); + context.SaveChanges(); + _cachedDisciplines = null; + } + } +} diff --git a/School/SchoolDataBaseImplement/Models/RequirementByDiscipline.cs b/School/SchoolDataBaseImplement/Models/RequirementByDiscipline.cs new file mode 100644 index 0000000..ec14d2c --- /dev/null +++ b/School/SchoolDataBaseImplement/Models/RequirementByDiscipline.cs @@ -0,0 +1,13 @@ +using System.ComponentModel.DataAnnotations; +using SchoolDataModels.ProxyModels; + +namespace SchoolDatabaseImplement.Models +{ + public class RequirementByDiscipline : RequirementByDisciplineModel + { + [Required] + public Requirement? Requirement { get; private set; } + [Required] + public Discipline? Discipline { get; set; } + } +} diff --git a/School/SchoolDataBaseImplement/Models/Student.cs b/School/SchoolDataBaseImplement/Models/Student.cs new file mode 100644 index 0000000..b7f962f --- /dev/null +++ b/School/SchoolDataBaseImplement/Models/Student.cs @@ -0,0 +1,50 @@ +using SchoolContracts.BindingModels; +using SchoolContracts.Extensions; +using SchoolContracts.ViewModels; +using SchoolDataModels; +using System.ComponentModel.DataAnnotations; + +namespace SchoolDatabaseImplement.Models +{ + public class Student : IStudentModel + { + [Required] + public int ExecutorId { get; private set; } + [Required] + public string Name { get; private set; } = string.Empty; + [Required] + public double Price { get; private set; } + [Required] + public int Course { get; private set; } + + public int Id { get; private set; } + [Required] + public Executor? Executor { get; private set; } + + [Required] + public List Disciplines { get; private set; } = new(); + + + public static Student Create(StudentBindingModel model) => model.CastWithCommonProperties(); + + public static implicit operator StudentViewModel?(Student? model) + { + if (model == null) + { + return null; + } + var res = model.CastWithCommonProperties(); + res.DirectorLogin = model.Executor?.Login ?? string.Empty; + res.Disciplines = model.Disciplines.Select(x => (DisciplineViewModel)x.Discipline).ToList(); + return res; + } + + public void Update(StudentBindingModel model) + { + Price = model.Price; + Course = model.Course; + } + + public StudentViewModel GetViewModel() => this.CastWithCommonProperties(); + } +} diff --git a/School/SchoolDataBaseImplement/Models/StudentByDiscipline.cs b/School/SchoolDataBaseImplement/Models/StudentByDiscipline.cs new file mode 100644 index 0000000..5558a74 --- /dev/null +++ b/School/SchoolDataBaseImplement/Models/StudentByDiscipline.cs @@ -0,0 +1,16 @@ +using System.ComponentModel.DataAnnotations; +using SchoolDataModels.Models; + +namespace SchoolDatabaseImplement.Models +{ + public class StudentByDiscipline : StudentByDisciplineModel + { + [Required] + public Student? Student { get; private set; } + [Required] + public Discipline? Discipline { get; private set; } + + [Required] + public List? Accounts { get; private set; } + } +} diff --git a/School/SchoolDataBaseImplement/SchoolDB.cs b/School/SchoolDataBaseImplement/SchoolDB.cs new file mode 100644 index 0000000..5681078 --- /dev/null +++ b/School/SchoolDataBaseImplement/SchoolDB.cs @@ -0,0 +1,33 @@ +using SchoolDatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; +using System.IO; + +namespace SchoolDatabaseImplement +{ + public class SchoolDB : DbContext + { + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + if (optionsBuilder.IsConfigured == false) + { + optionsBuilder.UseNpgsql(@" + Host=localhost; + Port=5432; + Database=University; + Username=postgres; + Password=1234; + Include Error Detail=true"); + } + base.OnConfiguring(optionsBuilder); + } + + public virtual DbSet Implementers { set; get; } + public virtual DbSet Requirements { set; get; } + public virtual DbSet RequirementByDisciplines { set; get; } + public virtual DbSet Executors { set; get; } + public virtual DbSet Students { set; get; } + public virtual DbSet StudentsByDisciplines { set; get; } + public virtual DbSet Accounts { set; get; } + public virtual DbSet Disciplines { set; get; } + } +} diff --git a/School/SchoolDataBaseImplement/SchoolDataBaseImplement.csproj b/School/SchoolDataBaseImplement/SchoolDataBaseImplement.csproj new file mode 100644 index 0000000..8c91214 --- /dev/null +++ b/School/SchoolDataBaseImplement/SchoolDataBaseImplement.csproj @@ -0,0 +1,16 @@ + + + + WinExe + net6.0-windows + enable + true + enable + + + + + + + + \ No newline at end of file