CourseWork_Bank/Bank/BankClientApp/Controllers/HomeController.cs

215 lines
8.0 KiB
C#
Raw Normal View History

2024-05-01 01:31:46 +04:00
using BankContracts.ViewModels;
using BankClientApp.Models;
2024-04-29 21:23:38 +04:00
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
2024-05-01 01:31:46 +04:00
using Newtonsoft.Json;
using BankContracts.BusinessLogicContracts;
using BankClientApp.Filter;
using BankContracts.BindingModels;
using BankDataModels.ProxyModels;
2024-04-29 21:23:38 +04:00
namespace BankClientApp.Controllers
{
2024-05-01 01:31:46 +04:00
[AuthorizationFilter]
2024-04-29 21:23:38 +04:00
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
2024-05-01 01:31:46 +04:00
private readonly IClientLogic _clientLogic;
private readonly IPurchaseLogic _purchaseLogic;
private readonly IOperationLogic _operationLogic;
private readonly IReportLogic _reportLogic;
private readonly IPaymentLogic _paymentLogic;
2024-04-29 21:23:38 +04:00
2024-05-01 01:31:46 +04:00
private ClientViewModel? _client;
public HomeController(ILogger<HomeController> logger,
IClientLogic clientLogic, IPurchaseLogic purchaseLogic, IOperationLogic operationLogic,
IReportLogic reportLogic, IPaymentLogic paymentLogic)
2024-04-29 21:23:38 +04:00
{
2024-05-01 01:31:46 +04:00
_reportLogic = reportLogic;
_clientLogic = clientLogic;
2024-04-29 21:23:38 +04:00
_logger = logger;
2024-05-01 01:31:46 +04:00
_purchaseLogic = purchaseLogic;
_operationLogic = operationLogic;
_paymentLogic = paymentLogic;
2024-04-29 21:23:38 +04:00
}
public IActionResult Index()
{
return View();
}
2024-05-01 01:31:46 +04:00
private ClientViewModel Client
{
get
{
if (_client == null)
{
try
{
_client = _clientLogic.ReadElement(new()
{
PhoneNumber = HttpContext.Session.GetString(SessionKeys.ClientPhoneNumber),
Password = HttpContext.Session.GetString(SessionKeys.ClientPassword),
});
}
catch (Exception e)
{
_logger.LogError(e, "Не удалось получить пользователя, хотя был пройден фильтр авторизации");
throw;
}
}
return _client;
}
}
2024-04-29 21:23:38 +04:00
public IActionResult Privacy()
{
2024-05-01 01:31:46 +04:00
return View(Client);
2024-04-29 21:23:38 +04:00
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
2024-05-01 01:31:46 +04:00
public IActionResult Purchases()
{
return View(_purchaseLogic.ReadList(new() { ClientId = Client.Id }));
}
public FileResult ReportOperationsInWord(int[] ids)
{
_logger.LogInformation("Запрошен отчет в формате word");
_logger.LogInformation("Получено {count} обследований для отчета", ids.Length);
MemoryStream mstream = new();
_reportLogic.SaveOperationsToWord(new()
{
Ids = ids,
Stream = mstream,
});
return File(mstream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, "reportWord.docx");
}
public FileResult ReportOperationsInExcel(int[] ids)
{
_logger.LogInformation("Запрошен отчет в формате excel");
_logger.LogInformation("Получено {count} операций для отчета", ids.Length);
MemoryStream mstream = new();
_reportLogic.SaveOperationsToExcel(new()
{
Ids = ids,
Stream = mstream
});
return File(mstream.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, "reportExcel.xlsx");
}
public IActionResult PurchasesReport()
{
return View(_purchaseLogic.ReadList(new() { ClientId = Client.Id }));
}
public IActionResult Payment()
{
ViewBag.Purchases = _purchaseLogic.ReadList(new() { ClientId = Client.Id });
return View();
}
public List<OperationViewModel> GetOperations(int purchase)
{
return _operationLogic.ReadList(new() { PurchasesIds = new() { purchase } }); ;
}
[HttpGet]
public IActionResult Purchase(int? id)
{
return View(Tuple.Create(
id.HasValue ? _purchaseLogic.ReadElement(new() { Id = id }) : null,
_operationLogic.ReadList()));
}
[HttpPost]
public void Purchase(DateTime datePurchase, List<int> carsIds, List<int> countOperations)
{
var isOperationUpdate = Request.RouteValues.TryGetValue("id", out var identValue);
isOperationUpdate &= int.TryParse((string?)identValue, out var id);
_logger.LogInformation("При изменении операции были получены данные:{idUpdated}, {datePurchase}", identValue, datePurchase);
PurchaseBindingModel model = new()
{
DatePurchase = DateOnly.FromDateTime(datePurchase),
OperationsModel = carsIds.Zip(countOperations).ToDictionary(
x => x.First,
x => new OperationByPurchaseModel() { OperationId = x.First, CountOperations = x.Second }
),
};
if (isOperationUpdate)
{
model.Id = id;
_purchaseLogic.Update(model);
Response.Redirect("../Purchases");
}
else
{
model.ClientId = Client.Id;
_purchaseLogic.Create(model);
Response.Redirect("Purchases");
}
}
public IActionResult RemovePurchase(int id)
{
_purchaseLogic.Delete(new() { Id = id });
return Redirect("~/Home/Purchases");
}
[HttpPost]
public Tuple<double, double> CalcPrice(int purchase, int car)
{
_paymentLogic.GetPaymentInfo(new() { OperationId = car, PurchaseId = purchase },
out var fullPrice, out var paidPrice);
return Tuple.Create(paidPrice, fullPrice - paidPrice);
}
[HttpPost]
public void Payment(double resultSum, int purchase, int car)
{
_logger.LogInformation("Получены данные: {resultSum}; {purchase} {car}", resultSum, purchase, car);
_paymentLogic.Create(new()
{
PaidPrice = resultSum,
Date = DateOnly.FromDateTime(DateTime.Now),
OperationByPurchaseId = _purchaseLogic.ReadElement(new() { Id = purchase }).OperationsModel[car].Id,
});
Response.Redirect("/Home/Payment");
}
public IActionResult ReportFromPurchases(string? getReport, string? sendToMail, DateTime startDate, DateTime endDate)
{
_logger.LogInformation("Попытка получить отчет: {@getReport}; {@sendToMail} Период: {0}---{1}", getReport, sendToMail, startDate, endDate);
if (startDate > endDate)
{
throw new Exception("Дата начала больше даты конца периода");
}
if (getReport != null)
{
return View(_purchaseLogic.ReadList(new()
{
DateFrom = DateOnly.FromDateTime(startDate),
DateTo = DateOnly.FromDateTime(endDate)
}));
}
if (sendToMail != null)
{
_reportLogic.SendCostsToEmail(
option: new()
{
DateFrom = DateOnly.FromDateTime(startDate),
DateTo = DateOnly.FromDateTime(endDate)
},
email: Client.Email
);
}
return View();
}
2024-04-29 21:23:38 +04:00
}
2024-05-01 01:31:46 +04:00
}