Merge branch 'Storekeeper' into Worker_Raspaev

This commit is contained in:
Николай 2023-05-16 15:42:10 +04:00
commit 70ae0159af
15 changed files with 788 additions and 62 deletions

View File

@ -22,18 +22,18 @@ namespace HardwareShopStorekeeperApp.Controllers
}
[HttpPost]
public void Register(string login, string email, string password, int role)
public void Register(string login, string email, string password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password) || role <= 0)
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
{
throw new Exception("Введите логин, email, пароль и роль");
throw new Exception("Введите логин, email, пароль");
}
APIClient.PostRequest("api/client/register", new UserBindingModel
APIClient.PostRequest("api/user/register", new UserBindingModel
{
Login = login,
Email = email,
Password = password,
Role = (UserRole)role
Role = UserRole.Кладовщик
});
Response.Redirect("Enter");
return;
@ -67,7 +67,7 @@ namespace HardwareShopStorekeeperApp.Controllers
{
throw new Exception("Введите почту и пароль");
}
APIClient.User = APIClient.GetRequest<UserViewModel>($"api/client/login?email={email}&password={password}");
APIClient.User = APIClient.GetRequest<UserViewModel>($"api/user/login?email={email}&password={password}");
if (APIClient.User == null)
{
throw new Exception("Неверные почта и/или пароль");

View File

@ -1,4 +1,7 @@
using Microsoft.AspNetCore.Mvc;
using HardwareShopContracts.BindingModels;
using HardwareShopContracts.ViewModels;
using HardwareShopDataModels.Enums;
using Microsoft.AspNetCore.Mvc;
namespace HardwareShopStorekeeperApp.Controllers
{
@ -12,51 +15,231 @@ namespace HardwareShopStorekeeperApp.Controllers
}
public IActionResult CreateOrder()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Goods = APIClient.GetRequest<List<GoodViewModel>>($"api/good/getgoods?userId={APIClient.User.Id}");
return View();
}
[HttpPost]
public void CreateOrder(int good, int count, string sum)
{
if (APIClient.User == null)
{
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
}
if (good <= 0)
{
throw new Exception("Некорректный идентификатор товара");
}
if (count <= 0)
{
throw new Exception("Количество должно быть больше 0");
}
if (Convert.ToDouble(sum.Replace('.', ',')) <= 0)
{
throw new Exception("Цена должна быть больше 0");
}
APIClient.PostRequest("api/order/createorder", new OrderBindingModel
{
UserId = APIClient.User.Id,
GoodId = good,
Count = count,
Sum = Convert.ToDouble(sum.Replace('.', ','))
});
Response.Redirect("Orders");
}
[HttpPost]
public void DeleteOrder(int Id)
{
if (APIClient.User == null)
{
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
}
if (Id <= 0)
{
throw new Exception("Некорректный идентификатор");
}
APIClient.PostRequest("api/order/deleteorder", new OrderBindingModel
{
Id = Id
});
Response.Redirect("Orders");
}
[HttpPost]
public void UpdateOrder(int id, int status)
{
if (APIClient.User == null)
{
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
}
if (id <= 0)
{
throw new Exception("Некорректный идентификатор");
}
if (status <= 0)
{
throw new Exception("Некорректный статус");
}
APIClient.PostRequest("api/order/updatedata", new OrderBindingModel
{
Id = id,
Status = (OrderStatus)status
});
Response.Redirect("Orders");
}
[HttpPost]
public double Calc(int count, int good)
{
var prod = APIClient.GetRequest<GoodViewModel>($"api/good/getgood?id={good}");
double result = Math.Round(count * (prod?.Price ?? 1), 2);
return result;
}
public IActionResult CreateGood()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Components = APIClient.GetRequest<List<ComponentViewModel>>($"api/component/getcomponents?userId={APIClient.User.Id}");
return View();
}
[HttpPost]
public void CreateGood([FromBody]GoodBindingModel goodModel)
{
if (APIClient.User == null)
{
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
}
if (string.IsNullOrEmpty(goodModel.GoodName))
{
throw new Exception("Название не должно быть пустым");
}
if (goodModel.Price <= 0)
{
throw new Exception("Цена должна быть больше 0");
}
goodModel.UserId = APIClient.User.Id;
APIClient.PostRequest("api/good/creategood", goodModel);
}
public IActionResult LinkBuilds()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
public IActionResult CreateComponent()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
[HttpPost]
public void CreateComponent(string name, string cost, DateTime date)
{
if (APIClient.User == null)
{
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
}
if (string.IsNullOrEmpty(name))
{
throw new Exception("Название не должно быть пустым");
}
if (string.IsNullOrEmpty(cost) || Convert.ToDouble(cost.Replace('.', ',')) <= 0)
{
throw new Exception("Цена должна быть больше 0");
}
APIClient.PostRequest("api/component/createcomponent", new ComponentBindingModel
{
UserId = APIClient.User.Id,
ComponentName = name,
Cost = Convert.ToDouble(cost.Replace('.', ',')),
DateCreate = date
});
Response.Redirect("Components");
}
[HttpGet]
public ComponentViewModel? GetComponent(int Id)
{
if (APIClient.User == null)
{
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
}
var result = APIClient.GetRequest<ComponentViewModel?>($"api/component/getcomponent?id={Id}");
if (result == null)
{
return default;
}
return result;
}
public IActionResult MainStorekeeper()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
public IActionResult Components()
{
return View();
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<ComponentViewModel>>($"api/component/getcomponents?userId={APIClient.User.Id}"));
}
public IActionResult Goods()
{
return View();
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<GoodViewModel>>($"api/good/getgoods?userId={APIClient.User.Id}"));
}
public IActionResult Orders()
{
return View();
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<OrderViewModel>>($"api/order/getorders?userId={APIClient.User.Id}"));
}
public IActionResult ListBuilds()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
public IActionResult Report()
{
if (APIClient.User == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
}

View File

@ -7,6 +7,7 @@ builder.Services.AddControllersWithViews();
var app = builder.Build();
APIClient.Connect(builder.Configuration);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
@ -26,4 +27,4 @@ app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
app.Run();

View File

@ -7,6 +7,7 @@
<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="~/HardwareShopStorekeeperApp.styles.css" asp-append-version="true" />
@await RenderSectionAsync("Styles", required: false)
</head>
<body>
<header>

View File

@ -1,4 +1,7 @@
@using HardwareShopContracts.ViewModels
@model List<ComponentViewModel>
@{
ViewData["Title"] = "Комплектующие";
Layout = "~/Views/Shared/_LayoutStorekeeper.cshtml";
@ -10,29 +13,45 @@
<div class="text-center">
<p>
<a asp-action="CreateComponent" class="btn btn-primary mx-2">Создать комплектующее</a>
<button type="button" class="btn btn-primary mx-2" data-bs-toggle="modal" data-bs-target="#exampleModal">Изменить комплектующее</button>
<button type="button" class="btn btn-primary mx-2">Удалить комплектующее</button>
<a asp-action="LinkBuilds" class="btn btn-primary mx-2">Привязка сборок</a>
</p>
<table class="table">
<thead>
<tr>
<th>
Название
</th>
<th>
Цена
</th>
<th>
Дата приобретения
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
@{
<p>
<a asp-action="CreateComponent" class="btn btn-primary mx-2">Создать комплектующее</a>
<button type="button" class="btn btn-primary mx-2" data-bs-toggle="modal" data-bs-target="#exampleModal">Изменить комплектующее</button>
<button type="button" class="btn btn-primary mx-2">Удалить комплектующее</button>
<a asp-action="LinkBuilds" class="btn btn-primary mx-2">Привязка сборок</a>
</p>
<table class="table">
<thead>
<tr>
<th>
Название
</th>
<th>
Цена
</th>
<th>
Дата приобретения
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.ComponentName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Cost)
</td>
<td>
@Html.DisplayFor(modelItem => item.DateCreate)
</td>
</tr>
}
</tbody>
</table>
}
</div>
<form method="post" class="d-flex flex-column align-items-center">

