diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs index 7b27063..3277e2f 100644 --- a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs @@ -5,67 +5,81 @@ using MotorPlantContracts.StoragesContracts; using MotorPlantContracts.ViewModels; using Microsoft.Extensions.Logging; using MotorPlantDataModels.Enums; +using MotorPlantDataModels.Models; namespace MotorPlantBusinessLogic.BusinessLogics { public class OrderLogic : IOrderLogic { - private readonly ILogger _logger; - private readonly IOrderStorage _orderStorage; + private readonly ILogger _logger; + private readonly IOrderStorage _orderStorage; + private readonly IShopStorage _shopStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) - { - _logger = logger; - _orderStorage = orderStorage; - } + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IShopStorage shopStorage) + { + _logger = logger; + _orderStorage = orderStorage; + _shopStorage = shopStorage; + } - public List? ReadList(OrderSearchModel? model) - { - _logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); - var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); - if (list == null) + public List? ReadList(OrderSearchModel? model) + { + _logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); + var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + + private void CheckModel(OrderBindingModel model, bool WithParams = true) + { + if (model == null) { - _logger.LogWarning("ReadList return null list"); - return null; + throw new ArgumentNullException(nameof(model)); } - _logger.LogInformation("ReadList. Count:{Count}", list.Count); - return list; - } - - public bool CreateOrder(OrderBindingModel model) - { - CheckModel(model); - - if (model.Status != OrderStatus.Неизвестен) - return false; - model.Status = OrderStatus.Принят; - - if (_orderStorage.Insert(model) == null) + if (!WithParams) { - model.Status = OrderStatus.Неизвестен; - _logger.LogWarning("Insert operation failed"); - return false; + return; } - return true; + 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 TakeOrderInWork(OrderBindingModel model) - { - return ToNextStatus(model, OrderStatus.Выполняется); - } + public bool CreateOrder(OrderBindingModel model) + { + CheckModel(model); + if (model.Status != OrderStatus.Неизвестен) + { + return false; + } + model.Status = OrderStatus.Принят; + if (_orderStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; - public bool FinishOrder(OrderBindingModel model) - { - return ToNextStatus(model, OrderStatus.Готов); - } + } - public bool DeliveryOrder(OrderBindingModel model) - { - return ToNextStatus(model, OrderStatus.Выдан); - } - - public bool ToNextStatus(OrderBindingModel model, OrderStatus orderStatus) - { + private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus) + { CheckModel(model, false); var element = _orderStorage.GetElement(new OrderSearchModel() { @@ -75,58 +89,58 @@ namespace MotorPlantBusinessLogic.BusinessLogics { throw new ArgumentNullException(nameof(element)); } - - model.EngineId = element.EngineId; 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 (model.Status != orderStatus - 1) + if (requiredStatus - model.Status == 1) { - _logger.LogWarning("Status update to " + orderStatus + " operation failed"); - return false; + 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; } - model.Status = orderStatus; - - if (model.Status == OrderStatus.Выдан) - { - model.DateImplement = DateTime.Now; - } - - if (_orderStorage.Update(model) == null) - { - model.Status--; - _logger.LogWarning("Changing status operation faled"); - return false; - } - return true; + _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); + throw new ArgumentException($"Невозможно присвоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); } - private void CheckModel(OrderBindingModel model, bool withParams = true) - { - if (model == null) + public bool TakeOrderInWork(OrderBindingModel model) + { + return ChangeStatus(model, OrderStatus.Выполняется); + } + + public bool FinishOrder(OrderBindingModel model) + { + return ChangeStatus(model, OrderStatus.Готов); + } + + public bool DeliveryOrder(OrderBindingModel model) + { + var order = _orderStorage.GetElement(new OrderSearchModel { - throw new ArgumentNullException(nameof(model)); - } - if (!withParams) + Id = model.Id, + }); + if (order == null) { - return; + throw new ArgumentNullException(nameof(order)); } - if (model.Count <= 0) + if (!_shopStorage.RestockingShops(new SupplyBindingModel { - throw new ArgumentNullException("Количество изделий должно быть больше 0", nameof(model.Count)); - } - if (model.Sum <= 0) + EngineId = order.EngineId, + Count = order.Count + })) { - throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum)); + throw new ArgumentException("Недостаточно места"); } - if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) - { - throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} должна быть позже даты его создания {model.DateCreate}"); - } - _logger.LogInformation("Engine. EngineId:{EngineId}.Count:{Count}.Sum:{Sum}Id:{Id}", model.EngineId, model.Count, model.Sum, model.Id); + + 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 new file mode 100644 index 0000000..a645ef6 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs @@ -0,0 +1,195 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.BusinessLogic +{ + public class ShopLogic : IShopLogic + { + private readonly ILogger _logger; + private readonly IShopStorage _shopStorage; + private readonly IEngineStorage _engineStorage; + + public ShopLogic(ILogger logger, IShopStorage shopStorage, IEngineStorage engineStorage) + { + _logger = logger; + _shopStorage = shopStorage; + _engineStorage = engineStorage; + } + + public List ReadList(ShopSearchModel model) + { + _logger.LogInformation("ReadList. ShopName:{Name}. Id:{ Id}", model?.Name, model?.Id); + var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + + public ShopViewModel ReadElement(ShopSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.Name, model.Id); + var element = _shopStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } + + public bool Create(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public bool Update(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + + public bool Delete(ShopBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_shopStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + + private void CheckModel(ShopBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.ShopName)) + { + throw new ArgumentNullException("Нет названия магазина", + nameof(model.ShopName)); + } + if (string.IsNullOrEmpty(model.Adress)) + { + throw new ArgumentNullException("Нет адресса магазина", + nameof(model.ShopName)); + } + if (model.DateOpen == null) + { + throw new ArgumentNullException("Нет даты открытия магазина", + nameof(model.ShopName)); + } + _logger.LogInformation("Shop. ShopName:{ShopName}.Address:{Address}. DateOpen:{DateOpen}. Id: { Id}", model.ShopName, model.Adress, model.DateOpen, model.Id); + var element = _shopStorage.GetElement(new ShopSearchModel + { + Name = model.ShopName + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Магазин с таким названием уже есть"); + } + } + + public bool MakeSupply(SupplyBindingModel model) + { + 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)); + } + + _shopStorage.Update(new ShopBindingModel() + { + Id = shop.Id, + ShopName = shop.ShopName, + Adress = shop.Adress, + DateOpen = shop.DateOpen, + ShopEngines = shop.ShopEngines, + MaxCount = shop.MaxCount, + }); + + return true; + } + + 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/ShopBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/ShopBindingModel.cs new file mode 100644 index 0000000..75dbc6f --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BindingModels/ShopBindingModel.cs @@ -0,0 +1,19 @@ +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BindingModels +{ + public class ShopBindingModel : IShopModel + { + public int Id { get; set; } + public string ShopName { get; set; } + public string Adress { get; set; } + public DateTime DateOpen { get; set; } + public int MaxCount { get; set; } + public Dictionary ShopEngines { get; set; } = new(); + } +} 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 new file mode 100644 index 0000000..bfa3267 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs @@ -0,0 +1,23 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BusinessLogicsContracts +{ + public interface IShopLogic + { + List? ReadList(ShopSearchModel? model); + ShopViewModel? ReadElement(ShopSearchModel? model); + 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/ShopSearchModel.cs b/MotorPlant/MotorPlantContracts/SearchModels/ShopSearchModel.cs new file mode 100644 index 0000000..470bafb --- /dev/null +++ b/MotorPlant/MotorPlantContracts/SearchModels/ShopSearchModel.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 ShopSearchModel + { + public int? Id { get; set; } + public string? Name { get; set; } + } +} 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 new file mode 100644 index 0000000..a0369c0 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs @@ -0,0 +1,24 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.StoragesContracts +{ + public interface IShopStorage + { + List GetFullList(); + List GetFilteredList(ShopSearchModel model); + ShopViewModel? GetElement(ShopSearchModel model); + ShopViewModel? Insert(ShopBindingModel model); + ShopViewModel? Update(ShopBindingModel model); + ShopViewModel? Delete(ShopBindingModel model); + 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/MotorPlantContracts/ViewModels/ShopViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/ShopViewModel.cs new file mode 100644 index 0000000..7e595f5 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/ViewModels/ShopViewModel.cs @@ -0,0 +1,33 @@ +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.ViewModels +{ + public class ShopViewModel : IShopModel + { + public int Id { get; set; } + + [DisplayName("Название магазина")] + + public string ShopName { get; set; } = string.Empty; + + [DisplayName("Адрес")] + + public string Adress { get; set; } = string.Empty; + + [DisplayName("Дата открытия")] + + public DateTime DateOpen { get; set; } + + [DisplayName("Вмещаемость")] + + public int MaxCount { get; set; } + + public Dictionary ShopEngines { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantDataModels/Models/IShopModel.cs b/MotorPlant/MotorPlantDataModels/Models/IShopModel.cs new file mode 100644 index 0000000..fef931e --- /dev/null +++ b/MotorPlant/MotorPlantDataModels/Models/IShopModel.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDataModels.Models +{ + public interface IShopModel : IId + { + string ShopName { get; } + string Adress { get; } + DateTime DateOpen { get; } + int MaxCount { get; } + } +} 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 688d32e..f61c9ac 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs @@ -9,96 +9,86 @@ namespace MotorPlantDatabaseImplement.Implements { public class OrderStorage : IOrderStorage { - public List GetFullList() - { - using var context = new MotorPlantDatabase(); - return context.Orders - .Select(x => AccessEngineStorage(x.GetViewModel)) - .ToList(); - } - public List GetFilteredList(OrderSearchModel model) - { - if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue && !model.ClientId.HasValue) - { - return new(); - } - using var context = new MotorPlantDatabase(); - if (model.Id.HasValue) - return context.Orders.Where(x => x.Id == model.Id).Select(x => AccessEngineStorage(x.GetViewModel)).ToList(); - if (model.ClientId.HasValue) - return context.Orders.Where(x => x.ClientId == model.ClientId).Select(x => AccessEngineStorage(x.GetViewModel)).ToList(); - return context.Orders.Where(x => x.DateCreate >= model.DateFrom).Where(x => x.DateCreate <= model.DateTo). - Select(x => AccessEngineStorage(x.GetViewModel)).ToList(); - } - 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); - } - 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); - } - 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; - } - } - foreach (var client in context.Clients) - { - if (client.Id == model.ClientId) - { - model.ClientFIO = client.ClientFIO; - return model; - } - } - return model; - } - } + public List GetFullList() + { + using var context = new MotorPlantDatabase(); + return context.Orders.Include(x => x.Engine).Select(x => x.GetViewModel).ToList(); + } + public List GetFilteredList(OrderSearchModel model) + { + if (!model.Id.HasValue && !model.DateFrom.HasValue) + { + return new(); + } + using var context = new MotorPlantDatabase(); + if (model.DateFrom.HasValue) + { + return context.Orders + .Include(x => x.Engine) + .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) + .Select(x => x.GetViewModel) + .ToList(); + } + return context.Orders + .Include(x => x.Engine) + .Where(x => x.Id == model.Id) + .Select(x => x.GetViewModel) + .ToList(); + } + public OrderViewModel? GetElement(OrderSearchModel model) + { + 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) + { + 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 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 new file mode 100644 index 0000000..9984575 --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs @@ -0,0 +1,200 @@ +using Microsoft.EntityFrameworkCore; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantDatabaseImplement.Models; +using MotorPlantDataModels.Models; + +namespace MotorPlantDatabaseImplement.Implements +{ + public class ShopStorage : IShopStorage + { + public ShopViewModel? Delete(ShopBindingModel model) + { + using var context = new MotorPlantDatabase(); + var element = context.Shops.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + context.Shops.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } + + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + using var context = new MotorPlantDatabase(); + return context.Shops.Include(x => x.Engines).ThenInclude(x => x.Engine).FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel; + } + + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name)) + { + return new(); + } + using var context = new MotorPlantDatabase(); + return context.Shops + .Include(x => x.Engines) + .ThenInclude(x => x.Engine) + .Select(x => x.GetViewModel) + .Where(x => x.ShopName.Contains(model.Name ?? string.Empty)) + .ToList(); + } + + public List GetFullList() + { + using var context = new MotorPlantDatabase(); + return context.Shops + .Include(x => x.Engines) + .ThenInclude(x => x.Engine) + .Select(x => x.GetViewModel) + .ToList(); + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + using var context = new MotorPlantDatabase(); + try + { + var newShop = Shop.Create(context, model); + if (newShop == null) + { + return null; + } + if (context.Shops.Any(x => x.ShopName == newShop.ShopName)) + { + throw new Exception("Не должно быть два магазина с одним названием"); + } + context.Shops.Add(newShop); + context.SaveChanges(); + return newShop.GetViewModel; + } + catch + { + throw; + } + } + + public ShopViewModel? Update(ShopBindingModel model) + { + 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) + { + 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/20240407191059_NewMigration1.Designer.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240407191059_NewMigration1.Designer.cs deleted file mode 100644 index 55c9712..0000000 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240407191059_NewMigration1.Designer.cs +++ /dev/null @@ -1,197 +0,0 @@ -// -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("20240407191059_NewMigration1")] - partial class NewMigration1 - { - /// - 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.Client", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("integer"); - - NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); - - b.Property("ClientFIO") - .IsRequired() - .HasColumnType("text"); - - b.Property("Email") - .IsRequired() - .HasColumnType("text"); - - b.Property("Password") - .IsRequired() - .HasColumnType("text"); - - b.HasKey("Id"); - - b.ToTable("Clients"); - }); - - 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("ClientId") - .HasColumnType("integer"); - - 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.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.Component", b => - { - b.Navigation("EngineComponents"); - }); - - modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Engine", b => - { - b.Navigation("Components"); - - b.Navigation("Orders"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240407191059_NewMigration1.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240407191059_NewMigration1.cs deleted file mode 100644 index 08f4cf1..0000000 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240407191059_NewMigration1.cs +++ /dev/null @@ -1,145 +0,0 @@ -using System; -using Microsoft.EntityFrameworkCore.Migrations; -using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; - -#nullable disable - -namespace MotorPlantDatabaseImplement.Migrations -{ - /// - public partial class NewMigration1 : Migration - { - /// - protected override void Up(MigrationBuilder migrationBuilder) - { - migrationBuilder.CreateTable( - name: "Clients", - columns: table => new - { - Id = table.Column(type: "integer", nullable: false) - .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), - ClientFIO = table.Column(type: "text", nullable: false), - Email = table.Column(type: "text", nullable: false), - Password = table.Column(type: "text", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Clients", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Components", - columns: table => new - { - Id = table.Column(type: "integer", nullable: false) - .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), - ComponentName = table.Column(type: "text", nullable: false), - Cost = table.Column(type: "double precision", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Components", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "Engines", - columns: table => new - { - Id = table.Column(type: "integer", nullable: false) - .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), - EngineName = table.Column(type: "text", nullable: false), - Price = table.Column(type: "double precision", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Engines", x => x.Id); - }); - - migrationBuilder.CreateTable( - name: "EngineComponents", - columns: table => new - { - Id = table.Column(type: "integer", nullable: false) - .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), - EngineId = table.Column(type: "integer", nullable: false), - ComponentId = table.Column(type: "integer", nullable: false), - Count = table.Column(type: "integer", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_EngineComponents", x => x.Id); - table.ForeignKey( - name: "FK_EngineComponents_Components_ComponentId", - column: x => x.ComponentId, - principalTable: "Components", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - table.ForeignKey( - name: "FK_EngineComponents_Engines_EngineId", - column: x => x.EngineId, - principalTable: "Engines", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateTable( - name: "Orders", - columns: table => new - { - Id = table.Column(type: "integer", nullable: false) - .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), - EngineId = table.Column(type: "integer", nullable: false), - ClientId = table.Column(type: "integer", nullable: false), - Count = table.Column(type: "integer", nullable: false), - Sum = table.Column(type: "double precision", nullable: false), - Status = table.Column(type: "integer", nullable: false), - DateCreate = table.Column(type: "timestamp without time zone", nullable: false), - DateImplement = table.Column(type: "timestamp without time zone", nullable: true) - }, - constraints: table => - { - table.PrimaryKey("PK_Orders", x => x.Id); - table.ForeignKey( - name: "FK_Orders_Engines_EngineId", - column: x => x.EngineId, - principalTable: "Engines", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); - }); - - migrationBuilder.CreateIndex( - name: "IX_EngineComponents_ComponentId", - table: "EngineComponents", - column: "ComponentId"); - - migrationBuilder.CreateIndex( - name: "IX_EngineComponents_EngineId", - table: "EngineComponents", - column: "EngineId"); - - migrationBuilder.CreateIndex( - name: "IX_Orders_EngineId", - table: "Orders", - column: "EngineId"); - } - - /// - protected override void Down(MigrationBuilder migrationBuilder) - { - migrationBuilder.DropTable( - name: "Clients"); - - migrationBuilder.DropTable( - name: "EngineComponents"); - - migrationBuilder.DropTable( - name: "Orders"); - - migrationBuilder.DropTable( - name: "Components"); - - migrationBuilder.DropTable( - name: "Engines"); - } - } -} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs index bc260ac..93bc711 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/MotorPlantDatabaseModelSnapshot.cs @@ -149,6 +149,59 @@ namespace MotorPlantDatabaseImplement.Migrations 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") @@ -177,6 +230,25 @@ namespace MotorPlantDatabaseImplement.Migrations .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"); @@ -188,6 +260,11 @@ namespace MotorPlantDatabaseImplement.Migrations b.Navigation("Orders"); }); + + modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Shop", b => + { + b.Navigation("Engines"); + }); #pragma warning restore 612, 618 } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs index 1951de7..9635b5e 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs @@ -11,6 +11,8 @@ namespace MotorPlantDatabaseImplement.Models public int Id { get; private set; } public int EngineId { get; private set; } + public virtual Engine Engine { get; set; } = new(); + [Required] public int ClientId { get; private set; } @@ -28,6 +30,8 @@ namespace MotorPlantDatabaseImplement.Models public DateTime? DateImplement { get; private set; } + public static Order Create(MotorPlantDatabase context, OrderBindingModel model) + { public static Order? Create(OrderBindingModel? model) { if (model == null) @@ -38,12 +42,13 @@ namespace MotorPlantDatabaseImplement.Models { Id = model.Id, EngineId = model.EngineId, + Engine = context.Engines.First(x => x.Id == model.EngineId), + Count = model.Count, ClientId = model.ClientId, Count = model.Count, Sum = model.Sum, Status = model.Status, DateCreate = model.DateCreate, - DateImplement = model.DateImplement }; } @@ -61,6 +66,8 @@ namespace MotorPlantDatabaseImplement.Models { Id = Id, EngineId = EngineId, + EngineName = Engine.EngineName, + Count = Count, ClientId = ClientId, Count = Count, Sum = Sum, diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs new file mode 100644 index 0000000..7eda723 --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs @@ -0,0 +1,114 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDatabaseImplement.Models +{ + public class Shop : IShopModel + { + public int Id { 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 + { + get + { + if (_shopEngines == null) + { + _shopEngines = Engines.ToDictionary(x => x.EngineId, x => (x.Engine as IEngineModel, x.Count)); + } + return _shopEngines; + } + } + [ForeignKey("ShopId")] + public virtual List Engines { get; set; } = new(); + public static Shop? Create(MotorPlantDatabase context, ShopBindingModel model) + { + if (model == null) + return null; + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + DateOpen = model.DateOpen, + MaxCount = model.MaxCount, + Engines = model.ShopEngines.Select(x => new ShopEngine + { + Engine = context.Engines.First(y => y.Id == x.Key), + Count = x.Value.Item2 + }).ToList() + }; + } + public void Update(ShopBindingModel? model) + { + if (model == null) + return; + ShopName = model.ShopName; + Adress = model.Adress; + DateOpen = model.DateOpen; + MaxCount = model.MaxCount; + } + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + DateOpen = DateOpen, + MaxCount = MaxCount, + ShopEngines = ShopEngines + }; + + public void UpdateEngines(MotorPlantDatabase context, ShopBindingModel model) + { + var shopEngines = context.ShopEngines.Where(rec => rec.ShopId == model.Id).ToList(); + if (shopEngines != null && shopEngines.Count > 0) + { + context.ShopEngines.RemoveRange(shopEngines.Where(rec => !model.ShopEngines.ContainsKey(rec.EngineId))); + context.SaveChanges(); + foreach (var uEngine in shopEngines) + { + uEngine.Count = model.ShopEngines[uEngine.EngineId].Item2; + model.ShopEngines.Remove(uEngine.EngineId); + } + context.SaveChanges(); + } + var shop = context.Shops.First(x => x.Id == Id); + foreach (var pc in model.ShopEngines) + { + context.ShopEngines.Add(new ShopEngine + { + Shop = shop, + Engine = context.Engines.First(x => x.Id == pc.Key), + Count = pc.Value.Item2 + }); + context.SaveChanges(); + } + _shopEngines = null; + } + + public void EnginesDictionatyUpdate(MotorPlantDatabase context) + { + UpdateEngines(context, new ShopBindingModel + { + Id = Id, + ShopEngines = ShopEngines, + }); + } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/ShopEngine.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/ShopEngine.cs new file mode 100644 index 0000000..c6ed0c0 --- /dev/null +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/ShopEngine.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDatabaseImplement.Models +{ + public class ShopEngine + { + public int Id { get; set; } + [Required] + public int EngineId { get; set; } + [Required] + public int ShopId { get; set; } + [Required] + public int Count { get; set; } + public virtual Shop Shop { get; set; } = new(); + public virtual Engine Engine { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabase.cs b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabase.cs index 9e8c49d..a56fc23 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabase.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/MotorPlantDatabase.cs @@ -9,7 +9,7 @@ namespace MotorPlantDatabaseImplement { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=MotorPlant_db;Username=postgres;Password=admin"); + optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=MotorPlantHard_db;Username=postgres;Password=admin"); } base.OnConfiguring(optionsBuilder); AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); @@ -19,6 +19,9 @@ namespace MotorPlantDatabaseImplement public virtual DbSet Engines { get; set; } public virtual DbSet EngineComponents { get; set; } public virtual DbSet Orders { get; set; } + public virtual DbSet Shops { get; set; } + public virtual DbSet ShopEngines { get; set; } + } public virtual DbSet Clients { set; get; } } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs b/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs index 5863f05..20e7f76 100644 --- a/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs +++ b/MotorPlant/MotorPlantFileImplement/DataFileSingleton.cs @@ -13,6 +13,9 @@ namespace MotorPlantFileImplement private readonly string EngineFileName = "Engine.xml"; + private readonly string ShopFileName = "Shop.xml"; + + public List Components { get; private set; } private readonly string ClientFileName = "Client.xml"; public List Components { get; private set; } @@ -21,6 +24,9 @@ namespace MotorPlantFileImplement public List Engines { get; private set; } + public List Shops { get; private set; } + + public static DataFileSingleton GetInstance() public List Clients { get; private set; } public static DataFileSingleton GetInstance() @@ -37,6 +43,9 @@ namespace MotorPlantFileImplement public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); + public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement); + + private DataFileSingleton() public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); private DataFileSingleton() @@ -46,6 +55,8 @@ namespace MotorPlantFileImplement Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; } + Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!; + } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { diff --git a/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs b/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs new file mode 100644 index 0000000..ae401af --- /dev/null +++ b/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs @@ -0,0 +1,147 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using MotorPlantFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantFileImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataFileSingleton _source; + public ShopStorage() + { + _source = DataFileSingleton.GetInstance(); + } + public List GetFullList() + { + return _source.Shops.Select(x => x.GetViewModel).ToList(); + } + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name)) + { + return new(); + } + return _source.Shops.Where(x => x.ShopName.Contains(model.Name)).Select(x => x.GetViewModel).ToList(); + + } + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + return _source.Shops.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.ShopName == model.Name) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = _source.Shops.Count > 0 ? _source.Shops.Max(x => x.Id) + 1 : 1; + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + _source.Shops.Add(newShop); + _source.SaveShops(); + return newShop.GetViewModel; + } + public ShopViewModel? Update(ShopBindingModel model) + { + var component = _source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (component == null) + { + return null; + } + component.Update(model); + _source.SaveShops(); + return component.GetViewModel; + } + public ShopViewModel? Delete(ShopBindingModel model) + { + var element = _source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + _source.Shops.Remove(element); + _source.SaveShops(); + return element.GetViewModel; + } + return null; + } + + public bool SellEngines(SupplySearchModel model) + { + 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; + } + + 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/Engine.cs b/MotorPlant/MotorPlantFileImplement/Models/Engine.cs index 47f3f3c..e00f328 100644 --- a/MotorPlant/MotorPlantFileImplement/Models/Engine.cs +++ b/MotorPlant/MotorPlantFileImplement/Models/Engine.cs @@ -7,7 +7,7 @@ namespace MotorPlantFileImplement.Models { public class Engine : IEngineModel { - public int Id { get; private set; } + public int Id { get; private set; } public string EngineName { get; private set; } = string.Empty; public double Price { get; private set; } public Dictionary Components { get; private set; } = new(); diff --git a/MotorPlant/MotorPlantFileImplement/Models/Shop.cs b/MotorPlant/MotorPlantFileImplement/Models/Shop.cs new file mode 100644 index 0000000..8c17a87 --- /dev/null +++ b/MotorPlant/MotorPlantFileImplement/Models/Shop.cs @@ -0,0 +1,107 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace MotorPlantFileImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + public string ShopName { get; private set; } + public string Adress { get; private set; } + public DateTime DateOpen { get; private set; } + public int MaxCount { get; private set; } + public Dictionary Engines { get; private set; } = new(); + private Dictionary? _shopEngines = null; + + public Dictionary ShopEngines + { + get + { + if (_shopEngines == null) + { + var source = DataFileSingleton.GetInstance(); + _shopEngines = Engines.ToDictionary(x => x.Key, y => ((source.Engines.FirstOrDefault(z => z.Id == y.Key) as IEngineModel)!, y.Value)); + } + return _shopEngines; + } + } + public static Shop? Create(ShopBindingModel model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + DateOpen = model.DateOpen, + MaxCount = model.MaxCount, + Engines = model.ShopEngines.ToDictionary(x => x.Key, x => x.Value.Item2) + }; + } + public static Shop? Create(XElement element) + { + if (element == null) + { + return null; + } + return new Shop() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ShopName = element.Element("ShopName")!.Value, + Adress = element.Element("Adress")!.Value, + MaxCount = Convert.ToInt32(element.Element("MaxCount")!.Value), + DateOpen = Convert.ToDateTime(element.Element("DateOpen")!.Value), + Engines = element.Element("ShopEngines")!.Elements("ShopEngine").ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) + }; + + } + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Adress = model.Adress; + DateOpen = model.DateOpen; + MaxCount = model.MaxCount; + if (model.ShopEngines.Count > 0) + { + Engines = model.ShopEngines.ToDictionary(x => x.Key, x => x.Value.Item2); + _shopEngines = null; + } + } + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + DateOpen = DateOpen, + MaxCount = MaxCount, + ShopEngines = ShopEngines + }; + + public XElement GetXElement => new XElement("Shop", + new XAttribute("Id", Id), + new XElement("ShopName", ShopName), + new XElement("Adress", Adress), + 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/DataListSingleton.cs b/MotorPlant/MotorPlantListImplement/DataListSingleton.cs index fb1b04a..cdd9430 100644 --- a/MotorPlant/MotorPlantListImplement/DataListSingleton.cs +++ b/MotorPlant/MotorPlantListImplement/DataListSingleton.cs @@ -12,6 +12,9 @@ namespace MotorPlantListImplement public List Engines { get; set; } + public List Shops { get; set; } + + private DataListSingleton() public List Clients { get; set; } private DataListSingleton() @@ -19,6 +22,8 @@ namespace MotorPlantListImplement Components = new List(); Orders = new List(); Engines = new List(); + Shops = new List(); + } Clients = new List(); } diff --git a/MotorPlant/MotorPlantListImplement/Implements/OrderStorage.cs b/MotorPlant/MotorPlantListImplement/Implements/OrderStorage.cs index f223056..90b6ebc 100644 --- a/MotorPlant/MotorPlantListImplement/Implements/OrderStorage.cs +++ b/MotorPlant/MotorPlantListImplement/Implements/OrderStorage.cs @@ -14,28 +14,28 @@ namespace MotorPlantListImplement.Implements { public class OrderStorage : IOrderStorage { - private readonly DataListSingleton _source; - public OrderStorage() - { - _source = DataListSingleton.GetInstance(); - } - public List GetFullList() - { - var result = new List(); - foreach (var order in _source.Orders) - { - result.Add(AttachNames(order.GetViewModel)); - } - return result; - } - public List GetFilteredList(OrderSearchModel model) - { - var result = new List(); - if (model == null || !model.Id.HasValue) - { - return result; - } - if (model.ClientId.HasValue) + private readonly DataListSingleton _source; + public OrderStorage() + { + _source = DataListSingleton.GetInstance(); + } + public List GetFullList() + { + var result = new List(); + foreach (var order in _source.Orders) + { + result.Add(AttachEngineName(order.GetViewModel)); + } + return result; + } + public List GetFilteredList(OrderSearchModel model) + { + var result = new List(); + if (model == null) + { + return result; + } + if (!model.DateFrom.HasValue || !model.DateTo.HasValue) { foreach (var order in _source.Orders) { diff --git a/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs b/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..c52700e --- /dev/null +++ b/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs @@ -0,0 +1,121 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using MotorPlantListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantListImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataListSingleton _source; + public ShopStorage() + { + _source = DataListSingleton.GetInstance(); + } + public List GetFullList() + { + var result = new List(); + foreach (var shop in _source.Shops) + { + result.Add(shop.GetViewModel); + } + return result; + } + public List GetFilteredList(ShopSearchModel model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.Name)) + { + return result; + } + foreach (var shop in _source.Shops) + { + if (shop.ShopName.Contains(model.Name)) + { + result.Add(shop.GetViewModel); + } + } + return result; + } + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) + { + return null; + } + foreach (var shop in _source.Shops) + { + if ((!string.IsNullOrEmpty(model.Name) && + shop.ShopName == model.Name) || + (model.Id.HasValue && shop.Id == model.Id)) + { + return shop.GetViewModel; + } + } + return null; + } + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = 1; + foreach (var shop in _source.Shops) + { + if (model.Id <= shop.Id) + { + model.Id = shop.Id + 1; + } + } + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + _source.Shops.Add(newShop); + return newShop.GetViewModel; + } + public ShopViewModel? Update(ShopBindingModel model) + { + foreach (var shop in _source.Shops) + { + if (shop.Id == model.Id) + { + shop.Update(model); + return shop.GetViewModel; + } + } + return null; + } + public ShopViewModel? Delete(ShopBindingModel model) + { + for (int i = 0; i < _source.Shops.Count; ++i) + { + if (_source.Shops[i].Id == model.Id) + { + var element = _source.Shops[i]; + _source.Shops.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } + public bool CheckAvailability(int engineId, int count) + { + return true; + } + public bool SellEngines(SupplySearchModel model) + { + throw new NotImplementedException(); + } + + public bool RestockingShops(SupplyBindingModel model) + { + throw new NotImplementedException(); + } + } +} diff --git a/MotorPlant/MotorPlantListImplement/Models/Shop.cs b/MotorPlant/MotorPlantListImplement/Models/Shop.cs new file mode 100644 index 0000000..05ac9bd --- /dev/null +++ b/MotorPlant/MotorPlantListImplement/Models/Shop.cs @@ -0,0 +1,58 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantListImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + public string ShopName { get; private set; } + public string Adress { get; private set; } + public DateTime DateOpen { get; private set; } + public int MaxCount { get; private set; } + public Dictionary ShopEngines { get; private set; } = new(); + public static Shop? Create(ShopBindingModel model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + DateOpen = model.DateOpen, + MaxCount = model.MaxCount, + ShopEngines = new() + }; + } + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Adress = model.Adress; + DateOpen = model.DateOpen; + MaxCount = model.MaxCount; + ShopEngines = model.ShopEngines; + } + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + DateOpen = DateOpen, + MaxCount = MaxCount, + ShopEngines = ShopEngines + }; + } +} diff --git a/MotorPlant/MotorPlantView/FormEngines.cs b/MotorPlant/MotorPlantView/FormEngines.cs index 7e129dc..0c6692a 100644 --- a/MotorPlant/MotorPlantView/FormEngines.cs +++ b/MotorPlant/MotorPlantView/FormEngines.cs @@ -15,11 +15,6 @@ namespace MotorPlantView.Forms _logic = logic; } - private void FormEngines_Load(object sender, EventArgs e) - { - LoadData(); - } - private void LoadData() { try @@ -37,7 +32,13 @@ namespace MotorPlantView.Forms catch (Exception ex) { _logger.LogError(ex, "Ошибка загрузки компонентов"); - } + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void FormEngines_Load(object sender, EventArgs e) + { + LoadData(); } private void buttonAdd_Click(object sender, EventArgs e) diff --git a/MotorPlant/MotorPlantView/FormMain.Designer.cs b/MotorPlant/MotorPlantView/FormMain.Designer.cs index ff4a3b5..ca693dd 100644 --- a/MotorPlant/MotorPlantView/FormMain.Designer.cs +++ b/MotorPlant/MotorPlantView/FormMain.Designer.cs @@ -22,6 +22,234 @@ #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() + { + toolStrip1 = new ToolStrip(); + 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(); + buttonIssuedOrder = new Button(); + buttonRef = new Button(); + dataGridView = new DataGridView(); + toolStrip1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // toolStrip1 + // + toolStrip1.ImageScalingSize = new Size(20, 20); + toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, отчетыToolStripMenuItem }); + toolStrip1.Location = new Point(0, 0); + toolStrip1.Name = "toolStrip1"; + toolStrip1.Size = new Size(985, 25); + toolStrip1.TabIndex = 0; + toolStrip1.Text = "toolStrip1"; + // + // toolStripDropDownButton1 + // + toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; + toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, магазиныToolStripMenuItem, поставкаToolStripMenuItem, продажаToolStripMenuItem }); + toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; + toolStripDropDownButton1.Name = "toolStripDropDownButton1"; + toolStripDropDownButton1.Size = new Size(88, 22); + toolStripDropDownButton1.Text = "Справочник"; + // + // Компоненты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.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, загруженностьМагазиновToolStripMenuItem, заказыПоГруппамToolStripMenuItem }); + отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; + отчетыToolStripMenuItem.Size = new Size(60, 25); + отчетыToolStripMenuItem.Text = "Отчеты"; + // + // списокДвигателей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; + // + // списокМагазинов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; + buttonCreateOrder.BackColor = SystemColors.ControlLight; + buttonCreateOrder.Location = new Point(797, 146); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(178, 30); + buttonCreateOrder.TabIndex = 1; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = false; + buttonCreateOrder.Click += buttonCreateOrder_Click; + // + // buttonTakeOrderInWork + // + buttonTakeOrderInWork.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonTakeOrderInWork.BackColor = SystemColors.ControlLight; + buttonTakeOrderInWork.Location = new Point(797, 194); + buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; + buttonTakeOrderInWork.Size = new Size(178, 30); + buttonTakeOrderInWork.TabIndex = 2; + buttonTakeOrderInWork.Text = "Отдать на выполнение"; + buttonTakeOrderInWork.UseVisualStyleBackColor = false; + buttonTakeOrderInWork.Click += buttonTakeOrderInWork_Click; + // + // buttonOrderReady + // + buttonOrderReady.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonOrderReady.BackColor = SystemColors.ControlLight; + buttonOrderReady.Location = new Point(797, 242); + buttonOrderReady.Name = "buttonOrderReady"; + buttonOrderReady.Size = new Size(178, 30); + buttonOrderReady.TabIndex = 3; + buttonOrderReady.Text = "Заказ готов"; + buttonOrderReady.UseVisualStyleBackColor = false; + buttonOrderReady.Click += buttonOrderReady_Click; + // + // buttonIssuedOrder + // + buttonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonIssuedOrder.BackColor = SystemColors.ControlLight; + buttonIssuedOrder.Location = new Point(797, 287); + buttonIssuedOrder.Name = "buttonIssuedOrder"; + buttonIssuedOrder.Size = new Size(178, 30); + buttonIssuedOrder.TabIndex = 4; + buttonIssuedOrder.Text = "Заказ выдан"; + buttonIssuedOrder.UseVisualStyleBackColor = false; + buttonIssuedOrder.Click += buttonIssuedOrder_Click; + // + // buttonRef + // + buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonRef.BackColor = SystemColors.ControlLight; + buttonRef.Location = new Point(797, 100); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(178, 30); + buttonRef.TabIndex = 5; + buttonRef.Text = "Обновить список"; + buttonRef.UseVisualStyleBackColor = false; + buttonRef.Click += buttonRef_Click; + // + // dataGridView + // + dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + dataGridView.BackgroundColor = SystemColors.ButtonHighlight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(0, 26); + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 24; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(780, 441); + dataGridView.TabIndex = 6; + // + // FormMain + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(985, 467); + Controls.Add(dataGridView); + Controls.Add(buttonRef); + Controls.Add(buttonIssuedOrder); + Controls.Add(buttonOrderReady); + Controls.Add(buttonTakeOrderInWork); + Controls.Add(buttonCreateOrder); + Controls.Add(toolStrip1); + Name = "FormMain"; + Text = "Моторный завод"; + Load += FormMain_Load; + toolStrip1.ResumeLayout(false); + toolStrip1.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. @@ -229,4 +457,25 @@ private ToolStripMenuItem списокЗаказовToolStripMenuItem; private ToolStripMenuItem клиентыToolStripMenuItem; } + private ToolStrip toolStrip1; + private Button buttonCreateOrder; + private Button buttonTakeOrderInWork; + private Button buttonOrderReady; + private Button buttonIssuedOrder; + private Button buttonRef; + private DataGridView dataGridView; + private ToolStripDropDownButton toolStripDropDownButton1; + 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; + 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 0822fab..88c3bd4 100644 --- a/MotorPlant/MotorPlantView/FormMain.cs +++ b/MotorPlant/MotorPlantView/FormMain.cs @@ -1,6 +1,7 @@ using Microsoft.Extensions.Logging; using MotorPlantContracts.BindingModels; using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantView; namespace MotorPlantView.Forms { @@ -167,6 +168,70 @@ namespace MotorPlantView.Forms } } + private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); + if (service is FormReportOrders form) + { + 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(); + } + } + } private void списокЗаказовToolStripMenuItem_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); 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.Designer.cs b/MotorPlant/MotorPlantView/FormSell.Designer.cs new file mode 100644 index 0000000..3696490 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSell.Designer.cs @@ -0,0 +1,122 @@ +namespace MotorPlantView +{ + partial class FormSell + { + /// + /// 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() + { + comboBoxEngine = new ComboBox(); + textBoxCount = new TextBox(); + buttonSave = new Button(); + buttonCancel = new Button(); + label1 = new Label(); + label2 = new Label(); + // + // comboBoxEngine + // + comboBoxEngine.FormattingEnabled = true; + comboBoxEngine.Location = new Point(110, 22); + comboBoxEngine.Margin = new Padding(3, 2, 3, 2); + comboBoxEngine.Name = "comboBoxEngine"; + comboBoxEngine.Size = new Size(133, 23); + comboBoxEngine.TabIndex = 0; + // + // textBoxCount + // + textBoxCount.Location = new Point(110, 71); + textBoxCount.Margin = new Padding(3, 2, 3, 2); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(133, 23); + textBoxCount.TabIndex = 1; + // + // buttonSave + // + buttonSave.Location = new Point(39, 129); + buttonSave.Margin = new Padding(3, 2, 3, 2); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(82, 22); + buttonSave.TabIndex = 2; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(160, 129); + buttonCancel.Margin = new Padding(3, 2, 3, 2); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(82, 22); + buttonCancel.TabIndex = 3; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(24, 25); + label1.Name = "label1"; + label1.Size = new Size(50, 15); + label1.TabIndex = 4; + label1.Text = "Движки"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(24, 74); + label2.Name = "label2"; + label2.Size = new Size(72, 15); + label2.TabIndex = 5; + label2.Text = "Количество"; + // + // FormSell + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(268, 176); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(textBoxCount); + Controls.Add(comboBoxEngine); + Margin = new Padding(3, 2, 3, 2); + Name = "FormSell"; + Text = "Продажа"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox comboBoxEngine; + private TextBox textBoxCount; + private Button buttonSave; + private Button buttonCancel; + private Label label1; + private Label label2; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormSell.cs b/MotorPlant/MotorPlantView/FormSell.cs new file mode 100644 index 0000000..a434303 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSell.cs @@ -0,0 +1,111 @@ +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; +using MotorPlantDataModels.Models; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.ViewModels; +using MotorPlantContracts.SearchModels; + +namespace MotorPlantView +{ + public partial class FormSell : Form + { + private readonly List? _engineList; + IShopLogic _shopLogic; + IEngineLogic _engineLogic; + public FormSell(IEngineLogic engineLogic, IShopLogic shopLogic) + { + InitializeComponent(); + _shopLogic = shopLogic; + _engineLogic = engineLogic; + _engineList = engineLogic.ReadList(null); + if (_engineList != null) + { + comboBoxEngine.DisplayMember = "EngineName"; + comboBoxEngine.ValueMember = "Id"; + comboBoxEngine.DataSource = _engineList; + comboBoxEngine.SelectedItem = null; + } + } + public int EngineId + { + get + { + return Convert.ToInt32(comboBoxEngine.SelectedValue); + } + set + { + comboBoxEngine.SelectedValue = value; + } + } + + public IEngineModel? EngineModel + { + get + { + if (_engineList == null) + { + return null; + } + foreach (var elem in _engineList) + { + if (elem.Id == EngineId) + { + return elem; + } + } + return null; + } + } + + + public int Count + { + get { return Convert.ToInt32(textBoxCount.Text); } + set + { textBoxCount.Text = value.ToString(); } + } + + private void buttonSave_Click(object sender, EventArgs e) + { + 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) + { + Close(); + } + } +} diff --git a/MotorPlant/MotorPlantView/FormSell.resx b/MotorPlant/MotorPlantView/FormSell.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSell.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/FormShop.Designer.cs b/MotorPlant/MotorPlantView/FormShop.Designer.cs new file mode 100644 index 0000000..a529389 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShop.Designer.cs @@ -0,0 +1,226 @@ +namespace MotorPlantView +{ + partial class FormShop + { + /// + /// 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() + { + dateTimePicker = new DateTimePicker(); + textBoxName = new TextBox(); + textBoxAdress = new TextBox(); + dataGridView = new DataGridView(); + IdColumn = new DataGridViewTextBoxColumn(); + Title = new DataGridViewTextBoxColumn(); + Cost = new DataGridViewTextBoxColumn(); + Count = new DataGridViewTextBoxColumn(); + buttonSave = new Button(); + buttonCancel = new Button(); + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + label4 = new Label(); + numeric = new NumericUpDown(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + ((System.ComponentModel.ISupportInitialize)numeric).BeginInit(); + SuspendLayout(); + // + // dateTimePicker + // + dateTimePicker.Location = new Point(625, 26); + dateTimePicker.Margin = new Padding(3, 2, 3, 2); + dateTimePicker.Name = "dateTimePicker"; + dateTimePicker.Size = new Size(219, 23); + dateTimePicker.TabIndex = 0; + // + // textBoxName + // + textBoxName.Location = new Point(625, 64); + textBoxName.Margin = new Padding(3, 2, 3, 2); + textBoxName.Name = "textBoxName"; + textBoxName.Size = new Size(219, 23); + textBoxName.TabIndex = 1; + // + // textBoxAdress + // + textBoxAdress.Location = new Point(625, 104); + textBoxAdress.Margin = new Padding(3, 2, 3, 2); + textBoxAdress.Name = "textBoxAdress"; + textBoxAdress.Size = new Size(219, 23); + textBoxAdress.TabIndex = 2; + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { IdColumn, Title, Cost, Count }); + dataGridView.Location = new Point(9, 24); + dataGridView.Margin = new Padding(3, 2, 3, 2); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(485, 285); + dataGridView.TabIndex = 3; + // + // IdColumn + // + IdColumn.HeaderText = "Номер платья"; + IdColumn.MinimumWidth = 6; + IdColumn.Name = "IdColumn"; + IdColumn.Visible = false; + IdColumn.Width = 125; + // + // Title + // + Title.HeaderText = "Название"; + Title.MinimumWidth = 6; + Title.Name = "Title"; + Title.Width = 125; + // + // Cost + // + Cost.HeaderText = "Цена"; + Cost.MinimumWidth = 6; + Cost.Name = "Cost"; + Cost.Width = 125; + // + // Count + // + Count.HeaderText = "Количество"; + Count.MinimumWidth = 6; + Count.Name = "Count"; + Count.Width = 125; + // + // buttonSave + // + buttonSave.Location = new Point(625, 179); + buttonSave.Margin = new Padding(3, 2, 3, 2); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(82, 22); + buttonSave.TabIndex = 4; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(761, 179); + buttonCancel.Margin = new Padding(3, 2, 3, 2); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(82, 22); + buttonCancel.TabIndex = 5; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(518, 29); + label1.Name = "label1"; + label1.Size = new Size(85, 15); + label1.TabIndex = 6; + label1.Text = "Дата создания"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(518, 66); + label2.Name = "label2"; + label2.Size = new Size(59, 15); + label2.TabIndex = 7; + label2.Text = "Название"; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(518, 106); + label3.Name = "label3"; + label3.Size = new Size(40, 15); + label3.TabIndex = 8; + label3.Text = "Адрес"; + // + // label4 + // + label4.AutoSize = true; + label4.Location = new Point(518, 144); + label4.Name = "label4"; + label4.Size = new Size(80, 15); + label4.TabIndex = 9; + label4.Text = "Вместимость"; + label4.TextAlign = ContentAlignment.TopCenter; + // + // numeric + // + numeric.Location = new Point(625, 142); + numeric.Margin = new Padding(3, 2, 3, 2); + numeric.Name = "numeric"; + numeric.Size = new Size(131, 23); + numeric.TabIndex = 10; + // + // FormShop + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(854, 338); + Controls.Add(numeric); + Controls.Add(label4); + Controls.Add(label3); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(dataGridView); + Controls.Add(textBoxAdress); + Controls.Add(textBoxName); + Controls.Add(dateTimePicker); + Margin = new Padding(3, 2, 3, 2); + Name = "FormShop"; + Text = "Форма магазина"; + Load += ShopForm_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ((System.ComponentModel.ISupportInitialize)numeric).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private DateTimePicker dateTimePicker; + private TextBox textBoxName; + private TextBox textBoxAdress; + private DataGridView dataGridView; + private Button buttonSave; + private Button buttonCancel; + private Label label1; + private Label label2; + private Label label3; + private DataGridViewTextBoxColumn IdColumn; + private DataGridViewTextBoxColumn Title; + private DataGridViewTextBoxColumn Cost; + private DataGridViewTextBoxColumn Count; + private Label label4; + private NumericUpDown numeric; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormShop.cs b/MotorPlant/MotorPlantView/FormShop.cs new file mode 100644 index 0000000..497ffe8 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShop.cs @@ -0,0 +1,123 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.SearchModels; +using MotorPlantDataModels.Models; +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 FormShop : Form + { + private readonly ILogger _logger; + private readonly IShopLogic _logic; + public int? _id; + private Dictionary _engines; + public FormShop(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void ShopForm_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Shop load"); + try + { + var shop = _logic.ReadElement(new ShopSearchModel { Id = _id }); + if (shop != null) + { + textBoxName.Text = shop.ShopName; + textBoxAdress.Text = shop.Adress; + dateTimePicker.Text = shop.DateOpen.ToString(); + numeric.Value = shop.MaxCount; + _engines = shop.ShopEngines ?? new Dictionary(); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Load shop error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + + private void LoadData() + { + _logger.LogInformation("Load engines"); + try + { + if (_engines != null) + { + foreach (var engine in _engines) + { + dataGridView.Rows.Add(new object[] { engine.Key, engine.Value.Item1.EngineName, engine.Value.Item1.Price, engine.Value.Item2 }); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Load engines into shop error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxAdress.Text)) + { + MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Save shop"); + try + { + var model = new ShopBindingModel + { + Id = _id ?? 0, + ShopName = textBoxName.Text, + Adress = textBoxAdress.Text, + DateOpen = dateTimePicker.Value.Date, + MaxCount = Convert.ToInt32(numeric.Value) + }; + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Save shop error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/MotorPlant/MotorPlantView/FormShop.resx b/MotorPlant/MotorPlantView/FormShop.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShop.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/FormShops.Designer.cs b/MotorPlant/MotorPlantView/FormShops.Designer.cs new file mode 100644 index 0000000..b4d34e3 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShops.Designer.cs @@ -0,0 +1,114 @@ +namespace MotorPlantView +{ + partial class FormShops + { + /// + /// 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() + { + dataGridView = new DataGridView(); + buttonAdd = new Button(); + buttonUpdate = new Button(); + buttonReset = new Button(); + buttonDelete = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.BackgroundColor = SystemColors.ButtonHighlight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(12, 12); + dataGridView.Name = "dataGridView"; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(617, 426); + dataGridView.TabIndex = 0; + // + // buttonAdd + // + buttonAdd.Location = new Point(665, 114); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(123, 45); + buttonAdd.TabIndex = 1; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += buttonAdd_Click; + // + // buttonUpdate + // + buttonUpdate.Location = new Point(665, 165); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(123, 44); + buttonUpdate.TabIndex = 2; + buttonUpdate.Text = "Изменить"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += buttonUpdate_Click; + // + // buttonReset + // + buttonReset.Location = new Point(665, 215); + buttonReset.Name = "buttonReset"; + buttonReset.Size = new Size(123, 48); + buttonReset.TabIndex = 3; + buttonReset.Text = "Обновить"; + buttonReset.UseVisualStyleBackColor = true; + buttonReset.Click += buttonReset_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(665, 269); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(123, 48); + buttonDelete.TabIndex = 4; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += buttonDelete_Click; + // + // FormShops + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(buttonDelete); + Controls.Add(buttonReset); + Controls.Add(buttonUpdate); + Controls.Add(buttonAdd); + Controls.Add(dataGridView); + Name = "FormShops"; + Text = "FormShops"; + Load += FormShops_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonAdd; + private Button buttonUpdate; + private Button buttonReset; + private Button buttonDelete; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormShops.cs b/MotorPlant/MotorPlantView/FormShops.cs new file mode 100644 index 0000000..8a4cbcb --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShops.cs @@ -0,0 +1,108 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantView.Forms; + +namespace MotorPlantView +{ + public partial class FormShops : Form + { + private readonly ILogger _logger; + private readonly IShopLogic _logic; + public FormShops(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["Adress"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["DateOpen"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ShopEngines"].Visible = false; + } + _logger.LogInformation("Load shops"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Load shop error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void FormShops_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void buttonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + if (service is FormShop form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void buttonUpdate_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + if (service is FormShop form) + { + var tmp = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + form._id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void buttonReset_Click(object sender, EventArgs e) + { + LoadData(); + } + + private void buttonDelete_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление магазина"); + try + { + if (!_logic.Delete(new ShopBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + } +} diff --git a/MotorPlant/MotorPlantView/FormShops.resx b/MotorPlant/MotorPlantView/FormShops.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormShops.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/FormSupply.Designer.cs b/MotorPlant/MotorPlantView/FormSupply.Designer.cs new file mode 100644 index 0000000..1b5719f --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSupply.Designer.cs @@ -0,0 +1,147 @@ +namespace MotorPlantView +{ + partial class FormSupply + { + /// + /// 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() + { + ShopComboBox = new ComboBox(); + EngineComboBox = new ComboBox(); + CountTextBox = new TextBox(); + SaveButton = new Button(); + Cancel = new Button(); + label1 = new Label(); + label2 = new Label(); + label3 = new Label(); + SuspendLayout(); + // + // ShopComboBox + // + ShopComboBox.FormattingEnabled = true; + ShopComboBox.Location = new Point(136, 26); + ShopComboBox.Margin = new Padding(3, 2, 3, 2); + ShopComboBox.Name = "ShopComboBox"; + ShopComboBox.Size = new Size(279, 23); + ShopComboBox.TabIndex = 0; + // + // EngineComboBox + // + EngineComboBox.FormattingEnabled = true; + EngineComboBox.Location = new Point(136, 59); + EngineComboBox.Margin = new Padding(3, 2, 3, 2); + EngineComboBox.Name = "EngineComboBox"; + EngineComboBox.Size = new Size(279, 23); + EngineComboBox.TabIndex = 1; + // + // CountTextBox + // + CountTextBox.Location = new Point(136, 96); + CountTextBox.Margin = new Padding(3, 2, 3, 2); + CountTextBox.Name = "CountTextBox"; + CountTextBox.Size = new Size(279, 23); + CountTextBox.TabIndex = 2; + // + // SaveButton + // + SaveButton.Location = new Point(220, 150); + SaveButton.Margin = new Padding(3, 2, 3, 2); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(94, 27); + SaveButton.TabIndex = 3; + SaveButton.Text = "Сохранить"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click; + // + // Cancel + // + Cancel.Location = new Point(319, 150); + Cancel.Margin = new Padding(3, 2, 3, 2); + Cancel.Name = "Cancel"; + Cancel.Size = new Size(94, 27); + Cancel.TabIndex = 4; + Cancel.Text = "Отмена"; + Cancel.UseVisualStyleBackColor = true; + Cancel.Click += CancelButton_Click; + // + // label1 + // + label1.AutoSize = true; + label1.Location = new Point(35, 28); + label1.Name = "label1"; + label1.Size = new Size(54, 15); + label1.TabIndex = 5; + label1.Text = "Магазин"; + // + // label2 + // + label2.AutoSize = true; + label2.Location = new Point(35, 62); + label2.Name = "label2"; + label2.Size = new Size(64, 15); + label2.TabIndex = 6; + label2.Text = "Двигатели"; + // + // label3 + // + label3.AutoSize = true; + label3.Location = new Point(35, 98); + label3.Name = "label3"; + label3.Size = new Size(72, 15); + label3.TabIndex = 7; + label3.Text = "Количество"; + // + // FormSupply + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(443, 195); + Controls.Add(label3); + Controls.Add(label2); + Controls.Add(label1); + Controls.Add(Cancel); + Controls.Add(SaveButton); + Controls.Add(CountTextBox); + Controls.Add(EngineComboBox); + Controls.Add(ShopComboBox); + Margin = new Padding(3, 2, 3, 2); + Name = "FormSupply"; + Text = "Форма поставки"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox ShopComboBox; + private ComboBox EngineComboBox; + private TextBox CountTextBox; + private Button SaveButton; + private Button Cancel; + private Label label1; + private Label label2; + private Label label3; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormSupply.cs b/MotorPlant/MotorPlantView/FormSupply.cs new file mode 100644 index 0000000..aa0174d --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSupply.cs @@ -0,0 +1,127 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.ViewModels; +using MotorPlantDataModels.Models; + +namespace MotorPlantView +{ + public partial class FormSupply : Form + { + private readonly List? _engineList; + private readonly List? _shopsList; + IShopLogic _shopLogic; + IEngineLogic _engineLogic; + public int ShopId + { + get + { + return Convert.ToInt32(ShopComboBox.SelectedValue); + } + set + { + ShopComboBox.SelectedValue = value; + } + } + public int EngineId + { + get + { + return Convert.ToInt32(EngineComboBox.SelectedValue); + } + set + { + EngineComboBox.SelectedValue = value; + } + } + + public IEngineModel? EngineModel + { + get + { + if (_engineList == null) + { + return null; + } + foreach (var elem in _engineList) + { + if (elem.Id == EngineId) + { + return elem; + } + } + return null; + } + } + + + public int Count + { + get { return Convert.ToInt32(CountTextBox.Text); } + set + { CountTextBox.Text = value.ToString(); } + } + public FormSupply(IEngineLogic engineLogic, IShopLogic shopLogic) + { + InitializeComponent(); + _shopLogic = shopLogic; + _engineLogic = engineLogic; + _engineList = engineLogic.ReadList(null); + _shopsList = shopLogic.ReadList(null); + if (_engineList != null) + { + EngineComboBox.DisplayMember = "EngineName"; + EngineComboBox.ValueMember = "Id"; + EngineComboBox.DataSource = _engineList; + EngineComboBox.SelectedItem = null; + } + if (_shopsList != null) + { + ShopComboBox.DisplayMember = "ShopName"; + ShopComboBox.ValueMember = "Id"; + ShopComboBox.DataSource = _shopsList; + ShopComboBox.SelectedItem = null; + } + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (ShopComboBox.SelectedValue == null) + { + MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (EngineComboBox.SelectedValue == null) + { + MessageBox.Show("Выберите пиццу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + try + { + var operationResult = _shopLogic.MakeSupply(new SupplyBindingModel + { + ShopId = Convert.ToInt32(ShopComboBox.SelectedValue), + EngineId = Convert.ToInt32(EngineComboBox.SelectedValue), + Count = Convert.ToInt32(CountTextBox.Text) + }); + if (!operationResult) + { + throw new Exception("Ошибка при создании поставки. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void CancelButton_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/MotorPlant/MotorPlantView/FormSupply.resx b/MotorPlant/MotorPlantView/FormSupply.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormSupply.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/Program.cs b/MotorPlant/MotorPlantView/Program.cs index e64216c..5dcd292 100644 --- a/MotorPlant/MotorPlantView/Program.cs +++ b/MotorPlant/MotorPlantView/Program.cs @@ -43,12 +43,16 @@ namespace MotorPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -62,8 +66,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(); + services.AddTransient(); services.AddTransient(); } } 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 +