This commit is contained in:
Вячеслав Иванов 2024-04-02 21:27:34 +04:00
parent c67efaf03c
commit 1733ff3820
10 changed files with 294 additions and 179 deletions

View File

@ -105,9 +105,9 @@ namespace PizzeriaBusinessLogic.BusinessLogics
{ {
throw new ArgumentNullException("Не указан правильный пароль", nameof(model.Password)); throw new ArgumentNullException("Не указан правильный пароль", nameof(model.Password));
} }
_logger.LogInformation("Client. ClientFIO:{ClientFIO}.Email:{Email}.Id:{Id}", _logger.LogInformation("Client. ClientFIO:{ClientFIO}.Email:{Email}.Id:{Id}",
model.ClientFIO, model.Email, model.Id); model.ClientFIO, model.Email, model.Id);
var element = _clientStorage.GetElement(new ClientSearchModel var element = _clientStorage.GetElement(new ClientSearchModel
{ {
ClientFIO = model.ClientFIO ClientFIO = model.ClientFIO
}); });

View File

@ -14,14 +14,14 @@ namespace PizzeriaBusinessLogic.BusinessLogics
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage; private readonly IOrderStorage _orderStorage;
private readonly AbstractMailWorker _mailWorker; private readonly AbstractMailWorker _mailWorker;
static readonly object _locker = new object(); static readonly object _locker = new object();
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker) public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker)
{ {
_logger = logger; _logger = logger;
_orderStorage = orderStorage; _orderStorage = orderStorage;
_mailWorker = mailWorker; _mailWorker = mailWorker;
} }
public OrderViewModel? ReadElement(OrderSearchModel model) public OrderViewModel? ReadElement(OrderSearchModel model)
{ {
@ -61,19 +61,19 @@ namespace PizzeriaBusinessLogic.BusinessLogics
if (model.Status != OrderStatus.Неизвестен) if (model.Status != OrderStatus.Неизвестен)
return false; return false;
model.Status = OrderStatus.Принят; model.Status = OrderStatus.Принят;
var element = _orderStorage.Insert(model); var element = _orderStorage.Insert(model);
if (element == null) if (element == null)
{ {
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Insert operation failed");
return false; return false;
} }
Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel
{ {
MailAddress = element.ClientEmail, MailAddress = element.ClientEmail,
Subject = $"Изменение статуса заказа номер {element.Id}", Subject = $"Изменение статуса заказа номер {element.Id}",
Text = $"Ваш заказ номер {element.Id} на пиццу {element.PizzaName} от {element.DateCreate} на сумму {element.Sum} принят." Text = $"Ваш заказ номер {element.Id} на пиццу {element.PizzaName} от {element.DateCreate} на сумму {element.Sum} принят."
})); }));
return true; return true;
} }
public bool TakeOrderInWork(OrderBindingModel model) public bool TakeOrderInWork(OrderBindingModel model)
@ -154,14 +154,14 @@ namespace PizzeriaBusinessLogic.BusinessLogics
_logger.LogWarning("Update operation failed"); _logger.LogWarning("Update operation failed");
return false; return false;
} }
string DateInfo = model.DateImplement.HasValue ? $"Дата выполнения {model.DateImplement}" : ""; string DateInfo = model.DateImplement.HasValue ? $"Дата выполнения {model.DateImplement}" : "";
Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel
{ {
MailAddress = element.ClientEmail, MailAddress = element.ClientEmail,
Subject = $"Изменение статуса заказа номер {element.Id}", Subject = $"Изменение статуса заказа номер {element.Id}",
Text = $"Ваш заказ номер {element.Id} на пиццу {element.PizzaName} от {element.DateCreate} на сумму {element.Sum} {model.Status}. {DateInfo}" Text = $"Ваш заказ номер {element.Id} на пиццу {element.PizzaName} от {element.DateCreate} на сумму {element.Sum} {model.Status}. {DateInfo}"
})); }));
return true; return true;
} }
_logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus); _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus);
throw new InvalidOperationException($"Невозможно приствоить статус {requiredStatus} заказу с текущим статусом {model.Status}"); throw new InvalidOperationException($"Невозможно приствоить статус {requiredStatus} заказу с текущим статусом {model.Status}");

View File

