This commit is contained in:
kagbie3nn@mail.ru 2024-06-17 23:07:23 +04:00
parent 2f34768114
commit 688621e4ef
26 changed files with 1306 additions and 182 deletions

View File

@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34714.143
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputersShopView", "ComputersShopView\ComputersShopView.csproj", "{67B93164-C2AC-4A4C-8D5E-3E7F6EA6A662}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputersShopView", "ComputersShopView\ComputersShopView.csproj", "{67B93164-C2AC-4A4C-8D5E-3E7F6EA6A662}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputersShopBusinessLogic", "ComputersShopBusinessLogic\ComputersShopBusinessLogic.csproj", "{14B3B9C9-08B7-4430-BDF6-090353500333}"
EndProject
@ -13,6 +13,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputersShopDataModels", "
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ComputersShopListImplement", "ComputersShopListImplement\ComputersShopListImplement.csproj", "{6FB73624-7C34-42DE-9846-B550AE0D32F2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ComputersShopFileImplement", "ComputersShopFileImplement\ComputersShopFileImplement.csproj", "{ED32280F-15D5-43E2-A76C-01DA7F5B0C5D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -39,6 +41,10 @@ Global
{6FB73624-7C34-42DE-9846-B550AE0D32F2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6FB73624-7C34-42DE-9846-B550AE0D32F2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6FB73624-7C34-42DE-9846-B550AE0D32F2}.Release|Any CPU.Build.0 = Release|Any CPU
{ED32280F-15D5-43E2-A76C-01DA7F5B0C5D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ED32280F-15D5-43E2-A76C-01DA7F5B0C5D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ED32280F-15D5-43E2-A76C-01DA7F5B0C5D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ED32280F-15D5-43E2-A76C-01DA7F5B0C5D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -18,10 +18,14 @@ namespace ComputersShopBusinessLogic.BusinessLogic
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
private readonly IShopLogic _shopLogic;
private readonly IComputerStorage _computerStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopLogic shopLogic, IComputerStorage computerStorage)
{
_logger = logger;
_orderStorage = orderStorage;
shopLogic = shopLogic;
_computerStorage = computerStorage;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
@ -63,6 +67,20 @@ namespace ComputersShopBusinessLogic.BusinessLogic
throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный");
}
model.Status = status;
if (model.Status == OrderStatus.Готов)
{
model.DateImplement = DateTime.Now;
var computer = _computerStorage.GetElement(new() { Id = viewModel.ComputerId });
if (computer == null)
{
throw new ArgumentNullException(nameof(computer));
}
if (!_shopLogic.AddComputers(computer, viewModel.Count))
{
throw new Exception($"AddComputers operation failed - нет места");
}
}
if (model.Status == OrderStatus.Выдан) model.DateImplement = DateTime.Now;
_orderStorage.Update(model);
return true;

View File

@ -3,12 +3,14 @@ using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ComputersShopBusinessLogic.BusinessLogic
{
@ -97,7 +99,8 @@ namespace ComputersShopBusinessLogic.BusinessLogic
}
if (model.Count <= 0)
{
throw new ArgumentException("Количество изделий должно быть больше 0");
return false;
throw new ArgumentException("Количество добавляемого компьютера должно быть больше 0", nameof(model.Count));
}
var shop = _shopStorage.GetElement(new ShopSearchModel
{
@ -107,11 +110,16 @@ namespace ComputersShopBusinessLogic.BusinessLogic
{
throw new ArgumentException("Магазина не существует");
}
if (model.Capacity - model.Computers.Select(x => x.Value.Item2).Sum() < model.Count)
{
throw new ArgumentNullException("В магазине не хватает места", nameof(model.Count));
}
if (shop.ShopComputers.ContainsKey(model.ComputerId))
{
var oldValue = shop.ShopComputers[model.ComputerId];
oldValue.Item2 += model.Count;
shop.ShopComputers[model.ComputerId] = oldValue;
Capacity = model.Capacity,
}
else
{
@ -156,5 +164,59 @@ namespace ComputersShopBusinessLogic.BusinessLogic
throw new InvalidOperationException("Магазин с таким названием уже есть");
}
}
public bool AddComputers(IComputerModel computer, int quantity)
{
if (computer == null)
{
throw new ArgumentNullException(nameof(computer));
}
if (quantity <= 0)
{
throw new ArgumentException("Количество компьютеров должно быть больше 0", nameof(quantity));
}
_logger.LogInformation("AddComputers. ShopName:{ShopName}. Id:{Id}", computer.ComputerName, computer.Id);
var allFreeQuantity = _shopStorage.GetFullList().Select(x => x.Capacity - x.Computers.Select(x => x.Value.Item2).Sum()).Sum();
if (allFreeQuantity < quantity)
{
_logger.LogWarning("AddComputers operation failed.");
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
int freeQuantity = shop.Capacity - shop.Computers.Select(x => x.Value.Item2).Sum();
if (freeQuantity <= 0)
{
continue;
}
if (freeQuantity < quantity)
{
if (!MakeSupply(new() { Id = shop.Id }, computer, freeQuantity))
{
_logger.LogWarning("AddComputers operation failed.");
return false;
}
quantity -= freeQuantity;
}
else
{
if (!MakeSupply(new() { Id = shop.Id }, computer, quantity))
{
_logger.LogWarning("AddComputers operation failed.");
return false;
}
quantity = 0;
}
if (quantity == 0)
{
return true;
}
}
_logger.LogWarning("AddComputers operation failed.");
return false;
}
public bool SellComputers(IComputerModel computer, int quantity)
{
return _shopStorage.SellComputers(computer, quantity);
}
}
}

View File

@ -14,5 +14,6 @@ namespace ComputersShopContracts.BindingModels
public string Adress { get; set; } = string.Empty;
public DateTime OpeningDate { get; set; } = DateTime.Now;
public Dictionary<int, (IComputerModel, int)> ShopComputers { get; set; } = new();
public int Capacity { get; set; }
}
}

