PIbd-23. Kislitsa E.D. Lab work 06 base #9

Closed
Egor wants to merge 4 commits from Lab6 into Lab5
45 changed files with 2532 additions and 498 deletions

View File

@ -0,0 +1,153 @@
using DinerContracts.BindingModels;
using DinerContracts.BusinessLogicsContracts;
using DinerContracts.SearchModels;
using DinerContracts.StoragesContracts;
using DinerContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace DinerBusinessLogic.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 List<ImplementerViewModel>? ReadList(ImplementerSearchModel? model)
{
_logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model?.ImplementerFIO, model?.Id);
var list = model == null ? _implementerStorage.GetFullList() : _implementerStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ImplementerViewModel? ReadElement(ImplementerSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadList. ImplementerFIO:{ImplementerFIO}. Id:{Id}", model.ImplementerFIO, model?.Id);
var element = _implementerStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool Create(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ImplementerBindingModel model)
{
CheckModel(model);
if (_implementerStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ImplementerBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_implementerStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ImplementerBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
throw new ArgumentNullException("Отсутствие ФИО в учётной записи", nameof(model.ImplementerFIO));
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password));
}
if (model.Qualification <= 0)
{
throw new ArgumentNullException("Указана некорректная квалификация", nameof(model.Qualification));
}
if (model.WorkExperience < 0)
{
throw new ArgumentNullException("Указан некоректный стаж работы", nameof(model.WorkExperience));
}
_logger.LogInformation("Implementer. ImplementerFIO:{ImplementerFIO}. Password:{Password}. " +
"Qualification:{Qualification}. WorkExperience:{ WorkExperience}. Id:{Id}",
model.ImplementerFIO, model.Password, model.Qualification, model.WorkExperience, model.Id);
var element = _implementerStorage.GetElement(new ImplementerSearchModel
{
ImplementerFIO = model.ImplementerFIO,
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Исполнитель с таким именем уже есть");
}
}
}
}

View File

