Compare commits

..

8 Commits

29 changed files with 1479 additions and 103 deletions

View File

@ -0,0 +1,117 @@
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.BusinessLogicContracts;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.StorageContracts;
using ComputerShopContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace ComputerShopBusinessLogic.BusinessLogics
{
public class AssemblyLogic : IAssemblyLogic
{
private readonly ILogger _logger;
private readonly IAssemblyStorage _assemblyStorage;
public AssemblyLogic(ILogger<AssemblyLogic> Logger, IAssemblyStorage AssemblyStorage)
{
_logger = Logger;
_assemblyStorage = AssemblyStorage;
}
public List<AssemblyViewModel>? ReadList(AssemblySearchModel? Model)
{
var List = (Model == null) ? _assemblyStorage.GetFullList() : _assemblyStorage.GetFilteredList(Model);
if (List == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count: {Count}", List.Count);
return List;
}
public AssemblyViewModel? ReadElement(AssemblySearchModel Model)
{
if (Model == null)
throw new ArgumentNullException(nameof(Model));
var Element = _assemblyStorage.GetElement(Model);
if (Element == null)
{
_logger.LogWarning("ReadElement Assembly not found");
return null;
}
_logger.LogInformation("ReadElement Assembly found. Id: {Id}", Element.Id);
return Element;
}
public bool Create(AssemblyBindingModel Model)
{
CheckModel(Model);
if (_assemblyStorage.Insert(Model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(AssemblyBindingModel Model)
{
CheckModel(Model);
if (_assemblyStorage.Update(Model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(AssemblyBindingModel Model)
{
CheckModel(Model, false);
_logger.LogInformation("Delete. Id:{Id}", Model.Id);
if (_assemblyStorage.Delete(Model) is null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(AssemblyBindingModel Model, bool WithParams = true)
{
if (Model == null)
throw new ArgumentNullException(nameof(Model));
if (!WithParams)
return;
if (string.IsNullOrEmpty(Model.AssemblyName))
throw new ArgumentException($"У сборки отсутствует название");
if (string.IsNullOrEmpty(Model.Category))
throw new ArgumentException($"У сборки отсутствует категория");
if (Model.Price <= 0)
throw new ArgumentException("Цена сборки должна быть больше 0", nameof(Model.Price));
var Element = _assemblyStorage.GetElement(new AssemblySearchModel
{
AssemblyName = Model.AssemblyName
});
if (Element != null && Element.Id != Model.Id)
throw new InvalidOperationException("Товар с таким названием уже есть");
}
}
}

View File

@ -0,0 +1,114 @@
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.BusinessLogicContracts;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.StorageContracts;
using ComputerShopContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace ComputerShopBusinessLogic.BusinessLogics
{
public class ComponentLogic : IComponentLogic
{
private readonly ILogger _logger;
private readonly IComponentStorage _componentStorage;
public ComponentLogic(ILogger<ComponentLogic> Logger, IComponentStorage ComponentStorage)
{
_logger = Logger;
_componentStorage = ComponentStorage;
}
public List<ComponentViewModel>? ReadList(ComponentSearchModel? Model)
{
var List = (Model == null) ? _componentStorage.GetFullList() : _componentStorage.GetFilteredList(Model);
if (List == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count: {Count}", List.Count);
return List;
}
public ComponentViewModel? ReadElement(ComponentSearchModel Model)
{
if (Model == null)
throw new ArgumentNullException(nameof(Model));
var Element = _componentStorage.GetElement(Model);
if (Element == null)
{
_logger.LogWarning("ReadElement component not found");
return null;
}
_logger.LogInformation("ReadElement component found. Id: {Id}", Element.Id);
return Element;
}
public bool Create(ComponentBindingModel Model)
{
CheckModel(Model);
if (_componentStorage.Insert(Model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ComponentBindingModel Model)
{
CheckModel(Model);
if (_componentStorage.Update(Model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ComponentBindingModel Model)
{
CheckModel(Model, false);
_logger.LogInformation("Delete. Id:{Id}", Model.Id);
if (_componentStorage.Delete(Model) is null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ComponentBindingModel Model, bool WithParams = true)
{
if (Model == null)
throw new ArgumentNullException(nameof(Model));
if (!WithParams)
return;
if (string.IsNullOrEmpty(Model.ComponentName))
throw new ArgumentException($"У комплектующей отсутствует название");
if (Model.Cost <= 0)
throw new ArgumentException("Цена комплектующей должна быть больше 0", nameof(Model.Cost));
var Element = _componentStorage.GetElement(new ComponentSearchModel
{
ComponentName = Model.ComponentName
});
if (Element != null && Element.Id != Model.Id)
throw new InvalidOperationException("Комплектующая с таким названием уже есть");
}
}
}

View File

@ -0,0 +1,117 @@
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.BusinessLogicContracts;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.StorageContracts;
using ComputerShopContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace ComputerShopBusinessLogic.BusinessLogics
{
public class ProductLogic : IProductLogic
{
private readonly ILogger _logger;
private readonly IProductStorage _productStorage;
public ProductLogic(ILogger<ProductLogic> Logger, IProductStorage ProductStorage)
{
_logger = Logger;
_productStorage = ProductStorage;
}
public List<ProductViewModel>? ReadList(ProductSearchModel? Model)
{
var List = (Model == null) ? _productStorage.GetFullList() : _productStorage.GetFilteredList(Model);
if (List == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count: {Count}", List.Count);
return List;
}
public ProductViewModel? ReadElement(ProductSearchModel Model)
{
if (Model == null)
throw new ArgumentNullException(nameof(Model));
var Element = _productStorage.GetElement(Model);
if (Element == null)
{
_logger.LogWarning("ReadElement Product not found");
return null;
}
_logger.LogInformation("ReadElement Product found. Id: {Id}", Element.Id);
return Element;
}
public bool Create(ProductBindingModel Model)
{
CheckModel(Model);
if (_productStorage.Insert(Model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ProductBindingModel Model)
{
CheckModel(Model);
if (_productStorage.Update(Model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ProductBindingModel Model)
{
CheckModel(Model, false);
_logger.LogInformation("Delete. Id:{Id}", Model.Id);
if (_productStorage.Delete(Model) is null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ProductBindingModel Model, bool WithParams = true)
{
if (Model == null)
throw new ArgumentNullException(nameof(Model));
if (!WithParams)
return;
if (string.IsNullOrEmpty(Model.ProductName))
throw new ArgumentException($"У товара отсутствует название");
if (Model.Price <= 0)
throw new ArgumentException("Цена товара должна быть больше 0", nameof(Model.Price));
if (Model.Warranty <= 0)
throw new ArgumentException("Гарантия на товар должна быть больше 0", nameof(Model.Warranty));
var Element = _productStorage.GetElement(new ProductSearchModel
{
ProductName = Model.ProductName
});
if (Element != null && Element.Id != Model.Id)
throw new InvalidOperationException("Товар с таким названием уже есть");
}
}
}

View File

@ -27,15 +27,26 @@ namespace ComputerShopBusinessLogic.BusinessLogics
/// Отчёт для doc/xls /// Отчёт для doc/xls
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public List<ReportOrderAssemblyViewModel> GetOrderAssemblies(List<OrderSearchModel> selectedOrders) { public List<ReportOrderAssemblyViewModel> GetReportOrdersAssemblies(List<OrderSearchModel> selectedOrders)
//!!!исправить на filteredList
return _orderStorage.GetReportWithAssembly(selectedOrders).Select(x => new ReportOrderAssemblyViewModel
{ {
OrderId = x.Id, return _orderStorage.GetOrdersAssemblies(selectedOrders);
DateCreateOrder = x.DateCreate, }
OrderSum = x.Sum, /// <summary>
/// Отчёт для почты/страницы
/// </summary>
/// <returns></returns>
public List<ReportOrdersViewModel> GetReportOrdersByDates(UserSearchModel currentUser, ReportBindingModel report)
{
return _orderStorage.GetOrdersInfoByDates(currentUser, report);
}
}); public void SaveReportOrderAssembliesToWordFile(ReportBindingModel model)
{
throw new NotImplementedException();
}
public void SaveReportOrderAssembliesToExcelFile(ReportBindingModel model)
{
throw new NotImplementedException();
} }
} }
} }

View File

@ -10,7 +10,7 @@ namespace ComputerShopContracts.BindingModels
public string AssemblyName { get; set; } = string.Empty; public string AssemblyName { get; set; } = string.Empty;
public double Cost { get; set; } public double Price { get; set; }
public string Category { get; set; } = string.Empty; public string Category { get; set; } = string.Empty;

View File

@ -8,14 +8,14 @@ namespace ComputerShopContracts.BindingModels
public int UserId { get; set; } public int UserId { get; set; }
public int? ShipmentId { get; set; }
public string ProductName { get; set; } = string.Empty; public string ProductName { get; set; } = string.Empty;
public double Cost { get; set; } public double Price { get; set; }
public int Warranty { get; set; } public int Warranty { get; set; }
public Dictionary<int, (IComponentModel, int)> ProductComponents { get; set; } = new(); public Dictionary<int, (IComponentModel, int)> ProductComponents { get; set; } = new();
public int? ShipmentId { get; set; }
} }
} }

View File

@ -1,4 +1,5 @@
using ComputerShopContracts.BindingModels; using ComputerShopContracts.BindingModels;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.ViewModels; using ComputerShopContracts.ViewModels;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -14,15 +15,15 @@ namespace ComputerShopContracts.BusinessLogicContracts
/// Получение отчёта для word/excel /// Получение отчёта для word/excel
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
List<ReportOrderAssemblyViewModel> GetOrderAssemblies(); List<ReportOrderAssemblyViewModel> GetReportOrdersAssemblies(List<OrderSearchModel> selectedOrders);
/// <summary> /// <summary>
/// Получение отчёта для почты /// Получение отчёта для почты
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
List<ReportOrderRequestAssemblyViewModel> GetOrderRequestAssemblies(); List<ReportOrdersViewModel> GetReportOrdersByDates(UserSearchModel currentUser, ReportBindingModel report);
void SaveOrderAssembliesToWordFile(ReportBindingModel model); void SaveReportOrderAssembliesToWordFile(ReportBindingModel model);
void SaveOrderAssembliesToExcelFile(ReportBindingModel model); void SaveReportOrderAssembliesToExcelFile(ReportBindingModel model);
} }
} }

View File

@ -6,6 +6,8 @@
public int? UserId { get; set; } public int? UserId { get; set; }
public string? AssemblyName { get; set; }
public string? Category { get; set; } public string? Category { get; set; }
} }
} }

View File

@ -5,5 +5,7 @@
public int? Id { get; set; } public int? Id { get; set; }
public int? UserId { get; set; } public int? UserId { get; set; }
public string? ComponentName { get; set; }
} }
} }

View File

@ -7,5 +7,7 @@
public int? UserId { get; set; } public int? UserId { get; set; }
public int? ShipmentId { get; set; } public int? ShipmentId { get; set; }
public string? ProductName { get; set; }
} }
} }

