Готовая 6 лаба

This commit is contained in:
platoff aeeee 2024-06-21 14:50:51 +04:00
parent 13ffe5732e
commit 62be76e0e6
56 changed files with 3404 additions and 1042 deletions

View File

@ -0,0 +1,174 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyBusinessLogic.BussinessLogic
{
// Класс, реализующий логику для исполнителей
public class ImplementerLogic : IImplementerLogic
{
private readonly ILogger _logger;
private readonly IImplementerStorage _implementerStorage;
// Конструктор
public ImplementerLogic(ILogger<ImplementerLogic> logger, IImplementerStorage implementerStorage)
{
_logger = logger;
_implementerStorage = implementerStorage;
}
// Вывод всего отфильтрованного списка
public List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model)
{
_logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model?.ImplementerFIO, model?.Id);
// list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
// Вывод конкретного элемента
public ImplementerViewModel? ReadElement(ImplementerSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadList. 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 bool Create(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
// Обновление данных о работнике
public bool Update(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
// Удаление работника
public bool Delete(ImplementerBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_implementerStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
// Проверка входного аргумента для методов Insert, Update и Delete
private void CheckModel(ImplementerBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
// Так как при удалении передаём как параметр false
if (!withParams)
{
return;
}
// Проверка на наличие ФИО
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
throw new ArgumentNullException("Отсутствие ФИО в учётной записи", nameof(model.ImplementerFIO));
}
// Проверка на наличие пароля
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password));
}
// Проверка на наличие квалификации
if (model.Qualification <= 0)
{
throw new ArgumentNullException("Указана некорректная квалификация", nameof(model.Qualification));
}
// Проверка на наличие квалификации
if (model.WorkExperience < 0)
{
throw new ArgumentNullException("Указан некорректный стаж работы", nameof(model.WorkExperience));
}
_logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}. Password:{Password}. " +
"Qualification:{Qualification}. WorkExperience:{ WorkExperience}. Id:{Id}",
model.ImplementerFIO, model.Password, model.Qualification, model.WorkExperience, model.Id);
// Для проверка на наличие такого же аккаунта
var element = _implementerStorage.GetElement(new ImplementerSearchModel
{
ImplementerFIO = model.ImplementerFIO,
});
// Если элемент найден и его Id не совпадает с Id переданного объекта
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Исполнитель с таким именем уже есть");
}
}
}
}

View File

@ -20,6 +20,8 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
private readonly IOrderStorage _orderStorage; private readonly IOrderStorage _orderStorage;
static readonly object locker = new object();
// Конструктор // Конструктор
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage) public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
{ {
@ -47,6 +49,30 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
return list; return list;
} }
// Вывод конкретного чека
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;
}
// Создание чека // Создание чека
public bool CreateOrder(OrderBindingModel model) public bool CreateOrder(OrderBindingModel model)
{ {
@ -71,9 +97,12 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
} }
public bool TakeOrderInWork(OrderBindingModel model) public bool TakeOrderInWork(OrderBindingModel model)
{
lock (locker)
{ {
return StatusUpdate(model, OrderStatus.Выполняется); return StatusUpdate(model, OrderStatus.Выполняется);
} }
}
public bool FinishOrder(OrderBindingModel model) public bool FinishOrder(OrderBindingModel model)
{ {
@ -152,6 +181,12 @@ namespace FurnitureAssemblyBusinessLogic.BussinessLogic
model.Status = newOrderStatus; model.Status = newOrderStatus;
// Помещаем id работника, не забываем про него...
if (viewModel.ImplementerId.HasValue)
{
model.ImplementerId = viewModel.ImplementerId;
}
// Проверка на выдачу // Проверка на выдачу
if (model.Status == OrderStatus.Выдан) if (model.Status == OrderStatus.Выдан)
{ {

View File

@ -0,0 +1,162 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDataModels.Enums;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyBusinessLogic.BussinessLogic
{
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 * order.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order {Order}", implementer.Id, order.Id);
_orderLogic.FinishOrder(new OrderBindingModel
{
Id = order.Id
});
Thread.Sleep(implementer.Qualification);
}
// Игнорируем ошибку, если с заказом что-то случится
catch (InvalidOperationException ex)
{
_logger.LogWarning(ex, "Error try get work");
}
// В случае ошибки прервём выполнение имитации работы
catch (Exception ex)
{
_logger.LogError(ex, "Error while do work");
throw;
}
}
});
}
// Ищем заказ, который уже во всю в работе (вдруг прервали исполнителя)
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 {Id} back to order {Order}", implementer.Id, runOrder.Id);
// Доделываем работу
Thread.Sleep(implementer.WorkExperience * 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);
}
// Заказа может не быть, просто игнорируем ошибку
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,23 @@
using FurnitureAssemblyDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.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

@ -14,6 +14,8 @@ namespace FurnitureAssemblyContracts.BindingModels
public int ClientId { get; set; } public int ClientId { get; set; }
public int? ImplementerId { get; set; }
public int FurnitureId { get; set; } public int FurnitureId { get; set; }
public int Count { get; set; } public int Count { get; set; }

View File

@ -0,0 +1,25 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.BusinessLogicsContracts
{
// Бизнес-логика для исполнителей
public interface IImplementerLogic
{
List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model);
ImplementerViewModel? ReadElement(ImplementerSearchModel model);
bool Create(ImplementerBindingModel model);
bool Update(ImplementerBindingModel model);
bool Delete(ImplementerBindingModel model);
}
}

View File

@ -14,6 +14,8 @@ namespace FurnitureAssemblyContracts.BusinessLogicsContracts
{ {
List<OrderViewModel>? ReadList(OrderSearchModel? model); List<OrderViewModel>? ReadList(OrderSearchModel? model);
OrderViewModel? ReadElement(OrderSearchModel model);
bool CreateOrder(OrderBindingModel model); bool CreateOrder(OrderBindingModel model);
bool TakeOrderInWork(OrderBindingModel model); bool TakeOrderInWork(OrderBindingModel model);

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.BusinessLogicsContracts
{
// Интерфейс для класса, имитирующего работу
public interface IWorkProcess
{
// Запуск работы
void DoWork(IImplementerLogic implementerLogic, IOrderLogic orderLogic);
}
}

View File

@ -10,8 +10,6 @@ namespace FurnitureAssemblyContracts.SearchModels
public class ClientSearchModel public class ClientSearchModel
{ {
public int? Id { get; set; } public int? Id { get; set; }
public string? ClientFIO { get; set; }
public string? Email { get; set; } public string? Email { get; set; }

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyContracts.SearchModels
{
// Модель для поиска исполнителя
public class ImplementerSearchModel
{
public int? Id { get; set; }
public string? ImplementerFIO { get; set; }
public string? Password { get; set; }
public int? WorkExperience { get; set; }
public int? Qualification { get; set; }
}
}

View File

@ -1,4 +1,5 @@
using System; using FurnitureAssemblyDataModels.Enums;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -15,9 +16,15 @@ namespace FurnitureAssemblyContracts.SearchModels
// для поиска по клиенту // для поиска по клиенту
public int? ClientId { get; set; } public int? ClientId { get; set; }
// Для поиска по исполнителю
public int? ImplementerId { get; set; }
// Два поля для возможности производить выборку // Два поля для возможности производить выборку
public DateTime? DateFrom { get; set; } public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; } public DateTime? DateTo { get; set; }
// Для статуса заказа
public OrderStatus? Status { get; set; }
} }
} }

View File

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

@ -20,6 +20,11 @@ namespace FurnitureAssemblyContracts.ViewModels
[DisplayName("ФИО клиента")] [DisplayName("ФИО клиента")]
public string ClientFIO { get; set; } = string.Empty; public string ClientFIO { get; set; } = string.Empty;
public int? ImplementerId { get; set; }
[DisplayName("ФИО исполнителя")]
public string ImplementerFIO { get; set; } = string.Empty;
public int FurnitureId { get; set; } public int FurnitureId { get; set; }
[DisplayName("Изделие")] [DisplayName("Изделие")]

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyDataModels.Models
{
// Интерфейс, отвечающий за исполнителя
public interface IImplementerModel : IId
{
string ImplementerFIO { get; }
string Password { get; }
int WorkExperience { get; }
int Qualification { get; }
}
}

View File

@ -13,6 +13,12 @@ namespace FurnitureAssemblyDataModels.Models
// id продукта // id продукта
int FurnitureId { get; } int FurnitureId { get; }
// id клиента
int ClientId { get; }
// id исполнителя
int? ImplementerId { get; }
// кол-во продуктов // кол-во продуктов
int Count { get; } int Count { get; }

View File

@ -29,5 +29,7 @@ namespace FurnitureAssemblyDatabaseImplement
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,107 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyDatabaseImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
using var context = new FurnitureAssemblyDatabase();
if (model.Id.HasValue)
return context.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
if (model.ImplementerFIO != null && model.Password != null)
return context.Implementers.FirstOrDefault(x => x.ImplementerFIO
.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel;
if (model.ImplementerFIO != null)
return context.Implementers.FirstOrDefault(x => x.ImplementerFIO
.Equals(model.ImplementerFIO))?.GetViewModel;
return null;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (model == null)
{
return new();
}
if (model.ImplementerFIO != null)
{
using var context = new FurnitureAssemblyDatabase();
return context.Implementers
.Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
public List<ImplementerViewModel> GetFullList()
{
using var context = new FurnitureAssemblyDatabase();
return context.Implementers.Select(x => x.GetViewModel).ToList();
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
using var context = new FurnitureAssemblyDatabase();
var res = Implementer.Create(model);
if (res != null)
{
context.Implementers.Add(res);
context.SaveChanges();
}
return res?.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
using var context = new FurnitureAssemblyDatabase();
var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
res.Update(model);
context.SaveChanges();
}
return res?.GetViewModel;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
using var context = new FurnitureAssemblyDatabase();
var res = context.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
context.Implementers.Remove(res);
context.SaveChanges();
}
return res?.GetViewModel;
}
}
}

