using BeautySaloonContracts.BindingModels;
using BeautySaloonContracts.ViewModels;
using BeautySaloonDataModels;
using System.ComponentModel.DataAnnotations.Schema;
namespace BeautySaloonDatabaseImplement;
///
/// Сущность заказы
///
public partial class Order : IOrderModel
{
///
/// Уникальный идентификатор
///
public int Id { get; set; }
///
/// Дата
///
public DateOnly Date { get; set; }
///
/// Сумма
///
public decimal Sum { get; set; }
///
/// Идентификатор клиента
///
public int ClientId { get; set; }
///
/// Идентификатор сотрудника
///
public int EmployeeId { get; set; }
public virtual Client Client { get; set; } = null!;
public virtual Employee Employee { get; set; } = null!;
public virtual List ServiceOrders { get; set; } = new List();
public Dictionary _orderServices = null;
public Dictionary OrderServices
{
get
{
if (_orderServices == null)
{
_orderServices = ServiceOrders
.ToDictionary(recPC => recPC.ServiceId,
recPC => (recPC.Date, recPC.Service as IServiceModel, recPC.EmployeeId));
}
return _orderServices;
}
}
public static Order? Create(NewdbContext context, OrderBindingModel? model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
Date = model.Date,
Sum = model.Sum,
ClientId = model.ClientId,
EmployeeId = model.EmployeeId,
ServiceOrders = model.OrderServices.Select(x => new ServiceOrder
{
Service = context.Services.First(y => y.Id == x.Key),
Date = x.Value.Item1,
EmployeeId = x.Value.Item3,
}).ToList()
};
}
public void Update(OrderBindingModel model)
{
Date = model.Date;
Sum = model.Sum;
EmployeeId = model.EmployeeId;
ClientId = model.ClientId;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
Date = Date,
Sum = Sum,
ClientId = ClientId,
EmployeeId = EmployeeId,
ClientName = Client.Name + " " + Client.Surname + " " + Client.Patronymic,
EmployeeName = Employee.Name + " " + Employee.Surname + " " + Employee.Patronymic,
ClientPhone = Client.Phone,
EmployeePhone = Employee.Phone
};
public void UpdateServices(NewdbContext context, OrderBindingModel model)
{
var orderServices = context.ServiceOrders
.Where(rec => rec.OrderId == model.Id).ToList();
if (orderServices != null && orderServices.Count > 0)
{ // удалили те, которых нет в модели
context.ServiceOrders
.RemoveRange(orderServices
.Where(rec => !model.OrderServices.ContainsKey(rec.ServiceId)));
context.SaveChanges();
// обновили данные у существующих записей
foreach (var updateService in orderServices)
{
updateService.Date = model.OrderServices[updateService.ServiceId].Item1;
updateService.EmployeeId =
model.OrderServices[updateService.ServiceId].Item3;
model.OrderServices.Remove(updateService.ServiceId);
}
context.SaveChanges();
}
var order = context.Orders.First(x => x.Id == Id);
foreach (var os in model.OrderServices)
{
context.ServiceOrders.Add(new ServiceOrder
{
Order = order,
Service = context.Services.First(x => x.Id == os.Key),
Date = os.Value.Item1,
EmployeeId = os.Value.Item3
});
context.SaveChanges();
}
_orderServices = null;
}
}