View File

@ -10,7 +10,7 @@
<form method="post" class="d-flex flex-column align-items-center">
<div class="col-sm-3">
<label class="form-label">Название</label>
<input type="text" class="form-control" name="email">
<input type="text" class="form-control" name="name">
</div>
<div class="col-sm-3">
<label class="form-label">Стоимость</label>

View File

@ -1,4 +1,5 @@
@{
@using HardwareShopContracts.ViewModels
@{
ViewData["Title"] = "Создание товара";
Layout = "~/Views/Shared/_LayoutStorekeeper.cshtml";
}
@ -7,36 +8,35 @@
<h2 class="display-4">Создание товара</h2>
</div>
<form method="post" class="d-flex flex-column align-items-center">
<div class="d-flex flex-column align-items-center">
<div class="col-sm-3">
<label class="form-label">Название</label>
<input type="text" class="form-control" name="email">
<input type="text" class="form-control" name="name" id="name" required>
</div>
<div class="col-sm-3">
<label class="form-label">Цена</label>
<input type="number" step="0.01" class="form-control" name="price" readonly min="0.01">
<input type="number" step="0.01" class="form-control" name="price" id="price" readonly min="0.01" value="0" required>
</div>
<h1 class="display-6">Комплектующие</h1>
<div class="d-flex justify-content-center">
<button type="button" class="btn btn-primary mx-2 mt-3" data-bs-toggle="modal" data-bs-target="#exampleModal">Добавить</button>
<button type="button" class="btn btn-primary mx-2 mt-3" data-bs-toggle="modal" data-bs-target="#exampleModal">Изменить</button>
<button type="button" class="btn btn-primary mx-2 mt-3">Удалить</button>
</div>
<table class="table table-hover">
<thead>
<tr>
<th id="name" scope="col">Комплектующее</th>
<th id="count" scope="col">Количество</th>
<th id="sum" scope="col">Сумма</th>
<th scope="col">Комплектующее</th>
<th scope="col">Количество</th>
<th scope="col">Сумма</th>
</tr>
</thead>
<tbody>
<tbody id="result">
</tbody>
</table>
<div class="col-sm-2 d-flex justify-content-evenly align-items-baseline">
<button type="submit" class="btn btn-primary mt-3 px-4">Сохранить</button>
<button type="button" class="btn btn-primary mt-3 px-4" id="creategood">Сохранить</button>
</div>
</form>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
@ -47,14 +47,83 @@
</div>
<div class="modal-body">
<label class="form-label">Комплектующее</label>
<select class="form-control" name="component"></select>
<select id="component" name="component" class="form-control" asp-items="@(new SelectList(@ViewBag.Components, "Id", "ComponentName"))"></select>
<label class="form-label">Количество</label>
<input type="number" class="form-control" name="count" min="1">
<input type="number" class="form-control" name="count" id="count" min="1" value="1" required>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="submit" class="btn btn-primary">Сохранить</button>
<button type="button" class="btn btn-primary" data-bs-dismiss="modal" id="savecomponent">Сохранить</button>
</div>
</div>
</div>
</div>
@section Scripts
{
<script>
let list = [];
const name = document.getElementById("name");
const submitComponentBtn = document.getElementById("savecomponent");
const editBtn = document.getElementById("editcomponent");
const saveBtn = document.getElementById("creategood");
const countElem = document.getElementById("count");
const resultTable = document.getElementById("result");
const totalPrice = document.getElementById("price");
submitComponentBtn.addEventListener("click", () => {
console.log('try to add component')
var count = $('#count').val();
var component = $('#component').val();
$.ajax({
method: "GET",
url: `/Storekeeper/GetComponent`,
data: { Id: component },
success: function (result) {
let flag = false
if (list.length > 0) {
list.forEach((elem) => {
if (elem.component.id === parseInt(result.id)) {
console.log('component already added')
flag = true
}
})
}
if (!flag) list.push({ component: result, count: count })
reloadTable()
countElem.value = '1'
}
});
})
saveBtn.addEventListener("click", () => {
console.log('try to add good')
let components = []
let counts = []
list.forEach((x) => {
components.push(x.component);
counts.push(parseInt(x.count))
})
$.ajax(
{
url: `/Storekeeper/CreateGood`,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({"GoodName": name.value,"Price": parseFloat(totalPrice.value),
"GoodComponentsComponents": components, "GoodComponentsCounts": counts })
}
).done(() => window.location.href = '/Storekeeper/Goods')
})
function reloadTable() {
resultTable.innerHTML = ''
let price = 0;
list.forEach((elem) => {
resultTable.innerHTML += `<tr><td>${elem.component.componentName}</td><td>${elem.count}</td><td>${Math.round(elem.component.cost * elem.count * 100) / 100}</td></tr>`
price += elem.component.cost * elem.count
})
totalPrice.value = Math.round(price * 100) / 100
}
</script>
}

View File

@ -10,17 +10,45 @@
<form method="post" class="d-flex flex-column align-items-center">
<div class="col-sm-3">
<label class="form-label">Товар</label>
<select class="form-control" name="good"></select>
<select id="good" name="good" class="form-control" asp-items="@(new SelectList(@ViewBag.Goods, "Id", "GoodName"))"></select>
</div>
<div class="col-sm-3">
<label class="form-label">Количество</label>
<input type="number" class="form-control" name="count" min="1">
<input type="number" class="form-control" name="count" id="count" min="1" value="1" required>
</div>
<div class="col-sm-3">
<label class="form-label">Сумма</label>
<input type="number" step="0.01" class="form-control" name="sum" readonly>
<input type="number" step="0.01" class="form-control" name="sum" id="sum" value="0" readonly required>
</div>
<div class="col-sm-2 d-flex justify-content-evenly align-items-baseline">
<button type="submit" class="btn btn-primary mt-3 px-4">Сохранить</button>
</div>
</form>
@section Scripts
{
<script>
$('#good').on('change', function () {
check();
});
$('#count').on('input', function () {
check();
});
function check() {
var count = $('#count').val();
var good = $('#good').val();
if (count && good) {
$.ajax({
method: "POST",
url: "/Storekeeper/Calc",
data: { count: count, good: good },
success: function (result) {
$("#sum").val(result);
}
});
};
}
check()
</script>
}

View File

@ -1,4 +1,7 @@
@using HardwareShopContracts.ViewModels
@model List<GoodViewModel>
@{
ViewData["Title"] = "Товары";
Layout = "~/Views/Shared/_LayoutStorekeeper.cshtml";
@ -26,6 +29,17 @@
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.GoodName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
</tr>
}
</tbody>
</table>
</div>

View File

@ -1,4 +1,7 @@
@using HardwareShopContracts.ViewModels
@model List<OrderViewModel>
@{
ViewData["Title"] = "Заказы";
Layout = "~/Views/Shared/_LayoutStorekeeper.cshtml";
@ -11,13 +14,12 @@
<div class="text-center">
<p>
<a asp-action="CreateOrder" class="btn btn-primary mx-2">Создать заказ</a>
<button type="button" class="btn btn-primary mx-2">Удалить заказ</button>
<button type="button" class="btn btn-primary mx-2">Принят</button>
<button type="button" class="btn btn-primary mx-2">Выполняется</button>
<button type="button" class="btn btn-primary mx-2">Готов</button>
<button type="button" class="btn btn-primary mx-2">Выдан</button>
<button type="button" class="btn btn-primary mx-2" id="delete">Удалить заказ</button>
<button type="button" class="btn btn-primary mx-2" id="inwork">Выполняется</button>
<button type="button" class="btn btn-primary mx-2" id="ready">Готов</button>
<button type="button" class="btn btn-primary mx-2" id="done">Выдан</button>
</p>
<table class="table">
<table class="table" id="table">
<thead>
<tr>
<th>
@ -44,6 +46,115 @@
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.GoodName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Count)
</td>
<td>
@Html.DisplayFor(modelItem => item.Sum)
</td>
<td>
@Html.DisplayFor(modelItem => item.Status)
</td>
<td>
@Html.DisplayFor(modelItem => item.DateCreate)
</td>
<td>
@Html.DisplayFor(modelItem => item.DateImplement)
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
@section Styles
{
<style>
tr{cursor: pointer;}
.selected{background-color: #0d6efd; color: white;}
</style>
}
@section Scripts
{
<script>
// get selected row
// display selected row data in text input
var table = document.getElementById("table");
var remove = document.getElementById("delete");
var inwork = document.getElementById("inwork");
var ready = document.getElementById("ready");
var done = document.getElementById("done");
var order = 0;
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
// remove the background from the previous selected row
if(typeof index !== "undefined") {
table.rows[index].classList.toggle("selected");
}
// get the selected row index
index = this.rowIndex;
// add class selected to the row
this.classList.toggle("selected");
order = parseInt(this.cells[0].innerText);
remove.addEventListener("click", () => {
console.log('try to delete order')
$.ajax(
{
url: `/Storekeeper/DeleteOrder`,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ id = 0 })
}
)
})
inwork.addEventListener("click", () => {
console.log('try to delete order')
$.ajax(
{
url: `/Storekeeper/UpdateOrder`,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ id = order, status = 1 })
}
)
})
ready.addEventListener("click", () => {
console.log('try to delete order')
$.ajax(
{
url: `/Storekeeper/UpdateOrder`,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ id = order, status = 2 })
}
)
})
done.addEventListener("click", () => {
console.log('try to delete order')
$.ajax(
{
url: `/Storekeeper/UpdateOrder`,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ id = order, status = 3 })
}
)
})
};
}
</script>
}

