CourseWork_Bank/Bank/BankClientApp/Controllers/HomeController.cs
2024-05-01 00:31:46 +03:00

215 lines
8.0 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 BankContracts.ViewModels;
using BankClientApp.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using Newtonsoft.Json;
using BankContracts.BusinessLogicContracts;
using BankClientApp.Filter;
using BankContracts.BindingModels;
using BankDataModels.ProxyModels;
namespace BankClientApp.Controllers
{
[AuthorizationFilter]
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IClientLogic _clientLogic;
private readonly IPurchaseLogic _purchaseLogic;
private readonly IOperationLogic _operationLogic;
private readonly IReportLogic _reportLogic;
private readonly IPaymentLogic _paymentLogic;
private ClientViewModel? _client;
public HomeController(ILogger<HomeController> logger,
IClientLogic clientLogic, IPurchaseLogic purchaseLogic, IOperationLogic operationLogic,
IReportLogic reportLogic, IPaymentLogic paymentLogic)
{
_reportLogic = reportLogic;
_clientLogic = clientLogic;
_logger = logger;
_purchaseLogic = purchaseLogic;
_operationLogic = operationLogic;
_paymentLogic = paymentLogic;
}
public IActionResult Index()
{
return View();
}
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;
}
}
public IActionResult Privacy()
{
return View(Client);
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
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();
}
}
}