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}" +
$"CostNum:{model.CostNum}");
var element = _storage.GetElement(new CostItemSearchModel { ID = model.ID });
if (element != null && element.ID != model.EmployeeID)
var element = _storage.GetElement(new CostItemSearchModel { Name = model.Name });
if (element != null && element.Name == model.Name)
{
throw new InvalidOperationException("Такая статья затрат уде есть");
}

View File

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

View File

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

View File

@ -20,5 +20,7 @@ namespace ElectronicsShopContracts.ViewModels
[DisplayName("Стоимость продукта")]
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.ViewModels;
using ElectronicsShopDataBaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Intrinsics.X86;
using System.Text;
using System.Threading.Tasks;
@ -21,7 +23,9 @@ namespace ElectronicsShopDataBaseImplement.Implements
using var context = new Database();
context.CostItems.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
return context.CostItems
.Include(x => x.Employee)
.FirstOrDefault(x => x.ID == newComponent.ID)?.GetViewModel;
}
public CostItemViewModel? Update(CostItemBindingModel model) {
@ -56,20 +60,22 @@ namespace ElectronicsShopDataBaseImplement.Implements
}
using var context = new Database();
return context.CostItems
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name)
&& x.Name == model.Name) ||
.Include(x => x.Employee)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name == model.Name) ||
(model.ID.HasValue && x.ID == model.ID))?.GetViewModel;
}
public List<CostItemViewModel> GetFillteredList(CostItemSearchModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new Database();
return context.CostItems.Where(x => x.Name.Contains(model.Name))
.Select(x => x.GetViewModel).ToList();
if (model.EmployeeID.HasValue) {
return context.CostItems
.Include(x => x.Employee)
.Where(x => x.EmployeeID == model.EmployeeID)
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
public List<CostItemViewModel> GetFullList()

View File

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

View File

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

View File

@ -12,6 +12,13 @@ namespace ElectronicsShopEmployeeApp.Controllers {
_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() {
if (APIEmployee.Employee == null) {
return Redirect("~/Home/Enter");
@ -102,39 +109,41 @@ namespace ElectronicsShopEmployeeApp.Controllers {
if (price <= 0) {
throw new Exception("Ñóììà çàòðàò äîëæíà áûòü áîëüøå 0");
}
APIEmployee.PostRequest("api/main/createcostitem", new CostItemBindingModel {
APIEmployee.PostRequest("api/employee/createcostitem", new CostItemBindingModel {
EmployeeID = APIEmployee.Employee.ID,
Name = name,
Price = price,
CostNum = costNum
});
Response.Redirect("CostItem");
}
[HttpGet]
public IActionResult Create() {
ViewBag.Orders = APIEmployee.GetRequset<List<ProductViewModel>>("api/main/getproductlist");
public IActionResult CreateProduct() {
ViewBag.CostItems = APIEmployee.GetRequset<List<CostItemViewModel>>($"api/employee/getcostitems?_employeeid={APIEmployee.Employee.ID}");
return View();
}
[HttpPost]
public void Create(int price, int costNum, string productName) {
public void CreateProduct(string name, int costitem, double productprice) {
if (APIEmployee.Employee == null) {
throw new Exception("Òîëüêî äëÿ àâòîðèçîâàííûõ");
}
if (price <= 0) {
if (productprice <= 0) {
throw new Exception("Ñòîèìîñòü òîâàðà äîëæíà áûòü áîëüøå 0");
}
APIEmployee.PostRequest("api/main/createproduct", new ProductBindingModel {
CostItemID = costNum,
ProductName = productName,
Price = Calc(price, costNum)
APIEmployee.PostRequest("api/employee/createproduct", new ProductBindingModel {
CostItemID = costitem,
ProductName = name,
Price = Calc(costitem, productprice)
});
Response.Redirect("Index");
}
private double Calc(int price, int costItem) {
var _costItem = APIEmployee.GetRequset<CostItemViewModel>($"api/main/getcostitem?_employeeID={costItem}");
return price * (_costItem?.Price ?? 1);
[HttpPost]
public double Calc(int costitem, double productprice) {
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"/>
</div>
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
</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;
}
<p>
<a asp-action="Create">Создать продукта</a>
<a asp-action="CreateProduct">Создать Товар</a>
</p>
<table class="table">
<thead>
@ -27,10 +27,10 @@
Номер продукта
</th>
<th>
Статья затрат
Название продукта
</th>
<th>
Название продукта
Статья затрат
</th>
<th>
Сумма
@ -44,10 +44,10 @@
@Html.DisplayFor(modelItem => item.ID)
</th>
<th>
@Html.DisplayFor(modelItem => item.CostItemID)
@Html.DisplayFor(modelItem => item.ProductName)
</th>
<th>
@Html.DisplayFor(modelItem => item.ProductName)
@Html.DisplayFor(modelItem => item.CostItemName)
</th>
<th>
@Html.DisplayFor(modelItem => item.Price)

View File

@ -12,7 +12,7 @@
<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">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"
aria-expanded="false" aria-label="Toggle navigation">
<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>
</li>
<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>
</ul>
</div>

View File

@ -2,6 +2,7 @@
using ElectronicsShopContracts.BusinessLogicContracts;
using ElectronicsShopContracts.SearchModels;
using ElectronicsShopContracts.ViewModels;
using ElectronicsShopDataBaseImplement.Models;
using Microsoft.AspNetCore.Mvc;
namespace ElectronicsShopRestAPI.Controllers {
@ -13,10 +14,14 @@ namespace ElectronicsShopRestAPI.Controllers {
private readonly ILogger _logger;
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;
_logic = logic;
_costItem = costItem;
_productLogic = productLogic;
}
[HttpGet]
@ -54,5 +59,49 @@ namespace ElectronicsShopRestAPI.Controllers {
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,27 +14,32 @@ namespace ElectronicsShopRestAPI.Controllers {
private readonly ILogger _logger;
private readonly IProductLogic _product;
private readonly IOrderLogic _order;
private readonly ICostItemLogic _costItem;
public MainController(ILogger<MainController> logger, IProductLogic product,
IOrderLogic orderLogic, ICostItemLogic costItemLogic) {
IOrderLogic orderLogic) {
_logger = logger;
_product = product;
_order = orderLogic;
_costItem = costItemLogic;
}
[HttpGet]
public List<ProductViewModel>? GetProductList() {
//tdoo
return null;
}
[HttpGet]
public ProductViewModel? GetProduct(int ProductID) {
return null;
}
[HttpGet]
public List<ProductViewModel>? GetProducts() {
try {
return _product.ReadList(null);
}
catch (Exception ex) {
_logger.LogError(ex, $"Ошибка получения данных");
throw;
}
}
// клиент должен получать свои заказы
// сотрудник должен получать все заказы
@ -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]
public void CreateOrder(OrderBindingModel model) {
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;
}
}
//Мейби нужны будут удаления, обновления, выбор конкретного заказа или продукта. Короче потом...
//А также для статей затрат.
}