This commit is contained in:
song2remaster 2024-05-05 21:43:24 +04:00
parent f245c6a3bc
commit 335a1b41f7
39 changed files with 2626 additions and 1054 deletions

View File

@ -11,7 +11,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantListImplement", "
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantBusinessLogic", "..\MotorPlantBusinessLogic\MotorPlantBusinessLogic.csproj", "{BE9E33C8-F7AD-4952-80B8-68FAE35E0BDC}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantBusinessLogic", "..\MotorPlantBusinessLogic\MotorPlantBusinessLogic.csproj", "{BE9E33C8-F7AD-4952-80B8-68FAE35E0BDC}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MotorPlantView", "..\MotorPlantView\MotorPlantView.csproj", "{76FE3E67-6BFC-4C12-AD2F-2267F8986605}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MotorPlantView", "..\MotorPlantView\MotorPlantView.csproj", "{76FE3E67-6BFC-4C12-AD2F-2267F8986605}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MotorPlantFileImplement", "MotorPlantFileImplement\MotorPlantFileImplement.csproj", "{3216A68E-02C0-4B3E-A608-6CD4D4B12CB4}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -39,6 +41,10 @@ Global
{76FE3E67-6BFC-4C12-AD2F-2267F8986605}.Debug|Any CPU.Build.0 = Debug|Any CPU {76FE3E67-6BFC-4C12-AD2F-2267F8986605}.Debug|Any CPU.Build.0 = Debug|Any CPU
{76FE3E67-6BFC-4C12-AD2F-2267F8986605}.Release|Any CPU.ActiveCfg = Release|Any CPU {76FE3E67-6BFC-4C12-AD2F-2267F8986605}.Release|Any CPU.ActiveCfg = Release|Any CPU
{76FE3E67-6BFC-4C12-AD2F-2267F8986605}.Release|Any CPU.Build.0 = Release|Any CPU {76FE3E67-6BFC-4C12-AD2F-2267F8986605}.Release|Any CPU.Build.0 = Release|Any CPU
{3216A68E-02C0-4B3E-A608-6CD4D4B12CB4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3216A68E-02C0-4B3E-A608-6CD4D4B12CB4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3216A68E-02C0-4B3E-A608-6CD4D4B12CB4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3216A68E-02C0-4B3E-A608-6CD4D4B12CB4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@ -0,0 +1,59 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Models;
using System.Xml.Linq;
namespace MotorPlantFileImplement.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,72 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantFileImplement.Models;
namespace MotorPlantFileImplement.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,53 @@
using MotorPlantFileImplement.Models;
using System.Xml.Linq;
namespace MotorPlantFileImplement
{
public class DataFileSingleton
{
private static DataFileSingleton? instance;
private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string EngineFileName = "Engine.xml";
private readonly string ShopFileName = "Shop.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Engine> Engines { 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 SaveEngines() => SaveData(Engines, EngineFileName, "Engines", 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)!)!;
Engines = LoadData(EngineFileName, "Engine", x => Engine.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,89 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Models;
using System.Xml.Linq;
namespace MotorPlantFileImplement.Models
{
public class Engine : IEngineModel
{
public int Id { get; private set; }
public string EngineName { 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)>? _EngineComponents = null;
public Dictionary<int, (IComponentModel, int)> EngineComponents
{
get
{
if (_EngineComponents == null)
{
var source = DataFileSingleton.GetInstance();
_EngineComponents = Components.ToDictionary(x => x.Key, y =>
((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!,
y.Value));
}
return _EngineComponents;
}
}
public static Engine? Create(EngineBindingModel model)
{
if (model == null)
{
return null;
}
return new Engine()
{
Id = model.Id,
EngineName = model.EngineName,
Price = model.Price,
Components = model.EngineComponents.ToDictionary(x => x.Key, x
=> x.Value.Item2)
};
}
public static Engine? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Engine()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
EngineName = element.Element("EngineName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components =
element.Element("EngineComponents")!.Elements("EngineComponent")
.ToDictionary(x =>
Convert.ToInt32(x.Element("Key")?.Value), x =>
Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(EngineBindingModel model)
{
if (model == null)
{
return;
}
EngineName = model.EngineName;
Price = model.Price;
Components = model.EngineComponents.ToDictionary(x => x.Key, x =>
x.Value.Item2);
_EngineComponents = null;
}
public EngineViewModel GetViewModel => new()
{
Id = Id,
EngineName = EngineName,
Price = Price,
EngineComponents = EngineComponents
};
public XElement GetXElement => new("Engine",
new XAttribute("Id", Id),
new XElement("EngineName", EngineName),
new XElement("Price", Price.ToString()),
new XElement("EngineComponents", Components.Select(x => new XElement("EngineComponent", new XElement("Key", x.Key), new XElement("Value", x.Value)))
.ToArray()));
}
}

View File

@ -0,0 +1,71 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantFileImplement.Models;
namespace MotorPlantFileImplement.Implements
{
public class EngineStorage : IEngineStorage
{
private readonly DataFileSingleton source;
public EngineStorage()
{
source = DataFileSingleton.GetInstance();
}
public EngineViewModel? GetElement(EngineSearchModel model)
{
if (string.IsNullOrEmpty(model.EngineName) && !model.Id.HasValue)
{
return null;
}
return source.Engines.FirstOrDefault(x => (!string.IsNullOrEmpty(model.EngineName) && x.EngineName == model.EngineName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<EngineViewModel> GetFilteredList(EngineSearchModel model)
{
if (string.IsNullOrEmpty(model.EngineName))
{
return new();
}
return source.Engines.Where(x => x.EngineName.Contains(model.EngineName)).Select(x => x.GetViewModel).ToList();
}
public List<EngineViewModel> GetFullList()
{
return source.Engines.Select(x => x.GetViewModel).ToList();
}
public EngineViewModel? Insert(EngineBindingModel model)
{
model.Id = source.Engines.Count > 0 ? source.Engines.Max(x => x.Id) + 1 : 1;
var newDoc = Engine.Create(model);
if (newDoc == null)
{
return null;
}
source.Engines.Add(newDoc);
source.SaveEngines();
return newDoc.GetViewModel;
}
public EngineViewModel? Update(EngineBindingModel model)
{
var document = source.Engines.FirstOrDefault(x => x.Id == model.Id);
if (document == null)
{
return null;
}
document.Update(model);
source.SaveEngines();
return document.GetViewModel;
}
public EngineViewModel? Delete(EngineBindingModel model)
{
var document = source.Engines.FirstOrDefault(x => x.Id == model.Id);
if (document == null)
{
return null;
}
document.Update(model);
source.SaveEngines();
return document.GetViewModel;
}
}
}

View File

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,88 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Enums;
using MotorPlantDataModels.Models;
using System.Xml.Linq;
namespace MotorPlantFileImplement.Models
{
public class Order : IOrderModel
{
public int EngineId { 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,
EngineId = model.EngineId,
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),
EngineId = Convert.ToInt32(element.Element("EngineId")!.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,
EngineId = EngineId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
};
public XElement GetXElement => new("Order",
new XAttribute("Id", Id),
new XElement("EngineId", EngineId),
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,79 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantFileImplement.Models;
namespace MotorPlantFileImplement.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 engine = source.Engines.FirstOrDefault(x => x.Id == order.EngineId);
viewModel.EngineName = engine?.EngineName;
return viewModel;
}
}
}

View File

@ -0,0 +1,103 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace MotorPlantFileImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; } = string.Empty;
public string Adress { get; private set; } = string.Empty;
public DateTime OpeningDate { get; private set; }
public Dictionary<int, int> Engines { get; private set; } = new();
private Dictionary<int, (IEngineModel, int)>? _shopEngines = null;
public Dictionary<int, (IEngineModel, int)> ShopEngines
{
get
{
if (_shopEngines == null)
{
var source = DataFileSingleton.GetInstance();
_shopEngines = Engines.ToDictionary(x => x.Key, y => ((source.Engines.FirstOrDefault(z => z.Id == y.Key) as IEngineModel)!, y.Value));
}
return _shopEngines;
}
}
public int EngineMaxCount { get; private set; }
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Adress = model.Adress,
OpeningDate = model.OpeningDate,
Engines = model.ShopEngines.ToDictionary(x => x.Key, x => x.Value.Item2),
EngineMaxCount = model.EngineMaxCount
};
}
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShopName = element.Element("ShopName")!.Value,
Adress = element.Element("Adress")!.Value,
OpeningDate = Convert.ToDateTime(element.Element("OpeningDate")!.Value),
Engines = element.Element("ShopEngines")!.Elements("ShopEngine")!.ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value),
x => Convert.ToInt32(x.Element("Value")?.Value)),
EngineMaxCount = Convert.ToInt32(element.Element("EngineMaxCount")!.Value)
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Adress = model.Adress;
OpeningDate = model.OpeningDate;
EngineMaxCount = model.EngineMaxCount;
Engines = model.ShopEngines.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopEngines = null;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Adress = Adress,
OpeningDate = OpeningDate,
ShopEngines = ShopEngines,
EngineMaxCount = EngineMaxCount
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("Adress", Adress),
new XElement("OpeningDate", OpeningDate.ToString()),
new XElement("ShopEngines", Engines.Select(
x => new XElement("ShopEngine", new XElement("Key", x.Key), new XElement("Value", x.Value))).ToArray()),
new XElement("EngineMaxCount", EngineMaxCount.ToString())
);
public void EnginesUpdate()
{
_shopEngines = null;
}
}
}

View File

@ -0,0 +1,145 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantFileImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataFileSingleton source;
public ShopStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ShopViewModel> GetFullList()
{
return source.Shops.Select(x => x.GetViewModel).ToList();
}
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 ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
return source.Shops.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ShopName) && x.ShopName == model.ShopName) ||
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = source.Shops.Count > 0 ? source.Shops.Max(x => x.Id) + 1 : 1;
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
source.Shops.Add(newShop);
source.SaveShops();
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
source.SaveShops();
return shop.GetViewModel;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
var shop = source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop != null)
{
source.Shops.Remove(shop);
source.SaveShops();
return shop.GetViewModel;
}
return null;
}
public bool Sale(SupplySearchModel model)
{
if (model == null || !model.EngineId.HasValue || !model.Count.HasValue)
return false;
int remainingSpace = source.Shops.Select(x => x.Engines.ContainsKey(model.EngineId.Value) ? x.Engines[model.EngineId.Value] : 0).Sum();
if (remainingSpace < model.Count)
{
return false;
}
var shops = source.Shops.Where(x => x.Engines.ContainsKey(model.EngineId.Value)).OrderByDescending(x => x.Engines[model.EngineId.Value]).ToList();
foreach (var shop in shops)
{
int residue = model.Count.Value - shop.Engines[model.EngineId.Value];
if (residue > 0)
{
shop.Engines.Remove(model.EngineId.Value);
shop.EnginesUpdate();
model.Count = residue;
}
else
{
if (residue == 0)
{
shop.Engines.Remove(model.EngineId.Value);
}
else
{
shop.Engines[model.EngineId.Value] = -residue;
}
shop.EnginesUpdate();
source.SaveShops();
return true;
}
}
source.SaveShops();
return false;
}
public bool RestockingShops(SupplyBindingModel model)
{
if (model == null || source.Shops.Select(x => x.EngineMaxCount - x.ShopEngines.Select(y => y.Value.Item2).Sum()).Sum() < model.Count)
{
return false;
}
foreach (Shop shop in source.Shops)
{
int free_places = shop.EngineMaxCount - shop.ShopEngines.Select(x => x.Value.Item2).Sum();
if (free_places <= 0)
continue;
free_places = Math.Min(free_places, model.Count);
model.Count -= free_places;
if (shop.Engines.ContainsKey(model.EngineId))
{
shop.Engines[model.EngineId] += free_places;
}
else
{
shop.Engines.Add(model.EngineId, free_places);
}
shop.EnginesUpdate();
if (model.Count == 0)
{
source.SaveShops();
return true;
}
}
return false;
}
}
}

