Compare commits

...

2 Commits

Author SHA1 Message Date
3632ee363b fix 2023-05-15 10:38:34 +04:00
c81e6b226e Implementers 2023-05-14 14:10:25 +04:00
41 changed files with 2334 additions and 518 deletions

View File

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

View File

@ -44,23 +44,38 @@ namespace GiftShopBusinessLogic.BusinessLogics
public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus) public bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus)
{ {
CheckModel(model); var vmodel = _orderStorage.GetElement(new() { Id = model.Id });
if (model.Status + 1 != newStatus) if (vmodel == null)
{ {
_logger.LogWarning("Status update to " + newStatus.ToString() + " operation failed. Order status incorrect."); throw new ArgumentNullException(nameof(model));
return false; }
if ((int)vmodel.Status + 1 != (int)newStatus)
{
throw new InvalidOperationException($"Попытка перевести заказ не в следующий статус: " +
$"Текущий статус: {vmodel.Status} \n" +
$"Планируемый статус: {newStatus} \n" +
$"Доступный статус: {(OrderStatus)((int)vmodel.Status + 1)}");
} }
model.Status = newStatus; model.Status = newStatus;
model.DateCreate = vmodel.DateCreate;
if (model.Status == OrderStatus.Выдан) if (model.DateImplement == null)
model.DateImplement = DateTime.Now; model.DateImplement = vmodel.DateImplement;
if (vmodel.ImplementerId.HasValue)
model.ImplementerId = vmodel.ImplementerId;
model.GiftId = vmodel.GiftId;
model.Sum = vmodel.Sum;
model.Count = vmodel.Count;
if (_orderStorage.Update(model) == null) if (_orderStorage.Update(model) == null)
{ {
model.Status--;
_logger.LogWarning("Update operation failed"); _logger.LogWarning("Update operation failed");
return false; return false;
} }
@ -73,8 +88,9 @@ namespace GiftShopBusinessLogic.BusinessLogics
} }
public bool DeliveryOrder(OrderBindingModel model) public bool DeliveryOrder(OrderBindingModel model)
{ {
return StatusUpdate(model, OrderStatus.Готов); model.DateImplement = DateTime.Now;
return StatusUpdate(model, OrderStatus.Готов);
} }
public bool FinishOrder(OrderBindingModel model) public bool FinishOrder(OrderBindingModel model)
@ -127,5 +143,28 @@ namespace GiftShopBusinessLogic.BusinessLogics
_logger.LogInformation("Order. OrderId:{Id}.Sum:{ Sum}. EngineId: { EngineId}", model.Id, model.Sum, model.GiftId); _logger.LogInformation("Order. OrderId:{Id}.Sum:{ Sum}. EngineId: { EngineId}", model.Id, model.Sum, model.GiftId);
} }
}
public OrderViewModel? ReadElement(OrderSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Id:{ Id}", model.Id);
var element = _orderStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
}
} }

View File

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

View File

@ -0,0 +1,17 @@
using GiftShopDataModels.Models;
namespace GiftShopContracts.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

@ -22,5 +22,7 @@ namespace GiftShopContracts.BindingModels
public DateTime DateCreate { get; set; } = DateTime.Now; public DateTime DateCreate { get; set; } = DateTime.Now;
public DateTime? DateImplement { get; set; } public DateTime? DateImplement { get; set; }
}
public int? ImplementerId { get; set; }
}
} }

View File

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

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,21 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.ViewModels;
namespace GiftShopContracts.StoragesContracts
{
public interface IImplementerStorage
{
List<ImplementerViewModel> GetFullList();
List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model);
ImplementerViewModel? GetElement(ImplementerSearchModel model);
ImplementerViewModel? Insert(ImplementerBindingModel model);
ImplementerViewModel? Update(ImplementerBindingModel model);
ImplementerViewModel? Delete(ImplementerBindingModel model);
}
}

View File

@ -0,0 +1,22 @@
using GiftShopDataModels.Models;
using System.ComponentModel;
namespace GiftShopContracts.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

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

View File

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

View File

@ -23,5 +23,7 @@ namespace GiftShopDatabaseImplement
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,117 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopDatabaseImplement.Models;
namespace GiftShopDatabaseImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
using var context = new GiftShopDatabase();
var res = context.Implementers
.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
context.Implementers.Remove(res);
context.SaveChanges();
}
return res?.GetViewModel;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
using var context = new GiftShopDatabase();
if (model.Id.HasValue)
return context.Implementers
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
if (model.ImplementerFIO != null && model.Password != null)
return context.Implementers
.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO)
&& x.Password.Equals(model.Password))
?.GetViewModel;
if (model.ImplementerFIO != null)
return context.Implementers
.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))
?.GetViewModel;
return null;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (model == null)
{
return new();
}
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
if (model.ImplementerFIO != null)
{
using var context = new GiftShopDatabase();
return context.Implementers
.Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
public List<ImplementerViewModel> GetFullList()
{
using var context = new GiftShopDatabase();
return context.Implementers
.Select(x => x.GetViewModel)
.ToList();
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
using var context = new GiftShopDatabase();
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 GiftShopDatabase();
var res = context.Implementers
.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
res.Update(model);
context.SaveChanges();
}
return res?.GetViewModel;
}
}
}

View File

