сырок сырочек что же с тобой сделали..............

This commit is contained in:
Milana Ievlewa 2024-05-29 16:37:52 +04:00
parent 7d8be45708
commit 7c2da1ba42
13 changed files with 157 additions and 117 deletions

View File

@ -4,6 +4,7 @@ using BeautySalonContracts.SearchModels;
using BeautySalonContracts.StoragesContracts;
using BeautySalonContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions;
namespace BeautySalonBusinessLogic.BusinessLogics
{
@ -126,10 +127,10 @@ namespace BeautySalonBusinessLogic.BusinessLogics
{
throw new ArgumentNullException("Нет телефона клиента", nameof(model.ClientEmail));
}
if (string.IsNullOrEmpty(model.ClientEmail))
if (!Regex.IsMatch(model.ClientEmail, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
{
throw new ArgumentNullException("Нет почты клиента", nameof(model.ClientEmail));
}
throw new ArgumentException("Некорретно введенный email", nameof(model.ClientEmail));
}
if (string.IsNullOrEmpty(model.ClientPassword))
{
throw new ArgumentNullException("Нет пароля", nameof(model.ClientPassword));

View File

@ -1,8 +1,10 @@
using BeautySalonContracts.BindingModels;
using BeautySalonBusinessLogic.MailWorker;
using BeautySalonContracts.BindingModels;
using BeautySalonContracts.BusinessLogicContracts;
using BeautySalonContracts.SearchModels;
using BeautySalonContracts.StoragesContracts;
using BeautySalonContracts.ViewModels;
using BeautySalonDataModels.Enums;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@ -16,71 +18,107 @@ namespace BeautySalonBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<StaffMemberLogic> logger, IOrderStorage orderStorage)
private readonly AbstractMailWorker _mailWorker;
private readonly IClientLogic _clientLogic;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, AbstractMailWorker mailWorker, IClientLogic clientLogic)
{
_logger = logger;
_orderStorage = orderStorage;
_mailWorker = mailWorker;
_clientLogic = clientLogic;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("Order. OrderID:{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. OrderDate: {OrderDate}. Id: {Id}",
model.OrderDate, model.Id);
_logger.LogInformation("ReadElement. DateFrom:{DateFrom}. DateTo:{DateTo}. Id:{Id}", 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);
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool Create(OrderBindingModel model)
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_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 bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
if (_orderStorage.Insert(model) == null)
if (model.Status != OrderStatus.Неизвестен)
{
_logger.LogWarning("Invalid order status");
return false;
}
model.Status = OrderStatus.Принят;
var result = _orderStorage.Insert(model);
if (result == null)
{
model.Status = OrderStatus.Неизвестен;
_logger.LogWarning("Insert operation failed");
return false;
}
SendOrderStatusMail(result.ClientId, $"Новый заказ создан. Номер заказа #{result.Id}", $"Заказ #{result.Id} от {result.DateCreate} на сумму {result.OrderAmount:0.00} принят");
return true;
}
public bool Update(OrderBindingModel model)
private bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus)
{
CheckModel(model);
if (_orderStorage.Update(model) == null)
var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (viewModel == null)
{
throw new ArgumentNullException(nameof(model));
}
if (viewModel.Status + 1 != newStatus)
{
_logger.LogWarning("Change status operation failed");
throw new InvalidOperationException();
}
model.Status = newStatus;
if (model.Status == OrderStatus.Готов)
{
model.DateImplement = DateTime.Now;
}
else
{
model.DateImplement = viewModel.DateImplement;
}
CheckModel(model, false);
var result = _orderStorage.Update(model);
if (result == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
//Отсылка письма при изменении статуса
SendOrderStatusMail(result.ClientId, $"Изменен статус заказа #{result.Id}", $"Заказ #{model.Id} изменен статус на {result.Status}");
return true;
}
public bool Delete(OrderBindingModel model)
public bool TakeOrderInWork(OrderBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id: {Id}", model.Id);
if (_orderStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
return StatusUpdate(model, OrderStatus.Выполняется);
}
public bool FinishOrder(OrderBindingModel model)
{
model.DateImplement = DateTime.Now;
return StatusUpdate(model, OrderStatus.Готов);
}
public bool DeliveryOrder(OrderBindingModel model)
{
return StatusUpdate(model, OrderStatus.Выдан);
}
private void CheckModel(OrderBindingModel model, bool withParams = true)
{
@ -94,9 +132,29 @@ namespace BeautySalonBusinessLogic.BusinessLogics
}
if (model.OrderAmount <= 0)
{
throw new ArgumentNullException("Cумма заказа должна быть больше 0",
nameof(model.OrderAmount));
throw new ArgumentNullException("Стоимость должна быть больше 0", nameof(model.OrderAmount));
}
_logger.LogInformation("Order. Id: {Id}. Sum: {Sum}.", model.Id, model.OrderAmount);
var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (element != null && element.Id == model.Id)
{
throw new InvalidOperationException("Заказ с таким номером уже есть");
}
}
private bool SendOrderStatusMail(int clientId, string subject, string text)
{
var client = _clientLogic.ReadElement(new() { Id = clientId });
if (client == null)
{
return false;
}
_mailWorker.MailSendAsync(new()
{
MailAddress = client.Email,
Subject = subject,
Text = text
});
return true;
}
}
}