@ -19,16 +19,39 @@ namespace DinerBusinessLogic.BusinessLogics
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("ReadList. Id:{ Id}", model?.Id);
_logger.LogInformation("ReadList. Id:{Id}", model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public OrderViewModel? ReadElement(OrderSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. Id:{Id}", model?.Id);
var element = _orderStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
@ -41,18 +64,13 @@ namespace DinerBusinessLogic.BusinessLogics
}
return true;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выполняется);
}
public bool FinishOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Готов);
}
public bool DeliveryOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выдан);
return StatusUpdate(model, OrderStatus.Готов);
}
private void CheckModel(OrderBindingModel model, bool withParams = true)
{
if (model == null)
@ -89,7 +107,60 @@ namespace DinerBusinessLogic.BusinessLogics
throw new InvalidOperationException("Изделие с таким идентификатором уже есть");
}
}
private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus)
public bool StatusUpdate(OrderBindingModel model, OrderStatus newOrderStatus)
{
var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (viewModel == null)
{
throw new ArgumentNullException(nameof(model));
}
if (viewModel.Status + 1 != newOrderStatus)
{
_logger.LogWarning("Status update operation failed. New status " + newOrderStatus.ToString() + " incorrect");
return false;
}
model.Status = newOrderStatus;
if (viewModel.ImplementerId.HasValue)
{
model.ImplementerId = viewModel.ImplementerId;
}
if (model.Status == OrderStatus.Готов)
{
model.DateImplement = DateTime.Now;
}
else
{
model.DateImplement = viewModel.DateImplement;
}
CheckModel(model, false);
if (_orderStorage.Update(model) == null)
{
model.Status--;
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выполняется);
}
public bool DeliveryOrder(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выдан);
}
private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus)
{
CheckModel(model, false);
var element = _orderStorage.GetElement(new OrderSearchModel()

View File

@ -0,0 +1,142 @@
using DinerContracts.BindingModels;
using DinerContracts.BusinessLogicsContracts;
using DinerContracts.SearchModels;
using DinerContracts.ViewModels;
using DinerDataModels.Enum;
using Microsoft.Extensions.Logging;
namespace DinerBusinessLogic.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, orders);
await Task.Run(async () =>
{
foreach (var order in orders)
{
try
{
_logger.LogDebug("DoWork. Worker {Id} try get order {Order}", implementer.Id, order.Id);
var notOccupied = _orderLogic.TakeOrderInWork(new OrderBindingModel
{
Id = order.Id,
ImplementerId = implementer.Id
});
if (notOccupied)
{
await Task.Delay(implementer.WorkExperience * _rnd.Next(100, 1000) * order.Count);
_logger.LogDebug("DoWork. Worker {Id} finish order { Order}", implementer.Id, order.Id);
_orderLogic.FinishOrder(new OrderBindingModel { Id = order.Id, ImplementerId = implementer.Id });
await Task.Delay(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, List<OrderViewModel> allOrders)
{
if (_orderLogic == null || implementer == null || allOrders == null || allOrders.Count == 0)
{
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 DinerDataModels.Models;
namespace DinerContracts.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

@ -9,6 +9,7 @@ namespace DinerContracts.BindingModels
public int Id { get; set; }
public int SnackId { get; set; }
public int ClientId { get; set; }
public int? ImplementerId { get; set; }
public string SnackName { get; set; } = string.Empty;
public int Count { get; set; }
public double Sum { get; set; }

View File

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

@ -7,6 +7,7 @@ namespace DinerContracts.BusinessLogicsContracts
public interface IOrderLogic
{
List<OrderViewModel>? ReadList(OrderSearchModel? model);
OrderViewModel? ReadElement(OrderSearchModel model);
bool CreateOrder(OrderBindingModel model);
bool TakeOrderInWork(OrderBindingModel model);
bool FinishOrder(OrderBindingModel model);

View File

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

View File

@ -0,0 +1,16 @@

namespace DinerContracts.SearchModels
{
public class ImplementerSearchModel
{
public int? Id { get; set; }
public string? ImplementerFIO { get; set; }
public string? Password { get; set; }
public int? WorkExperience { get; set; }
public int? Qualification { get; set; }
}
}

View File

@ -1,10 +1,16 @@
namespace DinerContracts.SearchModels
using DinerDataModels.Enum;
namespace DinerContracts.SearchModels
{
public class OrderSearchModel
{
public int? Id { get; set; }
public int? ClientId { get; set; }
public int? ImplementerId { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public OrderStatus? Status { get; set; }
}
}

View File

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

View File

@ -9,12 +9,15 @@ namespace DinerContracts.ViewModels
[DisplayName("Номер")]
public int Id { get; set; }
public int ClientId { get; set; }
public int? ImplementerId { get; set; }
public int SnackId { get; set; }
[DisplayName("Изделие")]
public string SnackName { get; set; } = string.Empty;
[DisplayName("Клиент")]
public string ClientFIO { get; set; } = string.Empty;
[DisplayName("Исполнитель")]
public string ImplementerFIO { get; set; } = string.Empty;
[DisplayName("Количество")]
public int Count { get; set; }
[DisplayName("Сумма")]

View File

@ -0,0 +1,14 @@

namespace DinerDataModels.Models
{
public interface IImplementerModel : IId
{
string ImplementerFIO { get; }
string Password { get; }
int WorkExperience { get; }
int Qualification { get; }
}
}

View File

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

View File

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

View File

@ -0,0 +1,129 @@
using DinerContracts.BindingModels;
using DinerContracts.SearchModels;
using DinerContracts.StoragesContracts;
using DinerContracts.ViewModels;
using DinerListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DinerListImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataListSingleton _source;
public ImplementerStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ImplementerViewModel> GetFullList()
{
var result = new List<ImplementerViewModel>();
foreach (var implementer in _source.Implementers)
{
result.Add(implementer.GetViewModel);
}
return result;
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
var result = new List<ImplementerViewModel>();
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
return result;
}
foreach (var implementer in _source.Implementers)
{
if (implementer.ImplementerFIO.Contains(model.ImplementerFIO))
{
result.Add(implementer.GetViewModel);
}
}
return result;
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO) && !model.Id.HasValue)
{
return null;
}
foreach (var implementer in _source.Implementers)
{
if ((!string.IsNullOrEmpty(model.ImplementerFIO) && implementer.ImplementerFIO == model.ImplementerFIO) ||
(model.Id.HasValue && implementer.Id == model.Id))
{
return implementer.GetViewModel;
}
}
return null;
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = 1;
foreach (var implementer in _source.Implementers)
{
if (model.Id <= implementer.Id)
{
model.Id = implementer.Id + 1;
}
}
var newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
_source.Implementers.Add(newImplementer);
return newImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
foreach (var implementer in _source.Implementers)
{
if (implementer.Id == model.Id)
{
implementer.Update(model);
return implementer.GetViewModel;
}
}
return null;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
for (int i = 0; i < _source.Implementers.Count; ++i)
{
if (_source.Implementers[i].Id == model.Id)
{
var element = _source.Implementers[i];
_source.Implementers.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -55,8 +55,7 @@ namespace DinerListImplement.Implements
else if (model.ClientId.HasValue)
{
var resultClie = new List<OrderViewModel>();
foreach (var order in _source.Orders)
{
if (order.ClientId == model.ClientId)
@ -66,8 +65,20 @@ namespace DinerListImplement.Implements
}
return result;
}
}
else if (model.ImplementerId.HasValue)
{
foreach (var order in _source.Orders)
{
if (order.ImplementerId == model.ImplementerId)
{
result.Add(AttachSnackName(order.GetViewModel));
}
}
return result;
}
return new();
}
@ -152,6 +163,7 @@ namespace DinerListImplement.Implements
}
var snack = _source.Products.FirstOrDefault(x => x.Id == model.SnackId);
var client = _source.Clients.FirstOrDefault(x => x.Id == model.ClientId);
var implementer = _source.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId);
if (snack != null)
{
model.SnackName = snack.SnackName;
@ -160,6 +172,10 @@ namespace DinerListImplement.Implements
{
model.ClientFIO = client.ClientFIO;
}
if (implementer != null)
{
model.ImplementerFIO = implementer.ImplementerFIO;
}
return model;
}
}

View File

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

View File

@ -2,6 +2,7 @@
using DinerContracts.ViewModels;
using DinerDataModels.Enum;
using DinerDataModels.Models;
using System.Reflection;
namespace DinerListImplement.Models
{
@ -9,6 +10,7 @@ namespace DinerListImplement.Models
{
public int Id { get; private set; }
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
public string SnackName { get; private set; }
public int SnackID { get; private set; }
public int Count { get; private set; }
@ -27,6 +29,7 @@ namespace DinerListImplement.Models
Id = model.Id,
SnackName = model.SnackName,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
SnackID = model.SnackId,
Count = model.Count,
Sum = model.Sum,
@ -56,6 +59,7 @@ namespace DinerListImplement.Models
SnackId = SnackID,
SnackName = SnackName,
ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count,
Sum = Sum,
Status = Status,

161
Diner/Diner/FormImplementer.Designer.cs generated Normal file
View File

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

View File

@ -0,0 +1,122 @@
using DinerContracts.BindingModels;
using DinerContracts.BusinessLogicsContracts;
using DinerContracts.SearchModels;
using Microsoft.Extensions.Logging;
namespace Diner
{
public partial class FormImplementer : Form
{
private readonly ILogger _logger;
private readonly IImplementerLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public FormImplementer(ILogger<FormImplementer> logger, IImplementerLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormImplementer_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Получение исполнителя");
var view = _logic.ReadElement(new ImplementerSearchModel { Id = _id.Value });
if (view != null)
{
textBoxImplementerFIO.Text = view.ImplementerFIO;
textBoxPassword.Text = view.Password;
textBoxWorkExperience.Text = view.WorkExperience.ToString();
textBoxQualification.Text = view.Qualification.ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxImplementerFIO.Text))
{
MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxPassword.Text))
{
MessageBox.Show("Введите пароль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxWorkExperience.Text))
{
MessageBox.Show("Введите ваш стаж", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxQualification.Text))
{
MessageBox.Show("Введите свою квалификацию", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение исполнителя");
try
{
var model = new ImplementerBindingModel
{
Id = _id ?? 0,
ImplementerFIO = textBoxImplementerFIO.Text,
Password = textBoxPassword.Text,
WorkExperience = Convert.ToInt16(textBoxWorkExperience.Text),
Qualification = Convert.ToInt16(textBoxQualification.Text)
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранеии. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения исполнителя");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

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

113
Diner/Diner/FormImplementers.Designer.cs generated Normal file
View File

@ -0,0 +1,113 @@
namespace Diner
{
partial class FormImplementers
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridView = new DataGridView();
buttonCreate = new Button();
buttonChange = new Button();
buttonDelete = new Button();
buttonUpdate = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 12);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(768, 426);
dataGridView.TabIndex = 0;
//
// buttonCreate
//
buttonCreate.Location = new Point(805, 22);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(160, 29);
buttonCreate.TabIndex = 1;
buttonCreate.Text = "Создать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += ButtonCreate_Click;
//
// buttonChange
//
buttonChange.Location = new Point(805, 90);
buttonChange.Name = "buttonChange";
buttonChange.Size = new Size(160, 29);
buttonChange.TabIndex = 2;
buttonChange.Text = "Изменить";
buttonChange.UseVisualStyleBackColor = true;
buttonChange.Click += ButtonChange_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(805, 153);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(160, 29);
buttonDelete.TabIndex = 3;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDelete_Click;
//
// buttonUpdate
//
buttonUpdate.Location = new Point(805, 218);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(160, 29);
buttonUpdate.TabIndex = 4;
buttonUpdate.Text = "Обновить";
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += ButtonUpdate_Click;
//
// FormImplementers
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(991, 450);
Controls.Add(buttonUpdate);
Controls.Add(buttonDelete);
Controls.Add(buttonChange);
Controls.Add(buttonCreate);
Controls.Add(dataGridView);
Name = "FormImplementers";
Text = "Исполнители";
Load += FormImplementers_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonCreate;
private Button buttonChange;
private Button buttonDelete;
private Button buttonUpdate;
}
}

View File

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

View File

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

View File

@ -1,219 +1,220 @@
namespace Diner
{
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
partial class FormMain
{
/// <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);
}
/// <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
#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();
buttonCreateOrder = new Button();
buttonTakeOrderInWork = new Button();
buttonOrderReady = new Button();
buttonIssuedOrder = new Button();
buttonRef = new Button();
toolStrip1 = new ToolStrip();
toolStripLabel1 = new ToolStripDropDownButton();
componentsToolStripMenuItem = new ToolStripMenuItem();
snacksToolStripMenuItem = new ToolStripMenuItem();
toolStripDropDownButton1 = new ToolStripDropDownButton();
списокЗакусокToolStripMenuItem = new ToolStripMenuItem();
закускиПоКомпонентамToolStripMenuItem = new ToolStripMenuItem();
списокЗаказовToolStripMenuItem = new ToolStripMenuItem();
клиентыToolStripMenuItem = new ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
toolStrip1.SuspendLayout();
SuspendLayout();
//
// dataGridView
//
dataGridView.BackgroundColor = SystemColors.ButtonHighlight;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(0, 27);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(986, 421);
dataGridView.TabIndex = 0;
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(1040, 88);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(202, 29);
buttonCreateOrder.TabIndex = 1;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click;
//
// buttonTakeOrderInWork
//
buttonTakeOrderInWork.Location = new Point(1040, 136);
buttonTakeOrderInWork.Name = "buttonTakeOrderInWork";
buttonTakeOrderInWork.Size = new Size(202, 29);
buttonTakeOrderInWork.TabIndex = 2;
buttonTakeOrderInWork.Text = "Отдать на выполнение";
buttonTakeOrderInWork.UseVisualStyleBackColor = true;
buttonTakeOrderInWork.Click += ButtonTakeOrderInWork_Click;
//
// buttonOrderReady
//
buttonOrderReady.Location = new Point(1040, 184);
buttonOrderReady.Name = "buttonOrderReady";
buttonOrderReady.Size = new Size(202, 29);
buttonOrderReady.TabIndex = 3;
buttonOrderReady.Text = "Заказ готов";
buttonOrderReady.UseVisualStyleBackColor = true;
buttonOrderReady.Click += ButtonOrderReady_Click;
//
// buttonIssuedOrder
//
buttonIssuedOrder.Location = new Point(1040, 237);
buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(202, 29);
buttonIssuedOrder.TabIndex = 4;
buttonIssuedOrder.Text = "Заказ выдан";
buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
//
// buttonRef
//
buttonRef.Location = new Point(1040, 287);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(202, 29);
buttonRef.TabIndex = 5;
buttonRef.Text = "Обновить список";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// toolStrip1
//
toolStrip1.ImageScalingSize = new Size(20, 20);
toolStrip1.Items.AddRange(new ToolStripItem[] { toolStripLabel1, toolStripDropDownButton1 });
toolStrip1.Location = new Point(0, 0);
toolStrip1.Name = "toolStrip1";
toolStrip1.Size = new Size(1280, 27);
toolStrip1.TabIndex = 6;
toolStrip1.Text = "toolStrip1";
//
// toolStripLabel1
//
toolStripLabel1.DropDownItems.AddRange(new ToolStripItem[] { componentsToolStripMenuItem, snacksToolStripMenuItem, клиентыToolStripMenuItem });
toolStripLabel1.Name = "toolStripLabel1";
toolStripLabel1.Size = new Size(117, 24);
toolStripLabel1.Text = "Справочники";
//
// componentsToolStripMenuItem
//
componentsToolStripMenuItem.Name = "componentsToolStripMenuItem";
componentsToolStripMenuItem.Size = new Size(182, 26);
componentsToolStripMenuItem.Text = "Компоненты";
componentsToolStripMenuItem.Click += ComponentToolStripMenuItem_Click;
//
// snacksToolStripMenuItem
//
snacksToolStripMenuItem.Name = "snacksToolStripMenuItem";
snacksToolStripMenuItem.Size = new Size(182, 26);
snacksToolStripMenuItem.Text = "Закуски";
snacksToolStripMenuItem.Click += ProductToolStripMenuItem_Click;
//
// toolStripDropDownButton1
//
toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text;
toolStripDropDownButton1.DropDownItems.AddRange(new ToolStripItem[] { списокЗакусокToolStripMenuItem, закускиПоКомпонентамToolStripMenuItem, списокЗаказовToolStripMenuItem });
toolStripDropDownButton1.ImageTransparentColor = Color.Magenta;
toolStripDropDownButton1.Name = "toolStripDropDownButton1";
toolStripDropDownButton1.Size = new Size(73, 24);
toolStripDropDownButton1.Text = "Отчёты";
//
// списокЗакусокToolStripMenuItem
//
списокЗакусокToolStripMenuItem.Name = "списокЗакусокToolStripMenuItem";
списокЗакусокToolStripMenuItem.Size = new Size(267, 26);
списокЗакусокToolStripMenuItem.Text = "Список закусок";
списокЗакусокToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click;
//
// закускиПоКомпонентамToolStripMenuItem
//
закускиПоКомпонентамToolStripMenuItem.Name = акускиПоКомпонентамToolStripMenuItem";
закускиПоКомпонентамToolStripMenuItem.Size = new Size(267, 26);
закускиПоКомпонентамToolStripMenuItem.Text = "Закуски по компонентам";
закускиПоКомпонентамToolStripMenuItem.Click += ComponentSnacksToolStripMenuItem_Click;
//
// списокЗаказовToolStripMenuItem
//
списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem";
списокЗаказовToolStripMenuItem.Size = new Size(267, 26);
списокЗаказовToolStripMenuItem.Text = "Список заказов";
списокЗаказовToolStripMenuItem.Click += OrdersToolStripMenuItem_Click;
//
// клиентыToolStripMenuItem
//
клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
клиентыToolStripMenuItem.Size = new Size(182, 26);
клиентыToolStripMenuItem.Text = "Клиенты";
клиентыToolStripMenuItem.Click += ClientsToolStripMenuItem_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1280, 450);
Controls.Add(toolStrip1);
Controls.Add(buttonRef);
Controls.Add(buttonIssuedOrder);
Controls.Add(buttonOrderReady);
Controls.Add(buttonTakeOrderInWork);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Name = "FormMain";
Text = "Закусочная";
Load += FormMain_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
toolStrip1.ResumeLayout(false);
toolStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormMain));
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonIssuedOrder = new Button();
buttonRef = new Button();
toolStrip = new ToolStrip();
manualsToolStripLabel = new ToolStripDropDownButton();
componentsToolStripMenuItem = new ToolStripMenuItem();
snacksToolStripMenuItem = new ToolStripMenuItem();
clientsToolStripMenuItem = new ToolStripMenuItem();
исполнителиToolStripMenuItem = new ToolStripMenuItem();
manualsStripDropDownButton = new ToolStripDropDownButton();
listComponentsToolStripMenuItem = new ToolStripMenuItem();
componentSnacksToolStripMenuItem = new ToolStripMenuItem();
ordersToolStripMenuItem = new ToolStripMenuItem();
workWithClientsToolStripMenuItem = new ToolStripMenuItem();
toolStripDropDownButton1 = new ToolStripDropDownButton();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
toolStrip.SuspendLayout();
SuspendLayout();
//
// dataGridView
//
dataGridView.BackgroundColor = SystemColors.ButtonHighlight;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(0, 27);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(986, 421);
dataGridView.TabIndex = 0;
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(1040, 88);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(202, 29);
buttonCreateOrder.TabIndex = 1;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += ButtonCreateOrder_Click;
//
// buttonIssuedOrder
//
buttonIssuedOrder.Location = new Point(1040, 159);
buttonIssuedOrder.Name = "buttonIssuedOrder";
buttonIssuedOrder.Size = new Size(202, 29);
buttonIssuedOrder.TabIndex = 4;
buttonIssuedOrder.Text = "Заказ выдан";
buttonIssuedOrder.UseVisualStyleBackColor = true;
buttonIssuedOrder.Click += ButtonIssuedOrder_Click;
//
// buttonRef
//
buttonRef.Location = new Point(1040, 233);
buttonRef.Name = "buttonRef";
buttonRef.Size = new Size(202, 29);
buttonRef.TabIndex = 5;
buttonRef.Text = "Обновить список";
buttonRef.UseVisualStyleBackColor = true;
buttonRef.Click += ButtonRef_Click;
//
// toolStrip
//
toolStrip.ImageScalingSize = new Size(20, 20);
toolStrip.Items.AddRange(new ToolStripItem[] { manualsToolStripLabel, manualsStripDropDownButton, toolStripDropDownButton1 });
toolStrip.Location = new Point(0, 0);
toolStrip.Name = "toolStrip";
toolStrip.Size = new Size(1280, 27);
toolStrip.TabIndex = 6;
toolStrip.Text = "toolStrip1";
//
// manualsToolStripLabel
//
manualsToolStripLabel.DropDownItems.AddRange(new ToolStripItem[] { componentsToolStripMenuItem, snacksToolStripMenuItem, clientsToolStripMenuItem, исполнителиToolStripMenuItem });
manualsToolStripLabel.Name = "manualsToolStripLabel";
manualsToolStripLabel.Size = new Size(117, 24);
manualsToolStripLabel.Text = "Справочники";
//
// componentsToolStripMenuItem
//
componentsToolStripMenuItem.Name = "componentsToolStripMenuItem";
componentsToolStripMenuItem.Size = new Size(224, 26);
componentsToolStripMenuItem.Text = "Компоненты";
componentsToolStripMenuItem.Click += ComponentToolStripMenuItem_Click;
//
// snacksToolStripMenuItem
//
snacksToolStripMenuItem.Name = "snacksToolStripMenuItem";
snacksToolStripMenuItem.Size = new Size(224, 26);
snacksToolStripMenuItem.Text = "Закуски";
snacksToolStripMenuItem.Click += ProductToolStripMenuItem_Click;
//
// clientsToolStripMenuItem
//
clientsToolStripMenuItem.Name = "clientsToolStripMenuItem";
clientsToolStripMenuItem.Size = new Size(224, 26);
clientsToolStripMenuItem.Text = "Клиенты";
clientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click;
//
// исполнителиToolStripMenuItem
//
исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem";
исполнителиToolStripMenuItem.Size = new Size(224, 26);
исполнителиToolStripMenuItem.Text = "Исполнители";
исполнителиToolStripMenuItem.Click += ImplementersToolStripMenuItem_Click;
//
// manualsStripDropDownButton
//
manualsStripDropDownButton.DropDownItems.AddRange(new ToolStripItem[] { listComponentsToolStripMenuItem, componentSnacksToolStripMenuItem, ordersToolStripMenuItem });
manualsStripDropDownButton.Name = "manualsStripDropDownButton";
manualsStripDropDownButton.Size = new Size(73, 24);
manualsStripDropDownButton.Text = "Отчеты";
//
// listComponentsToolStripMenuItem
//
listComponentsToolStripMenuItem.Name = "listComponentsToolStripMenuItem";
listComponentsToolStripMenuItem.Size = new Size(267, 26);
listComponentsToolStripMenuItem.Text = "Список закусок";
listComponentsToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click;
//
// componentSnacksToolStripMenuItem
//
componentSnacksToolStripMenuItem.Name = "componentSnacksToolStripMenuItem";
componentSnacksToolStripMenuItem.Size = new Size(267, 26);
componentSnacksToolStripMenuItem.Text = "Закуски по компонентам";
componentSnacksToolStripMenuItem.Click += ComponentSnacksToolStripMenuItem_Click;
//
// ordersToolStripMenuItem
//
ordersToolStripMenuItem.Name = "ordersToolStripMenuItem";
ordersToolStripMenuItem.Size = new Size(267, 26);
ordersToolStripMenuItem.Text = "Список заказов";
ordersToolStripMenuItem.Click += OrdersToolStripMenuItem_Click;
//
// workWithClientsToolStripMenuItem
//
workWithClientsToolStripMenuItem.Name = "workWithClientsToolStripMenuItem";
workWithClientsToolStripMenuItem.Size = new Size(32, 19);
//
// toolStripDropDownButton1
//
toolStripDropDownButton1.DisplayStyle = ToolStripItemDisplayStyle.Text;
toolStripDropDownButton1.Image = (Image)resources.GetObject("toolStripDropDownButton1.Image");
toolStripDropDownButton1.ImageTransparentColor = Color.Magenta;
toolStripDropDownButton1.Name = "toolStripDropDownButton1";
toolStripDropDownButton1.Size = new Size(114, 24);
toolStripDropDownButton1.Text = "Запуск работ";
toolStripDropDownButton1.Click += WorkProcessToolStripDropDownButton1_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1280, 450);
Controls.Add(toolStrip);
Controls.Add(buttonRef);
Controls.Add(buttonIssuedOrder);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Name = "FormMain";
Text = "Закусочная";
Load += FormMain_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
toolStrip.ResumeLayout(false);
toolStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
#endregion
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonTakeOrderInWork;
private Button buttonOrderReady;
private Button buttonIssuedOrder;
private Button buttonRef;
private ToolStrip toolStrip1;
private ToolStripDropDownButton toolStripLabel1;
private ToolStripMenuItem componentsToolStripMenuItem;
private ToolStripMenuItem snacksToolStripMenuItem;
private ToolStripDropDownButton toolStripDropDownButton1;
private ToolStripMenuItem списокЗакусокToolStripMenuItem;
private ToolStripMenuItem закускиПоКомпонентамToolStripMenuItem;
private ToolStripMenuItem списокЗаказовToolStripMenuItem;
private ToolStripMenuItem клиентыToolStripMenuItem;
}
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonIssuedOrder;
private Button buttonRef;
private ToolStrip toolStrip;
private ToolStripDropDownButton manualsToolStripLabel;
private ToolStripMenuItem componentsToolStripMenuItem;
private ToolStripMenuItem snacksToolStripMenuItem;
private ToolStripDropDownButton manualsStripDropDownButton;
private ToolStripMenuItem listComponentsToolStripMenuItem;
private ToolStripMenuItem componentSnacksToolStripMenuItem;
private ToolStripMenuItem ordersToolStripMenuItem;
private ToolStripMenuItem workWithClientsToolStripMenuItem;
private ToolStripMenuItem clientsToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem;
private ToolStripDropDownButton toolStripDropDownButton1;
}
}

View File

@ -5,205 +5,159 @@ using Microsoft.Extensions.Logging;
namespace Diner
{
public partial class FormMain : Form
{
private readonly ILogger _logger;
public partial class FormMain : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
private readonly IOrderLogic _orderLogic;
private readonly IReportLogic _reportLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic, IReportLogic reportLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
_reportLogic = reportLogic;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
// прописать логику
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["SnackId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["SnackName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ComponentToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
if (service is FormComponents form)
{
form.ShowDialog();
}
}
private void ProductToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSnacks));
if (service is FormSnacks form)
{
form.ShowDialog();
}
}
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
}
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,
SnackId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value),
SnackName = dataGridView.SelectedRows[0].Cells["SnackName"].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.FinishOrder(new OrderBindingModel
{
Id = id,
SnackId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value),
SnackName = dataGridView.SelectedRows[0].Cells["SnackName"].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)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'", id);
try
{
var operationResult = _orderLogic.DeliveryOrder(new OrderBindingModel
{
Id = id,
SnackId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value),
SnackName = dataGridView.SelectedRows[0].Cells["SnackName"].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)
{
LoadData();
}
private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveComponentsToWordFile(new ReportBindingModel { FileName = dialog.FileName });
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private readonly 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)
{
LoadData();
}
private void LoadData()
{
// прописать логику
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["SnackId"].Visible = false;
dataGridView.Columns["ImplementerId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["SnackName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ClientFIO"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ComponentToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
if (service is FormComponents form)
{
form.ShowDialog();
}
}
private void ProductToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSnacks));
if (service is FormSnacks form)
{
form.ShowDialog();
}
}
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
}
private void ButtonIssuedOrder_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
});
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)
{
LoadData();
}
private void ComponentsToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
if (dialog.ShowDialog() == DialogResult.OK)
{
_reportLogic.SaveComponentsToWordFile(new ReportBindingModel { FileName = dialog.FileName });
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void ComponentSnacksToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportSnackComponents));
if (service is FormReportSnackComponents form)
{
form.ShowDialog();
}
}
private void ComponentSnacksToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportSnackComponents));
if (service is FormReportSnackComponents form)
{
form.ShowDialog();
}
}
private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (service is FormReportOrders form)
{
form.ShowDialog();
}
}
private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClients));
private void OrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReportOrders));
if (service is FormReportOrders form)
{
form.ShowDialog();
}
}
private void ClientsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClients));
if (service is FormClients form)
{
form.ShowDialog();
}
}
}
if (service is FormClients form)
{
form.ShowDialog();
}
}
private void ImplementersToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormImplementers));
if (service is FormImplementers form)
{
form.ShowDialog();
}
}
private void WorkProcessToolStripDropDownButton1_Click(object sender, EventArgs e)
{
_workProcess.DoWork((Program.ServiceProvider?.GetService(typeof(IImplementerLogic)) as IImplementerLogic)!, _orderLogic);
MessageBox.Show("Процесс обработки запущен", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}

View File

@ -1,64 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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">
@ -117,7 +57,19 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="toolStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<metadata name="toolStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<assembly alias="System.Drawing" name="System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<data name="toolStripDropDownButton1.Image" type="System.Drawing.Bitmap, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>
iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8
YQUAAAAJcEhZcwAAEnQAABJ0Ad5mH3gAAAEISURBVEhL3ZErDsJAGIR7DlA47oArV8CDR9RiSDAQPBcA
Qx1BgUMQBEk1ooJAKE0I4Wlqf5gmu1n6oqW7hiZfthkx33aqeZ5HKvEFpmmSYRhSQScXINB1XSroDAke
96cUpAmupyPZsx7Z8x4drAnPpQmsgU7LdoHDJNIEYjnAlyBXJ3jPhVyaYLca8nLMhX+CPJXAOT+ouTj5
p5in4asApdWpS8XRwT+zShIFG/fOyxlZJbGC9f5G5bHzUf6LJFJQqTViyxlxEmRiHhLUW10qDbeRpUGC
ErwjE/OQoG9dIsviYGWsXMwxc24BYLcO5pgZc+cWJIG5MbsyAUDnHwlUAkFHJZraR9NeMVq3zi+WF/0A
AAAASUVORK5CYII=
</value>
</data>
</root>

View File

@ -40,11 +40,16 @@ namespace Diner
services.AddTransient<IComponentStorage, DinerDataBaseImplement.Implements.ComponentStorage>();
services.AddTransient<IOrderStorage, DinerDataBaseImplement.Implements.OrderStorage>();
services.AddTransient<ISnackStorage, DinerDataBaseImplement.Implements.SnackStorage>();
services.AddTransient<IImplementerStorage, DinerDataBaseImplement.Implements.ImplementerStorage>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<ISnackLogic, SnackLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
@ -60,6 +65,8 @@ namespace Diner
services.AddTransient<FormReportSnackComponents>();
services.AddTransient<FormReportOrders>();
services.AddTransient<FormClients>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormImplementer>();
}
}
}

