Compare commits

...

2 Commits

Author SHA1 Message Date
artiogf
23837db2a6 Lab6_Main 2023-06-14 23:31:18 +04:00
artiogf
da8011e379 Lab6_Main 2023-06-14 23:28:03 +04:00
50 changed files with 2682 additions and 433 deletions

View File

@ -0,0 +1,128 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopBusinessLogic.BusinessLogics
{
public class ImplementerLogic : IImplementerLogic
{
private readonly ILogger _logger;
private readonly IImplementerStorage _implementerStorage;
public ImplementerLogic(ILogger<IImplementerLogic> 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. ImplementerFIO:{ImplementerFIO}.Password:{Password}.Id:{ Id}", model?.ImplementerFIO, model?.Password?.Length, 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. ImplementerFIO:{ImplementerFIO}.Password:{Password}.Id:{ Id}", model?.ImplementerFIO, model?.Password?.Length, 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 (string.IsNullOrEmpty(model.ImplementerFIO))
{
throw new ArgumentNullException("Нет ФИО исполнителя", nameof(model.ImplementerFIO));
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Нет пароля исполнителя", nameof(model.Password));
}
if (model.WorkExperience < 0)
{
throw new ArgumentNullException("Стаж должен быть больше 0", nameof(model.WorkExperience));
}
if (model.Qualification < 0)
{
throw new ArgumentNullException("Квалификация должна быть положительной", nameof(model.Qualification));
}
_logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}.Password:{Password}.WorkExperience:{WorkExperience}.Qualification:{Qualification}.Id: { Id}",
model.ImplementerFIO, model.Password, model.WorkExperience, model.Qualification, model.Id);
var element = _implementerStorage.GetElement(new ImplementerSearchModel
{
ImplementerFIO = model.ImplementerFIO
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Исполнитель с таким ФИО уже есть");
}
}
}
}

View File

