first commit

This commit is contained in:
Salikh 2024-04-19 13:43:16 +04:00
parent c18421c599
commit a6eb44a555
45 changed files with 2150 additions and 133 deletions

View File

@ -0,0 +1,123 @@
using Microsoft.Extensions.Logging;
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
namespace MotorPlantBusinessLogic.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 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 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 bool Create(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Update(model) == null)
{
_logger.LogWarning("Update 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;
}
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

@ -12,17 +12,37 @@ namespace MotorPlantBusinessLogic.BusinessLogics
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage; private readonly IOrderStorage _orderStorage;
static readonly object _locker = new object();
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage) public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
{ {
_logger = logger; _logger = logger;
_orderStorage = orderStorage; _orderStorage = orderStorage;
} }
public List<OrderViewModel>? ReadList(OrderSearchModel? model) public OrderViewModel? ReadElement(OrderSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}",
model.ClientId, model.Status, model.ImplementerId, model.DateFrom, model.DateTo, 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;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{ {
_logger.LogInformation("ReadList. OrderId:{Id}", model?.Id); _logger.LogInformation("ReadList. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}",
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model); model?.ClientId, model?.Status, model?.ImplementerId, model?.DateFrom, model?.DateTo, model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null) if (list == null)
{ {
_logger.LogWarning("ReadList return null list"); _logger.LogWarning("ReadList return null list");
@ -49,12 +69,15 @@ namespace MotorPlantBusinessLogic.BusinessLogics
return true; return true;
} }
public bool TakeOrderInWork(OrderBindingModel model) public bool TakeOrderInWork(OrderBindingModel model)
{ {
return ToNextStatus(model, OrderStatus.Выполняется); lock (_locker)
} {
return ToNextStatus(model, OrderStatus.Выполняется);
}
}
public bool FinishOrder(OrderBindingModel model) public bool FinishOrder(OrderBindingModel model)
{ {
return ToNextStatus(model, OrderStatus.Готов); return ToNextStatus(model, OrderStatus.Готов);
} }
@ -73,36 +96,38 @@ namespace MotorPlantBusinessLogic.BusinessLogics
}); });
if (element == null) if (element == null)
{ {
throw new ArgumentNullException(nameof(element)); throw new InvalidOperationException(nameof(element));
} }
model.EngineId = element.EngineId; model.EngineId = element.EngineId;
model.DateCreate = element.DateCreate; model.DateCreate = element.DateCreate;
model.DateImplement = element.DateImplement; model.DateImplement = element.DateImplement;
model.Status = element.Status; model.ClientId = element.ClientId;
if (!model.ImplementerId.HasValue)
{
model.ImplementerId = element.ImplementerId;
}
model.Status = element.Status;
model.Count = element.Count; model.Count = element.Count;
model.Sum = element.Sum; model.Sum = element.Sum;
if (model.Status != orderStatus - 1) if (orderStatus - model.Status == 1)
{ {
_logger.LogWarning("Status update to " + orderStatus + " operation failed"); model.Status = orderStatus;
return false; if (model.Status == OrderStatus.Готов)
} {
model.Status = orderStatus; model.DateImplement = DateTime.Now;
}
if (model.Status == OrderStatus.Выдан) if (_orderStorage.Update(model) == null)
{ {
model.DateImplement = DateTime.Now; _logger.LogWarning("Update operation failed");
} return false;
}
if (_orderStorage.Update(model) == null) return true;
{ }
model.Status--; _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, orderStatus);
_logger.LogWarning("Changing status operation faled"); throw new InvalidOperationException($"Невозможно приствоить статус {orderStatus} заказу с текущим статусом {model.Status}");
return false; }
}
return true;
}
private void CheckModel(OrderBindingModel model, bool withParams = true) private void CheckModel(OrderBindingModel model, bool withParams = true)
{ {

View File

@ -0,0 +1,134 @@
using Microsoft.Extensions.Logging;
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Enums;
namespace MotorPlantBusinessLogic.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 { Status = 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));
}
}
private async Task WorkerWorkAsync(ImplementerViewModel implementer, List<OrderViewModel> orders)
{
if (_orderLogic == null || implementer == null)
{
return;
}
await RunOrderInWork(implementer);
await Task.Run(() =>
{
foreach (var order in orders)
{
try
{
_logger.LogDebug("DoWork. Worker {Id} try get order {Order}", implementer.Id, order.Id);
// пытаемся назначить заказ на исполнителя
_orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = order.Id,
ImplementerId = implementer.Id
});
// делаем работу
Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 1000) * order.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = order.Id
});
}
// кто-то мог уже перехватить заказ, игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// заканчиваем выполнение имитации в случае иной ошибки
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
// отдыхаем
Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100));
}
});
}
private async Task RunOrderInWork(ImplementerViewModel implementer)
{
if (_orderLogic == null || implementer == null)
{
return;
}
try
{
var runOrder = await Task.Run(() => _orderLogic.ReadElement(new OrderSearchModel
{
ImplementerId = implementer.Id,
Status = OrderStatus.Выполняется
}));
if (runOrder == null)
{
return;
}
_logger.LogDebug("DoWork. Worker {Id} back to order {Order}", implementer.Id, runOrder.Id);
// доделываем работу
Thread.Sleep(implementer.WorkExperience * _rnd.Next(100, 300) * runOrder.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, runOrder.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = runOrder.Id
});
// отдыхаем
Thread.Sleep(implementer.Qualification * _rnd.Next(10, 100));
}
// заказа может не быть, просто игнорируем ошибку
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// а может возникнуть иная ошибка, тогда просто заканчиваем выполнение имитации
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
}
}
}

View File

@ -0,0 +1,13 @@
using MotorPlantDataModels.Models;
namespace MotorPlantContracts.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

@ -16,6 +16,8 @@ namespace MotorPlantContracts.BindingModels
public int ClientId { get; set; } public int ClientId { get; set; }
public int? ImplementerId { get; set; }
public int Count { get; set; } public int Count { get; set; }
public double Sum { get; set; } public double Sum { get; set; }

View File

@ -0,0 +1,15 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.ViewModels;
namespace MotorPlantContracts.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

@ -12,5 +12,6 @@ namespace MotorPlantContracts.BusinessLogicsContracts
bool TakeOrderInWork(OrderBindingModel model); bool TakeOrderInWork(OrderBindingModel model);
bool FinishOrder(OrderBindingModel model); bool FinishOrder(OrderBindingModel model);
bool DeliveryOrder(OrderBindingModel model); bool DeliveryOrder(OrderBindingModel model);
} OrderViewModel? ReadElement(OrderSearchModel model);
}
} }

View File

@ -0,0 +1,7 @@
namespace MotorPlantContracts.BusinessLogicsContracts
{
public interface IWorkProcess
{
void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic);
}
}

View File

@ -0,0 +1,9 @@
namespace MotorPlantContracts.SearchModels
{
public class ImplementerSearchModel
{
public int? Id { get; set; }
public string? ImplementerFIO { get; set; }
public string? Password { get; set; }
}
}

