API employee

This commit is contained in:
kagbie3nn@mail.ru 2024-04-28 17:06:40 +04:00
parent 6270fe521c
commit 874723cbcd
12 changed files with 457 additions and 33 deletions

View File

@ -0,0 +1,85 @@
using Microsoft.AspNetCore.Mvc;
using ZooContracts.BindingModels;
using ZooContracts.BuisnessLogicsContracts;
using ZooContracts.BusinessLogicsContracts;
using ZooContracts.SearchModels;
using ZooContracts.ViewModels;
namespace ZooRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class MainController : Controller
{
private readonly ILogger _logger;
private readonly IRouteLogic _route;
private readonly IPreserveLogic _preserve;
public MainController(ILogger<MainController> logger, IRouteLogic route,
IPreserveLogic preserve)
{
_logger = logger;
_route = route;
_preserve = preserve;
}
[HttpGet]
public List<PreserveViewModel>? GetPreserveList()
{
try
{
return _preserve.ReadList(null);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка продуктов");
throw;
}
}
[HttpGet]
public PreserveViewModel? GetPreserve(int preserveId)
{
try
{
return _preserve.ReadElement(new PreserveSearchModel
{
Id =
preserveId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения заповедника по id={Id}",
preserveId);
throw;
}
}
[HttpGet]
public List<RouteViewModel>? GetRoutes(int clientId)
{
try
{
return _route.ReadList(new RouteSearchModel
{
ClientId = clientId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка маршрутов клиента id ={ Id}", clientId);
throw;
}
}
[HttpPost]
public void CreateRoute(RouteBindingModel model)
{
try
{
_route.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания маршрута");
throw;
}
}
}
}

View File

@ -0,0 +1,45 @@
using ZooContracts.ViewModels;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
namespace ZooShowEmployeeApp
{
public static class APIEmployee
{
private static readonly HttpClient _employee = new();
public static EmployeeViewModel? Employee { get; set; } = null;
public static void Connect(IConfiguration configuration)
{
_employee.BaseAddress = new Uri(configuration["IPAddress"]);
_employee.DefaultRequestHeaders.Accept.Clear();
_employee.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
}
public static T? GetRequest<T>(string requestUrl)
{
var response = _employee.GetAsync(requestUrl);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>(result);
}
else
{
throw new Exception(result);
}
}
public static void PostRequest<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8,
"application/json");
var response = _employee.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
throw new Exception(result);
}
}
}
}

View File