View File

@ -9,7 +9,7 @@ namespace DinerDataBaseImplement
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=localhost\SQLEXPRESS01;Initial Catalog=DinerDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
optionsBuilder.UseSqlServer(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=DinerDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
@ -18,5 +18,6 @@ namespace DinerDataBaseImplement
public virtual DbSet<SnackComponent> SnackComponents { set; get; }
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,122 @@
using DinerContracts.BindingModels;
using DinerContracts.SearchModels;
using DinerContracts.StoragesContracts;
using DinerContracts.ViewModels;
using DinerDataBaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace DinerDataBaseImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
public List<ImplementerViewModel> GetFullList()
{
using var context = new DinerDatabase();
return context.Implementers
.Include(x => x.Orders)
.Select(x => x.GetViewModel)
.ToList();
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
if (string.IsNullOrEmpty(model.ImplementerFIO))
{
return new();
}
using var context = new DinerDatabase();
return context.Implementers
.Include(x => x.Orders)
.Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
using var context = new DinerDatabase();
if (model.Id.HasValue)
{
return context.Implementers
.Include(x => x.Orders)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
}
else if (!string.IsNullOrEmpty(model.ImplementerFIO) && !string.IsNullOrEmpty(model.Password))
{
return context.Implementers
.Include(x => x.Orders)
.FirstOrDefault(x => (x.ImplementerFIO == model.ImplementerFIO && x.Password == model.Password))
?.GetViewModel;
}
return new();
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
var newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
using var context = new DinerDatabase();
context.Implementers.Add(newImplementer);
context.SaveChanges();
return context.Implementers
.Include(x => x.Orders)
.FirstOrDefault(x => x.Id == newImplementer.Id)
?.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
using var context = new DinerDatabase();
var order = context.Implementers
.Include(x => x.Orders)
.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return context.Implementers
.Include(x => x.Orders)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
using var context = new DinerDatabase();
var element = context.Implementers
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
var deletedElement = context.Implementers
.Include(x => x.Orders)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
context.Implementers.Remove(element);
context.SaveChanges();
return deletedElement;
}
return null;
}
}
}