@ -1,158 +1,168 @@
using Microsoft.AspNetCore.Mvc; using PizzeriaDataModels.Enums;
using PizzeriaClientApp.Models;
using PizzeriaContracts.BindingModels; using PizzeriaContracts.BindingModels;
using PizzeriaContracts.BusinessLogicsContracts;
using PizzeriaContracts.SearchModels;
using PizzeriaContracts.StoragesContracts;
using PizzeriaContracts.ViewModels; using PizzeriaContracts.ViewModels;
using System.Diagnostics; using PizzeriaBusinessLogic.MailWorker;
using Microsoft.Extensions.Logging;
namespace PizzeriaClientApp.Controllers namespace PizzeriaBusinessLogic.BusinessLogics
{ {
public class HomeController : Controller public class OrderLogic : IOrderLogic
{ {
private readonly ILogger<HomeController> _logger; private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
public HomeController(ILogger<HomeController> logger) private readonly AbstractMailWorker _mailWorker;
static readonly object _locker = new object();
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker)
{ {
_logger = logger; _logger = logger;
_orderStorage = orderStorage;
_mailWorker = mailWorker;
} }
public IActionResult Index() public OrderViewModel? ReadElement(OrderSearchModel model)
{ {
if (APIClient.Client == null) if (model == null)
{ {
return Redirect("~/Home/Enter"); throw new ArgumentNullException(nameof(model));
} }
return View(APIClient.GetRequest<List<OrderViewModel>>($"api/main/getorders?clientId={APIClient.Client.Id}")); _logger.LogInformation("ReadElement. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}",
model.ClientId, model.Status, model.ImplementerId, model.DateFrom, model.DateTo, 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;
} }
[HttpGet] public List<OrderViewModel>? ReadList(OrderSearchModel? model)
public IActionResult Privacy()
{ {
if (APIClient.Client == null) _logger.LogInformation("ReadList. ClientId:{ClientId}.Status:{Status}.ImplementerId:{ImplementerId}.DateFrom:{DateFrom}.DateTo:{DateTo}OrderId:{Id}",
model?.ClientId, model?.Status, model?.ImplementerId, model?.DateFrom, model?.DateTo, model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null)
{ {
return Redirect("~/Home/Enter"); _logger.LogWarning("ReadList return null list");
return null;
} }
return View(APIClient.Client); _logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
} }
[HttpPost] public bool CreateOrder(OrderBindingModel model)
public void Privacy(string login, string password, string fio)
{ {
if (APIClient.Client == null) CheckModel(model);
if (model.Status != OrderStatus.Неизвестен)
return false;
model.Status = OrderStatus.Принят;
var element = _orderStorage.Insert(model);
if (element == null)
{ {
throw new Exception("Вы как суда попали? Суда вход только авторизованным"); _logger.LogWarning("Insert operation failed");
return false;
} }
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio)) Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel
{ {
throw new Exception("Введите логин, пароль и ФИО"); MailAddress = element.ClientEmail,
Subject = $"Изменение статуса заказа номер {element.Id}",
Text = $"Ваш заказ номер {element.Id} на пиццу {element.PizzaName} от {element.DateCreate} на сумму {element.Sum} принят."
}));
return true;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
lock (_locker)
{
return ChangeStatus(model, OrderStatus.Выполняется);
} }
APIClient.PostRequest("api/client/updatedata", new ClientBindingModel }
public bool FinishOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Готов);
}
public bool DeliveryOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выдан);
}
private void CheckModel(OrderBindingModel model, bool withParams = true)
{
if (model == null)
{ {
Id = APIClient.Client.Id, throw new ArgumentNullException(nameof(model));
ClientFIO = fio, }
Email = login, if (!withParams)
Password = password {
return;
}
if (model.Count <= 0)
{
throw new ArgumentException("Колличество пиццы в заказе не может быть меньше 1", nameof(model.Count));
}
if (model.Sum <= 0)
{
throw new ArgumentException("Стоимость заказа на может быть меньше 1", nameof(model.Sum));
}
if (model.DateImplement.HasValue && model.DateImplement < model.DateCreate)
{
throw new ArithmeticException($"Дата выдачи заказа {model.DateImplement} не может быть раньше даты его создания {model.DateCreate}");
}
_logger.LogInformation("Pizza. PizzaId:{PizzaId}.Count:{Count}.Sum:{Sum}Id:{Id}",
model.PizzaId, model.Count, model.Sum, model.Id);
}
private bool ChangeStatus(OrderBindingModel model, OrderStatus requiredStatus)
{
CheckModel(model, false);
var element = _orderStorage.GetElement(new OrderSearchModel()
{
Id = model.Id
}); });
if (element == null)
APIClient.Client.ClientFIO = fio;
APIClient.Client.Email = login;
APIClient.Client.Password = password;
Response.Redirect("Index");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
[HttpGet]
public IActionResult Enter()
{
return View();
}
[HttpPost]
public void Enter(string login, string password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{ {
throw new Exception("Введите логин и пароль"); throw new InvalidOperationException(nameof(element));
} }
APIClient.Client = APIClient.GetRequest<ClientViewModel>($"api/client/login?login={login}&password={password}"); model.DateCreate = element.DateCreate;
if (APIClient.Client == null) model.PizzaId = element.PizzaId;
model.DateImplement = element.DateImplement;
model.ClientId = element.ClientId;
if (!model.ImplementerId.HasValue)
{ {
throw new Exception("Неверный логин/пароль"); model.ImplementerId = element.ImplementerId;
} }
Response.Redirect("Index"); model.Status = element.Status;
} model.Count = element.Count;
model.Sum = element.Sum;
[HttpGet] if (requiredStatus - model.Status == 1)
public IActionResult Register()
{
return View();
}
[HttpPost]
public void Register(string login, string password, string fio)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{ {
throw new Exception("Введите логин, пароль и ФИО"); model.Status = requiredStatus;
if (model.Status == OrderStatus.Готов)
{
model.DateImplement = DateTime.Now;
}
if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
string DateInfo = model.DateImplement.HasValue ? $"Дата выполнения {model.DateImplement}" : "";
Task.Run(() => _mailWorker.MailSendAsync(new MailSendInfoBindingModel
{
MailAddress = element.ClientEmail,
Subject = $"Изменение статуса заказа номер {element.Id}",
Text = $"Ваш заказ номер {element.Id} на пиццу {element.PizzaName} от {element.DateCreate} на сумму {element.Sum} {model.Status}. {DateInfo}"
}));
return true;
} }
APIClient.PostRequest("api/client/register", new ClientBindingModel _logger.LogWarning("Changing status operation faled: Current-{Status}:required-{requiredStatus}.", model.Status, requiredStatus);
{ throw new InvalidOperationException($"Невозможно приствоить статус {requiredStatus} заказу с текущим статусом {model.Status}");
ClientFIO = fio,
Email = login,
Password = password
});
Response.Redirect("Enter");
return;
} }
}
[HttpGet]
public IActionResult Create()
{
ViewBag.Pizzas = APIClient.GetRequest<List<PizzaViewModel>>("api/main/getpizzalist");
return View();
}
[HttpPost]
public void Create(int pizza, int count)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (count <= 0)
{
throw new Exception("Количество и сумма должны быть больше 0");
}
APIClient.PostRequest("api/main/createorder", new OrderBindingModel
{
ClientId = APIClient.Client.Id,
PizzaId = pizza,
Count = count,
Sum = Calc(count, pizza)
});
Response.Redirect("Index");
}
[HttpPost]
public double Calc(int count, int pizza)
{
var piz = APIClient.GetRequest<PizzaViewModel>($"api/main/getpizza?pizzaId={pizza}");
return count * (piz?.Price ?? 1);
}
[HttpGet]
public IActionResult Mails()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<MessageInfoViewModel>>($"api/client/getmessages?clientId={APIClient.Client.Id}"));
}
}
} }