View File

@ -6,6 +6,7 @@ using System.Threading.Tasks;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
namespace ComputersShopContracts.BusinessLogicsContracts
{
@ -17,5 +18,7 @@ namespace ComputersShopContracts.BusinessLogicsContracts
bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel model);
bool MakeSupply(SupplyBindingModel model);
bool AddComputers(IComputerModel computer, int quantity);
bool SellComputers(IComputerModel computer, int quantity);
}
}

View File

@ -1,6 +1,7 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
@ -17,5 +18,6 @@ namespace ComputersShopContracts.StoragesContracts
ShopViewModel? Insert(ShopBindingModel model);
ShopViewModel? Update(ShopBindingModel model);
ShopViewModel? Delete(ShopBindingModel model);
bool SellComputers(IComputerModel model, int quantity);
}
}

View File

@ -18,5 +18,7 @@ namespace ComputersShopContracts.ViewModels
[DisplayName("Дата открытия")]
public DateTime OpeningDate { get; set; }
public Dictionary<int, (IComputerModel, int)> ShopComputers { get; set; } = new();
[DisplayName("Вместимость магазина")]
public int Capacity { get; set; }
}
}

View File

@ -12,5 +12,6 @@ namespace ComputersShopDataModels.Models
string Adress { get; }
DateTime OpeningDate { get; }
Dictionary<int, (IComputerModel, int)> ShopComputers { get; }
public int Capacity { get; }
}
}

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\ComputersShopContracts\ComputersShopContracts.csproj" />
<ProjectReference Include="..\СomputersShopDataModels\СomputersShopDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,50 @@
namespace ComputersShopFileImplement
{
public class DataFileSingleton
{
private static DataFileSingleton? instance;
private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string ComputerFileName = "Computer.xml";
private readonly string ShopFileName = "Shop.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Computer> Computers { get; private set; }
public List<Shop> Shops { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
{
instance = new DataFileSingleton();
}
return instance;
}
public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement);
public void SaveComputers() => SaveData(Computers, ComputerFileName, "Computers", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Computers = LoadData(ComputerFileName, "Computer", x => Computer.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)
{
if (File.Exists(filename))
{
return
XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList();
}
return new List<T>();
}
private static void SaveData<T>(List<T> data, string filename, string xmlNodeName, Func<T, XElement> selectFunction)
{
if (data != null)
{
new XDocument(new XElement(xmlNodeName, data.Select(selectFunction).ToArray())).Save(filename);
}
}
}
}

View File

@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopFileImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
private readonly DataFileSingleton source;
public ComponentStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ComponentViewModel> GetFullList()
{
return source.Components.Select(x => x.GetViewModel).ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName))
{
return new();
}
return source.Components.Where(x => x.ComponentName.Contains(model.ComponentName)).Select(x => x.GetViewModel).ToList();
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
return source.Components.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == model.ComponentName) ||
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
model.Id = source.Components.Count > 0 ? source.Components.Max(x => x.Id) + 1 : 1;
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
source.Components.Add(newComponent);
source.SaveComponents();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
var component = source.Components.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
source.SaveComponents();
return component.GetViewModel;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
var element = source.Components.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Components.Remove(element);
source.SaveComponents();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopFileImplement.Implements
{
public class ComputerStorage : IComputerStorage
{
private readonly DataFileSingleton source;
public ComputerStorage()
{
source = DataFileSingleton.GetInstance();
}
public ComputerViewModel? GetElement(ComputerSearchModel model)
{
if (string.IsNullOrEmpty(model.ComputerName) && !model.Id.HasValue)
{
return null;
}
return source.Computers.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComputerName) && x.ComputerName == model.ComputerName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<ComputerViewModel> GetFilteredList(ComputerSearchModel model)
{
if (string.IsNullOrEmpty(model.ComputerName))
{
return new();
}
return source.Computers.Where(x => x.ComputerName.Contains(model.ComputerName)).Select(x => x.GetViewModel).ToList();
}
public List<ComputerViewModel> GetFullList()
{
return source.Computers.Select(x => x.GetViewModel).ToList();
}
public ComputerViewModel? Insert(ComputerBindingModel model)
{
model.Id = source.Computers.Count > 0 ? source.Computers.Max(x => x.Id) + 1 : 1;
var newDoc = Computer.Create(model);
if (newDoc == null)
{
return null;
}
source.Computers.Add(newDoc);
source.SaveComputers();
return newDoc.GetViewModel;
}
public ComputerViewModel? Update(ComputerBindingModel model)
{
var document = source.Computers.FirstOrDefault(x => x.Id == model.Id);
if (document == null)
{
return null;
}
document.Update(model);
source.SaveComputers();
return document.GetViewModel;
}
public ComputerViewModel? Delete(ComputerBindingModel model)
{
var document = source.Computers.FirstOrDefault(x => x.Id == model.Id);
if (document == null)
{
return null;
}
document.Update(model);
source.SaveComputers();
return document.GetViewModel;
}
}
}