View File

@ -1,4 +1,6 @@
namespace MotorPlantContracts.SearchModels using MotorPlantDataModels.Enums;
namespace MotorPlantContracts.SearchModels
{ {
public class OrderSearchModel public class OrderSearchModel
{ {
@ -6,6 +8,10 @@
public int? ClientId { get; set; } public int? ClientId { get; set; }
public OrderStatus? Status { get; set; }
public int? ImplementerId { get; set; }
public DateTime? DateFrom { get; set; } public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set;} public DateTime? DateTo { get; set;}

View File

@ -0,0 +1,16 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.ViewModels;
namespace MotorPlantContracts.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,22 @@
using MotorPlantDataModels.Models;
using System.ComponentModel;
namespace MotorPlantContracts.ViewModels
{
public class ImplementerViewModel : IImplementerModel
{
public int Id { get; set; }
[DisplayName("ФИО исполнителя")]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Пароль")]
public string Password { get; set; } = string.Empty;
[DisplayName("Стаж работы")]
public int WorkExperience { get; set; }
[DisplayName("Квалификация")]
public int Qualification { get; set; }
}
}

View File

@ -26,6 +26,11 @@ namespace MotorPlantContracts.ViewModels
[DisplayName("ФИО клиента")] [DisplayName("ФИО клиента")]
public string ClientFIO { get; set; } = string.Empty; public string ClientFIO { get; set; } = string.Empty;
public int? ImplementerId { get; set; }
[DisplayName("Исполнитель")]
public string? ImplementerFIO { get; set; } = null;
[DisplayName("Количество")] [DisplayName("Количество")]
public int Count { get; set; } public int Count { get; set; }

View File

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

View File

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

View File

@ -0,0 +1,79 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantDatabaseImplement.Models;
namespace MotorPlantDatabaseImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
public List<ImplementerViewModel> GetFullList()
{
using var context = new MotorPlantDatabase();
return context.Implementers.Select(x => x.GetViewModel).ToList();
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
return new();
}
using var context = new MotorPlantDatabase();
return context.Implementers.Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO)).Select(x => x.GetViewModel).ToList();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue)
{
return null;
}
using var context = new MotorPlantDatabase();
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 ImplementerViewModel? Insert(ImplementerBindingModel model)
{
var newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
using var context = new MotorPlantDatabase();
context.Implementers.Add(newImplementer);
context.SaveChanges();
return newImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
using var context = new MotorPlantDatabase();
var implementer = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (implementer == null)
{
return null;
}
implementer.Update(model);
context.SaveChanges();
return implementer.GetViewModel;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
using var context = new MotorPlantDatabase();
var implementer = context.Implementers.FirstOrDefault(rec => rec.Id == model.Id);
if (implementer != null)
{
context.Implementers.Remove(implementer);
context.SaveChanges();
return implementer.GetViewModel;
}
return null;
}
}
}

View File

@ -1,4 +1,5 @@
using MotorPlantContracts.BindingModels; using Microsoft.EntityFrameworkCore;
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels; using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts; using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels; using MotorPlantContracts.ViewModels;
@ -12,13 +13,12 @@ namespace MotorPlantDatabaseImplement.Implements
public List<OrderViewModel> GetFullList() public List<OrderViewModel> GetFullList()
{ {
using var context = new MotorPlantDatabase(); using var context = new MotorPlantDatabase();
return context.Orders return context.Orders.Include(x => x.Engine).Include(x => x.Client).Include(y => y.Implementer).Select(x => x.GetViewModel).ToList();
.Select(x => AccessEngineStorage(x.GetViewModel))
.ToList();
} }
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{ {
if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue && !model.ClientId.HasValue) if ((!model.DateFrom.HasValue || !model.DateTo.HasValue) && !model.ClientId.HasValue && !model.Status.HasValue)
{ {
return new(); return new();
} }
@ -27,30 +27,39 @@ namespace MotorPlantDatabaseImplement.Implements
return context.Orders.Where(x => x.Id == model.Id).Select(x => AccessEngineStorage(x.GetViewModel)).ToList(); return context.Orders.Where(x => x.Id == model.Id).Select(x => AccessEngineStorage(x.GetViewModel)).ToList();
if (model.ClientId.HasValue) if (model.ClientId.HasValue)
return context.Orders.Where(x => x.ClientId == model.ClientId).Select(x => AccessEngineStorage(x.GetViewModel)).ToList(); return context.Orders.Where(x => x.ClientId == model.ClientId).Select(x => AccessEngineStorage(x.GetViewModel)).ToList();
return context.Orders.Where(x => x.DateCreate >= model.DateFrom).Where(x => x.DateCreate <= model.DateTo). return context.Orders.Include(x => x.Engine).Include(x => x.Client).Include(x => x.Implementer).Where(x =>
Select(x => AccessEngineStorage(x.GetViewModel)).ToList(); (model.DateFrom.HasValue && model.DateTo.HasValue && x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) ||
(model.ClientId.HasValue && x.ClientId == model.ClientId) ||
(model.Status.HasValue && x.Status == model.Status))
.Select(x => x.GetViewModel).ToList();
} }
public OrderViewModel? GetElement(OrderSearchModel model) public OrderViewModel? GetElement(OrderSearchModel model)
{ {
if (!model.Id.HasValue) if (!model.Id.HasValue && (!model.ImplementerId.HasValue || !model.Status.HasValue))
{ {
return null; return null;
} }
using var context = new MotorPlantDatabase(); using var context = new MotorPlantDatabase();
return AccessEngineStorage(context.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel); return context.Orders.Include(x => x.Engine).Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x =>
(model.Id.HasValue && x.Id == model.Id) ||
(model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId && x.Status == model.Status))
?.GetViewModel;
} }
public OrderViewModel? Insert(OrderBindingModel model) public OrderViewModel? Insert(OrderBindingModel model)
{ {
var newOrder = Order.Create(model); using var context = new MotorPlantDatabase();
if (model == null)
return null;
var newOrder = Order.Create(context, model);
if (newOrder == null) if (newOrder == null)
{ {
return null; return null;
} }
using var context = new MotorPlantDatabase();
context.Orders.Add(newOrder); context.Orders.Add(newOrder);
context.SaveChanges(); context.SaveChanges();
return AccessEngineStorage(newOrder.GetViewModel); return AccessEngineStorage(newOrder.GetViewModel);
} }
public OrderViewModel? Update(OrderBindingModel model) public OrderViewModel? Update(OrderBindingModel model)
{ {
using var context = new MotorPlantDatabase(); using var context = new MotorPlantDatabase();
@ -60,10 +69,11 @@ namespace MotorPlantDatabaseImplement.Implements
{ {
return null; return null;
} }
order.Update(model); order.Update(context, model);
context.SaveChanges(); context.SaveChanges();
return AccessEngineStorage(order.GetViewModel); return AccessEngineStorage(order.GetViewModel);
} }
public OrderViewModel? Delete(OrderBindingModel model) public OrderViewModel? Delete(OrderBindingModel model)
{ {
using var context = new MotorPlantDatabase(); using var context = new MotorPlantDatabase();
@ -82,11 +92,11 @@ namespace MotorPlantDatabaseImplement.Implements
if (model == null) if (model == null)
return null; return null;
using var context = new MotorPlantDatabase(); using var context = new MotorPlantDatabase();
foreach (var Flower in context.Engines) foreach (var Engine in context.Engines)
{ {
if (Flower.Id == model.EngineId) if (Engine.Id == model.EngineId)
{ {
model.EngineName = Flower.EngineName; model.EngineName = Engine.EngineName;
break; break;
} }
} }
@ -98,6 +108,14 @@ namespace MotorPlantDatabaseImplement.Implements
return model; return model;
} }
} }
foreach (var implementer in context.Implementers)
{
if (implementer.Id == model.ImplementerId)
{
model.ImplementerFIO = implementer.ImplementerFIO;
return model;
}
}
return model; return model;
} }
} }

