ЗАФИКСИРОВАЛ

This commit is contained in:
devil_1nc 2024-06-24 01:08:20 +04:00
commit 8dc6f43608
26 changed files with 1848 additions and 535 deletions

View File

@ -31,7 +31,8 @@ namespace BusinessLogic.BusinessLogic
{ {
throw new Exception("Insert operation failed."); throw new Exception("Insert operation failed.");
} }
return sell; //return sell;
return new();
} }
public SellViewModel GetElement(SellSearchModel model) public SellViewModel GetElement(SellSearchModel model)
{ {
@ -41,17 +42,19 @@ namespace BusinessLogic.BusinessLogic
{ {
throw new Exception("Get element operation failed."); throw new Exception("Get element operation failed.");
} }
return sell; return new();
//return sell;
} }
public IEnumerable<SellViewModel> GetElements(SellSearchModel? model) public IEnumerable<SellViewModel> GetElements(SellSearchModel? model)
{ {
var sell_list = model == null ? _sellStorage.GetFullList(model) : _sellStorage.GetFilteredList(model); //var sell_list = _sellStorage.GetList(model);
if (sell_list is null || sell_list.Count() == 0) //if (sell_list is null || sell_list.Count() == 0)
{ //{
_logger.LogWarning("ReadList return null list"); // _logger.LogWarning("ReadList return null list");
return []; // return [];
} //}
return sell_list; return [];
//return sell_list;
} }
public SellViewModel Update(SellSearchModel model) public SellViewModel Update(SellSearchModel model)
{ {
@ -61,7 +64,8 @@ namespace BusinessLogic.BusinessLogic
{ {
throw new Exception("Update operation failed."); throw new Exception("Update operation failed.");
} }
return sell; return new();
//return sell;
} }
public SellViewModel Delete(SellSearchModel model) public SellViewModel Delete(SellSearchModel model)
{ {
@ -71,7 +75,8 @@ namespace BusinessLogic.BusinessLogic
{ {
throw new Exception("Update operation failed."); throw new Exception("Update operation failed.");
} }
return sell; return new();
//return sell;
} }
} }
} }

View File

@ -3,6 +3,7 @@ using Contracts.BusinessLogicContracts;
using Contracts.SearchModels; using Contracts.SearchModels;
using Contracts.StorageContracts; using Contracts.StorageContracts;
using Contracts.ViewModels; using Contracts.ViewModels;
using DataModels.Enums;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -101,5 +102,22 @@ namespace BusinessLogic.BusinessLogic
throw new ArgumentNullException("Нет названия поставки", nameof(model.Name)); throw new ArgumentNullException("Нет названия поставки", nameof(model.Name));
} }
} }
public bool StatusUpdate(SupplyBindingModel model, SupplyStatus newStatus)
{
if (model.Status + 1 != newStatus)
{
_logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Supply status incorrect.");
return false;
}
model.Status = newStatus;
if (_supplyStorage.Update(model) == null)
{
model.Status--;
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
} }
} }

View File

@ -1,6 +1,7 @@
using Contracts.BindingModels; using Contracts.BindingModels;
using Contracts.SearchModels; using Contracts.SearchModels;
using Contracts.ViewModels; using Contracts.ViewModels;
using DataModels.Enums;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -16,5 +17,6 @@ namespace Contracts.BusinessLogicContracts
bool Create(SupplyBindingModel model); bool Create(SupplyBindingModel model);
bool Update(SupplyBindingModel model); bool Update(SupplyBindingModel model);
bool Delete(SupplyBindingModel model); bool Delete(SupplyBindingModel model);
bool StatusUpdate(SupplyBindingModel model, SupplyStatus status);
} }
} }

View File

@ -14,8 +14,8 @@ namespace Contracts.StorageContracts
List<SupplyViewModel> GetFullList(); List<SupplyViewModel> GetFullList();
List<SupplyViewModel> GetFilteredList(SupplySearchModel model); List<SupplyViewModel> GetFilteredList(SupplySearchModel model);
SupplyViewModel? GetElement(SupplySearchModel model); SupplyViewModel? GetElement(SupplySearchModel model);
SupplyViewModel? Insert(SupplyBindingModel model); bool? Insert(SupplyBindingModel model);
SupplyViewModel? Update(SupplyBindingModel model); bool? Update(SupplyBindingModel model);
SupplyViewModel? Delete(SupplyBindingModel model); SupplyViewModel? Delete(SupplyBindingModel model);
} }
} }

View File

@ -7,6 +7,7 @@ using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -106,7 +107,7 @@ namespace DatabaseImplement.Implements
.ToList(); .ToList();
} }
public SupplyViewModel? Insert(SupplyBindingModel model) public bool? Insert(SupplyBindingModel model)
{ {
using var context = new Database(); using var context = new Database();
var newProduct = Supply.Create(context, model); var newProduct = Supply.Create(context, model);
@ -115,11 +116,18 @@ namespace DatabaseImplement.Implements
return null; return null;
} }
context.Supplies.Add(newProduct); context.Supplies.Add(newProduct);
context.SaveChanges(); try
return newProduct.GetViewModel; {
context.SaveChanges();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
return true;
} }
public SupplyViewModel? Update(SupplyBindingModel model) public bool? Update(SupplyBindingModel model)
{ {
using var context = new Database(); using var context = new Database();
using var transaction = context.Database.BeginTransaction(); using var transaction = context.Database.BeginTransaction();
@ -129,13 +137,12 @@ namespace DatabaseImplement.Implements
rec.Id == model.Id); rec.Id == model.Id);
if (product == null) if (product == null)
{ {
return null; return false;
} }
product.Update(model); product.Update(model);
context.SaveChanges(); context.SaveChanges();
product.UpdateProducts(context, model);
transaction.Commit(); transaction.Commit();
return product.GetViewModel; return true;
} }
catch catch
{ {

View File

@ -43,7 +43,7 @@ namespace DatabaseImplement.Models
Id = model.Id, Id = model.Id,
Name = model.Name, Name = model.Name,
Price = model.Price, Price = model.Price,
Rate = model.Rating, Rate = model.Rate,
IsBeingSold = model.IsBeingSold, IsBeingSold = model.IsBeingSold,
Amount = model.Amount Amount = model.Amount
}; };
@ -96,7 +96,7 @@ namespace DatabaseImplement.Models
Name = Name, Name = Name,
Price = Price, Price = Price,
IsBeingSold = IsBeingSold, IsBeingSold = IsBeingSold,
Rating = Rate, Rate = Rate,
Amount = Amount Amount = Amount
}; };
} }

View File