@ -15,128 +15,152 @@ namespace CarpentryWorkshopBusinessLogic.BusinessLogics
{
public class OrderLogic : IOrderLogic
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
{
_logger = logger;
_orderStorage = orderStorage;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("ReadList. Id:{ Id}", model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool CreateOrder(OrderBindingModel model)
{
_orderStorage.Insert(new OrderBindingModel
{
WoodId = model.WoodId,
WoodName = model.WoodName,
ClientId = model.ClientId,
ClientFIO = model.ClientFIO,
Count = model.Count,
Sum = model.Sum,
Status = OrderStatus.Принят,
DateCreate = DateTime.Now
}); ;
return true;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
var order = _orderStorage.GetElement(new OrderSearchModel
{
Id = model.Id
});
if (order == null)
{
throw new Exception("Элемент не найден");
}
if (order.Status.ToString() != "Принят")
{
throw new Exception("Заказ не в статусе \"Принят\"");
}
_orderStorage.Update(new OrderBindingModel
{
Id = order.Id,
WoodId = order.WoodId,
WoodName = order.WoodName,
ClientId = order.ClientId,
ClientFIO = order.ClientFIO,
Count = order.Count,
Sum = order.Sum,
DateCreate = order.DateCreate,
Status = OrderStatus.Выполняется
});
return true;
}
public bool FinishOrder(OrderBindingModel model)
{
var order = _orderStorage.GetElement(new OrderSearchModel
{
Id = model.Id
});
if (order == null)
{
throw new Exception("Не найден заказ");
}
if (order.Status.ToString() != "Выполняется")
{
throw new Exception("Заказ не в статусе \"Выполняется\"");
}
_orderStorage.Update(new OrderBindingModel
{
Id = order.Id,
WoodId = order.WoodId,
WoodName = order.WoodName,
ClientId = order.ClientId,
ClientFIO = order.ClientFIO,
Count = order.Count,
Sum = order.Sum,
DateCreate = order.DateCreate,
DateImplement = DateTime.Now,
Status = OrderStatus.Готов
});
return true;
}
public bool DeliveryOrder(OrderBindingModel model)
{
var order = _orderStorage.GetElement(new OrderSearchModel
{
Id = model.Id
});
if (order == null)
{
throw new Exception("Не найден заказ");
}
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
if (order.Status.ToString() != "Готов")
{
throw new Exception("Заказ не в статусе \"Готов\"");
}
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
{
_logger = logger;
_orderStorage = orderStorage;
}
_orderStorage.Update(new OrderBindingModel
{
Id = order.Id,
WoodId = order.WoodId,
WoodName = order.WoodName,
ClientId = order.ClientId,
ClientFIO = order.ClientFIO,
Count = order.Count,
Sum = order.Sum,
DateCreate = order.DateCreate,
DateImplement = order.DateImplement,
Status = OrderStatus.Выдан
});
return true;
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
}
}
if (model.Status != OrderStatus.Неизвестен)
{
_logger.LogWarning("Insert operation failed. Order status incorrect.");
return false;
}
model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null)
{
model.Status = OrderStatus.Неизвестен;
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus)
{
var vmodel = _orderStorage.GetElement(new() { Id = model.Id });
if (vmodel == null)
{
throw new ArgumentNullException(nameof(model));
}
if ((int)vmodel.Status + 1 != (int)newStatus)
{
throw new InvalidOperationException($"Попытка перевести заказ не в следующий статус: " +
$"Текущий статус: {vmodel.Status} \n" +
$"Планируемый статус: {newStatus} \n" +
$"Доступный статус: {(OrderStatus)((int)vmodel.Status + 1)}");
}
model.Status = newStatus;
model.DateCreate = vmodel.DateCreate;
if (model.DateImplement == null)
model.DateImplement = vmodel.DateImplement;
if (vmodel.ImplementerId.HasValue)
model.ImplementerId = vmodel.ImplementerId;
model.WoodId = vmodel.WoodId;
model.Sum = vmodel.Sum;
model.Count = vmodel.Count;
if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выполняется);
}
public bool DeliveryOrder(OrderBindingModel model)
{
model.DateImplement = DateTime.Now;
return StatusUpdate(model, OrderStatus.Готов);
}
public bool FinishOrder(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выдан);
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("Order. OrderId:{Id}", model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
private bool CheckModel(OrderBindingModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (model.Count <= 0)
{
throw new ArgumentException("Количество изделий в заказе должно быть больше 0", nameof(model.Count));
}
if (model.Sum <= 0)
{
throw new ArgumentException("Суммарная стоимость заказа должна быть больше 0", nameof(model.Sum));
}
if (model.DateCreate > model.DateImplement)
{
throw new ArgumentException("Время создания заказа не может быть больше времени его выполнения", nameof(model.DateImplement));
}
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,138 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Enums;
using Microsoft.Extensions.Logging;
namespace CarpentryWorkshopBusinessLogic.BusinessLogics
{
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 { Statuses = new() { OrderStatus.Принят } });
if (orders == null || orders.Count == 0)
{
_logger.LogWarning("DoWork. Orders is null or empty");
return;
}
_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, orders);
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.DeliveryOrder(new OrderBindingModel
{
Id = order.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;
}
}
});
}
/// <summary>
/// Ищем заказ, которые уже в работе (вдруг исполнителя прервали)
/// </summary>
/// <param name="implementer"></param>
/// <returns></returns>
private async Task RunOrderInWork(ImplementerViewModel implementer, List<OrderViewModel> allOrders)
{
if (_orderLogic == null || implementer == null || allOrders == null || allOrders.Count == 0)
{
return;
}
try
{
var runOrder = await Task.Run(() => allOrders.FirstOrDefault(x => x.ImplementerId == implementer.Id && x.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.DeliveryOrder(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

@ -134,7 +134,6 @@ namespace CarpentryWorkshopClientApp.Controllers
APIClient.PostRequest("api/main/createorder", new OrderBindingModel
{
ClientId = APIClient.Client.Id,
ClientFIO = APIClient.Client.ClientFIO,
WoodId = wood,
WoodName = prod.WoodName,
Count = count,

View File

@ -0,0 +1,22 @@
using CarpentryWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.BindingModels
{
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

@ -10,13 +10,15 @@ namespace CarpentryWorkshopContracts.BindingModels
{
public class OrderBindingModel : IOrderModel
{
public int Id { get; set; }
public int WoodId { get; set; }
public int ClientId { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; set; } = DateTime.Now;
public DateTime? DateImplement { get; set; }
}
public int Id { get; set; }
public int WoodId { get; set; }
public string WoodName { get; set; } = string.Empty;
public int ClientId { get; set; }
public int? ImplementerId { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; set; } = DateTime.Now;
public DateTime? DateImplement { get; set; }
}
}

View File

@ -0,0 +1,24 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.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

@ -11,11 +11,12 @@ namespace CarpentryWorkshopContracts.BusinessLogicsContracts
{
public interface IOrderLogic
{
List<OrderViewModel>? ReadList(OrderSearchModel? model);
bool CreateOrder(OrderBindingModel model);
bool TakeOrderInWork(OrderBindingModel model);
bool FinishOrder(OrderBindingModel model);
bool DeliveryOrder(OrderBindingModel model);
List<OrderViewModel>? ReadList(OrderSearchModel? model);
OrderViewModel? ReadElement(OrderSearchModel model);
bool CreateOrder(OrderBindingModel model);
bool TakeOrderInWork(OrderBindingModel model);
bool FinishOrder(OrderBindingModel model);
bool DeliveryOrder(OrderBindingModel model);
}
}
}

View File

@ -0,0 +1,10 @@
namespace CarpentryWorkshopContracts.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 CarpentryWorkshopContracts.SearchModels
{
public class ImplementerSearchModel
{
public int? Id { get; set; }
public string? ImplementerFIO { get; set; }
public string? Password { get; set; }
}
}

View File

@ -1,4 +1,5 @@
using System;
using CarpentryWorkshopDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -8,9 +9,12 @@ namespace CarpentryWorkshopContracts.SearchModels
{
public class OrderSearchModel
{
public int? Id { get; set; }
public int? ClientId { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
}
public int? Id { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public int? ClientId { get; set; }
public int? ImplementerId { get; set; }
public List<OrderStatus>? Statuses { get; set; }
}
}

View File

@ -0,0 +1,26 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.StoragesContracts
{
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,26 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopContracts.ViewModels
{
public class ImplementerViewModel
{
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

@ -11,24 +11,33 @@ namespace CarpentryWorkshopContracts.ViewModels
{
public class OrderViewModel : IOrderModel
{
[DisplayName("Номер")]
public int Id { get; set; }
public int WoodId { get; set; }
[DisplayName("Изделие")]
public string WoodName { get; set; } = string.Empty;
public int ClientId { get; set; }
[DisplayName("Номер")]
public int Id { get; set; }
public int WoodId { get; set; }
[DisplayName("Клиент")]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Количество")]
public int Count { get; set; }
[DisplayName("Сумма")]
public double Sum { get; set; }
[DisplayName("Статус")]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")]
public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")]
public DateTime? DateImplement { get; set; }
}
[DisplayName("Изделие")]
public string WoodName { get; set; } = string.Empty;
public int ClientId { get; set; }
public int? ImplementerId { get; set; }
[DisplayName("ФИО клиента")]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Фамилия исполнителя")]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Количество")]
public int Count { get; set; }
[DisplayName("Сумма")]
public double Sum { get; set; }
[DisplayName("Статус")]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")]
public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")]
public DateTime? DateImplement { get; set; }
}
}

View File

@ -11,6 +11,6 @@ namespace CarpentryWorkshopContracts.ViewModels
public string WoodName { get; set; } = string.Empty;
public double Sum { get; set; }
public string Status { get; set; }
}
public string Status { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,13 @@
namespace CarpentryWorkshopDataModels.Models
{
public interface IImplementerModel : IId
{
string ImplementerFIO { get; }
string Password { get; }
int WorkExperience { get; }
int Qualification { get; }
}
}

View File

@ -9,12 +9,13 @@ namespace CarpentryWorkshopDataModels.Models
{
public interface IOrderModel : IId
{
int WoodId { get; }
int ClientId { get; }
int WoodId { get; }
int? ImplementerId { get; }
string WoodName { get; }
int Count { get; }
double Sum { get; }
OrderStatus Status { get; }
DateTime DateCreate { get; }
DateTime? DateImplement { get; }
}
double Sum { get; }
OrderStatus Status { get; }
DateTime DateCreate { get; }
DateTime? DateImplement { get; }
}
}

View File

@ -9,7 +9,7 @@ namespace CarpentryWorkshopDatabaseImplement
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-VTSC074\SQLEXPRESS;Initial Catalog=CarpentryWorkshopDatabaseFullLab51;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-VTSC074\SQLEXPRESS;Initial Catalog=CarpentryWorkshopDatabaseFullLab6;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
@ -18,5 +18,6 @@ namespace CarpentryWorkshopDatabaseImplement
public virtual DbSet<Wood> Woods { set; get; }
public virtual DbSet<WoodComponent> WoodComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; }
}
public virtual DbSet<Implementer> Implementers { set; get; }
}
}

View File

@ -0,0 +1,84 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopDatabaseImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
using var context = new CarpentryWorkshopDatabase();
var implementer = context.Implementers.FirstOrDefault(rec => rec.Id == model.Id);
if (implementer != null)
{
context.Implementers.Remove(implementer);
context.SaveChanges();
return implementer.GetViewModel;
}
return null;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue)
{
return null;
}
using var context = new CarpentryWorkshopDatabase();
return context.Implementers.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ImplementerFIO) && x.ImplementerFIO == model.ImplementerFIO && (!string.IsNullOrEmpty(model.Password) ? x.Password == model.Password : true)) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
return new();
}
using var context = new CarpentryWorkshopDatabase();
return context.Implementers.Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO)).Select(x => x.GetViewModel).ToList();
}
public List<ImplementerViewModel> GetFullList()
{
using var context = new CarpentryWorkshopDatabase();
return context.Implementers.Select(x => x.GetViewModel).ToList();
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
var newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
using var context = new CarpentryWorkshopDatabase();
context.Implementers.Add(newImplementer);
context.SaveChanges();
return newImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
using var context = new CarpentryWorkshopDatabase();
var implementer = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (implementer == null)
{
return null;
}
implementer.Update(model);
context.SaveChanges();
return implementer.GetViewModel;
}
}
}