View File

@ -12,8 +12,8 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace MotorPlantDatabaseImplement.Migrations namespace MotorPlantDatabaseImplement.Migrations
{ {
[DbContext(typeof(MotorPlantDatabase))] [DbContext(typeof(MotorPlantDatabase))]
[Migration("20240407191059_NewMigration1")] [Migration("20240418124911_InitMigrationFor6Lab")]
partial class NewMigration1 partial class InitMigrationFor6Lab
{ {
/// <inheritdoc /> /// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder) protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -116,6 +116,33 @@ namespace MotorPlantDatabaseImplement.Migrations
b.ToTable("EngineComponents"); b.ToTable("EngineComponents");
}); });
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Qualification")
.HasColumnType("integer");
b.Property<int>("WorkExperience")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@ -139,6 +166,9 @@ namespace MotorPlantDatabaseImplement.Migrations
b.Property<int>("EngineId") b.Property<int>("EngineId")
.HasColumnType("integer"); .HasColumnType("integer");
b.Property<int?>("ImplementerId")
.HasColumnType("integer");
b.Property<int>("Status") b.Property<int>("Status")
.HasColumnType("integer"); .HasColumnType("integer");
@ -147,8 +177,12 @@ namespace MotorPlantDatabaseImplement.Migrations
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("EngineId"); b.HasIndex("EngineId");
b.HasIndex("ImplementerId");
b.ToTable("Orders"); b.ToTable("Orders");
}); });
@ -173,11 +207,27 @@ namespace MotorPlantDatabaseImplement.Migrations
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b =>
{ {
b.HasOne("MotorPlantDatabaseImplement.Models.Engine", null) b.HasOne("MotorPlantDatabaseImplement.Models.Client", "Client")
.WithMany()
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine")
.WithMany("Orders") .WithMany("Orders")
.HasForeignKey("EngineId") .HasForeignKey("EngineId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.HasOne("MotorPlantDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Order")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("Engine");
b.Navigation("Implementer");
}); });
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b => modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b =>
@ -191,6 +241,11 @@ namespace MotorPlantDatabaseImplement.Migrations
b.Navigation("Orders"); b.Navigation("Orders");
}); });
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Order");
});
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
} }

View File

@ -7,7 +7,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace MotorPlantDatabaseImplement.Migrations namespace MotorPlantDatabaseImplement.Migrations
{ {
/// <inheritdoc /> /// <inheritdoc />
public partial class NewMigration1 : Migration public partial class InitMigrationFor6Lab : Migration
{ {
/// <inheritdoc /> /// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder) protected override void Up(MigrationBuilder migrationBuilder)
@ -55,6 +55,22 @@ namespace MotorPlantDatabaseImplement.Migrations
table.PrimaryKey("PK_Engines", x => x.Id); table.PrimaryKey("PK_Engines", x => x.Id);
}); });
migrationBuilder.CreateTable(
name: "Implementers",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ImplementerFIO = table.Column<string>(type: "text", nullable: false),
Password = table.Column<string>(type: "text", nullable: false),
WorkExperience = table.Column<int>(type: "integer", nullable: false),
Qualification = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Implementers", x => x.Id);
});
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "EngineComponents", name: "EngineComponents",
columns: table => new columns: table => new
@ -90,6 +106,7 @@ namespace MotorPlantDatabaseImplement.Migrations
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
EngineId = table.Column<int>(type: "integer", nullable: false), EngineId = table.Column<int>(type: "integer", nullable: false),
ClientId = table.Column<int>(type: "integer", nullable: false), ClientId = table.Column<int>(type: "integer", nullable: false),
ImplementerId = table.Column<int>(type: "integer", nullable: true),
Count = table.Column<int>(type: "integer", nullable: false), Count = table.Column<int>(type: "integer", nullable: false),
Sum = table.Column<double>(type: "double precision", nullable: false), Sum = table.Column<double>(type: "double precision", nullable: false),
Status = table.Column<int>(type: "integer", nullable: false), Status = table.Column<int>(type: "integer", nullable: false),
@ -99,12 +116,23 @@ namespace MotorPlantDatabaseImplement.Migrations
constraints: table => constraints: table =>
{ {
table.PrimaryKey("PK_Orders", x => x.Id); table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Clients_ClientId",
column: x => x.ClientId,
principalTable: "Clients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey( table.ForeignKey(
name: "FK_Orders_Engines_EngineId", name: "FK_Orders_Engines_EngineId",
column: x => x.EngineId, column: x => x.EngineId,
principalTable: "Engines", principalTable: "Engines",
principalColumn: "Id", principalColumn: "Id",
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
column: x => x.ImplementerId,
principalTable: "Implementers",
principalColumn: "Id");
}); });
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
@ -117,18 +145,25 @@ namespace MotorPlantDatabaseImplement.Migrations
table: "EngineComponents", table: "EngineComponents",
column: "EngineId"); column: "EngineId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ClientId",
table: "Orders",
column: "ClientId");
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
name: "IX_Orders_EngineId", name: "IX_Orders_EngineId",
table: "Orders", table: "Orders",
column: "EngineId"); column: "EngineId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
} }
/// <inheritdoc /> /// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder) protected override void Down(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "EngineComponents"); name: "EngineComponents");
@ -138,8 +173,14 @@ namespace MotorPlantDatabaseImplement.Migrations
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "Components"); name: "Components");
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "Engines"); name: "Engines");
migrationBuilder.DropTable(
name: "Implementers");
} }
} }
} }

View File

