ПИбд-23 Волков Никита Андреевич Лабораторная работа №6 #8

Closed
bocchanskyy wants to merge 1 commits from Lab6Base into Lab5Base
44 changed files with 2581 additions and 680 deletions

View File

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

View File

@ -52,6 +52,15 @@ namespace ComputersShopBusinessLogic.BusinessLogics
return false; return false;
} }
model.Status = newStatus; model.Status = newStatus;
model.DateCreate = viewModel.DateCreate;
model.Sum = viewModel.Sum;
model.Count = viewModel.Count;
model.DateImplement = viewModel.DateImplement;
model.ComputerId = viewModel.ComputerId;
if (viewModel.ImplementerId.HasValue)
{
model.ImplementerId = viewModel.ImplementerId;
}
if (model.Status == OrderStatus.Готов) model.DateImplement = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc); if (model.Status == OrderStatus.Готов) model.DateImplement = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc);
else else
{ {
@ -118,5 +127,21 @@ namespace ComputersShopBusinessLogic.BusinessLogics
nameof(model.Sum)); nameof(model.Sum));
} }
} }
public OrderViewModel? ReadElement(OrderSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Id:{ Id}", model.Id);
var element = _orderStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
} }
} }

View File

@ -0,0 +1,159 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BusinessLogicContracts;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Enums;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopBusinessLogic.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,22 @@
using ComputersShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopContracts.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

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

View File

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

@ -16,5 +16,6 @@ namespace ComputersShopContracts.BusinessLogicContracts
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,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using СomputersShopDataModels.Models;
namespace ComputersShopContracts.BusinessLogicContracts
{
public interface IWorkProcess
{
// <summary>
/// Запуск работ
/// </summary>
void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic);
}
}

View File

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

View File

@ -1,4 +1,5 @@
using System; using ComputersShopDataModels.Enums;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -12,5 +13,7 @@ namespace ComputersShopContracts.SearchModels
public DateTime? DateFrom { get; set; } public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; } public DateTime? DateTo { get; set; }
public int? ClientId { get; set; } public int? ClientId { get; set; }
public int? ImplementerId { get; set; }
public OrderStatus? Status { get; set; }
} }
} }

View File

@ -0,0 +1,26 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopContracts.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,27 @@
using ComputersShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopContracts.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

@ -9,25 +9,28 @@ using System.Threading.Tasks;
namespace ComputersShopContracts.ViewModels namespace ComputersShopContracts.ViewModels
{ {
public class OrderViewModel : IOrderModel public class OrderViewModel : IOrderModel
{ {
[DisplayName("Номер")] [DisplayName("Номер")]
public int Id { get; set; } public int Id { get; set; }
public int ComputerId { get; set; } public int ComputerId { get; set; }
public int ClientId { get; set; } public int ClientId { get; set; }
[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; } = string.Empty;
[DisplayName("Компьютер")] [DisplayName("Компьютер")]
public string ComputerName { get; set; } = string.Empty; public string ComputerName { get; set; } = string.Empty;
[DisplayName("Количество")] [DisplayName("Количество")]
public int Count { get; set; } public int Count { get; set; }
[DisplayName("Сумма")] [DisplayName("Сумма")]
public double Sum { get; set; } public double Sum { get; set; }
[DisplayName("Статус")] [DisplayName("Статус")]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")] [DisplayName("Дата создания")]
public DateTime DateCreate { get; set; } = DateTime.Now; public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")] [DisplayName("Дата выполнения")]
public DateTime? DateImplement { get; set; } public DateTime? DateImplement { get; set; }
} }
} }

View File

@ -14,7 +14,7 @@ namespace ComputersShopDataBaseImplement
{ {
if (optionsBuilder.IsConfigured == false) if (optionsBuilder.IsConfigured == false)
{ {
optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=ComputersShopDatabaseFullLab5;Username=postgres;Password=hellothere132"); optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=ComputersShopDatabaseFull;Username=postgres;Password=hellothere132");
} }
base.OnConfiguring(optionsBuilder); base.OnConfiguring(optionsBuilder);
} }
@ -23,6 +23,7 @@ namespace ComputersShopDataBaseImplement
public virtual DbSet<ComputerComponent> ComputerComponents { set; get; } public virtual DbSet<ComputerComponent> ComputerComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; } public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Client> Clients { set; get; } public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; }
} }
} }

View File

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

View File

@ -12,124 +12,148 @@ using System.Threading.Tasks;
namespace ComputersShopDataBaseImplement.Implements namespace ComputersShopDataBaseImplement.Implements
{ {
public class OrderStorage : IOrderStorage public class OrderStorage : IOrderStorage
{ {
public OrderViewModel? Delete(OrderBindingModel model) public OrderViewModel? Delete(OrderBindingModel model)
{ {
using var context = new ComputersShopDataBase(); using var context = new ComputersShopDataBase();
var element = context.Orders var element = context.Orders
.FirstOrDefault(rec => rec.Id == model.Id); .FirstOrDefault(rec => rec.Id == model.Id);
if (element != null) if (element != null)
{ {
var deletedElement = context.Orders var deletedElement = context.Orders
.Include(x => x.Computer) .Include(x => x.Computer)
.Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => x.Id == model.Id) .FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel; ?.GetViewModel;
context.Orders.Remove(element); context.Orders.Remove(element);
context.SaveChanges(); context.SaveChanges();
return deletedElement; return deletedElement;
} }
return null; return null;
} }
public OrderViewModel? GetElement(OrderSearchModel model) public OrderViewModel? GetElement(OrderSearchModel model)
{ {
if (!model.Id.HasValue) if (!model.Id.HasValue)
{
return null;
}
using var context = new ComputersShopDataBase();
return context.Orders
.Include(x => x.Computer)
.Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => (model.Status == null || model.Status != null && model.Status == x.Status) &&
model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId ||
model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
using var context = new ComputersShopDataBase();
if (model.Id.HasValue)
{
return context.Orders
.Include(x => x.Computer)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.DateFrom != null && model.DateTo != null)
{
return context.Orders
.Include(x => x.Computer)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.ClientId.HasValue)
{
return context.Orders
.Include(x => x.Computer)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => x.ClientId == model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.ImplementerId.HasValue)
{ {
return null; return context.Orders
.Include(x => x.Computer)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => x.ImplementerId == model.ImplementerId)
.Select(x => x.GetViewModel)
.ToList();
} }
using var context = new ComputersShopDataBase();
return context.Orders return context.Orders
.Include(x => x.Computer) .Include(x => x.Computer)
.Include(x => x.Client) .Include(x => x.Client)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) .Include(x => x.Implementer)
?.GetViewModel; .Where(x => model.Status == x.Status)
.Select(x => x.GetViewModel)
.ToList();
} }
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFullList()
{ {
using var context = new ComputersShopDataBase(); using var context = new ComputersShopDataBase();
if (model.Id.HasValue) return context.Orders
{ .Include(x => x.Computer)
return context.Orders .Include(x => x.Client)
.Include(x => x.Computer) .Include(x => x.Implementer)
.Include(x => x.Client)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
} }
else if (model.DateFrom != null && model.DateTo != null)
{
return context.Orders
.Include(x => x.Computer)
.Include(x => x.Client)
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.ClientId.HasValue)
{
return context.Orders
.Include(x => x.Computer)
.Include(x => x.Client)
.Where(x => x.ClientId == model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
}
else
{
return new();
}
}
public List<OrderViewModel> GetFullList() public OrderViewModel? Insert(OrderBindingModel model)
{ {
using var context = new ComputersShopDataBase(); var newOrder = Order.Create(model);
return context.Orders if (newOrder == null)
.Include(x => x.Computer) {
.Include(x => x.Client) return null;
.Select(x => x.GetViewModel) }
.ToList();
}
public OrderViewModel? Insert(OrderBindingModel model) using var context = new ComputersShopDataBase();
{
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
using var context = new ComputersShopDataBase(); context.Orders.Add(newOrder);
context.SaveChanges();
context.Orders.Add(newOrder); return context.Orders
context.SaveChanges(); .Include(x => x.Computer)
return context.Orders .Include(x => x.Client)
.Include(x => x.Computer) .Include(x => x.Implementer)
.Include(x => x.Client)
.FirstOrDefault(x => x.Id == newOrder.Id) .FirstOrDefault(x => x.Id == newOrder.Id)
?.GetViewModel; ?.GetViewModel;
} }
public OrderViewModel? Update(OrderBindingModel model) public OrderViewModel? Update(OrderBindingModel model)
{ {
using var context = new ComputersShopDataBase(); using var context = new ComputersShopDataBase();
var order = context.Orders.Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id); var order = context.Orders.Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id);
if (order == null) if (order == null)
{ {
return null; return null;
} }
order.Update(model); order.Update(model);
context.SaveChanges(); context.SaveChanges();
return context.Orders return context.Orders
.Include(x => x.Computer) .Include(x => x.Computer)
.Include(x => x.Client) .Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => x.Id == model.Id) .FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel; ?.GetViewModel;
} }
} }
} }

