diff --git a/.gitignore b/.gitignore index ca1c7a3..7f76508 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,11 @@ # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs +# dll файлы +*.dll + +/MotorPlant/ImplementationExtensions + # Mono auto generated files mono_crash.* diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs index c3322c1..3277e2f 100644 --- a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/OrderLogic.cs @@ -14,15 +14,12 @@ namespace MotorPlantBusinessLogic.BusinessLogics private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; private readonly IShopStorage _shopStorage; - private readonly IShopLogic _shopLogic; - private readonly IEngineStorage _engineStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IEngineStorage engineStorage) + + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IShopStorage shopStorage) { _logger = logger; _orderStorage = orderStorage; _shopStorage = shopStorage; - _shopLogic = shopLogic; - _engineStorage = engineStorage; } public List? ReadList(OrderSearchModel? model) @@ -38,22 +35,31 @@ namespace MotorPlantBusinessLogic.BusinessLogics return list; } - private void CheckModel(OrderBindingModel model) + private void CheckModel(OrderBindingModel model, bool WithParams = true) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - if (model.Count <= 0) - { - throw new ArgumentNullException("Количество заказов должно быть больше нуля"); - } - if (model.Sum <= 0) - { - throw new ArgumentNullException("Цена заказа должна быть больше нуля"); - } - _logger.LogInformation("Order. OrderId:{Id}. Sum:{Sum}", model.Id, model.Sum); - } + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!WithParams) + { + return; + } + if (model.Count <= 0) + { + throw new ArgumentException("Количество движков в заказе не может быть меньше 1", nameof(model.Count)); + } + if (model.Sum <= 0) + { + throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum)); + } + if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) + { + throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}"); + } + _logger.LogInformation("Pizza. PizzaId:{PizzaId}.Count:{Count}.Sum:{Sum}Id:{Id}", + model.EngineId, model.Count, model.Sum, model.Id); + } public bool CreateOrder(OrderBindingModel model) { @@ -72,38 +78,38 @@ namespace MotorPlantBusinessLogic.BusinessLogics } - private bool ChangeStatus(OrderBindingModel model, OrderStatus status) + private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus) { - var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); - if (element == null) - { - _logger.LogWarning("Find order failed"); - return false; - } - if (element.Status != status - 1) - { - _logger.LogWarning("Status change failed"); - throw new InvalidOperationException("Невозможно перевести состояние заказа"); - } - if (status == OrderStatus.Готов) - { - var engine = _engineStorage.GetElement(new EngineSearchModel() { Id = model.EngineId }); - if (engine == null) - { - _logger.LogWarning("Status change error. Engine not found"); - return false; - } - if (!CheckSupply(engine, model.Count)) - { - _logger.LogWarning("Status change error. Shop doesnt have engines"); - return false; - } - } - model.Status = status; - if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; - _orderStorage.Update(model); - return true; - } + CheckModel(model, false); + var element = _orderStorage.GetElement(new OrderSearchModel() + { + Id = model.Id + }); + if (element == null) + { + throw new ArgumentNullException(nameof(element)); + } + model.DateCreate = element.DateCreate; + model.EngineId = element.EngineId; + model.DateImplement = element.DateImplement; + model.Status = element.Status; + model.Count = element.Count; + model.Sum = element.Sum; + if (requiredStatus - model.Status == 1) + { + model.Status = requiredStatus; + if (model.Status == OrderStatus.Выдан) + model.DateImplement = DateTime.Now; + if (_orderStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); + throw new ArgumentException($"Невозможно присвоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); + } public bool TakeOrderInWork(OrderBindingModel model) { @@ -117,67 +123,24 @@ namespace MotorPlantBusinessLogic.BusinessLogics public bool DeliveryOrder(OrderBindingModel model) { - return ChangeStatus(model, OrderStatus.Выдан); - } + var order = _orderStorage.GetElement(new OrderSearchModel + { + Id = model.Id, + }); + if (order == null) + { + throw new ArgumentNullException(nameof(order)); + } + if (!_shopStorage.RestockingShops(new SupplyBindingModel + { + EngineId = order.EngineId, + Count = order.Count + })) + { + throw new ArgumentException("Недостаточно места"); + } - public bool CheckSupply(IEngineModel engine, int count) - { - if (count <= 0) - { - _logger.LogWarning("Check supply operation error. Engine count < 0"); - return false; - } - int sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCount).Sum(); - int sumCount = _shopStorage.GetFullList().Select(x => x.ShopEngines.Select(y => y.Value.Item2).Sum()).Sum(); - int free = sumCapacity - sumCount; - - if (free < count) - { - _logger.LogWarning("Check supply error. No place for new Engines"); - return false; - } - foreach (var shop in _shopStorage.GetFullList()) - { - free = shop.MaxCount; - foreach (var doc in shop.ShopEngines) - { - free -= doc.Value.Item2; - } - if (free == 0) - { - continue; - } - if (free >= count) - { - if (_shopLogic.MakeSupply(new() - { - Id = shop.Id - }, engine, count)) - { - count = 0; - } - else - { - _logger.LogWarning("Supply error"); - return false; - } - } - else - { - if (_shopLogic.MakeSupply(new() { Id = shop.Id }, engine, free)) - count -= free; - else - { - _logger.LogWarning("Supply error"); - return false; - } - } - if (count <= 0) - { - return true; - } - } - return false; - } + return ChangeStatus(model, OrderStatus.Выдан); + } } } diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ReportLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ReportLogic.cs new file mode 100644 index 0000000..a9e051d --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ReportLogic.cs @@ -0,0 +1,147 @@ +using MotorPlantBusinessLogic.OfficePackage; +using MotorPlantBusinessLogic.OfficePackage.HelperModels; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.SearchModels; +using MotorPlantContracts.StoragesContracts; +using MotorPlantContracts.ViewModels; + +namespace MotorPlantBusinessLogic.BusinessLogic +{ + public class ReportLogic : IReportLogic + { + private readonly IComponentStorage _componentStorage; + + 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, IShopStorage shopStorage, + AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf) + { + _engineStorage = engineStorage; + _componentStorage = componentStorage; + _orderStorage = orderStorage; + _shopStorage = shopStorage; + + _saveToExcel = saveToExcel; + _saveToWord = saveToWord; + _saveToPdf = saveToPdf; + } + + public List GetEngineComponents() + { + + return _engineStorage.GetFullList().Select(x => new ReportEngineComponentViewModel + { + 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) + { + return _orderStorage.GetFilteredList(new OrderSearchModel { DateFrom = model.DateFrom, DateTo = model.DateTo }) + .Select(x => new ReportOrdersViewModel + { + Id = x.Id, + DateCreate = x.DateCreate, + EngineName = x.EngineName, + OrderStatus = x.Status.ToString(), + Sum = x.Sum + }) + .ToList(); + } + + public void SaveEngineToWordFile(ReportBindingModel model) + { + _saveToWord.CreateDoc(new WordInfo + { + FileName = model.FileName, + Title = "Список двигателей", + Engine = _engineStorage.GetFullList() + }); + } + + public void SaveEngineComponentToExcelFile(ReportBindingModel model) + { + _saveToExcel.CreateReport(new ExcelInfo + { + FileName = model.FileName, + Title = "Список двигателей", + EngineComponents = GetEngineComponents() + }); + } + + public void SaveOrdersToPdfFile(ReportBindingModel model) + { + _saveToPdf.CreateDoc(new PdfInfo + { + FileName = model.FileName, + Title = "Список заказов", + DateFrom = model.DateFrom!.Value, + DateTo = model.DateTo!.Value, + Orders = GetOrders(model) + }); + } + + public List GetShops() + { + return _shopStorage.GetFullList().Select(x => new ReportShopsViewModel + { + ShopName = x.ShopName, + Engines = x.ShopEngines.Select(x => (x.Value.Item1.EngineName, x.Value.Item2)).ToList(), + TotalCount = x.ShopEngines.Select(x => x.Value.Item2).Sum() + }).ToList(); + } + + public List GetGroupedOrders() + { + return _orderStorage.GetFullList().GroupBy(x => x.DateCreate.Date).Select(x => new ReportGroupOrdersViewModel + { + Date = x.Key, + OrdersCount = x.Count(), + OrdersSum = x.Select(y => y.Sum).Sum() + }).ToList(); + } + + public void SaveShopsToWordFile(ReportBindingModel model) + { + _saveToWord.CreateShopsDoc(new WordShopInfo + { + FileName = model.FileName, + Title = "Список магазинов", + Shops = _shopStorage.GetFullList() + }); + } + + public void SaveShopsToExcelFile(ReportBindingModel model) + { + _saveToExcel.CreateShopEnginesReport(new ExcelShop + { + FileName = model.FileName, + Title = "Наполненость магазинов", + ShopEngines = GetShops() + }); + } + + public void SaveGroupedOrdersToPdfFile(ReportBindingModel model) + { + _saveToPdf.CreateGroupedOrdersDoc(new PdfGroupedOrdersInfo + { + FileName = model.FileName, + Title = "Список заказов сгруппированных по дате заказов", + GroupedOrders = GetGroupedOrders() + }); + } + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs index 35e65a1..a645ef6 100644 --- a/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs +++ b/MotorPlant/MotorPlantBusinessLogic/BusinessLogic/ShopLogic.cs @@ -17,11 +17,13 @@ namespace MotorPlantBusinessLogic.BusinessLogic { private readonly ILogger _logger; private readonly IShopStorage _shopStorage; + private readonly IEngineStorage _engineStorage; - public ShopLogic(ILogger logger, IShopStorage shopStorage) + public ShopLogic(ILogger logger, IShopStorage shopStorage, IEngineStorage engineStorage) { _logger = logger; _shopStorage = shopStorage; + _engineStorage = engineStorage; } public List ReadList(ShopSearchModel model) @@ -75,6 +77,7 @@ namespace MotorPlantBusinessLogic.BusinessLogic } return true; } + public bool Delete(ShopBindingModel model) { CheckModel(model, false); @@ -123,52 +126,70 @@ namespace MotorPlantBusinessLogic.BusinessLogic } } - public bool MakeSell(IEngineModel model, int count) - { - return _shopStorage.SellEngines(model, count); - } - - public bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count) + public bool MakeSupply(SupplyBindingModel model) { - if (model == null) - throw new ArgumentNullException(nameof(model)); - if (engine == null) - throw new ArgumentNullException(nameof(engine)); - if (count <= 0) - throw new ArgumentNullException("Количество должно быть положительным числом"); + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (model.Count <= 0) + { + throw new ArgumentException("Количество движков должно быть больше 0"); + } + var shop = _shopStorage.GetElement(new ShopSearchModel + { + Id = model.ShopId + }); + if (shop == null) + { + throw new ArgumentException("Магазина не существует"); + } + if (shop.ShopEngines.ContainsKey(model.EngineId)) + { + var oldValue = shop.ShopEngines[model.EngineId]; + oldValue.Item2 += model.Count; + shop.ShopEngines[model.EngineId] = oldValue; + } + else + { + var pizza = _engineStorage.GetElement(new EngineSearchModel + { + Id = model.EngineId + }); + if (pizza == null) + { + throw new ArgumentException($"Поставка: Товар с id:{model.EngineId} не найденн"); + } + shop.ShopEngines.Add(model.EngineId, (pizza, model.Count)); + } - ShopViewModel? curModel = _shopStorage.GetElement(model); - _logger.LogInformation("Make Supply. Id: {Id}. ShopName: {Name}", model.Id, model.Name); - if (curModel == null) - throw new ArgumentNullException(nameof(curModel)); + _shopStorage.Update(new ShopBindingModel() + { + Id = shop.Id, + ShopName = shop.ShopName, + Adress = shop.Adress, + DateOpen = shop.DateOpen, + ShopEngines = shop.ShopEngines, + MaxCount = shop.MaxCount, + }); - var countItems = curModel.ShopEngines.Select(x => x.Value.Item2).Sum(); - if (curModel.MaxCount - countItems < count) - { - _logger.LogWarning("Shop is overflowed"); - return false; - } + return true; + } - if (curModel.ShopEngines.TryGetValue(engine.Id, out var pair)) - { - curModel.ShopEngines[engine.Id] = (pair.Item1, pair.Item2 + count); - _logger.LogInformation("Make Supply. Add Dress. ShopName: {ShopName}. DressName: {Name}. Count: {Count}", curModel.ShopName, pair.Item1, count + pair.Item2); - } - else - { - curModel.ShopEngines.Add(engine.Id, (engine, count)); - _logger.LogInformation("Make Supply. Add new Dress. ShopName: {ShopName}. DressName: {Name}. Count: {Count}", curModel.ShopName, pair.Item1, count); - } - - return Update(new() - { - Id = curModel.Id, - ShopName = curModel.ShopName, - DateOpen = curModel.DateOpen, - MaxCount = curModel.MaxCount, - Adress = curModel.Adress, - ShopEngines = curModel.ShopEngines, - }); - } + public bool MakeSell(SupplySearchModel model) + { + if (!model.EngineId.HasValue || !model.Count.HasValue) + { + return false; + } + _logger.LogInformation("Check pizza count in all shops"); + if (_shopStorage.SellEngines(model)) + { + _logger.LogInformation("Selling sucsess"); + return true; + } + _logger.LogInformation("Selling failed"); + return false; + } } } diff --git a/MotorPlant/MotorPlantBusinessLogic/MotorPlantBusinessLogic.csproj b/MotorPlant/MotorPlantBusinessLogic/MotorPlantBusinessLogic.csproj index 3558ce0..5d4f1a4 100644 --- a/MotorPlant/MotorPlantBusinessLogic/MotorPlantBusinessLogic.csproj +++ b/MotorPlant/MotorPlantBusinessLogic/MotorPlantBusinessLogic.csproj @@ -7,8 +7,10 @@ + + diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs new file mode 100644 index 0000000..819aae3 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs @@ -0,0 +1,164 @@ +using MotorPlantBusinessLogic.OfficePackage.HelperEnums; +using MotorPlantBusinessLogic.OfficePackage.HelperModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage +{ + public abstract class AbstractSaveToExcel + { + /// + /// Создание отчета + /// + /// + public void CreateReport(ExcelInfo info) + { + CreateExcel(info); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = 1, + Text = info.Title, + StyleInfo = ExcelStyleInfoType.Title + }); + + MergeCells(new ExcelMergeParameters + { + CellFromName = "A1", + CellToName = "C1" + }); + + uint rowIndex = 2; + foreach (var ic in info.EngineComponents) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = ic.EngineName, + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + + foreach (var (Component, Count) in ic.Components) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = Component, + 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 = ic.TotalCount.ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + } + + SaveExcel(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(IDocument info); + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs new file mode 100644 index 0000000..1611779 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs @@ -0,0 +1,112 @@ +using MotorPlantBusinessLogic.OfficePackage.HelperEnums; +using MotorPlantBusinessLogic.OfficePackage.HelperModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage +{ + public abstract class AbstractSaveToPdf + { + public void CreateDoc(PdfInfo info) + { + CreatePdf(info); + CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + CreateParagraph(new PdfParagraph + { + Text = $"с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}", + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + CreateTable(new List { "2cm", "3cm", "6cm", "4cm", "3cm" }); + + CreateRow(new PdfRowParameters + { + Texts = new List { "Номер", "Дата заказа", "Двигатель", "Статус", "Сумма" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + foreach (var order in info.Orders) + { + CreateRow(new PdfRowParameters + { + Texts = new List { order.Id.ToString(), order.DateCreate.ToShortDateString(), order.EngineName, order.Sum.ToString(), order.OrderStatus }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + CreateParagraph(new PdfParagraph + { + Text = $"Итого: {info.Orders.Sum(x => x.Sum)}\t", + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Right + }); + 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(IDocument info); + + /// + /// Создание параграфа с текстом + /// + /// + /// + protected abstract void CreateParagraph(PdfParagraph paragraph); + + /// + /// Создание таблицы + /// + /// + /// + protected abstract void CreateTable(List columns); + + /// + /// Создание и заполнение строки + /// + /// + protected abstract void CreateRow(PdfRowParameters rowParameters); + + /// + /// Сохранение файла + /// + /// + protected abstract void SavePdf(IDocument info); + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs new file mode 100644 index 0000000..7223858 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs @@ -0,0 +1,91 @@ +using MotorPlantBusinessLogic.OfficePackage.HelperEnums; +using MotorPlantBusinessLogic.OfficePackage.HelperModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage +{ + public abstract class AbstractSaveToWord + { + public void CreateDoc(WordInfo info) + { + CreateWord(info); + + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + + foreach (var engine in info.Engine) + { + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> {(engine.EngineName + " - ", new WordTextProperties { Size = "24", Bold = true}), + (engine.Price.ToString(), new WordTextProperties { Size = "24", })}, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Both + } + }); + } + + SaveWord(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(IDocument info); + protected abstract void CreateTable(List colums); + protected abstract void CreateRow(WordRowParameters rowParameters); + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs new file mode 100644 index 0000000..46dc1f8 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperEnums/ExcelStyleInfoType.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperEnums +{ + public enum ExcelStyleInfoType + { + Title, + + Text, + + TextWithBorder + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs new file mode 100644 index 0000000..7fa1ba9 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperEnums/PdfParagraphAlignmentType.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperEnums +{ + public enum PdfParagraphAlignmentType + { + Center, + + Left, + + Right + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs new file mode 100644 index 0000000..6e46b9b --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperEnums/WordJustificationType.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperEnums +{ + public enum WordJustificationType + { + Center, + + Both + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs new file mode 100644 index 0000000..0059ba6 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelCellParameters.cs @@ -0,0 +1,22 @@ +using MotorPlantBusinessLogic.OfficePackage.HelperEnums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperModels +{ + public class ExcelCellParameters + { + public string ColumnName { get; set; } = string.Empty; + + public uint RowIndex { get; set; } + + public string Text { get; set; } = string.Empty; + + public string CellReference => $"{ColumnName}{RowIndex}"; + + public ExcelStyleInfoType StyleInfo { get; set; } + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs new file mode 100644 index 0000000..c32d036 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs @@ -0,0 +1,18 @@ +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 ExcelInfo : IDocument + { + public string FileName { get; set; } = string.Empty; + + public string Title { get; set; } = string.Empty; + + public List EngineComponents { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs new file mode 100644 index 0000000..bec8b0e --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/ExcelMergeParameters.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperModels +{ + public class ExcelMergeParameters + { + public string CellFromName { get; set; } = string.Empty; + + public string CellToName { get; set; } = string.Empty; + + public string Merge => $"{CellFromName}:{CellToName}"; + } +} diff --git a/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 new file mode 100644 index 0000000..f919683 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs @@ -0,0 +1,22 @@ +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 PdfInfo : 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 Orders { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs new file mode 100644 index 0000000..200b549 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfParagraph.cs @@ -0,0 +1,18 @@ +using MotorPlantBusinessLogic.OfficePackage.HelperEnums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperModels +{ + public class PdfParagraph + { + public string Text { get; set; } = string.Empty; + + public string Style { get; set; } = string.Empty; + + public PdfParagraphAlignmentType ParagraphAlignment { get; set; } + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs new file mode 100644 index 0000000..dff6ba7 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/PdfRowParameters.cs @@ -0,0 +1,18 @@ +using MotorPlantBusinessLogic.OfficePackage.HelperEnums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperModels +{ + public class PdfRowParameters + { + public List Texts { get; set; } = new(); + + public string Style { get; set; } = string.Empty; + + public PdfParagraphAlignmentType ParagraphAlignment { get; set; } + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs new file mode 100644 index 0000000..0a03ba5 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs @@ -0,0 +1,18 @@ +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 WordInfo : IDocument + { + public string FileName { get; set; } = string.Empty; + + public string Title { get; set; } = string.Empty; + + public List Engine { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordParagraph.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordParagraph.cs new file mode 100644 index 0000000..c71e2b2 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordParagraph.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperModels +{ + public class WordParagraph + { + public List<(string, WordTextProperties)> Texts { get; set; } = new(); + + public WordTextProperties? TextProperties { get; set; } + } +} 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/HelperModels/WordTextProperties.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordTextProperties.cs new file mode 100644 index 0000000..2d497cb --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/HelperModels/WordTextProperties.cs @@ -0,0 +1,18 @@ +using MotorPlantBusinessLogic.OfficePackage.HelperEnums; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantBusinessLogic.OfficePackage.HelperModels +{ + public class WordTextProperties + { + public string Size { get; set; } = string.Empty; + + public bool Bold { get; set; } + + public WordJustificationType JustificationType { get; set; } + } +} diff --git a/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 new file mode 100644 index 0000000..3808437 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToExcel.cs @@ -0,0 +1,293 @@ +using DocumentFormat.OpenXml.Office2010.Excel; +using DocumentFormat.OpenXml.Office2013.Excel; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using DocumentFormat.OpenXml; +using MotorPlantBusinessLogic.OfficePackage.HelperEnums; +using MotorPlantBusinessLogic.OfficePackage.HelperModels; + + +namespace MotorPlantBusinessLogic.OfficePackage.Implements +{ + public class SaveToExcel : AbstractSaveToExcel + { + private SpreadsheetDocument? _spreadsheetDocument; + + private SharedStringTablePart? _shareStringPart; + + private Worksheet? _worksheet; + + /// + /// Настройка стилей для файла + /// + /// + private static void CreateStyles(WorkbookPart workbookpart) + { + var sp = workbookpart.AddNewPart(); + sp.Stylesheet = new Stylesheet(); + + var fonts = new Fonts() { Count = 2U, KnownFonts = true }; + + var fontUsual = new Font(); + fontUsual.Append(new FontSize() { Val = 12D }); + fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U }); + fontUsual.Append(new FontName() { Val = "Times New Roman" }); + fontUsual.Append(new FontFamilyNumbering() { Val = 2 }); + fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor }); + + var fontTitle = new Font(); + fontTitle.Append(new Bold()); + fontTitle.Append(new FontSize() { Val = 14D }); + fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Theme = 1U }); + fontTitle.Append(new FontName() { Val = "Times New Roman" }); + fontTitle.Append(new FontFamilyNumbering() { Val = 2 }); + fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor }); + + fonts.Append(fontUsual); + fonts.Append(fontTitle); + + var fills = new Fills() { Count = 2U }; + + var fill1 = new Fill(); + fill1.Append(new PatternFill() { PatternType = PatternValues.None }); + + var fill2 = new Fill(); + fill2.Append(new PatternFill() { PatternType = PatternValues.Gray125 }); + + fills.Append(fill1); + fills.Append(fill2); + + var borders = new Borders() { Count = 2U }; + + var borderNoBorder = new Border(); + borderNoBorder.Append(new LeftBorder()); + borderNoBorder.Append(new RightBorder()); + borderNoBorder.Append(new TopBorder()); + borderNoBorder.Append(new BottomBorder()); + borderNoBorder.Append(new DiagonalBorder()); + + var borderThin = new Border(); + + var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin }; + leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); + + var rightBorder = new RightBorder() { Style = BorderStyleValues.Thin }; + rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); + + var topBorder = new TopBorder() { Style = BorderStyleValues.Thin }; + topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); + + var bottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin }; + bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); + + borderThin.Append(leftBorder); + borderThin.Append(rightBorder); + borderThin.Append(topBorder); + borderThin.Append(bottomBorder); + borderThin.Append(new DiagonalBorder()); + + borders.Append(borderNoBorder); + borders.Append(borderThin); + + var cellStyleFormats = new CellStyleFormats() { Count = 1U }; + var cellFormatStyle = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U }; + + cellStyleFormats.Append(cellFormatStyle); + + var cellFormats = new CellFormats() { Count = 3U }; + var cellFormatFont = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 0U, FormatId = 0U, ApplyFont = true }; + var cellFormatFontAndBorder = new CellFormat() { NumberFormatId = 0U, FontId = 0U, FillId = 0U, BorderId = 1U, FormatId = 0U, ApplyFont = true, ApplyBorder = true }; + var cellFormatTitle = new CellFormat() { NumberFormatId = 0U, FontId = 1U, FillId = 0U, BorderId = 0U, FormatId = 0U, Alignment = new Alignment() { Vertical = VerticalAlignmentValues.Center, WrapText = true, Horizontal = HorizontalAlignmentValues.Center }, ApplyFont = true }; + + cellFormats.Append(cellFormatFont); + cellFormats.Append(cellFormatFontAndBorder); + cellFormats.Append(cellFormatTitle); + + var cellStyles = new CellStyles() { Count = 1U }; + + cellStyles.Append(new CellStyle() { Name = "Normal", FormatId = 0U, BuiltinId = 0U }); + + var differentialFormats = new DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats() { Count = 0U }; + + var tableStyles = new TableStyles() { Count = 0U, DefaultTableStyle = "TableStyleMedium2", DefaultPivotStyle = "PivotStyleLight16" }; + + var stylesheetExtensionList = new StylesheetExtensionList(); + + var stylesheetExtension1 = new StylesheetExtension() { Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" }; + stylesheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"); + stylesheetExtension1.Append(new SlicerStyles() { DefaultSlicerStyle = "SlicerStyleLight1" }); + + var stylesheetExtension2 = new StylesheetExtension() { Uri = "{9260A510-F301-46a8-8635-F512D64BE5F5}" }; + stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"); + stylesheetExtension2.Append(new TimelineStyles() { DefaultTimelineStyle = "TimeSlicerStyleLight1" }); + + stylesheetExtensionList.Append(stylesheetExtension1); + stylesheetExtensionList.Append(stylesheetExtension2); + + sp.Stylesheet.Append(fonts); + sp.Stylesheet.Append(fills); + sp.Stylesheet.Append(borders); + sp.Stylesheet.Append(cellStyleFormats); + sp.Stylesheet.Append(cellFormats); + sp.Stylesheet.Append(cellStyles); + sp.Stylesheet.Append(differentialFormats); + sp.Stylesheet.Append(tableStyles); + sp.Stylesheet.Append(stylesheetExtensionList); + } + + /// + /// Получение номера стиля из типа + /// + /// + /// + private static uint GetStyleValue(ExcelStyleInfoType styleInfo) + { + return styleInfo switch + { + ExcelStyleInfoType.Title => 2U, + ExcelStyleInfoType.TextWithBorder => 1U, + ExcelStyleInfoType.Text => 0U, + _ => 0U, + }; + } + + protected override void CreateExcel(IDocument info) + { + _spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook); + // Создаем книгу (в ней хранятся листы) + var workbookpart = _spreadsheetDocument.AddWorkbookPart(); + workbookpart.Workbook = new Workbook(); + + CreateStyles(workbookpart); + + // Получаем/создаем хранилище текстов для книги + _shareStringPart = _spreadsheetDocument.WorkbookPart!.GetPartsOfType().Any() + ? _spreadsheetDocument.WorkbookPart.GetPartsOfType().First() + : _spreadsheetDocument.WorkbookPart.AddNewPart(); + + // Создаем SharedStringTable, если его нет + if (_shareStringPart.SharedStringTable == null) + { + _shareStringPart.SharedStringTable = new SharedStringTable(); + } + + // Создаем лист в книгу + var worksheetPart = workbookpart.AddNewPart(); + worksheetPart.Worksheet = new Worksheet(new SheetData()); + + // Добавляем лист в книгу + var sheets = _spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets()); + var sheet = new Sheet() + { + Id = _spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), + SheetId = 1, + Name = "Лист" + }; + sheets.Append(sheet); + + _worksheet = worksheetPart.Worksheet; + } + + protected override void InsertCellInWorksheet(ExcelCellParameters excelParams) + { + if (_worksheet == null || _shareStringPart == null) + { + return; + } + var sheetData = _worksheet.GetFirstChild(); + if (sheetData == null) + { + return; + } + + // Ищем строку, либо добавляем ее + Row row; + if (sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).Any()) + { + row = sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).First(); + } + else + { + row = new Row() { RowIndex = excelParams.RowIndex }; + sheetData.Append(row); + } + + // Ищем нужную ячейку + Cell cell; + if (row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).Any()) + { + cell = row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).First(); + } + else + { + // Все ячейки должны быть последовательно друг за другом расположены + // нужно определить, после какой вставлять + Cell? refCell = null; + foreach (Cell rowCell in row.Elements()) + { + if (string.Compare(rowCell.CellReference!.Value, excelParams.CellReference, true) > 0) + { + refCell = rowCell; + break; + } + } + + var newCell = new Cell() { CellReference = excelParams.CellReference }; + row.InsertBefore(newCell, refCell); + + cell = newCell; + } + + // вставляем новый текст + _shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(excelParams.Text))); + _shareStringPart.SharedStringTable.Save(); + + cell.CellValue = new CellValue((_shareStringPart.SharedStringTable.Elements().Count() - 1).ToString()); + cell.DataType = new EnumValue(CellValues.SharedString); + cell.StyleIndex = GetStyleValue(excelParams.StyleInfo); + } + + protected override void MergeCells(ExcelMergeParameters excelParams) + { + if (_worksheet == null) + { + return; + } + MergeCells mergeCells; + + if (_worksheet.Elements().Any()) + { + mergeCells = _worksheet.Elements().First(); + } + else + { + mergeCells = new MergeCells(); + + if (_worksheet.Elements().Any()) + { + _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); + } + else + { + _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); + } + } + + var mergeCell = new MergeCell() + { + Reference = new StringValue(excelParams.Merge) + }; + mergeCells.Append(mergeCell); + } + + protected override void SaveExcel(IDocument info) + { + if (_spreadsheetDocument == null) + { + return; + } + _spreadsheetDocument.WorkbookPart!.Workbook.Save(); + _spreadsheetDocument.Dispose(); + } + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToPdf.cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToPdf.cs new file mode 100644 index 0000000..f1d91ab --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToPdf.cs @@ -0,0 +1,109 @@ +using MotorPlantBusinessLogic.OfficePackage.HelperEnums; +using MotorPlantBusinessLogic.OfficePackage.HelperModels; +using MigraDoc.DocumentObjectModel; +using MigraDoc.DocumentObjectModel.Tables; +using MigraDoc.Rendering; + + +namespace MotorPlantBusinessLogic.OfficePackage.Implements +{ + public class SaveToPdf : AbstractSaveToPdf + { + private Document? _document; + private Section? _section; + private Table? _table; + + private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type) + { + return type switch + { + PdfParagraphAlignmentType.Center => ParagraphAlignment.Center, + PdfParagraphAlignmentType.Left => ParagraphAlignment.Left, + PdfParagraphAlignmentType.Right => ParagraphAlignment.Right, + _ => ParagraphAlignment.Justify, + }; + } + + private static void DefineStyles(Document document) + { + var style = document.Styles["Normal"]; + style.Font.Name = "Times New Roman"; + style.Font.Size = 14; + + style = document.Styles.AddStyle("NormalTitle", "Normal"); + style.Font.Bold = true; + } + + protected override void CreatePdf(IDocument info) + { + _document = new Document(); + DefineStyles(_document); + + _section = _document.AddSection(); + } + + protected override void CreateParagraph(PdfParagraph pdfParagraph) + { + if (_section == null) + { + return; + } + var paragraph = _section.AddParagraph(pdfParagraph.Text); + paragraph.Format.SpaceAfter = "1cm"; + paragraph.Format.Alignment = GetParagraphAlignment(pdfParagraph.ParagraphAlignment); + paragraph.Style = pdfParagraph.Style; + } + + protected override void CreateTable(List columns) + { + if (_document == null) + { + return; + } + _table = _document.LastSection.AddTable(); + + foreach (var elem in columns) + { + _table.AddColumn(elem); + } + } + + protected override void CreateRow(PdfRowParameters rowParameters) + { + if (_table == null) + { + return; + } + var row = _table.AddRow(); + for (int i = 0; i < rowParameters.Texts.Count; ++i) + { + row.Cells[i].AddParagraph(rowParameters.Texts[i]); + + if (!string.IsNullOrEmpty(rowParameters.Style)) + { + row.Cells[i].Style = rowParameters.Style; + } + + Unit borderWidth = 0.5; + + row.Cells[i].Borders.Left.Width = borderWidth; + row.Cells[i].Borders.Right.Width = borderWidth; + row.Cells[i].Borders.Top.Width = borderWidth; + row.Cells[i].Borders.Bottom.Width = borderWidth; + + row.Cells[i].Format.Alignment = GetParagraphAlignment(rowParameters.ParagraphAlignment); + row.Cells[i].VerticalAlignment = VerticalAlignment.Center; + } + } + + protected override void SavePdf(IDocument info) + { + var renderer = new PdfDocumentRenderer(true) + { + Document = _document + }; + renderer.RenderDocument(); + renderer.PdfDocument.Save(info.FileName); + } + } +} diff --git a/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToWord .cs b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToWord .cs new file mode 100644 index 0000000..b3f15f6 --- /dev/null +++ b/MotorPlant/MotorPlantBusinessLogic/OfficePackage/Implements/SaveToWord .cs @@ -0,0 +1,207 @@ +using MotorPlantBusinessLogic.OfficePackage.HelperEnums; +using MotorPlantBusinessLogic.OfficePackage.HelperModels; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; + +namespace MotorPlantBusinessLogic.OfficePackage.Implements +{ + public class SaveToWord : AbstractSaveToWord + { + private WordprocessingDocument? _wordDocument; + + private Body? _docBody; + + /// + /// Получение типа выравнивания + /// + /// + /// + private static JustificationValues GetJustificationValues(WordJustificationType type) + { + return type switch + { + WordJustificationType.Both => JustificationValues.Both, + WordJustificationType.Center => JustificationValues.Center, + _ => JustificationValues.Left, + }; + } + + /// + /// Настройки страницы + /// + /// + private static SectionProperties CreateSectionProperties() + { + var properties = new SectionProperties(); + + var pageSize = new PageSize + { + Orient = PageOrientationValues.Portrait + }; + + properties.AppendChild(pageSize); + + return properties; + } + + /// + /// Задание форматирования для абзаца + /// + /// + /// + private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties) + { + if (paragraphProperties == null) + { + return null; + } + + var properties = new ParagraphProperties(); + + properties.AppendChild(new Justification() + { + Val = GetJustificationValues(paragraphProperties.JustificationType) + }); + + properties.AppendChild(new SpacingBetweenLines + { + LineRule = LineSpacingRuleValues.Auto + }); + + properties.AppendChild(new Indentation()); + + var paragraphMarkRunProperties = new ParagraphMarkRunProperties(); + if (!string.IsNullOrEmpty(paragraphProperties.Size)) + { + paragraphMarkRunProperties.AppendChild(new FontSize { Val = paragraphProperties.Size }); + } + properties.AppendChild(paragraphMarkRunProperties); + + return properties; + } + + protected override void CreateWord(IDocument info) + { + _wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document); + MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart(); + mainPart.Document = new Document(); + _docBody = mainPart.Document.AppendChild(new Body()); + } + + protected override void CreateParagraph(WordParagraph paragraph) + { + if (_docBody == null || paragraph == null) + { + return; + } + var docParagraph = new Paragraph(); + + docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties)); + + foreach (var run in paragraph.Texts) + { + var docRun = new Run(); + + var properties = new RunProperties(); + properties.AppendChild(new FontSize { Val = run.Item2.Size }); + if (run.Item2.Bold) + { + properties.AppendChild(new Bold()); + } + docRun.AppendChild(properties); + + docRun.AppendChild(new Text { Text = run.Item1, Space = SpaceProcessingModeValues.Preserve }); + + docParagraph.AppendChild(docRun); + } + + _docBody.AppendChild(docParagraph); + } + + protected override void SaveWord(IDocument info) + { + if (_docBody == null || _wordDocument == null) + { + return; + } + _docBody.AppendChild(CreateSectionProperties()); + + _wordDocument.MainDocumentPart!.Document.Save(); + + _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/ReportBindingModel.cs b/MotorPlant/MotorPlantContracts/BindingModels/ReportBindingModel.cs new file mode 100644 index 0000000..f2f911c --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BindingModels/ReportBindingModel.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BindingModels +{ + public class ReportBindingModel + { + public string FileName { get; set; } = string.Empty; + + public DateTime? DateFrom { get; set; } + + public DateTime? DateTo { get; set;} + } +} 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 new file mode 100644 index 0000000..3ca180e --- /dev/null +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IReportLogic.cs @@ -0,0 +1,24 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.BusinessLogicsContracts +{ + public interface IReportLogic + { + List GetEngineComponents(); + List GetOrders(ReportBindingModel model); + List GetShops(); + List GetGroupedOrders(); + void SaveEngineToWordFile(ReportBindingModel model); + void SaveEngineComponentToExcelFile(ReportBindingModel model); + void SaveOrdersToPdfFile(ReportBindingModel model); + void SaveShopsToWordFile(ReportBindingModel model); + void SaveShopsToExcelFile(ReportBindingModel model); + void SaveGroupedOrdersToPdfFile(ReportBindingModel model); + } +} diff --git a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs index ce4f7b0..bfa3267 100644 --- a/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs +++ b/MotorPlant/MotorPlantContracts/BusinessLogicsContracts/IShopLogic.cs @@ -14,10 +14,10 @@ namespace MotorPlantContracts.BusinessLogicsContracts { List? ReadList(ShopSearchModel? model); ShopViewModel? ReadElement(ShopSearchModel? model); - bool Create(ShopBindingModel? model); - bool Update(ShopBindingModel? model); - bool Delete(ShopBindingModel? model); - bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count); - bool MakeSell(IEngineModel model, int count); + bool Create(ShopBindingModel model); + bool Update(ShopBindingModel model); + bool Delete(ShopBindingModel model); + bool MakeSupply(SupplyBindingModel model); + bool MakeSell(SupplySearchModel model); } } diff --git a/MotorPlant/MotorPlantContracts/SearchModels/OrderSearchModel.cs b/MotorPlant/MotorPlantContracts/SearchModels/OrderSearchModel.cs index 2255ebd..93427fe 100644 --- a/MotorPlant/MotorPlantContracts/SearchModels/OrderSearchModel.cs +++ b/MotorPlant/MotorPlantContracts/SearchModels/OrderSearchModel.cs @@ -3,5 +3,9 @@ public class OrderSearchModel { public int? Id { get; set; } + + public DateTime? DateFrom { get; set; } + + public DateTime? DateTo { 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 index 0fb2755..a0369c0 100644 --- a/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs +++ b/MotorPlant/MotorPlantContracts/StoragesContracts/IShopStorage.cs @@ -18,6 +18,7 @@ namespace MotorPlantContracts.StoragesContracts ShopViewModel? Insert(ShopBindingModel model); ShopViewModel? Update(ShopBindingModel model); ShopViewModel? Delete(ShopBindingModel model); - bool SellEngines(IEngineModel model, int count); - } + bool SellEngines(SupplySearchModel model); + bool RestockingShops(SupplyBindingModel model); + } } diff --git a/MotorPlant/MotorPlantContracts/ViewModels/ReportEngineComponentViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/ReportEngineComponentViewModel.cs new file mode 100644 index 0000000..a76ad07 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/ViewModels/ReportEngineComponentViewModel.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantContracts.ViewModels +{ + public class ReportEngineComponentViewModel + { + public string EngineName { get; set; } = string.Empty; + + public int TotalCount { get; set; } + + public List<(string Component, int Count)> Components { get; set; } = new(); + } +} 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/ReportOrdersViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/ReportOrdersViewModel.cs new file mode 100644 index 0000000..a30a6c4 --- /dev/null +++ b/MotorPlant/MotorPlantContracts/ViewModels/ReportOrdersViewModel.cs @@ -0,0 +1,15 @@ +namespace MotorPlantContracts.ViewModels +{ + public class ReportOrdersViewModel + { + public int Id { get; set; } + + public DateTime DateCreate { get; set; } + + public string EngineName { get; set; } = string.Empty; + + public string OrderStatus { get; set; } = string.Empty; + + public double Sum { get; set; } + } +} diff --git a/MotorPlant/MotorPlantContracts/ViewModels/ReportShopsViewModel.cs b/MotorPlant/MotorPlantContracts/ViewModels/ReportShopsViewModel.cs new file mode 100644 index 0000000..747752d --- /dev/null +++ b/MotorPlant/MotorPlantContracts/ViewModels/ReportShopsViewModel.cs @@ -0,0 +1,9 @@ +namespace MotorPlantContracts.ViewModels +{ + public class ReportShopsViewModel + { + public string ShopName { get; set; } = string.Empty; + public int TotalCount { get; set; } + public List<(string Engine, int count)> Engines { get; set; } = new(); + } +} diff --git a/MotorPlant/MotorPlantDataModels/Models/ISupplyModel.cs b/MotorPlant/MotorPlantDataModels/Models/ISupplyModel.cs new file mode 100644 index 0000000..f243749 --- /dev/null +++ b/MotorPlant/MotorPlantDataModels/Models/ISupplyModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MotorPlantDataModels.Models +{ + public interface ISupplyModel + { + int ShopId { get; } + int EngineId { get; } + int Count { get; } + } +} diff --git a/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs b/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs index ae20ebb..25fd2e5 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Implements/OrderStorage.cs @@ -13,81 +13,83 @@ namespace MotorPlantDatabaseImplement.Implements public List GetFullList() { using var context = new MotorPlantDatabase(); - return context.Orders - .Select(x => AccessEngineStorage(x.GetViewModel)) - .ToList(); - } + return context.Orders.Include(x => x.Engine).Select(x => x.GetViewModel).ToList(); + } public List GetFilteredList(OrderSearchModel model) { - if (!model.Id.HasValue) + if (!model.Id.HasValue && !model.DateFrom.HasValue) { return new(); } using var context = new MotorPlantDatabase(); - return context.Orders.Where(x => x.Id == model.Id).Select(x => AccessEngineStorage(x.GetViewModel)).ToList(); - } + if (model.DateFrom.HasValue) + { + return context.Orders + .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 AccessEngineStorage(context.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel); - } + if (!model.Id.HasValue) + { + return null; + } + using var context = new MotorPlantDatabase(); + return context.Orders.Include(x => x.Engine) + .FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; + } public OrderViewModel? Insert(OrderBindingModel model) { - var newOrder = Order.Create(model); - if (newOrder == null) - { - return null; - } - using var context = new MotorPlantDatabase(); - context.Orders.Add(newOrder); - context.SaveChanges(); - return AccessEngineStorage(newOrder.GetViewModel); - } + using var context = new MotorPlantDatabase(); + if (model == null) + return null; + var newOrder = Order.Create(context, model); + if (newOrder == null) + { + return null; + } + context.Orders.Add(newOrder); + context.SaveChanges(); + return newOrder.GetViewModel; + } public OrderViewModel? Update(OrderBindingModel model) { - using var context = new MotorPlantDatabase(); - var order = context.Orders.FirstOrDefault(x => x.Id == - model.Id); - if (order == null) - { - return null; - } - order.Update(model); - context.SaveChanges(); - return AccessEngineStorage(order.GetViewModel); - } - - public OrderViewModel? Delete(OrderBindingModel model) - { - using var context = new MotorPlantDatabase(); - var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); - if (element != null) - { - context.Orders.Remove(element); - context.SaveChanges(); - return AccessEngineStorage(element.GetViewModel); - } - return null; - } - - public static OrderViewModel AccessEngineStorage(OrderViewModel model) - { - if (model == null) - return null; - using var context = new MotorPlantDatabase(); - foreach (var Engine in context.Engines) - { - if (Engine.Id == model.EngineId) - { - model.EngineName = Engine.EngineName; - break; - } - } - return model; - } - } + using var context = new MotorPlantDatabase(); + var order = context.Orders.FirstOrDefault(x => x.Id == model.Id); + if (order == null) + { + return null; + } + order.Update(model); + context.SaveChanges(); + return context.Orders + .Include(x => x.Engine) + .FirstOrDefault(x => x.Id == model.Id) + ?.GetViewModel; + } + public OrderViewModel? Delete(OrderBindingModel model) + { + using var context = new MotorPlantDatabase(); + var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + var deletedElement = context.Orders + .Include(x => x.Engine) + .FirstOrDefault(x => x.Id == model.Id) + ?.GetViewModel; + context.Orders.Remove(element); + context.SaveChanges(); + return deletedElement; + } + return null; + } + } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs b/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs index 5772557..9984575 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Implements/ShopStorage.cs @@ -84,61 +84,117 @@ namespace MotorPlantDatabaseImplement.Implements public ShopViewModel? Update(ShopBindingModel model) { - using var context = new MotorPlantDatabase(); - var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id); - if (shop == null) - { - return null; - } - try - { - if (context.Shops.Any(x => (x.ShopName == model.ShopName && x.Id != model.Id))) - { - throw new Exception("Не должно быть два магазина с одним названием"); - } - shop.Update(model); - shop.UpdateDresses(context, model); - context.SaveChanges(); - return shop.GetViewModel; - } - catch - { - throw; - } - } - public bool SellEngines(IEngineModel model, int count) + using var context = new MotorPlantDatabase(); + using var transaction = context.Database.BeginTransaction(); + try + { + var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop == null) + { + return null; + } + shop.Update(model); + context.SaveChanges(); + shop.UpdateEngines(context, model); + transaction.Commit(); + return shop.GetViewModel; + } + catch + { + transaction.Rollback(); + throw; + } + } + + public bool RestockingShops(SupplyBindingModel model) + { + using var context = new MotorPlantDatabase(); + var transaction = context.Database.BeginTransaction(); + var Shops = context.Shops.Include(x => x.Engines).ThenInclude(x => x.Engine).ToList(). + Where(x => x.MaxCount > x.ShopEngines.Select(x => x.Value.Item2).Sum()).ToList(); + if (model == null) + { + return false; + } + try + { + foreach (Shop shop in Shops) + { + int difference = shop.MaxCount - shop.ShopEngines.Select(x => x.Value.Item2).Sum(); + int refill = Math.Min(difference, model.Count); + model.Count -= refill; + if (shop.ShopEngines.ContainsKey(model.EngineId)) + { + var datePair = shop.ShopEngines[model.EngineId]; + datePair.Item2 += refill; + shop.ShopEngines[model.EngineId] = datePair; + } + else + { + var pizza = context.Engines.First(x => x.Id == model.EngineId); + shop.ShopEngines.Add(model.EngineId, (pizza, refill)); + } + shop.EnginesDictionatyUpdate(context); + if (model.Count == 0) + { + transaction.Commit(); + return true; + } + } + transaction.Rollback(); + return false; + } + catch + { + transaction.Rollback(); + throw; + } + } + + public bool SellEngines(SupplySearchModel model) { - if (model == null) - return false; - using var context = new MotorPlantDatabase(); - using var transaction = context.Database.BeginTransaction(); - List lst = new List(); - foreach (var el in context.ShopEngines.Where(x => x.EngineId == model.Id)) - { - int dif = count; - if (el.Count < dif) - dif = el.Count; - el.Count -= dif; - count -= dif; - if (el.Count == 0) - { - lst.Add(el); - } - if (count == 0) - break; - } - if (count > 0) - { - transaction.Rollback(); - return false; - } - foreach (var el in lst) - { - context.ShopEngines.Remove(el); - } - context.SaveChanges(); - transaction.Commit(); - return true; - } + using var context = new MotorPlantDatabase(); + var transaction = context.Database.BeginTransaction(); + try + { + var shops = context.Shops.Include(x => x.Engines).ThenInclude(x => x.Engine).ToList(). + Where(x => x.ShopEngines.ContainsKey(model.EngineId.Value)).OrderByDescending(x => x.ShopEngines[model.EngineId.Value].Item2).ToList(); + + foreach (var shop in shops) + { + int residue = model.Count.Value - shop.ShopEngines[model.EngineId.Value].Item2; + if (residue > 0) + { + shop.ShopEngines.Remove(model.EngineId.Value); + shop.EnginesDictionatyUpdate(context); + context.SaveChanges(); + model.Count = residue; + + } + else + { + if (residue == 0) + shop.ShopEngines.Remove(model.EngineId.Value); + else + { + var dataPair = shop.ShopEngines[model.EngineId.Value]; + dataPair.Item2 = -residue; + shop.ShopEngines[model.EngineId.Value] = dataPair; + } + + shop.EnginesDictionatyUpdate(context); + transaction.Commit(); + return true; + } + } + transaction.Rollback(); + return false; + } + catch + { + transaction.Rollback(); + throw; + } + } } } diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.Designer.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.Designer.cs similarity index 99% rename from MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.Designer.cs rename to MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.Designer.cs index 1151db6..b967a0f 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.Designer.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.Designer.cs @@ -12,8 +12,8 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace MotorPlantDatabaseImplement.Migrations { [DbContext(typeof(MotorPlantDatabase))] - [Migration("20240411140319_NewMig")] - partial class NewMig + [Migration("20240516204547_ThirdMigtation")] + partial class ThirdMigtation { /// protected override void BuildTargetModel(ModelBuilder modelBuilder) diff --git a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.cs b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.cs similarity index 99% rename from MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.cs rename to MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.cs index 5a17410..9cf9cab 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240411140319_NewMig.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Migrations/20240516204547_ThirdMigtation.cs @@ -7,7 +7,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; namespace MotorPlantDatabaseImplement.Migrations { /// - public partial class NewMig : Migration + public partial class ThirdMigtation : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs index 7355218..5c6bc31 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Order.cs @@ -12,7 +12,7 @@ namespace MotorPlantDatabaseImplement.Models [Required] public int EngineId { get; private set; } - + public virtual Engine Engine { get; set; } = new(); [Required] public int Count { get; private set; } @@ -27,16 +27,13 @@ namespace MotorPlantDatabaseImplement.Models public DateTime? DateImplement { get; private set; } - public static Order? Create(OrderBindingModel? model) + public static Order Create(MotorPlantDatabase context, OrderBindingModel model) { - if (model == null) - { - return null; - } return new Order() { Id = model.Id, EngineId = model.EngineId, + Engine = context.Engines.First(x => x.Id == model.EngineId), Count = model.Count, Sum = model.Sum, Status = model.Status, @@ -58,6 +55,7 @@ namespace MotorPlantDatabaseImplement.Models { Id = Id, EngineId = EngineId, + EngineName = Engine.EngineName, Count = Count, Sum = Sum, Status = Status, diff --git a/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs b/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs index 1aa014d..7eda723 100644 --- a/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs +++ b/MotorPlant/MotorPlantDatabaseImplement/Models/Shop.cs @@ -15,16 +15,16 @@ namespace MotorPlantDatabaseImplement.Models { public int Id { get; private set; } [Required] - public string ShopName { get; private set; } - [Required] - public string Adress { get; private set; } - [Required] + public string ShopName { get; private set; } = string.Empty; + [Required] + public string Adress { get; private set; } = string.Empty; + [Required] public DateTime DateOpen { get; private set; } [Required] public int MaxCount { get; private set; } private Dictionary? _shopEngines = null; [NotMapped] - public Dictionary? ShopEngines + public Dictionary ShopEngines { get { @@ -74,7 +74,7 @@ namespace MotorPlantDatabaseImplement.Models ShopEngines = ShopEngines }; - public void UpdateDresses(MotorPlantDatabase context, ShopBindingModel model) + public void UpdateEngines(MotorPlantDatabase context, ShopBindingModel model) { var shopEngines = context.ShopEngines.Where(rec => rec.ShopId == model.Id).ToList(); if (shopEngines != null && shopEngines.Count > 0) @@ -101,5 +101,14 @@ namespace MotorPlantDatabaseImplement.Models } _shopEngines = null; } - } + + public void EnginesDictionatyUpdate(MotorPlantDatabase context) + { + UpdateEngines(context, new ShopBindingModel + { + Id = Id, + ShopEngines = ShopEngines, + }); + } + } } diff --git a/MotorPlant/MotorPlantFileImplement/Implements/OrderStorage.cs b/MotorPlant/MotorPlantFileImplement/Implements/OrderStorage.cs index d79a83b..80f0646 100644 --- a/MotorPlant/MotorPlantFileImplement/Implements/OrderStorage.cs +++ b/MotorPlant/MotorPlantFileImplement/Implements/OrderStorage.cs @@ -31,12 +31,15 @@ namespace MotorPlantFileImplement.Implements public List GetFilteredList(OrderSearchModel model) { - if (!model.Id.HasValue) - { + if (!model.Id.HasValue && !model.DateFrom.HasValue || !model.DateTo.HasValue) + { return new(); } - return source.Orders.Where(x => x.Id == model.Id).Select(x => GetViewModel(x)).ToList(); - } + return source.Orders + .Where(x => x.Id == model.Id || (model.DateTo >= x.DateCreate && model.DateFrom <= x.DateCreate)) + .Select(x => GetViewModel(x)) + .ToList(); + } public List GetFullList() { diff --git a/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs b/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs index 29ae922..ae401af 100644 --- a/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs +++ b/MotorPlant/MotorPlantFileImplement/Implements/ShopStorage .cs @@ -75,44 +75,73 @@ namespace MotorPlantFileImplement.Implements return null; } - public bool SellEngines(IEngineModel model, int count) + public bool SellEngines(SupplySearchModel model) { - var eng = _source.Engines.FirstOrDefault(x => x.Id == model.Id); - int store = _source.Shops.SelectMany(x => x.ShopEngines).Sum(y => y.Key == model.Id ? y.Value.Item2 : 0); + if (model == null || !model.EngineId.HasValue || !model.Count.HasValue) + return false; + int remainingSpace = _source.Shops.Select(x => x.Engines.ContainsKey(model.EngineId.Value) ? x.Engines[model.EngineId.Value] : 0).Sum(); + if (remainingSpace < model.Count) + { + return false; + } + var shops = _source.Shops.Where(x => x.Engines.ContainsKey(model.EngineId.Value)).OrderByDescending(x => x.Engines[model.EngineId.Value]).ToList(); + foreach (var shop in shops) + { + int residue = model.Count.Value - shop.Engines[model.EngineId.Value]; + if (residue > 0) + { + shop.Engines.Remove(model.EngineId.Value); + shop.EngineUpdate(); + model.Count = residue; + } + else + { + if (residue == 0) + { + shop.Engines.Remove(model.EngineId.Value); + } + else + { + shop.Engines[model.EngineId.Value] = -residue; + } + shop.EngineUpdate(); + _source.SaveShops(); + return true; + } + } + _source.SaveShops(); + return false; + } - if (eng == null || store < count) - { - return false; - } - - for (int i = 0; i < _source.Shops.Count; i++) - { - var shop = _source.Shops[i]; - var engines = shop.ShopEngines; - foreach (var engine in engines.Where(x => x.Value.Item1.Id == eng.Id)) - { - var selling = Math.Min(engine.Value.Item2, count); - engines[engine.Value.Item1.Id] = (engine.Value.Item1, engine.Value.Item2 - selling); - - count -= selling; - - if (count <= 0) - { - break; - } - } - shop.Update(new ShopBindingModel - { - Id = model.Id, - ShopName = shop.ShopName, - Adress = shop.Adress, - MaxCount = shop.MaxCount, - DateOpen = shop.DateOpen, - ShopEngines = engines - }); - } - _source.SaveShops(); - return true; - } - } + public bool RestockingShops(SupplyBindingModel model) + { + if (model == null || _source.Shops.Select(x => x.MaxCount - x.ShopEngines.Select(y => y.Value.Item2).Sum()).Sum() < model.Count) + { + return false; + } + foreach (Shop shop in _source.Shops) + { + int free_places = shop.MaxCount - shop.ShopEngines.Select(x => x.Value.Item2).Sum(); + if (free_places <= 0) + continue; + free_places = Math.Min(free_places, model.Count); + model.Count -= free_places; + if (shop.Engines.ContainsKey(model.EngineId)) + { + shop.Engines[model.EngineId] += free_places; + } + else + { + shop.Engines.Add(model.EngineId, free_places); + } + shop.EngineUpdate(); + if (model.Count == 0) + { + _source.SaveShops(); + return true; + } + } + return false; + } + } } diff --git a/MotorPlant/MotorPlantFileImplement/Models/Shop.cs b/MotorPlant/MotorPlantFileImplement/Models/Shop.cs index 98d151d..8c17a87 100644 --- a/MotorPlant/MotorPlantFileImplement/Models/Shop.cs +++ b/MotorPlant/MotorPlantFileImplement/Models/Shop.cs @@ -98,5 +98,10 @@ namespace MotorPlantFileImplement.Models new XElement("DateOpen", DateOpen), new XElement("MaxCount", MaxCount), new XElement("ShopEngines", Engines.Select(x => new XElement("ShopEngine", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray())); - } + + public void EngineUpdate() + { + _shopEngines = null; + } + } } diff --git a/MotorPlant/MotorPlantListImplement/Implements/OrderStorage.cs b/MotorPlant/MotorPlantListImplement/Implements/OrderStorage.cs index 5e75a80..efc5ebb 100644 --- a/MotorPlant/MotorPlantListImplement/Implements/OrderStorage.cs +++ b/MotorPlant/MotorPlantListImplement/Implements/OrderStorage.cs @@ -31,14 +31,18 @@ namespace MotorPlantListImplement.Implements public List GetFilteredList(OrderSearchModel model) { var result = new List(); - if (model == null || !model.Id.HasValue) + if (model == null) { return result; } - foreach (var order in _source.Orders) + if (!model.DateFrom.HasValue || !model.DateTo.HasValue) + { + return result; + } + foreach (var order in _source.Orders) { - if (order.Id == model.Id) - { + if (order.Id == model.Id || (model.DateFrom <= order.DateCreate && order.DateCreate <= model.DateTo)) + { result.Add(AttachEngineName(order.GetViewModel)); } } diff --git a/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs b/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs index 2d61dae..c52700e 100644 --- a/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs +++ b/MotorPlant/MotorPlantListImplement/Implements/ShopStorage.cs @@ -108,9 +108,14 @@ namespace MotorPlantListImplement.Implements { return true; } - public bool SellEngines(IEngineModel model, int count) + public bool SellEngines(SupplySearchModel model) { - return true; - } - } + throw new NotImplementedException(); + } + + public bool RestockingShops(SupplyBindingModel model) + { + throw new NotImplementedException(); + } + } } diff --git a/MotorPlant/MotorPlantView/FormMain.Designer.cs b/MotorPlant/MotorPlantView/FormMain.Designer.cs index 43ec273..a68b404 100644 --- a/MotorPlant/MotorPlantView/FormMain.Designer.cs +++ b/MotorPlant/MotorPlantView/FormMain.Designer.cs @@ -1,214 +1,277 @@ namespace MotorPlantView.Forms { - partial class FormMain - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; + partial class FormMain + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } - #region Windows Form Designer generated code + #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - toolStrip1 = new ToolStrip(); - toolStripDropDownButton1 = new ToolStripDropDownButton(); - КомпонентыToolStripMenuItem = new ToolStripMenuItem(); - ДвигателиToolStripMenuItem = new ToolStripMenuItem(); - ShopsToolStripMenuItem = new ToolStripMenuItem(); - поставкиToolStripMenuItem = new ToolStripMenuItem(); - buttonCreateOrder = new Button(); - buttonTakeOrderInWork = new Button(); - buttonOrderReady = new Button(); - buttonIssuedOrder = new Button(); - buttonRef = new Button(); - dataGridView = new DataGridView(); - продажаToolStripMenuItem = new ToolStripMenuItem(); - toolStrip1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - SuspendLayout(); - // - // toolStrip1 - // - toolStrip1.ImageScalingSize = new Size(20, 20); - toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1 }); - 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, ShopsToolStripMenuItem, поставки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(180, 22); - КомпонентыToolStripMenuItem.Text = "Компоненты"; - КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; - // - // ДвигателиToolStripMenuItem - // - ДвигателиToolStripMenuItem.Name = "ДвигателиToolStripMenuItem"; - ДвигателиToolStripMenuItem.Size = new Size(180, 22); - ДвигателиToolStripMenuItem.Text = "Двигатели"; - ДвигателиToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; - // - // ShopsToolStripMenuItem - // - ShopsToolStripMenuItem.Name = "ShopsToolStripMenuItem"; - ShopsToolStripMenuItem.Size = new Size(180, 22); - ShopsToolStripMenuItem.Text = "Магазины"; - ShopsToolStripMenuItem.Click += ShopsToolStripMenuItem_Click; - // - // поставкиToolStripMenuItem - // - поставкиToolStripMenuItem.Name = "поставкиToolStripMenuItem"; - поставкиToolStripMenuItem.Size = new Size(180, 22); - поставкиToolStripMenuItem.Text = "Поставки"; - поставкиToolStripMenuItem.Click += SupplyToolStripMenuItem_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(11, 28); - 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; - // - // продажаToolStripMenuItem - // - продажаToolStripMenuItem.Name = "продажаToolStripMenuItem"; - продажаToolStripMenuItem.Size = new Size(180, 22); - продажаToolStripMenuItem.Text = "Продажа"; - продажаToolStripMenuItem.Click += SellToolStripMenuItem_Click; - // - // 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. + /// + 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(); + } - #endregion + #endregion - 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 ShopsToolStripMenuItem; - 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 01227b8..52a92bf 100644 --- a/MotorPlant/MotorPlantView/FormMain.cs +++ b/MotorPlant/MotorPlantView/FormMain.cs @@ -5,171 +5,239 @@ using MotorPlantView; namespace MotorPlantView.Forms { - public partial class FormMain : Form - { - private readonly ILogger _logger; - private readonly IOrderLogic _orderLogic; - public FormMain(ILogger logger, IOrderLogic orderLogic) - { - InitializeComponent(); - _logger = logger; - _orderLogic = orderLogic; - } - private void FormMain_Load(object sender, EventArgs e) - { - LoadData(); - } - private void LoadData() - { - _logger.LogInformation("Загрузка заказов"); - try - { - var list = _orderLogic.ReadList(null); + public partial class FormMain : Form + { + private readonly ILogger _logger; + private readonly IOrderLogic _orderLogic; + private readonly IReportLogic _reportLogic; - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["EngineId"].Visible = false; - dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; - } + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic) + { + InitializeComponent(); + _logger = logger; + _orderLogic = orderLogic; + _reportLogic = reportLogic; + } - _logger.LogInformation("Загрузка заказов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заказов"); - } - } - private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); + private void FormMain_Load(object sender, EventArgs e) + { + LoadData(); + } + private void LoadData() + { + _logger.LogInformation("Загрузка заказов"); + try + { + var list = _orderLogic.ReadList(null); - if (service is FormComponents form) - { - form.ShowDialog(); - } - } - private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormEngines)); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["EngineId"].Visible = false; + dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } - if (service is FormEngines form) - { - form.ShowDialog(); - } - } - private void buttonCreateOrder_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } - } - private void buttonTakeOrderInWork_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); - try - { - var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel - { - Id = id, - }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка передачи заказа в работу"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void buttonOrderReady_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - var engineId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["EngineId"].Value); - var count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value); - _logger.LogInformation("Order №{id}. Change status on 'Ready'", id); - try - { - var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id, EngineId = engineId, Count = count }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о готовности заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void buttonIssuedOrder_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Order №{id}. Status change on 'Given'", id); - try - { - var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel { Id = id }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - _logger.LogInformation("Order №{id} given", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Change status on 'Give' error"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void buttonRef_Click(object sender, EventArgs e) - { - LoadData(); - } - private void ShopsToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormShops)); + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + } + } - if (service is FormShops form) - { - form.ShowDialog(); - } - } + private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); - private void SupplyToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormSupply)); + if (service is FormComponents form) + { + form.ShowDialog(); + } + } - if (service is FormSupply form) - { - form.ShowDialog(); - } - } + private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormEngines)); - private void SellToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormSell)); - if (service is FormSell form) - { - form.ShowDialog(); - } - } - } + if (service is FormEngines form) + { + form.ShowDialog(); + } + } + + private void buttonCreateOrder_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); + if (service is FormCreateOrder form) + { + form.ShowDialog(); + LoadData(); + } + } + + private void buttonTakeOrderInWork_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); + try + { + var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel + { + Id = id, + }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка передачи заказа в работу"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void buttonOrderReady_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = + Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); + try + { + var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о готовности заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void buttonIssuedOrder_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); + try + { + var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel + { + Id = id + }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + _logger.LogInformation("Заказ №{id} выдан", id); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void buttonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + + private void списокДвигателейToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveEngineToWordFile(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(FormReportEngineComponents)); + if (service is FormReportEngineComponents form) + { + form.ShowDialog(); + } + } + + 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(); + } + } + } } diff --git a/MotorPlant/MotorPlantView/FormReportEngineComponents.Designer.cs b/MotorPlant/MotorPlantView/FormReportEngineComponents.Designer.cs new file mode 100644 index 0000000..9f5e36d --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportEngineComponents.Designer.cs @@ -0,0 +1,111 @@ +namespace MotorPlantView +{ + partial class FormReportEngineComponents + { + /// + /// 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(); + ColumEngine = new DataGridViewTextBoxColumn(); + ColumnComponent = new DataGridViewTextBoxColumn(); + ColumnCount = new DataGridViewTextBoxColumn(); + buttonSaveToExcel = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.AllowUserToOrderColumns = true; + dataGridView.AllowUserToResizeColumns = false; + dataGridView.AllowUserToResizeRows = false; + dataGridView.BackgroundColor = SystemColors.ControlLightLight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumEngine, ColumnComponent, ColumnCount }); + dataGridView.Location = new Point(1, 58); + dataGridView.Margin = new Padding(4, 3, 4, 3); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.RowTemplate.Height = 25; + dataGridView.Size = new Size(624, 459); + dataGridView.TabIndex = 0; + // + // ColumEngine + // + ColumEngine.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + ColumEngine.HeaderText = "Двигатель"; + ColumEngine.Name = "ColumEngine"; + ColumEngine.ReadOnly = true; + // + // ColumnComponent + // + ColumnComponent.HeaderText = "Компонент"; + ColumnComponent.Name = "ColumnComponent"; + ColumnComponent.ReadOnly = true; + ColumnComponent.Width = 200; + // + // ColumnCount + // + ColumnCount.HeaderText = "Количество"; + ColumnCount.Name = "ColumnCount"; + ColumnCount.ReadOnly = true; + // + // buttonSaveToExcel + // + buttonSaveToExcel.Location = new Point(12, 12); + buttonSaveToExcel.Name = "buttonSaveToExcel"; + buttonSaveToExcel.Size = new Size(180, 40); + buttonSaveToExcel.TabIndex = 1; + buttonSaveToExcel.Text = "Сохранить в Excel"; + buttonSaveToExcel.UseVisualStyleBackColor = true; + buttonSaveToExcel.Click += buttonSaveToExcel_Click; + // + // FormReportEngineComponents + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(625, 518); + Controls.Add(buttonSaveToExcel); + Controls.Add(dataGridView); + Name = "FormReportEngineComponents"; + Text = "FormReportEngineComponents"; + Load += FormReportProductComponents_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private DataGridViewTextBoxColumn ColumEngine; + private DataGridViewTextBoxColumn ColumnComponent; + private DataGridViewTextBoxColumn ColumnCount; + private Button buttonSaveToExcel; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormReportEngineComponents.cs b/MotorPlant/MotorPlantView/FormReportEngineComponents.cs new file mode 100644 index 0000000..864db71 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportEngineComponents.cs @@ -0,0 +1,70 @@ +using MotorPlantContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; + +namespace MotorPlantView +{ + public partial class FormReportEngineComponents : Form + { + private readonly ILogger _logger; + + private readonly IReportLogic _logic; + + public FormReportEngineComponents(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormReportProductComponents_Load(object sender, EventArgs e) + { + try + { + var dict = _logic.GetEngineComponents(); + if (dict != null) + { + dataGridView.Rows.Clear(); + foreach (var elem in dict) + { + dataGridView.Rows.Add(new object[] { elem.EngineName, "", "" }); + foreach (var listElem in elem.Components) + { + dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 }); + } + dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount }); + dataGridView.Rows.Add(Array.Empty()); + } + } + _logger.LogInformation("Loading list of engines with components"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Loading list of engines with components error"); + 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.SaveEngineComponentToExcelFile(new ReportBindingModel + { + FileName = dialog.FileName + }); + _logger.LogInformation("Saving list of engines with components"); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + _logger.LogError(ex, "Saving list of engines with components error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } +} diff --git a/MotorPlant/MotorPlantView/FormReportEngineComponents.resx b/MotorPlant/MotorPlantView/FormReportEngineComponents.resx new file mode 100644 index 0000000..53ab8e5 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportEngineComponents.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + True + + + True + + + True + + \ No newline at end of file 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/FormReportOrders.Designer.cs b/MotorPlant/MotorPlantView/FormReportOrders.Designer.cs new file mode 100644 index 0000000..06b3199 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportOrders.Designer.cs @@ -0,0 +1,137 @@ +namespace MotorPlantView +{ + partial class FormReportOrders + { + /// + /// 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() + { + panel = new Panel(); + buttonToPdf = new Button(); + buttonCreateReport = new Button(); + dateTimePickerTo = new DateTimePicker(); + labelTo = new Label(); + dateTimePickerFrom = new DateTimePicker(); + labelFrom = new Label(); + panel.SuspendLayout(); + SuspendLayout(); + // + // panel + // + panel.Controls.Add(buttonToPdf); + panel.Controls.Add(buttonCreateReport); + panel.Controls.Add(dateTimePickerTo); + panel.Controls.Add(labelTo); + panel.Controls.Add(dateTimePickerFrom); + panel.Controls.Add(labelFrom); + panel.Dock = DockStyle.Top; + panel.Location = new Point(0, 0); + panel.Name = "panel"; + panel.Size = new Size(1019, 38); + panel.TabIndex = 0; + // + // buttonToPdf + // + buttonToPdf.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonToPdf.Location = new Point(866, 5); + buttonToPdf.Margin = new Padding(4, 3, 4, 3); + buttonToPdf.Name = "buttonToPdf"; + buttonToPdf.Size = new Size(139, 27); + buttonToPdf.TabIndex = 6; + buttonToPdf.Text = "В Pdf"; + buttonToPdf.UseVisualStyleBackColor = true; + buttonToPdf.Click += ButtonToPdf_Click; + // + // buttonCreateReport + // + buttonCreateReport.Location = new Point(565, 5); + buttonCreateReport.Margin = new Padding(4, 3, 4, 3); + buttonCreateReport.Name = "buttonCreateReport"; + buttonCreateReport.Size = new Size(139, 27); + buttonCreateReport.TabIndex = 5; + buttonCreateReport.Text = "Сформировать"; + buttonCreateReport.UseVisualStyleBackColor = true; + buttonCreateReport.Click += ButtonCreateReport_Click; + // + // dateTimePickerTo + // + dateTimePickerTo.Location = new Point(257, 8); + dateTimePickerTo.Margin = new Padding(4, 3, 4, 3); + dateTimePickerTo.Name = "dateTimePickerTo"; + dateTimePickerTo.Size = new Size(163, 23); + dateTimePickerTo.TabIndex = 4; + // + // labelTo + // + labelTo.AutoSize = true; + labelTo.Location = new Point(217, 11); + labelTo.Margin = new Padding(4, 0, 4, 0); + labelTo.Name = "labelTo"; + labelTo.Size = new Size(21, 15); + labelTo.TabIndex = 3; + labelTo.Text = "по"; + // + // dateTimePickerFrom + // + dateTimePickerFrom.Location = new Point(36, 8); + dateTimePickerFrom.Margin = new Padding(4, 3, 4, 3); + dateTimePickerFrom.Name = "dateTimePickerFrom"; + dateTimePickerFrom.Size = new Size(163, 23); + dateTimePickerFrom.TabIndex = 2; + // + // labelFrom + // + labelFrom.AutoSize = true; + labelFrom.Location = new Point(13, 11); + labelFrom.Margin = new Padding(4, 0, 4, 0); + labelFrom.Name = "labelFrom"; + labelFrom.Size = new Size(15, 15); + labelFrom.TabIndex = 1; + labelFrom.Text = "С"; + // + // FormReportOrders + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1019, 450); + Controls.Add(panel); + Name = "FormReportOrders"; + Text = "FormReportOrders"; + panel.ResumeLayout(false); + panel.PerformLayout(); + ResumeLayout(false); + } + + #endregion + + private Panel panel; + private Label labelFrom; + private Button buttonToPdf; + private Button buttonCreateReport; + private DateTimePicker dateTimePickerTo; + private Label labelTo; + private DateTimePicker dateTimePickerFrom; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormReportOrders.cs b/MotorPlant/MotorPlantView/FormReportOrders.cs new file mode 100644 index 0000000..de0a81b --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportOrders.cs @@ -0,0 +1,92 @@ +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using Microsoft.Reporting.WinForms; + + +namespace MotorPlantView +{ + public partial class FormReportOrders : Form + { + private readonly ReportViewer reportViewer; + + private readonly ILogger _logger; + + private readonly IReportLogic _logic; + + public FormReportOrders(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\\ReportOrders.rdlc", FileMode.Open)); + Controls.Clear(); + Controls.Add(reportViewer); + Controls.Add(panel); + } + + private void ButtonCreateReport_Click(object sender, EventArgs e) + { + if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date) + { + MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + try + { + var dataSource = _logic.GetOrders(new ReportBindingModel + { + DateFrom = dateTimePickerFrom.Value, + DateTo = dateTimePickerTo.Value + }); + var source = new ReportDataSource("DataSetOrders", dataSource); + reportViewer.LocalReport.DataSources.Clear(); + reportViewer.LocalReport.DataSources.Add(source); + var parameters = new[] { new ReportParameter("ReportParameterPeriod", + $"c {dateTimePickerFrom.Value.ToShortDateString()} по {dateTimePickerTo.Value.ToShortDateString()}") }; + reportViewer.LocalReport.SetParameters(parameters); + + reportViewer.RefreshReport(); + _logger.LogInformation("Loading list of orders for period {From}-{To}", dateTimePickerFrom.Value.ToShortDateString(), dateTimePickerTo.Value.ToShortDateString()); + } + catch (Exception ex) + { + _logger.LogError(ex, "Loading list of orders for period error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonToPdf_Click(object sender, EventArgs e) + { + if (dateTimePickerFrom.Value.Date >= dateTimePickerTo.Value.Date) + { + MessageBox.Show("Дата начала должна быть меньше даты окончания", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + _logic.SaveOrdersToPdfFile(new ReportBindingModel + { + FileName = dialog.FileName, + DateFrom = dateTimePickerFrom.Value, + DateTo = dateTimePickerTo.Value + }); + _logger.LogInformation("Saving list of orders for period {From}-{To}", dateTimePickerFrom.Value.ToShortDateString(), dateTimePickerTo.Value.ToShortDateString()); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + _logger.LogError(ex, "Saving list of orders for period error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } +} diff --git a/MotorPlant/MotorPlantView/FormReportOrders.resx b/MotorPlant/MotorPlantView/FormReportOrders.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportOrders.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormReportShop.Designer.cs b/MotorPlant/MotorPlantView/FormReportShop.Designer.cs new file mode 100644 index 0000000..2e36897 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportShop.Designer.cs @@ -0,0 +1,116 @@ +namespace MotorPlantView +{ + partial class FormReportShop + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.buttonSaveToExcel = new System.Windows.Forms.Button(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + this.ColumnShop = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.ColumnPizza = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.ColumnCount = new System.Windows.Forms.DataGridViewTextBoxColumn(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // buttonSaveToExcel + // + this.buttonSaveToExcel.Location = new System.Drawing.Point(0, 6); + this.buttonSaveToExcel.Name = "buttonSaveToExcel"; + this.buttonSaveToExcel.Size = new System.Drawing.Size(223, 29); + this.buttonSaveToExcel.TabIndex = 3; + this.buttonSaveToExcel.Text = "Сохранить в Excel"; + this.buttonSaveToExcel.UseVisualStyleBackColor = true; + this.buttonSaveToExcel.Click += new System.EventHandler(this.ButtonSaveToExcel_Click); + // + // dataGridView + // + this.dataGridView.AllowUserToAddRows = false; + this.dataGridView.AllowUserToDeleteRows = false; + this.dataGridView.AllowUserToOrderColumns = true; + this.dataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.ColumnShop, + this.ColumnPizza, + this.ColumnCount}); + this.dataGridView.Dock = System.Windows.Forms.DockStyle.Bottom; + this.dataGridView.Location = new System.Drawing.Point(0, 47); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.ReadOnly = true; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(598, 403); + this.dataGridView.TabIndex = 2; + // + // ColumnShop + // + this.ColumnShop.FillWeight = 130F; + this.ColumnShop.HeaderText = "Магазин"; + this.ColumnShop.MinimumWidth = 6; + this.ColumnShop.Name = "ColumnShop"; + this.ColumnShop.ReadOnly = true; + // + // ColumnPizza + // + this.ColumnPizza.FillWeight = 140F; + this.ColumnPizza.HeaderText = "Пицца"; + this.ColumnPizza.MinimumWidth = 6; + this.ColumnPizza.Name = "ColumnPizza"; + this.ColumnPizza.ReadOnly = true; + // + // ColumnCount + // + this.ColumnCount.FillWeight = 90F; + this.ColumnCount.HeaderText = "Количество"; + this.ColumnCount.MinimumWidth = 6; + this.ColumnCount.Name = "ColumnCount"; + this.ColumnCount.ReadOnly = true; + // + // FormReportShop + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(598, 450); + this.Controls.Add(this.buttonSaveToExcel); + this.Controls.Add(this.dataGridView); + this.Name = "FormReportShop"; + this.Text = "Наполненость магазинов"; + this.Load += new System.EventHandler(this.FormReportShop_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private Button buttonSaveToExcel; + private DataGridView dataGridView; + private DataGridViewTextBoxColumn ColumnShop; + private DataGridViewTextBoxColumn ColumnPizza; + private DataGridViewTextBoxColumn ColumnCount; + } +} \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormReportShop.cs b/MotorPlant/MotorPlantView/FormReportShop.cs new file mode 100644 index 0000000..b6d1130 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportShop.cs @@ -0,0 +1,78 @@ +using Microsoft.Extensions.Logging; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace MotorPlantView +{ + public partial class FormReportShop : Form + { + private readonly ILogger _logger; + private readonly IReportLogic _logic; + + public FormReportShop(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormReportShop_Load(object sender, EventArgs e) + { + try + { + var dict = _logic.GetShops(); + if (dict != null) + { + dataGridView.Rows.Clear(); + foreach (var elem in dict) + { + dataGridView.Rows.Add(new object[] { elem.ShopName, "", "" }); + foreach (var listElem in elem.Engines) + { + dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 }); + } + dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount }); + dataGridView.Rows.Add(Array.Empty()); + } + } + _logger.LogInformation("Загрузка списка пицц по магазинам"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка пицц по магазинам"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonSaveToExcel_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + _logic.SaveShopsToExcelFile(new ReportBindingModel + { + FileName = dialog.FileName + }); + _logger.LogInformation("Сохранение списка пицц по магазинам"); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения списка пицц по магазинам"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } +} diff --git a/MotorPlant/MotorPlantView/FormReportShop.resx b/MotorPlant/MotorPlantView/FormReportShop.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/MotorPlant/MotorPlantView/FormReportShop.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/FormSell.cs b/MotorPlant/MotorPlantView/FormSell.cs index 09d47ad..a434303 100644 --- a/MotorPlant/MotorPlantView/FormSell.cs +++ b/MotorPlant/MotorPlantView/FormSell.cs @@ -10,6 +10,7 @@ using System.Windows.Forms; using MotorPlantDataModels.Models; using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.ViewModels; +using MotorPlantContracts.SearchModels; namespace MotorPlantView { @@ -73,44 +74,34 @@ namespace MotorPlantView private void buttonSave_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(textBoxCount.Text)) - { - MessageBox.Show("Заполните поле Количество", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - if (comboBoxEngine.SelectedValue == null) - { - MessageBox.Show("Выберите двигатель", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - - try - { - int count = Convert.ToInt32(textBoxCount.Text); - - bool res = _shopLogic.MakeSell( - _engineLogic.ReadElement(new() { Id = Convert.ToInt32(comboBoxEngine.SelectedValue) }), - count - ); - - if (!res) - { - throw new Exception("Ошибка при продаже."); - } - - MessageBox.Show("Продажа прошла успешно"); - DialogResult = DialogResult.OK; - Close(); - - } - catch (Exception err) - { - MessageBox.Show("Ошибка продажи"); - return; - } - } + if (comboBoxEngine.SelectedValue == null) + { + MessageBox.Show("Выберите пиццу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + try + { + bool resout = _shopLogic.MakeSell(new SupplySearchModel + { + EngineId = Convert.ToInt32(comboBoxEngine.SelectedValue), + Count = Convert.ToInt32(textBoxCount.Text) + }); + if (resout) + { + MessageBox.Show("Продажа проведена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + else + { + MessageBox.Show("Продажа не может быть создана.", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } private void buttonCancel_Click(object sender, EventArgs e) { diff --git a/MotorPlant/MotorPlantView/FormSupply.cs b/MotorPlant/MotorPlantView/FormSupply.cs index fa59e52..aa0174d 100644 --- a/MotorPlant/MotorPlantView/FormSupply.cs +++ b/MotorPlant/MotorPlantView/FormSupply.cs @@ -1,4 +1,5 @@ -using MotorPlantContracts.BusinessLogicsContracts; +using MotorPlantContracts.BindingModels; +using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.SearchModels; using MotorPlantContracts.ViewModels; using MotorPlantDataModels.Models; @@ -85,49 +86,35 @@ namespace MotorPlantView private void SaveButton_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(CountTextBox.Text)) + if (ShopComboBox.SelectedValue == null) { - MessageBox.Show("Заполните поле Количество", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (EngineComboBox.SelectedValue == null) { - MessageBox.Show("Выберите двигатель", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Выберите пиццу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } - if (ShopComboBox.SelectedValue == null) - { - MessageBox.Show("Выберите магазин", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); - return; - } - try { - int count = Convert.ToInt32(CountTextBox.Text); - - bool res = _shopLogic.MakeSupply( - new ShopSearchModel() { Id = Convert.ToInt32(ShopComboBox.SelectedValue) }, - _engineLogic.ReadElement(new() { Id = Convert.ToInt32(EngineComboBox.SelectedValue) }), - count - ); - - if (!res) + var operationResult = _shopLogic.MakeSupply(new SupplyBindingModel { - throw new Exception("Ошибка при пополнении. Дополнительная информация в логах"); + ShopId = Convert.ToInt32(ShopComboBox.SelectedValue), + EngineId = Convert.ToInt32(EngineComboBox.SelectedValue), + Count = Convert.ToInt32(CountTextBox.Text) + }); + if (!operationResult) + { + throw new Exception("Ошибка при создании поставки. Дополнительная информация в логах."); } - - MessageBox.Show("Пополнение прошло успешно"); + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); DialogResult = DialogResult.OK; Close(); - } - catch (Exception er) + catch (Exception ex) { - MessageBox.Show("Ошибка пополнения"); - return; + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } diff --git a/MotorPlant/MotorPlantView/MotorPlantView.csproj b/MotorPlant/MotorPlantView/MotorPlantView.csproj index 88a413b..0ee1ce6 100644 --- a/MotorPlant/MotorPlantView/MotorPlantView.csproj +++ b/MotorPlant/MotorPlantView/MotorPlantView.csproj @@ -28,6 +28,8 @@ + + diff --git a/MotorPlant/MotorPlantView/Program.cs b/MotorPlant/MotorPlantView/Program.cs index 1dd2729..fd0e0f1 100644 --- a/MotorPlant/MotorPlantView/Program.cs +++ b/MotorPlant/MotorPlantView/Program.cs @@ -6,8 +6,11 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; using MotorPlantBusinessLogic.BusinessLogics; +using System; using MotorPlantBusinessLogic.BusinessLogic; -using MotorPlantView; +using MotorPlantBusinessLogic.OfficePackage.Implements; +using MotorPlantBusinessLogic.OfficePackage; +using System.Text; namespace MotorPlantView { @@ -21,6 +24,7 @@ namespace MotorPlantView [STAThread] static void Main() { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); @@ -40,11 +44,17 @@ 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(); services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -55,7 +65,11 @@ namespace MotorPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); - } + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + } } } \ No newline at end of file diff --git a/MotorPlant/MotorPlantView/ReportGroupedOrders.rdlc b/MotorPlant/MotorPlantView/ReportGroupedOrders.rdlc new file mode 100644 index 0000000..2ef2b88 --- /dev/null +++ b/MotorPlant/MotorPlantView/ReportGroupedOrders.rdlc @@ -0,0 +1,441 @@ + + + 0 + + + + System.Data.DataSet + /* Local Connection */ + + 20791c83-cee8-4a38-bbd0-245fc17cefb3 + + + + + + PrecastConcretePlantContractsViewModels + /* Local Query */ + + + + Date + System.DateTime + + + OrdersCount + System.Int32 + + + OrdersSum + System.Decimal + + + + PrecastConcretePlantContracts.ViewModels + ReportGroupOrdersViewModel + PrecastConcretePlantContracts.ViewModels.ReportGroupOrdersViewModel, PrecastConcretePlantContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + + + + + + + + + true + true + + + + + Отчёт по заказам + + + + 0.6cm + 16.51cm + + + Middle + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Parameters!ReportParameterPeriod.Value + + + + + + + ReportParameterPeriod + 0.6cm + 0.6cm + 16.51cm + 1 + + + 2pt + 2pt + 2pt + 2pt + + + + + + + 3.90406cm + + + 3.97461cm + + + 3.65711cm + + + + + 0.6cm + + + + + true + true + + + + + Дата создания + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Количество заказов + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Общая сумма заказов + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + 0.6cm + + + + + true + true + + + + + =Fields!Date.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!OrdersCount.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!OrdersSum.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + + + + + + + + + + + + After + + + + + + + DataSetGroupedOrders + 1.88242cm + 2.68676cm + 1.2cm + 11.53578cm + 2 + + + + + + true + true + + + + + Итого: + + + + 3.29409cm + 8.06542cm + 0.6cm + 2.5cm + 3 + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Sum(Fields!OrdersSum.Value, "DataSetGroupedOrders") + + + + + + + 3.29409cm + 10.70653cm + 0.6cm + 3.48072cm + 4 + + + 2pt + 2pt + 2pt + 2pt + + + + 2in + + + + + + + ReportParameterPeriod + 1cm + 1cm + 21cm + + + Middle + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + Заказы + + + + + + + 1cm + 21cm + 1 + + + Middle + 2pt + 2pt + 2pt + 2pt + + + + + + + 2.5cm + + + 3.21438cm + + + 8.23317cm + + + 2.5cm + + + 2.5cm + + + + + 0.6cm + + + + + true + true + + + + + Номер + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Дата создания + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Двигатели + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Статус Заказа + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Сумма + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + 0.6cm + + + + + true + true + + + + + =Fields!Id.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!DateCreate.Value + + + + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!EngineName.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!OrderStatus.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Sum.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + + + + + + + + + + + + + + After + + + + + + + DataSetOrders + 2.48391cm + 0.55245cm + 1.2cm + 18.94755cm + 2 + + + + + + true + true + + + + + Итого: + + + + + + + 4cm + 12cm + 0.6cm + 2.5cm + 3 + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Sum(Fields!Sum.Value, "DataSetOrders") + + + + + + + 4cm + 14.5cm + 0.6cm + 2.5cm + 4 + + + 2pt + 2pt + 2pt + 2pt + + + + 5.72875cm +