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)
{
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.");
return false;
throw new ArgumentNullException(nameof(model));
}
if ((int)vmodel.Status + 1 != (int)newStatus)
{
throw new InvalidOperationException($"Попытка перевести заказ не в следующий статус: " +
$"Текущий статус: {vmodel.Status} \n" +
$"Планируемый статус: {newStatus} \n" +
$"Доступный статус: {(OrderStatus)((int)vmodel.Status + 1)}");
}
model.Status = newStatus;
model.DateCreate = vmodel.DateCreate;
if (model.Status == OrderStatus.Выдан)
model.DateImplement = DateTime.Now;
if (model.DateImplement == null)
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)
{
model.Status--;
_logger.LogWarning("Update operation failed");
return false;
}
@ -74,6 +89,7 @@ namespace GiftShopBusinessLogic.BusinessLogics
public bool DeliveryOrder(OrderBindingModel model)
{
model.DateImplement = DateTime.Now;
return StatusUpdate(model, OrderStatus.Готов);
}
@ -127,5 +143,28 @@ namespace GiftShopBusinessLogic.BusinessLogics
_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? 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,6 +8,8 @@ namespace GiftShopContracts.BusinessLogicsContracts
{
List<OrderViewModel>? ReadList(OrderSearchModel? model);
OrderViewModel? ReadElement(OrderSearchModel model);
bool CreateOrder(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
{
@ -9,5 +11,9 @@
public DateTime? DateFrom { 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

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

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<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,37 +29,52 @@ namespace GiftShopDatabaseImplement.Implements
return null;
}
using var context = new GiftShopDatabase();
return context.Orders.Include(x => x.Gift)
.Include(x => x.Client).FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
if (model.ImplementerId.HasValue)
{
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)
{
if (!model.DateFrom.HasValue && !model.DateTo.HasValue && !model.ClientId.HasValue)
if (model is null)
{
return new();
}
using var context = new GiftShopDatabase();
if (model.DateFrom.HasValue)
if (model.DateTo != null && model.DateFrom != null && model.ClientId.HasValue)
{
return context.Orders
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo && x.ClientId == model.ClientId)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.DateTo != null && model.DateFrom != null)
{
return context.Orders
.Include(x => x.Gift)
.Include(x => x.Client)
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.ToList()
.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)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
return context.Orders
.Include(x => x.Gift)
.Include(x => x.Client)
.Where(x => x.Id == model.Id)
.Where(x => x.Status == model.Status)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
@ -68,7 +83,7 @@ namespace GiftShopDatabaseImplement.Implements
{
using var context = new GiftShopDatabase();
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)
@ -85,6 +100,7 @@ namespace GiftShopDatabaseImplement.Implements
return context.Orders
.Include(x => x.Gift)
.Include(x => x.Client)
.Include(x => x.Implementer)
.FirstOrDefault(x => x.Id == newOrder.Id)
?.GetViewModel;
}
@ -93,7 +109,7 @@ namespace GiftShopDatabaseImplement.Implements
{
using var context = new GiftShopDatabase();
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)
{
return null;

View File

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

View File

@ -54,6 +54,22 @@ namespace GiftShopDatabaseImplement.Migrations
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(
name: "GiftComponents",
columns: table => new
@ -89,6 +105,7 @@ namespace GiftShopDatabaseImplement.Migrations
.Annotation("SqlServer:Identity", "1, 1"),
GiftId = 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),
Count = table.Column<int>(type: "int", nullable: false),
Sum = table.Column<double>(type: "float", nullable: false),
@ -111,6 +128,11 @@ namespace GiftShopDatabaseImplement.Migrations
principalTable: "Gifts",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
column: x => x.ImplementerId,
principalTable: "Implementers",
principalColumn: "Id");
});
migrationBuilder.CreateIndex(
@ -132,6 +154,11 @@ namespace GiftShopDatabaseImplement.Migrations
name: "IX_Orders_GiftId",
table: "Orders",
column: "GiftId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
}
/// <inheritdoc />
@ -151,6 +178,9 @@ namespace GiftShopDatabaseImplement.Migrations
migrationBuilder.DropTable(
name: "Gifts");
migrationBuilder.DropTable(
name: "Implementers");
}
}
}

