Ненавижу сериализацию словарей

This commit is contained in:
Илья Федотов 2024-05-30 20:32:16 +04:00
parent 92b18d3a1a
commit ee3dcbb46e
11 changed files with 218 additions and 143 deletions

View File

@ -12,7 +12,7 @@ namespace ElectronicsShopDataBaseImplement
optionsBuilder) optionsBuilder)
{ {
if (optionsBuilder.IsConfigured == false) { if (optionsBuilder.IsConfigured == false) {
optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-E2VPEN3\SQLEXPRESS;Initial Catalog=ElectronicsShopDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True"); optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-O0N00SH\SQLEXPRESS;Initial Catalog=ElectronicsShopDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
} }
base.OnConfiguring(optionsBuilder); base.OnConfiguring(optionsBuilder);
} }

View File

@ -69,11 +69,18 @@ namespace ElectronicsShopDataBaseImplement.Implements
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{ {
using var context = new Database();
if (!model.ID.HasValue && (model.DateFrom == null || model.DateTo == null)) if (!model.ID.HasValue && (model.DateFrom == null || model.DateTo == null))
{ {
return new(); return new();
} }
using var context = new Database(); else if (model.ClientID.HasValue) {
return context.Orders
.Include (x => x.Products)
.Where(x => x.ClientID == model.ClientID)
.Select(x => x.GetViewModel)
.ToList();
}
return context.Orders return context.Orders
.Include(x => x.Products) .Include(x => x.Products)
.ThenInclude(x => x._product) .ThenInclude(x => x._product)

View File

@ -116,7 +116,7 @@ namespace ElectronicsShopEmployeeApp.Controllers {
Price = price, Price = price,
CostNum = costNum CostNum = costNum
}); });
Response.Redirect("CostItem");
} }
[HttpGet] [HttpGet]

View File

@ -3,6 +3,7 @@ using ElectronicsShopContracts.BusinessLogicContracts;
using ElectronicsShopContracts.SearchModels; using ElectronicsShopContracts.SearchModels;
using ElectronicsShopContracts.ViewModels; using ElectronicsShopContracts.ViewModels;
using ElectronicsShopDataBaseImplement.Models; using ElectronicsShopDataBaseImplement.Models;
using ElectronicsShopDataModels.Models;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace ElectronicsShopRestAPI.Controllers { namespace ElectronicsShopRestAPI.Controllers {
@ -14,13 +15,15 @@ namespace ElectronicsShopRestAPI.Controllers {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IProductLogic _product; private readonly IProductLogic _product;
private readonly IOrderLogic _order; private readonly IOrderLogic _order;
private Dictionary<int, (IProductModel, int)> _ProductList;
private int? _ID;
public MainController(ILogger<MainController> logger, IProductLogic product, public MainController(ILogger<MainController> logger, IProductLogic product,
IOrderLogic orderLogic) { IOrderLogic orderLogic) {
_logger = logger; _logger = logger;
_product = product; _product = product;
_order = orderLogic; _order = orderLogic;
_ProductList = new Dictionary<int, (IProductModel, int)>();
} }
[HttpGet] [HttpGet]
@ -65,6 +68,17 @@ namespace ElectronicsShopRestAPI.Controllers {
} }
} }
[HttpGet]
public OrderViewModel? GetOrder(int _clientID) {
try {
return _order.ReadElement(new OrderSearchModel { ClientID = _clientID });
}
catch (Exception ex) {
_logger.LogError(ex, $"Ошибка получения данных clientid = {_clientID}");
throw;
}
}
[HttpPost] [HttpPost]
public void CreateOrder(OrderBindingModel model) { public void CreateOrder(OrderBindingModel model) {
@ -78,43 +92,10 @@ namespace ElectronicsShopRestAPI.Controllers {
throw; throw;
} }
} }
[HttpGet]
public List<OrderViewModel>? GetAddProduct(int _clientID,int _orderID)
{
try
{
return _order.ReadList(new OrderSearchModel
{
ID = _orderID,
ClientID = _clientID
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка заказов клиента id = {Id} ", _clientID);
throw;
}
}
[HttpPost] [HttpPost]
public void AddProduct(OrderBindingModel model) public void SaveOrder(Dictionary<int, (IProductModel, int)> list) {
{
try
{
var order=_order.ReadElement(new OrderSearchModel { ID = model.ID });//возвращает null
if (model != null&& order!=null)
{
order.ProductList = model.ProductList;
order.Sum += model.Sum;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания заказа");
throw;
}
} }
} }
} }

View File