View File

@ -12,7 +12,7 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace ComputersShopDataBaseImplement.Migrations namespace ComputersShopDataBaseImplement.Migrations
{ {
[DbContext(typeof(ComputersShopDataBase))] [DbContext(typeof(ComputersShopDataBase))]
[Migration("20240401150307_InitialCreate")] [Migration("20240414115616_InitialCreate")]
partial class InitialCreate partial class InitialCreate
{ {
/// <inheritdoc /> /// <inheritdoc />
@ -116,6 +116,33 @@ namespace ComputersShopDataBaseImplement.Migrations
b.ToTable("ComputerComponents"); b.ToTable("ComputerComponents");
}); });
modelBuilder.Entity("ComputersShopDataBaseImplement.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("ComputersShopDataBaseImplement.Models.Order", b => modelBuilder.Entity("ComputersShopDataBaseImplement.Models.Order", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@ -139,6 +166,9 @@ namespace ComputersShopDataBaseImplement.Migrations
b.Property<DateTime?>("DateImplement") b.Property<DateTime?>("DateImplement")
.HasColumnType("timestamp with time zone"); .HasColumnType("timestamp with time zone");
b.Property<int?>("ImplementerId")
.HasColumnType("integer");
b.Property<int>("Status") b.Property<int>("Status")
.HasColumnType("integer"); .HasColumnType("integer");
@ -151,6 +181,8 @@ namespace ComputersShopDataBaseImplement.Migrations
b.HasIndex("ComputerId"); b.HasIndex("ComputerId");
b.HasIndex("ImplementerId");
b.ToTable("Orders"); b.ToTable("Orders");
}); });
@ -187,9 +219,15 @@ namespace ComputersShopDataBaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.HasOne("ComputersShopDataBaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("Client"); b.Navigation("Client");
b.Navigation("Computer"); b.Navigation("Computer");
b.Navigation("Implementer");
}); });
modelBuilder.Entity("ComputersShopDataBaseImplement.Models.Client", b => modelBuilder.Entity("ComputersShopDataBaseImplement.Models.Client", b =>
@ -208,6 +246,11 @@ namespace ComputersShopDataBaseImplement.Migrations
b.Navigation("Orders"); b.Navigation("Orders");
}); });
modelBuilder.Entity("ComputersShopDataBaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
} }

View File

@ -55,6 +55,22 @@ namespace ComputersShopDataBaseImplement.Migrations
table.PrimaryKey("PK_Computers", x => x.Id); table.PrimaryKey("PK_Computers", 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: "ComputerComponents", name: "ComputerComponents",
columns: table => new columns: table => new
@ -90,6 +106,7 @@ namespace ComputersShopDataBaseImplement.Migrations
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ComputerId = table.Column<int>(type: "integer", nullable: false), ComputerId = 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),
@ -111,6 +128,11 @@ namespace ComputersShopDataBaseImplement.Migrations
principalTable: "Computers", principalTable: "Computers",
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(
@ -132,6 +154,11 @@ namespace ComputersShopDataBaseImplement.Migrations
name: "IX_Orders_ComputerId", name: "IX_Orders_ComputerId",
table: "Orders", table: "Orders",
column: "ComputerId"); column: "ComputerId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
} }
/// <inheritdoc /> /// <inheritdoc />
@ -151,6 +178,9 @@ namespace ComputersShopDataBaseImplement.Migrations
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "Computers"); name: "Computers");
migrationBuilder.DropTable(
name: "Implementers");
} }
} }
} }

View File

@ -113,6 +113,33 @@ namespace ComputersShopDataBaseImplement.Migrations
b.ToTable("ComputerComponents"); b.ToTable("ComputerComponents");
}); });
modelBuilder.Entity("ComputersShopDataBaseImplement.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("ComputersShopDataBaseImplement.Models.Order", b => modelBuilder.Entity("ComputersShopDataBaseImplement.Models.Order", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@ -136,6 +163,9 @@ namespace ComputersShopDataBaseImplement.Migrations
b.Property<DateTime?>("DateImplement") b.Property<DateTime?>("DateImplement")
.HasColumnType("timestamp with time zone"); .HasColumnType("timestamp with time zone");
b.Property<int?>("ImplementerId")
.HasColumnType("integer");
b.Property<int>("Status") b.Property<int>("Status")
.HasColumnType("integer"); .HasColumnType("integer");
@ -148,6 +178,8 @@ namespace ComputersShopDataBaseImplement.Migrations
b.HasIndex("ComputerId"); b.HasIndex("ComputerId");
b.HasIndex("ImplementerId");
b.ToTable("Orders"); b.ToTable("Orders");
}); });
@ -184,9 +216,15 @@ namespace ComputersShopDataBaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.HasOne("ComputersShopDataBaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("Client"); b.Navigation("Client");
b.Navigation("Computer"); b.Navigation("Computer");
b.Navigation("Implementer");
}); });
modelBuilder.Entity("ComputersShopDataBaseImplement.Models.Client", b => modelBuilder.Entity("ComputersShopDataBaseImplement.Models.Client", b =>
@ -205,6 +243,11 @@ namespace ComputersShopDataBaseImplement.Migrations
b.Navigation("Orders"); b.Navigation("Orders");
}); });
modelBuilder.Entity("ComputersShopDataBaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
} }

View File