@ -113,6 +113,33 @@ namespace MotorPlantDatabaseImplement.Migrations
b.ToTable("EngineComponents"); b.ToTable("EngineComponents");
}); });
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Qualification")
.HasColumnType("integer");
b.Property<int>("WorkExperience")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@ -136,6 +163,9 @@ namespace MotorPlantDatabaseImplement.Migrations
b.Property<int>("EngineId") b.Property<int>("EngineId")
.HasColumnType("integer"); .HasColumnType("integer");
b.Property<int?>("ImplementerId")
.HasColumnType("integer");
b.Property<int>("Status") b.Property<int>("Status")
.HasColumnType("integer"); .HasColumnType("integer");
@ -144,8 +174,12 @@ namespace MotorPlantDatabaseImplement.Migrations
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("EngineId"); b.HasIndex("EngineId");
b.HasIndex("ImplementerId");
b.ToTable("Orders"); b.ToTable("Orders");
}); });
@ -170,11 +204,27 @@ namespace MotorPlantDatabaseImplement.Migrations
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b => modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Order", b =>
{ {
b.HasOne("MotorPlantDatabaseImplement.Models.Engine", null) b.HasOne("MotorPlantDatabaseImplement.Models.Client", "Client")
.WithMany()
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("MotorPlantDatabaseImplement.Models.Engine", "Engine")
.WithMany("Orders") .WithMany("Orders")
.HasForeignKey("EngineId") .HasForeignKey("EngineId")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.HasOne("MotorPlantDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Order")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("Engine");
b.Navigation("Implementer");
}); });
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b => modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Component", b =>
@ -188,6 +238,11 @@ namespace MotorPlantDatabaseImplement.Migrations
b.Navigation("Orders"); b.Navigation("Orders");
}); });
modelBuilder.Entity("MotorPlantDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Order");
});
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
} }

View File

@ -0,0 +1,65 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Models;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace MotorPlantDatabaseImplement.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

@ -10,10 +10,20 @@ namespace MotorPlantDatabaseImplement.Models
{ {
public int Id { get; private set; } public int Id { get; private set; }
public int EngineId { get; private set; } [Required]
public int EngineId { get; private set; }
public virtual Engine Engine { get; set; } = new();
[Required]
public int ClientId { get; private set; } public int ClientId { get; private set; }
public virtual Client Client { get; private set; } = new();
public int? ImplementerId { get; private set; }
public virtual Implementer? Implementer { get; set; } = new();
[Required] [Required]
public int Count { get; private set; } public int Count { get; private set; }
@ -28,17 +38,17 @@ namespace MotorPlantDatabaseImplement.Models
public DateTime? DateImplement { get; private set; } public DateTime? DateImplement { get; private set; }
public static Order? Create(OrderBindingModel? model) public static Order Create(MotorPlantDatabase context, OrderBindingModel model)
{ {
if (model == null)
{
return null;
}
return new Order() return new Order()
{ {
Id = model.Id, Id = model.Id,
EngineId = model.EngineId, EngineId = model.EngineId,
Engine = context.Engines.First(x => x.Id == model.EngineId),
ClientId = model.ClientId, ClientId = model.ClientId,
Client = context.Clients.First(x => x.Id == model.ClientId),
ImplementerId = model.ImplementerId,
Implementer = model.ImplementerId.HasValue ? context.Implementers.First(x => x.Id == model.ImplementerId) : null,
Count = model.Count, Count = model.Count,
Sum = model.Sum, Sum = model.Sum,
Status = model.Status, Status = model.Status,
@ -47,7 +57,7 @@ namespace MotorPlantDatabaseImplement.Models
}; };
} }
public void Update(OrderBindingModel model) public void Update(MotorPlantDatabase context, OrderBindingModel? model)
{ {
if (model == null) if (model == null)
{ {
@ -55,13 +65,19 @@ namespace MotorPlantDatabaseImplement.Models
} }
Status = model.Status; Status = model.Status;
DateImplement = model.DateImplement; DateImplement = model.DateImplement;
} ImplementerId = model.ImplementerId;
Implementer = model.ImplementerId.HasValue ? context.Implementers.First(x => x.Id == model.ImplementerId) : null;
}
public OrderViewModel GetViewModel => new() public OrderViewModel GetViewModel => new()
{ {
Id = Id, Id = Id,
EngineId = EngineId, EngineId = EngineId,
EngineName = Engine.EngineName,
ClientId = ClientId, ClientId = ClientId,
ClientFIO = Client.ClientFIO,
ImplementerId = ImplementerId,
ImplementerFIO = Implementer != null ? Implementer.ImplementerFIO : null,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,

View File

@ -9,7 +9,7 @@ namespace MotorPlantDatabaseImplement
{ {
if (optionsBuilder.IsConfigured == false) if (optionsBuilder.IsConfigured == false)
{ {
optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=MotorPlant_db;Username=postgres;Password=admin"); optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=MotorPlant_lab6_db;Username=postgres;Password=admin");
} }
base.OnConfiguring(optionsBuilder); base.OnConfiguring(optionsBuilder);
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
@ -20,5 +20,6 @@ namespace MotorPlantDatabaseImplement
public virtual DbSet<EngineComponent> EngineComponents { get; set; } public virtual DbSet<EngineComponent> EngineComponents { get; set; }
public virtual DbSet<Order> Orders { get; set; } public virtual DbSet<Order> Orders { get; set; }
public virtual DbSet<Client> Clients { set; get; } public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; }
} }
} }

View File

@ -15,6 +15,8 @@ namespace MotorPlantFileImplement
private readonly string ClientFileName = "Client.xml"; private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
public List<Component> Components { get; private set; } public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; } public List<Order> Orders { get; private set; }
@ -23,6 +25,9 @@ namespace MotorPlantFileImplement
public List<Client> Clients { get; private set; } public List<Client> Clients { get; private set; }
public List<Implementer> Implementers { get; private set; }
public static DataFileSingleton GetInstance() public static DataFileSingleton GetInstance()
{ {
if (instance == null) if (instance == null)
@ -39,12 +44,15 @@ namespace MotorPlantFileImplement
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", 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() private DataFileSingleton()
{ {
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Engines = LoadData(EngineFileName, "Engine", x => Engine.Create(x)!)!; Engines = LoadData(EngineFileName, "Engine", x => Engine.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!;
} }
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction) private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)

View File

@ -0,0 +1,94 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantFileImplement.Models;
namespace MotorPlantFileImplement.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 (model == null)
{
return new();
}
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
if (model.ImplementerFIO != null)
{
return _source.Implementers
.Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (model.Id.HasValue)
{
return _source.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
if (model.ImplementerFIO != null && model.Password != null)
{
return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel;
}
if (model.ImplementerFIO != null)
{
return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel;
}
return null;
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = _source.Implementers.Count > 0 ? _source.Implementers.Max(x => x.Id) + 1 : 1;
var res = Implementer.Create(model);
if (res != null)
{
_source.Implementers.Add(res);
_source.SaveImplementers();
}
return res?.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
res.Update(model);
_source.SaveImplementers();
}
return res?.GetViewModel;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
_source.Implementers.Remove(res);
_source.SaveImplementers();
}
return res?.GetViewModel;
}
}
}

View File

