Product create

This commit is contained in:
Илья Федотов 2024-05-28 12:50:24 +04:00
parent 1a5a000ef4
commit e78b0ffdbe
16 changed files with 263 additions and 88 deletions

View File

@ -100,8 +100,8 @@ namespace ElectronicsShopBusinessLogic.BusinessLogic
} }
_logger.LogInformation($"CostItem. ID:{model.ID}.EmployeeID:{model.EmployeeID}.Name:{model.Name}.Price:{model.Price}" + _logger.LogInformation($"CostItem. ID:{model.ID}.EmployeeID:{model.EmployeeID}.Name:{model.Name}.Price:{model.Price}" +
$"CostNum:{model.CostNum}"); $"CostNum:{model.CostNum}");
var element = _storage.GetElement(new CostItemSearchModel { ID = model.ID }); var element = _storage.GetElement(new CostItemSearchModel { Name = model.Name });
if (element != null && element.ID != model.EmployeeID) if (element != null && element.Name == model.Name)
{ {
throw new InvalidOperationException("Такая статья затрат уде есть"); throw new InvalidOperationException("Такая статья затрат уде есть");
} }

View File

@ -9,5 +9,6 @@ namespace ElectronicsShopContracts.SearchModels {
public int? ID { get; set; } public int? ID { get; set; }
public string? Name { get; set; } public string? Name { get; set; }
public int? CostNum { get; set; } public int? CostNum { get; set; }
public int? EmployeeID { get; set; }
} }
} }

View File

@ -21,5 +21,8 @@ namespace ElectronicsShopContracts.ViewModels {
[DisplayName("Номер счета")] [DisplayName("Номер счета")]
public int CostNum { get; set; } public int CostNum { get; set; }
[DisplayName("Сотрудник")]
public string EmployeeFIO { get; set; } = string.Empty;
} }
} }

View File

@ -20,5 +20,7 @@ namespace ElectronicsShopContracts.ViewModels
[DisplayName("Стоимость продукта")] [DisplayName("Стоимость продукта")]
public double Price { get; set; } public double Price { get; set; }
[DisplayName("Статья затрат")]
public string CostItemName { get; set; } = string.Empty;
} }
} }

View File

@ -3,9 +3,11 @@ using ElectronicsShopContracts.SearchModels;
using ElectronicsShopContracts.StorageContracts; using ElectronicsShopContracts.StorageContracts;
using ElectronicsShopContracts.ViewModels; using ElectronicsShopContracts.ViewModels;
using ElectronicsShopDataBaseImplement.Models; using ElectronicsShopDataBaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.Intrinsics.X86;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -21,7 +23,9 @@ namespace ElectronicsShopDataBaseImplement.Implements
using var context = new Database(); using var context = new Database();
context.CostItems.Add(newComponent); context.CostItems.Add(newComponent);
context.SaveChanges(); context.SaveChanges();
return newComponent.GetViewModel; return context.CostItems
.Include(x => x.Employee)
.FirstOrDefault(x => x.ID == newComponent.ID)?.GetViewModel;
} }
public CostItemViewModel? Update(CostItemBindingModel model) { public CostItemViewModel? Update(CostItemBindingModel model) {
@ -56,20 +60,22 @@ namespace ElectronicsShopDataBaseImplement.Implements
} }
using var context = new Database(); using var context = new Database();
return context.CostItems return context.CostItems
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) .Include(x => x.Employee)
&& x.Name == model.Name) || .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name == model.Name) ||
(model.ID.HasValue && x.ID == model.ID))?.GetViewModel; (model.ID.HasValue && x.ID == model.ID))?.GetViewModel;
} }
public List<CostItemViewModel> GetFillteredList(CostItemSearchModel model) public List<CostItemViewModel> GetFillteredList(CostItemSearchModel model)
{ {
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new Database(); using var context = new Database();
return context.CostItems.Where(x => x.Name.Contains(model.Name)) if (model.EmployeeID.HasValue) {
.Select(x => x.GetViewModel).ToList(); return context.CostItems
.Include(x => x.Employee)
.Where(x => x.EmployeeID == model.EmployeeID)
.Select(x => x.GetViewModel)
.ToList();
}
return new();
} }
public List<CostItemViewModel> GetFullList() public List<CostItemViewModel> GetFullList()

View File

