почти работает (не выводит цену в таблицу)

This commit is contained in:
bulatova_karina 2024-04-08 21:11:09 +04:00
parent 793a09fb2c
commit b6dc101d9c
15 changed files with 255 additions and 261 deletions

View File

@ -8,7 +8,6 @@ using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels;
using ComputersShopDataModels.Models;
using Microsoft.Extensions.Logging;
@ -18,91 +17,48 @@ namespace ComputersShopBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IShopStorage _shopStorage;
public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage)
{
_logger = logger;
_shopStorage = shopStorage;
}
public List<ShopViewModel> ReadList(ShopSearchModel model)
public List<ShopViewModel>? ReadList(ShopSearchModel? model)
{
_logger.LogInformation("ReadList. ShopName:{Name}. Id:{ Id}", model?.Name, model?.Id);
_logger.LogInformation("ReadList. ShopName:{ShopName}.Id:{ Id}", model?.ShopName, model?.Id);
var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool MakeSupply(ShopSearchModel model, IComputerModel Computer, int count)
{
_logger.LogInformation("Try to supply shop. ShopName:{ShopName}. Id:{Id}", model.Name, model.Id);
if (model == null)
{
_logger.LogWarning("Read operation failed");
throw new ArgumentNullException(nameof(model));
}
if (Computer == null)
{
_logger.LogWarning("Read operation failed");
throw new ArgumentNullException(nameof(Computer));
}
if (count <= 0)
{
_logger.LogWarning("Read operation failed");
throw new ArgumentNullException("Количество должно быть положительным числом");
}
ShopViewModel curModel = ReadElement(model);
if (curModel == null)
{
_logger.LogWarning("Read operation failed");
throw new ArgumentNullException(nameof(curModel));
}
if (curModel.ShopComputers.TryGetValue(Computer.Id, out var pair))
{
curModel.ShopComputers[Computer.Id] = (pair.Item1, pair.Item2 + count);
}
else
{
curModel.ShopComputers.Add(Computer.Id, (Computer, count));
}
Update(new()
{
Id = curModel.Id,
ShopName = curModel.ShopName,
DateOpen = curModel.DateOpen,
Address = curModel.Address,
ShopComputers = curModel.ShopComputers,
});
_logger.LogInformation("Success. ComputerName:{ComputerName}. Id:{Id}. Supply:{count}", Computer.ComputerName, Computer.Id, count);
return true;
}
public ShopViewModel ReadElement(ShopSearchModel model)
public ShopViewModel? ReadElement(ShopSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.Name, model.Id);
_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");
@ -110,10 +66,10 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
return true;
}
public bool Update(ShopBindingModel model)
{
CheckModel(model);
if (_shopStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
@ -125,6 +81,7 @@ namespace ComputersShopBusinessLogic.BusinessLogics
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_shopStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
@ -132,7 +89,46 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
return true;
}
public bool AddComputerInShop(ShopSearchModel model, IComputerModel computer, int count)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (count <= 0)
{
throw new ArgumentException("Кол-во изделий должно быть больше 0", nameof(count));
}
_logger.LogInformation("AddComputerInShop. ShopName:{ShopName}.Id:{ Id}", model.ShopName, model.Id);
var element = _shopStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("AddComputerInShop element not found");
return false;
}
_logger.LogInformation("AddComputerInShop find. Id:{Id}", element.Id);
if (element.ShopComputers.TryGetValue(computer.Id, out var pair))
{
element.ShopComputers[computer.Id] = (computer, count + pair.Item2);
_logger.LogInformation("AddComputerInShop. Added {count} {computer} to '{ShopName}' shop", count, computer.ComputerName, element.ShopName);
}
else
{
element.ShopComputers[computer.Id] = (computer, count);
_logger.LogInformation("AddComputerInShop. Added {count} new computer {computer} to '{ShopName}' shop", count, computer.ComputerName, element.ShopName);
}
_shopStorage.Update(new()
{
Id = element.Id,
Address = element.Address,
ShopName = element.ShopName,
DateOpening = element.DateOpening,
ShopComputers = element.ShopComputers
});
return true;
}
private void CheckModel(ShopBindingModel model, bool withParams = true)
{
if (model == null)
@ -145,25 +141,14 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
if (string.IsNullOrEmpty(model.ShopName))
{
throw new ArgumentNullException("Нет названия магазина",
nameof(model.ShopName));
throw new ArgumentNullException("Нет названия магазина", nameof(model.ShopName));
}
if (string.IsNullOrEmpty(model.Address))
{
throw new ArgumentNullException("Нет адресса магазина",
nameof(model.Address));
}
if (model.DateOpen == null)
{
throw new ArgumentNullException("Нет даты открытия магазина",
nameof(model.DateOpen));
}
_logger.LogInformation("Shop. ShopName:{ShopName}.Address:{Address}. DateOpen:{DateOpen}. Id: { Id}", model.ShopName, model.Address, model.DateOpen, model.Id);
_logger.LogInformation("Shop. ShopName:{ShopName}.Address:{ Address}. Id:{ Id}", model.ShopName, model.Address, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel
{
Name = model.ShopName
ShopName = model.ShopName
});
if (element != null && element.Id != model.Id)
if (element != null && element.Id != model.Id && element.ShopName == model.ShopName)
{
throw new InvalidOperationException("Магазин с таким названием уже есть");
}

View File

@ -11,9 +11,13 @@ namespace ComputersShopContracts.BindingModels
public class ShopBindingModel : IShopModel
{
public int Id { get; set; }
public string ShopName { get; set; }
public string Address { get; set; }
public DateTime DateOpen { get; set; }
public Dictionary<int, (IComputerModel, int)> ShopComputers { get; set; } = new();
public string ShopName { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty;
public DateTime DateOpening { get; set; } = DateTime.Now;
public Dictionary<int, (IComputerModel, int)> ShopComputers
{
get;
set;
} = new();
}
}

View File

@ -6,7 +6,6 @@ using System.Threading.Tasks;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels;
using ComputersShopDataModels.Models;
namespace ComputersShopContracts.BusinessLogicsContracts
@ -18,6 +17,6 @@ namespace ComputersShopContracts.BusinessLogicsContracts
bool Create(ShopBindingModel model);
bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel model);
bool MakeSupply(ShopSearchModel model, IComputerModel computer, int count);
bool AddComputerInShop(ShopSearchModel model, IComputerModel computer, int count);
}
}