View File

@ -17,6 +17,8 @@ namespace ComputerShopContracts.StorageContracts
OrderViewModel? Insert(OrderBindingModel model); OrderViewModel? Insert(OrderBindingModel model);
OrderViewModel? Update(OrderBindingModel model); OrderViewModel? Update(OrderBindingModel model);
OrderViewModel? Delete(OrderBindingModel model); OrderViewModel? Delete(OrderBindingModel model);
List<OrderViewModel> GetReportWithAssembly(List<OrderSearchModel> model); //получение данных о заказах для отчётов
List<ReportOrderAssemblyViewModel> GetOrdersAssemblies(List<OrderSearchModel> model);
List<ReportOrdersViewModel> GetOrdersInfoByDates(UserSearchModel currentUser, ReportBindingModel report);
} }
} }

View File

@ -13,7 +13,7 @@ namespace ComputerShopContracts.ViewModels
public string AssemblyName { get; set; } = string.Empty; public string AssemblyName { get; set; } = string.Empty;
[DisplayName("Стоимость")] [DisplayName("Стоимость")]
public double Cost { get; set; } public double Price { get; set; }
[DisplayName("Категория")] [DisplayName("Категория")]
public string Category { get; set; } = string.Empty; public string Category { get; set; } = string.Empty;

View File