@ -27,6 +27,8 @@ namespace ElectronicsShopDataBaseImplement.Models
[Required] [Required]
public int CostNum { get; set; } public int CostNum { get; set; }
public virtual Employee Employee { get; set; }
public static CostItem? Create(CostItemBindingModel? model) public static CostItem? Create(CostItemBindingModel? model)
{ {
if (model == null) if (model == null)
@ -61,6 +63,7 @@ namespace ElectronicsShopDataBaseImplement.Models
Name = Name, Name = Name,
Price = Price, Price = Price,
CostNum = CostNum, CostNum = CostNum,
EmployeeFIO = Employee.EmployeeFIO
}; };
} }
} }

View File

@ -12,8 +12,7 @@ using System.Threading.Tasks;
namespace ElectronicsShopDataBaseImplement.Models namespace ElectronicsShopDataBaseImplement.Models
{ {
public class Product : IProductModel public class Product : IProductModel {
{
public int ID { get; set; } public int ID { get; set; }
[Required] [Required]
@ -23,7 +22,9 @@ namespace ElectronicsShopDataBaseImplement.Models
public double Price { get; set; } public double Price { get; set; }
[ForeignKey("CostItemID")] [ForeignKey("CostItemID")]
public int CostItemID { get; set; } public int CostItemID { get; set; }
public virtual CostItem CostItem {get; set;}
public static Product? Create(ProductBindingModel? model) public static Product? Create(ProductBindingModel? model)
{ {
@ -55,6 +56,7 @@ namespace ElectronicsShopDataBaseImplement.Models
ProductName = ProductName, ProductName = ProductName,
Price = Price, Price = Price,
CostItemID = CostItemID, CostItemID = CostItemID,
CostItemName = CostItem.Name
}; };
} }
} }

View File

@ -12,6 +12,13 @@ namespace ElectronicsShopEmployeeApp.Controllers {
_logger = logger; _logger = logger;
} }
public IActionResult CostItem() {
if (APIEmployee.Employee == null) {
return Redirect("~/Home/Enter");
}
return View(APIEmployee.GetRequset<List<CostItemViewModel>>($"api/employee/getcostitems?_employeeid={APIEmployee.Employee.ID}"));
}
public IActionResult Index() { public IActionResult Index() {
if (APIEmployee.Employee == null) { if (APIEmployee.Employee == null) {
return Redirect("~/Home/Enter"); return Redirect("~/Home/Enter");
@ -102,39 +109,41 @@ namespace ElectronicsShopEmployeeApp.Controllers {
if (price <= 0) { if (price <= 0) {
throw new Exception("Ñóììà çàòðàò äîëæíà áûòü áîëüøå 0"); throw new Exception("Ñóììà çàòðàò äîëæíà áûòü áîëüøå 0");
} }
APIEmployee.PostRequest("api/main/createcostitem", new CostItemBindingModel { APIEmployee.PostRequest("api/employee/createcostitem", new CostItemBindingModel {
EmployeeID = APIEmployee.Employee.ID, EmployeeID = APIEmployee.Employee.ID,
Name = name, Name = name,
Price = price, Price = price,
CostNum = costNum CostNum = costNum
}); });
Response.Redirect("CostItem");
} }
[HttpGet] [HttpGet]
public IActionResult Create() { public IActionResult CreateProduct() {
ViewBag.Orders = APIEmployee.GetRequset<List<ProductViewModel>>("api/main/getproductlist"); ViewBag.CostItems = APIEmployee.GetRequset<List<CostItemViewModel>>($"api/employee/getcostitems?_employeeid={APIEmployee.Employee.ID}");
return View(); return View();
} }
[HttpPost] [HttpPost]
public void Create(int price, int costNum, string productName) { public void CreateProduct(string name, int costitem, double productprice) {
if (APIEmployee.Employee == null) { if (APIEmployee.Employee == null) {
throw new Exception("Òîëüêî äëÿ àâòîðèçîâàííûõ"); throw new Exception("Òîëüêî äëÿ àâòîðèçîâàííûõ");
} }
if (price <= 0) { if (productprice <= 0) {
throw new Exception("Ñòîèìîñòü òîâàðà äîëæíà áûòü áîëüøå 0"); throw new Exception("Ñòîèìîñòü òîâàðà äîëæíà áûòü áîëüøå 0");
} }
APIEmployee.PostRequest("api/main/createproduct", new ProductBindingModel { APIEmployee.PostRequest("api/employee/createproduct", new ProductBindingModel {
CostItemID = costNum, CostItemID = costitem,
ProductName = productName, ProductName = name,
Price = Calc(price, costNum) Price = Calc(costitem, productprice)
}); });
Response.Redirect("Index"); Response.Redirect("Index");
} }
private double Calc(int price, int costItem) { [HttpPost]
var _costItem = APIEmployee.GetRequset<CostItemViewModel>($"api/main/getcostitem?_employeeID={costItem}"); public double Calc(int costitem, double productprice) {
return price * (_costItem?.Price ?? 1); var _costItem = APIEmployee.GetRequset<CostItemViewModel>($"api/employee/getcostitem?_costitemid={costitem}");
return productprice + (_costItem?.Price ?? 500);
} }
} }
} }

