Почти доделал

This commit is contained in:
2025-05-27 17:31:03 +04:00
parent da946e07ce
commit 491df32c85
279 changed files with 172737 additions and 1121 deletions

View File

@@ -7,6 +7,9 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ClosedXML" Version="0.105.0" />
<PackageReference Include="itext" Version="9.2.0" />
<PackageReference Include="itext7.bouncy-castle-adapter" Version="9.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.4" />
</ItemGroup>

View File

@@ -1,163 +0,0 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreBusinessLogic.Implementations;
public class AssemblyBusinessLogicContract : IAssemblyBusinessLogicContract
{
private readonly ILogger<AssemblyBusinessLogicContract> _logger;
private readonly IAssemblyStorageContract _assemblyStorage;
public AssemblyBusinessLogicContract(ILogger<AssemblyBusinessLogicContract> logger, IAssemblyStorageContract assemblyStorage)
{
_logger = logger;
_assemblyStorage = assemblyStorage;
}
public List<AssemblyViewModel>? ReadList(AssemblyBindingModel? model)
{
_logger.LogInformation("ReadList for assembly. UserID: {UserID}", model?.UserID);
List<AssemblyViewModel> list;
try
{
list = model == null ? _assemblyStorage.GetFullList() : _assemblyStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("GetFullList/GetFilteredList returned null. Returning empty list instead.");
list = new List<AssemblyViewModel>();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error retrieving assembly list from storage.");
return new List<AssemblyViewModel>();
}
_logger.LogInformation("ReadList. Count: {Count}", list.Count);
return list;
}
public AssemblyViewModel? ReadElement(AssemblyBindingModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement for assembly: {Id}, UserID: {UserID}", model.Id, model.UserID);
try
{
var element = _assemblyStorage.GetElement(model);
_logger.LogInformation("ReadElement found: {Id}", element.Id);
return element;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "ReadElement: Assembly not found for ID: {Id}", model.Id);
return null;
}
}
public void Create(AssemblyBindingModel model)
{
CheckModel(model);
try
{
_assemblyStorage.Insert(model);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Insert operation failed for assembly: {Name}", model.Name);
throw new Exception("Insert operation failed", ex);
}
}
public void Update(AssemblyBindingModel model)
{
CheckModel(model);
try
{
_assemblyStorage.Update(model);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Update operation failed for assembly: {Id}", model.Id);
throw new Exception("Update operation failed", ex);
}
}
public void Delete(AssemblyBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Assembly: {Id}", model.Id);
try
{
_assemblyStorage.Delete(model);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Delete operation failed for assembly: {Id}", model.Id);
throw new Exception("Delete operation failed", ex);
}
}
private void CheckModel(AssemblyBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Название сборки обязательно", nameof(model.Name));
}
if (model.Name.Length > 100)
{
throw new ArgumentException("Название сборки не должно превышать 100 символов", nameof(model.Name));
}
if (string.IsNullOrEmpty(model.Description))
{
throw new ArgumentNullException("Описание сборки обязательно", nameof(model.Description));
}
if (model.Description.Length > 500)
{
throw new ArgumentException("Описание сборки не должно превышать 500 символов", nameof(model.Description));
}
if (model.UserID <= 0)
{
throw new ArgumentException("ID пользователя должен быть больше 0", nameof(model.UserID));
}
if (model.OrderRequestId.HasValue && model.OrderRequestId <= 0)
{
throw new ArgumentException("ID заявки должен быть больше 0", nameof(model.OrderRequestId));
}
_logger.LogInformation("Assembly validation passed for: {Name}", model.Name);
var existingAssembly = _assemblyStorage.GetElement(new AssemblyBindingModel { Name = model.Name });
if (existingAssembly != null && existingAssembly.Id != (model.Id ?? 0))
{
throw new InvalidOperationException($"Сборка с названием {model.Name} уже существует");
}
}
}

View File

@@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
namespace ComputerStoreBusinessLogic.Implementations;
public class AssemblyBusinessLogicImplementation : IAssemblyBusinessLogicContract
{
private readonly IAssemblyStorageContract _assemblyStorage;
public AssemblyBusinessLogicImplementation(IAssemblyStorageContract assemblyStorage)
{
_assemblyStorage = assemblyStorage;
}
public List<AssemblyViewModel> GetFullList() => _assemblyStorage.GetFullList();
public AssemblyViewModel? GetElement(int id) => _assemblyStorage.GetElement(id);
public void Create(AssemblyCreateBindingModel model) => _assemblyStorage.Create(model);
public void Update(AssemblyCreateBindingModel model) => _assemblyStorage.Update(model);
public void Delete(int id) => _assemblyStorage.Delete(id);
public List<AssemblyViewModel> GetAssembliesWithoutRequest() => _assemblyStorage.GetAssembliesWithoutRequest();
public List<AssemblyViewModel> GetAssembliesByOrders(List<int> orderIds) => _assemblyStorage.GetAssembliesByOrders(orderIds);
public List<ComponentViewModel> GetComponentsByAssembly(int assemblyId) =>
_assemblyStorage.GetComponentsByAssembly(assemblyId);
public List<AssemblyViewModel> GetUnlinkedAssemblies(int userId) =>
_assemblyStorage.GetUnlinkedAssemblies(userId);
public List<AssemblyViewModel> GetAssembliesByRequest(int requestId) =>
_assemblyStorage.GetAssembliesByRequest(requestId);
public void AttachRequestToAssembly(int assemblyId, int requestId) =>
_assemblyStorage.AttachRequestToAssembly(assemblyId, requestId);
public void DetachRequestFromAssembly(int assemblyId) =>
_assemblyStorage.DetachRequestFromAssembly(assemblyId);
}

View File

@@ -1,186 +0,0 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreBusinessLogic.Implementations;
public class ComponentBusinessLogicContract : IComponentBusinessLogicContract
{
private readonly ILogger<ComponentBusinessLogicContract> _logger;
private readonly IComponentStorageContract _componentStorage;
public ComponentBusinessLogicContract(ILogger<ComponentBusinessLogicContract> logger, IComponentStorageContract componentStorage)
{
_logger = logger;
_componentStorage = componentStorage;
}
public List<ComponentViewModel>? ReadList(ComponentBindingModel? model)
{
_logger.LogInformation("ReadList for component. UserID: {UserID}", model?.UserID);
List<ComponentViewModel> list;
try
{
list = model == null ? _componentStorage.GetFullList() : _componentStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("GetFullList/GetFilteredList returned null. Returning empty list instead.");
list = new List<ComponentViewModel>();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error retrieving component list from storage.");
return new List<ComponentViewModel>();
}
_logger.LogInformation("ReadList. Count: {Count}", list.Count);
return list;
}
public ComponentViewModel? ReadElement(ComponentBindingModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement for component: {Id}, UserID: {UserID}", model.Id, model.UserID);
try
{
var element = _componentStorage.GetElement(model);
_logger.LogInformation("ReadElement found: {Id}", element.Id);
return element;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "ReadElement: Component not found for ID: {Id}", model.Id);
return null;
}
}
public void Create(ComponentBindingModel model)
{
CheckModel(model);
try
{
_componentStorage.Insert(model);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Insert operation failed for component: {ComponentName}", model.ComponentName);
throw new Exception("Insert operation failed", ex);
}
}
public void Update(ComponentBindingModel model)
{
CheckModel(model);
try
{
_componentStorage.Update(model);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Update operation failed for component: {Id}", model.Id);
throw new Exception("Update operation failed", ex);
}
}
public void Delete(ComponentBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Component: {Id}", model.Id);
try
{
_componentStorage.Delete(model);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Delete operation failed for component: {Id}", model.Id);
throw new Exception("Delete operation failed", ex);
}
}
public List<ComponentRequestAssemblyReportViewModel>? GetComponentsReport(DateTime startDate, DateTime endDate, int userId)
{
_logger.LogInformation("Generating components report for user: {UserID}, Period: {StartDate} - {EndDate}", userId, startDate, endDate);
try
{
var report = _componentStorage.GetComponentsReport(startDate, endDate, userId);
if (report == null)
{
_logger.LogWarning("GetComponentsReport returned null. Returning empty list instead.");
return new List<ComponentRequestAssemblyReportViewModel>();
}
_logger.LogInformation("Components report generated. Count: {Count}", report.Count);
return report;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error generating components report for user: {UserID}", userId);
return new List<ComponentRequestAssemblyReportViewModel>();
}
}
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 ArgumentNullException("Название комплектующего обязательно", nameof(model.ComponentName));
}
if (model.ComponentName.Length > 100)
{
throw new ArgumentException("Название комплектующего не должно превышать 100 символов", nameof(model.ComponentName));
}
if (string.IsNullOrEmpty(model.Manufacturer))
{
throw new ArgumentNullException("Производитель обязателен", nameof(model.Manufacturer));
}
if (model.Manufacturer.Length > 100)
{
throw new ArgumentException("Производитель не должен превышать 100 символов", nameof(model.Manufacturer));
}
if (model.Price <= 0)
{
throw new ArgumentException("Цена должна быть больше 0", nameof(model.Price));
}
if (model.UserID <= 0)
{
throw new ArgumentException("ID пользователя должен быть больше 0", nameof(model.UserID));
}
_logger.LogInformation("Component validation passed for: {ComponentName}", model.ComponentName);
var existingComponent = _componentStorage.GetElement(new ComponentBindingModel { ComponentName = model.ComponentName });
if (existingComponent != null && existingComponent.Id != (model.Id ?? 0))
{
throw new InvalidOperationException($"Комплектующее с названием {model.ComponentName} уже существует");
}
}
}

View File

@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
namespace ComputerStoreBusinessLogic.Implementations;
public class ComponentBusinessLogicImplementation : IComponentBusinessLogicContract
{
private readonly IComponentStorageContract _componentStorage;
public ComponentBusinessLogicImplementation(IComponentStorageContract componentStorage)
{
_componentStorage = componentStorage;
}
public List<ComponentViewModel> GetFullList() => _componentStorage.GetFullList();
public ComponentViewModel? GetElement(int id) => _componentStorage.GetElement(id);
public void Create(ComponentCreateBindingModel model) => _componentStorage.Create(model);
public void Update(ComponentCreateBindingModel model) => _componentStorage.Update(model);
public void Delete(int id) => _componentStorage.Delete(id);
public List<ProductViewModel> GetProductsByComponents(List<int> componentIds) => _componentStorage.GetProductsByComponents(componentIds);
public List<OrderBatchViewModel> GetUnlinkedBatches(int productId) => _componentStorage.GetUnlinkedBatches(productId);
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
using iText.Commons.Actions.Contexts;
namespace ComputerStoreBusinessLogic.Implementations;
public class OrderBatchBusinessLogicImplementation : IOrderBatchBusinessLogicContract
{
private readonly IOrderBatchStorageContract _orderBatchStorage;
public OrderBatchBusinessLogicImplementation(IOrderBatchStorageContract orderBatchStorage)
{
_orderBatchStorage = orderBatchStorage;
}
public List<OrderBatchViewModel> GetFullList() => _orderBatchStorage.GetFullList();
public OrderBatchViewModel? GetElement(int id) => _orderBatchStorage.GetElement(id);
public void Create(OrderBatchCreateBindingModel model) => _orderBatchStorage.Create(model);
public void Update(OrderBatchCreateBindingModel model) => _orderBatchStorage.Update(model);
public void Delete(int id) => _orderBatchStorage.Delete(id);
public List<OrderBatchViewModel> GetBatchesWithoutProduct(int userId, int productId) =>
_orderBatchStorage.GetBatchesWithoutProduct(userId, productId);
public List<OrderBatchViewModel> GetBatchesByProduct(int userId) =>
_orderBatchStorage.GetBatchesByProduct(userId);
public void AssignProductToBatches(List<int> batchIds, int productId) =>
_orderBatchStorage.AssignProductToBatches(batchIds, productId);
public List<OrderViewModel> GetOrdersByBatch(int batchId) => _orderBatchStorage.GetOrdersByBatch(batchId);
public void AddOrdersToBatch(int batchId, List<int> orderIds) => _orderBatchStorage.AddOrdersToBatch(batchId, orderIds);
public void RemoveOrdersFromBatch(int batchId, List<int> orderIds) => _orderBatchStorage.RemoveOrdersFromBatch(batchId, orderIds);
public List<AssemblyViewModel> GetUnlinkedAssemblies(int orderId) => _orderBatchStorage.GetUnlinkedAssemblies(orderId);
public List<AssemblyViewModel> GetAssembliesByOrders(List<int> orderIds) => _orderBatchStorage.GetAssembliesByOrders(orderIds);
}

View File

@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
namespace ComputerStoreBusinessLogic.Implementations;
public class OrderBusinessLogicImplementation : IOrderBusinessLogicContract
{
private readonly IOrderStorageContract _orderStorage;
public OrderBusinessLogicImplementation(IOrderStorageContract orderStorage)
{
_orderStorage = orderStorage;
}
public List<OrderViewModel> GetFullList() => _orderStorage.GetFullList();
public OrderViewModel? GetElement(int id) => _orderStorage.GetElement(id);
public void Create(OrderCreateBindingModel model) => _orderStorage.Create(model);
public void Update(OrderCreateBindingModel model) => _orderStorage.Update(model);
public void Delete(int id) => _orderStorage.Delete(id);
public List<OrderReportViewModel> GetOrdersWithDetailsByDateRange(int userId, DateTime start, DateTime end) =>
_orderStorage.GetOrdersWithDetailsByDateRange(userId, start, end);
}

View File

@@ -1,163 +0,0 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreBusinessLogic.Implementations;
public class ProductBusinessLogicContract : IProductBusinessLogicContract
{
private readonly ILogger<ProductBusinessLogicContract> _logger;
private readonly IProductStorageContract _productStorage;
public ProductBusinessLogicContract(ILogger<ProductBusinessLogicContract> logger, IProductStorageContract productStorage)
{
_logger = logger;
_productStorage = productStorage;
}
public List<ProductViewModel>? ReadList(ProductBindingModel? model)
{
_logger.LogInformation("ReadList for product. UserID: {UserID}", model?.UserID);
List<ProductViewModel> list;
try
{
list = model == null ? _productStorage.GetFullList() : _productStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("GetFullList/GetFilteredList returned null. Returning empty list instead.");
list = new List<ProductViewModel>();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error retrieving product list from storage.");
return new List<ProductViewModel>();
}
_logger.LogInformation("ReadList. Count: {Count}", list.Count);
return list;
}
public ProductViewModel? ReadElement(ProductBindingModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement for product: {Id}, UserID: {UserID}", model.Id, model.UserID);
try
{
var element = _productStorage.GetElement(model);
_logger.LogInformation("ReadElement found: {Id}", element.Id);
return element;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "ReadElement: Product not found for ID: {Id}", model.Id);
return null;
}
}
public void Create(ProductBindingModel model)
{
CheckModel(model);
try
{
_productStorage.Insert(model);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Insert operation failed for product: {Name}", model.Name);
throw new Exception("Insert operation failed", ex);
}
}
public void Update(ProductBindingModel model)
{
CheckModel(model);
try
{
_productStorage.Update(model);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Update operation failed for product: {Id}", model.Id);
throw new Exception("Update operation failed", ex);
}
}
public void Delete(ProductBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Product: {Id}", model.Id);
try
{
_productStorage.Delete(model);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Delete operation failed for product: {Id}", model.Id);
throw new Exception("Delete operation failed", ex);
}
}
private void CheckModel(ProductBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Название товара обязательно", nameof(model.Name));
}
if (model.Name.Length > 100)
{
throw new ArgumentException("Название товара не должно превышать 100 символов", nameof(model.Name));
}
if (string.IsNullOrEmpty(model.Category))
{
throw new ArgumentNullException("Категория товара обязательна", nameof(model.Category));
}
if (model.Category.Length > 100)
{
throw new ArgumentException("Категория товара не должна превышать 100 символов", nameof(model.Category));
}
if (model.Price <= 0)
{
throw new ArgumentException("Цена должна быть больше 0", nameof(model.Price));
}
if (model.UserID <= 0)
{
throw new ArgumentException("ID пользователя должен быть больше 0", nameof(model.UserID));
}
_logger.LogInformation("Product validation passed for: {Name}", model.Name);
var existingProduct = _productStorage.GetElement(new ProductBindingModel { Name = model.Name });
if (existingProduct != null && existingProduct.Id != (model.Id ?? 0))
{
throw new InvalidOperationException($"Товар с названием {model.Name} уже существует");
}
}
}

View File