@ -0,0 +1,79 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopDataBaseImplement.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> Orders { 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 static Implementer Create(ImplementerViewModel model)
{
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

@ -12,66 +12,72 @@ using System.Threading.Tasks;
namespace ComputersShopDataBaseImplement.Models namespace ComputersShopDataBaseImplement.Models
{ {
public class Order : IOrderModel public class Order : IOrderModel
{ {
[Required]
public int ComputerId { get; set; }
[Required]
public int ClientId { get; private set; }
public int? ImplementerId { get; set; }
[Required] [Required]
public int ComputerId { get; set; } public int Count { get; set; }
[Required] [Required]
public int ClientId { get; private set; } public double Sum { get; set; }
[Required] [Required]
public int Count { get; set; } public OrderStatus Status { get; set; }
[Required] [Required]
public double Sum { get; set; } public DateTime DateCreate { get; set; }
[Required]
public OrderStatus Status { get; set; }
[Required]
public DateTime DateCreate { get; set; }
public DateTime? DateImplement { get; set; } public DateTime? DateImplement { get; set; }
public virtual Computer Computer { get; set; } public virtual Computer Computer { get; set; }
public virtual Client Client { get; set; } public virtual Client Client { get; set; }
public virtual Implementer? Implementer { get; set; }
public int Id { get; set; } public int Id { get; set; }
public static Order? Create(OrderBindingModel? model) public static Order? Create(OrderBindingModel? model)
{ {
if (model == null) if (model == null)
{ {
return null; return null;
} }
return new Order() return new Order()
{ {
Id = model.Id, Id = model.Id,
ComputerId = model.ComputerId, ComputerId = model.ComputerId,
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,
DateCreate = model.DateCreate, DateCreate = model.DateCreate,
DateImplement = model.DateImplement DateImplement = model.DateImplement
}; };
} }
public void Update(OrderBindingModel? model) public void Update(OrderBindingModel? model)
{ {
if (model == null) if (model == null)
{ {
return; return;
} }
Status = model.Status; Status = model.Status;
DateImplement = model.DateImplement; DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
} }
public OrderViewModel GetViewModel => new() public OrderViewModel GetViewModel => new()
{ {
Id = Id, Id = Id,
ComputerId = ComputerId, ComputerId = ComputerId,
ClientId = ClientId, ClientId = ClientId,
ClientFIO = Client.ClientFIO, ClientFIO = Client.ClientFIO,
ImplementerId = ImplementerId,
ImplementerFIO = Implementer?.ImplementerFIO ?? string.Empty,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,
DateCreate = DateCreate, DateCreate = DateCreate,
DateImplement = DateImplement, DateImplement = DateImplement,
ComputerName = Computer.ComputerName ComputerName = Computer.ComputerName
}; };
} }
} }

View File

@ -8,51 +8,58 @@ using System.Xml.Linq;
namespace ComputersShopFileImplement namespace ComputersShopFileImplement
{ {
public class DataFileSingleton public class DataFileSingleton
{ {
private static DataFileSingleton? instance; private static DataFileSingleton? instance;
private readonly string ComponentFileName = "Component.xml"; private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml"; private readonly string OrderFileName = "Order.xml";
private readonly string ComputerFileName = "Computer.xml"; private readonly string ComputerFileName = "Computer.xml";
private readonly string ClientFileName = "Client.xml"; private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
public List<Component> Components { get; private set; } public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; } public List<Order> Orders { get; private set; }
public List<Computer> Computers { get; private set; } public List<Computer> Computers { get; private set; }
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)
{ {
instance = new DataFileSingleton(); instance = new DataFileSingleton();
} }
return instance; return instance;
} }
public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement); public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement);
public void SaveComputers() => SaveData(Computers, ComputerFileName, "Computers", x => x.GetXElement); public void SaveComputers() => SaveData(Computers, ComputerFileName, "Computers", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement); public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, OrderFileName, "Clients", x => x.GetXElement); public void SaveClients() => SaveData(Clients, OrderFileName, "Clients", x => x.GetXElement);
public void 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)!)!;
Computers = LoadData(ComputerFileName, "Computer", x => Computer.Create(x)!)!; Computers = LoadData(ComputerFileName, "Computer", x => Computer.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)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
return return
XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList(); XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList();
} }
return new List<T>(); return new List<T>();
} }
private static void SaveData<T>(List<T> data, string filename, string xmlNodeName, Func<T, XElement> selectFunction) private static void SaveData<T>(List<T> data, string filename, string xmlNodeName, Func<T, XElement> selectFunction)
{ {
if (data != null) if (data != null)
{ {
new XDocument(new XElement(xmlNodeName, data.Select(selectFunction).ToArray())).Save(filename); new XDocument(new XElement(xmlNodeName, data.Select(selectFunction).ToArray())).Save(filename);
} }
} }
} }
} }

View File

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

View File

@ -11,105 +11,105 @@ using System.Threading.Tasks;
namespace ComputersShopFileImplement.Implements namespace ComputersShopFileImplement.Implements
{ {
public class OrderStorage : IOrderStorage public class OrderStorage : IOrderStorage
{ {
private readonly DataFileSingleton source; private readonly DataFileSingleton source;
public OrderStorage() public OrderStorage()
{ {
source = DataFileSingleton.GetInstance(); source = DataFileSingleton.GetInstance();
} }
public OrderViewModel? GetElement(OrderSearchModel model) public OrderViewModel? GetElement(OrderSearchModel model)
{ {
if (!model.Id.HasValue) if (!model.Id.HasValue)
{ {
return null; return null;
} }
return GetViewModel(source.Orders.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)); return GetViewModel(source.Orders.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id));
} }
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{ {
if (!model.Id.HasValue && model.DateFrom.HasValue && model.DateTo.HasValue) if (!model.Id.HasValue && model.DateFrom.HasValue && model.DateTo.HasValue)
{ {
return source.Orders return source.Orders
.Where(x => model.DateFrom <= x.DateCreate.Date && x.DateCreate <= model.DateTo) .Where(x => model.DateFrom <= x.DateCreate.Date && x.DateCreate <= model.DateTo)
.Select(x => GetViewModel(x)) .Select(x => GetViewModel(x))
.ToList(); .ToList();
} }
if (!model.Id.HasValue && model.ClientId.HasValue) if (!model.Id.HasValue && model.ClientId.HasValue)
{ {
return source.Orders return source.Orders
.Where(x => x.ClientId == model.ClientId) .Where(x => x.ClientId == model.ClientId)
.Select(x => GetViewModel(x)) .Select(x => GetViewModel(x))
.ToList(); .ToList();
} }
var result = GetElement(model); var result = GetElement(model);
return result != null ? new() { result } : new(); return result != null ? new() { result } : new();
} }
public List<OrderViewModel> GetFullList() public List<OrderViewModel> GetFullList()
{ {
return source.Orders.Select(x => GetViewModel(x)).ToList(); return source.Orders.Select(x => GetViewModel(x)).ToList();
} }
public OrderViewModel? Insert(OrderBindingModel model) public OrderViewModel? Insert(OrderBindingModel model)
{ {
model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1; model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1;
var newOrder = Order.Create(model); var newOrder = Order.Create(model);
if (newOrder == null) if (newOrder == null)
{ {
return null; return null;
} }
source.Orders.Add(newOrder); source.Orders.Add(newOrder);
source.SaveOrders(); source.SaveOrders();
return GetViewModel(newOrder); return GetViewModel(newOrder);
} }
public OrderViewModel? Update(OrderBindingModel model) public OrderViewModel? Update(OrderBindingModel model)
{ {
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id); var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null) if (order == null)
{ {
return null; return null;
} }
order.Update(model); order.Update(model);
source.SaveOrders(); source.SaveOrders();
return GetViewModel(order); return GetViewModel(order);
} }
public OrderViewModel? Delete(OrderBindingModel model) public OrderViewModel? Delete(OrderBindingModel model)
{ {
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id); var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null) if (order == null)
{ {
return null; return null;
} }
order.Update(model); order.Update(model);
source.SaveOrders(); source.SaveOrders();
return GetViewModel(order); return GetViewModel(order);
} }
private OrderViewModel GetViewModel(Order order) private OrderViewModel GetViewModel(Order order)
{ {
var viewModel = order.GetViewModel; var viewModel = order.GetViewModel;
foreach (var comp in source.Computers) foreach (var comp in source.Computers)
{ {
if (comp.Id == order.ComputerId) if (comp.Id == order.ComputerId)
{ {
viewModel.ComputerName = comp.ComputerName; viewModel.ComputerName = comp.ComputerName;
break; break;
} }
} }
foreach (var client in source.Clients) foreach (var client in source.Clients)
{ {
if (client.Id == order.ClientId) if (client.Id == order.ClientId)
{ {
viewModel.ClientFIO = client.ClientFIO; viewModel.ClientFIO = client.ClientFIO;
break; break;
} }
} }
return viewModel; return viewModel;
} }
} }
} }