View File

@ -23,25 +23,27 @@ namespace FurnitureAssemblyDatabaseImplement.Implements
using var context = new FurnitureAssemblyDatabase(); using var context = new FurnitureAssemblyDatabase();
return context.Orders.Include(x => x.Furniture).Include(x => x.Client). return context.Orders.Include(x => x.Furniture)
FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) .Include(x => x.Client).Include(x => x.Implementer)
?.GetViewModel; .FirstOrDefault(x => (model.Status == null || model.Status != null && model.Status.Equals(x.Status)) &&
(model.ImplementerId.HasValue && x.ImplementerId == model.ImplementerId) ||
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
} }
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{ {
using var context = new FurnitureAssemblyDatabase(); using var context = new FurnitureAssemblyDatabase();
if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue && !model.ClientId.HasValue) if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue && !model.ClientId.HasValue && model.Status == null)
{ {
return new(); return new();
} }
return context.Orders return context.Orders
.Where(x => x.Id == model.Id || model.DateFrom <= x.DateCreate && x.DateCreate <= model.DateTo || x.ClientId == model.ClientId) .Where(x => x.Id == model.Id || model.DateFrom <= x.DateCreate && x.DateCreate <= model.DateTo ||
.Include(x => x.Furniture) x.ClientId == model.ClientId || model.Status.Equals(x.Status))
.Include(x => x.Client) .Include(x => x.Furniture).Include(x => x.Client)
.Select(x => x.GetViewModel) .Include(x => x.Implementer).Select(x => x.GetViewModel)
.ToList(); .ToList();
} }
@ -51,6 +53,7 @@ namespace FurnitureAssemblyDatabaseImplement.Implements
using var context = new FurnitureAssemblyDatabase(); using var context = new FurnitureAssemblyDatabase();
return context.Orders.Include(x => x.Furniture).Include(x => x.Client) return context.Orders.Include(x => x.Furniture).Include(x => x.Client)
.Include(x => x.Implementer)
.Select(x => x.GetViewModel).ToList(); .Select(x => x.GetViewModel).ToList();
} }
@ -64,11 +67,12 @@ namespace FurnitureAssemblyDatabaseImplement.Implements
} }
using var context = new FurnitureAssemblyDatabase(); using var context = new FurnitureAssemblyDatabase();
context.Orders.Add(newOrder); context.Orders.Add(newOrder);
context.SaveChanges(); context.SaveChanges();
return context.Orders.Include(x => x.Furniture).Include(x => x.Client) return context.Orders.Include(x => x.Furniture).Include(x => x.Client)
.FirstOrDefault(x => x.Id == newOrder.Id)?.GetViewModel; .Include(x => x.Implementer).FirstOrDefault(x => x.Id == newOrder.Id)?.GetViewModel;
} }
public OrderViewModel? Update(OrderBindingModel model) public OrderViewModel? Update(OrderBindingModel model)
@ -77,6 +81,7 @@ namespace FurnitureAssemblyDatabaseImplement.Implements
var order = context.Orders var order = context.Orders
.Include(x => x.Furniture) .Include(x => x.Furniture)
.Include(x => x.Client) .Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => x.Id == model.Id); .FirstOrDefault(x => x.Id == model.Id);
if (order == null) if (order == null)
@ -90,6 +95,7 @@ namespace FurnitureAssemblyDatabaseImplement.Implements
return context.Orders return context.Orders
.Include(x => x.Furniture) .Include(x => x.Furniture)
.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;
} }
@ -101,8 +107,9 @@ namespace FurnitureAssemblyDatabaseImplement.Implements
if (element != null) if (element != null)
{ {
var deletedElement = context.Orders.Include(x => x.Furniture) // для более корректного отображения модели
.Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; var deletedElement = context.Orders.Include(x => x.Furniture).Include(x => x.Client)
.Include(x => x.Implementer).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
context.Orders.Remove(element); context.Orders.Remove(element);
context.SaveChanges(); context.SaveChanges();

View File

@ -0,0 +1,257 @@
// <auto-generated />
using System;
using FurnitureAssemblyDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace FurnitureAssemblyDatabaseImplement.Migrations
{
[DbContext(typeof(FurnitureAssemblyDatabase))]
[Migration("20240621104629_lab6")]
partial class lab6
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.17")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Furniture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("FurnitureName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Furnitures");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.FurnitureWorkPiece", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("FurnitureId")
.HasColumnType("int");
b.Property<int>("WorkPieceId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("FurnitureId");
b.HasIndex("WorkPieceId");
b.ToTable("FurnitureWorkPieces");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("FurnitureId")
.HasColumnType("int");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("FurnitureId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.WorkPiece", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Cost")
.HasColumnType("float");
b.Property<string>("WorkPieceName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("WorkPieces");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.FurnitureWorkPiece", b =>
{
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Furniture", "Furniture")
.WithMany("WorkPieces")
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.WorkPiece", "WorkPiece")
.WithMany("FurnitureWorkPieces")
.HasForeignKey("WorkPieceId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Furniture");
b.Navigation("WorkPiece");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Order", b =>
{
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Furniture", "Furniture")
.WithMany("Orders")
.HasForeignKey("FurnitureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Order")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("Furniture");
b.Navigation("Implementer");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Client", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Furniture", b =>
{
b.Navigation("Orders");
b.Navigation("WorkPieces");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Order");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.WorkPiece", b =>
{
b.Navigation("FurnitureWorkPieces");
});
#pragma warning restore 612, 618
}
}
}

View File

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

View File

@ -93,6 +93,33 @@ namespace FurnitureAssemblyDatabaseImplement.Migrations
b.ToTable("FurnitureWorkPieces"); b.ToTable("FurnitureWorkPieces");
}); });
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Order", b => modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Order", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@ -116,6 +143,9 @@ namespace FurnitureAssemblyDatabaseImplement.Migrations
b.Property<int>("FurnitureId") b.Property<int>("FurnitureId")
.HasColumnType("int"); .HasColumnType("int");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status") b.Property<int>("Status")
.HasColumnType("int"); .HasColumnType("int");
@ -128,6 +158,8 @@ namespace FurnitureAssemblyDatabaseImplement.Migrations
b.HasIndex("FurnitureId"); b.HasIndex("FurnitureId");
b.HasIndex("ImplementerId");
b.ToTable("Orders"); b.ToTable("Orders");
}); });
@ -184,9 +216,15 @@ namespace FurnitureAssemblyDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.HasOne("FurnitureAssemblyDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Order")
.HasForeignKey("ImplementerId");
b.Navigation("Client"); b.Navigation("Client");
b.Navigation("Furniture"); b.Navigation("Furniture");
b.Navigation("Implementer");
}); });
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Client", b => modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Client", b =>
@ -201,6 +239,11 @@ namespace FurnitureAssemblyDatabaseImplement.Migrations
b.Navigation("WorkPieces"); b.Navigation("WorkPieces");
}); });
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Order");
});
modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.WorkPiece", b => modelBuilder.Entity("FurnitureAssemblyDatabaseImplement.Models.WorkPiece", b =>
{ {
b.Navigation("FurnitureWorkPieces"); b.Navigation("FurnitureWorkPieces");

View File

@ -24,6 +24,7 @@ namespace FurnitureAssemblyDatabaseImplement.Models
public Dictionary<int, (IWorkPieceModel, int)>? _furnitureWorkPieces = null; public Dictionary<int, (IWorkPieceModel, int)>? _furnitureWorkPieces = null;
// Это поле не будет "мапиться" в бд
[NotMapped] [NotMapped]
public Dictionary<int, (IWorkPieceModel, int)> FurnitureWorkPieces public Dictionary<int, (IWorkPieceModel, int)> FurnitureWorkPieces
{ {
@ -39,6 +40,7 @@ namespace FurnitureAssemblyDatabaseImplement.Models
} }
} }
// Для реализации связи многие ко многим с заготовками
[ForeignKey("FurnitureId")] [ForeignKey("FurnitureId")]
public virtual List<FurnitureWorkPiece> WorkPieces { get; set; } = new(); public virtual List<FurnitureWorkPiece> WorkPieces { get; set; } = new();

View File

