В принципе нормально

This commit is contained in:
Илья Федотов 2024-05-30 23:49:53 +04:00
parent 26745f6d2b
commit 5f4887ec8c
9 changed files with 123 additions and 101 deletions

View File

@ -1,9 +1,11 @@
using ElectronicsShopContracts.BindingModels; using DocumentFormat.OpenXml.Drawing.Charts;
using ElectronicsShopContracts.BindingModels;
using ElectronicsShopContracts.BusinessLogicContracts; using ElectronicsShopContracts.BusinessLogicContracts;
using ElectronicsShopContracts.SearchModels; using ElectronicsShopContracts.SearchModels;
using ElectronicsShopContracts.StorageContracts; using ElectronicsShopContracts.StorageContracts;
using ElectronicsShopContracts.ViewModels; using ElectronicsShopContracts.ViewModels;
using ElectronicsShopDataModels.Enums; using ElectronicsShopDataModels.Enums;
using ElectronicsShopDataModels.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -27,7 +29,8 @@ namespace ElectronicsShopBusinessLogic.BusinessLogic
} }
return true; return true;
} }
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{ {
_logger.LogInformation($"ReadList:ID:{model?.ID}"); _logger.LogInformation($"ReadList:ID:{model?.ID}");
var list = model == null ? _storage.GetFullList() : _storage.GetFilteredList(model); ; var list = model == null ? _storage.GetFullList() : _storage.GetFilteredList(model); ;
@ -46,10 +49,7 @@ namespace ElectronicsShopBusinessLogic.BusinessLogic
if (string.IsNullOrEmpty((model.ID).ToString())) { if (string.IsNullOrEmpty((model.ID).ToString())) {
throw new ArgumentNullException("Нет ID заказа", nameof(model.ID)); throw new ArgumentNullException("Нет ID заказа", nameof(model.ID));
} }
if (model.Sum <= 0) {////byda if (string.IsNullOrEmpty(model.ClientID.ToString())) {
throw new ArgumentNullException("Цена зака должна быть больше 0", nameof(model.Sum));
}
if (model.ClientID < 0) {
throw new ArgumentNullException("Некорректный идентификатор у клиента", nameof(model.ClientID)); throw new ArgumentNullException("Некорректный идентификатор у клиента", nameof(model.ClientID));
} }
_logger.LogInformation($"Order. ID:{model.ID}.Sum:{model.Sum}.DateCreate:{model.DateCreate}.ClientID:{model.ClientID}"); _logger.LogInformation($"Order. ID:{model.ID}.Sum:{model.Sum}.DateCreate:{model.DateCreate}.ClientID:{model.ClientID}");
@ -69,5 +69,28 @@ namespace ElectronicsShopBusinessLogic.BusinessLogic
return element; return element;
} }
public bool AddProduct(IProductModel product, int count, int orderID) {
var _order = ReadElement(new OrderSearchModel { ID = orderID });
try {
if (_order.ProductList.ContainsKey(product.ID)) {
_order.ProductList[product.ID] = (product, count);
}
else {
_order.ProductList.Add(product.ID, (product, count));
_storage.Update(new OrderBindingModel {
ClientID = _order.ClientID,
ProductList = _order.ProductList,
Sum = 5000,
DateCreate = DateTime.Now,
ID = _order.ID,
});
}
}
catch {
_logger.LogWarning("AddProduct. operation is failed");
return false;
}
return true;
}
} }
} }

View File

@ -1,9 +1,11 @@
using ElectronicsShopContracts.BindingModels; using ElectronicsShopContracts.BindingModels;
using ElectronicsShopContracts.SearchModels; using ElectronicsShopContracts.SearchModels;
using ElectronicsShopContracts.ViewModels; using ElectronicsShopContracts.ViewModels;
using ElectronicsShopDataModels.Models;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Numerics;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -15,5 +17,6 @@ namespace ElectronicsShopContracts.BusinessLogicContracts
OrderViewModel? ReadElement(OrderSearchModel model); OrderViewModel? ReadElement(OrderSearchModel model);
bool CreateOrder(OrderBindingModel model); bool CreateOrder(OrderBindingModel model);
bool AddProduct(IProductModel product, int count, int orderID);
} }
} }

