Изменения из базовой части

This commit is contained in:
Данияр Аглиуллов 2023-03-06 18:57:16 +04:00
commit 4d7b4acc75
45 changed files with 2698 additions and 585 deletions

View File

@ -0,0 +1,123 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.StoragesContract;
using ConfectioneryContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace ConfectioneryBusinessLogic
{
public class ImplementerLogic : IImplementerLogic
{
private readonly ILogger _logger;
private readonly IImplementerStorage _implementerStorage;
public ImplementerLogic(ILogger<ImplementerLogic> logger, IImplementerStorage implementerStorage)
{
_logger = logger;
_implementerStorage = implementerStorage;
}
public bool Create(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Delete(ImplementerBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_implementerStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public ImplementerViewModel? ReadElement(ImplementerSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. FIO:{FIO}.Id:{ Id}",
model.ImplementerFIO, model.Id);
var element = _implementerStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model)
{
_logger.LogInformation("ReadList. FIO:{FIO}.Id:{ Id} ", model?.ImplementerFIO, model?.Id);
var list = (model == null) ? _implementerStorage.GetFullList() :
_implementerStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool Update(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
private void CheckModel(ImplementerBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (model.WorkExperience < 0)
{
throw new ArgumentException("Опыт работы не должен быть отрицательным", nameof(model.WorkExperience));
}
if (model.Qualification < 0)
{
throw new ArgumentException("Квалификация не должна быть отрицательной", nameof(model.Qualification));
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Нет пароля исполнителя", nameof(model.ImplementerFIO));
}
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
throw new ArgumentNullException("Нет фио исполнителя", nameof(model.ImplementerFIO));
}
_logger.LogInformation("Implementer. Id: {Id}, FIO: {FIO}", model.Id, model.ImplementerFIO);
var element = _implementerStorage.GetElement(new ImplementerSearchModel
{
ImplementerFIO = model.ImplementerFIO,
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Исполнитель с таким фио уже есть");
}
}
}
}

View File

@ -94,11 +94,10 @@ namespace ConfectioneryBusinessLogic.BusinessLogics
} }
if ((int)vmodel.Status + 1 != (int)orderStatus) if ((int)vmodel.Status + 1 != (int)orderStatus)
{ {
throw new ArgumentException($"Попытка перевести заказ не в следующий статус: " + throw new InvalidOperationException($"Попытка перевести заказ не в следующий статус: " +
$"Текущий статус: {vmodel.Status} \n" + $"Текущий статус: {vmodel.Status} \n" +
$"Планируемый статус: {orderStatus} \n" + $"Планируемый статус: {orderStatus} \n" +
$"Доступный статус: {(OrderStatus)((int)vmodel.Status + 1)}", $"Доступный статус: {(OrderStatus)((int)vmodel.Status + 1)}");
nameof(vmodel));
} }
if (orderStatus == OrderStatus.Готов) if (orderStatus == OrderStatus.Готов)
{ {
@ -113,6 +112,8 @@ namespace ConfectioneryBusinessLogic.BusinessLogics
model.DateCreate = vmodel.DateCreate; model.DateCreate = vmodel.DateCreate;
if (model.DateImplement == null) if (model.DateImplement == null)
model.DateImplement = vmodel.DateImplement; model.DateImplement = vmodel.DateImplement;
if (vmodel.ImplementerId.HasValue)
model.ImplementerId = vmodel.ImplementerId;
model.PastryId = vmodel.PastryId; model.PastryId = vmodel.PastryId;
model.Sum = vmodel.Sum; model.Sum = vmodel.Sum;
model.Count= vmodel.Count; model.Count= vmodel.Count;
@ -123,5 +124,22 @@ namespace ConfectioneryBusinessLogic.BusinessLogics
} }
return true; return true;
} }
}
public OrderViewModel? ReadElement(OrderSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Id:{ Id}", model.Id);
var element = _orderStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
}
} }

View File

@ -0,0 +1,160 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels.Enums;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryBusinessLogic
{
public class WorkModeling : IWorkProcess
{
private readonly ILogger _logger;
private readonly Random _rnd;
private IOrderLogic? _orderLogic;
public WorkModeling(ILogger<WorkModeling> logger)
{
_logger = logger;
_rnd = new Random(1000);
}
public void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic)
{
_orderLogic = orderLogic;
var implementers = implementerLogic.ReadList(null);
if (implementers == null)
{
_logger.LogWarning("DoWork. Implementers is null");
return;
}
var orders = _orderLogic.ReadList(new OrderSearchModel { Status = OrderStatus.Принят });
if (orders == null || orders.Count == 0)
{
// Поскольку у нас могут быть заказы в работе мы не дожны заканчивать работы, если нет Принятых заказов
// Поэтому находим заказы в работе и продолжаем работу, если они есть
var workingOrders = _orderLogic.ReadList(new() { Status = OrderStatus.Выполняется });
if (workingOrders == null || workingOrders.Count == 0)
{
_logger.LogWarning("DoWork. Orders is null or empty");
return;
}
else
{
_logger.LogWarning("DoWork. Еще есть заказы в работе. для {Count} заказов", workingOrders.Count);
}
}
else
_logger.LogDebug("DoWork for {Count} orders", orders.Count);
foreach (var implementer in implementers)
{
Task.Run(() => WorkerWorkAsync(implementer, orders));
}
}
/// <summary>
/// Иммитация работы исполнителя
/// </summary>
/// <param name="implementer"></param>
/// <param name="orders"></param>
private async Task WorkerWorkAsync(ImplementerViewModel implementer, List<OrderViewModel> orders)
{
if (_orderLogic == null || implementer == null)
{
return;
}
await RunOrderInWork(implementer);
await Task.Run(() =>
{
foreach (var order in orders)
{
try
{
_logger.LogDebug("DoWork. Worker {Id} try get order {Order}", implementer.Id, order.Id);
// пытаемся назначить заказ на исполнителя
_orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = order.Id,
ImplementerId = implementer.Id
});
// делаем работу
Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 1000) * order.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = order.Id
});
}
// кто-то мог уже перехватить заказ, игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// заканчиваем выполнение имитации в случае иной ошибки
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
// отдыхаем
Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100));
}
});
}
/// <summary>
/// Ищем заказ, которые уже в работе (вдруг исполнителя прервали)
/// </summary>
/// <param name="implementer"></param>
/// <returns></returns>
private async Task RunOrderInWork(ImplementerViewModel implementer)
{
if (_orderLogic == null || implementer == null)
{
return;
}
try
{
var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel
{
ImplementerId = implementer.Id,
Status = OrderStatus.Выполняется
}));
if (runOrder == null)
{
return;
}
_logger.LogDebug("DoWork. Worker {Id} back to order {Order}", implementer.Id, runOrder.Id);
// доделываем работу
Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 300) * runOrder.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = runOrder.Id
});
// отдыхаем
Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100));
}
// заказа может не быть, просто игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// а может возникнуть иная ошибка, тогда просто заканчиваем выполнение имитации
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
}
}
}

View File

@ -11,11 +11,13 @@ namespace ConfectioneryFileImplement
private readonly string PastryFileName = "Pastry.xml"; private readonly string PastryFileName = "Pastry.xml";
private readonly string ShopFileName = "Shop.xml"; private readonly string ShopFileName = "Shop.xml";
private readonly string ClientFileName = "Client.xml"; private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
public List<Component> Components { get; private set; } public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; } public List<Order> Orders { get; private set; }
public List<Pastry> Pastries { get; private set; } public List<Pastry> Pastries { get; private set; }
public List<Client> Clients { get; private set; } public List<Client> Clients { get; private set; }
public List<Shop> Shops { get; private set; } public List<Shop> Shops { get; private set; }
public List<Implementer> Implementers { get; private set; }
public static DataFileSingleton GetInstance() public static DataFileSingleton GetInstance()
{ {
@ -30,6 +32,7 @@ namespace ConfectioneryFileImplement
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, OrderFileName, "Clients", x => x.GetXElement); public void SaveClients() => SaveData(Clients, OrderFileName, "Clients", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement); public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
public void SaveImplementers() => SaveData(Orders, ImplementerFileName, "Implementers", x => x.GetXElement);
private DataFileSingleton() private DataFileSingleton()
{ {
@ -38,6 +41,7 @@ namespace ConfectioneryFileImplement
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!; Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!;
} }
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction) private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{ {

View File

@ -0,0 +1,88 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ConfectioneryFileImplement
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
public string ImplementerFIO { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty;
public int WorkExperience { get; private set; }
public int Qualification { get; private set; }
public static Implementer? Create(XElement element)
{
if (element == null)
{
return null;
}
return new()
{
ImplementerFIO = element.Element("FIO")!.Value,
Password = element.Element("Password")!.Value,
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
Qualification = Convert.ToInt32(element.Element("Qualification")!.Value),
WorkExperience = Convert.ToInt32(element.Element("WorkExperience")!.Value),
};
}
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new()
{
Id = model.Id,
Password = model.Password,
Qualification = model.Qualification,
ImplementerFIO = model.ImplementerFIO,
WorkExperience = model.WorkExperience,
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
Password = model.Password;
Qualification = model.Qualification;
ImplementerFIO = model.ImplementerFIO;
WorkExperience = model.WorkExperience;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Password = Password,
Qualification = Qualification,
ImplementerFIO = ImplementerFIO,
};
public XElement GetXElement => new("Client",
new XAttribute("Id", Id),
new XElement("Password", Password),
new XElement("FIO", ImplementerFIO),
new XElement("Qualification", Qualification),
new XElement("WorkExperience", WorkExperience)
);
}
}

View File

@ -0,0 +1,90 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.StoragesContract;
using ConfectioneryContracts.ViewModels;
namespace ConfectioneryFileImplement
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataFileSingleton _source;
public ImplementerStorage()
{
_source = DataFileSingleton.GetInstance();
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
_source.Implementers.Remove(res);
_source.SaveImplementers();
}
return res?.GetViewModel;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (model.Id.HasValue)
return _source.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
if (model.ImplementerFIO != null && model.Password != null)
return _source.Implementers
.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO)
&& x.Password.Equals(model.Password))
?.GetViewModel;
if (model.ImplementerFIO != null)
return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel;
return null;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (model == null)
{
return new();
}
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
if (model.ImplementerFIO != null) // На случай если фио не будет уникальным (по заданию оно уникально)
{
return _source.Implementers
.Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
public List<ImplementerViewModel> GetFullList()
{
return _source.Implementers.Select(x => x.GetViewModel).ToList();
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = _source.Implementers.Count > 0 ? _source.Implementers.Max(x => x.Id) + 1 : 1;
var res = Implementer.Create(model);
if (res != null)
{
_source.Implementers.Add(res);
_source.SaveImplementers();
}
return res?.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
res.Update(model);
_source.SaveImplementers();
}
return res?.GetViewModel;
}
}
}