@ -24,17 +24,35 @@ namespace MotorPlantFileImplement.Implements
} }
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) 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.ImplementerId.HasValue && !model.Id.HasValue)
{
return source.Orders.Where(x => x.ImplementerId == model.ImplementerId).Select(x => x.GetViewModel).ToList();
}
if (model.Id.HasValue) if (model.Id.HasValue)
return source.Orders.Where(x => x.Id == model.Id) {
.Select(x => GetViewModel(x)) return source.Orders.Where(x => x.Id.Equals(model.Id)).Select(x => GetViewModel(x)).ToList();
.ToList(); }
if (model.ClientId.HasValue) return new();
return source.Orders.Where(x => x.ClientId == model.ClientId).Select(x => GetViewModel(x)).ToList();
return source.Orders.Where(x => x.DateCreate >= model.DateFrom).Where(x => x.DateCreate <= model.DateTo).
Select(x => GetViewModel(x)).ToList();
} }
public OrderViewModel? GetElement(OrderSearchModel model) public OrderViewModel? GetElement(OrderSearchModel model)
{ {
if (model.ImplementerId.HasValue)
{
return source.Orders.FirstOrDefault(x => x.ImplementerId == model.ImplementerId)?.GetViewModel;
}
if (!model.Id.HasValue) if (!model.Id.HasValue)
{ {
return null; return null;
@ -78,9 +96,9 @@ namespace MotorPlantFileImplement.Implements
private OrderViewModel GetViewModel(Order order) private OrderViewModel GetViewModel(Order order)
{ {
var viewModel = order.GetViewModel; var viewModel = order.GetViewModel;
var flower = source.Engines.FirstOrDefault(x => x.Id == order.EngineId); var engine = source.Engines.FirstOrDefault(x => x.Id == order.EngineId);
var client = source.Clients.FirstOrDefault(x => x.Id == order.ClientId); var client = source.Clients.FirstOrDefault(x => x.Id == order.ClientId);
viewModel.EngineName = flower?.EngineName; viewModel.EngineName = engine?.EngineName;
viewModel.ClientFIO = client?.ClientFIO; viewModel.ClientFIO = client?.ClientFIO;
return viewModel; return viewModel;
} }

View File

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

View File

@ -10,12 +10,14 @@ namespace MotorPlantFileImplement.Models
{ {
public int EngineId { get; private set; } public int EngineId { get; private set; }
public int ClientId { get; private set; } public int ClientId { get; private set; }
public int? ImplementerId { get; set; }
public int Count { get; private set; } public int Count { get; private set; }
public double Sum { get; private set; } public double Sum { get; private set; }
public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; private set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; private set; } = DateTime.Now; public DateTime DateCreate { get; private set; } = DateTime.Now;
public DateTime? DateImplement { get; private set; } public DateTime? DateImplement { get; private set; }
public int Id { get; private set; } public int Id { get; private set; }
public static Order? Create(OrderBindingModel? model) public static Order? Create(OrderBindingModel? model)
{ {
if (model == null) if (model == null)
@ -27,70 +29,64 @@ namespace MotorPlantFileImplement.Models
Id = model.Id, Id = model.Id,
EngineId = model.EngineId, EngineId = model.EngineId,
ClientId = model.ClientId, ClientId = model.ClientId,
Count = model.Count, ImplementerId = model.ImplementerId,
Count = model.Count,
Sum = model.Sum, Sum = model.Sum,
Status = model.Status, Status = model.Status,
DateCreate = model.DateCreate, DateCreate = model.DateCreate,
DateImplement = model.DateImplement DateImplement = model.DateImplement
}; };
} }
public static Order? Create(XElement element) public static Order? Create(XElement element)
{ {
if (element == null) if (element == null)
{ {
return null; return null;
} }
var order = new Order() string dateImplement = element.Element("DateImplement")!.Value;
{ return new Order()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value), Id = Convert.ToInt32(element.Attribute("Id")!.Value),
EngineId = Convert.ToInt32(element.Element("EngineId")!.Value), EngineId = Convert.ToInt32(element.Element("EngineId")!.Value),
ClientId = Convert.ToInt32(element.Element("ClientId")!.Value), ClientId = Convert.ToInt32(element.Element("ClientId")!.Value),
ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value), Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value), Sum = Convert.ToDouble(element.Element("Sum")!.Value),
DateCreate = DateTime.ParseExact(element.Element("DateCreate")!.Value, "G", null), Status = (OrderStatus)(Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value)),
}; DateCreate = DateTime.ParseExact(element.Element("DateCreate")!.Value, "G", null),
DateTime.TryParse(element.Element("DateImplement")!.Value, out DateTime dateImpl); DateImplement = (dateImplement == "" || dateImplement is null) ? Convert.ToDateTime(null) : Convert.ToDateTime(dateImplement)
};
order.DateImplement = dateImpl;
if (!Enum.TryParse(element.Element("Status")!.Value, out OrderStatus status))
{
return null;
}
order.Status = status;
return order;
} }
public void Update(OrderBindingModel? model) public void Update(OrderBindingModel? model)
{ {
if (model == null) if (model == null)
{ {
return; return;
} }
Id = model.Id;
EngineId = model.EngineId;
ClientId = model.ClientId;
Count = model.Count;
Sum = model.Sum;
Status = model.Status; Status = model.Status;
DateCreate = model.DateCreate; if (model.Status == OrderStatus.Выдан) DateImplement = model.DateImplement;
DateImplement = model.DateImplement;
} }
public OrderViewModel GetViewModel => new() public OrderViewModel GetViewModel => new()
{ {
Id = Id, Id = Id,
EngineId = EngineId, EngineId = EngineId,
ClientId = ClientId, ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,
DateCreate = DateCreate, DateCreate = DateCreate,
DateImplement = DateImplement DateImplement = DateImplement
}; };
public XElement GetXElement => new("Order", public XElement GetXElement => new("Order",
new XAttribute("Id", Id), new XAttribute("Id", Id),
new XElement("EngineId", EngineId), new XElement("EngineId", EngineId),
new XElement("ClientId", ClientId.ToString()), new XElement("ClientId", ClientId.ToString()),
new XElement("ImplementerId", ImplementerId),
new XElement("Count", Count.ToString()), new XElement("Count", Count.ToString()),
new XElement("Sum", Sum.ToString()), new XElement("Sum", Sum.ToString()),
new XElement("Status", Status.ToString()), new XElement("Status", Status.ToString()),

View File

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

View File

@ -0,0 +1,118 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.StoragesContracts;
using MotorPlantContracts.ViewModels;
using MotorPlantListImplement.Models;
namespace MotorPlantListImplement.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

@ -31,26 +31,44 @@ namespace MotorPlantListImplement.Implements
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{ {
var result = new List<OrderViewModel>(); var result = new List<OrderViewModel>();
if (model == null || !model.Id.HasValue) if (model.DateFrom.HasValue)
{
return result;
}
if (model.ClientId.HasValue)
{ {
foreach (var order in _source.Orders) foreach (var order in _source.Orders)
{ {
if (order.Id == model.Id && order.ClientId == model.ClientId) if (order.DateCreate >= model.DateFrom && order.DateCreate <= model.DateTo)
{ {
result.Add(AttachNames(order.GetViewModel)); result.Add(AttachNames(order.GetViewModel));
} }
} }
return result;
} }
foreach (var order in _source.Orders) else if (model.ClientId.HasValue && !model.Id.HasValue)
{ {
if (order.Id == model.Id && order.DateCreate >= model.DateFrom && order.DateCreate <= model.DateTo) foreach (var order in _source.Orders)
{ {
result.Add(AttachNames(order.GetViewModel)); if (order.ClientId == model.ClientId)
{
result.Add(AttachNames(order.GetViewModel));
}
}
}
else if (model.ImplementerId.HasValue && !model.Id.HasValue)
{
foreach (var order in _source.Orders)
{
if (order.ImplementerId == model.ImplementerId)
{
result.Add(AttachNames(order.GetViewModel));
}
}
}
else if (model.Id.HasValue)
{
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
result.Add(AttachNames(order.GetViewModel));
}
} }
} }
return result; return result;

View File

@ -0,0 +1,55 @@
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Models;
namespace MotorPlantListImplement.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()
{
Id = model.Id,
Password = model.Password,
Qualification = model.Qualification,
ImplementerFIO = model.ImplementerFIO,
WorkExperience = model.WorkExperience,
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
Password = model.Password;
Qualification = model.Qualification;
ImplementerFIO = model.ImplementerFIO;
WorkExperience = model.WorkExperience;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Password = Password,
Qualification = Qualification,
ImplementerFIO = ImplementerFIO,
};
}
}

