diff --git a/IceCreamShop/IceCreamShopBusinessLogic/BusinessLogics/OrderLogic.cs b/IceCreamShop/IceCreamShopBusinessLogic/BusinessLogics/OrderLogic.cs index 385ae5a..9d23e78 100644 --- a/IceCreamShop/IceCreamShopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/IceCreamShop/IceCreamShopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -4,6 +4,7 @@ using IceCreamShopContracts.SearchModels; using IceCreamShopContracts.StoragesContracts; using IceCreamShopContracts.ViewModels; using IceCreamShopDataModels.Enums; +using IceCreamShopDataModels.Models; using Microsoft.Extensions.Logging; namespace IceCreamShopBusinessLogic.BusinessLogics @@ -14,10 +15,20 @@ namespace IceCreamShopBusinessLogic.BusinessLogics private readonly IOrderStorage _orderStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + private readonly IIceCreamStorage _iceCreamStorage; + + private readonly IShopStorage _shopStorage; + + private readonly IShopLogic _shopLogic; + + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IIceCreamStorage iceCreamStorage, + IShopStorage shopStorage, IShopLogic shopLogic) { _logger = logger; _orderStorage = orderStorage; + _iceCreamStorage = iceCreamStorage; + _shopStorage = shopStorage; + _shopLogic = shopLogic; } public bool CreateOrder(OrderBindingModel model) @@ -110,12 +121,28 @@ namespace IceCreamShopBusinessLogic.BusinessLogics newStatus, order.Status); return false; } + if (newStatus == OrderStatus.Выдан) + { + var iceCream = _iceCreamStorage.GetElement(new IceCreamSearchModel() { Id = order.IceCreamId }); + if (iceCream == null) + { + _logger.LogWarning("Change status operation failed. Ice cream not found"); + return false; + } + if (!DeliverIceCreams(iceCream, order.Count)) + { + _logger.LogWarning("Change status operation failed. Ice creams delivery operation failed"); + return false; + } + } model.Status = newStatus; if (model.Status == OrderStatus.Готов) { model.DateImplement = DateTime.Now; } else + } + else { model.DateImplement = order.DateImplement; } @@ -126,5 +153,65 @@ namespace IceCreamShopBusinessLogic.BusinessLogics } return true; } + + private bool DeliverIceCreams(IIceCreamModel iceCream, int count) + { + if (count <= 0) + { + _logger.LogWarning("Ice creams delivery operation failed. Ice cream count <= 0"); + return false; + } + + var shopList = _shopStorage.GetFullList(); + int shopsCapacity = shopList.Sum(x => x.IceCreamsMaximum); + int currentIceCreams = shopList.Select(x => x.ShopIceCreams.Sum(y => y.Value.Item2)).Sum(); + int freePlaces = shopsCapacity - currentIceCreams; + + if (freePlaces < count) + { + _logger.LogWarning("Ice creams delivery operation failed. No space for new ice creams"); + return false; + } + + foreach (var shop in shopList) + { + freePlaces = shop.IceCreamsMaximum - shop.ShopIceCreams.Sum(x => x.Value.Item2); + if (freePlaces == 0) + { + continue; + } + if (freePlaces >= count) + { + if (_shopLogic.MakeShipment(new() { Id = shop.Id }, iceCream, count)) + { + count = 0; + } + else + { + _logger.LogWarning("Ice creams delivery operation failed"); + return false; + } + } + else + { + if (_shopLogic.MakeShipment(new() { Id = shop.Id }, iceCream, freePlaces)) + { + count -= freePlaces; + } + else + { + _logger.LogWarning("Ice creams delivery operation failed"); + return false; + } + } + if (count == 0) + { + return true; + } + } + return false; + } } + + } diff --git a/IceCreamShop/IceCreamShopBusinessLogic/BusinessLogics/ReportLogic.cs b/IceCreamShop/IceCreamShopBusinessLogic/BusinessLogics/ReportLogic.cs index 26da404..5887435 100644 --- a/IceCreamShop/IceCreamShopBusinessLogic/BusinessLogics/ReportLogic.cs +++ b/IceCreamShop/IceCreamShopBusinessLogic/BusinessLogics/ReportLogic.cs @@ -14,17 +14,20 @@ namespace IceCreamShopBusinessLogic.BusinessLogics private readonly IOrderStorage _orderStorage; + private readonly IShopStorage _shopStorage; + private readonly AbstractSaveToExcel _saveToExcel; private readonly AbstractSaveToWord _saveToWord; private readonly AbstractSaveToPdf _saveToPdf; - public ReportLogic(IIceCreamStorage iceCreamStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, + public ReportLogic(IIceCreamStorage iceCreamStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, IShopStorage shopStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf) { _iceCreamStorage = iceCreamStorage; _orderStorage = orderStorage; + _shopStorage = shopStorage; _saveToExcel = saveToExcel; _saveToWord = saveToWord; @@ -33,7 +36,6 @@ namespace IceCreamShopBusinessLogic.BusinessLogics public List GetIceCreamComponents() { - var iceCreams = _iceCreamStorage.GetFullList(); var list = new List(); @@ -58,6 +60,32 @@ namespace IceCreamShopBusinessLogic.BusinessLogics return list; } + public List GetShopIceCreams() + { + var shops = _shopStorage.GetFullList(); + + var list = new List(); + + foreach (var shop in shops) + { + var record = new ReportShopIceCreamViewModel + { + ShopName = shop.ShopName, + IceCreams = new List<(string IceCream, int Count)>(), + TotalCount = 0, + }; + foreach (var iceCream in shop.ShopIceCreams) + { + record.IceCreams.Add(new(iceCream.Value.Item1.IceCreamName, iceCream.Value.Item2)); + record.TotalCount += iceCream.Value.Item2; + } + + list.Add(record); + } + + return list; + } + public List GetOrders(ReportBindingModel model) { return _orderStorage.GetFilteredList(new OrderSearchModel { DateFrom = model.DateFrom, DateTo = model.DateTo }) @@ -72,6 +100,18 @@ namespace IceCreamShopBusinessLogic.BusinessLogics .ToList(); } + public List GetGroupedByDateOrders() + { + return _orderStorage.GetFullList().GroupBy(x => x.DateCreate.Date) + .Select(x => new ReportOrdersByDateViewModel + { + Date = x.Key, + Count = x.Count(), + Sum = x.Sum(y => y.Sum) + }) + .ToList(); + } + public void SaveIceCreamsToWordFile(ReportBindingModel model) { _saveToWord.CreateDoc(new WordInfo @@ -82,6 +122,16 @@ namespace IceCreamShopBusinessLogic.BusinessLogics }); } + public void SaveShopsToWordFile(ReportBindingModel model) + { + _saveToWord.CreateShopsTable(new WordInfo + { + FileName = model.FileName, + Title = "Список магазинов", + Shops = _shopStorage.GetFullList() + }); + } + public void SaveIceCreamComponentToExcelFile(ReportBindingModel model) { _saveToExcel.CreateReport(new ExcelInfo @@ -92,6 +142,16 @@ namespace IceCreamShopBusinessLogic.BusinessLogics }); } + public void SaveShopIceCreamToExcelFile(ReportBindingModel model) + { + _saveToExcel.CreateShopReport(new ExcelInfo + { + FileName = model.FileName, + Title = "Загруженность магазинов", + ShopIceCreams = GetShopIceCreams() + }); + } + public void SaveOrdersToPdfFile(ReportBindingModel model) { _saveToPdf.CreateDoc(new PdfInfo @@ -103,5 +163,15 @@ namespace IceCreamShopBusinessLogic.BusinessLogics Orders = GetOrders(model) }); } + + public void SaveGroupedOrdersToPdfFile(ReportBindingModel model) + { + _saveToPdf.CreateDocWithGroupedOrders(new PdfInfo + { + FileName = model.FileName, + Title = "Заказы по датам", + GroupedOrders = GetGroupedByDateOrders() + }); + } } } \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopBusinessLogic/BusinessLogics/ShopLogic.cs b/IceCreamShop/IceCreamShopBusinessLogic/BusinessLogics/ShopLogic.cs new file mode 100644 index 0000000..e4ddd2d --- /dev/null +++ b/IceCreamShop/IceCreamShopBusinessLogic/BusinessLogics/ShopLogic.cs @@ -0,0 +1,177 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.BusinessLogicsContracts; +using IceCreamShopContracts.SearchModels; +using IceCreamShopContracts.StoragesContracts; +using IceCreamShopContracts.ViewModels; +using IceCreamShopDataModels.Models; +using Microsoft.Extensions.Logging; + +namespace IceCreamShopBusinessLogic.BusinessLogics +{ + public class ShopLogic : IShopLogic + { + private readonly ILogger _logger; + + private readonly IShopStorage _shopStorage; + + public ShopLogic(ILogger logger, IShopStorage shopStorage) + { + _logger = logger; + _shopStorage = shopStorage; + } + + 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 MakeShipment(ShopSearchModel shopModel, IIceCreamModel iceCream, int count) + { + if (shopModel == null) + { + throw new ArgumentNullException(nameof(shopModel)); + } + if (iceCream == null) + { + throw new ArgumentNullException(nameof(iceCream)); + } + if (count <= 0) + { + throw new ArgumentException("Количество товаров(мороженого) в магазине должно быть больше нуля", nameof(count)); + } + _logger.LogInformation("MakeShipment(GetElement). ShopName: {ShopName}. Id: {Id}", shopModel.ShopName, shopModel.Id); + var shop = _shopStorage.GetElement(shopModel); + if (shop == null) + { + _logger.LogWarning("MakeShipment(GetElement). Element not found"); + return false; + } + if (shop.IceCreamsMaximum - shop.ShopIceCreams.Sum(x => x.Value.Item2) < count) + { + _logger.LogWarning("MakeShipment error. No space for new ice creams"); + return false; + } + if (shop.ShopIceCreams.ContainsKey(iceCream.Id)) + { + var shopIC = shop.ShopIceCreams[iceCream.Id]; + shopIC.Item2 += count; + shop.ShopIceCreams[iceCream.Id] = shopIC; + _logger.LogInformation("MakeShipment. Added {count} '{iceCream}' to '{ShopName}' shop", count, iceCream.IceCreamName, + shop.ShopName); + } + else + { + shop.ShopIceCreams.Add(iceCream.Id, (iceCream, count)); + _logger.LogInformation("MakeShipment. Added {count} new '{iceCream}' to '{ShopName}' shop", count, iceCream.IceCreamName, + shop.ShopName); + } + if (_shopStorage.Update(new ShopBindingModel() + { + Id = shop.Id, + ShopName = shop.ShopName, + Address = shop.Address, + DateOpening = shop.DateOpening, + IceCreamsMaximum = shop.IceCreamsMaximum, + ShopIceCreams = shop.ShopIceCreams, + }) == null) + { + _logger.LogWarning("MakeShipment. Update operation failed"); + return false; + } + return true; + } + + public bool MakeSale(IIceCreamModel model, int count) + { + return _shopStorage.MakeSale(model, count); + } + + private void CheckModel(ShopBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (!withParams) + { + return; + } + if (string.IsNullOrEmpty(model.ShopName)) + { + throw new ArgumentNullException("Нет названия магазина", nameof(model.ShopName)); + } + if (string.IsNullOrEmpty(model.Address)) + { + throw new ArgumentNullException("Нет адреса магазина", nameof(model.Address)); + } + _logger.LogInformation("Shop. ShopName: {ShopName}. Address: {Address}. Id: {Id}", model.ShopName, model.Address, model.Id); + var element = _shopStorage.GetElement(new ShopSearchModel + { + ShopName = model.ShopName + }); + if (element != null && element.Id != model.Id) + { + throw new InvalidOperationException("Магазин с таким названием уже есть"); + } + } + } +} diff --git a/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/AbstractSaveToExcel.cs b/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/AbstractSaveToExcel.cs index eb0087b..4d742a9 100644 --- a/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/AbstractSaveToExcel.cs +++ b/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/AbstractSaveToExcel.cs @@ -79,11 +79,82 @@ namespace IceCreamShopBusinessLogic.OfficePackage SaveExcel(info); } - /// - /// Создание excel-файла - /// - /// - protected abstract void CreateExcel(ExcelInfo info); + public void CreateShopReport(ExcelInfo info) + { + CreateExcel(info); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = 1, + Text = info.Title, + StyleInfo = ExcelStyleInfoType.Title + }); + + MergeCells(new ExcelMergeParameters + { + CellFromName = "A1", + CellToName = "C1" + }); + + uint rowIndex = 2; + foreach (var si in info.ShopIceCreams) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = si.ShopName, + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + + foreach (var (IceCream, Count) in si.IceCreams) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = IceCream, + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = Count.ToString(), + StyleInfo = ExcelStyleInfoType.TextWithBorder + }); + + rowIndex++; + } + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Итого", + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = si.TotalCount.ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + } + + SaveExcel(info); + } + + /// + /// Создание excel-файла + /// + /// + protected abstract void CreateExcel(ExcelInfo info); /// /// Добавляем новую ячейку в лист diff --git a/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/AbstractSaveToPdf.cs b/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/AbstractSaveToPdf.cs index b7b4ca5..2f5ef61 100644 --- a/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/AbstractSaveToPdf.cs +++ b/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/AbstractSaveToPdf.cs @@ -36,6 +36,34 @@ namespace IceCreamShopBusinessLogic.OfficePackage SavePdf(info); } + public void CreateDocWithGroupedOrders(PdfInfo info) + { + CreatePdf(info); + CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + + CreateTable(new List { "3cm", "4cm", "3cm" }); + + CreateRow(new PdfRowParameters + { + Texts = new List { "Дата", "Количество заказов", "Сумма" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + foreach (var order in info.GroupedOrders) + { + CreateRow(new PdfRowParameters + { + Texts = new List { order.Date.ToShortDateString(), order.Count.ToString(), order.Sum.ToString() }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + CreateParagraph(new PdfParagraph { Text = $"Итого: {info.GroupedOrders.Sum(x => x.Sum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right }); + + SavePdf(info); + } + /// /// Создание pdf-файла /// diff --git a/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/AbstractSaveToWord.cs b/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/AbstractSaveToWord.cs index 5cd6ca3..4450f36 100644 --- a/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/AbstractSaveToWord.cs +++ b/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/AbstractSaveToWord.cs @@ -36,6 +36,51 @@ namespace IceCreamShopBusinessLogic.OfficePackage SaveWord(info); } + public void CreateShopsTable(WordInfo info) + { + CreateWord(info); + + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + + CreateTable(new List { "3000", "3000", "3000" }); + + CreateRow(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { ("Название магазина", new WordTextProperties { Size = "24" }), + ("Адрес", new WordTextProperties { Size = "24" }), ("Дата открытия", new WordTextProperties { Size = "24" }) }, + TextProperties = new WordTextProperties + { + Size = "24", + Bold = true, + JustificationType = WordJustificationType.Center + } + }); + + foreach (var shop in info.Shops) + { + CreateRow(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { (shop.ShopName, new WordTextProperties { Size = "22" }), + (shop.Address, new WordTextProperties { Size = "22" }), (shop.DateOpening.ToString(), new WordTextProperties { Size = "22" })}, + TextProperties = new WordTextProperties + { + Size = "22", + JustificationType = WordJustificationType.Both + } + }); + } + + SaveWord(info); + } + /// /// Создание doc-файла /// @@ -49,6 +94,18 @@ namespace IceCreamShopBusinessLogic.OfficePackage /// protected abstract void CreateParagraph(WordParagraph paragraph); + /// + /// Создание таблицы + /// + /// + protected abstract void CreateTable(List columns); + + /// + /// Создание строки таблицы + /// + /// + protected abstract void CreateRow(WordParagraph paragraph); + /// /// Сохранение файла /// diff --git a/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs b/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs index 98d456f..9633f4f 100644 --- a/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs +++ b/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs @@ -9,5 +9,7 @@ namespace IceCreamShopBusinessLogic.OfficePackage.HelperModels public string Title { get; set; } = string.Empty; public List IceCreamComponents { get; set; } = new(); + + public List ShopIceCreams { get; set; } = new(); } } \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs b/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs index f68b3ce..6970917 100644 --- a/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs +++ b/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs @@ -13,5 +13,7 @@ namespace IceCreamShopBusinessLogic.OfficePackage.HelperModels public DateTime DateTo { get; set; } public List Orders { get; set; } = new(); + + public List GroupedOrders { get; set; } = new(); } } \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/HelperModels/WordInfo.cs b/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/HelperModels/WordInfo.cs index 31648f7..7be1a1f 100644 --- a/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/HelperModels/WordInfo.cs +++ b/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/HelperModels/WordInfo.cs @@ -9,5 +9,7 @@ namespace IceCreamShopBusinessLogic.OfficePackage.HelperModels public string Title { get; set; } = string.Empty; public List IceCreams { get; set; } = new(); + + public List Shops { get; set; } = new(); } } \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/Implements/SaveToWord.cs b/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/Implements/SaveToWord.cs index f9a74e6..ce926ce 100644 --- a/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/Implements/SaveToWord.cs +++ b/IceCreamShop/IceCreamShopBusinessLogic/OfficePackage/Implements/SaveToWord.cs @@ -3,6 +3,7 @@ using IceCreamShopBusinessLogic.OfficePackage.HelperModels; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; +using System.Security.Cryptography; namespace IceCreamShopBusinessLogic.OfficePackage.Implements { @@ -12,6 +13,8 @@ namespace IceCreamShopBusinessLogic.OfficePackage.Implements private Body? _docBody; + private Table? table; + /// /// Получение типа выравнивания /// @@ -119,6 +122,67 @@ namespace IceCreamShopBusinessLogic.OfficePackage.Implements _docBody.AppendChild(docParagraph); } + protected override void CreateTable(List columns) + { + if (_docBody == null || columns == null) + { + return; + } + + table = new(); + TableProperties properties = new(); + properties.AppendChild(new TableLayout { Type = TableLayoutValues.Fixed }); + properties.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 } + )); + properties.AppendChild(new TableWidth { Type = TableWidthUnitValues.Auto }); + table.AppendChild(properties); + + TableGrid tableGrid = new(); + foreach (var column in columns) + { + tableGrid.AppendChild(new GridColumn() { Width = column }); + } + table.AppendChild(tableGrid); + + _docBody.AppendChild(table); + } + + protected override void CreateRow(WordParagraph paragraph) + { + if (_docBody == null || table == null || paragraph == null) + { + return; + } + TableRow tableRow = new(); + foreach (var column in paragraph.Texts) + { + var tableParagraph = new Paragraph(); + tableParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties)); + + var tableRun = new Run(); + var runProperties = new RunProperties(); + runProperties.AppendChild(new FontSize { Val = column.Item2.Size }); + if (column.Item2.Bold) + { + runProperties.AppendChild(new Bold()); + } + tableRun.AppendChild(runProperties); + tableRun.AppendChild(new Text { Text = column.Item1, Space = SpaceProcessingModeValues.Preserve }); + tableParagraph.AppendChild(tableRun); + + TableCell cell = new(); + cell.AppendChild(tableParagraph); + tableRow.AppendChild(cell); + } + table.AppendChild(tableRow); + } + protected override void SaveWord(WordInfo info) { if (_docBody == null || _wordDocument == null) diff --git a/IceCreamShop/IceCreamShopContracts/BindingModels/ShopBindingModel.cs b/IceCreamShop/IceCreamShopContracts/BindingModels/ShopBindingModel.cs new file mode 100644 index 0000000..66393f0 --- /dev/null +++ b/IceCreamShop/IceCreamShopContracts/BindingModels/ShopBindingModel.cs @@ -0,0 +1,23 @@ +using IceCreamShopDataModels.Models; + +namespace IceCreamShopContracts.BindingModels +{ + public class ShopBindingModel : IShopModel + { + public int Id { get; set; } + + public string ShopName { get; set; } = string.Empty; + + public string Address { get; set; } = string.Empty; + + public DateTime DateOpening { get; set; } = DateTime.Now; + + public Dictionary ShopIceCreams + { + get; + set; + } = new(); + + public int IceCreamsMaximum { get; set; } + } +} diff --git a/IceCreamShop/IceCreamShopContracts/BusinessLogicsContracts/IReportLogic.cs b/IceCreamShop/IceCreamShopContracts/BusinessLogicsContracts/IReportLogic.cs index 9f01123..deace99 100644 --- a/IceCreamShop/IceCreamShopContracts/BusinessLogicsContracts/IReportLogic.cs +++ b/IceCreamShop/IceCreamShopContracts/BusinessLogicsContracts/IReportLogic.cs @@ -7,12 +7,22 @@ namespace IceCreamShopContracts.BusinessLogicsContracts { List GetIceCreamComponents(); + List GetShopIceCreams(); + List GetOrders(ReportBindingModel model); + List GetGroupedByDateOrders(); + void SaveIceCreamsToWordFile(ReportBindingModel model); + void SaveShopsToWordFile(ReportBindingModel model); + void SaveIceCreamComponentToExcelFile(ReportBindingModel model); + void SaveShopIceCreamToExcelFile(ReportBindingModel model); + void SaveOrdersToPdfFile(ReportBindingModel model); + + void SaveGroupedOrdersToPdfFile(ReportBindingModel model); } } \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopContracts/BusinessLogicsContracts/IShopLogic.cs b/IceCreamShop/IceCreamShopContracts/BusinessLogicsContracts/IShopLogic.cs new file mode 100644 index 0000000..9c2bd2c --- /dev/null +++ b/IceCreamShop/IceCreamShopContracts/BusinessLogicsContracts/IShopLogic.cs @@ -0,0 +1,24 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.SearchModels; +using IceCreamShopContracts.ViewModels; +using IceCreamShopDataModels.Models; + +namespace IceCreamShopContracts.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 MakeShipment(ShopSearchModel shopModel, IIceCreamModel iceCream, int count); + + bool MakeSale(IIceCreamModel model, int count); + } +} diff --git a/IceCreamShop/IceCreamShopContracts/SearchModels/ShopSearchModel.cs b/IceCreamShop/IceCreamShopContracts/SearchModels/ShopSearchModel.cs new file mode 100644 index 0000000..5c6f8cd --- /dev/null +++ b/IceCreamShop/IceCreamShopContracts/SearchModels/ShopSearchModel.cs @@ -0,0 +1,9 @@ +namespace IceCreamShopContracts.SearchModels +{ + public class ShopSearchModel + { + public int? Id { get; set; } + + public string? ShopName { get; set; } + } +} diff --git a/IceCreamShop/IceCreamShopContracts/StoragesContracts/IShopStorage.cs b/IceCreamShop/IceCreamShopContracts/StoragesContracts/IShopStorage.cs new file mode 100644 index 0000000..746c4f3 --- /dev/null +++ b/IceCreamShop/IceCreamShopContracts/StoragesContracts/IShopStorage.cs @@ -0,0 +1,24 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.SearchModels; +using IceCreamShopContracts.ViewModels; +using IceCreamShopDataModels.Models; + +namespace IceCreamShopContracts.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 MakeSale(IIceCreamModel model, int count); + } +} diff --git a/IceCreamShop/IceCreamShopContracts/ViewModels/ReportOrdersByDateViewModel.cs b/IceCreamShop/IceCreamShopContracts/ViewModels/ReportOrdersByDateViewModel.cs new file mode 100644 index 0000000..045de87 --- /dev/null +++ b/IceCreamShop/IceCreamShopContracts/ViewModels/ReportOrdersByDateViewModel.cs @@ -0,0 +1,11 @@ +namespace IceCreamShopContracts.ViewModels +{ + public class ReportOrdersByDateViewModel + { + public DateTime Date { get; set; } + + public int Count { get; set; } + + public double Sum { get; set; } + } +} diff --git a/IceCreamShop/IceCreamShopContracts/ViewModels/ReportShopIceCreamViewModel.cs b/IceCreamShop/IceCreamShopContracts/ViewModels/ReportShopIceCreamViewModel.cs new file mode 100644 index 0000000..8b2ada7 --- /dev/null +++ b/IceCreamShop/IceCreamShopContracts/ViewModels/ReportShopIceCreamViewModel.cs @@ -0,0 +1,11 @@ +namespace IceCreamShopContracts.ViewModels +{ + public class ReportShopIceCreamViewModel + { + public string ShopName { get; set; } = string.Empty; + + public int TotalCount { get; set; } + + public List<(string IceCream, int Count)> IceCreams { get; set; } = new(); + } +} diff --git a/IceCreamShop/IceCreamShopContracts/ViewModels/ShopViewModel.cs b/IceCreamShop/IceCreamShopContracts/ViewModels/ShopViewModel.cs new file mode 100644 index 0000000..b1873a2 --- /dev/null +++ b/IceCreamShop/IceCreamShopContracts/ViewModels/ShopViewModel.cs @@ -0,0 +1,28 @@ +using IceCreamShopDataModels.Models; +using System.ComponentModel; + +namespace IceCreamShopContracts.ViewModels +{ + public class ShopViewModel : IShopModel + { + public int Id { get; set; } + + [DisplayName("Название магазина")] + public string ShopName { get; set; } = string.Empty; + + [DisplayName("Адрес")] + public string Address { get; set; } = string.Empty; + + [DisplayName("Дата открытия")] + public DateTime DateOpening { get; set; } = DateTime.Now; + + public Dictionary ShopIceCreams + { + get; + set; + } = new(); + + [DisplayName("Максимальное количество мороженого")] + public int IceCreamsMaximum { get; set; } + } +} diff --git a/IceCreamShop/IceCreamShopDataModels/Models/IShopModel.cs b/IceCreamShop/IceCreamShopDataModels/Models/IShopModel.cs new file mode 100644 index 0000000..84e0301 --- /dev/null +++ b/IceCreamShop/IceCreamShopDataModels/Models/IShopModel.cs @@ -0,0 +1,15 @@ +namespace IceCreamShopDataModels.Models +{ + public interface IShopModel : IId + { + string ShopName { get; } + + string Address { get; } + + DateTime DateOpening { get; } + + Dictionary ShopIceCreams { get; } + + int IceCreamsMaximum { get; } + } +} diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/IceCreamShopDatabase.cs b/IceCreamShop/IceCreamShopDatabaseImplement/IceCreamShopDatabase.cs index c8aad1d..f884bbc 100644 --- a/IceCreamShop/IceCreamShopDatabaseImplement/IceCreamShopDatabase.cs +++ b/IceCreamShop/IceCreamShopDatabaseImplement/IceCreamShopDatabase.cs @@ -22,6 +22,10 @@ namespace IceCreamShopDatabaseImplement public virtual DbSet Orders { set; get; } + public virtual DbSet Shops { set; get; } + + public virtual DbSet ShopIceCreams { set; get; } + public virtual DbSet Clients { set; get; } } } \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Implements/ShopStorage.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..19729d2 --- /dev/null +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Implements/ShopStorage.cs @@ -0,0 +1,146 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.SearchModels; +using IceCreamShopContracts.StoragesContracts; +using IceCreamShopContracts.ViewModels; +using IceCreamShopDatabaseImplement.Models; +using IceCreamShopDataModels.Models; +using Microsoft.EntityFrameworkCore; + +namespace IceCreamShopDatabaseImplement.Implements +{ + public class ShopStorage : IShopStorage + { + public List GetFullList() + { + using var context = new IceCreamShopDatabase(); + return context.Shops + .Include(x => x.IceCreams) + .ThenInclude(x => x.IceCream) + .ToList() + .Select(x => x.GetViewModel) + .ToList(); + } + + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName)) + { + return new(); + } + using var context = new IceCreamShopDatabase(); + return context.Shops + .Include(x => x.IceCreams) + .ThenInclude(x => x.IceCream) + .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 null; + } + using var context = new IceCreamShopDatabase(); + return context.Shops + .Include(x => x.IceCreams) + .ThenInclude(x => x.IceCream) + .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 IceCreamShopDatabase(); + 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 IceCreamShopDatabase(); + using var transaction = context.Database.BeginTransaction(); + try + { + var shop = context.Shops.FirstOrDefault(rec => rec.Id == model.Id); + if (shop == null) + { + return null; + } + shop.Update(model); + context.SaveChanges(); + shop.UpdateIceCreams(context, model); + transaction.Commit(); + return shop.GetViewModel; + } + catch + { + transaction.Rollback(); + throw; + } + } + + public ShopViewModel? Delete(ShopBindingModel model) + { + using var context = new IceCreamShopDatabase(); + var element = context.Shops + .Include(x => x.IceCreams) + .FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + context.Shops.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } + + public bool MakeSale(IIceCreamModel model, int count) + { + using var context = new IceCreamShopDatabase(); + using var transaction = context.Database.BeginTransaction(); + try + { + foreach (var shop in context.Shops.Include(x => x.IceCreams).ThenInclude(x => x.IceCream) + .Where(x => x.IceCreams.Any(x => x.IceCreamId == model.Id)) + .ToList()) + { + var iceCream = shop.ShopIceCreams[model.Id]; + int min = Math.Min(iceCream.Item2, count); + if (min == iceCream.Item2) + { + shop.ShopIceCreams.Remove(model.Id); + } + else + { + shop.ShopIceCreams[model.Id] = (iceCream.Item1, iceCream.Item2 - min); + } + shop.UpdateIceCreams(context, new() { Id = shop.Id, ShopIceCreams = shop.ShopIceCreams }); + count -= min; + if (count == 0) + { + context.SaveChanges(); + transaction.Commit(); + return true; + } + } + transaction.Rollback(); + return false; + } + catch + { + transaction.Rollback(); + throw; + } + } + } +} diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20240408110201_ShopAddition.Designer.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20240408110201_ShopAddition.Designer.cs new file mode 100644 index 0000000..3cb2ad4 --- /dev/null +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20240408110201_ShopAddition.Designer.cs @@ -0,0 +1,250 @@ +// +using System; +using IceCreamShopDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace IceCreamShopDatabaseImplement.Migrations +{ + [DbContext(typeof(IceCreamShopDatabase))] + [Migration("20240408110201_ShopAddition")] + partial class ShopAddition + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.16") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("IceCreamShopDatabaseImplement.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("IceCreamShopDatabaseImplement.Models.IceCream", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("IceCreamName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("IceCreams"); + }); + + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.IceCreamComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("IceCreamId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("IceCreamId"); + + b.ToTable("IceCreamComponents"); + }); + + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("IceCreamId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("IceCreamId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DateOpening") + .HasColumnType("datetime2"); + + b.Property("IceCreamsMaximum") + .HasColumnType("int"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.ShopIceCream", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("IceCreamId") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("IceCreamId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopIceCreams"); + }); + + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.IceCreamComponent", b => + { + b.HasOne("IceCreamShopDatabaseImplement.Models.Component", "Component") + .WithMany("IceCreamComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("IceCreamShopDatabaseImplement.Models.IceCream", "IceCream") + .WithMany("Components") + .HasForeignKey("IceCreamId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("IceCream"); + }); + + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Order", b => + { + b.HasOne("IceCreamShopDatabaseImplement.Models.IceCream", "IceCream") + .WithMany("Orders") + .HasForeignKey("IceCreamId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("IceCream"); + }); + + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.ShopIceCream", b => + { + b.HasOne("IceCreamShopDatabaseImplement.Models.IceCream", "IceCream") + .WithMany("ShopIceCreams") + .HasForeignKey("IceCreamId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("IceCreamShopDatabaseImplement.Models.Shop", "Shop") + .WithMany("IceCreams") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("IceCream"); + + b.Navigation("Shop"); + }); + + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Component", b => + { + b.Navigation("IceCreamComponents"); + }); + + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.IceCream", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + + b.Navigation("ShopIceCreams"); + }); + + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Shop", b => + { + b.Navigation("IceCreams"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20240408110201_ShopAddition.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20240408110201_ShopAddition.cs new file mode 100644 index 0000000..fca0f16 --- /dev/null +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/20240408110201_ShopAddition.cs @@ -0,0 +1,78 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace IceCreamShopDatabaseImplement.Migrations +{ + /// + public partial class ShopAddition : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + 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), + Address = table.Column(type: "nvarchar(max)", nullable: false), + DateOpening = table.Column(type: "datetime2", nullable: false), + IceCreamsMaximum = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Shops", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ShopIceCreams", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ShopId = table.Column(type: "int", nullable: false), + IceCreamId = table.Column(type: "int", nullable: false), + Count = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ShopIceCreams", x => x.Id); + table.ForeignKey( + name: "FK_ShopIceCreams_IceCreams_IceCreamId", + column: x => x.IceCreamId, + principalTable: "IceCreams", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ShopIceCreams_Shops_ShopId", + column: x => x.ShopId, + principalTable: "Shops", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_ShopIceCreams_IceCreamId", + table: "ShopIceCreams", + column: "IceCreamId"); + + migrationBuilder.CreateIndex( + name: "IX_ShopIceCreams_ShopId", + table: "ShopIceCreams", + column: "ShopId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ShopIceCreams"); + + migrationBuilder.DropTable( + name: "Shops"); + } + } +} diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/IceCreamShopDatabaseModelSnapshot.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/IceCreamShopDatabaseModelSnapshot.cs index 6faaa96..60179c4 100644 --- a/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/IceCreamShopDatabaseModelSnapshot.cs +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Migrations/IceCreamShopDatabaseModelSnapshot.cs @@ -151,6 +151,59 @@ namespace IceCreamShopDatabaseImplement.Migrations b.ToTable("Orders"); }); + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DateOpening") + .HasColumnType("datetime2"); + + b.Property("IceCreamsMaximum") + .HasColumnType("int"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.ShopIceCream", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("IceCreamId") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("IceCreamId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopIceCreams"); + }); + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.IceCreamComponent", b => { b.HasOne("IceCreamShopDatabaseImplement.Models.Component", "Component") @@ -184,9 +237,28 @@ namespace IceCreamShopDatabaseImplement.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.Navigation("IceCream"); + }); + + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.ShopIceCream", b => + { + b.HasOne("IceCreamShopDatabaseImplement.Models.IceCream", "IceCream") + .WithMany("ShopIceCreams") + .HasForeignKey("IceCreamId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + b.Navigation("Client"); + b.HasOne("IceCreamShopDatabaseImplement.Models.Shop", "Shop") + .WithMany("IceCreams") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + b.Navigation("IceCream"); + + b.Navigation("Shop"); }); modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Client", b => @@ -204,6 +276,13 @@ namespace IceCreamShopDatabaseImplement.Migrations b.Navigation("Components"); b.Navigation("Orders"); + + b.Navigation("ShopIceCreams"); + }); + + modelBuilder.Entity("IceCreamShopDatabaseImplement.Models.Shop", b => + { + b.Navigation("IceCreams"); }); #pragma warning restore 612, 618 } diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Models/IceCream.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Models/IceCream.cs index 4105f97..2d89d40 100644 --- a/IceCreamShop/IceCreamShopDatabaseImplement/Models/IceCream.cs +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Models/IceCream.cs @@ -38,6 +38,9 @@ namespace IceCreamShopDatabaseImplement.Models [ForeignKey("IceCreamId")] public virtual List Orders { get; set; } = new(); + [ForeignKey("IceCreamId")] + public virtual List ShopIceCreams { get; set; } = new(); + public static IceCream Create(IceCreamShopDatabase context, IceCreamBindingModel model) { return new IceCream() diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Models/Shop.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Models/Shop.cs new file mode 100644 index 0000000..b7c8fec --- /dev/null +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Models/Shop.cs @@ -0,0 +1,110 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.ViewModels; +using IceCreamShopDataModels.Models; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace IceCreamShopDatabaseImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; set; } + + [Required] + public string ShopName { get; set; } = string.Empty; + + [Required] + public string Address { get; set; } = string.Empty; + + [Required] + public DateTime DateOpening { get; set; } + + [Required] + public int IceCreamsMaximum { get; set; } + + private Dictionary? _shopIceCreams = null; + + [NotMapped] + public Dictionary ShopIceCreams + { + get + { + if (_shopIceCreams == null) + { + _shopIceCreams = IceCreams + .ToDictionary(x => x.IceCreamId, x => (x.IceCream as IIceCreamModel, x.Count)); + } + return _shopIceCreams; + } + } + + [ForeignKey("ShopId")] + public virtual List IceCreams { get; set; } = new(); + + public static Shop Create(IceCreamShopDatabase context, ShopBindingModel model) + { + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Address = model.Address, + DateOpening = model.DateOpening, + IceCreamsMaximum = model.IceCreamsMaximum, + IceCreams = model.ShopIceCreams.Select(x => new ShopIceCream + { + IceCream = context.IceCreams.First(y => y.Id == x.Key), + Count = x.Value.Item2 + }).ToList() + }; + } + + public void Update(ShopBindingModel model) + { + ShopName = model.ShopName; + Address = model.Address; + DateOpening = model.DateOpening; + IceCreamsMaximum = model.IceCreamsMaximum; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Address = Address, + DateOpening = DateOpening, + IceCreamsMaximum = IceCreamsMaximum, + ShopIceCreams = ShopIceCreams + }; + + public void UpdateIceCreams(IceCreamShopDatabase context, ShopBindingModel model) + { + var shopIceCreams = context.ShopIceCreams.Where(rec => rec.ShopId == model.Id).ToList(); + if (shopIceCreams != null && shopIceCreams.Count > 0) + { + context.ShopIceCreams.RemoveRange(shopIceCreams.Where(rec => !model.ShopIceCreams.ContainsKey(rec.IceCreamId))); + context.SaveChanges(); + foreach (var updateIceCream in shopIceCreams) + { + if (model.ShopIceCreams.ContainsKey(updateIceCream.IceCreamId)) + { + updateIceCream.Count = model.ShopIceCreams[updateIceCream.IceCreamId].Item2; + model.ShopIceCreams.Remove(updateIceCream.IceCreamId); + } + } + context.SaveChanges(); + } + var shop = context.Shops.First(x => x.Id == Id); + foreach (var ic in model.ShopIceCreams) + { + context.ShopIceCreams.Add(new ShopIceCream + { + Shop = shop, + IceCream = context.IceCreams.First(x => x.Id == ic.Key), + Count = ic.Value.Item2 + }); + context.SaveChanges(); + } + _shopIceCreams = null; + } + } +} diff --git a/IceCreamShop/IceCreamShopDatabaseImplement/Models/ShopIceCream.cs b/IceCreamShop/IceCreamShopDatabaseImplement/Models/ShopIceCream.cs new file mode 100644 index 0000000..86b5b14 --- /dev/null +++ b/IceCreamShop/IceCreamShopDatabaseImplement/Models/ShopIceCream.cs @@ -0,0 +1,22 @@ +using System.ComponentModel.DataAnnotations; + +namespace IceCreamShopDatabaseImplement.Models +{ + public class ShopIceCream + { + public int Id { get; set; } + + [Required] + public int ShopId { get; set; } + + [Required] + public int IceCreamId { get; set; } + + [Required] + public int Count { get; set; } + + public virtual IceCream IceCream { get; set; } = new(); + + public virtual Shop Shop { get; set; } = new(); + } +} diff --git a/IceCreamShop/IceCreamShopFileImplement/DataFileSingleton.cs b/IceCreamShop/IceCreamShopFileImplement/DataFileSingleton.cs index b5bbb48..2d7f74e 100644 --- a/IceCreamShop/IceCreamShopFileImplement/DataFileSingleton.cs +++ b/IceCreamShop/IceCreamShopFileImplement/DataFileSingleton.cs @@ -15,6 +15,8 @@ namespace IceCreamShopFileImplement private readonly string ClientFileName = "Client.xml"; + private readonly string ShopFileName = "Shop.xml"; + public List Components { get; private set; } public List Orders { get; private set; } @@ -23,6 +25,8 @@ namespace IceCreamShopFileImplement public List Clients { get; private set; } + public List Shops { get; private set; } + public static DataFileSingleton GetInstance() { if (instance == null) @@ -40,12 +44,15 @@ namespace IceCreamShopFileImplement 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)!)!; IceCreams = LoadData(IceCreamFileName, "IceCream", x => IceCream.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/IceCreamShop/IceCreamShopFileImplement/Implements/ShopStorage.cs b/IceCreamShop/IceCreamShopFileImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..a79aadb --- /dev/null +++ b/IceCreamShop/IceCreamShopFileImplement/Implements/ShopStorage.cs @@ -0,0 +1,133 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.SearchModels; +using IceCreamShopContracts.StoragesContracts; +using IceCreamShopContracts.ViewModels; +using IceCreamShopDataModels.Models; +using IceCreamShopFileImplement.Models; +using System.Collections.Generic; + +namespace IceCreamShopFileImplement.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 element = source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + source.Shops.Remove(element); + source.SaveShops(); + return element.GetViewModel; + } + return null; + } + + public bool MakeSale(IIceCreamModel model, int count) + { + var iceCream = source.IceCreams.FirstOrDefault(x => x.Id == model.Id); + int countInShops = source.Shops.SelectMany(x => x.ShopIceCreams).Sum(y => y.Key == model.Id ? y.Value.Item2 : 0); + + if (iceCream == null || countInShops < count) + { + return false; + } + + foreach (var shop in source.Shops) + { + var shopIceCreams = shop.ShopIceCreams.Where(x => x.Key == model.Id); + if (shopIceCreams.Any()) + { + var shopIceCream = shopIceCreams.First(); + int min = Math.Min(shopIceCream.Value.Item2, count); + if (min == shopIceCream.Value.Item2) + { + shop.ShopIceCreams.Remove(shopIceCream.Key); + } + else + { + shop.ShopIceCreams[shopIceCream.Key] = (shopIceCream.Value.Item1, shopIceCream.Value.Item2 - min); + } + shop.Update(new ShopBindingModel + { + Id = shop.Id, + ShopName = shop.ShopName, + Address = shop.Address, + DateOpening = shop.DateOpening, + ShopIceCreams = shop.ShopIceCreams, + IceCreamsMaximum = shop.IceCreamsMaximum + }); + count -= min; + if (count <= 0) + { + break; + } + } + } + source.SaveShops(); + return true; + } + } +} diff --git a/IceCreamShop/IceCreamShopFileImplement/Models/Shop.cs b/IceCreamShop/IceCreamShopFileImplement/Models/Shop.cs new file mode 100644 index 0000000..ef5c368 --- /dev/null +++ b/IceCreamShop/IceCreamShopFileImplement/Models/Shop.cs @@ -0,0 +1,108 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.ViewModels; +using IceCreamShopDataModels.Models; +using System.Xml.Linq; + +namespace IceCreamShopFileImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + + public string ShopName { get; private set; } = string.Empty; + + public string Address { get; private set; } = string.Empty; + + public DateTime DateOpening { get; private set; } + + public Dictionary IceCreams { get; private set; } = new(); + + private Dictionary? _shopIceCreams = null; + + public Dictionary ShopIceCreams + { + get + { + if (_shopIceCreams == null) + { + var source = DataFileSingleton.GetInstance(); + _shopIceCreams = IceCreams.ToDictionary(x => x.Key, + y => ((source.IceCreams.FirstOrDefault(z => z.Id == y.Key) as IIceCreamModel)!, y.Value)); + } + return _shopIceCreams; + } + } + + public int IceCreamsMaximum { get; private set; } + + public static Shop? Create(ShopBindingModel? model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Address = model.Address, + DateOpening = model.DateOpening, + IceCreams = model.ShopIceCreams.ToDictionary(x => x.Key, x => x.Value.Item2), + IceCreamsMaximum = model.IceCreamsMaximum + }; + } + + public static Shop? Create(XElement element) + { + if (element == null) + { + return null; + } + return new Shop() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ShopName = element.Element("ShopName")!.Value, + Address = element.Element("Address")!.Value, + DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value), + IceCreamsMaximum = Convert.ToInt32(element.Element("IceCreamsMaximum")!.Value), + IceCreams = element.Element("ShopIceCreams")!.Elements("ShopIceCream") + .ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)) + }; + } + + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Address = model.Address; + DateOpening = model.DateOpening; + IceCreamsMaximum = model.IceCreamsMaximum; + IceCreams = model.ShopIceCreams.ToDictionary(x => x.Key, x => x.Value.Item2); + _shopIceCreams = null; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Address = Address, + DateOpening = DateOpening, + ShopIceCreams = ShopIceCreams, + IceCreamsMaximum = IceCreamsMaximum + }; + + public XElement GetXElement => new("Shop", + new XAttribute("Id", Id), + new XElement("ShopName", ShopName), + new XElement("Address", Address), + new XElement("DateOpening", DateOpening.ToString()), + new XElement("IceCreamsMaximum", IceCreamsMaximum.ToString()), + new XElement("ShopIceCreams", + IceCreams.Select(x => new XElement("ShopIceCream", + new XElement("Key", x.Key), + new XElement("Value", x.Value))).ToArray())); + } +} diff --git a/IceCreamShop/IceCreamShopListImplement/DataListSingleton.cs b/IceCreamShop/IceCreamShopListImplement/DataListSingleton.cs index 59d358e..1ea1660 100644 --- a/IceCreamShop/IceCreamShopListImplement/DataListSingleton.cs +++ b/IceCreamShop/IceCreamShopListImplement/DataListSingleton.cs @@ -14,12 +14,15 @@ namespace IceCreamShopListImplement public List Clients { get; set; } + public List Shops { get; set; } + private DataListSingleton() { Components = new List(); Orders = new List(); IceCreams = new List(); Clients = new List(); + Shops = new List(); } public static DataListSingleton GetInstance() diff --git a/IceCreamShop/IceCreamShopListImplement/Implements/ShopStorage.cs b/IceCreamShop/IceCreamShopListImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..c866429 --- /dev/null +++ b/IceCreamShop/IceCreamShopListImplement/Implements/ShopStorage.cs @@ -0,0 +1,115 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.SearchModels; +using IceCreamShopContracts.StoragesContracts; +using IceCreamShopContracts.ViewModels; +using IceCreamShopDataModels.Models; +using IceCreamShopListImplement.Models; + +namespace IceCreamShopListImplement.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 MakeSale(IIceCreamModel model, int count) + { + throw new NotImplementedException(); + } + } +} diff --git a/IceCreamShop/IceCreamShopListImplement/Models/Shop.cs b/IceCreamShop/IceCreamShopListImplement/Models/Shop.cs new file mode 100644 index 0000000..d85b820 --- /dev/null +++ b/IceCreamShop/IceCreamShopListImplement/Models/Shop.cs @@ -0,0 +1,65 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.ViewModels; +using IceCreamShopDataModels.Models; + +namespace IceCreamShopListImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; private set; } + + public string ShopName { get; private set; } = string.Empty; + + public string Address { get; private set; } = string.Empty; + + public DateTime DateOpening { get; private set; } + + public Dictionary ShopIceCreams + { + get; + private set; + } = new Dictionary(); + + public int IceCreamsMaximum { get; private set; } + + public static Shop? Create(ShopBindingModel? model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Address = model.Address, + DateOpening = model.DateOpening, + ShopIceCreams = model.ShopIceCreams, + IceCreamsMaximum = model.IceCreamsMaximum + }; + } + + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + Address = model.Address; + DateOpening = model.DateOpening; + ShopIceCreams = model.ShopIceCreams; + IceCreamsMaximum = model.IceCreamsMaximum; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Address = Address, + DateOpening = DateOpening, + ShopIceCreams = ShopIceCreams, + IceCreamsMaximum = IceCreamsMaximum + }; + } +} diff --git a/IceCreamShop/IceCreamShopView/FormIceCreamSale.Designer.cs b/IceCreamShop/IceCreamShopView/FormIceCreamSale.Designer.cs new file mode 100644 index 0000000..d520bb0 --- /dev/null +++ b/IceCreamShop/IceCreamShopView/FormIceCreamSale.Designer.cs @@ -0,0 +1,127 @@ +namespace IceCreamShopView +{ + partial class FormIceCreamSale + { + /// + /// 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() + { + buttonCancel = new Button(); + buttonSale = new Button(); + textBoxCount = new TextBox(); + labelCount = new Label(); + comboBoxIceCream = new ComboBox(); + labelIceCream = new Label(); + SuspendLayout(); + // + // buttonCancel + // + buttonCancel.Location = new Point(253, 83); + buttonCancel.Margin = new Padding(4, 3, 4, 3); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(88, 27); + buttonCancel.TabIndex = 17; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // buttonSale + // + buttonSale.Location = new Point(159, 83); + buttonSale.Margin = new Padding(4, 3, 4, 3); + buttonSale.Name = "buttonSale"; + buttonSale.Size = new Size(88, 27); + buttonSale.TabIndex = 16; + buttonSale.Text = "Продать"; + buttonSale.UseVisualStyleBackColor = true; + buttonSale.Click += ButtonSale_Click; + // + // textBoxCount + // + textBoxCount.Location = new Point(101, 51); + textBoxCount.Margin = new Padding(4, 3, 4, 3); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(252, 23); + textBoxCount.TabIndex = 15; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(13, 54); + labelCount.Margin = new Padding(4, 0, 4, 0); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(78, 15); + labelCount.TabIndex = 14; + labelCount.Text = "Количество :"; + // + // comboBoxIceCream + // + comboBoxIceCream.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxIceCream.FormattingEnabled = true; + comboBoxIceCream.Location = new Point(101, 15); + comboBoxIceCream.Margin = new Padding(4, 3, 4, 3); + comboBoxIceCream.Name = "comboBoxIceCream"; + comboBoxIceCream.Size = new Size(252, 23); + comboBoxIceCream.TabIndex = 13; + // + // labelIceCream + // + labelIceCream.AutoSize = true; + labelIceCream.Location = new Point(13, 19); + labelIceCream.Margin = new Padding(4, 0, 4, 0); + labelIceCream.Name = "labelIceCream"; + labelIceCream.Size = new Size(80, 15); + labelIceCream.TabIndex = 12; + labelIceCream.Text = "Мороженое :"; + // + // FormIceCreamSale + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(373, 123); + Controls.Add(buttonCancel); + Controls.Add(buttonSale); + Controls.Add(textBoxCount); + Controls.Add(labelCount); + Controls.Add(comboBoxIceCream); + Controls.Add(labelIceCream); + Name = "FormIceCreamSale"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Продажа мороженого"; + Load += FormIceCreamSale_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Button buttonCancel; + private Button buttonSale; + private TextBox textBoxCount; + private Label labelCount; + private ComboBox comboBoxIceCream; + private Label labelIceCream; + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopView/FormIceCreamSale.cs b/IceCreamShop/IceCreamShopView/FormIceCreamSale.cs new file mode 100644 index 0000000..da861e9 --- /dev/null +++ b/IceCreamShop/IceCreamShopView/FormIceCreamSale.cs @@ -0,0 +1,87 @@ +using IceCreamShopContracts.BusinessLogicsContracts; +using IceCreamShopContracts.BindingModels; +using Microsoft.Extensions.Logging; + +namespace IceCreamShopView +{ + public partial class FormIceCreamSale : Form + { + private readonly ILogger _logger; + + private readonly IIceCreamLogic _logicIceCream; + + private readonly IShopLogic _logicShop; + + public FormIceCreamSale(ILogger logger, IIceCreamLogic logicIceCream, IShopLogic logicShop) + { + InitializeComponent(); + _logger = logger; + _logicIceCream = logicIceCream; + _logicShop = logicShop; + } + + private void FormIceCreamSale_Load(object sender, EventArgs e) + { + _logger.LogInformation("Ice creams loading"); + try + { + var list = _logicIceCream.ReadList(null); + if (list != null) + { + comboBoxIceCream.DisplayMember = "IceCreamName"; + comboBoxIceCream.ValueMember = "Id"; + comboBoxIceCream.DataSource = list; + comboBoxIceCream.SelectedItem = null; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ice creams loading error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonSale_Click(object sender, EventArgs e) + { + if (comboBoxIceCream.SelectedValue == null) + { + MessageBox.Show("Выберите мороженое", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Ice cream sale"); + try + { + var operationResult = _logicShop.MakeSale( + new IceCreamBindingModel + { + Id = Convert.ToInt32(comboBoxIceCream.SelectedValue) + }, + 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, "Ice cream sale error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/IceCreamShop/IceCreamShopView/FormIceCreamSale.resx b/IceCreamShop/IceCreamShopView/FormIceCreamSale.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/IceCreamShop/IceCreamShopView/FormIceCreamSale.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/IceCreamShop/IceCreamShopView/FormMain.cs b/IceCreamShop/IceCreamShopView/FormMain.cs index 2191e95..17abf36 100644 --- a/IceCreamShop/IceCreamShopView/FormMain.cs +++ b/IceCreamShop/IceCreamShopView/FormMain.cs @@ -65,6 +65,33 @@ namespace IceCreamShopView } } + private void МагазиныToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShops)); + if (service is FormShops form) + { + form.ShowDialog(); + } + } + + private void ПополнениеМагазинаToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormMakeShipment)); + if (service is FormMakeShipment form) + { + form.ShowDialog(); + } + } + + private void ПродажаМороженогоToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormIceCreamSale)); + if (service is FormIceCreamSale form) + { + form.ShowDialog(); + } + } + private void КлиентыToolStripMenuItem_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormClients)); @@ -102,6 +129,34 @@ namespace IceCreamShopView } } + private void СписокМагазиновToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveShopsToWordFile(new ReportBindingModel { FileName = dialog.FileName }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + + private void ЗагруженностьМагазиновToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportShopIceCreams)); + if (service is FormReportShopIceCreams form) + { + form.ShowDialog(); + } + } + + private void ЗаказыПоДатамToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportGroupedOrders)); + if (service is FormReportGroupedOrders form) + { + form.ShowDialog(); + } + } + private void ButtonCreateOrder_Click(object sender, EventArgs e) { var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); diff --git a/IceCreamShop/IceCreamShopView/FormMain.designer.cs b/IceCreamShop/IceCreamShopView/FormMain.designer.cs index a161ec1..72733bf 100644 --- a/IceCreamShop/IceCreamShopView/FormMain.designer.cs +++ b/IceCreamShop/IceCreamShopView/FormMain.designer.cs @@ -32,11 +32,17 @@ справочникиToolStripMenuItem = new ToolStripMenuItem(); компонентыToolStripMenuItem = new ToolStripMenuItem(); мороженоеToolStripMenuItem = new ToolStripMenuItem(); + магазиныToolStripMenuItem = new ToolStripMenuItem(); клиентыToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem(); списокМороженогоToolStripMenuItem = new ToolStripMenuItem(); компонентыПоМороженымToolStripMenuItem = new ToolStripMenuItem(); списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + списокМагазиновToolStripMenuItem = new ToolStripMenuItem(); + загруженностьМагазиновToolStripMenuItem = new ToolStripMenuItem(); + заказыПоДатамToolStripMenuItem = new ToolStripMenuItem(); + пополнениеМагазинаToolStripMenuItem = new ToolStripMenuItem(); + продажаМороженогоToolStripMenuItem = new ToolStripMenuItem(); buttonIssuedOrder = new Button(); buttonOrderReady = new Button(); buttonTakeOrderInWork = new Button(); @@ -49,7 +55,7 @@ // // menuStrip // - menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem }); + menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem, пополнениеМагазинаToolStripMenuItem, продажаМороженогоToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; menuStrip.Padding = new Padding(7, 2, 0, 2); @@ -59,6 +65,7 @@ // // справочникиToolStripMenuItem // + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, мороженоеToolStripMenuItem, магазиныToolStripMenuItem }); справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, мороженоеToolStripMenuItem, клиентыToolStripMenuItem }); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.Size = new Size(94, 20); @@ -78,6 +85,13 @@ мороженоеToolStripMenuItem.Text = "Мороженое"; мороженоеToolStripMenuItem.Click += МороженоеToolStripMenuItem_Click; // + // магазиныToolStripMenuItem + // + магазиныToolStripMenuItem.Name = "магазиныToolStripMenuItem"; + магазиныToolStripMenuItem.Size = new Size(145, 22); + магазиныToolStripMenuItem.Text = "Магазины"; + магазиныToolStripMenuItem.Click += МагазиныToolStripMenuItem_Click; + // // клиентыToolStripMenuItem // клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; @@ -87,7 +101,7 @@ // // отчетыToolStripMenuItem // - отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокМороженогоToolStripMenuItem, компонентыПоМороженымToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокМороженогоToolStripMenuItem, компонентыПоМороженымToolStripMenuItem, списокЗаказовToolStripMenuItem, списокМагазиновToolStripMenuItem, загруженностьМагазиновToolStripMenuItem, заказыПоДатамToolStripMenuItem }); отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; отчетыToolStripMenuItem.Size = new Size(60, 20); отчетыToolStripMenuItem.Text = "Отчеты"; @@ -113,6 +127,41 @@ списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Click += СписокЗаказовToolStripMenuItem_Click; // + // списокМагазиновToolStripMenuItem + // + списокМагазиновToolStripMenuItem.Name = "списокМагазиновToolStripMenuItem"; + списокМагазиновToolStripMenuItem.Size = new Size(235, 22); + списокМагазиновToolStripMenuItem.Text = "Список магазинов"; + списокМагазиновToolStripMenuItem.Click += СписокМагазиновToolStripMenuItem_Click; + // + // загруженностьМагазиновToolStripMenuItem + // + загруженностьМагазиновToolStripMenuItem.Name = "загруженностьМагазиновToolStripMenuItem"; + загруженностьМагазиновToolStripMenuItem.Size = new Size(235, 22); + загруженностьМагазиновToolStripMenuItem.Text = "Загруженность магазинов"; + загруженностьМагазиновToolStripMenuItem.Click += ЗагруженностьМагазиновToolStripMenuItem_Click; + // + // заказыПоДатамToolStripMenuItem + // + заказыПоДатамToolStripMenuItem.Name = "заказыПоДатамToolStripMenuItem"; + заказыПоДатамToolStripMenuItem.Size = new Size(235, 22); + заказыПоДатамToolStripMenuItem.Text = "Заказы по датам"; + заказыПоДатамToolStripMenuItem.Click += ЗаказыПоДатамToolStripMenuItem_Click; + // + // пополнениеМагазинаToolStripMenuItem + // + пополнениеМагазинаToolStripMenuItem.Name = "пополнениеМагазинаToolStripMenuItem"; + пополнениеМагазинаToolStripMenuItem.Size = new Size(143, 20); + пополнениеМагазинаToolStripMenuItem.Text = "Пополнение магазина"; + пополнениеМагазинаToolStripMenuItem.Click += ПополнениеМагазинаToolStripMenuItem_Click; + // + // продажаМороженогоToolStripMenuItem + // + продажаМороженогоToolStripMenuItem.Name = "продажаМороженогоToolStripMenuItem"; + продажаМороженогоToolStripMenuItem.Size = new Size(143, 20); + продажаМороженогоToolStripMenuItem.Text = "Продажа мороженого"; + продажаМороженогоToolStripMenuItem.Click += ПродажаМороженогоToolStripMenuItem_Click; + // // buttonIssuedOrder // buttonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; @@ -227,10 +276,16 @@ private System.Windows.Forms.Button buttonCreateOrder; private System.Windows.Forms.DataGridView dataGridView; private System.Windows.Forms.Button buttonUpd; + private ToolStripMenuItem магазиныToolStripMenuItem; + private ToolStripMenuItem пополнениеМагазинаToolStripMenuItem; + private ToolStripMenuItem продажаМороженогоToolStripMenuItem; private ToolStripMenuItem отчетыToolStripMenuItem; private ToolStripMenuItem списокМороженогоToolStripMenuItem; private ToolStripMenuItem компонентыПоМороженымToolStripMenuItem; private ToolStripMenuItem списокЗаказовToolStripMenuItem; + private ToolStripMenuItem списокМагазиновToolStripMenuItem; + private ToolStripMenuItem загруженностьМагазиновToolStripMenuItem; + private ToolStripMenuItem заказыПоДатамToolStripMenuItem; private ToolStripMenuItem клиентыToolStripMenuItem; } } diff --git a/IceCreamShop/IceCreamShopView/FormMakeShipment.Designer.cs b/IceCreamShop/IceCreamShopView/FormMakeShipment.Designer.cs new file mode 100644 index 0000000..77ac97a --- /dev/null +++ b/IceCreamShop/IceCreamShopView/FormMakeShipment.Designer.cs @@ -0,0 +1,153 @@ +namespace IceCreamShopView +{ + partial class FormMakeShipment + { + /// + /// 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() + { + labelShop = new Label(); + comboBoxShop = new ComboBox(); + labelIceCream = new Label(); + comboBoxIceCream = new ComboBox(); + labelCount = new Label(); + textBoxCount = new TextBox(); + buttonSave = new Button(); + buttonCancel = new Button(); + SuspendLayout(); + // + // labelShop + // + labelShop.AutoSize = true; + labelShop.Location = new Point(14, 13); + labelShop.Margin = new Padding(4, 0, 4, 0); + labelShop.Name = "labelShop"; + labelShop.Size = new Size(60, 15); + labelShop.TabIndex = 2; + labelShop.Text = "Магазин :"; + // + // comboBoxShop + // + comboBoxShop.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxShop.FormattingEnabled = true; + comboBoxShop.Location = new Point(102, 10); + comboBoxShop.Margin = new Padding(4, 3, 4, 3); + comboBoxShop.Name = "comboBoxShop"; + comboBoxShop.Size = new Size(252, 23); + comboBoxShop.TabIndex = 5; + // + // labelIceCream + // + labelIceCream.AutoSize = true; + labelIceCream.Location = new Point(14, 48); + labelIceCream.Margin = new Padding(4, 0, 4, 0); + labelIceCream.Name = "labelIceCream"; + labelIceCream.Size = new Size(80, 15); + labelIceCream.TabIndex = 6; + labelIceCream.Text = "Мороженое :"; + // + // comboBoxIceCream + // + comboBoxIceCream.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxIceCream.FormattingEnabled = true; + comboBoxIceCream.Location = new Point(102, 44); + comboBoxIceCream.Margin = new Padding(4, 3, 4, 3); + comboBoxIceCream.Name = "comboBoxIceCream"; + comboBoxIceCream.Size = new Size(252, 23); + comboBoxIceCream.TabIndex = 7; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(14, 83); + labelCount.Margin = new Padding(4, 0, 4, 0); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(78, 15); + labelCount.TabIndex = 8; + labelCount.Text = "Количество :"; + // + // textBoxCount + // + textBoxCount.Location = new Point(102, 80); + textBoxCount.Margin = new Padding(4, 3, 4, 3); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(252, 23); + textBoxCount.TabIndex = 9; + // + // buttonSave + // + buttonSave.Location = new Point(160, 112); + buttonSave.Margin = new Padding(4, 3, 4, 3); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(88, 27); + buttonSave.TabIndex = 10; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(254, 112); + buttonCancel.Margin = new Padding(4, 3, 4, 3); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(88, 27); + buttonCancel.TabIndex = 11; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // FormMakeShipment + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(373, 147); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(textBoxCount); + Controls.Add(labelCount); + Controls.Add(comboBoxIceCream); + Controls.Add(labelIceCream); + Controls.Add(comboBoxShop); + Controls.Add(labelShop); + Name = "FormMakeShipment"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Пополнение магазина"; + Load += FormMakeShipment_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label labelShop; + private ComboBox comboBoxShop; + private Label labelIceCream; + private ComboBox comboBoxIceCream; + private Label labelCount; + private TextBox textBoxCount; + private Button buttonSave; + private Button buttonCancel; + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopView/FormMakeShipment.cs b/IceCreamShop/IceCreamShopView/FormMakeShipment.cs new file mode 100644 index 0000000..1c1217d --- /dev/null +++ b/IceCreamShop/IceCreamShopView/FormMakeShipment.cs @@ -0,0 +1,116 @@ +using IceCreamShopContracts.BusinessLogicsContracts; +using IceCreamShopContracts.SearchModels; +using Microsoft.Extensions.Logging; + +namespace IceCreamShopView +{ + public partial class FormMakeShipment : Form + { + private readonly ILogger _logger; + + private readonly IIceCreamLogic _logicIceCream; + + private readonly IShopLogic _logicShop; + + public FormMakeShipment(ILogger logger, IIceCreamLogic logicIceCream, IShopLogic logicShop) + { + InitializeComponent(); + _logger = logger; + _logicIceCream = logicIceCream; + _logicShop = logicShop; + } + + private void FormMakeShipment_Load(object sender, EventArgs e) + { + _logger.LogInformation("Ice creams loading"); + try + { + var list = _logicIceCream.ReadList(null); + if (list != null) + { + comboBoxIceCream.DisplayMember = "IceCreamName"; + comboBoxIceCream.ValueMember = "Id"; + comboBoxIceCream.DataSource = list; + comboBoxIceCream.SelectedItem = null; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ice creams loading error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + _logger.LogInformation("Shops loading"); + try + { + var list = _logicShop.ReadList(null); + if (list != null) + { + comboBoxShop.DisplayMember = "ShopName"; + comboBoxShop.ValueMember = "Id"; + comboBoxShop.DataSource = list; + comboBoxShop.SelectedItem = null; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Shops loading error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (comboBoxShop.SelectedValue == null) + { + MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxIceCream.SelectedValue == null) + { + MessageBox.Show("Выберите мороженое", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Shop replenishment"); + try + { + var iceCream = _logicIceCream.ReadElement(new IceCreamSearchModel + { Id = Convert.ToInt32(comboBoxIceCream.SelectedValue) }); + if (iceCream == null) + { + throw new Exception("Мороженое не найдено."); + } + var operationResult = _logicShop.MakeShipment(new ShopSearchModel + { + Id = Convert.ToInt32(comboBoxShop.SelectedValue) + }, + iceCream, + 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, "Shop replenishment error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + DialogResult = DialogResult.OK; + Close(); + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/IceCreamShop/IceCreamShopView/FormMakeShipment.resx b/IceCreamShop/IceCreamShopView/FormMakeShipment.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/IceCreamShop/IceCreamShopView/FormMakeShipment.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/IceCreamShop/IceCreamShopView/FormReportGroupedOrders.cs b/IceCreamShop/IceCreamShopView/FormReportGroupedOrders.cs new file mode 100644 index 0000000..51beeaf --- /dev/null +++ b/IceCreamShop/IceCreamShopView/FormReportGroupedOrders.cs @@ -0,0 +1,72 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using Microsoft.Reporting.WinForms; + +namespace IceCreamShopView +{ + 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 ButtonCreateReport_Click(object sender, EventArgs e) + { + try + { + var dataSource = _logic.GetGroupedByDateOrders(); + var source = new ReportDataSource("DataSetOrders", dataSource); + reportViewer.LocalReport.DataSources.Clear(); + reportViewer.LocalReport.DataSources.Add(source); + + reportViewer.RefreshReport(); + _logger.LogInformation("Loading list of grouped orders"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Loading list of grouped orders error"); + 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("Saving list of grouped orders"); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + _logger.LogError(ex, "Saving list of grouped orders error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopView/FormReportGroupedOrders.designer.cs b/IceCreamShop/IceCreamShopView/FormReportGroupedOrders.designer.cs new file mode 100644 index 0000000..f848ac3 --- /dev/null +++ b/IceCreamShop/IceCreamShopView/FormReportGroupedOrders.designer.cs @@ -0,0 +1,91 @@ +namespace IceCreamShopView +{ + 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() + { + panel = new Panel(); + buttonToPdf = new Button(); + buttonCreateReport = new Button(); + panel.SuspendLayout(); + SuspendLayout(); + // + // panel + // + panel.Controls.Add(buttonToPdf); + panel.Controls.Add(buttonCreateReport); + panel.Dock = DockStyle.Top; + panel.Location = new Point(0, 0); + panel.Margin = new Padding(4, 3, 4, 3); + panel.Name = "panel"; + panel.Size = new Size(1031, 40); + panel.TabIndex = 0; + // + // buttonToPdf + // + buttonToPdf.Anchor = AnchorStyles.Top | AnchorStyles.Right; + buttonToPdf.Location = new Point(188, 8); + buttonToPdf.Margin = new Padding(4, 3, 4, 3); + buttonToPdf.Name = "buttonToPdf"; + buttonToPdf.Size = new Size(139, 27); + buttonToPdf.TabIndex = 5; + buttonToPdf.Text = "В Pdf"; + buttonToPdf.UseVisualStyleBackColor = true; + buttonToPdf.Click += ButtonToPdf_Click; + // + // buttonCreateReport + // + buttonCreateReport.Location = new Point(11, 8); + buttonCreateReport.Margin = new Padding(4, 3, 4, 3); + buttonCreateReport.Name = "buttonCreateReport"; + buttonCreateReport.Size = new Size(139, 27); + buttonCreateReport.TabIndex = 4; + buttonCreateReport.Text = "Сформировать"; + buttonCreateReport.UseVisualStyleBackColor = true; + buttonCreateReport.Click += ButtonCreateReport_Click; + // + // FormReportGroupedOrders + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1031, 647); + Controls.Add(panel); + Margin = new Padding(4, 3, 4, 3); + Name = "FormReportGroupedOrders"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Заказы по датам"; + panel.ResumeLayout(false); + ResumeLayout(false); + } + + #endregion + + private System.Windows.Forms.Panel panel; + private System.Windows.Forms.Button buttonToPdf; + private System.Windows.Forms.Button buttonCreateReport; + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopView/FormReportGroupedOrders.resx b/IceCreamShop/IceCreamShopView/FormReportGroupedOrders.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/IceCreamShop/IceCreamShopView/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/IceCreamShop/IceCreamShopView/FormReportShopIceCreams.cs b/IceCreamShop/IceCreamShopView/FormReportShopIceCreams.cs new file mode 100644 index 0000000..aeb0ada --- /dev/null +++ b/IceCreamShop/IceCreamShopView/FormReportShopIceCreams.cs @@ -0,0 +1,70 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; + +namespace IceCreamShopView +{ + public partial class FormReportShopIceCreams : Form + { + private readonly ILogger _logger; + + private readonly IReportLogic _logic; + + public FormReportShopIceCreams(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + private void FormReportShopIceCreams_Load(object sender, EventArgs e) + { + try + { + var dict = _logic.GetShopIceCreams(); + if (dict != null) + { + dataGridView.Rows.Clear(); + foreach (var elem in dict) + { + dataGridView.Rows.Add(new object[] { elem.ShopName, "", "" }); + foreach (var listElem in elem.IceCreams) + { + dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 }); + } + dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount }); + dataGridView.Rows.Add(Array.Empty()); + } + } + _logger.LogInformation("Loading information on store workload"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Loading information on store workload error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonSaveToExcel_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + _logic.SaveShopIceCreamToExcelFile(new ReportBindingModel + { + FileName = dialog.FileName + }); + _logger.LogInformation("Saving information on store workload"); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + _logger.LogError(ex, "Saving information on store workload error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopView/FormReportShopIceCreams.designer.cs b/IceCreamShop/IceCreamShopView/FormReportShopIceCreams.designer.cs new file mode 100644 index 0000000..6fb9607 --- /dev/null +++ b/IceCreamShop/IceCreamShopView/FormReportShopIceCreams.designer.cs @@ -0,0 +1,114 @@ +namespace IceCreamShopView +{ + partial class FormReportShopIceCreams + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + buttonSaveToExcel = new Button(); + ColumnShop = new DataGridViewTextBoxColumn(); + ColumnIceCream = new DataGridViewTextBoxColumn(); + ColumnCount = new DataGridViewTextBoxColumn(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.AllowUserToOrderColumns = true; + dataGridView.AllowUserToResizeColumns = false; + dataGridView.AllowUserToResizeRows = false; + dataGridView.BackgroundColor = SystemColors.ControlLightLight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnShop, ColumnIceCream, ColumnCount }); + dataGridView.Dock = DockStyle.Bottom; + dataGridView.Location = new Point(0, 47); + dataGridView.Margin = new Padding(4, 3, 4, 3); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.Size = new Size(616, 510); + dataGridView.TabIndex = 0; + // + // buttonSaveToExcel + // + buttonSaveToExcel.Location = new Point(13, 10); + buttonSaveToExcel.Margin = new Padding(4, 3, 4, 3); + buttonSaveToExcel.Name = "buttonSaveToExcel"; + buttonSaveToExcel.Size = new Size(186, 27); + buttonSaveToExcel.TabIndex = 1; + buttonSaveToExcel.Text = "Сохранить в Excel"; + buttonSaveToExcel.UseVisualStyleBackColor = true; + buttonSaveToExcel.Click += ButtonSaveToExcel_Click; + // + // ColumnShop + // + ColumnShop.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + ColumnShop.HeaderText = "Магазин"; + ColumnShop.Name = "ColumnShop"; + ColumnShop.ReadOnly = true; + // + // ColumnIceCream + // + ColumnIceCream.HeaderText = "Мороженое"; + ColumnIceCream.Name = "ColumnIceCream"; + ColumnIceCream.ReadOnly = true; + ColumnIceCream.Width = 200; + // + // ColumnCount + // + ColumnCount.HeaderText = "Количество"; + ColumnCount.Name = "ColumnCount"; + ColumnCount.ReadOnly = true; + // + // FormReportShopIceCreams + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(616, 557); + Controls.Add(buttonSaveToExcel); + Controls.Add(dataGridView); + Margin = new Padding(4, 3, 4, 3); + Name = "FormReportShopIceCreams"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Загруженность магазинов"; + Load += FormReportShopIceCreams_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private System.Windows.Forms.DataGridView dataGridView; + private System.Windows.Forms.Button buttonSaveToExcel; + private DataGridViewTextBoxColumn ColumnShop; + private DataGridViewTextBoxColumn ColumnIceCream; + private DataGridViewTextBoxColumn ColumnCount; + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopView/FormReportShopIceCreams.resx b/IceCreamShop/IceCreamShopView/FormReportShopIceCreams.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/IceCreamShop/IceCreamShopView/FormReportShopIceCreams.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/IceCreamShop/IceCreamShopView/FormShop.Designer.cs b/IceCreamShop/IceCreamShopView/FormShop.Designer.cs new file mode 100644 index 0000000..26480fb --- /dev/null +++ b/IceCreamShop/IceCreamShopView/FormShop.Designer.cs @@ -0,0 +1,237 @@ +namespace IceCreamShopView +{ + 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() + { + labelName = new Label(); + textBoxName = new TextBox(); + labelAddress = new Label(); + textBoxAddress = new TextBox(); + dateTimePicker = new DateTimePicker(); + labelOpeningDate = new Label(); + groupBoxIceCreams = new GroupBox(); + dataGridView = new DataGridView(); + ColumnId = new DataGridViewTextBoxColumn(); + ColumnName = new DataGridViewTextBoxColumn(); + ColumnCount = new DataGridViewTextBoxColumn(); + buttonSave = new Button(); + buttonCancel = new Button(); + textBoxMaximum = new TextBox(); + labelMaximum = new Label(); + groupBoxIceCreams.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // labelName + // + labelName.AutoSize = true; + labelName.Location = new Point(14, 10); + labelName.Margin = new Padding(4, 0, 4, 0); + labelName.Name = "labelName"; + labelName.Size = new Size(65, 15); + labelName.TabIndex = 1; + labelName.Text = "Название :"; + // + // textBoxName + // + textBoxName.Location = new Point(92, 7); + textBoxName.Margin = new Padding(4, 3, 4, 3); + textBoxName.Name = "textBoxName"; + textBoxName.Size = new Size(252, 23); + textBoxName.TabIndex = 2; + // + // labelAddress + // + labelAddress.AutoSize = true; + labelAddress.Location = new Point(14, 40); + labelAddress.Margin = new Padding(4, 0, 4, 0); + labelAddress.Name = "labelAddress"; + labelAddress.Size = new Size(46, 15); + labelAddress.TabIndex = 3; + labelAddress.Text = "Адрес :"; + // + // textBoxAddress + // + textBoxAddress.Location = new Point(92, 37); + textBoxAddress.Margin = new Padding(4, 3, 4, 3); + textBoxAddress.Name = "textBoxAddress"; + textBoxAddress.Size = new Size(252, 23); + textBoxAddress.TabIndex = 4; + // + // dateTimePicker + // + dateTimePicker.Location = new Point(126, 66); + dateTimePicker.Name = "dateTimePicker"; + dateTimePicker.Size = new Size(218, 23); + dateTimePicker.TabIndex = 5; + // + // labelOpeningDate + // + labelOpeningDate.AutoSize = true; + labelOpeningDate.Location = new Point(14, 69); + labelOpeningDate.Margin = new Padding(4, 0, 4, 0); + labelOpeningDate.Name = "labelOpeningDate"; + labelOpeningDate.Size = new Size(93, 15); + labelOpeningDate.TabIndex = 6; + labelOpeningDate.Text = "Дата открытия :"; + // + // groupBoxIceCreams + // + groupBoxIceCreams.Controls.Add(dataGridView); + groupBoxIceCreams.Location = new Point(5, 138); + groupBoxIceCreams.Margin = new Padding(4, 3, 4, 3); + groupBoxIceCreams.Name = "groupBoxIceCreams"; + groupBoxIceCreams.Padding = new Padding(4, 3, 4, 3); + groupBoxIceCreams.Size = new Size(469, 288); + groupBoxIceCreams.TabIndex = 7; + groupBoxIceCreams.TabStop = false; + groupBoxIceCreams.Text = "Мороженое"; + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = SystemColors.ControlLightLight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnId, ColumnName, ColumnCount }); + dataGridView.Dock = DockStyle.Left; + dataGridView.Location = new Point(4, 19); + dataGridView.Margin = new Padding(4, 3, 4, 3); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(457, 266); + dataGridView.TabIndex = 0; + // + // ColumnId + // + ColumnId.HeaderText = "Id"; + ColumnId.Name = "ColumnId"; + ColumnId.ReadOnly = true; + ColumnId.Visible = false; + // + // ColumnName + // + ColumnName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + ColumnName.HeaderText = "Название мороженого"; + ColumnName.Name = "ColumnName"; + ColumnName.ReadOnly = true; + // + // ColumnCount + // + ColumnCount.HeaderText = "Количество"; + ColumnCount.Name = "ColumnCount"; + ColumnCount.ReadOnly = true; + // + // buttonSave + // + buttonSave.Location = new Point(256, 434); + buttonSave.Margin = new Padding(4, 3, 4, 3); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(88, 27); + buttonSave.TabIndex = 8; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += ButtonSave_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(360, 434); + buttonCancel.Margin = new Padding(4, 3, 4, 3); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(88, 27); + buttonCancel.TabIndex = 9; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // textBoxMaximum + // + textBoxMaximum.Location = new Point(169, 97); + textBoxMaximum.Margin = new Padding(4, 3, 4, 3); + textBoxMaximum.Name = "textBoxMaximum"; + textBoxMaximum.Size = new Size(175, 23); + textBoxMaximum.TabIndex = 11; + // + // labelMaximum + // + labelMaximum.AutoSize = true; + labelMaximum.Location = new Point(14, 100); + labelMaximum.Margin = new Padding(4, 0, 4, 0); + labelMaximum.Name = "labelMaximum"; + labelMaximum.Size = new Size(147, 15); + labelMaximum.TabIndex = 10; + labelMaximum.Text = "Максимум мороженого :"; + // + // FormShop + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(478, 468); + Controls.Add(textBoxMaximum); + Controls.Add(labelMaximum); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(groupBoxIceCreams); + Controls.Add(labelOpeningDate); + Controls.Add(dateTimePicker); + Controls.Add(textBoxAddress); + Controls.Add(labelAddress); + Controls.Add(textBoxName); + Controls.Add(labelName); + Name = "FormShop"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Магазин"; + Load += FormShop_Load; + groupBoxIceCreams.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label labelName; + private TextBox textBoxName; + private Label labelAddress; + private TextBox textBoxAddress; + private DateTimePicker dateTimePicker; + private Label labelOpeningDate; + private GroupBox groupBoxIceCreams; + private DataGridView dataGridView; + private DataGridViewTextBoxColumn ColumnId; + private DataGridViewTextBoxColumn ColumnName; + private DataGridViewTextBoxColumn ColumnCount; + private Button buttonSave; + private Button buttonCancel; + private TextBox textBoxMaximum; + private Label labelMaximum; + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopView/FormShop.cs b/IceCreamShop/IceCreamShopView/FormShop.cs new file mode 100644 index 0000000..37eb53c --- /dev/null +++ b/IceCreamShop/IceCreamShopView/FormShop.cs @@ -0,0 +1,132 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.BusinessLogicsContracts; +using IceCreamShopContracts.SearchModels; +using IceCreamShopDataModels.Models; +using Microsoft.Extensions.Logging; + +namespace IceCreamShopView +{ + public partial class FormShop : Form + { + private readonly ILogger _logger; + + private readonly IShopLogic _logic; + + private int? _id; + + private Dictionary _shopIceCreams; + + public int Id { set { _id = value; } } + + public FormShop(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + _shopIceCreams = new Dictionary(); + } + + private void FormShop_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Shop loading"); + try + { + var view = _logic.ReadElement(new ShopSearchModel { Id = _id.Value }); + if (view != null) + { + textBoxName.Text = view.ShopName; + textBoxAddress.Text = view.Address; + dateTimePicker.Value = view.DateOpening; + textBoxMaximum.Text = view.IceCreamsMaximum.ToString(); + _shopIceCreams = view.ShopIceCreams ?? new Dictionary(); + LoadData(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Shop loading error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + private void LoadData() + { + _logger.LogInformation("Shop ice creams loading"); + try + { + if (_shopIceCreams != null) + { + dataGridView.Rows.Clear(); + foreach (var iceCream in _shopIceCreams) + { + dataGridView.Rows.Add(new object[] { iceCream.Key, iceCream.Value.Item1.IceCreamName, iceCream.Value.Item2 }); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Shop ice creams loading error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxAddress.Text)) + { + MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(dateTimePicker.Text)) + { + MessageBox.Show("Заполните дату", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxMaximum.Text)) + { + MessageBox.Show("Заполните максимальное количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Shop saving"); + try + { + var model = new ShopBindingModel + { + Id = _id ?? 0, + ShopName = textBoxName.Text, + Address = textBoxAddress.Text, + DateOpening = dateTimePicker.Value, + IceCreamsMaximum = Convert.ToInt32(textBoxMaximum.Text), + ShopIceCreams = _shopIceCreams + }; + 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, "Shop saving error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/IceCreamShop/IceCreamShopView/FormShop.resx b/IceCreamShop/IceCreamShopView/FormShop.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/IceCreamShop/IceCreamShopView/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/IceCreamShop/IceCreamShopView/FormShops.Designer.cs b/IceCreamShop/IceCreamShopView/FormShops.Designer.cs new file mode 100644 index 0000000..5b61657 --- /dev/null +++ b/IceCreamShop/IceCreamShopView/FormShops.Designer.cs @@ -0,0 +1,126 @@ +namespace IceCreamShopView +{ + partial class FormShops + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + buttonUpd = new Button(); + buttonDel = new Button(); + buttonEdit = new Button(); + buttonAdd = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = SystemColors.ControlLightLight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Left; + dataGridView.Location = new Point(0, 0); + dataGridView.Margin = new Padding(4, 3, 4, 3); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(408, 360); + dataGridView.TabIndex = 2; + // + // buttonUpd + // + buttonUpd.Location = new Point(432, 152); + buttonUpd.Margin = new Padding(4, 3, 4, 3); + buttonUpd.Name = "buttonUpd"; + buttonUpd.Size = new Size(88, 27); + buttonUpd.TabIndex = 12; + buttonUpd.Text = "Обновить"; + buttonUpd.UseVisualStyleBackColor = true; + buttonUpd.Click += ButtonUpd_Click; + // + // buttonDel + // + buttonDel.Location = new Point(432, 105); + buttonDel.Margin = new Padding(4, 3, 4, 3); + buttonDel.Name = "buttonDel"; + buttonDel.Size = new Size(88, 27); + buttonDel.TabIndex = 11; + buttonDel.Text = "Удалить"; + buttonDel.UseVisualStyleBackColor = true; + buttonDel.Click += ButtonDel_Click; + // + // buttonEdit + // + buttonEdit.Location = new Point(432, 58); + buttonEdit.Margin = new Padding(4, 3, 4, 3); + buttonEdit.Name = "buttonEdit"; + buttonEdit.Size = new Size(88, 27); + buttonEdit.TabIndex = 10; + buttonEdit.Text = "Изменить"; + buttonEdit.UseVisualStyleBackColor = true; + buttonEdit.Click += ButtonEdit_Click; + // + // buttonAdd + // + buttonAdd.Location = new Point(432, 14); + buttonAdd.Margin = new Padding(4, 3, 4, 3); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(88, 27); + buttonAdd.TabIndex = 9; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += ButtonAdd_Click; + // + // FormShops + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(541, 360); + Controls.Add(buttonUpd); + Controls.Add(buttonDel); + Controls.Add(buttonEdit); + Controls.Add(buttonAdd); + Controls.Add(dataGridView); + Name = "FormShops"; + StartPosition = FormStartPosition.CenterScreen; + Text = "Магазины"; + Load += FormShops_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonUpd; + private Button buttonDel; + private Button buttonEdit; + private Button buttonAdd; + } +} \ No newline at end of file diff --git a/IceCreamShop/IceCreamShopView/FormShops.cs b/IceCreamShop/IceCreamShopView/FormShops.cs new file mode 100644 index 0000000..288f631 --- /dev/null +++ b/IceCreamShop/IceCreamShopView/FormShops.cs @@ -0,0 +1,104 @@ +using IceCreamShopContracts.BindingModels; +using IceCreamShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; + +namespace IceCreamShopView +{ + 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["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ShopIceCreams"].Visible = false; + } + _logger.LogInformation("Shops loading"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Shops loading error"); + 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 ButtonEdit_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("Deletion of shop"); + try + { + if (!_logic.Delete(new ShopBindingModel { Id = id })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Shop deletion error"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + private void ButtonUpd_Click(object sender, EventArgs e) + { + LoadData(); + } + } +} diff --git a/IceCreamShop/IceCreamShopView/FormShops.resx b/IceCreamShop/IceCreamShopView/FormShops.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/IceCreamShop/IceCreamShopView/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/IceCreamShop/IceCreamShopView/IceCreamShopView.csproj b/IceCreamShop/IceCreamShopView/IceCreamShopView.csproj index f99f40c..8f4beaf 100644 --- a/IceCreamShop/IceCreamShopView/IceCreamShopView.csproj +++ b/IceCreamShop/IceCreamShopView/IceCreamShopView.csproj @@ -37,6 +37,24 @@ + + + Form + + + Form + + + + + + Always + + + Always + + + Form diff --git a/IceCreamShop/IceCreamShopView/Program.cs b/IceCreamShop/IceCreamShopView/Program.cs index 07cfe11..55a8e59 100644 --- a/IceCreamShop/IceCreamShopView/Program.cs +++ b/IceCreamShop/IceCreamShopView/Program.cs @@ -40,11 +40,13 @@ namespace IceCreamShopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -59,9 +61,15 @@ namespace IceCreamShopView 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/IceCreamShop/IceCreamShopView/ReportGroupedOrders.rdlc b/IceCreamShop/IceCreamShopView/ReportGroupedOrders.rdlc new file mode 100644 index 0000000..8d36e09 --- /dev/null +++ b/IceCreamShop/IceCreamShopView/ReportGroupedOrders.rdlc @@ -0,0 +1,424 @@ + + + 0 + + + + System.Data.DataSet + /* Local Connection */ + + 10791c83-cee8-4a38-bbd0-245fc17cefb3 + + + + + + IceCreamShopContractsViewModels + /* Local Query */ + + + + Date + System.DateTime + + + Count + System.Int32 + + + Sum + System.Decimal + + + + IceCreamShopContracts.ViewModels + ReportOrdersByDateViewModel + IceCreamShopContracts.ViewModels.ReportOrdersByDateViewModel, IceCreamShopContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + + + + + + + + + true + true + + + + + Заказы по датам + + + + + + + 1cm + 21cm + + + Middle + 2pt + 2pt + 2pt + 2pt + + + + + + + 6.01401cm + + + 6.56042cm + + + 6.12687cm + + + + + 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!Count.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Sum.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + + + + + + + + + + + + After + + + + + + + DataSetOrders + 1.95474cm + 1.16099cm + 1.2cm + 18.7013cm + 1 + + + + + + true + true + + + + + Всего: + + + + + + + 4cm + 11.23542cm + 0.6cm + 2.5cm + 2 + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Sum(Fields!Sum.Value, "DataSetOrders") + + + + + + + 4cm + 13.73542cm + 0.6cm + 6.12687cm + 3 + + + 2pt + 2pt + 2pt + 2pt + + + + 5.72875cm +