@ -0,0 +1,86 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDataModels.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 FurnitureAssemblyDatabaseImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; set; }
[Required]
public string ImplementerFIO { get; set; } = string.Empty;
[Required]
public string Password { get; set; } = string.Empty;
[Required]
public int WorkExperience { get; set; }
[Required]
public int Qualification { get; set; }
// Для реализации связи один ко многим с заказами
[ForeignKey("ImplementerId")]
public virtual List<Order> Order { get; set; } = new();
public static Implementer? Create(ImplementerBindingModel model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
Password = model.Password,
ImplementerFIO = model.ImplementerFIO,
Qualification = model.Qualification,
WorkExperience = model.WorkExperience
};
}
public static Implementer Create(ImplementerViewModel model)
{
return new Implementer
{
Id = model.Id,
Password = model.Password,
ImplementerFIO = model.ImplementerFIO,
Qualification = model.Qualification,
WorkExperience = model.WorkExperience
};
}
public void Update(ImplementerBindingModel model)
{
if (model == null)
{
return;
}
Id = model.Id;
Password = model.Password;
ImplementerFIO = model.ImplementerFIO;
Qualification = model.Qualification;
WorkExperience = model.WorkExperience;
}
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Password = Password,
ImplementerFIO = ImplementerFIO,
Qualification = Qualification,
WorkExperience = WorkExperience
};
}
}

View File

@ -5,7 +5,6 @@ using FurnitureAssemblyDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -19,6 +18,10 @@ namespace FurnitureAssemblyDatabaseImplement.Models
[Required] [Required]
public int FurnitureId { get; private set; } public int FurnitureId { get; private set; }
[Required]
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
[Required] [Required]
public int Count { get; private set; } public int Count { get; private set; }
@ -34,13 +37,14 @@ namespace FurnitureAssemblyDatabaseImplement.Models
public DateTime? DateImplement { get; private set; } public DateTime? DateImplement { get; private set; }
[Required]
public int ClientId { get; private set; }
// Для передачи названия изделия // Для передачи названия изделия
public virtual Furniture Furniture { get; set; } = new(); public virtual Furniture Furniture { get; set; }
// Для передачи имени клиента // Для передачи имени клиента
public virtual Client Client { get; set; } = new(); public virtual Client Client { get; set; }
// Для передачи имени исполнителя
public virtual Implementer? Implementer { get; set; }
public static Order? Create(OrderBindingModel model) public static Order? Create(OrderBindingModel model)
{ {
@ -54,6 +58,7 @@ namespace FurnitureAssemblyDatabaseImplement.Models
Id = model.Id, Id = model.Id,
FurnitureId = model.FurnitureId, FurnitureId = model.FurnitureId,
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,
@ -69,6 +74,7 @@ namespace FurnitureAssemblyDatabaseImplement.Models
return; return;
} }
ImplementerId = model.ImplementerId;
Status = model.Status; Status = model.Status;
DateImplement = model.DateImplement; DateImplement = model.DateImplement;
} }
@ -78,13 +84,15 @@ namespace FurnitureAssemblyDatabaseImplement.Models
Id = Id, Id = Id,
FurnitureId = FurnitureId, FurnitureId = FurnitureId,
ClientId = ClientId, ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,
DateCreate = DateCreate, DateCreate = DateCreate,
DateImplement = DateImplement, DateImplement = DateImplement,
FurnitureName = Furniture.FurnitureName, FurnitureName = Furniture.FurnitureName,
ClientFIO = Client.ClientFIO ClientFIO = Client.ClientFIO,
ImplementerFIO = Implementer?.ImplementerFIO ?? string.Empty
}; };
} }
} }

View File

@ -21,6 +21,7 @@ namespace FurnitureAssemblyDatabaseImplement.Models
[Required] [Required]
public double Cost { get; set; } public double Cost { get; set; }
// для реализации связи многие ко многим с изделиями
[ForeignKey("WorkPieceId")] [ForeignKey("WorkPieceId")]
public virtual List<FurnitureWorkPiece> FurnitureWorkPieces { get; set; } = new(); public virtual List<FurnitureWorkPiece> FurnitureWorkPieces { get; set; } = new();

View File

@ -20,6 +20,8 @@ namespace FurnitureAssemblyFileImplement
private readonly string ClientFileName = "Client.xml"; private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
public List<WorkPiece> WorkPieces { get; private set; } public List<WorkPiece> WorkPieces { get; private set; }
public List<Order> Orders { get; private set; } public List<Order> Orders { get; private set; }
@ -28,6 +30,8 @@ namespace FurnitureAssemblyFileImplement
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)
@ -46,6 +50,8 @@ namespace FurnitureAssemblyFileImplement
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement); public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement);
public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement);
private DataFileSingleton() private DataFileSingleton()
{ {
@ -53,6 +59,7 @@ namespace FurnitureAssemblyFileImplement
Furnitures = LoadData(FurnitureFileName, "Furniture", x => Furniture.Create(x)!)!; Furnitures = LoadData(FurnitureFileName, "Furniture", x => Furniture.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!;
} }
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction) private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)

View File

@ -0,0 +1,112 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyFileImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataFileSingleton source;
public ImplementerStorage()
{
source = DataFileSingleton.GetInstance();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (model.Id.HasValue)
return source.Implementers
.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
if (model.ImplementerFIO != null && model.Password != null)
return source.Implementers.FirstOrDefault(x => x.ImplementerFIO
.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel;
if (model.ImplementerFIO != null)
return source.Implementers
.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel;
return null;
}
public List<ImplementerViewModel> GetFullList()
{
return source.Implementers.Select(x => x.GetViewModel).ToList();
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (model == null)
{
return new();
}
if (model.ImplementerFIO != null)
{
return source.Implementers
.Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO))
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
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;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
var element = source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Implementers.Remove(element);
source.SaveImplementers();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -28,20 +28,24 @@ namespace FurnitureAssemblyFileImplement.Implements
return null; return null;
} }
if (model.ImplementerId.HasValue && model.Status != null)
return source.Orders.FirstOrDefault(x => x.ImplementerId == model.ImplementerId && model.Status
.Equals(x.Status))?.GetViewModel;
return source.Orders return source.Orders
.FirstOrDefault(x => .FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
(model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
} }
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{ {
if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue && !model.ClientId.HasValue) if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue && !model.ClientId.HasValue && model.Status == null)
{ {
return new(); return new();
} }
return source.Orders return source.Orders
.Where(x => x.Id == model.Id || model.DateFrom <= x.DateCreate && x.DateCreate <= model.DateTo || x.ClientId == model.ClientId) .Where(x => x.Id == model.Id || model.DateFrom <= x.DateCreate && x.DateCreate <= model.DateTo
|| x.ClientId == model.ClientId || model.Status.Equals(x.Status))
.Select(x => GetViewModel(x)).ToList(); .Select(x => GetViewModel(x)).ToList();
} }
@ -50,7 +54,7 @@ namespace FurnitureAssemblyFileImplement.Implements
return source.Orders.Select(x => GetViewModel(x)).ToList(); return source.Orders.Select(x => GetViewModel(x)).ToList();
} }
// Для загрузки названий изделия в заказе // Для загрузки названий изделия и исполнителя в заказе
private OrderViewModel GetViewModel(Order order) private OrderViewModel GetViewModel(Order order)
{ {
var viewModel = order.GetViewModel; var viewModel = order.GetViewModel;
@ -59,6 +63,8 @@ namespace FurnitureAssemblyFileImplement.Implements
var client = source.Clients.FirstOrDefault(x => x.Id == order.ClientId); var client = source.Clients.FirstOrDefault(x => x.Id == order.ClientId);
var implementer = source.Implementers.FirstOrDefault(x => x.Id == order.ImplementerId);
if (furniture != null) if (furniture != null)
{ {
viewModel.FurnitureName = furniture.FurnitureName; viewModel.FurnitureName = furniture.FurnitureName;
@ -69,6 +75,11 @@ namespace FurnitureAssemblyFileImplement.Implements
viewModel.ClientFIO = client.ClientFIO; viewModel.ClientFIO = client.ClientFIO;
} }
if (implementer != null)
{
viewModel.ImplementerFIO = implementer.ImplementerFIO;
}
return viewModel; return viewModel;
} }

View File

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

View File

@ -20,6 +20,8 @@ namespace FurnitureAssemblyFileImplement.Models
public int ClientId { get; private set; } public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
public int Count { get; private set; } public int Count { get; private set; }
public double Sum { get; private set; } public double Sum { get; private set; }
@ -42,6 +44,7 @@ namespace FurnitureAssemblyFileImplement.Models
Id = model.Id, Id = model.Id,
FurnitureId = model.FurnitureId, FurnitureId = model.FurnitureId,
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,
@ -62,6 +65,7 @@ namespace FurnitureAssemblyFileImplement.Models
Id = Convert.ToInt32(element.Attribute("Id")!.Value), Id = Convert.ToInt32(element.Attribute("Id")!.Value),
FurnitureId = Convert.ToInt32(element.Element("FurnitureId")!.Value), FurnitureId = Convert.ToInt32(element.Element("FurnitureId")!.Value),
ClientId = Convert.ToInt32(element.Attribute("Id")!.Value), ClientId = Convert.ToInt32(element.Attribute("Id")!.Value),
ImplementerId = Convert.ToInt32(element.Attribute("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),
Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value), Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value),
@ -87,6 +91,7 @@ namespace FurnitureAssemblyFileImplement.Models
Id = Id, Id = Id,
FurnitureId = FurnitureId, FurnitureId = FurnitureId,
ClientId = ClientId, ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,
@ -98,6 +103,7 @@ namespace FurnitureAssemblyFileImplement.Models
new XAttribute("Id", Id), new XAttribute("Id", Id),
new XElement("FurnitureId", FurnitureId.ToString()), new XElement("FurnitureId", FurnitureId.ToString()),
new XElement("ClientId", ClientId.ToString()), new XElement("ClientId", ClientId.ToString()),
new XElement("ImplementerId", ImplementerId.ToString()),
new XElement("Count", Count.ToString()), new XElement("Count", Count.ToString()),
new XElement("Sum", Sum.ToString()), new XElement("Sum", Sum.ToString()),
new XElement("Status", Status.ToString()), new XElement("Status", Status.ToString()),