View File

@ -14,6 +14,7 @@ namespace ConfectioneryFileImplement.Models
public int ClientId { get; set; } public int ClientId { get; set; }
public int? ImplementerId { get; set; }
public int Count { get; private set; } public int Count { get; private set; }
@ -40,7 +41,8 @@ namespace ConfectioneryFileImplement.Models
Status = model.Status, Status = model.Status,
DateCreate = model.DateCreate, DateCreate = model.DateCreate,
DateImplement = model.DateImplement, DateImplement = model.DateImplement,
Id = model.Id, ImplementerId = model.ImplementerId,
Id = model.Id,
}; };
} }
public static Order? Create(XElement element) public static Order? Create(XElement element)
@ -59,6 +61,7 @@ namespace ConfectioneryFileImplement.Models
PastryId = Convert.ToInt32(element.Element("PastryId")!.Value), PastryId = Convert.ToInt32(element.Element("PastryId")!.Value),
ClientId = Convert.ToInt32(element.Element("ClientId")!.Value), ClientId = Convert.ToInt32(element.Element("ClientId")!.Value),
DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value), DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value),
ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value),
DateImplement = string.IsNullOrEmpty(dateImplement) ? null : Convert.ToDateTime(dateImplement), DateImplement = string.IsNullOrEmpty(dateImplement) ? null : Convert.ToDateTime(dateImplement),
}; };
} }
@ -74,20 +77,23 @@ namespace ConfectioneryFileImplement.Models
Sum = model.Sum; Sum = model.Sum;
Status = model.Status; Status = model.Status;
DateCreate = model.DateCreate; DateCreate = model.DateCreate;
ImplementerId = model.ImplementerId;
DateImplement = model.DateImplement; DateImplement = model.DateImplement;
Id = model.Id; Id = model.Id;
} }
public OrderViewModel GetViewModel => new() public OrderViewModel GetViewModel => new()
{ {
ImplementerFIO = DataFileSingleton.GetInstance().Implementers.FirstOrDefault(x => x.Id == ImplementerId)?.ImplementerFIO ?? string.Empty,
PastryName = DataFileSingleton.GetInstance().Pastries.FirstOrDefault(x => x.Id == PastryId)?.PastryName ?? string.Empty, PastryName = DataFileSingleton.GetInstance().Pastries.FirstOrDefault(x => x.Id == PastryId)?.PastryName ?? string.Empty,
ClientFIO = DataFileSingleton.GetInstance().Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty, ClientFIO = DataFileSingleton.GetInstance().Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty,
PastryId = PastryId, PastryId = PastryId,
ClientId = ClientId, ClientId = ClientId,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,
DateCreate = DateCreate, DateCreate = DateCreate,
DateImplement = DateImplement, DateImplement = DateImplement,
ImplementerId = ImplementerId,
Id = Id, Id = Id,
}; };
public XElement GetXElement => new("Order", public XElement GetXElement => new("Order",
@ -98,7 +104,8 @@ namespace ConfectioneryFileImplement.Models
new XElement("Sum", Sum.ToString()), new XElement("Sum", Sum.ToString()),
new XElement("Status", (int)Status), new XElement("Status", (int)Status),
new XElement("DateCreate", DateCreate), new XElement("DateCreate", DateCreate),
new XElement("DateImplement", DateImplement) new XElement("DateImplement", DateImplement),
new XElement("ImplementerId", ImplementerId)
); );
} }
} }

View File

@ -28,11 +28,15 @@ namespace ConfectioneryFileImplement
public OrderViewModel? GetElement(OrderSearchModel model) public OrderViewModel? GetElement(OrderSearchModel model)
{ {
if (!model.Id.HasValue) if (model.ImplementerId.HasValue)
{ {
return null; return _source.Orders.FirstOrDefault(x => x.ImplementerId == model.ImplementerId)?.GetViewModel;
} }
return _source.Orders.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel; if (!model.Id.HasValue)
{
return null;
}
return _source.Orders.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel;
} }
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
@ -51,7 +55,14 @@ namespace ConfectioneryFileImplement
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
} }
var result = GetElement(model); if (!model.Id.HasValue && model.Status.HasValue)
{
return _source.Orders
.Where(x => x.Status == model.Status)
.Select(x => x.GetViewModel)
.ToList();
}
var result = GetElement(model);
return result != null ? new() { result } : new(); return result != null ? new() { result } : new();
} }

View File

@ -9,6 +9,7 @@ namespace ConfectioneryListImplement
public List<Order> Orders { get; set; } public List<Order> Orders { get; set; }
public List<Pastry> Pastry { get; set; } public List<Pastry> Pastry { get; set; }
public List<Client> Clients { get; set; } public List<Client> Clients { get; set; }
public List<Implementer> Implementers { get; set; }
public List<Shop> Shops { get; set; } public List<Shop> Shops { get; set; }
private DataListSingleton() private DataListSingleton()
@ -17,6 +18,7 @@ namespace ConfectioneryListImplement
Orders = new List<Order>(); Orders = new List<Order>();
Pastry = new List<Pastry>(); Pastry = new List<Pastry>();
Clients = new List<Client>(); Clients = new List<Client>();
Implementers = new List<Implementer>();
Shops = new List<Shop>(); Shops = new List<Shop>();
} }
public static DataListSingleton GetInstance() public static DataListSingleton GetInstance()

View File

@ -0,0 +1,55 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels;
namespace ConfectioneryListImplement
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
public string ImplementerFIO { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty;
public int WorkExperience { get; private set; }
public int Qualification { get; private set; }
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new()
{
Id = model.Id,
Password = model.Password,
Qualification = model.Qualification,
ImplementerFIO = model.ImplementerFIO,
WorkExperience = model.WorkExperience,
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
Password = model.Password;
Qualification = model.Qualification;
ImplementerFIO = model.ImplementerFIO;
WorkExperience = model.WorkExperience;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Password = Password,
Qualification = Qualification,
ImplementerFIO = ImplementerFIO,
};
}
}

View File

@ -0,0 +1,84 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.StoragesContract;
using ConfectioneryContracts.ViewModels;
namespace ConfectioneryListImplement
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataListSingleton _source;
public ImplementerStorage()
{
_source = DataListSingleton.GetInstance();
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
_source.Implementers.Remove(res);
}
return res?.GetViewModel;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (model.Id.HasValue)
return _source.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
if (model.ImplementerFIO != null && model.Password != null)
return _source.Implementers
.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO)
&& x.Password.Equals(model.Password))
?.GetViewModel;
if (model.ImplementerFIO != null)
return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel;
return null;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (model == null)
{
return new();
}
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
if (model.ImplementerFIO != null) // На случай если фио не будет уникальным (по заданию оно уникально)
{
return _source.Implementers
.Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
public List<ImplementerViewModel> GetFullList()
{
return _source.Implementers.Select(x => x.GetViewModel).ToList();
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = _source.Implementers.Count > 0 ? _source.Implementers.Max(x => x.Id) + 1 : 1;
var res = Implementer.Create(model);
if (res != null)
{
_source.Implementers.Add(res);
}
return res?.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
res?.Update(model);
return res?.GetViewModel;
}
}
}

View File

@ -13,6 +13,8 @@ namespace ConfectioneryListImplement.Models
public int ClientId { get; private set; } public int ClientId { get; private set; }
public int? ImplementerId { 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; }
@ -38,6 +40,7 @@ namespace ConfectioneryListImplement.Models
Status = model.Status, Status = model.Status,
DateCreate = model.DateCreate, DateCreate = model.DateCreate,
DateImplement = model.DateImplement, DateImplement = model.DateImplement,
ImplementerId = model.ImplementerId,
Id = model.Id, Id = model.Id,
}; };
} }
@ -53,6 +56,7 @@ namespace ConfectioneryListImplement.Models
Status = model.Status; Status = model.Status;
DateCreate = model.DateCreate; DateCreate = model.DateCreate;
DateImplement = model.DateImplement; DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
Id = model.Id; Id = model.Id;
} }
public OrderViewModel GetViewModel => new() public OrderViewModel GetViewModel => new()
@ -60,7 +64,9 @@ namespace ConfectioneryListImplement.Models
PastryId = PastryId, PastryId = PastryId,
ClientFIO = DataListSingleton.GetInstance().Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty, ClientFIO = DataListSingleton.GetInstance().Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty,
ClientId = ClientId, ClientId = ClientId,
Count = Count, ImplementerId = ImplementerId,
ImplementerFIO = DataListSingleton.GetInstance().Implementers.FirstOrDefault(x => x.Id == ImplementerId)?.ImplementerFIO ?? string.Empty,
Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,
DateCreate = DateCreate, DateCreate = DateCreate,