@ -9,20 +9,20 @@ namespace ComputerShopContracts.ViewModels
public int UserId { get; set; } public int UserId { get; set; }
public int? ShipmentId { get; set; }
[DisplayName("Поставщик")]
public string? ProviderName { get; set; }
[DisplayName("Название товара")] [DisplayName("Название товара")]
public string ProductName { get; set; } = string.Empty; public string ProductName { get; set; } = string.Empty;
[DisplayName("Стоимость")] [DisplayName("Стоимость")]
public double Cost { get; set; } public double Price { get; set; }
[DisplayName("Гарантия (мес.)")] [DisplayName("Гарантия (мес.)")]
public int Warranty { get; set; } public int Warranty { get; set; }
public Dictionary<int, (IComponentModel, int)> ProductComponents { get; set; } = new(); public Dictionary<int, (IComponentModel, int)> ProductComponents { get; set; } = new();
public int? ShipmentId { get; set; }
[DisplayName("Поставщик")]
public string ProviderName { get; set; } = string.Empty;
} }
} }

View File

@ -1,4 +1,5 @@
using ComputerShopDataModels.Enums; using ComputerShopDataModels.Enums;
using ComputerShopDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -9,15 +10,13 @@ namespace ComputerShopContracts.ViewModels
{ {
public class ReportOrderAssemblyViewModel public class ReportOrderAssemblyViewModel
{ {
//!!!мб тут хранить списки промежуточных сущностей
public int OrderId { get; set; } public int OrderId { get; set; }
public DateTime DateCreateOrder { get; set; } public DateTime DateCreateOrder { get; set; }
public double OrderSum { get; set; } public double OrderSum { get; set; }
public OrderStatus OrderStatus { get; set; } public OrderStatus OrderStatus { get; set; }
public string AssemblyName { get; set; } //данные о сборках
public string AssemblyCategory { get; set; } public List<(string AssemblyName, string AssemblyCategory, double AssemblyPrice)> Assemblies { get; set; }
public double AssemblyCost { get; set; }
} }
} }

View File

@ -1,25 +0,0 @@
using ComputerShopDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerShopContracts.ViewModels
{
public class ReportOrderRequestAssemblyViewModel
{
//!!!мб тут хранить списки промежуточных сущностей
public int OrderID { get; set; }
public DateTime DateCreateOrder { get; set; }
public double OrderSum { get; set; }
public OrderStatus OrderStatus { get; set; }
public int RequestId { get; set; }
public string ClientFIO { get; set; }
public DateTime DateRequest { get; set; }
public string AssemblyName { get; set; }
public string AssemblyCategory { get; set; }
public double AssemblyCost { get; set; }
}
}

View File

@ -0,0 +1,23 @@
using ComputerShopDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerShopContracts.ViewModels
{
public class ReportOrdersViewModel
{
public int OrderId { get; set; }
public DateTime DateCreateOrder { get; set; }
public double OrderSum { get; set; }
public OrderStatus OrderStatus { get; set; }
//данные заявок
public List<(int RequestId, string ClientFIO, DateTime DateRequest)> Requests { get; set; }
//данные сборок
public List<(string AssemblyName, string AssemblyCategory, double AssemblyPrice)> Assemblies { get; set; }
}
}

View File

@ -18,7 +18,7 @@
/// <summary> /// <summary>
/// Стоимость /// Стоимость
/// </summary> /// </summary>
double Cost { get; } double Price { get; }
/// <summary> /// <summary>
/// Категория /// Категория

View File

@ -18,7 +18,7 @@
/// <summary> /// <summary>
/// Стоимость товара /// Стоимость товара
/// </summary> /// </summary>
double Cost { get; } double Price { get; }
/// <summary> /// <summary>
/// Гарантия /// Гарантия

View File

