From a19566b21972bdb8a3812afcd26ec8b40adb8461 Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Thu, 22 Feb 2024 01:58:33 +0400 Subject: [PATCH 01/11] LabWork01_Hard --- .../BusinessLogics/OrderLogic.cs | 3 +- .../BusinessLogics/PlaneLogic.cs | 3 +- .../BusinessLogics/ShopLogic.cs | 222 ++++++++++++++++++ .../BindingModels/ShopBindingModel.cs | 45 ++++ .../BusinessLogicsContracts/IShopLogic.cs | 62 +++++ .../SearchModels/ShopSearchModel.cs | 25 ++ .../StoragesContracts/IShopStorage.cs | 58 +++++ .../ViewModels/ShopViewModel.cs | 49 ++++ .../Models/IShopModel.cs | 34 +++ .../DataListSingleton.cs | 6 + .../Implements/ShopStorage.cs | 154 ++++++++++++ .../AircraftPlantListImplement/Models/Shop.cs | 97 ++++++++ .../FormCreateSupply.Designer.cs | 146 ++++++++++++ .../AircraftPlantView/FormCreateSupply.cs | 159 +++++++++++++ .../AircraftPlantView/FormCreateSupply.resx | 120 ++++++++++ .../AircraftPlantView/FormMain.Designer.cs | 28 ++- AircraftPlant/AircraftPlantView/FormMain.cs | 28 +++ .../AircraftPlantView/FormShop.Designer.cs | 188 +++++++++++++++ AircraftPlant/AircraftPlantView/FormShop.cs | 170 ++++++++++++++ AircraftPlant/AircraftPlantView/FormShop.resx | 129 ++++++++++ .../AircraftPlantView/FormShops.Designer.cs | 122 ++++++++++ AircraftPlant/AircraftPlantView/FormShops.cs | 153 ++++++++++++ .../AircraftPlantView/FormShops.resx | 120 ++++++++++ AircraftPlant/AircraftPlantView/Program.cs | 5 + 24 files changed, 2119 insertions(+), 7 deletions(-) create mode 100644 AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ShopLogic.cs create mode 100644 AircraftPlant/AircraftPlantContracts/BindingModels/ShopBindingModel.cs create mode 100644 AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IShopLogic.cs create mode 100644 AircraftPlant/AircraftPlantContracts/SearchModels/ShopSearchModel.cs create mode 100644 AircraftPlant/AircraftPlantContracts/StoragesContracts/IShopStorage.cs create mode 100644 AircraftPlant/AircraftPlantContracts/ViewModels/ShopViewModel.cs create mode 100644 AircraftPlant/AircraftPlantDataModels/Models/IShopModel.cs create mode 100644 AircraftPlant/AircraftPlantListImplement/Implements/ShopStorage.cs create mode 100644 AircraftPlant/AircraftPlantListImplement/Models/Shop.cs create mode 100644 AircraftPlant/AircraftPlantView/FormCreateSupply.Designer.cs create mode 100644 AircraftPlant/AircraftPlantView/FormCreateSupply.cs create mode 100644 AircraftPlant/AircraftPlantView/FormCreateSupply.resx create mode 100644 AircraftPlant/AircraftPlantView/FormShop.Designer.cs create mode 100644 AircraftPlant/AircraftPlantView/FormShop.cs create mode 100644 AircraftPlant/AircraftPlantView/FormShop.resx create mode 100644 AircraftPlant/AircraftPlantView/FormShops.Designer.cs create mode 100644 AircraftPlant/AircraftPlantView/FormShops.cs create mode 100644 AircraftPlant/AircraftPlantView/FormShops.resx diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs index c96ad04..ad4d0d4 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs @@ -33,8 +33,7 @@ namespace AircraftPlantBusinessLogic.BusinessLogics /// /// /// - public OrderLogic(ILogger logger, IOrderStorage -orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage) { _logger = logger; _orderStorage = orderStorage; diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/PlaneLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/PlaneLogic.cs index 82de87f..17a7b74 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/PlaneLogic.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/PlaneLogic.cs @@ -32,8 +32,7 @@ namespace AircraftPlantBusinessLogic.BusinessLogics /// /// /// - public PlaneLogic(ILogger logger, IPlaneStorage -planeStorage) + public PlaneLogic(ILogger logger, IPlaneStorage planeStorage) { _logger = logger; _planeStorage = planeStorage; diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ShopLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ShopLogic.cs new file mode 100644 index 0000000..7a6f6d3 --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ShopLogic.cs @@ -0,0 +1,222 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Models; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.BusinessLogics +{ + /// + /// Реализация интерфейса бизнес-логики для магазинов + /// + public class ShopLogic : IShopLogic + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Взаимодействие с хранилищем магазинов + /// + private readonly IShopStorage _shopStorage; + + /// + /// Конструктор + /// + /// + /// + public ShopLogic(ILogger logger, IShopStorage shopStorage) + { + _logger = logger; + _shopStorage = shopStorage; + } + + /// + /// Получение списка + /// + /// + /// + public List? ReadList(ShopSearchModel? model) + { + _logger.LogInformation("ReadList. ShopName:{ShopName}.Id:{ Id}", model?.ShopName, model?.Id); + + var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model); + if (list == null) + { + _logger.LogWarning("ReadList return null list"); + return null; + } + + _logger.LogInformation("ReadList. Count:{Count}", list.Count); + return list; + } + + /// + /// Получение отдельной записи + /// + /// + /// + /// + public ShopViewModel? ReadElement(ShopSearchModel model) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + + _logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.ShopName, model.Id); + + var element = _shopStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("ReadElement element not found"); + return null; + } + + _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); + return element; + } + + /// + /// Создание записи + /// + /// + /// + public bool Create(ShopBindingModel model) + { + CheckModel(model); + + if (_shopStorage.Insert(model) == null) + { + _logger.LogWarning("Insert operation failed"); + return false; + } + return true; + } + + /// + /// Изменение записи + /// + /// + /// + public bool Update(ShopBindingModel model) + { + CheckModel(model); + + if (_shopStorage.Update(model) == null) + { + _logger.LogWarning("Update operation failed"); + return false; + } + return true; + } + + /// + /// Удаление записи + /// + /// + /// + public bool Delete(ShopBindingModel model) + { + CheckModel(model, false); + _logger.LogInformation("Delete. Id:{Id}", model.Id); + + if (_shopStorage.Delete(model) == null) + { + _logger.LogWarning("Delete operation failed"); + return false; + } + return true; + } + + /// + /// Добавление изделия в магазин + /// + /// + /// + /// + /// + /// + /// + public bool AddPlaneInShop(ShopSearchModel model, IPlaneModel plane, int count) + { + if (model == null) + { + throw new ArgumentNullException(nameof(model)); + } + if (count <= 0) + { + throw new ArgumentException("Количество изделий должно быть больше 0", nameof(count)); + } + _logger.LogInformation("AddPlaneInShop. ShopName:{ShopName}.Id:{ Id}", model.ShopName, model.Id); + var element = _shopStorage.GetElement(model); + if (element == null) + { + _logger.LogWarning("AddPlaneInShop element not found"); + return false; + } + _logger.LogInformation("AddPlaneInShop find. Id:{Id}", element.Id); + + if (element.ShopPlanes.TryGetValue(plane.Id, out var pair)) + { + element.ShopPlanes[plane.Id] = (plane, count + pair.Item2); + _logger.LogInformation("AddPlaneInShop. Added {count} {plane} to '{ShopName}' shop", count, plane.PlaneName, element.ShopName); + } + else + { + element.ShopPlanes[plane.Id] = (plane, count); + _logger.LogInformation("AddPlaneInShop. Added {count} new plane {plane} to '{ShopName}' shop", count, plane.PlaneName, element.ShopName); + } + + _shopStorage.Update(new() + { + Id = element.Id, + Address = element.Address, + ShopName = element.ShopName, + DateOpening = element.DateOpening, + ShopPlanes = element.ShopPlanes + }); + 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)); + } + _logger.LogInformation("Shop. ShopName:{ShopName}.Address:{ Address}. Id:{ Id}", model.ShopName, model.Address, model.Id); + var element = _shopStorage.GetElement(new ShopSearchModel + { + ShopName = model.ShopName + }); + if (element != null && element.Id != model.Id && element.ShopName == model.ShopName) + { + throw new InvalidOperationException("Магазин с таким названием уже есть"); + } + } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/BindingModels/ShopBindingModel.cs b/AircraftPlant/AircraftPlantContracts/BindingModels/ShopBindingModel.cs new file mode 100644 index 0000000..74d61f5 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BindingModels/ShopBindingModel.cs @@ -0,0 +1,45 @@ +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.BindingModels +{ + /// + /// Модель для передачи данных пользователя + /// в методы для сохранения данных для магазинов + /// + public class ShopBindingModel : IShopModel + { + /// + /// Идентификатор + /// + public int Id { get; set; } + + /// + /// Название магазина + /// + public string ShopName { get; set; } = string.Empty; + + /// + /// Адрес магазина + /// + public string Address { get; set; } = string.Empty; + + /// + /// Дата открытия магазина + /// + public DateTime DateOpening { get; set; } = DateTime.Now; + + /// + /// Коллекция изделий в магазине + /// + public Dictionary ShopPlanes + { + get; + set; + } = new(); + } +} diff --git a/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IShopLogic.cs b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IShopLogic.cs new file mode 100644 index 0000000..f8bdb53 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IShopLogic.cs @@ -0,0 +1,62 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.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 AddPlaneInShop(ShopSearchModel model, IPlaneModel plane, int count); + } +} diff --git a/AircraftPlant/AircraftPlantContracts/SearchModels/ShopSearchModel.cs b/AircraftPlant/AircraftPlantContracts/SearchModels/ShopSearchModel.cs new file mode 100644 index 0000000..dec0ac8 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/SearchModels/ShopSearchModel.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.SearchModels +{ + /// + /// Модель для передачи данных пользователя + /// в методы для поиска данных для магазинов + /// + public class ShopSearchModel + { + /// + /// Идентификатор + /// + public int? Id { get; set; } + + /// + /// Название магазина + /// + public string? ShopName { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/StoragesContracts/IShopStorage.cs b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IShopStorage.cs new file mode 100644 index 0000000..9c89ffe --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IShopStorage.cs @@ -0,0 +1,58 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.ViewModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.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); + } +} diff --git a/AircraftPlant/AircraftPlantContracts/ViewModels/ShopViewModel.cs b/AircraftPlant/AircraftPlantContracts/ViewModels/ShopViewModel.cs new file mode 100644 index 0000000..7ca01d7 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/ViewModels/ShopViewModel.cs @@ -0,0 +1,49 @@ +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.ViewModels +{ + /// + /// Модель для передачи данных пользователю + /// для отображения для магазинов + /// + public class ShopViewModel : IShopModel + { + /// + /// Идентификатор + /// + public int Id { get; set; } + + /// + /// Название магазина + /// + [DisplayName("Название магазина")] + public string ShopName { get; set; } = string.Empty; + + /// + /// Адрес магазина + /// + [DisplayName("Адрес магазина")] + public string Address { get; set; } = string.Empty; + + /// + /// Дата открытия магазина + /// + [DisplayName("Дата открытия")] + public DateTime DateOpening { get; set; } = DateTime.Now; + + /// + /// Коллекция изделий в магазине + /// + public Dictionary ShopPlanes + { + get; + set; + } = new(); + } +} diff --git a/AircraftPlant/AircraftPlantDataModels/Models/IShopModel.cs b/AircraftPlant/AircraftPlantDataModels/Models/IShopModel.cs new file mode 100644 index 0000000..ca684fa --- /dev/null +++ b/AircraftPlant/AircraftPlantDataModels/Models/IShopModel.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantDataModels.Models +{ + /// + /// Интерфейс для модели магазина + /// + public interface IShopModel : IId + { + /// + /// Название магазина + /// + string ShopName { get; } + + /// + /// Адрес магазина + /// + string Address { get; } + + /// + /// Дата открытия магазина + /// + DateTime DateOpening { get; } + + /// + /// Коллекция изделий в магазине + /// + Dictionary ShopPlanes { get; } + } +} diff --git a/AircraftPlant/AircraftPlantListImplement/DataListSingleton.cs b/AircraftPlant/AircraftPlantListImplement/DataListSingleton.cs index eb745b4..736bfee 100644 --- a/AircraftPlant/AircraftPlantListImplement/DataListSingleton.cs +++ b/AircraftPlant/AircraftPlantListImplement/DataListSingleton.cs @@ -32,6 +32,11 @@ namespace AircraftPlantListImplement /// public List Planes { get; set; } + /// + /// Список классов-моделей магазинов + /// + public List Shops { get; set; } + /// /// Конструктор /// @@ -40,6 +45,7 @@ namespace AircraftPlantListImplement Components = new List(); Orders = new List(); Planes = new List(); + Shops = new List(); } /// diff --git a/AircraftPlant/AircraftPlantListImplement/Implements/ShopStorage.cs b/AircraftPlant/AircraftPlantListImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..9ca1ff9 --- /dev/null +++ b/AircraftPlant/AircraftPlantListImplement/Implements/ShopStorage.cs @@ -0,0 +1,154 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using AircraftPlantListImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantListImplement.Implements +{ + /// + /// Реализация интерфейса хранилища для магазина + /// + public class ShopStorage : IShopStorage + { + /// + /// Хранилище + /// + private readonly DataListSingleton _source; + + /// + /// Конструктор + /// + public ShopStorage() + { + _source = DataListSingleton.GetInstance(); + } + + /// + /// Получение полного списка + /// + /// + public List GetFullList() + { + var result = new List(); + foreach (var shop in _source.Shops) + { + result.Add(shop.GetViewModel); + } + return result; + } + + /// + /// Получение фильтрованного списка + /// + /// + /// + public List GetFilteredList(ShopSearchModel model) + { + var result = new List(); + if (string.IsNullOrEmpty(model.ShopName)) + { + return result; + } + + foreach (var shop in _source.Shops) + { + if (shop.ShopName.Contains(model.ShopName)) + { + result.Add(shop.GetViewModel); + } + } + return result; + } + + /// + /// Получение элемента + /// + /// + /// + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) + { + return null; + } + + foreach (var shop in _source.Shops) + { + if ((!string.IsNullOrEmpty(model.ShopName) && shop.ShopName == model.ShopName) || (model.Id.HasValue && shop.Id == model.Id)) + { + return shop.GetViewModel; + } + } + return null; + } + + /// + /// Добавление элемента + /// + /// + /// + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = 1; + foreach (var shop in _source.Shops) + { + if (model.Id <= shop.Id) + { + model.Id = shop.Id + 1; + } + } + + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + + _source.Shops.Add(newShop); + return newShop.GetViewModel; + } + + /// + /// Редактирование элемента + /// + /// + /// + public ShopViewModel? Update(ShopBindingModel model) + { + foreach (var shop in _source.Shops) + { + if (shop.Id == model.Id) + { + shop.Update(model); + return shop.GetViewModel; + } + } + return null; + } + + /// + /// Удаление элемента + /// + /// + /// + public ShopViewModel? Delete(ShopBindingModel model) + { + for (int i = 0; i < _source.Shops.Count; ++i) + { + if (_source.Shops[i].Id == model.Id) + { + var element = _source.Shops[i]; + _source.Shops.RemoveAt(i); + return element.GetViewModel; + } + } + return null; + } + } +} diff --git a/AircraftPlant/AircraftPlantListImplement/Models/Shop.cs b/AircraftPlant/AircraftPlantListImplement/Models/Shop.cs new file mode 100644 index 0000000..148979b --- /dev/null +++ b/AircraftPlant/AircraftPlantListImplement/Models/Shop.cs @@ -0,0 +1,97 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantListImplement.Models +{ + /// + /// Сущность "Магазин" + /// + public class Shop : IShopModel + { + /// + /// Идентификатор + /// + public int Id { get; private set; } + + /// + /// Название магазина + /// + public string ShopName { get; private set; } = string.Empty; + + /// + /// Адрес магазина + /// + public string Address { get; private set; } = string.Empty; + + /// + /// Дата открытия магазина + /// + public DateTime DateOpening { get; private set; } + + /// + /// Коллекция изделий в магазине + /// + public Dictionary ShopPlanes + { + get; + private set; + } = new Dictionary(); + + /// + /// Создание модели магазина + /// + /// + /// + public static Shop? Create(ShopBindingModel? model) + { + if (model == null) + { + return null; + } + + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Address = model.Address, + DateOpening = model.DateOpening, + ShopPlanes = model.ShopPlanes + }; + } + + /// + /// Изменение модели магазина + /// + /// + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + + ShopName = model.ShopName; + Address = model.Address; + DateOpening = model.DateOpening; + ShopPlanes = model.ShopPlanes; + } + + /// + /// Получение модели магазина + /// + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Address = Address, + DateOpening = DateOpening, + ShopPlanes = ShopPlanes + }; + } +} diff --git a/AircraftPlant/AircraftPlantView/FormCreateSupply.Designer.cs b/AircraftPlant/AircraftPlantView/FormCreateSupply.Designer.cs new file mode 100644 index 0000000..7ca6ad4 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormCreateSupply.Designer.cs @@ -0,0 +1,146 @@ +namespace AircraftPlantView +{ + partial class FormCreateSupply + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + comboBoxShop = new ComboBox(); + labelShop = new Label(); + labelPlane = new Label(); + comboBoxPlane = new ComboBox(); + numericUpDownCount = new NumericUpDown(); + labelCount = new Label(); + buttonCancel = new Button(); + buttonSave = new Button(); + ((System.ComponentModel.ISupportInitialize)numericUpDownCount).BeginInit(); + SuspendLayout(); + // + // comboBoxShop + // + comboBoxShop.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxShop.FormattingEnabled = true; + comboBoxShop.Location = new Point(90, 12); + comboBoxShop.Name = "comboBoxShop"; + comboBoxShop.Size = new Size(282, 23); + comboBoxShop.TabIndex = 0; + // + // labelShop + // + labelShop.AutoSize = true; + labelShop.Location = new Point(12, 15); + labelShop.Name = "labelShop"; + labelShop.Size = new Size(57, 15); + labelShop.TabIndex = 1; + labelShop.Text = "Магазин:"; + // + // labelPlane + // + labelPlane.AutoSize = true; + labelPlane.Location = new Point(12, 44); + labelPlane.Name = "labelPlane"; + labelPlane.Size = new Size(56, 15); + labelPlane.TabIndex = 2; + labelPlane.Text = "Изделие:"; + // + // comboBoxPlane + // + comboBoxPlane.DropDownStyle = ComboBoxStyle.DropDownList; + comboBoxPlane.FormattingEnabled = true; + comboBoxPlane.Location = new Point(90, 41); + comboBoxPlane.Name = "comboBoxPlane"; + comboBoxPlane.Size = new Size(282, 23); + comboBoxPlane.TabIndex = 3; + // + // numericUpDownCount + // + numericUpDownCount.Location = new Point(90, 70); + numericUpDownCount.Name = "numericUpDownCount"; + numericUpDownCount.Size = new Size(282, 23); + numericUpDownCount.TabIndex = 4; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(12, 72); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(75, 15); + labelCount.TabIndex = 5; + labelCount.Text = "Количество:"; + // + // buttonCancel + // + buttonCancel.Location = new Point(297, 99); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(75, 23); + buttonCancel.TabIndex = 6; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // buttonSave + // + buttonSave.Location = new Point(216, 99); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(75, 23); + buttonSave.TabIndex = 7; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // FormCreateSupply + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(384, 131); + Controls.Add(buttonSave); + Controls.Add(buttonCancel); + Controls.Add(labelCount); + Controls.Add(numericUpDownCount); + Controls.Add(comboBoxPlane); + Controls.Add(labelPlane); + Controls.Add(labelShop); + Controls.Add(comboBoxShop); + Name = "FormCreateSupply"; + Text = "Поступление"; + Load += FormCreateSupply_Load; + ((System.ComponentModel.ISupportInitialize)numericUpDownCount).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox comboBoxShop; + private Label labelShop; + private Label labelPlane; + private ComboBox comboBoxPlane; + private NumericUpDown numericUpDownCount; + private Label labelCount; + private Button buttonCancel; + private Button buttonSave; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormCreateSupply.cs b/AircraftPlant/AircraftPlantView/FormCreateSupply.cs new file mode 100644 index 0000000..b6b2fa0 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormCreateSupply.cs @@ -0,0 +1,159 @@ +using AircraftPlantBusinessLogic.BusinessLogics; +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.SearchModels; +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 AircraftPlantView +{ + /// + /// Форма для добавления поступления + /// + public partial class FormCreateSupply : Form + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Бизнес-логика для магазина + /// + private readonly IShopLogic _logicS; + + /// + /// Бизнес-логика для изделий + /// + private readonly IPlaneLogic _logicP; + + /// + /// Конструктор + /// + /// + /// + /// + public FormCreateSupply(ILogger logger, IShopLogic logicS, IPlaneLogic logicP) + { + InitializeComponent(); + _logger = logger; + _logicS = logicS; + _logicP = logicP; + } + + /// + /// Загрузка списиков магазинов и изделий + /// + /// + /// + private void FormCreateSupply_Load(object sender, EventArgs e) + { + _logger.LogInformation("Загрузка магазинов"); + try + { + var listShops = _logicS.ReadList(null); + if (listShops != null) + { + comboBoxShop.DisplayMember = "ShopName"; + comboBoxShop.ValueMember = "Id"; + comboBoxShop.DataSource = listShops; + comboBoxShop.SelectedItem = null; + } + + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка магазинов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + + _logger.LogInformation("Загрузка изделий"); + try + { + var listPlanes = _logicP.ReadList(null); + if (listPlanes != null) + { + comboBoxPlane.DisplayMember = "PlaneName"; + comboBoxPlane.ValueMember = "Id"; + comboBoxPlane.DataSource = listPlanes; + comboBoxPlane.SelectedItem = null; + } + + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка изделий"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// + /// Кнопка "Сохранить" + /// + /// + /// + private void buttonSave_Click(object sender, EventArgs e) + { + if (comboBoxShop.SelectedValue == null) + { + MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxPlane.SelectedValue == null) + { + MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Добавление изделия в магазин"); + try + { + var plane = _logicP.ReadElement(new() + { + Id = (int)comboBoxPlane.SelectedValue + }); + if (plane == null) + { + throw new Exception("Не найдено изделие. Дополнительная информация в логах."); + } + var resultOperation = _logicS.AddPlaneInShop( + new ShopSearchModel + { + Id = (int)comboBoxShop.SelectedValue + }, + plane, + (int)numericUpDownCount.Value + ); + 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/AircraftPlant/AircraftPlantView/FormCreateSupply.resx b/AircraftPlant/AircraftPlantView/FormCreateSupply.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormCreateSupply.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormMain.Designer.cs b/AircraftPlant/AircraftPlantView/FormMain.Designer.cs index a68fe27..8b19960 100644 --- a/AircraftPlant/AircraftPlantView/FormMain.Designer.cs +++ b/AircraftPlant/AircraftPlantView/FormMain.Designer.cs @@ -38,6 +38,8 @@ справочникиToolStripMenuItem = new ToolStripMenuItem(); компонентыToolStripMenuItem = new ToolStripMenuItem(); изделияToolStripMenuItem = new ToolStripMenuItem(); + магазиныToolStripMenuItem = new ToolStripMenuItem(); + buttonAddPlaneInShop = new Button(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); menuStrip.SuspendLayout(); SuspendLayout(); @@ -121,7 +123,7 @@ // // справочникиToolStripMenuItem // - справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem }); + справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, магазиныToolStripMenuItem }); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.Size = new Size(94, 20); справочникиToolStripMenuItem.Text = "Справочники"; @@ -129,22 +131,40 @@ // компонентыToolStripMenuItem // компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(145, 22); + компонентыToolStripMenuItem.Size = new Size(180, 22); компонентыToolStripMenuItem.Text = "Компоненты"; компонентыToolStripMenuItem.Click += компонентыToolStripMenuItem_Click; // // изделияToolStripMenuItem // изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; - изделияToolStripMenuItem.Size = new Size(145, 22); + изделияToolStripMenuItem.Size = new Size(180, 22); изделияToolStripMenuItem.Text = "Изделия"; изделияToolStripMenuItem.Click += изделияToolStripMenuItem_Click; // + // магазиныToolStripMenuItem + // + магазиныToolStripMenuItem.Name = "магазиныToolStripMenuItem"; + магазиныToolStripMenuItem.Size = new Size(180, 22); + магазиныToolStripMenuItem.Text = "Магазины"; + магазиныToolStripMenuItem.Click += магазиныToolStripMenuItem_Click; + // + // buttonAddPlaneInShop + // + buttonAddPlaneInShop.Location = new Point(822, 210); + buttonAddPlaneInShop.Name = "buttonAddPlaneInShop"; + buttonAddPlaneInShop.Size = new Size(150, 50); + buttonAddPlaneInShop.TabIndex = 7; + buttonAddPlaneInShop.Text = "Добавить изделие\r\nв магазин"; + buttonAddPlaneInShop.UseVisualStyleBackColor = true; + buttonAddPlaneInShop.Click += buttonAddPlaneInShop_Click; + // // FormMain // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(984, 361); + Controls.Add(buttonAddPlaneInShop); Controls.Add(buttonRefresh); Controls.Add(buttonIssuedOrder); Controls.Add(buttonOrderReady); @@ -175,5 +195,7 @@ private ToolStripMenuItem справочникиToolStripMenuItem; private ToolStripMenuItem компонентыToolStripMenuItem; private ToolStripMenuItem изделияToolStripMenuItem; + private ToolStripMenuItem магазиныToolStripMenuItem; + private Button buttonAddPlaneInShop; } } \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormMain.cs b/AircraftPlant/AircraftPlantView/FormMain.cs index 39a70bc..2006e9f 100644 --- a/AircraftPlant/AircraftPlantView/FormMain.cs +++ b/AircraftPlant/AircraftPlantView/FormMain.cs @@ -79,6 +79,20 @@ namespace AircraftPlantView } } + /// + /// Показать список всех магазинов + /// + /// + /// + private void магазиныToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShops)); + if (service is FormShops form) + { + form.ShowDialog(); + } + } + /// /// Кнопка "Создать заказ" /// @@ -179,6 +193,20 @@ namespace AircraftPlantView } } + /// + /// Кнопка "Добавить изделие в магазин" + /// + /// + /// + private void buttonAddPlaneInShop_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormCreateSupply)); + if (service is FormCreateSupply form) + { + form.ShowDialog(); + } + } + /// /// Кнопка "Обновить список" /// diff --git a/AircraftPlant/AircraftPlantView/FormShop.Designer.cs b/AircraftPlant/AircraftPlantView/FormShop.Designer.cs new file mode 100644 index 0000000..22f85ea --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormShop.Designer.cs @@ -0,0 +1,188 @@ +namespace AircraftPlantView +{ + partial class FormShop + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + labelName = new Label(); + textBoxName = new TextBox(); + labelAddress = new Label(); + textBoxAddress = new TextBox(); + dateTimePicker = new DateTimePicker(); + labelDateOpening = new Label(); + dataGridView = new DataGridView(); + ColumnID = new DataGridViewTextBoxColumn(); + ColumnPlaneName = new DataGridViewTextBoxColumn(); + ColumnCount = new DataGridViewTextBoxColumn(); + buttonCancel = new Button(); + buttonSave = new Button(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // labelName + // + labelName.AutoSize = true; + labelName.Location = new Point(12, 15); + labelName.Name = "labelName"; + labelName.Size = new Size(62, 15); + labelName.TabIndex = 0; + labelName.Text = "Название:"; + // + // textBoxName + // + textBoxName.Location = new Point(110, 12); + textBoxName.Name = "textBoxName"; + textBoxName.Size = new Size(200, 23); + textBoxName.TabIndex = 1; + // + // labelAddress + // + labelAddress.AutoSize = true; + labelAddress.Location = new Point(12, 44); + labelAddress.Name = "labelAddress"; + labelAddress.Size = new Size(43, 15); + labelAddress.TabIndex = 2; + labelAddress.Text = "Адрес:"; + // + // textBoxAddress + // + textBoxAddress.Location = new Point(110, 41); + textBoxAddress.Name = "textBoxAddress"; + textBoxAddress.Size = new Size(200, 23); + textBoxAddress.TabIndex = 3; + // + // dateTimePicker + // + dateTimePicker.Location = new Point(110, 70); + dateTimePicker.Name = "dateTimePicker"; + dateTimePicker.Size = new Size(200, 23); + dateTimePicker.TabIndex = 4; + // + // labelDateOpening + // + labelDateOpening.AutoSize = true; + labelDateOpening.Location = new Point(12, 76); + labelDateOpening.Name = "labelDateOpening"; + labelDateOpening.Size = new Size(90, 15); + labelDateOpening.TabIndex = 5; + labelDateOpening.Text = "Дата открытия:"; + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = Color.White; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnID, ColumnPlaneName, ColumnCount }); + dataGridView.GridColor = Color.White; + dataGridView.Location = new Point(12, 99); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(560, 321); + dataGridView.TabIndex = 6; + // + // ColumnID + // + ColumnID.HeaderText = "ID"; + ColumnID.Name = "ColumnID"; + ColumnID.ReadOnly = true; + ColumnID.Visible = false; + // + // ColumnPlaneName + // + ColumnPlaneName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + ColumnPlaneName.HeaderText = "Изделие"; + ColumnPlaneName.Name = "ColumnPlaneName"; + ColumnPlaneName.ReadOnly = true; + // + // ColumnCount + // + ColumnCount.HeaderText = "Количнство"; + ColumnCount.Name = "ColumnCount"; + ColumnCount.ReadOnly = true; + // + // buttonCancel + // + buttonCancel.Location = new Point(497, 426); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(75, 23); + buttonCancel.TabIndex = 7; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // buttonSave + // + buttonSave.Location = new Point(416, 426); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(75, 23); + buttonSave.TabIndex = 8; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // FormShop + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(584, 461); + Controls.Add(buttonSave); + Controls.Add(buttonCancel); + Controls.Add(dataGridView); + Controls.Add(labelDateOpening); + Controls.Add(dateTimePicker); + Controls.Add(textBoxAddress); + Controls.Add(labelAddress); + Controls.Add(textBoxName); + Controls.Add(labelName); + Name = "FormShop"; + Text = "Магазин"; + Load += FormShop_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private Label labelName; + private TextBox textBoxName; + private Label labelAddress; + private TextBox textBoxAddress; + private DateTimePicker dateTimePicker; + private Label labelDateOpening; + private DataGridView dataGridView; + private Button buttonCancel; + private Button buttonSave; + private DataGridViewTextBoxColumn ColumnID; + private DataGridViewTextBoxColumn ColumnPlaneName; + private DataGridViewTextBoxColumn ColumnCount; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormShop.cs b/AircraftPlant/AircraftPlantView/FormShop.cs new file mode 100644 index 0000000..a5a414d --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormShop.cs @@ -0,0 +1,170 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.BusinessLogicsContracts; +using AircraftPlantContracts.SearchModels; +using AircraftPlantDataModels.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 AircraftPlantView +{ + /// + /// Форма для магазина + /// + public partial class FormShop : Form + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Бизнес-логика для магазинов + /// + private readonly IShopLogic _logic; + + /// + /// Идентификатор + /// + private int? _id; + public int Id { set { _id = value; } } + + /// + /// Список изделий в магазине + /// + private Dictionary _shopPlanes; + + /// + /// Конструктор + /// + /// + /// + public FormShop(ILogger logger, IShopLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + _shopPlanes = new Dictionary(); + } + + /// + /// Загрузка списка изделий в магазине + /// + /// + /// + private void FormShop_Load(object sender, EventArgs e) + { + if (_id.HasValue) + { + _logger.LogInformation("Загрузка магазина"); + try + { + var view = _logic.ReadElement(new ShopSearchModel { Id = _id.Value }); + if (view != null) + { + textBoxName.Text = view.ShopName; + textBoxAddress.Text = view.Address; + dateTimePicker.Text = view.DateOpening.ToString(); + _shopPlanes = view.ShopPlanes ?? new Dictionary(); + LoadData(); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + /// + /// Кнопка "Сохранить" + /// + /// + /// + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxName.Text)) + { + MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (string.IsNullOrEmpty(textBoxAddress.Text)) + { + MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Сохранение магазина"); + try + { + var model = new ShopBindingModel + { + Id = _id ?? 0, + ShopName = textBoxName.Text, + Address = textBoxAddress.Text, + DateOpening = dateTimePicker.Value.Date + }; + var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); + if (!operationResult) + { + throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); + } + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка сохранения магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// + /// Кнопка "Отмена" + /// + /// + /// + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + + /// + /// Метод загрузки изделий магазина + /// + private void LoadData() + { + _logger.LogInformation("Загрузка изделий магазина"); + try + { + if (_shopPlanes != null) + { + dataGridView.Rows.Clear(); + foreach (var elem in _shopPlanes) + { + dataGridView.Rows.Add(new object[] + { + elem.Key, + elem.Value.Item1.PlaneName, + elem.Value.Item2 + }); + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки изделий магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/AircraftPlant/AircraftPlantView/FormShop.resx b/AircraftPlant/AircraftPlantView/FormShop.resx new file mode 100644 index 0000000..cfbf3c9 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormShop.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/AircraftPlant/AircraftPlantView/FormShops.Designer.cs b/AircraftPlant/AircraftPlantView/FormShops.Designer.cs new file mode 100644 index 0000000..31965d2 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormShops.Designer.cs @@ -0,0 +1,122 @@ +namespace AircraftPlantView +{ + 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 = Color.White; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Dock = DockStyle.Left; + dataGridView.GridColor = Color.White; + dataGridView.Location = new Point(0, 0); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowHeadersVisible = false; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(450, 361); + dataGridView.TabIndex = 0; + // + // buttonAdd + // + buttonAdd.Location = new Point(480, 15); + buttonAdd.Name = "buttonAdd"; + buttonAdd.Size = new Size(75, 23); + buttonAdd.TabIndex = 1; + buttonAdd.Text = "Добавить"; + buttonAdd.UseVisualStyleBackColor = true; + buttonAdd.Click += buttonAdd_Click; + // + // buttonUpdate + // + buttonUpdate.Location = new Point(480, 44); + buttonUpdate.Name = "buttonUpdate"; + buttonUpdate.Size = new Size(75, 23); + buttonUpdate.TabIndex = 2; + buttonUpdate.Text = "Изменить"; + buttonUpdate.UseVisualStyleBackColor = true; + buttonUpdate.Click += buttonUpdate_Click; + // + // buttonDelete + // + buttonDelete.Location = new Point(480, 73); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new Size(75, 23); + buttonDelete.TabIndex = 3; + buttonDelete.Text = "Удалить"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += buttonDelete_Click; + // + // buttonRefresh + // + buttonRefresh.Location = new Point(480, 102); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(75, 23); + buttonRefresh.TabIndex = 4; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += buttonRefresh_Click; + // + // FormShops + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(584, 361); + Controls.Add(buttonRefresh); + Controls.Add(buttonDelete); + Controls.Add(buttonUpdate); + Controls.Add(buttonAdd); + Controls.Add(dataGridView); + 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/AircraftPlant/AircraftPlantView/FormShops.cs b/AircraftPlant/AircraftPlantView/FormShops.cs new file mode 100644 index 0000000..c23ed43 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormShops.cs @@ -0,0 +1,153 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.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 AircraftPlantView +{ + /// + /// Форма для вывода всех магазинов + /// + 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 buttonAdd_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + if (service is FormShop form) + { + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + + /// + /// Кнопка "Изменить" + /// + /// + /// + private void buttonUpdate_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + var service = Program.ServiceProvider?.GetService(typeof(FormShop)); + if (service is FormShop form) + { + form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + } + } + + /// + /// Кнопка "Удалить" + /// + /// + /// + private void buttonDelete_Click(object sender, EventArgs e) + { + if (dataGridView.SelectedRows.Count == 1) + { + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); + _logger.LogInformation("Удаление магазина"); + try + { + if (!_logic.Delete(new ShopBindingModel { Id = id })) + { + throw new Exception("Ошибка при удалении. Дополнительная информация в логах."); + } + LoadData(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка удаления магазина"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + } + + /// + /// Кнопка "Обновить" + /// + /// + /// + private void buttonRefresh_Click(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["ShopPlanes"].Visible = false; + } + _logger.LogInformation("Загрузка магазинов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки магазинов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } +} diff --git a/AircraftPlant/AircraftPlantView/FormShops.resx b/AircraftPlant/AircraftPlantView/FormShops.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/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/AircraftPlant/AircraftPlantView/Program.cs b/AircraftPlant/AircraftPlantView/Program.cs index 90280e1..d0b5b40 100644 --- a/AircraftPlant/AircraftPlantView/Program.cs +++ b/AircraftPlant/AircraftPlantView/Program.cs @@ -49,10 +49,12 @@ namespace AircraftPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); services.AddTransient(); services.AddTransient(); @@ -61,6 +63,9 @@ namespace AircraftPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file From c92ca6304bd8a00ecde534163b0b7f6125df2269 Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Sun, 25 Feb 2024 01:25:10 +0400 Subject: [PATCH 02/11] Fix --- AircraftPlant/AircraftPlantView/FormPlane.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AircraftPlant/AircraftPlantView/FormPlane.cs b/AircraftPlant/AircraftPlantView/FormPlane.cs index 2edad4b..cb62d77 100644 --- a/AircraftPlant/AircraftPlantView/FormPlane.cs +++ b/AircraftPlant/AircraftPlantView/FormPlane.cs @@ -155,7 +155,7 @@ namespace AircraftPlantView { try { - _logger.LogInformation("Удаление компонента:{ ComponentName} - { Count}", dataGridView.SelectedRows[0].Cells[1].Value); + _logger.LogInformation("Удаление компонента:{ ComponentName} - { Count}", dataGridView.SelectedRows[0].Cells[1].Value, dataGridView.SelectedRows[0].Cells[2].Value); _planeComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value)); } catch (Exception ex) From 395e725e78d5fe6e246b1ef7ec67a3c8ec8c2834 Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Sun, 25 Feb 2024 23:08:05 +0400 Subject: [PATCH 03/11] LabWork02_Hard start --- .../BindingModels/ShopBindingModel.cs | 5 +++++ .../BusinessLogicsContracts/IShopLogic.cs | 16 ++++++++++++++++ .../StoragesContracts/IShopStorage.cs | 9 +++++++++ .../ViewModels/ShopViewModel.cs | 6 ++++++ .../AircraftPlantDataModels/Models/IShopModel.cs | 5 +++++ 5 files changed, 41 insertions(+) diff --git a/AircraftPlant/AircraftPlantContracts/BindingModels/ShopBindingModel.cs b/AircraftPlant/AircraftPlantContracts/BindingModels/ShopBindingModel.cs index 74d61f5..c8aa382 100644 --- a/AircraftPlant/AircraftPlantContracts/BindingModels/ShopBindingModel.cs +++ b/AircraftPlant/AircraftPlantContracts/BindingModels/ShopBindingModel.cs @@ -41,5 +41,10 @@ namespace AircraftPlantContracts.BindingModels get; set; } = new(); + + /// + /// Максимальное количество изделий + /// + public int MaxPlanes { get; set; } } } diff --git a/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IShopLogic.cs b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IShopLogic.cs index f8bdb53..f23492d 100644 --- a/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IShopLogic.cs +++ b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IShopLogic.cs @@ -58,5 +58,21 @@ namespace AircraftPlantContracts.BusinessLogicsContracts /// /// bool AddPlaneInShop(ShopSearchModel model, IPlaneModel plane, int count); + + /// + /// Добавление изделий в магазины + /// + /// + /// + /// + bool AddPlanes(IPlaneModel plane, int count); + + /// + /// Продажа изделий + /// + /// + /// + /// + bool SellPlanes(IPlaneModel plane, int count); } } diff --git a/AircraftPlant/AircraftPlantContracts/StoragesContracts/IShopStorage.cs b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IShopStorage.cs index 9c89ffe..9dbabac 100644 --- a/AircraftPlant/AircraftPlantContracts/StoragesContracts/IShopStorage.cs +++ b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IShopStorage.cs @@ -1,6 +1,7 @@ using AircraftPlantContracts.BindingModels; using AircraftPlantContracts.SearchModels; using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Models; using System; using System.Collections.Generic; using System.Linq; @@ -54,5 +55,13 @@ namespace AircraftPlantContracts.StoragesContracts /// /// ShopViewModel? Delete(ShopBindingModel model); + + /// + /// Продажа изделий + /// + /// + /// + /// + bool SellPlanes(IPlaneModel plane, int count); } } diff --git a/AircraftPlant/AircraftPlantContracts/ViewModels/ShopViewModel.cs b/AircraftPlant/AircraftPlantContracts/ViewModels/ShopViewModel.cs index 7ca01d7..44f1df3 100644 --- a/AircraftPlant/AircraftPlantContracts/ViewModels/ShopViewModel.cs +++ b/AircraftPlant/AircraftPlantContracts/ViewModels/ShopViewModel.cs @@ -45,5 +45,11 @@ namespace AircraftPlantContracts.ViewModels get; set; } = new(); + + /// + /// Максимальное количество изделий + /// + [DisplayName("Максимальное количество изделий")] + public int MaxPlanes { get; set; } } } diff --git a/AircraftPlant/AircraftPlantDataModels/Models/IShopModel.cs b/AircraftPlant/AircraftPlantDataModels/Models/IShopModel.cs index ca684fa..780d13a 100644 --- a/AircraftPlant/AircraftPlantDataModels/Models/IShopModel.cs +++ b/AircraftPlant/AircraftPlantDataModels/Models/IShopModel.cs @@ -30,5 +30,10 @@ namespace AircraftPlantDataModels.Models /// Коллекция изделий в магазине /// Dictionary ShopPlanes { get; } + + /// + /// Максимальное количество изделий + /// + int MaxPlanes { get; } } } From dc7cdf6cc213c1d5cd1c878122825fb9d89aa75c Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Mon, 26 Feb 2024 08:21:45 +0400 Subject: [PATCH 04/11] LabWork02_Hard Work in progress --- .../BusinessLogics/ShopLogic.cs | 28 +++ .../BusinessLogicsContracts/IShopLogic.cs | 8 - .../StoragesContracts/IShopStorage.cs | 8 + .../AircraftPlantFileImplement/Models/Shop.cs | 159 ++++++++++++++++++ .../Implements/ShopStorage.cs | 25 +++ .../AircraftPlantListImplement/Models/Shop.cs | 5 + 6 files changed, 225 insertions(+), 8 deletions(-) create mode 100644 AircraftPlant/AircraftPlantFileImplement/Models/Shop.cs diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ShopLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ShopLogic.cs index 7a6f6d3..0f2302e 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ShopLogic.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ShopLogic.cs @@ -187,6 +187,34 @@ namespace AircraftPlantBusinessLogic.BusinessLogics return true; } + /// + /// Продажа изделий + /// + /// + /// + /// + /// + /// + public bool SellPlanes(IPlaneModel plane, int count) + { + if (plane == null) + { + throw new ArgumentNullException(nameof(plane)); + } + if (count <= 0) + { + throw new ArgumentException("Количество изделий должно быть больше 0", nameof(count)); + } + + if (_shopStorage.SellPlanes(plane, count)) + { + _logger.LogInformation("Selling sucsess"); + return true; + } + _logger.LogInformation("Selling failed"); + return false; + } + /// /// Проверка модели магазина /// diff --git a/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IShopLogic.cs b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IShopLogic.cs index f23492d..2933e88 100644 --- a/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IShopLogic.cs +++ b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IShopLogic.cs @@ -59,14 +59,6 @@ namespace AircraftPlantContracts.BusinessLogicsContracts /// bool AddPlaneInShop(ShopSearchModel model, IPlaneModel plane, int count); - /// - /// Добавление изделий в магазины - /// - /// - /// - /// - bool AddPlanes(IPlaneModel plane, int count); - /// /// Продажа изделий /// diff --git a/AircraftPlant/AircraftPlantContracts/StoragesContracts/IShopStorage.cs b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IShopStorage.cs index 9dbabac..c60c3ea 100644 --- a/AircraftPlant/AircraftPlantContracts/StoragesContracts/IShopStorage.cs +++ b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IShopStorage.cs @@ -63,5 +63,13 @@ namespace AircraftPlantContracts.StoragesContracts /// /// bool SellPlanes(IPlaneModel plane, int count); + + /// + /// Проверка наличия изделий в магазинах в нужном количестве + /// + /// + /// + /// + bool Restock(IPlaneModel plane, int count); } } diff --git a/AircraftPlant/AircraftPlantFileImplement/Models/Shop.cs b/AircraftPlant/AircraftPlantFileImplement/Models/Shop.cs new file mode 100644 index 0000000..7762e08 --- /dev/null +++ b/AircraftPlant/AircraftPlantFileImplement/Models/Shop.cs @@ -0,0 +1,159 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace AircraftPlantFileImplement.Models +{ + /// + /// Сущность "Магазин" + /// + public class Shop : IShopModel + { + /// + /// Идентификатор + /// + public int Id { get; private set; } + + /// + /// Название магазина + /// + public string ShopName { get; private set; } = string.Empty; + + /// + /// Адрес магазина + /// + public string Address { get; private set; } = string.Empty; + + /// + /// Дата открытия магазина + /// + public DateTime DateOpening { get; private set; } + + /// + /// Коллекция изделий магазина в виде + /// «идентификатор изделия – количество изделий» + /// + public Dictionary Planes { get; private set; } = new(); + + /// + /// Коллекция изделий в магазине + /// + private Dictionary? _shopPlanes = null; + public Dictionary ShopPlanes + { + get + { + if (_shopPlanes == null) + { + var source = DataFileSingleton.GetInstance(); + _shopPlanes = Planes.ToDictionary(x => x.Key, y => ((source.Planes.FirstOrDefault(z => z.Id == y.Key) as IPlaneModel)!, y.Value)); + } + return _shopPlanes; + } + } + + /// + /// Максимальное количество изделий + /// + public int MaxPlanes { get; private set; } + + /// + /// Создание модели магазина из данных файла + /// + /// + /// + public static Shop? Create(XElement element) + { + if (element == null) + { + return null; + } + return new() + { + Id = Convert.ToInt32(element.Attribute("Id")!.Value), + ShopName = element.Element("ShopName")!.Value, + Address = element.Element("Address")!.Value, + DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value), + Planes = element.Element("ShopPlanes")!.Elements("ShopPlanes")! + .ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)), + MaxPlanes = Convert.ToInt32(element.Element("MaxPlanes")!.Value) + }; + } + + /// + /// Создание модели магазина + /// + /// + /// + public static Shop? Create(ShopBindingModel? model) + { + if (model == null) + { + return null; + } + + return new Shop() + { + Id = model.Id, + ShopName = model.ShopName, + Address = model.Address, + DateOpening = model.DateOpening, + Planes = model.ShopPlanes.ToDictionary(x => x.Key, x => x.Value.Item2), + MaxPlanes = model.MaxPlanes + }; + } + + /// + /// Изменение модели магазина + /// + /// + public void Update(ShopBindingModel? model) + { + if (model == null) + { + return; + } + + ShopName = model.ShopName; + Address = model.Address; + DateOpening = model.DateOpening; + Planes = model.ShopPlanes.ToDictionary(x => x.Key, x => x.Value.Item2); + MaxPlanes = model.MaxPlanes; + _shopPlanes = null; + } + + /// + /// Получение модели магазина + /// + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Address = Address, + DateOpening = DateOpening, + ShopPlanes = ShopPlanes, + MaxPlanes = MaxPlanes + }; + + /// + /// Запись данных о модели магазина в файл + /// + public XElement GetXElement => new("Shop", + new XAttribute("Id", Id), + new XElement("ShopName", ShopName), + new XElement("Address", Address), + new XElement("DateOpening", DateOpening.ToString()), + new XElement("ShopPlanes", Planes.Select(x => + new XElement("ShopPlanes", + new XElement("Key", x.Key), + new XElement("Value", x.Value)))), + new XElement("MaxPlanes", MaxPlanes.ToString() + .ToArray())); + } +} diff --git a/AircraftPlant/AircraftPlantListImplement/Implements/ShopStorage.cs b/AircraftPlant/AircraftPlantListImplement/Implements/ShopStorage.cs index 9ca1ff9..3c0baac 100644 --- a/AircraftPlant/AircraftPlantListImplement/Implements/ShopStorage.cs +++ b/AircraftPlant/AircraftPlantListImplement/Implements/ShopStorage.cs @@ -2,6 +2,7 @@ using AircraftPlantContracts.SearchModels; using AircraftPlantContracts.StoragesContracts; using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Models; using AircraftPlantListImplement.Models; using System; using System.Collections.Generic; @@ -150,5 +151,29 @@ namespace AircraftPlantListImplement.Implements } return null; } + + /// + /// Продажа изделий + /// + /// + /// + /// + /// + public bool SellPlanes(IPlaneModel plane, int count) + { + throw new NotImplementedException(); + } + + /// + /// Проверка наличия изделий в магазинах в нужном количестве + /// + /// + /// + /// + /// + public bool Restock(IPlaneModel plane, int count) + { + throw new NotImplementedException(); + } } } diff --git a/AircraftPlant/AircraftPlantListImplement/Models/Shop.cs b/AircraftPlant/AircraftPlantListImplement/Models/Shop.cs index 148979b..a73ba98 100644 --- a/AircraftPlant/AircraftPlantListImplement/Models/Shop.cs +++ b/AircraftPlant/AircraftPlantListImplement/Models/Shop.cs @@ -43,6 +43,11 @@ namespace AircraftPlantListImplement.Models private set; } = new Dictionary(); + /// + /// Максимальное количество изделий + /// + public int MaxPlanes { get; private set; } + /// /// Создание модели магазина /// From 8e6b339919c489012edaf8c0eca616fe4ffa579f Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Mon, 11 Mar 2024 02:22:57 +0400 Subject: [PATCH 05/11] LabWork02_Hard Work in progress 2 --- .../BusinessLogics/OrderLogic.cs | 110 +++++++++- .../BusinessLogics/ShopLogic.cs | 10 +- .../StoragesContracts/IShopStorage.cs | 10 +- .../DataFileSingleton.cs | 16 ++ .../Implements/ShopStorage.cs | 197 ++++++++++++++++++ .../AircraftPlantFileImplement/Models/Shop.cs | 5 +- .../Implements/ShopStorage.cs | 8 +- .../AircraftPlantListImplement/Models/Shop.cs | 7 +- .../AircraftPlantView/FormShop.Designer.cs | 28 ++- AircraftPlant/AircraftPlantView/FormShop.cs | 4 +- AircraftPlant/AircraftPlantView/FormShop.resx | 9 + 11 files changed, 385 insertions(+), 19 deletions(-) create mode 100644 AircraftPlant/AircraftPlantFileImplement/Implements/ShopStorage.cs diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs index ad4d0d4..408900e 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs @@ -4,6 +4,7 @@ using AircraftPlantContracts.SearchModels; using AircraftPlantContracts.StoragesContracts; using AircraftPlantContracts.ViewModels; using AircraftPlantDataModels.Enums; +using AircraftPlantDataModels.Models; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -28,15 +29,33 @@ namespace AircraftPlantBusinessLogic.BusinessLogics /// private readonly IOrderStorage _orderStorage; + /// + /// Взаимодействие с хранилищем магазинов + /// + private IShopStorage _shopStorage; + + /// + /// Бизнес-логика магазинов + /// + private IShopLogic _shopLogic; + + /// + /// Взаимодействие с хранилищем изделий + /// + private IPlaneStorage _planeStorage; + /// /// Конструктор /// /// /// - public OrderLogic(ILogger logger, IOrderStorage orderStorage) + public OrderLogic(ILogger logger, IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IPlaneStorage planeStorage) { _logger = logger; _orderStorage = orderStorage; + _shopStorage = shopStorage; + _shopLogic = shopLogic; + _planeStorage = planeStorage; } /// @@ -165,6 +184,21 @@ namespace AircraftPlantBusinessLogic.BusinessLogics return false; } + if (newStatus == OrderStatus.Готов) + { + var plane = _planeStorage.GetElement(new PlaneSearchModel { Id = model.Id }); + if (plane == null) + { + _logger.LogWarning("Status change error. Plane not found"); + return false; + } + if (!CheckSupply(plane, model.Count)) + { + _logger.LogWarning("Status change error. Shop doesnt have planes"); + return false; + } + } + model.Status = newStatus; if (model.Status == OrderStatus.Выдан) @@ -183,5 +217,79 @@ namespace AircraftPlantBusinessLogic.BusinessLogics } return true; } + + /// + /// Проверка заказа + /// + /// + /// + /// + public bool CheckSupply(IPlaneModel model, int count) + { + if (count <= 0) + { + _logger.LogWarning("Check supply operation error. Planes count < 0"); + return false; + } + + int sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxPlanes).Sum(); + int sumCount = _shopStorage.GetFullList().Select(x => x.ShopPlanes.Select(y => y.Value.Item2).Sum()).Sum(); + int free = sumCapacity - sumCount; + if (free < count) + { + _logger.LogWarning("Check supply error. No place for new planes"); + return false; + } + + foreach (var shop in _shopStorage.GetFullList()) + { + free = shop.MaxPlanes; + foreach (var plane in shop.ShopPlanes) + { + free -= plane.Value.Item2; + } + + if (free == 0) + { + continue; + } + + if (free >= count) + { + if (_shopLogic.AddPlaneInShop(new() + { + Id = shop.Id + }, model, count)) + { + count = 0; + } + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + else + { + if (_shopLogic.AddPlaneInShop(new() + { + Id = shop.Id + }, model, free)) + { + count -= free; + } + else + { + _logger.LogWarning("Supply error"); + return false; + } + } + if (count <= 0) + { + return true; + } + } + return false; + } } } diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ShopLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ShopLogic.cs index 0f2302e..50a74c1 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ShopLogic.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ShopLogic.cs @@ -165,6 +165,13 @@ namespace AircraftPlantBusinessLogic.BusinessLogics } _logger.LogInformation("AddPlaneInShop find. Id:{Id}", element.Id); + var countPlanes = element.ShopPlanes.Select(x => x.Value.Item2).Sum(); + if (element.MaxPlanes - countPlanes < count) + { + _logger.LogWarning("Shop is overflowed"); + return false; + } + if (element.ShopPlanes.TryGetValue(plane.Id, out var pair)) { element.ShopPlanes[plane.Id] = (plane, count + pair.Item2); @@ -182,7 +189,8 @@ namespace AircraftPlantBusinessLogic.BusinessLogics Address = element.Address, ShopName = element.ShopName, DateOpening = element.DateOpening, - ShopPlanes = element.ShopPlanes + ShopPlanes = element.ShopPlanes, + MaxPlanes = element.MaxPlanes }); return true; } diff --git a/AircraftPlant/AircraftPlantContracts/StoragesContracts/IShopStorage.cs b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IShopStorage.cs index c60c3ea..69bc7a2 100644 --- a/AircraftPlant/AircraftPlantContracts/StoragesContracts/IShopStorage.cs +++ b/AircraftPlant/AircraftPlantContracts/StoragesContracts/IShopStorage.cs @@ -59,17 +59,17 @@ namespace AircraftPlantContracts.StoragesContracts /// /// Продажа изделий /// - /// + /// /// /// - bool SellPlanes(IPlaneModel plane, int count); + bool SellPlanes(IPlaneModel model, int count); /// - /// Проверка наличия изделий в магазинах в нужном количестве + /// Проверка наличия в нужном количестве /// - /// + /// /// /// - bool Restock(IPlaneModel plane, int count); + bool CheckCount(IPlaneModel model, int count); } } diff --git a/AircraftPlant/AircraftPlantFileImplement/DataFileSingleton.cs b/AircraftPlant/AircraftPlantFileImplement/DataFileSingleton.cs index 4cd0625..b2d2414 100644 --- a/AircraftPlant/AircraftPlantFileImplement/DataFileSingleton.cs +++ b/AircraftPlant/AircraftPlantFileImplement/DataFileSingleton.cs @@ -33,6 +33,11 @@ namespace AircraftPlantFileImplement /// private readonly string PlaneFileName = "Plane.xml"; + /// + /// Название файла для хранения информации о магазинах + /// + private readonly string ShopFileName = "Shop.xml"; + /// /// Список классов-моделей компонентов /// @@ -48,6 +53,11 @@ namespace AircraftPlantFileImplement /// public List Planes { get; set; } + /// + /// Список классов-моделей магазина + /// + public List Shops { get; set; } + /// /// Конструктор /// @@ -56,6 +66,7 @@ namespace AircraftPlantFileImplement Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Planes = LoadData(PlaneFileName, "Plane", x => Plane.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; + Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!; } /// @@ -86,6 +97,11 @@ namespace AircraftPlantFileImplement /// public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); + /// + /// Сохранение магазинов + /// + public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement); + /// /// Метод для загрузки данных из xml-файла /// diff --git a/AircraftPlant/AircraftPlantFileImplement/Implements/ShopStorage.cs b/AircraftPlant/AircraftPlantFileImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..a2d1147 --- /dev/null +++ b/AircraftPlant/AircraftPlantFileImplement/Implements/ShopStorage.cs @@ -0,0 +1,197 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Models; +using AircraftPlantFileImplement.Models; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantFileImplement.Implements +{ + /// + /// Реализация интерфейса хранилища для магазина + /// + public class ShopStorage : IShopStorage + { + /// + /// Хранилище + /// + private readonly DataFileSingleton _source; + + /// + /// Конструктор + /// + public ShopStorage() + { + _source = DataFileSingleton.GetInstance(); + } + + /// + /// Получение полного списка + /// + /// + public List GetFullList() + { + return _source.Shops + .Select(x => x.GetViewModel) + .ToList(); + } + + /// + /// Получение фильтрованного списка + /// + /// + /// + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName)) + { + return new(); + } + + return _source.Shops + .Where(x => x.ShopName.Contains(model.ShopName)) + .Select(x => x.GetViewModel) + .ToList(); + } + + /// + /// Получение элемента + /// + /// + /// + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) + { + return null; + } + + return _source.Shops + .FirstOrDefault(x => + (!string.IsNullOrEmpty(model.ShopName) && + x.ShopName == model.ShopName) || + (model.Id.HasValue && x.Id == model.Id)) + ?.GetViewModel; + } + + /// + /// Добавление элемента + /// + /// + /// + public ShopViewModel? Insert(ShopBindingModel model) + { + model.Id = _source.Shops.Count > 0 ? _source.Shops.Max(x => x.Id) + 1 : 1; + + var newShop = Shop.Create(model); + if (newShop == null) + { + return null; + } + + _source.Shops.Add(newShop); + _source.SaveShops(); + return newShop.GetViewModel; + } + + /// + /// Редактирование элемента + /// + /// + /// + public ShopViewModel? Update(ShopBindingModel model) + { + var shop = _source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (shop == null) + { + return null; + } + + shop.Update(model); + _source.SaveShops(); + return shop.GetViewModel; + } + + /// + /// Удаление элемента + /// + /// + /// + public ShopViewModel? Delete(ShopBindingModel model) + { + var element = _source.Shops.FirstOrDefault(x => x.Id == model.Id); + if (element != null) + { + _source.Shops.Remove(element); + _source.SaveShops(); + return element.GetViewModel; + } + return null; + } + + /// + /// Продажа изделий + /// + /// + /// + /// + public bool SellPlanes(IPlaneModel model, int count) + { + var plane = _source.Planes.FirstOrDefault(x => x.Id == model.Id); + if (plane == null || !CheckCount(model, count)) + { + return false; + } + + foreach (var shop in _source.Shops) + { + var planes = shop.ShopPlanes; + foreach (var elem in planes.Where(x => x.Value.Item1.Id == plane.Id)) + { + var selling = Math.Min(elem.Value.Item2, count); + planes[elem.Value.Item1.Id] = (elem.Value.Item1, elem.Value.Item2 - selling); + count -= selling; + + if (count <= 0) + { + break; + } + } + + shop.Update(new ShopBindingModel + { + Id = model.Id, + ShopName = shop.ShopName, + Address = shop.Address, + DateOpening = shop.DateOpening, + ShopPlanes = planes, + MaxPlanes = shop.MaxPlanes + }); + } + + _source.SaveShops(); + return true; + } + + /// + /// Проверка наличия в нужном количестве + /// + /// + /// + /// + public bool CheckCount(IPlaneModel model, int count) + { + int store = _source.Shops + .Select(x => x.ShopPlanes + .Select(y => (y.Value.Item1.Id == model.Id ? y.Value.Item2 : 0)) + .Sum()).Sum(); + return store >= count; + } + } +} diff --git a/AircraftPlant/AircraftPlantFileImplement/Models/Shop.cs b/AircraftPlant/AircraftPlantFileImplement/Models/Shop.cs index 7762e08..e316af8 100644 --- a/AircraftPlant/AircraftPlantFileImplement/Models/Shop.cs +++ b/AircraftPlant/AircraftPlantFileImplement/Models/Shop.cs @@ -152,8 +152,7 @@ namespace AircraftPlantFileImplement.Models new XElement("ShopPlanes", Planes.Select(x => new XElement("ShopPlanes", new XElement("Key", x.Key), - new XElement("Value", x.Value)))), - new XElement("MaxPlanes", MaxPlanes.ToString() - .ToArray())); + new XElement("Value", x.Value))).ToArray()), + new XElement("MaxPlanes", MaxPlanes.ToString())); } } diff --git a/AircraftPlant/AircraftPlantListImplement/Implements/ShopStorage.cs b/AircraftPlant/AircraftPlantListImplement/Implements/ShopStorage.cs index 3c0baac..cd72d6f 100644 --- a/AircraftPlant/AircraftPlantListImplement/Implements/ShopStorage.cs +++ b/AircraftPlant/AircraftPlantListImplement/Implements/ShopStorage.cs @@ -159,19 +159,19 @@ namespace AircraftPlantListImplement.Implements /// /// /// - public bool SellPlanes(IPlaneModel plane, int count) + public bool SellPlanes(IPlaneModel model, int count) { throw new NotImplementedException(); } /// - /// Проверка наличия изделий в магазинах в нужном количестве + /// Проверка наличия в нужном количестве /// - /// + /// /// /// /// - public bool Restock(IPlaneModel plane, int count) + public bool CheckCount(IPlaneModel model, int count) { throw new NotImplementedException(); } diff --git a/AircraftPlant/AircraftPlantListImplement/Models/Shop.cs b/AircraftPlant/AircraftPlantListImplement/Models/Shop.cs index a73ba98..0c9b730 100644 --- a/AircraftPlant/AircraftPlantListImplement/Models/Shop.cs +++ b/AircraftPlant/AircraftPlantListImplement/Models/Shop.cs @@ -66,7 +66,8 @@ namespace AircraftPlantListImplement.Models ShopName = model.ShopName, Address = model.Address, DateOpening = model.DateOpening, - ShopPlanes = model.ShopPlanes + ShopPlanes = model.ShopPlanes, + MaxPlanes = model.MaxPlanes }; } @@ -85,6 +86,7 @@ namespace AircraftPlantListImplement.Models Address = model.Address; DateOpening = model.DateOpening; ShopPlanes = model.ShopPlanes; + MaxPlanes = model.MaxPlanes; } /// @@ -96,7 +98,8 @@ namespace AircraftPlantListImplement.Models ShopName = ShopName, Address = Address, DateOpening = DateOpening, - ShopPlanes = ShopPlanes + ShopPlanes = ShopPlanes, + MaxPlanes = MaxPlanes }; } } diff --git a/AircraftPlant/AircraftPlantView/FormShop.Designer.cs b/AircraftPlant/AircraftPlantView/FormShop.Designer.cs index 22f85ea..c15c129 100644 --- a/AircraftPlant/AircraftPlantView/FormShop.Designer.cs +++ b/AircraftPlant/AircraftPlantView/FormShop.Designer.cs @@ -40,7 +40,10 @@ ColumnCount = new DataGridViewTextBoxColumn(); buttonCancel = new Button(); buttonSave = new Button(); + labelMaxPlanes = new Label(); + numericUpDownMaxPlanes = new NumericUpDown(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDownMaxPlanes).BeginInit(); SuspendLayout(); // // labelName @@ -99,13 +102,13 @@ dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnID, ColumnPlaneName, ColumnCount }); dataGridView.GridColor = Color.White; - dataGridView.Location = new Point(12, 99); + dataGridView.Location = new Point(12, 128); dataGridView.MultiSelect = false; dataGridView.Name = "dataGridView"; dataGridView.ReadOnly = true; dataGridView.RowTemplate.Height = 25; dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridView.Size = new Size(560, 321); + dataGridView.Size = new Size(560, 292); dataGridView.TabIndex = 6; // // ColumnID @@ -148,11 +151,29 @@ buttonSave.UseVisualStyleBackColor = true; buttonSave.Click += buttonSave_Click; // + // labelMaxPlanes + // + labelMaxPlanes.AutoSize = true; + labelMaxPlanes.Location = new Point(12, 101); + labelMaxPlanes.Name = "labelMaxPlanes"; + labelMaxPlanes.Size = new Size(83, 15); + labelMaxPlanes.TabIndex = 9; + labelMaxPlanes.Text = "Вместимость:"; + // + // numericUpDownMaxPlanes + // + numericUpDownMaxPlanes.Location = new Point(110, 99); + numericUpDownMaxPlanes.Name = "numericUpDownMaxPlanes"; + numericUpDownMaxPlanes.Size = new Size(200, 23); + numericUpDownMaxPlanes.TabIndex = 10; + // // FormShop // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(584, 461); + Controls.Add(numericUpDownMaxPlanes); + Controls.Add(labelMaxPlanes); Controls.Add(buttonSave); Controls.Add(buttonCancel); Controls.Add(dataGridView); @@ -166,6 +187,7 @@ Text = "Магазин"; Load += FormShop_Load; ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ((System.ComponentModel.ISupportInitialize)numericUpDownMaxPlanes).EndInit(); ResumeLayout(false); PerformLayout(); } @@ -184,5 +206,7 @@ private DataGridViewTextBoxColumn ColumnID; private DataGridViewTextBoxColumn ColumnPlaneName; private DataGridViewTextBoxColumn ColumnCount; + private Label labelMaxPlanes; + private NumericUpDown numericUpDownMaxPlanes; } } \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormShop.cs b/AircraftPlant/AircraftPlantView/FormShop.cs index a5a414d..17e1f14 100644 --- a/AircraftPlant/AircraftPlantView/FormShop.cs +++ b/AircraftPlant/AircraftPlantView/FormShop.cs @@ -72,6 +72,7 @@ namespace AircraftPlantView textBoxName.Text = view.ShopName; textBoxAddress.Text = view.Address; dateTimePicker.Text = view.DateOpening.ToString(); + numericUpDownMaxPlanes.Value = view.MaxPlanes; _shopPlanes = view.ShopPlanes ?? new Dictionary(); LoadData(); } @@ -109,7 +110,8 @@ namespace AircraftPlantView Id = _id ?? 0, ShopName = textBoxName.Text, Address = textBoxAddress.Text, - DateOpening = dateTimePicker.Value.Date + DateOpening = dateTimePicker.Value.Date, + MaxPlanes = Convert.ToInt32(numericUpDownMaxPlanes.Value) }; var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); if (!operationResult) diff --git a/AircraftPlant/AircraftPlantView/FormShop.resx b/AircraftPlant/AircraftPlantView/FormShop.resx index cfbf3c9..3a1044b 100644 --- a/AircraftPlant/AircraftPlantView/FormShop.resx +++ b/AircraftPlant/AircraftPlantView/FormShop.resx @@ -126,4 +126,13 @@ True + + True + + + True + + + True + \ No newline at end of file From 30b284dda5c5ae475ebc6789ae942e133180d4f3 Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Mon, 11 Mar 2024 03:09:05 +0400 Subject: [PATCH 06/11] Fix --- .../BusinessLogics/OrderLogic.cs | 2 +- .../AircraftPlantView/FormMain.Designer.cs | 19 ++- AircraftPlant/AircraftPlantView/FormMain.cs | 14 ++ .../AircraftPlantView/FormSell.Designer.cs | 119 ++++++++++++++++ AircraftPlant/AircraftPlantView/FormSell.cs | 127 ++++++++++++++++++ AircraftPlant/AircraftPlantView/FormSell.resx | 120 +++++++++++++++++ AircraftPlant/AircraftPlantView/Program.cs | 1 + 7 files changed, 398 insertions(+), 4 deletions(-) create mode 100644 AircraftPlant/AircraftPlantView/FormSell.Designer.cs create mode 100644 AircraftPlant/AircraftPlantView/FormSell.cs create mode 100644 AircraftPlant/AircraftPlantView/FormSell.resx diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs index 408900e..870f28f 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs @@ -186,7 +186,7 @@ namespace AircraftPlantBusinessLogic.BusinessLogics if (newStatus == OrderStatus.Готов) { - var plane = _planeStorage.GetElement(new PlaneSearchModel { Id = model.Id }); + var plane = _planeStorage.GetElement(new PlaneSearchModel { Id = model.PlaneId }); if (plane == null) { _logger.LogWarning("Status change error. Plane not found"); diff --git a/AircraftPlant/AircraftPlantView/FormMain.Designer.cs b/AircraftPlant/AircraftPlantView/FormMain.Designer.cs index 8b19960..bbefa1b 100644 --- a/AircraftPlant/AircraftPlantView/FormMain.Designer.cs +++ b/AircraftPlant/AircraftPlantView/FormMain.Designer.cs @@ -40,6 +40,7 @@ изделияToolStripMenuItem = new ToolStripMenuItem(); магазиныToolStripMenuItem = new ToolStripMenuItem(); buttonAddPlaneInShop = new Button(); + buttonSellPlanes = new Button(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); menuStrip.SuspendLayout(); SuspendLayout(); @@ -131,21 +132,21 @@ // компонентыToolStripMenuItem // компонентыToolStripMenuItem.Name = "компонентыToolStripMenuItem"; - компонентыToolStripMenuItem.Size = new Size(180, 22); + компонентыToolStripMenuItem.Size = new Size(145, 22); компонентыToolStripMenuItem.Text = "Компоненты"; компонентыToolStripMenuItem.Click += компонентыToolStripMenuItem_Click; // // изделияToolStripMenuItem // изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; - изделияToolStripMenuItem.Size = new Size(180, 22); + изделияToolStripMenuItem.Size = new Size(145, 22); изделияToolStripMenuItem.Text = "Изделия"; изделияToolStripMenuItem.Click += изделияToolStripMenuItem_Click; // // магазиныToolStripMenuItem // магазиныToolStripMenuItem.Name = "магазиныToolStripMenuItem"; - магазиныToolStripMenuItem.Size = new Size(180, 22); + магазиныToolStripMenuItem.Size = new Size(145, 22); магазиныToolStripMenuItem.Text = "Магазины"; магазиныToolStripMenuItem.Click += магазиныToolStripMenuItem_Click; // @@ -159,11 +160,22 @@ buttonAddPlaneInShop.UseVisualStyleBackColor = true; buttonAddPlaneInShop.Click += buttonAddPlaneInShop_Click; // + // buttonSellPlanes + // + buttonSellPlanes.Location = new Point(822, 266); + buttonSellPlanes.Name = "buttonSellPlanes"; + buttonSellPlanes.Size = new Size(150, 23); + buttonSellPlanes.TabIndex = 8; + buttonSellPlanes.Text = "Продать изделия"; + buttonSellPlanes.UseVisualStyleBackColor = true; + buttonSellPlanes.Click += buttonSellPlanes_Click; + // // FormMain // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(984, 361); + Controls.Add(buttonSellPlanes); Controls.Add(buttonAddPlaneInShop); Controls.Add(buttonRefresh); Controls.Add(buttonIssuedOrder); @@ -197,5 +209,6 @@ private ToolStripMenuItem изделияToolStripMenuItem; private ToolStripMenuItem магазиныToolStripMenuItem; private Button buttonAddPlaneInShop; + private Button buttonSellPlanes; } } \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormMain.cs b/AircraftPlant/AircraftPlantView/FormMain.cs index 2006e9f..8241ddb 100644 --- a/AircraftPlant/AircraftPlantView/FormMain.cs +++ b/AircraftPlant/AircraftPlantView/FormMain.cs @@ -207,6 +207,20 @@ namespace AircraftPlantView } } + /// + /// Кнопка "Продать изделия" + /// + /// + /// + private void buttonSellPlanes_Click(object sender, EventArgs e) + { + var services = Program.ServiceProvider?.GetService(typeof(FormSell)); + if (services is FormSell form) + { + form.ShowDialog(); + } + } + /// /// Кнопка "Обновить список" /// diff --git a/AircraftPlant/AircraftPlantView/FormSell.Designer.cs b/AircraftPlant/AircraftPlantView/FormSell.Designer.cs new file mode 100644 index 0000000..000ee23 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormSell.Designer.cs @@ -0,0 +1,119 @@ +namespace AircraftPlantView +{ + 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() + { + comboBoxPlane = new ComboBox(); + labelPlane = new Label(); + labelCount = new Label(); + buttonCancel = new Button(); + buttonSave = new Button(); + textBoxCount = new TextBox(); + SuspendLayout(); + // + // comboBoxPlane + // + comboBoxPlane.FormattingEnabled = true; + comboBoxPlane.Location = new Point(90, 12); + comboBoxPlane.Name = "comboBoxPlane"; + comboBoxPlane.Size = new Size(282, 23); + comboBoxPlane.TabIndex = 0; + // + // labelPlane + // + labelPlane.AutoSize = true; + labelPlane.Location = new Point(12, 15); + labelPlane.Name = "labelPlane"; + labelPlane.Size = new Size(56, 15); + labelPlane.TabIndex = 2; + labelPlane.Text = "Изделие:"; + // + // labelCount + // + labelCount.AutoSize = true; + labelCount.Location = new Point(12, 43); + labelCount.Name = "labelCount"; + labelCount.Size = new Size(75, 15); + labelCount.TabIndex = 3; + labelCount.Text = "Количество:"; + // + // buttonCancel + // + buttonCancel.Location = new Point(297, 76); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new Size(75, 23); + buttonCancel.TabIndex = 4; + buttonCancel.Text = "Отмена"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += buttonCancel_Click; + // + // buttonSave + // + buttonSave.Location = new Point(216, 76); + buttonSave.Name = "buttonSave"; + buttonSave.Size = new Size(75, 23); + buttonSave.TabIndex = 5; + buttonSave.Text = "Сохранить"; + buttonSave.UseVisualStyleBackColor = true; + buttonSave.Click += buttonSave_Click; + // + // textBoxCount + // + textBoxCount.Location = new Point(90, 41); + textBoxCount.Name = "textBoxCount"; + textBoxCount.Size = new Size(282, 23); + textBoxCount.TabIndex = 6; + // + // FormSell + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(384, 111); + Controls.Add(textBoxCount); + Controls.Add(buttonSave); + Controls.Add(buttonCancel); + Controls.Add(labelCount); + Controls.Add(labelPlane); + Controls.Add(comboBoxPlane); + Name = "FormSell"; + Text = "Продажа"; + Load += FormSell_Load; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private ComboBox comboBoxPlane; + private Label labelPlane; + private Label labelCount; + private Button buttonCancel; + private Button buttonSave; + private TextBox textBoxCount; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormSell.cs b/AircraftPlant/AircraftPlantView/FormSell.cs new file mode 100644 index 0000000..e95a35d --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormSell.cs @@ -0,0 +1,127 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.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 AircraftPlantView +{ + /// + /// Форма продажи изделий + /// + public partial class FormSell : Form + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Бизнес-логика для изделий + /// + private readonly IPlaneLogic _logicP; + + /// + /// Бизнес-логика для магазинов + /// + private readonly IShopLogic _logicS; + + /// + /// Конструктор + /// + /// + /// + /// + public FormSell(ILogger logger, IPlaneLogic planeLogic, IShopLogic shopLogic) + { + InitializeComponent(); + _logger = logger; + _logicP = planeLogic; + _logicS = shopLogic; + } + + /// + /// Загрузка списка изделий + /// + /// + /// + private void FormSell_Load(object sender, EventArgs e) + { + _logger.LogInformation("Загрузка изделий для продажи"); + try + { + var list = _logicP.ReadList(null); + if (list != null) + { + comboBoxPlane.DisplayMember = "PlaneName"; + comboBoxPlane.ValueMember = "Id"; + comboBoxPlane.DataSource = list; + comboBoxPlane.SelectedItem = null; + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка изделий"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// + /// Кнопка "Сохранить" + /// + /// + /// + private void buttonSave_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(textBoxCount.Text)) + { + MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + if (comboBoxPlane.SelectedValue == null) + { + MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; + } + _logger.LogInformation("Продажа изделий"); + _logger.LogInformation("Создание заказа"); + try + { + var operationResult = _logicS.SellPlanes( + _logicP.ReadElement(new() { Id = Convert.ToInt32(comboBoxPlane.SelectedValue) }), + Convert.ToInt32(textBoxCount.Text) + ); + if (!operationResult) + { + throw new Exception("Ошибка при продаже изделий. Дополнительная информация в логах."); + } + MessageBox.Show("Продажа прошла успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); + DialogResult = DialogResult.OK; + Close(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка продажи изделий"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// + /// Кнопка "Отмена" + /// + /// + /// + private void buttonCancel_Click(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } +} diff --git a/AircraftPlant/AircraftPlantView/FormSell.resx b/AircraftPlant/AircraftPlantView/FormSell.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/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/AircraftPlant/AircraftPlantView/Program.cs b/AircraftPlant/AircraftPlantView/Program.cs index f9be320..4899db7 100644 --- a/AircraftPlant/AircraftPlantView/Program.cs +++ b/AircraftPlant/AircraftPlantView/Program.cs @@ -66,6 +66,7 @@ namespace AircraftPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file From 5d4ee306ce8615bf834f37659e434bf3d7eae24e Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Mon, 11 Mar 2024 03:16:54 +0400 Subject: [PATCH 07/11] Fix --- .../Implements/OrderStorage.cs | 32 ++++++++++++++----- AircraftPlant/AircraftPlantView/FormSell.cs | 2 +- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/AircraftPlant/AircraftPlantFileImplement/Implements/OrderStorage.cs b/AircraftPlant/AircraftPlantFileImplement/Implements/OrderStorage.cs index a0eaf82..61e31bd 100644 --- a/AircraftPlant/AircraftPlantFileImplement/Implements/OrderStorage.cs +++ b/AircraftPlant/AircraftPlantFileImplement/Implements/OrderStorage.cs @@ -8,6 +8,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; +using System.Xml.Linq; namespace AircraftPlantFileImplement.Implements { @@ -36,7 +37,7 @@ namespace AircraftPlantFileImplement.Implements public List GetFullList() { return _source.Orders - .Select(x => x.GetViewModel) + .Select(x => GetViewModel(x)) .ToList(); } @@ -54,7 +55,7 @@ namespace AircraftPlantFileImplement.Implements return _source.Orders .Where(x => x.Id.Equals(model.Id)) - .Select(x => x.GetViewModel) + .Select(x => GetViewModel(x)) .ToList(); } @@ -70,9 +71,8 @@ namespace AircraftPlantFileImplement.Implements return null; } - return _source.Orders - .FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id)) - ?.GetViewModel; + return GetViewModel(_source.Orders + .FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))); } /// @@ -92,7 +92,7 @@ namespace AircraftPlantFileImplement.Implements _source.Orders.Add(newOrder); _source.SaveOrders(); - return newOrder.GetViewModel; + return GetViewModel(newOrder); } /// @@ -110,7 +110,7 @@ namespace AircraftPlantFileImplement.Implements order.Update(model); _source.SaveOrders(); - return order.GetViewModel; + return GetViewModel(order); } /// @@ -125,9 +125,25 @@ namespace AircraftPlantFileImplement.Implements { _source.Orders.Remove(element); _source.SaveOrders(); - return element.GetViewModel; + return GetViewModel(element); } return null; } + + /// + /// Получение модели заказа + /// + /// + /// + private OrderViewModel GetViewModel(Order order) + { + var viewModel = order.GetViewModel; + var plane = _source.Planes.FirstOrDefault(x => x.Id == order.PlaneId); + if (plane != null) + { + viewModel.PlaneName = plane.PlaneName; + } + return viewModel; + } } } diff --git a/AircraftPlant/AircraftPlantView/FormSell.cs b/AircraftPlant/AircraftPlantView/FormSell.cs index e95a35d..82963ca 100644 --- a/AircraftPlant/AircraftPlantView/FormSell.cs +++ b/AircraftPlant/AircraftPlantView/FormSell.cs @@ -39,7 +39,7 @@ namespace AircraftPlantView /// /// /// - public FormSell(ILogger logger, IPlaneLogic planeLogic, IShopLogic shopLogic) + public FormSell(ILogger logger, IPlaneLogic planeLogic, IShopLogic shopLogic) { InitializeComponent(); _logger = logger; From 5a144131bda8180d84bef9d35a81504cb3abdc68 Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Mon, 11 Mar 2024 04:44:47 +0400 Subject: [PATCH 08/11] Fix --- .../BusinessLogics/OrderLogic.cs | 12 ++++++------ AircraftPlant/AircraftPlantView/FormShop.cs | 1 + 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs index 870f28f..41901c2 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/OrderLogic.cs @@ -184,23 +184,23 @@ namespace AircraftPlantBusinessLogic.BusinessLogics return false; } - if (newStatus == OrderStatus.Готов) + model.Status = newStatus; + + if (newStatus == OrderStatus.Выдан) { - var plane = _planeStorage.GetElement(new PlaneSearchModel { Id = model.PlaneId }); + var plane = _planeStorage.GetElement(new PlaneSearchModel { Id = element.PlaneId }); if (plane == null) { _logger.LogWarning("Status change error. Plane not found"); return false; } - if (!CheckSupply(plane, model.Count)) + if (!CheckSupply(plane, element.Count)) { - _logger.LogWarning("Status change error. Shop doesnt have planes"); + _logger.LogWarning("Status change error. Shop is overflowed"); return false; } } - model.Status = newStatus; - if (model.Status == OrderStatus.Выдан) { model.DateImplement = DateTime.Now; diff --git a/AircraftPlant/AircraftPlantView/FormShop.cs b/AircraftPlant/AircraftPlantView/FormShop.cs index 17e1f14..dc022f6 100644 --- a/AircraftPlant/AircraftPlantView/FormShop.cs +++ b/AircraftPlant/AircraftPlantView/FormShop.cs @@ -111,6 +111,7 @@ namespace AircraftPlantView ShopName = textBoxName.Text, Address = textBoxAddress.Text, DateOpening = dateTimePicker.Value.Date, + ShopPlanes = _shopPlanes, MaxPlanes = Convert.ToInt32(numericUpDownMaxPlanes.Value) }; var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); From 855bcfd6ec0ef8480bc7f70a4f8c7c811420d250 Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Mon, 25 Mar 2024 02:43:47 +0400 Subject: [PATCH 09/11] LabWork03_Hard --- .../AircraftPlantDatabase.cs | 10 + .../Implements/ShopStorage.cs | 218 ++++++++++++++++ .../20240324224237_HardCreate.Designer.cs | 246 ++++++++++++++++++ .../Migrations/20240324224237_HardCreate.cs | 78 ++++++ .../AircraftPlantDatabaseModelSnapshot.cs | 77 ++++++ .../Models/Shop.cs | 157 +++++++++++ .../Models/ShopPlane.cs | 48 ++++ 7 files changed, 834 insertions(+) create mode 100644 AircraftPlant/AircraftPlantDatabaseImplement/Implements/ShopStorage.cs create mode 100644 AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240324224237_HardCreate.Designer.cs create mode 100644 AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240324224237_HardCreate.cs create mode 100644 AircraftPlant/AircraftPlantDatabaseImplement/Models/Shop.cs create mode 100644 AircraftPlant/AircraftPlantDatabaseImplement/Models/ShopPlane.cs diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/AircraftPlantDatabase.cs b/AircraftPlant/AircraftPlantDatabaseImplement/AircraftPlantDatabase.cs index 549c5f6..3b35d4f 100644 --- a/AircraftPlant/AircraftPlantDatabaseImplement/AircraftPlantDatabase.cs +++ b/AircraftPlant/AircraftPlantDatabaseImplement/AircraftPlantDatabase.cs @@ -45,5 +45,15 @@ namespace AircraftPlantDatabaseImplement /// Таблица заказов /// public virtual DbSet Orders { set; get; } + + /// + /// Таблица магазинов + /// + public virtual DbSet Shops { set; get; } + + /// + /// Связь между магазинами и изделиями + /// + public virtual DbSet ShopPlanes { set; get; } } } diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Implements/ShopStorage.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Implements/ShopStorage.cs new file mode 100644 index 0000000..ef8750a --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Implements/ShopStorage.cs @@ -0,0 +1,218 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.SearchModels; +using AircraftPlantContracts.StoragesContracts; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDatabaseImplement.Models; +using AircraftPlantDataModels.Models; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantDatabaseImplement.Implements +{ + /// + /// Реализация интерфейса хранилища для магазинов + /// + public class ShopStorage : IShopStorage + { + /// + /// Получение полного списка + /// + /// + public List GetFullList() + { + using var context = new AircraftPlantDatabase(); + return context.Shops + .Include(x => x.Planes) + .ThenInclude(x => x.Plane) + .ToList() + .Select(x => x.GetViewModel) + .ToList(); + } + + /// + /// Получение фильтрованного списка + /// + /// + /// + public List GetFilteredList(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName)) + { + return new(); + } + + using var context = new AircraftPlantDatabase(); + return context.Shops + .Include(x => x.Planes) + .ThenInclude(x => x.Plane) + .Where(x => x.ShopName.Contains(model.ShopName)) + .ToList() + .Select(x => x.GetViewModel) + .ToList(); + } + + /// + /// Получение элемента + /// + /// + /// + public ShopViewModel? GetElement(ShopSearchModel model) + { + if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue) + { + return null; + } + + using var context = new AircraftPlantDatabase(); + return context.Shops + .Include(x => x.Planes) + .ThenInclude(x => x.Plane) + .FirstOrDefault(x => (!string.IsNullOrEmpty(model.ShopName) && + x.ShopName == model.ShopName) || + (model.Id.HasValue && x.Id == model.Id)) + ?.GetViewModel; + } + + /// + /// Добавление элемента + /// + /// + /// + public ShopViewModel? Insert(ShopBindingModel model) + { + using var context = new AircraftPlantDatabase(); + var newShop = Shop.Create(context, model); + if (newShop == null) + { + return null; + } + + context.Shops.Add(newShop); + context.SaveChanges(); + return newShop.GetViewModel; + } + + /// + /// Редактирование элемента + /// + /// + /// + public ShopViewModel? Update(ShopBindingModel model) + { + using var context = new AircraftPlantDatabase(); + using var transaction = context.Database.BeginTransaction(); + try + { + var shop = context.Shops.FirstOrDefault(rec => rec.Id == model.Id); + if (shop == null) + { + return null; + } + + shop.Update(model); + context.SaveChanges(); + shop.UpdatePlanes(context, model); + transaction.Commit(); + return shop.GetViewModel; + } + catch + { + transaction.Rollback(); + throw; + } + } + + /// + /// Удаление элемента + /// + /// + /// + public ShopViewModel? Delete(ShopBindingModel model) + { + using var context = new AircraftPlantDatabase(); + var element = context.Shops + .Include(x => x.Planes) + .FirstOrDefault(rec => rec.Id == model.Id); + if (element != null) + { + context.Shops.Remove(element); + context.SaveChanges(); + return element.GetViewModel; + } + return null; + } + + /// + /// Продажа изделий + /// + /// + /// + /// + public bool SellPlanes(IPlaneModel model, int count) + { + using var context = new AircraftPlantDatabase(); + using var transaction = context.Database.BeginTransaction(); + try + { + var shops = context.Shops + .Include(x => x.Planes) + .ThenInclude(x => x.Plane) + .ToList() + .Where(x => x.ShopPlanes.ContainsKey(model.Id)); + + foreach (var shop in shops) + { + int countInCurrentShop = shop.ShopPlanes[model.Id].Item2; + if (countInCurrentShop <= count) + { + var elem = context.ShopPlanes + .Where(x => x.PlaneId == model.Id) + .FirstOrDefault(x => x.ShopId == shop.Id); + context.ShopPlanes.Remove(elem); + shop.ShopPlanes.Remove(model.Id); + count -= countInCurrentShop; + } + else + { + shop.ShopPlanes[model.Id] = (shop.ShopPlanes[model.Id].Item1, countInCurrentShop - count); + count = 0; + shop.Update(new ShopBindingModel + { + Id = shop.Id, + ShopPlanes = shop.ShopPlanes + }); + } + if (count <= 0) + { + context.SaveChanges(); + transaction.Commit(); + return true; + } + } + transaction.Rollback(); + return false; + } + catch + { + transaction.Rollback(); + throw; + } + } + + /// + /// Проверка наличия в нужном количестве + /// + /// + /// + /// + /// + public bool CheckCount(IPlaneModel model, int count) + { + throw new NotImplementedException(); + } + } +} diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240324224237_HardCreate.Designer.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240324224237_HardCreate.Designer.cs new file mode 100644 index 0000000..9f22ccf --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240324224237_HardCreate.Designer.cs @@ -0,0 +1,246 @@ +// +using System; +using AircraftPlantDatabaseImplement; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace AircraftPlantDatabaseImplement.Migrations +{ + [DbContext(typeof(AircraftPlantDatabase))] + [Migration("20240324224237_HardCreate")] + partial class HardCreate + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "7.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Component", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Cost") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Components"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("DateCreate") + .HasColumnType("datetime2"); + + b.Property("DateImplement") + .HasColumnType("datetime2"); + + b.Property("PlaneId") + .HasColumnType("int"); + + b.Property("Status") + .HasColumnType("int"); + + b.Property("Sum") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.HasIndex("PlaneId"); + + b.ToTable("Orders"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Plane", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("PlaneName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Price") + .HasColumnType("float"); + + b.HasKey("Id"); + + b.ToTable("Planes"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.PlaneComponent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ComponentId") + .HasColumnType("int"); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("PlaneId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("ComponentId"); + + b.HasIndex("PlaneId"); + + b.ToTable("PlaneComponents"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DateOpening") + .HasColumnType("datetime2"); + + b.Property("MaxPlanes") + .HasColumnType("int"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.ShopPlane", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("PlaneId") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("PlaneId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopPlanes"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Order", b => + { + b.HasOne("AircraftPlantDatabaseImplement.Models.Plane", null) + .WithMany("Orders") + .HasForeignKey("PlaneId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.PlaneComponent", b => + { + b.HasOne("AircraftPlantDatabaseImplement.Models.Component", "Component") + .WithMany("PlaneComponents") + .HasForeignKey("ComponentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AircraftPlantDatabaseImplement.Models.Plane", "Plane") + .WithMany("Components") + .HasForeignKey("PlaneId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Component"); + + b.Navigation("Plane"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.ShopPlane", b => + { + b.HasOne("AircraftPlantDatabaseImplement.Models.Plane", "Plane") + .WithMany() + .HasForeignKey("PlaneId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AircraftPlantDatabaseImplement.Models.Shop", "Shop") + .WithMany("Planes") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Plane"); + + b.Navigation("Shop"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Component", b => + { + b.Navigation("PlaneComponents"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Plane", b => + { + b.Navigation("Components"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Shop", b => + { + b.Navigation("Planes"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240324224237_HardCreate.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240324224237_HardCreate.cs new file mode 100644 index 0000000..1dda3f4 --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/20240324224237_HardCreate.cs @@ -0,0 +1,78 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace AircraftPlantDatabaseImplement.Migrations +{ + /// + public partial class HardCreate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "Shops", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ShopName = table.Column(type: "nvarchar(max)", nullable: false), + Address = table.Column(type: "nvarchar(max)", nullable: false), + DateOpening = table.Column(type: "datetime2", nullable: false), + MaxPlanes = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_Shops", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "ShopPlanes", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ShopId = table.Column(type: "int", nullable: false), + PlaneId = table.Column(type: "int", nullable: false), + Count = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ShopPlanes", x => x.Id); + table.ForeignKey( + name: "FK_ShopPlanes_Planes_PlaneId", + column: x => x.PlaneId, + principalTable: "Planes", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ShopPlanes_Shops_ShopId", + column: x => x.ShopId, + principalTable: "Shops", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_ShopPlanes_PlaneId", + table: "ShopPlanes", + column: "PlaneId"); + + migrationBuilder.CreateIndex( + name: "IX_ShopPlanes_ShopId", + table: "ShopPlanes", + column: "ShopId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ShopPlanes"); + + migrationBuilder.DropTable( + name: "Shops"); + } + } +} diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/AircraftPlantDatabaseModelSnapshot.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/AircraftPlantDatabaseModelSnapshot.cs index 2f4a9d4..38a5ebd 100644 --- a/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/AircraftPlantDatabaseModelSnapshot.cs +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Migrations/AircraftPlantDatabaseModelSnapshot.cs @@ -121,6 +121,59 @@ namespace AircraftPlantDatabaseImplement.Migrations b.ToTable("PlaneComponents"); }); + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Shop", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Address") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DateOpening") + .HasColumnType("datetime2"); + + b.Property("MaxPlanes") + .HasColumnType("int"); + + b.Property("ShopName") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("Shops"); + }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.ShopPlane", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Count") + .HasColumnType("int"); + + b.Property("PlaneId") + .HasColumnType("int"); + + b.Property("ShopId") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("PlaneId"); + + b.HasIndex("ShopId"); + + b.ToTable("ShopPlanes"); + }); + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Order", b => { b.HasOne("AircraftPlantDatabaseImplement.Models.Plane", null) @@ -149,6 +202,25 @@ namespace AircraftPlantDatabaseImplement.Migrations b.Navigation("Plane"); }); + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.ShopPlane", b => + { + b.HasOne("AircraftPlantDatabaseImplement.Models.Plane", "Plane") + .WithMany() + .HasForeignKey("PlaneId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("AircraftPlantDatabaseImplement.Models.Shop", "Shop") + .WithMany("Planes") + .HasForeignKey("ShopId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Plane"); + + b.Navigation("Shop"); + }); + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Component", b => { b.Navigation("PlaneComponents"); @@ -160,6 +232,11 @@ namespace AircraftPlantDatabaseImplement.Migrations b.Navigation("Orders"); }); + + modelBuilder.Entity("AircraftPlantDatabaseImplement.Models.Shop", b => + { + b.Navigation("Planes"); + }); #pragma warning restore 612, 618 } } diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Models/Shop.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Models/Shop.cs new file mode 100644 index 0000000..3d71c89 --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Models/Shop.cs @@ -0,0 +1,157 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.ViewModels; +using AircraftPlantDataModels.Models; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using System.Net.Http.Headers; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantDatabaseImplement.Models +{ + /// + /// Сущность "Магазин" + /// + public class Shop : IShopModel + { + /// + /// Идентификатор + /// + public int Id { get; set; } + + /// + /// Название магазина + /// + [Required] + public string ShopName { get; set; } = string.Empty; + + /// + /// Адрес магазина + /// + [Required] + public string Address { get; set; } = string.Empty; + + /// + /// Дата открытия магазина + /// + [Required] + public DateTime DateOpening { get; set; } + + /// + /// Коллекция изделий в магазине + /// + private Dictionary? _shopPlanes = null; + + [NotMapped] + public Dictionary ShopPlanes + { + get + { + if (_shopPlanes == null) + { + _shopPlanes = Planes + .ToDictionary(recSP => recSP.PlaneId, recSP => (recSP.Plane as IPlaneModel, recSP.Count)); + } + return _shopPlanes; + } + } + + /// + /// Максимальное количество изделий + /// + public int MaxPlanes { get; set; } + + /// + /// Связь с классом связи магазина и изделий + /// + [ForeignKey("ShopId")] + public List Planes { get; set; } = new(); + + /// + /// Создание модели магазина + /// + /// + /// + /// + public static Shop Create(AircraftPlantDatabase context, ShopBindingModel model) + { + return new Shop + { + Id = model.Id, + ShopName = model.ShopName, + Address = model.Address, + DateOpening = model.DateOpening, + MaxPlanes = model.MaxPlanes, + Planes = model.ShopPlanes.Select(x => new ShopPlane + { + Plane = context.Planes.First(y => y.Id == x.Key), + Count = x.Value.Item2 + }).ToList() + }; + } + + /// + /// Изменение модели магазина + /// + /// + public void Update(ShopBindingModel model) + { + ShopName = model.ShopName; + Address = model.Address; + DateOpening = model.DateOpening; + MaxPlanes = model.MaxPlanes; + } + + /// + /// Получение модели магазина + /// + public ShopViewModel GetViewModel => new() + { + Id = Id, + ShopName = ShopName, + Address = Address, + DateOpening = DateOpening, + ShopPlanes = ShopPlanes, + MaxPlanes = MaxPlanes + }; + + /// + /// Метод обновления списка связей + /// + /// + /// + public void UpdatePlanes(AircraftPlantDatabase context, ShopBindingModel model) + { + var shopPlanes = context.ShopPlanes.Where(rec => rec.ShopId == model.Id).ToList(); + if (shopPlanes != null && shopPlanes.Count > 0) + { + // Удаление изделий, которых нет в магазине + context.ShopPlanes.RemoveRange(shopPlanes.Where(rec => !model.ShopPlanes.ContainsKey(rec.PlaneId))); + context.SaveChanges(); + // Обновление количества у существующих записей + foreach (var updatePlanes in shopPlanes) + { + updatePlanes.Count = model.ShopPlanes[updatePlanes.PlaneId].Item2; + model.ShopPlanes.Remove(updatePlanes.PlaneId); + } + context.SaveChanges(); + } + + var shop = context.Shops.First(x => x.Id == Id); + foreach (var sp in model.ShopPlanes) + { + context.ShopPlanes.Add(new ShopPlane + { + Shop = shop, + Plane = context.Planes.First(x => x.Id == sp.Key), + Count = sp.Value.Item2 + }); + context.SaveChanges(); + } + _shopPlanes = null; + } + } +} diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Models/ShopPlane.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Models/ShopPlane.cs new file mode 100644 index 0000000..df9a0e4 --- /dev/null +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Models/ShopPlane.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantDatabaseImplement.Models +{ + /// + /// Класс для связи магазина и изделия + /// + public class ShopPlane + { + /// + /// Идентификатор + /// + public int Id { get; set; } + + /// + /// Идентификатор магазина + /// + [Required] + public int ShopId { get; set; } + + /// + /// Идентификатор изделия + /// + [Required] + public int PlaneId { get; set; } + + /// + /// Количество изделий + /// + [Required] + public int Count { get; set; } + + /// + /// Магазин + /// + public virtual Shop Shop { get; set; } = new(); + + /// + /// Изделие + /// + public virtual Plane Plane { get; set; } = new(); + } +} From b22d11075225cb08115e6c78d80888b1cb6911ef Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Mon, 25 Mar 2024 10:05:23 +0400 Subject: [PATCH 10/11] Fix --- .../Implements/ShopStorage.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/AircraftPlant/AircraftPlantDatabaseImplement/Implements/ShopStorage.cs b/AircraftPlant/AircraftPlantDatabaseImplement/Implements/ShopStorage.cs index ef8750a..5dedc8d 100644 --- a/AircraftPlant/AircraftPlantDatabaseImplement/Implements/ShopStorage.cs +++ b/AircraftPlant/AircraftPlantDatabaseImplement/Implements/ShopStorage.cs @@ -180,10 +180,14 @@ namespace AircraftPlantDatabaseImplement.Implements { shop.ShopPlanes[model.Id] = (shop.ShopPlanes[model.Id].Item1, countInCurrentShop - count); count = 0; - shop.Update(new ShopBindingModel + shop.UpdatePlanes(context, new ShopBindingModel { Id = shop.Id, - ShopPlanes = shop.ShopPlanes + ShopName = shop.ShopName, + Address = shop.Address, + DateOpening = shop.DateOpening, + ShopPlanes = shop.ShopPlanes, + MaxPlanes = shop.MaxPlanes }); } if (count <= 0) From 09cbc915f8eca48864c26b938b5e65afcd5c456b Mon Sep 17 00:00:00 2001 From: Factorino73 Date: Mon, 8 Apr 2024 00:02:59 +0400 Subject: [PATCH 11/11] LabWork04_Hard --- .../BusinessLogics/ReportLogic.cs | 83 +++- .../OfficePackage/AbstractSaveToExcel.cs | 76 +++ .../OfficePackage/AbstractSaveToPdf.cs | 33 ++ .../OfficePackage/AbstractSaveToWord.cs | 59 +++ .../OfficePackage/HelperModels/ExcelInfo.cs | 5 + .../OfficePackage/HelperModels/PdfInfo.cs | 5 + .../OfficePackage/HelperModels/WordInfo.cs | 5 + .../OfficePackage/HelperModels/WordRow.cs | 25 + .../OfficePackage/Implements/SaveToWord.cs | 90 ++++ .../BusinessLogicsContracts/IReportLogic.cs | 30 ++ .../ViewModels/ReportGroupOrdersViewModel.cs | 29 ++ .../ViewModels/ReportShopPlanesViewModel.cs | 29 ++ .../AircraftPlantView/FormMain.Designer.cs | 73 ++- AircraftPlant/AircraftPlantView/FormMain.cs | 45 +- .../FormReportGroupOrders.Designer.cs | 85 ++++ .../FormReportGroupOrders.cs | 107 +++++ .../FormReportGroupOrders.resx | 120 +++++ .../FormReportShopPlanes.Designer.cs | 110 +++++ .../AircraftPlantView/FormReportShopPlanes.cs | 101 ++++ .../FormReportShopPlanes.resx | 138 ++++++ AircraftPlant/AircraftPlantView/Program.cs | 2 + .../AircraftPlantView/ReportGroupOrders.rdlc | 441 ++++++++++++++++++ 22 files changed, 1666 insertions(+), 25 deletions(-) create mode 100644 AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordRow.cs create mode 100644 AircraftPlant/AircraftPlantContracts/ViewModels/ReportGroupOrdersViewModel.cs create mode 100644 AircraftPlant/AircraftPlantContracts/ViewModels/ReportShopPlanesViewModel.cs create mode 100644 AircraftPlant/AircraftPlantView/FormReportGroupOrders.Designer.cs create mode 100644 AircraftPlant/AircraftPlantView/FormReportGroupOrders.cs create mode 100644 AircraftPlant/AircraftPlantView/FormReportGroupOrders.resx create mode 100644 AircraftPlant/AircraftPlantView/FormReportShopPlanes.Designer.cs create mode 100644 AircraftPlant/AircraftPlantView/FormReportShopPlanes.cs create mode 100644 AircraftPlant/AircraftPlantView/FormReportShopPlanes.resx create mode 100644 AircraftPlant/AircraftPlantView/ReportGroupOrders.rdlc diff --git a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ReportLogic.cs b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ReportLogic.cs index bc84035..f8b9be9 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ReportLogic.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/BusinessLogics/ReportLogic.cs @@ -33,6 +33,11 @@ namespace AircraftPlantBusinessLogic.BusinessLogics /// private readonly IOrderStorage _orderStorage; + /// + /// Хранилище магазинов + /// + private readonly IShopStorage _shopStorage; + /// /// Взаимодействие с отчетами в Excel-формате /// @@ -57,12 +62,13 @@ namespace AircraftPlantBusinessLogic.BusinessLogics /// /// /// - public ReportLogic(IPlaneStorage planeStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, + public ReportLogic(IPlaneStorage planeStorage, IComponentStorage componentStorage, IOrderStorage orderStorage, IShopStorage shopStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf) { _planeStorage = planeStorage; _componentStorage = componentStorage; _orderStorage = orderStorage; + _shopStorage = shopStorage; _saveToExcel = saveToExcel; _saveToWord = saveToWord; @@ -102,6 +108,39 @@ namespace AircraftPlantBusinessLogic.BusinessLogics .ToList(); } + /// + /// Получение списка заказов с группировкой по датам + /// + /// + public List GetGroupOrders() + { + return _orderStorage.GetFullList() + .GroupBy(x => x.DateCreate.Date) + .Select(x => new ReportGroupOrdersViewModel + { + DateCreate = x.Key, + Count = x.Count(), + Sum = x.Select(y => y.Sum).Sum() + }) + .ToList(); + } + + /// + /// Получение списка магазинов с указанием хранимых изделий + /// + /// + public List GetShopPlanes() + { + return _shopStorage.GetFullList() + .Select(x => new ReportShopPlanesViewModel + { + ShopName = x.ShopName, + Planes = x.ShopPlanes.Select(x => (x.Value.Item1.PlaneName, x.Value.Item2)).ToList(), + TotalCount = x.ShopPlanes.Select(x => x.Value.Item2).Sum() + }) + .ToList(); + } + /// /// Сохранение изделий в Word-файл /// @@ -145,5 +184,47 @@ namespace AircraftPlantBusinessLogic.BusinessLogics Orders = GetOrders(model) }); } + + /// + /// Сохранение магазинов в Word-файл + /// + /// + public void SaveShopsToWordFile(ReportBindingModel model) + { + _saveToWord.CreateShopsDoc(new WordInfo + { + FileName = model.FileName, + Title = "Список магазинов", + Shops = _shopStorage.GetFullList() + }); + } + + /// + /// Сохранение магазинов с указанием изделий в файл-Excel + /// + /// + public void SaveShopPlanesToExcelFile(ReportBindingModel model) + { + _saveToExcel.CreateShopPlanesReport(new ExcelInfo + { + FileName = model.FileName, + Title = "Ассортимент магазинов", + ShopPlanes = GetShopPlanes() + }); + } + + /// + /// Сохранение заказов с группировкой по датам в файл-Pdf + /// + /// + public void SaveGroupOrdersToPdfFile(ReportBindingModel model) + { + _saveToPdf.CreateGroupOrdersDoc(new PdfInfo + { + FileName= model.FileName, + Title = "Список заказов с группировкой по датам", + GroupOrders = GetGroupOrders() + }); + } } } diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs index 24a60fe..91bc3fa 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToExcel.cs @@ -88,6 +88,82 @@ namespace AircraftPlantBusinessLogic.OfficePackage SaveExcel(info); } + /// + /// Создание отчета в Excel-формате + /// по магазинам с расшифровкой по изделиям + /// + /// + public void CreateShopPlanesReport(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 sp in info.ShopPlanes) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = sp.ShopName, + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + + foreach (var (Plane, Count) in sp.Planes) + { + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "B", + RowIndex = rowIndex, + Text = Plane, + StyleInfo = ExcelStyleInfoType.TextWithBroder + }); + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = Count.ToString(), + StyleInfo = ExcelStyleInfoType.TextWithBroder + }); + + rowIndex++; + } + + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "A", + RowIndex = rowIndex, + Text = "Итого", + StyleInfo = ExcelStyleInfoType.Text + }); + InsertCellInWorksheet(new ExcelCellParameters + { + ColumnName = "C", + RowIndex = rowIndex, + Text = sp.TotalCount.ToString(), + StyleInfo = ExcelStyleInfoType.Text + }); + rowIndex++; + } + + SaveExcel(info); + } + /// /// Создание excel-файла /// diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs index 3c94b74..2854b8d 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToPdf.cs @@ -46,6 +46,39 @@ namespace AircraftPlantBusinessLogic.OfficePackage SavePdf(info); } + /// + /// Создание отчета в Pdf-формате + /// по закзам с группировкой по датам + /// + /// + public void CreateGroupOrdersDoc(PdfInfo info) + { + CreatePdf(info); + CreateParagraph(new PdfParagraph { Text = info.Title, Style = "NormalTitle", ParagraphAlignment = PdfParagraphAlignmentType.Center }); + + CreateTable(new List { "4cm", "3cm", "2cm" }); + + CreateRow(new PdfRowParameters + { + Texts = new List { "Дата заказа", "Количество", "Сумма" }, + Style = "NormalTitle", + ParagraphAlignment = PdfParagraphAlignmentType.Center + }); + + foreach (var order in info.GroupOrders) + { + CreateRow(new PdfRowParameters + { + Texts = new List { order.DateCreate.ToShortDateString(), order.Count.ToString(), order.Sum.ToString() }, + Style = "Normal", + ParagraphAlignment = PdfParagraphAlignmentType.Left + }); + } + CreateParagraph(new PdfParagraph { Text = $"Итого: {info.GroupOrders.Sum(x => x.Sum)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right }); + + SavePdf(info); + } + /// /// Создание pdf-файла /// diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs index 14ef29e..6dd7d35 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/AbstractSaveToWord.cs @@ -1,5 +1,6 @@ using AircraftPlantBusinessLogic.OfficePackage.HelperEnums; using AircraftPlantBusinessLogic.OfficePackage.HelperModels; +using DocumentFormat.OpenXml.Wordprocessing; using System; using System.Collections.Generic; using System.Linq; @@ -51,6 +52,52 @@ namespace AircraftPlantBusinessLogic.OfficePackage SaveWord(info); } + /// + /// Создание отчета по магазинам в doc-формате + /// + /// + public void CreateShopsDoc(WordInfo info) + { + CreateWord(info); + + CreateParagraph(new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24", }) }, + TextProperties = new WordTextProperties + { + Size = "24", + JustificationType = WordJustificationType.Center + } + }); + + CreateTable(new List { "3000", "3000", "3000" }); + CreateRow(new WordRow + { + Texts = new List { "Название", "Адрес", "Дата открытия" }, + TextProperties = new WordTextProperties + { + Size = "24", + Bold = true, + JustificationType = WordJustificationType.Center + } + }); + + foreach (var shop in info.Shops) + { + CreateRow(new WordRow + { + Texts = new List { shop.ShopName, shop.Address, shop.DateOpening.ToString() }, + TextProperties = new WordTextProperties + { + Size = "22", + JustificationType = WordJustificationType.Both + } + }); + } + + SaveWord(info); + } + /// /// Создание doc-файла /// @@ -63,6 +110,18 @@ namespace AircraftPlantBusinessLogic.OfficePackage /// protected abstract void CreateParagraph(WordParagraph paragraph); + /// + /// Создание таблицы + /// + /// + protected abstract void CreateTable(List columns); + + /// + /// Создание строки + /// + /// + protected abstract void CreateRow(WordRow row); + /// /// Сохранение файла /// diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs index 4cfd44d..68846b8 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/ExcelInfo.cs @@ -27,5 +27,10 @@ namespace AircraftPlantBusinessLogic.OfficePackage.HelperModels /// Список изделий с расшифровкой по компонентам /// public List PlaneComponents { get; set; } = new(); + + /// + /// Список магазинов с расшифровкой по изделиям + /// + public List ShopPlanes { get; set; } = new(); } } diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs index 9a4090a..db84a6f 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/PdfInfo.cs @@ -37,5 +37,10 @@ namespace AircraftPlantBusinessLogic.OfficePackage.HelperModels /// Список заказов /// public List Orders { get; set; } = new(); + + /// + /// Список заказов с группировкой по датам + /// + public List GroupOrders { get; set; } = new(); } } diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs index cb2f368..728c63a 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordInfo.cs @@ -27,5 +27,10 @@ namespace AircraftPlantBusinessLogic.OfficePackage.HelperModels /// Список изделий /// public List Planes { get; set; } = new(); + + /// + /// Список магазинов + /// + public List Shops { get; set; } = new(); } } diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordRow.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordRow.cs new file mode 100644 index 0000000..fec096b --- /dev/null +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/HelperModels/WordRow.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantBusinessLogic.OfficePackage.HelperModels +{ + /// + /// Модель для передачи данных + /// для создания строки файла-Word + /// + public class WordRow + { + /// + /// Список текстов в строке + /// + public List Texts { get; set; } = new(); + + /// + /// Свойства строки + /// + public WordTextProperties? TextProperties { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/Implements/SaveToWord.cs b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/Implements/SaveToWord.cs index 4645dca..57ba632 100644 --- a/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/Implements/SaveToWord.cs +++ b/AircraftPlant/AircraftPlantBusinessLogic/OfficePackage/Implements/SaveToWord.cs @@ -6,6 +6,7 @@ using DocumentFormat.OpenXml.Wordprocessing; using System; using System.Collections.Generic; using System.Linq; +using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; @@ -26,6 +27,11 @@ namespace AircraftPlantBusinessLogic.OfficePackage.Implements /// private Body? _docBody; + /// + /// Таблица + /// + private Table? _table; + /// /// Получение типа выравнивания текста /// @@ -141,6 +147,90 @@ namespace AircraftPlantBusinessLogic.OfficePackage.Implements _docBody.AppendChild(docParagraph); } + /// + /// Создание таблицы + /// + /// + protected override void CreateTable(List columns) + { + if (_docBody == null) + { + return; + } + + _table = new Table(); + + var tableProperties = new TableProperties(); + tableProperties.AppendChild(new TableLayout { Type = TableLayoutValues.Fixed }); + tableProperties.AppendChild(new TableBorders( + new TopBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new LeftBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new RightBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new BottomBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new InsideHorizontalBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 }, + new InsideVerticalBorder() { Val = new EnumValue(BorderValues.Single), Size = 4 } + )); + tableProperties.AppendChild(new TableWidth { Type = TableWidthUnitValues.Auto }); + _table.AppendChild(tableProperties); + + TableGrid tableGrid = new TableGrid(); + foreach (var column in columns) + { + tableGrid.AppendChild(new GridColumn() { Width = column }); + } + _table.AppendChild(tableGrid); + + _docBody.AppendChild(_table); + } + + /// + /// Создание строки + /// + /// + protected override void CreateRow(WordRow row) + { + if (_docBody == null || _table == null) + { + return; + } + + TableRow docRow = new TableRow(); + foreach (var column in row.Texts) + { + var docParagraph = new Paragraph(); + WordParagraph paragraph = new WordParagraph + { + Texts = new List<(string, WordTextProperties)> { (column, row.TextProperties) }, + TextProperties = row.TextProperties + }; + + docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties)); + + foreach (var run in paragraph.Texts) + { + var docRun = new Run(); + + var properties = new RunProperties(); + properties.AppendChild(new FontSize { Val = run.Item2.Size }); + if (run.Item2.Bold) + { + properties.AppendChild(new Bold()); + } + docRun.AppendChild(properties); + + docRun.AppendChild(new Text { Text = run.Item1, Space = SpaceProcessingModeValues.Preserve }); + + docParagraph.AppendChild(docRun); + } + + TableCell docCell = new TableCell(); + docCell.AppendChild(docParagraph); + docRow.AppendChild(docCell); + } + + _table.AppendChild(docRow); + } + /// /// Сохранение файла /// diff --git a/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IReportLogic.cs b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IReportLogic.cs index e53d342..98b0bd5 100644 --- a/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IReportLogic.cs +++ b/AircraftPlant/AircraftPlantContracts/BusinessLogicsContracts/IReportLogic.cs @@ -26,6 +26,18 @@ namespace AircraftPlantContracts.BusinessLogicsContracts /// List GetOrders(ReportBindingModel model); + /// + /// Получение списка заказов с группировкой по датам + /// + /// + List GetGroupOrders(); + + /// + /// Получение списка магазинов с указанием хранимых изделий + /// + /// + List GetShopPlanes(); + /// /// Сохранение изделий в файл-Word /// @@ -43,5 +55,23 @@ namespace AircraftPlantContracts.BusinessLogicsContracts /// /// void SaveOrdersToPdfFile(ReportBindingModel model); + + /// + /// Сохранение магазинов в Word-файл + /// + /// + void SaveShopsToWordFile(ReportBindingModel model); + + /// + /// Сохранение магазинов с указанием изделий в файл-Excel + /// + /// + void SaveShopPlanesToExcelFile(ReportBindingModel model); + + /// + /// Сохранение заказов с группировкой по датам в файл-Pdf + /// + /// + void SaveGroupOrdersToPdfFile(ReportBindingModel model); } } diff --git a/AircraftPlant/AircraftPlantContracts/ViewModels/ReportGroupOrdersViewModel.cs b/AircraftPlant/AircraftPlantContracts/ViewModels/ReportGroupOrdersViewModel.cs new file mode 100644 index 0000000..b7d8a75 --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/ViewModels/ReportGroupOrdersViewModel.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.ViewModels +{ + /// + /// Модель для отчета по заказам с группировкой по датам + /// + public class ReportGroupOrdersViewModel + { + /// + /// Дата создания заказа + /// + public DateTime DateCreate { get; set; } + + /// + /// Количество изделий + /// + public int Count { get; set; } + + /// + /// Сумма заказа + /// + public double Sum { get; set; } + } +} diff --git a/AircraftPlant/AircraftPlantContracts/ViewModels/ReportShopPlanesViewModel.cs b/AircraftPlant/AircraftPlantContracts/ViewModels/ReportShopPlanesViewModel.cs new file mode 100644 index 0000000..290471b --- /dev/null +++ b/AircraftPlant/AircraftPlantContracts/ViewModels/ReportShopPlanesViewModel.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AircraftPlantContracts.ViewModels +{ + /// + /// Модель для отчета по магазинам с расшифровкой по изделиям + /// + public class ReportShopPlanesViewModel + { + /// + /// Название магазина + /// + public string ShopName { get; set; } = string.Empty; + + /// + /// Максимальное количество изделий + /// + public int TotalCount { get; set; } + + /// + /// Список изделий в магазине + /// + public List<(string Plane, int Count)> Planes { get; set; } = new(); + } +} diff --git a/AircraftPlant/AircraftPlantView/FormMain.Designer.cs b/AircraftPlant/AircraftPlantView/FormMain.Designer.cs index 6a7ada2..ab50ec4 100644 --- a/AircraftPlant/AircraftPlantView/FormMain.Designer.cs +++ b/AircraftPlant/AircraftPlantView/FormMain.Designer.cs @@ -39,12 +39,15 @@ компонентыToolStripMenuItem = new ToolStripMenuItem(); изделияToolStripMenuItem = new ToolStripMenuItem(); магазиныToolStripMenuItem = new ToolStripMenuItem(); - buttonAddPlaneInShop = new Button(); - buttonSellPlanes = new Button(); отчетыToolStripMenuItem = new ToolStripMenuItem(); изделияToolStripMenuItem1 = new ToolStripMenuItem(); изделияСКомпонентамиToolStripMenuItem = new ToolStripMenuItem(); списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); + buttonAddPlaneInShop = new Button(); + buttonSellPlanes = new Button(); + заказыСГруппировкойToolStripMenuItem = new ToolStripMenuItem(); + списокМагазиновToolStripMenuItem = new ToolStripMenuItem(); + ассортиментМагазиновToolStripMenuItem = new ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); menuStrip.SuspendLayout(); SuspendLayout(); @@ -154,29 +157,9 @@ магазиныToolStripMenuItem.Text = "Магазины"; магазиныToolStripMenuItem.Click += магазиныToolStripMenuItem_Click; // - // buttonAddPlaneInShop - // - buttonAddPlaneInShop.Location = new Point(822, 210); - buttonAddPlaneInShop.Name = "buttonAddPlaneInShop"; - buttonAddPlaneInShop.Size = new Size(150, 50); - buttonAddPlaneInShop.TabIndex = 7; - buttonAddPlaneInShop.Text = "Добавить изделие\r\nв магазин"; - buttonAddPlaneInShop.UseVisualStyleBackColor = true; - buttonAddPlaneInShop.Click += buttonAddPlaneInShop_Click; - // - // buttonSellPlanes - // - buttonSellPlanes.Location = new Point(822, 266); - buttonSellPlanes.Name = "buttonSellPlanes"; - buttonSellPlanes.Size = new Size(150, 23); - buttonSellPlanes.TabIndex = 8; - buttonSellPlanes.Text = "Продать изделия"; - buttonSellPlanes.UseVisualStyleBackColor = true; - buttonSellPlanes.Click += buttonSellPlanes_Click; - // // отчетыToolStripMenuItem // - отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { изделияToolStripMenuItem1, изделияСКомпонентамиToolStripMenuItem, списокЗаказовToolStripMenuItem }); + отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { изделияToolStripMenuItem1, изделияСКомпонентамиToolStripMenuItem, списокЗаказовToolStripMenuItem, заказыСГруппировкойToolStripMenuItem, списокМагазиновToolStripMenuItem, ассортиментМагазиновToolStripMenuItem }); отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem"; отчетыToolStripMenuItem.Size = new Size(60, 20); отчетыToolStripMenuItem.Text = "Отчеты"; @@ -202,6 +185,47 @@ списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; // + // buttonAddPlaneInShop + // + buttonAddPlaneInShop.Location = new Point(822, 210); + buttonAddPlaneInShop.Name = "buttonAddPlaneInShop"; + buttonAddPlaneInShop.Size = new Size(150, 50); + buttonAddPlaneInShop.TabIndex = 7; + buttonAddPlaneInShop.Text = "Добавить изделие\r\nв магазин"; + buttonAddPlaneInShop.UseVisualStyleBackColor = true; + buttonAddPlaneInShop.Click += buttonAddPlaneInShop_Click; + // + // buttonSellPlanes + // + buttonSellPlanes.Location = new Point(822, 266); + buttonSellPlanes.Name = "buttonSellPlanes"; + buttonSellPlanes.Size = new Size(150, 23); + buttonSellPlanes.TabIndex = 8; + buttonSellPlanes.Text = "Продать изделия"; + buttonSellPlanes.UseVisualStyleBackColor = true; + buttonSellPlanes.Click += buttonSellPlanes_Click; + // + // заказыСГруппировкойToolStripMenuItem + // + заказыСГруппировкойToolStripMenuItem.Name = "заказыСГруппировкойToolStripMenuItem"; + заказыСГруппировкойToolStripMenuItem.Size = new Size(250, 22); + заказыСГруппировкойToolStripMenuItem.Text = "Список заказов с группировкой"; + заказыСГруппировкойToolStripMenuItem.Click += заказыСГруппировкойToolStripMenuItem_Click; + // + // списокМагазиновToolStripMenuItem + // + списокМагазиновToolStripMenuItem.Name = "списокМагазиновToolStripMenuItem"; + списокМагазиновToolStripMenuItem.Size = new Size(250, 22); + списокМагазиновToolStripMenuItem.Text = "Список магазинов"; + списокМагазиновToolStripMenuItem.Click += списокМагазиновToolStripMenuItem_Click; + // + // ассортиментМагазиновToolStripMenuItem + // + ассортиментМагазиновToolStripMenuItem.Name = "ассортиментМагазиновToolStripMenuItem"; + ассортиментМагазиновToolStripMenuItem.Size = new Size(250, 22); + ассортиментМагазиновToolStripMenuItem.Text = "Ассортимент магазинов"; + ассортиментМагазиновToolStripMenuItem.Click += ассортиментМагазиновToolStripMenuItem_Click; + // // FormMain // AutoScaleDimensions = new SizeF(7F, 15F); @@ -246,5 +270,8 @@ private ToolStripMenuItem изделияToolStripMenuItem1; private ToolStripMenuItem изделияСКомпонентамиToolStripMenuItem; private ToolStripMenuItem списокЗаказовToolStripMenuItem; + private ToolStripMenuItem заказыСГруппировкойToolStripMenuItem; + private ToolStripMenuItem списокМагазиновToolStripMenuItem; + private ToolStripMenuItem ассортиментМагазиновToolStripMenuItem; } } \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormMain.cs b/AircraftPlant/AircraftPlantView/FormMain.cs index f7e8e3a..6ba6319 100644 --- a/AircraftPlant/AircraftPlantView/FormMain.cs +++ b/AircraftPlant/AircraftPlantView/FormMain.cs @@ -113,7 +113,7 @@ namespace AircraftPlantView MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); } } - + /// /// Получить отчет по изделиям с расшифровкой по компонентам /// @@ -142,6 +142,49 @@ namespace AircraftPlantView } } + /// + /// Получить отчет по заказам с группировкой по датам + /// + /// + /// + private void заказыСГруппировкойToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportGroupOrders)); + if (service is FormReportGroupOrders form) + { + form.ShowDialog(); + } + } + + /// + /// Получить отчет со списком магазинов + /// + /// + /// + private void списокМагазиновToolStripMenuItem_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + _reportLogic.SaveShopsToWordFile(new ReportBindingModel { FileName = dialog.FileName }); + MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + + /// + /// Получить отчет по ассортименту магазинов + /// + /// + /// + private void ассортиментМагазиновToolStripMenuItem_Click(object sender, EventArgs e) + { + var service = Program.ServiceProvider?.GetService(typeof(FormReportShopPlanes)); + if (service is FormReportShopPlanes form) + { + form.ShowDialog(); + } + } + /// /// Кнопка "Создать заказ" /// diff --git a/AircraftPlant/AircraftPlantView/FormReportGroupOrders.Designer.cs b/AircraftPlant/AircraftPlantView/FormReportGroupOrders.Designer.cs new file mode 100644 index 0000000..66e1889 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportGroupOrders.Designer.cs @@ -0,0 +1,85 @@ +namespace AircraftPlantView +{ + partial class FormReportGroupOrders + { + /// + /// 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() + { + panelControl = new Panel(); + buttonMake = new Button(); + buttonToPdf = new Button(); + panelControl.SuspendLayout(); + SuspendLayout(); + // + // panelControl + // + panelControl.Controls.Add(buttonMake); + panelControl.Controls.Add(buttonToPdf); + panelControl.Dock = DockStyle.Top; + panelControl.Location = new Point(0, 0); + panelControl.Name = "panelControl"; + panelControl.Size = new Size(800, 47); + panelControl.TabIndex = 5; + // + // buttonMake + // + buttonMake.Location = new Point(589, 12); + buttonMake.Name = "buttonMake"; + buttonMake.Size = new Size(118, 23); + buttonMake.TabIndex = 5; + buttonMake.Text = "Сформировать"; + buttonMake.UseVisualStyleBackColor = true; + buttonMake.Click += buttonMake_Click; + // + // buttonToPdf + // + buttonToPdf.Location = new Point(713, 12); + buttonToPdf.Name = "buttonToPdf"; + buttonToPdf.Size = new Size(75, 23); + buttonToPdf.TabIndex = 4; + buttonToPdf.Text = "В Pdf"; + buttonToPdf.UseVisualStyleBackColor = true; + buttonToPdf.Click += buttonToPdf_Click; + // + // FormReportGroupOrders + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 361); + Controls.Add(panelControl); + Name = "FormReportGroupOrders"; + Text = "Заказы с группировкой по датам"; + panelControl.ResumeLayout(false); + ResumeLayout(false); + } + + #endregion + + private Panel panelControl; + private Button buttonMake; + private Button buttonToPdf; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormReportGroupOrders.cs b/AircraftPlant/AircraftPlantView/FormReportGroupOrders.cs new file mode 100644 index 0000000..eb89468 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportGroupOrders.cs @@ -0,0 +1,107 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.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 AircraftPlantView +{ + /// + /// Форма формирования отчета по заказам с группировкой по датам + /// + public partial class FormReportGroupOrders : Form + { + /// + /// Отчет + /// + private readonly ReportViewer reportViewer; + + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Бизнес-логика для отчетов + /// + private readonly IReportLogic _logic; + + /// + /// Конструктор + /// + public FormReportGroupOrders(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + + _logger = logger; + _logic = logic; + + reportViewer = new ReportViewer + { + Dock = DockStyle.Fill + }; + reportViewer.LocalReport.LoadReportDefinition(new FileStream("ReportGroupOrders.rdlc", FileMode.Open)); + Controls.Clear(); + Controls.Add(reportViewer); + Controls.Add(panelControl); + } + + /// + /// Кнопка "Сформировать" + /// + /// + /// + private void buttonMake_Click(object sender, EventArgs e) + { + try + { + var dataSource = _logic.GetGroupOrders(); + var source = new ReportDataSource("DataSetGroupOrders", dataSource); + reportViewer.LocalReport.DataSources.Clear(); + reportViewer.LocalReport.DataSources.Add(source); + reportViewer.RefreshReport(); + _logger.LogInformation("Загрузка списка заказов с группировкой по датам"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки списка заказов c группировкой по датам"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// + /// Кнопка "В Pdf" + /// + /// + /// + private void buttonToPdf_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + _logic.SaveGroupOrdersToPdfFile(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/AircraftPlant/AircraftPlantView/FormReportGroupOrders.resx b/AircraftPlant/AircraftPlantView/FormReportGroupOrders.resx new file mode 100644 index 0000000..af32865 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportGroupOrders.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/AircraftPlant/AircraftPlantView/FormReportShopPlanes.Designer.cs b/AircraftPlant/AircraftPlantView/FormReportShopPlanes.Designer.cs new file mode 100644 index 0000000..9f95e2d --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportShopPlanes.Designer.cs @@ -0,0 +1,110 @@ +namespace AircraftPlantView +{ + partial class FormReportShopPlanes + { + /// + /// 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() + { + buttonSaveToExcel = new Button(); + dataGridView = new DataGridView(); + ColumnShopName = new DataGridViewTextBoxColumn(); + ColumnPlaneName = new DataGridViewTextBoxColumn(); + ColumnCount = new DataGridViewTextBoxColumn(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + SuspendLayout(); + // + // buttonSaveToExcel + // + buttonSaveToExcel.Dock = DockStyle.Top; + buttonSaveToExcel.Location = new Point(0, 0); + buttonSaveToExcel.Name = "buttonSaveToExcel"; + buttonSaveToExcel.Size = new Size(584, 23); + buttonSaveToExcel.TabIndex = 2; + buttonSaveToExcel.Text = "Сохранить в Excel"; + buttonSaveToExcel.UseVisualStyleBackColor = true; + buttonSaveToExcel.Click += buttonSaveToExcel_Click; + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.BackgroundColor = Color.White; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnShopName, ColumnPlaneName, ColumnCount }); + dataGridView.Dock = DockStyle.Bottom; + dataGridView.GridColor = Color.Black; + dataGridView.Location = new Point(0, 29); + dataGridView.MultiSelect = false; + dataGridView.Name = "dataGridView"; + dataGridView.ReadOnly = true; + dataGridView.RowTemplate.Height = 25; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.Size = new Size(584, 332); + dataGridView.TabIndex = 3; + // + // ColumnShopName + // + ColumnShopName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + ColumnShopName.HeaderText = "Магазин"; + ColumnShopName.Name = "ColumnShopName"; + ColumnShopName.ReadOnly = true; + // + // ColumnPlaneName + // + ColumnPlaneName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; + ColumnPlaneName.HeaderText = "Изделие"; + ColumnPlaneName.Name = "ColumnPlaneName"; + ColumnPlaneName.ReadOnly = true; + // + // ColumnCount + // + ColumnCount.HeaderText = "Количество"; + ColumnCount.Name = "ColumnCount"; + ColumnCount.ReadOnly = true; + // + // FormReportShopPlanes + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(584, 361); + Controls.Add(dataGridView); + Controls.Add(buttonSaveToExcel); + Name = "FormReportShopPlanes"; + Text = "Ассортимент магазинов"; + Load += FormReportShopPlanes_Load; + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + ResumeLayout(false); + } + + #endregion + + private Button buttonSaveToExcel; + private DataGridView dataGridView; + private DataGridViewTextBoxColumn ColumnShopName; + private DataGridViewTextBoxColumn ColumnPlaneName; + private DataGridViewTextBoxColumn ColumnCount; + } +} \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/FormReportShopPlanes.cs b/AircraftPlant/AircraftPlantView/FormReportShopPlanes.cs new file mode 100644 index 0000000..60c13a2 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportShopPlanes.cs @@ -0,0 +1,101 @@ +using AircraftPlantContracts.BindingModels; +using AircraftPlantContracts.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 AircraftPlantView +{ + /// + /// Форма формирования отчета с ассортиментом магазинов + /// + public partial class FormReportShopPlanes : Form + { + /// + /// Логгер + /// + private readonly ILogger _logger; + + /// + /// Взаимодействие с отчетами + /// + private readonly IReportLogic _logic; + + /// + /// Конструктор + /// + public FormReportShopPlanes(ILogger logger, IReportLogic logic) + { + InitializeComponent(); + _logger = logger; + _logic = logic; + } + + /// + /// Загрузка данных + /// + /// + /// + private void FormReportShopPlanes_Load(object sender, EventArgs e) + { + try + { + var dict = _logic.GetShopPlanes(); + if (dict != null) + { + dataGridView.Rows.Clear(); + foreach (var elem in dict) + { + dataGridView.Rows.Add(new object[] { elem.ShopName, "", "" }); + foreach (var listElem in elem.Planes) + { + dataGridView.Rows.Add(new object[] { "", listElem.Item1, listElem.Item2 }); + } + dataGridView.Rows.Add(new object[] { "Итого", "", elem.TotalCount }); + dataGridView.Rows.Add(Array.Empty()); + } + } + _logger.LogInformation("Загрузка ассортимента магазинов"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Ошибка загрузки ассортимента магазинов"); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// + /// + /// + /// + /// + private void buttonSaveToExcel_Click(object sender, EventArgs e) + { + using var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" }; + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + _logic.SaveShopPlanesToExcelFile(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/AircraftPlant/AircraftPlantView/FormReportShopPlanes.resx b/AircraftPlant/AircraftPlantView/FormReportShopPlanes.resx new file mode 100644 index 0000000..a43dac9 --- /dev/null +++ b/AircraftPlant/AircraftPlantView/FormReportShopPlanes.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + True + + + True + + + True + + \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/Program.cs b/AircraftPlant/AircraftPlantView/Program.cs index e7722e3..31a3744 100644 --- a/AircraftPlant/AircraftPlantView/Program.cs +++ b/AircraftPlant/AircraftPlantView/Program.cs @@ -76,6 +76,8 @@ namespace AircraftPlantView services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); + services.AddTransient(); } } } \ No newline at end of file diff --git a/AircraftPlant/AircraftPlantView/ReportGroupOrders.rdlc b/AircraftPlant/AircraftPlantView/ReportGroupOrders.rdlc new file mode 100644 index 0000000..645722a --- /dev/null +++ b/AircraftPlant/AircraftPlantView/ReportGroupOrders.rdlc @@ -0,0 +1,441 @@ + + + 0 + + + + System.Data.DataSet + /* Local Connection */ + + 20791c83-cee8-4a38-bbd0-245fc17cefb3 + + + + + + AircraftPlantContractsViewModels + /* Local Query */ + + + + DateCreate + System.DateTime + + + Count + System.Int32 + + + Sum + System.Decimal + + + + AircraftPlantContracts.ViewModels + ReportGroupOrdersViewModel + AircraftPlantContracts.ViewModels.ReportGroupOrdersViewModel, AircraftPlantContracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null + + + + + + + + + true + true + + + + + Отчёт по заказам + + + + 0.6cm + 16.51cm + + + Middle + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Parameters!ReportParameterPeriod.Value + + + + + + + ReportParameterPeriod + 0.6cm + 0.6cm + 16.51cm + 1 + + + 2pt + 2pt + 2pt + 2pt + + + + + + + 3.90406cm + + + 3.97461cm + + + 3.65711cm + + + + + 0.6cm + + + + + true + true + + + + + Дата создания + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Количество заказов + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + Общая сумма заказов + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + 0.6cm + + + + + true + true + + + + + =Fields!DateCreate.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Count.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + true + true + + + + + =Fields!Sum.Value + + + 2pt + 2pt + 2pt + 2pt + + + + + + + + + + + + + + + + + + + After + + + + + + + DataSetGroupOrders + 1.88242cm + 2.68676cm + 1.2cm + 11.53578cm + 2 + + + + + + true + true + + + + + Итого: + + + + 3.29409cm + 8.06542cm + 0.6cm + 2.5cm + 3 + + + 2pt + 2pt + 2pt + 2pt + + + + true + true + + + + + =Sum(Fields!Sum.Value, "DataSetGroupOrders") + + + + + + + 3.29409cm + 10.70653cm + 0.6cm + 3.48072cm + 4 + + + 2pt + 2pt + 2pt + 2pt + + + + 2in +