CRUD для покупок готов

This commit is contained in:
Николай 2023-05-17 19:36:40 +04:00
parent f3d161527a
commit 64bdab2d57
6 changed files with 378 additions and 12 deletions

View File

@ -10,8 +10,8 @@ namespace HardwareShopDatabaseImplement
{ {
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{ {
optionsBuilder.UseNpgsql("Host=localhost;Port=5433;Database=Computer_Hardware_Store;Username=user;Password=12345"); optionsBuilder.UseNpgsql("Host=localhost;Port=5432;Database=Computer_Hardware_Store4;Username=postgres;Password=1234");
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
} }
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)

View File

@ -25,6 +25,30 @@ namespace HardwareShopRestApi.Controllers
_purchaseLogic = purchaseLogic; _purchaseLogic = purchaseLogic;
} }
[HttpGet]
public Tuple<PurchaseViewModel, List<Tuple<GoodViewModel, int>>>? GetPurchaseUpdate(int purchaseId)
{
try
{
var purchase = _purchaseLogic.ReadElement(new() { Id = purchaseId });
if (purchase == null)
return null;
var tuple = Tuple.Create(purchase,
purchase.PurchaseGoods.Select(x => Tuple.Create(new GoodViewModel
{
Id = x.Value.Item1.Id,
GoodName = x.Value.Item1.GoodName,
Price = x.Value.Item1.Price
}, x.Value.Item2)).ToList());
return tuple;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения покупки");
throw;
}
}
[HttpGet] [HttpGet]
public List<PurchaseViewModel>? GetPurchases(int userId) public List<PurchaseViewModel>? GetPurchases(int userId)
{ {
@ -72,7 +96,7 @@ namespace HardwareShopRestApi.Controllers
} }
[HttpPost] [HttpPost]
public void UpdatePurchase(PurchaseBindingModel model) public void UpdateStatusPurchase(PurchaseBindingModel model)
{ {
try try
{ {
@ -94,6 +118,12 @@ namespace HardwareShopRestApi.Controllers
{ {
try try
{ {
for (int i = 0; i < model.PurchaseGoodsCounts.Count; i++)
{
model.PurchaseGoods.Add(model.ListPurchaseGoods[i].Id, (model.ListPurchaseGoods[i] as IGoodModel, model.PurchaseGoodsCounts[i]));
}
model.PurchaseBuilds = _purchaseLogic.ReadElement(new() { Id = model.Id }).PurchaseBuilds;
model.Sum = Calc(model);
_purchaseLogic.Update(model); _purchaseLogic.Update(model);
} }
catch (Exception ex) catch (Exception ex)
@ -103,6 +133,20 @@ namespace HardwareShopRestApi.Controllers
} }
} }
private double Calc(PurchaseBindingModel purchase)
{
double price = 0;
foreach (var elem in purchase.PurchaseBuilds)
{
price += ((elem.Value.Item1?.Price ?? 0) * elem.Value.Item2);
}
foreach (var elem in purchase.PurchaseGoods)
{
price += ((elem.Value.Item1?.Price ?? 0) * elem.Value.Item2);
}
return Math.Round(price * 1.1, 2);
}
[HttpPost] [HttpPost]
public void DeletePurchase(PurchaseBindingModel model) public void DeletePurchase(PurchaseBindingModel model)
{ {

View File

@ -352,7 +352,7 @@ namespace HardwareShopWorkerApp.Controllers
} }
[HttpPost] [HttpPost]
public void UpdatePurchase(int id, int status) public void UpdateStatusPurchase(int id, int status)
{ {
if (APIClient.User == null) if (APIClient.User == null)
{ {
@ -366,13 +366,65 @@ namespace HardwareShopWorkerApp.Controllers
{ {
throw new Exception("Некорректный статус"); throw new Exception("Некорректный статус");
} }
APIClient.PostRequest("api/purchase/updatepurchase", new PurchaseBindingModel APIClient.PostRequest("api/purchase/UpdateStatusPurchase", new PurchaseBindingModel
{ {
Id = id, Id = id,
PurchaseStatus = (PurchaseStatus)status PurchaseStatus = (PurchaseStatus)status
}); });
} }
[HttpPost]
public void DeletePurchase(int purchaseId)
{
if (APIClient.User == null)
{
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
}
if (purchaseId <= 0)
{
throw new Exception("Некорректный идентификатор");
}
var purchase = APIClient.GetRequest<PurchaseViewModel>($"api/purchase/getpurchase?purchaseId={purchaseId}");
APIClient.PostRequest("api/purchase/DeletePurchase", new PurchaseBindingModel
{
Id = purchaseId,
PurchaseStatus = purchase.PurchaseStatus
});
}
[HttpGet]
public IActionResult UpdatePurchase(int purchaseId)
{
if (APIClient.User == null)
{
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
}
ViewBag.Goods = APIClient.GetRequest<List<GoodViewModel>>($"api/good/GetAllGoods");
return View(purchaseId);
}
[HttpPost]
public void UpdatePurchase([FromBody] PurchaseBindingModel purchaseModel)
{
if (APIClient.User == null)
{
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
}
purchaseModel.UserId = APIClient.User.Id;
APIClient.PostRequest("api/purchase/update", purchaseModel);
}
[HttpGet]
public Tuple<PurchaseViewModel, List<Tuple<GoodViewModel?, int>>>? GetPurchaseUpdate(int purchaseId)
{
if (APIClient.User == null)
{
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
}
var result = APIClient.GetRequest<Tuple<PurchaseViewModel, List<Tuple<GoodViewModel?, int>>>?>($"api/purchase/getpurchaseupdate?purchaseId={purchaseId}");
return result;
}
[HttpGet] [HttpGet]
public IActionResult WorkerReport() public IActionResult WorkerReport()
{ {

View File

@ -24,6 +24,7 @@
<th scope="col">Товар</th> <th scope="col">Товар</th>
<th scope="col">Количество</th> <th scope="col">Количество</th>
<th scope="col">Цена</th> <th scope="col">Цена</th>
<th scope="col">Действие</th>
</tr> </tr>
</thead> </thead>
<tbody id="result"> <tbody id="result">
@ -93,12 +94,21 @@
saveBtn.addEventListener("click", () => { saveBtn.addEventListener("click", () => {
console.log('try to add purchase') console.log('try to add purchase')
console.log(list)
if (list.length == 0) {
alert('failed add good. components are empty')
return
}
let goods = [] let goods = []
let counts = [] let counts = []
list.forEach((x) => { list.forEach((x) => {
goods.push(x.good); goods.push(x.good);
counts.push(parseInt(x.count)) counts.push(parseInt(x.count))
}) })
console.log(JSON.stringify({
"Sum": parseFloat(totalSum.value),
"ListPurchaseGoods": goods, "PurchaseGoodsCounts": counts
}));
$.ajax( $.ajax(
{ {
url: `/Home/CreatePurchase`, url: `/Home/CreatePurchase`,
@ -115,12 +125,25 @@
function reloadTable() { function reloadTable() {
resultTable.innerHTML = '' resultTable.innerHTML = ''
let price = 0; let price = 0;
let count = 0;
list.forEach((elem) => { list.forEach((elem) => {
resultTable.innerHTML += `<tr><td>${elem.good.goodName}</td><td>${elem.count}</td><td>${Math.round(elem.good.price * elem.count * 100) / 100}</td><td> \
<div> \
<button onclick="deleteGood(${count})" type="button" class="btn btn-danger"> \
<i class="fa fa-trash" aria-hidden="true"></i> \
</button> \
</div><td/></tr>`
count++;
console.log(elem); console.log(elem);
resultTable.innerHTML += `<tr><td>${elem.good.goodName}</td><td>${elem.count}</td><td>${Math.round(elem.good.price * elem.count * 100) / 100}</td></tr>`
price += elem.good.price * elem.count price += elem.good.price * elem.count
}) })
totalSum.value = Math.round(price * 100) / 100 totalSum.value = Math.round(price * 110) / 100
console.log(totalSum.value);
}
function deleteGood(id) {
list = list.filter(value => value.good.goodName != resultTable.rows[id].cells[0].innerText)
reloadTable()
} }
</script> </script>

View File

@ -17,8 +17,9 @@
<h2 class="display-4">Покупки</h2> <h2 class="display-4">Покупки</h2>
<p> <p>
<a asp-controller="Home" asp-action="CreatePurchase" class="btn btn-primary mx-2">Добавить</a> <a asp-controller="Home" asp-action="CreatePurchase" class="btn btn-primary mx-2">Добавить</a>
<button type="button" class="btn btn-primary mx-2" id="delete">Удалить заказ</button> <button type="button" class="btn btn-primary mx-2" id="delete">Удалить покупку</button>
<button type="button" class="btn btn-primary mx-2" id="done">Выдан</button> <button type="button" class="btn btn-primary mx-2" id="done">Выдан</button>
<button type="button" class="btn btn-primary mx-2" id="update">Обновить</button>
</p> </p>
</div> </div>
<div class="text-center"> <div class="text-center">
@ -117,20 +118,24 @@
{ {
url: `/Home/DeletePurchase`, url: `/Home/DeletePurchase`,
type: 'POST', type: 'POST',
data: { id: purchase } data: { purchaseId: purchase }
} }
).done(() => window.location.href = '/Home/Purchase') ).done(() => window.location.href = '/Home/Purchases')
}) })
done.addEventListener("click", () => { done.addEventListener("click", () => {
console.log('try to delete purchase') console.log('try to delete purchase')
$.ajax( $.ajax(
{ {
url: `/Home/UpdatePurchase`, url: `/Home/UpdateStatusPurchase`,
type: 'POST', type: 'POST',
data: { id: purchase, status: 1 } data: { id: purchase, status: 1 }
} }
).done(() => window.location.href = '/Home/Purchases') ).done(() => window.location.href = '/Home/Purchases')
}) })
update.addEventListener("click", () => {
console.log('try to update purchase')
window.location.href = '/Home/UpdatePurchase?purchaseId=' + purchase
})
}; };
} }

View File

@ -0,0 +1,242 @@
@using HardwareShopContracts.ViewModels
@model int
@{
ViewData["Title"] = "UpdatePurchase";
Layout = "~/Views/Shared/_LayoutWorker.cshtml";
}
<div class="text-center">
<h2 class="display-4">Редактирование покупки</h2>
</div>
<div class="d-flex flex-column align-items-center">
<div class="col-sm-3">
<label class="form-label">Цена</label>
<input type="number" step="0.01" class="form-control" name="sum" id="sum" 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">Удалить</button>
</div>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Товар</th>
<th scope="col">Количество</th>
<th scope="col">Цена</th>
<th scope="col">Действие</th>
</tr>
</thead>
<tbody id="result">
</tbody>
</table>
<div class="col-sm-2 d-flex justify-content-evenly align-items-baseline">
<button type="button" class="btn btn-primary mt-3 px-4" id="createpurchase">Сохранить</button>
</div>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Товар</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
</div>
<div class="modal-body">
<label class="form-label">Товар</label>
<select id="good" name="good" class="form-control" asp-items="@(new SelectList(@ViewBag.Goods, "Id", "GoodName"))"></select>
<label class="form-label">Количество</label>
<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="button" class="btn btn-primary" data-bs-dismiss="modal" id="savegood">Сохранить</button>
</div>
</div>
</div>
</div>
@section Scripts
{
<script>
const purchaseId = @Model
let list = [];
let status;
const submitGoodBtn = document.getElementById("savegood");
//const editBtn = document.getElementById("editcomponent");
const saveBtn = document.getElementById("createpurchase");
const countElem = document.getElementById("count");
const resultTable = document.getElementById("result");
submitGoodBtn.addEventListener("click", () => {
console.log('try to add good')
var count = $('#count').val();
var good = $('#good').val();
$.ajax({
method: "GET",
url: `/Home/GetGood`,
data: { Id: good },
success: function (result) {
let flag = false
if (list.length > 0) {
list.forEach((elem) => {
if (elem.good.id === parseInt(result.id)) {
console.log('good already added')
flag = true
}
})
}
if (!flag) list.push({ good: result, count: count })
reloadTable()
countElem.value = '1'
}
});
})
saveBtn.addEventListener("click", () => {
console.log('try to add purchase')
console.log(list)
if (list.length == 0) {
alert('failed add good. components are empty')
return
}
let goods = []
let counts = []
list.forEach((x) => {
goods.push(x.good);
counts.push(parseInt(x.count))
})
console.log(JSON.stringify({
"ListPurchaseGoods": goods, "PurchaseGoodsCounts": counts
}));
$.ajax(
{
url: `/Home/UpdatePurchase`,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
"Id": purchaseId, "ListPurchaseGoods": goods, "PurchaseGoodsCounts": counts, "PurchaseStatus": status
})
}
).done(() => window.location.href = '/Home/Purchases')
.fail(function (xhr, textStatus, errorThrown) {
alert(xhr.responseText);
})
})
function reloadTable() {
resultTable.innerHTML = ''
let price = 0;
let count = 0;
list.forEach((elem) => {
resultTable.innerHTML += `<tr><td>${elem.good.goodName}</td><td>${elem.count}</td><td>${Math.round(elem.good.price * elem.count * 100) / 100}</td><td> \
<div> \
<button onclick="deleteGood(${count})" type="button" class="btn btn-danger"> \
<i class="fa fa-trash" aria-hidden="true"></i> \
</button> \
</div><td/></tr>`
count++;
console.log(elem);
})
}
function deleteGood(id) {
list = list.filter(value => value.good.goodName != resultTable.rows[id].cells[0].innerText)
reloadTable()
}
function getPurchase() {
if (purchaseId) {
$.ajax({
method: "GET",
url: "/Home/GetPurchaseUpdate",
data: { purchaseId: purchaseId },
success: function (result) {
if (result) {
console.log(result)
status = result.item1.purchaseStatus
result.item2.forEach(elem => {
list.push({ good: elem.item1, count: elem.item2 })
})
reloadTable()
}
else
alert("Ошибка получения товара")
}
})
.fail(function (xhr, textStatus, errorThrown) {
alert(xhr.responseText);
})
};
}
getPurchase();
</script>
}
@*<form class="d-flex justify-content-evenly">
<div class=" col-sm-8">
<div class="text-center">
<h2 class="display-4">Товары</h2>
</div>
<div class="text-center" name="id">
<table class="table">
<thead>
<tr>
<th>
Номер
</th>
<th>
Название товара
</th>
<th>
Цена
</th>
<th>
Количество
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<div class="text-center d-flex flex-column mt-5">
<button type="button" class="btn btn-primary btn-lg mb-5" data-bs-toggle="modal" data-bs-target="#exampleModal">Добавить</button>
<button type="button" class="btn btn-primary btn-lg mb-5" data-bs-toggle="modal" data-bs-target="#exampleModal">Изменить</button>
<button type="button" class="btn btn-primary btn-lg mb-5">Удалить</button>
<button type="button" class="btn btn-primary btn-lg mb-5">Обновить</button>
<button type="button" class="btn btn-primary btn-lg mb-5">Сохранить</button>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Товар</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
</div>
<div class="modal-body">
<div>
<label class="form-label">Товар</label>
<select class="form-select">
<option value="1">Товар 1</option>
<option value="2">Товар 2</option>
</select>
</div>
<div>
<label class="form-label">Количество</label>
<input type="number" class="form-control">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="button" class="btn btn-primary">Сохранить</button>
</div>
</div>
</div>
</div>
</form>
*@