@ -0,0 +1,121 @@
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.StorageContracts;
using ComputerShopContracts.ViewModels;
using ComputerShopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace ComputerShopDatabaseImplement.Implements
{
public class AssemblyStorage : IAssemblyStorage
{
public List<AssemblyViewModel> GetFullList()
{
using var Context = new ComputerShopDatabase();
return Context.Assemblies
.Include(x => x.Components)
.ThenInclude(x => x.Assembly)
.Select(x => x.ViewModel)
.ToList();
}
public List<AssemblyViewModel> GetFilteredList(AssemblySearchModel Model)
{
using var Context = new ComputerShopDatabase();
// Optional search by Category name
if (!string.IsNullOrEmpty(Model.Category))
{
return Context.Assemblies
.Include(x => x.Components)
.ThenInclude(x => x.Assembly)
.Where(x => x.UserId == Model.UserId && x.Category == Model.Category)
.Select(x => x.ViewModel)
.ToList();
}
return Context.Assemblies
.Include(x => x.Components)
.ThenInclude(x => x.Assembly)
.Where(x => x.UserId == Model.UserId)
.Select(x => x.ViewModel)
.ToList();
}
public AssemblyViewModel? GetElement(AssemblySearchModel Model)
{
using var Context = new ComputerShopDatabase();
// AssemblyName is unique
if (!string.IsNullOrEmpty(Model.AssemblyName))
{
return Context.Assemblies
.Include(x => x.Components)
.ThenInclude(x => x.Assembly)
.FirstOrDefault(x => x.AssemblyName == Model.AssemblyName)?
.ViewModel;
}
return Context.Assemblies
.Include(x => x.Components)
.ThenInclude(x => x.Assembly)
.FirstOrDefault(x => x.Id == Model.Id)?
.ViewModel;
}
public AssemblyViewModel? Insert(AssemblyBindingModel Model)
{
using var Context = new ComputerShopDatabase();
var NewAssembly = Assembly.Create(Context, Model);
Context.Assemblies.Add(NewAssembly);
Context.SaveChanges();
return NewAssembly.ViewModel;
}
public AssemblyViewModel? Update(AssemblyBindingModel Model)
{
using var Context = new ComputerShopDatabase();
using var Transaction = Context.Database.BeginTransaction();
try
{
var ExistingAssembly = Context.Assemblies.FirstOrDefault(x => x.Id == Model.Id);
if (ExistingAssembly == null)
{
return null;
}
ExistingAssembly.Update(Model);
Context.SaveChanges();
ExistingAssembly.UpdateComponents(Context, Model);
Transaction.Commit();
return ExistingAssembly.ViewModel;
}
catch
{
Transaction.Rollback();
throw;
}
}
public AssemblyViewModel? Delete(AssemblyBindingModel Model)
{
using var Context = new ComputerShopDatabase();
var ExistingAssembly = Context.Assemblies.Include(x => x.Components).FirstOrDefault(x => x.Id == Model.Id);
if (ExistingAssembly == null)
{
return null;
}
Context.Assemblies.Remove(ExistingAssembly);
Context.SaveChanges();
return ExistingAssembly.ViewModel;
}
}
}

View File

@ -0,0 +1,90 @@
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.StorageContracts;
using ComputerShopContracts.ViewModels;
using ComputerShopDatabaseImplement.Models;
namespace ComputerShopDatabaseImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
public List<ComponentViewModel> GetFullList()
{
using var Context = new ComputerShopDatabase();
return Context.Components
.Select(x => x.ViewModel)
.ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel Model)
{
using var Context = new ComputerShopDatabase();
return Context.Components
.Where(x => x.UserId == Model.UserId)
.Select(x => x.ViewModel)
.ToList();
}
public ComponentViewModel? GetElement(ComponentSearchModel Model)
{
using var Context = new ComputerShopDatabase();
// ComponentName is unique
if (!string.IsNullOrEmpty(Model.ComponentName))
{
return Context.Components
.FirstOrDefault(x => x.ComponentName == Model.ComponentName)?
.ViewModel;
}
return Context.Components
.FirstOrDefault(x => x.Id == Model.Id)?
.ViewModel;
}
public ComponentViewModel? Insert(ComponentBindingModel Model)
{
using var Context = new ComputerShopDatabase();
var NewComponent = Component.Create(Model);
Context.Components.Add(NewComponent);
Context.SaveChanges();
return NewComponent.ViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel Model)
{
using var Context = new ComputerShopDatabase();
var ExistingComponent = Context.Components.FirstOrDefault(x => x.Id == Model.Id);
if (ExistingComponent == null)
{
return null;
}
ExistingComponent.Update(Model);
Context.SaveChanges();
return ExistingComponent.ViewModel;
}
public ComponentViewModel? Delete(ComponentBindingModel Model)
{
using var Context = new ComputerShopDatabase();
var ExistingComponent = Context.Components.FirstOrDefault(x => x.Id == Model.Id);
if (ExistingComponent == null)
{
return null;
}
Context.Components.Remove(ExistingComponent);
Context.SaveChanges();
return ExistingComponent.ViewModel;
}
}
}

View File