View File

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

View File

@ -11,100 +11,107 @@ using System.Xml.Linq;
namespace ComputersShopFileImplement.Models namespace ComputersShopFileImplement.Models
{ {
public class Order : IOrderModel public class Order : IOrderModel
{ {
public int ComputerId { get; private set; } public int ComputerId { get; private set; }
public int ClientId { get; set; } public int ClientId { get; 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; }
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)
{ {
return null; return null;
} }
return new Order() return new Order()
{ {
Id = model.Id, Id = model.Id,
ComputerId = model.ComputerId, ComputerId = model.ComputerId,
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,
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() var order = new Order()
{ {
Id = Convert.ToInt32(element.Attribute("Id")!.Value), Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ComputerId = Convert.ToInt32(element.Element("ComputerId")!.Value), ComputerId = Convert.ToInt32(element.Element("ComputerId")!.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), DateCreate = DateTime.ParseExact(element.Element("DateCreate")!.Value, "G", null),
}; };
DateTime.TryParse(element.Element("DateImplement")!.Value, out DateTime dateImpl); DateTime.TryParse(element.Element("DateImplement")!.Value, out DateTime dateImpl);
order.DateImplement = dateImpl; order.DateImplement = dateImpl;
if (!Enum.TryParse(element.Element("Status")!.Value, out OrderStatus status)) if (!Enum.TryParse(element.Element("Status")!.Value, out OrderStatus status))
{ {
return null; return null;
} }
order.Status = status; order.Status = status;
return order; return order;
} }
public void Update(OrderBindingModel? model) public void Update(OrderBindingModel? model)
{ {
if (model == null) if (model == null)
{ {
return; return;
} }
Status = model.Status; Status = model.Status;
DateImplement = model.DateImplement; DateImplement = model.DateImplement;
} ImplementerId = model.ImplementerId;
}
public OrderViewModel GetViewModel => new() public OrderViewModel GetViewModel => new()
{ {
Id = Id, Id = Id,
ComputerId = ComputerId, ComputerId = ComputerId,
ClientId = ClientId, ClientId = ClientId,
Count = Count, ImplementerId = ImplementerId,
Sum = Sum, Count = Count,
Status = Status, Sum = Sum,
DateCreate = DateCreate, Status = Status,
DateImplement = DateImplement DateCreate = DateCreate,
}; DateImplement = DateImplement
};
public XElement GetXElement => new("Order", public XElement GetXElement => new("Order",
new XAttribute("Id", Id), new XAttribute("Id", Id),
new XElement("ComputerId", ComputerId), new XElement("ComputerId", ComputerId),
new XElement("ClientId", ClientId), new XElement("ClientId", ClientId),
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()),
new XElement("DateCreate", DateCreate.ToString()), new XElement("DateCreate", DateCreate.ToString()),
new XElement("DateImplement", DateImplement.ToString())); new XElement("DateImplement", DateImplement.ToString()));
} }
} }

View File

@ -7,27 +7,29 @@ using System.Threading.Tasks;
namespace ComputersShopListImplement namespace ComputersShopListImplement
{ {
public class DataListSingleton public class DataListSingleton
{ {
private static DataListSingleton? _instance; private static DataListSingleton? _instance;
public List<Component> Components { get; set; } public List<Component> Components { get; set; }
public List<Order> Orders { get; set; } public List<Order> Orders { get; set; }
public List<Computer> Computers { get; set; } public List<Computer> Computers { get; set; }
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>();
Computers = new List<Computer>(); Computers = new List<Computer>();
Clients = new List<Client>(); Clients = new List<Client>();
Implementers = new List<Implementer>();
} }
public static DataListSingleton GetInstance() public static DataListSingleton GetInstance()
{ {
if (_instance == null) if (_instance == null)
{ {
_instance = new DataListSingleton(); _instance = new DataListSingleton();
} }
return _instance; return _instance;
} }
} }
} }

View File

