крякнул, плюнул и надежно склеил скотчем

This commit is contained in:
Леонид Малафеев 2024-05-05 22:05:04 +04:00
parent 50958317dd
commit 49c8023f82
22 changed files with 1426 additions and 698 deletions

View File

@ -4,6 +4,7 @@ using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.StoragesContracts; using JewelryStoreContracts.StoragesContracts;
using JewelryStoreContracts.ViewModels; using JewelryStoreContracts.ViewModels;
using JewerlyStoreDataModels.Enums; using JewerlyStoreDataModels.Enums;
using JewerlyStoreDataModels.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -18,11 +19,17 @@ namespace JewelryStoreBusinessLogic.BusinessLogics
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage; private readonly IOrderStorage _orderStorage;
private readonly IShopStorage _shopStorage;
private readonly IShopLogic _shopLogic;
private readonly IJewelStorage _jewelStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage) public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IJewelStorage jewelStorage)
{ {
_logger = logger; _logger = logger;
_orderStorage = orderStorage; _orderStorage = orderStorage;
_shopStorage = shopStorage;
_shopLogic = shopLogic;
_jewelStorage = jewelStorage;
} }
public bool CreateOrder(OrderBindingModel model) public bool CreateOrder(OrderBindingModel model)
@ -85,8 +92,19 @@ namespace JewelryStoreBusinessLogic.BusinessLogics
{ {
_logger.LogWarning("Status change operation failed"); _logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Заказ должен быть переведен в статус выполнения перед готовностью!"); throw new InvalidOperationException("Заказ должен быть переведен в статус выполнения перед готовностью!");
} }
model.Status = OrderStatus.Готов; model.Status = OrderStatus.Готов;
var jewel = _jewelStorage.GetElement(new JewelSearchModel() { Id = model.JewelId });
if (jewel == null)
{
_logger.LogWarning("Status change error. Jewel not found");
return false;
}
if (!CheckSupply(jewel, model.Count))
{
_logger.LogWarning("Status change error. Shop doesnt have jeweles");
return false;
}
_orderStorage.Update(model); _orderStorage.Update(model);
return true; return true;
} }
@ -132,5 +150,65 @@ namespace JewelryStoreBusinessLogic.BusinessLogics
throw new InvalidOperationException("Заказ с таким ID уже существует"); throw new InvalidOperationException("Заказ с таким ID уже существует");
} }
} }
public bool CheckSupply(IJewelModel jewel, int count)
{
if (count <= 0)
{
_logger.LogWarning("Check supply operation error. Jewel count < 0");
return false;
}
int Capacity = _shopStorage.GetFullList().Select(x => x.MaxCountJewels).Sum();
int currentCount = _shopStorage.GetFullList().Select(x => x.ShopJewels.Select(y => y.Value.Item2).Sum()).Sum();
int freeSpace = Capacity - currentCount;
if (freeSpace < count)
{
_logger.LogWarning("Check supply error. No place for new Jewels");
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
freeSpace = shop.MaxCountJewels;
foreach (var doc in shop.ShopJewels)
{
freeSpace -= doc.Value.Item2;
}
if (freeSpace == 0)
{
continue;
}
if (freeSpace >= count)
{
if (_shopLogic.AddJewel(new()
{
Id = shop.Id
}, jewel, count))
{
count = 0;
}
else
{
_logger.LogWarning("Supply error");
return false;
}
}
else
{
if (_shopLogic.AddJewel(new() { Id = shop.Id }, jewel, freeSpace))
count -= freeSpace;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (count <= 0)
{
return true;
}
}
return false;
}
} }
} }

View File

@ -144,9 +144,15 @@ namespace JewelryStoreBusinessLogic.BusinessLogics
Address = element.Address, Address = element.Address,
ShopName = element.ShopName, ShopName = element.ShopName,
DateOpen = element.DateOpen, DateOpen = element.DateOpen,
MaxCountJewels = element.MaxCountJewels,
ShopJewels = element.ShopJewels ShopJewels = element.ShopJewels
}); });
return true; return true;
} }
}
public bool SellJewels(IJewelModel jewel, int count)
{
return _shopStorage.SellJewels(jewel, count);
}
}
} }

View File

@ -13,6 +13,7 @@ namespace JewelryStoreContracts.BindingModels
public string Address { get; set; } = string.Empty; public string Address { get; set; } = string.Empty;
public DateTime DateOpen { get; set; } = DateTime.Now; public DateTime DateOpen { get; set; } = DateTime.Now;
public Dictionary<int, (IJewelModel, int)> ShopJewels { get; set; } = new(); public Dictionary<int, (IJewelModel, int)> ShopJewels { get; set; } = new();
public int Id { get; set; } public int MaxCountJewels { get; set; }
public int Id { get; set; }
} }
} }

View File

@ -18,5 +18,6 @@ namespace JewelryStoreContracts.BusinessLogicsContracts
bool Update(ShopBindingModel model); bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel model); bool Delete(ShopBindingModel model);
bool AddJewel(ShopSearchModel model, IJewelModel Jewel, int count); bool AddJewel(ShopSearchModel model, IJewelModel Jewel, int count);
} bool SellJewels(IJewelModel model, int count);
}
} }

View File

@ -1,6 +1,7 @@
using JewelryStoreContracts.BindingModels; using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.SearchModels; using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.ViewModels; using JewelryStoreContracts.ViewModels;
using JewerlyStoreDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -17,5 +18,6 @@ namespace JewelryStoreContracts.StoragesContracts
ShopViewModel? Insert(ShopBindingModel model); ShopViewModel? Insert(ShopBindingModel model);
ShopViewModel? Update(ShopBindingModel model); ShopViewModel? Update(ShopBindingModel model);
ShopViewModel? Delete(ShopBindingModel model); ShopViewModel? Delete(ShopBindingModel model);
} bool SellJewels(IJewelModel model, int count);
}
} }

View File

@ -18,7 +18,9 @@ namespace JewelryStoreContracts.ViewModels
[DisplayName("Дата открытия")] [DisplayName("Дата открытия")]
public DateTime DateOpen { get; set; } = DateTime.Now; public DateTime DateOpen { get; set; } = DateTime.Now;
public Dictionary<int, (IJewelModel, int)> ShopJewels { get; set; } = new(); [DisplayName("Макс. кол-во изделий")]
public int MaxCountJewels { get; set; }
public Dictionary<int, (IJewelModel, int)> ShopJewels { get; set; } = new();
public int Id { get; set; } public int Id { get; set; }
} }
} }

View File

@ -3,6 +3,7 @@ using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.StoragesContracts; using JewelryStoreContracts.StoragesContracts;
using JewelryStoreContracts.ViewModels; using JewelryStoreContracts.ViewModels;
using JewelryStoreListImplement.Models; using JewelryStoreListImplement.Models;
using JewerlyStoreDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -108,5 +109,10 @@ namespace JewelryStoreListImplement.Implements
} }
return null; return null;
} }
}
public bool SellJewels (IJewelModel jewel, int count)
{
throw new NotImplementedException();
}
}
} }