View File

@ -30,6 +30,10 @@ namespace ConfectioneryListImplement
public OrderViewModel? GetElement(OrderSearchModel model) public OrderViewModel? GetElement(OrderSearchModel model)
{ {
if (model.ImplementerId.HasValue)
{
return _source.Orders.FirstOrDefault(x => x.ImplementerId == model.ImplementerId)?.GetViewModel;
}
if (!model.Id.HasValue) if (!model.Id.HasValue)
{ {
return null; return null;
@ -61,6 +65,18 @@ namespace ConfectioneryListImplement
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
} }
if (!model.Id.HasValue && model.Status.HasValue)
{
return _source.Orders
.Where(x => x.Status == model.Status)
.Select(x => x.GetViewModel)
.ToList();
}
if (model.ImplementerId.HasValue)
{
var res = _source.Orders.FirstOrDefault(x => x.ImplementerId == model.ImplementerId);
return res != null ? new() { res.GetViewModel } : new();
}
foreach (var order in _source.Orders) foreach (var order in _source.Orders)
{ {
if (order.Id == model.Id) if (order.Id == model.Id)

View File

@ -30,6 +30,9 @@
<Compile Update="FormViewClients.cs"> <Compile Update="FormViewClients.cs">
<SubType>Form</SubType> <SubType>Form</SubType>
</Compile> </Compile>
<Compile Update="FormViewImplementers.cs">
<SubType>Form</SubType>
</Compile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -27,8 +27,7 @@ namespace ConfectioneryView
_logger.LogInformation("Получение компонента"); _logger.LogInformation("Получение компонента");
var view = _logic.ReadElement(new ComponentSearchModel var view = _logic.ReadElement(new ComponentSearchModel
{ {
Id = Id = _id.Value
_id.Value
}); });
if (view != null) if (view != null)
{ {

173
Confectionery/FormImplementer.Designer.cs generated Normal file
View File

@ -0,0 +1,173 @@
namespace ConfectioneryView
{
partial class FormImplementer
{
/// <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()
{
label1 = new Label();
label2 = new Label();
label3 = new Label();
label4 = new Label();
textBoxFio = new TextBox();
textBoxPassword = new TextBox();
numericUpDownWorkExperience = new NumericUpDown();
numericUpDownQualification = new NumericUpDown();
buttonCancel = new Button();
buttonSave = new Button();
((System.ComponentModel.ISupportInitialize)numericUpDownWorkExperience).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownQualification).BeginInit();
SuspendLayout();
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(79, 12);
label1.Name = "label1";
label1.Size = new Size(37, 15);
label1.TabIndex = 0;
label1.Text = "ФИО:";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(69, 41);
label2.Name = "label2";
label2.Size = new Size(52, 15);
label2.TabIndex = 1;
label2.Text = "Пароль:";
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(78, 68);
label3.Name = "label3";
label3.Size = new Size(38, 15);
label3.TabIndex = 2;
label3.Text = "Стаж:";
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(25, 97);
label4.Name = "label4";
label4.Size = new Size(91, 15);
label4.TabIndex = 3;
label4.Text = "Квалификация:";
//
// textBoxFio
//
textBoxFio.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxFio.Location = new Point(127, 9);
textBoxFio.Name = "textBoxFio";
textBoxFio.Size = new Size(271, 23);
textBoxFio.TabIndex = 4;
//
// textBoxPassword
//
textBoxPassword.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxPassword.Location = new Point(127, 38);
textBoxPassword.Name = "textBoxPassword";
textBoxPassword.PasswordChar = '*';
textBoxPassword.Size = new Size(271, 23);
textBoxPassword.TabIndex = 5;
//
// numericUpDownWorkExperience
//
numericUpDownWorkExperience.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
numericUpDownWorkExperience.Location = new Point(127, 66);
numericUpDownWorkExperience.Name = "numericUpDownWorkExperience";
numericUpDownWorkExperience.Size = new Size(271, 23);
numericUpDownWorkExperience.TabIndex = 6;
//
// numericUpDownQualification
//
numericUpDownQualification.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
numericUpDownQualification.Location = new Point(127, 95);
numericUpDownQualification.Name = "numericUpDownQualification";
numericUpDownQualification.Size = new Size(271, 23);
numericUpDownQualification.TabIndex = 7;
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(309, 138);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(89, 33);
buttonCancel.TabIndex = 8;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonSave.Location = new Point(214, 138);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(89, 33);
buttonSave.TabIndex = 9;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// FormImplementer
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(410, 183);
Controls.Add(buttonSave);
Controls.Add(buttonCancel);
Controls.Add(numericUpDownQualification);
Controls.Add(numericUpDownWorkExperience);
Controls.Add(textBoxPassword);
Controls.Add(textBoxFio);
Controls.Add(label4);
Controls.Add(label3);
Controls.Add(label2);
Controls.Add(label1);
Name = "FormImplementer";
Text = "Добавление / Редактирование исполнителя";
Load += FormImplementer_Load;
((System.ComponentModel.ISupportInitialize)numericUpDownWorkExperience).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownQualification).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label label1;
private Label label2;
private Label label3;
private Label label4;
private TextBox textBoxFio;
private TextBox textBoxPassword;
private NumericUpDown numericUpDownWorkExperience;
private NumericUpDown numericUpDownQualification;
private Button buttonCancel;
private Button buttonSave;
}
}

View File

@ -0,0 +1,101 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.SearchModels;
using Microsoft.Extensions.Logging;
using System.Windows.Forms;
namespace ConfectioneryView
{
public partial class FormImplementer : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public FormImplementer(ILogger<FormImplementer> logger, IImplementerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormImplementer_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение исполнителя");
var view = _logic.ReadElement(new ImplementerSearchModel
{
Id = _id.Value
});
if (view != null)
{
textBoxFio.Text = view.ImplementerFIO;
textBoxPassword.Text = view.Password;
numericUpDownQualification.Value = view.Qualification;
numericUpDownWorkExperience.Value = view.WorkExperience;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxPassword.Text))
{
MessageBox.Show("Заполните пароль", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxFio.Text))
{
MessageBox.Show("Заполните фио", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение исполнителя");
try
{
var model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = textBoxFio.Text,
Password = textBoxPassword.Text,
Qualification = (int)numericUpDownQualification.Value,
WorkExperience = (int)numericUpDownWorkExperience.Value,
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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,259 +1,250 @@
namespace ConfectioneryView namespace ConfectioneryView
{ {
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()
{ {
menuStrip1 = new MenuStrip(); menuStrip1 = new MenuStrip();
справочникиToolStripMenuItem = new ToolStripMenuItem(); справочникиToolStripMenuItem = new ToolStripMenuItem();
pastryToolStripMenuItem = new ToolStripMenuItem(); pastryToolStripMenuItem = new ToolStripMenuItem();
componentToolStripMenuItem = new ToolStripMenuItem(); componentToolStripMenuItem = new ToolStripMenuItem();
ShopsToolStripMenuItem = new ToolStripMenuItem(); ShopsToolStripMenuItem = new ToolStripMenuItem();
reportsToolStripMenuItem = new ToolStripMenuItem(); clientsToolStripMenuItem = new ToolStripMenuItem();
reportShopsToolStripMenuItem = new ToolStripMenuItem(); reportsToolStripMenuItem = new ToolStripMenuItem();
ShopPastriesToolStripMenuItem = new ToolStripMenuItem(); reportShopsToolStripMenuItem = new ToolStripMenuItem();
ordersToolStripMenuItem = new ToolStripMenuItem(); ShopPastriesToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView(); ordersToolStripMenuItem = new ToolStripMenuItem();
buttonCreateOrder = new Button(); dataGridView = new DataGridView();
buttonTakeOrderInWork = new Button(); buttonCreateOrder = new Button();
button2 = new Button(); button3 = new Button();
button3 = new Button(); button4 = new Button();
button4 = new Button(); buttonAddPastryInShop = new Button();
buttonAddPastryInShop = new Button(); ImplementersToolStripMenuItem = new ToolStripMenuItem();
buttonSellPastry = new Button(); DoWorkToolStripMenuItem = new ToolStripMenuItem();
clientsToolStripMenuItem = new ToolStripMenuItem(); buttonSellPastry = new Button();
menuStrip1.SuspendLayout(); menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout(); SuspendLayout();
// //
// menuStrip1 // menuStrip1
// //
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, reportsToolStripMenuItem }); menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, reportsToolStripMenuItem, DoWorkToolStripMenuItem });
menuStrip1.Location = new Point(0, 0); menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1"; menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(783, 24); menuStrip1.Size = new Size(783, 24);
menuStrip1.TabIndex = 0; menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1"; menuStrip1.Text = "menuStrip1";
// //
// справочникиToolStripMenuItem // справочникиToolStripMenuItem
// //
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { pastryToolStripMenuItem, componentToolStripMenuItem, ShopsToolStripMenuItem }); справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ShopsToolStripMenuItem, pastryToolStripMenuItem, componentToolStripMenuItem, clientsToolStripMenuItem });
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { pastryToolStripMenuItem, componentToolStripMenuItem, clientsToolStripMenuItem }); справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.Size = new Size(94, 20);
справочникиToolStripMenuItem.Size = new Size(94, 20); справочникиToolStripMenuItem.Text = "Справочники";
справочникиToolStripMenuItem.Text = "Справочники"; //
// // pastryToolStripMenuItem
// pastryToolStripMenuItem //
// pastryToolStripMenuItem.Name = "pastryToolStripMenuItem";
pastryToolStripMenuItem.Name = "pastryToolStripMenuItem"; pastryToolStripMenuItem.Size = new Size(145, 22);
pastryToolStripMenuItem.Size = new Size(180, 22); pastryToolStripMenuItem.Text = "Изделия";
pastryToolStripMenuItem.Text = "Изделия"; pastryToolStripMenuItem.Click += PastryToolStripMenuItem_Click;
pastryToolStripMenuItem.Click += PastryToolStripMenuItem_Click; //
// // componentToolStripMenuItem
// componentToolStripMenuItem //
// componentToolStripMenuItem.Name = "componentToolStripMenuItem";
componentToolStripMenuItem.Name = "componentToolStripMenuItem"; componentToolStripMenuItem.Size = new Size(145, 22);
componentToolStripMenuItem.Size = new Size(180, 22); componentToolStripMenuItem.Text = "Компоненты";
componentToolStripMenuItem.Text = "Компоненты"; componentToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click;
componentToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; //
// // ShopsToolStripMenuItem
// ShopsToolStripMenuItem //
// ShopsToolStripMenuItem.Name = "ShopsToolStripMenuItem";
ShopsToolStripMenuItem.Name = "ShopsToolStripMenuItem"; ShopsToolStripMenuItem.Size = new Size(145, 22);
ShopsToolStripMenuItem.Size = new Size(145, 22); ShopsToolStripMenuItem.Text = "Магазины";
ShopsToolStripMenuItem.Text = "Магазины"; ShopsToolStripMenuItem.Click += ShopsToolStripMenuItem_Click;
ShopsToolStripMenuItem.Click += ShopsToolStripMenuItem_Click; //
// // clientsToolStripMenuItem
// reportsToolStripMenuItem //
// clientsToolStripMenuItem.Name = "clientsToolStripMenuItem";
reportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { reportShopsToolStripMenuItem, ShopPastriesToolStripMenuItem, ordersToolStripMenuItem }); clientsToolStripMenuItem.Size = new Size(145, 22);
reportsToolStripMenuItem.Name = "reportsToolStripMenuItem"; clientsToolStripMenuItem.Text = "Клиенты";
reportsToolStripMenuItem.Size = new Size(60, 20); clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click;
reportsToolStripMenuItem.Text = "Отчеты"; //
// // reportsToolStripMenuItem
// reportShopsToolStripMenuItem //
// reportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { reportShopsToolStripMenuItem, ShopPastriesToolStripMenuItem, ordersToolStripMenuItem });
reportShopsToolStripMenuItem.Name = "reportShopsToolStripMenuItem"; reportsToolStripMenuItem.Name = "reportsToolStripMenuItem";
reportShopsToolStripMenuItem.Size = new Size(202, 22); reportsToolStripMenuItem.Size = new Size(60, 20);
reportShopsToolStripMenuItem.Text = "Список магазинов"; reportsToolStripMenuItem.Text = "Отчеты";
reportShopsToolStripMenuItem.Click += ReportShopsToolStripMenuItem_Click; //
// // reportShopsToolStripMenuItem
// ShopPastriesToolStripMenuItem //
// reportShopsToolStripMenuItem.Name = "reportShopsToolStripMenuItem";
ShopPastriesToolStripMenuItem.Name = "ShopPastriesToolStripMenuItem"; reportShopsToolStripMenuItem.Size = new Size(202, 22);
ShopPastriesToolStripMenuItem.Size = new Size(202, 22); reportShopsToolStripMenuItem.Text = "Список магазинов";
ShopPastriesToolStripMenuItem.Text = "Магазины с изделиями"; reportShopsToolStripMenuItem.Click += ReportShopsToolStripMenuItem_Click;
ShopPastriesToolStripMenuItem.Click += ShopPastriesToolStripMenuItem_Click; //
// // ShopPastriesToolStripMenuItem
// ordersToolStripMenuItem //
// ShopPastriesToolStripMenuItem.Name = "ShopPastriesToolStripMenuItem";
ordersToolStripMenuItem.Name = "ordersToolStripMenuItem"; ShopPastriesToolStripMenuItem.Size = new Size(202, 22);
ordersToolStripMenuItem.Size = new Size(202, 22); ShopPastriesToolStripMenuItem.Text = "Магазины с изделиями";
ordersToolStripMenuItem.Text = "Список заказов"; ShopPastriesToolStripMenuItem.Click += ShopPastriesToolStripMenuItem_Click;
ordersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; //
// // ordersToolStripMenuItem
// dataGridView //
// ordersToolStripMenuItem.Name = "ordersToolStripMenuItem";
dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; ordersToolStripMenuItem.Size = new Size(202, 22);
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; ordersToolStripMenuItem.Text = "Список заказов";
dataGridView.Location = new Point(12, 27); ordersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click;
dataGridView.Name = "dataGridView"; //
dataGridView.RowTemplate.Height = 25; // dataGridView
dataGridView.Size = new Size(606, 399); //
dataGridView.TabIndex = 1; dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
// dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
// buttonCreateOrder dataGridView.Location = new Point(12, 27);
// dataGridView.Name = "dataGridView";
buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; dataGridView.RowTemplate.Height = 25;
buttonCreateOrder.Location = new Point(624, 39); dataGridView.Size = new Size(606, 399);
buttonCreateOrder.Name = "buttonCreateOrder"; dataGridView.TabIndex = 1;
buttonCreateOrder.Size = new Size(147, 32); //
buttonCreateOrder.TabIndex = 2; // buttonCreateOrder
buttonCreateOrder.Text = "Создать заказ"; //
buttonCreateOrder.UseVisualStyleBackColor = true; buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonCreateOrder.Click += ButtonCreateOrder_Click; buttonCreateOrder.Location = new Point(624, 39);
// buttonCreateOrder.Name = "buttonCreateOrder";
// buttonTakeOrderInWork buttonCreateOrder.Size = new Size(147, 32);
// buttonCreateOrder.TabIndex = 2;
buttonTakeOrderInWork.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonCreateOrder.Text = "Создать заказ";
buttonTakeOrderInWork.Location = new Point(624, 98); buttonCreateOrder.UseVisualStyleBackColor = true;
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; buttonCreateOrder.Click += ButtonCreateOrder_Click;
buttonTakeOrderInWork.Size = new Size(147, 32); //
buttonTakeOrderInWork.TabIndex = 3; // button3
buttonTakeOrderInWork.Text = "Отдать на выполнение"; //
buttonTakeOrderInWork.UseVisualStyleBackColor = true; button3.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; button3.Location = new Point(624, 91);
// button3.Name = "button3";
// button2 button3.Size = new Size(147, 32);
// button3.TabIndex = 5;
button2.Anchor = AnchorStyles.Top | AnchorStyles.Right; button3.Text = "Заказ выдан";
button2.Location = new Point(624, 157); button3.UseVisualStyleBackColor = true;
button2.Name = "button2"; button3.Click += ButtonIssuedOrder_Click;
button2.Size = new Size(147, 32); //
button2.TabIndex = 4; // button4
button2.Text = "Заказ готов"; //
button2.UseVisualStyleBackColor = true; button4.Anchor = AnchorStyles.Top | AnchorStyles.Right;
button2.Click += ButtonOrderReady_Click; button4.Location = new Point(624, 150);
// button4.Name = "button4";
// button3 button4.Size = new Size(147, 32);
// button4.TabIndex = 6;
button3.Anchor = AnchorStyles.Top | AnchorStyles.Right; button4.Text = "Обновить список";
button3.Location = new Point(624, 215); button4.UseVisualStyleBackColor = true;
button3.Name = "button3"; button4.Click += ButtonRef_Click;
button3.Size = new Size(147, 32); //
button3.TabIndex = 5; // buttonAddPastryInShop
button3.Text = "Заказ выдан"; //
button3.UseVisualStyleBackColor = true; buttonAddPastryInShop.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
button3.Click += ButtonIssuedOrder_Click; buttonAddPastryInShop.Location = new Point(624, 260);
// buttonAddPastryInShop.Name = "buttonAddPastryInShop";
// button4 buttonAddPastryInShop.Size = new Size(147, 31);
// buttonAddPastryInShop.TabIndex = 7;
button4.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonAddPastryInShop.Text = "Пополнение магазина";
button4.Location = new Point(624, 274); buttonAddPastryInShop.UseVisualStyleBackColor = true;
button4.Name = "button4"; buttonAddPastryInShop.Click += ButtonAddPastryInShop_Click;
button4.Size = new Size(147, 32); //
button4.TabIndex = 6; // ImplementersToolStripMenuItem
button4.Text = "Обновить список"; //
button4.UseVisualStyleBackColor = true; ImplementersToolStripMenuItem.Name = "ImplementersToolStripMenuItem";
button4.Click += ButtonRef_Click; ImplementersToolStripMenuItem.Size = new Size(180, 22);
// ImplementersToolStripMenuItem.Text = "Исполнители";
// buttonAddPastryInShop ImplementersToolStripMenuItem.Click += ImplementersToolStripMenuItem_Click;
// //
buttonAddPastryInShop.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; // DoWorkToolStripMenuItem
buttonAddPastryInShop.Location = new Point(624, 384); //
buttonAddPastryInShop.Name = "buttonAddPastryInShop"; DoWorkToolStripMenuItem.Name = "DoWorkToolStripMenuItem";
buttonAddPastryInShop.Size = new Size(147, 31); DoWorkToolStripMenuItem.Size = new Size(92, 20);
buttonAddPastryInShop.TabIndex = 7; DoWorkToolStripMenuItem.Text = "Запуск работ";
buttonAddPastryInShop.Text = "Пополнение магазина"; DoWorkToolStripMenuItem.Click += DoWorkToolStripMenuItem_Click;
buttonAddPastryInShop.UseVisualStyleBackColor = true; //
buttonAddPastryInShop.Click += ButtonAddPastryInShop_Click; // buttonSellPastry
// //
// buttonSellPastry buttonSellPastry.Anchor = AnchorStyles.Top | AnchorStyles.Right;
// buttonSellPastry.Location = new Point(624, 207);
buttonSellPastry.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonSellPastry.Name = "buttonSellPastry";
buttonSellPastry.Location = new Point(624, 331); buttonSellPastry.Size = new Size(147, 31);
buttonSellPastry.Name = "buttonSellPastry"; buttonSellPastry.TabIndex = 8;
buttonSellPastry.Size = new Size(147, 31); buttonSellPastry.Text = "Продать изделие";
buttonSellPastry.TabIndex = 8; buttonSellPastry.UseVisualStyleBackColor = true;
buttonSellPastry.Text = "Продать изделие"; buttonSellPastry.Click += ButtonSellPastry_Click;
buttonSellPastry.UseVisualStyleBackColor = true; //
buttonSellPastry.Click += ButtonSellPastry_Click; // FormMain
// //
// clientsToolStripMenuItem AutoScaleDimensions = new SizeF(7F, 15F);
// AutoScaleMode = AutoScaleMode.Font;
clientsToolStripMenuItem.Name = "clientsToolStripMenuItem"; ClientSize = new Size(783, 438);
clientsToolStripMenuItem.Size = new Size(180, 22); Controls.Add(buttonSellPastry);
clientsToolStripMenuItem.Text = "Клиенты"; Controls.Add(buttonAddPastryInShop);
clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; Controls.Add(button4);
// Controls.Add(button3);
// FormMain Controls.Add(buttonCreateOrder);
// Controls.Add(dataGridView);
AutoScaleDimensions = new SizeF(7F, 15F); Controls.Add(menuStrip1);
AutoScaleMode = AutoScaleMode.Font; MainMenuStrip = menuStrip1;
ClientSize = new Size(783, 438); Name = "FormMain";
Controls.Add(buttonSellPastry); Text = "Кондитерская";
Controls.Add(buttonAddPastryInShop); Load += FormMain_Load;
Controls.Add(button4); menuStrip1.ResumeLayout(false);
Controls.Add(button3); menuStrip1.PerformLayout();
Controls.Add(button2); ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
Controls.Add(buttonTakeOrderInWork); ResumeLayout(false);
Controls.Add(buttonCreateOrder); PerformLayout();
Controls.Add(dataGridView); }
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormMain";
Text = "Кондитерская";
Load += FormMain_Load;
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion #endregion
private MenuStrip menuStrip1; private MenuStrip menuStrip1;
private ToolStripMenuItem справочникиToolStripMenuItem; private ToolStripMenuItem справочникиToolStripMenuItem;
private DataGridView dataGridView; private DataGridView dataGridView;
private Button buttonCreateOrder; private Button buttonCreateOrder;
private Button buttonTakeOrderInWork; private Button buttonTakeOrderInWork;
private Button button2; private Button button2;
private Button button3; private Button button3;
private Button button4; private Button button4;
private ToolStripMenuItem pastryToolStripMenuItem; private ToolStripMenuItem pastryToolStripMenuItem;
private ToolStripMenuItem componentToolStripMenuItem; private ToolStripMenuItem componentToolStripMenuItem;
private ToolStripMenuItem reportsToolStripMenuItem; private ToolStripMenuItem reportsToolStripMenuItem;
private ToolStripMenuItem reportShopsToolStripMenuItem; private ToolStripMenuItem reportShopsToolStripMenuItem;
private ToolStripMenuItem ShopPastriesToolStripMenuItem; private ToolStripMenuItem ShopPastriesToolStripMenuItem;
private ToolStripMenuItem ordersToolStripMenuItem; private ToolStripMenuItem ordersToolStripMenuItem;
private ToolStripMenuItem ShopsToolStripMenuItem; private ToolStripMenuItem ShopsToolStripMenuItem;
private Button buttonAddPastryInShop; private Button buttonAddPastryInShop;
private Button buttonSellPastry; private Button buttonSellPastry;
private ToolStripMenuItem clientsToolStripMenuItem; private ToolStripMenuItem clientsToolStripMenuItem;
} private ToolStripMenuItem ImplementersToolStripMenuItem;
private ToolStripMenuItem DoWorkToolStripMenuItem;
}
} }