@ -29,46 +29,61 @@ namespace GiftShopDatabaseImplement.Implements
return null; return null;
} }
using var context = new GiftShopDatabase(); using var context = new GiftShopDatabase();
return context.Orders.Include(x => x.Gift) if (model.ImplementerId.HasValue)
.Include(x => x.Client).FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; {
return context.Orders
.FirstOrDefault(x => x.ImplementerId == model.ImplementerId && x.Status.Equals(model.Status))
?.GetViewModel;
}
return context.Orders
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
} }
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{ {
if (!model.DateFrom.HasValue && !model.DateTo.HasValue && !model.ClientId.HasValue) if (model is null)
{ {
return new(); return new();
} }
using var context = new GiftShopDatabase(); using var context = new GiftShopDatabase();
if (model.DateFrom.HasValue) if (model.DateTo != null && model.DateFrom != null && model.ClientId.HasValue)
{ {
return context.Orders return context.Orders
.Include(x => x.Gift) .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo && x.ClientId == model.ClientId)
.Include(x => x.Client) .ToList()
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.ClientId.HasValue)
return context.Orders
.Include(x => x.Gift)
.Include(x => x.Client)
.Where(x => x.ClientId == model.ClientId)
.Select(x => x.GetViewModel) .Select(x => x.GetViewModel)
.ToList(); .ToList();
}
else if (model.DateTo != null && model.DateFrom != null)
{
return context.Orders
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.ClientId.HasValue)
{
return context.Orders
.Where(x => x.ClientId == model.ClientId)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
return context.Orders return context.Orders
.Include(x => x.Gift) .Where(x => x.Status == model.Status)
.Include(x => x.Client) .ToList()
.Where(x => x.Id == model.Id) .Select(x => x.GetViewModel)
.Select(x => x.GetViewModel) .ToList();
.ToList();
} }
public List<OrderViewModel> GetFullList() public List<OrderViewModel> GetFullList()
{ {
using var context = new GiftShopDatabase(); using var context = new GiftShopDatabase();
return context.Orders.Include(x => x.Gift) return context.Orders.Include(x => x.Gift)
.Include(x => x.Client).Select(x => x.GetViewModel).ToList(); .Include(x => x.Client).Include(x => x.Implementer).Select(x => x.GetViewModel).ToList();
} }
public OrderViewModel? Insert(OrderBindingModel model) public OrderViewModel? Insert(OrderBindingModel model)
@ -85,6 +100,7 @@ namespace GiftShopDatabaseImplement.Implements
return context.Orders return context.Orders
.Include(x => x.Gift) .Include(x => x.Gift)
.Include(x => x.Client) .Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => x.Id == newOrder.Id) .FirstOrDefault(x => x.Id == newOrder.Id)
?.GetViewModel; ?.GetViewModel;
} }
@ -93,7 +109,7 @@ namespace GiftShopDatabaseImplement.Implements
{ {
using var context = new GiftShopDatabase(); using var context = new GiftShopDatabase();
var order = context.Orders.Include(x => x.Gift) var order = context.Orders.Include(x => x.Gift)
.Include(x => x.Client).FirstOrDefault(x => x.Id == model.Id); .Include(x => x.Client).Include(x => x.Implementer).FirstOrDefault(x => x.Id == model.Id);
if (order == null) if (order == null)
{ {
return null; return null;

View File

@ -12,7 +12,7 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace GiftShopDatabaseImplement.Migrations namespace GiftShopDatabaseImplement.Migrations
{ {
[DbContext(typeof(GiftShopDatabase))] [DbContext(typeof(GiftShopDatabase))]
[Migration("20230428071341_SecMigration")] [Migration("20230515060908_SecMigration")]
partial class SecMigration partial class SecMigration
{ {
/// <inheritdoc /> /// <inheritdoc />
@ -116,6 +116,33 @@ namespace GiftShopDatabaseImplement.Migrations
b.ToTable("GiftComponents"); b.ToTable("GiftComponents");
}); });
modelBuilder.Entity("GiftShopDatabaseImplement.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("GiftShopDatabaseImplement.Models.Order", b => modelBuilder.Entity("GiftShopDatabaseImplement.Models.Order", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@ -143,6 +170,9 @@ namespace GiftShopDatabaseImplement.Migrations
.IsRequired() .IsRequired()
.HasColumnType("nvarchar(max)"); .HasColumnType("nvarchar(max)");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status") b.Property<int>("Status")
.HasColumnType("int"); .HasColumnType("int");
@ -155,6 +185,8 @@ namespace GiftShopDatabaseImplement.Migrations
b.HasIndex("GiftId"); b.HasIndex("GiftId");
b.HasIndex("ImplementerId");
b.ToTable("Orders"); b.ToTable("Orders");
}); });
@ -191,9 +223,15 @@ namespace GiftShopDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.HasOne("GiftShopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("Client"); b.Navigation("Client");
b.Navigation("Gift"); b.Navigation("Gift");
b.Navigation("Implementer");
}); });
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Client", b => modelBuilder.Entity("GiftShopDatabaseImplement.Models.Client", b =>
@ -212,6 +250,11 @@ namespace GiftShopDatabaseImplement.Migrations
b.Navigation("Orders"); b.Navigation("Orders");
}); });
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
} }

View File

@ -54,6 +54,22 @@ namespace GiftShopDatabaseImplement.Migrations
table.PrimaryKey("PK_Gifts", x => x.Id); table.PrimaryKey("PK_Gifts", x => x.Id);
}); });
migrationBuilder.CreateTable(
name: "Implementers",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ImplementerFIO = table.Column<string>(type: "nvarchar(max)", nullable: false),
Password = table.Column<string>(type: "nvarchar(max)", nullable: false),
WorkExperience = table.Column<int>(type: "int", nullable: false),
Qualification = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Implementers", x => x.Id);
});
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "GiftComponents", name: "GiftComponents",
columns: table => new columns: table => new
@ -89,6 +105,7 @@ namespace GiftShopDatabaseImplement.Migrations
.Annotation("SqlServer:Identity", "1, 1"), .Annotation("SqlServer:Identity", "1, 1"),
GiftId = table.Column<int>(type: "int", nullable: false), GiftId = table.Column<int>(type: "int", nullable: false),
ClientId = table.Column<int>(type: "int", nullable: false), ClientId = table.Column<int>(type: "int", nullable: false),
ImplementerId = table.Column<int>(type: "int", nullable: true),
GiftName = table.Column<string>(type: "nvarchar(max)", nullable: false), GiftName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Count = table.Column<int>(type: "int", nullable: false), Count = table.Column<int>(type: "int", nullable: false),
Sum = table.Column<double>(type: "float", nullable: false), Sum = table.Column<double>(type: "float", nullable: false),
@ -111,6 +128,11 @@ namespace GiftShopDatabaseImplement.Migrations
principalTable: "Gifts", principalTable: "Gifts",
principalColumn: "Id", principalColumn: "Id",
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
column: x => x.ImplementerId,
principalTable: "Implementers",
principalColumn: "Id");
}); });
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
@ -132,6 +154,11 @@ namespace GiftShopDatabaseImplement.Migrations
name: "IX_Orders_GiftId", name: "IX_Orders_GiftId",
table: "Orders", table: "Orders",
column: "GiftId"); column: "GiftId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
} }
/// <inheritdoc /> /// <inheritdoc />
@ -151,6 +178,9 @@ namespace GiftShopDatabaseImplement.Migrations
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "Gifts"); name: "Gifts");
migrationBuilder.DropTable(
name: "Implementers");
} }
} }
} }

View File

@ -113,6 +113,33 @@ namespace GiftShopDatabaseImplement.Migrations
b.ToTable("GiftComponents"); b.ToTable("GiftComponents");
}); });
modelBuilder.Entity("GiftShopDatabaseImplement.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("GiftShopDatabaseImplement.Models.Order", b => modelBuilder.Entity("GiftShopDatabaseImplement.Models.Order", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@ -140,6 +167,9 @@ namespace GiftShopDatabaseImplement.Migrations
.IsRequired() .IsRequired()
.HasColumnType("nvarchar(max)"); .HasColumnType("nvarchar(max)");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status") b.Property<int>("Status")
.HasColumnType("int"); .HasColumnType("int");
@ -152,6 +182,8 @@ namespace GiftShopDatabaseImplement.Migrations
b.HasIndex("GiftId"); b.HasIndex("GiftId");
b.HasIndex("ImplementerId");
b.ToTable("Orders"); b.ToTable("Orders");
}); });
@ -188,9 +220,15 @@ namespace GiftShopDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.HasOne("GiftShopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("Client"); b.Navigation("Client");
b.Navigation("Gift"); b.Navigation("Gift");
b.Navigation("Implementer");
}); });
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Client", b => modelBuilder.Entity("GiftShopDatabaseImplement.Models.Client", b =>
@ -209,6 +247,11 @@ namespace GiftShopDatabaseImplement.Migrations
b.Navigation("Orders"); b.Navigation("Orders");
}); });
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
} }