View File

@ -0,0 +1,88 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopFileImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataFileSingleton source;
public OrderStorage()
{
source = DataFileSingleton.GetInstance();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return GetViewModel(source.Orders.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id));
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
return source.Orders.Where(x => x.Id == model.Id).Select(x => GetViewModel(x)).ToList();
}
public List<OrderViewModel> GetFullList()
{
return source.Orders.Select(x => GetViewModel(x)).ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1;
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
source.Orders.Add(newOrder);
source.SaveOrders();
return GetViewModel(newOrder);
}
public OrderViewModel? Update(OrderBindingModel model)
{
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
source.SaveOrders();
return GetViewModel(order);
}
public OrderViewModel? Delete(OrderBindingModel model)
{
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
source.SaveOrders();
return GetViewModel(order);
}
private OrderViewModel GetViewModel(Order order)
{
var viewModel = order.GetViewModel;
var comp = source.Computers.FirstOrDefault(comp => comp.Id == order.ComputerId);
if (comp != null)
{
viewModel.ComputerName = comp.ComputerName;
}
return viewModel;
}
}
}

View File

@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopFileImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataFileSingleton source;
public ShopStorage()
{
source = DataFileSingleton.GetInstance();
}
public ShopViewModel? Delete(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop != null)
{
source.Shops.Remove(shop);
source.SaveShops();
return shop.GetViewModel;
}
return null;
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
return source.Shops
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ShopName) && x.ShopName == model.ShopName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName))
{
return new();
}
return source.Shops
.Where(x => x.ShopName.Contains(model.ShopName))
.Select(x => x.GetViewModel)
.ToList();
}
public List<ShopViewModel> GetFullList()
{
return source.Shops.Select(x => x.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 bool SellComputers(IComputerModel model, int quantity)
{
int hasCount = source.Shops
.SelectMany(x => x.Computers)
.Where(pair => pair.Key == model.Id)
.Sum(pair => pair.Value.Item2);
if (hasCount < quantity)
return false;
source.Shops.ForEach(x =>
{
if (x.Computers.TryGetValue(model.Id, out var pair))
{
if (quantity >= pair.Item2)
{
quantity -= pair.Item2;
x.Computers[model.Id] = (model, 0);
}
else
{
x.Computers[model.Id] = (model, pair.Item2 - quantity);
quantity = 0;
}
x.Update(new ShopBindingModel
{
Id = x.Id,
ShopAddress = x.ShopAddress,
Capacity = x.Capacity,
DateOpening = x.DateOpening,
ShopName = x.ShopName,
Computers = x.Computers
});
}
});
source.SaveShops();
return true;
}
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;
}
}
}

View File

@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ComputersShopFileImplement.Models
{
public class Component : IComponentModel
{
public int Id { get; private set; }
public string ComponentName { get; private set; } = string.Empty;
public double Cost { get; set; }
public static Component? Create(ComponentBindingModel model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public static Component? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Component()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ComponentName = element.Element("ComponentName")!.Value,
Cost = Convert.ToDouble(element.Element("Cost")!.Value)
};
}
public void Update(ComponentBindingModel model)
{
if (model == null)
{
return;
}
ComponentName = model.ComponentName;
Cost = model.Cost;
}
public ComponentViewModel GetViewModel => new()
{
Id = Id,
ComponentName = ComponentName,
Cost = Cost
};
public XElement GetXElement => new("Component",
new XAttribute("Id", Id),
new XElement("ComponentName", ComponentName),
new XElement("Cost", Cost.ToString()));
}
}

View File