@ -3,6 +3,7 @@ using ComputerShopContracts.SearchModels;
using ComputerShopContracts.StorageContracts; using ComputerShopContracts.StorageContracts;
using ComputerShopContracts.ViewModels; using ComputerShopContracts.ViewModels;
using ComputerShopDatabaseImplement.Models; using ComputerShopDatabaseImplement.Models;
using ComputerShopDataModels.Models;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System; using System;
@ -72,8 +73,8 @@ namespace ComputerShopDatabaseImplement.Implements
.ToList(); .ToList();
} }
//получение данных для отчёта сборок по выбранным заказам //получение данных сборок по выбранным заказам для отчёта (doc/xls)
public List<ReportOrderAssemblyViewModel> GetReportWithAssembly(List<OrderSearchModel> selectedModels) public List<ReportOrderAssemblyViewModel> GetOrdersAssemblies(List<OrderSearchModel> selectedModels)
{ {
using var context = new ComputerShopDatabase(); using var context = new ComputerShopDatabase();
//id заказов, которые выбрал пользователь //id заказов, которые выбрал пользователь
@ -84,30 +85,6 @@ namespace ComputerShopDatabaseImplement.Implements
.ThenInclude(x => x.Request) .ThenInclude(x => x.Request)
.ThenInclude(x => x.Assembly) .ThenInclude(x => x.Assembly)
.Where(x => id_of_selected_models.Contains(x.Id) && x.Requests.Any(r => r.Request.Assembly != null)) .Where(x => id_of_selected_models.Contains(x.Id) && x.Requests.Any(r => r.Request.Assembly != null))
context.Orders
.Where(x => id_of_selected_models.Contains(x.Id) && x.Requests.Any(r => r.Request.Assembly != null))
foreach (var selectedModel in selectedModels)
{
//заказ, у которого должна быть сборка
var order = context.Orders.FirstOrDefault(x => x.Id == selectedModel.Id && x.Requests.Any(r => r.Request.Assembly != null));
//если у заказа нет сборки, то его не надо обрабатывать
if (order == null)
{
continue;
}
}
var ordersWithAssemblies = selectedModels
//возвращение тех заказов, кот. принадлежат пользователю и кот. имеют сборку в соответствующей заявке
return context.Orders
.Where(x => x.UserId == model.UserId && x.Requests.Any(r => r.Request.Assembly != null))
.Include(x => x.Requests)
.ThenInclude(x => x.Request)
.ThenInclude(x => x.Assembly)
.ToList() .ToList()
.Select(x => new ReportOrderAssemblyViewModel .Select(x => new ReportOrderAssemblyViewModel
{ {
@ -115,9 +92,28 @@ namespace ComputerShopDatabaseImplement.Implements
DateCreateOrder = x.DateCreate, DateCreateOrder = x.DateCreate,
OrderSum = x.Sum, OrderSum = x.Sum,
OrderStatus = x.Status, OrderStatus = x.Status,
AssemblyName = x.Requests.FirstOrDefault(r => r.Request.Assembly != null)?.Request.Assembly.AssemblyName, Assemblies = x.Requests.Select(r => (r.Request.Assembly.AssemblyName, r.Request.Assembly.Category, r.Request.Assembly.Price)).ToList(),
})
.ToList();
}
//получение заказов (все, что создал сам пользователь) за период с расшифровкой по заявкам и сборкам для отчёта (почта/страница)
public List<ReportOrdersViewModel> GetOrdersInfoByDates(UserSearchModel currentUser, ReportBindingModel report)
{
using var context = new ComputerShopDatabase();
return context.Orders.Include(x => x.Requests)
.ThenInclude(x => x.Request)
.ThenInclude(x => x.Assembly)
.Where(x => x.UserId == currentUser.Id && x.DateCreate >= report.DateFrom && x.DateCreate <= report.DateTo)
.ToList()
.Select(x => new ReportOrdersViewModel
{
OrderId = x.Id,
DateCreateOrder = x.DateCreate,
OrderSum = x.Sum,
OrderStatus = x.Status,
Requests = x.Requests.Select(r => (r.Request.Id, r.Request.ClientFIO, r.Request.DateRequest)).ToList(),
Assemblies = x.Requests.Select(r => (r.Request.Assembly.AssemblyName, r.Request.Assembly.Category, r.Request.Assembly.Price)).ToList(),
}) })
.ToList(); .ToList();
} }

View File

@ -0,0 +1,126 @@
using ComputerShopContracts.BindingModels;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.StorageContracts;
using ComputerShopContracts.ViewModels;
using ComputerShopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace ComputerShopDatabaseImplement.Implements
{
public class ProductStorage : IProductStorage
{
public List<ProductViewModel> GetFullList()
{
using var Context = new ComputerShopDatabase();
return Context.Products
.Include(x => x.Shipment)
.Include(x => x.Components)
.ThenInclude(x => x.Product)
.Select(x => x.ViewModel)
.ToList();
}
public List<ProductViewModel> GetFilteredList(ProductSearchModel Model)
{
using var Context = new ComputerShopDatabase();
// Optional search by Shipment
if (Model.ShipmentId.HasValue)
{
return Context.Products
.Include(x => x.Shipment)
.Include(x => x.Components)
.ThenInclude(x => x.Product)
.Where(x => x.UserId == Model.UserId && x.ShipmentId == Model.ShipmentId)
.Select(x => x.ViewModel)
.ToList();
}
return Context.Products
.Include(x => x.Shipment)
.Include(x => x.Components)
.ThenInclude(x => x.Product)
.Where(x => x.UserId == Model.UserId)
.Select(x => x.ViewModel)
.ToList();
}
public ProductViewModel? GetElement(ProductSearchModel Model)
{
using var Context = new ComputerShopDatabase();
// ProductName is unique
if (!string.IsNullOrEmpty(Model.ProductName))
{
return Context.Products
.Include(x => x.Shipment)
.Include(x => x.Components)
.ThenInclude(x => x.Product)
.FirstOrDefault(x => x.ProductName == Model.ProductName)?
.ViewModel;
}
return Context.Products
.Include(x => x.Shipment)
.Include(x => x.Components)
.ThenInclude(x => x.Product)
.FirstOrDefault(x => x.Id == Model.Id)?
.ViewModel;
}
public ProductViewModel? Insert(ProductBindingModel Model)
{
using var Context = new ComputerShopDatabase();
var NewProduct = Product.Create(Context, Model);
Context.Products.Add(NewProduct);
Context.SaveChanges();
return NewProduct.ViewModel;
}
public ProductViewModel? Update(ProductBindingModel Model)
{
using var Context = new ComputerShopDatabase();
using var Transaction = Context.Database.BeginTransaction();
try
{
var ExistingProduct = Context.Products.FirstOrDefault(x => x.Id == Model.Id);
if (ExistingProduct == null)
{
return null;
}
ExistingProduct.Update(Model);
Context.SaveChanges();
ExistingProduct.UpdateComponents(Context, Model);
Transaction.Commit();
return ExistingProduct.ViewModel;
}
catch
{
Transaction.Rollback();
throw;
}
}
public ProductViewModel? Delete(ProductBindingModel Model)
{
using var Context = new ComputerShopDatabase();
var ExistingProduct = Context.Products.Include(x => x.Components).FirstOrDefault(x => x.Id == Model.Id);
if (ExistingProduct == null)
{
return null;
}
Context.Products.Remove(ExistingProduct);
Context.SaveChanges();
return ExistingProduct.ViewModel;
}
}
}