View File

@ -11,6 +11,7 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage.HelperModels
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportReinforcedComponentViewModel> ReinforcedComponents { get; set; } = new();
public List<ReportCosmeticProceduresViewModel> CosmeticProcedures { get; set; } = new();
public List<ReportProcedureCosmeticsViewModel> ProcedureCosmetics { get; set; } = new();
}
}

View File

@ -14,5 +14,6 @@ namespace PrecastConcretePlantBusinessLogic.OfficePackage.HelperModels
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<ReportOrdersViewModel> Orders { get; set; } = new();
public List<ReportServicesViewModel> Services { get; set; } = new();
}
}

View File

@ -22,9 +22,6 @@ namespace BeautySalonContracts.BusinessLogicsContracts
// Получение списка заказов за определенный период
List<ReportOrdersViewModel> GetOrders(ReportBindingModel model);
// Сохранение компонент в файл-Word
void SaveCosmeticsToWordFile(ReportBindingModel model);
// Сохранение процедур по косметике в файл-Word
void SaveCosmeticProceduresToWordFile(ReportBindingModel model);
// Сохранение косметики по процедурам в файл-Word

View File

@ -23,8 +23,6 @@ namespace BeautySalonContracts.ViewModels
[DisplayName("Почта клиента")]
public string ClientEmail { get; set; } = string.Empty;
[DisplayName("Пароль клиента")]
public string ClientPassword { get; set; } = string.Empty;

View File

@ -22,12 +22,10 @@ namespace BeautySalonContracts.ViewModels
public double ProcedureDuration { get; set; }
public int ClientId { get; set; }
public Dictionary<int, (ICosmeticModel, int)> CosmeticProcedures
public Dictionary<int, (ICosmeticModel, int)> ProcedureCosmetics
{
get;
set;
} = new();
//public List<OrderProcedureViewModel> OrderProcedures { get; set; } = new();
//public List<ServiceProcedureViewModel> ServiceProcedure { get; set; } = new();
}
}

View File

@ -8,6 +8,6 @@ namespace BeautySalonDataModels.Models
double ProcedurePrice { get; }
double ProcedureDuration { get; }
int ClientId { get; }
Dictionary<int, (ICosmeticModel, int)> ProcedureCosmetics { get; } //список косметики "участвующей" в заказе
}
}

View File

