From 4fd4b0351fc45f26762fe878586290cfaa017ff9 Mon Sep 17 00:00:00 2001 From: Sergey Kozyrev Date: Thu, 23 May 2024 20:02:34 +0400 Subject: [PATCH 1/3] AllIndex + SomeImplementerData --- .../SearchModels/ImplementerSearchModel.cs | 1 + .../DatabaseImplement.csproj | 1 + .../Implements/DetailStorage.cs | 4 +- .../Implements/ImplementerStorage.cs | 2 +- .../Implements/ProductStorage.cs | 2 +- Course/ImplemenerLogic/DataToLogic.cs | 13 ++ Course/ImplemenerLogic/ImplemenerLogic.csproj | 14 ++ .../Controllers/HomeController.cs | 160 ++++++++++-------- Course/ImplementerApp/ImplementerApp.csproj | 2 + Course/ImplementerApp/ImplementerData.cs | 77 +++++++++ Course/ImplementerApp/Program.cs | 18 ++ Course/ImplementerApp/UserImplementer.cs | 9 + .../Views/Home/CreateDetail.cshtml | 11 +- .../Views/Home/CreateProduct.cshtml | 7 +- Course/ImplementerApp/Views/Home/Index.cshtml | 4 +- .../Views/Home/IndexDetail.cshtml | 7 +- .../Views/Home/IndexNonReg.cshtml | 10 ++ .../Views/Home/IndexProduct.cshtml | 8 +- .../Views/Home/IndexProduction.cshtml | 7 +- .../ImplementerApp/Views/Home/Privacy.cshtml | 1 + .../Views/Shared/_Layout.cshtml | 9 +- Course/ImplementerApp/log4net.config | 16 ++ 22 files changed, 292 insertions(+), 91 deletions(-) create mode 100644 Course/ImplemenerLogic/DataToLogic.cs create mode 100644 Course/ImplemenerLogic/ImplemenerLogic.csproj create mode 100644 Course/ImplementerApp/ImplementerData.cs create mode 100644 Course/ImplementerApp/UserImplementer.cs create mode 100644 Course/ImplementerApp/Views/Home/IndexNonReg.cshtml create mode 100644 Course/ImplementerApp/log4net.config diff --git a/Course/Contracts/SearchModels/ImplementerSearchModel.cs b/Course/Contracts/SearchModels/ImplementerSearchModel.cs index 4fba103..deb4f46 100644 --- a/Course/Contracts/SearchModels/ImplementerSearchModel.cs +++ b/Course/Contracts/SearchModels/ImplementerSearchModel.cs @@ -10,5 +10,6 @@ namespace Contracts.SearchModels { public int? Id { get; set; } public string? Login { get; set; } + public string? Password { get; set; } } } diff --git a/Course/DatabaseImplement/DatabaseImplement.csproj b/Course/DatabaseImplement/DatabaseImplement.csproj index b4206ce..dfc5a94 100644 --- a/Course/DatabaseImplement/DatabaseImplement.csproj +++ b/Course/DatabaseImplement/DatabaseImplement.csproj @@ -7,6 +7,7 @@ + diff --git a/Course/DatabaseImplement/Implements/DetailStorage.cs b/Course/DatabaseImplement/Implements/DetailStorage.cs index 2260591..27fd95b 100644 --- a/Course/DatabaseImplement/Implements/DetailStorage.cs +++ b/Course/DatabaseImplement/Implements/DetailStorage.cs @@ -22,7 +22,7 @@ namespace DatabaseImplement.Implements public DetailViewModel? GetElement(DetailSearchModel model) { using var context = new FactoryGoWorkDatabase(); - return context.Details.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + return context.Details.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Equals(model.Name)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } public List GetFilteredList(DetailSearchModel model) @@ -35,7 +35,7 @@ namespace DatabaseImplement.Implements if (model.DateFrom.HasValue) return context.Details.Where(x => x.UserId == model.Id).Where(x => x.DateCreate < model.DateTo && x.DateCreate > model.DateFrom).Select(x => x.GetViewModel).ToList(); else - return context.Details.Where(x => x.UserId == model.Id).Select(x => x.GetViewModel).ToList(); + return context.Details.Where(x => x.UserId == model.UserId).Select(x => x.GetViewModel).ToList(); } diff --git a/Course/DatabaseImplement/Implements/ImplementerStorage.cs b/Course/DatabaseImplement/Implements/ImplementerStorage.cs index c96278d..05db08c 100644 --- a/Course/DatabaseImplement/Implements/ImplementerStorage.cs +++ b/Course/DatabaseImplement/Implements/ImplementerStorage.cs @@ -23,7 +23,7 @@ namespace DatabaseImplement.Implements { if (!model.Id.HasValue && string.IsNullOrEmpty(model.Login)) { return null; } using var context = new FactoryGoWorkDatabase(); - return context.Implementers.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) || (!string.IsNullOrEmpty(model.Login) && x.Login.Equals(model.Login)))?.GetViewModel; ; + return context.Implementers.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) || (!string.IsNullOrEmpty(model.Login) && !string.IsNullOrEmpty(model.Password) && x.Login.Equals(model.Login) && x.Password.Equals(model.Password)))?.GetViewModel; ; } public List GetFilteredList(ImplementerSearchModel model) diff --git a/Course/DatabaseImplement/Implements/ProductStorage.cs b/Course/DatabaseImplement/Implements/ProductStorage.cs index 93ad8c6..31c1fd9 100644 --- a/Course/DatabaseImplement/Implements/ProductStorage.cs +++ b/Course/DatabaseImplement/Implements/ProductStorage.cs @@ -39,7 +39,7 @@ namespace DatabaseImplement.Implements else if (model.WorkerId.HasValue) return context.Products.Where(p => p.MachineId.HasValue).Include(p => p.Machine).ThenInclude(p => p.Workers).Where(x => x.Machine.Workers.FirstOrDefault(y => y.WorkerId == model.WorkerId) != null).Select(x => x.GetViewModel).ToList(); else - return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).Where(x => x.UserId == model.Id).Select(x => x.GetViewModel).ToList(); + return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).Where(x => x.UserId == model.UserId).Select(x => x.GetViewModel).ToList(); } public List GetFullList() diff --git a/Course/ImplemenerLogic/DataToLogic.cs b/Course/ImplemenerLogic/DataToLogic.cs new file mode 100644 index 0000000..19211af --- /dev/null +++ b/Course/ImplemenerLogic/DataToLogic.cs @@ -0,0 +1,13 @@ +using DatabaseImplement.Implements; +using BusinessLogic.BusinessLogic; + +namespace ImplemenerLogic +{ + public static class DataToLogic + { + public static DetailLogic detailLogic() + { + return + } + } +} diff --git a/Course/ImplemenerLogic/ImplemenerLogic.csproj b/Course/ImplemenerLogic/ImplemenerLogic.csproj new file mode 100644 index 0000000..b2c1bac --- /dev/null +++ b/Course/ImplemenerLogic/ImplemenerLogic.csproj @@ -0,0 +1,14 @@ + + + + net6.0 + enable + enable + + + + + + + + diff --git a/Course/ImplementerApp/Controllers/HomeController.cs b/Course/ImplementerApp/Controllers/HomeController.cs index 54266c8..7eb8774 100644 --- a/Course/ImplementerApp/Controllers/HomeController.cs +++ b/Course/ImplementerApp/Controllers/HomeController.cs @@ -5,82 +5,119 @@ using BusinessLogic.BusinessLogic; using Contracts.BusinessLogicsContracts; using Contracts.ViewModels; using DataModels.Models; +using Contracts.BindingModels; namespace ImplementerApp.Controllers { public class HomeController : Controller { private readonly ILogger _logger; - private readonly IDetailLogic _detailLogic; - private readonly IImplementerLogic _userLogic; - private readonly IProductLogic _productLogic; - private readonly IProductionLogic _productionLogic; - - - public HomeController(ILogger logger) + private readonly ImplementerData _data; + public HomeController(ILogger logger, ImplementerData data) { _logger = logger; + _data = data; + } + public IActionResult IndexNonReg() + { + if (UserImplementer.user == null) + return View(); + return RedirectToAction("Index"); } - public IActionResult Index() { + if (UserImplementer.user == null) + return RedirectToAction("IndexNonReg"); return View(); } + [HttpGet] public IActionResult Enter() { - return View(); + if (UserImplementer.user == null) + return View(); + return RedirectToAction("Index"); } + [HttpPost] + public void Enter(string login, string password) + { + var user = _data.Login(login, password); + if (user != null) + { + UserImplementer.user = user; + Response.Redirect("Index"); + } + } + [HttpGet] public IActionResult Register() { return View(); } + [HttpPost] + public void Register(string name, string login, string email, string password1, string password2) + { + if (password1 == password2 && _data.Register(new() { Email = email, Login = login, Name = name, Password = password1 })) + { + Response.Redirect("Index"); + } + } + [HttpGet] public IActionResult IndexDetail() { - var details = new List(); - details.Add(new DetailViewModel + if (UserImplementer.user != null) { - Id = 1, - Name = "Test", - Cost = 55.5, - UserId = 1 - }); - details.Add(new DetailViewModel - { - Id = 2, - Name = "Test1", - Cost = 32, - UserId = 2 - }); - return View(details); + var list = _data.GetDetails(UserImplementer.user.Id); + if (list != null) + return View(list); + return View(new List()); + } + return RedirectToAction("IndexNonReg"); } - public IActionResult CreateDetail() - { - return View(); + [HttpPost] + public void IndexDetail(int id) + { + if (UserImplementer.user != null) + { + _data.DeleteDetail(id); + } + Response.Redirect("IndexDetail"); + } + [HttpGet] + public IActionResult CreateDetail(int id) + { + if (id != 0) + { + var value = _data.GetDetail(id); + if (value != null) + return View(value); + } + return View(new DetailViewModel()); } - + [HttpPost] + public IActionResult CreateDetail(DetailBindingModel model) + { + if (model.Id == 0) + { + model.DateCreate = DateTime.Now; + model.UserId = UserImplementer.user!.Id; + if (_data.CreateDetail(model)) + return RedirectToAction("IndexDetail"); + } + else + { + if (_data.UpdateDetail(model)) + return RedirectToAction("IndexDetail"); + } + return View(); + } + [HttpGet] public IActionResult IndexProduct() { - List products = new List - { - new ProductViewModel - { - Id = 1, - Name = "Изделие 1", - Cost = 10.99, - UserId = 1, - MachineId = 1 - }, - new ProductViewModel - { - Id = 2, - Name = "Изделие 2", - Cost = 19.99, - UserId = 2, - MachineId = 2 - } - }; - return View(products); - } + if (UserImplementer.user != null) { + var products = _data.GetProducts(UserImplementer.user.Id); + return View(products); + } + return RedirectToAction("IndexNonReg"); + } public IActionResult CreateProduct() { var details = new List(); @@ -100,27 +137,16 @@ namespace ImplementerApp.Controllers }); return View(details); } + [HttpGet] public IActionResult IndexProduction() { - List productionViewModels = new List + if (UserImplementer.user != null) { - new ProductionViewModel - { - Id = 1, - Name = "Производство А", - Cost = 1000.00, - UserId = 1 - }, - new ProductionViewModel - { - Id = 2, - Name = "Производство Б", - Cost = 1500.00, - UserId = 2 - } - }; - return View(productionViewModels); - } + var productions = _data.GetProductions(UserImplementer.user.Id); + return View(productions); + } + return RedirectToAction("IndexNonReg"); + } public IActionResult CreateProduction() { var details = new List(); diff --git a/Course/ImplementerApp/ImplementerApp.csproj b/Course/ImplementerApp/ImplementerApp.csproj index cbd6681..1ab9af5 100644 --- a/Course/ImplementerApp/ImplementerApp.csproj +++ b/Course/ImplementerApp/ImplementerApp.csproj @@ -8,11 +8,13 @@ + + diff --git a/Course/ImplementerApp/ImplementerData.cs b/Course/ImplementerApp/ImplementerData.cs new file mode 100644 index 0000000..9a5b14c --- /dev/null +++ b/Course/ImplementerApp/ImplementerData.cs @@ -0,0 +1,77 @@ +using Contracts.BusinessLogicsContracts; +using Contracts.ViewModels; +using Contracts.BindingModels; +using Contracts.StoragesContracts; +using Contracts.SearchModels; + +namespace ImplementerApp +{ + public class ImplementerData + { + private readonly ILogger _logger; + private readonly IImplementerLogic _implementerLogic; + private readonly IDetailLogic _detailLogic; + private readonly IProductionLogic _productionLogic; + private readonly IProductLogic _productLogic; + + public ImplementerData(ILogger logger, IImplementerLogic implementerLogic, IDetailLogic detailLogic, IProductionLogic productionLogic, IProductLogic productLogic) + { + _logger = logger; + _implementerLogic = implementerLogic; + _detailLogic = detailLogic; + _productionLogic = productionLogic; + _productLogic = productLogic; + } + + public ImplementerViewModel? Login(string login, string password) + { + return _implementerLogic.ReadElement(new() + { + Login = login, + Password = password + }); + } + + public bool Register(ImplementerBindingModel model) + { + return _implementerLogic.Create(model); + } + + public bool UpdateUser(ImplementerBindingModel model) + { + return _implementerLogic.Update(model); + } + + public List? GetDetails(int userId) + { + return _detailLogic.ReadList(new DetailSearchModel() { UserId = userId }); + } + + public bool DeleteDetail(int detailId) + { + return _detailLogic.Delete(new() { Id = detailId }); + } + public bool CreateDetail(DetailBindingModel model) + { + return _detailLogic.Create(model); + } + public bool UpdateDetail(DetailBindingModel model) + { + return _detailLogic.Update(model); + } + public DetailViewModel? GetDetail(int id) + { + return _detailLogic.ReadElement(new() { Id= id }); + } + + public List? GetProducts(int userId) + { + return _productLogic.ReadList(new ProductSearchModel() { UserId = userId }); + } + + public List? GetProductions(int userId) + { + return _productionLogic.ReadList(new() { UserId = userId }); + } + } +} diff --git a/Course/ImplementerApp/Program.cs b/Course/ImplementerApp/Program.cs index 36efc00..463d0ba 100644 --- a/Course/ImplementerApp/Program.cs +++ b/Course/ImplementerApp/Program.cs @@ -1,9 +1,27 @@ +using BusinessLogic.BusinessLogic; using Contracts.BusinessLogicsContracts; +using Contracts.StoragesContracts; +using DatabaseImplement.Implements; +using ImplementerApp; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation(); +builder.Logging.SetMinimumLevel(LogLevel.Trace); +builder.Logging.AddLog4Net("log4net.config"); + +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); + + var app = builder.Build(); if (!app.Environment.IsDevelopment()) diff --git a/Course/ImplementerApp/UserImplementer.cs b/Course/ImplementerApp/UserImplementer.cs new file mode 100644 index 0000000..ea8c905 --- /dev/null +++ b/Course/ImplementerApp/UserImplementer.cs @@ -0,0 +1,9 @@ +using Contracts.ViewModels; + +namespace ImplementerApp +{ + public static class UserImplementer + { + public static ImplementerViewModel? user { get; set; } + } +} diff --git a/Course/ImplementerApp/Views/Home/CreateDetail.cshtml b/Course/ImplementerApp/Views/Home/CreateDetail.cshtml index bf68c93..bb0d71a 100644 --- a/Course/ImplementerApp/Views/Home/CreateDetail.cshtml +++ b/Course/ImplementerApp/Views/Home/CreateDetail.cshtml @@ -1,17 +1,20 @@ -@{ +@using Contracts.ViewModels; +@{ ViewData["Title"] = "CreateDetail"; } +@model DetailViewModel;
-

Создание детали

+

Деталь

+
Название:
-
+
Цена:
-
+
diff --git a/Course/ImplementerApp/Views/Home/CreateProduct.cshtml b/Course/ImplementerApp/Views/Home/CreateProduct.cshtml index 0033b22..aa11933 100644 --- a/Course/ImplementerApp/Views/Home/CreateProduct.cshtml +++ b/Course/ImplementerApp/Views/Home/CreateProduct.cshtml @@ -19,22 +19,21 @@ - + @foreach (var detail in Model) { - + } diff --git a/Course/ImplementerApp/Views/Home/Index.cshtml b/Course/ImplementerApp/Views/Home/Index.cshtml index b3e0f4b..bceb1e4 100644 --- a/Course/ImplementerApp/Views/Home/Index.cshtml +++ b/Course/ImplementerApp/Views/Home/Index.cshtml @@ -3,14 +3,12 @@ }
-