View File

@ -0,0 +1,522 @@
// <auto-generated />
using System;
using ComputerShopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace ComputerShopDatabaseImplement.Migrations
{
[DbContext(typeof(ComputerShopDatabase))]
[Migration("20240501095656_Переименовал Price (Олег)")]
partial class ПереименовалPriceОлег
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.18")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Assembly", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("AssemblyName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Category")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Assemblies");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.AssemblyComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("AssemblyId")
.HasColumnType("integer");
b.Property<int>("ComponentId")
.HasColumnType("integer");
b.Property<int>("Count")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AssemblyId");
b.HasIndex("ComponentId");
b.ToTable("AssemblyComponents");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("text");
b.Property<double>("Cost")
.HasColumnType("double precision");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Components");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("DateCreate")
.HasColumnType("timestamp without time zone");
b.Property<int>("Status")
.HasColumnType("integer");
b.Property<double>("Sum")
.HasColumnType("double precision");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Orders");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<double>("Price")
.HasColumnType("double precision");
b.Property<string>("ProductName")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("ShipmentId")
.HasColumnType("integer");
b.Property<int>("UserId")
.HasColumnType("integer");
b.Property<int>("Warranty")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ShipmentId");
b.HasIndex("UserId");
b.ToTable("Products");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.ProductComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("integer");
b.Property<int>("Count")
.HasColumnType("integer");
b.Property<int>("ProductId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("ProductId");
b.ToTable("ProductComponents");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Request", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int?>("AssemblyId")
.HasColumnType("integer");
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("DateRequest")
.HasColumnType("timestamp without time zone");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AssemblyId");
b.HasIndex("UserId");
b.ToTable("Requests");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.RequestOrder", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("OrderId")
.HasColumnType("integer");
b.Property<int>("RequestId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("OrderId");
b.HasIndex("RequestId");
b.ToTable("RequestOrders");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Shipment", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("DateShipment")
.HasColumnType("timestamp without time zone");
b.Property<string>("ProviderName")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Shipments");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.ShipmentOrder", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("OrderId")
.HasColumnType("integer");
b.Property<int>("ShipmentId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("OrderId");
b.HasIndex("ShipmentId");
b.ToTable("ShipmentOrders");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Login")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<int>("Role")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Assembly", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.User", null)
.WithMany("Assemblies")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.AssemblyComponent", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.Assembly", "Assembly")
.WithMany("Components")
.HasForeignKey("AssemblyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerShopDatabaseImplement.Models.Component", "Component")
.WithMany("AssemblyComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Assembly");
b.Navigation("Component");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Component", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.User", null)
.WithMany("Components")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Order", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.User", null)
.WithMany("Orders")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Product", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.Shipment", "Shipment")
.WithMany("Products")
.HasForeignKey("ShipmentId");
b.HasOne("ComputerShopDatabaseImplement.Models.User", null)
.WithMany("Proucts")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Shipment");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.ProductComponent", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.Component", "Component")
.WithMany("ProductComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerShopDatabaseImplement.Models.Product", "Product")
.WithMany("Components")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Product");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Request", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.Assembly", "Assembly")
.WithMany("Requests")
.HasForeignKey("AssemblyId");
b.HasOne("ComputerShopDatabaseImplement.Models.User", "User")
.WithMany("Requests")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Assembly");
b.Navigation("User");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.RequestOrder", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.Order", "Order")
.WithMany("Requests")
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerShopDatabaseImplement.Models.Request", "Request")
.WithMany("Orders")
.HasForeignKey("RequestId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Order");
b.Navigation("Request");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Shipment", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.User", null)
.WithMany("Shipments")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.ShipmentOrder", b =>
{
b.HasOne("ComputerShopDatabaseImplement.Models.Order", "Order")
.WithMany("Shipments")
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerShopDatabaseImplement.Models.Shipment", "Shipment")
.WithMany("Orders")
.HasForeignKey("ShipmentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Order");
b.Navigation("Shipment");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Assembly", b =>
{
b.Navigation("Components");
b.Navigation("Requests");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Component", b =>
{
b.Navigation("AssemblyComponents");
b.Navigation("ProductComponents");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Order", b =>
{
b.Navigation("Requests");
b.Navigation("Shipments");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Product", b =>
{
b.Navigation("Components");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Request", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.Shipment", b =>
{
b.Navigation("Orders");
b.Navigation("Products");
});
modelBuilder.Entity("ComputerShopDatabaseImplement.Models.User", b =>
{
b.Navigation("Assemblies");
b.Navigation("Components");
b.Navigation("Orders");
b.Navigation("Proucts");
b.Navigation("Requests");
b.Navigation("Shipments");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ComputerShopDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class ПереименовалPriceОлег : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Cost",
table: "Products",
newName: "Price");
migrationBuilder.RenameColumn(
name: "Cost",
table: "Assemblies",
newName: "Price");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Price",
table: "Products",
newName: "Cost");
migrationBuilder.RenameColumn(
name: "Price",
table: "Assemblies",
newName: "Cost");
}
}
}

View File

@ -38,7 +38,7 @@ namespace ComputerShopDatabaseImplement.Migrations
.IsRequired() .IsRequired()
.HasColumnType("text"); .HasColumnType("text");
b.Property<double>("Cost") b.Property<double>("Price")
.HasColumnType("double precision"); .HasColumnType("double precision");
b.Property<int>("UserId") b.Property<int>("UserId")
@ -137,7 +137,7 @@ namespace ComputerShopDatabaseImplement.Migrations
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id")); NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<double>("Cost") b.Property<double>("Price")
.HasColumnType("double precision"); .HasColumnType("double precision");
b.Property<string>("ProductName") b.Property<string>("ProductName")

View File

@ -1,4 +1,5 @@
using ComputerShopContracts.BindingModels; using ComputerShopContracts.BindingModels;
using ComputerShopContracts.ViewModels;
using ComputerShopDataModels.Models; using ComputerShopDataModels.Models;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
@ -16,7 +17,7 @@ namespace ComputerShopDatabaseImplement.Models
public string AssemblyName { get; private set; } = string.Empty; public string AssemblyName { get; private set; } = string.Empty;
[Required] [Required]
public double Cost { get; private set; } public double Price { get; private set; }
[Required] [Required]
public string Category { get; private set; } = string.Empty; public string Category { get; private set; } = string.Empty;
@ -53,7 +54,7 @@ namespace ComputerShopDatabaseImplement.Models
Id = Model.Id, Id = Model.Id,
UserId = Model.UserId, UserId = Model.UserId,
AssemblyName = Model.AssemblyName, AssemblyName = Model.AssemblyName,
Cost = Model.Cost, Price = Model.Price,
Category = Model.Category, Category = Model.Category,
Components = Model.AssemblyComponents.Select(x => new AssemblyComponent Components = Model.AssemblyComponents.Select(x => new AssemblyComponent
{ {
@ -63,6 +64,64 @@ namespace ComputerShopDatabaseImplement.Models
}; };
} }
// TODO: Update(), ViewModel, UpdateComponents() public void Update(AssemblyBindingModel Model)
{
if (!string.IsNullOrEmpty(Model.AssemblyName))
{
AssemblyName = Model.AssemblyName;
}
if (!string.IsNullOrEmpty(Model.Category))
{
Category = Model.Category;
}
Price = Model.Price;
}
public AssemblyViewModel ViewModel => new()
{
Id = Id,
UserId = UserId,
AssemblyName = AssemblyName,
Price = Price,
Category = Category,
AssemblyComponents = AssemblyComponents,
};
public void UpdateComponents(ComputerShopDatabase Context, AssemblyBindingModel Model)
{
var AssemblyComponents = Context.AssemblyComponents.Where(x => x.AssemblyId == Model.Id).ToList();
if (AssemblyComponents != null && AssemblyComponents.Count > 0)
{
Context.AssemblyComponents
.RemoveRange(AssemblyComponents
.Where(x => !Model.AssemblyComponents.ContainsKey(x.ComponentId)));
Context.SaveChanges();
foreach (var ComponentToUpdate in AssemblyComponents)
{
ComponentToUpdate.Count = Model.AssemblyComponents[ComponentToUpdate.ComponentId].Item2;
Model.AssemblyComponents.Remove(ComponentToUpdate.ComponentId);
}
Context.SaveChanges();
}
var CurrentAssembly = Context.Assemblies.First(x => x.Id == Id);
foreach (var AssemblyComponent in Model.AssemblyComponents)
{
Context.AssemblyComponents.Add(new AssemblyComponent
{
Assembly = CurrentAssembly,
Component = Context.Components.First(x => x.Id == AssemblyComponent.Key),
Count = AssemblyComponent.Value.Item2
});
Context.SaveChanges();
}
_assemblyComponents = null;
}
} }
} }