View File

@ -1,29 +1,28 @@
using MotorPlantListImplement.Models; using MotorPlantListImplement.Models;
namespace MotorPlantListImplement namespace MotorPlantListImplement
{ {
public class DataListSingleton public class DataListSingleton
{ {
private static DataListSingleton? _instance; private static DataListSingleton? _instance;
public List<Component> Components { get; set; } public List<Component> Components { get; set; }
public List<Order> Orders { get; set; } public List<Order> Orders { get; set; }
public List<Engine> Engines { get; set; } public List<Engine> Engines { get; set; }
public List<Shop> Shops { get; set; } public List<Shop> Shops { get; set; }
private DataListSingleton() private DataListSingleton()
{ {
Components = new List<Component>(); Components = new List<Component>();
Orders = new List<Order>(); Orders = new List<Order>();
Engines = new List<Engine>(); Engines = new List<Engine>();
Shops = new List<Shop>(); Shops = new List<Shop>();
} }
public static DataListSingleton GetInstance() public static DataListSingleton GetInstance()
{ {
if (_instance == null) if (_instance == null)
{ {
_instance = new DataListSingleton(); _instance = new DataListSingleton();
} }
return _instance; return _instance;
} }
} }
} }

View File

@ -1,103 +1,112 @@
using MotorPlantContracts.StoragesContracts; using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels; using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantListImplement.Models; using MotorPlantListImplement.Models;
using MotorPlantContracts.VeiwModels;
namespace MotorPlantListImplement.Implements namespace MotorPlantListImplement.Implements
{ {
public class OrderStorage : IOrderStorage public class OrderStorage : IOrderStorage
{ {
private readonly DataListSingleton _source; private readonly DataListSingleton _source;
public OrderStorage() public OrderStorage()
{ {
_source = DataListSingleton.GetInstance(); _source = DataListSingleton.GetInstance();
} }
public OrderViewModel? Delete(OrderBindingModel model) public List<OrderViewModel> GetFullList()
{ {
for (int i = 0; i < _source.Orders.Count; ++i) var result = new List<OrderViewModel>();
{ foreach (var order in _source.Orders)
if (_source.Orders[i].Id == model.Id) {
{ result.Add(AttachEngineName(order.GetViewModel));
var element = _source.Orders[i]; }
_source.Orders.RemoveAt(i); return result;
return element.GetViewModel; }
} public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
} {
return null; var result = new List<OrderViewModel>();
} if (model == null || !model.Id.HasValue)
public OrderViewModel? GetElement(OrderSearchModel model) {
{ return result;
if (!model.Id.HasValue) }
{ foreach (var order in _source.Orders)
return null; {
} if (order.Id == model.Id)
foreach (var order in _source.Orders) {
{ result.Add(AttachEngineName(order.GetViewModel));
if (model.Id.HasValue && order.Id == model.Id) }
{ }
return order.GetViewModel; return result;
} }
} public OrderViewModel? GetElement(OrderSearchModel model)
return null; {
} if (!model.Id.HasValue)
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) {
{ return null;
var result = new List<OrderViewModel>(); }
foreach (var order in _source.Orders)
if (!model.Id.HasValue) {
{ if (model.Id.HasValue && order.Id == model.Id)
return result; {
} return AttachEngineName(order.GetViewModel);
foreach (var order in _source.Orders) }
{ }
if (model.Id.HasValue && order.Id == model.Id) return null;
{ }
result.Add(order.GetViewModel); public OrderViewModel? Insert(OrderBindingModel model)
} {
} model.Id = 1;
return result; foreach (var order in _source.Orders)
} {
public List<OrderViewModel> GetFullList() if (model.Id <= order.Id)
{ {
var result = new List<OrderViewModel>(); model.Id = order.Id + 1;
}
foreach (var order in _source.Orders) }
{ var newOrder = Order.Create(model);
result.Add(order.GetViewModel); if (newOrder == null)
} {
return result; return null;
} }
public OrderViewModel? Insert(OrderBindingModel model) _source.Orders.Add(newOrder);
{ return AttachEngineName(newOrder.GetViewModel);
model.Id = 1; }
public OrderViewModel? Update(OrderBindingModel model)
foreach (var order in _source.Orders) {
{ foreach (var order in _source.Orders)
if (model.Id <= order.Id) {
{ if (order.Id == model.Id)
model.Id = order.Id + 1; {
} order.Update(model);
} return AttachEngineName(order.GetViewModel);
var newOrder = Order.Create(model); }
if (newOrder == null) }
{ return null;
return null; }
} public OrderViewModel? Delete(OrderBindingModel model)
{
_source.Orders.Add(newOrder); for (int i = 0; i < _source.Orders.Count; ++i)
return newOrder.GetViewModel; {
} if (_source.Orders[i].Id == model.Id)
public OrderViewModel? Update(OrderBindingModel model) {
{ var element = _source.Orders[i];
foreach (var order in _source.Orders) _source.Orders.RemoveAt(i);
{ return AttachEngineName(element.GetViewModel);
if (order.Id == model.Id) }
{ }
order.Update(model); return null;
return order.GetViewModel; }
} private OrderViewModel AttachEngineName(OrderViewModel model)
} {
return null; foreach (var Engine in _source.Engines)
} {
} if (Engine.Id == model.EngineId)
{
model.EngineName = Engine.EngineName;
return model;
}
}
return model;
}
}
} }

View File

@ -11,97 +11,104 @@ using System.Threading.Tasks;
namespace MotorPlantListImplement.Implements namespace MotorPlantListImplement.Implements
{ {
public class ShopStorage : IShopStorage public class ShopStorage : IShopStorage
{ {
private readonly DataListSingleton _source; private readonly DataListSingleton _source;
public ShopStorage() public ShopStorage()
{ {
_source = DataListSingleton.GetInstance(); _source = DataListSingleton.GetInstance();
} }
public List<ShopViewModel> GetFullList() public List<ShopViewModel> GetFullList()
{ {
var result = new List<ShopViewModel>(); var result = new List<ShopViewModel>();
foreach (var shop in _source.Shops) foreach (var shop in _source.Shops)
{ {
result.Add(shop.GetViewModel); result.Add(shop.GetViewModel);
} }
return result; return result;
} }
public List<ShopViewModel> GetFilteredList(ShopSearchModel model) public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{ {
var result = new List<ShopViewModel>(); var result = new List<ShopViewModel>();
if (string.IsNullOrEmpty(model.Name)) if (string.IsNullOrEmpty(model.ShopName))
{ {
return result; return result;
} }
foreach (var shop in _source.Shops) foreach (var shop in _source.Shops)
{ {
if (shop.ShopName.Contains(model.Name)) if (shop.ShopName.Contains(model.ShopName))
{ {
result.Add(shop.GetViewModel); result.Add(shop.GetViewModel);
} }
} }
return result; return result;
} }
public ShopViewModel? GetElement(ShopSearchModel model) public ShopViewModel? GetElement(ShopSearchModel model)
{ {
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{ {
return null; return null;
} }
foreach (var shop in _source.Shops) foreach (var shop in _source.Shops)
{ {
if ((!string.IsNullOrEmpty(model.Name) && if ((!string.IsNullOrEmpty(model.ShopName) && shop.ShopName == model.ShopName) ||
shop.ShopName == model.Name) || (model.Id.HasValue && shop.Id == model.Id))
(model.Id.HasValue && shop.Id == model.Id)) {
{ return shop.GetViewModel;
return shop.GetViewModel; }
} }
} return null;
return null; }
} public ShopViewModel? Insert(ShopBindingModel model)
public ShopViewModel? Insert(ShopBindingModel model) {
{ model.Id = 1;
model.Id = 1; foreach (var shop in _source.Shops)
foreach (var shop in _source.Shops) {
{ if (model.Id <= shop.Id)
if (model.Id <= shop.Id) {
{ model.Id = shop.Id + 1;
model.Id = shop.Id + 1; }
} }
} var newShop = Shop.Create(model);
var newShop = Shop.Create(model); if (newShop == null)
if (newShop == null) {
{ return null;
return null; }
} _source.Shops.Add(newShop);
_source.Shops.Add(newShop); return newShop.GetViewModel;
return newShop.GetViewModel; }
} public ShopViewModel? Update(ShopBindingModel model)
public ShopViewModel? Update(ShopBindingModel model) {
{ foreach (var shop in _source.Shops)
foreach (var shop in _source.Shops) {
{ if (shop.Id == model.Id)
if (shop.Id == model.Id) {
{ shop.Update(model);
shop.Update(model); return shop.GetViewModel;
return shop.GetViewModel; }
} }
} return null;
return null; }
} public ShopViewModel? Delete(ShopBindingModel model)
public ShopViewModel? Delete(ShopBindingModel model) {
{ for (int i = 0; i < _source.Shops.Count; ++i)
for (int i = 0; i < _source.Shops.Count; ++i) {
{ if (_source.Shops[i].Id == model.Id)
if (_source.Shops[i].Id == model.Id) {
{ var element = _source.Shops[i];
var element = _source.Shops[i]; _source.Shops.RemoveAt(i);
_source.Shops.RemoveAt(i); return element.GetViewModel;
return element.GetViewModel; }
} }
} return null;
return null; }
} public bool Sale(SupplySearchModel model)
} {
throw new NotImplementedException();
}
public bool RestockingShops(SupplyBindingModel model)
{
throw new NotImplementedException();
}
}
} }