View File

@ -7,5 +7,5 @@
},
"AllowedHosts": "*",
"IPAddress": "http://localhost:5205/"
"IPAddress": "http://localhost:5254/"
}

View File

@ -1,4 +1,5 @@
using HardwareShopDataModels.Models;
using HardwareShopContracts.ViewModels;
using HardwareShopDataModels.Models;
namespace HardwareShopContracts.BindingModels
{
@ -17,5 +18,17 @@ namespace HardwareShopContracts.BindingModels
get;
set;
} = new();
public List<ComponentViewModel> GoodComponentsComponents
{
get;
set;
} = new();
public List<int> GoodComponentsCounts
{
get;
set;
} = new();
}
}

View File

@ -0,0 +1,93 @@
using HardwareShopContracts.BindingModels;
using HardwareShopContracts.BuisnessLogicsContracts;
using HardwareShopContracts.SearchModels;
using HardwareShopContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace HardwareShopRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ComponentController : Controller
{
private readonly ILogger _logger;
private readonly IComponentLogic _component;
public ComponentController(ILogger<ComponentController> logger, IComponentLogic component)
{
_logger = logger;
_component = component;
}
[HttpGet]
public List<ComponentViewModel>? GetComponents(int userId)
{
try
{
return _component.ReadList(new() { UserId = userId });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка комплектующих");
throw;
}
}
[HttpGet]
public ComponentViewModel? GetComponent(int id)
{
try
{
return _component.ReadElement(new() { Id = id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения комплектующего");
throw;
}
}
[HttpPost]
public void CreateComponent(ComponentBindingModel model)
{
try
{
_component.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания комплектующего");
throw;
}
}
[HttpPost]
public void UpdateData(ComponentBindingModel model)
{
try
{
_component.Update(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка обновления данных комплектующего");
throw;
}
}
[HttpPost]
public void DeleteComponent(ComponentBindingModel model)
{
try
{
_component.Delete(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления комплектующего");
throw;
}
}
}
}

View File

@ -0,0 +1,98 @@
using HardwareShopContracts.BindingModels;
using HardwareShopContracts.BuisnessLogicsContracts;
using HardwareShopContracts.ViewModels;
using HardwareShopDataModels.Models;
using Microsoft.AspNetCore.Mvc;
namespace HardwareShopRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class GoodController : Controller
{
private readonly ILogger _logger;
private readonly IGoodLogic _good;
public GoodController(ILogger<GoodController> logger, IGoodLogic good)
{
_logger = logger;
_good = good;
}
[HttpGet]
public List<GoodViewModel>? GetGoods(int userId)
{
try
{
return _good.ReadList(new() { UserId = userId });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка товаров");
throw;
}
}
[HttpGet]
public GoodViewModel? GetGood(int id)
{
try
{
return _good.ReadElement(new() { Id = id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения товара");
throw;
}
}
[HttpPost]
public void CreateGood(GoodBindingModel model)
{
try
{
for (int i = 0; i < model.GoodComponentsCounts.Count; i++)
{
model.GoodComponents.Add(model.GoodComponentsComponents[i].Id,
(model.GoodComponentsComponents[i] as IComponentModel, model.GoodComponentsCounts[i]));
}
_good.Create(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания товара");
throw;
}
}
[HttpPost]
public void UpdateData(GoodBindingModel model)
{
try
{
_good.Update(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка обновления данных товара");
throw;
}
}
[HttpPost]
public void DeleteGood(GoodBindingModel model)
{
try
{
_good.Delete(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления товара");
throw;
}
}
}
}

View File

@ -0,0 +1,96 @@
using HardwareShopContracts.BindingModels;
using HardwareShopContracts.BuisnessLogicsContracts;
using HardwareShopContracts.ViewModels;
using HardwareShopDatabaseImplement.Models.Storekeeper;
using HardwareShopDataModels.Enums;
using HardwareShopDataModels.Models;
using Microsoft.AspNetCore.Mvc;
namespace HardwareShopRestApi.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class OrderController : Controller
{
private readonly ILogger _logger;
private readonly IOrderLogic _order;
public OrderController(ILogger<OrderController> logger, IOrderLogic order)
{
_logger = logger;
_order = order;
}
[HttpGet]
public List<OrderViewModel>? GetOrders(int userId)
{
try
{
return _order.ReadList(new() { UserId = userId });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка заказов");
throw;
}
}
[HttpPost]
public void CreateOrder(OrderBindingModel model)
{
try
{
_order.CreateOrder(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания заказа");
throw;
}
}
[HttpPost]
public void UpdateData(OrderBindingModel model)
{
try
{
switch (model.Status)
{
case OrderStatus.Неизвестен:
break;
case OrderStatus.Принят:
break;
case OrderStatus.Выполняется:
_order.TakeOrderInWork(model);
break;
case OrderStatus.Готов:
_order.FinishOrder(model);
break;
case OrderStatus.Выдан:
_order.DeliveryOrder(model);
break;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка обновления данных заказа");
throw;
}
}
[HttpPost]
public void DeleteOrder(OrderBindingModel model)
{
try
{
_order.Delete(model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления заказа");
throw;
}
}
}
}