@ -59,7 +59,7 @@ namespace DatabaseImplement.Models
Deals = model.Deals; Deals = model.Deals;
Debug.WriteLine(model.AvailibleProducts.Keys); Debug.WriteLine(model.AvailibleProducts.Keys);
Products = model.AvailibleProducts.Select(x => new Products = model.AvailibleProducts.Select(x => new
SupplierProduct SupplierProduct
{ {
Product = context.Products.First(y => y.Id == x.Value.Item1.Id), Product = context.Products.First(y => y.Id == x.Value.Item1.Id),
Count = x.Value.Item2 Count = x.Value.Item2
@ -81,6 +81,7 @@ namespace DatabaseImplement.Models
} }
public void UpdateProducts(Database context, SupplierBindingModel model) public void UpdateProducts(Database context, SupplierBindingModel model)
{ {
var test = context.SupplierProducts.ToList();
var supplierProducts = context.SupplierProducts.Where(rec => rec.SupplierId == model.Id).ToList(); var supplierProducts = context.SupplierProducts.Where(rec => rec.SupplierId == model.Id).ToList();
if (supplierProducts != null && supplierProducts.Count > model.AvailibleProducts.Count) if (supplierProducts != null && supplierProducts.Count > model.AvailibleProducts.Count)
{ {

View File

@ -59,13 +59,13 @@ namespace DatabaseImplement.Models
{ {
Product = context.Products.First(y => y.Id == x.Key), Product = context.Products.First(y => y.Id == x.Key),
Count = x.Value.Item2 Count = x.Value.Item2
}).ToList() }).ToList(),
Status = SupplyStatus.Pending,
}; };
} }
public void Update(SupplyBindingModel model) public void Update(SupplyBindingModel model)
{ {
Name = model.Name; Status = model.Status;
Price = model.Price;
} }
public SupplyViewModel GetViewModel public SupplyViewModel GetViewModel
{ {
@ -78,41 +78,12 @@ namespace DatabaseImplement.Models
Name = Name, Name = Name,
Price = Price, Price = Price,
Products = SupplyProducts, Products = SupplyProducts,
SupplierId = SupplierId,
Date = Date, Date = Date,
Status = Status, Status = Status,
SupplierName = context.Suppliers.FirstOrDefault(x => x.Id == Id)?.Name ?? string.Empty, SupplierName = Supplier.Name,
}; };
} }
} }
public void UpdateProducts(Database context, SupplyBindingModel model)
{
var supplyProducts = context.SupplyProducts.Where(rec =>
rec.Id == model.Id).ToList();
if (supplyProducts != null && supplyProducts.Count > 0)
{ // удалили те, которых нет в модели
context.SupplyProducts.RemoveRange(supplyProducts.Where(rec
=> !model.SupplyProducts.ContainsKey(rec.ProductId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateProduct in supplyProducts)
{
updateProduct.Count = model.SupplyProducts[updateProduct.ProductId].Item2;
model.SupplyProducts.Remove(updateProduct.ProductId);
}
context.SaveChanges();
}
var supply = context.Supplies.First(x => x.Id == Id);
foreach (var pc in model.SupplyProducts)
{
context.SupplyProducts.Add(new SupplyProduct
{
Supply = supply,
Product = context.Products.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_supplyProducts = null;
}
} }
} }

View File

@ -33,6 +33,8 @@
menuStrip1 = new MenuStrip(); menuStrip1 = new MenuStrip();
товарыToolStripMenuItem = new ToolStripMenuItem(); товарыToolStripMenuItem = new ToolStripMenuItem();
поставщикиToolStripMenuItem = new ToolStripMenuItem(); поставщикиToolStripMenuItem = new ToolStripMenuItem();
buttonSupplyStatusArriving = new Button();
buttonSupplyStatusCompleted = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
menuStrip1.SuspendLayout(); menuStrip1.SuspendLayout();
SuspendLayout(); SuspendLayout();
@ -48,12 +50,13 @@
// //
// buttonCreateSupply // buttonCreateSupply
// //
buttonCreateSupply.Location = new Point(706, 12); buttonCreateSupply.Location = new Point(707, 27);
buttonCreateSupply.Name = "buttonCreateSupply"; buttonCreateSupply.Name = "buttonCreateSupply";
buttonCreateSupply.Size = new Size(154, 23); buttonCreateSupply.Size = new Size(154, 23);
buttonCreateSupply.TabIndex = 1; buttonCreateSupply.TabIndex = 1;
buttonCreateSupply.Text = "Оформить поставку"; buttonCreateSupply.Text = "Оформить поставку";
buttonCreateSupply.UseVisualStyleBackColor = true; buttonCreateSupply.UseVisualStyleBackColor = true;
buttonCreateSupply.Click += buttonCreateSupply_Click;
// //
// menuStrip1 // menuStrip1
// //
@ -78,11 +81,33 @@
поставщикиToolStripMenuItem.Text = "Поставщики"; поставщикиToolStripMenuItem.Text = "Поставщики";
поставщикиToolStripMenuItem.Click += поставщикиToolStripMenuItem_Click_1; поставщикиToolStripMenuItem.Click += поставщикиToolStripMenuItem_Click_1;
// //
// buttonSupplyStatusArriving
//
buttonSupplyStatusArriving.Location = new Point(707, 76);
buttonSupplyStatusArriving.Name = "buttonSupplyStatusArriving";
buttonSupplyStatusArriving.Size = new Size(154, 23);
buttonSupplyStatusArriving.TabIndex = 3;
buttonSupplyStatusArriving.Text = "Поставка в пути";
buttonSupplyStatusArriving.UseVisualStyleBackColor = true;
buttonSupplyStatusArriving.Click += buttonSupplyStatusArriving_Click;
//
// buttonSupplyStatusCompleted
//
buttonSupplyStatusCompleted.Location = new Point(707, 125);
buttonSupplyStatusCompleted.Name = "buttonSupplyStatusCompleted";
buttonSupplyStatusCompleted.Size = new Size(154, 23);
buttonSupplyStatusCompleted.TabIndex = 4;
buttonSupplyStatusCompleted.Text = "Поставка завершена";
buttonSupplyStatusCompleted.UseVisualStyleBackColor = true;
buttonSupplyStatusCompleted.Click += buttonSupplyStatusCompleted_Click;
//
// FormMain // FormMain
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(901, 384); ClientSize = new Size(901, 384);
Controls.Add(buttonSupplyStatusCompleted);
Controls.Add(buttonSupplyStatusArriving);
Controls.Add(buttonCreateSupply); Controls.Add(buttonCreateSupply);
Controls.Add(dataGridView); Controls.Add(dataGridView);
Controls.Add(menuStrip1); Controls.Add(menuStrip1);
@ -104,5 +129,7 @@
private MenuStrip menuStrip1; private MenuStrip menuStrip1;
private ToolStripMenuItem товарыToolStripMenuItem; private ToolStripMenuItem товарыToolStripMenuItem;
private ToolStripMenuItem поставщикиToolStripMenuItem; private ToolStripMenuItem поставщикиToolStripMenuItem;
private Button buttonSupplyStatusArriving;
private Button buttonSupplyStatusCompleted;
} }
} }

View File