View File

@ -11,6 +11,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\PizzeriaBusinessLogic\PizzeriaBusinessLogic.csproj" />
<ProjectReference Include="..\PizzeriaContracts\PizzeriaContracts.csproj" /> <ProjectReference Include="..\PizzeriaContracts\PizzeriaContracts.csproj" />
</ItemGroup> </ItemGroup>

View File

@ -19,9 +19,9 @@ namespace PizzeriaContracts.ViewModels
[DisplayName("ФИО клиента")] [DisplayName("ФИО клиента")]
public string ClientFIO { get; set; } = string.Empty; public string ClientFIO { get; set; } = string.Empty;
public string ClientEmail { get; set; } = string.Empty; public string ClientEmail { get; set; } = string.Empty;
public int? ImplementerId { get; set; } public int? ImplementerId { get; set; }
[DisplayName("Исполнитель")] [DisplayName("Исполнитель")]
public string? ImplementerFIO { get; set; } = null; public string? ImplementerFIO { get; set; } = null;

View File

@ -31,10 +31,10 @@ namespace PizzeriaDatabaseImplement.Implements
return null; return null;
} }
using var context = new PizzeriaDatabase(); using var context = new PizzeriaDatabase();
return context.Clients.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) || return context.Clients.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) ||
(!string.IsNullOrEmpty(model.ClientFIO) && x.ClientFIO == model.ClientFIO) || (!string.IsNullOrEmpty(model.ClientFIO) && x.ClientFIO == model.ClientFIO) ||
(!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && (string.IsNullOrEmpty(model.Password) || x.Password == model.Password)))?.GetViewModel; (!string.IsNullOrEmpty(model.Email) && x.Email == model.Email && (string.IsNullOrEmpty(model.Password) || x.Password == model.Password)))?.GetViewModel;
} }
public ClientViewModel? Insert(ClientBindingModel model) public ClientViewModel? Insert(ClientBindingModel model)
{ {

View File

@ -74,8 +74,8 @@ namespace PizzeriaDatabaseImplement.Models
Id = Id, Id = Id,
ClientId = ClientId, ClientId = ClientId,
ClientFIO = Client.ClientFIO, ClientFIO = Client.ClientFIO,
ClientEmail = Client.Email, ClientEmail = Client.Email,
PizzaId = PizzaId, PizzaId = PizzaId,
PizzaName = Pizza.PizzaName, PizzaName = Pizza.PizzaName,
ImplementerId = ImplementerId, ImplementerId = ImplementerId,
ImplementerFIO = Implementer != null ? Implementer.ImplementerFIO : null, ImplementerFIO = Implementer != null ? Implementer.ImplementerFIO : null,

View File

@ -19,6 +19,6 @@ namespace PizzeriaDatabaseImplement
public virtual DbSet<Order> Orders { set; get; } public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Client> Clients { set; get; } public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; } public virtual DbSet<Implementer> Implementers { set; get; }
public virtual DbSet<MessageInfo> MessageInfos { set; get; } public virtual DbSet<MessageInfo> MessageInfos { set; get; }
} }
} }