@ -1,5 +1,7 @@
using ElectronicsShopContracts.ViewModels; using ElectronicsShopContracts.BindingModels;
using ElectronicsShopContracts.ViewModels;
using Newtonsoft.Json; using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text; using System.Text;
@ -37,5 +39,26 @@ namespace ElectronicsShopUserApp {
throw new Exception(result); throw new Exception(result);
} }
} }
public static void PostDictRequest<T>(string requstUrl, OrderBindingModel model) {
var dict = new Dictionary<string, (string, string)>();
foreach (var item in model.ProductList) {
var key = item.Key.ToString();
var item1 = JsonConvert.SerializeObject(item.Value.Item1);
var item2 = item.Value.Item2.ToString();
dict.Add(key, (item1, item2));
}
var dictjs = JsonConvert.SerializeObject(dict);
var data = new StringContent(dictjs, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requstUrl, data,);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode) {
throw new Exception(result);
}
}
} }
} }

View File

@ -12,11 +12,12 @@ using System.Runtime.Serialization;
namespace ElectronicsShopUserApp.Controllers { namespace ElectronicsShopUserApp.Controllers {
public class HomeController : Controller { public class HomeController : Controller {
private readonly ILogger<HomeController> _logger; private readonly ILogger<HomeController> _logger;
private Dictionary<int, (IProductModel, int)> _productList;
//private readonly IOrderLogic _order; //private readonly IOrderLogic _order;
public HomeController(ILogger<HomeController> logger/*, IOrderLogic orderLogic*/) { public HomeController(ILogger<HomeController> logger/*, IOrderLogic orderLogic*/) {
_logger = logger; _logger = logger;
//_order = orderLogic; _productList = new Dictionary<int, (IProductModel, int)>();
} }
public IActionResult Index() { public IActionResult Index() {
@ -95,24 +96,54 @@ namespace ElectronicsShopUserApp.Controllers {
return; return;
} }
[HttpGet] public IActionResult Orders() {
public IActionResult CreateOrders() { if (APIClient.Client == null) {
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequset<List<OrderViewModel>>($"api/main/getorders?_clientid={APIClient.Client.ID}"));
}
ViewBag.Products =APIClient.GetRequset<List<ProductViewModel>>("api/main/getproducts"); [HttpGet]
public IActionResult CreateOrder() {
var view = APIClient.GetRequset<OrderViewModel>($"api/main/getorder?_clientid={APIClient.Client?.ID}") ?? new OrderViewModel {
ProductList = _productList
};
return View(view);
}
[HttpGet]
public IActionResult AddProduct() {
ViewBag.Products = APIClient.GetRequset<List<ProductViewModel>>($"api/main/getproducts");
return View(); return View();
} }
[HttpPost] [HttpPost]
public void CreateOrders(OrderBindingModel order) { public void AddProduct(double sum, int product, int count) {
if (APIClient.Client == null) if (APIClient.Client == null) {
{ throw new Exception("Òîëüêî äëÿ àâòîðèçîâàíûõ");
throw new Exception("Âû êàê ñóäà ïîïàëè? Ñóäà âõîä òîëüêî àâòîðèçîâàííûì");
} }
if (order.ProductList.Count > 0) if (sum <= 0) {
{ throw new Exception("Ñóììà çàòðàò äîëæíà áûòü áîëüøå 0");
throw new Exception("Êîëè÷åñòâî è ñóììà äîëæíû áûòü áîëüøå 0");
} }
Response.Redirect("Index"); var _product = APIClient.GetRequset<ProductViewModel>($"api/main/getproduct?_productid={product}");
_product.Price = sum;
if (_productList.ContainsKey(product)) {
_productList[product] = (_product, count);
} }
else {
_productList.Add(product, (_product, count));
}
APIClient.PostDictRequest<OrderBindingModel>($"api/main/saveorder", new OrderBindingModel {
ProductList = _productList,
Sum = CalcAll(_productList),
ClientID = APIClient.Client.ID,
});
Response.Redirect("CreateOrder");
}
[HttpPost] [HttpPost]
private double CalcAll(Dictionary<int, (IProductModel, int)> ProductList) private double CalcAll(Dictionary<int, (IProductModel, int)> ProductList)
{ {
@ -126,30 +157,8 @@ namespace ElectronicsShopUserApp.Controllers {
[HttpPost] [HttpPost]
public double Calc(int count, int product) public double Calc(int count, int product)
{ {
var prod = var prod = APIClient.GetRequset<ProductViewModel>($"api/main/getproduct?_productid={product}");
APIClient.GetRequset<ProductViewModel>($"api/main/getproduct?_productid={product}"
);
return count * (prod?.Price ?? 1); return count * (prod?.Price ?? 1);
} }
[HttpGet]
public IActionResult AddProduct()
{
ViewBag.Products = APIClient.GetRequset<List<ProductViewModel>>("api/main/getproducts");
return View();
}
[HttpPost]
public void AddProduct(int count/*, int product*/)
{
if (APIClient.Client == null)
{
throw new Exception("Âû êàê ñóäà ïîïàëè? Ñóäà âõîä òîëüêî àâòîðèçîâàííûì");
}
if (count <= 0)
{
throw new Exception("Êîëè÷åñòâî è ñóììà äîëæíû áûòü áîëüøå 0");
}
Response.Redirect("CreateOrder");
}
} }
} }

View File

@ -8,12 +8,7 @@
<div class="row"> <div class="row">
<div class="col-4">Продукты:</div> <div class="col-4">Продукты:</div>
<div class="col-8"> <div class="col-8">
<select id="product" name="product" class="form-control"> <select id="product" name="product" class="form-control" asp-items="@(new SelectList(ViewBag.Products, "ID", "ProductName"))"> </select>
@foreach (var product in ViewBag.Products)
{
<option value="@product.ID">@product.ProductName</option>
}
</select>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
@ -53,8 +48,7 @@
url: "/Home/Calc", url: "/Home/Calc",
data: { count: count, product: product }, data: { count: count, product: product },
success: function (result) { success: function (result) {
var roundedResult = parseFloat(result).toFixed(2); $("#sum").val(result);
$("#sum").val(roundedResult);
} }
}); });
}; };

