using DocumentFormat.OpenXml.Spreadsheet; using ElectronicsShopContracts.BindingModels; using ElectronicsShopContracts.SearchModels; using ElectronicsShopContracts.ViewModels; using ElectronicsShopEmployeeApp.Models; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using System.Diagnostics; namespace ElectronicsShopEmployeeApp.Controllers { public class HomeController : Controller { private readonly ILogger _logger; public HomeController(ILogger logger) { _logger = logger; } public IActionResult CostItem() { if (APIEmployee.Employee == null) { return Redirect("~/Home/Enter"); } return View(APIEmployee.GetRequset>($"api/employee/getcostitems?_employeeid={APIEmployee.Employee.ID}")); } public IActionResult Index() { if (APIEmployee.Employee == null) { return Redirect("~/Home/Enter"); } return View(APIEmployee.GetRequset>($"api/main/getproducts")); } [HttpGet] public IActionResult Privacy() { 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, Email = login, Password = password, }); APIEmployee.Employee.EmployeeFIO = fio; APIEmployee.Employee.Email = 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 }); } [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.GetRequset($"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, Email = login, Password = password }); Response.Redirect("Enter"); return; } [HttpGet] public IActionResult CreateCostItem() { return View(); } [HttpPost] public void CreateCostItem(string name, double price, int costNum) { if (APIEmployee.Employee == null) { throw new Exception("Только для авторизованых"); } if (price <= 0) { throw new Exception("Сумма затрат должна быть больше 0"); } APIEmployee.PostRequest("api/employee/createcostitem", new CostItemBindingModel { EmployeeID = APIEmployee.Employee.ID, Name = name, Price = price, CostNum = costNum }); Response.Redirect("CostItem"); } [HttpGet] public IActionResult EditCostItem(int id) { var _costitem = APIEmployee.GetRequset($"api/employee/getcostitem?_costitemid={id}"); if (_costitem == null) { return Redirect("/Home/CostItem"); } var obj = new CostItemViewModel { ID = _costitem.ID, Name = _costitem.Name, Price = _costitem.Price, CostNum = _costitem.CostNum, }; return View(obj); } [HttpPost] public void EditCostItem(string name, double price, int costNum, int _ID) { if (APIEmployee.Employee == null) { throw new Exception("Только для авторизованых"); } if (price <= 0) { throw new Exception("Сумма затрат должна быть больше 0"); } var _costitem = APIEmployee.GetRequset($"api/employee/getcostitem?_costitemid={_ID}"); if (_costitem == null) { throw new Exception("Ошибка получения данных"); } double oldPrice = _costitem.Price; APIEmployee.PostRequest("api/employee/editcostitem", new CostItemBindingModel { ID = _ID, Name = name, Price = price, CostNum = costNum, EmployeeID = APIEmployee.Employee.ID }); // перебираем список товаров по costitemid // Вычитаем из цены старую стоимость статьи затрат // перерасчитываем // отправляем запрос на изменение var productList = APIEmployee.GetRequset>($"api/main/getproducts?_costitemid={_ID}"); if (productList != null) { foreach (var item in productList) { APIEmployee.PostRequest("api/employee/editproduct", new ProductBindingModel { ID = item.ID, CostItemID = item.CostItemID, ProductName = item.ProductName, Price = Calc(item.CostItemID, item.Price - oldPrice) }); } } Response.Redirect("CostItem"); } [HttpGet] public IActionResult CreateProduct() { ViewBag.CostItems = APIEmployee.GetRequset>($"api/employee/getcostitems?_employeeid={APIEmployee.Employee?.ID}"); return View(); } [HttpPost] public void CreateProduct(string name, int costitem, double productprice, double price) { if (APIEmployee.Employee == null) { throw new Exception("Только для авторизованных"); } if (price <= 0) { throw new Exception("Стоимость товара должна быть больше 0"); } APIEmployee.PostRequest("api/employee/createproduct", new ProductBindingModel { CostItemID = costitem, ProductName = name, Price = Calc(costitem, productprice) }); Response.Redirect("Index"); } [HttpGet] public IActionResult DeleteCostItem(int id) { var _costItem = APIEmployee.GetRequset($"api/employee/getcostitem?_costitemid={id}"); if (_costItem == null) { throw new Exception("Ошибка получения данных"); } var _product = APIEmployee.GetRequset($"api/main/getproduct?_costitemID={_costItem.ID}"); if (_product != null) { throw new Exception("Статья затрат прикреплена к товару или товарам"); } APIEmployee.PostRequest("api/employee/deletecostitem", new CostItemBindingModel { ID = id }); return RedirectToAction("CostItem"); } [HttpGet] public IActionResult EditProduct(int id) { var _product = APIEmployee.GetRequset($"api/main/getproduct?_productid={id}"); if (_product == null) { throw new Exception("Ошибка получения данных"); } var _costitem = APIEmployee.GetRequset($"api/employee/getcostitem?_costitemid={_product.CostItemID}"); if (_costitem == null) { return Redirect("/Home/Index"); } ViewBag.CostItems = APIEmployee.GetRequset>($"api/employee/getcostitems?_employeeid={APIEmployee.Employee?.ID}"); var obj = new ProductViewModel { ProductName = _product.ProductName, CostItemID = _product.CostItemID, Price = _product.Price - _costitem.Price, ID = _product.ID }; if (ViewBag.CostItems.Count != 0) { var _costitemLoad = (APIEmployee.GetRequset($"api/employee/getcostitem?_costitemid={obj.CostItemID}")); if (_costitemLoad == null) { return Redirect("/Home/Index"); } if (_costitemLoad?.Name != ViewBag.CostItems[0].Name) { int index = 0; for (int i = 0; i < ViewBag.CostItems.Count; i++) { if (ViewBag.CostItems[i].Name == _costitemLoad?.Name) { index = i; break; } } var tmp = ViewBag.CostItems[0]; ViewBag.CostItems[0] = _costitemLoad; ViewBag.CostItems[index] = tmp; } } return View(obj); } [HttpPost] public void EditProduct(string name, int costitem, int _ID, double price, double productprice) { if (APIEmployee.Employee == null) { throw new Exception("Только для авторизованных"); } if (price <= 0) { throw new Exception("Стоимость товара должна быть больше 0"); } APIEmployee.PostRequest("api/employee/editproduct", new ProductBindingModel { ID = _ID, CostItemID = costitem, ProductName = name, Price = Calc(costitem, productprice) }); Response.Redirect("/Home/Index"); } [HttpGet] public IActionResult DeleteProduct(int id) { APIEmployee.PostRequest("api/employee/deleteproduct", new ProductBindingModel { ID = id }); return RedirectToAction("Index"); } [HttpPost] public double Calc(int costitem, double productprice) { var _costItem = APIEmployee.GetRequset($"api/employee/getcostitem?_costitemid={costitem}"); return productprice + (_costItem?.Price ?? 0); } [HttpPost] public double CalcReload(int costitem, int productid) { var _costItem = APIEmployee.GetRequset($"api/employee/getcostitem?_costitemid={costitem}"); var product = APIEmployee.GetRequset($"api/main/getproduct?_productid={productid}"); if (product == null) { throw new Exception("Ошибка получения данных"); } return product.Price + (_costItem?.Price ?? 0); } [HttpGet] public IActionResult Report() { if (APIEmployee.Employee == null) { return Redirect("/Home/Index"); } return View(APIEmployee.GetRequset>($"api/main/getproducts")); } [HttpPost] public void Report(DateTime DateFrom, DateTime DateTo) { if (DateTo == DateTime.MinValue || DateFrom > DateTo) { throw new Exception("Некоректно указан временной интервал"); } Response.Redirect($"ReportSearch?_datefrom={DateFrom}&_dateto={DateTo + DateTime.Now.TimeOfDay}"); } [HttpGet] public IActionResult ReportSearch(string _datefrom, string _dateto) { var reports = APIEmployee.GetRequset>($"api/client/getreport?_start={_datefrom}&_end={_dateto}"); (DateTime, DateTime, List?) tuple = (DateTime.Parse(_datefrom), DateTime.Parse(_dateto), reports); return View(tuple); } [HttpGet] public IActionResult ReportSearchFix() { string strUrl = Request.GetDisplayUrl(); strUrl = strUrl.Replace("https://localhost:7221/Home/ReportSearchFix/", ""); string ids = ""; List productsFix = new(); foreach (char i in strUrl) { if (int.TryParse(i.ToString(), out int id)) { var product = APIEmployee.GetRequset($"api/main/getproduct?_productid={id}") ?? throw new Exception("Товар не найден"); productsFix.Add(product); ids += "/" + id; } } if (string.IsNullOrEmpty(ids)) { throw new Exception("Нет выбранных товаров"); } (List, string) tuple = (productsFix, ids); return View(tuple); } [HttpGet] public IActionResult CreateWordReport(string ids) { var fileMemStream = APIEmployee.GetRequset($"api/Employee/CreateDocxReport?_ids={ids}"); if (fileMemStream == null) { throw new Exception("Ошибка создания отчета"); } return File(fileMemStream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "Report.docx"); } [HttpGet] public IActionResult CreateExcelReport(string ids) { var fileMemStream = APIEmployee.GetRequset($"api/Employee/CreateXlsxReport?_ids={ids}"); if (fileMemStream == null) { throw new Exception("Ошибка создания отчета"); } return File(fileMemStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Report.xlsx"); } [HttpGet] public IActionResult CreatePdfReport(string DateFrom, string DateTo) { APIEmployee.PostRequest("api/Employee/SendReportMail", new ReportBindingModel { ClientEmail = APIEmployee.Employee?.Email ?? throw new Exception("Ошибка получения адреса"), DateFrom = DateTime.Parse(DateFrom), DateTo = DateTime.Parse(DateTo), ClientID = APIEmployee.Employee.ID }); return View("Report"); } } }