View File

@ -9,98 +9,139 @@ namespace CarpentryWorkshopDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public List<OrderViewModel> GetFullList()
{
using var context = new CarpentryWorkshopDatabase();
return context.Orders
.Include(x => x.Wood)
.Include(x => x.Client)
.Select(x => x.GetViewModel)
.ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.ClientId.HasValue)
{
return new();
}
using var context = new CarpentryWorkshopDatabase();
if (model.ClientId.HasValue)
{
return context.Orders
.Include(x => x.Wood)
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new CarpentryWorkshopDatabase();
var element = context.Orders
.Include(x => x.Wood)
.Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new CarpentryWorkshopDatabase();
return context.Orders
.Include(x => x.Client)
.Where(x => x.ClientId == model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
}
if (model.DateFrom.HasValue)
{
return context.Orders.Include(x => x.Wood)
.Include(x => x.Implementer)
.FirstOrDefault(x =>
(model.Statuses == null || model.Statuses != null && model.Statuses.Contains(x.Status)) &&
model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId ||
model.Id.HasValue && x.Id == model.Id
)
?.GetViewModel;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (model.Id.HasValue)
{
var result = GetElement(model);
return result != null ? new() { result } : new();
}
using var context = new CarpentryWorkshopDatabase();
IQueryable<Order>? queryWhere = null;
if (model.DateFrom.HasValue && model.DateTo.HasValue)
{
queryWhere = context.Orders
.Where(x => model.DateFrom <= x.DateCreate.Date &&
x.DateCreate.Date <= model.DateTo);
}
else if (model.Statuses != null)
{
queryWhere = context.Orders.Where(x => model.Statuses.Contains(x.Status));
}
else if (model.ClientId.HasValue)
{
queryWhere = context.Orders.Where(x => x.ClientId == model.ClientId);
}
else
{
return new();
}
return queryWhere
.Include(x => x.Client)
.Where(x => (x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo))
.Select(x => x.GetViewModel)
.ToList();
}
return context.Orders.Include(x => x.Wood)
.Include(x => x.Client)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (model.Id == null && !model.Id.HasValue)
{
return null;
}
using var context = new CarpentryWorkshopDatabase();
return context.Orders.Include(x => x.Wood).Include(x => x.Client)
.FirstOrDefault(x => (model.Id != null && x.Id == model.Id) || (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
.Include(x => x.Implementer)
.Select(x => x.GetViewModel)
.ToList();
}
public List<OrderViewModel> GetFullList()
{
using var context = new CarpentryWorkshopDatabase();
return context.Orders
.Include(x => x.Wood)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Select(x => x.GetViewModel).ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
using var context = new CarpentryWorkshopDatabase();
context.Orders.Add(newOrder);
context.SaveChanges();
return context.Orders
.Include(x => x.Wood)
.Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => x.Id == newOrder.Id)
?.GetViewModel;
}
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new CarpentryWorkshopDatabase();
var element = context.Orders.Include(x => x.Wood).Include(x => x.Client).FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
//
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new CarpentryWorkshopDatabase();
var order = context.Orders.Include(x => x.Wood).Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return order.GetViewModel;
}
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new CarpentryWorkshopDatabase();
var order = context.Orders
.Include(x => x.Wood)
.Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return order.GetViewModel;
}
}
}

View File