View File

@ -6,43 +6,89 @@ using PizzeriaFileImplement.Models;
namespace PizzeriaFileImplement.Implements namespace PizzeriaFileImplement.Implements
{ {
public class MessageInfoStorage : IMessageInfoStorage public class ImplementerStorage : IImplementerStorage
{ {
private readonly DataFileSingleton _source; private readonly DataFileSingleton _source;
public MessageInfoStorage() public ImplementerStorage()
{ {
_source = DataFileSingleton.GetInstance(); _source = DataFileSingleton.GetInstance();
} }
public List<MessageInfoViewModel> GetFullList() public List<ImplementerViewModel> GetFullList()
{ {
return _source.Messages.Select(x => x.GetViewModel).ToList(); return _source.Implementers.Select(x => x.GetViewModel).ToList();
} }
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model) public List<ImplementerViewModel> GetFilteredList(ImplementerSearchModel model)
{ {
return _source.Messages.Where(x => x.ClientId == model.ClientId).Select(x => x.GetViewModel).ToList(); if (model == null)
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
if (model.MessageId != null)
{ {
return _source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; return new();
}
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
if (model.ImplementerFIO != null)
{
return _source.Implementers
.Where(x => x.ImplementerFIO.Equals(model.ImplementerFIO))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
public ImplementerViewModel? GetElement(ImplementerSearchModel model)
{
if (model.Id.HasValue)
{
return _source.Implementers.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
if (model.ImplementerFIO != null && model.Password != null)
{
return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO) && x.Password.Equals(model.Password))?.GetViewModel;
}
if (model.ImplementerFIO != null)
{
return _source.Implementers.FirstOrDefault(x => x.ImplementerFIO.Equals(model.ImplementerFIO))?.GetViewModel;
} }
return null; return null;
} }
public MessageInfoViewModel? Insert(MessageInfoBindingModel model) public ImplementerViewModel? Insert(ImplementerBindingModel model)
{ {
var newMessage = MessageInfo.Create(model); model.Id = _source.Implementers.Count > 0 ? _source.Implementers.Max(x => x.Id) + 1 : 1;
if (newMessage == null) var res = Implementer.Create(model);
if (res != null)
{ {
return null; _source.Implementers.Add(res);
_source.SaveImplementers();
} }
_source.Messages.Add(newMessage); return res?.GetViewModel;
_source.SaveMessages(); }
return newMessage.GetViewModel;
public ImplementerViewModel? Update(ImplementerBindingModel model)
{
var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
res.Update(model);
_source.SaveImplementers();
}
return res?.GetViewModel;
}
public ImplementerViewModel? Delete(ImplementerBindingModel model)
{
var res = _source.Implementers.FirstOrDefault(x => x.Id == model.Id);
if (res != null)
{
_source.Implementers.Remove(res);
_source.SaveImplementers();
}
return res?.GetViewModel;
} }
} }
} }

View File

@ -0,0 +1,58 @@
using PizzeriaContracts.BindingModels;
using PizzeriaContracts.SearchModels;
using PizzeriaContracts.StoragesContracts;
using PizzeriaContracts.ViewModels;
using PizzeriaFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PizzeriaFileImplement.Implements
{
public class MessageInfoStorage : IMessageInfoStorage
{
private readonly DataFileSingleton _source;
public MessageInfoStorage()
{
_source = DataFileSingleton.GetInstance();
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
if (model.MessageId != null)
{
return _source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel;
}
return null;
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
return _source.Messages
.Where(x => x.ClientId == model.ClientId)
.Select(x => x.GetViewModel)
.ToList();
}
public List<MessageInfoViewModel> GetFullList()
{
return _source.Messages
.Select(x => x.GetViewModel)
.ToList();
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
var newMessage = MessageInfo.Create(model);
if (newMessage == null)
{
return null;
}
_source.Messages.Add(newMessage);
_source.SaveMessages();
return newMessage.GetViewModel;
}
}
}