View File

@ -55,16 +55,23 @@ namespace ElectronicsShopDataBaseImplement.Implements
} }
public OrderViewModel? GetElement(OrderSearchModel model) public OrderViewModel? GetElement(OrderSearchModel model)
{ {
if (!model.ID.HasValue) using var context = new Database();
if (model.ClientID.HasValue) {
return context.Orders
.Include(x => x.Payments)
.Include(x => x.Products)
.ThenInclude(x => x._product)
.FirstOrDefault(x => (model.ClientID.HasValue && x.ClientID == model.ClientID))?.GetViewModel;
}
if (model.ID.HasValue)
{ {
return null; return context.Orders
} .Include(x => x.Payments)
using var context = new Database(); .Include(x => x.Products)
return context.Orders .ThenInclude(x => x._product)
.Include(x => x.Payments) .FirstOrDefault(x => (model.ID.HasValue && x.ID == model.ID))?.GetViewModel;
.Include(x => x.Products) }
.ThenInclude(x => x._product) return null;
.FirstOrDefault(x => (model.ID.HasValue && x.ID == model.ID))?.GetViewModel;
} }
public List<OrderViewModel> GetFilteredList(OrderSearchModel model) public List<OrderViewModel> GetFilteredList(OrderSearchModel model)

View File

@ -66,7 +66,7 @@ namespace ElectronicsShopRestAPI.Controllers {
_costItem.Create(model); _costItem.Create(model);
} }
catch (Exception ex) { catch (Exception ex) {
_logger.LogError(ex, "Ошибка создания заказа"); _logger.LogError(ex, "Ошибка создания статьи");
throw; throw;
} }
} }

View File

@ -5,6 +5,7 @@ using ElectronicsShopContracts.ViewModels;
using ElectronicsShopDataBaseImplement.Models; using ElectronicsShopDataBaseImplement.Models;
using ElectronicsShopDataModels.Models; using ElectronicsShopDataModels.Models;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace ElectronicsShopRestAPI.Controllers { namespace ElectronicsShopRestAPI.Controllers {
@ -16,14 +17,12 @@ namespace ElectronicsShopRestAPI.Controllers {
private readonly IProductLogic _product; private readonly IProductLogic _product;
private readonly IOrderLogic _order; private readonly IOrderLogic _order;
private readonly IMessageInfoLogic _message; private readonly IMessageInfoLogic _message;
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]
@ -79,24 +78,31 @@ namespace ElectronicsShopRestAPI.Controllers {
} }
} }
[HttpPost]
public void CreateOrder(OrderBindingModel model) {
try {
_order.CreateOrder(model);
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка создания заказа");
throw;
}
}
[HttpPost] [HttpPost]
public void AddProduct(OrderBindingModel model) public void AddProduct(List<string> jslist)
{ {
try var product = JsonConvert.DeserializeObject<ProductViewModel>(jslist[0]);
{ int count = JsonConvert.DeserializeObject<int>(jslist[1]);
var order=_order.ReadElement(new OrderSearchModel { ID = model.ID });//возвращает null int orderid = JsonConvert.DeserializeObject<int>(jslist[2]);
if (model != null&& order!=null)
{ try {
order.ProductList = model.ProductList; _order.AddProduct(product, count, orderid);
order.Sum += model.Sum; }
} catch (Exception ex) {
} _logger.LogError(ex, "Ошибка добавления заказа");
catch (Exception ex) throw;
{ }
_logger.LogError(ex, "Ошибка создания заказа");
throw;
}
} }
} }
} }

View File

@ -8,6 +8,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup> </ItemGroup>

View File

@ -40,25 +40,23 @@ namespace ElectronicsShopUserApp {
} }
} }
public static void PostDictRequest<T>(string requstUrl, OrderBindingModel model) { public static void ListPostRequest<T>(string requstUrl, T model, int count, int orderID) {
var dict = new Dictionary<string, (string, string)>(); var list = new List<string>() {
JsonConvert.SerializeObject(model),
JsonConvert.SerializeObject(count),
JsonConvert.SerializeObject(orderID),
};
foreach (var item in model.ProductList) { var json = JsonConvert.SerializeObject(list);
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 data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requstUrl, data,); var response = _client.PostAsync(requstUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result; var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode) { if (!response.Result.IsSuccessStatusCode) {
throw new Exception(result); throw new Exception(result);
} }
} }
} }
} }