@ -0,0 +1,120 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopListImplement.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)
{
if (model.Id.HasValue)
{
foreach (var implementer in _source.Implementers)
{
if (implementer.Id == model.Id)
{
return implementer.GetViewModel;
}
}
}
else if (!string.IsNullOrEmpty(model.ImplementerFIO) && !string.IsNullOrEmpty(model.Password))
{
foreach (var implementer in _source.Implementers)
{
if (implementer.ImplementerFIO == model.ImplementerFIO && implementer.Password == model.Password)
{
return implementer.GetViewModel;
}
}
}
return null;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
var result = new List<ImplementerViewModel>();
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
return result;
}
foreach (var implementer in _source.Implementers)
{
if (implementer.ImplementerFIO.Contains(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 newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
_source.Implementers.Add(newImplementer);
return newImplementer.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

@ -12,102 +12,102 @@ using System.Threading.Tasks;
namespace OrdersShopListImplement.Implements namespace OrdersShopListImplement.Implements
{ {
public class OrderStorage : IOrderStorage public class OrderStorage : IOrderStorage
{ {
private readonly DataListSingleton _source; private readonly DataListSingleton _source;
public OrderStorage() public OrderStorage()
{ {
_source = DataListSingleton.GetInstance(); _source = DataListSingleton.GetInstance();
} }
public List<OrderViewModel> GetFullList() public List<OrderViewModel> GetFullList()
{ {
var result = new List<OrderViewModel>(); var result = new List<OrderViewModel>();
foreach (var Order in _source.Orders) foreach (var Order in _source.Orders)
{ {
result.Add(GetViewModel(Order)); result.Add(GetViewModel(Order));
} }
return result; return result;
} }
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{ {
var result = new List<OrderViewModel>(); var result = new List<OrderViewModel>();
foreach (var order in _source.Orders) foreach (var order in _source.Orders)
{ {
if (order.Id == model.Id) if (order.Id == model.Id)
{ {
return new() { GetViewModel(order) }; return new() { GetViewModel(order) };
} }
else if (model.DateFrom.HasValue && model.DateTo.HasValue && model.DateFrom <= order.DateCreate.Date && order.DateCreate.Date <= model.DateTo) else if (model.DateFrom.HasValue && model.DateTo.HasValue && model.DateFrom <= order.DateCreate.Date && order.DateCreate.Date <= model.DateTo)
{ {
result.Add(GetViewModel(order)); result.Add(GetViewModel(order));
} }
else if (model.ClientId.HasValue && order.ClientId == model.ClientId) else if (model.ClientId.HasValue && order.ClientId == model.ClientId)
{ {
result.Add(GetViewModel(order)); result.Add(GetViewModel(order));
} }
} }
return result; return result;
} }
public OrderViewModel? GetElement(OrderSearchModel model) public OrderViewModel? GetElement(OrderSearchModel model)
{ {
if (!model.Id.HasValue) if (!model.Id.HasValue)
{ {
return null; return null;
} }
foreach (var Order in _source.Orders) foreach (var Order in _source.Orders)
{ {
if (model.Id.HasValue && Order.Id == model.Id) if (model.Id.HasValue && Order.Id == model.Id)
{ {
return GetViewModel(Order); return GetViewModel(Order);
} }
} }
return null; return null;
} }
public OrderViewModel? Insert(OrderBindingModel model) public OrderViewModel? Insert(OrderBindingModel model)
{ {
model.Id = 1; model.Id = 1;
foreach (var Order in _source.Orders) foreach (var Order in _source.Orders)
{ {
if (model.Id <= Order.Id) if (model.Id <= Order.Id)
{ {
model.Id = Order.Id + 1; model.Id = Order.Id + 1;
} }
} }
var newOrder = Order.Create(model); var newOrder = Order.Create(model);
if (newOrder == null) if (newOrder == null)
{ {
return null; return null;
} }
_source.Orders.Add(newOrder); _source.Orders.Add(newOrder);
return GetViewModel(newOrder); return GetViewModel(newOrder);
} }
public OrderViewModel? Update(OrderBindingModel model) public OrderViewModel? Update(OrderBindingModel model)
{ {
foreach (var Order in _source.Orders) foreach (var Order in _source.Orders)
{ {
if (Order.Id == model.Id) if (Order.Id == model.Id)
{ {
Order.Update(model); Order.Update(model);
return GetViewModel(Order); return GetViewModel(Order);
} }
} }
return null; return null;
} }
public OrderViewModel? Delete(OrderBindingModel model) public OrderViewModel? Delete(OrderBindingModel model)
{ {
for (int i = 0; i < _source.Orders.Count; ++i) for (int i = 0; i < _source.Orders.Count; ++i)
{ {
if (_source.Orders[i].Id == model.Id) if (_source.Orders[i].Id == model.Id)
{ {
var element = _source.Orders[i]; var element = _source.Orders[i];
_source.Orders.RemoveAt(i); _source.Orders.RemoveAt(i);
return GetViewModel(element); return GetViewModel(element);
} }
} }
return null; return null;
} }
private OrderViewModel GetViewModel(Order order) private OrderViewModel GetViewModel(Order order)
{ {
var viewModel = order.GetViewModel; var viewModel = order.GetViewModel;
foreach (var comp in _source.Computers) foreach (var comp in _source.Computers)
@ -118,15 +118,15 @@ namespace OrdersShopListImplement.Implements
break; break;
} }
} }
foreach (var client in _source.Clients) foreach (var client in _source.Clients)
{ {
if (client.Id == order.ClientId) if (client.Id == order.ClientId)
{ {
viewModel.ClientFIO = client.ClientFIO; viewModel.ClientFIO = client.ClientFIO;
break; break;
} }
} }
return viewModel; return viewModel;
} }
} }
} }

View File