View File

@ -0,0 +1,50 @@
@using ElectronicsShopContracts.ViewModels
@model OrderViewModel
@{
ViewData["Title"] = "CreateOrder";
}
<div class="text-center">
<h1 class="display-4">Создание корзины</h1>
</div>
<div class=" text-center">
<p>
<a asp-action="AddProduct">Добавить товар</a>
</p>
<table class="table">
<thead>
<tr>
<th>
Продукт
</th>
<th>
Количество
</th>
<th>
Сумма
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.ProductList) {
<tr>
<th>
@Html.DisplayFor(modelItem => item.Value.Item1.ProductName);
</th>
<th>
@Html.DisplayFor(modelItem => item.Value.Item2);
</th>
<th>
@Html.DisplayFor(modelItem => (item.Value.Item1.Price * item.Value.Item2));
</th>
<td>
<a class="btn btn-primary btn-sm" asp-action="DeleteProductOrder" asp-></a>
</td>
</tr>
}
</tbody>
</table>
</div>

View File

@ -1,45 +0,0 @@
@using ElectronicsShopContracts.ViewModels
@model OrderViewModel
@{
ViewData["Title"] = "CreateOrders";
}
<div class="text-center">
<h1 class="display-4">Корзина</h1>
@{
<table class="table">
<thead>
<th>
<th>
Продукт
</th>
<th>
Количество
</th>
<th>
Сумма
</th>
</th>
</thead>
<tbody>
@if(Model!=null){
@foreach (var item in Model.ProductList)
{
<th>
<th>
@Html.DisplayFor(modelItem => item.Value.Item1.ProductName)
</th>
<th>
@Html.DisplayFor(modelItem => item.Value.Item2)
</th>
<th>
@Html.DisplayFor(modelItem => item.Value.Item1.Price*item.Value.Item2)
</th>
</th>
}
}
</tbody>
</table>
}
</div>

View File

@ -0,0 +1,59 @@
@using ElectronicsShopContracts.ViewModels
@model List<OrderViewModel>
@{
ViewData["Title"] = "Orders";
}
<div class="text-center">
<h1 class="display-4">Корзины</h1>
</div>
<div class="text-center">
@{
if (Model == null) {
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<p>
<a asp-action="CreateOrder">Добавить корзину</a>
</p>
<table class="table">
<thead>
<tr>
<th>
Номер
</th>
<th>
Дата создания
</th>
<th>
Сумма
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<th>
@Html.DisplayFor(modelItem => item.ID)
</th>
<th>
@Html.DisplayFor(modelItem => item.DateCreate)
</th>
<th>
@Html.DisplayFor(modelItem => item.Sum)
</th>
<td>
<a class="btn btn-primary btn-sm" asp-action="EditCostItem" asp-route-ID="@item.ID">Изменить</a>
<a class="btn btn-primary btn-sm" asp-action="DeleteCostItem" asp-route-ID="@item.ID">Удалить</a>
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -32,10 +32,7 @@
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Register">Регистрация</a> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Register">Регистрация</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="CreateOrders">Создание корзин</a> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Orders">Корзины</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="AddProduct">Каталог</a>
</li> </li>
</ul> </ul>
</div> </div>