@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
namespace ComputerStoreBusinessLogic.Implementations;
public class ProductBusinessLogicImplementation : IProductBusinessLogicContract
{
private readonly IProductStorageContract _productStorage;
private readonly IOrderBatchStorageContract _orderBatchLogic;
public ProductBusinessLogicImplementation(IProductStorageContract productStorage, IOrderBatchStorageContract orderBatch)
{
_productStorage = productStorage;
_orderBatchLogic = orderBatch;
}
public List<ProductViewModel> GetFullList() => _productStorage.GetFullList();
public ProductViewModel? GetElement(int id) => _productStorage.GetElement(id);
public void Create(ProductCreateBindingModel model) => _productStorage.Create(model);
public void Update(ProductCreateBindingModel model) => _productStorage.Update(model);
public void Delete(int id) => _productStorage.Delete(id);
public void AttachBatchesToProduct(int productId, List<int> batchIds)
{
_orderBatchLogic.AssignProductToBatches(batchIds, productId);
}
public List<OrderBatchViewModel> GetBatchesByComponents(List<int> componentIds) => _productStorage.GetBatchesByComponents(componentIds);
public List<OrderBatchViewModel> GetUnlinkedBatches(int productId) => _productStorage.GetUnlinkedBatches(productId);
public List<ComponentViewModel> GetAllByComponent(int componentId) => _productStorage.GetAllByComponent(componentId);
}

View File

@@ -0,0 +1,129 @@
using System.Net.Mail;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using System.Net;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.ViewModels;
using iText.Kernel.Pdf.Canvas.Draw;
using ClosedXML.Excel;
using iText.Layout.Properties;
using iText.Kernel.Font;
using System.Net.Mime;
namespace ComputerStoreBusinessLogic.Implementations;
public class ReportService : IReportService
{
public byte[] GeneratePdf(List<OrderReportViewModel> data)
{
using var memoryStream = new MemoryStream();
var writer = new PdfWriter(memoryStream);
var pdf = new PdfDocument(writer);
var document = new Document(pdf);
// Загружаем шрифт с поддержкой кириллицы
var fontPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/fonts", "Montserrat-VariableFont_wght.ttf");
var font = PdfFontFactory.CreateFont(fontPath, "Identity-H"); // Identity-H для Unicode
// Устанавливаем шрифт по умолчанию
document.SetFont(font);
document.Add(new Paragraph("Отчет по заказам за период").SetFontSize(12));
document.Add(new Paragraph(" "));
var table = new Table(UnitValue.CreatePercentArray(7)).UseAllAvailableWidth();
table.AddHeaderCell("Order ID");
table.AddHeaderCell("Статус");
table.AddHeaderCell("Дата");
table.AddHeaderCell("Request ID");
table.AddHeaderCell("Описание заявки");
table.AddHeaderCell("Product ID");
table.AddHeaderCell("Название товара");
foreach (var item in data)
{
if (item.ProductId == 0)
{
continue;
};
table.AddCell(item.OrderId.ToString());
table.AddCell(item.OrderStatus);
table.AddCell(item.CreatedAt.ToShortDateString());
table.AddCell(item.RequestId.ToString());
table.AddCell(item.RequestDescription);
table.AddCell(item.ProductId.ToString());
table.AddCell(item.ProductName);
}
document.Add(table);
document.Close();
return memoryStream.ToArray();
}
public byte[] GenerateExcel(List<AssemblyViewModel> data)
{
using var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Сборки");
worksheet.Cell(1, 1).Value = "ID";
worksheet.Cell(1, 2).Value = "Название";
worksheet.Cell(1, 3).Value = "Описание";
for (int i = 0; i < data.Count; i++)
{
worksheet.Cell(i + 2, 1).Value = data[i].Id;
worksheet.Cell(i + 2, 2).Value = data[i].Name;
worksheet.Cell(i + 2, 3).Value = data[i].Description;
}
using var stream = new MemoryStream();
workbook.SaveAs(stream);
return stream.ToArray();
}
public byte[] GenerateExcelBatchesByComponents(List<OrderBatchViewModel> data)
{
using var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Партии товаров");
worksheet.Cell(1, 1).Value = "ID";
worksheet.Cell(1, 2).Value = "Название партии";
for (int i = 0; i < data.Count; i++)
{
worksheet.Cell(i + 2, 1).Value = data[i].Id;
worksheet.Cell(i + 2, 2).Value = data[i].Name;
}
using var stream = new MemoryStream();
workbook.SaveAs(stream);
return stream.ToArray();
}
public async Task SendEmailWithReport(string email, byte[] fileData, string fileName)
{
SmtpClient _smtpClient = new SmtpClient("smtp.gmail.com")
{
Port = 587,
Credentials = new NetworkCredential("nsshipilov@gmail.com", "pftn icnc mmcf jyun"),
EnableSsl = true
};
var message = new MailMessage(
from: "nsshipilov@gmail.com",
to: email,
subject: "Отчет по визиту",
body: "Прикреплен отчет за визит в формате PDF"
)
{
IsBodyHtml = false
};
// Добавляем вложение
using var ms = new MemoryStream(fileData);
var attachment = new Attachment(ms, fileName, MediaTypeNames.Application.Pdf);
message.Attachments.Add(attachment);
await _smtpClient.SendMailAsync(message);
}
}

View File

@@ -1,142 +0,0 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreBusinessLogic.Implementations;
public class RequestBusinessLogicContract : IRequestBusinessLogicContract
{
private readonly ILogger<RequestBusinessLogicContract> _logger;
private readonly IRequestStorageContract _requestStorage;
public RequestBusinessLogicContract(ILogger<RequestBusinessLogicContract> logger, IRequestStorageContract requestStorage)
{
_logger = logger;
_requestStorage = requestStorage;
}
public List<RequestViewModel>? ReadList(RequestBindingModel? model)
{
_logger.LogInformation("ReadList for request. UserID: {UserID}", model?.UserID);
List<RequestViewModel> list;
try
{
list = model == null ? _requestStorage.GetFullList() : _requestStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("GetFullList/GetFilteredList returned null. Returning empty list instead.");
list = new List<RequestViewModel>();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error retrieving request list from storage.");
return new List<RequestViewModel>();
}
_logger.LogInformation("ReadList. Count: {Count}", list.Count);
return list;
}
public RequestViewModel? ReadElement(RequestBindingModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement for request: {Id}, UserID: {UserID}", model.Id, model.UserID);
try
{
var element = _requestStorage.GetElement(model);
_logger.LogInformation("ReadElement found: {Id}", element.Id);
return element;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "ReadElement: Request not found for ID: {Id}", model.Id);
return null;
}
}
public void Create(RequestBindingModel model)
{
CheckModel(model);
try
{
_requestStorage.Insert(model);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Insert operation failed for request: {Id}", model.Id);
throw new Exception("Insert operation failed", ex);
}
}
public void Update(RequestBindingModel model)
{
CheckModel(model);
try
{
_requestStorage.Update(model);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Update operation failed for request: {Id}", model.Id);
throw new Exception("Update operation failed", ex);
}
}
public void Delete(RequestBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Request: {Id}", model.Id);
try
{
_requestStorage.Delete(model);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Delete operation failed for request: {Id}", model.Id);
throw new Exception("Delete operation failed", ex);
}
}
private void CheckModel(RequestBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (model.DateRequest == default)
{
throw new ArgumentNullException("Дата заявки обязательна", nameof(model.DateRequest));
}
if (model.UserID <= 0)
{
throw new ArgumentException("ID пользователя должен быть больше 0", nameof(model.UserID));
}
if (model.AssemblyId.HasValue && model.AssemblyId <= 0)
{
throw new ArgumentException("ID сборки должен быть больше 0", nameof(model.AssemblyId));
}
_logger.LogInformation("Request validation passed for: {Id}", model.Id);
}
}

View File

@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
namespace ComputerStoreBusinessLogic.Implementations;
public class RequestBusinessLogicImplementation : IRequestBusinessLogicContract
{
private readonly IRequestStorageContract _requestStorage;
public RequestBusinessLogicImplementation(IRequestStorageContract requestStorage)
{
_requestStorage = requestStorage;
}
public List<RequestViewModel> GetFullList() => _requestStorage.GetFullList();
public RequestViewModel? GetElement(int id) => _requestStorage.GetElement(id);
public void Create(RequestCreateBindingModel model) => _requestStorage.Create(model);
public void Update(RequestCreateBindingModel model) => _requestStorage.Update(model);
public void Delete(int id) => _requestStorage.Delete(id);
public void AttachAssemblyToRequest(int requestId, int assemblyId) => _requestStorage.AttachAssemblyToRequest(requestId, assemblyId);
public List<OrderViewModel> GetOrdersByRequest(int requestId) => _requestStorage.GetOrdersByRequest(requestId);
public void AddOrdersToRequest(int requestId, List<int> orderIds) => _requestStorage.AddOrdersToRequest(requestId, orderIds);
public void RemoveOrdersFromRequest(int requestId, List<int> orderIds) => _requestStorage.RemoveOrdersFromRequest(requestId, orderIds);
public List<AssemblyViewModel> GetUnlinkedAssemblies(int requestId)
{
return _requestStorage.GetUnlinkedAssemblies(requestId);
}
}

View File

@@ -1,190 +0,0 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreBusinessLogic.Implementations;
public class UserBusinessLogicContract : IUserBusinessLogicContract
{
private readonly ILogger<UserBusinessLogicContract> _logger;
private readonly IUserStorageContract _userStorage;
public UserBusinessLogicContract(ILogger<UserBusinessLogicContract> logger, IUserStorageContract userStorage)
{
_logger = logger;
_userStorage = userStorage;
}
public List<UserViewModel>? ReadList(UserBindingModel? model)
{
_logger.LogInformation("ReadList for user: {Login}", model?.Login);
List<UserViewModel> list;
try
{
list = model == null ? _userStorage.GetFullList() : _userStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("GetFullList/GetFilteredList returned null. Returning empty list instead.");
list = new List<UserViewModel>();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error retrieving user list from storage.");
return new List<UserViewModel>();
}
_logger.LogInformation("ReadList. Count: {Count}", list.Count);
return list;
}
public UserViewModel? ReadElement(UserBindingModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement for user: {Login}", model.Login);
try
{
var element = _userStorage.GetElement(model);
_logger.LogInformation("ReadElement found: {Login}", element.Login);
return element;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "ReadElement: User not found for login: {Login}", model.Login);
return null;
}
}
public void Create(UserBindingModel model)
{
CheckModel(model);
try
{
_userStorage.Insert(model);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Insert operation failed for user: {Login}", model.Login);
throw new Exception("Insert operation failed", ex);
}
}
public void Update(UserBindingModel model)
{
CheckModel(model);
try
{
_userStorage.Update(model);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Update operation failed for user: {Login}", model.Login);
throw new Exception("Update operation failed", ex);
}
}
public void Delete(UserBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Login: {Login}", model.Login);
try
{
_userStorage.Delete(model);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Delete operation failed for user: {Login}", model.Login);
throw new Exception("Delete operation failed", ex);
}
}
private void CheckModel(UserBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Login))
{
throw new ArgumentNullException("Логин обязателен", nameof(model.Login));
}
if (model.Login.Length > 50)
{
throw new ArgumentException("Логин не должен превышать 50 символов", nameof(model.Login));
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Пароль обязателен", nameof(model.Password));
}
if (model.Password.Length > 8)
{
throw new ArgumentException("Пароль не должен превышать 8 символов", nameof(model.Password));
}
if (!model.Password.Any(char.IsLetter) || !model.Password.Any(char.IsDigit))
{
throw new ArgumentException("Пароль должен содержать хотя бы одну букву и одну цифру", nameof(model.Password));
}
if (string.IsNullOrEmpty(model.FIO))
{
throw new ArgumentNullException("ФИО обязательно", nameof(model.FIO));
}
if (model.FIO.Length > 100)
{
throw new ArgumentException("ФИО не должно превышать 100 символов", nameof(model.FIO));
}
if (string.IsNullOrEmpty(model.Email))
{
throw new ArgumentNullException("Email обязателен", nameof(model.Email));
}
if (model.Email.Length > 100)
{
throw new ArgumentException("Email не должен превышать 100 символов", nameof(model.Email));
}
if (!new System.ComponentModel.DataAnnotations.EmailAddressAttribute().IsValid(model.Email))
{
throw new ArgumentException("Некорректный формат email", nameof(model.Email));
}
_logger.LogInformation("User validation passed for: {Login}", model.Login);
var existingUserByLogin = _userStorage.GetElement(new UserBindingModel { Login = model.Login });
var existingUserByEmail = _userStorage.GetElement(new UserBindingModel { Email = model.Email });
if (existingUserByLogin != null && existingUserByLogin.ID != (model.Id ?? 0))
{
throw new InvalidOperationException($"Пользователь с логином {model.Login} уже существует");
}
if (existingUserByEmail != null && existingUserByEmail.ID != (model.Id ?? 0))
{
throw new InvalidOperationException($"Пользователь с email {model.Email} уже существует");
}
}
}

View File

@@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.Enums;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
namespace ComputerStoreBusinessLogic.Implementations;
public class UserBusinessLogicImplementation : IUserBusinessLogicContract
{
private readonly IUserStorageContract _userStorage;
public UserBusinessLogicImplementation(IUserStorageContract userStorage)
{
_userStorage = userStorage;
}
public List<UserViewModel> GetFullList() => _userStorage.GetFullList();
public UserViewModel? GetElement(int id) => _userStorage.GetElement(id);
public void Create(UserBindingModel model)
{
if (string.IsNullOrEmpty(model.Login))
throw new ArgumentException("Логин не может быть пустым");
if (model.RoleType == UserType.Executor && model.Password.Length < 6)
throw new ArgumentException("Пароль слишком короткий");
_userStorage.Create(model);
}
public void Update(UserBindingModel model)
{
if (model.ID <= 0)
throw new ArgumentException("Неверный ID пользователя");
var existing = _userStorage.GetElement(model.ID);
if (existing == null)
throw new InvalidOperationException("Пользователь не найден");
if (string.IsNullOrEmpty(model.Login))
throw new ArgumentException("Логин не может быть пустым");
// Если пароль не указан — не меняем его
if (string.IsNullOrEmpty(model.Password))
{
var originalPassword = existing.Password;
model.Password = originalPassword;
}
_userStorage.Update(model);
}
public void Delete(int id)
{
if (id <= 0)
throw new ArgumentException("Неверный ID");
_userStorage.Delete(id);
}
public bool Authenticate(string login, string password, out UserViewModel? user)
{
user = _userStorage.GetFullList().FirstOrDefault(u => u.Login == login && u.Password == password);
return user != null;
}
public bool IsExecutor(int userId)
{
var user = _userStorage.GetElement(userId);
return user?.RoleType == UserType.Executor;
}
public bool IsGuarantor(int userId)
{
var user = _userStorage.GetElement(userId);
return user?.RoleType == UserType.Guarantor;
}
}

View File

@@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.BindingModels;
public class AssemblyBindingModel
{
public int? Id { get; set; }
public string? AssemblyName { get; set; }
public string? Description { get; set; }
public int UserId { get; set; }
public int? OrderRequestId { get; set; }
public List<int>? Components { get; set; }
}

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.BindingModels;
public class AssemblyCreateBindingModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public int UserId { get; set; }
public List<int> ComponentIds { get; set; } = new();
}

View File

@@ -1,16 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.BindingModels;
public class ComponentBindingModel
{
public int? Id { get; set; }
public string? ComponentName { get; set; }
public string? Manufacturer { get; set; }
public double Price { get; set; }
public int UserId { get; set; }
}

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.BindingModels;
public class ComponentCreateBindingModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; } = string.Empty;
public string Manufacturer { get; set; } = string.Empty;
public decimal Price { get; set; }
public int UserId { get; set; }
}

View File

@@ -1,16 +1,17 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.BindingModels;
public class ProductBindingModel
public class OrderBatchCreateBindingModel
{
public int? Id { get; set; }
public string? ProductName { get; set; }
public string? Category { get; set; }
public double Price { get; set; }
public int Id { get; set; }
[Required]
public string Name { get; set; } = string.Empty;
public int UserId { get; set; }
}

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.BindingModels;
public class OrderCreateBindingModel
{
public int Id { get; set; }
[Required(ErrorMessage = "Статус обязателен")]
public string Status { get; set; } = string.Empty;
public int UserId { get; set; }
public List<int> RequestIds { get; set; } = new();
public List<int> BatchIds { get; set; } = new();
}

View File

@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.BindingModels;
public class ProductCreateBindingModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
public int UserId { get; set; }
public List<int> ComponentIds { get; set; } = new();
}

View File

@@ -1,15 +1,19 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.BindingModels;
public class RequestBindingModel
public class RequestCreateBindingModel
{
public int? Id { get; set; }
public DateTime DateRequest { get; set; }
public int? AssemblyId { get; set; }
public int Id { get; set; }
[Required]
public string Description { get; set; } = string.Empty;
public int UserId { get; set; }
}
public int? AssemblyId { get; set; }
}

View File