@ -0,0 +1,59 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopListImplement.Models
{
public class Implementer : IImplementerModel
{
public string ImplementerFIO { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty;
public int WorkExperience { get; set; }
public int Qualification { get; set; }
public int Id { get; set; }
public static Implementer? Create(ImplementerBindingModel? model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
ImplementerFIO = model.ImplementerFIO,
Password = model.Password,
WorkExperience = model.WorkExperience,
Qualification = model.Qualification
};
}
public 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

@ -1,4 +1,4 @@
using ComputersShopContracts.BindingModels; using ComputersShopContracts.BindingModels;
using ComputersShopContracts.ViewModels; using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Enums; using ComputersShopDataModels.Enums;
using ComputersShopDataModels.Models; using ComputersShopDataModels.Models;
@ -12,62 +12,67 @@ using System.Threading.Tasks;
namespace ComputersShopListImplement.Models namespace ComputersShopListImplement.Models
{ {
public class Order : IOrderModel public class Order : IOrderModel
{ {
public int Id { get; private set; } public int Id { get; private set; }
public int ComputerId { get; private set; } public int ComputerId { get; private set; }
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; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен; public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; set; } = DateTime.Now; public DateTime DateCreate { get; set; } = DateTime.Now;
public DateTime? DateImplement { get; set; } public DateTime? DateImplement { get; set; }
public static Order? Create(OrderBindingModel? model) public static Order? Create(OrderBindingModel? model)
{ {
if (model == null) if (model == null)
{ {
return null; return null;
} }
return new Order() return new Order()
{ {
Id = model.Id, Id = model.Id,
ComputerId = model.ComputerId, ComputerId = model.ComputerId,
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,
DateCreate = model.DateCreate, DateCreate = model.DateCreate,
DateImplement = model.DateImplement DateImplement = model.DateImplement
}; };
} }
public void Update(OrderBindingModel? model) public void Update(OrderBindingModel? model)
{ {
if (model == null) if (model == null)
{ {
return; return;
} }
Status = model.Status; Status = model.Status;
DateImplement = model.DateImplement; DateImplement = model.DateImplement;
} ImplementerId = model.ImplementerId;
public OrderViewModel GetViewModel => new() }
{ public OrderViewModel GetViewModel => new()
Id = Id, {
ComputerId = ComputerId, Id = Id,
ClientId = ClientId, ComputerId = ComputerId,
ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,
DateCreate = DateCreate, DateCreate = DateCreate,
DateImplement = DateImplement DateImplement = DateImplement
}; };
} }
} }

View File

@ -0,0 +1,106 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BusinessLogicContracts;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace ComputersShopRestApi.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");
// Add services to the container. // Add services to the container.
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<IComputerStorage, ComputerStorage>(); builder.Services.AddTransient<IComputerStorage, ComputerStorage>();
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<IComputerLogic, ComputerLogic>(); builder.Services.AddTransient<IComputerLogic, ComputerLogic>();

View File

@ -0,0 +1,163 @@
namespace ComputersShopView
{
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.labelFIO = new System.Windows.Forms.Label();
this.labelPassword = new System.Windows.Forms.Label();
this.labelExperience = new System.Windows.Forms.Label();
this.labelQualification = new System.Windows.Forms.Label();
this.textBoxFIO = new System.Windows.Forms.TextBox();
this.textBoxPassword = new System.Windows.Forms.TextBox();
this.textBoxExperience = new System.Windows.Forms.TextBox();
this.textBoxQualification = new System.Windows.Forms.TextBox();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// labelFIO
//
this.labelFIO.AutoSize = true;
this.labelFIO.Location = new System.Drawing.Point(32, 9);
this.labelFIO.Name = "labelFIO";
this.labelFIO.Size = new System.Drawing.Size(45, 20);
this.labelFIO.TabIndex = 0;
this.labelFIO.Text = "ФИО:";
//
// labelPassword
//
this.labelPassword.AutoSize = true;
this.labelPassword.Location = new System.Drawing.Point(32, 50);
this.labelPassword.Name = "labelPassword";
this.labelPassword.Size = new System.Drawing.Size(65, 20);
this.labelPassword.TabIndex = 1;
this.labelPassword.Text = "Пароль:";
//
// labelExperience
//
this.labelExperience.AutoSize = true;
this.labelExperience.Location = new System.Drawing.Point(32, 105);
this.labelExperience.Name = "labelExperience";
this.labelExperience.Size = new System.Drawing.Size(102, 20);
this.labelExperience.TabIndex = 2;
this.labelExperience.Text = "Стаж работы:";
//
// labelQualification
//
this.labelQualification.AutoSize = true;
this.labelQualification.Location = new System.Drawing.Point(270, 105);
this.labelQualification.Name = "labelQualification";
this.labelQualification.Size = new System.Drawing.Size(114, 20);
this.labelQualification.TabIndex = 3;
this.labelQualification.Text = "Квалификация:";
//
// textBoxFIO
//
this.textBoxFIO.Location = new System.Drawing.Point(102, 6);
this.textBoxFIO.Name = "textBoxFIO";
this.textBoxFIO.Size = new System.Drawing.Size(282, 27);
this.textBoxFIO.TabIndex = 4;
//
// textBoxPassword
//
this.textBoxPassword.Location = new System.Drawing.Point(103, 50);
this.textBoxPassword.Name = "textBoxPassword";
this.textBoxPassword.Size = new System.Drawing.Size(281, 27);
this.textBoxPassword.TabIndex = 5;
//
// textBoxExperience
//
this.textBoxExperience.Location = new System.Drawing.Point(140, 105);
this.textBoxExperience.Name = "textBoxExperience";
this.textBoxExperience.Size = new System.Drawing.Size(124, 27);
this.textBoxExperience.TabIndex = 6;
//
// textBoxQualification
//
this.textBoxQualification.Location = new System.Drawing.Point(390, 105);
this.textBoxQualification.Name = "textBoxQualification";
this.textBoxQualification.Size = new System.Drawing.Size(96, 27);
this.textBoxQualification.TabIndex = 7;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(270, 157);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 8;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(392, 157);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 9;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// FormImplementer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(498, 202);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxQualification);
this.Controls.Add(this.textBoxExperience);
this.Controls.Add(this.textBoxPassword);
this.Controls.Add(this.textBoxFIO);
this.Controls.Add(this.labelQualification);
this.Controls.Add(this.labelExperience);
this.Controls.Add(this.labelPassword);
this.Controls.Add(this.labelFIO);
this.Name = "FormImplementer";
this.Text = "Исполнитель";
this.Load += new System.EventHandler(this.FormImplementer_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelFIO;
private Label labelPassword;
private Label labelExperience;
private Label labelQualification;
private TextBox textBoxFIO;
private TextBox textBoxPassword;
private TextBox textBoxExperience;
private TextBox textBoxQualification;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,100 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BusinessLogicContracts;
using ComputersShopContracts.SearchModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ComputersShopView
{
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;
textBoxExperience.Text = view.WorkExperience.ToString();
textBoxPassword.Text = view.Password;
textBoxQualification.Text = view.Qualification.ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxFIO.Text))
{
MessageBox.Show("Заполните ФИО", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение исполнителя");
try
{
var model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = textBoxFIO.Text,
Password = textBoxPassword.Text,
WorkExperience = Convert.ToInt32(textBoxExperience.Text),
Qualification = Convert.ToInt32(textBoxQualification.Text),
};
var operationResult = _id.HasValue ? _logic.Update(model) :
_logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения компонента");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,116 @@
namespace ComputersShopView
{
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.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonAdd = new System.Windows.Forms.Button();
this.buttonUpd = new System.Windows.Forms.Button();
this.buttonDel = new System.Windows.Forms.Button();
this.buttonRef = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Dock = System.Windows.Forms.DockStyle.Left;
this.dataGridView.Location = new System.Drawing.Point(0, 0);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(564, 450);
this.dataGridView.TabIndex = 0;
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(637, 37);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(94, 29);
this.buttonAdd.TabIndex = 1;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// buttonUpd
//
this.buttonUpd.Location = new System.Drawing.Point(637, 100);
this.buttonUpd.Name = "buttonUpd";
this.buttonUpd.Size = new System.Drawing.Size(94, 29);
this.buttonUpd.TabIndex = 2;
this.buttonUpd.Text = "Изменить";
this.buttonUpd.UseVisualStyleBackColor = true;
this.buttonUpd.Click += new System.EventHandler(this.ButtonUpd_Click);
//
// buttonDel
//
this.buttonDel.Location = new System.Drawing.Point(637, 164);
this.buttonDel.Name = "buttonDel";
this.buttonDel.Size = new System.Drawing.Size(94, 29);
this.buttonDel.TabIndex = 3;
this.buttonDel.Text = "Удалить";
this.buttonDel.UseVisualStyleBackColor = true;
this.buttonDel.Click += new System.EventHandler(this.ButtonDel_Click);
//
// buttonRef
//
this.buttonRef.Location = new System.Drawing.Point(637, 228);
this.buttonRef.Name = "buttonRef";
this.buttonRef.Size = new System.Drawing.Size(94, 29);
this.buttonRef.TabIndex = 4;
this.buttonRef.Text = "Обновить";
this.buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click);
//
// 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.buttonRef);
this.Controls.Add(this.buttonDel);
this.Controls.Add(this.buttonUpd);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.dataGridView);
this.Name = "FormImplementers";
this.Text = "Исполнители";
this.Load += new System.EventHandler(this.FormImplementers_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonAdd;
private Button buttonUpd;
private Button buttonDel;
private Button buttonRef;
}
}

View File

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

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -1,24 +1,24 @@
namespace ComputersShopView namespace ComputersShopView
{ {
partial class FormMain partial class FormMain
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary> /// <summary>
/// Clean up any resources being used. /// Clean up any resources being used.
/// </summary> /// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) if (disposing && (components != null))
{ {
components.Dispose(); components.Dispose();
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Windows Form Designer generated code #region Windows Form Designer generated code
@ -32,15 +32,15 @@
dictionaryToolStripMenuItem = new ToolStripMenuItem(); dictionaryToolStripMenuItem = new ToolStripMenuItem();
computerToolStripMenuItem = new ToolStripMenuItem(); computerToolStripMenuItem = new ToolStripMenuItem();
componentsToolStripMenuItem = new ToolStripMenuItem(); componentsToolStripMenuItem = new ToolStripMenuItem();
ClientsToolStripMenuItem = new ToolStripMenuItem(); clientsToolStripMenuItem = new ToolStripMenuItem();
reportsToolStripMenuItem = new ToolStripMenuItem(); implementersToolStripMenuItem = new ToolStripMenuItem();
listComputersToolStripMenuItem = new ToolStripMenuItem(); отчётыToolStripMenuItem = new ToolStripMenuItem();
componentsComputersToolStripMenuItem = new ToolStripMenuItem(); computerListToolStripMenuItem = new ToolStripMenuItem();
listOrdersToolStripMenuItem = new ToolStripMenuItem(); componentsOfComputersToolStripMenuItem = new ToolStripMenuItem();
listOrderToolStripMenuItem = new ToolStripMenuItem();
doWorkToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView(); dataGridView = new DataGridView();
buttonCreateOrder = new Button(); buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button();
buttonOrderReady = new Button();
buttonIssuedOrder = new Button(); buttonIssuedOrder = new Button();
buttonRef = new Button(); buttonRef = new Button();
menuStrip.SuspendLayout(); menuStrip.SuspendLayout();
@ -49,7 +49,7 @@
// //
// menuStrip // menuStrip
// //
menuStrip.Items.AddRange(new ToolStripItem[] { dictionaryToolStripMenuItem, reportsToolStripMenuItem }); menuStrip.Items.AddRange(new ToolStripItem[] { dictionaryToolStripMenuItem, отчётыToolStripMenuItem, doWorkToolStripMenuItem });
menuStrip.Location = new Point(0, 0); menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip"; menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1047, 24); menuStrip.Size = new Size(1047, 24);
@ -58,10 +58,10 @@
// //
// dictionaryToolStripMenuItem // dictionaryToolStripMenuItem
// //
dictionaryToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { componentsToolStripMenuItem, computerToolStripMenuItem, ClientsToolStripMenuItem }); dictionaryToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { componentsToolStripMenuItem, computerToolStripMenuItem, clientsToolStripMenuItem, implementersToolStripMenuItem });
dictionaryToolStripMenuItem.Name = "dictionaryToolStripMenuItem"; dictionaryToolStripMenuItem.Name = "dictionaryToolStripMenuItem";
dictionaryToolStripMenuItem.Size = new Size(94, 20); dictionaryToolStripMenuItem.Size = new Size(94, 20);
dictionaryToolStripMenuItem.Text = "Cправочники"; dictionaryToolStripMenuItem.Text = "Справочники";
// //
// computerToolStripMenuItem // computerToolStripMenuItem
// //
@ -77,40 +77,54 @@
componentsToolStripMenuItem.Text = "Компоненты"; componentsToolStripMenuItem.Text = "Компоненты";
componentsToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; componentsToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click;
// //
// ClientsToolStripMenuItem // clientsToolStripMenuItem
// //
ClientsToolStripMenuItem.Name = "ClientsToolStripMenuItem"; clientsToolStripMenuItem.Name = "clientsToolStripMenuItem";
ClientsToolStripMenuItem.Size = new Size(180, 22); clientsToolStripMenuItem.Size = new Size(180, 22);
ClientsToolStripMenuItem.Text = "Клиенты"; clientsToolStripMenuItem.Text = "Клиенты";
ClientsToolStripMenuItem.Click += clientsToolStripMenuItem_Click; clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click;
// //
// reportsToolStripMenuItem // implementersToolStripMenuItem
// //
reportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { listComputersToolStripMenuItem, componentsComputersToolStripMenuItem, listOrdersToolStripMenuItem }); implementersToolStripMenuItem.Name = "implementersToolStripMenuItem";
reportsToolStripMenuItem.Name = "reportsToolStripMenuItem"; implementersToolStripMenuItem.Size = new Size(180, 22);
reportsToolStripMenuItem.Size = new Size(60, 20); implementersToolStripMenuItem.Text = "Исполнители";
reportsToolStripMenuItem.Text = "Отчёты"; implementersToolStripMenuItem.Click += ImplementersToolStripMenuItem_Click;
// //
// listComputersToolStripMenuItem // отчётыToolStripMenuItem
// //
listComputersToolStripMenuItem.Name = "listComputersToolStripMenuItem"; отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { computerListToolStripMenuItem, componentsOfComputersToolStripMenuItem, listOrderToolStripMenuItem });
listComputersToolStripMenuItem.Size = new Size(224, 22); отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem";
listComputersToolStripMenuItem.Text = "Список компьютеров"; отчётыToolStripMenuItem.Size = new Size(60, 20);
listComputersToolStripMenuItem.Click += ComponentsDocxToolStripMenuItem_Click; отчётыToolStripMenuItem.Text = "Отчёты";
// //
// componentsComputersToolStripMenuItem // computerListToolStripMenuItem
// //
componentsComputersToolStripMenuItem.Name = "componentsComputersToolStripMenuItem"; computerListToolStripMenuItem.Name = "computerListToolStripMenuItem";
componentsComputersToolStripMenuItem.Size = new Size(224, 22); computerListToolStripMenuItem.Size = new Size(243, 22);
componentsComputersToolStripMenuItem.Text = "Компоненты компьютеров"; computerListToolStripMenuItem.Text = "Список компьютеров";
componentsComputersToolStripMenuItem.Click += ComputerComponentsToolStripMenuItem_Click; computerListToolStripMenuItem.Click += ComponentsDocxToolStripMenuItem_Click;
// //
// listOrdersToolStripMenuItem // componentsOfComputersToolStripMenuItem
// //
listOrdersToolStripMenuItem.Name = "listOrdersToolStripMenuItem"; componentsOfComputersToolStripMenuItem.Name = "componentsOfComputersToolStripMenuItem";
listOrdersToolStripMenuItem.Size = new Size(224, 22); componentsOfComputersToolStripMenuItem.Size = new Size(243, 22);
listOrdersToolStripMenuItem.Text = "Список заказов"; componentsOfComputersToolStripMenuItem.Text = "Компоненты по компьютерам";
listOrdersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; componentsOfComputersToolStripMenuItem.Click += ComputerComponentsToolStripMenuItem_Click;
//
// listOrderToolStripMenuItem
//
listOrderToolStripMenuItem.Name = "listOrderToolStripMenuItem";
listOrderToolStripMenuItem.Size = new Size(243, 22);
listOrderToolStripMenuItem.Text = "Список заказов";
listOrderToolStripMenuItem.Click += OrdersToolStripMenuItem_Click;
//
// doWorkToolStripMenuItem
//
doWorkToolStripMenuItem.Name = "doWorkToolStripMenuItem";
doWorkToolStripMenuItem.Size = new Size(92, 20);
doWorkToolStripMenuItem.Text = "Запуск работ";
doWorkToolStripMenuItem.Click += DoWorkToolStripMenuItem_Click;
// //
// dataGridView // dataGridView
// //
@ -131,29 +145,9 @@
buttonCreateOrder.UseVisualStyleBackColor = true; buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click; buttonCreateOrder.Click += ButtonCreateOrder_Click;
// //
// buttonTakeOrderInWork
//
buttonTakeOrderInWork.Location = new Point(835, 101);
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
buttonTakeOrderInWork.Size = new Size(200, 23);
buttonTakeOrderInWork.TabIndex = 3;
buttonTakeOrderInWork.Text = "Отдать на выполнение";
buttonTakeOrderInWork.UseVisualStyleBackColor = true;
buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click;
//
// buttonOrderReady
//
buttonOrderReady.Location = new Point(835, 156);
buttonOrderReady.Name = "buttonOrderReady";
buttonOrderReady.Size = new Size(200, 23);
buttonOrderReady.TabIndex = 4;
buttonOrderReady.Text = "Заказ готов";
buttonOrderReady.UseVisualStyleBackColor = true;
buttonOrderReady.Click += ButtonOrderReady_Click;
//
// buttonIssuedOrder // buttonIssuedOrder
// //
buttonIssuedOrder.Location = new Point(835, 212); buttonIssuedOrder.Location = new Point(835, 113);
buttonIssuedOrder.Name = "buttonIssuedOrder"; buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(200, 23); buttonIssuedOrder.Size = new Size(200, 23);
buttonIssuedOrder.TabIndex = 5; buttonIssuedOrder.TabIndex = 5;
@ -163,7 +157,7 @@
// //
// buttonRef // buttonRef
// //
buttonRef.Location = new Point(835, 269); buttonRef.Location = new Point(835, 170);
buttonRef.Name = "buttonRef"; buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(200, 23); buttonRef.Size = new Size(200, 23);
buttonRef.TabIndex = 6; buttonRef.TabIndex = 6;
@ -178,8 +172,6 @@
ClientSize = new Size(1047, 450); ClientSize = new Size(1047, 450);
Controls.Add(buttonRef); Controls.Add(buttonRef);
Controls.Add(buttonIssuedOrder); Controls.Add(buttonIssuedOrder);
Controls.Add(buttonOrderReady);
Controls.Add(buttonTakeOrderInWork);
Controls.Add(buttonCreateOrder); Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView); Controls.Add(dataGridView);
Controls.Add(menuStrip); Controls.Add(menuStrip);
@ -194,27 +186,22 @@
PerformLayout(); PerformLayout();
} }
private void ReportsToolStripMenuItem_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
#endregion #endregion
private MenuStrip menuStrip; private MenuStrip menuStrip;
private ToolStripMenuItem dictionaryToolStripMenuItem; private ToolStripMenuItem dictionaryToolStripMenuItem;
private DataGridView dataGridView; private DataGridView dataGridView;
private Button buttonCreateOrder; private Button buttonCreateOrder;
private Button buttonTakeOrderInWork; private Button buttonIssuedOrder;
private Button buttonOrderReady; private Button buttonRef;
private Button buttonIssuedOrder; private ToolStripMenuItem computerToolStripMenuItem;
private Button buttonRef; private ToolStripMenuItem componentsToolStripMenuItem;
private ToolStripMenuItem computerToolStripMenuItem; private ToolStripMenuItem отчётыToolStripMenuItem;
private ToolStripMenuItem componentsToolStripMenuItem; private ToolStripMenuItem computerListToolStripMenuItem;
private ToolStripMenuItem reportsToolStripMenuItem; private ToolStripMenuItem componentsOfComputersToolStripMenuItem;
private ToolStripMenuItem listComputersToolStripMenuItem; private ToolStripMenuItem listOrderToolStripMenuItem;
private ToolStripMenuItem componentsComputersToolStripMenuItem; private ToolStripMenuItem clientsToolStripMenuItem;
private ToolStripMenuItem listOrdersToolStripMenuItem; private ToolStripMenuItem implementersToolStripMenuItem;
private ToolStripMenuItem ClientsToolStripMenuItem; private ToolStripMenuItem doWorkToolStripMenuItem;
} }
} }