View File

@ -7,217 +7,238 @@ using System.Windows.Forms;
namespace ConfectioneryView namespace ConfectioneryView
{ {
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;
private readonly IReportLogic _reportLogic; private readonly IReportLogic _reportLogic;
private readonly IWorkProcess _workProcess;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic) public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger; _logger = logger;
_orderLogic = orderLogic; _orderLogic = orderLogic;
_reportLogic = reportLogic; _reportLogic = reportLogic;
} _workProcess = workProcess;
private void FormMain_Load(object sender, EventArgs e) }
{ private void FormMain_Load(object sender, EventArgs e)
LoadData(); {
} LoadData();
private void LoadData() }
{ private void LoadData()
try {
{ try
var list = _orderLogic.ReadList(null); {
if (list != null) var list = _orderLogic.ReadList(null);
{ if (list != null)
dataGridView.DataSource = list; {
dataGridView.Columns["Id"].HeaderText = "Íîìåð çàêàçà"; dataGridView.DataSource = list;
dataGridView.Columns["PastryId"].Visible = false; dataGridView.Columns["Id"].HeaderText = "Íîìåð çàêàçà";
dataGridView.Columns["ClientId"].Visible = false; dataGridView.Columns["PastryId"].Visible = false;
dataGridView.Columns["PastryName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView.Columns["ImplementerId"].Visible = false;
} dataGridView.Columns["PastryName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
_logger.LogInformation("Çàãðóçêà çàêàçîâ"); dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
} }
catch (Exception ex) _logger.LogInformation("Çàãðóçêà çàêàçîâ");
{ }
_logger.LogError(ex, "Îøèáêà çàãðóçêè çàêàçîâ"); catch (Exception ex)
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, {
MessageBoxIcon.Error); _logger.LogError(ex, "Îøèáêà çàãðóçêè çàêàçîâ");
} MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK,
} MessageBoxIcon.Error);
private void ComponentsToolStripMenuItem_Click(object sender, EventArgs }
e) }
{ private void ComponentsToolStripMenuItem_Click(object sender, EventArgs
var service = Program.ServiceProvider?.GetService(typeof(FormComponents)); e)
if (service is FormComponents form) {
{ var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
form.ShowDialog(); if (service is FormComponents form)
} {
} form.ShowDialog();
private void PastryToolStripMenuItem_Click(object sender, EventArgs e) }
{ }
var service = Program.ServiceProvider?.GetService(typeof(FormViewPastry)); private void PastryToolStripMenuItem_Click(object sender, EventArgs e)
if (service is FormViewPastry form) {
{ var service = Program.ServiceProvider?.GetService(typeof(FormViewPastry));
form.ShowDialog(); if (service is FormViewPastry form)
} {
} form.ShowDialog();
}
}
private void ButtonCreateOrder_Click(object sender, EventArgs e) private void ButtonCreateOrder_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form) if (service is FormCreateOrder form)
{ {
form.ShowDialog(); form.ShowDialog();
LoadData(); LoadData();
} }
} }
private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) private void ButtonTakeOrderInWork_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Çàêàç No{id}. Ìåíÿåòñÿ ñòàòóñ íà 'Â ðàáîòå'", id); _logger.LogInformation("Çàêàç No{id}. Ìåíÿåòñÿ ñòàòóñ íà 'Â ðàáîòå'", id);
try try
{ {
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id }); var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel { Id = id });
if (!operationResult) if (!operationResult)
{ {
throw new Exception("Îøèáêà ïðè ñîõðàíåíèè. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ."); throw new Exception("Îøèáêà ïðè ñîõðàíåíèè. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ.");
} }
LoadData(); LoadData();
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Îøèáêà ïåðåäà÷è çàêàçà â ðàáîòó"); _logger.LogError(ex, "Îøèáêà ïåðåäà÷è çàêàçà â ðàáîòó");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK,
MessageBoxIcon.Error); MessageBoxIcon.Error);
} }
} }
} }
private void ButtonOrderReady_Click(object sender, EventArgs e) private void ButtonOrderReady_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
OrderStatus orderStatus = (OrderStatus)dataGridView.SelectedRows[0].Cells["Status"].Value; OrderStatus orderStatus = (OrderStatus)dataGridView.SelectedRows[0].Cells["Status"].Value;
_logger.LogInformation("Çàêàç No{id}. Ìåíÿåòñÿ ñòàòóñ íà 'Ãîòîâ'", id); _logger.LogInformation("Çàêàç No{id}. Ìåíÿåòñÿ ñòàòóñ íà 'Ãîòîâ'", id);
try try
{ {
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel var operationResult = _orderLogic.FinishOrder(new OrderBindingModel
{ {
Id = id, Id = id,
Status = orderStatus Status = orderStatus
}); });
if (!operationResult) if (!operationResult)
{ {
throw new Exception("Îøèáêà ïðè ñîõðàíåíèè. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ."); throw new Exception("Îøèáêà ïðè ñîõðàíåíèè. Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ.");
} }
LoadData(); LoadData();
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Îøèáêà îòìåòêè î ãîòîâíîñòè çàêàçà"); _logger.LogError(ex, "Îøèáêà îòìåòêè î ãîòîâíîñòè çàêàçà");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
private void ButtonIssuedOrder_Click(object sender, EventArgs e) private void ButtonIssuedOrder_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
int id = int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Çàêàç No{id}. Ìåíÿåòñÿ ñòàòóñ íà 'Âûäàí'", id); _logger.LogInformation("Çàêàç No{id}. Ìåíÿåòñÿ ñòàòóñ íà 'Âûäàí'", id);
try try
{ {
var operationResult = _orderLogic.DeliveryOrder(new var operationResult = _orderLogic.DeliveryOrder(new
OrderBindingModel OrderBindingModel
{ Id = id }); { Id = id });
if (!operationResult) if (!operationResult)
{ {
throw new Exception("Îøèáêà ïðè ñîõðàíåíèè.Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ."); throw new Exception("Îøèáêà ïðè ñîõðàíåíèè.Äîïîëíèòåëüíàÿ èíôîðìàöèÿ â ëîãàõ.");
} }
_logger.LogInformation("Çàêàç No{id} âûäàí", id); _logger.LogInformation("Çàêàç No{id} âûäàí", id);
LoadData(); LoadData();
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Îøèáêà îòìåòêè î âûäà÷è çàêàçà"); _logger.LogError(ex, "Îøèáêà îòìåòêè î âûäà÷è çàêàçà");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK,
MessageBoxIcon.Error); MessageBoxIcon.Error);
} }
} }
} }
private void ButtonRef_Click(object sender, EventArgs e) private void ButtonRef_Click(object sender, EventArgs e)
{ {
LoadData(); LoadData();
} }
private void ReportShopsToolStripMenuItem_Click(object sender, EventArgs e) private void ReportShopsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK) if (dialog.ShowDialog() == DialogResult.OK)
{ {
_reportLogic.SaveShopsToWordFile(new ReportBindingModel { FileName = dialog.FileName }); _reportLogic.SaveShopsToWordFile(new ReportBindingModel { FileName = dialog.FileName });
MessageBox.Show("Âûïîëíåíî", "Óñïåõ", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Âûïîëíåíî", "Óñïåõ", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }
} }
private void ShopPastriesToolStripMenuItem_Click(object sender, EventArgs e) private void ShopPastriesToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportShopPastries)); var service = Program.ServiceProvider?.GetService(typeof(FormReportShopPastries));
if (service is FormReportShopPastries form) if (service is FormReportShopPastries form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (service is FormReportOrders form) if (service is FormReportOrders form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
private void ShopsToolStripMenuItem_Click(object sender, EventArgs e) private void ShopsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormViewShops)); var service = Program.ServiceProvider?.GetService(typeof(FormViewShops));
if (service is FormViewShops form) if (service is FormViewShops form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
private void ButtonAddPastryInShop_Click(object sender, EventArgs e) private void ButtonAddPastryInShop_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormAddPastryInShop)); var service = Program.ServiceProvider?.GetService(typeof(FormAddPastryInShop));
if (service is FormAddPastryInShop form) if (service is FormAddPastryInShop form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
private void ButtonSellPastry_Click(object sender, EventArgs e) private void ButtonSellPastry_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormSellPastry)); var service = Program.ServiceProvider?.GetService(typeof(FormSellPastry));
if (service is FormSellPastry form) if (service is FormSellPastry form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
private void ClientsToolStripMenuItem_Click(object sender, EventArgs e) private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormViewClients)); var service = Program.ServiceProvider?.GetService(typeof(FormViewClients));
if (service is FormViewClients form) if (service is FormViewClients form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
}
private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormViewImplementers));
if (service is FormViewImplementers form)
{
form.ShowDialog();
}
}
private void DoWorkToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((
Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!,
_orderLogic);
MessageBox.Show("Ïðîöåññ îáðàáîòêè çàïóùåí", "Ñîîáùåíèå",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
} }