View File

@ -4,11 +4,7 @@ using DinerContracts.StoragesContracts;
using DinerContracts.ViewModels;
using DinerDataBaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DinerDataBaseImplement.Implements
{
@ -21,6 +17,7 @@ namespace DinerDataBaseImplement.Implements
return context.Orders
.Include(x => x.Snack)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Select(x => x.GetViewModel)
.ToList();
}
@ -32,6 +29,7 @@ namespace DinerDataBaseImplement.Implements
return context.Orders
.Include(x => x.Snack)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo)
.Select(x => x.GetViewModel)
.ToList();
@ -41,6 +39,7 @@ namespace DinerDataBaseImplement.Implements
return context.Orders
.Include(x => x.Snack)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
@ -50,12 +49,29 @@ namespace DinerDataBaseImplement.Implements
return context.Orders
.Include(x => x.Snack)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => x.ClientId == model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
}
else if (model.ImplementerId.HasValue)
{
return context.Orders
.Include(x => x.Snack)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => x.ImplementerId == model.ImplementerId)
.Select(x => x.GetViewModel)
.ToList();
}
return new();
return context.Orders
.Include(x => x.Snack)
.Include(x => x.Client)
.Include(x => x.Implementer)
.Where(x => model.Status == x.Status)
.Select(x => x.GetViewModel)
.ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{

View File

@ -12,8 +12,8 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace DinerDataBaseImplement.Migrations
{
[DbContext(typeof(DinerDatabase))]
[Migration("20240402095625_Init")]
partial class Init
[Migration("20240429190440_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -70,6 +70,33 @@ namespace DinerDataBaseImplement.Migrations
b.ToTable("Components");
});
modelBuilder.Entity("DinerDataBaseImplement.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("DinerDataBaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -90,6 +117,9 @@ namespace DinerDataBaseImplement.Migrations
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("SnackId")
.HasColumnType("int");
@ -103,6 +133,8 @@ namespace DinerDataBaseImplement.Migrations
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("SnackId");
b.ToTable("Orders");
@ -162,6 +194,10 @@ namespace DinerDataBaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DinerDataBaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("DinerDataBaseImplement.Models.Snack", "Snack")
.WithMany("Orders")
.HasForeignKey("SnackId")
@ -170,6 +206,8 @@ namespace DinerDataBaseImplement.Migrations
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Snack");
});
@ -202,6 +240,11 @@ namespace DinerDataBaseImplement.Migrations
b.Navigation("SnackComponents");
});
modelBuilder.Entity("DinerDataBaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("DinerDataBaseImplement.Models.Snack", b =>
{
b.Navigation("Components");

View File

@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Migrations;
namespace DinerDataBaseImplement.Migrations
{
/// <inheritdoc />
public partial class Init : Migration
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
@ -40,6 +40,22 @@ namespace DinerDataBaseImplement.Migrations
table.PrimaryKey("PK_Components", 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: "Snacks",
columns: table => new
@ -61,6 +77,7 @@ namespace DinerDataBaseImplement.Migrations
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ClientId = table.Column<int>(type: "int", nullable: false),
ImplementerId = table.Column<int>(type: "int", nullable: true),
SnackId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false),
Sum = table.Column<double>(type: "float", nullable: false),
@ -77,6 +94,11 @@ namespace DinerDataBaseImplement.Migrations
principalTable: "Clients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Orders_Implementers_ImplementerId",
column: x => x.ImplementerId,
principalTable: "Implementers",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Orders_Snacks_SnackId",
column: x => x.SnackId,
@ -117,6 +139,11 @@ namespace DinerDataBaseImplement.Migrations
table: "Orders",
column: "ClientId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ImplementerId",
table: "Orders",
column: "ImplementerId");
migrationBuilder.CreateIndex(
name: "IX_Orders_SnackId",
table: "Orders",
@ -145,6 +172,9 @@ namespace DinerDataBaseImplement.Migrations
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "Implementers");
migrationBuilder.DropTable(
name: "Components");

View File

@ -67,6 +67,33 @@ namespace DinerDataBaseImplement.Migrations
b.ToTable("Components");
});
modelBuilder.Entity("DinerDataBaseImplement.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("DinerDataBaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -87,6 +114,9 @@ namespace DinerDataBaseImplement.Migrations
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("SnackId")
.HasColumnType("int");
@ -100,6 +130,8 @@ namespace DinerDataBaseImplement.Migrations
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("SnackId");
b.ToTable("Orders");
@ -159,6 +191,10 @@ namespace DinerDataBaseImplement.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("DinerDataBaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("DinerDataBaseImplement.Models.Snack", "Snack")
.WithMany("Orders")
.HasForeignKey("SnackId")
@ -167,6 +203,8 @@ namespace DinerDataBaseImplement.Migrations
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Snack");
});
@ -199,6 +237,11 @@ namespace DinerDataBaseImplement.Migrations
b.Navigation("SnackComponents");
});
modelBuilder.Entity("DinerDataBaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("DinerDataBaseImplement.Models.Snack", b =>
{
b.Navigation("Components");

View File

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

View File

@ -13,6 +13,7 @@ namespace DinerDataBaseImplement.Models
public int Id { get; private set; }
[Required]
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
[Required]
public int SnackId { get; private set; }
[Required]
@ -28,6 +29,7 @@ namespace DinerDataBaseImplement.Models
public virtual Snack Snack { get; set; }
public virtual Client Client { get; set; }
public virtual Implementer? Implementer { get; private set; }
public static Order? Create(OrderBindingModel? model)
{
if (model == null)
@ -39,6 +41,7 @@ namespace DinerDataBaseImplement.Models
Id = model.Id,
SnackId = model.SnackId,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
@ -52,22 +55,26 @@ namespace DinerDataBaseImplement.Models
{
return;
}
Sum = model.Sum;
if (model.Sum != 0)
Sum = model.Sum;
Status = model.Status;
DateImplement = model.DateImplement;
ImplementerId = model.ImplementerId;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
SnackId = SnackId,
ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
SnackName = Snack.SnackName,
ClientFIO = Client.ClientFIO
ClientFIO = Client.ClientFIO,
ImplementerFIO = Implementer?.ImplementerFIO
};
}
}

