diff --git a/SushiBar/SushiBarBusinessLogic_/ComponentLogic.cs b/SushiBar/SushiBarBusinessLogic_/BusinessLogics/ComponentLogic.cs similarity index 100% rename from SushiBar/SushiBarBusinessLogic_/ComponentLogic.cs rename to SushiBar/SushiBarBusinessLogic_/BusinessLogics/ComponentLogic.cs diff --git a/SushiBar/SushiBarBusinessLogic_/OrderLogic.cs b/SushiBar/SushiBarBusinessLogic_/BusinessLogics/OrderLogic.cs similarity index 86% rename from SushiBar/SushiBarBusinessLogic_/OrderLogic.cs rename to SushiBar/SushiBarBusinessLogic_/BusinessLogics/OrderLogic.cs index ac3e5f0..ae8df9d 100644 --- a/SushiBar/SushiBarBusinessLogic_/OrderLogic.cs +++ b/SushiBar/SushiBarBusinessLogic_/BusinessLogics/OrderLogic.cs @@ -17,10 +17,13 @@ namespace SushiBarBusinessLogic.BusinessLogics { private readonly ILogger _logger; private readonly IOrderStorage _orderStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + private readonly IShopStorage _shopStorage; + + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IShopStorage shopStorage) { _logger = logger; _orderStorage = orderStorage; + _shopStorage = shopStorage; } public List? ReadList(OrderSearchModel? model) { @@ -60,6 +63,22 @@ namespace SushiBarBusinessLogic.BusinessLogics public bool DeliveryOrder(OrderBindingModel model) { + var order = _orderStorage.GetElement(new OrderSearchModel + { + Id = model.Id, + }); + if (order == null) + { + throw new ArgumentNullException(nameof(order)); + } + if (!_shopStorage.RestockingShops(new SupplyBindingModel + { + SushiId = order.SushiId, + Count = order.Count + })) + { + throw new ArgumentException("Недостаточно места"); + } return ChangeStatus(model, OrderStatus.Выдан); } @@ -75,7 +94,7 @@ namespace SushiBarBusinessLogic.BusinessLogics } if (model.Count <= 0) { - throw new ArgumentException("Колличество пиццы в заказе не может быть меньше 1", nameof(model.Count)); + throw new ArgumentException("Колличество суши в заказе не может быть меньше 1", nameof(model.Count)); } if (model.Sum <= 0) { diff --git a/SushiBar/SushiBarBusinessLogic_/ReportLogic.cs b/SushiBar/SushiBarBusinessLogic_/BusinessLogics/ReportLogic.cs similarity index 61% rename from SushiBar/SushiBarBusinessLogic_/ReportLogic.cs rename to SushiBar/SushiBarBusinessLogic_/BusinessLogics/ReportLogic.cs index 81ae29c..9f795ff 100644 --- a/SushiBar/SushiBarBusinessLogic_/ReportLogic.cs +++ b/SushiBar/SushiBarBusinessLogic_/BusinessLogics/ReportLogic.cs @@ -11,24 +11,25 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace SushiBarBusinessLogic +namespace SushiBarBusinessLogic.BusinessLogics { public class ReportLogic : IReportLogic { private readonly IComponentStorage _componentStorage; private readonly ISushiStorage _SushiStorage; private readonly IOrderStorage _orderStorage; + private readonly IShopStorage _shopStorage; private readonly AbstractSaveToExcel _saveToExcel; private readonly AbstractSaveToWord _saveToWord; private readonly AbstractSaveToPdf _saveToPdf; - public ReportLogic(ISushiStorage SushiStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, + public ReportLogic(ISushiStorage SushiStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, IShopStorage shopStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf) { _SushiStorage = SushiStorage; _componentStorage = componentStorage; _orderStorage = orderStorage; - + _shopStorage = shopStorage; _saveToExcel = saveToExcel; _saveToWord = saveToWord; _saveToPdf = saveToPdf; @@ -89,5 +90,55 @@ namespace SushiBarBusinessLogic Orders = GetOrders(model) }); } + + public List GetShops() + { + return _shopStorage.GetFullList().Select(x => new ReportShopsViewModel + { + ShopName = x.ShopName, + Sushis = x.ShopSushis.Select(x => (x.Value.Item1.SushiName, x.Value.Item2)).ToList(), + TotalCount = x.ShopSushis.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.CreateShopSushisReport(new ExcelShop + { + FileName = model.FileName, + Title = "Наполненость магазинов", + ShopSushis = GetShops() + }); + } + + public void SaveGroupedOrdersToPdfFile(ReportBindingModel model) + { + _saveToPdf.CreateGroupedOrdersDoc(new PdfGroupedOrdersInfo + { + FileName = model.FileName, + Title = "Список заказов сгруппированных по дате заказов", + GroupedOrders = GetGroupedOrders() + }); + } } } diff --git a/SushiBar/SushiBarBusinessLogic_/BusinessLogics/ShopLogic.cs b/SushiBar/SushiBarBusinessLogic_/BusinessLogics/ShopLogic.cs new file mode 100644 index 0000000..f14617f --- /dev/null +++ b/SushiBar/SushiBarBusinessLogic_/BusinessLogics/ShopLogic.cs @@ -0,0 +1,186 @@ +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SushiBarContracts.BindingModels; +using SushiBarContracts.BusinessLogicsContracts; +using SushiBarContracts.SearchModels; +using SushiBarContracts.StoragesContracts; +using SushiBarContracts.ViewModels; + +namespace SushiBarBusinessLogic.BusinessLogics +{ + public class ShopLogic : IShopLogic + { + private readonly ILogger _logger; + private readonly IShopStorage _shopStorage; + private readonly ISushiStorage _sushiStorage; + + public ShopLogic(ILogger logger, IShopStorage shopStorage, ISushiStorage sushiStorage) + { + _logger = logger; + _shopStorage = shopStorage; + _sushiStorage = sushiStorage; + } + + public List? ReadList(ShopSearchModel? model) + { + _logger.LogInformation("ReadList. ShopName:{ShopName}.Id:{ Id}", model?.ShopName, model?.Id); + var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + + public ShopViewModel? ReadElement(ShopSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + _logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.ShopName, model.Id); + var element = _shopStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } + + public bool Create(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + public bool Update(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + + public bool Delete(ShopBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + if (_shopStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + + public bool MakeSupply(SupplyBindingModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (model.Count <= 0) + { + throw new ArgumentException("Количество изделий должно быть больше 0"); + } + var shop = _shopStorage.GetElement(new ShopSearchModel + { + Id = model.ShopId + }); + if (shop == null) + { + throw new ArgumentException("Магазина не существует"); + } + if (shop.ShopSushis.ContainsKey(model.SushiId)) + { + var oldValue = shop.ShopSushis[model.SushiId]; + oldValue.Item2 += model.Count; + shop.ShopSushis[model.SushiId] = oldValue; + } + else + { + var sushi = _sushiStorage.GetElement(new SushiSearchModel + { + Id = model.SushiId + }); + if (sushi == null) + { + throw new ArgumentException($"Поставка: Товар с id:{model.SushiId} не найденн"); + } + shop.ShopSushis.Add(model.SushiId, (sushi, model.Count)); + } + + _shopStorage.Update(new ShopBindingModel() + { + Id = shop.Id, + ShopName = shop.ShopName, + Adress = shop.Adress, + OpeningDate = shop.OpeningDate, + ShopSushis = shop.ShopSushis, + SushiMaxCount = shop.SushiMaxCount, + }); + return true; + } + + private void CheckModel(ShopBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.Adress)) + { + throw new ArgumentException("Адрес магазина длжен быть заполнен", nameof(model.Adress)); + } + if (string.IsNullOrEmpty(model.ShopName)) + { + throw new ArgumentException("Название магазина должно быть заполнено", nameof(model.ShopName)); + } + _logger.LogInformation("Shop. ShopName:{ShopName}.Adres:{Adres}.OpeningDate:{OpeningDate}.Id:{ Id}", model.ShopName, model.Adress, model.OpeningDate, model.Id); + var element = _shopStorage.GetElement(new ShopSearchModel + { + ShopName = model.ShopName + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Магазин с таким названием уже есть"); + } + } + + public bool Sale(SupplySearchModel model) + { + if (!model.SushiId.HasValue || !model.Count.HasValue) + { + return false; + } + _logger.LogInformation("Check sushi count in all shops"); + if (_shopStorage.Sale(model)) + { + _logger.LogInformation("Selling sucsess"); + return true; + } + _logger.LogInformation("Selling failed"); + return false; + } + } +} diff --git a/SushiBar/SushiBarBusinessLogic_/SushiLogic.cs b/SushiBar/SushiBarBusinessLogic_/BusinessLogics/SushiLogic.cs similarity index 93% rename from SushiBar/SushiBarBusinessLogic_/SushiLogic.cs rename to SushiBar/SushiBarBusinessLogic_/BusinessLogics/SushiLogic.cs index 339a27a..e9b39fc 100644 --- a/SushiBar/SushiBarBusinessLogic_/SushiLogic.cs +++ b/SushiBar/SushiBarBusinessLogic_/BusinessLogics/SushiLogic.cs @@ -92,11 +92,11 @@ namespace SushiBarBusinessLogic.BusinessLogics } if (string.IsNullOrEmpty(model.SushiName)) { - throw new ArgumentNullException("Нет названия пиццы", nameof(model.SushiName)); + throw new ArgumentNullException("Нет названия суши", nameof(model.SushiName)); } if (model.Price <= 0) { - throw new ArgumentNullException("Цена пиццы должна быть больше 0", nameof(model.Price)); + throw new ArgumentNullException("Цена суши должна быть больше 0", nameof(model.Price)); } if (model.SushiComponents == null || model.SushiComponents.Count == 0) { @@ -109,7 +109,7 @@ namespace SushiBarBusinessLogic.BusinessLogics }); if (element != null && element.Id != model.Id) { - throw new InvalidOperationException("Пицца с таким названием уже есть"); + throw new InvalidOperationException("Суши с таким названием уже есть"); } } } diff --git a/SushiBar/SushiBarBusinessLogic_/OfficePackage/AbstractSaveToExcel.cs b/SushiBar/SushiBarBusinessLogic_/OfficePackage/AbstractSaveToExcel.cs index 7c71989..dfe03e7 100644 --- a/SushiBar/SushiBarBusinessLogic_/OfficePackage/AbstractSaveToExcel.cs +++ b/SushiBar/SushiBarBusinessLogic_/OfficePackage/AbstractSaveToExcel.cs @@ -13,6 +13,7 @@ namespace SushiBarBusinessLogic.OfficePackage public void CreateReport(ExcelInfo info) { CreateExcel(info); + InsertCellInWorksheet(new ExcelCellParameters { ColumnName = "A", @@ -20,40 +21,46 @@ namespace SushiBarBusinessLogic.OfficePackage Text = info.Title, StyleInfo = ExcelStyleInfoType.Title }); + MergeCells(new ExcelMergeParameters { CellFromName = "A1", CellToName = "C1" }); + uint rowIndex = 2; - foreach (var sc in info.SushiComponents) + foreach (var pc in info.SushiComponents) { InsertCellInWorksheet(new ExcelCellParameters { ColumnName = "A", RowIndex = rowIndex, - Text = sc.SushiName, + Text = pc.SushiName, StyleInfo = ExcelStyleInfoType.Text }); rowIndex++; - foreach (var component in sc.Components) + + foreach (var (Component, Count) in pc.Components) { InsertCellInWorksheet(new ExcelCellParameters { ColumnName = "B", RowIndex = rowIndex, - Text = component.Item1, + Text = Component, StyleInfo = ExcelStyleInfoType.TextWithBroder }); + InsertCellInWorksheet(new ExcelCellParameters { ColumnName = "C", RowIndex = rowIndex, - Text = component.Item2.ToString(), + Text = Count.ToString(), StyleInfo = ExcelStyleInfoType.TextWithBroder }); + rowIndex++; } + InsertCellInWorksheet(new ExcelCellParameters { ColumnName = "A", @@ -65,33 +72,90 @@ namespace SushiBarBusinessLogic.OfficePackage { ColumnName = "C", RowIndex = rowIndex, - Text = sc.TotalCount.ToString(), + Text = pc.TotalCount.ToString(), StyleInfo = ExcelStyleInfoType.Text }); rowIndex++; } + SaveExcel(info); } - /// - /// Создание excel-файла - /// - /// - protected abstract void CreateExcel(ExcelInfo info); - /// - /// Добавляем новую ячейку в лист - /// - /// - protected abstract void InsertCellInWorksheet(ExcelCellParameters - excelParams); - /// - /// Объединение ячеек - /// - /// + + public void CreateShopSushisReport(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.ShopSushis) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = sr.ShopName, + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + + foreach (var (Sushi, Count) in sr.Sushis) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = Sushi, + StyleInfo = ExcelStyleInfoType.TextWithBroder + }); + + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = Count.ToString(), + StyleInfo = ExcelStyleInfoType.TextWithBroder + }); + + rowIndex++; + } + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Итого", + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = sr.TotalCount.ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + } + + SaveExcel(info); + } + + protected abstract void CreateExcel(IDocument info); + protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams); protected abstract void MergeCells(ExcelMergeParameters excelParams); - /// - /// Сохранение файла - /// - /// - protected abstract void SaveExcel(ExcelInfo info); + protected abstract void SaveExcel(IDocument info); } } diff --git a/SushiBar/SushiBarBusinessLogic_/OfficePackage/AbstractSaveToPdf.cs b/SushiBar/SushiBarBusinessLogic_/OfficePackage/AbstractSaveToPdf.cs index b3f0d21..1795203 100644 --- a/SushiBar/SushiBarBusinessLogic_/OfficePackage/AbstractSaveToPdf.cs +++ b/SushiBar/SushiBarBusinessLogic_/OfficePackage/AbstractSaveToPdf.cs @@ -13,67 +13,65 @@ namespace SushiBarBusinessLogic.OfficePackage 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 { "1cm", "3cm", "4cm", "6cm", "3cm" }); + 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", "3cm", "3cm" }); + CreateRow(new PdfRowParameters { - Texts = new List { "Номер", "Дата заказа", "Статус", "Изделие", "Сумма" }, + 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.Status.ToString(), order.SushiName, order.Sum.ToString() }, + Texts = new List { order.Id.ToString(), order.DateCreate.ToShortDateString(), order.SushiName, order.Status.ToString(), order.Sum.ToString() }, Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Left }); } - CreateParagraph(new PdfParagraph - { - Text = $"Итого: {info.Orders.Sum(x => x.Sum)}\t", - Style = "Normal", - ParagraphAlignment = PdfParagraphAlignmentType.Rigth - }); + CreateParagraph(new PdfParagraph { Text = $"Итого: {info.Orders.Sum(x => x.Sum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Rigth }); + SavePdf(info); } - /// - /// Создание doc-файла - /// - /// - protected abstract void CreatePdf(PdfInfo 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); + } + + 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(PdfInfo info); + protected abstract void SavePdf(IDocument info); } } diff --git a/SushiBar/SushiBarBusinessLogic_/OfficePackage/AbstractSaveToWord.cs b/SushiBar/SushiBarBusinessLogic_/OfficePackage/AbstractSaveToWord.cs index bd162a0..3e15d25 100644 --- a/SushiBar/SushiBarBusinessLogic_/OfficePackage/AbstractSaveToWord.cs +++ b/SushiBar/SushiBarBusinessLogic_/OfficePackage/AbstractSaveToWord.cs @@ -38,21 +38,52 @@ namespace SushiBarBusinessLogic.OfficePackage } SaveWord(info); } - /// - /// Создание doc-файла - /// - /// - protected abstract void CreateWord(WordInfo info); - /// - /// Создание абзаца с текстом - /// - /// - /// + + public void CreateShopsDoc(WordShopInfo info) + { + CreateWord(info); + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + + CreateTable(new List { "3000", "3000", "3000" }); + CreateRow(new WordRowParameters + { + Texts = new List { "Название", "Адрес", "Дата открытия" }, + TextProperties = new WordTextProperties + { + Size = "24", + Bold = true, + JustificationType = WordJustificationType.Center + } + }); + + foreach (var shop in info.Shops) + { + CreateRow(new WordRowParameters + { + Texts = new List { shop.ShopName, shop.Adress, shop.OpeningDate.ToString() }, + TextProperties = new WordTextProperties + { + Size = "22", + JustificationType = WordJustificationType.Both + } + }); + } + + SaveWord(info); + } + + protected abstract void CreateWord(IDocument info); protected abstract void CreateParagraph(WordParagraph paragraph); - /// - /// Сохранение файла - /// - /// - protected abstract void SaveWord(WordInfo info); + protected abstract void SaveWord(IDocument info); + protected abstract void CreateTable(List colums); + protected abstract void CreateRow(WordRowParameters rowParameters); } } \ No newline at end of file diff --git a/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/ExcelInfo.cs b/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/ExcelInfo.cs index d9b69b4..f4ea133 100644 --- a/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/ExcelInfo.cs +++ b/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/ExcelInfo.cs @@ -2,7 +2,7 @@ namespace SushiBarBusinessLogic.OfficePackage.HelperModels { - public class ExcelInfo + public class ExcelInfo : IDocument { public string FileName { get; set; } = string.Empty; public string Title { get; set; } = string.Empty; diff --git a/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/ExcelShop.cs b/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/ExcelShop.cs new file mode 100644 index 0000000..680c521 --- /dev/null +++ b/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/ExcelShop.cs @@ -0,0 +1,16 @@ +using SushiBarContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarBusinessLogic.OfficePackage.HelperModels +{ + public class ExcelShop : IDocument + { + public string FileName { get; set; } = string.Empty; + public string Title { get; set; } = string.Empty; + public List ShopSushis { get; set; } = new(); + } +} diff --git a/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/PdfGroupedOrdersInfo.cs b/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/PdfGroupedOrdersInfo.cs new file mode 100644 index 0000000..fbcc93d --- /dev/null +++ b/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/PdfGroupedOrdersInfo.cs @@ -0,0 +1,18 @@ +using SushiBarContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarBusinessLogic.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/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/PdfInfo.cs b/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/PdfInfo.cs index bf4b058..189cdd8 100644 --- a/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/PdfInfo.cs +++ b/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/PdfInfo.cs @@ -8,7 +8,7 @@ using System.Threading.Tasks; namespace SushiBarBusinessLogic.OfficePackage.HelperModels { - public class PdfInfo + public class PdfInfo : IDocument { public string FileName { get; set; } = string.Empty; public string Title { get; set; } = string.Empty; diff --git a/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/WordInfo.cs b/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/WordInfo.cs index 472a5aa..8e36208 100644 --- a/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/WordInfo.cs +++ b/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/WordInfo.cs @@ -2,7 +2,7 @@ namespace SushiBarBusinessLogic.OfficePackage.HelperModels { - public class WordInfo + public class WordInfo : IDocument { public string FileName { get; set; } = string.Empty; public string Title { get; set; } = string.Empty; diff --git a/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/WordRowParameters.cs b/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/WordRowParameters.cs new file mode 100644 index 0000000..2df1cd9 --- /dev/null +++ b/SushiBar/SushiBarBusinessLogic_/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 SushiBarBusinessLogic.OfficePackage.HelperModels +{ + public class WordRowParameters + { + public List Texts { get; set; } = new(); + public WordTextProperties TextProperties { get; set; } = new(); + } +} diff --git a/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/WordShopInfo.cs b/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/WordShopInfo.cs new file mode 100644 index 0000000..75515bf --- /dev/null +++ b/SushiBar/SushiBarBusinessLogic_/OfficePackage/HelperModels/WordShopInfo.cs @@ -0,0 +1,16 @@ +using SushiBarContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarBusinessLogic.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/SushiBar/SushiBarBusinessLogic_/OfficePackage/IDocument.cs b/SushiBar/SushiBarBusinessLogic_/OfficePackage/IDocument.cs new file mode 100644 index 0000000..14e64b9 --- /dev/null +++ b/SushiBar/SushiBarBusinessLogic_/OfficePackage/IDocument.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarBusinessLogic.OfficePackage +{ + public interface IDocument + { + public string FileName { get; set; } + public string Title { get; set; } + } +} diff --git a/SushiBar/SushiBarBusinessLogic_/OfficePackage/Implements/SaveToExcel.cs b/SushiBar/SushiBarBusinessLogic_/OfficePackage/Implements/SaveToExcel.cs index 99c7ee3..05ef135 100644 --- a/SushiBar/SushiBarBusinessLogic_/OfficePackage/Implements/SaveToExcel.cs +++ b/SushiBar/SushiBarBusinessLogic_/OfficePackage/Implements/SaveToExcel.cs @@ -14,167 +14,110 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements 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 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 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 - }); + 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 }); + 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 }); + 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 - }; + 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 - }; + 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 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}" - }; + + 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}" - }; + 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" - }); + stylesheetExtension2.Append(new TimelineStyles() { DefaultTimelineStyle = "TimeSlicerStyleLight1" }); + stylesheetExtensionList.Append(stylesheetExtension1); stylesheetExtensionList.Append(stylesheetExtension2); + sp.Stylesheet.Append(fonts); sp.Stylesheet.Append(fills); sp.Stylesheet.Append(borders); @@ -185,11 +128,7 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements sp.Stylesheet.Append(tableStyles); sp.Stylesheet.Append(stylesheetExtensionList); } - /// - /// Получение номера стиля из типа - /// - /// - /// + private static uint GetStyleValue(ExcelStyleInfoType styleInfo) { return styleInfo switch @@ -200,40 +139,44 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements _ => 0U, }; } - protected override void CreateExcel(ExcelInfo info) + + protected override void CreateExcel(IDocument info) { - _spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, - SpreadsheetDocumentType.Workbook); + _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(); + + // Получаем/создаем хранилище текстов для книги + _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 sheets = _spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets()); var sheet = new Sheet() { - Id = - _spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), + 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) @@ -245,6 +188,7 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements { return; } + // Ищем строку, либо добавляем ее Row row; if (sheetData.Elements().Where(r => r.RowIndex! == excelParams.RowIndex).Any()) @@ -256,7 +200,8 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements row = new Row() { RowIndex = excelParams.RowIndex }; sheetData.Append(row); } - // Ищем нужную ячейку + + // Ищем нужную ячейку Cell cell; if (row.Elements().Where(c => c.CellReference!.Value == excelParams.CellReference).Any()) { @@ -275,20 +220,22 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements break; } } - var newCell = new Cell() - { - CellReference = excelParams.CellReference - }; + + 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) @@ -296,6 +243,7 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements return; } MergeCells mergeCells; + if (_worksheet.Elements().Any()) { mergeCells = _worksheet.Elements().First(); @@ -303,24 +251,25 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements else { mergeCells = new MergeCells(); + if (_worksheet.Elements().Any()) { - _worksheet.InsertAfter(mergeCells, - _worksheet.Elements().First()); + _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); } else { - _worksheet.InsertAfter(mergeCells, - _worksheet.Elements().First()); + _worksheet.InsertAfter(mergeCells, _worksheet.Elements().First()); } } + var mergeCell = new MergeCell() { Reference = new StringValue(excelParams.Merge) }; mergeCells.Append(mergeCell); } - protected override void SaveExcel(ExcelInfo info) + + protected override void SaveExcel(IDocument info) { if (_spreadsheetDocument == null) { diff --git a/SushiBar/SushiBarBusinessLogic_/OfficePackage/Implements/SaveToPdf.cs b/SushiBar/SushiBarBusinessLogic_/OfficePackage/Implements/SaveToPdf.cs index a5840f7..ed10be5 100644 --- a/SushiBar/SushiBarBusinessLogic_/OfficePackage/Implements/SaveToPdf.cs +++ b/SushiBar/SushiBarBusinessLogic_/OfficePackage/Implements/SaveToPdf.cs @@ -11,6 +11,7 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements private Document? _document; private Section? _section; private Table? _table; + private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type) { return type switch @@ -21,24 +22,25 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements _ => ParagraphAlignment.Justify, }; } - /// - /// Создание стилей для документа - /// - /// + private static void DefineStyles(Document document) { var style = document.Styles["Normal"]; style.Font.Name = "Times New Roman"; style.Font.Size = 14; + style = document.Styles.AddStyle("NormalTitle", "Normal"); style.Font.Bold = true; } - protected override void CreatePdf(PdfInfo info) + + protected override void CreatePdf(IDocument info) { _document = new Document(); DefineStyles(_document); + _section = _document.AddSection(); } + protected override void CreateParagraph(PdfParagraph pdfParagraph) { if (_section == null) @@ -50,6 +52,7 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements paragraph.Format.Alignment = GetParagraphAlignment(pdfParagraph.ParagraphAlignment); paragraph.Style = pdfParagraph.Style; } + protected override void CreateTable(List columns) { if (_document == null) @@ -57,11 +60,13 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements return; } _table = _document.LastSection.AddTable(); + foreach (var elem in columns) { _table.AddColumn(elem); } } + protected override void CreateRow(PdfRowParameters rowParameters) { if (_table == null) @@ -72,20 +77,25 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements for (int i = 0; i < rowParameters.Texts.Count; ++i) { row.Cells[i].AddParagraph(rowParameters.Texts[i]); + if (!string.IsNullOrEmpty(rowParameters.Style)) { row.Cells[i].Style = rowParameters.Style; } + Unit borderWidth = 0.5; + row.Cells[i].Borders.Left.Width = borderWidth; row.Cells[i].Borders.Right.Width = borderWidth; row.Cells[i].Borders.Top.Width = borderWidth; row.Cells[i].Borders.Bottom.Width = borderWidth; + row.Cells[i].Format.Alignment = GetParagraphAlignment(rowParameters.ParagraphAlignment); row.Cells[i].VerticalAlignment = VerticalAlignment.Center; } } - protected override void SavePdf(PdfInfo info) + + protected override void SavePdf(IDocument info) { var renderer = new PdfDocumentRenderer(true) { @@ -95,4 +105,4 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements renderer.PdfDocument.Save(info.FileName); } } -} \ No newline at end of file +} \ No newline at end of file diff --git a/SushiBar/SushiBarBusinessLogic_/OfficePackage/Implements/SaveToWord.cs b/SushiBar/SushiBarBusinessLogic_/OfficePackage/Implements/SaveToWord.cs index 6c1fc93..0e5ffa3 100644 --- a/SushiBar/SushiBarBusinessLogic_/OfficePackage/Implements/SaveToWord.cs +++ b/SushiBar/SushiBarBusinessLogic_/OfficePackage/Implements/SaveToWord.cs @@ -11,13 +11,8 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements { private WordprocessingDocument? _wordDocument; private Body? _docBody; - /// - /// Получение типа выравнивания - /// - /// - /// - private static JustificationValues - GetJustificationValues(WordJustificationType type) + + private static JustificationValues GetJustificationValues(WordJustificationType type) { return type switch { @@ -26,59 +21,60 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements _ => 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 - }); + paragraphMarkRunProperties.AppendChild(new FontSize { Val = paragraphProperties.Size }); } properties.AppendChild(paragraphMarkRunProperties); + return properties; } - protected override void CreateWord(WordInfo info) + + protected override void CreateWord(IDocument info) { _wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document); MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart(); mainPart.Document = new Document(); _docBody = mainPart.Document.AppendChild(new Body()); } + protected override void CreateParagraph(WordParagraph paragraph) { if (_docBody == null || paragraph == null) @@ -88,9 +84,11 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements 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) @@ -98,24 +96,97 @@ namespace SushiBarBusinessLogic.OfficePackage.Implements properties.AppendChild(new Bold()); } docRun.AppendChild(properties); - docRun.AppendChild(new Text - { - Text = run.Item1, - Space = SpaceProcessingModeValues.Preserve - }); + + docRun.AppendChild(new Text { Text = run.Item1, Space = SpaceProcessingModeValues.Preserve }); + docParagraph.AppendChild(docRun); } + _docBody.AppendChild(docParagraph); } - protected override void SaveWord(WordInfo info) + + 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/SushiBar/SushiBarContracts/BindingModels/ShopBindingModel.cs b/SushiBar/SushiBarContracts/BindingModels/ShopBindingModel.cs new file mode 100644 index 0000000..dc490f3 --- /dev/null +++ b/SushiBar/SushiBarContracts/BindingModels/ShopBindingModel.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SushiBarDataModels.Models; + +namespace SushiBarContracts.BindingModels +{ + public class ShopBindingModel : IShopModel + { + public int Id { get; set; } + public string ShopName { get; set; } = string.Empty; + public string Adress { get; set; } = string.Empty; + public DateTime OpeningDate { get; set; } = DateTime.Now; + public Dictionary ShopSushis { get; set; } = new(); + public int SushiMaxCount { get; set; } + } +} diff --git a/SushiBar/SushiBarContracts/BindingModels/SupplyBindingModel.cs b/SushiBar/SushiBarContracts/BindingModels/SupplyBindingModel.cs new file mode 100644 index 0000000..c3520bc --- /dev/null +++ b/SushiBar/SushiBarContracts/BindingModels/SupplyBindingModel.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SushiBarDataModels.Models; + +namespace SushiBarContracts.BindingModels +{ + public class SupplyBindingModel : ISupplyModel + { + public int ShopId { get; set; } + public int SushiId { get; set; } + public int Count { get; set; } + } +} diff --git a/SushiBar/SushiBarContracts/BusinessLogicsContracts/IReportLogic.cs b/SushiBar/SushiBarContracts/BusinessLogicsContracts/IReportLogic.cs index a993281..5e036bc 100644 --- a/SushiBar/SushiBarContracts/BusinessLogicsContracts/IReportLogic.cs +++ b/SushiBar/SushiBarContracts/BusinessLogicsContracts/IReportLogic.cs @@ -7,8 +7,13 @@ namespace SushiBarContracts.BusinessLogicsContracts { List GetSushiComponents(); List GetOrders(ReportBindingModel model); + List GetShops(); + List GetGroupedOrders(); void SaveSushisToWordFile(ReportBindingModel model); void SaveSushiComponentToExcelFile(ReportBindingModel model); void SaveOrdersToPdfFile(ReportBindingModel model); + void SaveShopsToWordFile(ReportBindingModel model); + void SaveShopsToExcelFile(ReportBindingModel model); + void SaveGroupedOrdersToPdfFile(ReportBindingModel model); } } \ No newline at end of file diff --git a/SushiBar/SushiBarContracts/BusinessLogicsContracts/IShopLogic.cs b/SushiBar/SushiBarContracts/BusinessLogicsContracts/IShopLogic.cs new file mode 100644 index 0000000..7862fa4 --- /dev/null +++ b/SushiBar/SushiBarContracts/BusinessLogicsContracts/IShopLogic.cs @@ -0,0 +1,22 @@ +using SushiBarContracts.BindingModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SushiBarContracts.SearchModels; +using SushiBarContracts.ViewModels; + +namespace SushiBarContracts.BusinessLogicsContracts +{ + public interface IShopLogic + { + List? ReadList(ShopSearchModel? model); + ShopViewModel? ReadElement(ShopSearchModel model); + bool Create(ShopBindingModel model); + bool Update(ShopBindingModel model); + bool Delete(ShopBindingModel model); + bool MakeSupply(SupplyBindingModel model); + bool Sale(SupplySearchModel model); + } +} diff --git a/SushiBar/SushiBarContracts/SearchModels/ShopSearchModel.cs b/SushiBar/SushiBarContracts/SearchModels/ShopSearchModel.cs new file mode 100644 index 0000000..fbd2461 --- /dev/null +++ b/SushiBar/SushiBarContracts/SearchModels/ShopSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.SearchModels +{ + public class ShopSearchModel + { + public int? Id { get; set; } + public string? ShopName { get; set; } + } +} diff --git a/SushiBar/SushiBarContracts/SearchModels/SupplySearchModel.cs b/SushiBar/SushiBarContracts/SearchModels/SupplySearchModel.cs new file mode 100644 index 0000000..d74c710 --- /dev/null +++ b/SushiBar/SushiBarContracts/SearchModels/SupplySearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.SearchModels +{ + public class SupplySearchModel + { + public int? SushiId { get; set; } + public int? Count { get; set; } + } +} diff --git a/SushiBar/SushiBarContracts/StoragesContracts/IShopStorage.cs b/SushiBar/SushiBarContracts/StoragesContracts/IShopStorage.cs new file mode 100644 index 0000000..5fa2582 --- /dev/null +++ b/SushiBar/SushiBarContracts/StoragesContracts/IShopStorage.cs @@ -0,0 +1,23 @@ +using SushiBarContracts.BindingModels; +using SushiBarContracts.SearchModels; +using SushiBarContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.StoragesContracts +{ + public interface IShopStorage + { + List GetFullList(); + List GetFilteredList(ShopSearchModel model); + ShopViewModel? GetElement(ShopSearchModel model); + ShopViewModel? Insert(ShopBindingModel model); + ShopViewModel? Update(ShopBindingModel model); + ShopViewModel? Delete(ShopBindingModel model); + bool Sale(SupplySearchModel model); + bool RestockingShops(SupplyBindingModel model); + } +} diff --git a/SushiBar/SushiBarContracts/ViewModels/ReportGroupOrdersViewModel.cs b/SushiBar/SushiBarContracts/ViewModels/ReportGroupOrdersViewModel.cs new file mode 100644 index 0000000..cd2bcc0 --- /dev/null +++ b/SushiBar/SushiBarContracts/ViewModels/ReportGroupOrdersViewModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.ViewModels +{ + public class ReportGroupOrdersViewModel + { + public DateTime Date { get; set; } = DateTime.Now; + public int OrdersCount { get; set; } + public double OrdersSum { get; set; } + } +} diff --git a/SushiBar/SushiBarContracts/ViewModels/ReportShopsViewModel.cs b/SushiBar/SushiBarContracts/ViewModels/ReportShopsViewModel.cs new file mode 100644 index 0000000..d085d88 --- /dev/null +++ b/SushiBar/SushiBarContracts/ViewModels/ReportShopsViewModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarContracts.ViewModels +{ + public class ReportShopsViewModel + { + public string ShopName { get; set; } = string.Empty; + public int TotalCount { get; set; } + public List<(string Sushi, int count)> Sushis { get; set; } = new(); + } +} diff --git a/SushiBar/SushiBarContracts/ViewModels/ShopViewModel.cs b/SushiBar/SushiBarContracts/ViewModels/ShopViewModel.cs new file mode 100644 index 0000000..d257b9b --- /dev/null +++ b/SushiBar/SushiBarContracts/ViewModels/ShopViewModel.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SushiBarDataModels.Models; +using SushiBarContracts.ViewModels; + +namespace SushiBarContracts.ViewModels +{ + public class ShopViewModel : IShopModel + { + public int Id { get; set; } + [DisplayName("Название")] + public string ShopName { get; set; } = string.Empty; + [DisplayName("Адрес")] + public string Adress { get; set; } = string.Empty; + [DisplayName("Дата открытия")] + public DateTime OpeningDate { get; set; } + public Dictionary ShopSushis { get; set; } = new(); + [DisplayName("Вместимость")] + public int SushiMaxCount { get; set; } + } +} diff --git a/SushiBar/SushiBarDataModels/Models/IShopModel.cs b/SushiBar/SushiBarDataModels/Models/IShopModel.cs new file mode 100644 index 0000000..52caf62 --- /dev/null +++ b/SushiBar/SushiBarDataModels/Models/IShopModel.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarDataModels.Models +{ + public interface IShopModel : IId + { + string ShopName { get; } + string Adress { get; } + DateTime OpeningDate { get; } + Dictionary ShopSushis { get; } + public int SushiMaxCount { get; } + } +} diff --git a/SushiBar/SushiBarDataModels/Models/ISupplyModel.cs b/SushiBar/SushiBarDataModels/Models/ISupplyModel.cs new file mode 100644 index 0000000..d8b8348 --- /dev/null +++ b/SushiBar/SushiBarDataModels/Models/ISupplyModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarDataModels.Models +{ + public interface ISupplyModel + { + int ShopId { get; } + int SushiId { get; } + int Count { get; } + } +} diff --git a/SushiBar/SushiBarDatabaseImplement/Implements/OrderStorage.cs b/SushiBar/SushiBarDatabaseImplement/Implements/OrderStorage.cs index 33306be..2ac65a5 100644 --- a/SushiBar/SushiBarDatabaseImplement/Implements/OrderStorage.cs +++ b/SushiBar/SushiBarDatabaseImplement/Implements/OrderStorage.cs @@ -17,24 +17,20 @@ namespace SushiBarDatabaseImplement.Implements public List GetFullList() { using var context = new SushiBarDatabase(); - return context.Orders.Include(x => x.Sushi).Include(x => x.Client).Select(x => x.GetViewModel).ToList(); + return context.Orders.Include(x => x.Sushi).Select(x => x.GetViewModel).ToList(); } public List GetFilteredList(OrderSearchModel model) { + if (!model.DateFrom.HasValue || !model.DateFrom.HasValue || !model.DateTo.HasValue) + { + return new(); + } using var context = new SushiBarDatabase(); if (model.DateFrom.HasValue) { return context.Orders.Include(x => x.Sushi).Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo).Select(x => x.GetViewModel).ToList(); } - if (model.ClientId.HasValue) - { - return context.Orders.Include(x => x.Sushi).Where(x => x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList(); - } - if (model.ClientId.HasValue) - { - return context.Orders.Include(x => x.Sushi).Where(x => x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList(); - } return context.Orders.Include(x => x.Sushi).Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList(); } diff --git a/SushiBar/SushiBarDatabaseImplement/Implements/ShopStorage.cs b/SushiBar/SushiBarDatabaseImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..c5d472c --- /dev/null +++ b/SushiBar/SushiBarDatabaseImplement/Implements/ShopStorage.cs @@ -0,0 +1,186 @@ +using Microsoft.EntityFrameworkCore; +using SushiBarContracts.BindingModels; +using SushiBarContracts.SearchModels; +using SushiBarContracts.StoragesContracts; +using SushiBarContracts.ViewModels; +using SushiBarDatabaseImplement.Models; + + +namespace SushiBarDatabaseImplement.Implements +{ + public class ShopStorage : IShopStorage + { + public List GetFullList() + { + using var context = new SushiBarDatabase(); + return context.Shops.Include(x => x.Sushis).ThenInclude(x => x.Sushi).ToList(). + Select(x => x.GetViewModel).ToList(); + } + + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName)) + { + return new(); + } + using var context = new SushiBarDatabase(); + return context.Shops.Include(x => x.Sushis).ThenInclude(x => x.Sushi).Where(x => x.ShopName.Contains(model.ShopName)). + ToList().Select(x => x.GetViewModel).ToList(); + } + + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) + { + return new(); + } + using var context = new SushiBarDatabase(); + return context.Shops.Include(x => x.Sushis).ThenInclude(x => x.Sushi) + .FirstOrDefault(x => + (!string.IsNullOrEmpty(model.ShopName) && x.ShopName == model.ShopName) || + (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + using var context = new SushiBarDatabase(); + var newShop = Shop.Create(context, model); + if (newShop == null) + { + return null; + } + context.Shops.Add(newShop); + context.SaveChanges(); + return newShop.GetViewModel; + } + + public ShopViewModel? Update(ShopBindingModel model) + { + using var context = new SushiBarDatabase(); + 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.UpdateSushis(context, model); + transaction.Commit(); + return shop.GetViewModel; + } + catch + { + transaction.Rollback(); + throw; + } + } + + public ShopViewModel? Delete(ShopBindingModel model) + { + using var context = new SushiBarDatabase(); + var shop = context.Shops.Include(x => x.Sushis).FirstOrDefault(x => x.Id == model.Id); + if (shop != null) + { + context.Shops.Remove(shop); + context.SaveChanges(); + return shop.GetViewModel; + } + return null; + } + + public bool RestockingShops(SupplyBindingModel model) + { + using var context = new SushiBarDatabase(); + var transaction = context.Database.BeginTransaction(); + var Shops = context.Shops.Include(x => x.Sushis).ThenInclude(x => x.Sushi).ToList(). + Where(x => x.SushiMaxCount > x.ShopSushis.Select(x => x.Value.Item2).Sum()).ToList(); + if (model == null) + { + return false; + } + try + { + foreach (Shop shop in Shops) + { + int difference = shop.SushiMaxCount - shop.ShopSushis.Select(x => x.Value.Item2).Sum(); + int refill = Math.Min(difference, model.Count); + model.Count -= refill; + if (shop.ShopSushis.ContainsKey(model.SushiId)) + { + var datePair = shop.ShopSushis[model.SushiId]; + datePair.Item2 += refill; + shop.ShopSushis[model.SushiId] = datePair; + } + else + { + var sushi = context.Sushis.First(x => x.Id == model.SushiId); + shop.ShopSushis.Add(model.SushiId, (sushi, refill)); + } + shop.SushisDictionatyUpdate(context); + if (model.Count == 0) + { + transaction.Commit(); + return true; + } + } + transaction.Rollback(); + return false; + } + catch + { + transaction.Rollback(); + throw; + } + } + + public bool Sale(SupplySearchModel model) + { + using var context = new SushiBarDatabase(); + var transaction = context.Database.BeginTransaction(); + try + { + var shops = context.Shops.Include(x => x.Sushis).ThenInclude(x => x.Sushi).ToList(). + Where(x => x.ShopSushis.ContainsKey(model.SushiId.Value)).OrderByDescending(x => x.ShopSushis[model.SushiId.Value].Item2).ToList(); + + foreach (var shop in shops) + { + int residue = model.Count.Value - shop.ShopSushis[model.SushiId.Value].Item2; + if (residue > 0) + { + shop.ShopSushis.Remove(model.SushiId.Value); + shop.SushisDictionatyUpdate(context); + context.SaveChanges(); + model.Count = residue; + + } + else + { + if (residue == 0) + shop.ShopSushis.Remove(model.SushiId.Value); + else + { + var dataPair = shop.ShopSushis[model.SushiId.Value]; + dataPair.Item2 = -residue; + shop.ShopSushis[model.SushiId.Value] = dataPair; + } + + shop.SushisDictionatyUpdate(context); + transaction.Commit(); + return true; + } + } + transaction.Rollback(); + return false; + } + catch + { + transaction.Rollback(); + throw; + } + } + + } +} diff --git a/SushiBar/SushiBarDatabaseImplement/Migrations/20240420142132_InitialCreate.Designer.cs b/SushiBar/SushiBarDatabaseImplement/Migrations/20240313082356_InitialCreate.Designer.cs similarity index 78% rename from SushiBar/SushiBarDatabaseImplement/Migrations/20240420142132_InitialCreate.Designer.cs rename to SushiBar/SushiBarDatabaseImplement/Migrations/20240313082356_InitialCreate.Designer.cs index 6e49bbd..7809e8c 100644 --- a/SushiBar/SushiBarDatabaseImplement/Migrations/20240420142132_InitialCreate.Designer.cs +++ b/SushiBar/SushiBarDatabaseImplement/Migrations/20240313082356_InitialCreate.Designer.cs @@ -12,7 +12,7 @@ using SushiBarDatabaseImplement; namespace SushiBarDatabaseImplement.Migrations { [DbContext(typeof(SushiBarDatabase))] - [Migration("20240420142132_InitialCreate")] + [Migration("20240313082356_InitialCreate")] partial class InitialCreate { /// @@ -25,31 +25,6 @@ namespace SushiBarDatabaseImplement.Migrations SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); - modelBuilder.Entity("SushiBarDatabaseImplement.Models.Client", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("int"); - - SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - - b.Property("ClientFIO") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Email") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.Property("Password") - .IsRequired() - .HasColumnType("nvarchar(max)"); - - b.HasKey("Id"); - - b.ToTable("Clients"); - }); - modelBuilder.Entity("SushiBarDatabaseImplement.Models.Component", b => { b.Property("Id") @@ -78,9 +53,6 @@ namespace SushiBarDatabaseImplement.Migrations SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); - b.Property("ClientId") - .HasColumnType("int"); - b.Property("Count") .HasColumnType("int"); @@ -101,8 +73,6 @@ namespace SushiBarDatabaseImplement.Migrations b.HasKey("Id"); - b.HasIndex("ClientId"); - b.HasIndex("SushiId"); b.ToTable("Orders"); @@ -156,20 +126,12 @@ namespace SushiBarDatabaseImplement.Migrations modelBuilder.Entity("SushiBarDatabaseImplement.Models.Order", b => { - b.HasOne("SushiBarDatabaseImplement.Models.Client", "Client") - .WithMany("Orders") - .HasForeignKey("ClientId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - b.HasOne("SushiBarDatabaseImplement.Models.Sushi", "Sushi") .WithMany("Orders") .HasForeignKey("SushiId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); - b.Navigation("Client"); - b.Navigation("Sushi"); }); @@ -192,11 +154,6 @@ namespace SushiBarDatabaseImplement.Migrations b.Navigation("Sushi"); }); - modelBuilder.Entity("SushiBarDatabaseImplement.Models.Client", b => - { - b.Navigation("Orders"); - }); - modelBuilder.Entity("SushiBarDatabaseImplement.Models.Component", b => { b.Navigation("SushiComponents"); diff --git a/SushiBar/SushiBarDatabaseImplement/Migrations/20240420142132_InitialCreate.cs b/SushiBar/SushiBarDatabaseImplement/Migrations/20240313082356_InitialCreate.cs similarity index 79% rename from SushiBar/SushiBarDatabaseImplement/Migrations/20240420142132_InitialCreate.cs rename to SushiBar/SushiBarDatabaseImplement/Migrations/20240313082356_InitialCreate.cs index 43ae97b..4367175 100644 --- a/SushiBar/SushiBarDatabaseImplement/Migrations/20240420142132_InitialCreate.cs +++ b/SushiBar/SushiBarDatabaseImplement/Migrations/20240313082356_InitialCreate.cs @@ -11,21 +11,6 @@ namespace SushiBarDatabaseImplement.Migrations /// protected override void Up(MigrationBuilder migrationBuilder) { - migrationBuilder.CreateTable( - name: "Clients", - columns: table => new - { - Id = table.Column(type: "int", nullable: false) - .Annotation("SqlServer:Identity", "1, 1"), - ClientFIO = table.Column(type: "nvarchar(max)", nullable: false), - Email = table.Column(type: "nvarchar(max)", nullable: false), - Password = table.Column(type: "nvarchar(max)", nullable: false) - }, - constraints: table => - { - table.PrimaryKey("PK_Clients", x => x.Id); - }); - migrationBuilder.CreateTable( name: "Components", columns: table => new @@ -60,7 +45,6 @@ namespace SushiBarDatabaseImplement.Migrations { Id = table.Column(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), - ClientId = table.Column(type: "int", nullable: false), SushiId = table.Column(type: "int", nullable: false), Count = table.Column(type: "int", nullable: false), Sum = table.Column(type: "float", nullable: false), @@ -71,12 +55,6 @@ namespace SushiBarDatabaseImplement.Migrations constraints: table => { table.PrimaryKey("PK_Orders", x => x.Id); - table.ForeignKey( - name: "FK_Orders_Clients_ClientId", - column: x => x.ClientId, - principalTable: "Clients", - principalColumn: "Id", - onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Orders_Sushis_SushiId", column: x => x.SushiId, @@ -112,11 +90,6 @@ namespace SushiBarDatabaseImplement.Migrations onDelete: ReferentialAction.Cascade); }); - migrationBuilder.CreateIndex( - name: "IX_Orders_ClientId", - table: "Orders", - column: "ClientId"); - migrationBuilder.CreateIndex( name: "IX_Orders_SushiId", table: "Orders", @@ -142,9 +115,6 @@ namespace SushiBarDatabaseImplement.Migrations migrationBuilder.DropTable( name: "SushiComponents"); - migrationBuilder.DropTable( - name: "Clients"); - migrationBuilder.DropTable( name: "Components"); diff --git a/SushiBar/SushiBarDatabaseImplement/Migrations/20240424121819_InitCreate.Designer.cs b/SushiBar/SushiBarDatabaseImplement/Migrations/20240424121819_InitCreate.Designer.cs new file mode 100644 index 0000000..243ca74 --- /dev/null +++ b/SushiBar/SushiBarDatabaseImplement/Migrations/20240424121819_InitCreate.Designer.cs @@ -0,0 +1,296 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SushiBarDatabaseImplement; + +#nullable disable + +namespace SushiBarDatabaseImplement.Migrations +{ + [DbContext(typeof(SushiBarDatabase))] +<<<<<<<< HEAD:SushiBar/SushiBarDatabaseImplement/Migrations/20240420142132_InitialCreate.Designer.cs + [Migration("20240420142132_InitialCreate")] + partial class InitialCreate +======== + [Migration("20240424121819_InitCreate")] + partial class InitCreate +>>>>>>>> Lab_4_Hard:SushiBar/SushiBarDatabaseImplement/Migrations/20240424121819_InitCreate.Designer.cs + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.17") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("SushiBarDatabaseImplement.Models.Client", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientFIO") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Email") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Password") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Clients"); + }); + + modelBuilder.Entity("SushiBarDatabaseImplement.Models.Component", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Cost") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Components"); + }); + + modelBuilder.Entity("SushiBarDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ClientId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.Property("SushiId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ClientId"); + + b.HasIndex("SushiId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("SushiBarDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Adress") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OpeningDate") + .HasColumnType("datetime2"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("SushiMaxCount") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("SushiBarDatabaseImplement.Models.ShopSushis", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.Property("SushiId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ShopId"); + + b.HasIndex("SushiId"); + + b.ToTable("ShopSushis"); + }); + + modelBuilder.Entity("SushiBarDatabaseImplement.Models.Sushi", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Price") + .HasColumnType("float"); + + b.Property("SushiName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Sushis"); + }); + + modelBuilder.Entity("SushiBarDatabaseImplement.Models.SushiComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("SushiId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("SushiId"); + + b.ToTable("SushiComponents"); + }); + + modelBuilder.Entity("SushiBarDatabaseImplement.Models.Order", b => + { + b.HasOne("SushiBarDatabaseImplement.Models.Client", "Client") + .WithMany("Orders") + .HasForeignKey("ClientId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SushiBarDatabaseImplement.Models.Sushi", "Sushi") + .WithMany("Orders") + .HasForeignKey("SushiId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Client"); + + b.Navigation("Sushi"); + }); + + modelBuilder.Entity("SushiBarDatabaseImplement.Models.ShopSushis", b => + { + b.HasOne("SushiBarDatabaseImplement.Models.Shop", "Shop") + .WithMany("Sushis") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SushiBarDatabaseImplement.Models.Sushi", "Sushi") + .WithMany() + .HasForeignKey("SushiId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Shop"); + + b.Navigation("Sushi"); + }); + + modelBuilder.Entity("SushiBarDatabaseImplement.Models.SushiComponent", b => + { + b.HasOne("SushiBarDatabaseImplement.Models.Component", "Component") + .WithMany("SushiComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SushiBarDatabaseImplement.Models.Sushi", "Sushi") + .WithMany("Components") + .HasForeignKey("SushiId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Sushi"); + }); + + modelBuilder.Entity("SushiBarDatabaseImplement.Models.Client", b => + { + b.Navigation("Orders"); + }); + + modelBuilder.Entity("SushiBarDatabaseImplement.Models.Component", b => + { + b.Navigation("SushiComponents"); + }); + + modelBuilder.Entity("SushiBarDatabaseImplement.Models.Shop", b => + { + b.Navigation("Sushis"); + }); + + modelBuilder.Entity("SushiBarDatabaseImplement.Models.Sushi", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/SushiBar/SushiBarDatabaseImplement/Migrations/20240424121819_InitCreate.cs b/SushiBar/SushiBarDatabaseImplement/Migrations/20240424121819_InitCreate.cs new file mode 100644 index 0000000..30d0cab --- /dev/null +++ b/SushiBar/SushiBarDatabaseImplement/Migrations/20240424121819_InitCreate.cs @@ -0,0 +1,215 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SushiBarDatabaseImplement.Migrations +{ + /// + public partial class InitCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Clients", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ClientFIO = table.Column(type: "nvarchar(max)", nullable: false), + Email = table.Column(type: "nvarchar(max)", nullable: false), + Password = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Clients", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Components", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ComponentName = table.Column(type: "nvarchar(max)", nullable: false), + Cost = table.Column(type: "float", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Components", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Shops", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ShopName = table.Column(type: "nvarchar(max)", nullable: false), + Adress = table.Column(type: "nvarchar(max)", nullable: false), + OpeningDate = table.Column(type: "datetime2", nullable: false), + SushiMaxCount = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Shops", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Sushis", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + SushiName = table.Column(type: "nvarchar(max)", nullable: false), + Price = table.Column(type: "float", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Sushis", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "Orders", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ClientId = table.Column(type: "int", nullable: false), + SushiId = table.Column(type: "int", nullable: false), + Count = table.Column(type: "int", nullable: false), + Sum = table.Column(type: "float", nullable: false), + Status = table.Column(type: "int", nullable: false), + DateCreate = table.Column(type: "datetime2", nullable: false), + DateImplement = table.Column(type: "datetime2", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_Orders", x => x.Id); + table.ForeignKey( + name: "FK_Orders_Clients_ClientId", + column: x => x.ClientId, + principalTable: "Clients", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_Orders_Sushis_SushiId", + column: x => x.SushiId, + principalTable: "Sushis", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "ShopSushis", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + SushiId = table.Column(type: "int", nullable: false), + ShopId = table.Column(type: "int", nullable: false), + Count = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ShopSushis", x => x.Id); + table.ForeignKey( + name: "FK_ShopSushis_Shops_ShopId", + column: x => x.ShopId, + principalTable: "Shops", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ShopSushis_Sushis_SushiId", + column: x => x.SushiId, + principalTable: "Sushis", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "SushiComponents", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + SushiId = table.Column(type: "int", nullable: false), + ComponentId = table.Column(type: "int", nullable: false), + Count = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_SushiComponents", x => x.Id); + table.ForeignKey( + name: "FK_SushiComponents_Components_ComponentId", + column: x => x.ComponentId, + principalTable: "Components", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_SushiComponents_Sushis_SushiId", + column: x => x.SushiId, + principalTable: "Sushis", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_Orders_ClientId", + table: "Orders", + column: "ClientId"); + + migrationBuilder.CreateIndex( + name: "IX_Orders_SushiId", + table: "Orders", + column: "SushiId"); + + migrationBuilder.CreateIndex( + name: "IX_ShopSushis_ShopId", + table: "ShopSushis", + column: "ShopId"); + + migrationBuilder.CreateIndex( + name: "IX_ShopSushis_SushiId", + table: "ShopSushis", + column: "SushiId"); + + migrationBuilder.CreateIndex( + name: "IX_SushiComponents_ComponentId", + table: "SushiComponents", + column: "ComponentId"); + + migrationBuilder.CreateIndex( + name: "IX_SushiComponents_SushiId", + table: "SushiComponents", + column: "SushiId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "Orders"); + + migrationBuilder.DropTable( + name: "ShopSushis"); + + migrationBuilder.DropTable( + name: "SushiComponents"); + + migrationBuilder.DropTable( +<<<<<<<< HEAD:SushiBar/SushiBarDatabaseImplement/Migrations/20240420142132_InitialCreate.cs + name: "Clients"); +======== + name: "Shops"); +>>>>>>>> Lab_4_Hard:SushiBar/SushiBarDatabaseImplement/Migrations/20240424121819_InitCreate.cs + + migrationBuilder.DropTable( + name: "Components"); + + migrationBuilder.DropTable( + name: "Sushis"); + } + } +} diff --git a/SushiBar/SushiBarDatabaseImplement/Migrations/SushiBarDatabaseModelSnapshot.cs b/SushiBar/SushiBarDatabaseImplement/Migrations/SushiBarDatabaseModelSnapshot.cs index 43bf610..4f0ae5a 100644 --- a/SushiBar/SushiBarDatabaseImplement/Migrations/SushiBarDatabaseModelSnapshot.cs +++ b/SushiBar/SushiBarDatabaseImplement/Migrations/SushiBarDatabaseModelSnapshot.cs @@ -105,6 +105,59 @@ namespace SushiBarDatabaseImplement.Migrations b.ToTable("Orders"); }); + modelBuilder.Entity("SushiBarDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Adress") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("OpeningDate") + .HasColumnType("datetime2"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("SushiMaxCount") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("SushiBarDatabaseImplement.Models.ShopSushis", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.Property("SushiId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ShopId"); + + b.HasIndex("SushiId"); + + b.ToTable("ShopSushis"); + }); + modelBuilder.Entity("SushiBarDatabaseImplement.Models.Sushi", b => { b.Property("Id") @@ -170,6 +223,25 @@ namespace SushiBarDatabaseImplement.Migrations b.Navigation("Sushi"); }); + modelBuilder.Entity("SushiBarDatabaseImplement.Models.ShopSushis", b => + { + b.HasOne("SushiBarDatabaseImplement.Models.Shop", "Shop") + .WithMany("Sushis") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SushiBarDatabaseImplement.Models.Sushi", "Sushi") + .WithMany() + .HasForeignKey("SushiId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Shop"); + + b.Navigation("Sushi"); + }); + modelBuilder.Entity("SushiBarDatabaseImplement.Models.SushiComponent", b => { b.HasOne("SushiBarDatabaseImplement.Models.Component", "Component") @@ -199,6 +271,11 @@ namespace SushiBarDatabaseImplement.Migrations b.Navigation("SushiComponents"); }); + modelBuilder.Entity("SushiBarDatabaseImplement.Models.Shop", b => + { + b.Navigation("Sushis"); + }); + modelBuilder.Entity("SushiBarDatabaseImplement.Models.Sushi", b => { b.Navigation("Components"); diff --git a/SushiBar/SushiBarDatabaseImplement/Models/Shop.cs b/SushiBar/SushiBarDatabaseImplement/Models/Shop.cs new file mode 100644 index 0000000..8455db5 --- /dev/null +++ b/SushiBar/SushiBarDatabaseImplement/Models/Shop.cs @@ -0,0 +1,119 @@ +using SushiBarContracts.BindingModels; +using SushiBarContracts.ViewModels; +using SushiBarDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarDatabaseImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; set; } + public string ShopName { get; set; } = string.Empty; + + public string Adress { get; set; } = string.Empty; + + public DateTime OpeningDate { get; set; } + + public int SushiMaxCount { get; set; } + + private Dictionary? _shopSushis = null; + + public Dictionary ShopSushis + { + get + { + if (_shopSushis == null) + { + if (_shopSushis == null) + { + _shopSushis = Sushis + .ToDictionary(recSP => recSP.SushiId, recSP => (recSP.Sushi as ISushiModel, recSP.Count)); + } + return _shopSushis; + } + return _shopSushis; + } + } + + [ForeignKey("ShopId")] + public List Sushis { get; set; } = new(); + + public static Shop Create(SushiBarDatabase context, ShopBindingModel model) + { + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + OpeningDate = model.OpeningDate, + Sushis = model.ShopSushis.Select(x => new ShopSushis + { + Sushi = context.Sushis.First(y => y.Id == x.Key), + Count = x.Value.Item2 + }).ToList(), + SushiMaxCount = model.SushiMaxCount + }; + } + + public void Update(ShopBindingModel model) + { + ShopName = model.ShopName; + Adress = model.Adress; + OpeningDate = model.OpeningDate; + SushiMaxCount = model.SushiMaxCount; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + OpeningDate = OpeningDate, + ShopSushis = ShopSushis, + SushiMaxCount = SushiMaxCount + }; + + public void UpdateSushis(SushiBarDatabase context, ShopBindingModel model) + { + var ShopSushis = context.ShopSushis.Where(rec => rec.ShopId == model.Id).ToList(); + if (ShopSushis != null && ShopSushis.Count > 0) + { + context.ShopSushis.RemoveRange(ShopSushis.Where(rec => !model.ShopSushis.ContainsKey(rec.SushiId))); + context.SaveChanges(); + ShopSushis = context.ShopSushis.Where(rec => rec.ShopId == model.Id).ToList(); + foreach (var updateSushi in ShopSushis) + { + updateSushi.Count = model.ShopSushis[updateSushi.SushiId].Item2; + model.ShopSushis.Remove(updateSushi.SushiId); + } + context.SaveChanges(); + } + var shop = context.Shops.First(x => x.Id == Id); + foreach (var ar in model.ShopSushis) + { + context.ShopSushis.Add(new ShopSushis + { + Shop = shop, + Sushi = context.Sushis.First(x => x.Id == ar.Key), + Count = ar.Value.Item2 + }); + context.SaveChanges(); + } + _shopSushis = null; + } + + public void SushisDictionatyUpdate(SushiBarDatabase context) + { + UpdateSushis(context, new ShopBindingModel + { + Id = Id, + ShopSushis = ShopSushis, + }); + } + } +} diff --git a/SushiBar/SushiBarDatabaseImplement/Models/ShopSushis.cs b/SushiBar/SushiBarDatabaseImplement/Models/ShopSushis.cs new file mode 100644 index 0000000..1d54689 --- /dev/null +++ b/SushiBar/SushiBarDatabaseImplement/Models/ShopSushis.cs @@ -0,0 +1,28 @@ +using SushiBarDatabaseImplement.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarDatabaseImplement.Models +{ + public class ShopSushis + { + public int Id { get; set; } + + [Required] + public int SushiId { get; set; } + + [Required] + public int ShopId { get; set; } + + [Required] + public int Count { get; set; } + + public virtual Shop Shop { get; set; } = new(); + + public virtual Sushi Sushi { get; set; } = new(); + } +} diff --git a/SushiBar/SushiBarDatabaseImplement/SushiBarDatabaseImplement.csproj b/SushiBar/SushiBarDatabaseImplement/SushiBarDatabaseImplement.csproj index 5fcfde6..c018727 100644 --- a/SushiBar/SushiBarDatabaseImplement/SushiBarDatabaseImplement.csproj +++ b/SushiBar/SushiBarDatabaseImplement/SushiBarDatabaseImplement.csproj @@ -18,7 +18,7 @@ - + diff --git a/SushiBar/SushiBarDatabaseImplement/SushiBarDatatbase.cs b/SushiBar/SushiBarDatabaseImplement/SushiBarDatatbase.cs index b6b164e..e1d490f 100644 --- a/SushiBar/SushiBarDatabaseImplement/SushiBarDatatbase.cs +++ b/SushiBar/SushiBarDatabaseImplement/SushiBarDatatbase.cs @@ -22,6 +22,7 @@ namespace SushiBarDatabaseImplement public virtual DbSet Sushis { set; get; } public virtual DbSet SushiComponents { set; get; } public virtual DbSet Orders { set; get; } - public virtual DbSet Clients { set; get; } + public virtual DbSet Shops { get; set; } + public virtual DbSet ShopSushis { get; set; } } } diff --git a/SushiBar/SushiBarFileImplement/DataFileSingleton.cs b/SushiBar/SushiBarFileImplement/DataFileSingleton.cs index cec1f78..d949177 100644 --- a/SushiBar/SushiBarFileImplement/DataFileSingleton.cs +++ b/SushiBar/SushiBarFileImplement/DataFileSingleton.cs @@ -14,11 +14,11 @@ namespace SushiBarFileImplement private readonly string ComponentFileName = "Component.xml"; private readonly string OrderFileName = "Order.xml"; private readonly string SushiFileName = "Sushi.xml"; - private readonly string ClientFileName = "Client.xml"; + private readonly string ShopFileName = "Shop.xml"; public List Components { get; private set; } public List Orders { get; private set; } public List Sushis { get; private set; } - public List Clients { get; private set; } + public List Shops { get; private set; } public static DataFileSingleton GetInstance() { @@ -32,14 +32,14 @@ namespace SushiBarFileImplement public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement); public void SaveSushis() => SaveData(Sushis, SushiFileName, "Sushis", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); - public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); + public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement); private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Sushis = LoadData(SushiFileName, "Sushi", x => Sushi.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; - Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; + Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!; } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) diff --git a/SushiBar/SushiBarFileImplement/Implements/OrderStorage.cs b/SushiBar/SushiBarFileImplement/Implements/OrderStorage.cs index 748f870..a5d1561 100644 --- a/SushiBar/SushiBarFileImplement/Implements/OrderStorage.cs +++ b/SushiBar/SushiBarFileImplement/Implements/OrderStorage.cs @@ -24,21 +24,11 @@ namespace SushiBarFileImplement.Implements public List GetFilteredList(OrderSearchModel model) { - if (model.DateFrom.HasValue) + if (!model.DateFrom.HasValue || !model.DateFrom.HasValue || !model.DateTo.HasValue) { - return source.Orders.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) - .Select(x => GetViewModel(x)).ToList(); + return new(); } - if (model.ClientId.HasValue && !model.Id.HasValue) - { - return source.Orders.Where(x => x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList(); - } - - if (model.Id.HasValue) - { - return source.Orders.Where(x => x.Id.Equals(model.Id)).Select(x => GetViewModel(x)).ToList(); - } - return new(); + return source.Orders.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo).Select(x => AttachSushiName(x.GetViewModel)).ToList(); } public OrderViewModel? GetElement(OrderSearchModel model) @@ -100,23 +90,5 @@ namespace SushiBarFileImplement.Implements } return model; } - - private OrderViewModel GetViewModel(Order order) - { - var viewModel = order.GetViewModel; - - var sushi = source.Sushis.FirstOrDefault(x => x.Id == order.SushiId); - var client = source.Clients.FirstOrDefault(x => x.Id == order.ClientId); - - if (sushi != null) - { - viewModel.SushiName = sushi.SushiName; - } - if (client != null) - { - viewModel.ClientFIO = client.ClientFIO; - } - return viewModel; - } } } diff --git a/SushiBar/SushiBarFileImplement/Implements/ShopStorage.cs b/SushiBar/SushiBarFileImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..75281db --- /dev/null +++ b/SushiBar/SushiBarFileImplement/Implements/ShopStorage.cs @@ -0,0 +1,154 @@ +using SushiBarContracts.BindingModels; +using SushiBarContracts.SearchModels; +using SushiBarContracts.StoragesContracts; +using SushiBarContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SushiBarFileImplement.Models; + +namespace SushiBarFileImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataFileSingleton source; + + public ShopStorage() + { + source = DataFileSingleton.GetInstance(); + } + + public List GetFullList() + { + return source.Shops.Select(x => x.GetViewModel).ToList(); + } + + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName)) + { + return new(); + } + return source.Shops.Where(x => x.ShopName.Contains(model.ShopName)).Select(x => x.GetViewModel).ToList(); + } + + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) + { + return null; + } + return source.Shops.FirstOrDefault(x => + (!string.IsNullOrEmpty(model.ShopName) && x.ShopName == model.ShopName) || + (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = source.Shops.Count > 0 ? source.Shops.Max(x => x.Id) + 1 : 1; + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + source.Shops.Add(newShop); + source.SaveShops(); + return newShop.GetViewModel; + } + + public ShopViewModel? Update(ShopBindingModel model) + { + var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop == null) + { + return null; + } + shop.Update(model); + source.SaveShops(); + return shop.GetViewModel; + } + + public ShopViewModel? Delete(ShopBindingModel model) + { + var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop != null) + { + source.Shops.Remove(shop); + source.SaveShops(); + return shop.GetViewModel; + } + return null; + } + + public bool Sale(SupplySearchModel model) + { + if (model == null || !model.SushiId.HasValue || !model.Count.HasValue) + return false; + int remainingSpace = source.Shops.Select(x => x.Sushis.ContainsKey(model.SushiId.Value) ? x.Sushis[model.SushiId.Value] : 0).Sum(); + if (remainingSpace < model.Count) + { + return false; + } + var shops = source.Shops.Where(x => x.Sushis.ContainsKey(model.SushiId.Value)).OrderByDescending(x => x.Sushis[model.SushiId.Value]).ToList(); + foreach (var shop in shops) + { + int residue = model.Count.Value - shop.Sushis[model.SushiId.Value]; + if (residue > 0) + { + shop.Sushis.Remove(model.SushiId.Value); + shop.SushisUpdate(); + model.Count = residue; + } + else + { + if (residue == 0) + { + shop.Sushis.Remove(model.SushiId.Value); + } + else + { + shop.Sushis[model.SushiId.Value] = -residue; + } + shop.SushisUpdate(); + source.SaveShops(); + return true; + } + } + source.SaveShops(); + return false; + } + + public bool RestockingShops(SupplyBindingModel model) + { + if (model == null || source.Shops.Select(x => x.SushiMaxCount - x.ShopSushis.Select(y => y.Value.Item2).Sum()).Sum() < model.Count) + { + return false; + } + foreach (Shop shop in source.Shops) + { + int free_places = shop.SushiMaxCount - shop.ShopSushis.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.Sushis.ContainsKey(model.SushiId)) + { + shop.Sushis[model.SushiId] += free_places; + } + else + { + shop.Sushis.Add(model.SushiId, free_places); + } + shop.SushisUpdate(); + if (model.Count == 0) + { + source.SaveShops(); + return true; + } + } + return false; + } + } +} diff --git a/SushiBar/SushiBarFileImplement/Models/Shop.cs b/SushiBar/SushiBarFileImplement/Models/Shop.cs new file mode 100644 index 0000000..2b2f403 --- /dev/null +++ b/SushiBar/SushiBarFileImplement/Models/Shop.cs @@ -0,0 +1,112 @@ +using SushiBarDataModels.Models; +using SushiBarContracts.BindingModels; +using SushiBarContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; +using SushiBarFileImplement; + +namespace SushiBarFileImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + public string ShopName { get; private set; } = string.Empty; + public string Adress { get; private set; } = string.Empty; + public DateTime OpeningDate { get; private set; } + public Dictionary Sushis { get; private set; } = new(); + private Dictionary? _shopSushis = null; + + public Dictionary ShopSushis + { + get + { + if (_shopSushis == null) + { + var source = DataFileSingleton.GetInstance(); + _shopSushis = Sushis.ToDictionary(x => x.Key, y => ((source.Sushis.FirstOrDefault(z => z.Id == y.Key) as ISushiModel)!, y.Value)); + } + return _shopSushis; + } + } + + public int SushiMaxCount { get; private set; } + + public static Shop? Create(ShopBindingModel? model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + OpeningDate = model.OpeningDate, + Sushis = model.ShopSushis.ToDictionary(x => x.Key, x => x.Value.Item2), + SushiMaxCount = model.SushiMaxCount + }; + } + + public static Shop? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ShopName = element.Element("ShopName")!.Value, + Adress = element.Element("Adress")!.Value, + OpeningDate = Convert.ToDateTime(element.Element("OpeningDate")!.Value), + Sushis = element.Element("ShopSushis")!.Elements("ShopSushi")!.ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), + x => Convert.ToInt32(x.Element("Value")?.Value)), + SushiMaxCount = Convert.ToInt32(element.Element("SushiMaxCount")!.Value) + }; + } + + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Adress = model.Adress; + OpeningDate = model.OpeningDate; + SushiMaxCount = model.SushiMaxCount; + Sushis = model.ShopSushis.ToDictionary(x => x.Key, x => x.Value.Item2); + _shopSushis = null; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + OpeningDate = OpeningDate, + ShopSushis = ShopSushis, + SushiMaxCount = SushiMaxCount + }; + + public XElement GetXElement => new("Shop", + new XAttribute("Id", Id), + new XElement("ShopName", ShopName), + new XElement("Adress", Adress), + new XElement("OpeningDate", OpeningDate.ToString()), + new XElement("ShopSushis", Sushis.Select( + x => new XElement("ShopSushi", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray()), + new XElement("SushiMaxCount", SushiMaxCount.ToString()) + ); + + public void SushisUpdate() + { + _shopSushis = null; + } + } +} \ No newline at end of file diff --git a/SushiBar/SushiBarListImplement_/DataListSingleton.cs b/SushiBar/SushiBarListImplement_/DataListSingleton.cs index a5a7000..7893d08 100644 --- a/SushiBar/SushiBarListImplement_/DataListSingleton.cs +++ b/SushiBar/SushiBarListImplement_/DataListSingleton.cs @@ -13,13 +13,13 @@ namespace SushiBarListImplement public List Components { get; set; } public List Orders { get; set; } public List Sushis { get; set; } - public List Clients { get; set; } + public List Shops { get; set; } private DataListSingleton() { Components = new List(); Orders = new List(); Sushis = new List(); - Clients = new List(); + Shops = new List(); } public static DataListSingleton GetInstance() { diff --git a/SushiBar/SushiBarListImplement_/Implements/ShopStorage.cs b/SushiBar/SushiBarListImplement_/Implements/ShopStorage.cs new file mode 100644 index 0000000..c4212a6 --- /dev/null +++ b/SushiBar/SushiBarListImplement_/Implements/ShopStorage.cs @@ -0,0 +1,123 @@ +using SushiBarContracts.BindingModels; +using SushiBarContracts.SearchModels; +using SushiBarContracts.StoragesContracts; +using SushiBarContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SushiBarListImplement.Models; + +namespace SushiBarListImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataListSingleton _source; + + public ShopStorage() + { + _source = DataListSingleton.GetInstance(); + } + + public List GetFullList() + { + var result = new List(); + foreach (var shop in _source.Shops) + { + result.Add(shop.GetViewModel); + } + return result; + } + + public List GetFilteredList(ShopSearchModel model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.ShopName)) + { + return result; + } + foreach (var shop in _source.Shops) + { + if (shop.ShopName.Contains(model.ShopName)) + { + result.Add(shop.GetViewModel); + } + } + return result; + } + + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) + { + return null; + } + foreach (var shop in _source.Shops) + { + if ((!string.IsNullOrEmpty(model.ShopName) && shop.ShopName == model.ShopName) || + (model.Id.HasValue && shop.Id == model.Id)) + { + return shop.GetViewModel; + } + } + return null; + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = 1; + foreach (var shop in _source.Shops) + { + if (model.Id <= shop.Id) + { + model.Id = shop.Id + 1; + } + } + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + _source.Shops.Add(newShop); + return newShop.GetViewModel; + } + + public ShopViewModel? Update(ShopBindingModel model) + { + foreach (var shop in _source.Shops) + { + if (shop.Id == model.Id) + { + shop.Update(model); + return shop.GetViewModel; + } + } + return null; + } + + public ShopViewModel? Delete(ShopBindingModel model) + { + for (int i = 0; i < _source.Shops.Count; ++i) + { + if (_source.Shops[i].Id == model.Id) + { + var element = _source.Shops[i]; + _source.Shops.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } + + public bool Sale(SupplySearchModel model) + { + throw new NotImplementedException(); + } + + public bool RestockingShops(SupplyBindingModel model) + { + throw new NotImplementedException(); + } + } +} diff --git a/SushiBar/SushiBarListImplement_/Models/Shop.cs b/SushiBar/SushiBarListImplement_/Models/Shop.cs new file mode 100644 index 0000000..76c50f0 --- /dev/null +++ b/SushiBar/SushiBarListImplement_/Models/Shop.cs @@ -0,0 +1,59 @@ +using SushiBarContracts.BindingModels; +using SushiBarContracts.ViewModels; +using SushiBarDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SushiBarListImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + public string ShopName { get; private set; } = string.Empty; + public string Adress { get; private set; } = string.Empty; + public DateTime OpeningDate { get; private set; } + public Dictionary ShopSushis { get; private set; } = new(); + public int SushiMaxCount { get; private set; } + + public static Shop? Create(ShopBindingModel? model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Adress = model.Adress, + OpeningDate = model.OpeningDate, + SushiMaxCount = model.SushiMaxCount, + }; + } + + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Adress = model.Adress; + OpeningDate = model.OpeningDate; + SushiMaxCount = model.SushiMaxCount; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Adress = Adress, + OpeningDate = OpeningDate, + ShopSushis = ShopSushis, + SushiMaxCount = SushiMaxCount, + }; +} +} diff --git a/SushiBar/SushiBarView/FormCreateSupply.Designer.cs b/SushiBar/SushiBarView/FormCreateSupply.Designer.cs new file mode 100644 index 0000000..f71678a --- /dev/null +++ b/SushiBar/SushiBarView/FormCreateSupply.Designer.cs @@ -0,0 +1,143 @@ +namespace SushiBarView +{ + partial class FormCreateSupply + { + /// + /// 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.comboBoxShop = new System.Windows.Forms.ComboBox(); + this.labelShop = new System.Windows.Forms.Label(); + this.labelSushi = new System.Windows.Forms.Label(); + this.comboBoxSushi = new System.Windows.Forms.ComboBox(); + this.labelCount = new System.Windows.Forms.Label(); + this.textBoxCount = new System.Windows.Forms.TextBox(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.buttonSave = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // comboBoxShop + // + this.comboBoxShop.FormattingEnabled = true; + this.comboBoxShop.Location = new System.Drawing.Point(115, 12); + this.comboBoxShop.Name = "comboBoxShop"; + this.comboBoxShop.Size = new System.Drawing.Size(344, 28); + this.comboBoxShop.TabIndex = 0; + // + // labelShop + // + this.labelShop.AutoSize = true; + this.labelShop.Location = new System.Drawing.Point(12, 15); + this.labelShop.Name = "labelShop"; + this.labelShop.Size = new System.Drawing.Size(76, 20); + this.labelShop.TabIndex = 1; + this.labelShop.Text = "Магазин: "; + // + // labelSushi + // + this.labelSushi.AutoSize = true; + this.labelSushi.Location = new System.Drawing.Point(12, 49); + this.labelSushi.Name = "labelSushi"; + this.labelSushi.Size = new System.Drawing.Size(75, 20); + this.labelSushi.TabIndex = 2; + this.labelSushi.Text = "Изделие: "; + // + // comboBoxSushi + // + this.comboBoxSushi.FormattingEnabled = true; + this.comboBoxSushi.Location = new System.Drawing.Point(115, 46); + this.comboBoxSushi.Name = "comboBoxSushi"; + this.comboBoxSushi.Size = new System.Drawing.Size(344, 28); + this.comboBoxSushi.TabIndex = 3; + // + // labelCount + // + this.labelCount.AutoSize = true; + this.labelCount.Location = new System.Drawing.Point(12, 83); + this.labelCount.Name = "labelCount"; + this.labelCount.Size = new System.Drawing.Size(97, 20); + this.labelCount.TabIndex = 4; + this.labelCount.Text = "Количество: "; + // + // textBoxCount + // + this.textBoxCount.Location = new System.Drawing.Point(115, 80); + this.textBoxCount.Name = "textBoxCount"; + this.textBoxCount.Size = new System.Drawing.Size(344, 27); + this.textBoxCount.TabIndex = 5; + // + // buttonCancel + // + this.buttonCancel.Location = new System.Drawing.Point(300, 113); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(116, 39); + this.buttonCancel.TabIndex = 6; + this.buttonCancel.Text = "Отмена"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); + // + // buttonSave + // + this.buttonSave.Location = new System.Drawing.Point(168, 113); + this.buttonSave.Name = "buttonSave"; + this.buttonSave.Size = new System.Drawing.Size(116, 39); + this.buttonSave.TabIndex = 7; + this.buttonSave.Text = "Сохранить"; + this.buttonSave.UseVisualStyleBackColor = true; + this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click); + // + // FormCreateSupply + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(471, 164); + this.Controls.Add(this.buttonSave); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.textBoxCount); + this.Controls.Add(this.labelCount); + this.Controls.Add(this.comboBoxSushi); + this.Controls.Add(this.labelSushi); + this.Controls.Add(this.labelShop); + this.Controls.Add(this.comboBoxShop); + this.Name = "FormCreateSupply"; + this.Text = "Создание поставки"; + this.Load += new System.EventHandler(this.FormCreateSupply_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private ComboBox comboBoxShop; + private Label labelShop; + private Label labelSushi; + private ComboBox comboBoxSushi; + private Label labelCount; + private TextBox textBoxCount; + private Button buttonCancel; + private Button buttonSave; + } +} \ No newline at end of file diff --git a/SushiBar/SushiBarView/FormCreateSupply.cs b/SushiBar/SushiBarView/FormCreateSupply.cs new file mode 100644 index 0000000..7637142 --- /dev/null +++ b/SushiBar/SushiBarView/FormCreateSupply.cs @@ -0,0 +1,99 @@ +using Microsoft.Extensions.Logging; +using SushiBarContracts.BindingModels; +using SushiBarContracts.BusinessLogicsContracts; +using SushiBarContracts.ViewModels; +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using static System.Windows.Forms.VisualStyles.VisualStyleElement; + +namespace SushiBarView +{ + public partial class FormCreateSupply : Form + { + private readonly ILogger _logger; + private readonly ISushiLogic _logicP; + private readonly IShopLogic _logicS; + private List _shopList = new List(); + private List _sushiList = new List(); + + public FormCreateSupply(ILogger logger, ISushiLogic logicP, IShopLogic logicS) + { + InitializeComponent(); + _logger = logger; + _logicP = logicP; + _logicS = logicS; + } + + private void FormCreateSupply_Load(object sender, EventArgs e) + { + _shopList = _logicS.ReadList(null); + _sushiList = _logicP.ReadList(null); + if (_shopList != null) + { + comboBoxShop.DisplayMember = "ShopName"; + comboBoxShop.ValueMember = "Id"; + comboBoxShop.DataSource = _shopList; + comboBoxShop.SelectedItem = null; + _logger.LogInformation("Загрузка магазинов для поставок"); + } + if (_sushiList != null) + { + comboBoxSushi.DisplayMember = "SushiName"; + comboBoxSushi.ValueMember = "Id"; + comboBoxSushi.DataSource = _sushiList; + comboBoxSushi.SelectedItem = null; + _logger.LogInformation("Загрузка суши для поставок"); + } + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (comboBoxShop.SelectedValue == null) + { + MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxSushi.SelectedValue == null) + { + MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Создание поставки"); + try + { + var operationResult = _logicS.MakeSupply(new SupplyBindingModel + { + ShopId = Convert.ToInt32(comboBoxShop.SelectedValue), + SushiId = Convert.ToInt32(comboBoxSushi.SelectedValue), + Count = Convert.ToInt32(textBoxCount.Text) + }); + if (!operationResult) + { + throw new Exception("Ошибка при создании поставки. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка создания поставки"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/SushiBar/SushiBarView/FormCreateSupply.resx b/SushiBar/SushiBarView/FormCreateSupply.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SushiBar/SushiBarView/FormCreateSupply.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/SushiBar/SushiBarView/FormMain.Designer.cs b/SushiBar/SushiBarView/FormMain.Designer.cs index c215ef9..143c1e8 100644 --- a/SushiBar/SushiBarView/FormMain.Designer.cs +++ b/SushiBar/SushiBarView/FormMain.Designer.cs @@ -37,12 +37,21 @@ toolStripMenuItem1 = new ToolStripMenuItem(); componentsToolStripMenuItemToolStripMenuItem = new ToolStripMenuItem(); sushiToolStripMenuItemToolStripMenuItem = new ToolStripMenuItem(); + магазиныToolStripMenuItem = new ToolStripMenuItem(); отчётыToolStripMenuItem = new ToolStripMenuItem(); componentsToolStripMenuItem1 = new ToolStripMenuItem(); - componentSushiToolStripMenuItem1 = new ToolStripMenuItem(); + списокСушиToolStripMenuItem = new ToolStripMenuItem(); + сушиСИнгрToolStripMenuItem = new ToolStripMenuItem(); ordersToolStripMenuItem = new ToolStripMenuItem(); + заказыToolStripMenuItem = new ToolStripMenuItem(); + заказыПоГруппамToolStripMenuItem = new ToolStripMenuItem(); + магазиныToolStripMenuItem1 = new ToolStripMenuItem(); + информацияToolStripMenuItem = new ToolStripMenuItem(); + загруженностьToolStripMenuItem = new ToolStripMenuItem(); + операцииToolStripMenuItem = new ToolStripMenuItem(); + поставкаToolStripMenuItem = new ToolStripMenuItem(); + продажаToolStripMenuItem = new ToolStripMenuItem(); dataGridView = new DataGridView(); - ClientToolStripMenuItem = new ToolStripMenuItem(); menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); SuspendLayout(); @@ -99,7 +108,7 @@ // // menuStrip // - menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem1, отчётыToolStripMenuItem }); + menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem1, отчётыToolStripMenuItem, операцииToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; menuStrip.Size = new Size(922, 24); @@ -108,7 +117,7 @@ // // toolStripMenuItem1 // - toolStripMenuItem1.DropDownItems.AddRange(new ToolStripItem[] { componentsToolStripMenuItemToolStripMenuItem, sushiToolStripMenuItemToolStripMenuItem, ClientToolStripMenuItem }); + toolStripMenuItem1.DropDownItems.AddRange(new ToolStripItem[] { componentsToolStripMenuItemToolStripMenuItem, sushiToolStripMenuItemToolStripMenuItem, магазиныToolStripMenuItem }); toolStripMenuItem1.Name = "toolStripMenuItem1"; toolStripMenuItem1.Size = new Size(94, 20); toolStripMenuItem1.Text = "Справочники"; @@ -116,45 +125,117 @@ // componentsToolStripMenuItemToolStripMenuItem // componentsToolStripMenuItemToolStripMenuItem.Name = "componentsToolStripMenuItemToolStripMenuItem"; - componentsToolStripMenuItemToolStripMenuItem.Size = new Size(180, 22); + componentsToolStripMenuItemToolStripMenuItem.Size = new Size(145, 22); componentsToolStripMenuItemToolStripMenuItem.Text = "Компоненты"; componentsToolStripMenuItemToolStripMenuItem.Click += componentsToolStripMenuItem_Click; // // sushiToolStripMenuItemToolStripMenuItem // sushiToolStripMenuItemToolStripMenuItem.Name = "sushiToolStripMenuItemToolStripMenuItem"; - sushiToolStripMenuItemToolStripMenuItem.Size = new Size(180, 22); + sushiToolStripMenuItemToolStripMenuItem.Size = new Size(145, 22); sushiToolStripMenuItemToolStripMenuItem.Text = "Суши"; sushiToolStripMenuItemToolStripMenuItem.Click += sushiToolStripMenuItem_Click; // + // магазиныToolStripMenuItem + // + магазиныToolStripMenuItem.Name = "магазиныToolStripMenuItem"; + магазиныToolStripMenuItem.Size = new Size(145, 22); + магазиныToolStripMenuItem.Text = "Магазины"; + магазиныToolStripMenuItem.Click += shopsToolStripMenuItem_Click; + // // отчётыToolStripMenuItem // - отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { componentsToolStripMenuItem1, componentSushiToolStripMenuItem1, ordersToolStripMenuItem }); + отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { componentsToolStripMenuItem1, ordersToolStripMenuItem, магазиныToolStripMenuItem1 }); отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; отчётыToolStripMenuItem.Size = new Size(60, 20); отчётыToolStripMenuItem.Text = "Отчёты"; // // componentsToolStripMenuItem1 // + componentsToolStripMenuItem1.DropDownItems.AddRange(new ToolStripItem[] { списокСушиToolStripMenuItem, сушиСИнгрToolStripMenuItem }); componentsToolStripMenuItem1.Name = "componentsToolStripMenuItem1"; - componentsToolStripMenuItem1.Size = new Size(201, 22); + componentsToolStripMenuItem1.Size = new Size(180, 22); componentsToolStripMenuItem1.Text = "Суши"; componentsToolStripMenuItem1.Click += ComponentsToolStripMenuItem_Click; // - // componentSushiToolStripMenuItem1 + // списокСушиToolStripMenuItem // - componentSushiToolStripMenuItem1.Name = "componentSushiToolStripMenuItem1"; - componentSushiToolStripMenuItem1.Size = new Size(201, 22); - componentSushiToolStripMenuItem1.Text = "Суши с компонентами"; - componentSushiToolStripMenuItem1.Click += ComponentSushiToolStripMenuItem_Click; + списокСушиToolStripMenuItem.Name = "списокСушиToolStripMenuItem"; + списокСушиToolStripMenuItem.Size = new Size(201, 22); + списокСушиToolStripMenuItem.Text = "Список суши"; + списокСушиToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; + // + // сушиСИнгрToolStripMenuItem + // + сушиСИнгрToolStripMenuItem.Name = "сушиСИнгрToolStripMenuItem"; + сушиСИнгрToolStripMenuItem.Size = new Size(201, 22); + сушиСИнгрToolStripMenuItem.Text = "Суши с компонентами"; + сушиСИнгрToolStripMenuItem.Click += ComponentSushiToolStripMenuItem_Click; // // ordersToolStripMenuItem // + ordersToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { заказыToolStripMenuItem, заказыПоГруппамToolStripMenuItem }); ordersToolStripMenuItem.Name = "ordersToolStripMenuItem"; - ordersToolStripMenuItem.Size = new Size(201, 22); + ordersToolStripMenuItem.Size = new Size(180, 22); ordersToolStripMenuItem.Text = "Заказы"; ordersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; // + // заказыToolStripMenuItem + // + заказыToolStripMenuItem.Name = "заказыToolStripMenuItem"; + заказыToolStripMenuItem.Size = new Size(180, 22); + заказыToolStripMenuItem.Text = "Заказы"; + заказыToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; + // + // заказыПоГруппамToolStripMenuItem + // + заказыПоГруппамToolStripMenuItem.Name = "заказыПоГруппамToolStripMenuItem"; + заказыПоГруппамToolStripMenuItem.Size = new Size(180, 22); + заказыПоГруппамToolStripMenuItem.Text = "Заказы по группам"; + заказыПоГруппамToolStripMenuItem.Click += GroupOrdersToolStripMenuItem_Click; + // + // магазиныToolStripMenuItem1 + // + магазиныToolStripMenuItem1.DropDownItems.AddRange(new ToolStripItem[] { информацияToolStripMenuItem, загруженностьToolStripMenuItem }); + магазиныToolStripMenuItem1.Name = "магазиныToolStripMenuItem1"; + магазиныToolStripMenuItem1.Size = new Size(180, 22); + магазиныToolStripMenuItem1.Text = "Магазины"; + // + // информацияToolStripMenuItem + // + информацияToolStripMenuItem.Name = "информацияToolStripMenuItem"; + информацияToolStripMenuItem.Size = new Size(180, 22); + информацияToolStripMenuItem.Text = "Информация "; + информацияToolStripMenuItem.Click += InfoToolStripMenuItem_Click; + // + // загруженностьToolStripMenuItem + // + загруженностьToolStripMenuItem.Name = "загруженностьToolStripMenuItem"; + загруженностьToolStripMenuItem.Size = new Size(180, 22); + загруженностьToolStripMenuItem.Text = "Загруженность"; + загруженностьToolStripMenuItem.Click += BusyShopsToolStripMenuItem_Click; + // + // операцииToolStripMenuItem + // + операцииToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { поставкаToolStripMenuItem, продажаToolStripMenuItem }); + операцииToolStripMenuItem.Name = "операцииToolStripMenuItem"; + операцииToolStripMenuItem.Size = new Size(75, 20); + операцииToolStripMenuItem.Text = "Операции"; + // + // поставкаToolStripMenuItem + // + поставкаToolStripMenuItem.Name = "поставкаToolStripMenuItem"; + поставкаToolStripMenuItem.Size = new Size(125, 22); + поставкаToolStripMenuItem.Text = "Поставка"; + поставкаToolStripMenuItem.Click += transactionToolStripMenuItem_Click; + // + // продажаToolStripMenuItem + // + продажаToolStripMenuItem.Name = "продажаToolStripMenuItem"; + продажаToolStripMenuItem.Size = new Size(125, 22); + продажаToolStripMenuItem.Text = "Продажа"; + продажаToolStripMenuItem.Click += SellToolStripMenuItem_Click; + // // dataGridView // dataGridView.BackgroundColor = Color.White; @@ -165,13 +246,6 @@ dataGridView.Size = new Size(647, 344); dataGridView.TabIndex = 6; // - // ClientToolStripMenuItem - // - ClientToolStripMenuItem.Name = "ClientToolStripMenuItem"; - ClientToolStripMenuItem.Size = new Size(180, 22); - ClientToolStripMenuItem.Text = "Клиенты"; - ClientToolStripMenuItem.Click += ClientToolStripMenuItem_Click; - // // FormMain // AutoScaleDimensions = new SizeF(7F, 15F); @@ -209,8 +283,17 @@ private DataGridView dataGridView; private ToolStripMenuItem отчётыToolStripMenuItem; private ToolStripMenuItem componentsToolStripMenuItem1; - private ToolStripMenuItem componentSushiToolStripMenuItem1; private ToolStripMenuItem ordersToolStripMenuItem; - private ToolStripMenuItem ClientToolStripMenuItem; + private ToolStripMenuItem магазиныToolStripMenuItem; + private ToolStripMenuItem списокСушиToolStripMenuItem; + private ToolStripMenuItem сушиСИнгрToolStripMenuItem; + private ToolStripMenuItem заказыToolStripMenuItem; + private ToolStripMenuItem заказыПоГруппамToolStripMenuItem; + private ToolStripMenuItem магазиныToolStripMenuItem1; + private ToolStripMenuItem информацияToolStripMenuItem; + private ToolStripMenuItem загруженностьToolStripMenuItem; + private ToolStripMenuItem операцииToolStripMenuItem; + private ToolStripMenuItem поставкаToolStripMenuItem; + private ToolStripMenuItem продажаToolStripMenuItem; } } \ No newline at end of file diff --git a/SushiBar/SushiBarView/FormMain.cs b/SushiBar/SushiBarView/FormMain.cs index 936bcab..31f020c 100644 --- a/SushiBar/SushiBarView/FormMain.cs +++ b/SushiBar/SushiBarView/FormMain.cs @@ -57,8 +57,7 @@ namespace SushiBarView { dataGridView.DataSource = list; dataGridView.Columns["SushiId"].Visible = false; - dataGridView.Columns["ClientId"].Visible = false; - + } _logger.LogInformation("Загрузка заказов"); } @@ -92,7 +91,7 @@ namespace SushiBarView int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); - try + try { var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel @@ -133,8 +132,8 @@ namespace SushiBarView catch (Exception ex) { _logger.LogError(ex, "Ошибка отметки о готовности заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, +MessageBoxIcon.Error); } } } @@ -201,10 +200,56 @@ namespace SushiBarView } } - private void ClientToolStripMenuItem_Click(object sender, EventArgs e) + private void shopsToolStripMenuItem_Click(object sender, EventArgs e) { - var service = Program.ServiceProvider?.GetService(typeof(FormClients)); - if (service is FormClients form) + var service = Program.ServiceProvider?.GetService(typeof(FormShops)); + if (service is FormShops form) + { + form.ShowDialog(); + } + } + + private void transactionToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateSupply)); + if (service is FormCreateSupply form) + { + form.ShowDialog(); + } + } + + private void SellToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSellSushi)); + if (service is FormSellSushi form) + { + form.ShowDialog(); + } + } + + private void InfoToolStripMenuItem_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 BusyShopsToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportShop)); + if (service is FormReportShop form) + { + form.ShowDialog(); + } + } + + private void GroupOrdersToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportGroupedOrders)); + if (service is FormReportGroupedOrders form) { form.ShowDialog(); } diff --git a/SushiBar/SushiBarView/FormReportGroupedOrders.Designer.cs b/SushiBar/SushiBarView/FormReportGroupedOrders.Designer.cs new file mode 100644 index 0000000..e761a18 --- /dev/null +++ b/SushiBar/SushiBarView/FormReportGroupedOrders.Designer.cs @@ -0,0 +1,86 @@ +namespace SushiBarView +{ + 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/SushiBar/SushiBarView/FormReportGroupedOrders.cs b/SushiBar/SushiBarView/FormReportGroupedOrders.cs new file mode 100644 index 0000000..0ceb432 --- /dev/null +++ b/SushiBar/SushiBarView/FormReportGroupedOrders.cs @@ -0,0 +1,80 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Reporting.WinForms; +using SushiBarContracts.BindingModels; +using SushiBarContracts.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 SushiBarView +{ + 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("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/SushiBar/SushiBarView/FormReportGroupedOrders.resx b/SushiBar/SushiBarView/FormReportGroupedOrders.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SushiBar/SushiBarView/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/SushiBar/SushiBarView/FormReportShop.Designer.cs b/SushiBar/SushiBarView/FormReportShop.Designer.cs new file mode 100644 index 0000000..405a457 --- /dev/null +++ b/SushiBar/SushiBarView/FormReportShop.Designer.cs @@ -0,0 +1,116 @@ +namespace SushiBarView +{ + 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.ColumnSushi = 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.ColumnSushi, + 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; + // + // ColumnSushi + // + this.ColumnSushi.FillWeight = 140F; + this.ColumnSushi.HeaderText = "Пицца"; + this.ColumnSushi.MinimumWidth = 6; + this.ColumnSushi.Name = "ColumnSushi"; + this.ColumnSushi.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 ColumnSushi; + private DataGridViewTextBoxColumn ColumnCount; + } +} \ No newline at end of file diff --git a/SushiBar/SushiBarView/FormReportShop.cs b/SushiBar/SushiBarView/FormReportShop.cs new file mode 100644 index 0000000..0fb09a2 --- /dev/null +++ b/SushiBar/SushiBarView/FormReportShop.cs @@ -0,0 +1,78 @@ +using Microsoft.Extensions.Logging; +using SushiBarContracts.BindingModels; +using SushiBarContracts.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 SushiBarView +{ + 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.Sushis) + { + 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/SushiBar/SushiBarView/FormReportShop.resx b/SushiBar/SushiBarView/FormReportShop.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SushiBar/SushiBarView/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/SushiBar/SushiBarView/FormSellSushi.Designer.cs b/SushiBar/SushiBarView/FormSellSushi.Designer.cs new file mode 100644 index 0000000..7751a9c --- /dev/null +++ b/SushiBar/SushiBarView/FormSellSushi.Designer.cs @@ -0,0 +1,120 @@ +namespace SushiBarView +{ + partial class FormSellSushi + { + /// + /// 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.labelSushi = new System.Windows.Forms.Label(); + this.comboBoxSushi = new System.Windows.Forms.ComboBox(); + this.labelCount = new System.Windows.Forms.Label(); + this.textBoxCount = new System.Windows.Forms.TextBox(); + this.buttonSell = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // labelSushi + // + this.labelSushi.AutoSize = true; + this.labelSushi.Location = new System.Drawing.Point(12, 14); + this.labelSushi.Name = "labelSushi"; + this.labelSushi.Size = new System.Drawing.Size(75, 20); + this.labelSushi.TabIndex = 0; + this.labelSushi.Text = "Суши: "; + // + // comboBoxSushi + // + this.comboBoxSushi.FormattingEnabled = true; + this.comboBoxSushi.Location = new System.Drawing.Point(115, 11); + this.comboBoxSushi.Name = "comboBoxSushi"; + this.comboBoxSushi.Size = new System.Drawing.Size(239, 28); + this.comboBoxSushi.TabIndex = 1; + // + // labelCount + // + this.labelCount.AutoSize = true; + this.labelCount.Location = new System.Drawing.Point(12, 55); + this.labelCount.Name = "labelCount"; + this.labelCount.Size = new System.Drawing.Size(97, 20); + this.labelCount.TabIndex = 2; + this.labelCount.Text = "Количество: "; + // + // textBoxCount + // + this.textBoxCount.Location = new System.Drawing.Point(115, 52); + this.textBoxCount.Name = "textBoxCount"; + this.textBoxCount.Size = new System.Drawing.Size(239, 27); + this.textBoxCount.TabIndex = 3; + // + // buttonSell + // + this.buttonSell.Location = new System.Drawing.Point(128, 99); + this.buttonSell.Name = "buttonSell"; + this.buttonSell.Size = new System.Drawing.Size(94, 29); + this.buttonSell.TabIndex = 4; + this.buttonSell.Text = "Продать"; + this.buttonSell.UseVisualStyleBackColor = true; + this.buttonSell.Click += new System.EventHandler(this.ButtonSell_Click); + // + // buttonCancel + // + this.buttonCancel.Location = new System.Drawing.Point(242, 99); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(94, 29); + this.buttonCancel.TabIndex = 5; + this.buttonCancel.Text = "Отмена"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); + // + // FormSellSushi + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(366, 140); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonSell); + this.Controls.Add(this.textBoxCount); + this.Controls.Add(this.labelCount); + this.Controls.Add(this.comboBoxSushi); + this.Controls.Add(this.labelSushi); + this.Name = "FormSellSushi"; + this.Text = "Продажа суши"; + this.Load += new System.EventHandler(this.FormSellingSushi_Load); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private Label labelSushi; + private ComboBox comboBoxSushi; + private Label labelCount; + private TextBox textBoxCount; + private Button buttonSell; + private Button buttonCancel; + } +} \ No newline at end of file diff --git a/SushiBar/SushiBarView/FormSellSushi.cs b/SushiBar/SushiBarView/FormSellSushi.cs new file mode 100644 index 0000000..ab448cf --- /dev/null +++ b/SushiBar/SushiBarView/FormSellSushi.cs @@ -0,0 +1,88 @@ +using Microsoft.Extensions.Logging; +using SushiBarContracts.BusinessLogicsContracts; +using SushiBarContracts.SearchModels; +using SushiBarContracts.StoragesContracts; +using SushiBarContracts.ViewModels; +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 SushiBarView +{ + public partial class FormSellSushi : Form + { + private readonly ILogger _logger; + private readonly ISushiLogic _logicP; + private readonly IShopLogic _logicS; + private List _sushiList = new List(); + + public FormSellSushi(ILogger logger, ISushiLogic logicP, IShopLogic logicS) + { + InitializeComponent(); + _logger = logger; + _logicP = logicP; + _logicS = logicS; + } + + private void FormSellingSushi_Load(object sender, EventArgs e) + { + _sushiList = _logicP.ReadList(null); + if (_sushiList != null) + { + comboBoxSushi.DisplayMember = "SushiName"; + comboBoxSushi.ValueMember = "Id"; + comboBoxSushi.DataSource = _sushiList; + comboBoxSushi.SelectedItem = null; + _logger.LogInformation("Загрузка суши для продажи"); + } + } + + private void ButtonSell_Click(object sender, EventArgs e) + { + if (comboBoxSushi.SelectedValue == null) + { + MessageBox.Show("Выберите суши", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Создание покупки"); + try + { + bool resout = _logicS.Sale(new SupplySearchModel + { + SushiId = Convert.ToInt32(comboBoxSushi.SelectedValue), + Count = Convert.ToInt32(textBoxCount.Text) + }); + if (resout) + { + _logger.LogInformation("Проверка пройдена, продажа проведена"); + MessageBox.Show("Продажа проведена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + else + { + _logger.LogInformation("Проверка не пройдена"); + MessageBox.Show("Продажа не может быть создана.", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Warning); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка создания покупки"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} \ No newline at end of file diff --git a/SushiBar/SushiBarView/FormSellSushi.resx b/SushiBar/SushiBarView/FormSellSushi.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SushiBar/SushiBarView/FormSellSushi.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/SushiBar/SushiBarView/FormShop.Designer.cs b/SushiBar/SushiBarView/FormShop.Designer.cs new file mode 100644 index 0000000..04d34df --- /dev/null +++ b/SushiBar/SushiBarView/FormShop.Designer.cs @@ -0,0 +1,222 @@ +namespace SushiBarView +{ + partial class FormShop + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.labelName = new System.Windows.Forms.Label(); + this.textBoxName = new System.Windows.Forms.TextBox(); + this.textBoxAdress = new System.Windows.Forms.TextBox(); + this.labelAdress = new System.Windows.Forms.Label(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.buttonSave = new System.Windows.Forms.Button(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + this.id = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.SushiName = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.Count = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.label1 = new System.Windows.Forms.Label(); + this.dateTimeOpen = new System.Windows.Forms.DateTimePicker(); + this.label2 = new System.Windows.Forms.Label(); + this.numericUpSushiMaxCount = new System.Windows.Forms.NumericUpDown(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpSushiMaxCount)).BeginInit(); + this.SuspendLayout(); + // + // labelName + // + this.labelName.AutoSize = true; + this.labelName.Location = new System.Drawing.Point(11, 15); + this.labelName.Name = "labelName"; + this.labelName.Size = new System.Drawing.Size(84, 20); + this.labelName.TabIndex = 0; + this.labelName.Text = "Название: "; + // + // textBoxName + // + this.textBoxName.Location = new System.Drawing.Point(102, 12); + this.textBoxName.Name = "textBoxName"; + this.textBoxName.Size = new System.Drawing.Size(276, 27); + this.textBoxName.TabIndex = 1; + // + // textBoxAdress + // + this.textBoxAdress.Location = new System.Drawing.Point(102, 59); + this.textBoxAdress.Name = "textBoxAdress"; + this.textBoxAdress.Size = new System.Drawing.Size(427, 27); + this.textBoxAdress.TabIndex = 3; + // + // labelAdress + // + this.labelAdress.AutoSize = true; + this.labelAdress.Location = new System.Drawing.Point(11, 61); + this.labelAdress.Name = "labelAdress"; + this.labelAdress.Size = new System.Drawing.Size(58, 20); + this.labelAdress.TabIndex = 2; + this.labelAdress.Text = "Адрес: "; + // + // buttonCancel + // + this.buttonCancel.Location = new System.Drawing.Point(451, 457); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(130, 44); + this.buttonCancel.TabIndex = 5; + this.buttonCancel.Text = "Отмена"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); + // + // buttonSave + // + this.buttonSave.Location = new System.Drawing.Point(315, 457); + this.buttonSave.Name = "buttonSave"; + this.buttonSave.Size = new System.Drawing.Size(130, 44); + this.buttonSave.TabIndex = 6; + this.buttonSave.Text = "Сохранить"; + this.buttonSave.UseVisualStyleBackColor = true; + this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click); + // + // dataGridView + // + this.dataGridView.AllowUserToAddRows = false; + this.dataGridView.AllowUserToDeleteRows = false; + 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.id, + this.SushiName, + this.Count}); + this.dataGridView.Location = new System.Drawing.Point(12, 185); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.ReadOnly = true; + this.dataGridView.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None; + this.dataGridView.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(569, 266); + this.dataGridView.TabIndex = 7; + // + // id + // + this.id.HeaderText = "id"; + this.id.MinimumWidth = 6; + this.id.Name = "id"; + this.id.ReadOnly = true; + this.id.Visible = false; + // + // SushiName + // + this.SushiName.HeaderText = "Суши"; + this.SushiName.MinimumWidth = 6; + this.SushiName.Name = "SushiName"; + this.SushiName.ReadOnly = true; + // + // Count + // + this.Count.HeaderText = "Количество"; + this.Count.MinimumWidth = 6; + this.Count.Name = "Count"; + this.Count.ReadOnly = true; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(12, 103); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(110, 20); + this.label1.TabIndex = 8; + this.label1.Text = "Дата открытия"; + // + // dateTimeOpen + // + this.dateTimeOpen.Location = new System.Drawing.Point(128, 103); + this.dateTimeOpen.Name = "dateTimeOpen"; + this.dateTimeOpen.Size = new System.Drawing.Size(401, 27); + this.dateTimeOpen.TabIndex = 9; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(12, 148); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(100, 20); + this.label2.TabIndex = 10; + this.label2.Text = "Вместимость"; + // + // numericUpSushiMaxCount + // + this.numericUpSushiMaxCount.Location = new System.Drawing.Point(128, 146); + this.numericUpSushiMaxCount.Maximum = new decimal(new int[] { + 10000, + 0, + 0, + 0}); + this.numericUpSushiMaxCount.Name = "numericUpSushiMaxCount"; + this.numericUpSushiMaxCount.Size = new System.Drawing.Size(401, 27); + this.numericUpSushiMaxCount.TabIndex = 11; + // + // FormShop + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(593, 513); + this.Controls.Add(this.numericUpSushiMaxCount); + this.Controls.Add(this.label2); + this.Controls.Add(this.dateTimeOpen); + this.Controls.Add(this.label1); + this.Controls.Add(this.dataGridView); + this.Controls.Add(this.buttonSave); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.textBoxAdress); + this.Controls.Add(this.labelAdress); + this.Controls.Add(this.textBoxName); + this.Controls.Add(this.labelName); + this.Name = "FormShop"; + this.Text = "Магазин"; + this.Load += new System.EventHandler(this.FormShop_Load); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpSushiMaxCount)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private Label labelName; + private TextBox textBoxName; + private TextBox textBoxAdress; + private Label labelAdress; + private Button buttonCancel; + private Button buttonSave; + private DataGridView dataGridView; + private DataGridViewTextBoxColumn id; + private DataGridViewTextBoxColumn SushiName; + private DataGridViewTextBoxColumn Count; + private Label label1; + private DateTimePicker dateTimeOpen; + private Label label2; + private NumericUpDown numericUpSushiMaxCount; + } +} \ No newline at end of file diff --git a/SushiBar/SushiBarView/FormShop.cs b/SushiBar/SushiBarView/FormShop.cs new file mode 100644 index 0000000..bb46390 --- /dev/null +++ b/SushiBar/SushiBarView/FormShop.cs @@ -0,0 +1,127 @@ +using SushiBarDataModels.Models; +using Microsoft.Extensions.Logging; +using SushiBarContracts.BindingModels; +using SushiBarContracts.BusinessLogicsContracts; +using SushiBarContracts.SearchModels; +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 SushiBarView +{ + public partial class FormShop : Form + { + private readonly ILogger _logger; + private readonly IShopLogic _logic; + private int? _id; + public int Id { set { _id = value; } } + private Dictionary _ShopSushis; + private DateTime? _openingDate = null; + public FormShop(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + _ShopSushis = new Dictionary(); + } + private void FormShop_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Загрузка магазина"); + try + { + var view = _logic.ReadElement(new ShopSearchModel + { + Id = _id.Value + }); + if (view != null) + { + textBoxName.Text = view.ShopName; + textBoxAdress.Text = view.Adress; + dateTimeOpen.Value = view.OpeningDate; + numericUpSushiMaxCount.Value = view.SushiMaxCount; + _ShopSushis = view.ShopSushis ?? new Dictionary(); + LoadData(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void LoadData() + { + _logger.LogInformation("Загрузка изделий в магазине"); + try + { + if (_ShopSushis != null) + { + dataGridView.Rows.Clear(); + foreach (var sr in _ShopSushis) + { + dataGridView.Rows.Add(new object[] { sr.Key, sr.Value.Item1.SushiName, sr.Value.Item2 }); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки изделий магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxAdress.Text)) + { + MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение магазина"); + try + { + var model = new ShopBindingModel + { + Id = _id ?? 0, + ShopName = textBoxName.Text, + Adress = textBoxAdress.Text, + OpeningDate = dateTimeOpen.Value, + SushiMaxCount = (int)numericUpSushiMaxCount.Value + }; + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/SushiBar/SushiBarView/FormShop.resx b/SushiBar/SushiBarView/FormShop.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SushiBar/SushiBarView/FormShop.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SushiBar/SushiBarView/FormShops.Designer.cs b/SushiBar/SushiBarView/FormShops.Designer.cs new file mode 100644 index 0000000..b54a130 --- /dev/null +++ b/SushiBar/SushiBarView/FormShops.Designer.cs @@ -0,0 +1,130 @@ +namespace SushiBarView +{ + partial class FormShops + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.ToolsPanel = new System.Windows.Forms.Panel(); + this.buttonRef = new System.Windows.Forms.Button(); + this.buttonDel = new System.Windows.Forms.Button(); + this.buttonUpd = new System.Windows.Forms.Button(); + this.buttonAdd = new System.Windows.Forms.Button(); + this.dataGridView = new System.Windows.Forms.DataGridView(); + this.ToolsPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); + this.SuspendLayout(); + // + // ToolsPanel + // + this.ToolsPanel.Controls.Add(this.buttonRef); + this.ToolsPanel.Controls.Add(this.buttonDel); + this.ToolsPanel.Controls.Add(this.buttonUpd); + this.ToolsPanel.Controls.Add(this.buttonAdd); + this.ToolsPanel.Location = new System.Drawing.Point(608, 12); + this.ToolsPanel.Name = "ToolsPanel"; + this.ToolsPanel.Size = new System.Drawing.Size(180, 426); + this.ToolsPanel.TabIndex = 3; + // + // buttonRef + // + this.buttonRef.Location = new System.Drawing.Point(31, 206); + this.buttonRef.Name = "buttonRef"; + this.buttonRef.Size = new System.Drawing.Size(126, 36); + this.buttonRef.TabIndex = 3; + this.buttonRef.Text = "Обновить"; + this.buttonRef.UseVisualStyleBackColor = true; + this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click); + // + // buttonDel + // + this.buttonDel.Location = new System.Drawing.Point(31, 142); + this.buttonDel.Name = "buttonDel"; + this.buttonDel.Size = new System.Drawing.Size(126, 36); + this.buttonDel.TabIndex = 2; + this.buttonDel.Text = "Удалить"; + this.buttonDel.UseVisualStyleBackColor = true; + this.buttonDel.Click += new System.EventHandler(this.ButtonDel_Click); + // + // buttonUpd + // + this.buttonUpd.Location = new System.Drawing.Point(31, 76); + this.buttonUpd.Name = "buttonUpd"; + this.buttonUpd.Size = new System.Drawing.Size(126, 36); + this.buttonUpd.TabIndex = 1; + this.buttonUpd.Text = "Изменить"; + this.buttonUpd.UseVisualStyleBackColor = true; + this.buttonUpd.Click += new System.EventHandler(this.ButtonUpd_Click); + // + // buttonAdd + // + this.buttonAdd.Location = new System.Drawing.Point(31, 16); + this.buttonAdd.Name = "buttonAdd"; + this.buttonAdd.Size = new System.Drawing.Size(126, 36); + this.buttonAdd.TabIndex = 0; + this.buttonAdd.Text = "Добавить"; + this.buttonAdd.UseVisualStyleBackColor = true; + this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click); + // + // dataGridView + // + this.dataGridView.AllowUserToAddRows = false; + this.dataGridView.AllowUserToDeleteRows = false; + this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView.Location = new System.Drawing.Point(12, 12); + this.dataGridView.Name = "dataGridView"; + this.dataGridView.ReadOnly = true; + this.dataGridView.RowHeadersWidth = 51; + this.dataGridView.RowTemplate.Height = 29; + this.dataGridView.Size = new System.Drawing.Size(590, 426); + this.dataGridView.TabIndex = 2; + // + // FormShops + // + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Controls.Add(this.ToolsPanel); + this.Controls.Add(this.dataGridView); + this.Name = "FormShops"; + this.Text = "Магазины"; + this.Load += new System.EventHandler(this.FormShops_Load); + this.ToolsPanel.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private Panel ToolsPanel; + private Button buttonRef; + private Button buttonDel; + private Button buttonUpd; + private Button buttonAdd; + private DataGridView dataGridView; + } +} \ No newline at end of file diff --git a/SushiBar/SushiBarView/FormShops.cs b/SushiBar/SushiBarView/FormShops.cs new file mode 100644 index 0000000..a9fce63 --- /dev/null +++ b/SushiBar/SushiBarView/FormShops.cs @@ -0,0 +1,117 @@ +using Microsoft.Extensions.Logging; +using SushiBarContracts.ViewModels; +using SushiBarContracts.BindingModels; +using SushiBarContracts.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 SushiBarView +{ + public partial class FormShops : Form + { + private readonly ILogger _logger; + private readonly IShopLogic _logic; + + public FormShops(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormShops_Load(object sender, EventArgs e) + { + LoadData(); + } + + private void LoadData() + { + try + { + var list = _logic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["Id"].Visible = false; + dataGridView.Columns["ShopSushis"].Visible = false; + dataGridView.Columns["ShopName"].AutoSizeMode = + DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка магазинов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки магазинов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + if (service is FormShop form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + private void ButtonUpd_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + if (service is FormShop form) + { + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + private void ButtonDel_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление магазина"); + try + { + if (!_logic.Delete(new ShopBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/SushiBar/SushiBarView/FormShops.resx b/SushiBar/SushiBarView/FormShops.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/SushiBar/SushiBarView/FormShops.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/SushiBar/SushiBarView/Program.cs b/SushiBar/SushiBarView/Program.cs index c2864f9..6417726 100644 --- a/SushiBar/SushiBarView/Program.cs +++ b/SushiBar/SushiBarView/Program.cs @@ -9,11 +9,9 @@ using SushiBarView; using NLog.Extensions.Logging; using SushiBarBusinessLogic.OfficePackage.Implements; using SushiBarBusinessLogic.OfficePackage; -using SushiBarBusinessLogic; using SushiBarView.Reports; -using SushiBar.StoragesContracts; -using Microsoft.EntityFrameworkCore.Design; -using SushiBar.BusinessLogicsContracts; +using NLog.Extensions.Logging; +using SushiBarView; namespace SushiBarView { @@ -43,13 +41,10 @@ namespace SushiBarView services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); - + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); - services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -60,14 +55,23 @@ namespace SushiBarView 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(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/SushiBar/SushiBarView/ReportGroupedOrders.rdlc b/SushiBar/SushiBarView/ReportGroupedOrders.rdlc new file mode 100644 index 0000000..2ef2b88 --- /dev/null +++ b/SushiBar/SushiBarView/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 +