View File

@ -0,0 +1,118 @@
namespace ConfectioneryView
{
partial class FormViewImplementers
{
/// <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()
{
buttonRef = new Button();
buttonDel = new Button();
buttonUpd = new Button();
buttonAdd = new Button();
dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// buttonRef
//
buttonRef.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonRef.Location = new Point(626, 202);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(90, 37);
buttonRef.TabIndex = 9;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// buttonDel
//
buttonDel.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonDel.Location = new Point(626, 151);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(90, 33);
buttonDel.TabIndex = 8;
buttonDel.Text = "Удалить";
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// buttonUpd
//
buttonUpd.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonUpd.Location = new Point(626, 102);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(90, 34);
buttonUpd.TabIndex = 7;
buttonUpd.Text = "Изменить";
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += ButtonUpd_Click;
//
// buttonAdd
//
buttonAdd.Anchor = AnchorStyles.Top | AnchorStyles.Right;
buttonAdd.Location = new Point(626, 57);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(90, 30);
buttonAdd.TabIndex = 6;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridView
//
dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 12);
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(553, 302);
dataGridView.TabIndex = 5;
//
// FormViewImplementers
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(722, 319);
Controls.Add(buttonRef);
Controls.Add(buttonDel);
Controls.Add(buttonUpd);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Name = "FormViewImplementers";
Text = "Просмотр списка исполнителей";
Load += FormViewImplementers_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,111 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ConfectioneryView
{
public partial class FormViewImplementers : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
public FormViewImplementers(ILogger<FormViewImplementers> logger, IImplementerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormViewImplementers_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка исполнителей");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки исполнителей");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
if (service is FormImplementer form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
if (service is FormImplementer form)
{
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление исполнителя");
try
{
if (!_logic.Delete(new ImplementerBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления исполнителя");
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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

@ -41,13 +41,17 @@ namespace ConfectioneryView
services.AddTransient<IOrderStorage, OrderStorage>(); services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IPastryStorage, PastryStorage>(); services.AddTransient<IPastryStorage, PastryStorage>();
services.AddTransient<IClientStorage, ClientStorage>(); services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IShopStorage, ShopStorage>(); services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>(); services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>(); services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IPastryLogic, PastryLogic>(); services.AddTransient<IPastryLogic, PastryLogic>();
services.AddTransient<IReportLogic, ReportLogic>(); services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>(); services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IShopLogic, ShopLogic>(); services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>(); services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>(); services.AddTransient<AbstractSaveToWord, SaveToWord>();
@ -67,6 +71,8 @@ namespace ConfectioneryView
services.AddTransient<FormReportShopPastries>(); services.AddTransient<FormReportShopPastries>();
services.AddTransient<FormReportOrders>(); services.AddTransient<FormReportOrders>();
services.AddTransient<FormViewClients>(); services.AddTransient<FormViewClients>();
services.AddTransient<FormViewImplementers>();
services.AddTransient<FormImplementer>();
} }
} }
} }

View File

@ -0,0 +1,25 @@
using ConfectioneryDataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryContracts.BindingModels
{
/// <summary>
/// Исполнитель, выполняющий заказы
/// </summary>
public class ImplementerBindingModel : IImplementerModel
{
public int Id { get; set; }
public string ImplementerFIO { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public int WorkExperience { get; set; }
public int Qualification { get; set; }
}
}

View File

@ -8,6 +8,7 @@ namespace ConfectioneryContracts.BindingModels
public int Id { get; set; } public int Id { get; set; }
public int PastryId { get; set; } public int PastryId { get; set; }
public int ClientId { get; set; } public int ClientId { get; set; }
public int? ImplementerId { get; set; }
public int Count { get; set; } public int Count { get; set; }
public double Sum { get; set; } public double Sum { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;

View File

@ -0,0 +1,20 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.ViewModels;
namespace ConfectioneryContracts.BusinessLogicsContracts
{
public interface IImplementerLogic
{
List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model);
ImplementerViewModel? ReadElement(ImplementerSearchModel model);
bool Create(ImplementerBindingModel model);
bool Update(ImplementerBindingModel model);
bool Delete(ImplementerBindingModel model);
}
}

View File

@ -7,7 +7,8 @@ namespace ConfectioneryContracts.BusinessLogicsContracts
public interface IOrderLogic public interface IOrderLogic
{ {
List<OrderViewModel>? ReadList(OrderSearchModel? model); List<OrderViewModel>? ReadList(OrderSearchModel? model);
bool CreateOrder(OrderBindingModel model); OrderViewModel? ReadElement(OrderSearchModel 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

@ -0,0 +1,10 @@
namespace ConfectioneryContracts.BusinessLogicsContracts
{
public interface IWorkProcess
{
/// <summary>
/// Запуск работ
/// </summary>
void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic);
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryContracts.SearchModels
{
public class ImplementerSearchModel
{
public int? Id { get; set; }
public string? ImplementerFIO { get; set; }
public string? Password { get; set; }
}
}

View File

@ -1,4 +1,6 @@
namespace ConfectioneryContracts.SearchModels using ConfectioneryDataModels.Enums;
namespace ConfectioneryContracts.SearchModels
{ {
public class OrderSearchModel public class OrderSearchModel
{ {
@ -9,5 +11,9 @@
public DateTime? DateTo { get; set; } public DateTime? DateTo { get; set; }
public int? ClientId { get; set; } public int? ClientId { get; set; }
public int? ImplementerId { get; set; }
public OrderStatus? Status { get; set; }
} }
} }

View File

@ -0,0 +1,26 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryContracts.StoragesContract
{
public interface IImplementerStorage
{
List<ImplementerViewModel> GetFullList();
List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model);
ImplementerViewModel? GetElement(ImplementerSearchModel model);
ImplementerViewModel? Insert(ImplementerBindingModel model);
ImplementerViewModel? Update(ImplementerBindingModel model);
ImplementerViewModel? Delete(ImplementerBindingModel model);
}
}

View File

@ -0,0 +1,30 @@
using ConfectioneryDataModels;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryContracts.ViewModels
{
/// <summary>
/// Исполнитель, выполняющий заказы
/// </summary>
public class ImplementerViewModel : IImplementerModel
{
public int Id { get; set; }
[DisplayName("ФИО исполнителя")]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Пароль")]
public string Password { get; set; } = string.Empty;
[DisplayName("Стаж работы")]
public int WorkExperience { get; set; }
[DisplayName("Квалификация")]
public int Qualification { get; set; }
}
}

View File

@ -17,10 +17,15 @@ namespace ConfectioneryContracts.ViewModels
public int ClientId { get; set; } public int ClientId { get; set; }
[DisplayName("Фамилия клиента")] public int? ImplementerId { get; set; }
[DisplayName("Фамилия клиента")]
public string ClientFIO { get; set; } = string.Empty; public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Изделие")] [DisplayName("Фамилия исполнителя")]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Изделие")]
public string PastryName { get; set; } = string.Empty; public string PastryName { get; set; } = string.Empty;
[DisplayName("Количество")] [DisplayName("Количество")]

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfectioneryDataModels
{
public interface IImplementerModel : IId
{
string ImplementerFIO { get; }
string Password { get; }
int WorkExperience { get; }
int Qualification { get; }
}
}

View File

@ -6,6 +6,7 @@ namespace ConfectioneryDataModels.Models
{ {
int PastryId { get; } int PastryId { get; }
int ClientId { get; } int ClientId { get; }
int? ImplementerId { get; }
int Count { get; } int Count { get; }
double Sum { get; } double Sum { get; }
OrderStatus Status { get; } OrderStatus Status { get; }

View File

@ -28,5 +28,6 @@ namespace ConfectioneryDatabaseImplement
public virtual DbSet<ShopPastry> ShopPastries { set; get; } public virtual DbSet<ShopPastry> ShopPastries { set; get; }
public virtual DbSet<Client> Clients { set; get; } public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; }
} }
} }

View File

@ -0,0 +1,60 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels;
using System.ComponentModel.DataAnnotations.Schema;
namespace ConfectioneryDatabaseImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
public string ImplementerFIO { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty;
public int WorkExperience { get; private set; }
public int Qualification { get; private set; }
[ForeignKey("ImplementerId")]
public virtual List<Order> Orders { get; private set; } = new();
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new()
{
Id = model.Id,
Password = model.Password,
Qualification = model.Qualification,
ImplementerFIO = model.ImplementerFIO,
WorkExperience = model.WorkExperience,
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
Password = model.Password;
Qualification = model.Qualification;
ImplementerFIO = model.ImplementerFIO;
WorkExperience = model.WorkExperience;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Password = Password,
Qualification = Qualification,
ImplementerFIO = ImplementerFIO,
WorkExperience = WorkExperience,
};
}
}