View File

@ -24,12 +24,16 @@ namespace FurnitureAssemblyListImplement
// Список для хранения клиентов // Список для хранения клиентов
public List<Client> Clients { get; set; } public List<Client> Clients { get; set; }
// Список для хранения исполнителей
public List<Implementer> Implementers { get; set; }
public DataListSingleton() public DataListSingleton()
{ {
WorkPiece = new List<WorkPiece>(); WorkPiece = new List<WorkPiece>();
Furnitures = new List<Furniture>(); Furnitures = new List<Furniture>();
Orders = new List<Order>(); Orders = new List<Order>();
Clients = new List<Client>(); Clients = new List<Client>();
Implementers = new List<Implementer>();
} }
public static DataListSingleton GetInstance() public static DataListSingleton GetInstance()

View File

@ -0,0 +1,130 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.StoragesContracts;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyListImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
// Поле для работы со списком исполнителей
private readonly DataListSingleton _source;
public ImplementerStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ImplementerViewModel> GetFullList()
{
var result = new List<ImplementerViewModel>();
foreach (var implementer in _source.Implementers)
{
result.Add(implementer.GetViewModel);
}
return result;
}
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 ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue)
{
return null;
}
foreach (var implementer in _source.Implementers)
{
if ((!string.IsNullOrEmpty(model.ImplementerFIO) && implementer.ImplementerFIO == model.ImplementerFIO) ||
(model.Id.HasValue && implementer.Id == model.Id))
{
return implementer.GetViewModel;
}
}
return null;
}
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;
}
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;
}
}
}

View File

@ -90,7 +90,7 @@ namespace FurnitureAssemblyListImplement.Implements
return null; return null;
} }
// Метод для записи названия изделия на форме с заказами // Метод для записи названия изделия на форме с заказами и исполнителя
private OrderViewModel GetViewModel(Order order) private OrderViewModel GetViewModel(Order order)
{ {
var viewModel = order.GetViewModel; var viewModel = order.GetViewModel;
@ -114,6 +114,16 @@ namespace FurnitureAssemblyListImplement.Implements
} }
} }
foreach (var implementer in _source.Implementers)
{
if (implementer.Id == order.ImplementerId)
{
viewModel.ImplementerFIO = implementer.ImplementerFIO;
break;
}
}
return viewModel; return viewModel;
} }

View File

@ -0,0 +1,66 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FurnitureAssemblyListImplement.Models
{
public class Implementer : IImplementerModel
{
public int Id { get; private set; }
public string ImplementerFIO { get; private set; } = string.Empty;
public string Password { get; private set; } = string.Empty;
public int WorkExperience { get; private set; }
public int Qualification { get; private set; }
// Метод для создания объекта от класса-компонента на основе класса-BindingModel
public static Implementer? Create(ImplementerBindingModel? model)
{
if (model == null)
{
return null;
}
return new Implementer()
{
Id = model.Id,
Password = model.Password,
ImplementerFIO = model.ImplementerFIO,
Qualification = model.Qualification,
WorkExperience = model.WorkExperience
};
}
// Метод изменения существующего объекта
public void Update(ImplementerBindingModel? model)
{
if (model == null)
{
return;
}
Password = model.Password;
ImplementerFIO = model.ImplementerFIO;
Qualification = model.Qualification;
WorkExperience = model.WorkExperience;
}
// Метод для создания объекта класса ViewModel на основе данных объекта класса-компонента
public ImplementerViewModel GetViewModel => new()
{
Id = Id,
Password = Password,
ImplementerFIO = ImplementerFIO,
Qualification = Qualification,
WorkExperience = WorkExperience
};
}
}

View File

@ -21,6 +21,8 @@ namespace FurnitureAssemblyListImplement.Models
public int FurnitureId { get; private set; } public int FurnitureId { 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; }
@ -43,6 +45,7 @@ namespace FurnitureAssemblyListImplement.Models
Id = model.Id, Id = model.Id,
FurnitureId = model.FurnitureId, FurnitureId = model.FurnitureId,
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,
@ -58,6 +61,7 @@ namespace FurnitureAssemblyListImplement.Models
{ {
return; return;
} }
Status = model.Status; Status = model.Status;
DateImplement = model.DateImplement; DateImplement = model.DateImplement;
} }
@ -68,6 +72,7 @@ namespace FurnitureAssemblyListImplement.Models
Id = Id, Id = Id,
FurnitureId = FurnitureId, FurnitureId = FurnitureId,
ClientId = ClientId, ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,

View File