View File

@ -20,13 +20,15 @@ namespace ComputersShopView
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)
@ -44,6 +46,7 @@ namespace ComputersShopView
dataGridView.DataSource = list; dataGridView.DataSource = list;
dataGridView.Columns["ComputerId"].Visible = false; dataGridView.Columns["ComputerId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false; dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
} }
_logger.LogInformation("Загрузка заказов"); _logger.LogInformation("Загрузка заказов");
} }
@ -150,6 +153,7 @@ namespace ComputersShopView
{ {
Id = id, Id = id,
ComputerId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ComputerId"].Value), ComputerId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ComputerId"].Value),
ImplementerId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ImplementerId"].Value),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
@ -169,10 +173,6 @@ namespace ComputersShopView
} }
} }
} }
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
private void ComponentsDocxToolStripMenuItem_Click(object sender, EventArgs e) private void ComponentsDocxToolStripMenuItem_Click(object sender, EventArgs e)
{ {
@ -202,7 +202,7 @@ namespace ComputersShopView
} }
} }
private void clientsToolStripMenuItem_Click(object sender, EventArgs e) private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormClients)); var service = Program.ServiceProvider?.GetService(typeof(FormClients));
if (service is FormClients form) if (service is FormClients form)
@ -210,5 +210,28 @@ namespace ComputersShopView
form.ShowDialog(); form.ShowDialog();
} }
} }
private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (service is FormImplementers form)
{
form.ShowDialog();
}
}
private void DoWorkToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((
Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!,
_orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
} }
} }