Приложение "Завод "Иди работать". Исполнитель"

+

Главное меню

diff --git a/Course/ImplementerApp/Views/Home/IndexDetail.cshtml b/Course/ImplementerApp/Views/Home/IndexDetail.cshtml index ac228d1..f24d465 100644 --- a/Course/ImplementerApp/Views/Home/IndexDetail.cshtml +++ b/Course/ImplementerApp/Views/Home/IndexDetail.cshtml @@ -18,7 +18,7 @@ return; }

- Создать деталь + Создать деталь

Выбор Название КоличествоУдалить
- - @detail.Name +
@@ -57,7 +57,10 @@ Изменить } diff --git a/Course/ImplementerApp/Views/Home/IndexNonReg.cshtml b/Course/ImplementerApp/Views/Home/IndexNonReg.cshtml new file mode 100644 index 0000000..3d737d5 --- /dev/null +++ b/Course/ImplementerApp/Views/Home/IndexNonReg.cshtml @@ -0,0 +1,10 @@ +@{ + ViewData["Title"] = "Home Page"; +} + + diff --git a/Course/ImplementerApp/Views/Home/IndexProduct.cshtml b/Course/ImplementerApp/Views/Home/IndexProduct.cshtml index 820b716..97ac210 100644 --- a/Course/ImplementerApp/Views/Home/IndexProduct.cshtml +++ b/Course/ImplementerApp/Views/Home/IndexProduct.cshtml @@ -10,7 +10,6 @@

