This commit is contained in:
Вячеслав Иванов 2024-03-21 21:00:28 +04:00
parent 5855797d38
commit 5cf3fea289
11 changed files with 258 additions and 256 deletions

View File

@ -5,45 +5,45 @@ using System.Text;
namespace PizzeriaClientApp namespace PizzeriaClientApp
{ {
public class APIClient public class APIClient
{ {
private static readonly HttpClient _client = new(); private static readonly HttpClient _client = new();
public static ClientViewModel? Client { get; set; } = null; public static ClientViewModel? Client { get; set; } = null;
public static void Connect(IConfiguration configuration) public static void Connect(IConfiguration configuration)
{ {
_client.BaseAddress = new Uri(configuration["IPAddress"]); _client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear(); _client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
} }
public static T? GetRequest<T>(string requestUrl) public static T? GetRequest<T>(string requestUrl)
{ {
var response = _client.GetAsync(requestUrl); var response = _client.GetAsync(requestUrl);
var result = response.Result.Content.ReadAsStringAsync().Result; var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode) if (response.Result.IsSuccessStatusCode)
{ {
return JsonConvert.DeserializeObject<T>(result); return JsonConvert.DeserializeObject<T>(result);
} }
else else
{ {
throw new Exception(result); throw new Exception(result);
} }
} }
public static void PostRequest<T>(string requestUrl, T model) public static void PostRequest<T>(string requestUrl, T model)
{ {
var json = JsonConvert.SerializeObject(model); var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json"); var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data); var response = _client.PostAsync(requestUrl, 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

@ -8,140 +8,140 @@ namespace PizzeriaClientApp.Controllers
{ {
public class HomeController : Controller public class HomeController : Controller
{ {
private readonly ILogger<HomeController> _logger; private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger) public HomeController(ILogger<HomeController> logger)
{ {
_logger = logger; _logger = logger;
} }
public IActionResult Index() public IActionResult Index()
{ {
if (APIClient.Client == null) if (APIClient.Client == null)
{ {
return Redirect("~/Home/Enter"); return Redirect("~/Home/Enter");
} }
return View(APIClient.GetRequest<List<OrderViewModel>>($"api/main/getorders?clientId={APIClient.Client.Id}")); return View(APIClient.GetRequest<List<OrderViewModel>>($"api/main/getorders?clientId={APIClient.Client.Id}"));
} }
[HttpGet] [HttpGet]
public IActionResult Privacy() public IActionResult Privacy()
{ {
if (APIClient.Client == null) if (APIClient.Client == null)
{ {
return Redirect("~/Home/Enter"); return Redirect("~/Home/Enter");
} }
return View(APIClient.Client); return View(APIClient.Client);
} }
[HttpPost] [HttpPost]
public void Privacy(string login, string password, string fio) public void Privacy(string login, string password, string fio)
{ {
if (APIClient.Client == null) if (APIClient.Client == null)
{ {
throw new Exception("Вы как суда попали? Суда вход только авторизованным"); throw new Exception("Вы как суда попали? Суда вход только авторизованным");
} }
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio)) if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{ {
throw new Exception("Введите логин, пароль и ФИО"); throw new Exception("Введите логин, пароль и ФИО");
} }
APIClient.PostRequest("api/client/updatedata", new ClientBindingModel APIClient.PostRequest("api/client/updatedata", new ClientBindingModel
{ {
Id = APIClient.Client.Id, Id = APIClient.Client.Id,
ClientFIO = fio, ClientFIO = fio,
Email = login, Email = login,
Password = password Password = password
}); });
APIClient.Client.ClientFIO = fio; APIClient.Client.ClientFIO = fio;
APIClient.Client.Email = login; APIClient.Client.Email = login;
APIClient.Client.Password = password; APIClient.Client.Password = password;
Response.Redirect("Index"); Response.Redirect("Index");
} }
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error() public IActionResult Error()
{ {
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
} }
[HttpGet] [HttpGet]
public IActionResult Enter() public IActionResult Enter()
{ {
return View(); return View();
} }
[HttpPost] [HttpPost]
public void Enter(string login, string password) public void Enter(string login, string password)
{ {
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password)) if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{ {
throw new Exception("Введите логин и пароль"); throw new Exception("Введите логин и пароль");
} }
APIClient.Client = APIClient.GetRequest<ClientViewModel>($"api/client/login?login={login}&password={password}"); APIClient.Client = APIClient.GetRequest<ClientViewModel>($"api/client/login?login={login}&password={password}");
if (APIClient.Client == null) if (APIClient.Client == null)
{ {
throw new Exception("Неверный логин/пароль"); throw new Exception("Неверный логин/пароль");
} }
Response.Redirect("Index"); Response.Redirect("Index");
} }
[HttpGet] [HttpGet]
public IActionResult Register() public IActionResult Register()
{ {
return View(); return View();
} }
[HttpPost] [HttpPost]
public void Register(string login, string password, string fio) public void Register(string login, string password, string fio)
{ {
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio)) if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{ {
throw new Exception("Введите логин, пароль и ФИО"); throw new Exception("Введите логин, пароль и ФИО");
} }
APIClient.PostRequest("api/client/register", new ClientBindingModel APIClient.PostRequest("api/client/register", new ClientBindingModel
{ {
ClientFIO = fio, ClientFIO = fio,
Email = login, Email = login,
Password = password Password = password
}); });
Response.Redirect("Enter"); Response.Redirect("Enter");
return; return;
} }
[HttpGet] [HttpGet]
public IActionResult Create() public IActionResult Create()
{ {
ViewBag.Products = APIClient.GetRequest<List<PizzaViewModel>>("api/main/getpizzalist"); ViewBag.Pizzas = APIClient.GetRequest<List<PizzaViewModel>>("api/main/getpizzalist");
return View(); return View();
} }
[HttpPost] [HttpPost]
public void Create(int product, int count) public void Create(int pizza, int count)
{ {
if (APIClient.Client == null) if (APIClient.Client == null)
{ {
throw new Exception("Вы как суда попали? Суда вход только авторизованным"); throw new Exception("Вы как суда попали? Суда вход только авторизованным");
} }
if (count <= 0) if (count <= 0)
{ {
throw new Exception("Количество и сумма должны быть больше 0"); throw new Exception("Количество и сумма должны быть больше 0");
} }
APIClient.PostRequest("api/main/createorder", new OrderBindingModel APIClient.PostRequest("api/main/createorder", new OrderBindingModel
{ {
ClientId = APIClient.Client.Id, ClientId = APIClient.Client.Id,
PizzaId = product, PizzaId = pizza,
Count = count, Count = count,
Sum = Calc(count, product) Sum = Calc(count, pizza)
}); });
Response.Redirect("Index"); Response.Redirect("Index");
} }
[HttpPost] [HttpPost]
public double Calc(int count, int product) public double Calc(int count, int pizza)
{ {
var prod = APIClient.GetRequest<PizzaViewModel>($"api/main/getpizza?pizzaId={product}"); var piz = APIClient.GetRequest<PizzaViewModel>($"api/main/getpizza?pizzaId={pizza}");
return count * (prod?.Price ?? 1); return count * (piz?.Price ?? 1);
} }
} }
} }