View File

@ -16,7 +16,8 @@ namespace JewelryStoreListImplement.Models
public string Address { get; set; } = string.Empty; public string Address { get; set; } = string.Empty;
public DateTime DateOpen { get; set; } public DateTime DateOpen { get; set; }
public int Id { get; set; } public int MaxCountJewels { get; private set; }
public int Id { get; set; }
public Dictionary<int, (IJewelModel, int)> ShopJewels { get; private set; } = new Dictionary<int, (IJewelModel, int)>(); public Dictionary<int, (IJewelModel, int)> ShopJewels { get; private set; } = new Dictionary<int, (IJewelModel, int)>();
public static Shop? Create(ShopBindingModel? model) public static Shop? Create(ShopBindingModel? model)
@ -31,7 +32,8 @@ namespace JewelryStoreListImplement.Models
ShopName = model.ShopName, ShopName = model.ShopName,
Address = model.Address, Address = model.Address,
DateOpen = model.DateOpen, DateOpen = model.DateOpen,
ShopJewels = model.ShopJewels MaxCountJewels = model.MaxCountJewels,
ShopJewels = model.ShopJewels
}; };
} }
@ -44,7 +46,8 @@ namespace JewelryStoreListImplement.Models
ShopName = model.ShopName; ShopName = model.ShopName;
Address = model.Address; Address = model.Address;
DateOpen = model.DateOpen; DateOpen = model.DateOpen;
ShopJewels = model.ShopJewels; MaxCountJewels = model.MaxCountJewels;
ShopJewels = model.ShopJewels;
} }
public ShopViewModel GetViewModel => new() public ShopViewModel GetViewModel => new()
@ -53,7 +56,8 @@ namespace JewelryStoreListImplement.Models
ShopName = ShopName, ShopName = ShopName,
Address = Address, Address = Address,
DateOpen = DateOpen, DateOpen = DateOpen,
ShopJewels = ShopJewels ShopJewels = ShopJewels,
}; MaxCountJewels = MaxCountJewels
};
} }
} }

View File

@ -11,6 +11,7 @@ namespace JewerlyStoreDataModels.Models
string ShopName { get; } string ShopName { get; }
string Address { get; } string Address { get; }
DateTime DateOpen { get; } DateTime DateOpen { get; }
Dictionary<int, (IJewelModel, int)> ShopJewels { get; } int MaxCountJewels { get; }
Dictionary<int, (IJewelModel, int)> ShopJewels { get; }
} }
} }

View File

@ -15,9 +15,11 @@ namespace JewerlyStoreFileImplement
private readonly string ComponentFileName = "Component.xml"; private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml"; private readonly string OrderFileName = "Order.xml";
private readonly string JewelFileName = "Jewel.xml"; private readonly string JewelFileName = "Jewel.xml";
private readonly string ShopFileName = "Shop.xml";
public List<Component> Components { get; private set; } public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; } public List<Order> Orders { get; private set; }
public List<Jewel> Jewels { get; private set; } public List<Jewel> Jewels { get; private set; }
public List<Shop> Shops { get; private set; }
public static DataFileSingleton GetInstance() public static DataFileSingleton GetInstance()
{ {
@ -34,11 +36,14 @@ namespace JewerlyStoreFileImplement
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, OrderFileName, "Shops", x => x.GetXElement);
private DataFileSingleton() private DataFileSingleton()
{ {
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Jewels = LoadData(JewelFileName, "Jewel", x => Jewel.Create(x)!)!; Jewels = LoadData(JewelFileName, "Jewel", x => Jewel.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
} }
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction) private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)

View File

@ -0,0 +1,134 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.SearchModels;
using JewelryStoreContracts.StoragesContracts;
using JewelryStoreContracts.ViewModels;
using JewerlyStoreDataModels.Models;
using JewerlyStoreFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JewerlyStoreFileImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataFileSingleton source;
public ShopStorage()
{
source = DataFileSingleton.GetInstance();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return source.Shops.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName))
{
return new();
}
return source.Shops
.Select(x => x.GetViewModel)
.Where(x => x.ShopName.Contains(model.ShopName ?? string.Empty))
.ToList();
}
public List<ShopViewModel> GetFullList()
{
return source.Shops.Select(shop => shop.GetViewModel).ToList();
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = source.Shops.Count > 0 ? source.Shops.Max(x => x.Id) + 1 : 1;
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
source.Shops.Add(newShop);
source.SaveShops();
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
source.SaveShops();
return shop.GetViewModel;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
source.Shops.Remove(shop);
source.SaveShops();
return shop.GetViewModel;
}
public bool SellJewels(IJewelModel model, int count)
{
var jewel = source.Jewels.FirstOrDefault(x => x.Id == model.Id);
if (jewel == null)
{
return false;
}
int countStore = source.Shops
.SelectMany(x => x.ShopJewels)
.Where(y => y.Key == model.Id)
.Sum(y => y.Value.Item2);
if (count > countStore)
return false;
foreach (var shop in source.Shops)
{
var jewels = shop.ShopJewels;
foreach (var c in jewels.Where(x => x.Value.Item1.Id == jewel.Id))
{
int min = Math.Min(c.Value.Item2, count);
jewels[c.Value.Item1.Id] = (c.Value.Item1, c.Value.Item2 - min);
count -= min;
if (count <= 0)
break;
}
shop.Update(new ShopBindingModel
{
Id = shop.Id,
ShopName = shop.ShopName,
Address = shop.Address,
MaxCountJewels = shop.MaxCountJewels,
DateOpen = shop.DateOpen,
ShopJewels = jewels
});
source.SaveShops();
if (count <= 0)
return true;
}
return true;
}
}
}

View File

@ -0,0 +1,116 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.ViewModels;
using JewerlyStoreDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace JewerlyStoreFileImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public int MaxCountJewels { get; private set; }
public DateTime DateOpen { get; private set; }
public Dictionary<int, int> Jewels { get; private set; } = new();
private Dictionary<int, (IJewelModel, int)>? _shopJewels = null;
public Dictionary<int, (IJewelModel, int)> ShopJewels
{
get
{
if (_shopJewels == null)
{
var source = DataFileSingleton.GetInstance();
_shopJewels = Jewels.ToDictionary(
x => x.Key,
y => ((source.Jewels.FirstOrDefault(z => z.Id == y.Key) as IJewelModel)!, y.Value)
);
}
return _shopJewels;
}
}
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
MaxCountJewels = model.MaxCountJewels,
DateOpen = model.DateOpen,
Jewels = model.ShopJewels.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Shop()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShopName = element.Element("ShopName")!.Value,
Address = element.Element("Address")!.Value,
MaxCountJewels = Convert.ToInt32(element.Element("MaxCountJewels")!.Value),
DateOpen = Convert.ToDateTime(element.Element("DateOpen")!.Value),
Jewels = element.Element("ShopJewels")!.Elements("ShopJewel").ToDictionary(
x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value)
)
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
MaxCountJewels = model.MaxCountJewels;
DateOpen = model.DateOpen;
if (model.ShopJewels.Count > 0)
{
Jewels = model.ShopJewels.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopJewels = null;
}
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
MaxCountJewels = MaxCountJewels,
DateOpen = DateOpen,
ShopJewels = ShopJewels,
};
public XElement GetXElement => new(
"Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("Address", Address),
new XElement("MaxCountJewels", MaxCountJewels),
new XElement("DateOpening", DateOpen.ToString()),
new XElement("ShopJewels", Jewels.Select(x =>
new XElement("ShopJewel",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray()));
}
}