@ -0,0 +1,92 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ComputersShopFileImplement.Models
{
public class Computer : IComputerModel
{
public int Id { get; private set; }
public string ComputerName { get; private set; } = string.Empty;
public double Price { get; private set; }
public Dictionary<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _ComputerComponents = null;
public Dictionary<int, (IComponentModel, int)> ComputerComponents
{
get
{
if (_ComputerComponents == null)
{
var source = DataFileSingleton.GetInstance();
_ComputerComponents = Components.ToDictionary(x => x.Key, y =>
((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!,
y.Value));
}
return _ComputerComponents;
}
}
public static Computer? Create(ComputerBindingModel model)
{
if (model == null)
{
return null;
}
return new Computer()
{
Id = model.Id,
ComputerName = model.ComputerName,
Price = model.Price,
Components = model.ComputerComponents.ToDictionary(x => x.Key, x
=> x.Value.Item2)
};
}
public static Computer? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Computer()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ComputerName = element.Element("ComputerName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components =
element.Element("ComputerComponents")!.Elements("ComputerComponent")
.ToDictionary(x =>
Convert.ToInt32(x.Element("Key")?.Value), x =>
Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(ComputerBindingModel model)
{
if (model == null)
{
return;
}
ComputerName = model.ComputerName;
Price = model.Price;
Components = model.ComputerComponents.ToDictionary(x => x.Key, x =>
x.Value.Item2);
_ComputerComponents = null;
}
public ComputerViewModel GetViewModel => new()
{
Id = Id,
ComputerName = ComputerName,
Price = Price,
ComputerComponents = ComputerComponents
};
public XElement GetXElement => new("Computer",
new XAttribute("Id", Id),
new XElement("ComputerName", ComputerName),
new XElement("Price", Price.ToString()),
new XElement("ComputerComponents", Components.Select(x => new XElement("ComputerComponent", new XElement("Key", x.Key), new XElement("Value", x.Value)))
.ToArray()));
}
}

View File

@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ComputersShopFileImplement.Models
{
public class Order : IOrderModel
{
public int ComputerId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public int Id { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
ComputerId = model.ComputerId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement
};
}
public static Order? Create(XElement element)
{
if (element == null)
{
return null;
}
var order = new Order()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ComputerId = Convert.ToInt32(element.Element("ComputerId")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
DateCreate = DateTime.ParseExact(element.Element("DateCreate")!.Value, "G", null),
};
DateTime.TryParse(element.Element("DateImplement")!.Value, out DateTime dateImpl);
order.DateImplement = dateImpl;
if (!Enum.TryParse(element.Element("Status")!.Value, out OrderStatus status))
{
return null;
}
order.Status = status;
return order;
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
ComputerId = ComputerId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
};
public XElement GetXElement => new("Order",
new XAttribute("Id", Id),
new XElement("ComputerId", ComputerId),
new XElement("Count", Count.ToString()),
new XElement("Sum", Sum.ToString()),
new XElement("Status", Status.ToString()),
new XElement("DateCreate", DateCreate.ToString()),
new XElement("DateImplement", DateImplement.ToString()));
}
}

View File

@ -0,0 +1,105 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ComputersShopFileImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; } = string.Empty;
public string ShopAddress { get; private set; } = string.Empty;
public DateTime DateOpening { get; private set; }
public int Capacity { get; private set; }
public Dictionary<int, int> ComputersCount = new();
public Dictionary<int, (IComputerModel, int)>? _computers = null;
public Dictionary<int, (IComputerModel, int)> Computers
{
get
{
if (_computers == null)
{
var source = DataFileSingleton.GetInstance();
_computers = ComputersCount.ToDictionary(
x => x.Key,
y => ((source.Computers.FirstOrDefault(z => z.Id == y.Key) as IComputerModel)!,
y.Value)
);
}
return _computers;
}
}
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
ShopAddress = model.ShopAddress,
DateOpening = model.DateOpening,
Capacity = model.Capacity,
ComputersCount = model.Computers.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,
ShopAddress = element.Element("ShopAddress")!.Value,
DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value),
Capacity = Convert.ToInt32(element.Element("Capacity")!.Value),
ComputersCount = element.Element("Computers")!.Elements("Computer")
.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;
ShopAddress = model.ShopAddress;
DateOpening = model.DateOpening;
Capacity = model.Capacity;
ComputersCount = model.Computers.ToDictionary(x => x.Key, x => x.Value.Item2);
_computers = null;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
ShopAddress = ShopAddress,
DateOpening = DateOpening,
Capacity = Capacity,
Computers = Computers
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("ShopAddress", ShopAddress),
new XElement("DateOpening", DateOpening.ToString()),
new XElement("Capacity", Capacity.ToString()),
new XElement("Computers", ComputersCount.Select(x =>
new XElement("Computer",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray()));
}
}

View File

@ -2,6 +2,7 @@
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
@ -108,5 +109,9 @@ namespace ComputersShopListImplement.Implements
}
return null;
}
public bool SellComputers(IComputerModel model, int quantity)
{
throw new NotImplementedException();
}
}
}