@ -6,6 +6,7 @@ using Microsoft.AspNetCore.Mvc;
namespace FurnitureAssemblyRestApi.Controllers namespace FurnitureAssemblyRestApi.Controllers
{ {
// Указание для контроллера, что Route будет строиться по названиям контроллера и метода (так как у нас два Post-метода)
[Route("api/[controller]/[action]")] [Route("api/[controller]/[action]")]
[ApiController] [ApiController]
public class ClientController : Controller public class ClientController : Controller
@ -25,6 +26,7 @@ namespace FurnitureAssemblyRestApi.Controllers
{ {
try try
{ {
// Поиск записи по переданным логину и паролю
return _logic.ReadElement(new ClientSearchModel return _logic.ReadElement(new ClientSearchModel
{ {
Email = login, Email = login,
@ -43,6 +45,7 @@ namespace FurnitureAssemblyRestApi.Controllers
{ {
try try
{ {
// Создание клиента
_logic.Create(model); _logic.Create(model);
} }
catch (Exception ex) catch (Exception ex)
@ -57,6 +60,7 @@ namespace FurnitureAssemblyRestApi.Controllers
{ {
try try
{ {
// Изменение клиента
_logic.Update(model); _logic.Update(model);
} }
catch (Exception ex) catch (Exception ex)

View File

@ -0,0 +1,112 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.SearchModels;
using FurnitureAssemblyContracts.ViewModels;
using FurnitureAssemblyDataModels.Enums;
using Microsoft.AspNetCore.Mvc;
namespace FurnitureAssemblyRestApi.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

@ -6,6 +6,9 @@ using Microsoft.AspNetCore.Mvc;
namespace FurnitureAssemblyRestApi.Controllers namespace FurnitureAssemblyRestApi.Controllers
{ {
// Контроллер с логикой по заказам и изделиям
// Настройка контроллер для использования нескольких Post и Get запросов
[Route("api/[controller]/[action]")] [Route("api/[controller]/[action]")]
[ApiController] [ApiController]
public class MainController : Controller public class MainController : Controller

View File

@ -16,16 +16,19 @@ builder.Logging.AddLog4Net("log4net.config");
builder.Services.AddTransient<IClientStorage, ClientStorage>(); builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>(); builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IFurnitureStorage, FurnitureStorage>(); builder.Services.AddTransient<IFurnitureStorage, FurnitureStorage>();
builder.Services.AddTransient<IImplementerStorage, ImplementerStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>(); builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>(); builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IFurnitureLogic, FurnitureLogic>(); builder.Services.AddTransient<IFurnitureLogic, FurnitureLogic>();
builder.Services.AddTransient<IImplementerLogic, ImplementerLogic>();
builder.Services.AddControllers(); builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
// Äëÿ ðàáîòû app.UseSwaggerUI
builder.Services.AddSwaggerGen(c => builder.Services.AddSwaggerGen(c =>
{ {
c.SwaggerDoc("v1", new OpenApiInfo { Title = "FurnitureAssemblyRestApi", Version = "v1" }); c.SwaggerDoc("v1", new OpenApiInfo { Title = "FurnitureAssemblyRestApi", Version = "v1" });
@ -38,6 +41,7 @@ if (app.Environment.IsDevelopment())
{ {
app.UseSwagger(); app.UseSwagger();
// Âñòðîåííûé Swagger äëÿ ïðîâåðêè
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "FurnitureAssemblyRestApi v1")); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "FurnitureAssemblyRestApi v1"));
} }

View File

@ -28,61 +28,55 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.dataGridView = new System.Windows.Forms.DataGridView(); dataGridView = new DataGridView();
this.buttonDelete = new System.Windows.Forms.Button(); buttonDelete = new Button();
this.buttonRef = new System.Windows.Forms.Button(); buttonRef = new Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
this.SuspendLayout(); SuspendLayout();
// //
// dataGridView // dataGridView
// //
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(10, 9); dataGridView.Location = new Point(12, 12);
this.dataGridView.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); dataGridView.Name = "dataGridView";
this.dataGridView.Name = "dataGridView"; dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowHeadersWidth = 51; dataGridView.RowTemplate.Height = 29;
this.dataGridView.RowTemplate.Height = 29; dataGridView.Size = new Size(582, 426);
this.dataGridView.Size = new System.Drawing.Size(509, 320); dataGridView.TabIndex = 0;
this.dataGridView.TabIndex = 0;
// //
// buttonDelete // buttonDelete
// //
this.buttonDelete.Location = new System.Drawing.Point(558, 26); buttonDelete.Location = new Point(638, 35);
this.buttonDelete.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); buttonDelete.Name = "buttonDelete";
this.buttonDelete.Name = "buttonDelete"; buttonDelete.Size = new Size(125, 29);
this.buttonDelete.Size = new System.Drawing.Size(109, 22); buttonDelete.TabIndex = 1;
this.buttonDelete.TabIndex = 1; buttonDelete.Text = "Удалить";
this.buttonDelete.Text = "Удалить"; buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.UseVisualStyleBackColor = true; buttonDelete.Click += ButtonDelete_Click;
this.buttonDelete.Click += new System.EventHandler(this.ButtonDelete_Click);
// //
// buttonRef // buttonRef
// //
this.buttonRef.Location = new System.Drawing.Point(558, 77); buttonRef.Location = new Point(638, 103);
this.buttonRef.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); buttonRef.Name = "buttonRef";
this.buttonRef.Name = "buttonRef"; buttonRef.Size = new Size(125, 29);
this.buttonRef.Size = new System.Drawing.Size(109, 22); buttonRef.TabIndex = 2;
this.buttonRef.TabIndex = 2; buttonRef.Text = "Обновить";
this.buttonRef.Text = "Обновить"; buttonRef.UseVisualStyleBackColor = true;
this.buttonRef.UseVisualStyleBackColor = true; buttonRef.Click += ButtonRef_Click;
this.buttonRef.Click += new System.EventHandler(this.ButtonRef_Click);
// //
// FormClients // FormClients
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); AutoScaleDimensions = new SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(700, 338); ClientSize = new Size(800, 450);
this.Controls.Add(this.buttonRef); Controls.Add(buttonRef);
this.Controls.Add(this.buttonDelete); Controls.Add(buttonDelete);
this.Controls.Add(this.dataGridView); Controls.Add(dataGridView);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); Name = "FormClients";
this.Name = "FormClients"; Text = "Клиенты";
this.Text = "Клиенты"; Load += FormClients_Load;
this.Load += new System.EventHandler(this.FormClients_Load); ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
this.Click += new System.EventHandler(this.FormClients_Load); ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
} }
#endregion #endregion

View File

@ -28,130 +28,126 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.labelFurniture = new System.Windows.Forms.Label(); labelFurniture = new Label();
this.labelCount = new System.Windows.Forms.Label(); labelCount = new Label();
this.labelSum = new System.Windows.Forms.Label(); labelSum = new Label();
this.comboBoxFurniture = new System.Windows.Forms.ComboBox(); comboBoxFurniture = new ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox(); textBoxCount = new TextBox();
this.textBoxSum = new System.Windows.Forms.TextBox(); textBoxSum = new TextBox();
this.buttonSave = new System.Windows.Forms.Button(); buttonSave = new Button();
this.buttonCancel = new System.Windows.Forms.Button(); buttonCancel = new Button();
this.labelClient = new System.Windows.Forms.Label(); labelClient = new Label();
this.comboBoxClient = new System.Windows.Forms.ComboBox(); comboBoxClient = new ComboBox();
this.SuspendLayout(); SuspendLayout();
// //
// labelFurniture // labelFurniture
// //
this.labelFurniture.AutoSize = true; labelFurniture.AutoSize = true;
this.labelFurniture.Location = new System.Drawing.Point(21, 18); labelFurniture.Location = new Point(24, 24);
this.labelFurniture.Name = "labelFurniture"; labelFurniture.Name = "labelFurniture";
this.labelFurniture.Size = new System.Drawing.Size(56, 15); labelFurniture.Size = new Size(71, 20);
this.labelFurniture.TabIndex = 0; labelFurniture.TabIndex = 0;
this.labelFurniture.Text = "Изделие:"; labelFurniture.Text = "Изделие:";
// //
// labelCount // labelCount
// //
this.labelCount.AutoSize = true; labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(21, 86); labelCount.Location = new Point(24, 114);
this.labelCount.Name = "labelCount"; labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(75, 15); labelCount.Size = new Size(93, 20);
this.labelCount.TabIndex = 1; labelCount.TabIndex = 1;
this.labelCount.Text = "Количество:"; labelCount.Text = "Количество:";
// //
// labelSum // labelSum
// //
this.labelSum.AutoSize = true; labelSum.AutoSize = true;
this.labelSum.Location = new System.Drawing.Point(21, 118); labelSum.Location = new Point(24, 157);
this.labelSum.Name = "labelSum"; labelSum.Name = "labelSum";
this.labelSum.Size = new System.Drawing.Size(48, 15); labelSum.Size = new Size(58, 20);
this.labelSum.TabIndex = 2; labelSum.TabIndex = 2;
this.labelSum.Text = "Сумма:"; labelSum.Text = "Сумма:";
// //
// comboBoxFurniture // comboBoxFurniture
// //
this.comboBoxFurniture.FormattingEnabled = true; comboBoxFurniture.FormattingEnabled = true;
this.comboBoxFurniture.Location = new System.Drawing.Point(145, 16); comboBoxFurniture.Location = new Point(166, 21);
this.comboBoxFurniture.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); comboBoxFurniture.Name = "comboBoxFurniture";
this.comboBoxFurniture.Name = "comboBoxFurniture"; comboBoxFurniture.Size = new Size(278, 28);
this.comboBoxFurniture.Size = new System.Drawing.Size(244, 23); comboBoxFurniture.TabIndex = 3;
this.comboBoxFurniture.TabIndex = 3; comboBoxFurniture.SelectedIndexChanged += ComboBoxFurniture_SelectedIndexChanged;
// //
// textBoxCount // textBoxCount
// //
this.textBoxCount.Location = new System.Drawing.Point(145, 83); textBoxCount.Location = new Point(166, 111);
this.textBoxCount.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); textBoxCount.Name = "textBoxCount";
this.textBoxCount.Name = "textBoxCount"; textBoxCount.Size = new Size(278, 27);
this.textBoxCount.Size = new System.Drawing.Size(244, 23); textBoxCount.TabIndex = 4;
this.textBoxCount.TabIndex = 4; textBoxCount.TextChanged += TextBoxCount_TextChanged;
this.textBoxCount.TextChanged += new System.EventHandler(this.TextBoxCount_TextChanged);
// //
// textBoxSum // textBoxSum
// //
this.textBoxSum.Location = new System.Drawing.Point(145, 116); textBoxSum.Location = new Point(166, 154);
this.textBoxSum.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); textBoxSum.Name = "textBoxSum";
this.textBoxSum.Name = "textBoxSum"; textBoxSum.Size = new Size(278, 27);
this.textBoxSum.Size = new System.Drawing.Size(244, 23); textBoxSum.TabIndex = 5;
this.textBoxSum.TabIndex = 5;
// //
// buttonSave // buttonSave
// //
this.buttonSave.Location = new System.Drawing.Point(201, 149); buttonSave.Location = new Point(230, 199);
this.buttonSave.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); buttonSave.Name = "buttonSave";
this.buttonSave.Name = "buttonSave"; buttonSave.Size = new Size(94, 29);
this.buttonSave.Size = new System.Drawing.Size(82, 22); buttonSave.TabIndex = 6;
this.buttonSave.TabIndex = 6; buttonSave.Text = "Сохранить";
this.buttonSave.Text = "Сохранить"; buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.UseVisualStyleBackColor = true; buttonSave.Click += ButtonSave_Click;
// //
// buttonCancel // buttonCancel
// //
this.buttonCancel.Location = new System.Drawing.Point(298, 149); buttonCancel.Location = new Point(340, 199);
this.buttonCancel.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); buttonCancel.Name = "buttonCancel";
this.buttonCancel.Name = "buttonCancel"; buttonCancel.Size = new Size(94, 29);
this.buttonCancel.Size = new System.Drawing.Size(82, 22); buttonCancel.TabIndex = 7;
this.buttonCancel.TabIndex = 7; buttonCancel.Text = "Отмена";
this.buttonCancel.Text = "Отмена"; buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.UseVisualStyleBackColor = true; buttonCancel.Click += ButtonCancel_Click;
// //
// labelClient // labelClient
// //
this.labelClient.AutoSize = true; labelClient.AutoSize = true;
this.labelClient.Location = new System.Drawing.Point(21, 52); labelClient.Location = new Point(24, 69);
this.labelClient.Name = "labelClient"; labelClient.Name = "labelClient";
this.labelClient.Size = new System.Drawing.Size(60, 15); labelClient.Size = new Size(74, 20);
this.labelClient.TabIndex = 8; labelClient.TabIndex = 8;
this.labelClient.Text = "Заказчик:"; labelClient.Text = "Заказчик:";
// //
// comboBoxClient // comboBoxClient
// //
this.comboBoxClient.FormattingEnabled = true; comboBoxClient.FormattingEnabled = true;
this.comboBoxClient.Location = new System.Drawing.Point(145, 50); comboBoxClient.Location = new Point(166, 66);
this.comboBoxClient.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); comboBoxClient.Name = "comboBoxClient";
this.comboBoxClient.Name = "comboBoxClient"; comboBoxClient.Size = new Size(278, 28);
this.comboBoxClient.Size = new System.Drawing.Size(244, 23); comboBoxClient.TabIndex = 9;
this.comboBoxClient.TabIndex = 9;
// //
// FormCreateOrder // FormCreateOrder
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); AutoScaleDimensions = new SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(419, 192); ClientSize = new Size(479, 256);
this.Controls.Add(this.comboBoxClient); Controls.Add(comboBoxClient);
this.Controls.Add(this.labelClient); Controls.Add(labelClient);
this.Controls.Add(this.buttonCancel); Controls.Add(buttonCancel);
this.Controls.Add(this.buttonSave); Controls.Add(buttonSave);
this.Controls.Add(this.textBoxSum); Controls.Add(textBoxSum);
this.Controls.Add(this.textBoxCount); Controls.Add(textBoxCount);
this.Controls.Add(this.comboBoxFurniture); Controls.Add(comboBoxFurniture);
this.Controls.Add(this.labelSum); Controls.Add(labelSum);
this.Controls.Add(this.labelCount); Controls.Add(labelCount);
this.Controls.Add(this.labelFurniture); Controls.Add(labelFurniture);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); Name = "FormCreateOrder";
this.Name = "FormCreateOrder"; Text = "Заказ";
this.Text = "Заказ"; Load += FormCreateOrder_Load;
this.ResumeLayout(false); ResumeLayout(false);
this.PerformLayout(); PerformLayout();
} }
#endregion #endregion