View File

@ -113,6 +113,33 @@ namespace GiftShopDatabaseImplement.Migrations
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 =>
{
b.Property<int>("Id")
@ -140,6 +167,9 @@ namespace GiftShopDatabaseImplement.Migrations
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
@ -152,6 +182,8 @@ namespace GiftShopDatabaseImplement.Migrations
b.HasIndex("GiftId");
b.HasIndex("ImplementerId");
b.ToTable("Orders");
});
@ -188,9 +220,15 @@ namespace GiftShopDatabaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("GiftShopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.Navigation("Client");
b.Navigation("Gift");
b.Navigation("Implementer");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Client", b =>
@ -209,6 +247,11 @@ namespace GiftShopDatabaseImplement.Migrations
b.Navigation("Orders");
});
modelBuilder.Entity("GiftShopDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
#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]
public int ClientId { get; set; }
public int? ImplementerId { get; private set; }
public string GiftName { get; private set; } = string.Empty;
[Required]
@ -35,6 +37,8 @@ namespace GiftShopDatabaseImplement.Models
public Client Client { get; set; }
public Implementer? Implementer { get; set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
@ -47,6 +51,7 @@ namespace GiftShopDatabaseImplement.Models
Id = model.Id,
GiftId = model.GiftId,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
GiftName = model.GiftName,
Count = model.Count,
Sum = model.Sum,
@ -62,14 +67,9 @@ namespace GiftShopDatabaseImplement.Models
{
return;
}
GiftId = model.GiftId;
GiftName = model.GiftName;
Count = model.Count;
Sum = model.Sum;
Status = model.Status;
DateCreate = model.DateCreate;
DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
}
public OrderViewModel GetViewModel
@ -82,13 +82,15 @@ namespace GiftShopDatabaseImplement.Models
Id = Id,
GiftId = GiftId,
ClientId = ClientId,
ImplementerId = ImplementerId,
ClientFIO = context.Clients.FirstOrDefault(x => x.Id == ClientId)?.ClientFIO ?? string.Empty,
GiftName = context.Gifts.FirstOrDefault(x => x.Id == GiftId)?.GiftName ?? string.Empty,
Count = Count,
Sum = Sum,
Status = Status,
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 ImplementerFileName = "Implementer.xml";
public List<Component> Components { 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<Implementer> Implementers { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
@ -40,11 +44,14 @@ namespace GiftShopFileImplement
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement);
public void SaveImplementers() => SaveData(Implementers, OrderFileName, "Implementers", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Gifts = LoadData(GiftFileName, "Gift", x => Gift.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)

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,6 +10,12 @@ namespace GiftShopFileImplement.Models
{
public int GiftId { 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; }
@ -32,7 +38,10 @@ namespace GiftShopFileImplement.Models
{
Id = model.Id,
GiftId = model.GiftId,
GiftName = model.GiftName,
Count = model.Count,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
@ -50,8 +59,11 @@ namespace GiftShopFileImplement.Models
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
GiftId = Convert.ToInt32(element.Element("GiftId")!.Value),
GiftName = element.Element("GiftName")!.Value,
Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
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)
};
@ -68,11 +80,7 @@ namespace GiftShopFileImplement.Models
{
return;
}
GiftId = model.GiftId;
Count = model.Count;
Sum = model.Sum;
Status = model.Status;
DateCreate = model.DateCreate;
DateImplement = model.DateImplement;
}
@ -80,6 +88,9 @@ namespace GiftShopFileImplement.Models
{
Id = Id,
GiftId = GiftId,
ClientId = ClientId,
ImplementerId = ImplementerId,
GiftName = GiftName,
Count = Count,
Sum = Sum,
Status = Status,
@ -89,7 +100,10 @@ namespace GiftShopFileImplement.Models
public XElement GetXElement => new("Order",
new XAttribute("Id", Id),
new XElement("GiftName", GiftName),
new XElement("GiftId", GiftId.ToString()),
new XElement("ClientId", ClientId.ToString()),
new XElement("ImplementerId", ImplementerId.ToString()),
new XElement("Count", Count.ToString()),
new XElement("Sum", Sum.ToString()),
new XElement("Status", Status.ToString()),

View File

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

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,8 +9,12 @@ namespace GiftShopListImplement.Models
{
public int GiftId { get; private set; }
public int? ImplementerId { 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; }
@ -38,7 +42,9 @@ namespace GiftShopListImplement.Models
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement
DateImplement = model.DateImplement,
ImplementerId = model.ImplementerId,
ClientId = model.ClientId,
};
}
@ -49,7 +55,6 @@ namespace GiftShopListImplement.Models
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
@ -61,7 +66,9 @@ namespace GiftShopListImplement.Models
Sum = Sum,
Status = Status,
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.
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IImplementerStorage, ImplementerStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IGiftStorage, GiftStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IImplementerLogic, ImplementerLogic>();
builder.Services.AddTransient<IGiftLogic, GiftLogic>();
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

@ -32,17 +32,17 @@
справочники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();
buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button();
buttonOrderReady = new Button();
buttonIssuedOrder = new Button();
buttonRef = new Button();
клиентыToolStripMenuItem = new ToolStripMenuItem();
запускРаботToolStripMenuItem = new ToolStripMenuItem();
menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
@ -50,7 +50,7 @@
// menuStrip
//
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.Name = "menuStrip";
menuStrip.Size = new Size(1367, 28);
@ -59,7 +59,7 @@
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem });
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { компонентыToolStripMenuItem, изделияToolStripMenuItem, клиентыToolStripMenuItem, исполнителиToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(117, 24);
справочникиToolStripMenuItem.Text = "Справочники";
@ -67,17 +67,31 @@
// компонентыToolStripMenuItem
//
компонентыToolStripMenuItem.Name = омпонентыToolStripMenuItem";
компонентыToolStripMenuItem.Size = new Size(224, 26);
компонентыToolStripMenuItem.Size = new Size(185, 26);
компонентыToolStripMenuItem.Text = "Компоненты";
компонентыToolStripMenuItem.Click += КомпонентыToolStripMenuItem_Click;
//
// изделияToolStripMenuItem
//
изделияToolStripMenuItem.Name = "изделияToolStripMenuItem";
изделияToolStripMenuItem.Size = new Size(224, 26);
изделияToolStripMenuItem.Size = new Size(185, 26);
изделияToolStripMenuItem.Text = "Изделия";
изделияToolStripMenuItem.Click += ИзделияToolStripMenuItem_Click;
//
// клиентыToolStripMenuItem
//
клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
клиентыToolStripMenuItem.Size = new Size(185, 26);
клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += ClientsToolStripMenuItem_Click;
//
// исполнителиToolStripMenuItem
//
исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem";
исполнителиToolStripMenuItem.Size = new Size(185, 26);
исполнителиToolStripMenuItem.Text = "Исполнители";
исполнителиToolStripMenuItem.Click += исполнителиToolStripMenuItem_Click;
//
// отчётыToolStripMenuItem
//
отчётыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { списокКомпонентовToolStripMenuItem, компонентыПоИзделиямToolStripMenuItem, списокЗаказовToolStripMenuItem });
@ -119,39 +133,19 @@
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(1155, 67);
buttonCreateOrder.Location = new Point(1155, 90);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(189, 41);
buttonCreateOrder.Size = new Size(189, 57);
buttonCreateOrder.TabIndex = 2;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click;
//
// buttonTakeOrderInWork
//
buttonTakeOrderInWork.Location = new Point(1155, 136);
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
buttonTakeOrderInWork.Size = new Size(189, 41);
buttonTakeOrderInWork.TabIndex = 3;
buttonTakeOrderInWork.Text = "Отдать на выполнение";
buttonTakeOrderInWork.UseVisualStyleBackColor = true;
buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click;
//
// buttonOrderReady
//
buttonOrderReady.Location = new Point(1155, 211);
buttonOrderReady.Name = "buttonOrderReady";
buttonOrderReady.Size = new Size(189, 41);
buttonOrderReady.TabIndex = 4;
buttonOrderReady.Text = "Заказ готов";
buttonOrderReady.UseVisualStyleBackColor = true;
buttonOrderReady.Click += ButtonOrderReady_Click;
//
// buttonIssuedOrder
//
buttonIssuedOrder.Location = new Point(1155, 290);
buttonIssuedOrder.Location = new Point(1155, 228);
buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(189, 41);
buttonIssuedOrder.Size = new Size(189, 57);
buttonIssuedOrder.TabIndex = 5;
buttonIssuedOrder.Text = "Заказ выдан";
buttonIssuedOrder.UseVisualStyleBackColor = true;
@ -161,18 +155,18 @@
//
buttonRef.Location = new Point(1155, 356);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(189, 41);
buttonRef.Size = new Size(189, 57);
buttonRef.TabIndex = 6;
buttonRef.Text = "Обновить список";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// клиентыToolStripMenuItem
// запускРаботToolStripMenuItem
//
клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
клиентыToolStripMenuItem.Size = new Size(224, 26);
клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += new System.EventHandler(this.ClientsToolStripMenuItem_Click);
запускРаботToolStripMenuItem.Name = "запускРаботToolStripMenuItem";
запускРаботToolStripMenuItem.Size = new Size(114, 24);
запускРаботToolStripMenuItem.Text = "Запуск работ";
запускРаботToolStripMenuItem.Click += запускРаботToolStripMenuItem_Click;
//
// FormMain
//
@ -181,8 +175,6 @@
ClientSize = new Size(1367, 471);
Controls.Add(buttonRef);
Controls.Add(buttonIssuedOrder);
Controls.Add(buttonOrderReady);
Controls.Add(buttonTakeOrderInWork);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Controls.Add(menuStrip);
@ -205,8 +197,6 @@
private ToolStripMenuItem изделияToolStripMenuItem;
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonTakeOrderInWork;
private Button buttonOrderReady;
private Button buttonIssuedOrder;
private Button buttonRef;
private ToolStripMenuItem отчётыToolStripMenuItem;
@ -214,5 +204,7 @@
private ToolStripMenuItem компонентыПоИзделиямToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem;
private ToolStripMenuItem запускРаботToolStripMenuItem;
}
}