View File

@ -0,0 +1,74 @@
@using ElectronicsShopContracts.ViewModels
@model List<CostItemViewModel>
@{
ViewData["Title"] = "CostItem";
}
<div class="text-center">
<h1 class="display-4">Статьи затрат</h1>
</div>
<div class="text-center">
@{
if (Model == null) {
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<p>
<a asp-action="CreateCostItem">Создать</a>
</p>
<p>
<a asp-action="UpdateCostItem">Изменить</a>
</p>
<p>
<a asp-action="CreateCostItem">Удалить</a>
</p>
// todo delete updates
<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.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmployeeFIO)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.CostNum)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -1,3 +0,0 @@
@{
ViewData["Title"] = "Create";
}

View File

@ -30,18 +30,4 @@
<input type="submit" value="Создать" class="btn btn-outline-primary"/> <input type="submit" value="Создать" class="btn btn-outline-primary"/>
</div> </div>
</div> </div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
</form> </form>
<script>
$('#price').on('price', function () {
check();
}
$('#costnum').on('costnum', function () {
check();
}
function check() {
var price = $('#price').val();
var costnum = $('#costnum').val();
}
</script>

View File

@ -0,0 +1,64 @@
@{
ViewData["Title"] = "CreateProduct";
}
<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 id="name" type="text" name="name" />
</div>
</div>
<div class="row">
<div class="col-4">Статья затрат:</div>
<div class="col-8">
<select id="costitem" class="form-control" asp-items="@(new SelectList(ViewBag.CostItems, "ID", "Name"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Стоимость товара:</div>
<div class="col-8">
<input id="productprice" type="text" name="productprice" />
</div>
</div>
<div class="row">
<div class="col-4">С учетом затрат:</div>
<div class="col-8">
<input id="price" type="text" name="price" readonly />
</div>
</div>
<div class="row">
<div class="col-4"></div>
<div class="col-8">
<input type="submit" value="Создать" class="btn btn-outline-primary" />
</div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
</form>
<script>
$('#costitem').on('change', function () {
check();
});
$('#productprice'.on('change', function () {
check():
});
function check() {
var costitem = $('#costitem').val();
var productprice = $('#productprice').val();
if (costitem && productprice) {
$.ajax({
method: "POST",
url: "/Home/Calc",
data: { costitem: costitem, productprice: productprice },
success: function (result) {
$("#price").val(result);
}
});
};
}
</script>

View File

@ -18,7 +18,7 @@
return; return;
} }
<p> <p>
<a asp-action="Create">Создать продукта</a> <a asp-action="CreateProduct">Создать Товар</a>
</p> </p>
<table class="table"> <table class="table">
<thead> <thead>
@ -27,10 +27,10 @@
Номер продукта Номер продукта
</th> </th>
<th> <th>
Статья затрат Название продукта
</th> </th>
<th> <th>
Название продукта Статья затрат
</th> </th>
<th> <th>
Сумма Сумма
@ -44,10 +44,10 @@
@Html.DisplayFor(modelItem => item.ID) @Html.DisplayFor(modelItem => item.ID)
</th> </th>
<th> <th>
@Html.DisplayFor(modelItem => item.CostItemID) @Html.DisplayFor(modelItem => item.ProductName)
</th> </th>
<th> <th>
@Html.DisplayFor(modelItem => item.ProductName) @Html.DisplayFor(modelItem => item.CostItemName)
</th> </th>
<th> <th>
@Html.DisplayFor(modelItem => item.Price) @Html.DisplayFor(modelItem => item.Price)

View File

@ -12,7 +12,7 @@
<header> <header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container-fluid"> <div class="container-fluid">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">ElectronicsShopEmployeeApp</a> <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Магазин электроники (Сотрудник)</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent" <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation"> aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span> <span class="navbar-toggler-icon"></span>
@ -32,7 +32,7 @@
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Register">Регистрация</a> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Register">Регистрация</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="CreateCostItem">Создание статьи затрат</a> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="CostItem">Статьи затрат</a>
</li> </li>
</ul> </ul>
</div> </div>

View File

@ -2,6 +2,7 @@
using ElectronicsShopContracts.BusinessLogicContracts; using ElectronicsShopContracts.BusinessLogicContracts;
using ElectronicsShopContracts.SearchModels; using ElectronicsShopContracts.SearchModels;
using ElectronicsShopContracts.ViewModels; using ElectronicsShopContracts.ViewModels;
using ElectronicsShopDataBaseImplement.Models;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace ElectronicsShopRestAPI.Controllers { namespace ElectronicsShopRestAPI.Controllers {
@ -13,10 +14,14 @@ namespace ElectronicsShopRestAPI.Controllers {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IEmployeeLogic _logic; private readonly IEmployeeLogic _logic;
private readonly ICostItemLogic _costItem;
private readonly IProductLogic _productLogic;
public EmployeeController(ILogger<EmployeeController> logger, IEmployeeLogic logic) { public EmployeeController(ILogger<EmployeeController> logger, IEmployeeLogic logic, ICostItemLogic costItem, IProductLogic productLogic) {
_logger = logger; _logger = logger;
_logic = logic; _logic = logic;
_costItem = costItem;
_productLogic = productLogic;
} }
[HttpGet] [HttpGet]
@ -54,5 +59,49 @@ namespace ElectronicsShopRestAPI.Controllers {
throw; throw;
} }
} }
[HttpPost]
public void CreateCostItem(CostItemBindingModel model) {
try {
_costItem.Create(model);
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка создания заказа");
throw;
}
}
[HttpGet]
public List<CostItemViewModel>? GetCostItems(int _employeeID) {
try {
return _costItem.ReadList(new CostItemSearchModel { EmployeeID = _employeeID });
}
catch (Exception ex) {
_logger.LogError(ex, $"Ошибка получения данных списка заказов сотрудника ID ={_employeeID}");
throw;
}
}
[HttpGet]
public CostItemViewModel? GetCostItem(int _costItemID) {
try {
return _costItem.ReadElement(new CostItemSearchModel { ID = _costItemID });
}
catch (Exception ex) {
_logger.LogError(ex, $"Ошибка получения статьи затрат ID={_costItemID}");
throw;
}
}
[HttpPost]
public void CreateProduct(ProductBindingModel model) {
try {
_productLogic.Create(model);
}
catch(Exception ex) {
_logger.LogError(ex, "Ошибка создания заказа");
throw;
}
}
} }
} }

