CourseWork_BankYouBankrupt/BankYouBankrupt/BankYouBankruptCashierApp/Controllers/HomeController.cs
2023-05-20 08:00:06 +04:00

723 lines
22 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using BankYouBankruptCashierApp.Models;
using BankYouBankruptContracts.BindingModels;
using BankYouBankruptContracts.ViewModels;
using BankYouBankruptContracts.ViewModels.Client.Default;
using BankYouBankruptContracts.ViewModels.Client.Diagram;
using BankYouBankruptContracts.ViewModels.Client.Reports;
using BankYouBankruptDataModels.Enums;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Xml.Linq;
namespace BankYouBankruptCashierApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
#region Загрузка главной страницы
//вытаскивает через API клиента Get-запросом список его собственных заказов
[HttpGet]
public IActionResult Index()
{
if (APICashier.Cashier == null)
{
return Redirect("~/Home/Enter");
}
return View(APICashier.GetRequest<List<AccountViewModel>>($"/api/Account/GetAllAccounts"));
}
#endregion
#region Обновление данных пользователя
//изменемение ланных Get-ом
[HttpGet]
public IActionResult Privacy()
{
if (APICashier.Cashier == null)
{
return Redirect("~/Home/Enter");
}
return View(APICashier.Cashier);
}
//изменение данных Post-ом
[HttpPost]
public void Privacy(string login, string password, string name, string surname, string patronymic, string telephone)
{
if (APICashier.Cashier == null)
{
throw new Exception("Вы как сюда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(name)
|| string.IsNullOrEmpty(surname) || string.IsNullOrEmpty(patronymic)
|| string.IsNullOrEmpty(telephone))
{
throw new Exception("Введите логин, пароль, ФИО и телефон");
}
APICashier.PostRequest("/api/Cashier/UpdateData", new CashierBindingModel
{
Id = APICashier.Cashier.Id,
Name = name,
Surname = surname,
Patronymic = patronymic,
Telephone = telephone,
Email = login,
Password = password
});
APICashier.Cashier.Name = name;
APICashier.Cashier.Surname = surname;
APICashier.Cashier.Patronymic = patronymic;
APICashier.Cashier.Email = login;
APICashier.Cashier.Password = password;
APICashier.Cashier.Telephone = telephone;
Response.Redirect("Enter");
}
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
public IActionResult Login(string login, string password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{
APICashier.SetErrorMessage("Необходимо заполнить оба поля");
return Redirect("ErrorPage");
}
APICashier.Cashier = APICashier.GetRequest<CashierViewModel>($"api/Cashier/Login?login={login}&password={password}");
if (APICashier.Cashier == null)
{
APICashier.SetErrorMessage("Неверный логин или пароль");
return Redirect("ErrorPage");
}
return Redirect("Enter");
}
[HttpPost]
public IActionResult Logout()
{
APICashier.Cashier = null;
return Redirect("Enter");
}
#endregion
#region Вывод ошибок
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
});
}
[HttpGet]
public IActionResult ErrorPage()
{
return View();
}
#endregion
#region Вход в приложение
//просто открытие вьюхи
[HttpGet]
public IActionResult Enter()
{
return View();
}
//отсылаем указанные данные на проверку
[HttpPost]
public IActionResult Enter(string login, string password)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{
APICashier.SetErrorMessage("Введите логин и пароль");
return Redirect("ErrorPage");
}
APICashier.Cashier = APICashier.GetRequest<CashierViewModel>($"/api/Cashier/Login?login={login}&password={password}");
if (APICashier.Cashier == null)
{
APICashier.SetErrorMessage("Неверный логин или пароль");
return Redirect("ErrorPage");
}
return Redirect("Index");
}
#endregion
#region Регистрация
//просто открытие вьюхи
[HttpGet]
public IActionResult Register()
{
return View();
}
//Post-запрос по созданию нового пользователя
[HttpPost]
public void Register(string login, string password, string name, string surname, string patronymic, string telephone)
{
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(name)
|| string.IsNullOrEmpty(surname) || string.IsNullOrEmpty(patronymic) || string.IsNullOrEmpty(telephone))
{
throw new Exception("Введите логин, пароль, ФИО и телефон");
}
APICashier.PostRequest("/api/Cashier/Register", new CashierBindingModel
{
Name = name,
Surname = surname,
Patronymic = patronymic,
Email = login,
Password = password,
Telephone = telephone
});
//переход на вкладку "Enter", чтобы пользователь сразу смог зайти
Response.Redirect("Enter");
return;
}
#endregion
#region Открытие нового счёта
//открытие счёта. Получаем и передаём список изделий во вьюху?
[HttpGet]
public IActionResult CreateAccount()
{
if (APICashier.Cashier == null)
{
return Redirect("~/Home/Enter");
}
//запрашиваем список в формате вспомогательной вьюшки из-за работы select в asp net
ViewBag.Clients = APICashier.GetRequest<List<ClientViewModel>>($"/api/Client/GetAllClients").Select(x => new ClientSelectViewModel
{
Id = x.Id,
FullName = x.Surname + " " + x.Name + " " + x.Patronymic
}).ToList();
return View();
}
//создание заказа Post-запросом
[HttpPost]
public IActionResult CreateAccount(int clientId, string accountNumber, string password, int balance)
{
if (APICashier.Cashier == null)
{
APICashier.SetErrorMessage("Необходимо авторизоваться");
return Redirect("ErrorPage");
}
if (clientId <= 0 || string.IsNullOrEmpty(accountNumber) || string.IsNullOrEmpty(password) || balance < 0)
{
APICashier.SetErrorMessage("Проверьте корректность вводимых данных");
return Redirect("ErrorPage");
}
APICashier.PostRequest("/api/Account/Register", new AccountBindingModel
{
CashierId = APICashier.Cashier.Id,
ClientId = clientId,
AccountNumber = accountNumber,
PasswordAccount = password,
Balance = balance,
DateOpen = DateTime.Now
});
return Redirect("Index");
}
#endregion
#region Работа с заявками на зачисление
//для страницы "Заявки на зачисление"
[HttpGet]
public IActionResult Crediting()
{
if (APICashier.Cashier == null)
{
APICashier.SetErrorMessage("Необходимо авторизоваться");
Response.Redirect("ErrorPage");
}
return View(APICashier.GetRequest<List<CreditingViewModel>>($"/api/Account/FindOpenCrediting"));
}
//открытие вьюхи одобрения заявки на зачисление
[HttpGet]
public IActionResult CloseCrediting()
{
if (APICashier.Cashier == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Creditings = APICashier.GetRequest<List<CreditingViewModel>>("/api/Account/FindOpenCrediting");
ViewBag.Accounts = APICashier.GetRequest<List<AccountViewModel>>("/api/Account/GetAllAccounts");
return View();
}
//одобрения заявки на зачисление Post-запросом
[HttpPost]
public IActionResult CloseCrediting(int creditingId, int accountPayeeId)
{
if (APICashier.Cashier == null)
{
APICashier.SetErrorMessage("Необходимо авторизоваться");
return Redirect("ErrorPage");
}
if (creditingId <= 0 || accountPayeeId <= 0)
{
APICashier.SetErrorMessage("Проверьте коректность передавваемых значений");
return Redirect("ErrorPage");
}
//получаем необходимые данные для запроса
APICashier.Crediting = APICashier.GetRequest<CreditingViewModel>($"/api/Account/FindCrediting?id={creditingId}");
APICashier.Card = APICashier.GetRequest<CardViewModel>($"/api/Card/FindCard?id={APICashier.Crediting.CardId}");
APICashier.PostRequest("/api/Account/CloseCrediting", new MoneyTransferBindingModel
{
CashierId = APICashier.Cashier.Id,
CreditingId = creditingId,
Sum = APICashier.Crediting.Sum,
AccountPayeeId = accountPayeeId
});
//очистка данных
APICashier.Crediting = null;
APICashier.Card = null;
return Redirect("Crediting");
}
#endregion
#region Работа с заявками на снятие
//для страницы "Заявки на снятие"
[HttpGet]
public IActionResult Debiting()
{
if (APICashier.Cashier == null)
{
APICashier.SetErrorMessage("Необходимо авторизоваться");
Response.Redirect("ErrorPage");
}
return View(APICashier.GetRequest<List<DebitingViewModel>>($"/api/Account/FindOpenDebiting"));
}
//открытие вьюхи одобрения заявки на снятие
[HttpGet]
public IActionResult CloseDebiting()
{
if (APICashier.Cashier == null)
{
APICashier.SetErrorMessage("Необходимо авторизоваться");
Response.Redirect("ErrorPage");
}
ViewBag.Debitings = APICashier.GetRequest<List<DebitingViewModel>>("/api/Account/FindOpenDebiting");
ViewBag.Accounts = APICashier.GetRequest<List<AccountViewModel>>("/api/Account/GetAllAccounts");
return View();
}
//одобрения заявки на снятие Post-запросом
[HttpPost]
public IActionResult CloseDebiting(int debitingId, int accountId)
{
if (APICashier.Cashier == null)
{
APICashier.SetErrorMessage("Необходимо авторизоваться");
return Redirect("ErrorPage");
}
if (debitingId <= 0 || accountId <= 0)
{
APICashier.SetErrorMessage("Проверьте корректность передаваемых значений");
return Redirect("ErrorPage");
}
//получаем необходимые данные для запроса
APICashier.Debiting = APICashier.GetRequest<DebitingViewModel>($"/api/Account/FindDebiting?id={debitingId}");
APICashier.Card = APICashier.GetRequest<CardViewModel>($"/api/Card/FindCard?id={APICashier.Debiting.CardId}");
APICashier.PostRequest("/api/Account/CloseDebiting", new CashWithdrawalBindingModel
{
CashierId = APICashier.Cashier.Id,
DebitingId = debitingId,
Sum = APICashier.Debiting.Sum,
AccountId = accountId
});
APICashier.Debiting = null;
APICashier.Card = null;
return Redirect("Debiting");
}
#endregion
//получение номера запрашиваемого счёта для снятия - для работы с начислениями и списаниями
[HttpPost]
public string GetAccountNumber(int id)
{
if (APICashier.Cashier == null)
{
APICashier.SetErrorMessage("Необходимо авторизоваться");
Response.Redirect("ErrorPage");
}
APICashier.Debiting = APICashier.GetRequest<DebitingViewModel>($"/api/Account/FindDebiting?id={id}");
APICashier.Crediting = APICashier.GetRequest<CreditingViewModel>($"/api/Account/FindCrediting?id={id}");
if(APICashier.Debiting == null)
{
APICashier.Card = APICashier.GetRequest<CardViewModel>($"/api/Card/FindCard?id={APICashier.Crediting.CardId}");
}
else
{
APICashier.Card = APICashier.GetRequest<CardViewModel>($"/api/Card/FindCard?id={APICashier.Debiting.CardId}");
}
APICashier.Account = APICashier.GetRequest<AccountViewModel>($"/api/Account/GetAccount?accountId={APICashier.Card.AccountId}");
string AccountNumber = APICashier.Account.AccountNumber;
APICashier.Debiting = null;
APICashier.Card = null;
APICashier.Account = null;
return AccountNumber;
}
#region Работа с переводом со счёта на счёт
[HttpGet]
public IActionResult MoneyTransfers()
{
if (APICashier.Cashier == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Accounts = APICashier.GetRequest<List<AccountViewModel>>("/api/Account/GetAllAccounts");
return View();
}
[HttpPost]
public IActionResult MoneyTransfers(int accountSenderId, int accountPayeeId, int sumMoneyTransfer)
{
if (APICashier.Cashier == null)
{
APICashier.SetErrorMessage("Необходимо авторизоваться");
return Redirect("ErrorPage");
}
if (accountPayeeId <= 0 || accountSenderId <= 0 || sumMoneyTransfer <= 0)
{
APICashier.SetErrorMessage("Проверьте корректность передаваемых значений");
return Redirect("ErrorPage");
}
APICashier.PostRequest("/api/Account/CloseCrediting", new MoneyTransferBindingModel
{
CashierId = APICashier.Cashier.Id,
Sum = sumMoneyTransfer,
AccountPayeeId = accountPayeeId,
AccountSenderId = accountSenderId
});
return Redirect("Index");
}
#endregion
#region Отчёт с выборкой по счетам
[HttpGet]
public IActionResult ReportWithAccounts()
{
if (APICashier.Cashier == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Accounts = APICashier.GetRequest<List<AccountViewModel>>("/api/Account/GetAllAccounts");
return View(new List<ReportCashierAccountsViewModel>());
}
//создание excel отчёта у касира
[HttpPost]
public IActionResult CreateCashierExcelReport(string accountId)
{
if (APICashier.Cashier == null)
{
APICashier.SetErrorMessage("Необходимо авторизоваться");
return Redirect("ErrorPage");
}
if (string.IsNullOrEmpty(accountId))
{
APICashier.SetErrorMessage("Необходимо выбрать счёт для создания отчёта");
return Redirect("ErrorPage");
}
APICashier.PostRequest("api/Report/CreateExcelCashier", new ReportSupportBindingModel()
{
AccountId = int.Parse(accountId),
Email = APICashier.Cashier.Email
});
return Redirect("ReportSuccess");
}
//создание excel отчёта у касира
[HttpPost]
public IActionResult CreateCashierWordReport(string accountId)
{
if (APICashier.Cashier == null)
{
APICashier.SetErrorMessage("Необходимо авторизоваться");
return Redirect("ErrorPage");
}
if (string.IsNullOrEmpty(accountId))
{
APICashier.SetErrorMessage("Необходимо выбрать счёт для создания отчёта");
return Redirect("ErrorPage");
}
APICashier.PostRequest("api/Report/CreateWordCashier", new ReportSupportBindingModel()
{
AccountId = int.Parse(accountId),
Email = APICashier.Cashier.Email
});
return Redirect("ReportSuccess");
}
[HttpPost]
public IActionResult ReportWithAccounts(string accountId)
{
if (APICashier.Cashier == null)
{
APICashier.SetErrorMessage("Необходимо авторизоваться");
return Redirect("ErrorPage");
}
if (string.IsNullOrEmpty(accountId))
{
APICashier.SetErrorMessage("Необходимо выбрать счёт для создания отчёта");
return Redirect("ErrorPage");
}
ViewBag.Accounts = APICashier.GetRequest<List<AccountViewModel>>("/api/Account/GetAllAccounts");
var cashWithdrawals = APICashier.GetRequest<List<CashWithdrawalViewModel>>("api/Account/FindAllCashWithdrawal").Where(x => x.AccountId == int.Parse(accountId))
.Select(x => new ReportCashierAccountsViewModel
{
CashierSurname = x.SurmaneCashier,
Sum = x.Sum,
AccountSenderNumber = x.AccountNumber,
DateOperation = x.DateOperation,
typeOperation = TypeOperationEnum.Снятие
});
var moneyTransfers = APICashier.GetRequest<List<MoneyTransferViewModel>>("/api/Account/FindAllMoneyTransfer").Where(x => (x.AccountPayeeId == int.Parse(accountId) || x.AccountSenderId == int.Parse(accountId)))
.Select(x => new ReportCashierAccountsViewModel
{
CashierSurname = x.CashierSurname,
Sum = x.Sum,
AccountPayeeNumber = x.AccountPayeeNumber,
AccountSenderNumber = x.AccountSenderNumber != null ? x.AccountSenderNumber : "---",
DateOperation = x.DateOperation,
typeOperation = x.AccountSenderId.HasValue ? TypeOperationEnum.Перевод : TypeOperationEnum.Пополнение
});
return View(cashWithdrawals.Concat(moneyTransfers).OrderBy(x => x.DateOperation).ToList());
}
#endregion
#region Получение отчёта PDF
[HttpGet]
public IActionResult CreateReport()
{
if (APICashier.Cashier == null)
{
return Redirect("~/Home/Enter");
}
//запрашиваем список в формате вспомогательной вьюшки из-за работы select в asp net
ViewBag.Clients = APICashier.GetRequest<List<ClientViewModel>>($"/api/Client/GetAllClients").Select(x => new ClientSelectViewModel
{
Id = x.Id,
FullName = x.Surname + " " + x.Name + " " + x.Patronymic
}).ToList();
return View();
}
[HttpPost]
public IActionResult CreateReport(int clientId, DateTime dateFrom, DateTime dateTo)
{
if (APICashier.Cashier == null)
{
APICashier.SetErrorMessage("Необходимо авторизоваться");
return Redirect("ErrorPage");
}
if (clientId <= 0 || dateFrom == dateTo || dateFrom > dateTo || dateFrom.Year == 0001 || dateTo.Year == 0001)
{
APICashier.SetErrorMessage("Пожалуйста, установите корректные границы периода для отчёта и выберите счёт");
return Redirect("ErrorPage");
}
//запрашиваем список в формате вспомогательной вьюшки из-за работы select в asp net
ViewBag.Clients = APICashier.GetRequest<List<ClientViewModel>>($"/api/Client/GetAllClients").Select(x => new ClientSelectViewModel
{
Id = x.Id,
FullName = x.Surname + " " + x.Name + " " + x.Patronymic
}).ToList();
return View(APICashier.PostRequestReport<ReportCashierViewModelForHTML, ReportSupportBindingModel>("api/Report/CreateCashierReport", new ReportSupportBindingModel()
{
ClientId = clientId,
Email = APICashier.Cashier.Email,
DateFrom = dateFrom,
DateTo = dateTo
}));
}
#endregion
#region Диаграмма
[HttpGet]
public IActionResult Diagram()
{
if (APICashier.Cashier == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Accounts = APICashier.GetRequest<List<AccountViewModel>>($"api/Account/GetAllAccounts");
return View();
}
[HttpPost]
public IActionResult Diagram(int accountId)
{
if (APICashier.Cashier == null)
{
return Redirect("~/Home/Enter");
}
if (accountId <= 0)
{
APICashier.SetErrorMessage("Для построения диаграммы необходимо выбрать счёт");
return Redirect("ErrorPage");
}
ViewBag.Accounts = APICashier.GetRequest<List<AccountViewModel>>($"api/Account/GetAllAccounts");
return View(new CashierDiagramViewModel()
{
DiagramName = "Hello World",
Elements = APICashier.GetRequest<List<CashierDiagramElementsViewModel>>($"api/Account/getAccountMonthResult?cardId={accountId}")
});
}
#endregion
[HttpGet]
public IActionResult ReportSuccess()
{
if (APICashier.Cashier == null)
{
APICashier.SetErrorMessage("Необходимо авторизоваться");
Response.Redirect("ErrorPage");
}
return View();
}
}
}