View File

@ -13,12 +13,15 @@ namespace GiftShopView
private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic)
private readonly IWorkProcess _workProcess;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic, IWorkProcess workProcess)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
_workProcess = workProcess;
}
private void FormMain_Load(object sender, EventArgs e)
@ -38,6 +41,7 @@ namespace GiftShopView
dataGridView.Columns["GiftId"].Visible = false;
dataGridView.Columns["GiftName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
}
_logger.LogInformation("Загрузка заказов");
}
@ -50,8 +54,7 @@ namespace GiftShopView
private void КомпонентыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormComponents));
var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
if (service is FormComponents form)
{
form.ShowDialog();
@ -61,7 +64,6 @@ namespace GiftShopView
private void ИзделияToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormGifts));
if (service is FormGifts form)
{
form.ShowDialog();
@ -78,73 +80,6 @@ namespace GiftShopView
}
}
private void ButtonTakeOrderInWork_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = id,
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 ButtonOrderReady_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'", id);
try
{
var operationResult = _orderLogic.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)
{
if (dataGridView.SelectedRows.Count == 1)
@ -226,5 +161,21 @@ namespace GiftShopView
form.ShowDialog();
}
}
private void исполнителиToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (service is FormImplementers form)
{
form.ShowDialog();
}
}
private void запускРаботToolStripMenuItem_Click(object sender, EventArgs e)
{
_workProcess.DoWork((Program.ServiceProvider?
.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}

View File

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