View File

@ -1,62 +1,54 @@
using MotorPlantContracts.BindingModels; using MotorPlantContracts.BindingModels;
using MotorPlantDataModels.Models; using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Enums; using MotorPlantDataModels.Enums;
using MotorPlantContracts.VeiwModels; using MotorPlantDataModels.Models;
namespace MotorPlantListImplement.Models namespace MotorPlantListImplement.Models
{ {
public class Order : IOrderModel public class Order : IOrderModel
{ {
public int EngineId { get; private set; } public int Id { get; private set; }
public string EngineName { get; private set; } public int EngineId { get; private set; }
public int Count { get; private set; } public int Count { get; private set; }
public double Sum { get; private set; } public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; private set; }
public DateTime DateCreate { get; private set; } = DateTime.Now; public DateTime DateCreate { get; private set; }
public DateTime? DateImplement { get; private set; } public DateTime? DateImplement { get; private set; }
public int Id { get; private set; } public static Order? Create(OrderBindingModel? model)
public static Order? Create(OrderBindingModel? model) {
{ if (model == null)
if (model == null) {
{ return null;
return null; }
} return new Order()
return new Order() {
{ Id = model.Id,
Id = model.Id, EngineId = model.EngineId,
EngineId = model.EngineId, Count = model.Count,
EngineName = model.EngineName, Sum = model.Sum,
Count = model.Count, Status = model.Status,
Sum = model.Sum, DateCreate = model.DateCreate,
Status = model.Status, DateImplement = model.DateImplement,
DateCreate = model.DateCreate, };
DateImplement = model.DateImplement }
}; public void Update(OrderBindingModel? model)
} {
public void Update(OrderBindingModel? model) if (model == null)
{ {
if (model == null) return;
{ }
return; Status = model.Status;
} DateImplement = model.DateImplement;
EngineId = model.EngineId; }
EngineName = model.EngineName; public OrderViewModel GetViewModel => new()
Count = model.Count; {
Sum = model.Sum; Id = Id,
Status = model.Status; EngineId = EngineId,
DateCreate = model.DateCreate; Count = Count,
DateImplement = model.DateImplement; Sum = Sum,
} Status = Status,
public OrderViewModel GetViewModel => new() DateCreate = DateCreate,
{ DateImplement = DateImplement,
Id = Id, };
EngineId = EngineId, }
EngineName = EngineName,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
};
}
} }

View File

@ -9,46 +9,49 @@ using System.Threading.Tasks;
namespace MotorPlantListImplement.Models namespace MotorPlantListImplement.Models
{ {
public class Shop : IShopModel public class Shop : IShopModel
{ {
public int Id { get; private set; } public int Id { get; private set; }
public string ShopName { get; private set; } public string ShopName { get; private set; } = string.Empty;
public string Adress { get; private set; } public string Adress { get; private set; } = string.Empty;
public DateTime DateOpen { get; private set; } public DateTime OpeningDate { get; private set; }
public Dictionary<int, (IEngineModel, int)> ShopEngines { get; private set; } = new(); public Dictionary<int, (IEngineModel, int)> ShopEngines { get; private set; } = new();
public static Shop? Create(ShopBindingModel model) public int EngineMaxCount { get; private set; }
{
if (model == null) public static Shop? Create(ShopBindingModel? model)
{ {
return null; if (model == null)
} {
return new Shop() return null;
{ }
Id = model.Id, return new Shop()
ShopName = model.ShopName, {
Adress = model.Adress, Id = model.Id,
DateOpen = model.DateOpen, ShopName = model.ShopName,
ShopEngines = new() Adress = model.Adress,
}; OpeningDate = model.OpeningDate,
} EngineMaxCount = model.EngineMaxCount,
public void Update(ShopBindingModel? model) };
{ }
if (model == null) public void Update(ShopBindingModel? model)
{ {
return; if (model == null)
} {
ShopName = model.ShopName; return;
Adress = model.Adress; }
DateOpen = model.DateOpen; ShopName = model.ShopName;
ShopEngines = model.ShopEngines; Adress = model.Adress;
} OpeningDate = model.OpeningDate;
public ShopViewModel GetViewModel => new() EngineMaxCount = model.EngineMaxCount;
{ }
Id = Id, public ShopViewModel GetViewModel => new()
ShopName = ShopName, {
Adress = Adress, Id = Id,
DateOpen = DateOpen, ShopName = ShopName,
ShopEngines = ShopEngines Adress = Adress,
}; OpeningDate = OpeningDate,
} ShopEngines = ShopEngines,
EngineMaxCount = EngineMaxCount,
};
}
} }

View File

@ -1,115 +1,138 @@
using Microsoft.Extensions.Logging; using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.SearchModels; using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts; using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.VeiwModels; using MotorPlantContracts.ViewModels;
using Microsoft.Extensions.Logging;
using MotorPlantDataModels.Enums; using MotorPlantDataModels.Enums;
namespace MotorPlantBusinessLogic.BusinessLogics namespace MotorPlantBusinessLogic.BusinessLogics
{ {
public class OrderLogic : IOrderLogic public class OrderLogic : IOrderLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage; private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage) private readonly IShopStorage _shopStorage;
{ public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopStorage shopStorage)
_logger = logger; {
_orderStorage = orderStorage; _logger = logger;
} _orderStorage = orderStorage;
public List<OrderViewModel>? ReadList(OrderSearchModel? model) _shopStorage = shopStorage;
{ }
_logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); public List<OrderViewModel>? ReadList(OrderSearchModel? model)
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); {
if (list == null) _logger.LogInformation("ReadList. OrderId:{Id}", model?.Id);
{ var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
_logger.LogWarning("ReadList return null list"); if (list == null)
return null; {
} _logger.LogWarning("ReadList return null list");
_logger.LogInformation("ReadList. Count:{Count}", list.Count); return null;
return list; }
} _logger.LogInformation("ReadList. Count:{Count}", list.Count);
public bool CreateOrder(OrderBindingModel model) return list;
{ }
CheckModel(model); public bool CreateOrder(OrderBindingModel model)
if (model.Status != OrderStatus.Неизвестен) {
return false; CheckModel(model);
model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null) if (model.Status != OrderStatus.Неизвестен)
{ return false;
_logger.LogWarning("Insert operation failed"); model.Status = OrderStatus.Принят;
return false;
} if (_orderStorage.Insert(model) == null)
return true; {
} model.Status = OrderStatus.Неизвестен;
public bool TakeOrderInWork(OrderBindingModel model) _logger.LogWarning("Insert operation failed");
{ return false;
return ChangeStatus(model, OrderStatus.Выполняется); }
} return true;
public bool FinishOrder(OrderBindingModel model) }
{ public bool TakeOrderInWork(OrderBindingModel model)
return ChangeStatus(model, OrderStatus.Готов); {
} return ToNextStatus(model, OrderStatus.Выполняется);
public bool DeliveryOrder(OrderBindingModel model) }
{ public bool FinishOrder(OrderBindingModel model)
return ChangeStatus(model, OrderStatus.Выдан); {
} return ToNextStatus(model, OrderStatus.Готов);
private void CheckModel(OrderBindingModel model, bool withParams = true) }
{ public bool DeliveryOrder(OrderBindingModel model)
if (model == null) {
{ var order = _orderStorage.GetElement(new OrderSearchModel
throw new ArgumentNullException(nameof(model)); {
} Id = model.Id,
if (!withParams) });
{ if (order == null)
return; {
} throw new ArgumentNullException(nameof(order));
if (model.Count <= 0) }
{ if (!_shopStorage.RestockingShops(new SupplyBindingModel
throw new ArgumentException("Колличество моторов в заказе не может быть меньше 1", nameof(model.Count)); {
} EngineId = order.EngineId,
if (model.Sum <= 0) Count = order.Count
{ }))
throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum)); {
} throw new ArgumentException("Недостаточно места");
if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate) }
{ return ToNextStatus(model, OrderStatus.Выдан);
throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}"); }
} public bool ToNextStatus(OrderBindingModel model, OrderStatus orderStatus)
_logger.LogInformation("Engine. EngineId:{EngineId}.Count:{Count}.Sum:{Sum}Id:{Id}", {
model.EngineId, model.Count, model.Sum, model.Id); CheckModel(model, false);
} var element = _orderStorage.GetElement(new OrderSearchModel()
private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus) {
{ Id = model.Id
CheckModel(model, false); });
var element = _orderStorage.GetElement(new OrderSearchModel() if (element == null)
{ {
Id = model.Id throw new ArgumentNullException(nameof(element));
}); }
if (element == null) model.EngineId = element.EngineId;
{ model.DateCreate = element.DateCreate;
throw new ArgumentNullException(nameof(element)); model.DateImplement = element.DateImplement;
} model.Status = element.Status;
model.DateCreate = element.DateCreate; model.Count = element.Count;
model.EngineId = element.EngineId; model.Sum = element.Sum;
model.DateImplement = element.DateImplement; if (model.Status != orderStatus - 1)
model.Status = element.Status; {
model.Count = element.Count; _logger.LogWarning("Status update to " + orderStatus + " operation failed");
model.Sum = element.Sum; return false;
if (requiredStatus - model.Status == 1) }
{ model.Status = orderStatus;
model.Status = requiredStatus; if (model.Status == OrderStatus.Выдан)
if (model.Status == OrderStatus.Выдан) {
model.DateImplement = DateTime.Now; model.DateImplement = DateTime.Now;
if (_orderStorage.Update(model) == null) }
{ if (_orderStorage.Update(model) == null)
_logger.LogWarning("Update operation failed"); {
return false; model.Status--;
} _logger.LogWarning("Changing status operation faled");
return true; return false;
} }
_logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); return true;
throw new ArgumentException($"Невозможно присвоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); }
} private void CheckModel(OrderBindingModel model, bool withParams = true)
} {
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (model.Count <= 0)
{
throw new ArgumentNullException("Количество изделий должно быть больше 0", nameof(model.Count));
}
if (model.Sum <= 0)
{
throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum));
}
if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate)
{
throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} должна быть позже даты его создания {model.DateCreate}");
}
_logger.LogInformation("Engine. EngineId:{EngineId}.Count:{Count}.Sum:{Sum}Id:{Id}", model.EngineId, model.Count, model.Sum, model.Id);
}
}
} }