View File

@ -0,0 +1,90 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.StoragesContract;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDatabaseImplement.Models;
namespace ConfectioneryDatabaseImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
using var context = new ConfectioneryDatabase();
var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
context.Implementers.Remove(res);
context.SaveChanges();
}
return res?.GetViewModel;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
using var context = new ConfectioneryDatabase();
if (model.Id.HasValue)
return context.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
if (model.ImplementerFIO != null && model.Password != null)
return context.Implementers
.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO)
&& x.Password.Equals(model.Password))
?.GetViewModel;
if (model.ImplementerFIO != null)
return context.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel;
return null;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (model == null)
{
return new();
}
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
if (model.ImplementerFIO != null) // На случай если фио не будет уникальным (по заданию оно уникально)
{
using var context = new ConfectioneryDatabase();
return context.Implementers
.Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
public List<ImplementerViewModel> GetFullList()
{
using var context = new ConfectioneryDatabase();
return context.Implementers.Select(x => x.GetViewModel).ToList();
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
using var context = new ConfectioneryDatabase();
var res = Implementer.Create(model);
if (res != null)
{
context.Implementers.Add(res);
context.SaveChanges();
}
return res?.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
using var context = new ConfectioneryDatabase();
var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
res.Update(model);
context.SaveChanges();
}
return res?.GetViewModel;
}
}
}