View File

@ -1,198 +1,209 @@
namespace JewelryStoreView namespace JewerlyStoreView
{ {
partial class FormMain partial class FormMain
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary> /// <summary>
/// Clean up any resources being used. /// Clean up any resources being used.
/// </summary> /// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) if (disposing && (components != null))
{ {
components.Dispose(); components.Dispose();
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>
/// Required method for Designer support - do not modify /// Required method for Designer support - do not modify
/// the contents of this method with the code editor. /// the contents of this method with the code editor.
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
dataGridView = new DataGridView(); menuStrip = new MenuStrip();
menuStripMain = new MenuStrip(); справочникиToolStripMenuItem = new ToolStripMenuItem();
справочникиToolStripMenuItem = new ToolStripMenuItem(); компонентыToolStripMenuItem = new ToolStripMenuItem();
компонентыToolStripMenuItem = new ToolStripMenuItem(); изделиеToolStripMenuItem = new ToolStripMenuItem();
изделияToolStripMenuItem = new ToolStripMenuItem(); магазиныToolStripMenuItem = new ToolStripMenuItem();
магазинToolStripMenuItem = new ToolStripMenuItem(); пополнениеМагазинаToolStripMenuItem = new ToolStripMenuItem();
buttonCreateOrder = new Button(); продажаИзделийToolStripMenuItem = new ToolStripMenuItem();
buttonTakeOrderInWork = new Button(); dataGridView = new DataGridView();
buttonOrderReady = new Button(); buttonCreateOrder = new Button();
buttonIssuedOrder = new Button(); buttonTakeOrderInWork = new Button();
buttonRefresh = new Button(); buttonOrderReady = new Button();
buttonAddJewel = new Button(); buttonIssuedOrder = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); buttonUpd = new Button();
menuStripMain.SuspendLayout(); menuStrip.SuspendLayout();
SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
// SuspendLayout();
// dataGridView //
// // menuStrip
dataGridView.BackgroundColor = SystemColors.Control; //
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; menuStrip.ImageScalingSize = new Size(20, 20);
dataGridView.Location = new Point(12, 31); menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, пополнениеМагазинаToolStripMenuItem, продажаИзделийToolStripMenuItem });
dataGridView.Name = "dataGridView"; menuStrip.Location = new Point(0, 0);
dataGridView.RowTemplate.Height = 25; menuStrip.Name = "menuStrip";
dataGridView.Size = new Size(762, 407); menuStrip.Padding = new Padding(5, 2, 0, 2);
dataGridView.TabIndex = 0; menuStrip.Size = new Size(1003, 24);
// menuStrip.TabIndex = 0;
// menuStripMain menuStrip.Text = "menuStrip1";
// //
menuStripMain.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem }); // справочникиToolStripMenuItem
menuStripMain.Location = new Point(0, 0); //
menuStripMain.Name = "menuStripMain"; справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделиеToolStripMenuItem, магазиныToolStripMenuItem });
menuStripMain.Size = new Size(1021, 24); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
menuStripMain.TabIndex = 2; справочникиToolStripMenuItem.Size = new Size(94, 20);
menuStripMain.Text = "menuStripMain"; справочникиToolStripMenuItem.Text = "Справочники";
// //
// справочникиToolStripMenuItem // компонентыToolStripMenuItem
// //
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, магазинToolStripMenuItem }); компонентыToolStripMenuItem.Name = омпонентыToolStripMenuItem";
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; компонентыToolStripMenuItem.Size = new Size(145, 22);
справочникиToolStripMenuItem.Size = new Size(94, 20); компонентыToolStripMenuItem.Text = "Компоненты";
справочникиToolStripMenuItem.Text = "Справочники"; компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click;
// //
// компонентыToolStripMenuItem // изделиеToolStripMenuItem
// //
компонентыToolStripMenuItem.Name = омпонентыToolStripMenuItem"; изделиеToolStripMenuItem.Name = "изделиеToolStripMenuItem";
компонентыToolStripMenuItem.Size = new Size(145, 22); изделиеToolStripMenuItem.Size = new Size(145, 22);
компонентыToolStripMenuItem.Text = "Компоненты"; изделиеToolStripMenuItem.Text = "Изделие";
компонентыToolStripMenuItem.Click += компонентыToolStripMenuItem_Click_1; изделиеToolStripMenuItem.Click += ЗакускаToolStripMenuItem_Click;
// //
// изделияToolStripMenuItem // магазиныToolStripMenuItem
// //
изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
изделияToolStripMenuItem.Size = new Size(145, 22); магазиныToolStripMenuItem.Size = new Size(145, 22);
изделияToolStripMenuItem.Text = "Изделия"; магазиныToolStripMenuItem.Text = "Магазины";
изделияToolStripMenuItem.Click += изделияToolStripMenuItem_Click; магазиныToolStripMenuItem.Click += МагазиныToolStripMenuItem_Click;
// //
// магазинToolStripMenuItem // пополнениеМагазинаToolStripMenuItem
// //
магазинToolStripMenuItem.Name = агазинToolStripMenuItem"; пополнениеМагазинаToolStripMenuItem.Name = "пополнениеМагазинаToolStripMenuItem";
магазинToolStripMenuItem.Size = new Size(145, 22); пополнениеМагазинаToolStripMenuItem.Size = new Size(143, 20);
магазинToolStripMenuItem.Text = "Магазины"; пополнениеМагазинаToolStripMenuItem.Text = "Пополнение магазина";
магазинToolStripMenuItem.Click += МагазиныToolStripMenuItem_Click; пополнениеМагазинаToolStripMenuItem.Click += ПополнениеМагазиныToolStripMenuItem_Click;
// //
// buttonCreateOrder // продажаИзделийToolStripMenuItem
// //
buttonCreateOrder.Location = new Point(836, 31); продажаИзделийToolStripMenuItem.Name = "продажаИзделийToolStripMenuItem";
buttonCreateOrder.Margin = new Padding(2); продажаИзделийToolStripMenuItem.Size = new Size(117, 20);
buttonCreateOrder.Name = "buttonCreateOrder"; продажаИзделийToolStripMenuItem.Text = "Продажа изделий";
buttonCreateOrder.Size = new Size(147, 34); продажаИзделийToolStripMenuItem.Click += sellJewelsToolStripMenuItem_Click;
buttonCreateOrder.TabIndex = 3; //
buttonCreateOrder.Text = "Создать заказ"; // dataGridView
buttonCreateOrder.UseVisualStyleBackColor = true; //
buttonCreateOrder.Click += ButtonCreateOrder_Click; dataGridView.BackgroundColor = SystemColors.ControlLightLight;
// dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
// buttonTakeOrderInWork dataGridView.Location = new Point(10, 23);
// dataGridView.Margin = new Padding(3, 2, 3, 2);
buttonTakeOrderInWork.Location = new Point(836, 81); dataGridView.Name = "dataGridView";
buttonTakeOrderInWork.Margin = new Padding(2); dataGridView.RowHeadersWidth = 51;
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; dataGridView.RowTemplate.Height = 29;
buttonTakeOrderInWork.Size = new Size(147, 36); dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
buttonTakeOrderInWork.TabIndex = 4; dataGridView.Size = new Size(802, 305);
buttonTakeOrderInWork.Text = "Отдать на выполнение"; dataGridView.TabIndex = 1;
buttonTakeOrderInWork.UseVisualStyleBackColor = true; //
buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; // buttonCreateOrder
// //
// buttonOrderReady buttonCreateOrder.Location = new Point(817, 44);
// buttonCreateOrder.Margin = new Padding(3, 2, 3, 2);
buttonOrderReady.Location = new Point(836, 132); buttonCreateOrder.Name = "buttonCreateOrder";
buttonOrderReady.Margin = new Padding(2); buttonCreateOrder.Size = new Size(175, 28);
buttonOrderReady.Name = "buttonOrderReady"; buttonCreateOrder.TabIndex = 2;
buttonOrderReady.Size = new Size(147, 34); buttonCreateOrder.Text = "Создать заказ";
buttonOrderReady.TabIndex = 5; buttonCreateOrder.UseVisualStyleBackColor = true;
buttonOrderReady.Text = "Заказ готов"; buttonCreateOrder.Click += ButtonCreateOrder_Click;
buttonOrderReady.UseVisualStyleBackColor = true; //
buttonOrderReady.Click += ButtonOrderReady_Click; // buttonTakeOrderInWork
// //
// buttonIssuedOrder buttonTakeOrderInWork.Location = new Point(817, 84);
// buttonTakeOrderInWork.Margin = new Padding(3, 2, 3, 2);
buttonIssuedOrder.Location = new Point(836, 183); buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
buttonIssuedOrder.Margin = new Padding(2); buttonTakeOrderInWork.Size = new Size(175, 28);
buttonIssuedOrder.Name = "buttonIssuedOrder"; buttonTakeOrderInWork.TabIndex = 3;
buttonIssuedOrder.Size = new Size(147, 35); buttonTakeOrderInWork.Text = "Отдать на выполнение";
buttonIssuedOrder.TabIndex = 6; buttonTakeOrderInWork.UseVisualStyleBackColor = true;
buttonIssuedOrder.Text = "Заказ выдан"; buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click;
buttonIssuedOrder.UseVisualStyleBackColor = true; //
buttonIssuedOrder.Click += ButtonIssuedOrder_Click; // buttonOrderReady
// //
// buttonRefresh buttonOrderReady.Location = new Point(817, 124);
// buttonOrderReady.Margin = new Padding(3, 2, 3, 2);
buttonRefresh.Location = new Point(836, 234); buttonOrderReady.Name = "buttonOrderReady";
buttonRefresh.Margin = new Padding(2); buttonOrderReady.Size = new Size(175, 28);
buttonRefresh.Name = "buttonRefresh"; buttonOrderReady.TabIndex = 4;
buttonRefresh.Size = new Size(147, 39); buttonOrderReady.Text = "Заказ готов";
buttonRefresh.TabIndex = 7; buttonOrderReady.UseVisualStyleBackColor = true;
buttonRefresh.Text = "Обновить список"; buttonOrderReady.Click += ButtonOrderReady_Click;
buttonRefresh.UseVisualStyleBackColor = true; //
buttonRefresh.Click += ButtonRefresh_Click; // buttonIssuedOrder
// //
// buttonAddJewel buttonIssuedOrder.Location = new Point(817, 166);
// buttonIssuedOrder.Margin = new Padding(3, 2, 3, 2);
buttonAddJewel.Location = new Point(836, 287); buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonAddJewel.Name = "buttonAddJewel"; buttonIssuedOrder.Size = new Size(175, 28);
buttonAddJewel.Size = new Size(147, 35); buttonIssuedOrder.TabIndex = 5;
buttonAddJewel.TabIndex = 8; buttonIssuedOrder.Text = "Заказ выдан";
buttonAddJewel.Text = "Добавить украшение"; buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonAddJewel.UseVisualStyleBackColor = true; buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
buttonAddJewel.Click += ButtonAddJewel_Click; //
// // buttonUpd
// FormMain //
// buttonUpd.Location = new Point(817, 208);
AutoScaleDimensions = new SizeF(7F, 15F); buttonUpd.Margin = new Padding(3, 2, 3, 2);
AutoScaleMode = AutoScaleMode.Font; buttonUpd.Name = "buttonUpd";
ClientSize = new Size(1021, 450); buttonUpd.Size = new Size(175, 28);
Controls.Add(buttonAddJewel); buttonUpd.TabIndex = 6;
Controls.Add(buttonRefresh); buttonUpd.Text = "Обновить список";
Controls.Add(buttonIssuedOrder); buttonUpd.UseVisualStyleBackColor = true;
Controls.Add(buttonOrderReady); buttonUpd.Click += ButtonUpd_Click;
Controls.Add(buttonTakeOrderInWork); //
Controls.Add(buttonCreateOrder); // FormMain
Controls.Add(menuStripMain); //
Controls.Add(dataGridView); AutoScaleDimensions = new SizeF(7F, 15F);
MainMenuStrip = menuStripMain; AutoScaleMode = AutoScaleMode.Font;
Name = "FormMain"; ClientSize = new Size(1003, 338);
Text = "Ювелирный"; Controls.Add(buttonUpd);
Load += FormMain_Load; Controls.Add(buttonIssuedOrder);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); Controls.Add(buttonOrderReady);
menuStripMain.ResumeLayout(false); Controls.Add(buttonTakeOrderInWork);
menuStripMain.PerformLayout(); Controls.Add(buttonCreateOrder);
ResumeLayout(false); Controls.Add(dataGridView);
PerformLayout(); Controls.Add(menuStrip);
} MainMenuStrip = menuStrip;
Margin = new Padding(3, 2, 3, 2);
Name = "FormMain";
Text = "Ювелирный";
Load += FormMain_Load;
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion #endregion
private DataGridView dataGridView; private MenuStrip menuStrip;
private MenuStrip menuStripMain; private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem справочникиToolStripMenuItem; private DataGridView dataGridView;
private ToolStripMenuItem компонентыToolStripMenuItem; private Button buttonCreateOrder;
private ToolStripMenuItem изделияToolStripMenuItem; private Button buttonTakeOrderInWork;
private ToolStripMenuItem магазинToolStripMenuItem; private Button buttonOrderReady;
private Button buttonCreateOrder; private Button buttonIssuedOrder;
private Button buttonTakeOrderInWork; private Button buttonUpd;
private Button buttonOrderReady; private ToolStripMenuItem компонентыToolStripMenuItem;
private Button buttonIssuedOrder; private ToolStripMenuItem изделиеToolStripMenuItem;
private Button buttonRefresh; private ToolStripMenuItem магазиныToolStripMenuItem;
private Button buttonAddJewel; private ToolStripMenuItem пополнениеМагазинаToolStripMenuItem;
} private ToolStripMenuItem продажаИзделийToolStripMenuItem;
}
} }