@ -1,4 +1,7 @@
using Contracts.BusinessLogicContracts; using Contracts.BindingModels;
using Contracts.BusinessLogicContracts;
using DataModels.Enums;
using DataModels.Models;
using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
@ -68,5 +71,70 @@ namespace WinFormsApp
form.ShowDialog(); form.ShowDialog();
} }
} }
private void buttonCreateSupply_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSupply));
if (service is FormSupply form)
{
form.ShowDialog();
}
}
private void buttonSupplyStatusArriving_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
Guid id = (Guid)dataGridView.SelectedRows[0].Cells["Id"].Value;
_logger.LogInformation("Поставка No{id}. Меняется статус", id);
try
{
var operationResult = _supplyLogic.StatusUpdate(new SupplyBindingModel
{
Id = id,
Status = (SupplyStatus)dataGridView.SelectedRows[0].Cells["Status"].Value
}, SupplyStatus.Arriving);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void buttonSupplyStatusCompleted_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
Guid id = (Guid)dataGridView.SelectedRows[0].Cells["Id"].Value;
_logger.LogInformation("Поставка No{id}. Меняется статус", id);
try
{
var operationResult = _supplyLogic.StatusUpdate(new SupplyBindingModel
{
Id = id,
Status = (SupplyStatus)dataGridView.SelectedRows[0].Cells["Status"].Value
}, SupplyStatus.Completed);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
} }
} }

209
WinFormsApp/FormSupplier.Designer.cs generated Normal file
View File

@ -0,0 +1,209 @@
namespace WinFormsApp
{
partial class FormSupplier
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
buttonCancel = new Button();
buttonSave = new Button();
label1 = new Label();
groupBoxProducts = new GroupBox();
buttonDeleteProduct = new Button();
buttonUpdateProduct = new Button();
buttonAddProduct = new Button();
dataGridView = new DataGridView();
ProductId = new DataGridViewTextBoxColumn();
ProductName = new DataGridViewTextBoxColumn();
ProductAmount = new DataGridViewTextBoxColumn();
textBoxName = new TextBox();
numericUpDownDeals = new NumericUpDown();
label2 = new Label();
groupBoxProducts.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownDeals).BeginInit();
SuspendLayout();
//
// buttonCancel
//
buttonCancel.Location = new Point(307, 83);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 12;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// buttonSave
//
buttonSave.Location = new Point(307, 35);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.TabIndex = 11;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonSave_Click;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(18, 18);
label1.Name = "label1";
label1.Size = new Size(215, 15);
label1.TabIndex = 10;
label1.Text = "Имя/название компании поставщика";
//
// groupBoxProducts
//
groupBoxProducts.Controls.Add(buttonDeleteProduct);
groupBoxProducts.Controls.Add(buttonUpdateProduct);
groupBoxProducts.Controls.Add(buttonAddProduct);
groupBoxProducts.Controls.Add(dataGridView);
groupBoxProducts.Location = new Point(12, 145);
groupBoxProducts.Name = "groupBoxProducts";
groupBoxProducts.Size = new Size(776, 288);
groupBoxProducts.TabIndex = 9;
groupBoxProducts.TabStop = false;
groupBoxProducts.Text = "Товары";
//
// buttonDeleteProduct
//
buttonDeleteProduct.Location = new Point(435, 132);
buttonDeleteProduct.Name = "buttonDeleteProduct";
buttonDeleteProduct.Size = new Size(126, 49);
buttonDeleteProduct.TabIndex = 4;
buttonDeleteProduct.Text = "Удалить";
buttonDeleteProduct.UseVisualStyleBackColor = true;
//
// buttonUpdateProduct
//
buttonUpdateProduct.Location = new Point(435, 77);
buttonUpdateProduct.Name = "buttonUpdateProduct";
buttonUpdateProduct.Size = new Size(126, 49);
buttonUpdateProduct.TabIndex = 3;
buttonUpdateProduct.Text = "Изменить";
buttonUpdateProduct.UseVisualStyleBackColor = true;
//
// buttonAddProduct
//
buttonAddProduct.Location = new Point(435, 22);
buttonAddProduct.Name = "buttonAddProduct";
buttonAddProduct.Size = new Size(126, 49);
buttonAddProduct.TabIndex = 2;
buttonAddProduct.Text = "Добавить";
buttonAddProduct.UseVisualStyleBackColor = true;
buttonAddProduct.Click += buttonAddProduct_Click;
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ProductId, ProductName, ProductAmount });
dataGridView.Location = new Point(6, 22);
dataGridView.Name = "dataGridView";
dataGridView.Size = new Size(423, 241);
dataGridView.TabIndex = 1;
//
// ProductId
//
ProductId.HeaderText = "Id";
ProductId.Name = "ProductId";
ProductId.ReadOnly = true;
ProductId.Visible = false;
//
// ProductName
//
ProductName.HeaderText = "Название";
ProductName.Name = "ProductName";
ProductName.ReadOnly = true;
//
// ProductAmount
//
ProductAmount.HeaderText = "Количество";
ProductAmount.Name = "ProductAmount";
ProductAmount.ReadOnly = true;
//
// textBoxName
//
textBoxName.Location = new Point(18, 36);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(215, 23);
textBoxName.TabIndex = 8;
//
// numericUpDownDeals
//
numericUpDownDeals.Location = new Point(18, 85);
numericUpDownDeals.Name = "numericUpDownDeals";
numericUpDownDeals.Size = new Size(120, 23);
numericUpDownDeals.TabIndex = 13;
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(18, 67);
label2.Name = "label2";
label2.Size = new Size(87, 15);
label2.TabIndex = 14;
label2.Text = "Кол-во сделок";
//
// FormSupplier
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(label2);
Controls.Add(numericUpDownDeals);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(label1);
Controls.Add(groupBoxProducts);
Controls.Add(textBoxName);
Name = "FormSupplier";
Text = "FormSupplier";
Load += FormSupplier_Load;
groupBoxProducts.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownDeals).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonCancel;
private Button buttonSave;
private Label label1;
private GroupBox groupBoxProducts;
private Button buttonDeleteProduct;
private Button buttonUpdateProduct;
private Button buttonAddProduct;
private DataGridView dataGridView;
private DataGridViewTextBoxColumn ProductId;
private DataGridViewTextBoxColumn ProductName;
private DataGridViewTextBoxColumn ProductAmount;
private TextBox textBoxName;
private NumericUpDown numericUpDownDeals;
private Label label2;
}
}

143
WinFormsApp/FormSupplier.cs Normal file
View File