View File

@ -11,146 +11,177 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace MotorPlantBusinessLogic.BusinessLogic namespace MotorPlantBusinessLogic.BusinessLogics
{ {
public class ShopLogic : IShopLogic public class ShopLogic : IShopLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IShopStorage _shopStorage; private readonly IShopStorage _shopStorage;
public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage) private readonly IEngineStorage _EngineStorage;
{ public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage, IEngineStorage EngineStorage)
_logger = logger; {
_shopStorage = shopStorage; _logger = logger;
} _shopStorage = shopStorage;
public List<ShopViewModel> ReadList(ShopSearchModel model) _EngineStorage = EngineStorage;
{ }
_logger.LogInformation("ReadList. ShopName:{Name}. Id:{ Id}", model?.Name, model?.Id); public List<ShopViewModel>? ReadList(ShopSearchModel? model)
var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model); {
if (list == null) _logger.LogInformation("ReadList. ShopName:{ShopName}.Id:{ Id}", model?.ShopName, model?.Id);
{ var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model);
_logger.LogWarning("ReadList return null list"); if (list == null)
return null; {
} _logger.LogWarning("ReadList return null list");
_logger.LogInformation("ReadList. Count:{Count}", list.Count); return null;
return list; }
} _logger.LogInformation("ReadList. Count:{Count}", list.Count);
public ShopViewModel ReadElement(ShopSearchModel model) return list;
{ }
if (model == null) public ShopViewModel? ReadElement(ShopSearchModel model)
{ {
throw new ArgumentNullException(nameof(model)); if (model == null)
} {
_logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.Name, model.Id); throw new ArgumentNullException(nameof(model));
var element = _shopStorage.GetElement(model); }
if (element == null) _logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.ShopName, model.Id);
{ var element = _shopStorage.GetElement(model);
_logger.LogWarning("ReadElement element not found"); if (element == null)
return null; {
} _logger.LogWarning("ReadElement element not found");
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id); return null;
return element; }
} _logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool Create(ShopBindingModel model)
{
CheckModel(model);
if (_shopStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ShopBindingModel model)
{
CheckModel(model);
if (_shopStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ShopBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_shopStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public bool MakeSupply(SupplyBindingModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (model.Count <= 0)
{
throw new ArgumentException("Количество изделий должно быть больше 0");
}
var shop = _shopStorage.GetElement(new ShopSearchModel
{
Id = model.ShopId
});
if (shop == null)
{
throw new ArgumentException("Магазина не существует");
}
if (shop.ShopEngines.ContainsKey(model.EngineId))
{
var oldValue = shop.ShopEngines[model.EngineId];
oldValue.Item2 += model.Count;
shop.ShopEngines[model.EngineId] = oldValue;
}
else
{
var Engine = _EngineStorage.GetElement(new EngineSearchModel
{
Id = model.EngineId
});
if (Engine == null)
{
throw new ArgumentException($"Поставка: Товар с id:{model.EngineId} не найденн");
}
if (shop.ShopEngines.Sum(kv => kv.Value.Item2) + model.Count > shop.EngineMaxCount)
{
throw new ArgumentException("Превышена максимальная вместимость магазина");
}
shop.ShopEngines.Add(model.EngineId, (Engine, model.Count));
}
_shopStorage.Update(new ShopBindingModel()
{
Id = shop.Id,
ShopName = shop.ShopName,
Adress = shop.Adress,
OpeningDate = shop.OpeningDate,
ShopEngines = shop.ShopEngines,
EngineMaxCount = shop.EngineMaxCount,
});
public bool Create(ShopBindingModel model) return true;
{ }
CheckModel(model); private void CheckModel(ShopBindingModel model, bool withParams = true)
if (_shopStorage.Insert(model) == null) {
{ if (model == null)
_logger.LogWarning("Insert operation failed"); {
return false; throw new ArgumentNullException(nameof(model));
} }
return true; if (!withParams)
} {
return;
}
if (string.IsNullOrEmpty(model.Adress))
{
throw new ArgumentException("Адрес магазина длжен быть заполнен", nameof(model.Adress));
}
if (string.IsNullOrEmpty(model.ShopName))
{
throw new ArgumentException("Название магазина должно быть заполнено", nameof(model.ShopName));
}
_logger.LogInformation("Shop. ShopName:{ShopName}.Adres:{Adres}.OpeningDate:{OpeningDate}.Id:{ Id}", model.ShopName, model.Adress, model.OpeningDate, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel
{
ShopName = model.ShopName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Магазин с таким названием уже есть");
}
}
public bool Sale(SupplySearchModel model)
{
if (!model.EngineId.HasValue || !model.Count.HasValue)
{
return false;
}
_logger.LogInformation("Check Engine count in all shops");
if (_shopStorage.Sale(model))
{
_logger.LogInformation("Selling sucsess");
return true;
}
_logger.LogInformation("Selling failed");
return false;
}
public bool Update(ShopBindingModel model) public bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count)
{ {
CheckModel(model); throw new NotImplementedException();
if (_shopStorage.Update(model) == null) }
{ }
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ShopBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_shopStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ShopBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.ShopName))
{
throw new ArgumentNullException("Нет названия магазина",
nameof(model.ShopName));
}
if (string.IsNullOrEmpty(model.Adress))
{
throw new ArgumentNullException("Нет адресса магазина",
nameof(model.ShopName));
}
if (model.DateOpen == null)
{
throw new ArgumentNullException("Нет даты открытия магазина",
nameof(model.ShopName));
}
_logger.LogInformation("Shop. ShopName:{ShopName}.Address:{Address}. DateOpen:{DateOpen}. Id: { Id}", model.ShopName, model.Adress, model.DateOpen, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel
{
Name = model.ShopName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Магазин с таким названием уже есть");
}
}
public bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count)
{
if (model == null)
throw new ArgumentNullException(nameof(model));
if (engine == null)
throw new ArgumentNullException(nameof(engine));
if (count <= 0)
throw new ArgumentNullException("Количество должно быть положительным числом");
ShopViewModel? curModel = _shopStorage.GetElement(model);
_logger.LogInformation("Make Supply. Id: {Id}. ShopName: {Name}", model.Id, model.Name);
if (curModel == null)
throw new ArgumentNullException(nameof(curModel));
if (curModel.ShopEngines.TryGetValue(engine.Id, out var pair))
{
curModel.ShopEngines[engine.Id] = (pair.Item1, pair.Item2 + count);
_logger.LogInformation("Make Supply. Add Engine. EngineName: {Name}. Count: {Count}", pair.Item1, count + pair.Item2);
}
else
{
curModel.ShopEngines.Add(engine.Id, (engine, count));
_logger.LogInformation("Make Supply. Add new Engine. EngineName: {Name}. Count: {Count}", pair.Item1, count);
}
return Update(new()
{
Id = curModel.Id,
ShopName = curModel.ShopName,
DateOpen = curModel.DateOpen,
Adress = curModel.Adress,
ShopEngines = curModel.ShopEngines,
});
}
}
} }

View File