@@ -1,18 +1,29 @@
using ComputerStoreContracts.Enums;
using System;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerStoreContracts.Enums;
namespace ComputerStoreContracts.BindingModels;
public class UserBindingModel
{
public int? Id { get; set; }
public string? Login { get; set; }
public string? Password { get; set; }
public string? FIO { get; set; }
public string? Email { get; set; }
public UserType UserType { get; set; }
public int ID { get; set; }
[Required]
public string Login { get; set; } = string.Empty;
public string? Password { get; set; }
[Required]
public string FIO { get; set; } = string.Empty;
[Required]
[EmailAddress]
public string Email { get; set; } = string.Empty;
[Required]
public UserType RoleType { get; set; }
}

View File

@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerStoreContracts.Enums;
namespace ComputerStoreContracts.BindingModels;
public class UserRegisterBindingModel
{
[Required]
public string Login { get; set; } = string.Empty;
[Required]
public string Password { get; set; } = string.Empty;
[Required]
public string FIO { get; set; } = string.Empty;
[Required]
[EmailAddress]
public string Email { get; set; } = string.Empty;
[Required]
public UserType RoleType { get; set; }
}

View File

@@ -1,18 +1,23 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.BusinessLogicContracts;
public interface IAssemblyBusinessLogicContract
{
List<AssemblyViewModel>? ReadList(AssemblyBindingModel? model);
AssemblyViewModel? ReadElement(AssemblyBindingModel model);
void Create(AssemblyBindingModel model);
void Update(AssemblyBindingModel model);
void Delete(AssemblyBindingModel model);
}
List<AssemblyViewModel> GetFullList();
AssemblyViewModel? GetElement(int id);
void Create(AssemblyCreateBindingModel model);
void Update(AssemblyCreateBindingModel model);
void Delete(int id);
// Бизнес-методы
List<ComponentViewModel> GetComponentsByAssembly(int assemblyId);
List<AssemblyViewModel> GetUnlinkedAssemblies(int userId);
List<AssemblyViewModel> GetAssembliesByRequest(int requestId);
void AttachRequestToAssembly(int assemblyId, int requestId);
void DetachRequestFromAssembly(int assemblyId);
List<AssemblyViewModel> GetAssembliesWithoutRequest();
List<AssemblyViewModel> GetAssembliesByOrders(List<int> orderIds);
}

View File

@@ -1,19 +1,16 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.BusinessLogicContracts;
public interface IComponentBusinessLogicContract
{
List<ComponentViewModel>? ReadList(ComponentBindingModel? model);
ComponentViewModel? ReadElement(ComponentBindingModel model);
void Create(ComponentBindingModel model);
void Update(ComponentBindingModel model);
void Delete(ComponentBindingModel model);
List<ComponentRequestAssemblyReportViewModel>? GetComponentsReport(DateTime startDate, DateTime endDate, int userId);
List<ComponentViewModel> GetFullList();
ComponentViewModel? GetElement(int id);
void Create(ComponentCreateBindingModel model);
void Update(ComponentCreateBindingModel model);
void Delete(int id);
List<ProductViewModel> GetProductsByComponents(List<int> componentIds);
List<OrderBatchViewModel> GetUnlinkedBatches(int productId);
}

View File

@@ -0,0 +1,21 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.ViewModels;
namespace ComputerStoreContracts.BusinessLogicContracts;
public interface IOrderBatchBusinessLogicContract
{
List<OrderBatchViewModel> GetFullList();
OrderBatchViewModel? GetElement(int id);
void Create(OrderBatchCreateBindingModel model);
void Update(OrderBatchCreateBindingModel model);
void Delete(int id);
List<OrderViewModel> GetOrdersByBatch(int batchId);
void AddOrdersToBatch(int batchId, List<int> orderIds);
void RemoveOrdersFromBatch(int batchId, List<int> orderIds);
List<OrderBatchViewModel> GetBatchesByProduct(int userId);
List<OrderBatchViewModel> GetBatchesWithoutProduct(int userId, int productId);
void AssignProductToBatches(List<int> batchIds, int productId);
List<AssemblyViewModel> GetUnlinkedAssemblies(int orderId);
List<AssemblyViewModel> GetAssembliesByOrders(List<int> orderIds);
}

View File

@@ -0,0 +1,15 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.ViewModels;
namespace ComputerStoreContracts.BusinessLogicContracts;
public interface IOrderBusinessLogicContract
{
List<OrderViewModel> GetFullList();
OrderViewModel? GetElement(int id);
void Create(OrderCreateBindingModel model);
void Update(OrderCreateBindingModel model);
void Delete(int id);
List<OrderReportViewModel> GetOrdersWithDetailsByDateRange(int userId, DateTime start, DateTime end);
}

View File

@@ -1,18 +1,17 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.BusinessLogicContracts;
public interface IProductBusinessLogicContract
{
List<ProductViewModel>? ReadList(ProductBindingModel? model);
ProductViewModel? ReadElement(ProductBindingModel model);
void Create(ProductBindingModel model);
void Update(ProductBindingModel model);
void Delete(ProductBindingModel model);
List<ProductViewModel> GetFullList();
ProductViewModel? GetElement(int id);
void Create(ProductCreateBindingModel model);
void Update(ProductCreateBindingModel model);
void Delete(int id);
List<OrderBatchViewModel> GetBatchesByComponents(List<int> componentIds);
void AttachBatchesToProduct(int productId, List<int> batchIds);
List<OrderBatchViewModel> GetUnlinkedBatches(int productId);
List<ComponentViewModel> GetAllByComponent(int componentId);
}

View File

@@ -0,0 +1,11 @@
using ComputerStoreContracts.ViewModels;
namespace ComputerStoreContracts.BusinessLogicContracts;
public interface IReportService
{
byte[] GeneratePdf(List<OrderReportViewModel> data);
byte[] GenerateExcel(List<AssemblyViewModel> data);
byte[] GenerateExcelBatchesByComponents(List<OrderBatchViewModel> data);
Task SendEmailWithReport(string email, byte[] fileData, string fileName);
}

View File

@@ -1,18 +1,19 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.BusinessLogicContracts;
public interface IRequestBusinessLogicContract
{
List<RequestViewModel>? ReadList(RequestBindingModel? model);
RequestViewModel? ReadElement(RequestBindingModel model);
void Create(RequestBindingModel model);
void Update(RequestBindingModel model);
void Delete(RequestBindingModel model);
}
List<RequestViewModel> GetFullList();
RequestViewModel? GetElement(int id);
void Create(RequestCreateBindingModel model);
void Update(RequestCreateBindingModel model);
void Delete(int id);
List<OrderViewModel> GetOrdersByRequest(int requestId);
void AddOrdersToRequest(int requestId, List<int> orderIds);
void RemoveOrdersFromRequest(int requestId, List<int> orderIds);
List<AssemblyViewModel> GetUnlinkedAssemblies(int requestId);
void AttachAssemblyToRequest(int requestId, int assemblyId);
}

View File

@@ -1,18 +1,16 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.BusinessLogicContracts;
public interface IUserBusinessLogicContract
{
List<UserViewModel>? ReadList(UserBindingModel? model);
UserViewModel? ReadElement(UserBindingModel model);
List<UserViewModel> GetFullList();
UserViewModel? GetElement(int id);
void Create(UserBindingModel model);
void Update(UserBindingModel model);
void Delete(UserBindingModel model);
}
void Delete(int id);
public bool Authenticate(string login, string password, out UserViewModel? user);
public bool IsExecutor(int userId);
public bool IsGuarantor(int userId);
}

View File

@@ -11,9 +11,21 @@ namespace ComputerStoreContracts.StoragesContracts;
public interface IAssemblyStorageContract
{
List<AssemblyViewModel> GetFullList();
List<AssemblyViewModel> GetFilteredList(AssemblyBindingModel model);
AssemblyViewModel GetElement(AssemblyBindingModel model);
AssemblyViewModel Insert(AssemblyBindingModel model);
AssemblyViewModel Update(AssemblyBindingModel model);
AssemblyViewModel Delete(AssemblyBindingModel model);
AssemblyViewModel? GetElement(int id);
void Create(AssemblyCreateBindingModel model);
void Update(AssemblyCreateBindingModel model);
void Delete(int id);
// Получить сборки без привязки к заявке
List<AssemblyViewModel> GetAssembliesWithoutRequest();
// Получить сборки по списку заказов
List<ComponentViewModel> GetComponentsByAssembly(int assemblyId);
List<AssemblyViewModel> GetAssembliesByOrders(List<int> orderIds);
List<AssemblyViewModel> GetUnlinkedAssemblies(int userId);
List<AssemblyViewModel> GetAssembliesByRequest(int requestId);
void AttachRequestToAssembly(int assemblyId, int requestId);
void DetachRequestFromAssembly(int assemblyId);
}

View File

@@ -11,11 +11,14 @@ namespace ComputerStoreContracts.StoragesContracts;
public interface IComponentStorageContract
{
List<ComponentViewModel> GetFullList();
List<ComponentViewModel> GetFilteredList(ComponentBindingModel model);
ComponentViewModel GetElement(ComponentBindingModel model);
ComponentViewModel Insert(ComponentBindingModel model);
ComponentViewModel Update(ComponentBindingModel model);
ComponentViewModel Delete(ComponentBindingModel model);
List<ProductViewModel> GetProductsByComponent(int componentId, int userId);
List<ComponentRequestAssemblyReportViewModel> GetComponentsReport(DateTime startDate, DateTime endDate, int userId);
}
ComponentViewModel? GetElement(int id);
void Create(ComponentCreateBindingModel model);
void Update(ComponentCreateBindingModel model);
void Delete(int id);
// Получить товары по комплектующим
List<ProductViewModel> GetProductsByComponents(List<int> componentIds);
// Получить непривязанные партии товаров
List<OrderBatchViewModel> GetUnlinkedBatches(int productId);
}

View File

@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.ViewModels;
namespace ComputerStoreContracts.StoragesContracts;
public interface IOrderBatchStorageContract
{
List<OrderBatchViewModel> GetFullList();
OrderBatchViewModel? GetElement(int id);
void Create(OrderBatchCreateBindingModel model);
void Update(OrderBatchCreateBindingModel model);
void Delete(int id);
// Методы для поручителя
List<OrderBatchViewModel> GetBatchesByProduct(int userId); // Все партии пользователя (с привязкой)
List<OrderBatchViewModel> GetBatchesWithoutProduct(int userId, int productId);
void AssignProductToBatches(List<int> batchIds, int productId);
List<OrderViewModel> GetOrdersByBatch(int batchId);
void AddOrdersToBatch(int batchId, List<int> orderIds);
void RemoveOrdersFromBatch(int batchId, List<int> orderIds);
// Получить непривязанные сборки (для поручителя)
List<AssemblyViewModel> GetUnlinkedAssemblies(int orderId);
// Получить сборки по выбранным заказам
List<AssemblyViewModel> GetAssembliesByOrders(List<int> orderIds);
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.ViewModels;
namespace ComputerStoreContracts.StoragesContracts;
public interface IOrderStorageContract
{
List<OrderViewModel> GetFullList();
OrderViewModel? GetElement(int id);
void Create(OrderCreateBindingModel model);
void Update(OrderCreateBindingModel model);
void Delete(int id);
// Для поручителя: получить список партий товаров, связанных с выбранными заказами
List<AssemblyViewModel> GetAssembliesByOrders(List<int> orderIds);
// Получить заказы за период, связанные с товарами и заявками
public List<OrderReportViewModel> GetOrdersWithDetailsByDateRange(int userId, DateTime start, DateTime end);
}

View File

@@ -11,9 +11,14 @@ namespace ComputerStoreContracts.StoragesContracts;
public interface IProductStorageContract
{
List<ProductViewModel> GetFullList();
List<ProductViewModel> GetFilteredList(ProductBindingModel model);
ProductViewModel GetElement(ProductBindingModel model);
ProductViewModel Insert(ProductBindingModel model);
ProductViewModel Update(ProductBindingModel model);
ProductViewModel Delete(ProductBindingModel model);
}
ProductViewModel? GetElement(int id);
void Create(ProductCreateBindingModel model);
void Update(ProductCreateBindingModel model);
void Delete(int id);
// Получить непривязанные партии товаров
List<OrderBatchViewModel> GetUnlinkedBatches(int productId);
public List<OrderBatchViewModel> GetBatchesByComponents(List<int> componentIds);
// Получить все товары по комплектующему
List<ComponentViewModel> GetAllByComponent(int componentId);
}

View File

@@ -1,19 +1,25 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.ViewModels;
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.ViewModels;
namespace ComputerStoreContracts.StoragesContracts;
public interface IRequestStorageContract
{
List<RequestViewModel> GetFullList();
List<RequestViewModel> GetFilteredList(RequestBindingModel model);
RequestViewModel GetElement(RequestBindingModel model);
RequestViewModel Insert(RequestBindingModel model);
RequestViewModel Update(RequestBindingModel model);
RequestViewModel Delete(RequestBindingModel model);
RequestViewModel? GetElement(int id);
void Create(RequestCreateBindingModel model);
void Update(RequestCreateBindingModel model);
void Delete(int id);
List<OrderViewModel> GetOrdersByRequest(int requestId);
void AddOrdersToRequest(int requestId, List<int> orderIds);
void RemoveOrdersFromRequest(int requestId, List<int> orderIds);
// Привязать сборку к заявке
List<AssemblyViewModel> GetUnlinkedAssemblies(int requestId);
void AttachAssemblyToRequest(int requestId, int assemblyId);
}

View File

@@ -11,10 +11,8 @@ namespace ComputerStoreContracts.StoragesContracts;
public interface IUserStorageContract
{
List<UserViewModel> GetFullList();
List<UserViewModel> GetFilteredList(UserBindingModel model);
UserViewModel GetElement(UserBindingModel model);
UserViewModel Insert(UserBindingModel model);
UserViewModel Update(UserBindingModel model);
UserViewModel Delete(UserBindingModel model);
}
UserViewModel? GetElement(int id);
void Create(UserBindingModel model);
void Update(UserBindingModel model);
void Delete(int id);
}

View File

@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -10,12 +9,8 @@ namespace ComputerStoreContracts.ViewModels;
public class AssemblyViewModel
{
public int Id { get; set; }
[DisplayName("Имя сборки")]
public string AssemblyName { get; set; } = string.Empty;
[DisplayName("Описание сборки")]
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public int UserID { get; set; }
public int? OrderRequestId { get; set; }
public int UserId { get; set; }
public List<int> ComponentIds { get; set; } = new();
}

View File

@@ -1,25 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.ViewModels;
public class ComponentRequestAssemblyReportViewModel
{
public string ComponentName { get; set; } = string.Empty;
[DisplayName("Даты запросов")]
public List<DateTime> DateRequests { get; set; } = new();
[DisplayName("Сборки")]
public List<string> Assemblies { get; set; } = new();
[DisplayName("Производитель")]
public string Manufacturer { get; set; } = string.Empty;
[DisplayName("ID компонента")]
public int ComponentId { get; set; }
}

View File