View File

@ -0,0 +1,257 @@
// <auto-generated />
using System;
using ConfectioneryDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace ConfectioneryDatabaseImplement.Migrations
{
[DbContext(typeof(ConfectioneryDatabase))]
[Migration("20230306113501_implementer")]
partial class implementer
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("PastryId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("PastryId");
b.ToTable("Orders");
});
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Pastry", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("PastryName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Pastries");
});
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.PastryComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("PastryId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("PastryId");
b.ToTable("PastryComponents");
});
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Order", b =>
{
b.HasOne("ConfectioneryDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ConfectioneryDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", "Pastry")
.WithMany("Orders")
.HasForeignKey("PastryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Pastry");
});
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.PastryComponent", b =>
{
b.HasOne("ConfectioneryDatabaseImplement.Models.Component", "Component")
.WithMany("PastryComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", "Pastry")
.WithMany("Components")
.HasForeignKey("PastryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Pastry");
});
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Client", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Component", b =>
{
b.Navigation("PastryComponents");
});
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Pastry", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,67 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ConfectioneryDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class implementer : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "ImplementerId",
table: "Orders",
type: "int",
nullable: true);
migrationBuilder.CreateTable(
name: "Implementers",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ImplementerFIO = table.Column<string>(type: "nvarchar(max)", nullable: false),
Password = table.Column<string>(type: "nvarchar(max)", nullable: false),
WorkExperience = table.Column<int>(type: "int", nullable: false),
Qualification = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Implementers", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
migrationBuilder.AddForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
table: "Orders",
column: "ImplementerId",
principalTable: "Implementers",
principalColumn: "Id");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
table: "Orders");
migrationBuilder.DropTable(
name: "Implementers");
migrationBuilder.DropIndex(
name: "IX_Orders_ImplementerId",
table: "Orders");
migrationBuilder.DropColumn(
name: "ImplementerId",
table: "Orders");
}
}
}

View File

@ -10,17 +10,17 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace ConfectioneryDatabaseImplement.Migrations namespace ConfectioneryDatabaseImplement.Migrations
{ {
[DbContext(typeof(ConfectioneryDatabase))] [DbContext(typeof(ConfectioneryDatabase))]
partial class ConfectioneryDatabaseModelSnapshot : ModelSnapshot partial class ConfectioneryDatabaseModelSnapshot : ModelSnapshot
{ {
protected override void BuildModel(ModelBuilder modelBuilder) protected override void BuildModel(ModelBuilder modelBuilder)
{ {
#pragma warning disable 612, 618 #pragma warning disable 612, 618
modelBuilder modelBuilder
.HasAnnotation("ProductVersion", "7.0.3") .HasAnnotation("ProductVersion", "7.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128); .HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Client", b => modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Client", b =>
{ {
@ -28,7 +28,7 @@ namespace ConfectioneryDatabaseImplement.Migrations
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
.HasColumnType("int"); .HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id")); SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO") b.Property<string>("ClientFIO")
.IsRequired() .IsRequired()
@ -59,21 +59,48 @@ namespace ConfectioneryDatabaseImplement.Migrations
.IsRequired() .IsRequired()
.HasColumnType("nvarchar(max)"); .HasColumnType("nvarchar(max)");
b.Property<double>("Cost") b.Property<double>("Cost")
.HasColumnType("float"); .HasColumnType("float");
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("Components"); b.ToTable("Components");
}); });
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Order", b => modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Implementer", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
.HasColumnType("int"); .HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id")); SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId") b.Property<int>("ClientId")
.HasColumnType("int"); .HasColumnType("int");
@ -81,75 +108,80 @@ namespace ConfectioneryDatabaseImplement.Migrations
b.Property<int>("Count") b.Property<int>("Count")
.HasColumnType("int"); .HasColumnType("int");
b.Property<DateTime>("DateCreate") b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2"); .HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement") b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2"); .HasColumnType("datetime2");
b.Property<int>("PastryId") b.Property<int?>("ImplementerId")
.HasColumnType("int"); .HasColumnType("int");
b.Property<int>("Status") b.Property<int>("PastryId")
.HasColumnType("int"); .HasColumnType("int");
b.Property<double>("Sum") b.Property<int>("Status")
.HasColumnType("float"); .HasColumnType("int");
b.HasKey("Id"); b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ClientId"); b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("PastryId"); b.HasIndex("PastryId");
b.ToTable("Orders"); b.ToTable("Orders");
}); });
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Pastry", b => modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Pastry", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
.HasColumnType("int"); .HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id")); SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("PastryName") b.Property<string>("PastryName")
.IsRequired() .IsRequired()
.HasColumnType("nvarchar(max)"); .HasColumnType("nvarchar(max)");
b.Property<double>("Price") b.Property<double>("Price")
.HasColumnType("float"); .HasColumnType("float");
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("Pastries"); b.ToTable("Pastries");
}); });
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.PastryComponent", b => modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.PastryComponent", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
.ValueGeneratedOnAdd() .ValueGeneratedOnAdd()
.HasColumnType("int"); .HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id")); SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId") b.Property<int>("ComponentId")
.HasColumnType("int"); .HasColumnType("int");
b.Property<int>("Count") b.Property<int>("Count")
.HasColumnType("int"); .HasColumnType("int");
b.Property<int>("PastryId") b.Property<int>("PastryId")
.HasColumnType("int"); .HasColumnType("int");
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("ComponentId"); b.HasIndex("ComponentId");
b.HasIndex("PastryId"); b.HasIndex("PastryId");
b.ToTable("PastryComponents"); b.ToTable("PastryComponents");
}); });
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Shop", b => modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Shop", b =>
{ {
@ -217,6 +249,10 @@ namespace ConfectioneryDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.HasOne("ConfectioneryDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", "Pastry") b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", "Pastry")
.WithMany("Orders") .WithMany("Orders")
.HasForeignKey("PastryId") .HasForeignKey("PastryId")
@ -225,6 +261,8 @@ namespace ConfectioneryDatabaseImplement.Migrations
b.Navigation("Client"); b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Pastry"); b.Navigation("Pastry");
}); });
@ -236,11 +274,11 @@ namespace ConfectioneryDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", "Pastry") b.HasOne("ConfectioneryDatabaseImplement.Models.Pastry", "Pastry")
.WithMany("Components") .WithMany("Components")
.HasForeignKey("PastryId") .HasForeignKey("PastryId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.Navigation("Component"); b.Navigation("Component");
@ -283,9 +321,14 @@ namespace ConfectioneryDatabaseImplement.Migrations
b.Navigation("PastryComponents"); b.Navigation("PastryComponents");
}); });
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Pastry", b => modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Implementer", b =>
{ {
b.Navigation("Components"); b.Navigation("Orders");
});
modelBuilder.Entity("ConfectioneryDatabaseImplement.Models.Pastry", b =>
{
b.Navigation("Components");
b.Navigation("Orders"); b.Navigation("Orders");
@ -297,6 +340,6 @@ namespace ConfectioneryDatabaseImplement.Migrations
b.Navigation("ShopPastries"); b.Navigation("ShopPastries");
}); });
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
} }
} }