@ -12,7 +12,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace CarpentryWorkshopDatabaseImplement.Migrations
{
[DbContext(typeof(CarpentryWorkshopDatabase))]
[Migration("20230420093100_InitialCreate")]
[Migration("20230614192918_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
@ -70,7 +70,7 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
b.ToTable("Components");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b =>
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@ -78,10 +78,33 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
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("CarpentryWorkshopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
@ -94,6 +117,9 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
@ -111,6 +137,8 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("WoodId");
b.ToTable("Orders");
@ -164,17 +192,27 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b =>
{
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", null)
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Wood", null)
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Order")
.HasForeignKey("ImplementerId");
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Wood", "Wood")
.WithMany("Orders")
.HasForeignKey("WoodId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Wood");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.WoodComponent", b =>
@ -206,6 +244,11 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
b.Navigation("WoodComponents");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Order");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Wood", b =>
{
b.Navigation("Components");

View File

@ -40,6 +40,22 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
table.PrimaryKey("PK_Components", x => x.Id);
});
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.CreateTable(
name: "Woods",
columns: table => new
@ -61,9 +77,9 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
WoodId = table.Column<int>(type: "int", nullable: false),
WoodName = table.Column<string>(type: "nvarchar(max)", nullable: false),
ImplementerId = table.Column<int>(type: "int", nullable: true),
ClientId = table.Column<int>(type: "int", nullable: false),
ClientFIO = table.Column<string>(type: "nvarchar(max)", nullable: false),
WoodName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Count = table.Column<int>(type: "int", nullable: false),
Sum = table.Column<double>(type: "float", nullable: false),
Status = table.Column<int>(type: "int", nullable: false),
@ -79,6 +95,11 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
principalTable: "Clients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
column: x => x.ImplementerId,
principalTable: "Implementers",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Orders_Woods_WoodId",
column: x => x.WoodId,
@ -119,6 +140,11 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
table: "Orders",
column: "ClientId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
migrationBuilder.CreateIndex(
name: "IX_Orders_WoodId",
table: "Orders",
@ -147,6 +173,9 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "Implementers");
migrationBuilder.DropTable(
name: "Components");

View File

@ -67,7 +67,7 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
b.ToTable("Components");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b =>
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
@ -75,10 +75,33 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
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("CarpentryWorkshopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
@ -91,6 +114,9 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
@ -108,6 +134,8 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("WoodId");
b.ToTable("Orders");
@ -161,17 +189,27 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Order", b =>
{
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", null)
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Wood", null)
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Order")
.HasForeignKey("ImplementerId");
b.HasOne("CarpentryWorkshopDatabaseImplement.Models.Wood", "Wood")
.WithMany("Orders")
.HasForeignKey("WoodId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Wood");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.WoodComponent", b =>
@ -203,6 +241,11 @@ namespace CarpentryWorkshopDatabaseImplement.Migrations
b.Navigation("WoodComponents");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Order");
});
modelBuilder.Entity("CarpentryWorkshopDatabaseImplement.Models.Wood", b =>
{
b.Navigation("Components");

View File

@ -0,0 +1,70 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopDatabaseImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; set; }
[Required]
public string ImplementerFIO { get; set; } = string.Empty;
[Required]
public string Password { get; set; } = string.Empty;
[Required]
public int WorkExperience { get; set; }
[Required]
public int Qualification { get; set; }
[ForeignKey("ImplementerId")]
public virtual List<Order> Order { get; set; } = new();
public static Implementer? Create(ImplementerBindingModel? model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
ImplementerFIO = model.ImplementerFIO,
Password = model.Password,
WorkExperience = model.WorkExperience,
Qualification = model.Qualification
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
ImplementerFIO = model.ImplementerFIO;
Password = model.Password;
WorkExperience = model.WorkExperience;
Qualification = model.Qualification;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
ImplementerFIO = ImplementerFIO,
Password = Password,
WorkExperience = WorkExperience,
Qualification = Qualification
};
}
}

View File

@ -5,71 +5,97 @@ using CarpentryWorkshopDataModels.Models;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection.Metadata;
namespace CarpentryWorkshopDatabaseImplement.Models
{
public class Order : IOrderModel
{
public int Id { get; set; }
[ForeignKey("WoodId")]
public int WoodId { get; set; }
[ForeignKey("ClientId")]
public int ClientId { get; set; }
[Required]
public int Count { get; set; }
[Required]
public double Sum { get; set; }
[Required]
public OrderStatus Status { get; set; }
[Required]
public DateTime DateCreate { get; set; }
public int Id { get; private set; }
public int WoodId { get; private set; }
public int? ImplementerId { get; private set; }
[Required]
public int ClientId { get; set; }
public string WoodName { get; private set; } = string.Empty;
[Required]
public int Count { get; private set; }
[Required]
public double Sum { get; private set; }
[Required]
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
[Required]
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public virtual Wood Wood { get; set; }
public DateTime? DateImplement { get; set; }
public Wood Wood { get; set; }
public Client Client { get; set; }
public Implementer? Implementer { get; set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
WoodId = model.WoodId,
ClientId = model.ClientId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement
};
}
{
if (model == null)
{
return null;
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
return new Order()
{
Id = model.Id,
WoodId = model.WoodId,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
WoodName = model.WoodName,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement
};
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
WoodId = WoodId,
WoodName = Wood.WoodName,
ClientId = ClientId,
ClientFIO = Client.ClientFIO,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
};
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
}
public OrderViewModel GetViewModel
{
get
{
using var context = new CarpentryWorkshopDatabase();
return new OrderViewModel
{
Id = Id,
WoodId = WoodId,
ClientId = ClientId,
ImplementerId = ImplementerId,
ClientFIO = context.Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty,
WoodName = context.Woods.FirstOrDefault(x => x.Id == WoodId)?.WoodName ?? string.Empty,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
ImplementerFIO = Implementer?.ImplementerFIO ?? string.Empty
};
}
}
}
}

View File

@ -10,10 +10,12 @@ namespace CarpentryWorkshopFileImplement
private readonly string OrderFileName = "Order.xml";
private readonly string WoodFileName = "Wood.xml";
private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Wood> Woods { get; private set; }
public List<Client> Clients { get; private set; }
public List<Implementer> Implementers { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
@ -26,12 +28,15 @@ namespace CarpentryWorkshopFileImplement
public void SaveWoods() => SaveData(Woods, WoodFileName, "Woods", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement);
public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Woods = LoadData(WoodFileName, "Wood", x => Wood.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{

View File

@ -0,0 +1,93 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopFileImplement.Implements
{
public class ClientStorage : IClientStorage
{
private readonly DataFileSingleton source;
public ClientStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ClientViewModel> GetFullList()
{
return source.Clients
.Select(x => x.GetViewModel)
.ToList();
}
public List<ClientViewModel> GetFilteredList(ClientSearchModel model)
{
if (string.IsNullOrEmpty(model.ClientFIO) && string.IsNullOrEmpty(model.Email))
{
return new();
}
return source.Clients
.Where(x => (!string.IsNullOrEmpty(model.ClientFIO) && x.ClientFIO.Contains(model.ClientFIO)) ||
(!string.IsNullOrEmpty(model.Email) && x.ClientFIO.Contains(model.Email)))
.Select(x => x.GetViewModel)
.ToList();
}
public ClientViewModel? GetElement(ClientSearchModel model)
{
if (!model.Id.HasValue && string.IsNullOrEmpty(model.ClientFIO) && string.IsNullOrEmpty(model.Email) && string.IsNullOrEmpty(model.Password))
{
return null;
}
return source.Clients
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) ||
(!string.IsNullOrEmpty(model.ClientFIO) && x.ClientFIO == model.ClientFIO) ||
(!string.IsNullOrEmpty(model.Email) && !string.IsNullOrEmpty(model.Password) && x.Email == model.Email && x.Password == model.Password))
?.GetViewModel;
}
public ClientViewModel? Insert(ClientBindingModel model)
{
model.Id = source.Components.Count > 0 ? source.Components.Max(x => x.Id) + 1 : 1;
var newClient = Client.Create(model);
if (newClient == null)
{
return null;
}
source.Clients.Add(newClient);
source.SaveClients();
return newClient.GetViewModel;
}
public ClientViewModel? Update(ClientBindingModel model)
{
var client = source.Clients.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
return null;
}
client.Update(model);
source.SaveClients();
return client.GetViewModel;
}
public ClientViewModel? Delete(ClientBindingModel model)
{
var element = source.Clients.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Clients.Remove(element);
source.SaveClients();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,92 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarpentryWorkshopFileImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataFileSingleton source;
public ImplementerStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ImplementerViewModel> GetFullList()
{
return source.Implementers
.Select(x => x.GetViewModel)
.ToList();
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
return new();
}
return source.Implementers
.Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (!model.Id.HasValue && string.IsNullOrEmpty(model.ImplementerFIO) && string.IsNullOrEmpty(model.Password))
{
return null;
}
return source.Implementers
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) ||
(!string.IsNullOrEmpty(model.ImplementerFIO) && x.ImplementerFIO == model.ImplementerFIO &&
!string.IsNullOrEmpty(model.Password) && x.Password == model.Password))
?.GetViewModel;
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = source.Components.Count > 0 ? source.Components.Max(x => x.Id) + 1 : 1;
var newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
source.Implementers.Add(newImplementer);
source.SaveImplementers();
return newImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
var implementer = source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (implementer == null)
{
return null;
}
implementer.Update(model);
source.SaveImplementers();
return implementer.GetViewModel;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
var element = source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Implementers.Remove(element);
source.SaveImplementers();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -13,103 +13,129 @@ namespace CarpentryWorkshopFileImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataFileSingleton source;
public OrderStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<OrderViewModel> GetFullList()
private readonly DataFileSingleton source;
public OrderStorage()
{
return source.Orders.Select(x => GetViewModel(x)).ToList();
source = DataFileSingleton.GetInstance();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
public OrderViewModel? Delete(OrderBindingModel model)
{
if (model.DateFrom.HasValue)
var element = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
return source.Orders
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.Select(x => GetViewModel(x))
.ToList();
source.Orders.Remove(element);
source.SaveOrders();
return element.GetViewModel;
}
if (model.ClientId.HasValue && !model.Id.HasValue)
{
return source.Orders
.Where(x => x.ClientId == model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
}
if (model.Id.HasValue)
{
return source.Orders
.Where(x => x.Id.Equals(model.Id))
.Select(x => GetViewModel(x))
.ToList();
}
return new();
return null;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (model.ImplementerId.HasValue && model.Statuses != null)
{
return source.Orders
.FirstOrDefault(x => x.ImplementerId == model.ImplementerId &&
model.Statuses.Contains(x.Status))
?.GetViewModel;
}
if (model.ImplementerId.HasValue)
{
return source.Orders
.FirstOrDefault(x => x.ImplementerId == model.ImplementerId)
?.GetViewModel;
}
if (!model.Id.HasValue)
{
return null;
}
return source.Orders.FirstOrDefault(x =>
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
return source.Orders
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
private OrderViewModel GetViewModel(Order order)
{
var viewModel = order.GetViewModel;
var wood = source
.Woods.FirstOrDefault(x => x.Id == order.WoodId);
var client = source
.Clients.FirstOrDefault(x => x.Id == order.ClientId);
if (wood != null)
viewModel.WoodName = wood.WoodName;
if (client != null)
viewModel.ClientFIO = client.ClientFIO;
return viewModel;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (model.DateFrom.HasValue)
return source.Orders
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.Select(x => GetViewModel(x))
.ToList();
if (model.ClientId.HasValue && !model.Id.HasValue)
return source.Orders
.Where(x => x.ClientId == model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
if (model.Id.HasValue)
return source.Orders
.Where(x => x.Id.Equals(model.Id))
.Select(x => GetViewModel(x))
.ToList();
return new();
}
public List<OrderViewModel> GetFullList()
{
return source.Orders.Select(x => x.GetViewModel).ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1;
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
source.Orders.Add(newOrder);
source.SaveOrders();
return GetViewModel(newOrder);
return newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
source.SaveOrders();
return GetViewModel(order);
}
public OrderViewModel? Delete(OrderBindingModel model)
{
var element = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Orders.Remove(element);
source.SaveOrders();
return GetViewModel(element);
}
return null;
return order.GetViewModel;
}
}
}

View File

@ -0,0 +1,75 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace CarpentryWorkshopFileImplement.Models
{
public class Client : IClientModel
{
public int Id { get; private set; }
public string ClientFIO { get; private set; } = string.Empty;
public string Email { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty;
public static Client? Create(ClientBindingModel model)
{
if (model == null)
{
return null;
}
return new Client()
{
Id = model.Id,
ClientFIO = model.ClientFIO,
Email = model.Email,
Password = model.Password
};
}
public static Client? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Client()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ClientFIO = element.Element("ClientFIO")!.Value,
Email = element.Element("Email")!.Value,
Password = element.Element("Password")!.Value
};
}
public void Update(ClientBindingModel model)
{
if (model == null)
{
return;
}
ClientFIO = model.ClientFIO;
Email = model.Email;
Password = model.Password;
}
public ClientViewModel GetViewModel => new()
{
Id = Id,
ClientFIO = ClientFIO,
Email = Email,
Password = Password
};
public XElement GetXElement => new("Client",
new XAttribute("Id", Id),
new XElement("ClientFIO", ClientFIO),
new XElement("Email", Email),
new XElement("Password", Password));
}
}

View File

@ -0,0 +1,85 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace CarpentryWorkshopFileImplement.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; }
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
ImplementerFIO = model.ImplementerFIO,
Password = model.Password,
WorkExperience = model.WorkExperience,
Qualification = model.Qualification,
};
}
public static Implementer? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Implementer()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ImplementerFIO = element.Element("ImplementerFIO")!.Value,
Password = element.Element("Password")!.Value,
WorkExperience = Convert.ToInt32(element.Element("Cost")!.Value),
Qualification = Convert.ToInt32(element.Element("Cost")!.Value)
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
ImplementerFIO = model.ImplementerFIO;
Password = model.Password;
WorkExperience = model.WorkExperience;
Qualification = model.Qualification;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
ImplementerFIO = ImplementerFIO,
Password = Password,
WorkExperience = WorkExperience,
Qualification = Qualification
};
public XElement GetXElement => new("Implementer",
new XAttribute("Id", Id),
new XElement("ImplementerFIO", ImplementerFIO),
new XElement("Password", Password),
new XElement("WorkExperience", WorkExperience),
new XElement("Qualification", Qualification));
}
}