View File

@ -0,0 +1,162 @@
namespace FurnitureAssemblyView
{
partial class FormImplementer
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
labelFIO = new Label();
labelPassword = new Label();
labelWorkExperience = new Label();
labelQualification = new Label();
textBoxImplementerFIO = new TextBox();
textBoxPassword = new TextBox();
textBoxWorkExperience = new TextBox();
textBoxQualification = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// labelFIO
//
labelFIO.AutoSize = true;
labelFIO.Location = new Point(38, 27);
labelFIO.Name = "labelFIO";
labelFIO.Size = new Size(45, 20);
labelFIO.TabIndex = 0;
labelFIO.Text = "ФИО:";
//
// labelPassword
//
labelPassword.AutoSize = true;
labelPassword.Location = new Point(38, 79);
labelPassword.Name = "labelPassword";
labelPassword.Size = new Size(65, 20);
labelPassword.TabIndex = 1;
labelPassword.Text = "Пароль:";
//
// labelWorkExperience
//
labelWorkExperience.AutoSize = true;
labelWorkExperience.Location = new Point(38, 136);
labelWorkExperience.Name = "labelWorkExperience";
labelWorkExperience.Size = new Size(102, 20);
labelWorkExperience.TabIndex = 2;
labelWorkExperience.Text = "Стаж работы:";
//
// labelQualification
//
labelQualification.AutoSize = true;
labelQualification.Location = new Point(319, 136);
labelQualification.Name = "labelQualification";
labelQualification.Size = new Size(114, 20);
labelQualification.TabIndex = 3;
labelQualification.Text = "Квалификация:";
//
// textBoxImplementerFIO
//
textBoxImplementerFIO.Location = new Point(160, 24);
textBoxImplementerFIO.Name = "textBoxImplementerFIO";
textBoxImplementerFIO.Size = new Size(436, 27);
textBoxImplementerFIO.TabIndex = 4;
//
// textBoxPassword
//
textBoxPassword.Location = new Point(160, 76);
textBoxPassword.Name = "textBoxPassword";
textBoxPassword.Size = new Size(436, 27);
textBoxPassword.TabIndex = 5;
//
// textBoxWorkExperience
//
textBoxWorkExperience.Location = new Point(160, 133);
textBoxWorkExperience.Name = "textBoxWorkExperience";
textBoxWorkExperience.Size = new Size(126, 27);
textBoxWorkExperience.TabIndex = 6;
//
// textBoxQualification
//
textBoxQualification.Location = new Point(444, 133);
textBoxQualification.Name = "textBoxQualification";
textBoxQualification.Size = new Size(152, 27);
textBoxQualification.TabIndex = 7;
//
// buttonSave
//
buttonSave.Location = new Point(387, 178);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(94, 29);
buttonSave.TabIndex = 8;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(502, 178);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 9;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormImplementer
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(662, 224);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxQualification);
Controls.Add(textBoxWorkExperience);
Controls.Add(textBoxPassword);
Controls.Add(textBoxImplementerFIO);
Controls.Add(labelQualification);
Controls.Add(labelWorkExperience);
Controls.Add(labelPassword);
Controls.Add(labelFIO);
Name = "FormImplementer";
Text = "Исполнитель";
Load += FormImplementer_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelFIO;
private Label labelPassword;
private Label labelWorkExperience;
private Label labelQualification;
private TextBox textBoxImplementerFIO;
private TextBox textBoxPassword;
private TextBox textBoxWorkExperience;
private TextBox textBoxQualification;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,138 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using FurnitureAssemblyContracts.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 FurnitureAssemblyView
{
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)
{
// Проверка на заполнение поля id. Если оно заполнено, то пробуем получить запись и выести её на экран
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение исполнителя");
var view = _logic.ReadElement(new ImplementerSearchModel { Id = _id.Value });
if (view != null)
{
textBoxImplementerFIO.Text = view.ImplementerFIO;
textBoxPassword.Text = view.Password;
textBoxWorkExperience.Text = view.WorkExperience.ToString();
textBoxQualification.Text = view.Qualification.ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
// Проверка на заполнение поля с ФИО исполнителя
if (string.IsNullOrEmpty(textBoxImplementerFIO.Text))
{
MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Проверка на заполнение поля с паролем
if (string.IsNullOrEmpty(textBoxPassword.Text))
{
MessageBox.Show("Введите пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Проверка на заполнение поля со стажем
if (string.IsNullOrEmpty(textBoxWorkExperience.Text))
{
MessageBox.Show("Введите ваш стаж", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Проверка на заполнение поля с квалификацией
if (string.IsNullOrEmpty(textBoxQualification.Text))
{
MessageBox.Show("Введите свою квалификацию", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение исполнителя");
try
{
var model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = textBoxImplementerFIO.Text,
Password = textBoxPassword.Text,
WorkExperience = Convert.ToInt16(textBoxWorkExperience.Text),
Qualification = Convert.ToInt16(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,114 @@
namespace FurnitureAssemblyView
{
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()
{
dataGridView = new DataGridView();
buttonCreate = new Button();
buttonChange = new Button();
buttonDelete = new Button();
buttonUpdate = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 12);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(768, 426);
dataGridView.TabIndex = 0;
//
// buttonCreate
//
buttonCreate.Location = new Point(805, 22);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(160, 29);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click;
//
// buttonChange
//
buttonChange.Location = new Point(805, 90);
buttonChange.Name = "buttonChange";
buttonChange.Size = new Size(160, 29);
buttonChange.TabIndex = 2;
buttonChange.Text = "Изменить";
buttonChange.UseVisualStyleBackColor = true;
buttonChange.Click += ButtonChange_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(805, 153);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(160, 29);
buttonDelete.TabIndex = 3;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDelete_Click;
//
// buttonUpdate
//
buttonUpdate.Location = new Point(805, 218);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(160, 29);
buttonUpdate.TabIndex = 4;
buttonUpdate.Text = "Обновить";
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += ButtonUpdate_Click;
//
// FormImplementers
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(991, 450);
Controls.Add(buttonUpdate);
Controls.Add(buttonDelete);
Controls.Add(buttonChange);
Controls.Add(buttonCreate);
Controls.Add(dataGridView);
Name = "FormImplementers";
Text = "Исполнители";
Load += FormImplementers_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonCreate;
private Button buttonChange;
private Button buttonDelete;
private Button buttonUpdate;
}
}

View File

@ -0,0 +1,127 @@
using FurnitureAssemblyContracts.BindingModels;
using FurnitureAssemblyContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace FurnitureAssemblyView
{
public partial class FormImplementers : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
public FormImplementers(ILogger<FormWorkPieces> 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);
// Растягиваем колонку Название на всю ширину, колонку Id скрываем
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка исполнителей");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки исполнителей");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCreate_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 ButtonChange_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 ButtonDelete_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 ButtonUpdate_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

@ -28,203 +28,187 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.dataGridView = new System.Windows.Forms.DataGridView(); dataGridView = new DataGridView();
this.buttonCreateOrder = new System.Windows.Forms.Button(); buttonCreateOrder = new Button();
this.buttonTakeOrderInWork = new System.Windows.Forms.Button(); buttonIssuedOrder = new Button();
this.buttonOrderReady = new System.Windows.Forms.Button(); buttonRefresh = new Button();
this.buttonIssuedOrder = new System.Windows.Forms.Button(); menuStrip = new MenuStrip();
this.buttonRefresh = new System.Windows.Forms.Button(); toolStripMenuItem = new ToolStripMenuItem();
this.menuStrip = new System.Windows.Forms.MenuStrip(); workPieceToolStripMenuItem = new ToolStripMenuItem();
this.toolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); furnitureToolStripMenuItem = new ToolStripMenuItem();
this.workPieceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); reportsToolStripMenuItem = new ToolStripMenuItem();
this.furnitureToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); workPiecesToolStripMenuItem = new ToolStripMenuItem();
this.reportsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); workPieceFurnituresToolStripMenuItem = new ToolStripMenuItem();
this.workPiecesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); ordersToolStripMenuItem = new ToolStripMenuItem();
this.workPieceFurnituresToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); workWithClientsToolStripMenuItem = new ToolStripMenuItem();
this.ordersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); clientsToolStripMenuItem = new ToolStripMenuItem();
this.workWithClientsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); workWithImplementerToolStripMenuItem = new ToolStripMenuItem();
this.clientsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); implementerToolStripMenuItem = new ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); startingWorkToolStripMenuItem = new ToolStripMenuItem();
this.menuStrip.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
this.SuspendLayout(); menuStrip.SuspendLayout();
SuspendLayout();
// //
// dataGridView // dataGridView
// //
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(10, 27); dataGridView.Location = new Point(11, 36);
this.dataGridView.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); dataGridView.Name = "dataGridView";
this.dataGridView.Name = "dataGridView"; dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowHeadersWidth = 51; dataGridView.RowTemplate.Height = 29;
this.dataGridView.RowTemplate.Height = 29; dataGridView.Size = new Size(1010, 403);
this.dataGridView.Size = new System.Drawing.Size(820, 302); dataGridView.TabIndex = 0;
this.dataGridView.TabIndex = 0;
// //
// buttonCreateOrder // buttonCreateOrder
// //
this.buttonCreateOrder.Location = new System.Drawing.Point(887, 50); buttonCreateOrder.Location = new Point(1057, 67);
this.buttonCreateOrder.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); buttonCreateOrder.Name = "buttonCreateOrder";
this.buttonCreateOrder.Name = "buttonCreateOrder"; buttonCreateOrder.Size = new Size(235, 46);
this.buttonCreateOrder.Size = new System.Drawing.Size(206, 34); buttonCreateOrder.TabIndex = 1;
this.buttonCreateOrder.TabIndex = 1; buttonCreateOrder.Text = "Создать заказ";
this.buttonCreateOrder.Text = "Создать заказ"; buttonCreateOrder.UseVisualStyleBackColor = true;
this.buttonCreateOrder.UseVisualStyleBackColor = true; buttonCreateOrder.Click += ButtonCreateOrder_Click;
//
// buttonTakeOrderInWork
//
this.buttonTakeOrderInWork.Location = new System.Drawing.Point(887, 107);
this.buttonTakeOrderInWork.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
this.buttonTakeOrderInWork.Size = new System.Drawing.Size(206, 36);
this.buttonTakeOrderInWork.TabIndex = 2;
this.buttonTakeOrderInWork.Text = "Отдать на выполнение";
this.buttonTakeOrderInWork.UseVisualStyleBackColor = true;
this.buttonTakeOrderInWork.Click += new System.EventHandler(this.ButtonTakeOrderInWork_Click);
//
// buttonOrderReady
//
this.buttonOrderReady.Location = new System.Drawing.Point(887, 165);
this.buttonOrderReady.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.buttonOrderReady.Name = "buttonOrderReady";
this.buttonOrderReady.Size = new System.Drawing.Size(206, 31);
this.buttonOrderReady.TabIndex = 3;
this.buttonOrderReady.Text = "Заказ готов";
this.buttonOrderReady.UseVisualStyleBackColor = true;
this.buttonOrderReady.Click += new System.EventHandler(this.ButtonOrderReady_Click);
// //
// buttonIssuedOrder // buttonIssuedOrder
// //
this.buttonIssuedOrder.Location = new System.Drawing.Point(887, 217); buttonIssuedOrder.Location = new Point(1057, 133);
this.buttonIssuedOrder.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); buttonIssuedOrder.Name = "buttonIssuedOrder";
this.buttonIssuedOrder.Name = "buttonIssuedOrder"; buttonIssuedOrder.Size = new Size(235, 44);
this.buttonIssuedOrder.Size = new System.Drawing.Size(206, 33); buttonIssuedOrder.TabIndex = 4;
this.buttonIssuedOrder.TabIndex = 4; buttonIssuedOrder.Text = "Заказ выдан";
this.buttonIssuedOrder.Text = "Заказ выдан"; buttonIssuedOrder.UseVisualStyleBackColor = true;
this.buttonIssuedOrder.UseVisualStyleBackColor = true; buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
this.buttonIssuedOrder.Click += new System.EventHandler(this.ButtonIssuedOrder_Click);
// //
// buttonRefresh // buttonRefresh
// //
this.buttonRefresh.Location = new System.Drawing.Point(887, 269); buttonRefresh.Location = new Point(1057, 203);
this.buttonRefresh.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); buttonRefresh.Name = "buttonRefresh";
this.buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Size = new Size(235, 39);
this.buttonRefresh.Size = new System.Drawing.Size(206, 29); buttonRefresh.TabIndex = 5;
this.buttonRefresh.TabIndex = 5; buttonRefresh.Text = "Обновить";
this.buttonRefresh.Text = "Обновить"; buttonRefresh.UseVisualStyleBackColor = true;
this.buttonRefresh.UseVisualStyleBackColor = true; buttonRefresh.Click += ButtonRef_Click;
this.buttonRefresh.Click += new System.EventHandler(this.ButtonRef_Click);
// //
// menuStrip // menuStrip
// //
this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20); menuStrip.ImageScalingSize = new Size(20, 20);
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { menuStrip.Items.AddRange(new ToolStripItem[] { toolStripMenuItem, reportsToolStripMenuItem, workWithClientsToolStripMenuItem, workWithImplementerToolStripMenuItem, startingWorkToolStripMenuItem });
this.toolStripMenuItem, menuStrip.Location = new Point(0, 0);
this.reportsToolStripMenuItem, menuStrip.Name = "menuStrip";
this.workWithClientsToolStripMenuItem}); menuStrip.Padding = new Padding(6, 3, 0, 3);
this.menuStrip.Location = new System.Drawing.Point(0, 0); menuStrip.Size = new Size(1331, 30);
this.menuStrip.Name = "menuStrip"; menuStrip.TabIndex = 6;
this.menuStrip.Padding = new System.Windows.Forms.Padding(5, 2, 0, 2); menuStrip.Text = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(1135, 24);
this.menuStrip.TabIndex = 6;
this.menuStrip.Text = "menuStrip";
// //
// toolStripMenuItem // toolStripMenuItem
// //
this.toolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { toolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { workPieceToolStripMenuItem, furnitureToolStripMenuItem });
this.workPieceToolStripMenuItem, toolStripMenuItem.Name = "toolStripMenuItem";
this.furnitureToolStripMenuItem}); toolStripMenuItem.Size = new Size(117, 24);
this.toolStripMenuItem.Name = "toolStripMenuItem"; toolStripMenuItem.Text = "Справочники";
this.toolStripMenuItem.Size = new System.Drawing.Size(94, 20);
this.toolStripMenuItem.Text = "Справочники";
// //
// workPieceToolStripMenuItem // workPieceToolStripMenuItem
// //
this.workPieceToolStripMenuItem.Name = "workPieceToolStripMenuItem"; workPieceToolStripMenuItem.Name = "workPieceToolStripMenuItem";
this.workPieceToolStripMenuItem.Size = new System.Drawing.Size(180, 22); workPieceToolStripMenuItem.Size = new Size(162, 26);
this.workPieceToolStripMenuItem.Text = "Заготовки"; workPieceToolStripMenuItem.Text = "Заготовки";
workPieceToolStripMenuItem.Click += WorkPieceToolStripMenuItem_Click;
// //
// furnitureToolStripMenuItem // furnitureToolStripMenuItem
// //
this.furnitureToolStripMenuItem.Name = "furnitureToolStripMenuItem"; furnitureToolStripMenuItem.Name = "furnitureToolStripMenuItem";
this.furnitureToolStripMenuItem.Size = new System.Drawing.Size(180, 22); furnitureToolStripMenuItem.Size = new Size(162, 26);
this.furnitureToolStripMenuItem.Text = "Изделия"; furnitureToolStripMenuItem.Text = "Изделия";
furnitureToolStripMenuItem.Click += FurnitureToolStripMenuItem_Click;
// //
// reportsToolStripMenuItem // reportsToolStripMenuItem
// //
this.reportsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { reportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { workPiecesToolStripMenuItem, workPieceFurnituresToolStripMenuItem, ordersToolStripMenuItem });
this.workPiecesToolStripMenuItem, reportsToolStripMenuItem.Name = "reportsToolStripMenuItem";
this.workPieceFurnituresToolStripMenuItem, reportsToolStripMenuItem.Size = new Size(73, 24);
this.ordersToolStripMenuItem}); reportsToolStripMenuItem.Text = "Отчёты";
this.reportsToolStripMenuItem.Name = "reportsToolStripMenuItem";
this.reportsToolStripMenuItem.Size = new System.Drawing.Size(60, 20);
this.reportsToolStripMenuItem.Text = "Отчёты";
// //
// workPiecesToolStripMenuItem // workPiecesToolStripMenuItem
// //
this.workPiecesToolStripMenuItem.Name = "workPiecesToolStripMenuItem"; workPiecesToolStripMenuItem.Name = "workPiecesToolStripMenuItem";
this.workPiecesToolStripMenuItem.Size = new System.Drawing.Size(203, 22); workPiecesToolStripMenuItem.Size = new Size(256, 26);
this.workPiecesToolStripMenuItem.Text = "Список заготовок"; workPiecesToolStripMenuItem.Text = "Список заготовок";
this.workPiecesToolStripMenuItem.Click += new System.EventHandler(this.WorkPiecesToolStripMenuItem_Click); workPiecesToolStripMenuItem.Click += WorkPiecesToolStripMenuItem_Click;
// //
// workPieceFurnituresToolStripMenuItem // workPieceFurnituresToolStripMenuItem
// //
this.workPieceFurnituresToolStripMenuItem.Name = "workPieceFurnituresToolStripMenuItem"; workPieceFurnituresToolStripMenuItem.Name = "workPieceFurnituresToolStripMenuItem";
this.workPieceFurnituresToolStripMenuItem.Size = new System.Drawing.Size(203, 22); workPieceFurnituresToolStripMenuItem.Size = new Size(256, 26);
this.workPieceFurnituresToolStripMenuItem.Text = "Заготовки по изделиям"; workPieceFurnituresToolStripMenuItem.Text = "Заготовки по изделиям";
this.workPieceFurnituresToolStripMenuItem.Click += new System.EventHandler(this.WorkPieceFurnituresToolStripMenuItem_Click); workPieceFurnituresToolStripMenuItem.Click += WorkPieceFurnituresToolStripMenuItem_Click;
// //
// ordersToolStripMenuItem // ordersToolStripMenuItem
// //
this.ordersToolStripMenuItem.Name = "ordersToolStripMenuItem"; ordersToolStripMenuItem.Name = "ordersToolStripMenuItem";
this.ordersToolStripMenuItem.Size = new System.Drawing.Size(203, 22); ordersToolStripMenuItem.Size = new Size(256, 26);
this.ordersToolStripMenuItem.Text = "Список заказов"; ordersToolStripMenuItem.Text = "Список заказов";
this.ordersToolStripMenuItem.Click += new System.EventHandler(this.OrdersToolStripMenuItem_Click); ordersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click;
// //
// workWithClientsToolStripMenuItem // workWithClientsToolStripMenuItem
// //
this.workWithClientsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { workWithClientsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { clientsToolStripMenuItem });
this.clientsToolStripMenuItem}); workWithClientsToolStripMenuItem.Name = "workWithClientsToolStripMenuItem";
this.workWithClientsToolStripMenuItem.Name = "workWithClientsToolStripMenuItem"; workWithClientsToolStripMenuItem.Size = new Size(161, 24);
this.workWithClientsToolStripMenuItem.Size = new System.Drawing.Size(129, 20); workWithClientsToolStripMenuItem.Text = "Работа с клиентами";
this.workWithClientsToolStripMenuItem.Text = "Работа с клиентами";
// //
// clientsToolStripMenuItem // clientsToolStripMenuItem
// //
this.clientsToolStripMenuItem.Name = "clientsToolStripMenuItem"; clientsToolStripMenuItem.Name = "clientsToolStripMenuItem";
this.clientsToolStripMenuItem.Size = new System.Drawing.Size(180, 22); clientsToolStripMenuItem.Size = new Size(152, 26);
this.clientsToolStripMenuItem.Text = "Клиенты"; clientsToolStripMenuItem.Text = "Клиенты";
this.clientsToolStripMenuItem.Click += new System.EventHandler(this.ClientsToolStripMenuItem_Click); clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click;
//
// workWithImplementerToolStripMenuItem
//
workWithImplementerToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { implementerToolStripMenuItem });
workWithImplementerToolStripMenuItem.Name = "workWithImplementerToolStripMenuItem";
workWithImplementerToolStripMenuItem.Size = new Size(196, 24);
workWithImplementerToolStripMenuItem.Text = "Работа с исполнителями";
//
// implementerToolStripMenuItem
//
implementerToolStripMenuItem.Name = "implementerToolStripMenuItem";
implementerToolStripMenuItem.Size = new Size(185, 26);
implementerToolStripMenuItem.Text = "Исполнители";
implementerToolStripMenuItem.Click += ImplementerToolStripMenuItem_Click;
//
// startingWorkToolStripMenuItem
//
startingWorkToolStripMenuItem.Name = "startingWorkToolStripMenuItem";
startingWorkToolStripMenuItem.Size = new Size(114, 24);
startingWorkToolStripMenuItem.Text = "Запуск работ";
startingWorkToolStripMenuItem.Click += StartingWorkToolStripMenuItem_Click;
// //
// FormMain // FormMain
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); AutoScaleDimensions = new SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1135, 338); ClientSize = new Size(1331, 474);
this.Controls.Add(this.buttonRefresh); Controls.Add(buttonRefresh);
this.Controls.Add(this.buttonIssuedOrder); Controls.Add(buttonIssuedOrder);
this.Controls.Add(this.buttonOrderReady); Controls.Add(buttonCreateOrder);
this.Controls.Add(this.buttonTakeOrderInWork); Controls.Add(dataGridView);
this.Controls.Add(this.buttonCreateOrder); Controls.Add(menuStrip);
this.Controls.Add(this.dataGridView); MainMenuStrip = menuStrip;
this.Controls.Add(this.menuStrip); Name = "FormMain";
this.MainMenuStrip = this.menuStrip; Text = "Сборка мебели";
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2); Load += FormMain_Load;
this.Name = "FormMain"; ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
this.Text = "Сборка мебели"; menuStrip.ResumeLayout(false);
this.Load += new System.EventHandler(this.FormMain_Load); menuStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); ResumeLayout(false);
this.menuStrip.ResumeLayout(false); PerformLayout();
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
} }
#endregion #endregion
private DataGridView dataGridView; private DataGridView dataGridView;
private Button buttonCreateOrder; private Button buttonCreateOrder;
private Button buttonTakeOrderInWork;
private Button buttonOrderReady;
private Button buttonIssuedOrder; private Button buttonIssuedOrder;
private Button buttonRefresh; private Button buttonRefresh;
private MenuStrip menuStrip; private MenuStrip menuStrip;
@ -237,5 +221,8 @@
private ToolStripMenuItem ordersToolStripMenuItem; private ToolStripMenuItem ordersToolStripMenuItem;
private ToolStripMenuItem workWithClientsToolStripMenuItem; private ToolStripMenuItem workWithClientsToolStripMenuItem;
private ToolStripMenuItem clientsToolStripMenuItem; private ToolStripMenuItem clientsToolStripMenuItem;
private ToolStripMenuItem workWithImplementerToolStripMenuItem;
private ToolStripMenuItem implementerToolStripMenuItem;
private ToolStripMenuItem startingWorkToolStripMenuItem;
} }
} }