View File

@ -51,5 +51,7 @@ namespace ComputersShopListImplement.Models
OpeningDate = OpeningDate,
ShopComputers = ShopComputers
};
public int Capacity => throw new NotImplementedException();
}
}

View File

@ -28,161 +28,177 @@
/// </summary>
private void InitializeComponent()
{
buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button();
buttonOrderReady = new Button();
buttonIssuedOrder = new Button();
buttonRef = new Button();
dataGridView = new DataGridView();
menuStrip = new MenuStrip();
ListToolStripMenuItem = new ToolStripMenuItem();
ComponentsToolStripMenuItem = new ToolStripMenuItem();
ComputersToolStripMenuItem = new ToolStripMenuItem();
ShopsToolStripMenuItem = new ToolStripMenuItem();
SupplyShopToolStripMenuItem = new ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(751, 34);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(158, 32);
buttonCreateOrder.TabIndex = 1;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click;
//
// buttonTakeOrderInWork
//
buttonTakeOrderInWork.Location = new Point(751, 72);
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
buttonTakeOrderInWork.Size = new Size(158, 32);
buttonTakeOrderInWork.TabIndex = 2;
buttonTakeOrderInWork.Text = "Отдать на выполнение";
buttonTakeOrderInWork.UseVisualStyleBackColor = true;
buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click;
//
// buttonOrderReady
//
buttonOrderReady.Location = new Point(751, 110);
buttonOrderReady.Name = "buttonOrderReady";
buttonOrderReady.Size = new Size(158, 32);
buttonOrderReady.TabIndex = 3;
buttonOrderReady.Text = "Заказ готов";
buttonOrderReady.UseVisualStyleBackColor = true;
buttonOrderReady.Click += ButtonOrderReady_Click;
//
// buttonIssuedOrder
//
buttonIssuedOrder.Location = new Point(751, 148);
buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(158, 32);
buttonIssuedOrder.TabIndex = 4;
buttonIssuedOrder.Text = "Заказ выдан";
buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
//
// buttonRef
//
buttonRef.Location = new Point(751, 186);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(158, 32);
buttonRef.TabIndex = 5;
buttonRef.Text = "Обновить список";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// dataGridView
//
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(-4, 24);
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(749, 285);
dataGridView.TabIndex = 6;
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.справочникToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.computerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.componentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.магазиныToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.пополнениеМагазинаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.продатьКомпьютеромToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonCreateOrder = new System.Windows.Forms.Button();
this.buttonTakeOrderInWork = new System.Windows.Forms.Button();
this.buttonOrderReady = new System.Windows.Forms.Button();
this.buttonIssuedOrder = new System.Windows.Forms.Button();
this.buttonRef = new System.Windows.Forms.Button();
this.menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { ListToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(921, 24);
menuStrip.TabIndex = 7;
menuStrip.Text = "menuStrip";
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.справочникToolStripMenuItem,
this.пополнениеМагазинаToolStripMenuItem,
this.продатьКомпьютеромToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(1047, 24);
this.menuStrip.TabIndex = 0;
this.menuStrip.Text = "menuStrip1";
//
// ListToolStripMenuItem
// справочникToolStripMenuItem
//
ListToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ComponentsToolStripMenuItem, ComputersToolStripMenuItem, ShopsToolStripMenuItem, SupplyShopToolStripMenuItem });
ListToolStripMenuItem.Name = "ListToolStripMenuItem";
ListToolStripMenuItem.Size = new Size(94, 20);
ListToolStripMenuItem.Text = "Справочники";
this.справочникToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.computerToolStripMenuItem,
this.componentsToolStripMenuItem,
this.магазиныToolStripMenuItem});
this.справочникToolStripMenuItem.Name = "справочникToolStripMenuItem";
this.справочникToolStripMenuItem.Size = new System.Drawing.Size(94, 20);
this.справочникToolStripMenuItem.Text = "Справочники";
//
// ComponentsToolStripMenuItem
// computerToolStripMenuItem
//
ComponentsToolStripMenuItem.Name = "ComponentsToolStripMenuItem1";
ComponentsToolStripMenuItem.Size = new Size(145, 22);
ComponentsToolStripMenuItem.Text = "Компоненты";
ComponentsToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click;
this.computerToolStripMenuItem.Name = "computerToolStripMenuItem";
this.computerToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.computerToolStripMenuItem.Text = "Компьютеры";
this.computerToolStripMenuItem.Click += ComputersToolStripMenuItem_Click;
//
// изделияToolStripMenuItem
// componentsToolStripMenuItem
//
ComputersToolStripMenuItem.Name = "изделияToolStripMenuItem";
ComputersToolStripMenuItem.Size = new Size(145, 22);
ComputersToolStripMenuItem.Text = "Изделия";
ComputersToolStripMenuItem.Click += ComputersToolStripMenuItem_Click;
this.componentsToolStripMenuItem.Name = "componentsToolStripMenuItem";
this.componentsToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.componentsToolStripMenuItem.Text = "Компоненты";
this.componentsToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click;
//
// ShopsToolStripMenuItem
// магазиныToolStripMenuItem
//
ShopsToolStripMenuItem.Name = "ShopsToolStripMenuItem";
ShopsToolStripMenuItem.Size = new Size(198, 22);
ShopsToolStripMenuItem.Text = "Магазины";
ShopsToolStripMenuItem.Click += shopsToolStripMenuItem_Click;
this.магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
this.магазиныToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.магазиныToolStripMenuItem.Text = "Магазины";
this.магазиныToolStripMenuItem.Click += ShopToolStripMenuItem_Click;
//
// SupplyShopToolStripMenuItem
// пополнениеМагазинаToolStripMenuItem
//
SupplyShopToolStripMenuItem.Name = "SupplyShopToolStripMenuItem";
SupplyShopToolStripMenuItem.Size = new Size(198, 22);
SupplyShopToolStripMenuItem.Text = "Пополнение магазина";
SupplyShopToolStripMenuItem.Click += transactionToolStripMenuItem_Click;
this.пополнениеМагазинаToolStripMenuItem.Name = "пополнениеМагазинаToolStripMenuItem";
this.пополнениеМагазинаToolStripMenuItem.Size = new System.Drawing.Size(143, 20);
this.пополнениеМагазинаToolStripMenuItem.Text = "Пополнение магазина";
this.пополнениеМагазинаToolStripMenuItem.Click += shopReplenishmentToolStripMenuItem_Click;
//
// продатьКомпьютеромToolStripMenuItem
//
this.продатьКомпьютеромToolStripMenuItem.Name = "продатьКомпьютеромToolStripMenuItem";
this.продатьКомпьютеромToolStripMenuItem.Size = new System.Drawing.Size(131, 20);
this.продатьКомпьютеромToolStripMenuItem.Text = "Продать компьютер";
this.продатьКомпьютеромToolStripMenuItem.Click += ButtonSellComputer_Click;
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(12, 27);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowTemplate.Height = 25;
this.dataGridView.Size = new System.Drawing.Size(817, 411);
this.dataGridView.TabIndex = 1;
//
// buttonCreateOrder
//
this.buttonCreateOrder.Location = new System.Drawing.Point(835, 50);
this.buttonCreateOrder.Name = "buttonCreateOrder";
this.buttonCreateOrder.Size = new System.Drawing.Size(200, 23);
this.buttonCreateOrder.TabIndex = 2;
this.buttonCreateOrder.Text = "Создать заказ";
this.buttonCreateOrder.UseVisualStyleBackColor = true;
this.buttonCreateOrder.Click += ButtonCreateOrder_Click;
//
// buttonTakeOrderInWork
//
this.buttonTakeOrderInWork.Location = new System.Drawing.Point(835, 101);
this.buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
this.buttonTakeOrderInWork.Size = new System.Drawing.Size(200, 23);
this.buttonTakeOrderInWork.TabIndex = 3;
this.buttonTakeOrderInWork.Text = "Отдать на выполнение";
this.buttonTakeOrderInWork.UseVisualStyleBackColor = true;
this.buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click;
//
// buttonOrderReady
//
this.buttonOrderReady.Location = new System.Drawing.Point(835, 156);
this.buttonOrderReady.Name = "buttonOrderReady";
this.buttonOrderReady.Size = new System.Drawing.Size(200, 23);
this.buttonOrderReady.TabIndex = 4;
this.buttonOrderReady.Text = "Заказ готов";
this.buttonOrderReady.UseVisualStyleBackColor = true;
this.buttonOrderReady.Click += ButtonOrderReady_Click;
//
// buttonIssuedOrder
//
this.buttonIssuedOrder.Location = new System.Drawing.Point(835, 212);
this.buttonIssuedOrder.Name = "buttonIssuedOrder";
this.buttonIssuedOrder.Size = new System.Drawing.Size(200, 23);
this.buttonIssuedOrder.TabIndex = 5;
this.buttonIssuedOrder.Text = "Заказ выдан";
this.buttonIssuedOrder.UseVisualStyleBackColor = true;
this.buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
//
// buttonRef
//
this.buttonRef.Location = new System.Drawing.Point(835, 269);
this.buttonRef.Name = "buttonRef";
this.buttonRef.Size = new System.Drawing.Size(200, 23);
this.buttonRef.TabIndex = 6;
this.buttonRef.Text = "Обновить список";
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += ButtonRef_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(921, 310);
Controls.Add(dataGridView);
Controls.Add(buttonRef);
Controls.Add(buttonIssuedOrder);
Controls.Add(buttonOrderReady);
Controls.Add(buttonTakeOrderInWork);
Controls.Add(buttonCreateOrder);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormMain";
Text = "Компьютерный магазин";
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1047, 450);
this.Controls.Add(this.buttonRef);
this.Controls.Add(this.buttonIssuedOrder);
this.Controls.Add(this.buttonOrderReady);
this.Controls.Add(this.buttonTakeOrderInWork);
this.Controls.Add(this.buttonCreateOrder);
this.Controls.Add(this.dataGridView);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMain";
this.Text = "Магазин электроники";
Load += FormMain_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private MenuStrip menuStrip;
private ToolStripMenuItem справочникToolStripMenuItem;
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonTakeOrderInWork;
private Button buttonOrderReady;
private Button buttonIssuedOrder;
private Button buttonRef;
private DataGridView dataGridView;
private MenuStrip menuStrip;
private ToolStripMenuItem ListToolStripMenuItem;
private ToolStripMenuItem ComponentsToolStripMenuItem;
private ToolStripMenuItem ComputersToolStripMenuItem;
private ToolStripMenuItem ShopsToolStripMenuItem;
private ToolStripMenuItem SupplyShopToolStripMenuItem;
private ToolStripMenuItem computerToolStripMenuItem;
private ToolStripMenuItem componentsToolStripMenuItem;
private ToolStripMenuItem магазиныToolStripMenuItem;
private ToolStripMenuItem пополнениеМагазинаToolStripMenuItem;
private ToolStripMenuItem продатьКомпьютеромToolStripMenuItem;
}
}