View File

@ -4,6 +4,8 @@ using CarpentryWorkshopDataModels.Enums;
using CarpentryWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
@ -14,15 +16,27 @@ namespace CarpentryWorkshopFileImplement.Models
{
public class Order : IOrderModel
{
public int Id { get; private set; }
public int WoodId { get; private set; }
public int? ImplementerId { get; set; }
public int ClientId { get; private set; }
public string WoodName { get; private set; } = string.Empty;
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public static Order? Create(OrderBindingModel? model)
public int Id { get; private set; }
public static Order? Create(OrderBindingModel model)
{
if (model == null)
{
@ -31,13 +45,15 @@ namespace CarpentryWorkshopFileImplement.Models
return new Order()
{
Id = model.Id,
ImplementerId = model.ImplementerId,
WoodId = model.WoodId,
WoodName = model.WoodName,
ClientId = model.ClientId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
DateImplement = model.DateImplement
};
}
@ -47,21 +63,27 @@ namespace CarpentryWorkshopFileImplement.Models
{
return null;
}
return new Order()
var order = new Order()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value),
WoodId = Convert.ToInt32(element.Element("WoodId")!.Value),
ClientId = Convert.ToInt32(element.Element("ClientId")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
WoodName = element.Element("WoodName")!.Value,
Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value),
DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value),
DateImplement = string.IsNullOrEmpty(element.Element("DateImplement")!.Value) ?
null : Convert.ToDateTime(element.Element("DateImplement")!.Value)
DateCreate = DateTime.ParseExact(element.Element("DateCreate")!.Value, "G", null)
};
DateTime.TryParse(element.Element("DateImplement")!.Value, out DateTime dateImpl);
order.DateImplement = dateImpl;
return order;
}
public void Update(OrderBindingModel? model)
public void Update(OrderBindingModel model)
{
if (model == null)
{
@ -73,20 +95,24 @@ namespace CarpentryWorkshopFileImplement.Models
public OrderViewModel GetViewModel => new()
{
Id = Id,
ImplementerId = ImplementerId,
WoodId = WoodId,
ClientId = ClientId,
WoodName = WoodName,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
Id = Id,
Status = Status
DateImplement = DateImplement
};
public XElement GetXElement => new("Order",
new XAttribute("Id", Id),
new XElement("WoodId", WoodId),
new XElement("ClientId", ClientId),
new XElement("WoodName", WoodName),
new XElement("WoodId", WoodId.ToString()),
new XElement("ClientId", ClientId.ToString()),
new XElement("ImplementerId", ImplementerId.ToString()),
new XElement("Count", Count.ToString()),
new XElement("Sum", Sum.ToString()),
new XElement("Status", Status.ToString()),

View File

@ -9,12 +9,14 @@ namespace CarpentryWorkshopListImplement
public List<Order> Orders { get; set; }
public List<Wood> Woods { get; set; }
public List<Client> Clients { get; set; }
public List<Implementer> Implementers { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
Orders = new List<Order>();
Woods = new List<Wood>();
Clients = new List<Client>();
Implementers = new List<Implementer>();
}
public static DataListSingleton GetInstance()
{

View File

@ -0,0 +1,126 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.StoragesContracts;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopListImplement.Models;
namespace CarpentryWorkshopListImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataListSingleton _source;
public ImplementerStorage()
{
_source = DataListSingleton.GetInstance();
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
for (int i = 0; i < _source.Implementers.Count; ++i)
{
if (_source.Implementers[i].Id == model.Id)
{
var element = _source.Implementers[i];
_source.Implementers.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
foreach (var x in _source.Implementers)
{
if (model.Id.HasValue && x.Id == model.Id)
return x.GetViewModel;
if (model.ImplementerFIO != null && model.Password != null &&
x.ImplementerFIO.Equals(model.ImplementerFIO) &&
x.Password.Equals(model.Password))
return x.GetViewModel;
if (model.ImplementerFIO != null && x.ImplementerFIO.Equals(model.ImplementerFIO))
return x.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();
}
List<ImplementerViewModel> result = new();
if (model.ImplementerFIO != null)
{
foreach (var implementer in _source.Implementers)
{
if (implementer.ImplementerFIO.Equals(model.ImplementerFIO))
{
result.Add(implementer.GetViewModel);
}
}
}
return result;
}
public List<ImplementerViewModel> GetFullList()
{
var result = new List<ImplementerViewModel>();
foreach (var implementer in _source.Implementers)
{
result.Add(implementer.GetViewModel);
}
return result;
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = 1;
foreach (var implementer in _source.Implementers)
{
if (model.Id <= implementer.Id)
{
model.Id = implementer.Id + 1;
}
}
var res = Implementer.Create(model);
if (res != null)
{
_source.Implementers.Add(res);
}
return res?.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
foreach (var implementer in _source.Implementers)
{
if (implementer.Id == model.Id)
{
implementer.Update(model);
return implementer.GetViewModel;
}
}
return null;
}
}
}

View File

@ -13,20 +13,57 @@ namespace CarpentryWorkshopListImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataListSingleton _source;
public OrderStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<OrderViewModel> GetFullList()
private readonly DataListSingleton _source;
public OrderStorage()
{
var result = new List<OrderViewModel>();
_source = DataListSingleton.GetInstance();
}
public OrderViewModel? Delete(OrderBindingModel model)
{
for (int i = 0; i < _source.Orders.Count; ++i)
{
if (_source.Orders[i].Id == model.Id)
{
var element = _source.Orders[i];
_source.Orders.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
foreach (var order in _source.Orders)
{
result.Add(GetViewModel(order));
if (model.Id.HasValue && order.Id == model.Id)
{
return order.GetViewModel;
}
else if (model.ImplementerId.HasValue && model.Statuses != null &&
order.ImplementerId == model.ImplementerId &&
model.Statuses.Contains(order.Status))
{
return GetViewModel(order);
}
else if (model.ImplementerId.HasValue &&
model.ImplementerId == order.ImplementerId)
{
return GetViewModel(order);
}
}
return result;
return null;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
var result = new List<OrderViewModel>();
@ -59,25 +96,22 @@ namespace CarpentryWorkshopListImplement.Implements
{
result.Add(GetViewModel(order));
}
else if (model.ImplementerId.HasValue && order.ImplementerId == model.ImplementerId)
{
result.Add(GetViewModel(order));
}
else if (model.Statuses != null && model.Statuses.Contains(order.Status))
{
result.Add(GetViewModel(order));
}
}
}
return result;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
foreach (var order in _source.Orders)
{
if (model.Id.HasValue && order.Id == model.Id)
{
return GetViewModel(order);
}
}
return null;
}
private OrderViewModel GetViewModel(Order order)
{
var viewModel = order.GetViewModel;
@ -99,9 +133,22 @@ namespace CarpentryWorkshopListImplement.Implements
}
return viewModel;
}
public List<OrderViewModel> GetFullList()
{
var result = new List<OrderViewModel>();
foreach (var order in _source.Orders)
{
result.Add(order.GetViewModel);
}
return result;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
model.Id = 1;
foreach (var order in _source.Orders)
{
if (model.Id <= order.Id)
@ -109,14 +156,19 @@ namespace CarpentryWorkshopListImplement.Implements
model.Id = order.Id + 1;
}
}
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
_source.Orders.Add(newOrder);
return GetViewModel(newOrder);
return newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
foreach (var order in _source.Orders)
@ -124,22 +176,10 @@ namespace CarpentryWorkshopListImplement.Implements
if (order.Id == model.Id)
{
order.Update(model);
return GetViewModel(order);
}
}
return null;
}
public OrderViewModel? Delete(OrderBindingModel model)
{
for (int i = 0; i < _source.Orders.Count; ++i)
{
if (_source.Orders[i].Id == model.Id)
{
var element = _source.Orders[i];
_source.Orders.RemoveAt(i);
return GetViewModel(element);
return order.GetViewModel;
}
}
return null;
}
}