@ -24,82 +24,73 @@ namespace BeautySalonDatabaseImplement.Implements
return element.GetViewModel;
}
return null;
}
public ClientViewModel? GetElement(ClientSearchModel model)
{
using var context = new BeautySalonDatabase();
if (model.Id.HasValue)
return context.Clients
.FirstOrDefault(x => x.Id == model.Id)?
.GetViewModel;
if (!string.IsNullOrEmpty(model.ClientLogin) &&
!string.IsNullOrEmpty(model.ClientPassword))
return context.Clients
.FirstOrDefault(x =>
x.ClientLogin.Equals(model.ClientLogin) &&
x.ClientPassword.Equals(model.ClientPassword))?
.GetViewModel;
return null;
}
public List<ClientViewModel> GetFilteredList(ClientSearchModel model)
{
using var context = new BeautySalonDatabase();
if (model.Id.HasValue)
{
var res = GetElement(model);
return res != null ? new() { res } : new();
}
if (!string.IsNullOrEmpty(model.ClientEmail))
{
using var context = new BeautySalonDatabase();
return context.Clients
.Where(x => x.Id == model.Id)
.Include(x => x.Orders)
.Where(x => x.ClientEmail.Contains(model.ClientEmail))
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
public List<ClientViewModel> GetFullList()
public ClientViewModel? GetElement(ClientSearchModel model)
{
using var context = new BeautySalonDatabase();
return context.Clients
.Select(x => x.GetViewModel)
.ToList();
if (model.Id.HasValue)
return context.Clients.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
if (model.ClientEmail != null && model.ClientPassword != null)
return context.Clients.FirstOrDefault(x => x.ClientEmail.Equals(model.ClientEmail)
&& x.ClientPassword.Equals(model.ClientPassword))
?.GetViewModel;
if (model.ClientEmail != null)
return context.Clients.FirstOrDefault(x => x.ClientEmail.Equals(model.ClientEmail))?.GetViewModel;
return null;
}
public ClientViewModel? Insert(ClientBindingModel model)
{
using var context = new BeautySalonDatabase();
var newClient = Client.Create(model);
if (newClient == null)
{
return null;
}
using var context = new BeautySalonDatabase();
context.Clients.Add(newClient);
context.SaveChanges();
return newClient.GetViewModel;
}
public ClientViewModel? Update(ClientBindingModel model)
{
using var context = new BeautySalonDatabase();
var client = context.Clients.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
return null;
}
client.Update(model);
context.SaveChanges();
return client.GetViewModel;
}
public ClientViewModel? Delete(ClientBindingModel model)
{
using var context = new BeautySalonDatabase();
var element = context.Clients
.Include(x => x.Orders)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Clients.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -1,6 +1,7 @@
using BeautySalonContracts.BindingModels;
using BeautySalonContracts.ViewModels;
using BeautySalonDataModels.Models;
using DocumentFormat.OpenXml.Drawing.Charts;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
@ -20,17 +21,11 @@ namespace BeautySalonDatabaseImplement.Models
[Required]
public string ClientPhone { get; set; } = string.Empty;
[Required]
public string ClientPassword { get; set; } = string.Empty;
[ForeignKey("ClientId")]
public virtual List<Evaluation> Evaluations { get; set; } = new();
public virtual List<Order> Orders { get; set; } = new();
[ForeignKey("ClientId")]
public virtual List<Order_> Orders { get; set; } = new();
[ForeignKey("ClientId")]
public virtual List<Procedure> Procedures { get; set; } = new();
public virtual List<MessageInfo> Messages { get; set; } = new();
public static Client? Create(ClientBindingModel model)
{

View File

@ -18,7 +18,7 @@ namespace BeautySalonDatabaseImplement.Models
public int ProcedureId { get; set; }
[Required]
public int ProcedureCosmeticCount { get; set; }
public int Count { get; set; }
public virtual Cosmetic Cosmetic { get; set; } = new();

View File

@ -23,12 +23,11 @@ namespace BeautySalonDatabaseImplement.Models
[Required]
public int ProcedureId { get; set; }
public virtual Procedure? Procedure { get; set; }
public virtual Procedure Procedure { get; set; } = new();
[Required]
public int ClientId { get; set; }
public virtual Client Client { get; set; } = new();
public virtual Client? Client { get; set; }
public static Evaluation? Create(EvaluationBindingModel? model)
{

View File

@ -24,9 +24,11 @@ namespace BeautySalonDatabaseImplement.Models
[Required]
public double ProcedureDuration { get; set; }
[Required]
public int ClientId { get; set; }
public virtual Client Client { get; set; } = null!;
public virtual Client Client { get; set; }
#region
//// связь процедуры и оценок один - ко - многим
//[ForeignKey("ProcedureId")]
//public virtual List<Evaluation> Evaluations { get; set; } = new();
@ -60,19 +62,21 @@ namespace BeautySalonDatabaseImplement.Models
// return _cosmeticProcedures;
// }
//}
#endregion
private Dictionary<int, string>? _cosmeticProcedures = null;//Это поле для хранения словаря OrderCosmetics.
private Dictionary<int, (ICosmeticModel, int)>? _procedureCosmetics = null;//Это поле для хранения словаря OrderCosmetics.
[NotMapped]
public Dictionary<int, string> CosmeticProcedure//представляет список косметики, участвующей в заказе. Не присутствует в базе данных.
public Dictionary<int, (ICosmeticModel, int)> ProcedureCosmetics//представляет список косметики, участвующей в заказе. Не присутствует в базе данных.
{
get
{
if (_cosmeticProcedures == null)
if (_procedureCosmetics == null)
{
_cosmeticProcedures = Cosmetics
.ToDictionary(recPC => recPC.CosmeticId, recPC => recPC.Cosmetic.CosmeticName);
_procedureCosmetics = Cosmetics
.ToDictionary(recPC => recPC.CosmeticId, recPC =>
(recPC.Cosmetic as ICosmeticModel, recPC.Count));
}
return _cosmeticProcedures;
return _procedureCosmetics;
}
}
@ -88,9 +92,6 @@ namespace BeautySalonDatabaseImplement.Models
//[ForeignKey("ProcedureId")]
//public virtual List<ServiceProcedure> Services { get; set; } = new();
public static Procedure Create(BeautySalonDatabase context, ProcedureBindingModel model)
{
if (model == null)
@ -104,7 +105,7 @@ namespace BeautySalonDatabaseImplement.Models
ProcedurePrice = model.ProcedurePrice,
ProcedureDuration = model.ProcedureDuration,
ClientId = model.ClientId,
Cosmetics = model.ProcedureCosmetics.Select(x => new ProcedureCosmetic
Cosmetics = model.ProcedureCosmetics.Select(x => new CosmeticProcedure
{
Cosmetic = context.Cosmetics.First(y => y.Id == x.Key)
}).ToList(),
@ -126,7 +127,7 @@ namespace BeautySalonDatabaseImplement.Models
ProcedureName = ProcedureName,
ProcedurePrice = ProcedurePrice,
ProcedureDuration = ProcedureDuration,
CosmeticProcedures = CosmeticProcedures,
ProcedureCosmetics = ProcedureCosmetics,
ClientId = ClientId
};
@ -135,7 +136,7 @@ namespace BeautySalonDatabaseImplement.Models
var procedureCosmetics = context.CosmeticProcedures.Where(rec => rec.ProcedureId == model.Id).ToList();
if (procedureCosmetics != null && procedureCosmetics.Count > 0)
{ // удалили те, которых нет в модели
context.CosmeticProcedures.RemoveRange(procedureCosmetics.Where(rec => !model.CosmeticProcedure.ContainsKey(rec.CosmeticId)));
context.CosmeticProcedures.RemoveRange(procedureCosmetics.Where(rec => !model.ProcedureCosmetics.ContainsKey(rec.CosmeticId)));
context.SaveChanges();
// обновили количество у существующих записей
foreach (var updateCosmetic in procedureCosmetics)
@ -144,17 +145,17 @@ namespace BeautySalonDatabaseImplement.Models
}
context.SaveChanges();
}
var service = context.Procedures.First(x => x.Id == Id);
var procedure = context.Procedures.First(x => x.Id == Id);
foreach (var rp in model.ProcedureCosmetics)
{
context.CosmeticProcedures.Add(new Procedure
context.CosmeticProcedures.Add(new CosmeticProcedure
{
Procedure = procedure,
Cosmetic = context.Cosmetics.First(x => x.Id == rp.Key),
});
context.SaveChanges();
}
_cosmeticProcedures = null;
_procedureCosmetics = null;
}