@ -7,12 +7,13 @@ using System.Threading.Tasks;
namespace MotorPlantContracts.BindingModels namespace MotorPlantContracts.BindingModels
{ {
public class ShopBindingModel : IShopModel public class ShopBindingModel : IShopModel
{ {
public int Id { get; set; } public int Id { get; set; }
public string ShopName { get; set; } public string ShopName { get; set; } = string.Empty;
public string Adress { get; set; } public string Adress { get; set; } = string.Empty;
public DateTime DateOpen { get; set; } public DateTime OpeningDate { get; set; } = DateTime.Now;
public Dictionary<int, (IEngineModel, int)> ShopEngines { get; set; } = new(); public Dictionary<int, (IEngineModel, int)> ShopEngines { get; set; } = new();
} public int EngineMaxCount { get; set; }
}
} }

View File

@ -0,0 +1,16 @@
using MotorPlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantContracts.BindingModels
{
public class SupplyBindingModel : ISupplyModel
{
public int ShopId { get; set; }
public int EngineId { get; set; }
public int Count { get; set; }
}
}

View File

@ -1,16 +1,15 @@
using MotorPlantContracts.BindingModels; using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels; using MotorPlantContracts.SearchModels;
using MotorPlantContracts.VeiwModels; using MotorPlantContracts.ViewModels;
namespace MotorPlantContracts.BusinessLogicsContracts namespace MotorPlantContracts.BusinessLogicsContracts
{ {
public interface IOrderLogic public interface IOrderLogic
{ {
List<OrderViewModel>? ReadList(OrderSearchModel? model); List<OrderViewModel>? ReadList(OrderSearchModel? model);
bool CreateOrder(OrderBindingModel model); bool CreateOrder(OrderBindingModel model);
bool TakeOrderInWork(OrderBindingModel model); bool TakeOrderInWork(OrderBindingModel model);
bool FinishOrder(OrderBindingModel model); bool FinishOrder(OrderBindingModel model);
bool DeliveryOrder(OrderBindingModel model); bool DeliveryOrder(OrderBindingModel model);
}
}
} }

View File

@ -10,13 +10,15 @@ using System.Threading.Tasks;
namespace MotorPlantContracts.BusinessLogicsContracts namespace MotorPlantContracts.BusinessLogicsContracts
{ {
public interface IShopLogic public interface IShopLogic
{ {
List<ShopViewModel>? ReadList(ShopSearchModel? model); List<ShopViewModel>? ReadList(ShopSearchModel? model);
ShopViewModel? ReadElement(ShopSearchModel? model); ShopViewModel? ReadElement(ShopSearchModel model);
bool Create(ShopBindingModel? model); bool Create(ShopBindingModel model);
bool Update(ShopBindingModel? model); bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel? model); bool Delete(ShopBindingModel model);
bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count); bool Sale(SupplySearchModel model);
} bool MakeSupply(ShopSearchModel model, IEngineModel engine, int count);
}
} }

View File

@ -1,14 +1,9 @@
using System; 
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantContracts.SearchModels namespace MotorPlantContracts.SearchModels
{ {
public class ShopSearchModel public class ShopSearchModel
{ {
public int? Id { get; set; } public int? Id { get; set; }
public string? Name { get; set; } public string? ShopName { get; set; }
} }
} }

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantContracts.SearchModels
{
public class SupplySearchModel
{
public int? EngineId { get; set; }
public int? Count { get; set; }
}
}

View File

@ -1,17 +1,16 @@
using MotorPlantContracts.BindingModels; using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels; using MotorPlantContracts.SearchModels;
using MotorPlantContracts.VeiwModels; using MotorPlantContracts.ViewModels;
namespace MotorPlantContracts.StoragesContracts namespace MotorPlantContracts.StoragesContracts
{ {
public interface IOrderStorage public interface IOrderStorage
{ {
List<OrderViewModel> GetFullList(); List<OrderViewModel> GetFullList();
List<OrderViewModel> GetFilteredList(OrderSearchModel model); List<OrderViewModel> GetFilteredList(OrderSearchModel model);
OrderViewModel? GetElement(OrderSearchModel model); OrderViewModel? GetElement(OrderSearchModel model);
OrderViewModel? Insert(OrderBindingModel model); OrderViewModel? Insert(OrderBindingModel model);
OrderViewModel? Update(OrderBindingModel model); OrderViewModel? Update(OrderBindingModel model);
OrderViewModel? Delete(OrderBindingModel model); OrderViewModel? Delete(OrderBindingModel model);
} }
} }

View File

@ -17,5 +17,7 @@ namespace MotorPlantContracts.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 Sale(SupplySearchModel model);
bool RestockingShops(SupplyBindingModel model);
}
} }

View File