View File

@ -18,6 +18,8 @@ namespace MotorPlantListImplement.Models
public int ClientId { get; private set; } public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
public int Count { get; private set; } public int Count { get; private set; }
public double Sum { get; private set; } public double Sum { get; private set; }
@ -39,6 +41,7 @@ namespace MotorPlantListImplement.Models
Id = model.Id, Id = model.Id,
EngineId = model.EngineId, EngineId = model.EngineId,
ClientId = model.ClientId, ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
Count = model.Count, Count = model.Count,
Sum = model.Sum, Sum = model.Sum,
Status = model.Status, Status = model.Status,
@ -52,20 +55,15 @@ namespace MotorPlantListImplement.Models
{ {
return; return;
} }
Id = model.Id;
EngineId = model.EngineId;
ClientId = model.ClientId;
Count = model.Count;
Sum = model.Sum;
Status = model.Status; Status = model.Status;
DateCreate = model.DateCreate; if (model.Status == OrderStatus.Выдан) DateImplement = model.DateImplement;
DateImplement = model.DateImplement;
} }
public OrderViewModel GetViewModel => new() public OrderViewModel GetViewModel => new()
{ {
Id = Id, Id = Id,
EngineId = EngineId, EngineId = EngineId,
ClientId = ClientId, ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,

View File

@ -0,0 +1,107 @@
using Microsoft.AspNetCore.Mvc;
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.SearchModels;
using MotorPlantContracts.ViewModels;
using MotorPlantDataModels.Enums;
namespace MotorPlantRestApi.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

@ -11,10 +11,12 @@ builder.Logging.AddLog4Net("log4net.config");
builder.Services.AddTransient<IClientStorage, ClientStorage>(); builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IImplementerStorage, ImplementerStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>(); builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IEngineStorage, EngineStorage>(); builder.Services.AddTransient<IEngineStorage, EngineStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>(); builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IImplementerLogic, ImplementerLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>(); builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IEngineLogic, EngineLogic>(); builder.Services.AddTransient<IEngineLogic, EngineLogic>();

View File

@ -104,6 +104,7 @@ namespace MotorPlantView.Forms
var operationResult = _logicO.CreateOrder(new OrderBindingModel var operationResult = _logicO.CreateOrder(new OrderBindingModel
{ {
EngineId = Convert.ToInt32(comboBoxEngine.SelectedValue), EngineId = Convert.ToInt32(comboBoxEngine.SelectedValue),
ClientId = Convert.ToInt32(comboBoxClient.SelectedValue),
Count = Convert.ToInt32(textBoxCount.Text), Count = Convert.ToInt32(textBoxCount.Text),
Sum = Convert.ToDouble(textBoxSum.Text) Sum = Convert.ToDouble(textBoxSum.Text)
}); });

View File

@ -0,0 +1,167 @@
namespace MotorPlantView
{
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()
{
this.textBoxFIO = new System.Windows.Forms.TextBox();
this.labelFIO = new System.Windows.Forms.Label();
this.textBoxPassword = new System.Windows.Forms.TextBox();
this.labelPassword = new System.Windows.Forms.Label();
this.labelWorkExperience = new System.Windows.Forms.Label();
this.numericUpDownWorkExperience = new System.Windows.Forms.NumericUpDown();
this.numericUpDownQualification = new System.Windows.Forms.NumericUpDown();
this.labelQualification = new System.Windows.Forms.Label();
this.buttonCancel = new System.Windows.Forms.Button();
this.buttonSave = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWorkExperience)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownQualification)).BeginInit();
this.SuspendLayout();
//
// textBoxFIO
//
this.textBoxFIO.Location = new System.Drawing.Point(157, 12);
this.textBoxFIO.Name = "textBoxFIO";
this.textBoxFIO.Size = new System.Drawing.Size(382, 27);
this.textBoxFIO.TabIndex = 3;
//
// labelFIO
//
this.labelFIO.AutoSize = true;
this.labelFIO.Location = new System.Drawing.Point(12, 15);
this.labelFIO.Name = "labelFIO";
this.labelFIO.Size = new System.Drawing.Size(139, 20);
this.labelFIO.TabIndex = 2;
this.labelFIO.Text = "ФИО исполнителя:";
//
// textBoxPassword
//
this.textBoxPassword.Location = new System.Drawing.Point(157, 50);
this.textBoxPassword.Name = "textBoxPassword";
this.textBoxPassword.Size = new System.Drawing.Size(205, 27);
this.textBoxPassword.TabIndex = 5;
//
// labelPassword
//
this.labelPassword.AutoSize = true;
this.labelPassword.Location = new System.Drawing.Point(12, 53);
this.labelPassword.Name = "labelPassword";
this.labelPassword.Size = new System.Drawing.Size(65, 20);
this.labelPassword.TabIndex = 4;
this.labelPassword.Text = "Пароль:";
//
// labelWorkExperience
//
this.labelWorkExperience.AutoSize = true;
this.labelWorkExperience.Location = new System.Drawing.Point(12, 99);
this.labelWorkExperience.Name = "labelWorkExperience";
this.labelWorkExperience.Size = new System.Drawing.Size(105, 20);
this.labelWorkExperience.TabIndex = 6;
this.labelWorkExperience.Text = "Опыт работы:";
//
// numericUpDownWorkExperience
//
this.numericUpDownWorkExperience.Location = new System.Drawing.Point(157, 97);
this.numericUpDownWorkExperience.Name = "numericUpDownWorkExperience";
this.numericUpDownWorkExperience.Size = new System.Drawing.Size(124, 27);
this.numericUpDownWorkExperience.TabIndex = 8;
//
// numericUpDownQualification
//
this.numericUpDownQualification.Location = new System.Drawing.Point(157, 142);
this.numericUpDownQualification.Name = "numericUpDownQualification";
this.numericUpDownQualification.Size = new System.Drawing.Size(124, 27);
this.numericUpDownQualification.TabIndex = 10;
//
// labelQualification
//
this.labelQualification.AutoSize = true;
this.labelQualification.Location = new System.Drawing.Point(12, 144);
this.labelQualification.Name = "labelQualification";
this.labelQualification.Size = new System.Drawing.Size(114, 20);
this.labelQualification.TabIndex = 9;
this.labelQualification.Text = "Квалификация:";
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(422, 203);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(136, 40);
this.buttonCancel.TabIndex = 12;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(265, 203);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(130, 40);
this.buttonSave.TabIndex = 11;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// FormImplementer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(570, 255);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.numericUpDownQualification);
this.Controls.Add(this.labelQualification);
this.Controls.Add(this.numericUpDownWorkExperience);
this.Controls.Add(this.labelWorkExperience);
this.Controls.Add(this.textBoxPassword);
this.Controls.Add(this.labelPassword);
this.Controls.Add(this.textBoxFIO);
this.Controls.Add(this.labelFIO);
this.Name = "FormImplementer";
this.Text = "Исполнитель";
this.Load += new System.EventHandler(this.FormImplementer_Load);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownWorkExperience)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownQualification)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private TextBox textBoxFIO;
private Label labelFIO;
private TextBox textBoxPassword;
private Label labelPassword;
private Label labelWorkExperience;
private NumericUpDown numericUpDownWorkExperience;
private NumericUpDown numericUpDownQualification;
private Label labelQualification;
private Button buttonCancel;
private Button buttonSave;
}
}