View File

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

View File

@ -15,6 +15,8 @@ namespace GiftShopDatabaseImplement.Models
[Required] [Required]
public int ClientId { get; set; } public int ClientId { get; set; }
public int? ImplementerId { get; private set; }
public string GiftName { get; private set; } = string.Empty; public string GiftName { get; private set; } = string.Empty;
[Required] [Required]
@ -35,6 +37,8 @@ namespace GiftShopDatabaseImplement.Models
public Client Client { get; set; } public Client Client { get; set; }
public Implementer? Implementer { get; set; }
public static Order? Create(OrderBindingModel? model) public static Order? Create(OrderBindingModel? model)
{ {
if (model == null) if (model == null)
@ -47,6 +51,7 @@ namespace GiftShopDatabaseImplement.Models
Id = model.Id, Id = model.Id,
GiftId = model.GiftId, GiftId = model.GiftId,
ClientId = model.ClientId, ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
GiftName = model.GiftName, GiftName = model.GiftName,
Count = model.Count, Count = model.Count,
Sum = model.Sum, Sum = model.Sum,
@ -61,16 +66,11 @@ namespace GiftShopDatabaseImplement.Models
if (model == null) if (model == null)
{ {
return; return;
} }
Status = model.Status;
GiftId = model.GiftId; DateImplement = model.DateImplement;
GiftName = model.GiftName; ImplementerId = model.ImplementerId;
Count = model.Count; }
Sum = model.Sum;
Status = model.Status;
DateCreate = model.DateCreate;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel public OrderViewModel GetViewModel
{ {
@ -82,13 +82,15 @@ namespace GiftShopDatabaseImplement.Models
Id = Id, Id = Id,
GiftId = GiftId, GiftId = GiftId,
ClientId = ClientId, ClientId = ClientId,
ImplementerId = ImplementerId,
ClientFIO = context.Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty, ClientFIO = context.Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty,
GiftName = context.Gifts.FirstOrDefault(x => x.Id == GiftId)?.GiftName ?? string.Empty, GiftName = context.Gifts.FirstOrDefault(x => x.Id == GiftId)?.GiftName ?? string.Empty,
Count = Count, Count = Count,
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,
DateCreate = DateCreate, DateCreate = DateCreate,
DateImplement = DateImplement DateImplement = DateImplement,
ImplementerFIO = Implementer?.ImplementerFIO ?? string.Empty
}; };
} }
} }

View File

@ -15,6 +15,8 @@ namespace GiftShopFileImplement
private readonly string ClientFileName = "Client.xml"; private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
public List<Component> Components { get; private set; } public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; } public List<Order> Orders { get; private set; }
@ -23,6 +25,8 @@ namespace GiftShopFileImplement
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)
@ -40,12 +44,15 @@ namespace GiftShopFileImplement
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, OrderFileName, "Implementers", x => x.GetXElement);
private DataFileSingleton() private DataFileSingleton()
{ {
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!; Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Gifts = LoadData(GiftFileName, "Gift", x => Gift.Create(x)!)!; Gifts = LoadData(GiftFileName, "Gift", x => Gift.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!; Orders = LoadData(OrderFileName, "Order", x => Order.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,103 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.SearchModels;
using GiftShopContracts.StoragesContracts;
using GiftShopContracts.ViewModels;
using GiftShopFileImplement.Models;
namespace GiftShopFileImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataFileSingleton _source;
public ImplementerStorage()
{
_source = DataFileSingleton.GetInstance();
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
_source.Implementers.Remove(res);
_source.SaveImplementers();
}
return res?.GetViewModel;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (model.Id.HasValue)
return _source.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
if (model.ImplementerFIO != null && model.Password != null)
return _source.Implementers
.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO)
&& x.Password.Equals(model.Password))
?.GetViewModel;
if (model.ImplementerFIO != null)
return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel;
return null;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (model == null)
{
return new();
}
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
if (model.ImplementerFIO != null)
{
return _source.Implementers
.Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
public List<ImplementerViewModel> GetFullList()
{
return _source.Implementers.Select(x => x.GetViewModel).ToList();
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = _source.Implementers.Count > 0 ? _source.Implementers.Max(x => x.Id) + 1 : 1;
var res = Implementer.Create(model);
if (res != null)
{
_source.Implementers.Add(res);
_source.SaveImplementers();
}
return res?.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
res.Update(model);
_source.SaveImplementers();
}
return res?.GetViewModel;
}
}
}

View File

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

View File

@ -10,7 +10,13 @@ namespace GiftShopFileImplement.Models
{ {
public int GiftId { get; private set; } public int GiftId { get; private set; }
public int Count { get; private set; } public int? ImplementerId { get; set; }
public int ClientId { get; private set; }
public string GiftName { get; private set; } = string.Empty;
public int Count { get; private set; }
public double Sum { get; private set; } public double Sum { get; private set; }
@ -32,8 +38,11 @@ namespace GiftShopFileImplement.Models
{ {
Id = model.Id, Id = model.Id,
GiftId = model.GiftId, GiftId = model.GiftId,
Count = model.Count, GiftName = model.GiftName,
Sum = model.Sum, Count = model.Count,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
Sum = model.Sum,
Status = model.Status, Status = model.Status,
DateCreate = model.DateCreate, DateCreate = model.DateCreate,
DateImplement = model.DateImplement DateImplement = model.DateImplement
@ -47,14 +56,17 @@ namespace GiftShopFileImplement.Models
return null; return null;
} }
var order = new Order() var order = new Order()
{ {
Id = Convert.ToInt32(element.Attribute("Id")!.Value), Id = Convert.ToInt32(element.Attribute("Id")!.Value),
GiftId = Convert.ToInt32(element.Element("GiftId")!.Value), GiftId = Convert.ToInt32(element.Element("GiftId")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value), GiftName = element.Element("GiftName")!.Value,
Sum = Convert.ToDouble(element.Element("Sum")!.Value), Count = Convert.ToInt32(element.Element("Count")!.Value),
Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value), Sum = Convert.ToDouble(element.Element("Sum")!.Value),
DateCreate = DateTime.ParseExact(element.Element("DateCreate")!.Value, "G", null) ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value),
}; ClientId = Convert.ToInt32(element.Element("ClientId")!.Value),
Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value),
DateCreate = DateTime.ParseExact(element.Element("DateCreate")!.Value, "G", null)
};
DateTime.TryParse(element.Element("DateImplement")!.Value, out DateTime dateImpl); DateTime.TryParse(element.Element("DateImplement")!.Value, out DateTime dateImpl);
order.DateImplement = dateImpl; order.DateImplement = dateImpl;
@ -67,33 +79,35 @@ namespace GiftShopFileImplement.Models
if (model == null) if (model == null)
{ {
return; return;
} }
GiftId = model.GiftId; Status = model.Status;
Count = model.Count; DateImplement = model.DateImplement;
Sum = model.Sum; }
Status = model.Status;
DateCreate = model.DateCreate;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new() public OrderViewModel GetViewModel => new()
{ {
Id = Id, Id = Id,
GiftId = GiftId, GiftId = GiftId,
Count = Count, ClientId = ClientId,
Sum = Sum, ImplementerId = ImplementerId,
Status = Status, GiftName = GiftName,
DateCreate = DateCreate, Count = Count,
DateImplement = DateImplement Sum = Sum,
}; Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement
};
public XElement GetXElement => new("Order", public XElement GetXElement => new("Order",
new XAttribute("Id", Id), new XAttribute("Id", Id),
new XElement("GiftId", GiftId.ToString()), new XElement("GiftName", GiftName),
new XElement("Count", Count.ToString()), new XElement("GiftId", GiftId.ToString()),
new XElement("Sum", Sum.ToString()), new XElement("ClientId", ClientId.ToString()),
new XElement("Status", Status.ToString()), new XElement("ImplementerId", ImplementerId.ToString()),
new XElement("DateCreate", DateCreate.ToString()), new XElement("Count", Count.ToString()),
new XElement("DateImplement", DateImplement.ToString())); new XElement("Sum", Sum.ToString()),
} new XElement("Status", Status.ToString()),
new XElement("DateCreate", DateCreate.ToString()),
new XElement("DateImplement", DateImplement.ToString()));
}
} }