View File

@ -64,9 +64,9 @@ namespace ComputerShopDatabaseImplement.Models
} }
//отдельный метод изменения стоимости заказа (+ или -) на стоимость сборки внутри заявки (после действий с заявками, кот. привязаны к заказу) //отдельный метод изменения стоимости заказа (+ или -) на стоимость сборки внутри заявки (после действий с заявками, кот. привязаны к заказу)
public void ChangeSum(double cost_of_assembly, bool justUpdate = false) public void ChangeSum(double price_of_assembly, bool justUpdate = false)
{ {
Sum += cost_of_assembly; Sum += price_of_assembly;
} }
public OrderViewModel GetViewModel => new() public OrderViewModel GetViewModel => new()

View File

@ -1,4 +1,5 @@
using ComputerShopContracts.BindingModels; using ComputerShopContracts.BindingModels;
using ComputerShopContracts.ViewModels;
using ComputerShopDataModels.Models; using ComputerShopDataModels.Models;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations.Schema;
@ -12,19 +13,19 @@ namespace ComputerShopDatabaseImplement.Models
[Required] [Required]
public int UserId { get; set; } public int UserId { get; set; }
public int? ShipmentId { get; set; }
public virtual Shipment? Shipment { get; set; }
[Required] [Required]
public string ProductName { get; set; } = string.Empty; public string ProductName { get; set; } = string.Empty;
[Required] [Required]
public double Cost { get; set; } public double Price { get; set; }
[Required] [Required]
public int Warranty { get; set; } public int Warranty { get; set; }
public int? ShipmentId { get; set; }
public virtual Shipment? Shipment { get; set; }
[ForeignKey("ProductId")] [ForeignKey("ProductId")]
public virtual List<ProductComponent> Components { get; set; } = new(); public virtual List<ProductComponent> Components { get; set; } = new();
@ -53,16 +54,74 @@ namespace ComputerShopDatabaseImplement.Models
{ {
Id = Model.Id, Id = Model.Id,
UserId = Model.UserId, UserId = Model.UserId,
ShipmentId = Model.ShipmentId,
ProductName = Model.ProductName, ProductName = Model.ProductName,
Cost = Model.Cost, Price = Model.Price,
Warranty = Model.Warranty, Warranty = Model.Warranty,
Components = Model.ProductComponents.Select(x => new ProductComponent Components = Model.ProductComponents.Select(x => new ProductComponent
{ {
Component = Context.Components.First(y => y.Id == x.Key), Component = Context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2 Count = x.Value.Item2
}).ToList(), }).ToList(),
ShipmentId = Model.ShipmentId,
}; };
} }
public void Update(ProductBindingModel Model)
{
if (!string.IsNullOrEmpty(Model.ProductName))
{
ProductName = Model.ProductName;
}
ShipmentId = Model.ShipmentId;
Price = Model.Price;
Warranty = Model.Warranty;
}
public ProductViewModel ViewModel => new()
{
Id = Id,
UserId = UserId,
ShipmentId = ShipmentId,
ProviderName = Shipment?.ProviderName,
Price = Price,
Warranty = Warranty,
ProductComponents = ProductComponents,
};
public void UpdateComponents(ComputerShopDatabase Context, ProductBindingModel Model)
{
var ProductComponents = Context.ProductComponents.Where(x => x.ProductId == Model.Id).ToList();
if (ProductComponents != null && ProductComponents.Count > 0)
{
Context.ProductComponents
.RemoveRange(ProductComponents
.Where(x => !Model.ProductComponents.ContainsKey(x.ComponentId)));
Context.SaveChanges();
foreach (var ComponentToUpdate in ProductComponents)
{
ComponentToUpdate.Count = Model.ProductComponents[ComponentToUpdate.ComponentId].Item2;
Model.ProductComponents.Remove(ComponentToUpdate.ComponentId);
}
Context.SaveChanges();
}
var CurrentProduct = Context.Products.First(x => x.Id == Id);
foreach (var ProductComponent in Model.ProductComponents)
{
Context.ProductComponents.Add(new ProductComponent
{
Product = CurrentProduct,
Component = Context.Components.First(x => x.Id == ProductComponent.Key),
Count = ProductComponent.Value.Item2
});
Context.SaveChanges();
}
_productComponents = null;
}
} }
} }