View File

@ -19,12 +19,14 @@ namespace ComputersShopView
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
@ -39,7 +41,6 @@ namespace ComputersShopView
{
dataGridView.DataSource = list;
dataGridView.Columns["ComputerId"].Visible = false;
dataGridView.Columns["ComputerName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка заказов");
}
@ -49,11 +50,9 @@ namespace ComputersShopView
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ComponentsToolStripMenuItem_Click(object sender, EventArgs
e)
private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormComponents));
var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
if (service is FormComponents form)
{
form.ShowDialog();
@ -67,40 +66,41 @@ namespace ComputersShopView
form.ShowDialog();
}
}
private void ShopToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShops));
if (service is FormShops form)
{
form.ShowDialog();
}
}
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
}
private OrderBindingModel CreateBindingModel(int id, bool isDone = false)
{
return new OrderBindingModel
{
Id = id,
ComputerId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ComputerId"].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 = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
};
}
private void ButtonTakeOrderInWork_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(CreateBindingModel(id));
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = id,
ComputerId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ComputerId"].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 = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString())
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
@ -110,8 +110,7 @@ namespace ComputersShopView
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@ -119,13 +118,19 @@ namespace ComputersShopView
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'",
id);
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);
try
{
var operationResult = _orderLogic.FinishOrder(CreateBindingModel(id));
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel
{
Id = id,
ComputerId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ComputerId"].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 = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString())
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
@ -135,8 +140,7 @@ namespace ComputersShopView
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@ -144,13 +148,19 @@ namespace ComputersShopView
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'",
id);
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(CreateBindingModel(id));
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel
{
Id = id,
ComputerId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ComputerId"].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 = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString())
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
@ -161,8 +171,7 @@ namespace ComputersShopView
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@ -170,21 +179,24 @@ namespace ComputersShopView
{
LoadData();
}
private void shopsToolStripMenuItem_Click(object sender, EventArgs e)
private void shopReplenishmentToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShops));
if (service is FormShops form)
var service = Program.ServiceProvider?.GetService(typeof(FormShopReplenishment));
if (service is FormShopReplenishment form)
{
form.ShowDialog();
}
}
private void transactionToolStripMenuItem_Click(object sender, EventArgs e)
private void ButtonSellComputer_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateSupply));
if (service is FormCreateSupply form)
var service = Program.ServiceProvider?.GetService(typeof(FormSellComputers));
if (service is FormSellComputers form)
{
form.ShowDialog();
LoadData();
}
}
}