View File

@ -0,0 +1,56 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Models;
namespace CarpentryWorkshopListImplement.Models
{
public class Implementer : IImplementerModel
{
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 int Id { 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,
WorkExperience = WorkExperience
};
}
}

View File

@ -1,4 +1,5 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.ViewModels;
using CarpentryWorkshopDataModels.Enums;
using CarpentryWorkshopDataModels.Models;
@ -14,31 +15,44 @@ namespace CarpentryWorkshopListImplement.Models
public class Order : IOrderModel
{
public int WoodId { get; private set; }
public string WoodName { get; private set; }
public int ClientId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; }
public int Id { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order
return new Order()
{
Id = model.Id,
WoodId = model.WoodId,
ImplementerId = model.ImplementerId,
ClientId = model.ClientId,
WoodName = model.WoodName,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
Id = model.Id,
DateImplement = model.DateImplement
};
}
public void Update(OrderBindingModel? model)
{
if (model == null)
@ -48,16 +62,21 @@ namespace CarpentryWorkshopListImplement.Models
Status = model.Status;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
WoodId = WoodId,
ClientId = ClientId,
WoodName = WoodName,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
Id = Id,
Status = Status,
ImplementerId = ImplementerId
};
public int? ImplementerId { get; private set; }
}
}

View File