Изделия

-ProductMachineAdd
@{ if (Model == null) @@ -19,7 +18,7 @@ ProductMachineAdd return; }

- Создать изделие + Создать изделие

- Удалить + + + +
@@ -64,7 +63,10 @@ ProductMachineAdd Изменить } diff --git a/Course/ImplementerApp/Views/Home/IndexProduction.cshtml b/Course/ImplementerApp/Views/Home/IndexProduction.cshtml index 6bdc916..3ef96cf 100644 --- a/Course/ImplementerApp/Views/Home/IndexProduction.cshtml +++ b/Course/ImplementerApp/Views/Home/IndexProduction.cshtml @@ -18,7 +18,7 @@ return; }

- Создать производство + Создать производство

- Удалить +
+ + +
@@ -57,7 +57,10 @@ Изменить } diff --git a/Course/ImplementerApp/Views/Home/Privacy.cshtml b/Course/ImplementerApp/Views/Home/Privacy.cshtml index dcde174..62b4e65 100644 --- a/Course/ImplementerApp/Views/Home/Privacy.cshtml +++ b/Course/ImplementerApp/Views/Home/Privacy.cshtml @@ -5,6 +5,7 @@

Личные данные

+
Логин:
diff --git a/Course/ImplementerApp/Views/Shared/_Layout.cshtml b/Course/ImplementerApp/Views/Shared/_Layout.cshtml index ca5b590..ee64ee1 100644 --- a/Course/ImplementerApp/Views/Shared/_Layout.cshtml +++ b/Course/ImplementerApp/Views/Shared/_Layout.cshtml @@ -1,4 +1,8 @@ - +@{ + ViewData["Name"] = UserImplementer.user == null ? "Пользователь" : UserImplementer.user.Name; +} + + @@ -13,7 +17,8 @@ diff --git a/Course/ImplementerApp/log4net.config b/Course/ImplementerApp/log4net.config new file mode 100644 index 0000000..1fd1998 --- /dev/null +++ b/Course/ImplementerApp/log4net.config @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file -- 2.25.1 From d748583b955063402b70a098d7abab93d0862a74 Mon Sep 17 00:00:00 2001 From: Sergey Kozyrev Date: Sat, 25 May 2024 21:36:21 +0400 Subject: [PATCH 2/3] CRUD base --- .../Controllers/HomeController.cs | 156 ++++++++++++------ Course/ImplementerApp/ImplementerData.cs | 34 ++++ .../Views/Home/CreateProduct.cshtml | 96 +++++++++-- .../Views/Home/CreateProduction.cshtml | 89 ++++++++-- 4 files changed, 304 insertions(+), 71 deletions(-) diff --git a/Course/ImplementerApp/Controllers/HomeController.cs b/Course/ImplementerApp/Controllers/HomeController.cs index 7eb8774..e8630a4 100644 --- a/Course/ImplementerApp/Controllers/HomeController.cs +++ b/Course/ImplementerApp/Controllers/HomeController.cs @@ -18,22 +18,23 @@ namespace ImplementerApp.Controllers _logger = logger; _data = data; } + private bool IsLoggedIn { get {return UserImplementer.user != null; } } public IActionResult IndexNonReg() { - if (UserImplementer.user == null) + if (!IsLoggedIn) return View(); return RedirectToAction("Index"); } public IActionResult Index() { - if (UserImplementer.user == null) + if (!IsLoggedIn) return RedirectToAction("IndexNonReg"); return View(); } [HttpGet] public IActionResult Enter() { - if (UserImplementer.user == null) + if (!IsLoggedIn) return View(); return RedirectToAction("Index"); } @@ -112,30 +113,60 @@ namespace ImplementerApp.Controllers [HttpGet] public IActionResult IndexProduct() { - if (UserImplementer.user != null) { - var products = _data.GetProducts(UserImplementer.user.Id); + if (IsLoggedIn) { + var products = _data.GetProducts(UserImplementer.user!.Id); return View(products); } return RedirectToAction("IndexNonReg"); } - public IActionResult CreateProduct() + [HttpPost] + public IActionResult IndexProduct(int id) + { + _data.DeleteProduct(id); + return RedirectToAction("IndexProduct"); + } + [HttpGet] + public IActionResult CreateProduct(int id) { - var details = new List(); - details.Add(new DetailViewModel - { - Id = 1, - Name = "Test", - Cost = 55.5, - UserId = 1 - }); - details.Add(new DetailViewModel - { - Id = 2, - Name = "Test1", - Cost = 32, - UserId = 2 - }); - return View(details); + var details = _data.GetDetails(UserImplementer.user!.Id); + ViewBag.AllDetails = details; + if (id != 0) + { + var value = _data.GetProduct(id); + if (value != null) + return View(value); + } + return View(new ProductViewModel()); + } + [HttpPost] + public IActionResult CreateProduct(int id, string title, int[] detailIds, int[] counts) + { + ProductBindingModel model = new ProductBindingModel(); + model.Id = id; + model.Name = title; + model.UserId = UserImplementer.user!.Id; + var details = _data.GetDetails(UserImplementer.user!.Id); + double sum = 0; + for (int i = 0; i < detailIds.Length; i++) + { + var detail = details!.FirstOrDefault(x => x.Id == detailIds[i])!; + if (counts[i] <= 0) + continue; + model.ProductDetails[detailIds[i]] = (detail, counts[i]); + sum += detail.Cost * counts[i]; + } + if (model.ProductDetails.Count == 0) + return RedirectToAction("IndexProduct"); + model.Cost = sum; + if (id != 0) + { + _data.UpdateProduct(model); + } + else + { + _data.CreateProduct(model); + } + return RedirectToAction("IndexProduct"); } [HttpGet] public IActionResult IndexProduction() @@ -147,37 +178,66 @@ namespace ImplementerApp.Controllers } return RedirectToAction("IndexNonReg"); } - public IActionResult CreateProduction() + [HttpPost] + public IActionResult IndexProduction(int id) + { + _data.DeleteProduction(id); + return RedirectToAction("IndexProduction"); + } + [HttpGet] + public IActionResult CreateProduction(int id) { - var details = new List(); - details.Add(new DetailViewModel + var details = _data.GetDetails(UserImplementer.user!.Id); + ViewBag.AllDetails = details; + if (id != 0) + { + var value = _data.GetProduction(id); + if (value != null) + return View(value); + } + return View(new ProductionViewModel()); + } + [HttpPost] + public IActionResult CreateProduction(int id, string title, int[] detailIds) + { + ProductionBindingModel model = new ProductionBindingModel(); + model.Id = id; + model.Name = title; + model.UserId = UserImplementer.user!.Id; + var details = _data.GetDetails(UserImplementer.user!.Id); + double sum = 0; + for (int i = 0; i < detailIds.Length; i++) { - Id = 1, - Name = "Test", - Cost = 55.5, - UserId = 1 - }); - details.Add(new DetailViewModel - { - Id = 2, - Name = "Test1", - Cost = 32, - UserId = 2 - }); - return View(details); + var detail = details!.FirstOrDefault(x => x.Id == detailIds[i])!; + model.ProductionDetails[detailIds[i]] = detail; + sum += detail.Cost; + } + model.Cost = sum; + bool changed = false; + if (model.ProductionDetails.Count > 0) + { + if (id != 0) + { + changed = _data.UpdateProduction(model); + } + else + { + changed = _data.CreateProduction(model); + } + } + if (changed) + return RedirectToAction("IndexProduction"); + else + { + ViewBag.AllDetails = details; + return View(model); + } } public IActionResult Privacy() { - ImplementerViewModel user = new() - { - Email = "mail@mail.ru", - Login = "Login", - Password = "password", - Name = "User" - - }; - - return View(user); + if (IsLoggedIn) + return View(UserImplementer.user); + return RedirectToAction("IndexNonReg"); } public IActionResult DetailTimeReport() { diff --git a/Course/ImplementerApp/ImplementerData.cs b/Course/ImplementerApp/ImplementerData.cs index 9a5b14c..a27ec5f 100644 --- a/Course/ImplementerApp/ImplementerData.cs +++ b/Course/ImplementerApp/ImplementerData.cs @@ -69,9 +69,43 @@ namespace ImplementerApp return _productLogic.ReadList(new ProductSearchModel() { UserId = userId }); } + public ProductViewModel? GetProduct(int id) + { + return _productLogic.ReadElement(new() { Id = id }); + } + + public bool UpdateProduct(ProductBindingModel model) + { + return _productLogic.Update(model); + } + public bool DeleteProduct(int productId) + { + return _productLogic.Delete(new() { Id = productId }); + } + public bool CreateProduct(ProductBindingModel model) + { + return _productLogic.Create(model); + } + public List? GetProductions(int userId) { return _productionLogic.ReadList(new() { UserId = userId }); } + public ProductionViewModel? GetProduction(int id) + { + return _productionLogic.ReadElement(new() { Id = id }); + } + public bool CreateProduction(ProductionBindingModel model) + { + return _productionLogic.Create(model); + } + public bool UpdateProduction(ProductionBindingModel model) + { + return _productionLogic.Update(model); + } + public bool DeleteProduction(int productionId) + { + return _productionLogic.Delete(new() { Id = productionId}); + } } } diff --git a/Course/ImplementerApp/Views/Home/CreateProduct.cshtml b/Course/ImplementerApp/Views/Home/CreateProduct.cshtml index aa11933..985149c 100644 --- a/Course/ImplementerApp/Views/Home/CreateProduct.cshtml +++ b/Course/ImplementerApp/Views/Home/CreateProduct.cshtml @@ -1,18 +1,19 @@ @using Contracts.ViewModels -@model List +@model ProductViewModel; @{ - ViewData["Title"] = "CreateProduct"; + ViewData["Title"] = "CreateProduct"; + ViewBag.Details = Model.DetailProducts; }
-