View File

@ -0,0 +1,124 @@
namespace ComputersShopView
{
partial class FormSellComputers
{
/// <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();
comboBoxDocuments = new ComboBox();
numericUpDownCount = new NumericUpDown();
labelDocument = new Label();
labelCount = new Label();
ButtonSave = new Button();
((System.ComponentModel.ISupportInitialize)numericUpDownCount).BeginInit();
SuspendLayout();
//
// ButtonCancel
//
ButtonCancel.Location = new Point(233, 60);
ButtonCancel.Margin = new Padding(3, 2, 3, 2);
ButtonCancel.Name = "ButtonCancel";
ButtonCancel.Size = new Size(82, 22);
ButtonCancel.TabIndex = 1;
ButtonCancel.Text = "Отмена";
ButtonCancel.UseVisualStyleBackColor = true;
ButtonCancel.Click += ButtonCancel_Click;
//
// comboBoxDocuments
//
comboBoxDocuments.FormattingEnabled = true;
comboBoxDocuments.Location = new Point(89, 6);
comboBoxDocuments.Margin = new Padding(3, 2, 3, 2);
comboBoxDocuments.Name = "comboBoxDocuments";
comboBoxDocuments.Size = new Size(226, 23);
comboBoxDocuments.TabIndex = 2;
//
// numericUpDownCount
//
numericUpDownCount.Location = new Point(90, 33);
numericUpDownCount.Margin = new Padding(3, 2, 3, 2);
numericUpDownCount.Name = "numericUpDownCount";
numericUpDownCount.Size = new Size(225, 23);
numericUpDownCount.TabIndex = 3;
//
// labelDocument
//
labelDocument.AutoSize = true;
labelDocument.Location = new Point(12, 9);
labelDocument.Name = "labelDocument";
labelDocument.Size = new Size(71, 15);
labelDocument.TabIndex = 4;
labelDocument.Text = "Компьютер";
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(11, 35);
labelCount.Name = "labelCount";
labelCount.Size = new Size(72, 15);
labelCount.TabIndex = 5;
labelCount.Text = "Количество";
//
// ButtonSave
//
ButtonSave.Location = new Point(145, 60);
ButtonSave.Margin = new Padding(3, 2, 3, 2);
ButtonSave.Name = "ButtonSave";
ButtonSave.Size = new Size(82, 22);
ButtonSave.TabIndex = 6;
ButtonSave.Text = "Сохранить";
ButtonSave.UseVisualStyleBackColor = true;
ButtonSave.Click += ButtonSave_Click;
//
// FormSellComputers
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(326, 93);
Controls.Add(ButtonSave);
Controls.Add(labelCount);
Controls.Add(labelDocument);
Controls.Add(numericUpDownCount);
Controls.Add(comboBoxDocuments);
Controls.Add(ButtonCancel);
Margin = new Padding(3, 2, 3, 2);
Name = "FormSellComputers";
Text = "Продажа компьютеров";
((System.ComponentModel.ISupportInitialize)numericUpDownCount).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button ButtonCancel;
private ComboBox comboBoxDocuments;
private NumericUpDown numericUpDownCount;
private Label labelDocument;
private Label labelCount;
private Button ButtonSave;
}
}