View File

@ -22,13 +22,16 @@ namespace FurnitureAssemblyView
private readonly IReportLogic _reportLogic; private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic) private readonly IWorkProcess _workProcess;
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)
@ -49,8 +52,10 @@ namespace FurnitureAssemblyView
dataGridView.DataSource = list; dataGridView.DataSource = list;
dataGridView.Columns["FurnitureId"].Visible = false; dataGridView.Columns["FurnitureId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false; dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
dataGridView.Columns["FurnitureName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView.Columns["FurnitureName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
} }
_logger.LogInformation("Загрузка заказов"); _logger.LogInformation("Загрузка заказов");
@ -94,64 +99,6 @@ namespace FurnitureAssemblyView
} }
private void ButtonTakeOrderInWork_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = id
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonOrderReady_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);
try
{
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel
{
Id = id
});
if (!operationResult)
{
throw new Exception("Заказ не отправлен в сборку. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonIssuedOrder_Click(object sender, EventArgs e) private void ButtonIssuedOrder_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
@ -232,5 +179,22 @@ namespace FurnitureAssemblyView
form.ShowDialog(); form.ShowDialog();
} }
} }
private void StartingWorkToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void ImplementerToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (service is FormImplementers form)
{
form.ShowDialog();
}
}
} }
} }