@ -0,0 +1,107 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.SearchModels;
using CarpentryWorkshopContracts.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace CarpentryWorkshopRestApi.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;
}
}
}
}

View File

@ -7,7 +7,6 @@ using Microsoft.Extensions.Logging;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.SetMinimumLevel(LogLevel.Trace);
builder.Logging.AddLog4Net("log4net.config");
// Add services to the container.
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="d:/temp/SushiBarRestApi.log" />
<file value="c:/temp/CarpentryWorkshopRestApi.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />

View File

@ -97,7 +97,6 @@ namespace CarpentryWorkshopView
WoodId = Convert.ToInt32(comboBoxWood.SelectedValue),
WoodName = comboBoxWood.Text,
ClientId = Convert.ToInt32(comboBoxClient.SelectedValue),
ClientFIO = comboBoxClient.Text,
Count = Convert.ToInt32(textBoxCount.Text),
Sum = Convert.ToDouble(textBoxSum.Text)
});

View File

@ -0,0 +1,169 @@
namespace CarpentryWorkshopView
{
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()
{
labelFIO = new Label();
labelPassword = new Label();
labelWorkExperience = new Label();
labelQualification = new Label();
textBoxPassword = new TextBox();
textBoxFIO = new TextBox();
textBoxWorkExperience = new TextBox();
textBoxQualification = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// labelFIO
//
labelFIO.AutoSize = true;
labelFIO.Location = new Point(10, 11);
labelFIO.Name = "labelFIO";
labelFIO.Size = new Size(34, 15);
labelFIO.TabIndex = 0;
labelFIO.Text = "ФИО";
//
// labelPassword
//
labelPassword.AutoSize = true;
labelPassword.Location = new Point(10, 36);
labelPassword.Name = "labelPassword";
labelPassword.Size = new Size(49, 15);
labelPassword.TabIndex = 1;
labelPassword.Text = "Пароль";
//
// labelWorkExperience
//
labelWorkExperience.AutoSize = true;
labelWorkExperience.Location = new Point(10, 61);
labelWorkExperience.Name = "labelWorkExperience";
labelWorkExperience.Size = new Size(79, 15);
labelWorkExperience.TabIndex = 2;
labelWorkExperience.Text = "Стаж работы";
//
// labelQualification
//
labelQualification.AutoSize = true;
labelQualification.Location = new Point(10, 86);
labelQualification.Name = "labelQualification";
labelQualification.Size = new Size(88, 15);
labelQualification.TabIndex = 3;
labelQualification.Text = "Квалификация";
//
// textBoxPassword
//
textBoxPassword.Location = new Point(113, 34);
textBoxPassword.Margin = new Padding(3, 2, 3, 2);
textBoxPassword.Name = "textBoxPassword";
textBoxPassword.Size = new Size(211, 23);
textBoxPassword.TabIndex = 4;
//
// textBoxFIO
//
textBoxFIO.Location = new Point(113, 9);
textBoxFIO.Margin = new Padding(3, 2, 3, 2);
textBoxFIO.Name = "textBoxFIO";
textBoxFIO.Size = new Size(211, 23);
textBoxFIO.TabIndex = 5;
//
// textBoxWorkExperience
//
textBoxWorkExperience.Location = new Point(113, 58);
textBoxWorkExperience.Margin = new Padding(3, 2, 3, 2);
textBoxWorkExperience.Name = "textBoxWorkExperience";
textBoxWorkExperience.Size = new Size(211, 23);
textBoxWorkExperience.TabIndex = 6;
//
// textBoxQualification
//
textBoxQualification.Location = new Point(113, 83);
textBoxQualification.Margin = new Padding(3, 2, 3, 2);
textBoxQualification.Name = "textBoxQualification";
textBoxQualification.Size = new Size(209, 23);
textBoxQualification.TabIndex = 7;
//
// buttonSave
//
buttonSave.Location = new Point(147, 110);
buttonSave.Margin = new Padding(3, 2, 3, 2);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(89, 22);
buttonSave.TabIndex = 8;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(242, 110);
buttonCancel.Margin = new Padding(3, 2, 3, 2);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(82, 22);
buttonCancel.TabIndex = 9;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormImplementer
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(334, 140);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxQualification);
Controls.Add(textBoxWorkExperience);
Controls.Add(textBoxFIO);
Controls.Add(textBoxPassword);
Controls.Add(labelQualification);
Controls.Add(labelWorkExperience);
Controls.Add(labelPassword);
Controls.Add(labelFIO);
Margin = new Padding(3, 2, 3, 2);
Name = "FormImplementer";
StartPosition = FormStartPosition.CenterParent;
Text = "Исполнитель";
Load += FormImplementer_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelFIO;
private Label labelPassword;
private Label labelWorkExperience;
private Label labelQualification;
private TextBox textBoxPassword;
private TextBox textBoxFIO;
private TextBox textBoxWorkExperience;
private TextBox textBoxQualification;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,101 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.BusinessLogicsContracts;
using CarpentryWorkshopContracts.SearchModels;
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 CarpentryWorkshopView
{
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;
textBoxWorkExperience.Text = view.WorkExperience.ToString();
textBoxQualification.Text = view.Qualification.ToString();
}
}
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(textBoxFIO.Text))
{
MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxPassword.Text))
{
MessageBox.Show("Заполните пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение исполнителя");
try
{
var model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = textBoxFIO.Text,
Password = textBoxPassword.Text,
WorkExperience = Convert.ToInt32(textBoxWorkExperience.Text),
Qualification = Convert.ToInt32(textBoxQualification.Text)
};
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

@ -0,0 +1,117 @@
namespace CarpentryWorkshopView
{
partial class FormImplementers
{
/// <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()
{
dataGridViewImplementers = new DataGridView();
buttonRef = new Button();
buttonDel = new Button();
buttonUpd = new Button();
buttonAdd = new Button();
((System.ComponentModel.ISupportInitialize)dataGridViewImplementers).BeginInit();
SuspendLayout();
//
// dataGridViewImplementers
//
dataGridViewImplementers.BackgroundColor = SystemColors.ControlLightLight;
dataGridViewImplementers.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewImplementers.Location = new Point(1, 1);
dataGridViewImplementers.Name = "dataGridViewImplementers";
dataGridViewImplementers.RowHeadersVisible = false;
dataGridViewImplementers.RowHeadersWidth = 51;
dataGridViewImplementers.RowTemplate.Height = 29;
dataGridViewImplementers.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewImplementers.Size = new Size(650, 402);
dataGridViewImplementers.TabIndex = 0;
//
// buttonRef
//
buttonRef.Location = new Point(668, 117);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(102, 29);
buttonRef.TabIndex = 1;
buttonRef.Text = "Обновить";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// buttonDel
//
buttonDel.Location = new Point(668, 82);
buttonDel.Name = "buttonDel";
buttonDel.Size = new Size(102, 29);
buttonDel.TabIndex = 2;
buttonDel.Text = "Удалить";
buttonDel.UseVisualStyleBackColor = true;
buttonDel.Click += ButtonDel_Click;
//
// buttonUpd
//
buttonUpd.Location = new Point(668, 47);
buttonUpd.Name = "buttonUpd";
buttonUpd.Size = new Size(102, 29);
buttonUpd.TabIndex = 3;
buttonUpd.Text = "Изменить";
buttonUpd.UseVisualStyleBackColor = true;
buttonUpd.Click += ButtonUpd_Click;
//
// buttonAdd
//
buttonAdd.Location = new Point(668, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(102, 29);
buttonAdd.TabIndex = 4;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// FormImplementers
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(782, 403);
Controls.Add(buttonAdd);
Controls.Add(buttonUpd);
Controls.Add(buttonDel);
Controls.Add(buttonRef);
Controls.Add(dataGridViewImplementers);
Name = "FormImplementers";
StartPosition = FormStartPosition.CenterParent;
Text = "Исполнители";
Load += FormImplementers_Load;
((System.ComponentModel.ISupportInitialize)dataGridViewImplementers).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridViewImplementers;
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
}
}

View File

@ -0,0 +1,112 @@
using CarpentryWorkshopContracts.BindingModels;
using CarpentryWorkshopContracts.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 CarpentryWorkshopView
{
public partial class FormImplementers : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
public FormImplementers(ILogger<FormImplementers> logger, IImplementerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormImplementers_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridViewImplementers.DataSource = list;
dataGridViewImplementers.Columns["Id"].Visible = false;
dataGridViewImplementers.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 (dataGridViewImplementers.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementer));
if (service is FormImplementer form)
{
form.Id = Convert.ToInt32(dataGridViewImplementers.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (dataGridViewImplementers.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
DialogResult.Yes)
{
int id = Convert.ToInt32(dataGridViewImplementers.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,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -37,6 +37,8 @@
изделияПоКомпонентамToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовToolStripMenuItem = new ToolStripMenuItem();
клиентыToolStripMenuItem = new ToolStripMenuItem();
запускРаботToolStripMenuItem = new ToolStripMenuItem();
исполнителиToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
ButtonCreateOrder = new Button();
ButtonTakeOrderInWork = new Button();
@ -49,10 +51,10 @@
//
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, клиентыToolStripMenuItem });
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, клиентыToolStripMenuItem, запускРаботToolStripMenuItem, исполнителиToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(950, 24);
menuStrip1.Size = new Size(1051, 24);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1";
//
@ -112,6 +114,20 @@
клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click;
//
// запускРаботToolStripMenuItem
//
запускРаботToolStripMenuItem.Name = апускРаботToolStripMenuItem";
запускРаботToolStripMenuItem.Size = new Size(92, 20);
запускРаботToolStripMenuItem.Text = "Запуск Работ";
запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click;
//
// исполнителиToolStripMenuItem
//
исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem";
исполнителиToolStripMenuItem.Size = new Size(94, 20);
исполнителиToolStripMenuItem.Text = "Исполнители";
исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click_1;
//
// dataGridView
//
dataGridView.BackgroundColor = SystemColors.ButtonHighlight;
@ -121,12 +137,12 @@
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(821, 243);
dataGridView.Size = new Size(922, 243);
dataGridView.TabIndex = 1;
//
// ButtonCreateOrder
//
ButtonCreateOrder.Location = new Point(828, 44);
ButtonCreateOrder.Location = new Point(929, 44);
ButtonCreateOrder.Name = "ButtonCreateOrder";
ButtonCreateOrder.Size = new Size(122, 23);
ButtonCreateOrder.TabIndex = 2;
@ -136,7 +152,7 @@
//
// ButtonTakeOrderInWork
//
ButtonTakeOrderInWork.Location = new Point(828, 73);
ButtonTakeOrderInWork.Location = new Point(929, 73);
ButtonTakeOrderInWork.Name = "ButtonTakeOrderInWork";
ButtonTakeOrderInWork.Size = new Size(122, 42);
ButtonTakeOrderInWork.TabIndex = 3;
@ -146,7 +162,7 @@
//
// ButtonOrderReady
//
ButtonOrderReady.Location = new Point(828, 121);
ButtonOrderReady.Location = new Point(929, 121);
ButtonOrderReady.Name = "ButtonOrderReady";
ButtonOrderReady.Size = new Size(122, 23);
ButtonOrderReady.TabIndex = 4;
@ -156,7 +172,7 @@
//
// ButtonIssuedOrder
//
ButtonIssuedOrder.Location = new Point(828, 150);
ButtonIssuedOrder.Location = new Point(929, 150);
ButtonIssuedOrder.Name = "ButtonIssuedOrder";
ButtonIssuedOrder.Size = new Size(122, 23);
ButtonIssuedOrder.TabIndex = 5;
@ -166,7 +182,7 @@
//
// ButtonRef
//
ButtonRef.Location = new Point(828, 179);
ButtonRef.Location = new Point(929, 179);
ButtonRef.Name = "ButtonRef";
ButtonRef.Size = new Size(122, 23);
ButtonRef.TabIndex = 6;
@ -178,7 +194,7 @@
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(950, 280);
ClientSize = new Size(1051, 280);
Controls.Add(ButtonRef);
Controls.Add(ButtonIssuedOrder);
Controls.Add(ButtonOrderReady);
@ -213,5 +229,7 @@
private ToolStripMenuItem изделияПоКомпонентамToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem запускРаботToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem;
}
}

View File

@ -18,13 +18,15 @@ namespace CarpentryWorkshopView
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
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();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
}
private void FormMain_Load(object sender, EventArgs e)
{
@ -42,6 +44,7 @@ namespace CarpentryWorkshopView
dataGridView.DataSource = list;
dataGridView.Columns[1].Visible = false;
dataGridView.Columns[3].Visible = false;
dataGridView.Columns[4].Visible = false;
}
_logger.LogInformation("Загрузка продуктов");
@ -185,5 +188,18 @@ namespace CarpentryWorkshopView
form.ShowDialog();
}
}
private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void исполнителиToolStripMenuItem_Click_1(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (service is FormImplementers form)
{
form.ShowDialog();
}
}
}
}

View File

@ -39,12 +39,15 @@ namespace CarpentryWorkshopView
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IWoodStorage, WoodStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IWoodLogic, WoodLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
@ -60,6 +63,8 @@ namespace CarpentryWorkshopView
services.AddTransient<FormReportWoodComponents>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormClients>();
}
services.AddTransient<FormImplementer>();
services.AddTransient<FormImplementers>();
}
}
}