View File

@ -9,6 +9,6 @@ namespace ComputersShopContracts.SearchModels
public class ShopSearchModel
{
public int? Id { get; set; }
public string? Name { get; set; }
public string? ShopName { get; set; }
}
}

View File

@ -13,11 +13,15 @@ namespace ComputersShopContracts.ViewModels
{
public int Id { get; set; }
[DisplayName("Название магазина")]
public string ShopName { get; set; }
public string ShopName { get; set; } = string.Empty;
[DisplayName("Адрес магазина")]
public string Address { get; set; }
public string Address { get; set; } = string.Empty;
[DisplayName("Дата открытия")]
public DateTime DateOpen { get; set; }
public Dictionary<int, (IComputerModel, int)> ShopComputers { get; set; } = new();
public DateTime DateOpening { get; set; } = DateTime.Now;
public Dictionary<int, (IComputerModel, int)> ShopComputers
{
get;
set;
} = new();
}
}

View File

@ -10,7 +10,7 @@ namespace ComputersShopDataModels.Models
{
string ShopName { get; }
string Address { get; }
DateTime DateOpen { get; }
DateTime DateOpening { get; }
Dictionary<int, (IComputerModel, int)> ShopComputers { get; }
}
}

View File

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using ComputersShopListImplement.Models;

View File