View File

@ -1,4 +1,64 @@
<root> <?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd: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:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true"> <xsd:element name="root" msdata:IsDataSet="true">

View File

@ -44,12 +44,15 @@ namespace FurnitureAssemblyView
services.AddTransient<IOrderStorage, OrderStorage>(); services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IFurnitureStorage, FurnitureStorage>(); services.AddTransient<IFurnitureStorage, FurnitureStorage>();
services.AddTransient<IClientStorage, ClientStorage>(); services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IWorkPieceLogic, WorkPieceLogic>(); services.AddTransient<IWorkPieceLogic, WorkPieceLogic>();
services.AddTransient<IOrderLogic, OrderLogic>(); services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IFurnitureLogic, FurnitureLogic>(); services.AddTransient<IFurnitureLogic, FurnitureLogic>();
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<AbstractSaveToExcel, SaveToExcel>(); services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>(); services.AddTransient<AbstractSaveToWord, SaveToWord>();
@ -65,6 +68,8 @@ namespace FurnitureAssemblyView
services.AddTransient<FormReportFurnitureWorkPieces>(); services.AddTransient<FormReportFurnitureWorkPieces>();
services.AddTransient<FormReportOrders>(); services.AddTransient<FormReportOrders>();
services.AddTransient<FormClients>(); services.AddTransient<FormClients>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormImplementer>();
} }
} }
} }

View File

@ -424,6 +424,7 @@
<PaddingBottom>2pt</PaddingBottom> <PaddingBottom>2pt</PaddingBottom>
</Style> </Style>
</Textbox> </Textbox>
<rd:Selected>true</rd:Selected>
</CellContents> </CellContents>
</TablixCell> </TablixCell>
<TablixCell> <TablixCell>
@ -483,7 +484,7 @@
<Top>2.48391cm</Top> <Top>2.48391cm</Top>
<Left>0.55245cm</Left> <Left>0.55245cm</Left>
<Height>1.2cm</Height> <Height>1.2cm</Height>
<Width>19.84714cm</Width> <Width>19.84713cm</Width>
<ZIndex>2</ZIndex> <ZIndex>2</ZIndex>
<Style> <Style>
<Border> <Border>