View File

@ -1,7 +1,7 @@
using JewelryStoreContracts.BindingModels; using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.BusinessLogicsContracts; using JewelryStoreContracts.BusinessLogicsContracts;
using JewelryStoreView;
using JewerlyStoreDataModels.Enums; using JewerlyStoreDataModels.Enums;
using JewerlyStoreView;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -13,188 +13,184 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
namespace JewelryStoreView namespace JewerlyStoreView
{ {
public partial class FormMain : Form public partial class FormMain : Form
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic) private readonly IOrderLogic _orderLogic;
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
}
private void FormMain_Load(object sender, EventArgs e) public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic)
{ {
LoadData(); InitializeComponent();
} _logger = logger;
_orderLogic = orderLogic;
}
private void LoadData() private void FormMain_Load(object sender, EventArgs e)
{ {
try LoadData();
{ }
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["JewelId"].Visible = false;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCreateOrder_Click(object sender, EventArgs e) private void LoadData()
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); try
if (service is FormCreateOrder form) {
{ var list = _orderLogic.ReadList(null);
form.ShowDialog(); if (list != null)
LoadData(); {
} dataGridView.DataSource = list;
} dataGridView.Columns["JewelId"].Visible = false;
dataGridView.Columns["JewelName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Orders loading");
}
catch (Exception ex)
{
_logger.LogError(ex, "Orders loading error");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void sellJewelsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShopSell));
if (service is FormShopSell form)
{
form.ShowDialog();
}
}
private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
{ if (service is FormComponents form)
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); {
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); form.ShowDialog();
try }
{ }
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = id,
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
JewelId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["JewelId"].Value),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonOrderReady_Click(object sender, EventArgs e) private void ЗакускаToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) var service = Program.ServiceProvider?.GetService(typeof(FormJewels));
{ if (service is FormJewels form)
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); {
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id); form.ShowDialog();
try }
{ }
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel private void МагазиныToolStripMenuItem_Click(object sender, EventArgs e)
{ {
Id = id, var service = Program.ServiceProvider?.GetService(typeof(FormShops));
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), if (service is FormShops form)
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), {
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), form.ShowDialog();
JewelId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["JewelId"].Value), }
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()) }
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); private void ПополнениеМагазиныToolStripMenuItem_Click(object sender, EventArgs e)
} {
} var service = Program.ServiceProvider?.GetService(typeof(FormAddJewel));
} if (service is FormAddJewel form)
{
form.ShowDialog();
}
}
private void ButtonIssuedOrder_Click(object sender, EventArgs e) private void ButtonCreateOrder_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
{ if (service is FormCreateOrder form)
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); {
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id); form.ShowDialog();
try LoadData();
{ }
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel }
{
Id = id,
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
JewelId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["JewelId"].Value),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ №{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void ButtonRefresh_Click(object sender, EventArgs e)
{
LoadData();
}
private void компонентыToolStripMenuItem_Click_1(object sender, EventArgs e) private void ButtonTakeOrderInWork_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); if (dataGridView.SelectedRows.Count == 1)
if (service is FormComponents form) {
{ int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
form.ShowDialog(); _logger.LogInformation("Order №{id}. Status changes to 'В работе'", id);
} try
} {
var operationResult = _orderLogic.TakeOrderInWork(CreateBindingModel(id));
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error taking an order to work");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void изделияToolStripMenuItem_Click(object sender, EventArgs e) private void ButtonOrderReady_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormJewels)); if (dataGridView.SelectedRows.Count == 1)
if (service is FormJewels form) {
{ int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
form.ShowDialog(); _logger.LogInformation("Order №{id}. Status changes to 'Готов'", id);
} try
} {
private void МагазиныToolStripMenuItem_Click(object sender, EventArgs e) var operationResult = _orderLogic.FinishOrder(CreateBindingModel(id));
{ if (!operationResult)
var service = Program.ServiceProvider?.GetService(typeof(FormShops)); {
if (service is FormShops form) throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
{ }
form.ShowDialog(); LoadData();
} }
} catch (Exception ex)
{
_logger.LogError(ex, "Order readiness marking error");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonAddJewel_Click(object sender, EventArgs e) private void ButtonIssuedOrder_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormAddJewel)); if (dataGridView.SelectedRows.Count == 1)
if (service is FormAddJewel form) {
{ int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
form.ShowDialog(); _logger.LogInformation("Order №{id}. Status changes to 'Выдан'", id);
LoadData(); try
} {
} var operationResult = _orderLogic.DeliveryOrder(CreateBindingModel(id));
} if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Order №{id} issued", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Order issue marking error");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
LoadData();
}
private OrderBindingModel CreateBindingModel(int id)
{
return new OrderBindingModel
{
Id = id,
JewelId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["JewelId"].Value),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = (System.DateTime)dataGridView.SelectedRows[0].Cells["DateCreate"].Value,
};
}
}
} }