View File

@ -24,7 +24,9 @@ namespace ConfectioneryDatabaseImplement.Models
[Required] [Required]
public int ClientId { get; private set; } public int ClientId { get; private set; }
[Required] public int? ImplementerId { get; private set; }
[Required]
public int Count { get; private set; } public int Count { get; private set; }
[Required] [Required]
@ -40,9 +42,10 @@ namespace ConfectioneryDatabaseImplement.Models
public Pastry Pastry { get; private set; } public Pastry Pastry { get; private set; }
public Client Client { get; private set; } public Client Client { get; private set; }
public Implementer? Implementer { get; private set; }
public static Order? Create(OrderBindingModel? model) public static Order? Create(OrderBindingModel? model)
{ {
if (model == null) if (model == null)
@ -57,6 +60,7 @@ namespace ConfectioneryDatabaseImplement.Models
Sum = model.Sum, Sum = model.Sum,
Status = model.Status, Status = model.Status,
DateCreate = model.DateCreate, DateCreate = model.DateCreate,
ImplementerId = model.ImplementerId,
DateImplement = model.DateImplement, DateImplement = model.DateImplement,
Id = model.Id, Id = model.Id,
}; };
@ -74,6 +78,7 @@ namespace ConfectioneryDatabaseImplement.Models
Status = model.Status; Status = model.Status;
DateCreate = model.DateCreate; DateCreate = model.DateCreate;
DateImplement = model.DateImplement; DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
Id = model.Id; Id = model.Id;
} }
public OrderViewModel GetViewModel public OrderViewModel GetViewModel
@ -86,12 +91,15 @@ namespace ConfectioneryDatabaseImplement.Models
PastryName = context.Pastries.FirstOrDefault(x => x.Id == PastryId)?.PastryName ?? string.Empty, PastryName = context.Pastries.FirstOrDefault(x => x.Id == PastryId)?.PastryName ?? string.Empty,
// ?????? // ??????
ClientFIO = Client?.ClientFIO ?? context.Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty, ClientFIO = Client?.ClientFIO ?? context.Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty,
ImplementerFIO = Implementer?.ImplementerFIO ??
context.Implementers.FirstOrDefault(x => x.Id == ImplementerId)?.ImplementerFIO ?? string.Empty,
PastryId = PastryId, PastryId = PastryId,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,
DateCreate = DateCreate, DateCreate = DateCreate,
DateImplement = DateImplement, DateImplement = DateImplement,
ImplementerId = ImplementerId,
Id = Id, Id = Id,
}; };
} }

View File

@ -4,7 +4,6 @@ using ConfectioneryContracts.StoragesContract;
using ConfectioneryContracts.ViewModels; using ConfectioneryContracts.ViewModels;
using ConfectioneryDatabaseImplement.Models; using ConfectioneryDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.Security.Cryptography.X509Certificates;
namespace ConfectioneryDatabaseImplement.Implements namespace ConfectioneryDatabaseImplement.Implements
{ {
@ -13,7 +12,10 @@ namespace ConfectioneryDatabaseImplement.Implements
public OrderViewModel? Delete(OrderBindingModel model) public OrderViewModel? Delete(OrderBindingModel model)
{ {
using var context = new ConfectioneryDatabase(); using var context = new ConfectioneryDatabase();
var element = context.Orders.Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id); var element = context.Orders
.Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => x.Id == model.Id);
if (element != null) if (element != null)
{ {
context.Orders.Remove(element); context.Orders.Remove(element);
@ -26,41 +28,52 @@ namespace ConfectioneryDatabaseImplement.Implements
public OrderViewModel? GetElement(OrderSearchModel model) public OrderViewModel? GetElement(OrderSearchModel model)
{ {
using var context = new ConfectioneryDatabase(); using var context = new ConfectioneryDatabase();
if (!model.Id.HasValue) // Находим первого либо по айди заказа, либо по айди исполнителя, либо по айди исполнителя и статусу заказа, исходя из того что есть в модели
{ return context.Orders
return null; .Include(x => x.Client)
} .Include(x => x.Implementer)
return context.Orders .FirstOrDefault(x =>
.Include(x => x.Client) (!model.Status.HasValue || model.Status.HasValue && x.Status == model.Status) &&
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId ||
?.GetViewModel; model.Id.HasValue && x.Id == model.Id
)
?.GetViewModel;
} }
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{ {
if (model.Id.HasValue) if (model.Id.HasValue)
{ {
var result = GetElement(model); var result = GetElement(model);
return result != null ? new() { result } : new(); return result != null ? new() { result } : new();
} }
using var context = new ConfectioneryDatabase();
if (model.DateFrom.HasValue && model.DateTo.HasValue) // если не ищем по айдишнику, значит ищем по диапазону дат using var context = new ConfectioneryDatabase();
{ IQueryable<Order>? queryWhere = null;
return context.Orders
.Where(x => model.DateFrom <= x.DateCreate.Date && x.DateCreate <= model.DateTo) if (model.DateFrom.HasValue && model.DateTo.HasValue) // если не ищем по айдишнику, значит ищем по диапазону дат
.Include(x => x.Client) {
queryWhere = context.Orders
.Where(x => model.DateFrom <= x.DateCreate.Date &&
x.DateCreate.Date <= model.DateTo);
}
else if (model.Status.HasValue)
{
queryWhere = context.Orders.Where(x => x.Status == model.Status);
}
else if (model.ClientId.HasValue)
{
queryWhere = context.Orders.Where(x => x.ClientId == model.ClientId);
}
else
{
return new();
}
return queryWhere
.Include(x => x.Client)
.Include(x => x.Implementer)
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
}
if (model.ClientId.HasValue)
{
return context.Orders
.Where(x => x.Client.Id == model.ClientId)
.Include(x => x.Client)
.Select(x => x.GetViewModel)
.ToList();
}
return new();
} }
public List<OrderViewModel> GetFullList() public List<OrderViewModel> GetFullList()
@ -68,7 +81,8 @@ namespace ConfectioneryDatabaseImplement.Implements
using var context = new ConfectioneryDatabase(); using var context = new ConfectioneryDatabase();
return context.Orders return context.Orders
.Include(x => x.Client) .Include(x => x.Client)
.Select(x => x.GetViewModel) .Include(x => x.Implementer)
.Select(x => x.GetViewModel)
.ToList(); .ToList();
} }
@ -90,7 +104,8 @@ namespace ConfectioneryDatabaseImplement.Implements
using var context = new ConfectioneryDatabase(); using var context = new ConfectioneryDatabase();
var order = context.Orders var order = context.Orders
.Include(x => x.Client) .Include(x => x.Client)
.FirstOrDefault(x => x.Id == model.Id); .Include(x => x.Implementer)
.FirstOrDefault(x => x.Id == model.Id);
if (order == null) if (order == null)
{ {
return null; return null;

View File

@ -0,0 +1,107 @@
using ConfectioneryContracts.BindingModels;
using ConfectioneryContracts.BusinessLogicsContracts;
using ConfectioneryContracts.SearchModels;
using ConfectioneryContracts.ViewModels;
using ConfectioneryDataModels.Enums;
using Microsoft.AspNetCore.Mvc;
namespace ConfectioneryRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ImplementerController : Controller
{
private readonly ILogger _logger;
private readonly IOrderLogic _order;
private readonly IImplementerLogic _logic;
public ImplementerController(IOrderLogic order, IImplementerLogic logic, ILogger<ImplementerController> logger)
{
_logger = logger;
_order = order;
_logic = logic;
}
[HttpGet]
public ImplementerViewModel? Login(string login, string password)
{
try
{
return _logic.ReadElement(new ImplementerSearchModel
{
ImplementerFIO = login,
Password = password
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка авторизации сотрудника");
throw;
}
}
[HttpGet]
public List<OrderViewModel>? GetNewOrders()
{
try
{
return _order.ReadList(new OrderSearchModel
{
Status = OrderStatus.Принят
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения новых заказов");
throw;
}
}
[HttpGet]
public OrderViewModel? GetImplementerOrder(int implementerId)
{
try
{
return _order.ReadElement(new OrderSearchModel
{
ImplementerId = implementerId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения текущего заказа исполнителя");
throw;
}
}
[HttpPost]
public void TakeOrderInWork(OrderBindingModel model)
{
try
{
_order.TakeOrderInWork(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка перевода заказа с №{Id} в работу", model.Id);
throw;
}
}
[HttpPost]
public void FinishOrder(OrderBindingModel model)
{
try
{
_order.FinishOrder(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа с №{Id}", model.Id);
throw;
}
}
}
}