View File

@ -0,0 +1,86 @@
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ComputersShopView
{
public partial class FormSellComputers : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _shopLogic;
private readonly IComputerLogic _computerLogic;
private readonly List<ComputerViewModel>? _listComputer;
public FormSellComputers(ILogger<FormSellComputers> logger, IShopLogic shopLogic, IComputerLogic computerLogic)
{
InitializeComponent();
_logger = logger;
_shopLogic = shopLogic;
_computerLogic = computerLogic;
_listComputer = computerLogic.ReadList(null);
if (_listComputer != null)
{
comboBoxDocuments.DisplayMember = "ComputerName";
comboBoxDocuments.ValueMember = "Id";
comboBoxDocuments.DataSource = _listComputer;
comboBoxDocuments.SelectedItem = null;
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (comboBoxDocuments.SelectedValue == null)
{
MessageBox.Show("Выберите компьютер", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(numericUpDownCount.Text))
{
MessageBox.Show("Заполните количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Продажа поездок");
try
{
var comp = _computerLogic.ReadElement(new()
{
Id = (int)comboBoxDocuments.SelectedValue
});
if (comp == null)
{
throw new Exception("Компьютер не найден. Дополнительная информация в логах.");
}
var operationResult = _shopLogic.SellComputers(
computer: comp,
quantity: (int)numericUpDownCount.Value
);
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

@ -47,7 +47,8 @@ namespace ComputersShopView
textBoxName.Text = view.ShopName;
textBoxAdress.Text = view.Adress;
dateTimeOpen.Value = view.OpeningDate;
_ShopComputers = view.ShopComputers ?? new Dictionary<int, (IComputerModel, int)>();
numericUpDownCapacity.Value = view.Capacity;
_ShopComputers = view.ShopComputers ?? new Dictionary<int, (IComputerModel, int)>();
LoadData();
}
}
@ -101,6 +102,7 @@ namespace ComputersShopView
ShopName = textBoxName.Text,
Adress = textBoxAdress.Text,
OpeningDate = dateTimeOpen.Value
Capacity = (int)numericUpDownCapacity.Value,
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)

View File

@ -2,11 +2,10 @@ using ComputersShopBusinessLogic;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.StoragesContracts;
using Microsoft.Extensions.DependencyInjection;
using ComputersShopListImplement.Implements;
using ComputersShopFileImplement.Implements;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using ComputersShopDataModels;
using ComputersShopListImplement;
using ComputersShopView;
using ComputersShopBusinessLogic.BusinessLogic;
@ -57,6 +56,7 @@ namespace ComputersShop
services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormCreateSupply>();
services.AddTransient<FormSellComputers>();
}
}
}