View File

@ -117,10 +117,7 @@
<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="menuStripMain.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"> <metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>40, 22</value> <value>17, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>64</value>
</metadata> </metadata>
</root> </root>

View File

@ -1,188 +1,214 @@
namespace JewerlyStoreView namespace JewerlyStoreView
{ {
partial class FormShop partial class FormShop
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary> /// <summary>
/// Clean up any resources being used. /// Clean up any resources being used.
/// </summary> /// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) if (disposing && (components != null))
{ {
components.Dispose(); components.Dispose();
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>
/// Required method for Designer support - do not modify /// Required method for Designer support - do not modify
/// the contents of this method with the code editor. /// the contents of this method with the code editor.
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.labelShop = new System.Windows.Forms.Label(); labelShop = new Label();
this.labelAddress = new System.Windows.Forms.Label(); labelAddress = new Label();
this.labelDate = new System.Windows.Forms.Label(); labelDate = new Label();
this.textBoxName = new System.Windows.Forms.TextBox(); textBoxName = new TextBox();
this.textBoxAddress = new System.Windows.Forms.TextBox(); textBoxAddress = new TextBox();
this.dateTimePickerDateOpen = new System.Windows.Forms.DateTimePicker(); dateTimePickerDateOpen = new DateTimePicker();
this.dataGridView = new System.Windows.Forms.DataGridView(); dataGridView = new DataGridView();
this.ButtonSave = new System.Windows.Forms.Button(); ID = new DataGridViewTextBoxColumn();
this.ButtonCancel = new System.Windows.Forms.Button(); JewelName = new DataGridViewTextBoxColumn();
this.ID = new System.Windows.Forms.DataGridViewTextBoxColumn(); Count = new DataGridViewTextBoxColumn();
this.JewelName = new System.Windows.Forms.DataGridViewTextBoxColumn(); ButtonSave = new Button();
this.Count = new System.Windows.Forms.DataGridViewTextBoxColumn(); ButtonCancel = new Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); labelMaxCountPrinteds = new Label();
this.SuspendLayout(); textBoxMaxCount = new TextBox();
// ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
// labelShop SuspendLayout();
// //
this.labelShop.AutoSize = true; // labelShop
this.labelShop.Location = new System.Drawing.Point(12, 21); //
this.labelShop.Name = "labelShop"; labelShop.AutoSize = true;
this.labelShop.Size = new System.Drawing.Size(69, 20); labelShop.Location = new Point(10, 16);
this.labelShop.TabIndex = 0; labelShop.Name = "labelShop";
this.labelShop.Text = "Магазин"; labelShop.Size = new Size(54, 15);
// labelShop.TabIndex = 0;
// labelAddress labelShop.Text = "Магазин";
// //
this.labelAddress.AutoSize = true; // labelAddress
this.labelAddress.Location = new System.Drawing.Point(195, 21); //
this.labelAddress.Name = "labelAddress"; labelAddress.AutoSize = true;
this.labelAddress.Size = new System.Drawing.Size(51, 20); labelAddress.Location = new Point(171, 16);
this.labelAddress.TabIndex = 1; labelAddress.Name = "labelAddress";
this.labelAddress.Text = "Адрес"; labelAddress.Size = new Size(40, 15);
// labelAddress.TabIndex = 1;
// labelDate labelAddress.Text = "Адрес";
// //
this.labelDate.AutoSize = true; // labelDate
this.labelDate.Location = new System.Drawing.Point(474, 21); //
this.labelDate.Name = "labelDate"; labelDate.AutoSize = true;
this.labelDate.Size = new System.Drawing.Size(110, 20); labelDate.Location = new Point(415, 16);
this.labelDate.TabIndex = 2; labelDate.Name = "labelDate";
this.labelDate.Text = "Дата открытия"; labelDate.Size = new Size(87, 15);
// labelDate.TabIndex = 2;
// textBoxName labelDate.Text = "Дата открытия";
// //
this.textBoxName.Location = new System.Drawing.Point(12, 44); // textBoxName
this.textBoxName.Name = "textBoxName"; //
this.textBoxName.Size = new System.Drawing.Size(160, 27); textBoxName.Location = new Point(10, 33);
this.textBoxName.TabIndex = 3; textBoxName.Margin = new Padding(3, 2, 3, 2);
// textBoxName.Name = "textBoxName";
// textBoxAddress textBoxName.Size = new Size(140, 23);
// textBoxName.TabIndex = 3;
this.textBoxAddress.Location = new System.Drawing.Point(195, 44); //
this.textBoxAddress.Name = "textBoxAddress"; // textBoxAddress
this.textBoxAddress.Size = new System.Drawing.Size(246, 27); //
this.textBoxAddress.TabIndex = 4; textBoxAddress.Location = new Point(171, 33);
// textBoxAddress.Margin = new Padding(3, 2, 3, 2);
// dateTimePickerDateOpen textBoxAddress.Name = "textBoxAddress";
// textBoxAddress.Size = new Size(216, 23);
this.dateTimePickerDateOpen.Location = new System.Drawing.Point(474, 44); textBoxAddress.TabIndex = 4;
this.dateTimePickerDateOpen.Name = "dateTimePickerDateOpen"; //
this.dateTimePickerDateOpen.Size = new System.Drawing.Size(250, 27); // dateTimePickerDateOpen
this.dateTimePickerDateOpen.TabIndex = 5; //
// dateTimePickerDateOpen.Location = new Point(415, 33);
// dataGridView dateTimePickerDateOpen.Margin = new Padding(3, 2, 3, 2);
// dateTimePickerDateOpen.Name = "dateTimePickerDateOpen";
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; dateTimePickerDateOpen.Size = new Size(219, 23);
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { dateTimePickerDateOpen.TabIndex = 5;
this.ID, //
this.JewelName, // dataGridView
this.Count}); //
this.dataGridView.Location = new System.Drawing.Point(12, 77); dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Name = "dataGridView"; dataGridView.Columns.AddRange(new DataGridViewColumn[] { ID, JewelName, Count });
this.dataGridView.RowHeadersWidth = 51; dataGridView.Location = new Point(10, 105);
this.dataGridView.RowTemplate.Height = 29; dataGridView.Margin = new Padding(3, 2, 3, 2);
this.dataGridView.Size = new System.Drawing.Size(712, 330); dataGridView.Name = "dataGridView";
this.dataGridView.TabIndex = 6; dataGridView.RowHeadersWidth = 51;
// dataGridView.RowTemplate.Height = 29;
// ButtonSave dataGridView.Size = new Size(623, 248);
// dataGridView.TabIndex = 6;
this.ButtonSave.Location = new System.Drawing.Point(490, 413); //
this.ButtonSave.Name = "ButtonSave"; // ID
this.ButtonSave.Size = new System.Drawing.Size(111, 29); //
this.ButtonSave.TabIndex = 7; ID.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
this.ButtonSave.Text = "Сохранить"; ID.HeaderText = "ID";
this.ButtonSave.UseVisualStyleBackColor = true; ID.MinimumWidth = 6;
this.ButtonSave.Click += new System.EventHandler(this.ButtonSave_Click); ID.Name = "ID";
// ID.Visible = false;
// ButtonCancel //
// // JewelName
this.ButtonCancel.Location = new System.Drawing.Point(630, 413); //
this.ButtonCancel.Name = "ButtonCancel"; JewelName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
this.ButtonCancel.Size = new System.Drawing.Size(94, 29); JewelName.HeaderText = "JewelName";
this.ButtonCancel.TabIndex = 8; JewelName.MinimumWidth = 6;
this.ButtonCancel.Text = "Отмена"; JewelName.Name = "JewelName";
this.ButtonCancel.UseVisualStyleBackColor = true; //
this.ButtonCancel.Click += new System.EventHandler(this.ButtonCancel_Click); // Count
// //
// ID Count.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
// Count.HeaderText = "Count";
this.ID.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; Count.MinimumWidth = 6;
this.ID.HeaderText = "ID"; Count.Name = "Count";
this.ID.MinimumWidth = 6; //
this.ID.Name = "ID"; // ButtonSave
this.ID.Visible = false; //
// ButtonSave.Location = new Point(448, 357);
// JewelName ButtonSave.Margin = new Padding(3, 2, 3, 2);
// ButtonSave.Name = "ButtonSave";
this.JewelName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; ButtonSave.Size = new Size(97, 22);
this.JewelName.HeaderText = "JewelName"; ButtonSave.TabIndex = 7;
this.JewelName.MinimumWidth = 6; ButtonSave.Text = "Сохранить";
this.JewelName.Name = "JewelName"; ButtonSave.UseVisualStyleBackColor = true;
// ButtonSave.Click += ButtonSave_Click;
// Count //
// // ButtonCancel
this.Count.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; //
this.Count.HeaderText = "Count"; ButtonCancel.Location = new Point(551, 357);
this.Count.MinimumWidth = 6; ButtonCancel.Margin = new Padding(3, 2, 3, 2);
this.Count.Name = "Count"; ButtonCancel.Name = "ButtonCancel";
// ButtonCancel.Size = new Size(82, 22);
// FormShop ButtonCancel.TabIndex = 8;
// ButtonCancel.Text = "Отмена";
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); ButtonCancel.UseVisualStyleBackColor = true;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; ButtonCancel.Click += ButtonCancel_Click;
this.ClientSize = new System.Drawing.Size(740, 450); //
this.Controls.Add(this.ButtonCancel); // labelMaxCountPrinteds
this.Controls.Add(this.ButtonSave); //
this.Controls.Add(this.dataGridView); labelMaxCountPrinteds.Location = new Point(10, 68);
this.Controls.Add(this.dateTimePickerDateOpen); labelMaxCountPrinteds.Name = "labelMaxCountPrinteds";
this.Controls.Add(this.textBoxAddress); labelMaxCountPrinteds.Size = new Size(140, 30);
this.Controls.Add(this.textBoxName); labelMaxCountPrinteds.TabIndex = 10;
this.Controls.Add(this.labelDate); labelMaxCountPrinteds.Text = "Максимальное количество изделий :";
this.Controls.Add(this.labelAddress); //
this.Controls.Add(this.labelShop); // textBoxMaxCount
this.Name = "FormShop"; //
this.Text = "Магазин"; textBoxMaxCount.Location = new Point(155, 78);
this.Load += new System.EventHandler(this.FormShop_Load); textBoxMaxCount.Margin = new Padding(3, 2, 3, 2);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); textBoxMaxCount.Name = "textBoxMaxCount";
this.ResumeLayout(false); textBoxMaxCount.Size = new Size(219, 23);
this.PerformLayout(); textBoxMaxCount.TabIndex = 11;
//
// FormShop
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(659, 426);
Controls.Add(ButtonCancel);
Controls.Add(ButtonSave);
Controls.Add(dataGridView);
Controls.Add(dateTimePickerDateOpen);
Controls.Add(textBoxAddress);
Controls.Add(textBoxName);
Controls.Add(labelDate);
Controls.Add(labelAddress);
Controls.Add(labelShop);
Controls.Add(textBoxMaxCount);
Controls.Add(labelMaxCountPrinteds);
Margin = new Padding(3, 2, 3, 2);
Name = "FormShop";
Text = "Магазин";
Load += FormShop_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
} #endregion
#endregion private Label labelShop;
private Label labelAddress;
private Label labelDate;
private Label labelMaxCountPrinteds;
private TextBox textBoxMaxCount;
private TextBox textBoxName;
private TextBox textBoxAddress;
private DateTimePicker dateTimePickerDateOpen;
private DataGridView dataGridView;
private Button ButtonSave;
private Button ButtonCancel;
private DataGridViewTextBoxColumn ID;
private DataGridViewTextBoxColumn JewelName;
private DataGridViewTextBoxColumn Count;
private Label labelShop; }
private Label labelAddress;
private Label labelDate;
private TextBox textBoxName;
private TextBox textBoxAddress;
private DateTimePicker dateTimePickerDateOpen;
private DataGridView dataGridView;
private Button ButtonSave;
private Button ButtonCancel;
private DataGridViewTextBoxColumn ID;
private DataGridViewTextBoxColumn JewelName;
private DataGridViewTextBoxColumn Count;
}
} }