View File

@ -8,7 +8,6 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging; using NLog.Extensions.Logging;
namespace ComputersShopView namespace ComputersShopView
{ {
internal static class Program internal static class Program
@ -40,28 +39,33 @@ namespace ComputersShopView
services.AddTransient<IComponentStorage, ComponentStorage>(); services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IComputerStorage, ComputerStorage>(); services.AddTransient<IComputerStorage, ComputerStorage>();
services.AddTransient<IOrderStorage, OrderStorage>(); services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IClientStorage, ClientStorage>(); services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>(); services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IComputerLogic, ComputerLogic>(); services.AddTransient<IComputerLogic, ComputerLogic>();
services.AddTransient<IOrderLogic, OrderLogic>(); services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IReportLogic, ReportLogic>(); services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IClientLogic, ClientLogic>(); services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<AbstractSaveToWord, SaveToWord>(); services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>(); services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>(); services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
services.AddTransient<FormMain>(); services.AddTransient<FormMain>();
services.AddTransient<FormClients>(); services.AddTransient<FormClients>();
services.AddTransient<FormComponent>(); services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>(); services.AddTransient<FormComponents>();
services.AddTransient<FormCreateOrder>(); services.AddTransient<FormCreateOrder>();
services.AddTransient<FormComputer>(); services.AddTransient<FormComputer>();
services.AddTransient<FormComputers>(); services.AddTransient<FormComputers>();
services.AddTransient<FormComputerComponent>(); services.AddTransient<FormComputerComponent>();
services.AddTransient<FormReportComputerComponents>(); services.AddTransient<FormReportComputerComponents>();
services.AddTransient<FormReportOrders>(); services.AddTransient<FormReportOrders>();
} services.AddTransient<FormImplementer>();
services.AddTransient<FormImplementers>();
}
} }
} }

View File

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

View File

@ -11,6 +11,7 @@ namespace ComputersShopDataModels.Models
{ {
int ComputerId { get; } int ComputerId { 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; }