View File

@ -100,17 +100,33 @@ namespace ElectronicsShopUserApp.Controllers {
if (APIClient.Client == null) { if (APIClient.Client == null) {
return Redirect("~/Home/Enter"); return Redirect("~/Home/Enter");
} }
return View(APIClient.GetRequset<List<OrderViewModel>>($"api/main/getorders?_clientid={APIClient.Client.ID}")); return View(APIClient.GetRequset<List<OrderViewModel>>($"api/main/getorders?_clientid={APIClient.Client.ID}"));
} }
[HttpGet] [HttpGet]
public IActionResult CreateOrder() { public IActionResult CreateOrder() {
var view = APIClient.GetRequset<OrderViewModel>($"api/main/getorder?_clientid={APIClient.Client?.ID}") ?? new OrderViewModel { if (APIClient.Client == null) {
ProductList = _productList return Redirect("~/Home/Enter");
}; }
return View(view); APIClient.PostRequest("api/main/createorder", new OrderBindingModel {
ClientID = APIClient.Client.ID,
DateCreate = DateTime.Now,
});
return RedirectToAction("OrderView");
} }
[HttpGet]
public IActionResult OrderView() {
if (APIClient.Client == null) {
return Redirect("~/Home/Enter");
}
var view = APIClient.GetRequset<OrderViewModel>($"api/main/getorder?_clientid={APIClient.Client?.ID}");
return View(view);
}
[HttpGet] [HttpGet]
public IActionResult AddProduct() { public IActionResult AddProduct() {
ViewBag.Products = APIClient.GetRequset<List<ProductViewModel>>($"api/main/getproducts"); ViewBag.Products = APIClient.GetRequset<List<ProductViewModel>>($"api/main/getproducts");
@ -118,30 +134,12 @@ namespace ElectronicsShopUserApp.Controllers {
} }
[HttpPost] [HttpPost]
public void AddProduct(double sum, int product, int count) { public void AddProduct(int product, int count) {
if (APIClient.Client == null) { var _product = APIClient.GetRequset<ProductViewModel>($"api/main/getproduct?_productid={product}");
throw new Exception("Òîëüêî äëÿ àâòîðèçîâàíûõ"); var _order = APIClient.GetRequset<OrderViewModel>($"api/main/getorder?_clientid={APIClient.Client?.ID}");
}
if (sum <= 0) {
throw new Exception("Ñóììà çàòðàò äîëæíà áûòü áîëüøå 0");
}
var _product = APIClient.GetRequset<ProductViewModel>($"api/main/getproduct?_productid={product}");
_product.Price = sum;
if (_productList.ContainsKey(product)) { APIClient.ListPostRequest($"api/main/addproduct", _product, count, _order.ID);
_productList[product] = (_product, count); Response.Redirect("OrderView");
}
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]
@ -157,28 +155,8 @@ namespace ElectronicsShopUserApp.Controllers {
[HttpPost] [HttpPost]
public double Calc(int count, int product) public double Calc(int count, int product)
{ {
var prod = APIClient.GetRequset<ProductViewModel>($"api/main/getproduct?_productid={product}"); var _product = APIClient.GetRequset<ProductViewModel>($"api/main/getproduct?_productid={product}");
return count * (prod?.Price ?? 1); return count * (_product?.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

@ -3,7 +3,7 @@
@model OrderViewModel @model OrderViewModel
@{ @{
ViewData["Title"] = "CreateOrder"; ViewData["Title"] = "OrderView";
} }
<div class="text-center"> <div class="text-center">
@ -11,6 +11,12 @@
</div> </div>
<div class=" text-center"> <div class=" text-center">
<div class="row">
<label class="col-4">Номер корзины:</label>
<div class="col-8">
<input id="OrderID" class="form-control" type="text" name="OrderID" value="@Model.ID" readonly />
</div>
</div>
<p> <p>
<a asp-action="AddProduct">Добавить товар</a> <a asp-action="AddProduct">Добавить товар</a>
</p> </p>