View File

@ -15,117 +15,124 @@ using System.Windows.Forms;
namespace JewerlyStoreView namespace JewerlyStoreView
{ {
public partial class FormShop : Form public partial class FormShop : Form
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IShopLogic _logic; private readonly IShopLogic _logic;
private int? _id; private int? _id;
private Dictionary<int, (IJewelModel, int)> _shopJewels; private Dictionary<int, (IJewelModel, int)> _shopJewels;
public int Id { set { _id = value; } } public int Id { set { _id = value; } }
public FormShop(ILogger<FormShop> logger, IShopLogic logic) public FormShop(ILogger<FormShop> logger, IShopLogic logic)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger; _logger = logger;
_logic = logic; _logic = logic;
_shopJewels = new Dictionary<int, (IJewelModel, int)>(); _shopJewels = new Dictionary<int, (IJewelModel, int)>();
} }
private void FormShop_Load(object sender, EventArgs e) private void FormShop_Load(object sender, EventArgs e)
{ {
if (_id.HasValue) if (_id.HasValue)
{ {
_logger.LogInformation("Загрузка магазина"); _logger.LogInformation("Загрузка магазина");
try try
{ {
var view = _logic.ReadElement(new ShopSearchModel var view = _logic.ReadElement(new ShopSearchModel
{ {
Id = _id.Value Id = _id.Value
}); });
if (view != null) if (view != null)
{ {
textBoxName.Text = view.ShopName; textBoxName.Text = view.ShopName;
textBoxAddress.Text = view.Address.ToString(); textBoxAddress.Text = view.Address.ToString();
dateTimePickerDateOpen.Text = view.DateOpen.ToString(); dateTimePickerDateOpen.Text = view.DateOpen.ToString();
_shopJewels = view.ShopJewels ?? new Dictionary<int, (IJewelModel, int)>(); textBoxMaxCount.Text = view.MaxCountJewels.ToString();
LoadData(); _shopJewels = view.ShopJewels ?? new Dictionary<int, (IJewelModel, int)>();
} LoadData();
} }
catch (Exception ex) }
{ 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);
} }
} }
private void LoadData() }
{ private void LoadData()
_logger.LogInformation("Загрузка изделий магазина"); {
try _logger.LogInformation("Загрузка изделий магазина");
{ try
if (_shopJewels != null) {
{ if (_shopJewels != null)
dataGridView.Rows.Clear(); {
foreach (var element in _shopJewels) dataGridView.Rows.Clear();
{ foreach (var element in _shopJewels)
dataGridView.Rows.Add(new object[] { element.Key, element.Value.Item1.JewelName, element.Value.Item2 }); {
} dataGridView.Rows.Add(new object[] { element.Key, element.Value.Item1.JewelName, element.Value.Item2 });
} }
} }
catch (Exception ex) }
{ 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);
} }
}
private void ButtonSave_Click(object sender, EventArgs e) private void ButtonSave_Click(object sender, EventArgs e)
{ {
if (string.IsNullOrEmpty(textBoxName.Text)) if (string.IsNullOrEmpty(textBoxName.Text))
{ {
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
if (string.IsNullOrEmpty(textBoxAddress.Text)) if (string.IsNullOrEmpty(textBoxAddress.Text))
{ {
MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
if (string.IsNullOrEmpty(dateTimePickerDateOpen.Text)) if (string.IsNullOrEmpty(dateTimePickerDateOpen.Text))
{ {
MessageBox.Show("Заполните дату", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Заполните дату", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
_logger.LogInformation("Сохранение магазина"); if (string.IsNullOrEmpty(textBoxMaxCount.Text))
try {
{ MessageBox.Show("Заполните макс. количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
var model = new ShopBindingModel return;
{ }
Id = _id ?? 0, _logger.LogInformation("Сохранение магазина");
ShopName = textBoxName.Text, try
Address = textBoxAddress.Text, {
DateOpen = DateTime.Parse(dateTimePickerDateOpen.Text), var model = new ShopBindingModel
ShopJewels = _shopJewels {
}; Id = _id ?? 0,
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model); ShopName = textBoxName.Text,
if (!operationResult) Address = textBoxAddress.Text,
{ DateOpen = DateTime.Parse(dateTimePickerDateOpen.Text),
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); MaxCountJewels = Convert.ToInt32(textBoxMaxCount.Text),
} ShopJewels = _shopJewels
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); };
DialogResult = DialogResult.OK; var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
Close(); if (!operationResult)
} {
catch (Exception ex) throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
{ }
_logger.LogError(ex, "Ошибка сохранения магазина"); MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); DialogResult = DialogResult.OK;
} Close();
} }
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) private void ButtonCancel_Click(object sender, EventArgs e)
{ {
DialogResult = DialogResult.Cancel; DialogResult = DialogResult.Cancel;
Close(); Close();
} }
} }
} }

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<root> <root>
<!-- <!--
Microsoft ResX Schema Microsoft ResX Schema
Version 2.0 Version 2.0
The primary goals of this format is to allow a simple XML format The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes various data types are done through the TypeConverter classes
associated with the data types. associated with the data types.
Example: Example:
... ado.net/XML headers & schema ... ... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader> <resheader name="version">2.0</resheader>
@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment> <comment>This is a comment</comment>
</data> </data>
There are any number of "resheader" rows that contain simple There are any number of "resheader" rows that contain simple
name/value pairs. name/value pairs.
Each data row contains a name, and value. The row also contains a Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture. text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the Classes that don't support this are serialized and stored with the
mimetype set. mimetype set.
The mimetype is used for serialized objects, and tells the The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly: extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below. read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64 mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64 mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64 mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter : using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
--> -->