Создание изделия

+

Создание изделия

-
-
Название:
-
-
+
+
Название:
+
+
Детали
@@ -21,24 +22,38 @@
+ - @foreach (var detail in Model) + @foreach (var detail in ViewBag.Details) { - - + + + }
- Удалить +
+ + +
Название КоличествоСтоимость Удалить
@detail.Name
- + + @detail.Value.Item1.Name + + @detail.Value.Item1.Cost +
+ +
Сумма:
@@ -54,6 +69,61 @@ \ No newline at end of file + diff --git a/Course/ImplementerApp/Views/Home/CreateProduction.cshtml b/Course/ImplementerApp/Views/Home/CreateProduction.cshtml index de8b108..01e5847 100644 --- a/Course/ImplementerApp/Views/Home/CreateProduction.cshtml +++ b/Course/ImplementerApp/Views/Home/CreateProduction.cshtml @@ -1,9 +1,10 @@ @using Contracts.ViewModels -@model List +@model ProductionViewModel @{ ViewData["Title"] = "CreateProduction"; + ViewBag.Details = Model.DetailProductions; }

Создание производства

@@ -11,31 +12,42 @@
Название:
-
+
-
Details
+
Детали
- + + - @foreach (var detail in Model) + @foreach (var detail in ViewBag.Details) { - + - + + }
Выбор НазваниеСтоимостьУдалить
- + + @detail.Value.Name @detail.Name@detail.Value.Cost
+ +
Сумма:
@@ -51,6 +63,63 @@ \ No newline at end of file + -- 2.25.1 From 613d84a9012aefaf59cdd96d655ddcff96bb1786 Mon Sep 17 00:00:00 2001 From: Sergey Kozyrev Date: Sun, 26 May 2024 23:23:24 +0400 Subject: [PATCH 3/3] Word+Excel files AddFirstReport --- Course/BusinessLogic/BusinessLogic.csproj | 2 + .../OfficePackage/AbstractSaveToExcel.cs | 84 ++++++ .../OfficePackage/AbstractSaveToPdf.cs | 48 +++ .../OfficePackage/AbstractSaveToWord.cs | 46 +++ .../HelperEnums/ExcelStyleInfoType.cs | 10 + .../HelperEnums/PdfParagraphAlignmentType.cs | 9 + .../HelperEnums/WordJustificationType.cs | 8 + .../HelperModels/ExcelCellParameters.cs | 14 + .../OfficePackage/HelperModels/ExcelInfo.cs | 11 + .../HelperModels/ExcelMergeParameters.cs | 10 + .../OfficePackage/HelperModels/PdfInfo.cs | 13 + .../HelperModels/PdfParagraph.cs | 11 + .../HelperModels/PdfRowParameters.cs | 11 + .../OfficePackage/HelperModels/WordInfo.cs | 9 + .../HelperModels/WordParagraph.cs | 9 + .../HelperModels/WordTextProperties.cs | 11 + .../OfficePackage/Implements/SaveToExcel.cs | 283 ++++++++++++++++++ .../OfficePackage/Implements/SaveToPdf.cs | 114 +++++++ .../OfficePackage/Implements/SaveToWord.cs | 121 ++++++++ .../Contracts/ViewModels/ProductViewModel.cs | 1 + .../Implements/DetailStorage.cs | 2 +- .../Implements/ProductStorage.cs | 6 +- Course/DatabaseImplement/Models/Product.cs | 5 +- .../Controllers/HomeController.cs | 117 +++++--- Course/ImplementerApp/ImplementerApp.csproj | 1 + Course/ImplementerApp/ImplementerData.cs | 35 ++- Course/ImplementerApp/Program.cs | 11 +- .../Views/Home/CreateDetail.cshtml | 68 +++-- .../Views/Home/CreateProduct.cshtml | 66 +++- .../Views/Home/CreateProduction.cshtml | 57 +++- .../Views/Home/DetailTimeChoose.cshtml | 76 +++++ Course/ImplementerApp/Views/Home/Index.cshtml | 2 + .../Views/Home/IndexProduct.cshtml | 6 + .../ImplementerApp/Views/Home/Privacy.cshtml | 107 +++++-- .../Views/Home/ProductMachineAdd.cshtml | 7 +- .../ImplementerApp/Views/Home/Register.cshtml | 126 ++++++-- .../Views/Home/ReportsMenu.cshtml | 2 +- 37 files changed, 1366 insertions(+), 153 deletions(-) create mode 100644 Course/BusinessLogic/OfficePackage/AbstractSaveToExcel.cs create mode 100644 Course/BusinessLogic/OfficePackage/AbstractSaveToPdf.cs create mode 100644 Course/BusinessLogic/OfficePackage/AbstractSaveToWord.cs create mode 100644 Course/BusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs create mode 100644 Course/BusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs create mode 100644 Course/BusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs create mode 100644 Course/BusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs create mode 100644 Course/BusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs create mode 100644 Course/BusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs create mode 100644 Course/BusinessLogic/OfficePackage/HelperModels/PdfInfo.cs create mode 100644 Course/BusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs create mode 100644 Course/BusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs create mode 100644 Course/BusinessLogic/OfficePackage/HelperModels/WordInfo.cs create mode 100644 Course/BusinessLogic/OfficePackage/HelperModels/WordParagraph.cs create mode 100644 Course/BusinessLogic/OfficePackage/HelperModels/WordTextProperties.cs create mode 100644 Course/BusinessLogic/OfficePackage/Implements/SaveToExcel.cs create mode 100644 Course/BusinessLogic/OfficePackage/Implements/SaveToPdf.cs create mode 100644 Course/BusinessLogic/OfficePackage/Implements/SaveToWord.cs create mode 100644 Course/ImplementerApp/Views/Home/DetailTimeChoose.cshtml diff --git a/Course/BusinessLogic/BusinessLogic.csproj b/Course/BusinessLogic/BusinessLogic.csproj index 75a93ab..ae71d8d 100644 --- a/Course/BusinessLogic/BusinessLogic.csproj +++ b/Course/BusinessLogic/BusinessLogic.csproj @@ -7,7 +7,9 @@ + + diff --git a/Course/BusinessLogic/OfficePackage/AbstractSaveToExcel.cs b/Course/BusinessLogic/OfficePackage/AbstractSaveToExcel.cs new file mode 100644 index 0000000..22b8e14 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/AbstractSaveToExcel.cs @@ -0,0 +1,84 @@ +using BusinessLogic.OfficePackage.HelperEnums; +using BusinessLogic.OfficePackage.HelperModels; + +namespace BusinessLogic.OfficePackage +{ + public abstract class AbstractSaveToExcel + { + public void CreateReport(ExcelInfo info) + { + CreateExcel(info); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = 1, + Text = info.Title, + StyleInfo = ExcelStyleInfoType.Title + }); + + MergeCells(new ExcelMergeParameters + { + CellFromName = "A1", + CellToName = "C1" + }); + + uint rowIndex = 2; + /* foreach (var pc in info.DressComponents) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = pc.DressName, + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + + foreach (var (Dress, Count) in pc.Components) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = Dress, + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = Count.ToString(), + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + rowIndex++; + } + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Итого", + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = pc.TotalCount.ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + }*/ + + SaveExcel(info); + } + + 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/Course/BusinessLogic/OfficePackage/AbstractSaveToPdf.cs b/Course/BusinessLogic/OfficePackage/AbstractSaveToPdf.cs new file mode 100644 index 0000000..71043d9 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/AbstractSaveToPdf.cs @@ -0,0 +1,48 @@ +using BusinessLogic.OfficePackage.HelperEnums; +using BusinessLogic.OfficePackage.HelperModels; +using System.Collections.Generic; +using System.Linq; + +namespace BusinessLogic.OfficePackage +{ + public abstract class AbstractSaveToPdf + { + public void CreateDoc(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 { "2cm", "3cm", "6cm", "4cm", "3cm" }); + + CreateRow(new PdfRowParameters + { + Texts = new List { "Номер", "Дата заказа", "Изделие", "Статус", "Сумма" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + /* foreach (var order in info.Orders) + { + CreateRow(new PdfRowParameters + { + Texts = new List { order.Id.ToString(), order.DateCreate.ToShortDateString(), order.DressName, order.Status.ToString(), order.Sum.ToString() }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + CreateParagraph(new PdfParagraph { Text = $"Итого: {info.Orders.Sum(x => x.Sum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right }); +*/ + SavePdf(info); + } + 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/Course/BusinessLogic/OfficePackage/AbstractSaveToWord.cs b/Course/BusinessLogic/OfficePackage/AbstractSaveToWord.cs new file mode 100644 index 0000000..8841686 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/AbstractSaveToWord.cs @@ -0,0 +1,46 @@ +using BusinessLogic.OfficePackage.HelperEnums; +using BusinessLogic.OfficePackage.HelperModels; + +namespace BusinessLogic.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.Both + } + }); + /*foreach (var dress in info.Dresses) + { + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> + { + ($"{dress.DressName} - ", new WordTextProperties { Size = "24", Bold = true}), + (dress.Price.ToString(), new WordTextProperties { Size = "24" }) + }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Both + } + }) ; + + }*/ + SaveWord(info); + } + protected abstract void CreateWord(WordInfo info); + protected abstract void CreateParagraph(WordParagraph paragraph); + protected abstract void SaveWord(WordInfo info); + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs b/Course/BusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs new file mode 100644 index 0000000..8013cb4 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs @@ -0,0 +1,10 @@ + +namespace BusinessLogic.OfficePackage.HelperEnums +{ + public enum ExcelStyleInfoType + { + Title, + Text, + TextWithBorder + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs b/Course/BusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs new file mode 100644 index 0000000..8895a3d --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs @@ -0,0 +1,9 @@ +namespace BusinessLogic.OfficePackage.HelperEnums +{ + public enum PdfParagraphAlignmentType + { + Center, + Left, + Right + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs b/Course/BusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs new file mode 100644 index 0000000..e459beb --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs @@ -0,0 +1,8 @@ +namespace BusinessLogic.OfficePackage.HelperEnums +{ + public enum WordJustificationType + { + Center, + Both + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs b/Course/BusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs new file mode 100644 index 0000000..ff71053 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs @@ -0,0 +1,14 @@ + +using BusinessLogic.OfficePackage.HelperEnums; + +namespace BusinessLogic.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/Course/BusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs b/Course/BusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs new file mode 100644 index 0000000..e04c2a4 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs @@ -0,0 +1,11 @@ +using Contracts.ViewModels; + +namespace BusinessLogic.OfficePackage.HelperModels +{ + public class ExcelInfo + { + public string FileName { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + //public List DressComponents { get; set; } = new(); + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs b/Course/BusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs new file mode 100644 index 0000000..e14eb60 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs @@ -0,0 +1,10 @@ + +namespace BusinessLogic.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/Course/BusinessLogic/OfficePackage/HelperModels/PdfInfo.cs b/Course/BusinessLogic/OfficePackage/HelperModels/PdfInfo.cs new file mode 100644 index 0000000..dfc02f9 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/PdfInfo.cs @@ -0,0 +1,13 @@ +using Contracts.ViewModels; + +namespace BusinessLogic.OfficePackage.HelperModels +{ + public class PdfInfo + { + public string FileName { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public DateTime DateFrom { get; set; } + public DateTime DateTo { get; set; } + //public List Orders { get; set; } = new(); + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs b/Course/BusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs new file mode 100644 index 0000000..c021855 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs @@ -0,0 +1,11 @@ +using BusinessLogic.OfficePackage.HelperEnums; + +namespace BusinessLogic.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/Course/BusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs b/Course/BusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs new file mode 100644 index 0000000..eb25d67 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs @@ -0,0 +1,11 @@ +using BusinessLogic.OfficePackage.HelperEnums; + +namespace BusinessLogic.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/Course/BusinessLogic/OfficePackage/HelperModels/WordInfo.cs b/Course/BusinessLogic/OfficePackage/HelperModels/WordInfo.cs new file mode 100644 index 0000000..14fabfc --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/WordInfo.cs @@ -0,0 +1,9 @@ +namespace BusinessLogic.OfficePackage.HelperModels +{ + public class WordInfo + { + public string FileName { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + //public List Dresses { get; set; } = new(); + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperModels/WordParagraph.cs b/Course/BusinessLogic/OfficePackage/HelperModels/WordParagraph.cs new file mode 100644 index 0000000..0b50a51 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/WordParagraph.cs @@ -0,0 +1,9 @@ + +namespace BusinessLogic.OfficePackage.HelperModels +{ + public class WordParagraph + { + public List<(string, WordTextProperties)> Texts { get; set; } = new(); + public WordTextProperties? TextProperties { get; set; } + } +} diff --git a/Course/BusinessLogic/OfficePackage/HelperModels/WordTextProperties.cs b/Course/BusinessLogic/OfficePackage/HelperModels/WordTextProperties.cs new file mode 100644 index 0000000..7eea2f6 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/HelperModels/WordTextProperties.cs @@ -0,0 +1,11 @@ +using BusinessLogic.OfficePackage.HelperEnums; + +namespace BusinessLogic.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/Course/BusinessLogic/OfficePackage/Implements/SaveToExcel.cs b/Course/BusinessLogic/OfficePackage/Implements/SaveToExcel.cs new file mode 100644 index 0000000..3d431d6 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/Implements/SaveToExcel.cs @@ -0,0 +1,283 @@ +using BusinessLogic.OfficePackage.HelperModels; +using BusinessLogic.OfficePackage.HelperEnums; +using DocumentFormat.OpenXml.Office2010.Excel; +using DocumentFormat.OpenXml.Office2013.Excel; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using DocumentFormat.OpenXml; + +namespace BusinessLogic.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.TextWithBorder => 1U, + ExcelStyleInfoType.Text => 0U, + _ => 0U, + }; + } + + protected override void CreateExcel(ExcelInfo info) + { + _spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook); + // Создаем книгу (в ней хранятся листы) + 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.Dispose(); + } + } +} diff --git a/Course/BusinessLogic/OfficePackage/Implements/SaveToPdf.cs b/Course/BusinessLogic/OfficePackage/Implements/SaveToPdf.cs new file mode 100644 index 0000000..15b36ac --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/Implements/SaveToPdf.cs @@ -0,0 +1,114 @@ +using BusinessLogic.OfficePackage.HelperEnums; +using BusinessLogic.OfficePackage.HelperModels; +using MigraDoc.DocumentObjectModel; +using MigraDoc.DocumentObjectModel.Tables; +using MigraDoc.Rendering; + +namespace BusinessLogic.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.Right => 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) + { + var renderer = new PdfDocumentRenderer(true) + { + Document = _document + }; + renderer.RenderDocument(); + renderer.PdfDocument.Save(info.FileName); + } + } +} \ No newline at end of file diff --git a/Course/BusinessLogic/OfficePackage/Implements/SaveToWord.cs b/Course/BusinessLogic/OfficePackage/Implements/SaveToWord.cs new file mode 100644 index 0000000..aac8665 --- /dev/null +++ b/Course/BusinessLogic/OfficePackage/Implements/SaveToWord.cs @@ -0,0 +1,121 @@ +using BusinessLogic.OfficePackage.HelperEnums; +using BusinessLogic.OfficePackage.HelperModels; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; + +namespace BusinessLogic.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) + { + _wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document); + 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.Dispose(); + } + } +} diff --git a/Course/Contracts/ViewModels/ProductViewModel.cs b/Course/Contracts/ViewModels/ProductViewModel.cs index 6ac9be4..8598255 100644 --- a/Course/Contracts/ViewModels/ProductViewModel.cs +++ b/Course/Contracts/ViewModels/ProductViewModel.cs @@ -17,6 +17,7 @@ namespace Contracts.ViewModels public double Cost { get; set; } public int UserId { get; set; } public int? MachineId { get; set; } + public string? MachineName { get; set; } public Dictionary DetailProducts { get; set; } = new(); } } diff --git a/Course/DatabaseImplement/Implements/DetailStorage.cs b/Course/DatabaseImplement/Implements/DetailStorage.cs index 27fd95b..2b888e5 100644 --- a/Course/DatabaseImplement/Implements/DetailStorage.cs +++ b/Course/DatabaseImplement/Implements/DetailStorage.cs @@ -33,7 +33,7 @@ namespace DatabaseImplement.Implements } using var context = new FactoryGoWorkDatabase(); if (model.DateFrom.HasValue) - return context.Details.Where(x => x.UserId == model.Id).Where(x => x.DateCreate < model.DateTo && x.DateCreate > model.DateFrom).Select(x => x.GetViewModel).ToList(); + return context.Details.Where(x => x.UserId == model.UserId).Where(x => x.DateCreate <= model.DateTo && x.DateCreate >= model.DateFrom).Select(x => x.GetViewModel).ToList(); else return context.Details.Where(x => x.UserId == model.UserId).Select(x => x.GetViewModel).ToList(); diff --git a/Course/DatabaseImplement/Implements/ProductStorage.cs b/Course/DatabaseImplement/Implements/ProductStorage.cs index 31c1fd9..da482e2 100644 --- a/Course/DatabaseImplement/Implements/ProductStorage.cs +++ b/Course/DatabaseImplement/Implements/ProductStorage.cs @@ -24,7 +24,7 @@ namespace DatabaseImplement.Implements public ProductViewModel? GetElement(ProductSearchModel model) { using var context = new FactoryGoWorkDatabase(); - return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).Include(p => p.Machine).FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } public List GetFilteredList(ProductSearchModel model) @@ -35,11 +35,11 @@ namespace DatabaseImplement.Implements } using var context = new FactoryGoWorkDatabase(); if (model.DetailId.HasValue) - return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).Where(x => x.UserId == model.Id).Where(x => x.Details.FirstOrDefault(y => y.DetailId == model.DetailId) != null).Select(x => x.GetViewModel).ToList(); + return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).Include(p => p.Machine).Where(x => x.UserId == model.UserId).Where(x => x.Details.FirstOrDefault(y => y.DetailId == model.DetailId) != null).Select(x => x.GetViewModel).ToList(); else if (model.WorkerId.HasValue) return context.Products.Where(p => p.MachineId.HasValue).Include(p => p.Machine).ThenInclude(p => p.Workers).Where(x => x.Machine.Workers.FirstOrDefault(y => y.WorkerId == model.WorkerId) != null).Select(x => x.GetViewModel).ToList(); else - return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).Where(x => x.UserId == model.UserId).Select(x => x.GetViewModel).ToList(); + return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).Include(p => p.Machine).Where(x => x.UserId == model.UserId).Select(x => x.GetViewModel).ToList(); } public List GetFullList() diff --git a/Course/DatabaseImplement/Models/Product.cs b/Course/DatabaseImplement/Models/Product.cs index 1543963..d27299b 100644 --- a/Course/DatabaseImplement/Models/Product.cs +++ b/Course/DatabaseImplement/Models/Product.cs @@ -72,7 +72,7 @@ namespace DatabaseImplement.Models return; Name = model.Name; Cost = model.Cost; - MachineId = model.MachineId; + MachineId = model.MachineId == null ? MachineId : model.MachineId; } public ProductViewModel GetViewModel => new() { @@ -81,7 +81,8 @@ namespace DatabaseImplement.Models Cost = Cost, UserId = UserId, DetailProducts = DetailProducts, - MachineId= MachineId + MachineId= MachineId, + MachineName = Machine == null ? null : Machine.Title }; public void UpdateDetails(FactoryGoWorkDatabase context, ProductBindingModel model) { diff --git a/Course/ImplementerApp/Controllers/HomeController.cs b/Course/ImplementerApp/Controllers/HomeController.cs index e8630a4..485577f 100644 --- a/Course/ImplementerApp/Controllers/HomeController.cs +++ b/Course/ImplementerApp/Controllers/HomeController.cs @@ -6,6 +6,7 @@ using Contracts.BusinessLogicsContracts; using Contracts.ViewModels; using DataModels.Models; using Contracts.BindingModels; +using DatabaseImplement.Models; namespace ImplementerApp.Controllers { @@ -19,6 +20,7 @@ namespace ImplementerApp.Controllers _data = data; } private bool IsLoggedIn { get {return UserImplementer.user != null; } } + private int UserId { get { return UserImplementer.user!.Id; } } public IActionResult IndexNonReg() { if (!IsLoggedIn) @@ -53,6 +55,11 @@ namespace ImplementerApp.Controllers { return View(); } + public IActionResult Logout() + { + UserImplementer.user = null; + return RedirectToAction("IndexNonReg"); + } [HttpPost] public void Register(string name, string login, string email, string password1, string password2) { @@ -233,32 +240,66 @@ namespace ImplementerApp.Controllers return View(model); } } + [HttpGet] public IActionResult Privacy() { if (IsLoggedIn) return View(UserImplementer.user); return RedirectToAction("IndexNonReg"); } - public IActionResult DetailTimeReport() + [HttpPost] + public IActionResult Privacy(int id, string login, string email, string password, string name) { - List detailTimeReports = new List - { - new DetailTimeReport - { - DetailName = "Деталь А", - Productions = new List { "Производство 1", "Производство 2" }, - Products = new List { "Машина X", "Машина Y" } - }, - new DetailTimeReport - { - DetailName = "Деталь B", - Productions = new List { "Производство 3", "Производство 4" }, - Products = new List { "Машина Z", "Машина W" } - } - }; - return View(detailTimeReports); + if (!IsLoggedIn) + return RedirectToAction("IndexNonReg"); + ImplementerBindingModel user = new() { Id = id, Login = login, Email = email, Password = password, Name = name }; + if (_data.UpdateUser(user)) + { + UserImplementer.user = new ImplementerViewModel { Id = id, Login = login, Password = password, Name = name, Email = email }; + } + return View(user); } - public IActionResult DetailWorkshopReport() + [HttpGet] + public IActionResult DetailTimeChoose() + { + if (!IsLoggedIn) + return RedirectToAction("IndexNonReg"); + return View(); + } + [HttpPost] + public IActionResult SendReport(DateTime startDate, DateTime endDate) + { + + return Ok(); + } + [HttpPost] + public IActionResult TimeReportWeb(DateTime startDate, DateTime endDate) + { + if (!IsLoggedIn) + return RedirectToAction("IndexNonReg"); + + + HttpContext.Session.SetString("StartDate", startDate.ToString()); + HttpContext.Session.SetString("EndDate", endDate.ToString()); + + return RedirectToAction("DetailTimeReport"); + } + [HttpGet] + public IActionResult DetailTimeReport() + { + var startDateStr = HttpContext.Session.GetString("StartDate"); + var endDateStr = HttpContext.Session.GetString("EndDate"); + var startDate = DateTime.Parse(startDateStr); + var endDate = DateTime.Parse(endDateStr).AddDays(1); + + var values = _data.GetTimeReport(startDate, endDate, UserId); + + ViewBag.StartDate = startDate; + ViewBag.EndDate = endDate; + + return View(values); + } + public IActionResult DetailWorkshopReport() { List detailWorkshopReports = new List { @@ -279,29 +320,29 @@ namespace ImplementerApp.Controllers { return View(); } - public IActionResult ProductMachineAdd() + [HttpGet] + public IActionResult ProductMachineAdd(int id) { - List machines = new List - { - new MachineViewModel - { - Id = 1, - Title = "Токарный станок", - Country = "Германия", - UserId = 1, - WorkerMachines = new() - }, - new MachineViewModel - { - Id = 2, - Title = "Фрезерный станок", - Country = "Япония", - UserId = 2, - WorkerMachines = new() - } - }; + if (!IsLoggedIn) + return RedirectToAction("IndexNonReg"); + var product = _data.GetProduct(id); + ViewBag.Product = product; + var machines = _data.GetMachines(); return View(machines); } + [HttpPost] + public IActionResult ProductMachineAdd(int productId, int machineId) + { + if (!IsLoggedIn) + return RedirectToAction("IndexNonReg"); + var product = _data.GetProduct(productId); + if (product == null) + return RedirectToAction("Index"); + ProductBindingModel productBinding = new() { Id = productId, Cost = product.Cost, Name = product.Name, UserId = product.UserId, ProductDetails = product.DetailProducts, MachineId = machineId }; + _data.UpdateProduct(productBinding); + return RedirectToAction("IndexProduct"); + + } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() diff --git a/Course/ImplementerApp/ImplementerApp.csproj b/Course/ImplementerApp/ImplementerApp.csproj index 1ab9af5..ac4c132 100644 --- a/Course/ImplementerApp/ImplementerApp.csproj +++ b/Course/ImplementerApp/ImplementerApp.csproj @@ -9,6 +9,7 @@ + diff --git a/Course/ImplementerApp/ImplementerData.cs b/Course/ImplementerApp/ImplementerData.cs index a27ec5f..6d872a4 100644 --- a/Course/ImplementerApp/ImplementerData.cs +++ b/Course/ImplementerApp/ImplementerData.cs @@ -13,14 +13,16 @@ namespace ImplementerApp private readonly IDetailLogic _detailLogic; private readonly IProductionLogic _productionLogic; private readonly IProductLogic _productLogic; + private readonly IMachineLogic _machineLogic; - public ImplementerData(ILogger logger, IImplementerLogic implementerLogic, IDetailLogic detailLogic, IProductionLogic productionLogic, IProductLogic productLogic) + public ImplementerData(ILogger logger, IImplementerLogic implementerLogic, IDetailLogic detailLogic, IProductionLogic productionLogic, IProductLogic productLogic, IMachineLogic machineLogic) { _logger = logger; _implementerLogic = implementerLogic; _detailLogic = detailLogic; _productionLogic = productionLogic; _productLogic = productLogic; + _machineLogic = machineLogic; } public ImplementerViewModel? Login(string login, string password) @@ -31,12 +33,10 @@ namespace ImplementerApp Password = password }); } - public bool Register(ImplementerBindingModel model) { return _implementerLogic.Create(model); } - public bool UpdateUser(ImplementerBindingModel model) { return _implementerLogic.Update(model); @@ -46,7 +46,6 @@ namespace ImplementerApp { return _detailLogic.ReadList(new DetailSearchModel() { UserId = userId }); } - public bool DeleteDetail(int detailId) { return _detailLogic.Delete(new() { Id = detailId }); @@ -68,12 +67,10 @@ namespace ImplementerApp { return _productLogic.ReadList(new ProductSearchModel() { UserId = userId }); } - public ProductViewModel? GetProduct(int id) { return _productLogic.ReadElement(new() { Id = id }); } - public bool UpdateProduct(ProductBindingModel model) { return _productLogic.Update(model); @@ -106,6 +103,32 @@ namespace ImplementerApp public bool DeleteProduction(int productionId) { return _productionLogic.Delete(new() { Id = productionId}); + } + + public List? GetMachines() + { + return _machineLogic.ReadList(null); + } + + public List GetTimeReport(DateTime? startDate, DateTime? endDate, int UserId) + { + var details = _detailLogic.ReadList(new() { DateFrom = startDate, DateTo = endDate, UserId = UserId }); + if (details == null) + return new(); + List detailTimeReports = new List(); + foreach (var detail in details) + { + var report = new DetailTimeReport(); + report.DetailName = detail.Name; + var products = _productLogic.ReadList(new() { DetailId = detail.Id, UserId = UserId }); + if (products != null) + report.Products = products.Select(p => p.Name).ToList(); + var productions = _productionLogic.ReadList(new() { DetailId = detail.Id, UserId = UserId }); + if (productions != null) + report.Productions = productions.Select(p => p.Name).ToList(); + detailTimeReports.Add(report); + } + return detailTimeReports; } } } diff --git a/Course/ImplementerApp/Program.cs b/Course/ImplementerApp/Program.cs index 463d0ba..cdae25d 100644 --- a/Course/ImplementerApp/Program.cs +++ b/Course/ImplementerApp/Program.cs @@ -3,6 +3,7 @@ using Contracts.BusinessLogicsContracts; using Contracts.StoragesContracts; using DatabaseImplement.Implements; using ImplementerApp; +using Microsoft.Extensions.Options; var builder = WebApplication.CreateBuilder(args); @@ -15,12 +16,20 @@ builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddTransient(); builder.Services.AddTransient(); +builder.Services.AddSession(options => +{ + options.IdleTimeout = TimeSpan.FromMinutes(30); + options.Cookie.HttpOnly = true; + options.Cookie.IsEssential = true; +}); var app = builder.Build(); @@ -34,7 +43,7 @@ app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); - +app.UseSession(); app.UseAuthorization(); app.MapControllerRoute( diff --git a/Course/ImplementerApp/Views/Home/CreateDetail.cshtml b/Course/ImplementerApp/Views/Home/CreateDetail.cshtml index bb0d71a..3bb2e17 100644 --- a/Course/ImplementerApp/Views/Home/CreateDetail.cshtml +++ b/Course/ImplementerApp/Views/Home/CreateDetail.cshtml @@ -1,23 +1,57 @@ @using Contracts.ViewModels; @{ - ViewData["Title"] = "CreateDetail"; + ViewData["Title"] = "CreateDetail"; } @model DetailViewModel;
-

Деталь

+

Деталь

- - -
-
Название:
-
-
-
-
Цена:
-
-
-
-
-
-
- \ No newline at end of file +
+ +
+
Название:
+
+ + +
+
+
+
Цена:
+
+ + +
+
+
+
+
+
+
+ + + diff --git a/Course/ImplementerApp/Views/Home/CreateProduct.cshtml b/Course/ImplementerApp/Views/Home/CreateProduct.cshtml index 985149c..17473cf 100644 --- a/Course/ImplementerApp/Views/Home/CreateProduct.cshtml +++ b/Course/ImplementerApp/Views/Home/CreateProduct.cshtml @@ -9,10 +9,13 @@

Создание изделия

-
+
Название:
-
+
+ + +
Детали
@@ -79,7 +82,7 @@ $('#sum').val(sum.toFixed(2)); } - $('.deleteDetail').click(function () { + $(document).on('click', '.deleteDetail', function () { var row = $(this).closest('tr'); row.remove(); updateSum(); @@ -96,34 +99,69 @@ var detailName = selectedDetail.text(); var detailCost = selectedDetail.data('cost'); + var exists = false; + $('#detailsTable tbody tr').each(function () { + if ($(this).data('detail-id') == detailId) { + exists = true; + return false; + } + }); + + if (exists) { + alert('Эта деталь уже добавлена.'); + return; + } + var newRow = ` ${detailName} - + ${detailCost} `; $('#detailsTable tbody').append(newRow); - $('.deleteDetail').off('click').on('click', function () { - var row = $(this).closest('tr'); - row.remove(); - updateSum(); - }); - - $('.detail-count').off('change').on('change', function () { - updateSum(); - }); - + updateSum(); $('#detailSelect').val(''); } else { alert('Выберите деталь для добавления'); } }); + + $('#productForm').submit(function (event) { + var title = $('#title').val(); + var isValid = true; + + $('#titleError').text(''); + if (title.length < 2 || title.length > 50) { + $('#titleError').text('Название должно быть от 2 до 50 символов.'); + isValid = false; + } + + var totalDetails = $('#detailsTable tbody tr').length; + if (totalDetails == 0) { + alert('Пожалуйста, добавьте хотя бы одну деталь.'); + isValid = false; + } + + $('#detailsTable tbody tr').each(function () { + var count = $(this).find('input[name="counts"]').val(); + if (count < 1) { + alert('Количество каждой детали должно быть не менее 1.'); + isValid = false; + return false; + } + }); + + if (!isValid) { + event.preventDefault(); + } + }); + updateSum(); }); diff --git a/Course/ImplementerApp/Views/Home/CreateProduction.cshtml b/Course/ImplementerApp/Views/Home/CreateProduction.cshtml index 01e5847..bb64739 100644 --- a/Course/ImplementerApp/Views/Home/CreateProduction.cshtml +++ b/Course/ImplementerApp/Views/Home/CreateProduction.cshtml @@ -9,10 +9,13 @@

Создание производства

- +
Название:
-
+
+ + +
Детали
@@ -30,7 +33,7 @@ { - + @detail.Value.Name @detail.Value.Cost @@ -72,7 +75,7 @@ $('#sum').val(sum.toFixed(2)); } - $('.deleteDetail').off('click').on('click', function () { + $(document).on('click', '.deleteDetail', function () { var row = $(this).closest('tr'); row.remove(); updateSum(); @@ -81,6 +84,7 @@ $('#addDetail').click(function () { var selectedDetail = $('#detailSelect option:selected'); if (selectedDetail.val()) { + var detailId = selectedDetail.val(); var exists = false; $('#detailsTable tbody tr').each(function () { if ($(this).data('detail-id') == detailId) { @@ -88,22 +92,24 @@ return false; } }); - if (exists) { return; } + if (exists) { + alert('Эта деталь уже добавлена.'); + return; + } - var detailId = selectedDetail.val(); var detailName = selectedDetail.text(); var detailCost = selectedDetail.data('cost'); var newRow = ` - - - - ${detailName} - - ${detailCost} - - - `; + + + + ${detailName} + + ${detailCost} + + + `; $('#detailsTable tbody').append(newRow); $('.deleteDetail').off('click').on('click', function () { @@ -120,6 +126,27 @@ } }); + $('#productionForm').submit(function (event) { + var title = $('#title').val(); + var isValid = true; + + $('#titleError').text(''); + if (title.length < 2 || title.length > 50) { + $('#titleError').text('Название должно быть от 2 до 50 символов.'); + isValid = false; + } + + var totalDetails = $('#detailsTable tbody tr').length; + if (totalDetails == 0) { + alert('Пожалуйста, добавьте хотя бы одну деталь.'); + isValid = false; + } + + if (!isValid) { + event.preventDefault(); + } + }); + updateSum(); }); diff --git a/Course/ImplementerApp/Views/Home/DetailTimeChoose.cshtml b/Course/ImplementerApp/Views/Home/DetailTimeChoose.cshtml new file mode 100644 index 0000000..b05f0e8 --- /dev/null +++ b/Course/ImplementerApp/Views/Home/DetailTimeChoose.cshtml @@ -0,0 +1,76 @@ +@{ + ViewData["Title"] = "Создание отчета"; +} + +
+

Создание отчета

+
+ +
+
+ +
+
+ + +
+
+
+
+ +
+
+ + +
+
+
+
+ +
+
+ + + + diff --git a/Course/ImplementerApp/Views/Home/Index.cshtml b/Course/ImplementerApp/Views/Home/Index.cshtml index bceb1e4..8c21602 100644 --- a/Course/ImplementerApp/Views/Home/Index.cshtml +++ b/Course/ImplementerApp/Views/Home/Index.cshtml @@ -10,5 +10,7 @@ Производства Личные данные Меню отчетов + Выйти +
diff --git a/Course/ImplementerApp/Views/Home/IndexProduct.cshtml b/Course/ImplementerApp/Views/Home/IndexProduct.cshtml index 97ac210..c75d75f 100644 --- a/Course/ImplementerApp/Views/Home/IndexProduct.cshtml +++ b/Course/ImplementerApp/Views/Home/IndexProduct.cshtml @@ -32,6 +32,9 @@ Цена + + Станок + Привязка станка к изделию @@ -56,6 +59,9 @@ @Html.DisplayFor(modelItem => item.Cost) + + @Html.DisplayFor(modelItem => item.MachineName) + Привязать станок diff --git a/Course/ImplementerApp/Views/Home/Privacy.cshtml b/Course/ImplementerApp/Views/Home/Privacy.cshtml index 62b4e65..fa5d1b6 100644 --- a/Course/ImplementerApp/Views/Home/Privacy.cshtml +++ b/Course/ImplementerApp/Views/Home/Privacy.cshtml @@ -2,28 +2,87 @@ ViewData["Title"] = "Privacy Policy"; }
-

Личные данные

+

Личные данные

-
- -
-
Логин:
-
-
-
-
Почта:
-
-
-
-
Пароль:
-
-
-
-
ФИО:
-
-
-
-
-
-
-
\ No newline at end of file +
+ +
+
Логин:
+
+ + +
+
+
+
Почта:
+
+ + +
+
+
+
Пароль:
+
+ + +
+
+
+
ФИО:
+
+ + +
+
+
+
+
+
+
+ + + diff --git a/Course/ImplementerApp/Views/Home/ProductMachineAdd.cshtml b/Course/ImplementerApp/Views/Home/ProductMachineAdd.cshtml index 37daa6a..2ecb2c8 100644 --- a/Course/ImplementerApp/Views/Home/ProductMachineAdd.cshtml +++ b/Course/ImplementerApp/Views/Home/ProductMachineAdd.cshtml @@ -7,7 +7,7 @@ }
-

Изделие - @ViewBag.Product

+

Изделие - @ViewBag.Product.Name

@@ -19,8 +19,9 @@
@machine.Title
-
- + + +
diff --git a/Course/ImplementerApp/Views/Home/Register.cshtml b/Course/ImplementerApp/Views/Home/Register.cshtml index 924d990..06d2595 100644 --- a/Course/ImplementerApp/Views/Home/Register.cshtml +++ b/Course/ImplementerApp/Views/Home/Register.cshtml @@ -1,33 +1,103 @@ @{ - ViewData["Title"] = "Register"; + ViewData["Title"] = "Register"; }
-

Регистрация

+

Регистрация

-
-
-
Имя:
-
-
-
-
Логин:
-
-
-
-
Почта:
-
-
-
-
Пароль:
-
-
-
-
Повтор пароля:
-
-
-
-
-
-
-
\ No newline at end of file +
+
+
Имя:
+
+ + +
+
+
+
Логин:
+
+ + +
+
+
+
Почта:
+
+ + +
+
+
+
Пароль:
+
+ + +
+
+
+
Повтор пароля:
+
+ + +
+
+
+
+
+
+
+ + + diff --git a/Course/ImplementerApp/Views/Home/ReportsMenu.cshtml b/Course/ImplementerApp/Views/Home/ReportsMenu.cshtml index caac5d0..dfbef55 100644 --- a/Course/ImplementerApp/Views/Home/ReportsMenu.cshtml +++ b/Course/ImplementerApp/Views/Home/ReportsMenu.cshtml @@ -6,6 +6,6 @@

Меню создания отчетов

-- 2.25.1