View File

@ -9,13 +9,16 @@ namespace GiftShopListImplement
public List<Order> Orders { get; set; } public List<Order> Orders { get; set; }
public List<Gift> Gifts { get; set; } public List<Gift> Gifts { get; set; }
public List<Client> Clients { get; set; } public List<Client> Clients { get; set; }
public List<Implementer> Implementers { get; set; }
private DataListSingleton() private DataListSingleton()
{ {
Components = new List<Component>(); Components = new List<Component>();
Orders = new List<Order>(); Orders = new List<Order>();
Gifts = new List<Gift>(); Gifts = new List<Gift>();
} Clients = new List<Client>();
Implementers = new List<Implementer>();
}
public static DataListSingleton GetInstance() public static DataListSingleton GetInstance()
{ {
if (_instance == null) if (_instance == null)

View File

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

View File

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

View File

@ -9,9 +9,13 @@ namespace GiftShopListImplement.Models
{ {
public int GiftId { get; private set; } public int GiftId { get; private set; }
public string GiftName { get; private set; } public int? ImplementerId { get; private set; }
public int Count { get; private set; } public string GiftName { get; private set; }
public int ClientId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; } public double Sum { get; private set; }
@ -38,8 +42,10 @@ namespace GiftShopListImplement.Models
Sum = model.Sum, Sum = model.Sum,
Status = model.Status, Status = model.Status,
DateCreate = model.DateCreate, DateCreate = model.DateCreate,
DateImplement = model.DateImplement DateImplement = model.DateImplement,
}; ImplementerId = model.ImplementerId,
ClientId = model.ClientId,
};
} }
public void Update(OrderBindingModel? model) public void Update(OrderBindingModel? model)
@ -49,7 +55,6 @@ namespace GiftShopListImplement.Models
return; return;
} }
Status = model.Status; Status = model.Status;
DateImplement = model.DateImplement;
} }
public OrderViewModel GetViewModel => new() public OrderViewModel GetViewModel => new()
@ -61,7 +66,9 @@ namespace GiftShopListImplement.Models
Sum = Sum, Sum = Sum,
Status = Status, Status = Status,
DateCreate = DateCreate, DateCreate = DateCreate,
DateImplement = DateImplement DateImplement = DateImplement,
}; ClientId = ClientId,
ImplementerId = ImplementerId
};
} }
} }

View File

@ -0,0 +1,103 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.BusinessLogicsContracts;
using GiftShopContracts.SearchModels;
using GiftShopContracts.ViewModels;
using GiftShopDataModels.Enums;
using Microsoft.AspNetCore.Mvc;
namespace GiftShopRestApi.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

@ -12,11 +12,13 @@ builder.Logging.AddLog4Net("log4net.config");
// Add services to the container. // Add services to the container.
builder.Services.AddTransient<IClientStorage, ClientStorage>(); builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IImplementerStorage, ImplementerStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>(); builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IGiftStorage, GiftStorage>(); builder.Services.AddTransient<IGiftStorage, GiftStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>(); builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>(); builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IImplementerLogic, ImplementerLogic>();
builder.Services.AddTransient<IGiftLogic, GiftLogic>(); builder.Services.AddTransient<IGiftLogic, GiftLogic>();
builder.Services.AddControllers(); builder.Services.AddControllers();

View File