View File

@ -0,0 +1,119 @@
namespace JewerlyStoreView
{
partial class FormShopSell
{
/// <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()
{
labelJewel = new Label();
labelCount = new Label();
comboBoxJewel = new ComboBox();
textBoxCount = new TextBox();
buttonCancel = new Button();
buttonSell = new Button();
SuspendLayout();
//
// labelJewel
//
labelJewel.AutoSize = true;
labelJewel.Location = new Point(12, 9);
labelJewel.Name = "labelJewel";
labelJewel.Size = new Size(56, 15);
labelJewel.TabIndex = 0;
labelJewel.Text = "Изделие:";
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(12, 38);
labelCount.Name = "labelCount";
labelCount.Size = new Size(75, 15);
labelCount.TabIndex = 1;
labelCount.Text = "Количество:";
//
// comboBoxJewel
//
comboBoxJewel.FormattingEnabled = true;
comboBoxJewel.Location = new Point(88, 6);
comboBoxJewel.Name = "comboBoxJewel";
comboBoxJewel.Size = new Size(297, 23);
comboBoxJewel.TabIndex = 2;
//
// textBoxCount
//
textBoxCount.Location = new Point(88, 35);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(297, 23);
textBoxCount.TabIndex = 3;
//
// buttonCancel
//
buttonCancel.Location = new Point(310, 64);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 4;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// buttonSell
//
buttonSell.Location = new Point(229, 64);
buttonSell.Name = "buttonSell";
buttonSell.Size = new Size(75, 23);
buttonSell.TabIndex = 5;
buttonSell.Text = "Продать";
buttonSell.UseVisualStyleBackColor = true;
buttonSell.Click += buttonSell_Click;
//
// FormShopSell
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(397, 93);
Controls.Add(buttonSell);
Controls.Add(buttonCancel);
Controls.Add(textBoxCount);
Controls.Add(comboBoxJewel);
Controls.Add(labelCount);
Controls.Add(labelJewel);
Name = "FormShopSell";
Text = "Продажа";
Load += FormShopSell_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelJewel;
private Label labelCount;
private ComboBox comboBoxJewel;
private TextBox textBoxCount;
private Button buttonCancel;
private Button buttonSell;
}
}

View File

@ -0,0 +1,95 @@
using JewelryStoreContracts.BindingModels;
using JewelryStoreContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace JewerlyStoreView
{
public partial class FormShopSell : Form
{
private readonly ILogger _logger;
private readonly IJewelLogic _logicJewel;
private readonly IShopLogic _logicShop;
public FormShopSell(ILogger<FormShopSell> logger, IJewelLogic logicJewel, IShopLogic logicShop)
{
InitializeComponent();
_logger = logger;
_logicJewel = logicJewel;
_logicShop = logicShop;
}
private void FormShopSell_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка изделий для продажи");
try
{
var list = _logicJewel.ReadList(null);
if (list != null)
{
comboBoxJewel.DisplayMember = "JewelName";
comboBoxJewel.ValueMember = "Id";
comboBoxJewel.DataSource = list;
comboBoxJewel.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка изделий");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonSell_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxJewel.SelectedValue == null)
{
MessageBox.Show("Выберите изделий", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание продажи");
try
{
var operationResult = _logicShop.SellJewels(
new JewelBindingModel
{
Id = Convert.ToInt32(comboBoxJewel.SelectedValue)
},
Convert.ToInt32(textBoxCount.Text)
);
if (!operationResult)
{
throw new Exception("Ошибка при создании продажи. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания продажи");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

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

@ -54,6 +54,7 @@ namespace JewelryStoreView
services.AddTransient<FormAddJewel>(); services.AddTransient<FormAddJewel>();
services.AddTransient<FormShop>(); services.AddTransient<FormShop>();
services.AddTransient<FormShops>(); services.AddTransient<FormShops>();
} services.AddTransient<FormShopSell>();
}
} }
} }