View File

@ -12,12 +12,13 @@ APIClient.Connect(builder.Configuration);
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment()) if (!app.Environment.IsDevelopment())
{ {
app.UseExceptionHandler("/Home/Error"); 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. // 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.UseHsts();
} }
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseStaticFiles(); app.UseStaticFiles();
app.UseRouting(); app.UseRouting();
@ -25,7 +26,7 @@ app.UseRouting();
app.UseAuthorization(); app.UseAuthorization();
app.MapControllerRoute( app.MapControllerRoute(
name: "default", name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"); pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run(); app.Run();

View File

@ -8,7 +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="pizza" name="pizza" class="form-control" asp-items="@(new SelectList(@ViewBag.Pizza,"Id", "PizzaName"))"></select> <select id="pizza" name="pizza" class="form-control" asp-items="@(new SelectList(@ViewBag.Pizzas,"Id", "PizzaName"))"></select>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
@ -40,7 +40,7 @@
$.ajax({ $.ajax({
method: "POST", method: "POST",
url: "/Home/Calc", url: "/Home/Calc",
data: { count: count, pizza: pizza }, data: { count: count, pizza: pizza },
success: function (result) { success: function (result) {
$("#sum").val(result); $("#sum").val(result);
} }

View File

@ -1,4 +1,4 @@
@{ @{
ViewData["Title"] = "Enter"; ViewData["Title"] = "Enter";
} }

View File

@ -1,4 +1,4 @@
@using PizzeriaContracts.ViewModels @using PizzeriaContracts.ViewModels
@model List<OrderViewModel> @model List<OrderViewModel>

View File

@ -1,4 +1,4 @@
@using PizzeriaContracts.ViewModels @using PizzeriaContracts.ViewModels
@model ClientViewModel @model ClientViewModel

View File

@ -1,4 +1,4 @@
@{ @{
ViewData["Title"] = "Register"; ViewData["Title"] = "Register";
} }

View File

@ -44,7 +44,7 @@
<footer class="border-top footer text-muted"> <footer class="border-top footer text-muted">
<div class="container"> <div class="container">
&copy; 2023 - PizzeriaShowClientApp - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a> &copy; 2023 - PizzeriaClientApp - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div> </div>
</footer> </footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/jquery/dist/jquery.min.js"></script>

View File

@ -2,47 +2,48 @@
for details on configuring this project to bundle and minify static web assets. */ for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand { a.navbar-brand {
white-space: normal; white-space: normal;
text-align: center; text-align: center;
word-break: break-all; word-break: break-all;
} }
a { a {
color: #0077cc; color: #0077cc;
} }
.btn-primary { .btn-primary {
color: #fff; color: #fff;
background-color: #1b6ec2; background-color: #1b6ec2;
border-color: #1861ac; border-color: #1861ac;
} }
.nav-pills .nav-link.active, .nav-pills .show > .nav-link { .nav-pills .nav-link.active, .nav-pills .show > .nav-link {
color: #fff; color: #fff;
background-color: #1b6ec2; background-color: #1b6ec2;
border-color: #1861ac; border-color: #1861ac;
} }
.border-top { .border-top {
border-top: 1px solid #e5e5e5; border-top: 1px solid #e5e5e5;
} }
.border-bottom { .border-bottom {
border-bottom: 1px solid #e5e5e5; border-bottom: 1px solid #e5e5e5;
} }
.box-shadow { .box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05); box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
} }
button.accept-policy { button.accept-policy {
font-size: 1rem; font-size: 1rem;
line-height: inherit; line-height: inherit;
} }
.footer { .footer {
position: absolute; position: absolute;
bottom: 0; bottom: 0;
width: 100%; width: 100%;
white-space: nowrap; white-space: nowrap;
line-height: 60px; line-height: 60px;
} }

View File

@ -6,77 +6,77 @@ using PizzeriaContracts.ViewModels;
namespace PizzeriaRestApi.Controllers namespace PizzeriaRestApi.Controllers
{ {
[Route("api/[controller]/[action]")] [Route("api/[controller]/[action]")]
[ApiController] [ApiController]
public class MainController : Controller public class MainController : Controller
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IOrderLogic _order; private readonly IOrderLogic _order;
private readonly IPizzaLogic _pizza; private readonly IPizzaLogic _pizza;
public MainController(ILogger<MainController> logger, IOrderLogic order, IPizzaLogic pizza) public MainController(ILogger<MainController> logger, IOrderLogic order, IPizzaLogic pizza)
{ {
_logger = logger; _logger = logger;
_order = order; _order = order;
_pizza = pizza; _pizza = pizza;
} }
[HttpGet] [HttpGet]
public List<PizzaViewModel>? GetPizzaList() public List<PizzaViewModel>? GetPizzaList()
{ {
try try
{ {
return _pizza.ReadList(null); return _pizza.ReadList(null);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка получения списка продуктов"); _logger.LogError(ex, "Ошибка получения списка продуктов");
throw; throw;
} }
} }
[HttpGet] [HttpGet]
public PizzaViewModel? GetPizza(int pizzaId) public PizzaViewModel? GetPizza(int pizzaId)
{ {
try try
{ {
return _pizza.ReadElement(new PizzaSearchModel { Id = pizzaId }); return _pizza.ReadElement(new PizzaSearchModel { Id = pizzaId });
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка получения продукта по id={Id}", pizzaId); _logger.LogError(ex, "Ошибка получения продукта по id={Id}", pizzaId);
throw; throw;
} }
} }
[HttpGet] [HttpGet]
public List<OrderViewModel>? GetOrders(int clientId) public List<OrderViewModel>? GetOrders(int clientId)
{ {
try try
{ {
return _order.ReadList(new OrderSearchModel { ClientId = clientId }); return _order.ReadList(new OrderSearchModel { ClientId = clientId });
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка получения списка заказов клиента id={Id}", clientId); _logger.LogError(ex, "Ошибка получения списка заказов клиента id={Id}", clientId);
throw; throw;
} }
} }
[HttpPost] [HttpPost]
public void CreateOrder(OrderBindingModel model) public void CreateOrder(OrderBindingModel model)
{ {
try try
{ {
_order.CreateOrder(model); _order.CreateOrder(model);
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка создания заказа"); _logger.LogError(ex, "Ошибка создания заказа");
throw; throw;
} }
} }
} }
} }