@ -32,13 +32,14 @@ namespace ComputersShopListImplement.Implements
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
var result = new List<ShopViewModel>();
if (string.IsNullOrEmpty(model.Name))
if (string.IsNullOrEmpty(model.ShopName))
{
return result;
}
foreach (var shop in _source.Shops)
{
if (shop.ShopName.Contains(model.Name))
if (shop.ShopName.Contains(model.ShopName))
{
result.Add(shop.GetViewModel);
}
@ -47,15 +48,14 @@ namespace ComputersShopListImplement.Implements
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
foreach (var shop in _source.Shops)
{
if ((!string.IsNullOrEmpty(model.Name) &&
shop.ShopName == model.Name) ||
(model.Id.HasValue && shop.Id == model.Id))
if ((!string.IsNullOrEmpty(model.ShopName) && shop.ShopName == model.ShopName) || (model.Id.HasValue && shop.Id == model.Id))
{
return shop.GetViewModel;
}
@ -72,11 +72,13 @@ namespace ComputersShopListImplement.Implements
model.Id = shop.Id + 1;
}
}
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
_source.Shops.Add(newShop);
return newShop.GetViewModel;
}

View File

@ -13,43 +13,48 @@ namespace ComputersShopListImplement.Models
public class Shop : IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; }
public string Address { get; private set; }
public DateTime DateOpen { get; private set; }
public Dictionary<int, (IComputerModel, int)> ShopComputers { get; private set; } = new();
public static Shop? Create(ShopBindingModel model)
public string ShopName { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public DateTime DateOpening { get; private set; }
public Dictionary<int, (IComputerModel, int)> ShopComputers
{
get;
private set;
} = new Dictionary<int, (IComputerModel, int)>();
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpen = model.DateOpen,
ShopComputers = new()
DateOpening = model.DateOpening,
ShopComputers = model.ShopComputers
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
DateOpen = model.DateOpen;
DateOpening = model.DateOpening;
ShopComputers = model.ShopComputers;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpen = DateOpen,
DateOpening = DateOpening,
ShopComputers = ShopComputers
};
}

View File

@ -32,16 +32,16 @@
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.dateTimePicker = new System.Windows.Forms.DateTimePicker();
this.textBoxAdress = new System.Windows.Forms.TextBox();
this.textBoxAddress = new System.Windows.Forms.TextBox();
this.textBoxName = new System.Windows.Forms.TextBox();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.dataGridViewShop = new System.Windows.Forms.DataGridView();
this.id = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ComputerName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Price = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Count = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewShop)).BeginInit();
this.SuspendLayout();
//
// label1
@ -78,13 +78,13 @@
this.dateTimePicker.Size = new System.Drawing.Size(403, 27);
this.dateTimePicker.TabIndex = 3;
//
// textBoxAdress
// textBoxAddress
//
this.textBoxAdress.Location = new System.Drawing.Point(104, 61);
this.textBoxAdress.Name = "textBoxAdress";
this.textBoxAdress.Size = new System.Drawing.Size(403, 27);
this.textBoxAdress.TabIndex = 4;
this.textBoxAdress.TextChanged += new System.EventHandler(this.FormShop_Load);
this.textBoxAddress.Location = new System.Drawing.Point(104, 61);
this.textBoxAddress.Name = "textBoxAddress";
this.textBoxAddress.Size = new System.Drawing.Size(403, 27);
this.textBoxAddress.TabIndex = 4;
this.textBoxAddress.TextChanged += new System.EventHandler(this.FormShop_Load);
//
// textBoxName
//
@ -93,20 +93,20 @@
this.textBoxName.Size = new System.Drawing.Size(403, 27);
this.textBoxName.TabIndex = 5;
//
// dataGridView
// dataGridViewShop
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.dataGridViewShop.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridViewShop.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.id,
this.ComputerName,
this.Price,
this.Count});
this.dataGridView.Location = new System.Drawing.Point(23, 156);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(507, 173);
this.dataGridView.TabIndex = 6;
this.dataGridViewShop.Location = new System.Drawing.Point(23, 156);
this.dataGridViewShop.Name = "dataGridViewShop";
this.dataGridViewShop.RowHeadersWidth = 51;
this.dataGridViewShop.RowTemplate.Height = 29;
this.dataGridViewShop.Size = new System.Drawing.Size(507, 173);
this.dataGridViewShop.TabIndex = 6;
//
// id
//
@ -164,16 +164,17 @@
this.ClientSize = new System.Drawing.Size(546, 395);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.dataGridViewShop);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.textBoxAdress);
this.Controls.Add(this.textBoxAddress);
this.Controls.Add(this.dateTimePicker);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "FormShop";
this.Text = "Магазин";
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.Load += new System.EventHandler(this.FormShop_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridViewShop)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
@ -185,9 +186,9 @@
private Label label2;
private Label label3;
private DateTimePicker dateTimePicker;
private TextBox textBoxAdress;
private TextBox textBoxAddress;
private TextBox textBoxName;
private DataGridView dataGridView;
private DataGridView dataGridViewShop;
private DataGridViewTextBoxColumn id;
private DataGridViewTextBoxColumn ComputerName;
private DataGridViewTextBoxColumn Price;