View File

@ -14,31 +14,36 @@ namespace ElectronicsShopRestAPI.Controllers {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IProductLogic _product; private readonly IProductLogic _product;
private readonly IOrderLogic _order; private readonly IOrderLogic _order;
private readonly ICostItemLogic _costItem;
public MainController(ILogger<MainController> logger, IProductLogic product, public MainController(ILogger<MainController> logger, IProductLogic product,
IOrderLogic orderLogic, ICostItemLogic costItemLogic) { IOrderLogic orderLogic) {
_logger = logger; _logger = logger;
_product = product; _product = product;
_order = orderLogic; _order = orderLogic;
_costItem = costItemLogic;
} }
[HttpGet]
public List<ProductViewModel>? GetProductList() {
//tdoo
return null;
}
[HttpGet] [HttpGet]
public ProductViewModel? GetProduct(int ProductID) { public ProductViewModel? GetProduct(int ProductID) {
return null; return null;
} }
[HttpGet]
public List<ProductViewModel>? GetProducts() {
try {
return _product.ReadList(null);
}
catch (Exception ex) {
_logger.LogError(ex, $"Ошибка получения данных");
throw;
}
}
// клиент должен получать свои заказы // клиент должен получать свои заказы
// сотрудник должен получать все заказы // сотрудник должен получать все заказы
[HttpGet] [HttpGet]
public List<OrderViewModel>? GetOrders(int _clientID) { public List<OrderViewModel>? GetOrders(int _clientID) {
try try
{ {
@ -54,37 +59,11 @@ namespace ElectronicsShopRestAPI.Controllers {
} }
} }
[HttpGet]
public List<ProductViewModel>? GetProducts() {
try {
return _product.ReadList(null);
}
catch (Exception ex) {
_logger.LogError(ex, $"Ошибка получения данных");
throw;
}
}
[HttpPost] [HttpPost]
public void CreateOrder(OrderBindingModel model) { public void CreateOrder(OrderBindingModel model) {
return; return;
} }
[HttpPost]
public void CreateProduct(OrderBindingModel model) {
return;
}
[HttpPost]
public void CreateCostItem(CostItemBindingModel model) {
try {
_costItem.Create(model);
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка создания заказа");
throw;
}
}
//Мейби нужны будут удаления, обновления, выбор конкретного заказа или продукта. Короче потом... //Мейби нужны будут удаления, обновления, выбор конкретного заказа или продукта. Короче потом...
//А также для статей затрат. //А также для статей затрат.
} }