@ -0,0 +1,174 @@
namespace GiftShopView
{
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()
{
FIOTextBox = new TextBox();
PasswordTextBox = new TextBox();
LabelFIO = new Label();
LabelPassword = new Label();
QualificationNumericUpDown = new NumericUpDown();
WorkExpNumericUpDown = new NumericUpDown();
LabelWorkExperience = new Label();
LabelQualification = new Label();
ButtonCancel = new Button();
ButtonSave = new Button();
((System.ComponentModel.ISupportInitialize)QualificationNumericUpDown).BeginInit();
((System.ComponentModel.ISupportInitialize)WorkExpNumericUpDown).BeginInit();
SuspendLayout();
//
// FIOTextBox
//
FIOTextBox.Location = new Point(144, 13);
FIOTextBox.Margin = new Padding(3, 4, 3, 4);
FIOTextBox.Name = "FIOTextBox";
FIOTextBox.Size = new Size(194, 27);
FIOTextBox.TabIndex = 0;
//
// PasswordTextBox
//
PasswordTextBox.Location = new Point(144, 66);
PasswordTextBox.Margin = new Padding(3, 4, 3, 4);
PasswordTextBox.Name = "PasswordTextBox";
PasswordTextBox.Size = new Size(194, 27);
PasswordTextBox.TabIndex = 1;
//
// LabelFIO
//
LabelFIO.AutoSize = true;
LabelFIO.Location = new Point(14, 20);
LabelFIO.Name = "LabelFIO";
LabelFIO.Size = new Size(49, 20);
LabelFIO.TabIndex = 2;
LabelFIO.Text = "ФИО: ";
//
// LabelPassword
//
LabelPassword.AutoSize = true;
LabelPassword.Location = new Point(14, 69);
LabelPassword.Name = "LabelPassword";
LabelPassword.Size = new Size(69, 20);
LabelPassword.TabIndex = 3;
LabelPassword.Text = "Пароль: ";
//
// QualificationNumericUpDown
//
QualificationNumericUpDown.Location = new Point(144, 175);
QualificationNumericUpDown.Margin = new Padding(3, 4, 3, 4);
QualificationNumericUpDown.Name = "QualificationNumericUpDown";
QualificationNumericUpDown.Size = new Size(194, 27);
QualificationNumericUpDown.TabIndex = 4;
//
// WorkExpNumericUpDown
//
WorkExpNumericUpDown.Location = new Point(144, 123);
WorkExpNumericUpDown.Margin = new Padding(3, 4, 3, 4);
WorkExpNumericUpDown.Name = "WorkExpNumericUpDown";
WorkExpNumericUpDown.Size = new Size(194, 27);
WorkExpNumericUpDown.TabIndex = 5;
//
// LabelWorkExperience
//
LabelWorkExperience.AutoSize = true;
LabelWorkExperience.Location = new Point(14, 123);
LabelWorkExperience.Name = "LabelWorkExperience";
LabelWorkExperience.Size = new Size(109, 20);
LabelWorkExperience.TabIndex = 6;
LabelWorkExperience.Text = "Опыт работы: ";
//
// LabelQualification
//
LabelQualification.AutoSize = true;
LabelQualification.Location = new Point(14, 177);
LabelQualification.Name = "LabelQualification";
LabelQualification.Size = new Size(118, 20);
LabelQualification.TabIndex = 7;
LabelQualification.Text = "Квалификация: ";
//
// ButtonCancel
//
ButtonCancel.Location = new Point(211, 225);
ButtonCancel.Margin = new Padding(3, 4, 3, 4);
ButtonCancel.Name = "ButtonCancel";
ButtonCancel.Size = new Size(111, 39);
ButtonCancel.TabIndex = 8;
ButtonCancel.Text = "Отмена";
ButtonCancel.UseVisualStyleBackColor = true;
ButtonCancel.Click += ButtonCancel_Click;
//
// ButtonSave
//
ButtonSave.Location = new Point(94, 225);
ButtonSave.Margin = new Padding(3, 4, 3, 4);
ButtonSave.Name = "ButtonSave";
ButtonSave.Size = new Size(111, 39);
ButtonSave.TabIndex = 9;
ButtonSave.Text = "Сохранить";
ButtonSave.UseVisualStyleBackColor = true;
ButtonSave.Click += ButtonSave_Click;
//
// FormImplementer
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(350, 285);
Controls.Add(ButtonSave);
Controls.Add(ButtonCancel);
Controls.Add(LabelQualification);
Controls.Add(LabelWorkExperience);
Controls.Add(WorkExpNumericUpDown);
Controls.Add(QualificationNumericUpDown);
Controls.Add(LabelPassword);
Controls.Add(LabelFIO);
Controls.Add(PasswordTextBox);
Controls.Add(FIOTextBox);
Margin = new Padding(3, 4, 3, 4);
Name = "FormImplementer";
Text = "Исполнитель";
Load += FormImplementer_Load;
((System.ComponentModel.ISupportInitialize)QualificationNumericUpDown).EndInit();
((System.ComponentModel.ISupportInitialize)WorkExpNumericUpDown).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox FIOTextBox;
private TextBox PasswordTextBox;
private Label LabelFIO;
private Label LabelPassword;
private NumericUpDown QualificationNumericUpDown;
private NumericUpDown WorkExpNumericUpDown;
private Label LabelWorkExperience;
private Label LabelQualification;
private Button ButtonCancel;
private Button ButtonSave;
}
}

View File