View File

@ -10,7 +10,6 @@ using System.Windows.Forms;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.SearchModels;
using ComputersShopDataModels;
using ComputersShopDataModels.Models;
using Microsoft.Extensions.Logging;
@ -20,13 +19,16 @@ namespace ComputersShopView
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
public int? _id;
private Dictionary<int, (IComputerModel, int)> _Computers;
private int? _id;
public int Id { set { _id = value; } }
private Dictionary<int, (IComputerModel, int)> _shopComputers;
public FormShop(ILogger<FormShop> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_shopComputers = new Dictionary<int, (IComputerModel, int)>();
}
private void FormShop_Load(object sender, EventArgs e)
{
@ -35,43 +37,47 @@ namespace ComputersShopView
_logger.LogInformation("Загрузка магазина");
try
{
var shop = _logic.ReadElement(new ShopSearchModel { Id = _id });
if (shop != null)
var view = _logic.ReadElement(new ShopSearchModel { Id = _id.Value });
if (view != null)
{
textBoxName.Text = shop.ShopName;
textBoxAdress.Text = shop.Address;
dateTimePicker.Text = shop.DateOpen.ToString();
_Computers = shop.ShopComputers;
textBoxName.Text = view.ShopName;
textBoxAddress.Text = view.Address;
dateTimePicker.Text = view.DateOpening.ToString();
_shopComputers = view.ShopComputers ?? new Dictionary<int, (IComputerModel, int)>();
LoadData();
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка товаров магазина");
_logger.LogInformation("Загрузка изделий магазина");
try
{
if (_Computers != null)
if (_shopComputers != null)
{
foreach (var Computer in _Computers)
dataGridViewShop.Rows.Clear();
foreach (var elem in _shopComputers)
{
dataGridView.Rows.Add(new object[] { Computer.Key, Computer.Value.Item1.ComputerName, Computer.Value.Item1.Price, Computer.Value.Item2 });
dataGridViewShop.Rows.Add(new object[]
{
elem.Key,
elem.Value.Item1.ComputerName,
elem.Value.Item2
});
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компьютеров магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError(ex, "Ошибка загрузки изделий магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
@ -88,7 +94,7 @@ namespace ComputersShopView
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxAdress.Text))
if (string.IsNullOrEmpty(textBoxAddress.Text))
{
MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
@ -100,9 +106,9 @@ namespace ComputersShopView
{
Id = _id ?? 0,
ShopName = textBoxName.Text,
Address = textBoxAdress.Text,
DateOpen = dateTimePicker.Value.Date,
ShopComputers = _Computers
Address = textBoxAddress.Text,
DateOpening = dateTimePicker.Value.Date,
ShopComputers = _shopComputers
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)

View File

@ -33,8 +33,6 @@ namespace ComputersShopView
dataGridViewShops.DataSource = list;
dataGridViewShops.Columns["Id"].Visible = false;
dataGridViewShops.Columns["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridViewShops.Columns["Address"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridViewShops.Columns["DateOpen"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridViewShops.Columns["ShopComputers"].Visible = false;
}
_logger.LogInformation("Загрузка магазинов");
@ -70,8 +68,7 @@ namespace ComputersShopView
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
{
var tmp = Convert.ToInt32(dataGridViewShops.SelectedRows[0].Cells["Id"].Value);
form._id = Convert.ToInt32(dataGridViewShops.SelectedRows[0].Cells["Id"].Value);
form.Id = Convert.ToInt32(dataGridViewShops.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();

View File

@ -31,11 +31,12 @@
this.labelShop = new System.Windows.Forms.Label();
this.labelComputer = new System.Windows.Forms.Label();
this.labelCount = new System.Windows.Forms.Label();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.comboBoxComputer = new System.Windows.Forms.ComboBox();
this.comboBoxShop = new System.Windows.Forms.ComboBox();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.numericUpDownCount = new System.Windows.Forms.NumericUpDown();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).BeginInit();
this.SuspendLayout();
//
// labelShop
@ -65,13 +66,6 @@
this.labelCount.TabIndex = 2;
this.labelCount.Text = "Количество:";
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(142, 139);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(349, 27);
this.textBoxCount.TabIndex = 3;
//
// comboBoxComputer
//
this.comboBoxComputer.FormattingEnabled = true;
@ -108,21 +102,30 @@
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// numericUpDownCount
//
this.numericUpDownCount.Location = new System.Drawing.Point(142, 139);
this.numericUpDownCount.Name = "numericUpDownCount";
this.numericUpDownCount.Size = new System.Drawing.Size(348, 27);
this.numericUpDownCount.TabIndex = 8;
//
// FormSupply
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(552, 227);
this.Controls.Add(this.numericUpDownCount);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.comboBoxShop);
this.Controls.Add(this.comboBoxComputer);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.labelComputer);
this.Controls.Add(this.labelShop);
this.Name = "FormSupply";
this.Text = "Поставки";
this.Load += new System.EventHandler(this.FormSupply_Load);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
@ -133,10 +136,10 @@
private Label labelShop;
private Label labelComputer;
private Label labelCount;
private TextBox textBoxCount;
private ComboBox comboBoxComputer;
private ComboBox comboBoxShop;
private Button buttonSave;
private Button buttonCancel;
private NumericUpDown numericUpDownCount;
}
}

View File

@ -13,132 +13,105 @@ using ComputersShopContracts.SearchModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels;
using ComputersShopDataModels.Models;
using Microsoft.Extensions.Logging;
namespace ComputersShopView
{
public partial class FormSupply : Form
{
private readonly List<ComputerViewModel>? _ComputerList;
private readonly List<ShopViewModel>? _shopsList;
IShopLogic _shopLogic;
IComputerLogic _ComputerLogic;
public int ShopId
{
get
{
return Convert.ToInt32(comboBoxShop.SelectedValue);
}
set
{
comboBoxShop.SelectedValue = value;
}
}
public int ComputerId
{
get
{
return
Convert.ToInt32(comboBoxComputer.SelectedValue);
}
set
{
comboBoxComputer.SelectedValue = value;
}
}
private readonly ILogger _logger;
private readonly IShopLogic _logicS;
private readonly IComputerLogic _logicC;
public IComputerModel? ComputerModel
{
get
{
if (_ComputerList == null)
{
return null;
}
foreach (var elem in _ComputerList)
{
if (elem.Id == ComputerId)
{
return elem;
}
}
return null;
}
}
public int Count
{
get { return Convert.ToInt32(textBoxCount.Text); }
set
{ textBoxCount.Text = value.ToString(); }
}
public FormSupply(IComputerLogic ComputerLogic, IShopLogic shopLogic)
public FormSupply(ILogger<FormSupply> logger, IShopLogic logicS, IComputerLogic logicC)
{
InitializeComponent();
_shopLogic = shopLogic;
_ComputerLogic = ComputerLogic;
_ComputerList = ComputerLogic.ReadList(null);
_shopsList = shopLogic.ReadList(null);
if (_ComputerList != null)
_logger = logger;
_logicS = logicS;
_logicC = logicC;
}
private void FormSupply_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка магазинов");
try
{
comboBoxComputer.DisplayMember = "ComputerName";
comboBoxComputer.ValueMember = "Id";
comboBoxComputer.DataSource = _ComputerList;
comboBoxComputer.SelectedItem = null;
var listShops = _logicS.ReadList(null);
if (listShops != null)
{
comboBoxShop.DisplayMember = "ShopName";
comboBoxShop.ValueMember = "Id";
comboBoxShop.DataSource = listShops;
comboBoxShop.SelectedItem = null;
}
}
if (_shopsList != null)
catch (Exception ex)
{
comboBoxShop.DisplayMember = "ShopName";
comboBoxShop.ValueMember = "Id";
comboBoxShop.DataSource = _shopsList;
comboBoxShop.SelectedItem = null;
_logger.LogError(ex, "Ошибка загрузки списка магазинов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
_logger.LogInformation("Загрузка изделий");
try
{
var listComputers = _logicC.ReadList(null);
if (listComputers != null)
{
comboBoxComputer.DisplayMember = "ComputerName";
comboBoxComputer.ValueMember = "Id";
comboBoxComputer.DataSource = listComputers;
comboBoxComputer.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))
if (comboBoxShop.SelectedValue == null)
{
MessageBox.Show("Заполните поле Количество", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxComputer.SelectedValue == null)
{
MessageBox.Show("Выберите компьютер", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxShop.SelectedValue == null)
{
MessageBox.Show("Выберите магазин", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Добавление изделия в магазин");
try
{
int count = Convert.ToInt32(textBoxCount.Text);
bool res = _shopLogic.MakeSupply(
new ShopSearchModel() { Id = Convert.ToInt32(comboBoxShop.SelectedValue) },
_ComputerLogic.ReadElement(new() { Id = Convert.ToInt32(comboBoxComputer.SelectedValue) }),
count
);
if (!res)
var computer = _logicC.ReadElement(new()
{
throw new Exception("Ошибка при пополнении. Дополнительная информация в логах");
Id = (int)comboBoxComputer.SelectedValue
});
if (computer == null)
{
throw new Exception("Не найдено изделие. Дополнительная информация в логах.");
}
MessageBox.Show("Пополнение прошло успешно");
var resultOperation = _logicS.AddComputerInShop(
new ShopSearchModel
{
Id = (int)comboBoxShop.SelectedValue
},
computer,
(int)numericUpDownCount.Value
);
if (!resultOperation)
{
throw new Exception("Ошибка при добавлении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception err)
catch (Exception ex)
{
MessageBox.Show("Ошибка пополнения");
return;
_logger.LogError(ex, "Ошибка добавления поступления");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

View File

@ -1,7 +1,8 @@
using ComputersShopBusinessLogic.BusinessLogics;
using ComputersShopBusinessLogic.BusinessLogics;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.StoragesContracts;
using ComputersShopListImplement.Implements;
using ComputersShopView;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
@ -11,10 +12,14 @@ namespace ComputersShopView
{
internal static class Program
{
/// <summary>
/// IoC-êîíòåéíåð
/// </summary>
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
@ -22,11 +27,18 @@ namespace ComputersShopView
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
}
/// <summary>
/// Íàñòðîéêà IoC-êîíòåéíåðà è ëîããåðà
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services.AddLogging(option =>
@ -34,14 +46,17 @@ namespace ComputersShopView
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IComputerStorage, ComputerStorage>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IComputerLogic, ComputerLogic>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
@ -49,10 +64,9 @@ namespace ComputersShopView
services.AddTransient<FormComputer>();
services.AddTransient<FormComputerComponent>();
services.AddTransient<FormComputers>();
services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormShop>();
services.AddTransient<FormSupply>();
}
}
}