@ -1,33 +1,26 @@
using MotorPlantDataModels.Enums; using MotorPlantDataModels.Enums;
using MotorPlantDataModels.Models; using MotorPlantDataModels.Models;
using System.ComponentModel; using System.ComponentModel;
namespace MotorPlantContracts.VeiwModels
namespace MotorPlantContracts.ViewModels
{ {
public class OrderViewModel : IOrderModel public class OrderViewModel : IOrderModel
{ {
[DisplayName("Номер")] [DisplayName("Номер")]
public int Id { get; set; } public int Id { get; set; }
public int EngineId { get; set; }
public int EngineId { get; set; } [DisplayName("Изделие")]
public string EngineName { get; set; } = string.Empty;
[DisplayName("Изделие")] [DisplayName("Количество")]
public string EngineName { get; set; } = string.Empty; public int Count { get; set; }
[DisplayName("Сумма")]
[DisplayName("Количество")] public double Sum { get; set; }
public int Count { get; set; } [DisplayName("Статус")]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Сумма")] [DisplayName("Дата создания")]
public double Sum { get; set; } public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")]
[DisplayName("Статус")] public DateTime? DateImplement { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; }
[DisplayName("Дата создания")]
public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")]
public DateTime? DateImplement { get; set; }
}
}
}

View File

@ -8,22 +8,17 @@ using System.Threading.Tasks;
namespace MotorPlantContracts.ViewModels namespace MotorPlantContracts.ViewModels
{ {
public class ShopViewModel : IShopModel public class ShopViewModel : IShopModel
{ {
public int Id { get; set; } public int Id { get; set; }
[DisplayName("Название")]
[DisplayName("Название магазина")] public string ShopName { get; set; } = string.Empty;
[DisplayName("Адрес")]
public string ShopName { get; set; } = string.Empty; public string Adress { get; set; } = string.Empty;
[DisplayName("Дата открытия")]
[DisplayName("Адрес")] public DateTime OpeningDate { get; set; }
public Dictionary<int, (IEngineModel, int)> ShopEngines { get; set; } = new();
public string Adress { get; set; } = string.Empty; [DisplayName("Вместимость")]
public int EngineMaxCount { get; set; }
[DisplayName("Дата открытия")] }
public DateTime DateOpen { get; set; }
public Dictionary<int, (IEngineModel, int)> ShopEngines { get; set; } = new();
}
} }

View File

@ -1,4 +1,6 @@
using System; using MotorPlantDataModels;
using MotorPlantDataModels.Models;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -6,10 +8,12 @@ using System.Threading.Tasks;
namespace MotorPlantDataModels.Models namespace MotorPlantDataModels.Models
{ {
public interface IShopModel : IId public interface IShopModel : IId
{ {
string ShopName { get; } string ShopName { get; }
string Adress { get; } string Adress { get; }
DateTime DateOpen { get; } DateTime OpeningDate { get; }
} Dictionary<int, (IEngineModel, int)> ShopEngines { get; }
public int EngineMaxCount { get; }
}
} }

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorPlantDataModels.Models
{
public interface ISupplyModel
{
int ShopId { get; }
int EngineId { get; }
int Count { get; }
}
}

View File

@ -0,0 +1,143 @@
namespace MotorPlantView.Forms
{
partial class FormCreateSupply
{
/// <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()
{
this.comboBoxShop = new System.Windows.Forms.ComboBox();
this.labelShop = new System.Windows.Forms.Label();
this.labelEngine = new System.Windows.Forms.Label();
this.comboBoxEngine = new System.Windows.Forms.ComboBox();
this.labelCount = new System.Windows.Forms.Label();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// comboBoxShop
//
this.comboBoxShop.FormattingEnabled = true;
this.comboBoxShop.Location = new System.Drawing.Point(115, 12);
this.comboBoxShop.Name = "comboBoxShop";
this.comboBoxShop.Size = new System.Drawing.Size(344, 28);
this.comboBoxShop.TabIndex = 0;
//
// labelShop
//
this.labelShop.AutoSize = true;
this.labelShop.Location = new System.Drawing.Point(12, 15);
this.labelShop.Name = "labelShop";
this.labelShop.Size = new System.Drawing.Size(76, 20);
this.labelShop.TabIndex = 1;
this.labelShop.Text = "Магазин: ";
//
// labelEngine
//
this.labelEngine.AutoSize = true;
this.labelEngine.Location = new System.Drawing.Point(12, 49);
this.labelEngine.Name = "labelEngine";
this.labelEngine.Size = new System.Drawing.Size(75, 20);
this.labelEngine.TabIndex = 2;
this.labelEngine.Text = "Изделие: ";
//
// comboBoxEngine
//
this.comboBoxEngine.FormattingEnabled = true;
this.comboBoxEngine.Location = new System.Drawing.Point(115, 46);
this.comboBoxEngine.Name = "comboBoxEngine";
this.comboBoxEngine.Size = new System.Drawing.Size(344, 28);
this.comboBoxEngine.TabIndex = 3;
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(12, 83);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(97, 20);
this.labelCount.TabIndex = 4;
this.labelCount.Text = "Количество: ";
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(115, 80);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(344, 27);
this.textBoxCount.TabIndex = 5;
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(300, 113);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(116, 39);
this.buttonCancel.TabIndex = 6;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(168, 113);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(116, 39);
this.buttonSave.TabIndex = 7;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// FormCreateSupply
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(471, 164);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.comboBoxEngine);
this.Controls.Add(this.labelEngine);
this.Controls.Add(this.labelShop);
this.Controls.Add(this.comboBoxShop);
this.Name = "FormCreateSupply";
this.Text = "Создание поставки";
this.Load += new System.EventHandler(this.FormCreateSupply_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private ComboBox comboBoxShop;
private Label labelShop;
private Label labelEngine;
private ComboBox comboBoxEngine;
private Label labelCount;
private TextBox textBoxCount;
private Button buttonCancel;
private Button buttonSave;
}
}

View File

@ -0,0 +1,93 @@
using Microsoft.Extensions.Logging;
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.ViewModels;
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 MotorPlantView.Forms
{
public partial class FormCreateSupply : Form
{
private readonly ILogger _logger;
private readonly IEngineLogic _logicP;
private readonly IShopLogic _logicS;
private List<ShopViewModel> _shopList = new List<ShopViewModel>();
private List<EngineViewModel> _EngineList = new List<EngineViewModel>();
public FormCreateSupply(ILogger<FormCreateSupply> logger, IEngineLogic logicP, IShopLogic logicS)
{
InitializeComponent();
_logger = logger;
_logicP = logicP;
_logicS = logicS;
}
private void FormCreateSupply_Load(object sender, EventArgs e)
{
_shopList = _logicS.ReadList(null);
_EngineList = _logicP.ReadList(null);
if (_shopList != null)
{
comboBoxShop.DisplayMember = "ShopName";
comboBoxShop.ValueMember = "Id";
comboBoxShop.DataSource = _shopList;
comboBoxShop.SelectedItem = null;
_logger.LogInformation("Загрузка магазинов для поставок");
}
if (_EngineList != null)
{
comboBoxEngine.DisplayMember = "EngineName";
comboBoxEngine.ValueMember = "Id";
comboBoxEngine.DataSource = _EngineList;
comboBoxEngine.SelectedItem = null;
_logger.LogInformation("Загрузка двигателей для поставок");
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (comboBoxShop.SelectedValue == null)
{
MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxEngine.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание поставки");
try
{
var operationResult = _logicS.MakeSupply(new SupplyBindingModel
{
ShopId = Convert.ToInt32(comboBoxShop.SelectedValue),
EngineId = Convert.ToInt32(comboBoxEngine.SelectedValue),
Count = 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

@ -1,206 +1,213 @@
namespace MotorPlantView.Forms namespace MotorPlantView.Forms
{ {
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()
{ {
toolStrip1 = new ToolStrip(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMain));
toolStripDropDownButton1 = new ToolStripDropDownButton(); toolStrip1 = new ToolStrip();
КомпонентыToolStripMenuItem = new ToolStripMenuItem(); toolStripDropDownButton1 = new ToolStripDropDownButton();
ДвигателиToolStripMenuItem = new ToolStripMenuItem(); КомпонентыToolStripMenuItem = new ToolStripMenuItem();
ShopsToolStripMenuItem = new ToolStripMenuItem(); ДвигателиToolStripMenuItem = new ToolStripMenuItem();
поставкиToolStripMenuItem = new ToolStripMenuItem(); buttonCreateOrder = new Button();
buttonCreateOrder = new Button(); buttonTakeOrderInWork = new Button();
buttonTakeOrderInWork = new Button(); buttonOrderReady = new Button();
buttonOrderReady = new Button(); buttonIssuedOrder = new Button();
buttonIssuedOrder = new Button(); buttonRef = new Button();
buttonRef = new Button(); dataGridView = new DataGridView();
dataGridView = new DataGridView(); operationToolStripMenuItem = new ToolStripMenuItem();
toolStrip1.SuspendLayout(); transactionToolStripMenuItem = new ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); продажаToolStripMenuItem = new ToolStripMenuItem();
SuspendLayout(); магазиныToolStripMenuItem = new ToolStripMenuItem();
// toolStrip1.SuspendLayout();
// toolStrip1 ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
// SuspendLayout();
toolStrip1.ImageScalingSize = new Size(20, 20); //
toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1 }); // toolStrip1
toolStrip1.Location = new Point(0, 0); //
toolStrip1.Name = "toolStrip1"; toolStrip1.ImageScalingSize = new Size(20, 20);
toolStrip1.Size = new Size(985, 25); toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, operationToolStripMenuItem });
toolStrip1.TabIndex = 0; toolStrip1.Location = new Point(0, 0);
toolStrip1.Text = "toolStrip1"; toolStrip1.Name = "toolStrip1";
// toolStrip1.Size = new Size(969, 25);
// toolStripDropDownButton1 toolStrip1.TabIndex = 0;
// toolStrip1.Text = "toolStrip1";
toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; //
toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, ShopsToolStripMenuItem, поставкиToolStripMenuItem }); // toolStripDropDownButton1
toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; //
toolStripDropDownButton1.Name = "toolStripDropDownButton1"; toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text;
toolStripDropDownButton1.Size = new Size(90, 22); toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, магазиныToolStripMenuItem });
toolStripDropDownButton1.Text = "Справочник"; toolStripDropDownButton1.Image = (Image)resources.GetObject("toolStripDropDownButton1.Image");
// toolStripDropDownButton1.ImageTransparentColor = Color.Magenta;
// КомпонентыToolStripMenuItem toolStripDropDownButton1.Name = "toolStripDropDownButton1";
// toolStripDropDownButton1.Size = new Size(88, 22);
КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem"; toolStripDropDownButton1.Text = "Справочник";
КомпонентыToolStripMenuItem.Size = new Size(148, 22); //
КомпонентыToolStripMenuItem.Text = "Компоненты"; // КомпонентыToolStripMenuItem
КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; //
// КомпонентыToolStripMenuItem.Name = омпонентыToolStripMenuItem";
// ДвигателиToolStripMenuItem КомпонентыToolStripMenuItem.Size = new Size(180, 22);
// КомпонентыToolStripMenuItem.Text = "Компоненты";
ДвигателиToolStripMenuItem.Name = "ДвигателиToolStripMenuItem"; КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click;
ДвигателиToolStripMenuItem.Size = new Size(148, 22); //
ДвигателиToolStripMenuItem.Text = "Двигатели"; // ДвигателиToolStripMenuItem
ДвигателиToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; //
// ДвигателиToolStripMenuItem.Name = "ДвигателиToolStripMenuItem";
// ShopsToolStripMenuItem ДвигателиToolStripMenuItem.Size = new Size(180, 22);
// ДвигателиToolStripMenuItem.Text = "Двигатели";
ShopsToolStripMenuItem.Name = "ShopsToolStripMenuItem"; ДвигателиToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click;
ShopsToolStripMenuItem.Size = new Size(148, 22); //
ShopsToolStripMenuItem.Text = "Магазины"; // buttonCreateOrder
ShopsToolStripMenuItem.Click += ShopsToolStripMenuItem_Click; //
// buttonCreateOrder.Location = new Point(800, 56);
// поставкиToolStripMenuItem buttonCreateOrder.Name = "buttonCreateOrder";
// buttonCreateOrder.Size = new Size(141, 24);
поставкиToolStripMenuItem.Name = "поставкиToolStripMenuItem"; buttonCreateOrder.TabIndex = 1;
поставкиToolStripMenuItem.Size = new Size(148, 22); buttonCreateOrder.Text = "Создать заказ";
поставкиToolStripMenuItem.Text = "Поставки"; buttonCreateOrder.UseVisualStyleBackColor = true;
поставкиToolStripMenuItem.Click += SupplyToolStripMenuItem_Click; buttonCreateOrder.Click += buttonCreateOrder_Click;
// //
// buttonCreateOrder // buttonTakeOrderInWork
// //
buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonTakeOrderInWork.Location = new Point(800, 100);
buttonCreateOrder.BackColor = SystemColors.ControlLight; buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
buttonCreateOrder.Location = new Point(860, 114); buttonTakeOrderInWork.Size = new Size(141, 24);
buttonCreateOrder.Name = "buttonCreateOrder"; buttonTakeOrderInWork.TabIndex = 2;
buttonCreateOrder.Size = new Size(87, 48); buttonTakeOrderInWork.Text = "Отдать на выполнение";
buttonCreateOrder.TabIndex = 1; buttonTakeOrderInWork.UseVisualStyleBackColor = true;
buttonCreateOrder.Text = "Создать заказ"; buttonTakeOrderInWork.Click += buttonTakeOrderInWork_Click;
buttonCreateOrder.UseVisualStyleBackColor = false; //
buttonCreateOrder.Click += buttonCreateOrder_Click; // buttonOrderReady
// //
// buttonTakeOrderInWork buttonOrderReady.Location = new Point(800, 142);
// buttonOrderReady.Name = "buttonOrderReady";
buttonTakeOrderInWork.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonOrderReady.Size = new Size(141, 24);
buttonTakeOrderInWork.BackColor = SystemColors.ControlLight; buttonOrderReady.TabIndex = 3;
buttonTakeOrderInWork.Location = new Point(860, 178); buttonOrderReady.Text = "Заказ готов";
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; buttonOrderReady.UseVisualStyleBackColor = true;
buttonTakeOrderInWork.Size = new Size(87, 48); buttonOrderReady.Click += buttonOrderReady_Click;
buttonTakeOrderInWork.TabIndex = 2; //
buttonTakeOrderInWork.Text = "Отдать на выполнение"; // buttonIssuedOrder
buttonTakeOrderInWork.UseVisualStyleBackColor = false; //
buttonTakeOrderInWork.Click += buttonTakeOrderInWork_Click; buttonIssuedOrder.Location = new Point(800, 181);
// buttonIssuedOrder.Name = "buttonIssuedOrder";
// buttonOrderReady buttonIssuedOrder.Size = new Size(141, 24);
// buttonIssuedOrder.TabIndex = 4;
buttonOrderReady.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonIssuedOrder.Text = "Заказ выдан";
buttonOrderReady.BackColor = SystemColors.ControlLight; buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonOrderReady.Location = new Point(860, 245); buttonIssuedOrder.Click += buttonIssuedOrder_Click;
buttonOrderReady.Name = "buttonOrderReady"; //
buttonOrderReady.Size = new Size(87, 48); // buttonRef
buttonOrderReady.TabIndex = 3; //
buttonOrderReady.Text = "Заказ готов"; buttonRef.Location = new Point(800, 222);
buttonOrderReady.UseVisualStyleBackColor = false; buttonRef.Name = "buttonRef";
buttonOrderReady.Click += buttonOrderReady_Click; buttonRef.Size = new Size(141, 24);
// buttonRef.TabIndex = 5;
// buttonIssuedOrder buttonRef.Text = "Обновить список";
// buttonRef.UseVisualStyleBackColor = true;
buttonIssuedOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonRef.Click += buttonRef_Click;
buttonIssuedOrder.BackColor = SystemColors.ControlLight; //
buttonIssuedOrder.Location = new Point(860, 311); // dataGridView
buttonIssuedOrder.Name = "buttonIssuedOrder"; //
buttonIssuedOrder.Size = new Size(87, 48); dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
buttonIssuedOrder.TabIndex = 4; dataGridView.Location = new Point(0, 26);
buttonIssuedOrder.Text = "Заказ выдан"; dataGridView.Name = "dataGridView";
buttonIssuedOrder.UseVisualStyleBackColor = false; dataGridView.ReadOnly = true;
buttonIssuedOrder.Click += buttonIssuedOrder_Click; dataGridView.RowHeadersWidth = 51;
// dataGridView.RowTemplate.Height = 24;
// buttonRef dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
// dataGridView.Size = new Size(763, 435);
buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right; dataGridView.TabIndex = 6;
buttonRef.BackColor = SystemColors.ControlLight; //
buttonRef.Location = new Point(860, 60); // operationToolStripMenuItem
buttonRef.Name = "buttonRef"; //
buttonRef.Size = new Size(87, 48); operationToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { transactionToolStripMenuItem, продажаToolStripMenuItem });
buttonRef.TabIndex = 5; operationToolStripMenuItem.Name = "operationToolStripMenuItem";
buttonRef.Text = "Обновить список"; operationToolStripMenuItem.Size = new Size(75, 25);
buttonRef.UseVisualStyleBackColor = false; operationToolStripMenuItem.Text = "Операции";
buttonRef.Click += buttonRef_Click; //
// // transactionToolStripMenuItem
// dataGridView //
// transactionToolStripMenuItem.Name = "transactionToolStripMenuItem";
dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; transactionToolStripMenuItem.Size = new Size(180, 22);
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; transactionToolStripMenuItem.Text = "Поставка";
dataGridView.BackgroundColor = SystemColors.ButtonHighlight; transactionToolStripMenuItem.Click += transactionToolStripMenuItem_Click;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; //
dataGridView.Location = new Point(11, 28); // продажаToolStripMenuItem
dataGridView.Name = "dataGridView"; //
dataGridView.ReadOnly = true; продажаToolStripMenuItem.Name = "продажаToolStripMenuItem";
dataGridView.RowHeadersWidth = 51; продажаToolStripMenuItem.Size = new Size(180, 22);
dataGridView.RowTemplate.Height = 24; продажаToolStripMenuItem.Text = "Продажа";
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; продажаToolStripMenuItem.Click += SellToolStripMenuItem_Click;
dataGridView.Size = new Size(780, 441); //
dataGridView.TabIndex = 6; // магазиныToolStripMenuItem
// //
// FormMain магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
// магазиныToolStripMenuItem.Size = new Size(180, 22);
AutoScaleDimensions = new SizeF(7F, 15F); магазиныToolStripMenuItem.Text = "Магазины";
AutoScaleMode = AutoScaleMode.Font; магазиныToolStripMenuItem.Click += shopsToolStripMenuItem_Click;
ClientSize = new Size(985, 467); //
Controls.Add(dataGridView); // FormMain
Controls.Add(buttonRef); //
Controls.Add(buttonIssuedOrder); AutoScaleDimensions = new SizeF(7F, 15F);
Controls.Add(buttonOrderReady); AutoScaleMode = AutoScaleMode.Font;
Controls.Add(buttonTakeOrderInWork); ClientSize = new Size(969, 461);
Controls.Add(buttonCreateOrder); Controls.Add(dataGridView);
Controls.Add(toolStrip1); Controls.Add(buttonRef);
Name = "FormMain"; Controls.Add(buttonIssuedOrder);
Text = "Моторный завод"; Controls.Add(buttonOrderReady);
Load += FormMain_Load; Controls.Add(buttonTakeOrderInWork);
toolStrip1.ResumeLayout(false); Controls.Add(buttonCreateOrder);
toolStrip1.PerformLayout(); Controls.Add(toolStrip1);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); Name = "FormMain";
ResumeLayout(false); Text = "Моторный завод";
PerformLayout(); Load += FormMain_Load;
} toolStrip1.ResumeLayout(false);
toolStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion #endregion
private ToolStrip toolStrip1; private ToolStrip toolStrip1;
private Button buttonCreateOrder; private Button buttonCreateOrder;
private Button buttonTakeOrderInWork; private Button buttonTakeOrderInWork;
private Button buttonOrderReady; private Button buttonOrderReady;
private Button buttonIssuedOrder; private Button buttonIssuedOrder;
private Button buttonRef; private Button buttonRef;
private DataGridView dataGridView; private DataGridView dataGridView;
private ToolStripDropDownButton toolStripDropDownButton1; private ToolStripDropDownButton toolStripDropDownButton1;
private ToolStripMenuItem КомпонентыToolStripMenuItem; private ToolStripMenuItem КомпонентыToolStripMenuItem;
private ToolStripMenuItem ДвигателиToolStripMenuItem; private ToolStripMenuItem ДвигателиToolStripMenuItem;
private ToolStripMenuItem ShopsToolStripMenuItem; private ToolStripMenuItem магазиныToolStripMenuItem;
private ToolStripMenuItem поставкиToolStripMenuItem; private ToolStripMenuItem operationToolStripMenuItem;
} private ToolStripMenuItem transactionToolStripMenuItem;
private ToolStripMenuItem продажаToolStripMenuItem;
}
} }