@ -0,0 +1,98 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.BusinessLogicsContracts;
using GiftShopContracts.SearchModels;
using Microsoft.Extensions.Logging;
namespace GiftShopView
{
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 ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(PasswordTextBox.Text))
{
MessageBox.Show("Заполните пароль", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(FIOTextBox.Text))
{
MessageBox.Show("Заполните фио", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение исполнителя");
try
{
var model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = FIOTextBox.Text,
Password = PasswordTextBox.Text,
Qualification = (int)QualificationNumericUpDown.Value,
WorkExperience = (int)WorkExpNumericUpDown.Value,
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void FormImplementer_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение исполнителя");
var view = _logic.ReadElement(new ImplementerSearchModel
{
Id = _id.Value
});
if (view != null)
{
FIOTextBox.Text = view.ImplementerFIO;
PasswordTextBox.Text = view.Password;
QualificationNumericUpDown.Value = view.Qualification;
WorkExpNumericUpDown.Value = view.WorkExperience;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

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,121 @@
namespace GiftShopView
{
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();
AddButton = new Button();
ChangeButton = new Button();
DeleteButton = new Button();
UpdateButton = new Button();
((System.ComponentModel.ISupportInitialize)DataGridView).BeginInit();
SuspendLayout();
//
// DataGridView
//
DataGridView.BackgroundColor = SystemColors.ControlLightLight;
DataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
DataGridView.Location = new Point(1, 1);
DataGridView.Margin = new Padding(3, 4, 3, 4);
DataGridView.Name = "DataGridView";
DataGridView.RowHeadersWidth = 51;
DataGridView.RowTemplate.Height = 25;
DataGridView.Size = new Size(543, 434);
DataGridView.TabIndex = 0;
//
// AddButton
//
AddButton.Location = new Point(566, 41);
AddButton.Margin = new Padding(3, 4, 3, 4);
AddButton.Name = "AddButton";
AddButton.Size = new Size(112, 37);
AddButton.TabIndex = 1;
AddButton.Text = "Добавить";
AddButton.UseVisualStyleBackColor = true;
AddButton.Click += AddButton_Click;
//
// ChangeButton
//
ChangeButton.Location = new Point(566, 102);
ChangeButton.Margin = new Padding(3, 4, 3, 4);
ChangeButton.Name = "ChangeButton";
ChangeButton.Size = new Size(112, 35);
ChangeButton.TabIndex = 2;
ChangeButton.Text = "Изменить";
ChangeButton.UseVisualStyleBackColor = true;
ChangeButton.Click += ChangeButton_Click;
//
// DeleteButton
//
DeleteButton.Location = new Point(566, 172);
DeleteButton.Margin = new Padding(3, 4, 3, 4);
DeleteButton.Name = "DeleteButton";
DeleteButton.Size = new Size(112, 32);
DeleteButton.TabIndex = 3;
DeleteButton.Text = "Удалить";
DeleteButton.UseVisualStyleBackColor = true;
DeleteButton.Click += DeleteButton_Click;
//
// UpdateButton
//
UpdateButton.Location = new Point(566, 232);
UpdateButton.Margin = new Padding(3, 4, 3, 4);
UpdateButton.Name = "UpdateButton";
UpdateButton.Size = new Size(112, 31);
UpdateButton.TabIndex = 4;
UpdateButton.Text = "Обновить";
UpdateButton.UseVisualStyleBackColor = true;
UpdateButton.Click += UpdateButton_Click;
//
// FormImplementers
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(690, 445);
Controls.Add(UpdateButton);
Controls.Add(DeleteButton);
Controls.Add(ChangeButton);
Controls.Add(AddButton);
Controls.Add(DataGridView);
Margin = new Padding(3, 4, 3, 4);
Name = "FormImplementers";
Text = "Исполнители";
Load += FormImplementers_Load;
((System.ComponentModel.ISupportInitialize)DataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView DataGridView;
private Button AddButton;
private Button ChangeButton;
private Button DeleteButton;
private Button UpdateButton;
}
}

View File

@ -0,0 +1,111 @@
using GiftShopContracts.BindingModels;
using GiftShopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
namespace GiftShopView
{
public partial class FormImplementers : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
public FormImplementers(ILogger<FormImplementers> logger, IImplementerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void AddButton_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 ChangeButton_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 DeleteButton_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 UpdateButton_Click(object sender, EventArgs e)
{
LoadData();
}
private void FormImplementers_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
DataGridView.DataSource = list;
DataGridView.Columns["Id"].Visible = false;
DataGridView.Columns["ImplementerFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка исполнителей");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки исполнителей");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

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

View File

@ -1,218 +1,210 @@
namespace GiftShopView namespace GiftShopView
{ {
partial class FormMain partial class FormMain
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary> /// <summary>
/// Clean up any resources being used. /// Clean up any resources being used.
/// </summary> /// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) if (disposing && (components != null))
{ {
components.Dispose(); components.Dispose();
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>
/// Required method for Designer support - do not modify /// Required method for Designer support - do not modify
/// the contents of this method with the code editor. /// the contents of this method with the code editor.
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
menuStrip = new MenuStrip(); menuStrip = new MenuStrip();
справочникиToolStripMenuItem = new ToolStripMenuItem(); справочникиToolStripMenuItem = new ToolStripMenuItem();
компонентыToolStripMenuItem = new ToolStripMenuItem(); компонентыToolStripMenuItem = new ToolStripMenuItem();
изделияToolStripMenuItem = new ToolStripMenuItem(); изделияToolStripMenuItem = new ToolStripMenuItem();
отчётыToolStripMenuItem = new ToolStripMenuItem(); клиентыToolStripMenuItem = new ToolStripMenuItem();
списокКомпонентовToolStripMenuItem = new ToolStripMenuItem(); исполнителиToolStripMenuItem = new ToolStripMenuItem();
компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem(); отчётыToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовToolStripMenuItem = new ToolStripMenuItem(); списокКомпонентовToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView(); компонентыПоИзделиямToolStripMenuItem = new ToolStripMenuItem();
buttonCreateOrder = new Button(); списокЗаказовToolStripMenuItem = new ToolStripMenuItem();
buttonTakeOrderInWork = new Button(); dataGridView = new DataGridView();
buttonOrderReady = new Button(); buttonCreateOrder = new Button();
buttonIssuedOrder = new Button(); buttonIssuedOrder = new Button();
buttonRef = new Button(); buttonRef = new Button();
клиентыToolStripMenuItem = new ToolStripMenuItem(); запускРаботToolStripMenuItem = new ToolStripMenuItem();
menuStrip.SuspendLayout(); menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout(); SuspendLayout();
// //
// menuStrip // menuStrip
// //
menuStrip.ImageScalingSize = new Size(20, 20); menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem }); menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, отчётыToolStripMenuItem, запускРаботToolStripMenuItem });
menuStrip.Location = new Point(0, 0); menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip"; menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1367, 28); menuStrip.Size = new Size(1367, 28);
menuStrip.TabIndex = 0; menuStrip.TabIndex = 0;
menuStrip.Text = "menuStrip1"; menuStrip.Text = "menuStrip1";
// //
// справочникиToolStripMenuItem // справочникиToolStripMenuItem
// //
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem }); справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem"; справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(117, 24); справочникиToolStripMenuItem.Size = new Size(117, 24);
справочникиToolStripMenuItem.Text = "Справочники"; справочникиToolStripMenuItem.Text = "Справочники";
// //
// компонентыToolStripMenuItem // компонентыToolStripMenuItem
// //
компонентыToolStripMenuItem.Name = омпонентыToolStripMenuItem"; компонентыToolStripMenuItem.Name = омпонентыToolStripMenuItem";
компонентыToolStripMenuItem.Size = new Size(224, 26); компонентыToolStripMenuItem.Size = new Size(185, 26);
компонентыToolStripMenuItem.Text = "Компоненты"; компонентыToolStripMenuItem.Text = "Компоненты";
компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click; компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click;
// //
// изделияToolStripMenuItem // изделияToolStripMenuItem
// //
изделияToolStripMenuItem.Name = "изделияToolStripMenuItem"; изделияToolStripMenuItem.Name = "изделияToolStripMenuItem";
изделияToolStripMenuItem.Size = new Size(224, 26); изделияToolStripMenuItem.Size = new Size(185, 26);
изделияToolStripMenuItem.Text = "Изделия"; изделияToolStripMenuItem.Text = "Изделия";
изделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click; изделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click;
// //
// отчётыToolStripMenuItem // клиентыToolStripMenuItem
// //
отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem }); клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem"; клиентыToolStripMenuItem.Size = new Size(185, 26);
отчётыToolStripMenuItem.Size = new Size(73, 24); клиентыToolStripMenuItem.Text = "Клиенты";
отчётыToolStripMenuItem.Text = "Отчёты"; клиентыToolStripMenuItem.Click += ClientsToolStripMenuItem_Click;
// //
// списокКомпонентовToolStripMenuItem // исполнителиToolStripMenuItem
// //
списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem"; исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem";
списокКомпонентовToolStripMenuItem.Size = new Size(276, 26); исполнителиToolStripMenuItem.Size = new Size(185, 26);
списокКомпонентовToolStripMenuItem.Text = "Список компонентов"; исполнителиToolStripMenuItem.Text = "Исполнители";
списокКомпонентовToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click;
// //
// компонентыПоИзделиямToolStripMenuItem // отчётыToolStripMenuItem
// //
компонентыПоИзделиямToolStripMenuItem.Name = омпонентыПоИзделиямToolStripMenuItem"; отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem });
компонентыПоИзделиямToolStripMenuItem.Size = new Size(276, 26); отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem";
компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям"; отчётыToolStripMenuItem.Size = new Size(73, 24);
компонентыПоИзделиямToolStripMenuItem.Click += ComponentGiftsToolStripMenuItem_Click; отчётыToolStripMenuItem.Text = "Отчёты";
// //
// списокЗаказовToolStripMenuItem // списокКомпонентовToolStripMenuItem
// //
списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem"; списокКомпонентовToolStripMenuItem.Name = "списокКомпонентовToolStripMenuItem";
списокЗаказовToolStripMenuItem.Size = new Size(276, 26); списокКомпонентовToolStripMenuItem.Size = new Size(276, 26);
списокЗаказовToolStripMenuItem.Text = "Список заказов"; списокКомпонентовToolStripMenuItem.Text = "Список компонентов";
списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click; списокКомпонентовToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click;
// //
// dataGridView // компонентыПоИзделиямToolStripMenuItem
// //
dataGridView.BackgroundColor = SystemColors.ControlLightLight; компонентыПоИзделиямToolStripMenuItem.Name = омпонентыПоИзделиямToolStripMenuItem";
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; компонентыПоИзделиямToolStripMenuItem.Size = new Size(276, 26);
dataGridView.Location = new Point(12, 41); компонентыПоИзделиямToolStripMenuItem.Text = "Компоненты по изделиям";
dataGridView.Name = "dataGridView"; компонентыПоИзделиямToolStripMenuItem.Click += ComponentGiftsToolStripMenuItem_Click;
dataGridView.RowHeadersWidth = 51; //
dataGridView.RowTemplate.Height = 29; // списокЗаказовToolStripMenuItem
dataGridView.Size = new Size(1123, 423); //
dataGridView.TabIndex = 1; списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem";
// списокЗаказовToolStripMenuItem.Size = new Size(276, 26);
// buttonCreateOrder списокЗаказовToolStripMenuItem.Text = "Список заказов";
// списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click;
buttonCreateOrder.Location = new Point(1155, 67); //
buttonCreateOrder.Name = "buttonCreateOrder"; // dataGridView
buttonCreateOrder.Size = new Size(189, 41); //
buttonCreateOrder.TabIndex = 2; dataGridView.BackgroundColor = SystemColors.ControlLightLight;
buttonCreateOrder.Text = "Создать заказ"; dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
buttonCreateOrder.UseVisualStyleBackColor = true; dataGridView.Location = new Point(12, 41);
buttonCreateOrder.Click += ButtonCreateOrder_Click; dataGridView.Name = "dataGridView";
// dataGridView.RowHeadersWidth = 51;
// buttonTakeOrderInWork dataGridView.RowTemplate.Height = 29;
// dataGridView.Size = new Size(1123, 423);
buttonTakeOrderInWork.Location = new Point(1155, 136); dataGridView.TabIndex = 1;
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork"; //
buttonTakeOrderInWork.Size = new Size(189, 41); // buttonCreateOrder
buttonTakeOrderInWork.TabIndex = 3; //
buttonTakeOrderInWork.Text = "Отдать на выполнение"; buttonCreateOrder.Location = new Point(1155, 90);
buttonTakeOrderInWork.UseVisualStyleBackColor = true; buttonCreateOrder.Name = "buttonCreateOrder";
buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click; buttonCreateOrder.Size = new Size(189, 57);
// buttonCreateOrder.TabIndex = 2;
// buttonOrderReady buttonCreateOrder.Text = "Создать заказ";
// buttonCreateOrder.UseVisualStyleBackColor = true;
buttonOrderReady.Location = new Point(1155, 211); buttonCreateOrder.Click += ButtonCreateOrder_Click;
buttonOrderReady.Name = "buttonOrderReady"; //
buttonOrderReady.Size = new Size(189, 41); // buttonIssuedOrder
buttonOrderReady.TabIndex = 4; //
buttonOrderReady.Text = "Заказ готов"; buttonIssuedOrder.Location = new Point(1155, 228);
buttonOrderReady.UseVisualStyleBackColor = true; buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonOrderReady.Click += ButtonOrderReady_Click; buttonIssuedOrder.Size = new Size(189, 57);
// buttonIssuedOrder.TabIndex = 5;
// buttonIssuedOrder buttonIssuedOrder.Text = "Заказ выдан";
// buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Location = new Point(1155, 290); buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
buttonIssuedOrder.Name = "buttonIssuedOrder"; //
buttonIssuedOrder.Size = new Size(189, 41); // buttonRef
buttonIssuedOrder.TabIndex = 5; //
buttonIssuedOrder.Text = "Заказ выдан"; buttonRef.Location = new Point(1155, 356);
buttonIssuedOrder.UseVisualStyleBackColor = true; buttonRef.Name = "buttonRef";
buttonIssuedOrder.Click += ButtonIssuedOrder_Click; buttonRef.Size = new Size(189, 57);
// buttonRef.TabIndex = 6;
// buttonRef buttonRef.Text = "Обновить список";
// buttonRef.UseVisualStyleBackColor = true;
buttonRef.Location = new Point(1155, 356); buttonRef.Click += ButtonRef_Click;
buttonRef.Name = "buttonRef"; //
buttonRef.Size = new Size(189, 41); // запускРаботToolStripMenuItem
buttonRef.TabIndex = 6; //
buttonRef.Text = "Обновить список"; запускРаботToolStripMenuItem.Name = апускРаботToolStripMenuItem";
buttonRef.UseVisualStyleBackColor = true; запускРаботToolStripMenuItem.Size = new Size(114, 24);
buttonRef.Click += ButtonRef_Click; запускРаботToolStripMenuItem.Text = "Запуск работ";
// запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click;
// клиентыToolStripMenuItem //
// // FormMain
клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem"; //
клиентыToolStripMenuItem.Size = new Size(224, 26); AutoScaleDimensions = new SizeF(8F, 20F);
клиентыToolStripMenuItem.Text = "Клиенты"; AutoScaleMode = AutoScaleMode.Font;
клиентыToolStripMenuItem.Click += new System.EventHandler(this.ClientsToolStripMenuItem_Click); ClientSize = new Size(1367, 471);
// Controls.Add(buttonRef);
// FormMain Controls.Add(buttonIssuedOrder);
// Controls.Add(buttonCreateOrder);
AutoScaleDimensions = new SizeF(8F, 20F); Controls.Add(dataGridView);
AutoScaleMode = AutoScaleMode.Font; Controls.Add(menuStrip);
ClientSize = new Size(1367, 471); MainMenuStrip = menuStrip;
Controls.Add(buttonRef); Name = "FormMain";
Controls.Add(buttonIssuedOrder); Text = "Магазин подарков";
Controls.Add(buttonOrderReady); Load += FormMain_Load;
Controls.Add(buttonTakeOrderInWork); menuStrip.ResumeLayout(false);
Controls.Add(buttonCreateOrder); menuStrip.PerformLayout();
Controls.Add(dataGridView); ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
Controls.Add(menuStrip); ResumeLayout(false);
MainMenuStrip = menuStrip; PerformLayout();
Name = "FormMain"; }
Text = "Магазин подарков";
Load += FormMain_Load;
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion #endregion
private MenuStrip menuStrip; private MenuStrip menuStrip;
private ToolStripMenuItem справочникиToolStripMenuItem; private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem компонентыToolStripMenuItem; private ToolStripMenuItem компонентыToolStripMenuItem;
private ToolStripMenuItem изделияToolStripMenuItem; private ToolStripMenuItem изделияToolStripMenuItem;
private DataGridView dataGridView; private DataGridView dataGridView;
private Button buttonCreateOrder; private Button buttonCreateOrder;
private Button buttonTakeOrderInWork; private Button buttonIssuedOrder;
private Button buttonOrderReady; private Button buttonRef;
private Button buttonIssuedOrder; private ToolStripMenuItem отчётыToolStripMenuItem;
private Button buttonRef; private ToolStripMenuItem списокКомпонентовToolStripMenuItem;
private ToolStripMenuItem отчётыToolStripMenuItem; private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem;
private ToolStripMenuItem списокКомпонентовToolStripMenuItem; private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem; private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem; private ToolStripMenuItem исполнителиToolStripMenuItem;
private ToolStripMenuItem клиентыToolStripMenuItem; private ToolStripMenuItem запускРаботToolStripMenuItem;
} }
} }