@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -10,12 +9,8 @@ namespace ComputerStoreContracts.ViewModels;
public class ComponentViewModel
{
public int Id { get; set; }
[DisplayName("Имя комплектующего")]
public string ComponentName { get; set; } = string.Empty;
[DisplayName("Производитель")]
public string Name { get; set; } = string.Empty;
public string Manufacturer { get; set; } = string.Empty;
public double Price { get; set; }
public decimal Price { get; set; }
public int UserId { get; set; }
}
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.ViewModels;
public class OrderBatchViewModel
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public int UserId { get; set; }
public DateTime CreatedAt { get; set; }
public int? ProductId { get; set; }
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.ViewModels;
public class OrderReportViewModel
{
public int OrderId { get; set; }
public string OrderStatus { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
public int RequestId { get; set; }
public string RequestDescription { get; set; } = string.Empty;
public int ProductId { get; set; }
public string ProductName { get; set; } = string.Empty;
public decimal ProductPrice { get; set; }
public int UserId { get; set; }
public string UserFIO { get; set; } = string.Empty;
}

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerStoreContracts.ViewModels;
public class OrderViewModel
{
public int Id { get; set; }
public string Status { get; set; } = string.Empty;
public int UserId { get; set; }
public DateTime CreatedAt { get; set; }
public List<int> RequestIds { get; set; } = new();
public List<int> BatchIds { get; set; } = new();
}

View File

@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -10,15 +9,8 @@ namespace ComputerStoreContracts.ViewModels;
public class ProductViewModel
{
public int Id { get; set; }
[DisplayName("Название товара")]
public string ProductName { get; set; } = string.Empty;
[DisplayName("Категория товара")]
public string Category { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Price { get; set; }
public int UserID { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
public int UserId { get; set; }
public List<int> ComponentIds { get; set; } = new();
}

View File

@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -9,17 +8,9 @@ namespace ComputerStoreContracts.ViewModels;
public class RequestViewModel
{
[DisplayName("Дата создания")]
public DateTime DateRequest { get; set; } = DateTime.Now;
[DisplayName("ID сборки")]
public int? AssemblyId { get; set; }
public AssemblyViewModel? Assembly { get; set; }
[DisplayName("Номер")]
public int Id { get; set; }
[DisplayName("ID пользователя")]
public int UserID { get; set; }
}
public string Description { get; set; } = string.Empty;
public int UserId { get; set; }
public int? AssemblyId { get; set; }
public DateTime CreatedAt { get; set; }
}

View File

@@ -1,27 +1,18 @@
using ComputerStoreContracts.Enums;
using System;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerStoreContracts.Enums;
namespace ComputerStoreContracts.ViewModels;
public class UserViewModel
{
public int Id { get; set; }
[DisplayName("Логин")]
public int ID { get; set; }
public string Login { get; set; } = string.Empty;
[DisplayName("Пароль")]
public string Password { get; set; } = string.Empty;
[DisplayName("ФИО")]
public string FIO { get; set; } = string.Empty;
[DisplayName("Почта")]
public string Email { get; set; } = string.Empty;
public UserType UserType { get; set; }
public string Password { get; set; } = string.Empty;
public UserType RoleType { get; set; }
}

View File

@@ -8,6 +8,14 @@
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.5" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
<ItemGroup>

View File

@@ -1,12 +1,85 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputerStoreDatabase.Models;
using Microsoft.EntityFrameworkCore;
namespace ComputerStoreDatabase
namespace ComputerStoreDatabase;
public class ComputerStoreDbContext : DbContext
{
internal class ComputerStoreDbContext
public DbSet<User> Users { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Request> Requests { get; set; }
public DbSet<OrderRequest> OrderRequests { get; set; }
public DbSet<OrderBatch> OrderBatches { get; set; }
public DbSet<OrderOrderBatch> OrderOrderBatches { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Component> Components { get; set; }
public DbSet<ProductComponent> ProductComponents { get; set; }
public DbSet<Assembly> Assemblies { get; set; }
public DbSet<ComponentAssembly> ComponentAssemblies { get; set; }
public ComputerStoreDbContext(DbContextOptions<ComputerStoreDbContext> options)
: base(options)
{
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Many-to-many: Product <-> Component
modelBuilder.Entity<ProductComponent>()
.HasKey(pc => pc.Id);
modelBuilder.Entity<ProductComponent>()
.HasOne(pc => pc.Product)
.WithMany(p => p.ComponentsLink)
.HasForeignKey(pc => pc.ProductId);
modelBuilder.Entity<ProductComponent>()
.HasOne(pc => pc.Component)
.WithMany(c => c.ProductsLink)
.HasForeignKey(pc => pc.ComponentId);
// Many-to-many: Order <-> Request
modelBuilder.Entity<OrderRequest>()
.HasKey(or => or.Id);
modelBuilder.Entity<OrderRequest>()
.HasOne(or => or.Order)
.WithMany(o => o.OrderRequests)
.HasForeignKey(or => or.OrderId);
modelBuilder.Entity<OrderRequest>()
.HasOne(or => or.Request)
.WithMany(r => r.OrderRequests)
.HasForeignKey(or => or.RequestId);
// Many-to-many: Order <-> Batch
modelBuilder.Entity<OrderOrderBatch>()
.HasKey(ob => ob.Id);
modelBuilder.Entity<OrderOrderBatch>()
.HasOne(ob => ob.Order)
.WithMany(o => o.OrderBatchesLink)
.HasForeignKey(ob => ob.OrderId);
modelBuilder.Entity<OrderOrderBatch>()
.HasOne(ob => ob.OrderBatch)
.WithMany(b => b.OrdersLink)
.HasForeignKey(ob => ob.OrderBatchId);
// Many-to-many: Component <-> Assembly
modelBuilder.Entity<ComponentAssembly>()
.HasKey(ca => ca.Id);
modelBuilder.Entity<ComponentAssembly>()
.HasOne(ca => ca.Component)
.WithMany(c => c.AssembliesLink)
.HasForeignKey(ca => ca.ComponentId);
modelBuilder.Entity<ComponentAssembly>()
.HasOne(ca => ca.Assembly)
.WithMany(a => a.ComponentsLink)
.HasForeignKey(ca => ca.AssemblyId);
base.OnModelCreating(modelBuilder);
}
}

View File

@@ -0,0 +1,23 @@
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore;
namespace ComputerStoreDatabase;
public class ComputerStoreDbContextFactory : IDesignTimeDbContextFactory<ComputerStoreDbContext>
{
public ComputerStoreDbContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<ComputerStoreDbContext>();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseNpgsql(connectionString);
return new ComputerStoreDbContext(builder.Options);
}
}

View File

@@ -0,0 +1,201 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
using ComputerStoreDatabase.Models;
using Microsoft.EntityFrameworkCore;
namespace ComputerStoreDatabase.Implementations;
public class AssemblyStorageImplementation : IAssemblyStorageContract
{
private readonly ComputerStoreDbContext _context;
public AssemblyStorageImplementation(ComputerStoreDbContext context)
{
_context = context;
}
public List<AssemblyViewModel> GetFullList() => _context.Assemblies
.Select(a => new AssemblyViewModel
{
Id = a.Id,
Name = a.Name,
Description = a.Description,
UserId = a.UserId
}).ToList();
public AssemblyViewModel? GetElement(int id) => _context.Assemblies
.Where(a => a.Id == id)
.Select(a => new AssemblyViewModel
{
Id = a.Id,
Name = a.Name,
Description = a.Description,
UserId = a.UserId
}).FirstOrDefault();
public void Create(AssemblyCreateBindingModel model)
{
var assembly = new Assembly
{
Name = model.Name,
Description = model.Description,
UserId = model.UserId
};
// Добавляем связь с компонентами
foreach (var componentId in model.ComponentIds)
{
var component = _context.Components.Find(componentId);
if (component != null)
{
assembly.ComponentsLink.Add(new ComponentAssembly
{
ComponentId = componentId
});
}
}
_context.Assemblies.Add(assembly);
_context.SaveChanges();
}
public void Update(AssemblyCreateBindingModel model)
{
var assembly = _context.Assemblies
.Include(a => a.ComponentsLink)
.FirstOrDefault(a => a.Id == model.Id);
if (assembly == null) throw new Exception("Сборка не найдена");
assembly.Name = model.Name;
assembly.Description = model.Description;
// Удаляем старые связи
var oldLinks = assembly.ComponentsLink.ToList();
foreach (var link in oldLinks)
{
_context.ComponentAssemblies.Remove(link);
}
// Добавляем новые
foreach (var componentId in model.ComponentIds)
{
_context.ComponentAssemblies.Add(new ComponentAssembly
{
AssemblyId = model.Id,
ComponentId = componentId
});
}
_context.Assemblies.Update(assembly);
_context.SaveChanges();
}
public void Delete(int id)
{
var assembly = _context.Assemblies.Find(id);
if (assembly != null)
{
_context.Assemblies.Remove(assembly);
_context.SaveChanges();
}
}
public List<ComponentViewModel> GetComponentsByAssembly(int assemblyId)
{
return _context.ComponentAssemblies
.Where(ca => ca.AssemblyId == assemblyId)
.Select(ca => new ComponentViewModel
{
Id = ca.Component.Id,
Name = ca.Component.Name,
Manufacturer = ca.Component.Manufacturer,
Price = ca.Component.Price,
UserId = ca.Component.UserID
}).ToList();
}
public List<AssemblyViewModel> GetAssembliesWithoutRequest()
{
var requestAssemblyIds = _context.Requests
.Where(r => r.AssemblyId.HasValue)
.Select(r => r.AssemblyId.Value)
.ToList();
return _context.Assemblies
.Where(a => !requestAssemblyIds.Contains(a.Id))
.Select(a => new AssemblyViewModel
{
Id = a.Id,
Name = a.Name,
Description = a.Description,
UserId = a.UserId
}).ToList();
}
public List<AssemblyViewModel> GetAssembliesByOrders(List<int> orderIds)
{
var requestIds = _context.OrderRequests
.Where(or => orderIds.Contains(or.OrderId))
.Select(or => or.RequestId)
.ToList();
var assemblyIds = _context.Assemblies
.Where(a => a.RequestId.HasValue && requestIds.Contains(a.RequestId.Value))
.Select(a => a.Id)
.Distinct()
.ToList();
return _context.Assemblies
.Where(a => assemblyIds.Contains(a.Id))
.Select(a => new AssemblyViewModel
{
Id = a.Id,
Name = a.Name,
Description = a.Description,
UserId = a.UserId
}).ToList();
}
public List<AssemblyViewModel> GetUnlinkedAssemblies(int userId) => _context.Assemblies
.Where(a => !a.RequestId.HasValue)
.Select(a => new AssemblyViewModel
{
Id = a.Id,
Name = a.Name,
Description = a.Description,
UserId = a.UserId
}).ToList();
public List<AssemblyViewModel> GetAssembliesByRequest(int requestId) => _context.Assemblies
.Where(a => a.RequestId == requestId)
.Select(a => new AssemblyViewModel
{
Id = a.Id,
Name = a.Name,
Description = a.Description,
UserId = a.UserId
}).ToList();
public void AttachRequestToAssembly(int assemblyId, int requestId)
{
var assembly = _context.Assemblies.Find(assemblyId);
if (assembly == null) throw new Exception("Сборка не найдена");
assembly.RequestId = requestId;
_context.Assemblies.Update(assembly);
_context.SaveChanges();
}
public void DetachRequestFromAssembly(int assemblyId)
{
var assembly = _context.Assemblies.Find(assemblyId);
if (assembly == null || !assembly.RequestId.HasValue) return;
assembly.RequestId = null;
_context.Assemblies.Update(assembly);
_context.SaveChanges();
}
}

View File

@@ -0,0 +1,115 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
using ComputerStoreDatabase.Models;
namespace ComputerStoreDatabase.Implementations;
public class ComponentStorageImplementation : IComponentStorageContract
{
private readonly ComputerStoreDbContext _context;
public ComponentStorageImplementation(ComputerStoreDbContext context)
{
_context = context;
}
public List<ComponentViewModel> GetFullList() => _context.Components
.Select(c => new ComponentViewModel
{
Id = c.Id,
Name = c.Name,
Manufacturer = c.Manufacturer,
Price = c.Price,
UserId = c.UserID
}).ToList();
public ComponentViewModel? GetElement(int id) => _context.Components
.Where(c => c.Id == id)
.Select(c => new ComponentViewModel
{
Id = c.Id,
Name = c.Name,
Manufacturer = c.Manufacturer,
Price = c.Price,
UserId = c.UserID
}).FirstOrDefault();
public void Create(ComponentCreateBindingModel model)
{
var component = new Component
{
Name = model.Name,
Manufacturer = model.Manufacturer,
Price = model.Price,
UserID = model.UserId
};
_context.Components.Add(component);
_context.SaveChanges();
}
public void Update(ComponentCreateBindingModel model)
{
var component = _context.Components.Find(model.Id);
if (component == null) throw new Exception("Комплектующее не найдено");
component.Name = model.Name;
component.Manufacturer = model.Manufacturer;
component.Price = model.Price;
_context.Components.Update(component);
_context.SaveChanges();
}
public void Delete(int id)
{
var component = _context.Components.Find(id);
if (component != null)
{
_context.Components.Remove(component);
_context.SaveChanges();
}
}
public List<ProductViewModel> GetProductsByComponents(List<int> componentIds)
{
return _context.ProductComponents
.Where(pc => componentIds.Contains(pc.ComponentId))
.Select(pc => pc.Product)
.Distinct()
.Select(p => new ProductViewModel
{
Id = p.Id,
Name = p.Name,
Price = p.Price,
UserId = p.UserID
}).ToList();
}
public List<OrderBatchViewModel> GetUnlinkedBatches(int productId)
{
var linkedBatchIds = _context.ProductComponents
.Where(pc => pc.ProductId == productId)
.Select(pc => pc.ComponentId)
.ToList();
var componentIds = _context.Components
.Where(c => c.UserID == productId)
.Select(c => c.Id)
.ToList();
var batchIdsWithComponent = _context.OrderOrderBatches
.Where(ob => componentIds.Contains(ob.OrderBatchId))
.Select(ob => ob.OrderBatchId)
.ToList();
return _context.OrderBatches
.Where(b => !batchIdsWithComponent.Contains(b.Id))
.Select(b => new OrderBatchViewModel
{
Id = b.Id,
Name = b.Name,
UserId = b.UserID
}).ToList();
}
}

View File

@@ -0,0 +1,188 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
using ComputerStoreDatabase.Models;
namespace ComputerStoreDatabase.Implementations;
public class OrderBatchStorageImplementation : IOrderBatchStorageContract
{
private readonly ComputerStoreDbContext _context;
public OrderBatchStorageImplementation(ComputerStoreDbContext context)
{
_context = context;
}
public List<OrderBatchViewModel> GetFullList() => _context.OrderBatches
.Select(b => new OrderBatchViewModel
{
Id = b.Id,
Name = b.Name,
UserId = b.UserID,
ProductId = b.ProductId,
CreatedAt = b.CreatedAt,
}).ToList();
public OrderBatchViewModel? GetElement(int id) => _context.OrderBatches
.Where(b => b.Id == id)
.Select(b => new OrderBatchViewModel
{
Id = b.Id,
Name = b.Name,
UserId = b.UserID,
CreatedAt = b.CreatedAt,
}).FirstOrDefault();
public void Create(OrderBatchCreateBindingModel model)
{
var batch = new OrderBatch
{
Name = model.Name,
UserID = model.UserId,
CreatedAt = DateTime.UtcNow,
};
_context.OrderBatches.Add(batch);
_context.SaveChanges();
}
public void Update(OrderBatchCreateBindingModel model)
{
var batch = _context.OrderBatches.Find(model.Id);
if (batch == null) throw new Exception("Партия не найдена");
batch.Name = model.Name;
_context.OrderBatches.Update(batch);
_context.SaveChanges();
}
public List<OrderBatchViewModel> GetBatchesByProduct(int userId) => _context.OrderBatches
.Where(b => b.UserID == userId && b.ProductId.HasValue)
.Select(b => new OrderBatchViewModel
{
Id = b.Id,
Name = b.Name,
UserId = b.UserID
}).ToList();
public List<OrderBatchViewModel> GetBatchesWithoutProduct(int userId, int productId) => _context.OrderBatches
.Where(b => !b.ProductId.HasValue || b.ProductId == productId )
.Select(b => new OrderBatchViewModel
{
Id = b.Id,
Name = b.Name,
UserId = b.UserID
}).ToList();
public void AssignProductToBatches(List<int> batchIds, int productId)
{
var batches = _context.OrderBatches
.Where(b => batchIds.Contains(b.Id))
.ToList();
foreach (var batch in batches)
{
batch.ProductId = productId;
}
_context.SaveChanges();
}
public void Delete(int id)
{
var batch = _context.OrderBatches.Find(id);
if (batch != null)
{
_context.OrderBatches.Remove(batch);
_context.SaveChanges();
}
}
public List<AssemblyViewModel> GetUnlinkedAssemblies(int orderId)
{
var requestIds = _context.OrderRequests
.Where(or => or.OrderId == orderId)
.Select(or => or.RequestId)
.ToList();
var assemblyIds = _context.Requests
.Where(r => requestIds.Contains(r.Id))
.Select(r => r.AssemblyId)
.Where(a => a.HasValue)
.Select(a => a.Value)
.ToList();
return _context.Assemblies
.Where(a => !assemblyIds.Contains(a.Id))
.Select(a => new AssemblyViewModel
{
Id = a.Id,
Name = a.Name,
Description = a.Description,
UserId = a.UserId
}).ToList();
}
public List<AssemblyViewModel> GetAssembliesByOrders(List<int> orderIds)
{
var requestIds = _context.OrderRequests
.Where(or => orderIds.Contains(or.OrderId))
.Select(or => or.RequestId)
.ToList();
var assemblyIds = _context.Requests
.Where(r => requestIds.Contains(r.Id) && r.AssemblyId.HasValue)
.Select(r => r.AssemblyId.Value)
.ToList();
return _context.Assemblies
.Where(a => assemblyIds.Contains(a.Id))
.Select(a => new AssemblyViewModel
{
Id = a.Id,
Name = a.Name,
Description = a.Description,
UserId = a.UserId
}).ToList();
}
public List<OrderViewModel> GetOrdersByBatch(int batchId)
{
return _context.OrderOrderBatches
.Where(ob => ob.OrderBatchId == batchId)
.Select(ob => ob.Order)
.Select(o => new OrderViewModel
{
Id = o.Id,
Status = o.Status,
UserId = o.UserID,
CreatedAt = o.CreatedAt,
}).ToList();
}
public void AddOrdersToBatch(int batchId, List<int> orderIds)
{
foreach (var orderId in orderIds)
{
if (!_context.OrderOrderBatches.Any(ob => ob.OrderId == orderId && ob.OrderBatchId == batchId))
{
_context.OrderOrderBatches.Add(new OrderOrderBatch
{
OrderId = orderId,
OrderBatchId = batchId
});
}
}
_context.SaveChanges();
}
public void RemoveOrdersFromBatch(int batchId, List<int> orderIds)
{
var links = _context.OrderOrderBatches
.Where(ob => ob.OrderBatchId == batchId && orderIds.Contains(ob.OrderId));
_context.OrderOrderBatches.RemoveRange(links);
_context.SaveChanges();
}
}

View File

@@ -0,0 +1,157 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
using ComputerStoreDatabase.Models;
using Microsoft.EntityFrameworkCore;
namespace ComputerStoreDatabase.Implementations;
public class OrderStorageImplementation : IOrderStorageContract
{
private readonly ComputerStoreDbContext _context;
public OrderStorageImplementation(ComputerStoreDbContext context)
{
_context = context;
}
public List<OrderViewModel> GetFullList() => _context.Orders
.Select(o => new OrderViewModel
{
Id = o.Id,
CreatedAt = o.CreatedAt,
Status = o.Status,
UserId = o.UserID,
RequestIds = o.OrderRequests.Select(or => or.RequestId).ToList(),
BatchIds = o.OrderBatchesLink.Select(ob => ob.OrderBatchId).ToList()
}).ToList();
public OrderViewModel? GetElement(int id) => _context.Orders
.Where(o => o.Id == id)
.Select(o => new OrderViewModel
{
Id = o.Id,
CreatedAt = o.CreatedAt,
Status = o.Status,
UserId = o.UserID,
RequestIds = o.OrderRequests.Select(or => or.RequestId).ToList(),
BatchIds = o.OrderBatchesLink.Select(ob => ob.OrderBatchId).ToList()
}).FirstOrDefault();
public void Create(OrderCreateBindingModel model)
{
var order = new Order
{
Status = model.Status,
UserID = model.UserId,
OrderRequests = model.RequestIds.Select(r => new OrderRequest
{
OrderId = model.UserId, // будет обновлено после SaveChanges
RequestId = r
}).ToList(),
OrderBatchesLink = model.BatchIds.Select(b => new OrderOrderBatch
{
OrderId = model.UserId, // будет обновлено после SaveChanges
OrderBatchId = b
}).ToList(),
CreatedAt = DateTime.UtcNow,
};
_context.Orders.Add(order);
_context.SaveChanges();
}
public void Update(OrderCreateBindingModel model)
{
var order = _context.Orders
.Include(o => o.OrderRequests)
.Include(o => o.OrderBatchesLink)
.FirstOrDefault(o => o.Id == model.Id);
if (order == null) throw new Exception("Order not found");
order.Status = model.Status;
order.UserID = model.UserId;
// Обновление связей
var newRequests = model.RequestIds.Except(order.OrderRequests.Select(r => r.RequestId)).ToList();
var removedRequests = order.OrderRequests.Where(r => !model.RequestIds.Contains(r.RequestId)).ToList();
foreach (var id in newRequests)
order.OrderRequests.Add(new OrderRequest { OrderId = model.Id, RequestId = id });
foreach (var req in removedRequests)
_context.OrderRequests.Remove(req);
var newBatches = model.BatchIds.Except(order.OrderBatchesLink.Select(b => b.OrderBatchId)).ToList();
var removedBatches = order.OrderBatchesLink.Where(b => !model.BatchIds.Contains(b.OrderBatchId)).ToList();
foreach (var id in newBatches)
order.OrderBatchesLink.Add(new OrderOrderBatch { OrderId = model.Id, OrderBatchId = id });
foreach (var batch in removedBatches)
_context.OrderOrderBatches.Remove(batch);
_context.SaveChanges();
}
public void Delete(int id)
{
var order = _context.Orders.Find(id);
if (order != null)
{
_context.Orders.Remove(order);
_context.SaveChanges();
}
}
public List<AssemblyViewModel> GetAssembliesByOrders(List<int> orderIds) => _context.Requests
.Where(r => orderIds.Contains(r.Id) && r.AssemblyId.HasValue)
.Select(r => new AssemblyViewModel
{
Id = r.Assembly!.Id,
Name = r.Assembly.Name,
Description = r.Assembly.Description,
UserId = r.Assembly.UserId
}).ToList();
public List<OrderReportViewModel> GetOrdersWithDetailsByDateRange(
int userId,
DateTime start,
DateTime end)
{
return _context.Orders
.Where(o => o.UserID == userId && o.CreatedAt >= start.ToUniversalTime() && o.CreatedAt <= end.ToUniversalTime())
.SelectMany(o => o.OrderRequests.Select(or => new OrderReportViewModel
{
OrderId = o.Id,
OrderStatus = o.Status,
CreatedAt = o.CreatedAt,
RequestId = or.RequestId,
RequestDescription = or.Request.Description,
ProductId = o.OrderBatchesLink!= null
? _context.OrderOrderBatches
.Where(ca => ca.OrderId == o.Id)
.Select(ca => ca.OrderBatch)
.Select(c => c.Product)
.Select(pc => pc.Id)
.FirstOrDefault()
: 0,
ProductName = o.OrderBatchesLink != null
? _context.OrderOrderBatches
.Where(ca => ca.OrderId == o.Id)
.Select(ca => ca.OrderBatch)
.Select(c => c.Product)
.Select(pc => pc.Name)
.FirstOrDefault() ?? "N/A"
: "N/A",
UserId = o.UserID,
UserFIO = o.User.FIO
}))
.ToList();
}
}

View File

@@ -0,0 +1,156 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
using ComputerStoreDatabase.Models;
using Microsoft.EntityFrameworkCore;
namespace ComputerStoreDatabase.Implementations;
public class ProductStorageImplementation : IProductStorageContract
{
private readonly ComputerStoreDbContext _context;
public ProductStorageImplementation(ComputerStoreDbContext context)
{
_context = context;
}
public List<ProductViewModel> GetFullList() => _context.Products
.Select(p => new ProductViewModel
{
Id = p.Id,
Name = p.Name,
Price = p.Price,
UserId = p.UserID
}).ToList();
public ProductViewModel? GetElement(int id) => _context.Products
.Where(p => p.Id == id)
.Select(p => new ProductViewModel
{
Id = p.Id,
Name = p.Name,
Price = p.Price,
UserId = p.UserID
}).FirstOrDefault();
public void Create(ProductCreateBindingModel model)
{
var product = new Product
{
Name = model.Name,
Price = model.Price,
UserID = model.UserId
};
foreach (var componentId in model.ComponentIds)
{
var component = _context.Components.Find(componentId);
if (component != null)
{
product.ComponentsLink.Add(new ProductComponent
{
ComponentId = componentId
});
}
}
_context.Products.Add(product);
_context.SaveChanges();
}
public void Update(ProductCreateBindingModel model)
{
var product = _context.Products
.Include(p => p.ComponentsLink)
.FirstOrDefault(p => p.Id == model.Id);
if (product == null) throw new Exception("Товар не найден");
product.Name = model.Name;
product.Price = model.Price;
// Удаляем старые связи
var oldLinks = product.ComponentsLink.ToList();
foreach (var link in oldLinks)
{
_context.ProductComponents.Remove(link);
}
// Добавляем новые
foreach (var componentId in model.ComponentIds)
{
_context.ProductComponents.Add(new ProductComponent
{
ProductId = model.Id,
ComponentId = componentId
});
}
_context.Products.Update(product);
_context.SaveChanges();
}
public void Delete(int id)
{
var product = _context.Products.Find(id);
if (product != null)
{
_context.Products.Remove(product);
_context.SaveChanges();
}
}
public List<OrderBatchViewModel> GetUnlinkedBatches(int productId)
{
var linkedBatchIds = _context.OrderBatches
.Join(_context.ProductComponents,
b => b.Id,
pc => pc.ComponentId,
(b, pc) => new { Batch = b, ProductComponent = pc })
.Where(j => j.ProductComponent.ProductId == productId)
.Select(j => j.Batch.Id)
.ToList();
return _context.OrderBatches
.Where(b => !linkedBatchIds.Contains(b.Id))
.Select(b => new OrderBatchViewModel
{
Id = b.Id,
Name = b.Name,
UserId = b.UserID
}).ToList();
}
public List<OrderBatchViewModel> GetBatchesByComponents(List<int> componentIds)
{
var productIds = _context.ProductComponents
.Where(pc => componentIds.Contains(pc.ComponentId))
.Select(pc => pc.ProductId)
.Distinct()
.ToList();
return _context.OrderBatches
.Where(b => productIds.Contains(b.ProductId ?? 0))
.Select(b => new OrderBatchViewModel
{
Id = b.Id,
Name = b.Name,
UserId = b.UserID
}).ToList();
}
public List<ComponentViewModel> GetAllByComponent(int componentId)
{
return _context.ProductComponents
.Where(pc => pc.ProductId == componentId)
.Select(pc => pc.Component)
.Distinct()
.Select(p => new ComponentViewModel
{
Id = p.Id,
Name = p.Name,
Price = p.Price,
Manufacturer = p.Manufacturer,
UserId = p.UserID
}).ToList();
}
}

View File

@@ -0,0 +1,144 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
using ComputerStoreDatabase.Models;
namespace ComputerStoreDatabase.Implementations;
public class RequestStorageImplementation : IRequestStorageContract
{
private readonly ComputerStoreDbContext _context;
public RequestStorageImplementation(ComputerStoreDbContext context)
{
_context = context;
}
public List<RequestViewModel> GetFullList() => _context.Requests
.Select(r => new RequestViewModel
{
Id = r.Id,
Description = r.Description,
UserId = r.UserID,
AssemblyId = r.AssemblyId,
CreatedAt = r.CreatedAt,
}).ToList();
public RequestViewModel? GetElement(int id) => _context.Requests
.Where(r => r.Id == id)
.Select(r => new RequestViewModel
{
Id = r.Id,
Description = r.Description,
UserId = r.UserID,
AssemblyId = r.AssemblyId,
CreatedAt = r.CreatedAt,
}).FirstOrDefault();
public void Create(RequestCreateBindingModel model)
{
var request = new Request
{
Description = model.Description,
UserID = model.UserId,
AssemblyId = model.AssemblyId,
CreatedAt = DateTime.UtcNow,
};
_context.Requests.Add(request);
_context.SaveChanges();
}
public void Update(RequestCreateBindingModel model)
{
var request = _context.Requests.Find(model.Id);
if (request == null) throw new Exception("Заявка не найдена");
request.Description = model.Description;
request.UserID = model.UserId;
request.AssemblyId = model.AssemblyId;
_context.Requests.Update(request);
_context.SaveChanges();
}
public void Delete(int id)
{
var request = _context.Requests.Find(id);
if (request != null)
{
_context.Requests.Remove(request);
_context.SaveChanges();
}
}
public List<AssemblyViewModel> GetUnlinkedAssemblies(int requestId)
{
var linkedAssemblyIds = _context.Requests
.Where(r => r.Id == requestId)
.Select(r => r.AssemblyId)
.Where(a => a.HasValue)
.Select(a => a.Value)
.ToList();
return _context.Assemblies
.Where(a => !linkedAssemblyIds.Contains(a.Id))
.Select(a => new AssemblyViewModel
{
Id = a.Id,
Name = a.Name,
Description = a.Description,
UserId = a.UserId
}).ToList();
}
public void AttachAssemblyToRequest(int requestId, int assemblyId)
{
var assembly = _context.Assemblies.Find(assemblyId);
if (assembly == null) throw new Exception("Сборка не найдена");
assembly.RequestId = requestId;
_context.Assemblies.Update(assembly);
_context.SaveChanges();
}
public List<OrderViewModel> GetOrdersByRequest(int requestId)
{
return _context.OrderRequests
.Where(or => or.RequestId == requestId)
.Select(or => or.Order)
.Select(o => new OrderViewModel
{
Id = o.Id,
Status = o.Status,
UserId = o.UserID,
CreatedAt = o.CreatedAt,
}).ToList();
}
public void AddOrdersToRequest(int requestId, List<int> orderIds)
{
foreach (var orderId in orderIds)
{
if (!_context.OrderRequests.Any(or => or.RequestId == requestId && or.OrderId == orderId))
{
_context.OrderRequests.Add(new OrderRequest
{
RequestId = requestId,
OrderId = orderId
});
}
}
_context.SaveChanges();
}
public void RemoveOrdersFromRequest(int requestId, List<int> orderIds)
{
var links = _context.OrderRequests
.Where(or => or.RequestId == requestId && orderIds.Contains(or.OrderId));
_context.OrderRequests.RemoveRange(links);
_context.SaveChanges();
}
}

View File

@@ -0,0 +1,78 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreContracts.ViewModels;
using ComputerStoreDatabase.Models;
namespace ComputerStoreDatabase.Implementations;
public class UserStorageImplementation : IUserStorageContract
{
private readonly ComputerStoreDbContext _context;
public UserStorageImplementation(ComputerStoreDbContext context)
{
_context = context;
}
public List<UserViewModel> GetFullList() => _context.Users
.Select(u => new UserViewModel
{
ID = u.ID,
Login = u.Login,
FIO = u.FIO,
Email = u.Email,
RoleType = u.UserType,
Password = u.Password
}).ToList();
public UserViewModel? GetElement(int id) => _context.Users
.Where(u => u.ID == id)
.Select(u => new UserViewModel
{
ID = u.ID,
Login = u.Login,
FIO = u.FIO,
Email = u.Email,
RoleType = u.UserType,
Password = u.Password
}).FirstOrDefault();
public void Create(UserBindingModel model)
{
var user = new User
{
Login = model.Login,
Password = model.Password!,
FIO = model.FIO,
Email = model.Email,
UserType = model.RoleType
};
_context.Users.Add(user);
_context.SaveChanges();
}
public void Update(UserBindingModel model)
{
var user = _context.Users.Find(model.ID);
if (user == null) throw new Exception("User not found");
user.Login = model.Login;
user.FIO = model.FIO;
user.Email = model.Email;
user.UserType = model.RoleType;
if (!string.IsNullOrEmpty(model.Password)) user.Password = model.Password!;
_context.Users.Update(user);
_context.SaveChanges();
}
public void Delete(int id)
{
var user = _context.Users.Find(id);
if (user != null)
{
_context.Users.Remove(user);
_context.SaveChanges();
}
}
}

View File

@@ -0,0 +1,511 @@
// <auto-generated />
using System;
using ComputerStoreDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace ComputerStoreDatabase.Migrations
{
[DbContext(typeof(ComputerStoreDbContext))]
[Migration("20250515190512_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ComputerStoreDatabase.Models.Assembly", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Assemblies");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Manufacturer")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<decimal>("Price")
.HasColumnType("numeric");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserID");
b.ToTable("Components");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.ComponentAssembly", 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.HasKey("Id");
b.HasIndex("AssemblyId");
b.HasIndex("ComponentId");
b.ToTable("ComponentAssemblies");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserID");
b.ToTable("Orders");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderBatch", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserID");
b.ToTable("OrderBatches");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderOrderBatch", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("OrderBatchId")
.HasColumnType("integer");
b.Property<int>("OrderId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("OrderBatchId");
b.HasIndex("OrderId");
b.ToTable("OrderOrderBatches");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderRequest", 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("OrderRequests");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<decimal>("Price")
.HasColumnType("numeric");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserID");
b.ToTable("Products");
});
modelBuilder.Entity("ComputerStoreDatabase.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>("ProductId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("ProductId");
b.ToTable("ProductComponents");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Request", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int?>("AssemblyId")
.HasColumnType("integer");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AssemblyId");
b.HasIndex("UserID");
b.ToTable("Requests");
});
modelBuilder.Entity("ComputerStoreDatabase.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>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Login")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserType")
.HasColumnType("integer");
b.HasKey("ID");
b.ToTable("Users");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Assembly", b =>
{
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Assemblies")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Component", b =>
{
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Components")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.ComponentAssembly", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Assembly", "Assembly")
.WithMany("ComponentsLink")
.HasForeignKey("AssemblyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerStoreDatabase.Models.Component", "Component")
.WithMany("AssembliesLink")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Assembly");
b.Navigation("Component");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Order", b =>
{
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Orders")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderBatch", b =>
{
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("OrderBatches")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderOrderBatch", b =>
{
b.HasOne("ComputerStoreDatabase.Models.OrderBatch", "OrderBatch")
.WithMany("OrdersLink")
.HasForeignKey("OrderBatchId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerStoreDatabase.Models.Order", "Order")
.WithMany("OrderBatchesLink")
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Order");
b.Navigation("OrderBatch");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderRequest", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Order", "Order")
.WithMany("OrderRequests")
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerStoreDatabase.Models.Request", "Request")
.WithMany("OrderRequests")
.HasForeignKey("RequestId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Order");
b.Navigation("Request");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Product", b =>
{
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Products")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.ProductComponent", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Component", "Component")
.WithMany("ProductsLink")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerStoreDatabase.Models.Product", "Product")
.WithMany("ComponentsLink")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Product");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Request", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Assembly", "Assembly")
.WithMany()
.HasForeignKey("AssemblyId");
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Requests")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Assembly");
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Assembly", b =>
{
b.Navigation("ComponentsLink");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Component", b =>
{
b.Navigation("AssembliesLink");
b.Navigation("ProductsLink");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Order", b =>
{
b.Navigation("OrderBatchesLink");
b.Navigation("OrderRequests");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderBatch", b =>
{
b.Navigation("OrdersLink");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Product", b =>
{
b.Navigation("ComponentsLink");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Request", b =>
{
b.Navigation("OrderRequests");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.User", b =>
{
b.Navigation("Assemblies");
b.Navigation("Components");
b.Navigation("OrderBatches");
b.Navigation("Orders");
b.Navigation("Products");
b.Navigation("Requests");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,382 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace ComputerStoreDatabase.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
ID = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Login = table.Column<string>(type: "text", nullable: false),
Password = table.Column<string>(type: "text", nullable: false),
FIO = table.Column<string>(type: "text", nullable: false),
Email = table.Column<string>(type: "text", nullable: false),
UserType = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.ID);
});
migrationBuilder.CreateTable(
name: "Assemblies",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "text", nullable: false),
Description = table.Column<string>(type: "text", nullable: false),
UserId = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Assemblies", x => x.Id);
table.ForeignKey(
name: "FK_Assemblies_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Components",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "text", nullable: false),
Manufacturer = table.Column<string>(type: "text", nullable: false),
Price = table.Column<decimal>(type: "numeric", nullable: false),
UserID = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Components", x => x.Id);
table.ForeignKey(
name: "FK_Components_Users_UserID",
column: x => x.UserID,
principalTable: "Users",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "OrderBatches",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "text", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
UserID = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_OrderBatches", x => x.Id);
table.ForeignKey(
name: "FK_OrderBatches_Users_UserID",
column: x => x.UserID,
principalTable: "Users",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Status = table.Column<string>(type: "text", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
UserID = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Users_UserID",
column: x => x.UserID,
principalTable: "Users",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "text", nullable: false),
Price = table.Column<decimal>(type: "numeric", nullable: false),
UserID = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.Id);
table.ForeignKey(
name: "FK_Products_Users_UserID",
column: x => x.UserID,
principalTable: "Users",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Requests",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Description = table.Column<string>(type: "text", nullable: false),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
UserID = table.Column<int>(type: "integer", nullable: false),
AssemblyId = table.Column<int>(type: "integer", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Requests", x => x.Id);
table.ForeignKey(
name: "FK_Requests_Assemblies_AssemblyId",
column: x => x.AssemblyId,
principalTable: "Assemblies",
principalColumn: "Id");
table.ForeignKey(
name: "FK_Requests_Users_UserID",
column: x => x.UserID,
principalTable: "Users",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ComponentAssemblies",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ComponentId = table.Column<int>(type: "integer", nullable: false),
AssemblyId = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ComponentAssemblies", x => x.Id);
table.ForeignKey(
name: "FK_ComponentAssemblies_Assemblies_AssemblyId",
column: x => x.AssemblyId,
principalTable: "Assemblies",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ComponentAssemblies_Components_ComponentId",
column: x => x.ComponentId,
principalTable: "Components",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "OrderOrderBatches",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
OrderId = table.Column<int>(type: "integer", nullable: false),
OrderBatchId = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_OrderOrderBatches", x => x.Id);
table.ForeignKey(
name: "FK_OrderOrderBatches_OrderBatches_OrderBatchId",
column: x => x.OrderBatchId,
principalTable: "OrderBatches",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_OrderOrderBatches_Orders_OrderId",
column: x => x.OrderId,
principalTable: "Orders",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ProductComponents",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
ProductId = table.Column<int>(type: "integer", nullable: false),
ComponentId = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ProductComponents", x => x.Id);
table.ForeignKey(
name: "FK_ProductComponents_Components_ComponentId",
column: x => x.ComponentId,
principalTable: "Components",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ProductComponents_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "OrderRequests",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
OrderId = table.Column<int>(type: "integer", nullable: false),
RequestId = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_OrderRequests", x => x.Id);
table.ForeignKey(
name: "FK_OrderRequests_Orders_OrderId",
column: x => x.OrderId,
principalTable: "Orders",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_OrderRequests_Requests_RequestId",
column: x => x.RequestId,
principalTable: "Requests",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Assemblies_UserId",
table: "Assemblies",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_ComponentAssemblies_AssemblyId",
table: "ComponentAssemblies",
column: "AssemblyId");
migrationBuilder.CreateIndex(
name: "IX_ComponentAssemblies_ComponentId",
table: "ComponentAssemblies",
column: "ComponentId");
migrationBuilder.CreateIndex(
name: "IX_Components_UserID",
table: "Components",
column: "UserID");
migrationBuilder.CreateIndex(
name: "IX_OrderBatches_UserID",
table: "OrderBatches",
column: "UserID");
migrationBuilder.CreateIndex(
name: "IX_OrderOrderBatches_OrderBatchId",
table: "OrderOrderBatches",
column: "OrderBatchId");
migrationBuilder.CreateIndex(
name: "IX_OrderOrderBatches_OrderId",
table: "OrderOrderBatches",
column: "OrderId");
migrationBuilder.CreateIndex(
name: "IX_OrderRequests_OrderId",
table: "OrderRequests",
column: "OrderId");
migrationBuilder.CreateIndex(
name: "IX_OrderRequests_RequestId",
table: "OrderRequests",
column: "RequestId");
migrationBuilder.CreateIndex(
name: "IX_Orders_UserID",
table: "Orders",
column: "UserID");
migrationBuilder.CreateIndex(
name: "IX_ProductComponents_ComponentId",
table: "ProductComponents",
column: "ComponentId");
migrationBuilder.CreateIndex(
name: "IX_ProductComponents_ProductId",
table: "ProductComponents",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_Products_UserID",
table: "Products",
column: "UserID");
migrationBuilder.CreateIndex(
name: "IX_Requests_AssemblyId",
table: "Requests",
column: "AssemblyId");
migrationBuilder.CreateIndex(
name: "IX_Requests_UserID",
table: "Requests",
column: "UserID");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ComponentAssemblies");
migrationBuilder.DropTable(
name: "OrderOrderBatches");
migrationBuilder.DropTable(
name: "OrderRequests");
migrationBuilder.DropTable(
name: "ProductComponents");
migrationBuilder.DropTable(
name: "OrderBatches");
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "Requests");
migrationBuilder.DropTable(
name: "Components");
migrationBuilder.DropTable(
name: "Products");
migrationBuilder.DropTable(
name: "Assemblies");
migrationBuilder.DropTable(
name: "Users");
}
}
}

View File

@@ -0,0 +1,522 @@
// <auto-generated />
using System;
using ComputerStoreDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace ComputerStoreDatabase.Migrations
{
[DbContext(typeof(ComputerStoreDbContext))]
[Migration("20250516051629_EditAsm")]
partial class EditAsm
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ComputerStoreDatabase.Models.Assembly", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("RequestId")
.HasColumnType("integer");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("RequestId");
b.HasIndex("UserId");
b.ToTable("Assemblies");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Manufacturer")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<decimal>("Price")
.HasColumnType("numeric");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserID");
b.ToTable("Components");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.ComponentAssembly", 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.HasKey("Id");
b.HasIndex("AssemblyId");
b.HasIndex("ComponentId");
b.ToTable("ComponentAssemblies");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserID");
b.ToTable("Orders");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderBatch", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserID");
b.ToTable("OrderBatches");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderOrderBatch", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("OrderBatchId")
.HasColumnType("integer");
b.Property<int>("OrderId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("OrderBatchId");
b.HasIndex("OrderId");
b.ToTable("OrderOrderBatches");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderRequest", 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("OrderRequests");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<decimal>("Price")
.HasColumnType("numeric");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserID");
b.ToTable("Products");
});
modelBuilder.Entity("ComputerStoreDatabase.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>("ProductId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("ProductId");
b.ToTable("ProductComponents");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Request", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int?>("AssemblyId")
.HasColumnType("integer");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AssemblyId");
b.HasIndex("UserID");
b.ToTable("Requests");
});
modelBuilder.Entity("ComputerStoreDatabase.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>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Login")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserType")
.HasColumnType("integer");
b.HasKey("ID");
b.ToTable("Users");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Assembly", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Request", "Request")
.WithMany()
.HasForeignKey("RequestId");
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Assemblies")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Request");
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Component", b =>
{
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Components")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.ComponentAssembly", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Assembly", "Assembly")
.WithMany("ComponentsLink")
.HasForeignKey("AssemblyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerStoreDatabase.Models.Component", "Component")
.WithMany("AssembliesLink")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Assembly");
b.Navigation("Component");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Order", b =>
{
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Orders")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderBatch", b =>
{
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("OrderBatches")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderOrderBatch", b =>
{
b.HasOne("ComputerStoreDatabase.Models.OrderBatch", "OrderBatch")
.WithMany("OrdersLink")
.HasForeignKey("OrderBatchId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerStoreDatabase.Models.Order", "Order")
.WithMany("OrderBatchesLink")
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Order");
b.Navigation("OrderBatch");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderRequest", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Order", "Order")
.WithMany("OrderRequests")
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerStoreDatabase.Models.Request", "Request")
.WithMany("OrderRequests")
.HasForeignKey("RequestId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Order");
b.Navigation("Request");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Product", b =>
{
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Products")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.ProductComponent", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Component", "Component")
.WithMany("ProductsLink")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerStoreDatabase.Models.Product", "Product")
.WithMany("ComponentsLink")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Product");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Request", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Assembly", "Assembly")
.WithMany()
.HasForeignKey("AssemblyId");
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Requests")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Assembly");
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Assembly", b =>
{
b.Navigation("ComponentsLink");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Component", b =>
{
b.Navigation("AssembliesLink");
b.Navigation("ProductsLink");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Order", b =>
{
b.Navigation("OrderBatchesLink");
b.Navigation("OrderRequests");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderBatch", b =>
{
b.Navigation("OrdersLink");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Product", b =>
{
b.Navigation("ComponentsLink");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Request", b =>
{
b.Navigation("OrderRequests");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.User", b =>
{
b.Navigation("Assemblies");
b.Navigation("Components");
b.Navigation("OrderBatches");
b.Navigation("Orders");
b.Navigation("Products");
b.Navigation("Requests");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,48 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ComputerStoreDatabase.Migrations
{
/// <inheritdoc />
public partial class EditAsm : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "RequestId",
table: "Assemblies",
type: "integer",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_Assemblies_RequestId",
table: "Assemblies",
column: "RequestId");
migrationBuilder.AddForeignKey(
name: "FK_Assemblies_Requests_RequestId",
table: "Assemblies",
column: "RequestId",
principalTable: "Requests",
principalColumn: "Id");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Assemblies_Requests_RequestId",
table: "Assemblies");
migrationBuilder.DropIndex(
name: "IX_Assemblies_RequestId",
table: "Assemblies");
migrationBuilder.DropColumn(
name: "RequestId",
table: "Assemblies");
}
}
}

View File

@@ -0,0 +1,533 @@
// <auto-generated />
using System;
using ComputerStoreDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace ComputerStoreDatabase.Migrations
{
[DbContext(typeof(ComputerStoreDbContext))]
[Migration("20250516062414_EditOrB")]
partial class EditOrB
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ComputerStoreDatabase.Models.Assembly", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("RequestId")
.HasColumnType("integer");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("RequestId");
b.HasIndex("UserId");
b.ToTable("Assemblies");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Manufacturer")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<decimal>("Price")
.HasColumnType("numeric");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserID");
b.ToTable("Components");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.ComponentAssembly", 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.HasKey("Id");
b.HasIndex("AssemblyId");
b.HasIndex("ComponentId");
b.ToTable("ComponentAssemblies");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserID");
b.ToTable("Orders");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderBatch", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("ProductId")
.HasColumnType("integer");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ProductId");
b.HasIndex("UserID");
b.ToTable("OrderBatches");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderOrderBatch", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("OrderBatchId")
.HasColumnType("integer");
b.Property<int>("OrderId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("OrderBatchId");
b.HasIndex("OrderId");
b.ToTable("OrderOrderBatches");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderRequest", 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("OrderRequests");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<decimal>("Price")
.HasColumnType("numeric");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserID");
b.ToTable("Products");
});
modelBuilder.Entity("ComputerStoreDatabase.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>("ProductId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("ProductId");
b.ToTable("ProductComponents");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Request", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int?>("AssemblyId")
.HasColumnType("integer");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AssemblyId");
b.HasIndex("UserID");
b.ToTable("Requests");
});
modelBuilder.Entity("ComputerStoreDatabase.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>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Login")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserType")
.HasColumnType("integer");
b.HasKey("ID");
b.ToTable("Users");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Assembly", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Request", "Request")
.WithMany()
.HasForeignKey("RequestId");
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Assemblies")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Request");
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Component", b =>
{
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Components")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.ComponentAssembly", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Assembly", "Assembly")
.WithMany("ComponentsLink")
.HasForeignKey("AssemblyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerStoreDatabase.Models.Component", "Component")
.WithMany("AssembliesLink")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Assembly");
b.Navigation("Component");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Order", b =>
{
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Orders")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderBatch", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Product", "Product")
.WithMany()
.HasForeignKey("ProductId");
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("OrderBatches")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderOrderBatch", b =>
{
b.HasOne("ComputerStoreDatabase.Models.OrderBatch", "OrderBatch")
.WithMany("OrdersLink")
.HasForeignKey("OrderBatchId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerStoreDatabase.Models.Order", "Order")
.WithMany("OrderBatchesLink")
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Order");
b.Navigation("OrderBatch");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderRequest", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Order", "Order")
.WithMany("OrderRequests")
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerStoreDatabase.Models.Request", "Request")
.WithMany("OrderRequests")
.HasForeignKey("RequestId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Order");
b.Navigation("Request");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Product", b =>
{
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Products")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.ProductComponent", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Component", "Component")
.WithMany("ProductsLink")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerStoreDatabase.Models.Product", "Product")
.WithMany("ComponentsLink")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Product");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Request", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Assembly", "Assembly")
.WithMany()
.HasForeignKey("AssemblyId");
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Requests")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Assembly");
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Assembly", b =>
{
b.Navigation("ComponentsLink");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Component", b =>
{
b.Navigation("AssembliesLink");
b.Navigation("ProductsLink");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Order", b =>
{
b.Navigation("OrderBatchesLink");
b.Navigation("OrderRequests");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderBatch", b =>
{
b.Navigation("OrdersLink");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Product", b =>
{
b.Navigation("ComponentsLink");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Request", b =>
{
b.Navigation("OrderRequests");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.User", b =>
{
b.Navigation("Assemblies");
b.Navigation("Components");
b.Navigation("OrderBatches");
b.Navigation("Orders");
b.Navigation("Products");
b.Navigation("Requests");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,48 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ComputerStoreDatabase.Migrations
{
/// <inheritdoc />
public partial class EditOrB : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "ProductId",
table: "OrderBatches",
type: "integer",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_OrderBatches_ProductId",
table: "OrderBatches",
column: "ProductId");
migrationBuilder.AddForeignKey(
name: "FK_OrderBatches_Products_ProductId",
table: "OrderBatches",
column: "ProductId",
principalTable: "Products",
principalColumn: "Id");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_OrderBatches_Products_ProductId",
table: "OrderBatches");
migrationBuilder.DropIndex(
name: "IX_OrderBatches_ProductId",
table: "OrderBatches");
migrationBuilder.DropColumn(
name: "ProductId",
table: "OrderBatches");
}
}
}

View File

@@ -0,0 +1,530 @@
// <auto-generated />
using System;
using ComputerStoreDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace ComputerStoreDatabase.Migrations
{
[DbContext(typeof(ComputerStoreDbContext))]
partial class ComputerStoreDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ComputerStoreDatabase.Models.Assembly", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("RequestId")
.HasColumnType("integer");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("RequestId");
b.HasIndex("UserId");
b.ToTable("Assemblies");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Manufacturer")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<decimal>("Price")
.HasColumnType("numeric");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserID");
b.ToTable("Components");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.ComponentAssembly", 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.HasKey("Id");
b.HasIndex("AssemblyId");
b.HasIndex("ComponentId");
b.ToTable("ComponentAssemblies");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserID");
b.ToTable("Orders");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderBatch", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<int?>("ProductId")
.HasColumnType("integer");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ProductId");
b.HasIndex("UserID");
b.ToTable("OrderBatches");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderOrderBatch", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("OrderBatchId")
.HasColumnType("integer");
b.Property<int>("OrderId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("OrderBatchId");
b.HasIndex("OrderId");
b.ToTable("OrderOrderBatches");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderRequest", 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("OrderRequests");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<decimal>("Price")
.HasColumnType("numeric");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("UserID");
b.ToTable("Products");
});
modelBuilder.Entity("ComputerStoreDatabase.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>("ProductId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("ProductId");
b.ToTable("ProductComponents");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Request", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int?>("AssemblyId")
.HasColumnType("integer");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserID")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AssemblyId");
b.HasIndex("UserID");
b.ToTable("Requests");
});
modelBuilder.Entity("ComputerStoreDatabase.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>("FIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Login")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserType")
.HasColumnType("integer");
b.HasKey("ID");
b.ToTable("Users");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Assembly", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Request", "Request")
.WithMany()
.HasForeignKey("RequestId");
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Assemblies")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Request");
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Component", b =>
{
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Components")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.ComponentAssembly", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Assembly", "Assembly")
.WithMany("ComponentsLink")
.HasForeignKey("AssemblyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerStoreDatabase.Models.Component", "Component")
.WithMany("AssembliesLink")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Assembly");
b.Navigation("Component");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Order", b =>
{
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Orders")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderBatch", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Product", "Product")
.WithMany()
.HasForeignKey("ProductId");
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("OrderBatches")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Product");
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderOrderBatch", b =>
{
b.HasOne("ComputerStoreDatabase.Models.OrderBatch", "OrderBatch")
.WithMany("OrdersLink")
.HasForeignKey("OrderBatchId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerStoreDatabase.Models.Order", "Order")
.WithMany("OrderBatchesLink")
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Order");
b.Navigation("OrderBatch");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderRequest", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Order", "Order")
.WithMany("OrderRequests")
.HasForeignKey("OrderId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerStoreDatabase.Models.Request", "Request")
.WithMany("OrderRequests")
.HasForeignKey("RequestId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Order");
b.Navigation("Request");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Product", b =>
{
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Products")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.ProductComponent", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Component", "Component")
.WithMany("ProductsLink")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("ComputerStoreDatabase.Models.Product", "Product")
.WithMany("ComponentsLink")
.HasForeignKey("ProductId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Product");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Request", b =>
{
b.HasOne("ComputerStoreDatabase.Models.Assembly", "Assembly")
.WithMany()
.HasForeignKey("AssemblyId");
b.HasOne("ComputerStoreDatabase.Models.User", "User")
.WithMany("Requests")
.HasForeignKey("UserID")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Assembly");
b.Navigation("User");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Assembly", b =>
{
b.Navigation("ComponentsLink");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Component", b =>
{
b.Navigation("AssembliesLink");
b.Navigation("ProductsLink");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Order", b =>
{
b.Navigation("OrderBatchesLink");
b.Navigation("OrderRequests");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.OrderBatch", b =>
{
b.Navigation("OrdersLink");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Product", b =>
{
b.Navigation("ComponentsLink");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.Request", b =>
{
b.Navigation("OrderRequests");
});
modelBuilder.Entity("ComputerStoreDatabase.Models.User", b =>
{
b.Navigation("Assemblies");
b.Navigation("Components");
b.Navigation("OrderBatches");
b.Navigation("Orders");
b.Navigation("Products");
b.Navigation("Requests");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -8,8 +8,10 @@ using System.Threading.Tasks;
namespace ComputerStoreDatabase.Models;
[Table("Assemblies")]
public class Assembly
{
[Key]
public int Id { get; set; }
[Required]
@@ -17,16 +19,20 @@ public class Assembly
public string Description { get; set; } = string.Empty;
public int UserID { get; set; }
// Внешний ключ на Request
public int? RequestId { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; } = new();
[ForeignKey("RequestId")]
public virtual Request? Request { get; set; }
public int? OrderRequestId { get; set; }
// Внешний ключ
[Required]
public int UserId { get; set; } // Явное поле
[ForeignKey("OrderRequestId")]
public virtual Request Request { get; set; } = new();
[ForeignKey("UserId")] // Ссылка на это поле
[InverseProperty("Assemblies")]
public virtual User User { get; set; } = null!;
[ForeignKey("AssemblyId")]
public virtual List<ComponentsAssemblies> ComponentsAssemblies { get; set; } = new();
// Многие ко многим: Assembly <-> Component
public virtual List<ComponentAssembly> ComponentsLink { get; set; } = new();
}

View File

@@ -8,27 +8,29 @@ using System.Threading.Tasks;
namespace ComputerStoreDatabase.Models;
[Table("Components")]
public class Component
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; } = string.Empty;
[Required]
public string Manufacturer { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
public decimal Price { get; set; }
// Внешний ключ
public int UserID { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; } = new();
[InverseProperty("Components")]
public virtual User User { get; set; } = null!;
[ForeignKey("ComponentId")]
public virtual List<ProductsComponents> ProductsComponents { get; set; } = new();
// Многие ко многим: Product <-> Component
public virtual List<ProductComponent> ProductsLink { get; set; } = new();
[ForeignKey("ComponentId")]
public virtual List<ComponentsAssemblies> ComponentsAssemblies { get; set; } = new();
}
// Многие ко многим: Assembly <-> Component
public virtual List<ComponentAssembly> AssembliesLink { get; set; } = new();
}

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
@@ -7,15 +8,19 @@ using System.Threading.Tasks;
namespace ComputerStoreDatabase.Models;
public class ComponentsAssemblies
[Table("ComponentAssemblies")]
public class ComponentAssembly
{
public int AssemblyId { get; set; }
[ForeignKey("AssemblyId")]
public virtual Assembly Assembly { get; set; } = new();
[Key]
public int Id { get; set; }
public int ComponentId { get; set; }
[ForeignKey("ComponentId")]
public virtual Component Component { get; set; } = new();
}
public virtual Component Component { get; set; } = null!;
public int AssemblyId { get; set; }
[ForeignKey("AssemblyId")]
public virtual Assembly Assembly { get; set; } = null!;
}

View File

@@ -0,0 +1,34 @@
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 ComputerStoreDatabase.Models;
[Table("Orders")]
public class Order
{
[Key]
public int Id { get; set; }
[Required]
public string Status { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
// Внешний ключ
public int UserID { get; set; }
[ForeignKey("UserID")]
[InverseProperty("Orders")]
public virtual User User { get; set; } = null!;
// Многие ко многим: Order <-> Request
public virtual List<OrderRequest> OrderRequests { get; set; } = new();
// Многие ко многим: Order <-> Batch
public virtual List<OrderOrderBatch> OrderBatchesLink { get; set; } = new();
}

View File

@@ -0,0 +1,37 @@
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 ComputerStoreDatabase.Models;
[Table("OrderBatches")]
public class OrderBatch
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
// Внешний ключ на Product
public int? ProductId { get; set; }
[ForeignKey("ProductId")]
public virtual Product? Product { get; set; }
// Внешний ключ
public int UserID { get; set; }
[ForeignKey("UserID")]
[InverseProperty("OrderBatches")]
public virtual User User { get; set; } = null!;
// Многие ко многим: Order <-> Batch
public virtual List<OrderOrderBatch> OrdersLink { get; set; } = new();
}

View File

@@ -0,0 +1,26 @@
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 ComputerStoreDatabase.Models;
[Table("OrderOrderBatches")]
public class OrderOrderBatch
{
[Key]
public int Id { get; set; }
public int OrderId { get; set; }
[ForeignKey("OrderId")]
public virtual Order Order { get; set; } = null!;
public int OrderBatchId { get; set; }
[ForeignKey("OrderBatchId")]
public virtual OrderBatch OrderBatch { get; set; } = null!;
}

View File

@@ -0,0 +1,26 @@
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 ComputerStoreDatabase.Models;
[Table("OrderRequests")]
public class OrderRequest
{
[Key]
public int Id { get; set; }
public int OrderId { get; set; }
[ForeignKey("OrderId")]
public virtual Order Order { get; set; } = null!;
public int RequestId { get; set; }
[ForeignKey("RequestId")]
public virtual Request Request { get; set; } = null!;
}

View File

@@ -8,24 +8,24 @@ using System.Threading.Tasks;
namespace ComputerStoreDatabase.Models;
[Table("Products")]
public class Product
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; } = string.Empty;
[Required]
public string Category { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
public decimal Price { get; set; }
// Внешний ключ
public int UserID { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; } = new();
[InverseProperty("Products")]
public virtual User User { get; set; } = null!;
[ForeignKey("ProductId")]
public virtual List<ProductsComponents> ProductsComponents { get; set; } = new();
// Многие ко многим: Product <-> Component
public virtual List<ProductComponent> ComponentsLink { get; set; } = new();
}

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
@@ -7,15 +8,20 @@ using System.Threading.Tasks;
namespace ComputerStoreDatabase.Models;
public class ProductsComponents
[Table("ProductComponents")]
public class ProductComponent
{
[Key]
public int Id { get; set; }
public int ProductId { get; set; }
[ForeignKey("ProductId")]
public virtual Product Product { get; set; } = new();
public virtual Product Product { get; set; } = null!;
public int ComponentId { get; set; }
[ForeignKey("ComponentId")]
public virtual Component Component { get; set; } = new();
}
public virtual Component Component { get; set; } = null!;
}

View File

@@ -8,20 +8,31 @@ using System.Threading.Tasks;
namespace ComputerStoreDatabase.Models;
[Table("Requests")]
public class Request
{
[Key]
public int Id { get; set; }
[Required]
public DateTime DateRequest { get; set; }
public string Description { get; set; } = string.Empty;
public int? AssemblyId { get; set; }
[ForeignKey("AssemblyId")]
public virtual Assembly Assembly { get; set; } = new();
public DateTime CreatedAt { get; set; }
// Внешний ключ
public int UserID { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; } = new();
[InverseProperty("Requests")]
public virtual User User { get; set; } = null!;
// Многие ко многим: Order <-> Request
public virtual List<OrderRequest> OrderRequests { get; set; } = new();
// Привязка к сборке
public int? AssemblyId { get; set; }
[ForeignKey("AssemblyId")]
public virtual Assembly? Assembly { get; set; }
}

View File

@@ -11,8 +11,10 @@ using ComputerStoreContracts.Enums;
namespace ComputerStoreDatabase.Models;
[Table("Users")]
public class User
{
[Key]
public int ID { get; set; }
[Required]
@@ -29,15 +31,22 @@ public class User
public UserType UserType { get; set; }
[ForeignKey("UserID")]
// Навигации
[InverseProperty("User")]
public virtual List<Product> Products { get; set; } = new();
[ForeignKey("UserID")]
[InverseProperty("User")]
public virtual List<Component> Components { get; set; } = new();
[ForeignKey("UserID")]
[InverseProperty("User")]
public virtual List<Assembly> Assemblies { get; set; } = new();
[ForeignKey("UserID")]
[InverseProperty("User")]
public virtual List<Order> Orders { get; set; } = new();
[InverseProperty("User")]
public virtual List<Request> Requests { get; set; } = new();
[InverseProperty("User")]
public virtual List<OrderBatch> OrderBatches { get; set; } = new();
}

View File

@@ -0,0 +1,5 @@
{
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Port=5432;Database=ComputerStoreDB;Username=postgres;Password=030405"
}
}

View File

@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.5" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ComputerStoreBusinessLogic\ComputerStoreBusinessLogic.csproj" />
<ProjectReference Include="..\ComputerStoreContracts\ComputerStoreContracts.csproj" />
<ProjectReference Include="..\ComputerStoreDatabase\ComputerStoreDatabase.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\fonts\" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,77 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.Enums;
using ComputerStoreExecutorWebApp.Models;
using Microsoft.AspNetCore.Mvc;
namespace ComputerStoreExecutorWebApp.Controllers;
public class AccountController : Controller
{
private readonly IUserBusinessLogicContract _userLogic;
public AccountController(IUserBusinessLogicContract userLogic)
{
_userLogic = userLogic;
}
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
public IActionResult Login(LoginViewModel model)
{
if (!ModelState.IsValid) return View(model);
var user = _userLogic.GetFullList()
.FirstOrDefault(u => u.Login == model.Login && u.Password == model.Password);
if (user == null || !_userLogic.IsExecutor(user.ID))
{
ModelState.AddModelError("", "Неверный логин или пароль");
return View(model);
}
// Сохраняем ID пользователя в сессии
HttpContext.Session.SetInt32("UserId", user.ID);
return RedirectToAction("Index", "Home");
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Logout()
{
// Очищаем сессию
HttpContext.Session.Clear();
// Перенаправляем на Login
return RedirectToAction("Login");
}
[HttpPost]
public IActionResult Register(RegisterViewModel model)
{
if (!ModelState.IsValid) return View(model);
var bindingModel = new UserBindingModel
{
Login = model.Login,
Password = model.Password,
FIO = model.FIO,
Email = model.Email,
RoleType = UserType.Executor
};
_userLogic.Create(bindingModel);
return RedirectToAction("Login");
}
}

View File

@@ -0,0 +1,37 @@
using System.Diagnostics;
using ComputerStoreExecutorWebApp.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ComputerStoreExecutorWebApp.Controllers;
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
var userId = HttpContext.Session.GetInt32("UserId");
if (!userId.HasValue)
return RedirectToAction("Login", "Account");
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}

View File

@@ -0,0 +1,106 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace ComputerStoreExecutorWebApp.Controllers;
public class OrderBatchController : Controller
{
private readonly IOrderBatchBusinessLogicContract _batchLogic;
private readonly IOrderBusinessLogicContract _orderLogic;
public OrderBatchController(
IOrderBatchBusinessLogicContract batchLogic,
IOrderBusinessLogicContract orderLogic)
{
_batchLogic = batchLogic;
_orderLogic = orderLogic;
}
public IActionResult Index()
{
var userId = GetUserId();
return View(_batchLogic.GetFullList().Where(b => b.UserId == userId));
}
[HttpGet]
public IActionResult Create()
{
ViewBag.Orders = GetMyOrders();
return View();
}
[HttpPost]
public IActionResult Create(OrderBatchCreateBindingModel model)
{
if (!ModelState.IsValid) return View(model);
model.UserId = GetUserId();
_batchLogic.Create(model);
return RedirectToAction(nameof(Index));
}
[HttpGet]
public IActionResult Edit(int id)
{
var model = _batchLogic.GetElement(id);
if (model == null || model.UserId != GetUserId()) return NotFound();
return View(model);
}
[HttpPost]
public IActionResult Edit(OrderBatchViewModel model)
{
if (!ModelState.IsValid) return View(model);
model.UserId = GetUserId();
var binding = new OrderBatchCreateBindingModel
{
Id = model.Id,
Name = model.Name,
UserId = model.UserId,
};
_batchLogic.Update(binding);
return RedirectToAction(nameof(Index));
}
[HttpGet]
public IActionResult Link(int id)
{
var batch = _batchLogic.GetElement(id);
if (batch == null || batch.UserId != GetUserId()) return NotFound();
var linkedOrderIds = _batchLogic.GetOrdersByBatch(id).Select(o => o.Id).ToList();
var allOrders = GetMyOrders(); // Все свои заказы
ViewBag.AllOrders = allOrders;
ViewBag.LinkedOrderIds = linkedOrderIds;
ViewBag.BatchId = id;
return View();
}
[HttpPost]
public IActionResult Link(int id, List<int> orderIds)
{
var userId = GetUserId();
_batchLogic.AddOrdersToBatch(id, orderIds);
return RedirectToAction(nameof(Index));
}
[HttpPost]
public IActionResult Delete(int id)
{
_batchLogic.Delete(id);
return RedirectToAction(nameof(Index));
}
private int GetUserId() => HttpContext.Session.GetInt32("UserId") ?? throw new UnauthorizedAccessException("User not logged in");
private List<OrderViewModel> GetMyOrders()
{
return _orderLogic.GetFullList().Where(o => o.UserId == GetUserId()).ToList();
}
}

View File

@@ -0,0 +1,91 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ComputerStoreExecutorWebApp.Controllers;
public class OrderController : Controller
{
private readonly IOrderBusinessLogicContract _orderLogic;
private readonly List<string> _orderStatuses = new()
{
"Новый",
"В обработке",
"Ожидает оплаты",
"Выполнен",
"Отменён"
};
public OrderController(IOrderBusinessLogicContract orderLogic)
{
_orderLogic = orderLogic;
}
public IActionResult Index()
{
var userId = GetUserId();
return View(_orderLogic.GetFullList());
}
[HttpGet]
public IActionResult Create()
{
ViewBag.Statuses = _orderStatuses;
return View();
}
[HttpPost]
public IActionResult Create(OrderCreateBindingModel model)
{
if (!ModelState.IsValid) return View(model);
model.UserId = GetUserId();
_orderLogic.Create(model);
return RedirectToAction(nameof(Index));
}
[HttpGet]
public IActionResult Edit(int id)
{
var model = _orderLogic.GetElement(id);
if (model == null) return NotFound();
ViewBag.Statuses = _orderStatuses;
return View(model);
}
[HttpPost]
public IActionResult Edit(OrderViewModel model)
{
if (!ModelState.IsValid) return View(model);
var bindingModel = new OrderCreateBindingModel
{
Id = model.Id,
Status = model.Status,
UserId = GetUserId()
// RequestIds, BatchIds — если нужно
};
_orderLogic.Update(bindingModel);
return RedirectToAction(nameof(Index));
}
[HttpGet]
public IActionResult Delete(int id)
{
_orderLogic.Delete(id);
return RedirectToAction(nameof(Index));
}
private int GetUserId()
{
var userId = HttpContext.Session.GetInt32("UserId");
if (!userId.HasValue)
throw new UnauthorizedAccessException("Пользователь не авторизован");
return userId.Value;
}
}

View File

@@ -0,0 +1,82 @@
using ComputerStoreContracts.BusinessLogicContracts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace ComputerStoreExecutorWebApp.Controllers;
public class ReportController : Controller
{
private readonly IOrderBusinessLogicContract _orderLogic;
private readonly IReportService _reportService;
private readonly IAssemblyBusinessLogicContract _assemblyLogic;
private readonly IProductBusinessLogicContract _productLogic;
private readonly IComponentBusinessLogicContract _componentLogic;
public ReportController(
IOrderBusinessLogicContract orderLogic,
IReportService reportService, IAssemblyBusinessLogicContract assembly, IProductBusinessLogicContract productLogic, IComponentBusinessLogicContract componentLogic)
{
_componentLogic = componentLogic;
_productLogic = productLogic;
_assemblyLogic = assembly;
_orderLogic = orderLogic;
_reportService = reportService;
}
public ActionResult Report()
{
ViewBag.MyOrders = _orderLogic.GetFullList().Where(c => c.UserId == GetUserId());
return View();
}
[HttpGet]
public IActionResult OrdersReport()
{
return View();
}
[HttpPost]
public IActionResult OrdersReport(DateTime startDate, DateTime endDate)
{
var userId = GetUserId();
var data = _orderLogic.GetOrdersWithDetailsByDateRange(userId, startDate, endDate);
ViewBag.ReportData = data;
ViewBag.StartDate = startDate.ToShortDateString();
ViewBag.EndDate = endDate.ToShortDateString();
return View();
}
[HttpPost]
public async Task<IActionResult> SendPdfByEmail(DateTime startDate, DateTime endDate, string email)
{
var userId = GetUserId();
var reportData = _orderLogic.GetOrdersWithDetailsByDateRange(userId, startDate, endDate);
var pdfBytes = _reportService.GeneratePdf(reportData);
await _reportService.SendEmailWithReport(email, pdfBytes, $"Report_{startDate:yyyy-MM-dd}_to_{endDate:yyyy-MM-dd}.pdf");
TempData["Success"] = "Отчет успешно отправлен!";
return RedirectToAction(nameof(OrdersReport));
}
[HttpPost]
public IActionResult Report(List<int> orderIds)
{
if (orderIds == null || !orderIds.Any())
return BadRequest("Не выбраны заказы");
var data = _assemblyLogic.GetAssembliesByOrders(orderIds);
var excelBytes = _reportService.GenerateExcel(data);
return File(excelBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Assemblies.xlsx");
}
private int GetUserId()
{
var userId = HttpContext.Session.GetInt32("UserId");
if (!userId.HasValue)
throw new UnauthorizedAccessException("Пользователь не авторизован");
return userId.Value;
}
}

View File

@@ -0,0 +1,137 @@
using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace ComputerStoreExecutorWebApp.Controllers;
public class RequestController : Controller
{
private readonly IRequestBusinessLogicContract _requestLogic;
private readonly IOrderBusinessLogicContract _orderLogic;
private readonly IAssemblyBusinessLogicContract _assemblyLogic;
public RequestController(
IRequestBusinessLogicContract requestLogic,
IOrderBusinessLogicContract orderLogic, IAssemblyBusinessLogicContract assemblyLogic)
{
_assemblyLogic = assemblyLogic;
_requestLogic = requestLogic;
_orderLogic = orderLogic;
}
public IActionResult Index()
{
var userId = GetUserId();
return View(_requestLogic.GetFullList().Where(r => r.UserId == userId));
}
[HttpGet]
public IActionResult Create()
{
ViewBag.Orders = GetMyOrders();
return View();
}
[HttpPost]
public IActionResult Create(RequestCreateBindingModel model)
{
if (!ModelState.IsValid) return View(model);
model.UserId = GetUserId();
_requestLogic.Create(model);
return RedirectToAction(nameof(Index));
}
[HttpGet]
public IActionResult Edit(int id)
{
var model = _requestLogic.GetElement(id);
if (model == null || model.UserId != GetUserId()) return NotFound();
ViewBag.Orders = GetMyOrders();
ViewBag.LinkedOrderIds = _requestLogic.GetOrdersByRequest(id).Select(o => o.Id).ToList();
return View(model);
}
[HttpPost]
public IActionResult Edit(RequestViewModel model)
{
if (!ModelState.IsValid) return View(model);
model.UserId = GetUserId();
var binding = new RequestCreateBindingModel
{
Id = model.Id,
Description = model.Description,
AssemblyId = model.AssemblyId,
UserId = model.UserId
};
_requestLogic.Update(binding);
return RedirectToAction(nameof(Index));
}
[HttpGet]
public IActionResult Link(int id)
{
var request = _requestLogic.GetElement(id);
if (request == null || request.UserId != GetUserId()) return NotFound();
var linkedOrderIds = _requestLogic.GetOrdersByRequest(id).Select(o => o.Id).ToList();
var allOrders = GetMyOrders();
ViewBag.AllOrders = allOrders;
ViewBag.LinkedOrderIds = linkedOrderIds;
ViewBag.RequestId = id;
return View();
}
[HttpPost]
public IActionResult Link(int id, List<int> orderIds)
{
_requestLogic.AddOrdersToRequest(id, orderIds);
return RedirectToAction(nameof(Index));
}
[HttpGet]
public IActionResult Assembly(int id)
{
var userId = GetUserId();
var request = _requestLogic.GetElement(id);
if (request == null || request.UserId != userId)
return NotFound();
ViewBag.UnlinkedAssemblies = _assemblyLogic.GetUnlinkedAssemblies(userId);
ViewBag.LinkedAssemblies = _assemblyLogic.GetAssembliesByRequest(id);
ViewBag.RequestId = id;
return View();
}
[HttpPost]
public IActionResult Assembly(int id, List<int> assemblyIds)
{
foreach (var assId in assemblyIds)
{
_assemblyLogic.AttachRequestToAssembly(assId, id);
}
return RedirectToAction(nameof(Index));
}
[HttpPost]
public IActionResult Delete(int id)
{
_requestLogic.Delete(id);
return RedirectToAction(nameof(Index));
}
private int GetUserId() => HttpContext.Session.GetInt32("UserId") ?? throw new UnauthorizedAccessException("User not logged in");
private List<OrderViewModel> GetMyOrders() => _orderLogic.GetFullList().Where(o => o.UserId == GetUserId()).ToList();
}

View File

@@ -0,0 +1,9 @@
namespace ComputerStoreExecutorWebApp.Models
{
public class ErrorViewModel
{
public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}

View File

@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace ComputerStoreExecutorWebApp.Models;
public class LoginViewModel
{
[Required]
public string Login { get; set; } = string.Empty;
[Required]
[DataType(DataType.Password)]
public string Password { get; set; } = string.Empty;
}

View File

@@ -0,0 +1,25 @@
using System.ComponentModel.DataAnnotations;
namespace ComputerStoreExecutorWebApp.Models;
public class RegisterViewModel
{
[Required]
public string Login { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Compare("Password")]
public string ConfirmPassword { get; set; }
[Required]
public string FIO { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
}

View File

@@ -0,0 +1,85 @@
using ComputerStoreBusinessLogic.Implementations;
using ComputerStoreContracts.BusinessLogicContracts;
using ComputerStoreContracts.StoragesContracts;
using ComputerStoreDatabase.Implementations;
using ComputerStoreDatabase;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// PostgreSQL DbContext
builder.Services.AddDbContext<ComputerStoreDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
// StorageContracts
builder.Services.AddScoped<IUserStorageContract, UserStorageImplementation>();
builder.Services.AddScoped<IOrderStorageContract, OrderStorageImplementation>();
builder.Services.AddScoped<IOrderBatchStorageContract, OrderBatchStorageImplementation>();
builder.Services.AddScoped<IRequestStorageContract, RequestStorageImplementation>();
builder.Services.AddScoped<IAssemblyStorageContract, AssemblyStorageImplementation>();
builder.Services.AddScoped<IComponentStorageContract, ComponentStorageImplementation>();
builder.Services.AddScoped<IProductStorageContract, ProductStorageImplementation>();
// BusinessLogicContracts
builder.Services.AddScoped<IUserBusinessLogicContract, UserBusinessLogicImplementation>();
builder.Services.AddScoped<IOrderBusinessLogicContract, OrderBusinessLogicImplementation>();
builder.Services.AddScoped<IOrderBatchBusinessLogicContract, OrderBatchBusinessLogicImplementation>();
builder.Services.AddScoped<IRequestBusinessLogicContract, RequestBusinessLogicImplementation>();
builder.Services.AddScoped<IAssemblyBusinessLogicContract, AssemblyBusinessLogicImplementation>();
builder.Services.AddScoped<IComponentBusinessLogicContract, ComponentBusinessLogicImplementation>();
builder.Services.AddScoped<IProductBusinessLogicContract, ProductBusinessLogicImplementation>();
// ReportService
builder.Services.AddScoped<IReportService, ReportService>();
// Session
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>
builder.Services.AddAuthentication("Cookie")
.AddCookie("Cookie", options =>
{
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/Forbidden";
});
var app = builder.Build();
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
using (var scope = app.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<ComputerStoreDbContext>();
context.Database.EnsureCreated();
context.Database.Migrate(); // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
}
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Account}/{action=Login}/{id?}");
app.Run();

View File

@@ -0,0 +1,23 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5008",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7113;http://localhost:5008",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -0,0 +1,6 @@
namespace ComputerStoreExecutorWebApp.Services
{
public interface IReportService
{
}
}

View File

@@ -0,0 +1,19 @@
@model ComputerStoreExecutorWebApp.Models.LoginViewModel
<div class="container mt-5">
<h2>Вход</h2>
<form asp-action="Login" method="post">
<div class="mb-3">
<label asp-for="Login" class="form-label"></label>
<input asp-for="Login" class="form-control" />
<span asp-validation-for="Login" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="Password" class="form-label"></label>
<input asp-for="Password" type="password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Войти</button>
</form>
<p class="mt-3">Нет аккаунта? <a asp-action="Register">Зарегистрируйтесь</a></p>
</div>

View File

@@ -0,0 +1,33 @@
@model ComputerStoreExecutorWebApp.Models.RegisterViewModel
<div class="container mt-5">
<h2>Регистрация</h2>
<form asp-action="Register" method="post">
<div class="mb-3">
<label asp-for="Login" class="form-label"></label>
<input asp-for="Login" class="form-control" />
<span asp-validation-for="Login" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="Password" class="form-label"></label>
<input asp-for="Password" type="password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="ConfirmPassword" class="form-label"></label>
<input asp-for="ConfirmPassword" type="password" class="form-control" />
<span asp-validation-for="ConfirmPassword" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="FIO" class="form-label"></label>
<input asp-for="FIO" class="form-control" />
<span asp-validation-for="FIO" class="text-danger"></span>
</div>
<div class="mb-3">
<label asp-for="Email" class="form-label"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-success">Зарегистрироваться</button>
</form>
</div>

View File

@@ -0,0 +1,20 @@
@{
ViewData["Title"] = "Главная";
}
<div class="container mt-5">
<h2>Добро пожаловать!</h2>
<p>Вы успешно вошли в систему как исполнитель.</p>
<div class="list-group mb-3">
<a asp-controller="Order" asp-action="Index" class="list-group-item list-group-item-action">Заказы</a>
<a asp-controller="OrderBatch" asp-action="Index" class="list-group-item list-group-item-action">Партии товаров</a>
<a asp-controller="Request" asp-action="Index" class="list-group-item list-group-item-action">Заявки</a>
<a asp-controller="Report" asp-action="Report" class="list-group-item list-group-item-action">Сформировать отчет</a>
<a asp-controller="Report" asp-action="OrdersReport" class="list-group-item list-group-item-action">PDF отчет</a>
</div>
<form asp-controller="Account" asp-action="Logout" method="post">
<button type="submit" class="btn btn-danger">Выйти</button>
</form>
</div>

View File

@@ -0,0 +1,6 @@
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p>

View File

@@ -0,0 +1,26 @@
@model ComputerStoreContracts.BindingModels.OrderCreateBindingModel
@{
ViewData["Title"] = "Создать заказ";
}
<div class="container mt-5">
<h4>Создать заказ</h4>
<hr />
<form asp-action="Create">
<div class="mb-3">
<label asp-for="Status" class="form-label"></label>
<select asp-for="Status" class="form-control" asp-items="@(new SelectList(ViewBag.Statuses))">
<option value="">-- Выберите статус --</option>
</select>
<span asp-validation-for="Status" class="text-danger"></span>
</div>
<!-- Если нужно привязать заявки или партии — можно добавить Select -->
<div class="mb-3">
<input type="submit" value="Создать" class="btn btn-primary" />
</div>
</form>
<a asp-action="Index" class="btn btn-secondary">Назад к списку</a>
</div>

View File

@@ -0,0 +1,28 @@
@model ComputerStoreContracts.ViewModels.OrderViewModel
@{
ViewData["Title"] = "Редактировать заказ";
}
<div class="container mt-5">
<h4>Редактировать заказ</h4>
<hr />
<form asp-action="Edit">
<input type="hidden" asp-for="Id" />
<div class="mb-3">
<label asp-for="Status" class="form-label"></label>
<select asp-for="Status" class="form-control" asp-items="@(new SelectList(ViewBag.Statuses))">
<option value="">-- Выберите статус --</option>
</select>
<span asp-validation-for="Status" class="text-danger"></span>
</div>
<input type="hidden" asp-for="UserId" />
<div class="mb-3">
<button type="submit" value="Сохранить" class="btn btn-primary">Сохранить</button>
</div>
</form>
<a asp-action="Index" class="btn btn-secondary">Назад к списку</a>
</div>

View File

@@ -0,0 +1,36 @@
@model IEnumerable<ComputerStoreContracts.ViewModels.OrderViewModel>
@{
ViewData["Title"] = "Заказы";
}
<div class="container mt-5">
<h2>Ваши заказы</h2>
<p>
<a asp-action="Create" class="btn btn-success">Создать новый заказ</a>
</p>
<table class="table table-striped table-bordered">
<thead class="table-dark">
<tr>
<th>ID</th>
<th>Статус</th>
<th>Дата создания</th>
<th>Действия</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.Id</td>
<td>@item.Status</td>
<td>@item.CreatedAt.ToShortDateString()</td>
<td>
<a asp-action="Edit" asp-route-id="@item.Id" class="btn btn-primary btn-sm">Редактировать</a>
<a asp-action="Delete" asp-route-id="@item.Id" class="btn btn-danger btn-sm">Удалить</a>
</td>
</tr>
}
</tbody>
</table>
</div>

View File

@@ -0,0 +1,14 @@
@model ComputerStoreContracts.BindingModels.OrderBatchCreateBindingModel
<div class="container mt-5">
<h4>Создать партию</h4>
<form asp-action="Create">
<div class="mb-3">
<label asp-for="Name" class="form-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Создать</button>
</form>
</div>

View File

@@ -0,0 +1,25 @@
@model ComputerStoreContracts.ViewModels.OrderBatchViewModel
@{
ViewData["Title"] = "Редактировать партию";
}
<div class="container mt-5">
<h4>Редактировать партию</h4>
<hr />
<form asp-action="Edit" method="post">
<input type="hidden" asp-for="Id" />
<div class="mb-3">
<label asp-for="Name" class="form-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<!-- Если нужно — можно добавить привязку к заказам -->
<div class="mb-3">
<button type="submit" class="btn btn-primary">Сохранить</button>
<a asp-action="Index" class="btn btn-secondary">Отмена</a>
</div>
</form>
</div>

View File

@@ -0,0 +1,35 @@
@model IEnumerable<ComputerStoreContracts.ViewModels.OrderBatchViewModel>
<div class="container mt-5">
<h4>Партии товаров</h4>
<a asp-action="Create" class="btn btn-success mb-3">Создать партию</a>
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Название</th>
<th>Дата создания</th>
<th>Действия</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.Id</td>
<td>@item.Name</td>
<td>@item.CreatedAt.ToShortDateString()</td>
<td>
<a asp-action="Link" asp-route-id="@item.Id" class="btn btn-info btn-sm">Привязать заказы</a>
<a asp-action="Edit" asp-route-id="@item.Id" class="btn btn-primary btn-sm">Редактировать</a>
<form asp-action="Delete" method="post" style="display:inline">
<input type="hidden" name="id" value="@item.Id" />
<button type="submit" class="btn btn-danger btn-sm">Удалить</button>
</form>
</td>
</tr>
}
</tbody>
</table>
</div>

Some files were not shown because too many files have changed in this diff Show More