View File

@ -1,167 +1,170 @@
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using MotorPlantContracts.BindingModels; using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantView;
namespace MotorPlantView.Forms namespace MotorPlantView.Forms
{ {
public partial class FormMain : Form public partial class FormMain : Form
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic; private readonly IOrderLogic _orderLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic) public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger; _logger = logger;
_orderLogic = orderLogic; _orderLogic = orderLogic;
} }
private void FormMain_Load(object sender, EventArgs e) private void FormMain_Load(object sender, EventArgs e)
{ {
LoadData(); LoadData();
} }
private void LoadData() private void LoadData()
{ {
_logger.LogInformation("Çàãðóçêà çàêàçîâ"); _logger.LogInformation("Загрузка заказов");
try try
{ {
var list = _orderLogic.ReadList(null); var list = _orderLogic.ReadList(null);
if (list != null) if (list != null)
{ {
dataGridView.DataSource = list; dataGridView.DataSource = list;
dataGridView.Columns["EngineId"].Visible = false; dataGridView.Columns["EngineId"].Visible = false;
dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
} }
_logger.LogInformation("Çàãðóçêà çàêàçîâ"); _logger.LogInformation("Загрузка заказов");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Îøèáêà çàãðóçêè çàêàçîâ"); _logger.LogError(ex, "Ошибка загрузки заказов");
} }
} }
private void ÊîìïîíåíòûToolStripMenuItem_Click(object sender, EventArgs e) private void КомпонентыToolStripMenuItem_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();
}
}
private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormEngines));
if (service is FormComponents form) if (service is FormEngines form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
private void ÈçäåëèÿToolStripMenuItem_Click(object sender, EventArgs e) private void buttonCreateOrder_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormEngines)); var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
if (service is FormEngines form) {
{ form.ShowDialog();
form.ShowDialog(); LoadData();
} }
} }
private void buttonCreateOrder_Click(object sender, EventArgs e) private void buttonTakeOrderInWork_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); if (dataGridView.SelectedRows.Count == 1)
if (service is FormCreateOrder form) {
{ int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
form.ShowDialog(); _logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
LoadData(); try
} {
} var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
private void buttonTakeOrderInWork_Click(object sender, EventArgs e) {
{ Id = id,
if (dataGridView.SelectedRows.Count == 1) });
{ if (!operationResult)
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); {
_logger.LogInformation("Çàêàç ¹{id}. Ìåíÿåòñÿ ñòàòóñ íà 'Â ðàáîòå'", id); throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
try }
{ LoadData();
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel }
{ catch (Exception ex)
Id = id, {
}); _logger.LogError(ex, "Ошибка передачи заказа в работу");
if (!operationResult) MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
{ }
throw new Exception("Îøèáêà ïðè ñîõðàíåíèè. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ."); }
} }
LoadData(); private void buttonOrderReady_Click(object sender, EventArgs e)
} {
catch (Exception ex) if (dataGridView.SelectedRows.Count == 1)
{ {
_logger.LogError(ex, "Îøèáêà ïåðåäà÷è çàêàçà â ðàáîòó"); int id =
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error); Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
} _logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);
} try
} {
private void buttonOrderReady_Click(object sender, EventArgs e) var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id });
{ if (!operationResult)
if (dataGridView.SelectedRows.Count == 1) {
{ throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
int id = }
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); LoadData();
_logger.LogInformation("Çàêàç ¹{id}. Ìåíÿåòñÿ ñòàòóñ íà 'Ãîòîâ'", id); }
try catch (Exception ex)
{ {
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel { Id = id }); _logger.LogError(ex, "Ошибка отметки о готовности заказа");
if (!operationResult) MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
{ }
throw new Exception("Îøèáêà ïðè ñîõðàíåíèè. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ."); }
} }
LoadData(); private void buttonIssuedOrder_Click(object sender, EventArgs e)
} {
catch (Exception ex) if (dataGridView.SelectedRows.Count == 1)
{ {
_logger.LogError(ex, "Îøèáêà îòìåòêè î ãîòîâíîñòè çàêàçà"); int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
} try
} {
} var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel
private void buttonIssuedOrder_Click(object sender, EventArgs e) {
{ Id = id
if (dataGridView.SelectedRows.Count == 1) });
{ if (!operationResult)
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); {
_logger.LogInformation("Çàêàç ¹{id}. Ìåíÿåòñÿ ñòàòóñ íà 'Âûäàí'", id); throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
try }
{ _logger.LogInformation("Заказ №{id} выдан", id);
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel LoadData();
{ }
Id = id catch (Exception ex)
}); {
if (!operationResult) _logger.LogError(ex, "Ошибка отметки о выдачи заказа"); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
{ }
throw new Exception("Îøèáêà ïðè ñîõðàíåíèè. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ."); }
} }
_logger.LogInformation("Çàêàç ¹{id} âûäàí", id); private void buttonRef_Click(object sender, EventArgs e)
LoadData(); {
} LoadData();
catch (Exception ex) }
{ private void shopsToolStripMenuItem_Click(object sender, EventArgs e)
_logger.LogError(ex, "Îøèáêà îòìåòêè î âûäà÷è çàêàçà"); MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error); {
} var service = Program.ServiceProvider?.GetService(typeof(FormShops));
} if (service is FormShops form)
} {
private void buttonRef_Click(object sender, EventArgs e) form.ShowDialog();
{ }
LoadData(); }
} private void transactionToolStripMenuItem_Click(object sender, EventArgs e)
private void ShopsToolStripMenuItem_Click(object sender, EventArgs e) {
{ var service = Program.ServiceProvider?.GetService(typeof(FormCreateSupply));
var service = Program.ServiceProvider?.GetService(typeof(FormShops)); if (service is FormCreateSupply form)
{
if (service is FormShops form) form.ShowDialog();
{ }
form.ShowDialog(); }
} private void SellToolStripMenuItem_Click(object sender, EventArgs e)
} {
var service = Program.ServiceProvider?.GetService(typeof(FormSellEngines));
private void SupplyToolStripMenuItem_Click(object sender, EventArgs e) if (service is FormSellEngines form)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormSupply)); form.ShowDialog();
}
if (service is FormSupply form) }
{ }
form.ShowDialog();
}
}
}
} }

