diff --git a/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs b/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs index c218de0..ef480d3 100644 --- a/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/OrderLogic.cs @@ -4,7 +4,9 @@ using GiftShopContracts.SearchModels; using GiftShopContracts.StoragesContracts; using GiftShopContracts.ViewModels; using GiftShopDataModels.Enums; +using GiftShopDataModels.Models; using Microsoft.Extensions.Logging; +using System.Xml.Linq; namespace GiftShopBusinessLogic.BusinessLogics { @@ -14,10 +16,17 @@ namespace GiftShopBusinessLogic.BusinessLogics private readonly IOrderStorage _orderStorage; - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + private readonly IShopStorage _shopStorage; + private readonly IShopLogic _shopLogic; + private readonly IGiftStorage _giftStorage; + + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IGiftStorage giftStorage, IShopLogic shopLogic, IShopStorage shopStorage) { _logger = logger; _orderStorage = orderStorage; + _giftStorage = giftStorage; + _shopLogic = shopLogic; + _shopStorage = shopStorage; } public bool CreateOrder(OrderBindingModel model) @@ -41,37 +50,97 @@ namespace GiftShopBusinessLogic.BusinessLogics return true; } + public bool CheckSupply(IGiftModel gift, int count) + { + if (count <= 0) + { + _logger.LogWarning("Check then supply operation error. Gift count < 0."); + return false; + } - public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) + int sumCapacity = 0; + int sumCount = 0; + sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCapacity).Sum(); + sumCount = _shopStorage.GetFullList().Select(x => x.ShopGifts.Select(y => y.Value.Item2).Sum()).Sum(); + int freeSpace = sumCapacity - sumCount; + + if (freeSpace - count < 0) + { + _logger.LogWarning("Check then supply operation error. There's no place for new Gift in shops."); + return false; + } + + foreach (var shop in _shopStorage.GetFullList()) + { + freeSpace = shop.MaxCapacity; + foreach (var doc in shop.ShopGifts) + { + freeSpace -= doc.Value.Item2; + } + if (freeSpace == 0) + { + continue; + } + if (freeSpace - count >= 0) + { + if (_shopLogic.MakeSupply(new() { Id = shop.Id }, gift, count)) + count = 0; + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + if (freeSpace - count < 0) + { + if (_shopLogic.MakeSupply(new() { Id = shop.Id }, gift, freeSpace)) + count -= freeSpace; + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + if (count <= 0) + { + return true; + } + } + return false; + } + public bool StatusUpdate(OrderBindingModel model, OrderStatus status) { - var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); - //CheckModel(model); - - if (model.Status + 1 != newStatus) - { - _logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Order status incorrect."); - return false; - } - - model.Status = newStatus; - - if (model.Status == OrderStatus.Выдан) - model.DateImplement = DateTime.Now; - else - { - model.DateImplement = viewModel.DateImplement; - } - CheckModel(model); - - if (_orderStorage.Update(model) == null) - { - model.Status--; - _logger.LogWarning("Update operation failed"); - return false; - } - - return true; - } + CheckModel(model); + var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id }); + if (element == null) + { + _logger.LogWarning("Read operation failed"); + return false; + } + if (element.Status != status - 1) + { + _logger.LogWarning("Status change operation failed"); + throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный"); + } + if (element.Status == OrderStatus.Готов) + { + var gift = _giftStorage.GetElement(new GiftSearchModel() { Id = model.GiftId }); + if (gift == null) + { + _logger.LogWarning("Status update to " + status.ToString() + " operation failed. Document not found."); + return false; + } + if (CheckSupply(gift, model.Count) == false) + { + _logger.LogWarning("Status update to " + status.ToString() + " operation failed. Shop supply error."); + return false; + } + } + model.Status = status; + if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now; + _orderStorage.Update(model); + return true; + } public bool TakeOrderInWork(OrderBindingModel model) { @@ -110,27 +179,18 @@ namespace GiftShopBusinessLogic.BusinessLogics { throw new ArgumentNullException(nameof(model)); } - if (!withParams) { return; } - - if (model.GiftId < 0) - { - throw new ArgumentNullException("Некорректный идентификатор изделия", nameof(model.GiftId)); - } - if (model.Count <= 0) { throw new ArgumentNullException("Количество изделий в заказе должно быть больше 0", nameof(model.Count)); } - if (model.Sum <= 0) { throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum)); } - _logger.LogInformation("Order. OrderId:{Id}.Sum:{ Sum}. EngineId: { EngineId}", model.Id, model.Sum, model.GiftId); } } diff --git a/GiftShop/GiftShopBusinessLogic/BusinessLogics/ReportLogic.cs b/GiftShop/GiftShopBusinessLogic/BusinessLogics/ReportLogic.cs index 3137ded..344df20 100644 --- a/GiftShop/GiftShopBusinessLogic/BusinessLogics/ReportLogic.cs +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/ReportLogic.cs @@ -15,19 +15,22 @@ namespace GiftShopBusinessLogic.BusinessLogics private readonly IGiftStorage _giftStorage; private readonly IOrderStorage _orderStorage; - - private readonly AbstractSaveToExcel _saveToExcel; + + private readonly IShopStorage _shopStorage; + + private readonly AbstractSaveToExcel _saveToExcel; private readonly AbstractSaveToWord _saveToWord; private readonly AbstractSaveToPdf _saveToPdf; - public ReportLogic(IGiftStorage giftStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, + public ReportLogic(IGiftStorage giftStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, IShopStorage shopStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf) { _giftStorage = giftStorage; _componentStorage = componentStorage; _orderStorage = orderStorage; + _shopStorage = shopStorage; _saveToExcel = saveToExcel; _saveToWord = saveToWord; @@ -71,11 +74,19 @@ namespace GiftShopBusinessLogic.BusinessLogics Gifts = _giftStorage.GetFullList() }); } - /// - /// Сохранение компонент с указаеним продуктов в файл-Excel - /// - /// - public void SaveGiftComponentToExcelFile(ReportBindingModel model) + // hard + public void SaveShopsToWordFile(ReportBindingModel model) + { + var tmp = _shopStorage.GetFullList(); + _saveToWord.CreateTableDoc(new WordInfo + { + FileName = model.FileName, + Title = "Список магазинов", + Shops = _shopStorage.GetFullList() + }); + } + + public void SaveGiftComponentToExcelFile(ReportBindingModel model) { _saveToExcel.CreateReport(new ExcelInfo { @@ -84,10 +95,7 @@ namespace GiftShopBusinessLogic.BusinessLogics GiftComponents = GetGiftComponent() }); } - /// - /// Сохранение заказов в файл-Pdf - /// - /// + public void SaveOrdersToPdfFile(ReportBindingModel model) { _saveToPdf.CreateDoc(new PdfInfo @@ -99,5 +107,56 @@ namespace GiftShopBusinessLogic.BusinessLogics Orders = GetOrders(model) }); } - } + // + public List GetDatesOrders() + { + return _orderStorage.GetFullList().GroupBy(x => x.DateCreate.Date).Select(x => new ReportDateOrdersViewModel + { + DateOfOrders = x.Key, + Count = x.Count(), + Sum = x.Sum(y => y.Sum) + }).ToList(); + } + public List GetShopsGifts() + { + var shops = _shopStorage.GetFullList(); + var list = new List(); + foreach (var shop in shops) + { + var record = new ReportShopGiftViewModel + { + ShopName = shop.ShopName, + Gifts = new List>(), + TotalCount = 0 + }; + foreach (var gift in shop.ShopGifts) + { + record.Gifts.Add(new Tuple(gift.Value.Item1.GiftName, gift.Value.Item2)); + record.TotalCount += + gift.Value.Item2; + } + list.Add(record); + } + return list; + } + public void SaveShopsGiftsToExcelFile(ReportBindingModel model) + { + _saveToExcel.CreateShopReport(new ExcelInfo + { + FileName = model.FileName, + Title = "Загруженность магазинов", + ShopGifts = GetShopsGifts() + }); + } + public void SaveDatesOrdersToPdfFile(ReportBindingModel model) + { + _saveToPdf.CreateReportDateDoc(new PdfInfo + { + FileName = model.FileName, + Title = "Заказы по датам", + DateOrders = GetDatesOrders() + }); + } + } } diff --git a/GiftShop/GiftShopBusinessLogic/BusinessLogics/ShopLogic.cs b/GiftShop/GiftShopBusinessLogic/BusinessLogics/ShopLogic.cs new file mode 100644 index 0000000..79ed61d --- /dev/null +++ b/GiftShop/GiftShopBusinessLogic/BusinessLogics/ShopLogic.cs @@ -0,0 +1,236 @@ +using Microsoft.Extensions.Logging; +using GiftShopContracts.BindingModels; +using GiftShopContracts.BusinessLogicsContracts; +using GiftShopContracts.SearchModels; +using GiftShopContracts.StoragesContracts; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GiftShopBusinessLogic.BusinessLogics +{ + public class ShopLogic: IShopLogic + { + private readonly ILogger _logger; + private readonly IShopStorage _shopStorage; + public ShopLogic(ILogger logger, IShopStorage ShopStorage) + { + _logger = logger; + _shopStorage = ShopStorage; + } + public bool AddGift(ShopSearchModel model, IGiftModel gift, int quantity) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + if (quantity <= 0) + { + throw new ArgumentException("Количество добавляемого изделия должно быть больше 0", nameof(quantity)); + } + + _logger.LogInformation("AddGiftInShop. ShopName:{ShopName}.Id:{Id}", model.ShopName, model.Id); + var element = _shopStorage.GetElement(model); + + if (element == null) + { + _logger.LogWarning("AddGiftInShop element not found"); + return false; + } + if (element.MaxCapacity - element.ShopGifts.Select(x => x.Value.Item2).Sum() < quantity) + { + throw new ArgumentNullException("Магазин переполнен", nameof(quantity)); + } + + _logger.LogInformation("AddGiftInShop find. Id:{Id}", element.Id); + + if (element.ShopGifts.TryGetValue(gift.Id, out var pair)) + { + element.ShopGifts[gift.Id] = (gift, quantity + pair.Item2); + _logger.LogInformation("AddGiftInShop. Has been added {quantity} {gift} in {ShopName}", quantity, gift.GiftName, element.ShopName); + } + else + { + element.ShopGifts[gift.Id] = (gift, quantity); + _logger.LogInformation("AddGiftInShop. Has been added {quantity} new gift {gift} in {ShopName}", quantity, gift.GiftName, element.ShopName); + } + + _shopStorage.Update(new() + { + Id = element.Id, + ShopAdress = element.ShopAdress, + ShopName = element.ShopName, + OpeningDate = element.OpeningDate, + ShopGifts = element.ShopGifts + }); + return true; + } + + public bool Create(ShopBindingModel model) + { + CheckModel(model); + if (_shopStorage.Insert(model) == null) + { + _logger.LogWarning("Insert 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 MakeSell(IGiftModel gift, int count) + { + return _shopStorage.SellGifts(gift, count); + } + + 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 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 bool MakeSupply(ShopSearchModel model, IGiftModel gift, int count) + { + + if (model == null) + throw new ArgumentNullException(nameof(model)); + if (gift == null) + throw new ArgumentNullException(nameof(gift)); + if (count <= 0) + throw new ArgumentNullException("Количество должно быть положительным числом"); + + ShopViewModel curModel = _shopStorage.GetElement(model); + if (curModel == null) + throw new ArgumentNullException(nameof(curModel)); + var countItems = curModel.ShopGifts.Select(x => x.Value.Item2).Sum(); + if (curModel.MaxCapacity - countItems >= count) + { + if (curModel.ShopGifts.TryGetValue(gift.Id, out var sameDocument)) + { + curModel.ShopGifts[gift.Id] = (gift, sameDocument.Item2 + count); + _logger.LogInformation("Same gift found by supply. Added {0} of {1} in {2} shop", count, gift.GiftName, curModel.ShopName); + } + else + { + curModel.ShopGifts[gift.Id] = (gift, count); + _logger.LogInformation("New gift added by supply. Added {0} of {1} in {2} shop", count, gift.GiftName, curModel.ShopName); + } + _shopStorage.Update(new() + { + Id = curModel.Id, + ShopName = curModel.ShopName, + ShopAdress = curModel.ShopAdress, + OpeningDate = curModel.OpeningDate, + ShopGifts = curModel.ShopGifts, + MaxCapacity = curModel.MaxCapacity + }); + } + else + { + _logger.LogWarning("Required shop is overflowed"); + return false; + } + return true; + } + + public bool Update(ShopBindingModel model) + { + CheckModel(model, false); + + if (string.IsNullOrEmpty(model.ShopName)) + { + throw new ArgumentNullException("Нет названия магазина", nameof(model.ShopName)); + } + + if (_shopStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + + private void CheckModel(ShopBindingModel model, bool withParams = true) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + if (!withParams) + { + return; + } + + if (string.IsNullOrEmpty(model.ShopName)) + { + throw new ArgumentNullException("Нет названия магазина", nameof(model.ShopName)); + } + if (string.IsNullOrEmpty(model.ShopAdress)) + { + throw new ArgumentNullException("Нет адресса магазина", nameof(model.ShopAdress)); + } + if (model.OpeningDate == null) + { + throw new ArgumentNullException("Нет даты открытия магазина", nameof(model.OpeningDate)); + } + _logger.LogInformation("Shop. ShopName:{0}.ShopAddress:{1}. Id: {2}", model.ShopName, model.ShopAdress, model.Id); + var element = _shopStorage.GetElement(new ShopSearchModel + { + ShopName = model.ShopName + }); + + if (element != null && element.Id != model.Id && element.ShopName == model.ShopName) + { + throw new InvalidOperationException("Магазин с таким названием уже есть"); + } + } + } +} diff --git a/GiftShop/GiftShopBusinessLogic/OfficePackage/AbstractSaveToExcel.cs b/GiftShop/GiftShopBusinessLogic/OfficePackage/AbstractSaveToExcel.cs index 5c4cb94..7774242 100644 --- a/GiftShop/GiftShopBusinessLogic/OfficePackage/AbstractSaveToExcel.cs +++ b/GiftShop/GiftShopBusinessLogic/OfficePackage/AbstractSaveToExcel.cs @@ -75,8 +75,72 @@ namespace GiftShopBusinessLogic.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 pc in info.ShopGifts) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = pc.ShopName, + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + foreach (var gift in pc.Gifts) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = gift.Item1, + StyleInfo = + ExcelStyleInfoType.TextWithBroder + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = gift.Item2.ToString(), + StyleInfo = + ExcelStyleInfoType.TextWithBroder + }); + rowIndex++; + } + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Итого", + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = pc.TotalCount.ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + } + SaveExcel(info); + } + /// Создание excel-файла + protected abstract void CreateExcel(ExcelInfo info); /// Добавляем новую ячейку в лист protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams); /// Объединение ячеек diff --git a/GiftShop/GiftShopBusinessLogic/OfficePackage/AbstractSaveToPdf.cs b/GiftShop/GiftShopBusinessLogic/OfficePackage/AbstractSaveToPdf.cs index 95df287..1e3bcf5 100644 --- a/GiftShop/GiftShopBusinessLogic/OfficePackage/AbstractSaveToPdf.cs +++ b/GiftShop/GiftShopBusinessLogic/OfficePackage/AbstractSaveToPdf.cs @@ -52,8 +52,41 @@ namespace GiftShopBusinessLogic.OfficePackage SavePdf(info); } - /// Создание doc-файла - protected abstract void CreatePdf(PdfInfo info); + public void CreateReportDateDoc(PdfInfo info) + { + CreatePdf(info); + CreateParagraph(new PdfParagraph + { + Text = info.Title, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + CreateTable(new List { "3cm", "3cm", "7cm" }); + CreateRow(new PdfRowParameters + { + Texts = new List { "Дата", "Количество", "Сумма" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + foreach (var order in info.DateOrders) + { + CreateRow(new PdfRowParameters + { + Texts = new List { order.DateOfOrders.ToShortDateString(), order.Count.ToString(), order.Sum.ToString() }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + CreateParagraph(new PdfParagraph + { + Text = $"Итого: {info.DateOrders.Sum(x => x.Sum)}\t", + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + SavePdf(info); + } + /// Создание doc-файла + protected abstract void CreatePdf(PdfInfo info); /// Создание параграфа с текстом protected abstract void CreateParagraph(PdfParagraph paragraph); /// Создание таблицы diff --git a/GiftShop/GiftShopBusinessLogic/OfficePackage/AbstractSaveToWord.cs b/GiftShop/GiftShopBusinessLogic/OfficePackage/AbstractSaveToWord.cs index 4024dfe..c23ada1 100644 --- a/GiftShop/GiftShopBusinessLogic/OfficePackage/AbstractSaveToWord.cs +++ b/GiftShop/GiftShopBusinessLogic/OfficePackage/AbstractSaveToWord.cs @@ -37,11 +37,39 @@ namespace GiftShopBusinessLogic.OfficePackage SaveWord(info); } - /// Создание doc-файла - protected abstract void CreateWord(WordInfo info); + public void CreateTableDoc(WordInfo info) + { + CreateWord(info); + List> list = new List>(); + foreach (var shop in info.Shops) + { + var ls = new List + { + shop.ShopName, + shop.ShopAdress, + shop.OpeningDate.ToShortDateString() + }; + list.Add(ls); + } + var wordTable = new WordTable + { + Headers = new List { + "Название", + "Адрес", + "Дата открытия"}, + Columns = 3, + RowText = list + }; + CreateTable(wordTable); + SaveWord(info); + } + /// Создание doc-файла + protected abstract void CreateWord(WordInfo info); /// Создание абзаца с текстом protected abstract void CreateParagraph(WordParagraph paragraph); /// Сохранение файла protected abstract void SaveWord(WordInfo info); - } + + protected abstract void CreateTable(WordTable table); + } } diff --git a/GiftShop/GiftShopBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs b/GiftShop/GiftShopBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs index b5a7d7f..5b0fd58 100644 --- a/GiftShop/GiftShopBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs +++ b/GiftShop/GiftShopBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs @@ -9,5 +9,6 @@ namespace GiftShopBusinessLogic.OfficePackage.HelperModels public string Title { get; set; } = string.Empty; public List GiftComponents { get; set; } = new(); - } + public List ShopGifts { get; set; } = new(); + } } diff --git a/GiftShop/GiftShopBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs b/GiftShop/GiftShopBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs index d6abadd..609808b 100644 --- a/GiftShop/GiftShopBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs +++ b/GiftShop/GiftShopBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs @@ -13,5 +13,6 @@ namespace GiftShopBusinessLogic.OfficePackage.HelperModels public DateTime DateTo { get; set; } public List Orders { get; set; } = new(); - } + public List DateOrders { get; set; } = new(); + } } diff --git a/GiftShop/GiftShopBusinessLogic/OfficePackage/HelperModels/WordInfo.cs b/GiftShop/GiftShopBusinessLogic/OfficePackage/HelperModels/WordInfo.cs index 4c3859a..0a690de 100644 --- a/GiftShop/GiftShopBusinessLogic/OfficePackage/HelperModels/WordInfo.cs +++ b/GiftShop/GiftShopBusinessLogic/OfficePackage/HelperModels/WordInfo.cs @@ -9,5 +9,7 @@ namespace GiftShopBusinessLogic.OfficePackage.HelperModels public string Title { get; set; } = string.Empty; public List Gifts { get; set; } = new(); - } + + public List Shops { get; set; } = new(); + } } diff --git a/GiftShop/GiftShopBusinessLogic/OfficePackage/HelperModels/WordTable.cs b/GiftShop/GiftShopBusinessLogic/OfficePackage/HelperModels/WordTable.cs new file mode 100644 index 0000000..7b85656 --- /dev/null +++ b/GiftShop/GiftShopBusinessLogic/OfficePackage/HelperModels/WordTable.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using System.Text; +using System.Threading.Tasks; + +namespace GiftShopBusinessLogic.OfficePackage.HelperModels +{ + public class WordTable + { + public List Headers { get; set; } = new(); + public List> RowText { get; set; } = new(); + public int Columns { get; set; } + } +} diff --git a/GiftShop/GiftShopBusinessLogic/OfficePackage/Implements/SaveToWord.cs b/GiftShop/GiftShopBusinessLogic/OfficePackage/Implements/SaveToWord.cs index 1e2551a..a679229 100644 --- a/GiftShop/GiftShopBusinessLogic/OfficePackage/Implements/SaveToWord.cs +++ b/GiftShop/GiftShopBusinessLogic/OfficePackage/Implements/SaveToWord.cs @@ -113,7 +113,85 @@ namespace GiftShopBusinessLogic.OfficePackage.Implements } _docBody.AppendChild(CreateSectionProperties()); _wordDocument.MainDocumentPart!.Document.Save(); - _wordDocument.Close(); + _wordDocument.Dispose(); } - } + // + protected override void CreateTable(WordTable table) + { + if (_docBody == null || table == null) + { + return; + } + Table docTable = new Table(); + TableProperties tableProps = new TableProperties( + new TopBorder + { + Val = new EnumValue(BorderValues.Single), + Size = 12 + }, + new BottomBorder + { + Val = new EnumValue(BorderValues.Single), + Size = 12 + }, + new LeftBorder + { + Val = new EnumValue(BorderValues.Single), + Size = 12 + }, + new RightBorder + { + Val = new EnumValue(BorderValues.Single), + Size = 12 + }, + new InsideHorizontalBorder + { + Val = new EnumValue(BorderValues.Single), + Size = 12 + }, + new InsideVerticalBorder + { + Val = new EnumValue(BorderValues.Single), + Size = 12 + }); + docTable.AppendChild(tableProps); + TableGrid tableGrid = new TableGrid(); + for (int i = 0; i < table.Columns; i++) + { + tableGrid.AppendChild(new GridColumn()); + } + docTable.AppendChild(tableGrid); + TableRow tableRow = new TableRow(); + foreach (var text in table.Headers) + { + tableRow.AppendChild(CreateTableCell(text)); + } + docTable.AppendChild(tableRow); + int height = table.RowText.Count; + int width = table.Columns; + for (int i = 0; i < height; i++) + { + tableRow = new TableRow(); + for (int j = 0; j < width; j++) + { + var element = table.RowText[i][j]; + tableRow.AppendChild(CreateTableCell(element)); + } + docTable.AppendChild(tableRow); + } + + _docBody.AppendChild(docTable); + } + + private TableCell CreateTableCell(string element) + { + var tableParagraph = new Paragraph(); + var run = new Run(); + run.AppendChild(new Text { Text = element }); + tableParagraph.AppendChild(run); + var tableCell = new TableCell(); + tableCell.AppendChild(tableParagraph); + return tableCell; + } + } } diff --git a/GiftShop/GiftShopContracts/BindingModels/ShopBindingModel.cs b/GiftShop/GiftShopContracts/BindingModels/ShopBindingModel.cs new file mode 100644 index 0000000..a50a91c --- /dev/null +++ b/GiftShop/GiftShopContracts/BindingModels/ShopBindingModel.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using GiftShopDataModels.Models; + +namespace GiftShopContracts.BindingModels +{ + public class ShopBindingModel : IShopModel + { + public int Id { get; set; } + public string ShopName { get; set; } = string.Empty; + public string ShopAdress { get; set; } = string.Empty; + public DateTime OpeningDate { get; set; } = DateTime.Now; + public int MaxCapacity { get; set; } + public Dictionary ShopGifts { get; set; } = new(); + } +} diff --git a/GiftShop/GiftShopContracts/BusinessLogicsContracts/IReportLogic.cs b/GiftShop/GiftShopContracts/BusinessLogicsContracts/IReportLogic.cs index b22164e..df665a8 100644 --- a/GiftShop/GiftShopContracts/BusinessLogicsContracts/IReportLogic.cs +++ b/GiftShop/GiftShopContracts/BusinessLogicsContracts/IReportLogic.cs @@ -5,31 +5,24 @@ namespace GiftShopContracts.BusinessLogicsContracts { public interface IReportLogic { - /// - /// Получение списка компонент с указанием, в каких изделиях используются - /// - /// List GetGiftComponent(); - /// - /// Получение списка заказов за определенный период - /// - /// - /// + List GetOrders(ReportBindingModel model); - /// - /// Сохранение компонент в файл-Word - /// - /// - void SaveGiftsToWordFile(ReportBindingModel model); - /// - /// Сохранение компонент с указаеним продуктов в файл-Excel - /// - /// - void SaveGiftComponentToExcelFile(ReportBindingModel model); - /// - /// Сохранение заказов в файл-Pdf - /// - /// - void SaveOrdersToPdfFile(ReportBindingModel model); - } + + List GetDatesOrders(); + + List GetShopsGifts(); + + void SaveGiftsToWordFile(ReportBindingModel model); + + void SaveShopsToWordFile(ReportBindingModel model); + + void SaveGiftComponentToExcelFile(ReportBindingModel model); + + void SaveShopsGiftsToExcelFile(ReportBindingModel model); + + void SaveOrdersToPdfFile(ReportBindingModel model); + + void SaveDatesOrdersToPdfFile(ReportBindingModel model); + } } diff --git a/GiftShop/GiftShopContracts/BusinessLogicsContracts/IShopLogic.cs b/GiftShop/GiftShopContracts/BusinessLogicsContracts/IShopLogic.cs new file mode 100644 index 0000000..d13271e --- /dev/null +++ b/GiftShop/GiftShopContracts/BusinessLogicsContracts/IShopLogic.cs @@ -0,0 +1,24 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.ViewModels; +using GiftShopContracts.SearchModels; +using GiftShopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GiftShopContracts.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 AddGift(ShopSearchModel model, IGiftModel gift, int quantity); + bool MakeSupply(ShopSearchModel model, IGiftModel gift, int count); + bool MakeSell(IGiftModel gift, int count); + } +} diff --git a/GiftShop/GiftShopContracts/SearchModels/ShopSearchModel.cs b/GiftShop/GiftShopContracts/SearchModels/ShopSearchModel.cs new file mode 100644 index 0000000..8066886 --- /dev/null +++ b/GiftShop/GiftShopContracts/SearchModels/ShopSearchModel.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GiftShopContracts.SearchModels +{ + public class ShopSearchModel + { + public int? Id { get; set; } + public string? ShopName { get; set; } + } +} diff --git a/GiftShop/GiftShopContracts/StoragesContracts/IShopStorage.cs b/GiftShop/GiftShopContracts/StoragesContracts/IShopStorage.cs new file mode 100644 index 0000000..0b4ca21 --- /dev/null +++ b/GiftShop/GiftShopContracts/StoragesContracts/IShopStorage.cs @@ -0,0 +1,23 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GiftShopContracts.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); + public bool SellGifts(IGiftModel model, int count); + } +} diff --git a/GiftShop/GiftShopContracts/ViewModels/ReportDateOrdersViewModel.cs b/GiftShop/GiftShopContracts/ViewModels/ReportDateOrdersViewModel.cs new file mode 100644 index 0000000..27ab7ef --- /dev/null +++ b/GiftShop/GiftShopContracts/ViewModels/ReportDateOrdersViewModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GiftShopContracts.ViewModels +{ + public class ReportDateOrdersViewModel + { + public DateTime DateOfOrders { get; set; } + public int Count { get; set; } + public double Sum { get; set; } + } +} diff --git a/GiftShop/GiftShopContracts/ViewModels/ReportShopIceCreamViewModel.cs b/GiftShop/GiftShopContracts/ViewModels/ReportShopIceCreamViewModel.cs new file mode 100644 index 0000000..b571ac6 --- /dev/null +++ b/GiftShop/GiftShopContracts/ViewModels/ReportShopIceCreamViewModel.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GiftShopContracts.ViewModels +{ + public class ReportShopGiftViewModel + { + public string ShopName { get; set; } = string.Empty; + public int TotalCount { get; set; } + public List> Gifts { get; set; } = new(); + } +} diff --git a/GiftShop/GiftShopContracts/ViewModels/ShopViewModel.cs b/GiftShop/GiftShopContracts/ViewModels/ShopViewModel.cs new file mode 100644 index 0000000..5ba49d1 --- /dev/null +++ b/GiftShop/GiftShopContracts/ViewModels/ShopViewModel.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using GiftShopDataModels.Models; + +namespace GiftShopContracts.ViewModels +{ + public class ShopViewModel : IShopModel + { + public Dictionary ShopGifts { get; set; } = new(); + public int Id { get; set; } + + [DisplayName("Название магазина")] + public string ShopName { get; set; } = string.Empty; + + [DisplayName("Адрес магазина")] + public string ShopAdress { get; set; } = string.Empty; + + [DisplayName("Дата открытия")] + public DateTime OpeningDate { get; set; } = DateTime.Now; + + [DisplayName("Вместимость")] + public int MaxCapacity { get; set; } + } +} diff --git a/GiftShop/GiftShopDataModels/Models/IShopModel.cs b/GiftShop/GiftShopDataModels/Models/IShopModel.cs new file mode 100644 index 0000000..5db1556 --- /dev/null +++ b/GiftShop/GiftShopDataModels/Models/IShopModel.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GiftShopDataModels.Models +{ + public interface IShopModel : IId + { + public int Id { get; set; } + public string ShopName { get; } + public string ShopAdress { get; } + DateTime OpeningDate { get; } + Dictionary ShopGifts { get; } + int MaxCapacity { get; } + } +} diff --git a/GiftShop/GiftShopDatabaseImplement/GiftShopDatabase.cs b/GiftShop/GiftShopDatabaseImplement/GiftShopDatabase.cs index 0b1a140..6aeea5a 100644 --- a/GiftShop/GiftShopDatabaseImplement/GiftShopDatabase.cs +++ b/GiftShop/GiftShopDatabaseImplement/GiftShopDatabase.cs @@ -9,7 +9,7 @@ namespace GiftShopDatabaseImplement { if (optionsBuilder.IsConfigured == false) { - optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-Arkad1y;Initial Catalog=GiftShopDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); + optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-Arkad1y;Initial Catalog=GiftShopDataBaseHard;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); } base.OnConfiguring(optionsBuilder); } @@ -21,5 +21,9 @@ namespace GiftShopDatabaseImplement public virtual DbSet GiftComponents { set; get; } public virtual DbSet Orders { set; get; } + + public virtual DbSet Shops { set; get; } + + public virtual DbSet ShopGifts { set; get;} } } diff --git a/GiftShop/GiftShopDatabaseImplement/Implements/ShopStorage.cs b/GiftShop/GiftShopDatabaseImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..9a5b7ff --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Implements/ShopStorage.cs @@ -0,0 +1,148 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.StoragesContracts; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using GiftShopDatabaseImplement.Models; +using Microsoft.EntityFrameworkCore; + +namespace GiftShopDatabaseImplement.Implements +{ + public class ShopStorage : IShopStorage + { + public ShopViewModel? Delete(ShopBindingModel model) + { + using var context = new GiftShopDatabase(); + var element = context.Shops.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + context.Shops.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } + + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) + { + return null; + } + using var context = new GiftShopDatabase(); + return context.Shops + .Include(x => x.Gifts) + .ThenInclude(x => x.Gift) + .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) + ?.GetViewModel; + } + + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName)) + { + return new(); + } + using var context = new GiftShopDatabase(); + return context.Shops + .Include(x => x.Gifts) + .ThenInclude(x => x.Gift) + .Select(x => x.GetViewModel) + .Where(x => x.ShopName.Contains(model.ShopName ?? string.Empty)) + .ToList(); + } + + public List GetFullList() + { + using var context = new GiftShopDatabase(); + return context.Shops + .Include(x => x.Gifts) + .ThenInclude(x => x.Gift) + .Select(x => x.GetViewModel) + .ToList(); + } + + public ShopViewModel? Insert(ShopBindingModel model) + { + using var context = new GiftShopDatabase(); + try + { + var newShop = Shop.Create(context, model); + if (newShop == null) + { + return null; + } + if (context.Shops.Any(x => x.ShopName == newShop.ShopName)) + { + throw new Exception("Не должно быть два магазина с одним названием"); + } + context.Shops.Add(newShop); + context.SaveChanges(); + return newShop.GetViewModel; + } + catch + { + throw; + } + } + + public ShopViewModel? Update(ShopBindingModel model) + { + using var context = new GiftShopDatabase(); + var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop == null) + { + return null; + } + try + { + if (context.Shops.Any(x => (x.ShopName == model.ShopName && x.Id != model.Id))) + { + throw new Exception("Не должно быть два магазина с одним названием"); + } + shop.Update(model); + shop.UpdateGifts(context, model); + context.SaveChanges(); + return shop.GetViewModel; + } + catch + { + throw; + } + } + public bool SellGifts(IGiftModel model, int count) + { + if (model == null) + return false; + using var context = new GiftShopDatabase(); + using var transaction = context.Database.BeginTransaction(); + List lst = new List(); + foreach(var el in context.ShopGifts.Where(x => x.GiftId == model.Id)) + { + int dif = count; + if (el.Count < dif) + dif = el.Count; + el.Count -= dif; + count -= dif; + if(el.Count == 0) + { + lst.Add(el); + } + if (count == 0) + break; + } + if (count > 0) + { + transaction.Rollback(); + return false; + } + foreach(var el in lst) + { + context.ShopGifts.Remove(el); + } + context.SaveChanges(); + transaction.Commit(); + return true; + } + } +} diff --git a/GiftShop/GiftShopDatabaseImplement/Models/Shop.cs b/GiftShop/GiftShopDatabaseImplement/Models/Shop.cs new file mode 100644 index 0000000..f8c338e --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Models/Shop.cs @@ -0,0 +1,115 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GiftShopDatabaseImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; set; } + [Required] + public string ShopName { get; private set; } + [Required] + public string ShopAdress { get; private set; } + [Required] + public DateTime OpeningDate { get; private set; } + [Required] + public int MaxCapacity { get; private set; } + private Dictionary? _shopGifts = + null; + [NotMapped] + public Dictionary ShopGifts + { + get + { + if (_shopGifts == null) + { + _shopGifts = Gifts + .ToDictionary(x => x.GiftId, x => + (x.Gift as IGiftModel, x.Count)); + } + return _shopGifts; + } + } + [ForeignKey("ShopId")] + public virtual List Gifts { get; set; } = new(); + public static Shop? Create(GiftShopDatabase context, ShopBindingModel model) + { + if (model == null) + return null; + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + ShopAdress = model.ShopAdress, + OpeningDate = model.OpeningDate, + MaxCapacity = model.MaxCapacity, + Gifts = model.ShopGifts.Select(x => new ShopGift + { + Gift = context.Gifts.First(y => y.Id == x.Key), + Count = x.Value.Item2 + }).ToList() + }; + } + + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + ShopAdress = model.ShopAdress; + OpeningDate = model.OpeningDate; + MaxCapacity = model.MaxCapacity; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + ShopAdress = ShopAdress, + OpeningDate = OpeningDate, + ShopGifts = ShopGifts, + MaxCapacity = MaxCapacity + }; + + public void UpdateGifts(GiftShopDatabase context, ShopBindingModel model) + { + var shopGifts = context.ShopGifts.Where(rec => + rec.ShopId == model.Id).ToList(); + if (shopGifts != null && shopGifts.Count > 0) + { + context.ShopGifts.RemoveRange(shopGifts.Where(rec => !model.ShopGifts.ContainsKey(rec.GiftId))); + + context.SaveChanges(); + foreach (var updateGift in shopGifts) + { + updateGift.Count = + model.ShopGifts[updateGift.GiftId].Item2; + model.ShopGifts.Remove(updateGift.GiftId); + } + context.SaveChanges(); + } + var shop = context.Shops.First(x => x.Id == Id); + foreach (var pc in model.ShopGifts) + { + context.ShopGifts.Add(new ShopGift + { + Shop = shop, + Gift = context.Gifts.First(x => x.Id == pc.Key), + Count = pc.Value.Item2 + }); + context.SaveChanges(); + } + _shopGifts = null; + } + } +} diff --git a/GiftShop/GiftShopDatabaseImplement/Models/ShopGift.cs b/GiftShop/GiftShopDatabaseImplement/Models/ShopGift.cs new file mode 100644 index 0000000..16351e5 --- /dev/null +++ b/GiftShop/GiftShopDatabaseImplement/Models/ShopGift.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GiftShopDatabaseImplement.Models +{ + public class ShopGift + { + public int Id { get; set; } + [Required] + public int GiftId { get; set; } + [Required] + public int ShopId { get; set; } + [Required] + public int Count { get; set; } + public virtual Shop Shop { get; set; } = new(); + public virtual Gift Gift { get; set; } = new(); + } +} diff --git a/GiftShop/GiftShopFileImplement/DataFileSingleton.cs b/GiftShop/GiftShopFileImplement/DataFileSingleton.cs index f80089e..766f5d1 100644 --- a/GiftShop/GiftShopFileImplement/DataFileSingleton.cs +++ b/GiftShop/GiftShopFileImplement/DataFileSingleton.cs @@ -12,13 +12,16 @@ namespace GiftShopFileImplement private readonly string OrderFileName = "Order.xml"; private readonly string GiftFileName = "Gift.xml"; + private readonly string ShopFileName = "Shops.xml"; - public List Components { get; private set; } + public List Components { get; private set; } public List Orders { get; private set; } public List Gifts { get; private set; } + public List Shops { get; private set; } + public static DataFileSingleton GetInstance() { if (instance == null) @@ -34,12 +37,15 @@ namespace GiftShopFileImplement public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); - private DataFileSingleton() + public void SaveShops() => SaveData(Shops, OrderFileName, "Shops", x => x.GetXElement); + + private DataFileSingleton() { Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Gifts = LoadData(GiftFileName, "Gift", x => Gift.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; - } + Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!; + } private static List? LoadData(string filename, string xmlNodeName, Func selectFunction) { diff --git a/GiftShop/GiftShopFileImplement/Implements/ShopStorage.cs b/GiftShop/GiftShopFileImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..d176a07 --- /dev/null +++ b/GiftShop/GiftShopFileImplement/Implements/ShopStorage.cs @@ -0,0 +1,128 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.StoragesContracts; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using GiftShopFileImplement; +using GiftShopFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GiftShopFileImplement.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 component = _source.Shops.FirstOrDefault(x => x.Id ==model.Id); + if (component == null) + { + return null; + } + component.Update(model); + _source.SaveShops(); + return component.GetViewModel; + } + public ShopViewModel? Delete(ShopBindingModel model) + { + var element = _source.Shops.FirstOrDefault(x => x.Id == + model.Id); + if (element != null) + { + _source.Shops.Remove(element); + _source.SaveShops(); + return element.GetViewModel; + } + return null; + } + + public bool CheckAvailability(int giftId, int count) + { + int minus = _source.Shops.Select(x => x.ShopGifts.Select(y => (y.Value.Item1.Id == giftId ? y.Value.Item2 : 0)).Sum()).Sum(); + count -= minus; + return count <= 0; + } + + public bool SellGifts(IGiftModel model, int count) + { + var gift = _source.Gifts.FirstOrDefault(x => x.Id == model.Id); + + if (gift == null || !CheckAvailability(gift.Id, count)) + { + return false; + } + + for (int i = 0; i < _source.Shops.Count; i++) + { + var shop = _source.Shops[i]; + var gifts = shop.ShopGifts; + + foreach (var gifty in gifts.Where(x => x.Value.Item1.Id == gift.Id)) + { + var min = Math.Min(gifty.Value.Item2, count); + gifts[gifty.Value.Item1.Id] = (gifty.Value.Item1, gifty.Value.Item2 - min); + count -= min; + + if (count <= 0) + { + break; + } + } + + shop.Update(new ShopBindingModel + { + Id = shop.Id, + ShopName = shop.ShopName, + ShopAdress = shop.ShopAdress, + OpeningDate = shop.OpeningDate, + MaxCapacity = shop.MaxCapacity, + ShopGifts = gifts + }); + } + _source.SaveShops(); + return true; + } + + } +} diff --git a/GiftShop/GiftShopFileImplement/Models/Shop.cs b/GiftShop/GiftShopFileImplement/Models/Shop.cs new file mode 100644 index 0000000..70daf3d --- /dev/null +++ b/GiftShop/GiftShopFileImplement/Models/Shop.cs @@ -0,0 +1,104 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using System.Xml.Linq; + +namespace GiftShopFileImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; set; } + public string ShopName { get; private set; } + public string ShopAdress { get; private set; } + public DateTime OpeningDate { get; private set; } + public Dictionary Gifts { get; private set; } = new(); + + private Dictionary? _shopGifts = null; + public Dictionary ShopGifts + { + get + { + if (_shopGifts == null) + { + var source = DataFileSingleton.GetInstance(); + _shopGifts = Gifts.ToDictionary(x => x.Key, y => + ((source.Gifts.FirstOrDefault(z => z.Id == y.Key) as IGiftModel)!, + y.Value)); + } + return _shopGifts; + } + } + + public int MaxCapacity { get; private set; } + + public static Shop? Create(ShopBindingModel model) + { + if (model == null) + return null; + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + ShopAdress = model.ShopAdress, + OpeningDate = model.OpeningDate, + MaxCapacity = model.MaxCapacity, + Gifts = model.ShopGifts.ToDictionary(x => x.Key, x => x.Value.Item2) + }; + } + + public static Shop? Create(XElement element) + { + if (element == null) + { + return null; + } + return new Shop() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ShopName = element.Element("ShopName")!.Value, + ShopAdress = element.Element("ShopAdress")!.Value, + MaxCapacity = Convert.ToInt32(element.Element("MaxCapacity")!.Value), + OpeningDate = Convert.ToDateTime(element.Element("OpeningDate")!.Value), + Gifts = element.Element("ShopGifts")!.Elements("ShopGifts").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; + ShopAdress = model.ShopAdress; + OpeningDate = model.OpeningDate; + MaxCapacity = model.MaxCapacity; + if (model.ShopGifts.Count > 0) + { + Gifts = model.ShopGifts.ToDictionary(x => x.Key, x => x.Value.Item2); + _shopGifts = null; + } + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + ShopAdress = ShopAdress, + OpeningDate = OpeningDate, + MaxCapacity = MaxCapacity, + ShopGifts = ShopGifts + }; + + public XElement GetXElement => new("Shop", + new XAttribute("Id", Id), + new XElement("ShopName", ShopName), + new XElement("ShopAdress", ShopAdress), + new XElement("OpeningDate", OpeningDate), + new XElement("MaxCapacity", MaxCapacity), + new XElement("Gifts", Gifts.Select(x => new XElement("Gifts", + new XElement("Key", x.Key), + new XElement("Value", x.Value))).ToArray())); + } +} diff --git a/GiftShop/GiftShopListImplement/DataListSingleton.cs b/GiftShop/GiftShopListImplement/DataListSingleton.cs index 735e678..99d7f02 100644 --- a/GiftShop/GiftShopListImplement/DataListSingleton.cs +++ b/GiftShop/GiftShopListImplement/DataListSingleton.cs @@ -8,12 +8,14 @@ namespace GiftShopListImplement public List Components { get; set; } public List Orders { get; set; } public List Gifts { get; set; } + public List Shops { get; set; } private DataListSingleton() { Components = new List(); Orders = new List(); Gifts = new List(); + Shops = new List(); } public static DataListSingleton GetInstance() { diff --git a/GiftShop/GiftShopListImplement/Implements/ShopStorage.cs b/GiftShop/GiftShopListImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..e7b6acd --- /dev/null +++ b/GiftShop/GiftShopListImplement/Implements/ShopStorage.cs @@ -0,0 +1,170 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.SearchModels; +using GiftShopContracts.StoragesContracts; +using GiftShopContracts.ViewModels; +using GiftShopListImplement.Models; +using GiftShopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Reflection; + +namespace GiftShopListImplement.Implements +{ + public class ShopStorage : IShopStorage + { + private readonly DataListSingleton _source; + public ShopStorage() + { + _source = DataListSingleton.GetInstance(); + } + 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 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 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 List GetFullList() + { + var result = new List(); + + foreach (var shop in _source.Shops) + { + result.Add(shop.GetViewModel); + } + + return result; + } + + 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 bool CheckAvailability(int giftId, int count) + { + int minus = _source.Shops.Select(x => x.ShopGifts.Select(y => (y.Value.Item1.Id == giftId ? y.Value.Item2 : 0)).Sum()).Sum(); + count -= minus; + return count <= 0; + } + public bool SellGifts(IGiftModel model, int count) + { + + var gift = _source.Gifts.FirstOrDefault(x => x.Id == model.Id); + + if (gift == null || !CheckAvailability(gift.Id, count)) + { + return false; + } + + for (int i = 0; i < _source.Shops.Count; i++) + { + var shop = _source.Shops[i]; + var gifts = shop.ShopGifts; + + foreach (var shopgift in gifts.Where(x => x.Value.Item1.Id == gift.Id)) + { + var min = Math.Min(shopgift.Value.Item2, count); + gifts[shopgift.Value.Item1.Id] = (shopgift.Value.Item1, shopgift.Value.Item2 - min); + count -= min; + + if (count <= 0) + { + break; + } + } + + shop.Update(new ShopBindingModel + { + Id = shop.Id, + ShopName = shop.ShopName, + ShopAdress = shop.ShopAdress, + OpeningDate = shop.OpeningDate, + MaxCapacity = shop.MaxCapacity, + ShopGifts = gifts + }); + } + return true; + } + } +} diff --git a/GiftShop/GiftShopListImplement/Models/Shop.cs b/GiftShop/GiftShopListImplement/Models/Shop.cs new file mode 100644 index 0000000..e0be7a4 --- /dev/null +++ b/GiftShop/GiftShopListImplement/Models/Shop.cs @@ -0,0 +1,64 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GiftShopListImplement.Models +{ + public class Shop : IShopModel + { + public int Id { get; set; } + public string ShopName { get; private set; } = string.Empty; + public string ShopAdress { get; private set; } = string.Empty; + + public DateTime OpeningDate { get; private set; } + + public int MaxCapacity { get; private set; } + + public Dictionary ShopGifts { get; private set; } = new(); + + public static Shop? Create(ShopBindingModel? model) + { + if (model == null) + { + return null; + } + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + ShopAdress = model.ShopAdress, + OpeningDate = model.OpeningDate, + MaxCapacity = model.MaxCapacity, + ShopGifts = new() + }; + } + + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + ShopName = model.ShopName; + ShopAdress = model.ShopAdress; + OpeningDate = model.OpeningDate; + MaxCapacity = model.MaxCapacity; + ShopGifts = model.ShopGifts; + } + + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + ShopAdress = ShopAdress, + OpeningDate = OpeningDate, + MaxCapacity = MaxCapacity, + ShopGifts = ShopGifts + }; + } +} diff --git a/GiftShop/GiftShopView/FormMain.Designer.cs b/GiftShop/GiftShopView/FormMain.Designer.cs index 925cc18..c90673d 100644 --- a/GiftShop/GiftShopView/FormMain.Designer.cs +++ b/GiftShop/GiftShopView/FormMain.Designer.cs @@ -20,190 +20,267 @@ base.Dispose(disposing); } - #region Windows Form Designer generated code + #region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - menuStrip = new MenuStrip(); - справочникиToolStripMenuItem = new ToolStripMenuItem(); - компонентыToolStripMenuItem = new ToolStripMenuItem(); - изделияToolStripMenuItem = new ToolStripMenuItem(); - dataGridView = new DataGridView(); - buttonCreateOrder = new Button(); - buttonTakeOrderInWork = new Button(); - buttonOrderReady = new Button(); - buttonIssuedOrder = new Button(); - buttonRef = new Button(); - отчётыToolStripMenuItem = new ToolStripMenuItem(); - списокКомпонентовToolStripMenuItem = new ToolStripMenuItem(); - компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); - списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); - menuStrip.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - SuspendLayout(); - // - // menuStrip - // - menuStrip.ImageScalingSize = new Size(20, 20); - menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem }); - menuStrip.Location = new Point(0, 0); - menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(1367, 28); - menuStrip.TabIndex = 0; - menuStrip.Text = "menuStrip1"; - // - // справочникиToolStripMenuItem - // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem }); - справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; - справочникиToolStripMenuItem.Size = new Size(117, 24); - справочникиToolStripMenuItem.Text = "Справочники"; - // - // компонентыToolStripMenuItem - // - компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(224, 26); - компонентыToolStripMenuItem.Text = "Компоненты"; - компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; - // - // изделияToolStripMenuItem - // - изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; - изделияToolStripMenuItem.Size = new Size(224, 26); - изделияToolStripMenuItem.Text = "Изделия"; - изделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; - // - // dataGridView - // - dataGridView.BackgroundColor = SystemColors.ControlLightLight; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.Location = new Point(12, 41); - dataGridView.Name = "dataGridView"; - dataGridView.RowHeadersWidth = 51; - dataGridView.RowTemplate.Height = 29; - dataGridView.Size = new Size(1123, 423); - dataGridView.TabIndex = 1; - // - // buttonCreateOrder - // - buttonCreateOrder.Location = new Point(1155, 67); - buttonCreateOrder.Name = "buttonCreateOrder"; - buttonCreateOrder.Size = new Size(189, 41); - buttonCreateOrder.TabIndex = 2; - buttonCreateOrder.Text = "Создать заказ"; - buttonCreateOrder.UseVisualStyleBackColor = true; - buttonCreateOrder.Click += ButtonCreateOrder_Click; - // - // buttonTakeOrderInWork - // - buttonTakeOrderInWork.Location = new Point(1155, 136); - buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; - buttonTakeOrderInWork.Size = new Size(189, 41); - buttonTakeOrderInWork.TabIndex = 3; - buttonTakeOrderInWork.Text = "Отдать на выполнение"; - buttonTakeOrderInWork.UseVisualStyleBackColor = true; - buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; - // - // buttonOrderReady - // - buttonOrderReady.Location = new Point(1155, 211); - buttonOrderReady.Name = "buttonOrderReady"; - buttonOrderReady.Size = new Size(189, 41); - buttonOrderReady.TabIndex = 4; - buttonOrderReady.Text = "Заказ готов"; - buttonOrderReady.UseVisualStyleBackColor = true; - buttonOrderReady.Click += ButtonOrderReady_Click; - // - // buttonIssuedOrder - // - buttonIssuedOrder.Location = new Point(1155, 290); - buttonIssuedOrder.Name = "buttonIssuedOrder"; - buttonIssuedOrder.Size = new Size(189, 41); - buttonIssuedOrder.TabIndex = 5; - buttonIssuedOrder.Text = "Заказ выдан"; - buttonIssuedOrder.UseVisualStyleBackColor = true; - buttonIssuedOrder.Click += ButtonIssuedOrder_Click; - // - // buttonRef - // - buttonRef.Location = new Point(1155, 356); - buttonRef.Name = "buttonRef"; - buttonRef.Size = new Size(189, 41); - buttonRef.TabIndex = 6; - buttonRef.Text = "Обновить список"; - buttonRef.UseVisualStyleBackColor = true; - buttonRef.Click += ButtonRef_Click; - // - // отчётыToolStripMenuItem - // - отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem }); - отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; - отчётыToolStripMenuItem.Size = new Size(73, 24); - отчётыToolStripMenuItem.Text = "Отчёты"; - // - // списокКомпонентовToolStripMenuItem - // - списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem"; - списокКомпонентовToolStripMenuItem.Size = new Size(276, 26); - списокКомпонентовToolStripMenuItem.Text = "Список компонентов"; - списокКомпонентовToolStripMenuItem.Click += new System.EventHandler(this.ComponentsToolStripMenuItem_Click); - // - // компонентыПоИзделиямToolStripMenuItem - // - компонентыПоИзделиямToolStripMenuItem.Name = "компонентыПоИзделиямToolStripMenuItem"; - компонентыПоИзделиямToolStripMenuItem.Size = new Size(276, 26); - компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям"; - компонентыПоИзделиямToolStripMenuItem.Click += new System.EventHandler(this.ComponentGiftsToolStripMenuItem_Click); - // - // списокЗаказовToolStripMenuItem - // - списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; - списокЗаказовToolStripMenuItem.Size = new Size(276, 26); - списокЗаказовToolStripMenuItem.Text = "Список заказов"; - списокЗаказовToolStripMenuItem.Click += new System.EventHandler(this.OrdersToolStripMenuItem_Click); - // - // FormMain - // - AutoScaleDimensions = new SizeF(8F, 20F); - AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1367, 471); - Controls.Add(buttonRef); - Controls.Add(buttonIssuedOrder); - Controls.Add(buttonOrderReady); - Controls.Add(buttonTakeOrderInWork); - Controls.Add(buttonCreateOrder); - Controls.Add(dataGridView); - Controls.Add(menuStrip); - MainMenuStrip = menuStrip; - Name = "FormMain"; - Text = "Магазин подарков"; - Load += FormMain_Load; - menuStrip.ResumeLayout(false); - menuStrip.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - ResumeLayout(false); - PerformLayout(); - } + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + menuStrip = new MenuStrip(); + справочники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(); + dataGridView = new DataGridView(); + buttonCreateOrder = new Button(); + buttonTakeOrderInWork = new Button(); + buttonOrderReady = new Button(); + buttonIssuedOrder = new Button(); + buttonRef = new Button(); + shopReplenishment = new Button(); + списокМагазиновToolStripMenuItem = new ToolStripMenuItem(); + подаркиПоМагазинамToolStripMenuItem = new ToolStripMenuItem(); + заказыПоДатамToolStripMenuItem = new ToolStripMenuItem(); + menuStrip.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(20, 20); + menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчетыToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Padding = new Padding(8, 2, 0, 2); + menuStrip.Size = new Size(1709, 33); + menuStrip.TabIndex = 0; + menuStrip.Text = "menuStrip1"; + // + // справочникиToolStripMenuItem + // + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, магазиныToolStripMenuItem, поставкиToolStripMenuItem, продажиToolStripMenuItem }); + справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; + справочникиToolStripMenuItem.Size = new Size(139, 29); + справочникиToolStripMenuItem.Text = "Справочники"; + // + // компонентыToolStripMenuItem + // + компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; + компонентыToolStripMenuItem.Size = new Size(218, 34); + компонентыToolStripMenuItem.Text = "Компоненты"; + компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; + // + // изделияToolStripMenuItem + // + изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; + изделияToolStripMenuItem.Size = new Size(218, 34); + изделияToolStripMenuItem.Text = "Изделия"; + изделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; + // + // магазиныToolStripMenuItem + // + магазиныToolStripMenuItem.Name = "магазиныToolStripMenuItem"; + магазиныToolStripMenuItem.Size = new Size(218, 34); + магазиныToolStripMenuItem.Text = "Магазины"; + магазиныToolStripMenuItem.Click += МагазиныToolStripMenuItem_Click; + // + // поставкиToolStripMenuItem + // + поставкиToolStripMenuItem.Name = "поставкиToolStripMenuItem"; + поставкиToolStripMenuItem.Size = new Size(218, 34); + поставкиToolStripMenuItem.Text = "Поставки"; + поставкиToolStripMenuItem.Click += поставкиToolStripMenuItem_Click; + // + // продажиToolStripMenuItem + // + продажиToolStripMenuItem.Name = "продажиToolStripMenuItem"; + продажиToolStripMenuItem.Size = new Size(218, 34); + продажиToolStripMenuItem.Text = "Продажи"; + продажиToolStripMenuItem.Click += продажиToolStripMenuItem_Click; + // + // отчетыToolStripMenuItem + // + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, списокИзделийToolStripMenuItem, списокЗаказовToolStripMenuItem, списокМагазиновToolStripMenuItem, подаркиПоМагазинамToolStripMenuItem, заказыПоДатамToolStripMenuItem }); + отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; + отчетыToolStripMenuItem.Size = new Size(88, 29); + отчетыToolStripMenuItem.Text = "Отчеты"; + // + // списокКомпонентовToolStripMenuItem + // + списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem"; + списокКомпонентовToolStripMenuItem.Size = new Size(327, 34); + списокКомпонентовToolStripMenuItem.Text = "Список компонентов"; + списокКомпонентовToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; + // + // списокИзделийToolStripMenuItem + // + списокИзделийToolStripMenuItem.Name = "списокИзделийToolStripMenuItem"; + списокИзделийToolStripMenuItem.Size = new Size(327, 34); + списокИзделийToolStripMenuItem.Text = "Компоненты по изделиям"; + списокИзделийToolStripMenuItem.Click += ComponentGiftsToolStripMenuItem_Click; + // + // списокЗаказовToolStripMenuItem + // + списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; + списокЗаказовToolStripMenuItem.Size = new Size(327, 34); + списокЗаказовToolStripMenuItem.Text = "Список заказов"; + списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; + // + // dataGridView + // + dataGridView.BackgroundColor = SystemColors.ControlLightLight; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(15, 51); + dataGridView.Margin = new Padding(4); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(1404, 529); + dataGridView.TabIndex = 1; + // + // buttonCreateOrder + // + buttonCreateOrder.Location = new Point(1444, 84); + buttonCreateOrder.Margin = new Padding(4); + buttonCreateOrder.Name = "buttonCreateOrder"; + buttonCreateOrder.Size = new Size(236, 51); + buttonCreateOrder.TabIndex = 2; + buttonCreateOrder.Text = "Создать заказ"; + buttonCreateOrder.UseVisualStyleBackColor = true; + buttonCreateOrder.Click += ButtonCreateOrder_Click; + // + // buttonTakeOrderInWork + // + buttonTakeOrderInWork.Location = new Point(1444, 170); + buttonTakeOrderInWork.Margin = new Padding(4); + buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; + buttonTakeOrderInWork.Size = new Size(236, 51); + buttonTakeOrderInWork.TabIndex = 3; + buttonTakeOrderInWork.Text = "Отдать на выполнение"; + buttonTakeOrderInWork.UseVisualStyleBackColor = true; + buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; + // + // buttonOrderReady + // + buttonOrderReady.Location = new Point(1444, 264); + buttonOrderReady.Margin = new Padding(4); + buttonOrderReady.Name = "buttonOrderReady"; + buttonOrderReady.Size = new Size(236, 51); + buttonOrderReady.TabIndex = 4; + buttonOrderReady.Text = "Заказ готов"; + buttonOrderReady.UseVisualStyleBackColor = true; + buttonOrderReady.Click += ButtonOrderReady_Click; + // + // buttonIssuedOrder + // + buttonIssuedOrder.Location = new Point(1444, 362); + buttonIssuedOrder.Margin = new Padding(4); + buttonIssuedOrder.Name = "buttonIssuedOrder"; + buttonIssuedOrder.Size = new Size(236, 51); + buttonIssuedOrder.TabIndex = 5; + buttonIssuedOrder.Text = "Заказ выдан"; + buttonIssuedOrder.UseVisualStyleBackColor = true; + buttonIssuedOrder.Click += ButtonIssuedOrder_Click; + // + // buttonRef + // + buttonRef.Location = new Point(1444, 445); + buttonRef.Margin = new Padding(4); + buttonRef.Name = "buttonRef"; + buttonRef.Size = new Size(236, 51); + buttonRef.TabIndex = 6; + buttonRef.Text = "Обновить список"; + buttonRef.UseVisualStyleBackColor = true; + buttonRef.Click += ButtonRef_Click; + // + // shopReplenishment + // + shopReplenishment.Location = new Point(1444, 525); + shopReplenishment.Margin = new Padding(4); + shopReplenishment.Name = "shopReplenishment"; + shopReplenishment.Size = new Size(236, 51); + shopReplenishment.TabIndex = 7; + shopReplenishment.Text = "Пополнение магазина"; + shopReplenishment.UseVisualStyleBackColor = true; + shopReplenishment.Click += ShopReplenishment_Click; + // + // списокМагазиновToolStripMenuItem + // + списокМагазиновToolStripMenuItem.Name = "списокМагазиновToolStripMenuItem"; + списокМагазиновToolStripMenuItem.Size = new Size(327, 34); + списокМагазиновToolStripMenuItem.Text = "Список магазинов"; + списокМагазиновToolStripMenuItem.Click += списокМагазиновToolStripMenuItem_Click; + // + // подаркиПоМагазинамToolStripMenuItem + // + подаркиПоМагазинамToolStripMenuItem.Name = "подаркиПоМагазинамToolStripMenuItem"; + подаркиПоМагазинамToolStripMenuItem.Size = new Size(327, 34); + подаркиПоМагазинамToolStripMenuItem.Text = "Подарки по магазинам"; + подаркиПоМагазинамToolStripMenuItem.Click += подаркиПоМагазинамToolStripMenuItem_Click; + // + // заказыПоДатамToolStripMenuItem + // + заказыПоДатамToolStripMenuItem.Name = "заказыПоДатамToolStripMenuItem"; + заказыПоДатамToolStripMenuItem.Size = new Size(327, 34); + заказыПоДатамToolStripMenuItem.Text = "Заказы по датам"; + заказыПоДатамToolStripMenuItem.Click += заказыПоДатамToolStripMenuItem_Click; + // + // FormMain + // + AutoScaleDimensions = new SizeF(10F, 25F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1709, 589); + Controls.Add(shopReplenishment); + Controls.Add(buttonRef); + Controls.Add(buttonIssuedOrder); + Controls.Add(buttonOrderReady); + Controls.Add(buttonTakeOrderInWork); + Controls.Add(buttonCreateOrder); + Controls.Add(dataGridView); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; + Margin = new Padding(4); + Name = "FormMain"; + Text = "Магазин подарков"; + Load += FormMain_Load; + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } - #endregion + #endregion - private MenuStrip menuStrip; + private MenuStrip menuStrip; private ToolStripMenuItem справочникиToolStripMenuItem; private ToolStripMenuItem компонентыToolStripMenuItem; private ToolStripMenuItem изделияToolStripMenuItem; + private ToolStripMenuItem магазиныToolStripMenuItem; private DataGridView dataGridView; private Button buttonCreateOrder; private Button buttonTakeOrderInWork; private Button buttonOrderReady; private Button buttonIssuedOrder; private Button buttonRef; - private ToolStripMenuItem отчётыToolStripMenuItem; - private ToolStripMenuItem списокКомпонентовToolStripMenuItem; - private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem; - private ToolStripMenuItem списокЗаказовToolStripMenuItem; - } + private Button shopReplenishment; + private ToolStripMenuItem поставкиToolStripMenuItem; + private ToolStripMenuItem продажиToolStripMenuItem; + + private ToolStripMenuItem отчетыToolStripMenuItem; + private ToolStripMenuItem списокКомпонентовToolStripMenuItem; + private ToolStripMenuItem списокИзделийToolStripMenuItem; + private ToolStripMenuItem списокЗаказовToolStripMenuItem; + private ToolStripMenuItem списокМагазиновToolStripMenuItem; + private ToolStripMenuItem подаркиПоМагазинамToolStripMenuItem; + private ToolStripMenuItem заказыПоДатамToolStripMenuItem; + } } \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormMain.cs b/GiftShop/GiftShopView/FormMain.cs index 2f4070f..936466b 100644 --- a/GiftShop/GiftShopView/FormMain.cs +++ b/GiftShop/GiftShopView/FormMain.cs @@ -1,217 +1,283 @@ -using GiftShopContracts.BindingModels; +using GiftShopBusinessLogic.BusinessLogics; +using GiftShopContracts.BindingModels; using GiftShopContracts.BusinessLogicsContracts; using GiftShopDataModels.Enums; +using GiftShopView; using Microsoft.Extensions.Logging; namespace GiftShopView { - public partial class FormMain : Form - { - private readonly ILogger _logger; + public partial class FormMain : Form + { + private readonly ILogger _logger; - private readonly IOrderLogic _orderLogic; + private readonly IOrderLogic _orderLogic; - private readonly IReportLogic _reportLogic; + private readonly IReportLogic _reportLogic; + public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic) + { + InitializeComponent(); + _logger = logger; + _orderLogic = orderLogic; + _reportLogic = reportLogic; + } - public FormMain(ILogger logger, IOrderLogic orderLogic, IReportLogic reportLogic) - { - InitializeComponent(); - _logger = logger; - _orderLogic = orderLogic; - _reportLogic = reportLogic; - } + private void FormMain_Load(object sender, EventArgs e) + { + LoadData(); + } - private void FormMain_Load(object sender, EventArgs e) - { - LoadData(); - } + private void LoadData() + { + _logger.LogInformation("Загрузка заказов"); + try + { + var list = _orderLogic.ReadList(null); + if (list != null) + { + dataGridView.DataSource = list; + dataGridView.Columns["GiftId"].Visible = false; + dataGridView.Columns["GiftName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + } + _logger.LogInformation("Загрузка заказов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки заказов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } - private void LoadData() - { - _logger.LogInformation("Загрузка заказов"); - try - { - var list = _orderLogic.ReadList(null); - if (list != null) - { - dataGridView.DataSource = list; - dataGridView.Columns["GiftId"].Visible = false; - dataGridView.Columns["GiftName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; - } - _logger.LogInformation("Загрузка заказов"); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка загрузки заказов"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } + private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = + Program.ServiceProvider?.GetService(typeof(FormComponents)); + if (service is FormComponents form) + { + form.ShowDialog(); + } + } - private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = - Program.ServiceProvider?.GetService(typeof(FormComponents)); - if (service is FormComponents form) - { - form.ShowDialog(); - } - } + private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormGifts)); - private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormGifts)); + if (service is FormGifts form) + { + form.ShowDialog(); + } + } + private void МагазиныToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShops)); - if (service is FormGifts form) - { - form.ShowDialog(); - } - } + if (service is FormShops form) + { + form.ShowDialog(); + } + } + private void продажиToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSell)); - private void ButtonCreateOrder_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); - if (service is FormCreateOrder form) - { - form.ShowDialog(); - LoadData(); - } - } + if (service is FormSell form) + { + form.ShowDialog(); + } + } - private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); - try - { - var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel - { - Id = id, + private void поставкиToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormSupply)); + + if (service is FormSupply form) + { + form.ShowDialog(); + } + } + private void ButtonCreateOrder_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); + if (service is FormCreateOrder form) + { + form.ShowDialog(); + LoadData(); + } + } + + private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); + try + { + var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel + { + Id = id, GiftId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["GiftId"].Value), GiftName = dataGridView.SelectedRows[0].Cells["GiftName"].Value.ToString(), Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), - }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка передачи заказа в работу"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, - MessageBoxIcon.Error); - } - } - } + }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка передачи заказа в работу"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } - private void ButtonOrderReady_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); - try - { - var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel - { - Id = id, - GiftId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["GiftId"].Value), - GiftName = dataGridView.SelectedRows[0].Cells["GiftName"].Value.ToString(), - Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), - Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), - Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), - DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), - }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о готовности заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + private void ButtonOrderReady_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); + try + { + var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel + { + Id = id, + GiftId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["GiftId"].Value), + GiftName = dataGridView.SelectedRows[0].Cells["GiftName"].Value.ToString(), + Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), + Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), + Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), + DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), + }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о готовности заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } - private void ButtonIssuedOrder_Click(object sender, EventArgs e) - { - if (dataGridView.SelectedRows.Count == 1) - { - int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); - _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); - try - { - var operationResult = _orderLogic.FinishOrder(new OrderBindingModel - { - Id = id, - GiftId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["GiftId"].Value), - GiftName = dataGridView.SelectedRows[0].Cells["GiftName"].Value.ToString(), - Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), - Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), - Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), - DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), - }); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } - _logger.LogInformation("Заказ №{id} выдан", id); - LoadData(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); - MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } + private void ButtonIssuedOrder_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); + try + { + var operationResult = _orderLogic.FinishOrder(new OrderBindingModel + { + Id = id, + GiftId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["GiftId"].Value), + GiftName = dataGridView.SelectedRows[0].Cells["GiftName"].Value.ToString(), + Status = Enum.Parse(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), + Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), + Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), + DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), + }); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + _logger.LogInformation("Заказ №{id} выдан", id); + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + private void ShopReplenishment_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShopReplenishment)); - private void ButtonRef_Click(object sender, EventArgs e) - { - LoadData(); - } + if (service is FormShopReplenishment form) + { + form.ShowDialog(); + } + } + private void ButtonRef_Click(object sender, EventArgs e) + { + LoadData(); + } - private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e) - { - using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + //4 + private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; - if (dialog.ShowDialog() == DialogResult.OK) - { - _reportLogic.SaveGiftsToWordFile(new ReportBindingModel - { - FileName = dialog.FileName - }); - MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - } + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveGiftsToWordFile(new ReportBindingModel + { + FileName = dialog.FileName + }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + private void ComponentGiftsToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportGiftComponents)); - private void ComponentGiftsToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportGiftComponents)); + if (service is FormReportGiftComponents form) + { + form.ShowDialog(); + } + } + private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); - if (service is FormReportGiftComponents form) - { - form.ShowDialog(); - } - } - - private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) - { - var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); - - if (service is FormReportOrders form) - { - form.ShowDialog(); - } - } - } + if (service is FormReportOrders form) + { + form.ShowDialog(); + } + } + // 4 hard + 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(FormReportShopsGifts)); + if (service is FormReportShopsGifts form) + { + form.ShowDialog(); + } + } + + private void заказыПоДатамToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportDateOrders)); + if (service is FormReportDateOrders form) + { + form.ShowDialog(); + } + } + } } diff --git a/GiftShop/GiftShopView/FormMain.resx b/GiftShop/GiftShopView/FormMain.resx index 1263609..80db743 100644 --- a/GiftShop/GiftShopView/FormMain.resx +++ b/GiftShop/GiftShopView/FormMain.resx @@ -1,4 +1,64 @@ - + + + @@ -61,6 +121,6 @@ 17, 17 - 26 + 37 \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormReportDateOrders.Designer.cs b/GiftShop/GiftShopView/FormReportDateOrders.Designer.cs new file mode 100644 index 0000000..2169cc2 --- /dev/null +++ b/GiftShop/GiftShopView/FormReportDateOrders.Designer.cs @@ -0,0 +1,82 @@ +namespace GiftShopView +{ + partial class FormReportDateOrders + { + /// + /// 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(); + MakeButton = new Button(); + ToPdfButton = new Button(); + SuspendLayout(); + // + // panel + // + panel.Location = new Point(12, 71); + panel.Name = "panel"; + panel.Size = new Size(776, 367); + panel.TabIndex = 0; + // + // MakeButton + // + MakeButton.Location = new Point(12, 36); + MakeButton.Name = "MakeButton"; + MakeButton.Size = new Size(131, 29); + MakeButton.TabIndex = 1; + MakeButton.Text = "Сформировать"; + MakeButton.UseVisualStyleBackColor = true; + MakeButton.Click += MakeButton_Click; + // + // ToPdfButton + // + ToPdfButton.Location = new Point(149, 36); + ToPdfButton.Name = "ToPdfButton"; + ToPdfButton.Size = new Size(94, 29); + ToPdfButton.TabIndex = 2; + ToPdfButton.Text = "В PDF"; + ToPdfButton.UseVisualStyleBackColor = true; + ToPdfButton.Click += ToPdfButton_Click; + // + // ReportDateOrdersForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(ToPdfButton); + Controls.Add(MakeButton); + Controls.Add(panel); + Name = "ReportDateOrdersForm"; + Text = "Заказы по датам"; + ResumeLayout(false); + } + + #endregion + + private Panel panel; + private Button MakeButton; + private Button ToPdfButton; + } +} \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormReportDateOrders.cs b/GiftShop/GiftShopView/FormReportDateOrders.cs new file mode 100644 index 0000000..8852ee4 --- /dev/null +++ b/GiftShop/GiftShopView/FormReportDateOrders.cs @@ -0,0 +1,77 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using Microsoft.Reporting.WinForms; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace GiftShopView +{ + public partial class FormReportDateOrders : Form + { + private readonly ReportViewer reportViewer; + + private readonly ILogger _logger; + + private readonly IReportLogic _logic; + public FormReportDateOrders(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + reportViewer = new ReportViewer + { + Dock = DockStyle.Fill + }; + reportViewer.LocalReport.LoadReportDefinition(new FileStream("ReportOrdersByDate.rdlc", FileMode.Open)); + panel.Controls.Add(reportViewer); + } + + private void MakeButton_Click(object sender, EventArgs e) + { + try + { + var dataSource = _logic.GetDatesOrders(); + var source = new ReportDataSource("DataSetOrders", dataSource); + reportViewer.LocalReport.DataSources.Clear(); + reportViewer.LocalReport.DataSources.Add(source); + reportViewer.RefreshReport(); + _logger.LogInformation("Загрузка списка заказов на весь период по датам"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка заказов на период"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ToPdfButton_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + _logic.SaveDatesOrdersToPdfFile(new ReportBindingModel + { + FileName = dialog.FileName + }); + _logger.LogInformation("Сохранение списка заказов на весь период по датам"); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения списка заказов на период"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } +} diff --git a/GiftShop/GiftShopView/FormReportDateOrders.resx b/GiftShop/GiftShopView/FormReportDateOrders.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/GiftShop/GiftShopView/FormReportDateOrders.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/GiftShop/GiftShopView/FormReportShopsGifts.Designer.cs b/GiftShop/GiftShopView/FormReportShopsGifts.Designer.cs new file mode 100644 index 0000000..e3e3cb8 --- /dev/null +++ b/GiftShop/GiftShopView/FormReportShopsGifts.Designer.cs @@ -0,0 +1,103 @@ +namespace GiftShopView +{ + partial class FormReportShopsGifts + { + /// + /// 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(); + ShopColumn = new DataGridViewTextBoxColumn(); + GiftColumn = new DataGridViewTextBoxColumn(); + CountColumn = new DataGridViewTextBoxColumn(); + SaveButton = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { ShopColumn, GiftColumn, CountColumn }); + dataGridView.Location = new Point(12, 64); + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 29; + dataGridView.Size = new Size(682, 374); + dataGridView.TabIndex = 0; + // + // ShopColumn + // + ShopColumn.HeaderText = "Магазин"; + ShopColumn.MinimumWidth = 6; + ShopColumn.Name = "ShopColumn"; + ShopColumn.Width = 250; + // + // GiftColumn + // + GiftColumn.HeaderText = "Подарок"; + GiftColumn.MinimumWidth = 6; + GiftColumn.Name = "GiftColumn"; + GiftColumn.Width = 250; + // + // CountColumn + // + CountColumn.HeaderText = "Количество"; + CountColumn.MinimumWidth = 6; + CountColumn.Name = "CountColumn"; + CountColumn.Width = 125; + // + // SaveButton + // + SaveButton.Location = new Point(12, 29); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(108, 29); + SaveButton.TabIndex = 1; + SaveButton.Text = "Сохранить в"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click_1; + // + // ReportShopsIceCreamsForm + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(702, 450); + Controls.Add(SaveButton); + Controls.Add(dataGridView); + Name = "FormReportShopsGifts"; + Text = "Подарки по магазинам"; + Load += FormReportShopsGifts_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button SaveButton; + private DataGridViewTextBoxColumn ShopColumn; + private DataGridViewTextBoxColumn GiftColumn; + private DataGridViewTextBoxColumn CountColumn; + } +} \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormReportShopsGifts.cs b/GiftShop/GiftShopView/FormReportShopsGifts.cs new file mode 100644 index 0000000..b0c661d --- /dev/null +++ b/GiftShop/GiftShopView/FormReportShopsGifts.cs @@ -0,0 +1,89 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace GiftShopView +{ + public partial class FormReportShopsGifts : Form + { + private readonly ILogger _logger; + private readonly IReportLogic _logic; + + public FormReportShopsGifts(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + + } + + private void FormReportShopsGifts_Load(object sender, EventArgs e) + { + try + { + var dict = _logic.GetShopsGifts(); + if (dict != null) + { + dataGridView.Rows.Clear(); + foreach (var elem in dict) + { + dataGridView.Rows.Add(new object[] { elem.ShopName, "", "" }); + foreach (var listElem in elem.Gifts) + { + dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 }); + } + dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount }); + dataGridView.Rows.Add(Array.Empty()); + } + } + _logger.LogInformation("Загрузка списка мороженных по магазинам"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка мороженных по магазинам"); + + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + + } + private void SaveButton_Click_1(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog + { + Filter = "xlsx|*.xlsx" + }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + _logic.SaveShopsGiftsToExcelFile(new + ReportBindingModel + { + FileName = dialog.FileName + }); + _logger.LogInformation("Сохранение списка подарков по магазинам"); + + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения списка подарков по магазинам"); + + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + } + } +} diff --git a/GiftShop/GiftShopView/FormReportShopsGifts.resx b/GiftShop/GiftShopView/FormReportShopsGifts.resx new file mode 100644 index 0000000..51eccb4 --- /dev/null +++ b/GiftShop/GiftShopView/FormReportShopsGifts.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + True + + + True + + + True + + \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormSell.Designer.cs b/GiftShop/GiftShopView/FormSell.Designer.cs new file mode 100644 index 0000000..ab3f832 --- /dev/null +++ b/GiftShop/GiftShopView/FormSell.Designer.cs @@ -0,0 +1,124 @@ +namespace GiftShopView +{ + partial class FormSell + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + GiftComboBox = new ComboBox(); + GiftLabel = new Label(); + CountLabel = new Label(); + CountTextBox = new TextBox(); + SaveButton = new Button(); + CancelButton = new Button(); + SuspendLayout(); + // + // GiftComboBox + // + GiftComboBox.FormattingEnabled = true; + GiftComboBox.Location = new Point(149, 30); + GiftComboBox.Margin = new Padding(4, 5, 4, 5); + GiftComboBox.Name = "GiftComboBox"; + GiftComboBox.Size = new Size(241, 33); + GiftComboBox.TabIndex = 0; + // + // GiftLabel + // + GiftLabel.AutoSize = true; + GiftLabel.Location = new Point(51, 33); + GiftLabel.Margin = new Padding(4, 0, 4, 0); + GiftLabel.Name = "GiftLabel"; + GiftLabel.Size = new Size(90, 25); + GiftLabel.TabIndex = 1; + GiftLabel.Text = "Подарок:"; + // + // CountLabel + // + CountLabel.AutoSize = true; + CountLabel.Location = new Point(30, 82); + CountLabel.Margin = new Padding(4, 0, 4, 0); + CountLabel.Name = "CountLabel"; + CountLabel.Size = new Size(111, 25); + CountLabel.TabIndex = 2; + CountLabel.Text = "Количество:"; + // + // CountTextBox + // + CountTextBox.Location = new Point(149, 79); + CountTextBox.Margin = new Padding(4, 5, 4, 5); + CountTextBox.Name = "CountTextBox"; + CountTextBox.Size = new Size(241, 31); + CountTextBox.TabIndex = 3; + // + // SaveButton + // + SaveButton.Location = new Point(51, 157); + SaveButton.Margin = new Padding(4, 5, 4, 5); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(152, 50); + SaveButton.TabIndex = 4; + SaveButton.Text = "Сохранить"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click; + // + // CancelButton + // + CancelButton.Location = new Point(250, 157); + CancelButton.Margin = new Padding(4, 5, 4, 5); + CancelButton.Name = "CancelButton"; + CancelButton.Size = new Size(152, 50); + CancelButton.TabIndex = 5; + CancelButton.Text = "Отмена"; + CancelButton.UseVisualStyleBackColor = true; + // + // SellForm + // + AutoScaleDimensions = new SizeF(10F, 25F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(415, 221); + Controls.Add(CancelButton); + Controls.Add(SaveButton); + Controls.Add(CountTextBox); + Controls.Add(CountLabel); + Controls.Add(GiftLabel); + Controls.Add(GiftComboBox); + Margin = new Padding(4, 5, 4, 5); + Name = "SellForm"; + Text = "Форма продажи"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox GiftComboBox; + private Label GiftLabel; + private Label CountLabel; + private TextBox CountTextBox; + private Button SaveButton; + private Button CancelButton; + } +} \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormSell.cs b/GiftShop/GiftShopView/FormSell.cs new file mode 100644 index 0000000..cfeb8d2 --- /dev/null +++ b/GiftShop/GiftShopView/FormSell.cs @@ -0,0 +1,116 @@ +using GiftShopContracts.BusinessLogicsContracts; +using GiftShopContracts.SearchModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace GiftShopView +{ + public partial class FormSell : Form + { + private readonly List? _GiftList; + IShopLogic _shopLogic; + IGiftLogic _GiftLogic; + public FormSell(IGiftLogic GiftLogic, IShopLogic shopLogic) + { + InitializeComponent(); + _shopLogic = shopLogic; + _GiftLogic = GiftLogic; + _GiftList = GiftLogic.ReadList(null); + if (_GiftList != null) + { + GiftComboBox.DisplayMember = "GiftName"; + GiftComboBox.ValueMember = "Id"; + GiftComboBox.DataSource = _GiftList; + GiftComboBox.SelectedItem = null; + } + } + public int GiftId + { + get + { + return Convert.ToInt32(GiftComboBox.SelectedValue); + } + set + { + GiftComboBox.SelectedValue = value; + } + } + + public IGiftModel? GiftModel + { + get + { + if (_GiftList == null) + { + return null; + } + foreach (var elem in _GiftList) + { + if (elem.Id == GiftId) + { + return elem; + } + } + return null; + } + } + + + public int Count + { + get { return Convert.ToInt32(CountTextBox.Text); } + set + { CountTextBox.Text = value.ToString(); } + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(CountTextBox.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (GiftComboBox.SelectedValue == null) + { + MessageBox.Show("Выберите подарок", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + try + { + int count = Convert.ToInt32(CountTextBox.Text); + + bool res = _shopLogic.MakeSell( + _GiftLogic.ReadElement(new() { Id = Convert.ToInt32(GiftComboBox.SelectedValue) }), + count + ); + + if (!res) + { + throw new Exception("Ошибка при продаже."); + } + + MessageBox.Show("Продажа прошла успешно"); + DialogResult = DialogResult.OK; + Close(); + + } + catch (Exception err) + { + MessageBox.Show("Ошибка продажи"); + return; + } + } + } +} diff --git a/GiftShop/GiftShopView/FormSell.resx b/GiftShop/GiftShopView/FormSell.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/GiftShop/GiftShopView/FormSell.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormShop.Designer.cs b/GiftShop/GiftShopView/FormShop.Designer.cs new file mode 100644 index 0000000..088ada6 --- /dev/null +++ b/GiftShop/GiftShopView/FormShop.Designer.cs @@ -0,0 +1,221 @@ +namespace GiftShopView +{ + 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() + { + shopNameLabel = new Label(); + shopAddressLabel = new Label(); + openingDateLabel = new Label(); + addressTextBox = new TextBox(); + openingDatePicker = new DateTimePicker(); + dataGridView = new DataGridView(); + PackageName = new DataGridViewTextBoxColumn(); + PackagePrice = new DataGridViewTextBoxColumn(); + PackageCount = new DataGridViewTextBoxColumn(); + SaveButton = new Button(); + ButtonCancel = new Button(); + nameTextBox = new TextBox(); + labelCapacity = new Label(); + CapacityUpDown = new NumericUpDown(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // shopNameLabel + // + shopNameLabel.AutoSize = true; + shopNameLabel.Location = new Point(18, 15); + shopNameLabel.Margin = new Padding(4, 0, 4, 0); + shopNameLabel.Name = "shopNameLabel"; + shopNameLabel.Size = new Size(179, 25); + shopNameLabel.TabIndex = 0; + shopNameLabel.Text = "Название магазина: "; + // + // shopAddressLabel + // + shopAddressLabel.AutoSize = true; + shopAddressLabel.Location = new Point(18, 66); + shopAddressLabel.Margin = new Padding(4, 0, 4, 0); + shopAddressLabel.Name = "shopAddressLabel"; + shopAddressLabel.Size = new Size(151, 25); + shopAddressLabel.TabIndex = 1; + shopAddressLabel.Text = "Адрес магазина: "; + // + // openingDateLabel + // + openingDateLabel.AutoSize = true; + openingDateLabel.Location = new Point(18, 120); + openingDateLabel.Margin = new Padding(4, 0, 4, 0); + openingDateLabel.Name = "openingDateLabel"; + openingDateLabel.Size = new Size(140, 25); + openingDateLabel.TabIndex = 2; + openingDateLabel.Text = "Дата открытия: "; + // + // addressTextBox + // + addressTextBox.Location = new Point(204, 62); + addressTextBox.Margin = new Padding(4, 5, 4, 5); + addressTextBox.Name = "addressTextBox"; + addressTextBox.Size = new Size(246, 31); + addressTextBox.TabIndex = 4; + // + // openingDatePicker + // + openingDatePicker.Location = new Point(204, 114); + openingDatePicker.Margin = new Padding(4); + openingDatePicker.Name = "openingDatePicker"; + openingDatePicker.Size = new Size(246, 31); + openingDatePicker.TabIndex = 9; + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = SystemColors.Window; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { PackageName, PackagePrice, PackageCount }); + dataGridView.Location = new Point(20, 225); + dataGridView.Margin = new Padding(4, 5, 4, 5); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(1109, 418); + dataGridView.TabIndex = 6; + // + // PackageName + // + PackageName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + PackageName.HeaderText = "Название изделия"; + PackageName.MinimumWidth = 6; + PackageName.Name = "PackageName"; + // + // PackagePrice + // + PackagePrice.HeaderText = "Цена"; + PackagePrice.MinimumWidth = 6; + PackagePrice.Name = "PackagePrice"; + PackagePrice.Width = 125; + // + // PackageCount + // + PackageCount.HeaderText = "Количество"; + PackageCount.MinimumWidth = 6; + PackageCount.Name = "PackageCount"; + PackageCount.Width = 125; + // + // SaveButton + // + SaveButton.Location = new Point(789, 671); + SaveButton.Margin = new Padding(4, 5, 4, 5); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(164, 59); + SaveButton.TabIndex = 7; + SaveButton.Text = "Сохранить"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click; + // + // ButtonCancel + // + ButtonCancel.Location = new Point(961, 671); + ButtonCancel.Margin = new Padding(4, 5, 4, 5); + ButtonCancel.Name = "ButtonCancel"; + ButtonCancel.Size = new Size(164, 59); + ButtonCancel.TabIndex = 8; + ButtonCancel.Text = "Отменить"; + ButtonCancel.UseVisualStyleBackColor = true; + ButtonCancel.Click += ButtonCancel_Click; + // + // nameTextBox + // + nameTextBox.Location = new Point(204, 11); + nameTextBox.Margin = new Padding(4); + nameTextBox.Name = "nameTextBox"; + nameTextBox.Size = new Size(246, 31); + nameTextBox.TabIndex = 10; + // + // labelCapacity + // + labelCapacity.AutoSize = true; + labelCapacity.Location = new Point(20, 167); + labelCapacity.Margin = new Padding(4, 0, 4, 0); + labelCapacity.Name = "labelCapacity"; + labelCapacity.Size = new Size(121, 25); + labelCapacity.TabIndex = 11; + labelCapacity.Text = "Вместимость:"; + // + // CapacityUpDown + // + CapacityUpDown.Location = new Point(204, 161); + CapacityUpDown.Name = "CapacityUpDown"; + CapacityUpDown.Size = new Size(246, 31); + CapacityUpDown.TabIndex = 12; + // + // FormShop + // + AutoScaleDimensions = new SizeF(10F, 25F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1142, 750); + Controls.Add(CapacityUpDown); + Controls.Add(labelCapacity); + Controls.Add(nameTextBox); + Controls.Add(ButtonCancel); + Controls.Add(SaveButton); + Controls.Add(dataGridView); + Controls.Add(openingDatePicker); + Controls.Add(addressTextBox); + Controls.Add(openingDateLabel); + Controls.Add(shopAddressLabel); + Controls.Add(shopNameLabel); + Margin = new Padding(4, 5, 4, 5); + Name = "FormShop"; + Text = "Магазин"; + Load += FormShop_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label shopNameLabel; + private Label shopAddressLabel; + private Label openingDateLabel; + private TextBox addressTextBox; + private DateTimePicker openingDatePicker; + private DataGridView dataGridView; + private Button SaveButton; + private Button ButtonCancel; + private DataGridViewTextBoxColumn PackageName; + private DataGridViewTextBoxColumn PackagePrice; + private DataGridViewTextBoxColumn PackageCount; + private TextBox nameTextBox; + private Label labelCapacity; + private NumericUpDown CapacityUpDown; + } +} \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormShop.cs b/GiftShop/GiftShopView/FormShop.cs new file mode 100644 index 0000000..04e3a42 --- /dev/null +++ b/GiftShop/GiftShopView/FormShop.cs @@ -0,0 +1,144 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.BusinessLogicsContracts; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace GiftShopView +{ + public partial class FormShop : Form + { + private readonly List? _listShops; + private readonly IShopLogic _logic; + private readonly ILogger _logger; + public int Id { get; set; } + + public FormShop(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _listShops = logic.ReadList(null); + _logic = logic; + } + + private IShopModel? GetShop(int id) + { + if (_listShops == null) + { + return null; + } + foreach (var elem in _listShops) + { + if (elem.Id == id) + { + return elem; + } + } + return null; + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(nameTextBox.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + if (string.IsNullOrEmpty(addressTextBox.Text)) + { + MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + _logger.LogInformation("Сохранение изделия"); + + try + { + DateTime.TryParse(openingDatePicker.Text, out var dateTime); + ShopBindingModel model = new() + { + ShopName = nameTextBox.Text, + ShopAdress = addressTextBox.Text, + OpeningDate = dateTime, + MaxCapacity = Convert.ToInt32(CapacityUpDown.Value) + }; + var vmodel = GetShop(Id); + bool operationResult = false; + + if (vmodel != null) + { + model.Id = vmodel.Id; + model.ShopGifts = vmodel.ShopGifts; + operationResult = _logic.Update(model); + } + else + { + operationResult = _logic.Create(model); + } + + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + + private void FormShop_Load(object sender, EventArgs e) + { + LoadData(); + } + private void LoadData(bool extendDate = true) + { + try + { + var model = GetShop(extendDate ? Id : Convert.ToInt32(nameTextBox.Text)); + if (model != null) + { + nameTextBox.Text = model.ShopName; + addressTextBox.Text = model.ShopAdress; + openingDatePicker.Text = Convert.ToString(model.OpeningDate); + CapacityUpDown.Value = Convert.ToInt32(model.MaxCapacity); + dataGridView.Rows.Clear(); + foreach (var el in model.ShopGifts.Values) + { + dataGridView.Rows.Add(new object[] { el.Item1.GiftName, el.Item1.Price, el.Item2 }); + } + + } + _logger.LogInformation("Загрузка магазинов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки магазинов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + } + + } +} diff --git a/GiftShop/GiftShopView/FormShop.resx b/GiftShop/GiftShopView/FormShop.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/GiftShop/GiftShopView/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/GiftShop/GiftShopView/FormShopReplenishment.Designer.cs b/GiftShop/GiftShopView/FormShopReplenishment.Designer.cs new file mode 100644 index 0000000..ea59248 --- /dev/null +++ b/GiftShop/GiftShopView/FormShopReplenishment.Designer.cs @@ -0,0 +1,152 @@ +namespace GiftShopView +{ + partial class FormShopReplenishment + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(800, 450); + this.Text = "FormShopReplenishment"; + + shopNameLabel = new Label(); + packageNameLabel = new Label(); + countLabel = new Label(); + shopNameComboBox = new ComboBox(); + giftNameComboBox = new ComboBox(); + countTextBox = new TextBox(); + buttonSave = new Button(); + buttonCancel = new Button(); + SuspendLayout(); + // + // shopNameLabel + // + shopNameLabel.AutoSize = true; + shopNameLabel.Location = new Point(14, 12); + shopNameLabel.Name = "shopNameLabel"; + shopNameLabel.Size = new Size(154, 20); + shopNameLabel.TabIndex = 0; + shopNameLabel.Text = "Название магазина: "; + // + // packageNameLabel + // + packageNameLabel.AutoSize = true; + packageNameLabel.Location = new Point(14, 49); + packageNameLabel.Name = "packageNameLabel"; + packageNameLabel.Size = new Size(145, 20); + packageNameLabel.TabIndex = 1; + packageNameLabel.Text = "Название изделия: "; + // + // countLabel + // + countLabel.AutoSize = true; + countLabel.Location = new Point(14, 88); + countLabel.Name = "countLabel"; + countLabel.Size = new Size(97, 20); + countLabel.TabIndex = 2; + countLabel.Text = "Количество: "; + // + // shopNameComboBox + // + shopNameComboBox.FormattingEnabled = true; + shopNameComboBox.Location = new Point(171, 9); + shopNameComboBox.Margin = new Padding(3, 4, 3, 4); + shopNameComboBox.Name = "shopNameComboBox"; + shopNameComboBox.Size = new Size(170, 28); + shopNameComboBox.TabIndex = 3; + // + // giftNameComboBox + // + giftNameComboBox.FormattingEnabled = true; + giftNameComboBox.Location = new Point(171, 49); + giftNameComboBox.Margin = new Padding(3, 4, 3, 4); + giftNameComboBox.Name = "giftNameComboBox"; + giftNameComboBox.Size = new Size(170, 28); + giftNameComboBox.TabIndex = 4; + // + // countTextBox + // + countTextBox.Location = new Point(171, 87); + countTextBox.Margin = new Padding(3, 4, 3, 4); + countTextBox.Name = "countTextBox"; + countTextBox.Size = new Size(170, 27); + countTextBox.TabIndex = 5; + // + // buttonSave + // + buttonSave.Location = new Point(151, 144); + buttonSave.Margin = new Padding(3, 4, 3, 4); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(98, 31); + buttonSave.TabIndex = 6; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += SaveButton_Click; + // + // buttonCancel + // + buttonCancel.Location = new Point(255, 144); + buttonCancel.Margin = new Padding(3, 4, 3, 4); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(86, 31); + buttonCancel.TabIndex = 7; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += ButtonCancel_Click; + // + // FormShopReplenishment + // + AutoScaleDimensions = new SizeF(8F, 20F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(353, 200); + Controls.Add(buttonCancel); + Controls.Add(buttonSave); + Controls.Add(countTextBox); + Controls.Add(giftNameComboBox); + Controls.Add(shopNameComboBox); + Controls.Add(countLabel); + Controls.Add(packageNameLabel); + Controls.Add(shopNameLabel); + Margin = new Padding(3, 4, 3, 4); + Name = "FormShopReplenishment"; + Text = "Пополнение магазина"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label shopNameLabel; + private Label packageNameLabel; + private Label countLabel; + private ComboBox shopNameComboBox; + private ComboBox giftNameComboBox; + private TextBox countTextBox; + private Button buttonSave; + private Button buttonCancel; + } +} \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormShopReplenishment.cs b/GiftShop/GiftShopView/FormShopReplenishment.cs new file mode 100644 index 0000000..1fda654 --- /dev/null +++ b/GiftShop/GiftShopView/FormShopReplenishment.cs @@ -0,0 +1,104 @@ +using GiftShopContracts.BusinessLogicsContracts; +using GiftShopContracts.ViewModels; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace GiftShopView +{ + public partial class FormShopReplenishment : Form + { + private readonly ILogger _logger; + private readonly IShopLogic _ShopLogic; + private readonly IGiftLogic _giftLogic; + private readonly List? _listShops; + private readonly List? _listGifts; + public FormShopReplenishment(ILogger logger, IShopLogic ShopLogic, IGiftLogic giftLogic) + { + InitializeComponent(); + _ShopLogic = ShopLogic; + _giftLogic = giftLogic; + _logger = logger; + _listShops = ShopLogic.ReadList(null); + if (_listShops != null) + { + shopNameComboBox.DisplayMember = "ShopName"; + shopNameComboBox.ValueMember = "Id"; + shopNameComboBox.DataSource = _listShops; + shopNameComboBox.SelectedItem = null; + } + + _listGifts = giftLogic.ReadList(null); + if (_listGifts != null) + { + giftNameComboBox.DisplayMember = "GiftName"; + giftNameComboBox.ValueMember = "Id"; + giftNameComboBox.DataSource = _listGifts; + giftNameComboBox.SelectedItem = null; + } + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (shopNameComboBox.SelectedValue == null) + { + MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + if (giftNameComboBox.SelectedValue == null) + { + MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + _logger.LogInformation("Добавление изделия в магазин"); + + try + { + var gift = _giftLogic.ReadElement(new() + { + Id = (int)giftNameComboBox.SelectedValue + }); + + if (gift == null) + { + throw new Exception("Не найдено изделие. Дополнительная информация в логах."); + } + + var resultOperation = _ShopLogic.AddGift( + model: new() { Id = (int)shopNameComboBox.SelectedValue }, + gift: gift, + quantity: Convert.ToInt32(countTextBox.Text) + ); + + if (!resultOperation) + { + throw new Exception("Ошибка при добавлении. Дополнительная информация в логах."); + } + + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void ButtonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/GiftShop/GiftShopView/FormShopReplenishment.resx b/GiftShop/GiftShopView/FormShopReplenishment.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/GiftShop/GiftShopView/FormShopReplenishment.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/GiftShop/GiftShopView/FormShops.Designer.cs b/GiftShop/GiftShopView/FormShops.Designer.cs new file mode 100644 index 0000000..0a5bfb3 --- /dev/null +++ b/GiftShop/GiftShopView/FormShops.Designer.cs @@ -0,0 +1,126 @@ +namespace GiftShopView +{ + partial class FormShops + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + dataGridView = new DataGridView(); + buttonAdd = new Button(); + buttonUpdate = new Button(); + buttonDelete = new Button(); + buttonRefresh = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = SystemColors.Window; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Location = new Point(1, 1); + dataGridView.Margin = new Padding(4, 5, 4, 5); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.RowHeadersVisible = false; + dataGridView.RowHeadersWidth = 51; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(786, 745); + dataGridView.TabIndex = 0; + // + // buttonAdd + // + buttonAdd.Location = new Point(836, 20); + buttonAdd.Margin = new Padding(4, 5, 4, 5); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(172, 66); + buttonAdd.TabIndex = 1; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += AddButton_Click; + // + // buttonUpdate + // + buttonUpdate.Location = new Point(836, 111); + buttonUpdate.Margin = new Padding(4, 5, 4, 5); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(172, 66); + buttonUpdate.TabIndex = 2; + buttonUpdate.Text = "Изменить"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += UpdateButton_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(836, 204); + buttonDelete.Margin = new Padding(4, 5, 4, 5); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(172, 66); + buttonDelete.TabIndex = 3; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += DeleteButton_Click; + // + // buttonRefresh + // + buttonRefresh.Location = new Point(836, 299); + buttonRefresh.Margin = new Padding(4, 5, 4, 5); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(172, 66); + buttonRefresh.TabIndex = 4; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += RefreshButton_Click; + // + // FormShops + // + AutoScaleDimensions = new SizeF(10F, 25F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(1026, 750); + Controls.Add(buttonRefresh); + Controls.Add(buttonDelete); + Controls.Add(buttonUpdate); + Controls.Add(buttonAdd); + Controls.Add(dataGridView); + Margin = new Padding(4, 5, 4, 5); + Name = "FormShops"; + Text = "Магазины"; + Load += FormShops_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private DataGridView dataGridView; + private Button buttonAdd; + private Button buttonUpdate; + private Button buttonDelete; + private Button buttonRefresh; + } +} \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormShops.cs b/GiftShop/GiftShopView/FormShops.cs new file mode 100644 index 0000000..85459d3 --- /dev/null +++ b/GiftShop/GiftShopView/FormShops.cs @@ -0,0 +1,125 @@ +using GiftShopContracts.BindingModels; +using GiftShopContracts.BusinessLogicsContracts; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace GiftShopView +{ + 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["ShopAdress"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["OpeningDate"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["MaxCapacity"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + dataGridView.Columns["ShopGifts"].Visible = false; + } + + _logger.LogInformation("Загрузка магазинов"); + + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки магазинов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + private void RefreshButton_Click(object sender, EventArgs e) + { + LoadData(); + } + + private void DeleteButton_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление магазина"); + + try + { + if (!_logic.Delete(new ShopBindingModel + { + Id = id + })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления изделия"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + private void UpdateButton_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 AddButton_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + + if (service is FormShop form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } +} diff --git a/GiftShop/GiftShopView/FormShops.resx b/GiftShop/GiftShopView/FormShops.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/GiftShop/GiftShopView/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/GiftShop/GiftShopView/FormSupply.Designer.cs b/GiftShop/GiftShopView/FormSupply.Designer.cs new file mode 100644 index 0000000..655364d --- /dev/null +++ b/GiftShop/GiftShopView/FormSupply.Designer.cs @@ -0,0 +1,111 @@ +namespace GiftShopView +{ + partial class FormSupply + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + ShopComboBox = new ComboBox(); + GiftComboBox = new ComboBox(); + CountTextBox = new TextBox(); + SaveButton = new Button(); + CancelButton = new Button(); + SuspendLayout(); + // + // ShopComboBox + // + ShopComboBox.FormattingEnabled = true; + ShopComboBox.Location = new Point(18, 20); + ShopComboBox.Margin = new Padding(4, 5, 4, 5); + ShopComboBox.Name = "ShopComboBox"; + ShopComboBox.Size = new Size(472, 33); + ShopComboBox.TabIndex = 0; + // + // GiftComboBox + // + GiftComboBox.FormattingEnabled = true; + GiftComboBox.Location = new Point(18, 69); + GiftComboBox.Margin = new Padding(4, 5, 4, 5); + GiftComboBox.Name = "GiftComboBox"; + GiftComboBox.Size = new Size(472, 33); + GiftComboBox.TabIndex = 1; + // + // CountTextBox + // + CountTextBox.Location = new Point(18, 116); + CountTextBox.Margin = new Padding(4, 5, 4, 5); + CountTextBox.Name = "CountTextBox"; + CountTextBox.Size = new Size(472, 31); + CountTextBox.TabIndex = 2; + // + // SaveButton + // + SaveButton.Location = new Point(152, 200); + SaveButton.Margin = new Padding(4, 5, 4, 5); + SaveButton.Name = "SaveButton"; + SaveButton.Size = new Size(157, 52); + SaveButton.TabIndex = 3; + SaveButton.Text = "Сохранить"; + SaveButton.UseVisualStyleBackColor = true; + SaveButton.Click += SaveButton_Click; + // + // CancelButton + // + CancelButton.Location = new Point(338, 200); + CancelButton.Margin = new Padding(4, 5, 4, 5); + CancelButton.Name = "CancelButton"; + CancelButton.Size = new Size(157, 52); + CancelButton.TabIndex = 4; + CancelButton.Text = "Отмена"; + CancelButton.UseVisualStyleBackColor = true; + CancelButton.Click += CancelButton_Click; + // + // SupplyForm + // + AutoScaleDimensions = new SizeF(10F, 25F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(508, 266); + Controls.Add(CancelButton); + Controls.Add(SaveButton); + Controls.Add(CountTextBox); + Controls.Add(GiftComboBox); + Controls.Add(ShopComboBox); + Margin = new Padding(4, 5, 4, 5); + Name = "SupplyForm"; + Text = "Форма поставок"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox ShopComboBox; + private ComboBox GiftComboBox; + private TextBox CountTextBox; + private Button SaveButton; + private Button CancelButton; + } +} \ No newline at end of file diff --git a/GiftShop/GiftShopView/FormSupply.cs b/GiftShop/GiftShopView/FormSupply.cs new file mode 100644 index 0000000..3fff529 --- /dev/null +++ b/GiftShop/GiftShopView/FormSupply.cs @@ -0,0 +1,153 @@ +using GiftShopBusinessLogic.BusinessLogics; +using GiftShopContracts.BusinessLogicsContracts; +using GiftShopContracts.SearchModels; +using GiftShopContracts.ViewModels; +using GiftShopDataModels.Models; +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace GiftShopView +{ + public partial class FormSupply : Form + { + private readonly List? _GiftList; + private readonly List? _shopsList; + IShopLogic _shopLogic; + IGiftLogic _GiftLogic; + public int ShopId + { + get + { + return + Convert.ToInt32(ShopComboBox.SelectedValue); + } + set + { + ShopComboBox.SelectedValue = value; + } + } + public int GiftId + { + get + { + return + Convert.ToInt32(GiftComboBox.SelectedValue); + } + set + { + GiftComboBox.SelectedValue = value; + } + } + + public IGiftModel? GiftModel + { + get + { + if (_GiftList == null) + { + return null; + } + foreach (var elem in _GiftList) + { + if (elem.Id == GiftId) + { + return elem; + } + } + return null; + } + } + + + public int Count + { + get { return Convert.ToInt32(CountTextBox.Text); } + set + { CountTextBox.Text = value.ToString(); } + } + public FormSupply(IGiftLogic GiftLogic, IShopLogic shopLogic) + { + InitializeComponent(); + _shopLogic = shopLogic; + _GiftLogic = GiftLogic; + _GiftList = GiftLogic.ReadList(null); + _shopsList = shopLogic.ReadList(null); + if (_GiftList != null) + { + GiftComboBox.DisplayMember = "GiftName"; + GiftComboBox.ValueMember = "Id"; + GiftComboBox.DataSource = _GiftList; + GiftComboBox.SelectedItem = null; + } + if (_shopsList != null) + { + ShopComboBox.DisplayMember = "ShopName"; + ShopComboBox.ValueMember = "Id"; + ShopComboBox.DataSource = _shopsList; + ShopComboBox.SelectedItem = null; + } + } + + private void SaveButton_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(CountTextBox.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (GiftComboBox.SelectedValue == null) + { + MessageBox.Show("Выберите подарок", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (ShopComboBox.SelectedValue == null) + { + MessageBox.Show("Выберите магазин", "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + + try + { + int count = Convert.ToInt32(CountTextBox.Text); + + bool res = _shopLogic.MakeSupply( + new ShopSearchModel() { Id = Convert.ToInt32(ShopComboBox.SelectedValue) }, + _GiftLogic.ReadElement(new() { Id = Convert.ToInt32(GiftComboBox.SelectedValue) }), + count + ); + + if (!res) + { + throw new Exception("Ошибка при пополнении. Дополнительная информация в логах"); + } + + MessageBox.Show("Пополнение прошло успешно"); + DialogResult = DialogResult.OK; + Close(); + + } + catch (Exception err) + { + MessageBox.Show("Ошибка пополнения"); + return; + } + } + + private void CancelButton_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/GiftShop/GiftShopView/FormSupply.resx b/GiftShop/GiftShopView/FormSupply.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/GiftShop/GiftShopView/FormSupply.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/GiftShop/GiftShopView/Program.cs b/GiftShop/GiftShopView/Program.cs index aaeacf1..7ecf85c 100644 --- a/GiftShop/GiftShopView/Program.cs +++ b/GiftShop/GiftShopView/Program.cs @@ -34,25 +34,36 @@ namespace GiftShopView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); - services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); + services.AddTransient(); + services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); - services.AddTransient(); + + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); - services.AddTransient(); - services.AddTransient(); - } - } + services.AddTransient(); + services.AddTransient(); + + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + } + } } \ No newline at end of file diff --git a/GiftShop/GiftShopView/ReportOrdersByDate.rdlc b/GiftShop/GiftShopView/ReportOrdersByDate.rdlc new file mode 100644 index 0000000..d849467 --- /dev/null +++ b/GiftShop/GiftShopView/ReportOrdersByDate.rdlc @@ -0,0 +1,400 @@ + + + + + + true + true + + + + + Заказы + + + + + + + 0.24cm + 1cm + 21cm + + + Middle + 2pt + 2pt + 2pt + 2pt + + + + + + + 3cm + + + 3cm + + + 7cm + + + + + 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!DateOfOrders.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 + 2.72391cm + 0.55245cm + 1.2cm + 13cm + 1 + + + + + + true + true + + + + + Всего: + + + + + + + 4.24cm + 8.55245cm + 0.6cm + 2.5cm + 2 + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Sum(Fields!Sum.Value, "DataSetOrders") + + + + + + + 4.24cm + 11.05245cm + 0.6cm + 2.5cm + 3 + + + 2pt + 2pt + 2pt + 2pt + + + + 2in +