@ -0,0 +1,143 @@
using Contracts.BindingModels;
using Contracts.BusinessLogicContracts;
using Contracts.SearchModels;
using DatabaseImplement.Models;
using DataModels.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 WinFormsApp
{
public partial class FormSupplier : Form
{
private readonly ILogger _logger;
private readonly ISupplierLogic _logic;
private Guid? _id;
private Dictionary<Guid, (IProduct, int)> _supplierProducts;
public Guid Id { set { _id = value; } }
public FormSupplier(ILogger<FormSupply> logger, ISupplierLogic supplierLogic)
{
InitializeComponent();
_logger = logger;
_supplierProducts = new Dictionary<Guid, (IProduct, int)>();
_logic = supplierLogic;
}
private void FormSupplier_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка изделия");
try
{
var view = _logic.ReadElement(new SupplierSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.Name;
_supplierProducts = view.AvailibleProducts ?? new Dictionary<Guid, (IProduct, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка компонент изделия");
try
{
if (_supplierProducts != null)
{
dataGridView.Rows.Clear();
foreach (var pc in _supplierProducts)
{
dataGridView.Rows.Add(new object[] { pc.Key, pc.Value.Item1.Name, pc.Value.Item2 });
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонент изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void buttonAddProduct_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSupplierProduct));
if (service is FormSupplierProduct form)
{
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ProductModel == null)
{
return;
}
_logger.LogInformation("Добавление нового компонента");
if (_supplierProducts.ContainsKey(form.Id))
{
_supplierProducts[form.Id] = (form.ProductModel, form.Count);
}
else
{
_supplierProducts.Add(form.Id, (form.ProductModel, form.Count));
}
LoadData();
}
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните информацию", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (_supplierProducts == null || _supplierProducts.Count == 0)
{
MessageBox.Show("Заполните товары", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение изделия");
try
{
var model = new SupplierBindingModel
{
Id = _id ?? Guid.NewGuid(),
Name = textBoxName.Text,
AvailibleProducts = _supplierProducts,
Deals = Convert.ToInt32(numericUpDownDeals.Value),
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения изделия"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,129 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="ProductId.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ProductName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ProductAmount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,95 @@
namespace WinFormsApp
{
partial class FormSupplierProduct
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
buttonCancel = new Button();
buttonSave = new Button();
comboBoxProduct = new ComboBox();
numericUpDownCount = new NumericUpDown();
((System.ComponentModel.ISupportInitialize)numericUpDownCount).BeginInit();
SuspendLayout();
//
// buttonCancel
//
buttonCancel.Location = new Point(179, 77);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 8;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSave
//
buttonSave.Location = new Point(179, 53);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.TabIndex = 7;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// comboBoxProduct
//
comboBoxProduct.FormattingEnabled = true;
comboBoxProduct.Location = new Point(12, 12);
comboBoxProduct.Name = "comboBoxProduct";
comboBoxProduct.Size = new Size(121, 23);
comboBoxProduct.TabIndex = 6;
//
// numericUpDownCount
//
numericUpDownCount.Location = new Point(13, 55);
numericUpDownCount.Name = "numericUpDownCount";
numericUpDownCount.Size = new Size(120, 23);
numericUpDownCount.TabIndex = 5;
//
// FormSupplierProduct
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(291, 123);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(comboBoxProduct);
Controls.Add(numericUpDownCount);
Name = "FormSupplierProduct";
Text = "FormSupplierProduct";
((System.ComponentModel.ISupportInitialize)numericUpDownCount).EndInit();
ResumeLayout(false);
}
#endregion
private Button buttonCancel;
private Button buttonSave;
private ComboBox comboBoxProduct;
private NumericUpDown numericUpDownCount;
}
}

View File

@ -0,0 +1,88 @@
using Contracts.BusinessLogicContracts;
using Contracts.ViewModels;
using DataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsApp
{
public partial class FormSupplierProduct : Form
{
private readonly List<ProductViewModel>? _list;
public Guid Id
{
get
{
return (Guid)comboBoxProduct.SelectedValue;
}
set
{
comboBoxProduct.SelectedValue = value;
}
}
public IProduct? ProductModel
{
get
{
if (_list == null)
{
return null;
}
foreach (var elem in _list)
{
if (elem.Id == Id)
{
return elem;
}
}
return null;
}
}
public int Count
{
get { return Convert.ToInt32(numericUpDownCount.Value); }
set { numericUpDownCount.Value = value; }
}
public FormSupplierProduct(IProductLogic logic)
{
InitializeComponent();
_list = logic.ReadList(null);
if (_list != null)
{
comboBoxProduct.DisplayMember = "Name";
comboBoxProduct.ValueMember = "Id";
comboBoxProduct.DataSource = _list;
comboBoxProduct.SelectedItem = null;
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (numericUpDownCount.Value == null || numericUpDownCount.Value <= 0)
{
MessageBox.Show("Кол-во товаров должно иметь значение больше 0", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxProduct.SelectedValue == null)
{
MessageBox.Show("Выберите товар", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
DialogResult = DialogResult.OK;
Close();
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -28,308 +28,59 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
groupBoxCreateSupplier = new GroupBox();
label4 = new Label();
label3 = new Label();
numericUpDownDeals = new NumericUpDown();
groupBoxSupplierProducts = new GroupBox();
buttonDeleteProduct = new Button();
label2 = new Label();
buttonCancel = new Button();
label1 = new Label();
buttonSaveSupplier = new Button();
numericUpDownCount = new NumericUpDown();
comboBoxProducts = new ComboBox();
dataGridViewProducts = new DataGridView();
buttonAddSupplierProduct = new Button();
textBoxName = new TextBox();
groupBoxControls = new GroupBox();
buttonDeleteSupplier = new Button();
buttonUpdateSupplier = new Button();
buttonCreateSupplier = new Button();
dataGridView = new DataGridView(); dataGridView = new DataGridView();
ColumnId = new DataGridViewTextBoxColumn(); buttonAdd = new Button();
Column = new DataGridViewTextBoxColumn(); buttonEdit = new Button();
Column2 = new DataGridViewTextBoxColumn();
groupBoxCreateSupplier.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownDeals).BeginInit();
groupBoxSupplierProducts.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownCount).BeginInit();
((System.ComponentModel.ISupportInitialize)dataGridViewProducts).BeginInit();
groupBoxControls.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout(); SuspendLayout();
// //
// groupBoxCreateSupplier
//
groupBoxCreateSupplier.BackColor = Color.Transparent;
groupBoxCreateSupplier.Controls.Add(label4);
groupBoxCreateSupplier.Controls.Add(label3);
groupBoxCreateSupplier.Controls.Add(numericUpDownDeals);
groupBoxCreateSupplier.Controls.Add(groupBoxSupplierProducts);
groupBoxCreateSupplier.Controls.Add(textBoxName);
groupBoxCreateSupplier.Dock = DockStyle.Right;
groupBoxCreateSupplier.Location = new Point(288, 0);
groupBoxCreateSupplier.Name = "groupBoxCreateSupplier";
groupBoxCreateSupplier.Size = new Size(367, 637);
groupBoxCreateSupplier.TabIndex = 6;
groupBoxCreateSupplier.TabStop = false;
groupBoxCreateSupplier.Text = "Создание/изменение поставщика";
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(17, 93);
label4.Name = "label4";
label4.Size = new Size(87, 15);
label4.TabIndex = 15;
label4.Text = "Кол-во сделок";
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(6, 54);
label3.Name = "label3";
label3.Size = new Size(101, 15);
label3.TabIndex = 14;
label3.Text = "Имя поставщика";
//
// numericUpDownDeals
//
numericUpDownDeals.Location = new Point(110, 91);
numericUpDownDeals.Maximum = new decimal(new int[] { 100000, 0, 0, 0 });
numericUpDownDeals.Name = "numericUpDownDeals";
numericUpDownDeals.Size = new Size(245, 23);
numericUpDownDeals.TabIndex = 14;
//
// groupBoxSupplierProducts
//
groupBoxSupplierProducts.Controls.Add(buttonDeleteProduct);
groupBoxSupplierProducts.Controls.Add(label2);
groupBoxSupplierProducts.Controls.Add(buttonCancel);
groupBoxSupplierProducts.Controls.Add(label1);
groupBoxSupplierProducts.Controls.Add(buttonSaveSupplier);
groupBoxSupplierProducts.Controls.Add(numericUpDownCount);
groupBoxSupplierProducts.Controls.Add(comboBoxProducts);
groupBoxSupplierProducts.Controls.Add(dataGridViewProducts);
groupBoxSupplierProducts.Controls.Add(buttonAddSupplierProduct);
groupBoxSupplierProducts.Location = new Point(0, 149);
groupBoxSupplierProducts.Name = "groupBoxSupplierProducts";
groupBoxSupplierProducts.Size = new Size(361, 482);
groupBoxSupplierProducts.TabIndex = 10;
groupBoxSupplierProducts.TabStop = false;
groupBoxSupplierProducts.Text = "Доступные товары поставщика";
//
// buttonDeleteProduct
//
buttonDeleteProduct.Location = new Point(58, 307);
buttonDeleteProduct.Name = "buttonDeleteProduct";
buttonDeleteProduct.Size = new Size(81, 23);
buttonDeleteProduct.TabIndex = 15;
buttonDeleteProduct.Text = "Удалить";
buttonDeleteProduct.UseVisualStyleBackColor = true;
buttonDeleteProduct.Click += buttonDeleteProduct_Click;
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(6, 251);
label2.Name = "label2";
label2.Size = new Size(46, 15);
label2.TabIndex = 13;
label2.Text = "Кол-во";
//
// buttonCancel
//
buttonCancel.Location = new Point(262, 453);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(13, 223);
label1.Name = "label1";
label1.Size = new Size(39, 15);
label1.TabIndex = 12;
label1.Text = "Товар";
//
// buttonSaveSupplier
//
buttonSaveSupplier.Location = new Point(29, 453);
buttonSaveSupplier.Name = "buttonSaveSupplier";
buttonSaveSupplier.Size = new Size(75, 23);
buttonSaveSupplier.TabIndex = 4;
buttonSaveSupplier.Text = "Сохранить";
buttonSaveSupplier.UseVisualStyleBackColor = true;
buttonSaveSupplier.Click += buttonSaveProduct_Click;
//
// numericUpDownCount
//
numericUpDownCount.Location = new Point(58, 249);
numericUpDownCount.Maximum = new decimal(new int[] { 100000, 0, 0, 0 });
numericUpDownCount.Name = "numericUpDownCount";
numericUpDownCount.Size = new Size(297, 23);
numericUpDownCount.TabIndex = 11;
//
// comboBoxProducts
//
comboBoxProducts.FormattingEnabled = true;
comboBoxProducts.Location = new Point(58, 220);
comboBoxProducts.Name = "comboBoxProducts";
comboBoxProducts.Size = new Size(297, 23);
comboBoxProducts.TabIndex = 10;
//
// dataGridViewProducts
//
dataGridViewProducts.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewProducts.Columns.AddRange(new DataGridViewColumn[] { ColumnId, Column, Column2 });
dataGridViewProducts.Dock = DockStyle.Top;
dataGridViewProducts.Location = new Point(3, 19);
dataGridViewProducts.Name = "dataGridViewProducts";
dataGridViewProducts.Size = new Size(355, 195);
dataGridViewProducts.TabIndex = 8;
//
// buttonAddSupplierProduct
//
buttonAddSupplierProduct.Location = new Point(58, 278);
buttonAddSupplierProduct.Name = "buttonAddSupplierProduct";
buttonAddSupplierProduct.Size = new Size(81, 23);
buttonAddSupplierProduct.TabIndex = 9;
buttonAddSupplierProduct.Text = "Добавить";
buttonAddSupplierProduct.UseVisualStyleBackColor = true;
buttonAddSupplierProduct.Click += buttonAddSupplierProduct_Click;
//
// textBoxName
//
textBoxName.Location = new Point(110, 51);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(245, 23);
textBoxName.TabIndex = 0;
//
// groupBoxControls
//
groupBoxControls.BackColor = Color.Transparent;
groupBoxControls.Controls.Add(buttonDeleteSupplier);
groupBoxControls.Controls.Add(buttonUpdateSupplier);
groupBoxControls.Controls.Add(buttonCreateSupplier);
groupBoxControls.Dock = DockStyle.Right;
groupBoxControls.Location = new Point(655, 0);
groupBoxControls.Name = "groupBoxControls";
groupBoxControls.Size = new Size(264, 637);
groupBoxControls.TabIndex = 5;
groupBoxControls.TabStop = false;
groupBoxControls.Text = "Действия";
//
// buttonDeleteSupplier
//
buttonDeleteSupplier.Location = new Point(69, 120);
buttonDeleteSupplier.Name = "buttonDeleteSupplier";
buttonDeleteSupplier.Size = new Size(139, 23);
buttonDeleteSupplier.TabIndex = 3;
buttonDeleteSupplier.Text = "Удалить поставщика";
buttonDeleteSupplier.UseVisualStyleBackColor = true;
buttonDeleteSupplier.Click += buttonDeleteSupplier_Click;
//
// buttonUpdateSupplier
//
buttonUpdateSupplier.Location = new Point(46, 51);
buttonUpdateSupplier.Name = "buttonUpdateSupplier";
buttonUpdateSupplier.Size = new Size(179, 63);
buttonUpdateSupplier.TabIndex = 2;
buttonUpdateSupplier.Text = "Редактировать информацию о поставщике";
buttonUpdateSupplier.UseVisualStyleBackColor = true;
buttonUpdateSupplier.Click += buttonUpdateSupplier_Click;
//
// buttonCreateSupplier
//
buttonCreateSupplier.Location = new Point(69, 22);
buttonCreateSupplier.Name = "buttonCreateSupplier";
buttonCreateSupplier.Size = new Size(139, 23);
buttonCreateSupplier.TabIndex = 1;
buttonCreateSupplier.Text = "Добавить поставщика";
buttonCreateSupplier.UseVisualStyleBackColor = true;
buttonCreateSupplier.Click += buttonCreateSupplier_Click;
//
// dataGridView // dataGridView
// //
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Left; dataGridView.Dock = DockStyle.Left;
dataGridView.Location = new Point(0, 0); dataGridView.Location = new Point(0, 0);
dataGridView.Name = "dataGridView"; dataGridView.Name = "dataGridView";
dataGridView.Size = new Size(392, 637); dataGridView.Size = new Size(615, 637);
dataGridView.TabIndex = 4; dataGridView.TabIndex = 4;
// //
// ColumnId // buttonAdd
// //
ColumnId.HeaderText = "Id"; buttonAdd.Location = new Point(635, 50);
ColumnId.Name = "ColumnId"; buttonAdd.Name = "buttonAdd";
ColumnId.ReadOnly = true; buttonAdd.Size = new Size(75, 23);
buttonAdd.TabIndex = 5;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += buttonAdd_Click;
// //
// Column // buttonEdit
// //
Column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; buttonEdit.Location = new Point(648, 115);
Column.HeaderText = "Продукт"; buttonEdit.Name = "buttonEdit";
Column.Name = "Column"; buttonEdit.Size = new Size(122, 23);
Column.ReadOnly = true; buttonEdit.TabIndex = 6;
// buttonEdit.Text = "Редактировать";
// Column2 buttonEdit.UseVisualStyleBackColor = true;
// buttonEdit.Click += buttonEdit_Click;
Column2.HeaderText = "Кол-во";
Column2.Name = "Column2";
Column2.ReadOnly = true;
// //
// FormSuppliers // FormSuppliers
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(919, 637); ClientSize = new Size(919, 637);
Controls.Add(groupBoxCreateSupplier); Controls.Add(buttonEdit);
Controls.Add(groupBoxControls); Controls.Add(buttonAdd);
Controls.Add(dataGridView); Controls.Add(dataGridView);
Name = "FormSuppliers"; Name = "FormSuppliers";
Text = "FormSuppliers"; Text = "FormSuppliers";
Load += FormSuppliers_Load; Load += FormSuppliers_Load;
groupBoxCreateSupplier.ResumeLayout(false);
groupBoxCreateSupplier.PerformLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownDeals).EndInit();
groupBoxSupplierProducts.ResumeLayout(false);
groupBoxSupplierProducts.PerformLayout();
((System.ComponentModel.ISupportInitialize)numericUpDownCount).EndInit();
((System.ComponentModel.ISupportInitialize)dataGridViewProducts).EndInit();
groupBoxControls.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false); ResumeLayout(false);
} }
#endregion #endregion
private GroupBox groupBoxCreateSupplier;
private Button buttonCancel;
private Button buttonSaveSupplier;
private TextBox textBoxName;
private GroupBox groupBoxControls;
private Button buttonDeleteSupplier;
private Button buttonUpdateSupplier;
private Button buttonCreateSupplier;
private DataGridView dataGridView; private DataGridView dataGridView;
private DataGridView dataGridViewProducts; private Button buttonAdd;
private GroupBox groupBoxSupplierProducts; private Button buttonEdit;
private Button buttonAddSupplierProduct;
private ComboBox comboBoxProducts;
private Label label2;
private Label label1;
private NumericUpDown numericUpDownCount;
private Label label4;
private Label label3;
private NumericUpDown numericUpDownDeals;
private Button buttonDeleteProduct;
private DataGridViewTextBoxColumn ColumnId;
private DataGridViewTextBoxColumn Column;
private DataGridViewTextBoxColumn Column2;
} }
} }

View File

@ -22,48 +22,24 @@ namespace WinFormsApp
{ {
public partial class FormSuppliers : Form public partial class FormSuppliers : Form
{ {
private Guid? _id;
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly ISupplierLogic _supplierLogic; private readonly ISupplierLogic _supplierLogic;
private readonly IProductLogic _productLogic; private readonly IProductLogic _productLogic;
private Dictionary<Guid, (IProduct, int)> _supplierProducts;
private List<ProductViewModel> _productList;
public FormSuppliers(ILogger<FormMain> logger, ISupplierLogic supplierLogic, IProductLogic productLogic) public FormSuppliers(ILogger<FormMain> logger, ISupplierLogic supplierLogic, IProductLogic productLogic)
{ {
InitializeComponent(); InitializeComponent();
_supplierLogic = supplierLogic; _supplierLogic = supplierLogic;
_logger = logger; _logger = logger;
_productLogic = productLogic; _productLogic = productLogic;
_supplierProducts = new Dictionary<Guid, (IProduct, int)>();
_productList = _productLogic.ReadList(null);
if (_productList != null)
{
comboBoxProducts.DisplayMember = "Name";
comboBoxProducts.ValueMember = "Id";
comboBoxProducts.DataSource = _productList;
comboBoxProducts.SelectedItem = null;
}
} }
private void FormSuppliers_Load(object sender, EventArgs e) private void FormSuppliers_Load(object sender, EventArgs e)
{ {
LoadData(); LoadData();
groupBoxCreateSupplier.Hide();
//groupBoxCreateProduct.Enabled = false;
}
private void LoadSupplierData()
{
dataGridViewProducts.Rows.Clear();
foreach (var pc in _supplierProducts)
{
dataGridViewProducts.Rows.Add(new object[] { pc.Key, pc.Value.Item1.Name, pc.Value.Item2 });
}
} }
private void LoadData() private void LoadData()
{ {
_logger.LogInformation("Загрузка поставщиков");
try try
{ {
var list = _supplierLogic.ReadList(null); var list = _supplierLogic.ReadList(null);
@ -71,196 +47,40 @@ namespace WinFormsApp
{ {
dataGridView.DataSource = list; dataGridView.DataSource = list;
} }
_logger.LogInformation("Загрузка поставщиков"); _logger.LogInformation("Загрузка компьютеров");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка загрузки поставщиков"); _logger.LogError(ex, "Ошибка загрузки компьютеров");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
private void buttonCreateSupplier_Click(object sender, EventArgs e) private void buttonAdd_Click(object sender, EventArgs e)
{ {
//надо сделать че нибудь с фронтом а то всё грустно var service = Program.ServiceProvider?.GetService(typeof(FormSupplier));
groupBoxControls.Hide(); if (service is FormSupplier form)
//groupBoxControls.Enabled = false;
groupBoxCreateSupplier.Show();
//groupBoxCreateProduct.Enabled = true;
}
private void buttonUpdateSupplier_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count <= 0) return;
_id = (Guid)dataGridView.SelectedRows[0].Cells["Id"].Value;
groupBoxControls.Hide();
groupBoxCreateSupplier.Show();
_logger.LogInformation("Получение поставщика");
var view = _supplierLogic.ReadElement(new SupplierSearchModel
{ {
Id = _id.Value if (form.ShowDialog() == DialogResult.OK)
}); {
_supplierProducts = view.AvailibleProducts; LoadData();
textBoxName.Text = view.Name; }
numericUpDownDeals.Value = view.Deals; }
LoadSupplierData();
} }
private void buttonCancel_Click(object sender, EventArgs e) private void buttonEdit_Click(object sender, EventArgs e)
{ {
_id = null;
_supplierProducts.Clear();
groupBoxControls.Show();
//groupBoxControls.Enabled = false;
groupBoxCreateSupplier.Hide();
//groupBoxCreateProduct.Enabled = true;
textBoxName.Text = string.Empty;
}
private void buttonDeleteSupplier_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
if (MessageBox.Show("Удалить запись?", "Вопрос", var service = Program.ServiceProvider?.GetService(typeof(FormSupplier));
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) if (service is FormSupplier form)
{ {
Guid id = (Guid)dataGridView.SelectedRows[0].Cells["Id"].Value; form.Id = (Guid)dataGridView.SelectedRows[0].Cells["Id"].Value;
_logger.LogInformation("Удаление товара"); if (form.ShowDialog() == DialogResult.OK)
try
{ {
if (!_productLogic.Delete(new ProductBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData(); LoadData();
} }
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления товара");
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
public IProduct? ProductModel
{
get
{
if (_productList == null)
{
return null;
}
foreach (var elem in _productList)
{
if (elem.Id == Id)
{
return elem;
}
}
return null;
}
}
public Guid Id
{
get
{
return (Guid)comboBoxProducts.SelectedValue;
}
set
{
comboBoxProducts.SelectedValue = value;
}
}
private void buttonAddSupplierProduct_Click(object sender, EventArgs e)
{
Debug.WriteLine(comboBoxProducts.SelectedValue);
if (_supplierProducts.ContainsKey(Id))
{
_supplierProducts[Id] = (ProductModel, Convert.ToInt16(numericUpDownCount.Value));
}
else
{
_supplierProducts.Add(Id, (ProductModel, Convert.ToInt16(numericUpDownCount.Value)));
}
LoadSupplierData();
}
private void buttonSaveProduct_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните имя поставщика", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение поставщика");
try
{
var model = new SupplierBindingModel
{
Id = _id ?? Guid.Empty,
Name = textBoxName.Text,
Deals = Convert.ToInt32(numericUpDownDeals.Value),
AvailibleProducts = _supplierProducts
};
var operationResult = _id.HasValue ? _supplierLogic.Update(model) : _supplierLogic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения поставщика");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
finally
{
LoadData();
_id = null;
_supplierProducts = new Dictionary<Guid, (IProduct, int)>();
textBoxName.Text = string.Empty;
numericUpDownDeals.Value = 0;
//groupBoxControls.Enabled = true;
groupBoxControls.Show();
//groupBoxCreateSupplier.Enabled = false;
groupBoxCreateSupplier.Hide();
textBoxName.Text = string.Empty;
}
}
private void buttonDeleteProduct_Click(object sender, EventArgs e)
{
if (dataGridViewProducts.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
_logger.LogInformation("Удаление продукта из списка доступных продуктов поставщика");
Debug.WriteLine(_supplierProducts.Keys);
Debug.WriteLine(_supplierProducts.Values);
Debug.WriteLine((Guid)dataGridView.SelectedRows[0].Cells[0].Value);
_supplierProducts?.Remove((Guid)dataGridView.SelectedRows[0].Cells[0].Value);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadSupplierData();
} }
} }
} }

View File

@ -117,13 +117,4 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="ColumnId.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Column.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Column2.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root> </root>

210
WinFormsApp/FormSupply.Designer.cs generated Normal file
View File

@ -0,0 +1,210 @@
namespace WinFormsApp
{
partial class FormSupply
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
textBoxName = new TextBox();
dataGridView = new DataGridView();
ProductId = new DataGridViewTextBoxColumn();
ProductName = new DataGridViewTextBoxColumn();
ProductAmount = new DataGridViewTextBoxColumn();
groupBoxProducts = new GroupBox();
buttonDeleteProduct = new Button();
buttonUpdateProduct = new Button();
buttonAddProduct = new Button();
label1 = new Label();
buttonSave = new Button();
buttonCancel = new Button();
textBoxPrice = new TextBox();
comboBoxSupplier = new ComboBox();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
groupBoxProducts.SuspendLayout();
SuspendLayout();
//
// textBoxName
//
textBoxName.Location = new Point(18, 41);
textBoxName.Multiline = true;
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(434, 103);
textBoxName.TabIndex = 0;
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ProductId, ProductName, ProductAmount });
dataGridView.Location = new Point(6, 22);
dataGridView.Name = "dataGridView";
dataGridView.Size = new Size(423, 241);
dataGridView.TabIndex = 1;
//
// ProductId
//
ProductId.HeaderText = "Id";
ProductId.Name = "ProductId";
ProductId.ReadOnly = true;
ProductId.Visible = false;
//
// ProductName
//
ProductName.HeaderText = "Название";
ProductName.Name = "ProductName";
ProductName.ReadOnly = true;
//
// ProductAmount
//
ProductAmount.HeaderText = "Количество";
ProductAmount.Name = "ProductAmount";
ProductAmount.ReadOnly = true;
//
// groupBoxProducts
//
groupBoxProducts.Controls.Add(buttonDeleteProduct);
groupBoxProducts.Controls.Add(buttonUpdateProduct);
groupBoxProducts.Controls.Add(buttonAddProduct);
groupBoxProducts.Controls.Add(dataGridView);
groupBoxProducts.Location = new Point(12, 150);
groupBoxProducts.Name = "groupBoxProducts";
groupBoxProducts.Size = new Size(776, 288);
groupBoxProducts.TabIndex = 2;
groupBoxProducts.TabStop = false;
groupBoxProducts.Text = "Товары";
//
// buttonDeleteProduct
//
buttonDeleteProduct.Location = new Point(435, 132);
buttonDeleteProduct.Name = "buttonDeleteProduct";
buttonDeleteProduct.Size = new Size(126, 49);
buttonDeleteProduct.TabIndex = 4;
buttonDeleteProduct.Text = "Удалить";
buttonDeleteProduct.UseVisualStyleBackColor = true;
buttonDeleteProduct.Click += buttonDeleteProduct_Click;
//
// buttonUpdateProduct
//
buttonUpdateProduct.Location = new Point(435, 77);
buttonUpdateProduct.Name = "buttonUpdateProduct";
buttonUpdateProduct.Size = new Size(126, 49);
buttonUpdateProduct.TabIndex = 3;
buttonUpdateProduct.Text = "Изменить";
buttonUpdateProduct.UseVisualStyleBackColor = true;
buttonUpdateProduct.Click += buttonUpdateProduct_Click;
//
// buttonAddProduct
//
buttonAddProduct.Location = new Point(435, 22);
buttonAddProduct.Name = "buttonAddProduct";
buttonAddProduct.Size = new Size(126, 49);
buttonAddProduct.TabIndex = 2;
buttonAddProduct.Text = "Добавить";
buttonAddProduct.UseVisualStyleBackColor = true;
buttonAddProduct.Click += buttonAddProduct_Click;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(18, 23);
label1.Name = "label1";
label1.Size = new Size(100, 15);
label1.TabIndex = 3;
label1.Text = "Общие сведения";
//
// buttonSave
//
buttonSave.Location = new Point(654, 40);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.TabIndex = 4;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(654, 88);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
//
// textBoxPrice
//
textBoxPrice.Enabled = false;
textBoxPrice.Location = new Point(473, 88);
textBoxPrice.Name = "textBoxPrice";
textBoxPrice.Size = new Size(100, 23);
textBoxPrice.TabIndex = 6;
//
// comboBoxSupplier
//
comboBoxSupplier.FormattingEnabled = true;
comboBoxSupplier.Location = new Point(473, 41);
comboBoxSupplier.Name = "comboBoxSupplier";
comboBoxSupplier.Size = new Size(121, 23);
comboBoxSupplier.TabIndex = 7;
//
// FormSupply
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(comboBoxSupplier);
Controls.Add(textBoxPrice);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(label1);
Controls.Add(groupBoxProducts);
Controls.Add(textBoxName);
Name = "FormSupply";
Text = "FormSupply";
Load += FormSupply_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
groupBoxProducts.ResumeLayout(false);
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBoxName;
private DataGridView dataGridView;
private DataGridViewTextBoxColumn ProductId;
private DataGridViewTextBoxColumn ProductName;
private DataGridViewTextBoxColumn ProductAmount;
private GroupBox groupBoxProducts;
private Button buttonAddProduct;
private Label label1;
private Button buttonUpdateProduct;
private Button buttonDeleteProduct;
private Button buttonSave;
private Button buttonCancel;
private TextBox textBoxPrice;
private ComboBox comboBoxSupplier;
}
}

222
WinFormsApp/FormSupply.cs Normal file
View File

@ -0,0 +1,222 @@
using Contracts.BindingModels;
using Contracts.BusinessLogicContracts;
using Contracts.SearchModels;
using DataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsApp
{
public partial class FormSupply : Form
{
private readonly ILogger _logger;
private readonly ISupplyLogic _logic;
private readonly ISupplierLogic _supplierLogic;
private Guid? _id;
private Dictionary<Guid, (IProduct, int)> _supplyProducts;
public Guid Id { set { _id = value; } }
public FormSupply(ILogger<FormSupply> logger, ISupplyLogic logic, ISupplierLogic supplierLogic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_supplyProducts = new Dictionary<Guid, (IProduct, int)>();
_supplierLogic = supplierLogic;
}
private void FormSupply_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка изделия");
try
{
var view = _logic.ReadElement(new SupplySearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxName.Text = view.Name;
_supplyProducts = view.Products ?? new Dictionary<Guid, (IProduct, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
try
{
var list = _supplierLogic.ReadList(null);
if (list != null)
{
comboBoxSupplier.DisplayMember = "Name";
comboBoxSupplier.ValueMember = "Id";
comboBoxSupplier.DataSource = list;
comboBoxSupplier.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка клиентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка компонент изделия");
try
{
if (_supplyProducts != null)
{
dataGridView.Rows.Clear();
foreach (var pc in _supplyProducts)
{
dataGridView.Rows.Add(new object[] { pc.Key, pc.Value.Item1.Name, pc.Value.Item2 });
}
textBoxPrice.Text = CalcPrice().ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонент изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void buttonAddProduct_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSupplyProduct));
if (service is FormSupplyProduct form)
{
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ProductModel == null)
{
return;
}
_logger.LogInformation("Добавление нового компонента");
if (_supplyProducts.ContainsKey(form.Id))
{
_supplyProducts[form.Id] = (form.ProductModel, form.Count);
}
else
{
_supplyProducts.Add(form.Id, (form.ProductModel, form.Count));
}
LoadData();
}
}
}
private void buttonUpdateProduct_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormSupplyProduct));
if (service is FormSupplyProduct form)
{
Guid id = (Guid)dataGridView.SelectedRows[0].Cells[0].Value;
form.Id = id;
form.Count = _supplyProducts[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ProductModel == null)
{
return;
}
_logger.LogInformation("Изменение компонента");
_supplyProducts[form.Id] = (form.ProductModel, form.Count);
LoadData();
}
}
}
}
private void buttonDeleteProduct_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
_logger.LogInformation("Удаление компонента");
_supplyProducts?.Remove((Guid)dataGridView.SelectedRows[0].Cells[0].Value);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните информацию", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (_supplyProducts == null || _supplyProducts.Count == 0)
{
MessageBox.Show("Заполните товары", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение изделия");
try
{
var model = new SupplyBindingModel
{
Id = _id ?? Guid.NewGuid(),
Name = textBoxName.Text,
Date = DateTime.UtcNow,
Price = Convert.ToDouble(textBoxPrice.Text),
SupplierId = (Guid)comboBoxSupplier.SelectedValue,
SupplyProducts = _supplyProducts,
};
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 double CalcPrice()
{
double price = 0;
foreach (var elem in _supplyProducts)
{
price += ((elem.Value.Item1?.Price ?? 0) * elem.Value.Item2);
}
return Math.Round(price * 1.1, 2);
}
}
}

129
WinFormsApp/FormSupply.resx Normal file
View File

@ -0,0 +1,129 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="ProductId.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ProductName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ProductAmount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,94 @@
namespace WinFormsApp
{
partial class FormSupplyProduct
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
numericUpDownCount = new NumericUpDown();
comboBoxProduct = new ComboBox();
buttonSave = new Button();
buttonCancel = new Button();
((System.ComponentModel.ISupportInitialize)numericUpDownCount).BeginInit();
SuspendLayout();
//
// numericUpDownCount
//
numericUpDownCount.Location = new Point(26, 76);
numericUpDownCount.Name = "numericUpDownCount";
numericUpDownCount.Size = new Size(120, 23);
numericUpDownCount.TabIndex = 1;
//
// comboBoxProduct
//
comboBoxProduct.FormattingEnabled = true;
comboBoxProduct.Location = new Point(25, 33);
comboBoxProduct.Name = "comboBoxProduct";
comboBoxProduct.Size = new Size(121, 23);
comboBoxProduct.TabIndex = 2;
//
// buttonSave
//
buttonSave.Location = new Point(192, 74);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.TabIndex = 3;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(192, 98);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 4;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormSupplyProduct
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(287, 138);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(comboBoxProduct);
Controls.Add(numericUpDownCount);
Name = "FormSupplyProduct";
Text = "FormSupplyProduct";
((System.ComponentModel.ISupportInitialize)numericUpDownCount).EndInit();
ResumeLayout(false);
}
#endregion
private NumericUpDown numericUpDownCount;
private ComboBox comboBoxProduct;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,88 @@
using Contracts.BusinessLogicContracts;
using Contracts.ViewModels;
using DataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsApp
{
public partial class FormSupplyProduct : Form
{
private readonly List<ProductViewModel>? _list;
public Guid Id
{
get
{
return (Guid)comboBoxProduct.SelectedValue;
}
set
{
comboBoxProduct.SelectedValue = value;
}
}
public IProduct? ProductModel
{
get
{
if (_list == null)
{
return null;
}
foreach (var elem in _list)
{
if (elem.Id == Id)
{
return elem;
}
}
return null;
}
}
public int Count
{
get { return Convert.ToInt32(numericUpDownCount.Value); }
set { numericUpDownCount.Value = value; }
}
public FormSupplyProduct(IProductLogic logic)
{
InitializeComponent();
_list = logic.ReadList(null);
if (_list != null)
{
comboBoxProduct.DisplayMember = "Name";
comboBoxProduct.ValueMember = "Id";
comboBoxProduct.DataSource = _list;
comboBoxProduct.SelectedItem = null;
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (numericUpDownCount.Value == null || numericUpDownCount.Value <= 0)
{
MessageBox.Show("Кол-во товаров должно иметь значение больше 0", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxProduct.SelectedValue == null)
{
MessageBox.Show("Выберите товар", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
DialogResult = DialogResult.OK;
Close();
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -47,6 +47,11 @@ namespace WinFormsApp
services.AddTransient<FormMain>(); services.AddTransient<FormMain>();
services.AddTransient<FormProducts>(); services.AddTransient<FormProducts>();
services.AddTransient<FormSuppliers>(); services.AddTransient<FormSuppliers>();
services.AddTransient<FormSupplier>();
services.AddTransient<FormSupply>();
services.AddTransient<FormSupplyProduct>();
services.AddTransient<FormSupplierProduct>();
} }
} }
} }