View File

@ -0,0 +1,94 @@
using Microsoft.Extensions.Logging;
using MotorPlantContracts.BindingModels;
using MotorPlantContracts.BusinessLogicsContracts;
using MotorPlantContracts.SearchModels;
namespace MotorPlantView
{
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;
numericUpDownWorkExperience.Value = view.WorkExperience;
numericUpDownQualification.Value = view.Qualification;
}
}
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 = (int)numericUpDownWorkExperience.Value,
Qualification = (int)numericUpDownQualification.Value
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при создании или обновлении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

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

@ -0,0 +1,130 @@
namespace MotorPlantView
{
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()
{
this.ToolsPanel = new System.Windows.Forms.Panel();
this.buttonRef = new System.Windows.Forms.Button();
this.buttonDel = new System.Windows.Forms.Button();
this.buttonUpd = new System.Windows.Forms.Button();
this.buttonAdd = new System.Windows.Forms.Button();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.ToolsPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// ToolsPanel
//
this.ToolsPanel.Controls.Add(this.buttonRef);
this.ToolsPanel.Controls.Add(this.buttonDel);
this.ToolsPanel.Controls.Add(this.buttonUpd);
this.ToolsPanel.Controls.Add(this.buttonAdd);
this.ToolsPanel.Location = new System.Drawing.Point(608, 12);
this.ToolsPanel.Name = "ToolsPanel";
this.ToolsPanel.Size = new System.Drawing.Size(180, 426);
this.ToolsPanel.TabIndex = 3;
//
// buttonRef
//
this.buttonRef.Location = new System.Drawing.Point(31, 206);
this.buttonRef.Name = "buttonRef";
this.buttonRef.Size = new System.Drawing.Size(126, 36);
this.buttonRef.TabIndex = 3;
this.buttonRef.Text = "Обновить";
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += new System.EventHandler(this.buttonRef_Click);
//
// buttonDel
//
this.buttonDel.Location = new System.Drawing.Point(31, 142);
this.buttonDel.Name = "buttonDel";
this.buttonDel.Size = new System.Drawing.Size(126, 36);
this.buttonDel.TabIndex = 2;
this.buttonDel.Text = "Удалить";
this.buttonDel.UseVisualStyleBackColor = true;
this.buttonDel.Click += new System.EventHandler(this.buttonDel_Click);
//
// buttonUpd
//
this.buttonUpd.Location = new System.Drawing.Point(31, 76);
this.buttonUpd.Name = "buttonUpd";
this.buttonUpd.Size = new System.Drawing.Size(126, 36);
this.buttonUpd.TabIndex = 1;
this.buttonUpd.Text = "Изменить";
this.buttonUpd.UseVisualStyleBackColor = true;
this.buttonUpd.Click += new System.EventHandler(this.buttonUpd_Click);
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(31, 16);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(126, 36);
this.buttonAdd.TabIndex = 0;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// dataGridView
//
this.dataGridView.AllowUserToAddRows = false;
this.dataGridView.AllowUserToDeleteRows = false;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(12, 12);
this.dataGridView.Name = "dataGridView";
this.dataGridView.ReadOnly = true;
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(590, 426);
this.dataGridView.TabIndex = 2;
//
// FormImplementers
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.ToolsPanel);
this.Controls.Add(this.dataGridView);
this.Name = "FormImplementers";
this.Text = "Исполнители";
this.Load += new System.EventHandler(this.FormImplementers_Load);
this.ToolsPanel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private Panel ToolsPanel;
private Button buttonRef;
private Button buttonDel;
private Button buttonUpd;
private Button buttonAdd;
private DataGridView dataGridView;
}
}

View File

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

View File

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