View File

@ -95,7 +95,7 @@ namespace ComputerShopDatabaseImplement.Models
{ {
var currentRequest = context.Requests.First(x => x.Id == Id); var currentRequest = context.Requests.First(x => x.Id == Id);
//стоимость сборки, связанной с заявкой (или 0, если заявка не связана со сборкой) //стоимость сборки, связанной с заявкой (или 0, если заявка не связана со сборкой)
double cost_of_assembly = (currentRequest.Assembly.Cost != null) ? currentRequest.Assembly.Cost : 0; double price_of_assembly = (currentRequest.Assembly.Price != null) ? currentRequest.Assembly.Price : 0;
var requestOrders = context.RequestOrders.Where(x => x.RequestId == model.Id).ToList(); var requestOrders = context.RequestOrders.Where(x => x.RequestId == model.Id).ToList();
@ -108,7 +108,7 @@ namespace ComputerShopDatabaseImplement.Models
context.RequestOrders.Remove(delOrder); context.RequestOrders.Remove(delOrder);
var order = context.Orders.First(x => x.Id == delOrder.OrderId); var order = context.Orders.First(x => x.Id == delOrder.OrderId);
//вычитание из стоимости соответствующего заказа стоимость соответствующей сборки //вычитание из стоимости соответствующего заказа стоимость соответствующей сборки
order.ChangeSum(-cost_of_assembly); order.ChangeSum(-price_of_assembly);
context.SaveChanges(); context.SaveChanges();
} }
} }
@ -123,7 +123,7 @@ namespace ComputerShopDatabaseImplement.Models
Order = order Order = order
}); });
//увеличение стоимости заказа, с которым связываем заявку, на стоимость сборки //увеличение стоимости заказа, с которым связываем заявку, на стоимость сборки
order.ChangeSum(cost_of_assembly); order.ChangeSum(price_of_assembly);
context.SaveChanges(); context.SaveChanges();
} }
_requestOrders = null; _requestOrders = null;
@ -134,7 +134,7 @@ namespace ComputerShopDatabaseImplement.Models
public void ConnectAssembly(ComputerShopDatabase context, RequestBindingModel model) public void ConnectAssembly(ComputerShopDatabase context, RequestBindingModel model)
{ {
//стоимость старой сборки (или 0, если её не было) //стоимость старой сборки (или 0, если её не было)
double cost_of_old_assembly = (Assembly.Cost != null) ? Assembly.Cost : 0; double price_of_old_assembly = (Assembly.Price != null) ? Assembly.Price : 0;
AssemblyId = model.AssemblyId; AssemblyId = model.AssemblyId;
Assembly = context.Assemblies.First(x => x.Id == model.AssemblyId); Assembly = context.Assemblies.First(x => x.Id == model.AssemblyId);
@ -143,9 +143,9 @@ namespace ComputerShopDatabaseImplement.Models
{ {
var connectedOrder = context.Orders.First(x => x.Id == request_order.Key); var connectedOrder = context.Orders.First(x => x.Id == request_order.Key);
//вычитание из стоимости заказа старой сборки //вычитание из стоимости заказа старой сборки
connectedOrder.ChangeSum(-cost_of_old_assembly); connectedOrder.ChangeSum(-price_of_old_assembly);
//прибавление стоимости новой сборки //прибавление стоимости новой сборки
connectedOrder.ChangeSum(Assembly.Cost); connectedOrder.ChangeSum(Assembly.Price);
context.SaveChanges(); context.SaveChanges();
} }
} }