124
MotorPlantView/FormSellEngines.Designer.cs generated Normal file
View File

@ -0,0 +1,124 @@
namespace MotorPlantView.Forms
{
partial class FormSellEngines
{
/// <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()
{
labelEngine = new Label();
comboBoxEngine = new ComboBox();
labelCount = new Label();
textBoxCount = new TextBox();
buttonSell = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// labelEngine
//
labelEngine.AutoSize = true;
labelEngine.Location = new Point(10, 10);
labelEngine.Name = "labelEngine";
labelEngine.Size = new Size(69, 15);
labelEngine.TabIndex = 0;
labelEngine.Text = "Двигатель: ";
//
// comboBoxEngine
//
comboBoxEngine.FormattingEnabled = true;
comboBoxEngine.Location = new Point(101, 8);
comboBoxEngine.Margin = new Padding(3, 2, 3, 2);
comboBoxEngine.Name = "comboBoxEngine";
comboBoxEngine.Size = new Size(210, 23);
comboBoxEngine.TabIndex = 1;
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(10, 41);
labelCount.Name = "labelCount";
labelCount.Size = new Size(78, 15);
labelCount.TabIndex = 2;
labelCount.Text = "Количество: ";
//
// textBoxCount
//
textBoxCount.Location = new Point(101, 39);
textBoxCount.Margin = new Padding(3, 2, 3, 2);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(210, 23);
textBoxCount.TabIndex = 3;
//
// buttonSell
//
buttonSell.Location = new Point(112, 74);
buttonSell.Margin = new Padding(3, 2, 3, 2);
buttonSell.Name = "buttonSell";
buttonSell.Size = new Size(82, 22);
buttonSell.TabIndex = 4;
buttonSell.Text = "Продать";
buttonSell.UseVisualStyleBackColor = true;
buttonSell.Click += ButtonSell_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(212, 74);
buttonCancel.Margin = new Padding(3, 2, 3, 2);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(82, 22);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormSellEngines
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(320, 105);
Controls.Add(buttonCancel);
Controls.Add(buttonSell);
Controls.Add(textBoxCount);
Controls.Add(labelCount);
Controls.Add(comboBoxEngine);
Controls.Add(labelEngine);
Margin = new Padding(3, 2, 3, 2);
Name = "FormSellEngines";
Text = "Продажа двигателей";
Load += FormSellingEngine_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelEngine;
private ComboBox comboBoxEngine;
private Label labelCount;
private TextBox textBoxCount;
private Button buttonSell;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,82 @@
using Microsoft.Extensions.Logging;
using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.ViewModels;
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 MotorPlantView.Forms
{
public partial class FormSellEngines : Form
{
private readonly ILogger _logger;
private readonly IEngineLogic _logicP;
private readonly IShopLogic _logicS;
private List<EngineViewModel> _EngineList = new List<EngineViewModel>();
public FormSellEngines(ILogger<FormSellEngines> logger, IEngineLogic logicP, IShopLogic logicS)
{
InitializeComponent();
_logger = logger;
_logicP = logicP;
_logicS = logicS;
}
private void FormSellingEngine_Load(object sender, EventArgs e)
{
_EngineList = _logicP.ReadList(null);
if (_EngineList != null)
{
comboBoxEngine.DisplayMember = "EngineName";
comboBoxEngine.ValueMember = "Id";
comboBoxEngine.DataSource = _EngineList;
comboBoxEngine.SelectedItem = null;
_logger.LogInformation("Загрузка двигателей для продажи");
}
}
private void ButtonSell_Click(object sender, EventArgs e)
{
if (comboBoxEngine.SelectedValue == null)
{
MessageBox.Show("Выберите пиццу", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание покупки");
try
{
bool resout = _logicS.Sale(new SupplySearchModel
{
EngineId = Convert.ToInt32(comboBoxEngine.SelectedValue),
Count = Convert.ToInt32(textBoxCount.Text)
});
if (resout)
{
_logger.LogInformation("Проверка пройдена, продажа проведена");
MessageBox.Show("Продажа проведена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
else
{
_logger.LogInformation("Проверка не пройдена");
MessageBox.Show("Продажа не может быть создана.", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
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

@ -1,54 +1,61 @@
using Microsoft.Extensions.DependencyInjection;
using MotorPlantContracts.BusinessLogicsContracts; using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.StoragesContracts; using MotorPlantContracts.StoragesContracts;
using MotorPlantListImplement.Implements; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging; using NLog.Extensions.Logging;
using MotorPlantBusinessLogic.BusinessLogics; using MotorPlantBusinessLogic.BusinessLogics;
using MotorPlantBusinessLogic.BusinessLogic; using MotorPlantBusinessLogic.BusinessLogic;
using MotorPlantView.Forms; using MotorPlantListImplement.Implements;
namespace MotorPlantView namespace MotorPlantView.Forms
{ {
internal static class Program internal static class Program
{ {
private static ServiceProvider? _serviceProvider; private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider; public static ServiceProvider? ServiceProvider => _serviceProvider;
[STAThread] /// <summary>
static void Main() /// The main entry point for the application.
{ /// </summary>
ApplicationConfiguration.Initialize(); [STAThread]
var services = new ServiceCollection(); static void Main()
ConfigureServices(services); {
_serviceProvider = services.BuildServiceProvider(); // To customize application configuration such as set high DPI settings or default font,
Application.Run(_serviceProvider.GetRequiredService<FormMain>()); // see https://aka.ms/applicationconfiguration.
} ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
private static void ConfigureServices(ServiceCollection services) Application.Run(_serviceProvider.GetRequiredService<FormMain>());
{ }
services.AddLogging(option => private static void ConfigureServices(ServiceCollection services)
{ {
option.SetMinimumLevel(LogLevel.Information); services.AddLogging(option =>
option.AddNLog("nlog.config"); {
}); option.SetMinimumLevel(LogLevel.Information);
services.AddTransient<IComponentStorage, ComponentStorage>(); option.AddNLog("nlog.config");
services.AddTransient<IOrderStorage, OrderStorage>(); });
services.AddTransient<IEngineStorage, EngineStorage>(); services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>(); services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IOrderLogic, OrderLogic>(); services.AddTransient<IEngineStorage, EngineStorage>();
services.AddTransient<IEngineLogic, EngineLogic>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IEngineLogic, EngineLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormEngine>();
services.AddTransient<FormEngineComponent>();
services.AddTransient<FormEngines>();
services.AddTransient<IShopStorage, ShopStorage>(); services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IShopLogic, ShopLogic>(); services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormEngine>();
services.AddTransient<FormEngineComponent>();
services.AddTransient<FormEngines>();
services.AddTransient<FormShop>(); services.AddTransient<FormShop>();
services.AddTransient<FormShops>(); services.AddTransient<FormShops>();
services.AddTransient<FormSupply>(); services.AddTransient<FormCreateSupply>();
services.AddTransient<FormSellEngines>();
} }
} }
} }