View File

@ -5,226 +5,177 @@ using Microsoft.Extensions.Logging;
namespace GiftShopView namespace GiftShopView
{ {
public partial class FormMain : Form public partial class FormMain : Form
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic; private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic; private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic) private readonly IWorkProcess _workProcess;
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
}
private void FormMain_Load(object sender, EventArgs e) public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
{ {
LoadData(); InitializeComponent();
} _logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
}
private void LoadData() private void FormMain_Load(object sender, EventArgs e)
{ {
_logger.LogInformation("Загрузка заказов"); LoadData();
try }
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["GiftId"].Visible = false;
dataGridView.Columns["GiftName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ClientId"].Visible = false;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e) private void LoadData()
{ {
var service = _logger.LogInformation("Загрузка заказов");
Program.ServiceProvider?.GetService(typeof(FormComponents)); try
if (service is FormComponents form) {
{ var list = _orderLogic.ReadList(null);
form.ShowDialog(); if (list != null)
} {
} dataGridView.DataSource = list;
dataGridView.Columns["GiftId"].Visible = false;
dataGridView.Columns["GiftName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e) private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormGifts)); var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
if (service is FormComponents form)
{
form.ShowDialog();
}
}
if (service is FormGifts form) private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e)
{ {
form.ShowDialog(); var service = Program.ServiceProvider?.GetService(typeof(FormGifts));
} if (service is FormGifts form)
} {
form.ShowDialog();
}
}
private void ButtonCreateOrder_Click(object sender, EventArgs e) private void ButtonCreateOrder_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder)); var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form) if (service is FormCreateOrder form)
{ {
form.ShowDialog(); form.ShowDialog();
LoadData(); LoadData();
} }
} }
private void ButtonTakeOrderInWork_Click(object sender, EventArgs e) private void ButtonIssuedOrder_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) if (dataGridView.SelectedRows.Count == 1)
{ {
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id); _logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try try
{ {
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel var operationResult = _orderLogic.FinishOrder(new OrderBindingModel
{ {
Id = id, Id = id,
GiftId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["GiftId"].Value), GiftId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["GiftId"].Value),
ClientId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ClientId"].Value), ClientId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ClientId"].Value),
GiftName = dataGridView.SelectedRows[0].Cells["GiftName"].Value.ToString(), GiftName = dataGridView.SelectedRows[0].Cells["GiftName"].Value.ToString(),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()), Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value), Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()), Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()), DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
}); });
if (!operationResult) if (!operationResult)
{ {
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
} }
LoadData(); _logger.LogInformation("Заказ №{id} выдан", id);
} LoadData();
catch (Exception ex) }
{ catch (Exception ex)
_logger.LogError(ex, "Ошибка передачи заказа в работу"); {
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, _logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
} }
private void ButtonOrderReady_Click(object sender, EventArgs e) private void ButtonRef_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) LoadData();
{ }
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel
{
Id = id,
GiftId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["GiftId"].Value),
ClientId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ClientId"].Value),
GiftName = dataGridView.SelectedRows[0].Cells["GiftName"].Value.ToString(),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
});
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 ComponentsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count == 1) using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.FinishOrder(new OrderBindingModel
{
Id = id,
GiftId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["GiftId"].Value),
ClientId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ClientId"].Value),
GiftName = dataGridView.SelectedRows[0].Cells["GiftName"].Value.ToString(),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
});
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ №{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonRef_Click(object sender, EventArgs e) if (dialog.ShowDialog() == DialogResult.OK)
{ {
LoadData(); _reportLogic.SaveGiftsToWordFile(new ReportBindingModel
} {
FileName = dialog.FileName
});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e) private void ComponentGiftsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" }; var service = Program.ServiceProvider?.GetService(typeof(FormReportGiftComponents));
if (dialog.ShowDialog() == DialogResult.OK) if (service is FormReportGiftComponents form)
{ {
_reportLogic.SaveGiftsToWordFile(new ReportBindingModel form.ShowDialog();
{ }
FileName = dialog.FileName }
});
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void ComponentGiftsToolStripMenuItem_Click(object sender, EventArgs e) private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportGiftComponents)); var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (service is FormReportGiftComponents form) if (service is FormReportOrders form)
{ {
form.ShowDialog(); form.ShowDialog();
} }
} }
private void OrdersToolStripMenuItem_Click(object sender, EventArgs e) private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders)); var service = Program.ServiceProvider?.GetService(typeof(FormClients));
if (service is FormClients form)
{
form.ShowDialog();
}
}
if (service is FormReportOrders form) private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e)
{ {
form.ShowDialog(); var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
} if (service is FormImplementers form)
} {
form.ShowDialog();
}
}
private void ClientsToolStripMenuItem_Click(object sender, EventArgs e) private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormClients)); _workProcess.DoWork((Program.ServiceProvider?
if (service is FormClients form) .GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
{ MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
form.ShowDialog(); }
} }
}
}
} }

View File

@ -35,14 +35,17 @@ namespace GiftShopView
services.AddTransient<IOrderStorage, OrderStorage>(); services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IGiftStorage, GiftStorage>(); services.AddTransient<IGiftStorage, GiftStorage>();
services.AddTransient<IClientStorage, ClientStorage>(); services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IClientLogic, ClientLogic>(); services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IComponentLogic, ComponentLogic>(); services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>(); services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IGiftLogic, GiftLogic>(); services.AddTransient<IGiftLogic, GiftLogic>();
services.AddTransient<IReportLogic, ReportLogic>(); services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>(); services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>(); services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>(); services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
@ -56,6 +59,8 @@ namespace GiftShopView
services.AddTransient<FormReportOrders>(); services.AddTransient<FormReportOrders>();
services.AddTransient<FormReportGiftComponents>(); services.AddTransient<FormReportGiftComponents>();
services.AddTransient<FormClients>(); services.AddTransient<FormClients>();
} services.AddTransient<FormImplementer>();
services.AddTransient<FormImplementers>();
}
} }
} }