@ -1,4 +1,6 @@
using Microsoft.AspNetCore.Mvc;
using ZooContracts.BindingModels;
using ZooContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using ZooShowEmployeeApp.Models;
@ -15,18 +17,117 @@ namespace ZooShowEmployeeApp.Controllers
public IActionResult Index()
{
return View();
if (APIEmployee.Employee == null)
{
return Redirect("~/Home/Enter");
}
return
View(APIEmployee.GetRequest<List<RouteViewModel>>($"api/main/getorders?clientId={APIEmployee.Employee.Id}"));
}
[HttpGet]
public IActionResult Privacy()
{
return View();
if (APIEmployee.Employee == null)
{
return Redirect("~/Home/Enter");
}
return View(APIEmployee.Employee);
}
[HttpPost]
public void Privacy(string login, string password, string fio)
{
if (APIEmployee.Employee == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(login) ||
string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{
throw new Exception("Введите логин, пароль и ФИО");
}
APIEmployee.PostRequest("api/employee/updatedata", new
EmployeeBindingModel
{
Id = APIEmployee.Employee.Id,
EmployeeFIO = fio,
Login = login,
Password = password
}); ;
APIEmployee.Employee.EmployeeFIO = fio;
APIEmployee.Employee.Login = login;
APIEmployee.Employee.Password = password;
Response.Redirect("Index");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
return View(new ErrorViewModel
{
RequestId =
Activity.Current?.Id ?? HttpContext.TraceIdentifier
});
}
[HttpGet]
public IActionResult Enter()
{
return View();
}
[HttpPost]
public void Enter(string login, string password)
{
if (string.IsNullOrEmpty(login) ||
string.IsNullOrEmpty(password))
{
throw new Exception("Введите логин и пароль");
}
APIEmployee.Employee =
APIEmployee.GetRequest<EmployeeViewModel>($"api/employee/login?login={login}&password={password}");
if (APIEmployee.Employee == null)
{
throw new Exception("Неверный логин/пароль");
}
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public void Register(string login, string password, string fio)
{
if (string.IsNullOrEmpty(login) ||
string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{
throw new Exception("Введите логин, пароль и ФИО");
}
APIEmployee.PostRequest("api/employee/register", new
EmployeeBindingModel
{
EmployeeFIO = fio,
Login = login,
Password = password
});
Response.Redirect("Enter");
return;
}
[HttpGet]
public IActionResult Create()
{
ViewBag.Preserver =
APIEmployee.GetRequest<List<PreserveViewModel>>("api/main/getpreservelist");
return View();
}
[HttpPost]
public double Calc(int count, int preserve)
{
var prod =
APIEmployee.GetRequest<PreserveViewModel>($"api/main/getpreserve?preserveId={preserve}"
);
return count * (prod?.PreservePrice ?? 1);
}
}
}

View File

@ -1,10 +1,10 @@
using ZooShowEmployeeApp;
using Microsoft.EntityFrameworkCore.Infrastructure;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
APIEmployee.Connect(builder.Configuration);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
@ -12,16 +12,11 @@ if (!app.Environment.IsDevelopment())
// 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.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

View File

@ -0,0 +1,49 @@
@{
ViewData["Title"] = "Create";
}
<div class="text-center">
<h2 class="display-4">Создание Заповедника</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Название:</div>
<div class="col-8">
<select id="preserve" name="preserve" class="form-control" aspitems="@(new SelectList(@ViewBag.Preserve,"Id", "PreserveName"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Стоимость:</div>
<div class="col-8">
<input type="text" id="PreservePrice" name="PreservePrice" readonly />
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Создать" class="btn
btn-primary" />
</div>
</div>
</form>
<script>
$('#preserve').on('change', function () {
check();
});
$('#PreservePrice').on('change', function () {
check();
});
function check() {
var price = $('#PreservePrice').val();
var preserve = $('#preserve').val();
if (price && product) {
$.ajax({
method: "POST",
url: "/Home/Calc",
data: { price: price, preserve: preserve },
success: function (result) {
$("#sum").val(result);
}
});
};
}
</script>

View File

@ -0,0 +1,20 @@
@{
ViewData["Title"] = "Enter";
}
<div class="text-center">
<h2 class="display-4">Вход в приложение</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" /></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Вход" class="btn btnprimary" /></div>
</div>
</form>

View File

@ -1,8 +1,65 @@
@{
@using ZooContracts.ViewModels
@model List<RouteViewModel>
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
<h1 class="display-4">Маршруты</h1>
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<table class="table">
<thead>
<tr>
<th>
Номер
</th>
<th>
Заповедники
</th>
<th>
Дата начала
</th>
<th>
Дата окончания
</th>
<th>
Статус
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem =>
item.Id)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.RouteName)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.DateStart)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.DateFinish)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.Status)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -1,6 +1,38 @@
@{
@using ZooContracts.ViewModels
@model ClientViewModel
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p>
<div class="text-center">
<h2 class="display-4">Личные данные</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8">
<input type="text" name="login"
value="@Model.Email" />
</div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8">
<input type="password" name="password"
value="@Model.Password" />
</div>
</div>
<div class="row">
<div class="col-4">ФИО:</div>
<div class="col-8">
<input type="text" name="fio"
value="@Model.ClientFIO" />
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Сохранить" class="btn
btn-primary" />
</div>
</div>
</form>

View File

@ -0,0 +1,27 @@
@{
ViewData["Title"] = "Register";
}
<div class="text-center">
<h2 class="display-4">Регистрация</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" /></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8"><input type="password" name="password" /></div>
</div>
<div class="row">
<div class="col-4">ФИО:</div>
<div class="col-8"><input type="text" name="fio" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Регистрация"
class="btn btn-primary" />
</div>
</div>
</form>

View File

@ -6,24 +6,28 @@
<title>@ViewData["Title"] - ZooShowEmployeeApp</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/ZooShowEmployeeApp.styles.css" asp-append-version="true" />
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container-fluid">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">ZooShowEmployeeApp</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Зоопарк "Юрский период"</a>
<button class="navbar-toggler" type="button" datatoggle="collapse" data-target=".navbar-collapse" ariacontrols="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Enter">Вход</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Register">Регистрация</a>
</li>
</ul>
</div>
@ -38,12 +42,10 @@
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2024 - ZooShowEmployeeApp - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
&copy; 2024 - Зоопарк Юрский период - - <a asp-area="" aspcontroller="Home" asp-action="Privacy">Личные данные</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
@RenderSection("Scripts", required: false)
</body>
</html>

View File

@ -6,4 +6,13 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ZooBusinessLogic\ZooBusinessLogic.csproj" />
<ProjectReference Include="..\ZooDataBaseImplement\ZooDataBaseImplement.csproj" />
</ItemGroup>
</Project>

View File

@ -5,5 +5,7 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"IPAddress": "http://localhost:5044/"
}