@ -32,17 +32,19 @@
toolStripDropDownButton1 = new ToolStripDropDownButton(); toolStripDropDownButton1 = new ToolStripDropDownButton();
КомпонентыToolStripMenuItem = new ToolStripMenuItem(); КомпонентыToolStripMenuItem = new ToolStripMenuItem();
ДвигателиToolStripMenuItem = new ToolStripMenuItem(); ДвигателиToolStripMenuItem = new ToolStripMenuItem();
клиентыToolStripMenuItem = new ToolStripMenuItem();
исполнителиToolStripMenuItem = new ToolStripMenuItem();
отчетыToolStripMenuItem = new ToolStripMenuItem(); отчетыToolStripMenuItem = new ToolStripMenuItem();
списокДвигателейToolStripMenuItem = new ToolStripMenuItem(); списокДвигателейToolStripMenuItem = new ToolStripMenuItem();
компонентыПоДвигателямToolStripMenuItem = new ToolStripMenuItem(); компонентыПоДвигателямToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); списокЗаказовToolStripMenuItem = new ToolStripMenuItem();
запускРаботToolStripMenuItem = new ToolStripMenuItem();
buttonCreateOrder = new Button(); buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button(); buttonTakeOrderInWork = new Button();
buttonOrderReady = new Button(); buttonOrderReady = new Button();
buttonIssuedOrder = new Button(); buttonIssuedOrder = new Button();
buttonRef = new Button(); buttonRef = new Button();
dataGridView = new DataGridView(); dataGridView = new DataGridView();
клиентыToolStripMenuItem = new ToolStripMenuItem();
toolStrip1.SuspendLayout(); toolStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout(); SuspendLayout();
@ -50,7 +52,7 @@
// toolStrip1 // toolStrip1
// //
toolStrip1.ImageScalingSize = new Size(20, 20); toolStrip1.ImageScalingSize = new Size(20, 20);
toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, отчетыToolStripMenuItem }); toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripDropDownButton1, отчетыToolStripMenuItem, запускРаботToolStripMenuItem });
toolStrip1.Location = new Point(0, 0); toolStrip1.Location = new Point(0, 0);
toolStrip1.Name = "toolStrip1"; toolStrip1.Name = "toolStrip1";
toolStrip1.Size = new Size(985, 25); toolStrip1.Size = new Size(985, 25);
@ -60,7 +62,7 @@
// toolStripDropDownButton1 // toolStripDropDownButton1
// //
toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text; toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text;
toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, клиентыToolStripMenuItem }); toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { КомпонентыToolStripMenuItem, ДвигателиToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem });
toolStripDropDownButton1.ImageTransparentColor = Color.Magenta; toolStripDropDownButton1.ImageTransparentColor = Color.Magenta;
toolStripDropDownButton1.Name = "toolStripDropDownButton1"; toolStripDropDownButton1.Name = "toolStripDropDownButton1";
toolStripDropDownButton1.Size = new Size(88, 22); toolStripDropDownButton1.Size = new Size(88, 22);
@ -69,17 +71,31 @@
// КомпонентыToolStripMenuItem // КомпонентыToolStripMenuItem
// //
КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem"; КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem";
КомпонентыToolStripMenuItem.Size = new Size(180, 22); КомпонентыToolStripMenuItem.Size = new Size(149, 22);
КомпонентыToolStripMenuItem.Text = "Компоненты"; КомпонентыToolStripMenuItem.Text = "Компоненты";
КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; КомпонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click;
// //
// ДвигателиToolStripMenuItem // ДвигателиToolStripMenuItem
// //
ДвигателиToolStripMenuItem.Name = "ДвигателиToolStripMenuItem"; ДвигателиToolStripMenuItem.Name = "ДвигателиToolStripMenuItem";
ДвигателиToolStripMenuItem.Size = new Size(180, 22); ДвигателиToolStripMenuItem.Size = new Size(149, 22);
ДвигателиToolStripMenuItem.Text = "Двигатели"; ДвигателиToolStripMenuItem.Text = "Двигатели";
ДвигателиToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; ДвигателиToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click;
// //
// клиентыToolStripMenuItem
//
клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
клиентыToolStripMenuItem.Size = new Size(149, 22);
клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click;
//
// исполнителиToolStripMenuItem
//
исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem";
исполнителиToolStripMenuItem.Size = new Size(149, 22);
исполнителиToolStripMenuItem.Text = "Исполнители";
исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click;
//
// отчетыToolStripMenuItem // отчетыToolStripMenuItem
// //
отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокДвигателейToolStripMenuItem, компонентыПоДвигателямToolStripMenuItem, списокЗаказовToolStripMenuItem }); отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокДвигателейToolStripMenuItem, компонентыПоДвигателямToolStripMenuItem, списокЗаказовToolStripMenuItem });
@ -108,6 +124,13 @@
списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокЗаказовToolStripMenuItem.Text = "Список заказов";
списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click; списокЗаказовToolStripMenuItem.Click += списокЗаказовToolStripMenuItem_Click;
// //
// запускРаботToolStripMenuItem
//
запускРаботToolStripMenuItem.Name = апускРаботToolStripMenuItem";
запускРаботToolStripMenuItem.Size = new Size(92, 25);
запускРаботToolStripMenuItem.Text = "Запуск работ";
запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click;
//
// buttonCreateOrder // buttonCreateOrder
// //
buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right; buttonCreateOrder.Anchor = AnchorStyles.Top | AnchorStyles.Right;
@ -182,13 +205,6 @@
dataGridView.Size = new Size(780, 441); dataGridView.Size = new Size(780, 441);
dataGridView.TabIndex = 6; dataGridView.TabIndex = 6;
// //
// клиентыToolStripMenuItem
//
клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
клиентыToolStripMenuItem.Size = new Size(180, 22);
клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += клиентыToolStripMenuItem_Click;
//
// FormMain // FormMain
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
@ -228,5 +244,7 @@
private ToolStripMenuItem компонентыПоДвигателямToolStripMenuItem; private ToolStripMenuItem компонентыПоДвигателямToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem; private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem;
private ToolStripMenuItem запускРаботToolStripMenuItem;
} }
} }

View File

@ -9,13 +9,15 @@ namespace MotorPlantView.Forms
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic; private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic; private readonly IReportLogic _reportLogic;
private readonly IWorkProcess _workProcess;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic) public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger; _logger = logger;
_orderLogic = orderLogic; _orderLogic = orderLogic;
_reportLogic = reportLogic; _reportLogic = reportLogic;
_workProcess = workProcess;
} }
private void FormMain_Load(object sender, EventArgs e) private void FormMain_Load(object sender, EventArgs e)
{ {
@ -33,6 +35,7 @@ namespace MotorPlantView.Forms
dataGridView.DataSource = list; dataGridView.DataSource = list;
dataGridView.Columns["EngineId"].Visible = false; dataGridView.Columns["EngineId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false; dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView.Columns["EngineName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
} }
@ -184,5 +187,20 @@ namespace MotorPlantView.Forms
form.ShowDialog(); form.ShowDialog();
} }
} }
private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (service is FormImplementers form)
{
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);
}
} }
} }

View File

@ -41,15 +41,19 @@ namespace MotorPlantView
option.AddNLog("nlog.config"); option.AddNLog("nlog.config");
}); });
services.AddTransient<IComponentStorage, ComponentStorage>(); services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>(); services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IEngineStorage, EngineStorage>(); services.AddTransient<IEngineStorage, EngineStorage>();
services.AddTransient<IClientStorage, ClientStorage>(); services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>(); services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>(); services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IEngineLogic, EngineLogic>(); services.AddTransient<IEngineLogic, EngineLogic>();
services.AddTransient<IReportLogic, ReportLogic>(); services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>(); services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>(); services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>(); services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
@ -65,6 +69,8 @@ namespace MotorPlantView
services.AddTransient<FormReportOrders>(); services.AddTransient<FormReportOrders>();
services.AddTransient<FormReportEngineComponents>(); services.AddTransient<FormReportEngineComponents>();
services.AddTransient<FormClients>(); services.AddTransient<FormClients>();
} services.AddTransient<FormImplementers>();
services.AddTransient<FormImplementer>();
}
} }
} }