From c1c043c6c334f62ee8b35b0a102542bbe5391e99 Mon Sep 17 00:00:00 2001 From: Salikh Date: Fri, 17 May 2024 03:17:15 +0400 Subject: [PATCH] first commit --- .../BusinessLogic/OrderLogic.cs | 187 +++----- .../BusinessLogic/ReportLogic.cs | 96 ++-- .../BusinessLogic/ShopLogic.cs | 109 +++-- .../OfficePackage/AbstractSaveToExcel.cs | 93 +++- .../OfficePackage/AbstractSaveToPdf.cs | 33 +- .../OfficePackage/AbstractSaveToWord.cs | 60 ++- .../OfficePackage/HelperModels/ExcelInfo.cs | 2 +- .../OfficePackage/HelperModels/ExcelShop.cs | 11 + .../HelperModels/PdfGroupedOrdersInfo.cs | 13 + .../OfficePackage/HelperModels/PdfInfo.cs | 2 +- .../OfficePackage/HelperModels/WordInfo.cs | 2 +- .../HelperModels/WordRowParameters.cs | 14 + .../HelperModels/WordShopInfo.cs | 16 + .../OfficePackage/IDocument.cs | 14 + .../OfficePackage/Implements/SaveToExcel.cs | 4 +- .../OfficePackage/Implements/SaveToPdf.cs | 4 +- .../OfficePackage/Implements/SaveToWord .cs | 76 ++- .../BindingModels/SupplyBindingModel.cs | 16 + .../BusinessLogicsContracts/IReportLogic.cs | 9 +- .../BusinessLogicsContracts/IShopLogic.cs | 10 +- .../SearchModels/SupplySearchModel.cs | 14 + .../StoragesContracts/IShopStorage.cs | 5 +- .../ViewModels/ReportGroupOrdersViewModel.cs | 15 + .../ViewModels/ReportShopsViewModel.cs | 9 + .../Models/ISupplyModel.cs | 15 + .../Implements/OrderStorage.cs | 116 +++-- .../Implements/ShopStorage.cs | 166 ++++--- .../20240516204547_ThirdMigtation.Designer.cs | 246 ++++++++++ ...ig.cs => 20240516204547_ThirdMigtation.cs} | 2 +- .../Models/Order.cs | 10 +- .../Models/Shop.cs | 23 +- .../Implements/ShopStorage .cs | 105 +++-- .../MotorPlantFileImplement/Models/Shop.cs | 7 +- .../Implements/OrderStorage.cs | 2 +- .../Implements/ShopStorage.cs | 13 +- .../MotorPlantView/FormMain.Designer.cs | 98 +++- MotorPlant/MotorPlantView/FormMain.cs | 114 ++++- .../FormReportGroupedOrders.Designer.cs | 86 ++++ .../MotorPlantView/FormReportGroupedOrders.cs | 80 ++++ .../FormReportGroupedOrders.resx | 120 +++++ .../MotorPlantView/FormReportShop.Designer.cs | 116 +++++ MotorPlant/MotorPlantView/FormReportShop.cs | 78 ++++ MotorPlant/MotorPlantView/FormReportShop.resx | 120 +++++ MotorPlant/MotorPlantView/FormSell.cs | 67 ++- MotorPlant/MotorPlantView/FormSupply.cs | 45 +- MotorPlant/MotorPlantView/Program.cs | 9 + .../MotorPlantView/ReportGroupedOrders.rdlc | 441 ++++++++++++++++++ 47 files changed, 2356 insertions(+), 537 deletions(-) create mode 100644 MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelShop.cs create mode 100644 MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfGroupedOrdersInfo.cs create mode 100644 MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordRowParameters.cs create mode 100644 MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordShopInfo.cs create mode 100644 MotorPlant/MotorPlantBusinessLogic/OfficePackage/IDocument.cs create mode 100644 MotorPlant/MotorPlantContracts/BindingModels/SupplyBindingModel.cs create mode 100644 MotorPlant/MotorPlantContracts/SearchModels/SupplySearchModel.cs create mode 100644 MotorPlant/MotorPlantContracts/ViewModels/ReportGroupOrdersViewModel.cs create mode 100644 MotorPlant/MotorPlantContracts/ViewModels/ReportShopsViewModel.cs create mode 100644 MotorPlant/MotorPlantDataModels/Models/ISupplyModel.cs create mode 100644 MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.Designer.cs rename MotorPlant/MotorPlantDatabaseImplement/Migrations/{20240411140319_NewMig.cs => 20240516204547_ThirdMigtation.cs} (99%) create mode 100644 MotorPlant/MotorPlantView/FormReportGroupedOrders.Designer.cs create mode 100644 MotorPlant/MotorPlantView/FormReportGroupedOrders.cs create mode 100644 MotorPlant/MotorPlantView/FormReportGroupedOrders.resx create mode 100644 MotorPlant/MotorPlantView/FormReportShop.Designer.cs create mode 100644 MotorPlant/MotorPlantView/FormReportShop.cs create mode 100644 MotorPlant/MotorPlantView/FormReportShop.resx create mode 100644 MotorPlant/MotorPlantView/ReportGroupedOrders.rdlc diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs index c3322c1..3277e2f 100644 --- a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs @@ -14,15 +14,12 @@ namespace MotorPlantBusinessLogic.BusinessLogics private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; private readonly IShopStorage _shopStorage; - private readonly IShopLogic _shopLogic; - private readonly IEngineStorage _engineStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IEngineStorage engineStorage) + + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IShopStorage shopStorage) { _logger = logger; _orderStorage = orderStorage; _shopStorage = shopStorage; - _shopLogic = shopLogic; - _engineStorage = engineStorage; } public List? ReadList(OrderSearchModel? model) @@ -38,22 +35,31 @@ namespace MotorPlantBusinessLogic.BusinessLogics return list; } - private void CheckModel(OrderBindingModel model) + private void CheckModel(OrderBindingModel model, bool WithParams = true) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - if (model.Count <= 0) - { - throw new ArgumentNullException("Количество заказов должно быть больше нуля"); - } - if (model.Sum <= 0) - { - throw new ArgumentNullException("Цена заказа должна быть больше нуля"); - } - _logger.LogInformation("Order. OrderId:{Id}. Sum:{Sum}", model.Id, model.Sum); - } + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!WithParams) + { + return; + } + if (model.Count <= 0) + { + throw new ArgumentException("Количество движков в заказе не может быть меньше 1", nameof(model.Count)); + } + if (model.Sum <= 0) + { + throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum)); + } + if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) + { + throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}"); + } + _logger.LogInformation("Pizza. PizzaId:{PizzaId}.Count:{Count}.Sum:{Sum}Id:{Id}", + model.EngineId, model.Count, model.Sum, model.Id); + } public bool CreateOrder(OrderBindingModel model) { @@ -72,38 +78,38 @@ namespace MotorPlantBusinessLogic.BusinessLogics } - private bool ChangeStatus(OrderBindingModel model, OrderStatus status) + private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus) { - var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); - if (element == null) - { - _logger.LogWarning("Find order failed"); - return false; - } - if (element.Status != status - 1) - { - _logger.LogWarning("Status change failed"); - throw new InvalidOperationException("Невозможно перевести состояние заказа"); - } - if (status == OrderStatus.Готов) - { - var engine = _engineStorage.GetElement(new EngineSearchModel() { Id = model.EngineId }); - if (engine == null) - { - _logger.LogWarning("Status change error. Engine not found"); - return false; - } - if (!CheckSupply(engine, model.Count)) - { - _logger.LogWarning("Status change error. Shop doesnt have engines"); - return false; - } - } - model.Status = status; - if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; - _orderStorage.Update(model); - return true; - } + CheckModel(model, false); + var element = _orderStorage.GetElement(new OrderSearchModel() + { + Id = model.Id + }); + if (element == null) + { + throw new ArgumentNullException(nameof(element)); + } + model.DateCreate = element.DateCreate; + model.EngineId = element.EngineId; + model.DateImplement = element.DateImplement; + model.Status = element.Status; + model.Count = element.Count; + model.Sum = element.Sum; + if (requiredStatus - model.Status == 1) + { + model.Status = requiredStatus; + if (model.Status == OrderStatus.Выдан) + model.DateImplement = DateTime.Now; + if (_orderStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); + throw new ArgumentException($"Невозможно присвоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); + } public bool TakeOrderInWork(OrderBindingModel model) { @@ -117,67 +123,24 @@ namespace MotorPlantBusinessLogic.BusinessLogics public bool DeliveryOrder(OrderBindingModel model) { - return ChangeStatus(model, OrderStatus.Выдан); - } + var order = _orderStorage.GetElement(new OrderSearchModel + { + Id = model.Id, + }); + if (order == null) + { + throw new ArgumentNullException(nameof(order)); + } + if (!_shopStorage.RestockingShops(new SupplyBindingModel + { + EngineId = order.EngineId, + Count = order.Count + })) + { + throw new ArgumentException("Недостаточно места"); + } - public bool CheckSupply(IEngineModel engine, int count) - { - if (count <= 0) - { - _logger.LogWarning("Check supply operation error. Engine count < 0"); - return false; - } - int sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCount).Sum(); - int sumCount = _shopStorage.GetFullList().Select(x => x.ShopEngines.Select(y => y.Value.Item2).Sum()).Sum(); - int free = sumCapacity - sumCount; - - if (free < count) - { - _logger.LogWarning("Check supply error. No place for new Engines"); - return false; - } - foreach (var shop in _shopStorage.GetFullList()) - { - free = shop.MaxCount; - foreach (var doc in shop.ShopEngines) - { - free -= doc.Value.Item2; - } - if (free == 0) - { - continue; - } - if (free >= count) - { - if (_shopLogic.MakeSupply(new() - { - Id = shop.Id - }, engine, count)) - { - count = 0; - } - else - { - _logger.LogWarning("Supply error"); - return false; - } - } - else - { - if (_shopLogic.MakeSupply(new() { Id = shop.Id }, engine, free)) - count -= free; - else - { - _logger.LogWarning("Supply error"); - return false; - } - } - if (count <= 0) - { - return true; - } - } - return false; - } + return ChangeStatus(model, OrderStatus.Выдан); + } } } diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ReportLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ReportLogic.cs index 9483f6d..a9e051d 100644 --- a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ReportLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ReportLogic.cs @@ -1,15 +1,10 @@ -using MotorPlantBusinessLogic.OfficePackage.HelperModels; -using MotorPlantBusinessLogic.OfficePackage; +using MotorPlantBusinessLogic.OfficePackage; +using MotorPlantBusinessLogic.OfficePackage.HelperModels; using MotorPlantContracts.BindingModels; using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.SearchModels; using MotorPlantContracts.StoragesContracts; using MotorPlantContracts.ViewModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace MotorPlantBusinessLogic.BusinessLogic { @@ -17,22 +12,25 @@ namespace MotorPlantBusinessLogic.BusinessLogic { private readonly IComponentStorage _componentStorage; - private readonly IEngineStorage _engineStorage; + private readonly IEngineStorage _engineStorage; private readonly IOrderStorage _orderStorage; + private readonly IShopStorage _shopStorage; + private readonly AbstractSaveToExcel _saveToExcel; private readonly AbstractSaveToWord _saveToWord; private readonly AbstractSaveToPdf _saveToPdf; - public ReportLogic(IEngineStorage engineStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, + public ReportLogic(IEngineStorage engineStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, IShopStorage shopStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf) { _engineStorage = engineStorage; - _componentStorage = componentStorage; - _orderStorage = orderStorage; + _componentStorage = componentStorage; + _orderStorage = orderStorage; + _shopStorage = shopStorage; _saveToExcel = saveToExcel; _saveToWord = saveToWord; @@ -42,28 +40,12 @@ namespace MotorPlantBusinessLogic.BusinessLogic public List GetEngineComponents() { - var engines = _engineStorage.GetFullList(); - - var list = new List(); - - foreach (var engine in engines) + return _engineStorage.GetFullList().Select(x => new ReportEngineComponentViewModel { - var record = new ReportEngineComponentViewModel - { - EngineName = engine.EngineName, - Components = new List<(string Component, int Count)>(), - TotalCount = 0, - }; - foreach (var component in engine.EngineComponents) - { - record.Components.Add(new(component.Value.Item1.ComponentName, component.Value.Item2)); - record.TotalCount += component.Value.Item2; - } - - list.Add(record); - } - - return list; + EngineName = x.EngineName, + Components = x.EngineComponents.Select(x => (x.Value.Item1.ComponentName, x.Value.Item2)).ToList(), + TotalCount = x.EngineComponents.Select(x => x.Value.Item2).Sum() + }).ToList(); } public List GetOrders(ReportBindingModel model) @@ -111,5 +93,55 @@ namespace MotorPlantBusinessLogic.BusinessLogic Orders = GetOrders(model) }); } + + public List GetShops() + { + return _shopStorage.GetFullList().Select(x => new ReportShopsViewModel + { + ShopName = x.ShopName, + Engines = x.ShopEngines.Select(x => (x.Value.Item1.EngineName, x.Value.Item2)).ToList(), + TotalCount = x.ShopEngines.Select(x => x.Value.Item2).Sum() + }).ToList(); + } + + public List GetGroupedOrders() + { + return _orderStorage.GetFullList().GroupBy(x => x.DateCreate.Date).Select(x => new ReportGroupOrdersViewModel + { + Date = x.Key, + OrdersCount = x.Count(), + OrdersSum = x.Select(y => y.Sum).Sum() + }).ToList(); + } + + public void SaveShopsToWordFile(ReportBindingModel model) + { + _saveToWord.CreateShopsDoc(new WordShopInfo + { + FileName = model.FileName, + Title = "Список магазинов", + Shops = _shopStorage.GetFullList() + }); + } + + public void SaveShopsToExcelFile(ReportBindingModel model) + { + _saveToExcel.CreateShopEnginesReport(new ExcelShop + { + FileName = model.FileName, + Title = "Наполненость магазинов", + ShopEngines = GetShops() + }); + } + + public void SaveGroupedOrdersToPdfFile(ReportBindingModel model) + { + _saveToPdf.CreateGroupedOrdersDoc(new PdfGroupedOrdersInfo + { + FileName = model.FileName, + Title = "Список заказов сгруппированных по дате заказов", + GroupedOrders = GetGroupedOrders() + }); + } } } diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs index 35e65a1..a645ef6 100644 --- a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs @@ -17,11 +17,13 @@ namespace MotorPlantBusinessLogic.BusinessLogic { private readonly ILogger _logger; private readonly IShopStorage _shopStorage; + private readonly IEngineStorage _engineStorage; - public ShopLogic(ILogger logger, IShopStorage shopStorage) + public ShopLogic(ILogger logger, IShopStorage shopStorage, IEngineStorage engineStorage) { _logger = logger; _shopStorage = shopStorage; + _engineStorage = engineStorage; } public List ReadList(ShopSearchModel model) @@ -75,6 +77,7 @@ namespace MotorPlantBusinessLogic.BusinessLogic } return true; } + public bool Delete(ShopBindingModel model) { CheckModel(model, false); @@ -123,52 +126,70 @@ namespace MotorPlantBusinessLogic.BusinessLogic } } - public bool MakeSell(IEngineModel model, int count) - { - return _shopStorage.SellEngines(model, count); - } - - public bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count) + public bool MakeSupply(SupplyBindingModel model) { - if (model == null) - throw new ArgumentNullException(nameof(model)); - if (engine == null) - throw new ArgumentNullException(nameof(engine)); - if (count <= 0) - throw new ArgumentNullException("Количество должно быть положительным числом"); + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (model.Count <= 0) + { + throw new ArgumentException("Количество движков должно быть больше 0"); + } + var shop = _shopStorage.GetElement(new ShopSearchModel + { + Id = model.ShopId + }); + if (shop == null) + { + throw new ArgumentException("Магазина не существует"); + } + if (shop.ShopEngines.ContainsKey(model.EngineId)) + { + var oldValue = shop.ShopEngines[model.EngineId]; + oldValue.Item2 += model.Count; + shop.ShopEngines[model.EngineId] = oldValue; + } + else + { + var pizza = _engineStorage.GetElement(new EngineSearchModel + { + Id = model.EngineId + }); + if (pizza == null) + { + throw new ArgumentException($"Поставка: Товар с id:{model.EngineId} не найденн"); + } + shop.ShopEngines.Add(model.EngineId, (pizza, model.Count)); + } - ShopViewModel? curModel = _shopStorage.GetElement(model); - _logger.LogInformation("Make Supply. Id: {Id}. ShopName: {Name}", model.Id, model.Name); - if (curModel == null) - throw new ArgumentNullException(nameof(curModel)); + _shopStorage.Update(new ShopBindingModel() + { + Id = shop.Id, + ShopName = shop.ShopName, + Adress = shop.Adress, + DateOpen = shop.DateOpen, + ShopEngines = shop.ShopEngines, + MaxCount = shop.MaxCount, + }); - var countItems = curModel.ShopEngines.Select(x => x.Value.Item2).Sum(); - if (curModel.MaxCount - countItems < count) - { - _logger.LogWarning("Shop is overflowed"); - return false; - } + return true; + } - if (curModel.ShopEngines.TryGetValue(engine.Id, out var pair)) - { - curModel.ShopEngines[engine.Id] = (pair.Item1, pair.Item2 + count); - _logger.LogInformation("Make Supply. Add Dress. ShopName: {ShopName}. DressName: {Name}. Count: {Count}", curModel.ShopName, pair.Item1, count + pair.Item2); - } - else - { - curModel.ShopEngines.Add(engine.Id, (engine, count)); - _logger.LogInformation("Make Supply. Add new Dress. ShopName: {ShopName}. DressName: {Name}. Count: {Count}", curModel.ShopName, pair.Item1, count); - } - - return Update(new() - { - Id = curModel.Id, - ShopName = curModel.ShopName, - DateOpen = curModel.DateOpen, - MaxCount = curModel.MaxCount, - Adress = curModel.Adress, - ShopEngines = curModel.ShopEngines, - }); - } + public bool MakeSell(SupplySearchModel model) + { + if (!model.EngineId.HasValue || !model.Count.HasValue) + { + return false; + } + _logger.LogInformation("Check pizza count in all shops"); + if (_shopStorage.SellEngines(model)) + { + _logger.LogInformation("Selling sucsess"); + return true; + } + _logger.LogInformation("Selling failed"); + return false; + } } } diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs index 30ff911..819aae3 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs @@ -84,28 +84,81 @@ namespace MotorPlantBusinessLogic.OfficePackage SaveExcel(info); } - /// - /// Создание excel-файла - /// - /// - protected abstract void CreateExcel(ExcelInfo info); + public void CreateShopEnginesReport(ExcelShop 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 sr in info.ShopEngines) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = sr.ShopName, + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + + foreach (var (Engine, Count) in sr.Engines) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = Engine, + 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 = sr.TotalCount.ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + } + + SaveExcel(info); + } + + protected abstract void CreateExcel(IDocument info); protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams); - - /// - /// Объединение ячеек - /// - /// protected abstract void MergeCells(ExcelMergeParameters excelParams); - - /// - /// Сохранение файла - /// - /// - protected abstract void SaveExcel(ExcelInfo info); + protected abstract void SaveExcel(IDocument info); } } diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs index b746823..1611779 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs @@ -48,11 +48,40 @@ namespace MotorPlantBusinessLogic.OfficePackage SavePdf(info); } + public void CreateGroupedOrdersDoc(PdfGroupedOrdersInfo info) + { + CreatePdf(info); + CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + + CreateTable(new List { "4cm", "3cm", "2cm" }); + CreateRow(new PdfRowParameters + { + Texts = new List { "Дата заказа", "Кол-во", "Сумма" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + + foreach (var groupedOrder in info.GroupedOrders) + { + CreateRow(new PdfRowParameters + { + Texts = new List { groupedOrder.Date.ToShortDateString(), groupedOrder.OrdersCount.ToString(), groupedOrder.OrdersSum.ToString() }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + + CreateParagraph(new PdfParagraph { Text = $"Итого: {info.GroupedOrders.Sum(x => x.OrdersSum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + + SavePdf(info); + } + /// /// Создание pdf-файла /// /// - protected abstract void CreatePdf(PdfInfo info); + protected abstract void CreatePdf(IDocument info); /// /// Создание параграфа с текстом @@ -78,6 +107,6 @@ namespace MotorPlantBusinessLogic.OfficePackage /// Сохранение файла /// /// - protected abstract void SavePdf(PdfInfo info); + protected abstract void SavePdf(IDocument info); } } diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs index 33a498c..7223858 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs @@ -41,23 +41,51 @@ namespace MotorPlantBusinessLogic.OfficePackage SaveWord(info); } - /// - /// Создание doc-файла - /// - /// - protected abstract void CreateWord(WordInfo info); + public void CreateShopsDoc(WordShopInfo 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 + } + }); - /// - /// Создание абзаца с текстом - /// - /// - /// + CreateTable(new List { "3000", "3000", "3000" }); + CreateRow(new WordRowParameters + { + Texts = new List { "Название", "Адрес", "Дата открытия" }, + TextProperties = new WordTextProperties + { + Size = "24", + Bold = true, + JustificationType = WordJustificationType.Center + } + }); + + foreach (var shop in info.Shops) + { + CreateRow(new WordRowParameters + { + Texts = new List { shop.ShopName, shop.Adress, shop.DateOpen.ToString() }, + TextProperties = new WordTextProperties + { + Size = "22", + JustificationType = WordJustificationType.Both + } + }); + } + + SaveWord(info); + } + + protected abstract void CreateWord(IDocument info); protected abstract void CreateParagraph(WordParagraph paragraph); - - /// - /// Сохранение файла - /// - /// - protected abstract void SaveWord(WordInfo info); + protected abstract void SaveWord(IDocument info); + protected abstract void CreateTable(List colums); + protected abstract void CreateRow(WordRowParameters rowParameters); } } diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs index 71b04fb..c32d036 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; namespace MotorPlantBusinessLogic.OfficePackage.HelperModels { - public class ExcelInfo + public class ExcelInfo : IDocument { public string FileName { get; set; } = string.Empty; diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelShop.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelShop.cs new file mode 100644 index 0000000..600eecf --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelShop.cs @@ -0,0 +1,11 @@ +using MotorPlantContracts.ViewModels; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperModels +{ + public class ExcelShop : IDocument + { + public string FileName { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public List ShopEngines { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfGroupedOrdersInfo.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfGroupedOrdersInfo.cs new file mode 100644 index 0000000..75c655a --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfGroupedOrdersInfo.cs @@ -0,0 +1,13 @@ +using MotorPlantContracts.ViewModels; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperModels +{ + public class PdfGroupedOrdersInfo : IDocument + { + 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 GroupedOrders { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs index 308fbe9..f919683 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; namespace MotorPlantBusinessLogic.OfficePackage.HelperModels { - public class PdfInfo + public class PdfInfo : IDocument { public string FileName { get; set; } = string.Empty; diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs index 2589b0c..0a03ba5 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs @@ -7,7 +7,7 @@ using System.Threading.Tasks; namespace MotorPlantBusinessLogic.OfficePackage.HelperModels { - public class WordInfo + public class WordInfo : IDocument { public string FileName { get; set; } = string.Empty; diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordRowParameters.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordRowParameters.cs new file mode 100644 index 0000000..7cb81a9 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordRowParameters.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperModels +{ + public class WordRowParameters + { + public List Texts { get; set; } = new(); + public WordTextProperties TextProperties { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordShopInfo.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordShopInfo.cs new file mode 100644 index 0000000..f781da1 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordShopInfo.cs @@ -0,0 +1,16 @@ +using MotorPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperModels +{ + public class WordShopInfo : IDocument + { + public string FileName { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public List Shops { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/IDocument.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/IDocument.cs new file mode 100644 index 0000000..1076a82 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/IDocument.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage +{ + public interface IDocument + { + public string FileName { get; set; } + public string Title { get; set; } + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToExcel.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToExcel.cs index 12f3ef8..3808437 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToExcel.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToExcel.cs @@ -151,7 +151,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements }; } - protected override void CreateExcel(ExcelInfo info) + protected override void CreateExcel(IDocument info) { _spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook); // Создаем книгу (в ней хранятся листы) @@ -280,7 +280,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements mergeCells.Append(mergeCell); } - protected override void SaveExcel(ExcelInfo info) + protected override void SaveExcel(IDocument info) { if (_spreadsheetDocument == null) { diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToPdf.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToPdf.cs index 238d541..f1d91ab 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToPdf.cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToPdf.cs @@ -34,7 +34,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements style.Font.Bold = true; } - protected override void CreatePdf(PdfInfo info) + protected override void CreatePdf(IDocument info) { _document = new Document(); DefineStyles(_document); @@ -96,7 +96,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements } } - protected override void SavePdf(PdfInfo info) + protected override void SavePdf(IDocument info) { var renderer = new PdfDocumentRenderer(true) { diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToWord .cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToWord .cs index 1c4ea71..b3f15f6 100644 --- a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToWord .cs +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToWord .cs @@ -81,7 +81,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements return properties; } - protected override void CreateWord(WordInfo info) + protected override void CreateWord(IDocument info) { _wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document); MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart(); @@ -119,7 +119,7 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements _docBody.AppendChild(docParagraph); } - protected override void SaveWord(WordInfo info) + protected override void SaveWord(IDocument info) { if (_docBody == null || _wordDocument == null) { @@ -131,5 +131,77 @@ namespace MotorPlantBusinessLogic.OfficePackage.Implements _wordDocument.Dispose(); } + + private Table? _lastTable; + protected override void CreateTable(List columns) + { + if (_docBody == null) + return; + + _lastTable = new Table(); + + var tableProp = new TableProperties(); + tableProp.AppendChild(new TableLayout { Type = TableLayoutValues.Fixed }); + tableProp.AppendChild(new TableBorders( + new TopBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new LeftBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new RightBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new BottomBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new InsideHorizontalBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new InsideVerticalBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 } + )); + tableProp.AppendChild(new TableWidth { Type = TableWidthUnitValues.Auto }); + _lastTable.AppendChild(tableProp); + + TableGrid tableGrid = new TableGrid(); + foreach (var column in columns) + { + tableGrid.AppendChild(new GridColumn() { Width = column }); + } + _lastTable.AppendChild(tableGrid); + + _docBody.AppendChild(_lastTable); + } + + protected override void CreateRow(WordRowParameters rowParameters) + { + if (_docBody == null || _lastTable == null) + return; + + TableRow docRow = new TableRow(); + foreach (var column in rowParameters.Texts) + { + var docParagraph = new Paragraph(); + WordParagraph paragraph = new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { (column, rowParameters.TextProperties) }, + TextProperties = rowParameters.TextProperties + }; + + 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); + } + + TableCell docCell = new TableCell(); + docCell.AppendChild(docParagraph); + docRow.AppendChild(docCell); + } + _lastTable.AppendChild(docRow); + } } } diff --git a/MotorPlant/MotorPlantContracts/BindingModels/SupplyBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/SupplyBindingModel.cs new file mode 100644 index 0000000..332cfee --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BindingModels/SupplyBindingModel.cs @@ -0,0 +1,16 @@ +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BindingModels +{ + public class SupplyBindingModel : ISupplyModel + { + public int ShopId { get; set; } + public int EngineId { get; set; } + public int Count { get; set; } + } +} diff --git a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IReportLogic.cs b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IReportLogic.cs index d8e7efb..3ca180e 100644 --- a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IReportLogic.cs +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IReportLogic.cs @@ -11,13 +11,14 @@ namespace MotorPlantContracts.BusinessLogicsContracts public interface IReportLogic { List GetEngineComponents(); - List GetOrders(ReportBindingModel model); - + List GetShops(); + List GetGroupedOrders(); void SaveEngineToWordFile(ReportBindingModel model); - void SaveEngineComponentToExcelFile(ReportBindingModel model); - void SaveOrdersToPdfFile(ReportBindingModel model); + void SaveShopsToWordFile(ReportBindingModel model); + void SaveShopsToExcelFile(ReportBindingModel model); + void SaveGroupedOrdersToPdfFile(ReportBindingModel model); } } diff --git a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs index ce4f7b0..bfa3267 100644 --- a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs @@ -14,10 +14,10 @@ namespace MotorPlantContracts.BusinessLogicsContracts { List? ReadList(ShopSearchModel? model); ShopViewModel? ReadElement(ShopSearchModel? model); - bool Create(ShopBindingModel? model); - bool Update(ShopBindingModel? model); - bool Delete(ShopBindingModel? model); - bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count); - bool MakeSell(IEngineModel model, int count); + bool Create(ShopBindingModel model); + bool Update(ShopBindingModel model); + bool Delete(ShopBindingModel model); + bool MakeSupply(SupplyBindingModel model); + bool MakeSell(SupplySearchModel model); } } diff --git a/MotorPlant/MotorPlantContracts/SearchModels/SupplySearchModel.cs b/MotorPlant/MotorPlantContracts/SearchModels/SupplySearchModel.cs new file mode 100644 index 0000000..b7dc7e7 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/SearchModels/SupplySearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.SearchModels +{ + public class SupplySearchModel + { + public int? EngineId { get; set; } + public int? Count { get; set; } + } +} diff --git a/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs b/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs index 0fb2755..a0369c0 100644 --- a/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs +++ b/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs @@ -18,6 +18,7 @@ namespace MotorPlantContracts.StoragesContracts ShopViewModel? Insert(ShopBindingModel model); ShopViewModel? Update(ShopBindingModel model); ShopViewModel? Delete(ShopBindingModel model); - bool SellEngines(IEngineModel model, int count); - } + bool SellEngines(SupplySearchModel model); + bool RestockingShops(SupplyBindingModel model); + } } diff --git a/MotorPlant/MotorPlantContracts/ViewModels/ReportGroupOrdersViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/ReportGroupOrdersViewModel.cs new file mode 100644 index 0000000..8c98eee --- /dev/null +++ b/MotorPlant/MotorPlantContracts/ViewModels/ReportGroupOrdersViewModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.ViewModels +{ + public class ReportGroupOrdersViewModel + { + public DateTime Date { get; set; } = DateTime.Now; + public int OrdersCount { get; set; } + public double OrdersSum { get; set; } + } +} diff --git a/MotorPlant/MotorPlantContracts/ViewModels/ReportShopsViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/ReportShopsViewModel.cs new file mode 100644 index 0000000..747752d --- /dev/null +++ b/MotorPlant/MotorPlantContracts/ViewModels/ReportShopsViewModel.cs @@ -0,0 +1,9 @@ +namespace MotorPlantContracts.ViewModels +{ + public class ReportShopsViewModel + { + public string ShopName { get; set; } = string.Empty; + public int TotalCount { get; set; } + public List<(string Engine, int count)> Engines { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantDataModels/Models/ISupplyModel.cs b/MotorPlant/MotorPlantDataModels/Models/ISupplyModel.cs new file mode 100644 index 0000000..f243749 --- /dev/null +++ b/MotorPlant/MotorPlantDataModels/Models/ISupplyModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDataModels.Models +{ + public interface ISupplyModel + { + int ShopId { get; } + int EngineId { get; } + int Count { get; } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs b/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs index f198b99..25fd2e5 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs @@ -13,10 +13,8 @@ namespace MotorPlantDatabaseImplement.Implements public List GetFullList() { using var context = new MotorPlantDatabase(); - return context.Orders - .Select(x => AccessEngineStorage(x.GetViewModel)) - .ToList(); - } + return context.Orders.Include(x => x.Engine).Select(x => x.GetViewModel).ToList(); + } public List GetFilteredList(OrderSearchModel model) { if (!model.Id.HasValue && !model.DateFrom.HasValue) @@ -24,8 +22,6 @@ namespace MotorPlantDatabaseImplement.Implements return new(); } using var context = new MotorPlantDatabase(); - return context.Orders.Where(x => x.Id == model.Id).Select(x => AccessEngineStorage(x.GetViewModel)).ToList(); - } if (model.DateFrom.HasValue) { return context.Orders @@ -42,66 +38,58 @@ namespace MotorPlantDatabaseImplement.Implements } public OrderViewModel? GetElement(OrderSearchModel model) { - if (!model.Id.HasValue) - { - return null; - } - using var context = new MotorPlantDatabase(); - return AccessEngineStorage(context.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel); - } + if (!model.Id.HasValue) + { + return null; + } + using var context = new MotorPlantDatabase(); + return context.Orders.Include(x => x.Engine) + .FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + } public OrderViewModel? Insert(OrderBindingModel model) { - var newOrder = Order.Create(model); - if (newOrder == null) - { - return null; - } - using var context = new MotorPlantDatabase(); - context.Orders.Add(newOrder); - context.SaveChanges(); - return AccessEngineStorage(newOrder.GetViewModel); - } + using var context = new MotorPlantDatabase(); + if (model == null) + return null; + var newOrder = Order.Create(context, model); + if (newOrder == null) + { + return null; + } + context.Orders.Add(newOrder); + context.SaveChanges(); + return newOrder.GetViewModel; + } public OrderViewModel? Update(OrderBindingModel model) { - using var context = new MotorPlantDatabase(); - var order = context.Orders.FirstOrDefault(x => x.Id == - model.Id); - if (order == null) - { - return null; - } - order.Update(model); - context.SaveChanges(); - return AccessEngineStorage(order.GetViewModel); - } - - public OrderViewModel? Delete(OrderBindingModel model) - { - using var context = new MotorPlantDatabase(); - var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); - if (element != null) - { - context.Orders.Remove(element); - context.SaveChanges(); - return AccessEngineStorage(element.GetViewModel); - } - return null; - } - - public static OrderViewModel AccessEngineStorage(OrderViewModel model) - { - if (model == null) - return null; - using var context = new MotorPlantDatabase(); - foreach (var Engine in context.Engines) - { - if (Engine.Id == model.EngineId) - { - model.EngineName = Engine.EngineName; - break; - } - } - return model; - } - } + using var context = new MotorPlantDatabase(); + var order = context.Orders.FirstOrDefault(x => x.Id == model.Id); + if (order == null) + { + return null; + } + order.Update(model); + context.SaveChanges(); + return context.Orders + .Include(x => x.Engine) + .FirstOrDefault(x => x.Id == model.Id) + ?.GetViewModel; + } + public OrderViewModel? Delete(OrderBindingModel model) + { + using var context = new MotorPlantDatabase(); + var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + var deletedElement = context.Orders + .Include(x => x.Engine) + .FirstOrDefault(x => x.Id == model.Id) + ?.GetViewModel; + context.Orders.Remove(element); + context.SaveChanges(); + return deletedElement; + } + return null; + } + } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs b/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs index 5772557..9984575 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs @@ -84,61 +84,117 @@ namespace MotorPlantDatabaseImplement.Implements public ShopViewModel? Update(ShopBindingModel model) { - using var context = new MotorPlantDatabase(); - var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id); - if (shop == null) - { - return null; - } - try - { - if (context.Shops.Any(x => (x.ShopName == model.ShopName && x.Id != model.Id))) - { - throw new Exception("Не должно быть два магазина с одним названием"); - } - shop.Update(model); - shop.UpdateDresses(context, model); - context.SaveChanges(); - return shop.GetViewModel; - } - catch - { - throw; - } - } - public bool SellEngines(IEngineModel model, int count) + using var context = new MotorPlantDatabase(); + using var transaction = context.Database.BeginTransaction(); + try + { + var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop == null) + { + return null; + } + shop.Update(model); + context.SaveChanges(); + shop.UpdateEngines(context, model); + transaction.Commit(); + return shop.GetViewModel; + } + catch + { + transaction.Rollback(); + throw; + } + } + + public bool RestockingShops(SupplyBindingModel model) + { + using var context = new MotorPlantDatabase(); + var transaction = context.Database.BeginTransaction(); + var Shops = context.Shops.Include(x => x.Engines).ThenInclude(x => x.Engine).ToList(). + Where(x => x.MaxCount > x.ShopEngines.Select(x => x.Value.Item2).Sum()).ToList(); + if (model == null) + { + return false; + } + try + { + foreach (Shop shop in Shops) + { + int difference = shop.MaxCount - shop.ShopEngines.Select(x => x.Value.Item2).Sum(); + int refill = Math.Min(difference, model.Count); + model.Count -= refill; + if (shop.ShopEngines.ContainsKey(model.EngineId)) + { + var datePair = shop.ShopEngines[model.EngineId]; + datePair.Item2 += refill; + shop.ShopEngines[model.EngineId] = datePair; + } + else + { + var pizza = context.Engines.First(x => x.Id == model.EngineId); + shop.ShopEngines.Add(model.EngineId, (pizza, refill)); + } + shop.EnginesDictionatyUpdate(context); + if (model.Count == 0) + { + transaction.Commit(); + return true; + } + } + transaction.Rollback(); + return false; + } + catch + { + transaction.Rollback(); + throw; + } + } + + public bool SellEngines(SupplySearchModel model) { - if (model == null) - return false; - using var context = new MotorPlantDatabase(); - using var transaction = context.Database.BeginTransaction(); - List lst = new List(); - foreach (var el in context.ShopEngines.Where(x => x.EngineId == model.Id)) - { - int dif = count; - if (el.Count < dif) - dif = el.Count; - el.Count -= dif; - count -= dif; - if (el.Count == 0) - { - lst.Add(el); - } - if (count == 0) - break; - } - if (count > 0) - { - transaction.Rollback(); - return false; - } - foreach (var el in lst) - { - context.ShopEngines.Remove(el); - } - context.SaveChanges(); - transaction.Commit(); - return true; - } + using var context = new MotorPlantDatabase(); + var transaction = context.Database.BeginTransaction(); + try + { + var shops = context.Shops.Include(x => x.Engines).ThenInclude(x => x.Engine).ToList(). + Where(x => x.ShopEngines.ContainsKey(model.EngineId.Value)).OrderByDescending(x => x.ShopEngines[model.EngineId.Value].Item2).ToList(); + + foreach (var shop in shops) + { + int residue = model.Count.Value - shop.ShopEngines[model.EngineId.Value].Item2; + if (residue > 0) + { + shop.ShopEngines.Remove(model.EngineId.Value); + shop.EnginesDictionatyUpdate(context); + context.SaveChanges(); + model.Count = residue; + + } + else + { + if (residue == 0) + shop.ShopEngines.Remove(model.EngineId.Value); + else + { + var dataPair = shop.ShopEngines[model.EngineId.Value]; + dataPair.Item2 = -residue; + shop.ShopEngines[model.EngineId.Value] = dataPair; + } + + shop.EnginesDictionatyUpdate(context); + transaction.Commit(); + return true; + } + } + transaction.Rollback(); + return false; + } + catch + { + transaction.Rollback(); + throw; + } + } } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.Designer.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.Designer.cs new file mode 100644 index 0000000..b967a0f --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.Designer.cs @@ -0,0 +1,246 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using MotorPlantDatabaseImplement; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace MotorPlantDatabaseImplement.Migrations +{ + [DbContext(typeof(MotorPlantDatabase))] + [Migration("20240516204547_ThirdMigtation")] + partial class ThirdMigtation + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.16") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ComponentName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Cost") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.ToTable("Components"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Engine", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("EngineName") + .IsRequired() + .HasColumnType("text"); + + b.Property("Price") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.ToTable("Engines"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("integer"); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("EngineId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("EngineId"); + + b.ToTable("EngineComponents"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("DateCreate") + .HasColumnType("timestamp without time zone"); + + b.Property("DateImplement") + .HasColumnType("timestamp without time zone"); + + b.Property("EngineId") + .HasColumnType("integer"); + + b.Property("Status") + .HasColumnType("integer"); + + b.Property("Sum") + .HasColumnType("double precision"); + + b.HasKey("Id"); + + b.HasIndex("EngineId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Adress") + .IsRequired() + .HasColumnType("text"); + + b.Property("DateOpen") + .HasColumnType("timestamp without time zone"); + + b.Property("MaxCount") + .HasColumnType("integer"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.ShopEngine", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("integer"); + + b.Property("EngineId") + .HasColumnType("integer"); + + b.Property("ShopId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("EngineId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopEngines"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.EngineComponent", b => + { + b.HasOne("MotorPlantDatabaseImplement.Models.Component", "Component") + .WithMany("EngineComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine") + .WithMany("Components") + .HasForeignKey("EngineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Engine"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => + { + b.HasOne("MotorPlantDatabaseImplement.Models.Engine", null) + .WithMany("Orders") + .HasForeignKey("EngineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.ShopEngine", b => + { + b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine") + .WithMany() + .HasForeignKey("EngineId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("MotorPlantDatabaseImplement.Models.Shop", "Shop") + .WithMany("Engines") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Engine"); + + b.Navigation("Shop"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b => + { + b.Navigation("EngineComponents"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Engine", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Shop", b => + { + b.Navigation("Engines"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.cs similarity index 99% rename from MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.cs rename to MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.cs index 5a17410..9cf9cab 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.cs @@ -7,7 +7,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace MotorPlantDatabaseImplement.Migrations { /// - public partial class NewMig : Migration + public partial class ThirdMigtation : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs index 7355218..5c6bc31 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs @@ -12,7 +12,7 @@ namespace MotorPlantDatabaseImplement.Models [Required] public int EngineId { get; private set; } - + public virtual Engine Engine { get; set; } = new(); [Required] public int Count { get; private set; } @@ -27,16 +27,13 @@ namespace MotorPlantDatabaseImplement.Models public DateTime? DateImplement { get; private set; } - public static Order? Create(OrderBindingModel? model) + public static Order Create(MotorPlantDatabase context, OrderBindingModel model) { - if (model == null) - { - return null; - } return new Order() { Id = model.Id, EngineId = model.EngineId, + Engine = context.Engines.First(x => x.Id == model.EngineId), Count = model.Count, Sum = model.Sum, Status = model.Status, @@ -58,6 +55,7 @@ namespace MotorPlantDatabaseImplement.Models { Id = Id, EngineId = EngineId, + EngineName = Engine.EngineName, Count = Count, Sum = Sum, Status = Status, diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs index 1aa014d..7eda723 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs @@ -15,16 +15,16 @@ namespace MotorPlantDatabaseImplement.Models { public int Id { get; private set; } [Required] - public string ShopName { get; private set; } - [Required] - public string Adress { get; private set; } - [Required] + public string ShopName { get; private set; } = string.Empty; + [Required] + public string Adress { get; private set; } = string.Empty; + [Required] public DateTime DateOpen { get; private set; } [Required] public int MaxCount { get; private set; } private Dictionary? _shopEngines = null; [NotMapped] - public Dictionary? ShopEngines + public Dictionary ShopEngines { get { @@ -74,7 +74,7 @@ namespace MotorPlantDatabaseImplement.Models ShopEngines = ShopEngines }; - public void UpdateDresses(MotorPlantDatabase context, ShopBindingModel model) + public void UpdateEngines(MotorPlantDatabase context, ShopBindingModel model) { var shopEngines = context.ShopEngines.Where(rec => rec.ShopId == model.Id).ToList(); if (shopEngines != null && shopEngines.Count > 0) @@ -101,5 +101,14 @@ namespace MotorPlantDatabaseImplement.Models } _shopEngines = null; } - } + + public void EnginesDictionatyUpdate(MotorPlantDatabase context) + { + UpdateEngines(context, new ShopBindingModel + { + Id = Id, + ShopEngines = ShopEngines, + }); + } + } } diff --git a/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs b/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs index 29ae922..ae401af 100644 --- a/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs +++ b/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs @@ -75,44 +75,73 @@ namespace MotorPlantFileImplement.Implements return null; } - public bool SellEngines(IEngineModel model, int count) + public bool SellEngines(SupplySearchModel model) { - var eng = _source.Engines.FirstOrDefault(x => x.Id == model.Id); - int store = _source.Shops.SelectMany(x => x.ShopEngines).Sum(y => y.Key == model.Id ? y.Value.Item2 : 0); + if (model == null || !model.EngineId.HasValue || !model.Count.HasValue) + return false; + int remainingSpace = _source.Shops.Select(x => x.Engines.ContainsKey(model.EngineId.Value) ? x.Engines[model.EngineId.Value] : 0).Sum(); + if (remainingSpace < model.Count) + { + return false; + } + var shops = _source.Shops.Where(x => x.Engines.ContainsKey(model.EngineId.Value)).OrderByDescending(x => x.Engines[model.EngineId.Value]).ToList(); + foreach (var shop in shops) + { + int residue = model.Count.Value - shop.Engines[model.EngineId.Value]; + if (residue > 0) + { + shop.Engines.Remove(model.EngineId.Value); + shop.EngineUpdate(); + model.Count = residue; + } + else + { + if (residue == 0) + { + shop.Engines.Remove(model.EngineId.Value); + } + else + { + shop.Engines[model.EngineId.Value] = -residue; + } + shop.EngineUpdate(); + _source.SaveShops(); + return true; + } + } + _source.SaveShops(); + return false; + } - if (eng == null || store < count) - { - return false; - } - - for (int i = 0; i < _source.Shops.Count; i++) - { - var shop = _source.Shops[i]; - var engines = shop.ShopEngines; - foreach (var engine in engines.Where(x => x.Value.Item1.Id == eng.Id)) - { - var selling = Math.Min(engine.Value.Item2, count); - engines[engine.Value.Item1.Id] = (engine.Value.Item1, engine.Value.Item2 - selling); - - count -= selling; - - if (count <= 0) - { - break; - } - } - shop.Update(new ShopBindingModel - { - Id = model.Id, - ShopName = shop.ShopName, - Adress = shop.Adress, - MaxCount = shop.MaxCount, - DateOpen = shop.DateOpen, - ShopEngines = engines - }); - } - _source.SaveShops(); - return true; - } - } + public bool RestockingShops(SupplyBindingModel model) + { + if (model == null || _source.Shops.Select(x => x.MaxCount - x.ShopEngines.Select(y => y.Value.Item2).Sum()).Sum() < model.Count) + { + return false; + } + foreach (Shop shop in _source.Shops) + { + int free_places = shop.MaxCount - shop.ShopEngines.Select(x => x.Value.Item2).Sum(); + if (free_places <= 0) + continue; + free_places = Math.Min(free_places, model.Count); + model.Count -= free_places; + if (shop.Engines.ContainsKey(model.EngineId)) + { + shop.Engines[model.EngineId] += free_places; + } + else + { + shop.Engines.Add(model.EngineId, free_places); + } + shop.EngineUpdate(); + if (model.Count == 0) + { + _source.SaveShops(); + return true; + } + } + return false; + } + } } diff --git a/MotorPlant/MotorPlantFileImplement/Models/Shop.cs b/MotorPlant/MotorPlantFileImplement/Models/Shop.cs index 98d151d..8c17a87 100644 --- a/MotorPlant/MotorPlantFileImplement/Models/Shop.cs +++ b/MotorPlant/MotorPlantFileImplement/Models/Shop.cs @@ -98,5 +98,10 @@ namespace MotorPlantFileImplement.Models new XElement("DateOpen", DateOpen), new XElement("MaxCount", MaxCount), new XElement("ShopEngines", Engines.Select(x => new XElement("ShopEngine", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray())); - } + + public void EngineUpdate() + { + _shopEngines = null; + } + } } diff --git a/MotorPlant/MotorPlantListImplement/Implements/OrderStorage.cs b/MotorPlant/MotorPlantListImplement/Implements/OrderStorage.cs index a973288..efc5ebb 100644 --- a/MotorPlant/MotorPlantListImplement/Implements/OrderStorage.cs +++ b/MotorPlant/MotorPlantListImplement/Implements/OrderStorage.cs @@ -31,7 +31,7 @@ namespace MotorPlantListImplement.Implements public List GetFilteredList(OrderSearchModel model) { var result = new List(); - if (model == null || !model.Id.HasValue) + if (model == null) { return result; } diff --git a/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs b/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs index 2d61dae..c52700e 100644 --- a/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs +++ b/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs @@ -108,9 +108,14 @@ namespace MotorPlantListImplement.Implements { return true; } - public bool SellEngines(IEngineModel model, int count) + public bool SellEngines(SupplySearchModel model) { - return true; - } - } + throw new NotImplementedException(); + } + + public bool RestockingShops(SupplyBindingModel model) + { + throw new NotImplementedException(); + } + } } diff --git a/MotorPlant/MotorPlantView/FormMain.Designer.cs b/MotorPlant/MotorPlantView/FormMain.Designer.cs index b4652b7..a68b404 100644 --- a/MotorPlant/MotorPlantView/FormMain.Designer.cs +++ b/MotorPlant/MotorPlantView/FormMain.Designer.cs @@ -1,26 +1,26 @@ namespace MotorPlantView.Forms { - partial class FormMain - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; + partial class FormMain + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } - #region Windows Form Designer generated code + #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify @@ -32,10 +32,16 @@ toolStripDropDownButton1 = new ToolStripDropDownButton(); КомпонентыToolStripMenuItem = new ToolStripMenuItem(); ДвигателиToolStripMenuItem = new ToolStripMenuItem(); + магазиныToolStripMenuItem = new ToolStripMenuItem(); + поставкаToolStripMenuItem = new ToolStripMenuItem(); + продажаToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem(); списокДвигателейToolStripMenuItem = new ToolStripMenuItem(); компонентыПоДвигателямToolStripMenuItem = new ToolStripMenuItem(); списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + списокМагазиновToolStripMenuItem = new ToolStripMenuItem(); + загруженностьМагазиновToolStripMenuItem = new ToolStripMenuItem(); + заказыПоГруппамToolStripMenuItem = new ToolStripMenuItem(); buttonCreateOrder = new Button(); buttonTakeOrderInWork = new Button(); buttonOrderReady = new Button(); @@ -59,7 +65,7 @@ // toolStripDropDownButton1 // toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; - toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem }); + toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, магазиныToolStripMenuItem, поставкаToolStripMenuItem, продажаToolStripMenuItem }); toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; toolStripDropDownButton1.Name = "toolStripDropDownButton1"; toolStripDropDownButton1.Size = new Size(88, 22); @@ -79,9 +85,30 @@ ДвигателиToolStripMenuItem.Text = "Двигатели"; ДвигателиToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; // + // магазиныToolStripMenuItem + // + магазиныToolStripMenuItem.Name = "магазиныToolStripMenuItem"; + магазиныToolStripMenuItem.Size = new Size(145, 22); + магазиныToolStripMenuItem.Text = "Магазины"; + магазиныToolStripMenuItem.Click += магазиныToolStripMenuItem_Click; + // + // поставкаToolStripMenuItem + // + поставкаToolStripMenuItem.Name = "поставкаToolStripMenuItem"; + поставкаToolStripMenuItem.Size = new Size(145, 22); + поставкаToolStripMenuItem.Text = "Поставка"; + поставкаToolStripMenuItem.Click += поставкаToolStripMenuItem_Click; + // + // продажаToolStripMenuItem + // + продажаToolStripMenuItem.Name = "продажаToolStripMenuItem"; + продажаToolStripMenuItem.Size = new Size(145, 22); + продажаToolStripMenuItem.Text = "Продажа"; + продажаToolStripMenuItem.Click += продажаToolStripMenuItem_Click; + // // отчетыToolStripMenuItem // - отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокДвигателейToolStripMenuItem, компонентыПоДвигателямToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокДвигателейToolStripMenuItem, компонентыПоДвигателямToolStripMenuItem, списокЗаказовToolStripMenuItem, списокМагазиновToolStripMenuItem, загруженностьМагазиновToolStripMenuItem, заказыПоГруппамToolStripMenuItem }); отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; отчетыToolStripMenuItem.Size = new Size(60, 25); отчетыToolStripMenuItem.Text = "Отчеты"; @@ -107,6 +134,27 @@ списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; // + // списокМагазиновToolStripMenuItem + // + списокМагазиновToolStripMenuItem.Name = "списокМагазиновToolStripMenuItem"; + списокМагазиновToolStripMenuItem.Size = new Size(228, 22); + списокМагазиновToolStripMenuItem.Text = "Список магазинов"; + списокМагазиновToolStripMenuItem.Click += списокМагазиновToolStripMenuItem_Click; + // + // загруженностьМагазиновToolStripMenuItem + // + загруженностьМагазиновToolStripMenuItem.Name = "загруженностьМагазиновToolStripMenuItem"; + загруженностьМагазиновToolStripMenuItem.Size = new Size(228, 22); + загруженностьМагазиновToolStripMenuItem.Text = "Загруженность магазинов"; + загруженностьМагазиновToolStripMenuItem.Click += загруженностьМагазиновToolStripMenuItem_Click; + // + // заказыПоГруппамToolStripMenuItem + // + заказыПоГруппамToolStripMenuItem.Name = "заказыПоГруппамToolStripMenuItem"; + заказыПоГруппамToolStripMenuItem.Size = new Size(228, 22); + заказыПоГруппамToolStripMenuItem.Text = "Заказы по группам"; + заказыПоГруппамToolStripMenuItem.Click += заказыПоГруппамToolStripMenuItem_Click; + // // buttonCreateOrder // buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; @@ -203,7 +251,7 @@ PerformLayout(); } - #endregion + #endregion private ToolStrip toolStrip1; private Button buttonCreateOrder; @@ -219,5 +267,11 @@ private ToolStripMenuItem списокДвигателейToolStripMenuItem; private ToolStripMenuItem компонентыПоДвигателямToolStripMenuItem; private ToolStripMenuItem списокЗаказовToolStripMenuItem; + private ToolStripMenuItem магазиныToolStripMenuItem; + private ToolStripMenuItem поставкаToolStripMenuItem; + private ToolStripMenuItem продажаToolStripMenuItem; + private ToolStripMenuItem списокМагазиновToolStripMenuItem; + private ToolStripMenuItem загруженностьМагазиновToolStripMenuItem; + private ToolStripMenuItem заказыПоГруппамToolStripMenuItem; } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormMain.cs b/MotorPlant/MotorPlantView/FormMain.cs index a036221..52a92bf 100644 --- a/MotorPlant/MotorPlantView/FormMain.cs +++ b/MotorPlant/MotorPlantView/FormMain.cs @@ -18,6 +18,7 @@ namespace MotorPlantView.Forms _orderLogic = orderLogic; _reportLogic = reportLogic; } + private void FormMain_Load(object sender, EventArgs e) { LoadData(); @@ -29,38 +30,41 @@ namespace MotorPlantView.Forms { var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["EngineId"].Visible = false; - dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; - } + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["EngineId"].Visible = false; + dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } - _logger.LogInformation("Загрузка заказов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заказов"); - } - } - private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + } + } - if (service is FormComponents form) - { - form.ShowDialog(); - } - } - private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormEngines)); + private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + + if (service is FormComponents form) + { + form.ShowDialog(); + } + } + + private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormEngines)); if (service is FormEngines form) { form.ShowDialog(); } } + private void buttonCreateOrder_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); @@ -70,6 +74,7 @@ namespace MotorPlantView.Forms LoadData(); } } + private void buttonTakeOrderInWork_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) @@ -95,6 +100,7 @@ namespace MotorPlantView.Forms } } } + private void buttonOrderReady_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) @@ -118,6 +124,7 @@ namespace MotorPlantView.Forms } } } + private void buttonIssuedOrder_Click(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count == 1) @@ -139,10 +146,12 @@ namespace MotorPlantView.Forms } catch (Exception ex) { - _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } + private void buttonRef_Click(object sender, EventArgs e) { LoadData(); @@ -175,5 +184,60 @@ namespace MotorPlantView.Forms form.ShowDialog(); } } + + private void поставкаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSupply)); + if (service is FormSupply form) + { + form.ShowDialog(); + } + } + + private void продажаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSell)); + if (service is FormSell form) + { + form.ShowDialog(); + } + } + + private void списокМагазиновToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveShopsToWordFile(new ReportBindingModel { FileName = dialog.FileName }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + + private void загруженностьМагазиновToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportShop)); + if (service is FormReportShop form) + { + form.ShowDialog(); + } + } + + private void заказыПоГруппамToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportGroupedOrders)); + if (service is FormReportGroupedOrders form) + { + form.ShowDialog(); + } + } + + private void магазиныToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShops)); + if (service is FormShops form) + { + form.ShowDialog(); + } + } } } diff --git a/MotorPlant/MotorPlantView/FormReportGroupedOrders.Designer.cs b/MotorPlant/MotorPlantView/FormReportGroupedOrders.Designer.cs new file mode 100644 index 0000000..4c22887 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportGroupedOrders.Designer.cs @@ -0,0 +1,86 @@ +namespace MotorPlantView +{ + partial class FormReportGroupedOrders + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.panel = new System.Windows.Forms.Panel(); + this.buttonToPDF = new System.Windows.Forms.Button(); + this.buttonMake = new System.Windows.Forms.Button(); + this.panel.SuspendLayout(); + this.SuspendLayout(); + // + // panel + // + this.panel.Controls.Add(this.buttonToPDF); + this.panel.Controls.Add(this.buttonMake); + this.panel.Dock = System.Windows.Forms.DockStyle.Top; + this.panel.Location = new System.Drawing.Point(0, 0); + this.panel.Name = "panel"; + this.panel.Size = new System.Drawing.Size(970, 52); + this.panel.TabIndex = 1; + // + // buttonToPDF + // + this.buttonToPDF.Location = new System.Drawing.Point(486, 12); + this.buttonToPDF.Name = "buttonToPDF"; + this.buttonToPDF.Size = new System.Drawing.Size(411, 29); + this.buttonToPDF.TabIndex = 5; + this.buttonToPDF.Text = "В PDF"; + this.buttonToPDF.UseVisualStyleBackColor = true; + this.buttonToPDF.Click += new System.EventHandler(this.buttonToPDF_Click); + // + // buttonMake + // + this.buttonMake.Location = new System.Drawing.Point(49, 12); + this.buttonMake.Name = "buttonMake"; + this.buttonMake.Size = new System.Drawing.Size(377, 29); + this.buttonMake.TabIndex = 4; + this.buttonMake.Text = "Сформировать"; + this.buttonMake.UseVisualStyleBackColor = true; + this.buttonMake.Click += new System.EventHandler(this.ButtonMake_Click); + // + // FormReportGroupedOrders + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(970, 450); + this.Controls.Add(this.panel); + this.Name = "FormReportGroupedOrders"; + this.Text = "Отчёт по группированным заказам "; + this.panel.ResumeLayout(false); + this.ResumeLayout(false); + + } + + #endregion + + private Panel panel; + private Button buttonToPDF; + private Button buttonMake; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormReportGroupedOrders.cs b/MotorPlant/MotorPlantView/FormReportGroupedOrders.cs new file mode 100644 index 0000000..8b0e34f --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportGroupedOrders.cs @@ -0,0 +1,80 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Reporting.WinForms; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MotorPlantView +{ + public partial class FormReportGroupedOrders : Form + { + private readonly ReportViewer reportViewer; + private readonly ILogger _logger; + private readonly IReportLogic _logic; + + public FormReportGroupedOrders(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + reportViewer = new ReportViewer + { + Dock = DockStyle.Fill + }; + reportViewer.LocalReport.LoadReportDefinition(new FileStream("C:\\Users\\salih\\OneDrive\\Рабочий стол\\MotorPlant\\MotorPlant\\MotorPlantView\\ReportGroupedOrders.rdlc", FileMode.Open)); + Controls.Clear(); + Controls.Add(reportViewer); + Controls.Add(panel); + } + + private void ButtonMake_Click(object sender, EventArgs e) + { + try + { + var dataSource = _logic.GetGroupedOrders(); + var source = new ReportDataSource("DataSetGroupedOrders", dataSource); + reportViewer.LocalReport.DataSources.Clear(); + reportViewer.LocalReport.DataSources.Add(source); + + reportViewer.RefreshReport(); + _logger.LogInformation("Загрузка списка группированных заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка группированных заказов на период"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + + private void buttonToPDF_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + _logic.SaveGroupedOrdersToPdfFile(new ReportBindingModel + { + FileName = dialog.FileName, + }); + _logger.LogInformation("Сохранение списка группированных заказов"); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения списка группированных заказов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } +} diff --git a/MotorPlant/MotorPlantView/FormReportGroupedOrders.resx b/MotorPlant/MotorPlantView/FormReportGroupedOrders.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportGroupedOrders.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormReportShop.Designer.cs b/MotorPlant/MotorPlantView/FormReportShop.Designer.cs new file mode 100644 index 0000000..2e36897 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportShop.Designer.cs @@ -0,0 +1,116 @@ +namespace MotorPlantView +{ + partial class FormReportShop + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.buttonSaveToExcel = new System.Windows.Forms.Button(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + this.ColumnShop = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.ColumnPizza = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // buttonSaveToExcel + // + this.buttonSaveToExcel.Location = new System.Drawing.Point(0, 6); + this.buttonSaveToExcel.Name = "buttonSaveToExcel"; + this.buttonSaveToExcel.Size = new System.Drawing.Size(223, 29); + this.buttonSaveToExcel.TabIndex = 3; + this.buttonSaveToExcel.Text = "Сохранить в Excel"; + this.buttonSaveToExcel.UseVisualStyleBackColor = true; + this.buttonSaveToExcel.Click += new System.EventHandler(this.ButtonSaveToExcel_Click); + // + // dataGridView + // + this.dataGridView.AllowUserToAddRows = false; + this.dataGridView.AllowUserToDeleteRows = false; + this.dataGridView.AllowUserToOrderColumns = true; + this.dataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.ColumnShop, + this.ColumnPizza, + this.ColumnCount}); + this.dataGridView.Dock = System.Windows.Forms.DockStyle.Bottom; + this.dataGridView.Location = new System.Drawing.Point(0, 47); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.ReadOnly = true; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(598, 403); + this.dataGridView.TabIndex = 2; + // + // ColumnShop + // + this.ColumnShop.FillWeight = 130F; + this.ColumnShop.HeaderText = "Магазин"; + this.ColumnShop.MinimumWidth = 6; + this.ColumnShop.Name = "ColumnShop"; + this.ColumnShop.ReadOnly = true; + // + // ColumnPizza + // + this.ColumnPizza.FillWeight = 140F; + this.ColumnPizza.HeaderText = "Пицца"; + this.ColumnPizza.MinimumWidth = 6; + this.ColumnPizza.Name = "ColumnPizza"; + this.ColumnPizza.ReadOnly = true; + // + // ColumnCount + // + this.ColumnCount.FillWeight = 90F; + this.ColumnCount.HeaderText = "Количество"; + this.ColumnCount.MinimumWidth = 6; + this.ColumnCount.Name = "ColumnCount"; + this.ColumnCount.ReadOnly = true; + // + // FormReportShop + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(598, 450); + this.Controls.Add(this.buttonSaveToExcel); + this.Controls.Add(this.dataGridView); + this.Name = "FormReportShop"; + this.Text = "Наполненость магазинов"; + this.Load += new System.EventHandler(this.FormReportShop_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private Button buttonSaveToExcel; + private DataGridView dataGridView; + private DataGridViewTextBoxColumn ColumnShop; + private DataGridViewTextBoxColumn ColumnPizza; + private DataGridViewTextBoxColumn ColumnCount; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormReportShop.cs b/MotorPlant/MotorPlantView/FormReportShop.cs new file mode 100644 index 0000000..b6d1130 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportShop.cs @@ -0,0 +1,78 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MotorPlantView +{ + public partial class FormReportShop : Form + { + private readonly ILogger _logger; + private readonly IReportLogic _logic; + + public FormReportShop(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormReportShop_Load(object sender, EventArgs e) + { + try + { + var dict = _logic.GetShops(); + if (dict != null) + { + dataGridView.Rows.Clear(); + foreach (var elem in dict) + { + dataGridView.Rows.Add(new object[] { elem.ShopName, "", "" }); + foreach (var listElem in elem.Engines) + { + dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 }); + } + dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount }); + dataGridView.Rows.Add(Array.Empty()); + } + } + _logger.LogInformation("Загрузка списка пицц по магазинам"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка пицц по магазинам"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonSaveToExcel_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + _logic.SaveShopsToExcelFile(new ReportBindingModel + { + FileName = dialog.FileName + }); + _logger.LogInformation("Сохранение списка пицц по магазинам"); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения списка пицц по магазинам"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } +} diff --git a/MotorPlant/MotorPlantView/FormReportShop.resx b/MotorPlant/MotorPlantView/FormReportShop.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportShop.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormSell.cs b/MotorPlant/MotorPlantView/FormSell.cs index 09d47ad..a434303 100644 --- a/MotorPlant/MotorPlantView/FormSell.cs +++ b/MotorPlant/MotorPlantView/FormSell.cs @@ -10,6 +10,7 @@ using System.Windows.Forms; using MotorPlantDataModels.Models; using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.ViewModels; +using MotorPlantContracts.SearchModels; namespace MotorPlantView { @@ -73,44 +74,34 @@ namespace MotorPlantView private void buttonSave_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(textBoxCount.Text)) - { - MessageBox.Show("Заполните поле Количество", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - if (comboBoxEngine.SelectedValue == null) - { - MessageBox.Show("Выберите двигатель", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - - try - { - int count = Convert.ToInt32(textBoxCount.Text); - - bool res = _shopLogic.MakeSell( - _engineLogic.ReadElement(new() { Id = Convert.ToInt32(comboBoxEngine.SelectedValue) }), - count - ); - - if (!res) - { - throw new Exception("Ошибка при продаже."); - } - - MessageBox.Show("Продажа прошла успешно"); - DialogResult = DialogResult.OK; - Close(); - - } - catch (Exception err) - { - MessageBox.Show("Ошибка продажи"); - return; - } - } + if (comboBoxEngine.SelectedValue == null) + { + MessageBox.Show("Выберите пиццу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + try + { + bool resout = _shopLogic.MakeSell(new SupplySearchModel + { + EngineId = Convert.ToInt32(comboBoxEngine.SelectedValue), + Count = Convert.ToInt32(textBoxCount.Text) + }); + if (resout) + { + MessageBox.Show("Продажа проведена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + else + { + MessageBox.Show("Продажа не может быть создана.", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } private void buttonCancel_Click(object sender, EventArgs e) { diff --git a/MotorPlant/MotorPlantView/FormSupply.cs b/MotorPlant/MotorPlantView/FormSupply.cs index fa59e52..aa0174d 100644 --- a/MotorPlant/MotorPlantView/FormSupply.cs +++ b/MotorPlant/MotorPlantView/FormSupply.cs @@ -1,4 +1,5 @@ -using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.SearchModels; using MotorPlantContracts.ViewModels; using MotorPlantDataModels.Models; @@ -85,49 +86,35 @@ namespace MotorPlantView private void SaveButton_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(CountTextBox.Text)) + if (ShopComboBox.SelectedValue == null) { - MessageBox.Show("Заполните поле Количество", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (EngineComboBox.SelectedValue == null) { - MessageBox.Show("Выберите двигатель", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Выберите пиццу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - if (ShopComboBox.SelectedValue == null) - { - MessageBox.Show("Выберите магазин", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - try { - int count = Convert.ToInt32(CountTextBox.Text); - - bool res = _shopLogic.MakeSupply( - new ShopSearchModel() { Id = Convert.ToInt32(ShopComboBox.SelectedValue) }, - _engineLogic.ReadElement(new() { Id = Convert.ToInt32(EngineComboBox.SelectedValue) }), - count - ); - - if (!res) + var operationResult = _shopLogic.MakeSupply(new SupplyBindingModel { - throw new Exception("Ошибка при пополнении. Дополнительная информация в логах"); + ShopId = Convert.ToInt32(ShopComboBox.SelectedValue), + EngineId = Convert.ToInt32(EngineComboBox.SelectedValue), + Count = Convert.ToInt32(CountTextBox.Text) + }); + if (!operationResult) + { + throw new Exception("Ошибка при создании поставки. Дополнительная информация в логах."); } - - MessageBox.Show("Пополнение прошло успешно"); + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); DialogResult = DialogResult.OK; Close(); - } - catch (Exception er) + catch (Exception ex) { - MessageBox.Show("Ошибка пополнения"); - return; + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } diff --git a/MotorPlant/MotorPlantView/Program.cs b/MotorPlant/MotorPlantView/Program.cs index 0ec24fd..fd0e0f1 100644 --- a/MotorPlant/MotorPlantView/Program.cs +++ b/MotorPlant/MotorPlantView/Program.cs @@ -44,10 +44,13 @@ namespace MotorPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -59,8 +62,14 @@ namespace MotorPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/ReportGroupedOrders.rdlc b/MotorPlant/MotorPlantView/ReportGroupedOrders.rdlc new file mode 100644 index 0000000..2ef2b88 --- /dev/null +++ b/MotorPlant/MotorPlantView/ReportGroupedOrders.rdlc @@ -0,0 +1,441 @@ + + + 0 + + + + System.Data.DataSet + /* Local Connection */ + + 20791c83-cee8-4a38-bbd0-245fc17cefb3 + + + + + + PrecastConcretePlantContractsViewModels + /* Local Query */ + + + + Date + System.DateTime + + + OrdersCount + System.Int32 + + + OrdersSum + System.Decimal + + + + PrecastConcretePlantContracts.ViewModels + ReportGroupOrdersViewModel + PrecastConcretePlantContracts.ViewModels.ReportGroupOrdersViewModel, PrecastConcretePlantContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + + + + + + + + + true + true + + + + + Отчёт по заказам + + + + 0.6cm + 16.51cm + + + Middle + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Parameters!ReportParameterPeriod.Value + + + + + + + ReportParameterPeriod + 0.6cm + 0.6cm + 16.51cm + 1 + + + 2pt + 2pt + 2pt + 2pt + + + + + + + 3.90406cm + + + 3.97461cm + + + 3.65711cm + + + + + 0.6cm + + + + + true + true + + + + + Дата создания + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Количество заказов + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Общая сумма заказов + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + 0.6cm + + + + + true + true + + + + + =Fields!Date.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!OrdersCount.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!OrdersSum.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + + + + + + + + + + + + After + + + + + + + DataSetGroupedOrders + 1.88242cm + 2.68676cm + 1.2cm + 11.53578cm + 2 + + + + + + true + true + + + + + Итого: + + + + 3.29409cm + 8.06542cm + 0.6cm + 2.5cm + 3 + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Sum(Fields!OrdersSum.Value, "DataSetGroupedOrders") + + + + + + + 3.29409cm + 10.70653cm + 0.6cm + 3.48072cm + 4 + + + 2pt + 2pt + 2pt + 2pt + + + + 2in +