View File

@ -10,10 +10,12 @@ namespace DinerFileImplement
private readonly string OrderFileName = "Order.xml";
private readonly string ProductFileName = "Snack.xml";
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; }
public List<Snack> Snacks { get; private set; }
public List<Client> Clients { get; private set; }
public List<Implementer> Implementers { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
@ -26,12 +28,14 @@ namespace DinerFileImplement
public void SaveSnacks() => SaveData(Snacks, ProductFileName, "Snacks", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, ClientFileName, "Clients", x => x.GetXElement);
public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Snacks = LoadData(ProductFileName, "Snack", x => Snack.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Clients = LoadData(OrderFileName, "Order", x => Client.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{

View File

@ -0,0 +1,85 @@
using DinerContracts.BindingModels;
using DinerContracts.SearchModels;
using DinerContracts.StoragesContracts;
using DinerContracts.ViewModels;
using DinerFileImplement.Models;
namespace DinerFileImplement.Implements
{
public class ImplementerStorage : IImplementerStorage
{
private readonly DataFileSingleton source;
public ImplementerStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ImplementerViewModel> GetFullList()
{
return source.Implementers.Select(x => x.GetViewModel).ToList();
}
public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{
return source.Implementers.Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return source.Implementers.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public ImplementerViewModel? Insert(ImplementerBindingModel model)
{
model.Id = source.Implementers.Count > 0 ? source.Implementers.Max(x => x.Id) + 1 : 1;
var newImplementer = Implementer.Create(model);
if (newImplementer == null)
{
return null;
}
source.Implementers.Add(newImplementer);
source.SaveImplementers();
return newImplementer.GetViewModel;
}
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
var implementer = source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (implementer == null)
{
return null;
}
implementer.Update(model);
source.SaveImplementers();
return implementer.GetViewModel;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
var element = source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Implementers.Remove(element);
source.SaveImplementers();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -57,6 +57,13 @@ namespace DinerFileImplement.Implements
.Select(x => AttachSnackName(x.GetViewModel))
.ToList();
}
else if (model.ImplementerId.HasValue)
{
return source.Orders
.Where(x => x.ImplementerId == model.ImplementerId)
.Select(x => AttachSnackName(x.GetViewModel))
.ToList();
}
return new();
}
@ -98,6 +105,7 @@ namespace DinerFileImplement.Implements
}
var snack = source.Snacks.FirstOrDefault(x => x.Id == model.SnackId);
var client = source.Clients.FirstOrDefault(x => x.Id == model.ClientId);
var implementer = source.Implementers.FirstOrDefault(x => x.Id == model.ImplementerId);
if (snack != null)
{
model.SnackName = snack.SnackName;
@ -106,6 +114,10 @@ namespace DinerFileImplement.Implements
{
model.ClientFIO = client.ClientFIO;
}
if (implementer != null)
{
model.ImplementerFIO = implementer.ImplementerFIO;
}
return model;
}
}

View File

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

View File

@ -2,6 +2,7 @@
using DinerContracts.ViewModels;
using DinerDataModels.Enum;
using DinerDataModels.Models;
using System.Reflection;
using System.Xml.Linq;
namespace DinerFileImplement.Models
@ -11,6 +12,7 @@ namespace DinerFileImplement.Models
public int Id { get; private set; }
public int SnackID { get; private set; }
public int ClientId { get; private set; }
public int? ImplementerId { get; private set; }
public int Count { get; private set; }
@ -32,6 +34,7 @@ namespace DinerFileImplement.Models
Id = model.Id,
SnackID = model.SnackId,
ClientId = model.ClientId,
ImplementerId = model.ImplementerId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
@ -50,6 +53,7 @@ namespace DinerFileImplement.Models
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
SnackID = Convert.ToInt32(element.Element("SnackID")!.Value),
ClientId = Convert.ToInt32(element.Element("ClientId")!.Value),
ImplementerId = Convert.ToInt32(element.Element("ImplementerId")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value),
@ -74,6 +78,7 @@ namespace DinerFileImplement.Models
Id = Id,
SnackId = SnackID,
ClientId = ClientId,
ImplementerId = ImplementerId,
Count = Count,
Sum = Sum,
Status = Status,
@ -84,6 +89,7 @@ namespace DinerFileImplement.Models
new XAttribute("Id", Id),
new XElement("SnackID", SnackID.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

@ -0,0 +1,112 @@
using DinerContracts.BindingModels;
using DinerContracts.BusinessLogicsContracts;
using DinerContracts.SearchModels;
using DinerContracts.ViewModels;
using DinerDataModels.Enum;
using Microsoft.AspNetCore.Mvc;
namespace DinerRestApi.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

@ -10,11 +10,12 @@ builder.Logging.SetMinimumLevel(LogLevel.Trace);
builder.Logging.AddLog4Net("log4net.config");
// Add services to the container.
builder.Services.AddTransient<IImplementerStorage, ImplementerStorage>();
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<ISnackStorage, SnackStorage>();
builder.Services.AddTransient<IImplementerLogic, ImplementerLogic>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<ISnackLogic, SnackLogic>();