Все предфинальные изменения пулю))

This commit is contained in:
Алексей Крюков 2024-05-29 17:24:55 +04:00
parent 4da35faa7a
commit 0f70b85ca6
179 changed files with 8299 additions and 6989 deletions

View File

@ -9,10 +9,6 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.19.0" /> <PackageReference Include="DocumentFormat.OpenXml" Version="2.19.0" />
<PackageReference Include="MailKit" Version="4.5.0" /> <PackageReference Include="MailKit" Version="4.5.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.18">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" /> <PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
</ItemGroup> </ItemGroup>

View File

@ -1,29 +1,22 @@
using BankContracts.BindingModels.Cashier; using BankContracts.BindingModels.Cashier;
using BankContracts.BusinessLogicsContracts.Cashier; using BankContracts.BusinessLogicsContracts.Cashier;
using BankContracts.SearchModels.Cashier; using BankContracts.SearchModels.Cashier;
using BankContracts.StoragesModels.Cashier; using BankContracts.StoragesContracts.Cashier;
using BankContracts.ViewModels; using BankContracts.ViewModels.Cashier.Diagram;
using BankContracts.ViewModels.Cashier.ViewModels;
using BankDataModels.Enums;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.BusinessLogic.Cashier namespace BankBusinessLogic.BusinessLogics.Cashier
{ {
// Класс, реализующий бизнес-логику для счетов
public class AccountLogic : IAccountLogic public class AccountLogic : IAccountLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IAccountStorage _accountStorage; private readonly IAccountStorage _accountStorage;
private readonly ICashWithdrawalLogic _cashWithdrawalLogic; private readonly ICashWithdrawalLogic _cashWithdrawalLogic;
private readonly IMoneyTransferLogic _moneyTransferLogic; private readonly IMoneyTransferLogic _moneyTransferLogic;
// Конструктор
public AccountLogic(ILogger<AccountLogic> logger, IAccountStorage accountStorage, public AccountLogic(ILogger<AccountLogic> logger, IAccountStorage accountStorage,
ICashWithdrawalLogic cashWithdrawalLogic, IMoneyTransferLogic moneyTransferLogic) ICashWithdrawalLogic cashWithdrawalLogic, IMoneyTransferLogic moneyTransferLogic)
{ {
@ -33,7 +26,6 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
_moneyTransferLogic = moneyTransferLogic; _moneyTransferLogic = moneyTransferLogic;
} }
// Вывод конкретного счёта
public AccountViewModel? ReadElement(AccountSearchModel model) public AccountViewModel? ReadElement(AccountSearchModel model)
{ {
if (model == null) if (model == null)
@ -57,19 +49,11 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return element; return element;
} }
// Вывод всего списка счетов
public List<AccountViewModel>? ReadList(AccountSearchModel? model) public List<AccountViewModel>? ReadList(AccountSearchModel? model)
{ {
if (model != null) //_logger.LogInformation("ReadList. AccountNumber:{AccountNumber}. Id:{Id}", model.AccountNumber, model?.Id);
{
_logger.LogInformation("ReadList. AccountNumber:{AccountNumber}. Id:{Id}", model.AccountNumber, model.Id);
}
else
{
_logger.LogInformation("ReadList without filter model");
}
// list хранит весь список в случае, если model пришло со значением null на вход метода //list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _accountStorage.GetFullList() : _accountStorage.GetFilteredList(model); var list = model == null ? _accountStorage.GetFullList() : _accountStorage.GetFilteredList(model);
if (list == null) if (list == null)
@ -83,11 +67,10 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return list; return list;
} }
//метод, отвечающий за изменение баланса счёта
// Метод, отвечающий за изменение баланса счёта
public bool ChangeBalance(AccountSearchModel? model, int sum) public bool ChangeBalance(AccountSearchModel? model, int sum)
{ {
// Ищем счёт //ищем счёт
var account = ReadElement(model); var account = ReadElement(model);
if (account == null) if (account == null)
@ -95,13 +78,13 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
throw new ArgumentNullException("Счёт не найден", nameof(account)); throw new ArgumentNullException("Счёт не найден", nameof(account));
} }
// Проверяем возможность операции снятия (sum может быть отрицательной) //проверяем возможность операции снятия (sum может быть отрицательной)
if (sum + account.Balance < 0) if (sum + account.Balance < 0)
{ {
return false; return false;
} }
// Обновляем балланс счёта //обновляем балланс счёта
_accountStorage.Update(new AccountBindingModel _accountStorage.Update(new AccountBindingModel
{ {
Id = account.Id, Id = account.Id,
@ -111,7 +94,6 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return true; return true;
} }
// Создание счёта
public bool Create(AccountBindingModel model) public bool Create(AccountBindingModel model)
{ {
CheckModel(model); CheckModel(model);
@ -126,7 +108,6 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return true; return true;
} }
// Обновление счёта
public bool Update(AccountBindingModel model) public bool Update(AccountBindingModel model)
{ {
CheckModel(model); CheckModel(model);
@ -141,7 +122,6 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return true; return true;
} }
// Удаление счёта
public bool Delete(AccountBindingModel model) public bool Delete(AccountBindingModel model)
{ {
CheckModel(model, false); CheckModel(model, false);
@ -158,7 +138,42 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return true; return true;
} }
// Проверка входного аргумента для методов Insert, Update и Delete public List<CashierDiagramElementsViewModel> GetMonthInfo(int AccountId)
{
Dictionary<(int, int), int> cashWithdrawals = _cashWithdrawalLogic.ReadList(new CashWithdrawalSearchModel()
{
AccountId = AccountId,
}).Where(x => x.DebitingStatus == StatusEnum.Закрыта ).GroupBy(x => new { x.DateOperation.Month, x.DateOperation.Year })
.Select(x => new { x.Key.Month, x.Key.Year, Sum = x.Select(y => y.Sum).Sum() }).ToDictionary(x => (x.Month, x.Year), x => (x.Sum));
Dictionary<(int, int), int> moneyTransfers = _moneyTransferLogic.ReadList(new MoneyTransferSearchModel()
{
AccountPayeeId = AccountId,
}).GroupBy(x => new { x.DateOperation.Month, x.DateOperation.Year })
.Select(x => new { x.Key.Month, x.Key.Year, Sum = x.Select(y => y.Sum).Sum() }).ToDictionary(x => (x.Month, x.Year), x => (x.Sum));
Dictionary<(int, int), int> moneyTransfersDebiting = _moneyTransferLogic.ReadList(new MoneyTransferSearchModel()
{
AccountSenderId = AccountId,
}).GroupBy(x => new { x.DateOperation.Month, x.DateOperation.Year })
.Select(x => new { x.Key.Month, x.Key.Year, Sum = x.Select(y => y.Sum).Sum() }).ToDictionary(x => (x.Month, x.Year), x => (x.Sum));
List<CashierDiagramElementsViewModel> result = new();
int sum = 0;
foreach (var key in cashWithdrawals.Keys.Union(moneyTransfers.Keys).Union(moneyTransfers.Keys).OrderBy(x => x.Item1 * 12 + x.Item2))
{
if (cashWithdrawals.ContainsKey(key)) sum += cashWithdrawals.GetValueOrDefault(key);
if (moneyTransfers.ContainsKey(key)) sum += moneyTransfers.GetValueOrDefault(key);
if (moneyTransfers.ContainsKey(key)) sum -= moneyTransfersDebiting.GetValueOrDefault(key);
result.Add(new CashierDiagramElementsViewModel() { Name = Enum.GetName(typeof(Months), key.Item1) + " " + key.Item2.ToString(), Value = sum });
}
return result;
}
//проверка входного аргумента для методов Insert, Update и Delete
private void CheckModel(AccountBindingModel model, bool withParams = true) private void CheckModel(AccountBindingModel model, bool withParams = true)
{ {
if (model == null) if (model == null)
@ -166,52 +181,57 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
// Так как при удалении передаём как параметр false //так как при удалении передаём как параметр false
if (!withParams) if (!withParams)
{ {
return; return;
} }
// Проверка на наличие номера счёта //проверка на наличие номера счёта
if (string.IsNullOrEmpty(model.AccountNumber)) if (string.IsNullOrEmpty(model.AccountNumber))
{ {
throw new ArgumentNullException("Отсутствие номера у счёта", nameof(model.AccountNumber)); throw new ArgumentNullException("Отсутствие номера у счёта", nameof(model.AccountNumber));
} }
// Проверка на наличие id клиента (И всё-таки не будет лишним добавить Id клиента) //проверка на наличие id владельца
if (model.ClientId < 0) if (model.CashierId < 0)
{ {
throw new ArgumentNullException("Некорректный Id клиента", nameof(model.ClientId)); throw new ArgumentNullException("Некорректный Id владельца счёта", nameof(model.CashierId));
} }
// Проверка на наличие id кассира, создавшего счёт //проверка на наличие id кассира, создавшего счёт
if (model.CashierId < 0) if (model.CashierId < 0)
{ {
throw new ArgumentNullException("Некорректный Id кассира, открывшего счёт", nameof(model.CashierId)); throw new ArgumentNullException("Некорректный Id кассира, открывшего счёт", nameof(model.CashierId));
} }
if (model.Balance < 0) //проверка на наличие пароля счёта
if (string.IsNullOrEmpty(model.PasswordAccount) )
{ {
throw new ArgumentNullException("Некорректный пароль счёта", nameof(model.PasswordAccount));
}
if (model.Balance < 0) {
throw new ArgumentNullException("Изначальный баланс аккаунта не может быть < 0", nameof(model.Balance)); throw new ArgumentNullException("Изначальный баланс аккаунта не может быть < 0", nameof(model.Balance));
} }
// Проверка на корректную дату открытия счёта //проверка на корректную дату открытия счёта
if (model.DateOpen > DateTime.Now) if (model.DateOpen > DateTime.Now)
{ {
throw new ArgumentNullException("Дата открытия счёта не может быть ранее текущей", nameof(model.DateOpen)); throw new ArgumentNullException("Дата открытия счёта не может быть ранее текущей", nameof(model.DateOpen));
} }
_logger.LogInformation("Account. AccountNumber:{AccountNumber}. ClientId:{ClientId}. " + _logger.LogInformation("Account. AccountNumber:{AccountNumber}. PasswordAccount:{PasswordAccount}. ClientId:{ClientId}. " +
"CashierId:{CashierId}. DateOpen:{DateOpen}. Id:{Id}", "CashierId:{CashierId}. DateOpen:{DateOpen}. Id:{Id}",
model.AccountNumber, model.ClientId, model.CashierId, model.DateOpen, model.Id); model.AccountNumber, model.PasswordAccount, model.ClientId, model.CashierId, model.DateOpen, model.Id);
// Для проверка на наличие такого же счёта //для проверка на наличие такого же счёта
var element = _accountStorage.GetElement(new AccountSearchModel var element = _accountStorage.GetElement(new AccountSearchModel
{ {
AccountNumber = model.AccountNumber, AccountNumber = model.AccountNumber,
}); });
// Если элемент найден и его Id не совпадает с Id переданного объекта //если элемент найден и его Id не совпадает с Id переданного объекта
if (element != null && element.Id != model.Id) if (element != null && element.Id != model.Id)
{ {
throw new InvalidOperationException("Счёт с таким номером уже существует"); throw new InvalidOperationException("Счёт с таким номером уже существует");

View File

@ -2,19 +2,14 @@
using BankContracts.BindingModels.Client; using BankContracts.BindingModels.Client;
using BankContracts.BusinessLogicsContracts.Cashier; using BankContracts.BusinessLogicsContracts.Cashier;
using BankContracts.SearchModels.Cashier; using BankContracts.SearchModels.Cashier;
using BankContracts.StoragesModels.Cashier; using BankContracts.StoragesContracts.Cashier;
using BankContracts.StoragesModels.Client; using BankContracts.StoragesContracts.Client;
using BankContracts.ViewModels.Cashier.ViewModels; using BankContracts.ViewModels.Cashier.ViewModels;
using BankDataModels.Enums;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.BusinessLogic.Cashier namespace BankBusinessLogic.BusinessLogics.Cashier
{ {
// Класс, реализующий бизнес-логику для снятия наличных
public class CashWithdrawalLogic : ICashWithdrawalLogic public class CashWithdrawalLogic : ICashWithdrawalLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
@ -23,15 +18,14 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
private readonly IDebitingStorage _debitingStorage; private readonly IDebitingStorage _debitingStorage;
// Конструктор public CashWithdrawalLogic(ILogger<CashWithdrawalLogic> logger, ICashWithdrawalStorage cashWithdrawalStorage,
public CashWithdrawalLogic(ILogger<CashWithdrawalLogic> logger, ICashWithdrawalStorage cashWithdrawalStorage, IDebitingStorage debitingStorage) IDebitingStorage debitingStorage)
{ {
_logger = logger; _logger = logger;
_cashWithdrawalStorage = cashWithdrawalStorage; _cashWithdrawalStorage = cashWithdrawalStorage;
_debitingStorage = debitingStorage; _debitingStorage = debitingStorage;
} }
// Вывод конкретной операции
public CashWithdrawalViewModel? ReadElement(CashWithdrawalSearchModel model) public CashWithdrawalViewModel? ReadElement(CashWithdrawalSearchModel model)
{ {
if (model == null) if (model == null)
@ -39,8 +33,8 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
_logger.LogInformation("ReadElement. AccountId:{AccountId}. Sum:{Sum}. DateWithdrawal:{DateWithdrawal}. Id:{Id}", _logger.LogInformation("ReadElement. AccountId:{AccountId}. Sum:{Sum}. DateOperation:{DateOperation}. Id:{Id}",
model.AccountId, model.Sum, model.DateWithdrawal, model?.Id); model.AccountId, model.Sum, model.DateTo, model?.Id);
var element = _cashWithdrawalStorage.GetElement(model); var element = _cashWithdrawalStorage.GetElement(model);
@ -56,13 +50,12 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return element; return element;
} }
// Вывод всего списка операций
public List<CashWithdrawalViewModel>? ReadList(CashWithdrawalSearchModel? model) public List<CashWithdrawalViewModel>? ReadList(CashWithdrawalSearchModel? model)
{ {
_logger.LogInformation("ReadElement. AccountId:{AccountId}. Sum:{Sum}. DateWithdrawal:{DateWithdrawal}. Id:{Id}", _logger.LogInformation("ReadElement. AccountId:{AccountId}. Sum:{Sum}. DateOperation:{DateOperation}. Id:{Id}",
model?.AccountId, model?.Sum, model?.DateWithdrawal, model?.Id); model?.AccountId, model?.Sum, model?.DateTo, model?.Id);
// list хранит весь список в случае, если model пришло со значением null на вход метода //list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _cashWithdrawalStorage.GetFullList() : _cashWithdrawalStorage.GetFilteredList(model); var list = model == null ? _cashWithdrawalStorage.GetFullList() : _cashWithdrawalStorage.GetFilteredList(model);
if (list == null) if (list == null)
@ -76,7 +69,6 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return list; return list;
} }
// Создание операции
public bool Create(CashWithdrawalBindingModel model, bool flag) public bool Create(CashWithdrawalBindingModel model, bool flag)
{ {
CheckModel(model); CheckModel(model);
@ -93,6 +85,8 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
_debitingStorage.Update(new DebitingBindingModel _debitingStorage.Update(new DebitingBindingModel
{ {
Id = model.DebitingId, Id = model.DebitingId,
DateClose = DateTime.Now,
Status = StatusEnum.Закрыта
}); });
} }
else else
@ -100,13 +94,14 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
_debitingStorage.Update(new DebitingBindingModel _debitingStorage.Update(new DebitingBindingModel
{ {
Id = model.DebitingId, Id = model.DebitingId,
DateClose = DateTime.Now,
Status = StatusEnum.Отклонено
}); });
} }
return true; return true;
} }
// Обновление операции
public bool Update(CashWithdrawalBindingModel model) public bool Update(CashWithdrawalBindingModel model)
{ {
CheckModel(model); CheckModel(model);
@ -121,7 +116,6 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return true; return true;
} }
// Удаление операции
public bool Delete(CashWithdrawalBindingModel model) public bool Delete(CashWithdrawalBindingModel model)
{ {
CheckModel(model, false); CheckModel(model, false);
@ -138,7 +132,7 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return true; return true;
} }
// Проверка входного аргумента для методов Insert, Update и Delete //проверка входного аргумента для методов Insert, Update и Delete
private void CheckModel(CashWithdrawalBindingModel model, bool withParams = true) private void CheckModel(CashWithdrawalBindingModel model, bool withParams = true)
{ {
if (model == null) if (model == null)
@ -146,32 +140,32 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
// Так как при удалении передаём как параметр false //так как при удалении передаём как параметр false
if (!withParams) if (!withParams)
{ {
return; return;
} }
// Проверка на корректность Id счёта //проверка на корректность Id счёта
if (model.AccountId < 0) if (model.AccountId < 0)
{ {
throw new ArgumentNullException("Некорректный Id счёта", nameof(model.AccountId)); throw new ArgumentNullException("Некорректный Id счёта", nameof(model.AccountId));
} }
// Проверка на корректность снимаемой суммы //проверка на корректность снимаемой суммы
if (model.Sum <= 0) if (model.Sum <= 0)
{ {
throw new ArgumentNullException("Снимаемая сумма не может раняться нулю или быть меньше его", nameof(model.Sum)); throw new ArgumentNullException("Снимаемая сумма не может раняться нулю или быть меньше его", nameof(model.Sum));
} }
// Проверка на корректную дату операции //проверка на корректную дату операции
if (model.DateWithdrawal > DateTime.Now) if (model.DateOperation > DateTime.Now)
{ {
throw new ArgumentNullException("Дата операции не может быть позднее текущей", nameof(model.DateWithdrawal)); throw new ArgumentNullException("Дата операции не может быть позднее текущей", nameof(model.DateOperation));
} }
_logger.LogInformation("CashWithdrawal: AccountId:{AccountId}. Sum:{Sum}. DateWithdrawal:{DateWithdrawal}. Id:{Id}", _logger.LogInformation("CashWithdrawal: AccountId:{AccountId}. Sum:{Sum}. DateOperation:{DateOperation}. Id:{Id}",
model.AccountId, model.Sum, model.DateWithdrawal, model?.Id); model.AccountId, model.Sum, model.DateOperation, model?.Id);
} }
} }
} }

View File

@ -1,33 +1,24 @@
using BankContracts.BindingModels.Cashier; using BankContracts.BindingModels.Cashier;
using BankContracts.BindingModels.Client;
using BankContracts.BusinessLogicsContracts.Cashier; using BankContracts.BusinessLogicsContracts.Cashier;
using BankContracts.SearchModels.Cashier; using BankContracts.SearchModels.Cashier;
using BankContracts.StoragesModels.Cashier; using BankContracts.StoragesContracts.Cashier;
using BankContracts.ViewModels.Cashier.ViewModels; using BankContracts.ViewModels.Cashier.ViewModels;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.BusinessLogic.Cashier namespace BankBusinessLogic.BusinessLogics.Cashier
{ {
// Класс, реализующий бизнес-логику для кассиров
public class CashierLogic : ICashierLogic public class CashierLogic : ICashierLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly ICashierStorage _cashierStorage; private readonly ICashierStorage _cashierStorage;
// Конструктор
public CashierLogic(ILogger<CashierLogic> logger, ICashierStorage cashierStorage) public CashierLogic(ILogger<CashierLogic> logger, ICashierStorage cashierStorage)
{ {
_logger = logger; _logger = logger;
_cashierStorage = cashierStorage; _cashierStorage = cashierStorage;
} }
// Вывод конкретного клиента
public CashierViewModel? ReadElement(CashierSearchModel model) public CashierViewModel? ReadElement(CashierSearchModel model)
{ {
if (model == null) if (model == null)
@ -43,20 +34,21 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
if (element == null) if (element == null)
{ {
_logger.LogWarning("ReadElement element not found"); _logger.LogWarning("ReadElement element not found");
return null; return null;
} }
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id); _logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element; return element;
} }
// Вывод отфильтрованного списка
public List<CashierViewModel>? ReadList(CashierSearchModel? model) public List<CashierViewModel>? ReadList(CashierSearchModel? model)
{ {
_logger.LogInformation("ReadList. CashierName:{Name}. CashierSurname:{Surname}. CashierPatronymic:{Patronymic}. Id:{Id}", _logger.LogInformation("ReadList. CashierName:{Name}. CashierSurname:{Surname}. CashierPatronymic:{Patronymic}. Id:{Id}",
model.Name, model.Surname, model.Patronymic, model?.Id); model.Name, model.Surname, model.Patronymic, model?.Id);
// list хранит весь список в случае, если model пришло со значением null на вход метода //list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _cashierStorage.GetFullList() : _cashierStorage.GetFilteredList(model); var list = model == null ? _cashierStorage.GetFullList() : _cashierStorage.GetFilteredList(model);
if (list == null) if (list == null)
@ -70,7 +62,6 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return list; return list;
} }
// Создание кассира
public bool Create(CashierBindingModel model) public bool Create(CashierBindingModel model)
{ {
CheckModel(model); CheckModel(model);
@ -78,13 +69,13 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
if (_cashierStorage.Insert(model) == null) if (_cashierStorage.Insert(model) == null)
{ {
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Insert operation failed");
return false; return false;
} }
return true; return true;
} }
// Обновление кассира
public bool Update(CashierBindingModel model) public bool Update(CashierBindingModel model)
{ {
CheckModel(model); CheckModel(model);
@ -92,13 +83,13 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
if (_cashierStorage.Update(model) == null) if (_cashierStorage.Update(model) == null)
{ {
_logger.LogWarning("Update operation failed"); _logger.LogWarning("Update operation failed");
return false; return false;
} }
return true; return true;
} }
// Удаление кассира
public bool Delete(CashierBindingModel model) public bool Delete(CashierBindingModel model)
{ {
CheckModel(model, false); CheckModel(model, false);
@ -115,7 +106,7 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return true; return true;
} }
// Проверка входного аргумента для методов Insert, Update и Delete //проверка входного аргумента для методов Insert, Update и Delete
private void CheckModel(CashierBindingModel model, bool withParams = true) private void CheckModel(CashierBindingModel model, bool withParams = true)
{ {
if (model == null) if (model == null)
@ -123,59 +114,53 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
// Так как при удалении передаём как параметр false //так как при удалении передаём как параметр false
if (!withParams) if (!withParams)
{ {
return; return;
} }
// Проверка на наличие имени //проверка на наличие имени
if (string.IsNullOrEmpty(model.Name)) if (string.IsNullOrEmpty(model.Name))
{ {
throw new ArgumentNullException("Отсутствие имени в учётной записи", nameof(model.Name)); throw new ArgumentNullException("Отсутствие имени в учётной записи", nameof(model.Name));
} }
// Проверка на наличие фамилия //проверка на наличие фамилия
if (string.IsNullOrEmpty(model.Surname)) if (string.IsNullOrEmpty(model.Surname))
{ {
throw new ArgumentNullException("Отсутствие фамилии в учётной записи", nameof(model.Surname)); throw new ArgumentNullException("Отсутствие фамилии в учётной записи", nameof(model.Name));
} }
// Проверка на наличие отчество //проверка на наличие отчество
if (string.IsNullOrEmpty(model.Patronymic)) if (string.IsNullOrEmpty(model.Patronymic))
{ {
throw new ArgumentNullException("Отсутствие отчества в учётной записи", nameof(model.Patronymic)); throw new ArgumentNullException("Отсутствие отчества в учётной записи", nameof(model.Name));
} }
// Проверка на наличие почты //проверка на наличие почты
if (string.IsNullOrEmpty(model.Email)) if (string.IsNullOrEmpty(model.Email))
{ {
throw new ArgumentNullException("Отсутствие почты в учётной записи (логина)", nameof(model.Email)); throw new ArgumentNullException("Отсутствие почты в учётной записи (логина)", nameof(model.Email));
} }
// Проверка на наличие пароля //проверка на наличие пароля
if (string.IsNullOrEmpty(model.Password)) if (string.IsNullOrEmpty(model.Password))
{ {
throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password)); throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password));
} }
// Проверка на мобильный телефон
if (string.IsNullOrEmpty(model.MobilePhone))
{
throw new ArgumentNullException("Отсутствие почты в учётной записи (логина)", nameof(model.MobilePhone));
}
_logger.LogInformation("Cashier. CashierName:{Name}. CashierSurname:{Surname}. CashierPatronymic:{Patronymic}. " + _logger.LogInformation("Cashier. CashierName:{Name}. CashierSurname:{Surname}. CashierPatronymic:{Patronymic}. " +
"Email:{Email}. Password:{Password}. MobilePhone:{MobilePhone} Id:{Id}", "Email:{Email}. Password:{Password}. Id:{Id}",
model.Name, model.Surname, model.Patronymic, model.Email, model.Password, model.MobilePhone, model.Id); model.Name, model.Surname, model.Patronymic, model.Email, model.Password, model.Id);
// Для проверка на наличие такого же аккаунта //для проверка на наличие такого же аккаунта
var element = _cashierStorage.GetElement(new CashierSearchModel var element = _cashierStorage.GetElement(new CashierSearchModel
{ {
Email = model.Email, Email = model.Email,
}); });
// Если элемент найден и его Id не совпадает с Id переданного объекта //если элемент найден и его Id не совпадает с Id переданного объекта
if (element != null && element.Id != model.Id) if (element != null && element.Id != model.Id)
{ {
throw new InvalidOperationException("Аккаунт с таким логином уже есть"); throw new InvalidOperationException("Аккаунт с таким логином уже есть");

View File

@ -2,19 +2,14 @@
using BankContracts.BindingModels.Client; using BankContracts.BindingModels.Client;
using BankContracts.BusinessLogicsContracts.Cashier; using BankContracts.BusinessLogicsContracts.Cashier;
using BankContracts.SearchModels.Cashier; using BankContracts.SearchModels.Cashier;
using BankContracts.StoragesModels.Cashier; using BankContracts.StoragesContracts.Cashier;
using BankContracts.StoragesModels.Client; using BankContracts.StoragesContracts.Client;
using BankContracts.ViewModels.Cashier.ViewModels; using BankContracts.ViewModels.Cashier.ViewModels;
using BankDataModels.Enums;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.BusinessLogic.Cashier namespace BankBusinessLogic.BusinessLogics.Cashier
{ {
// Класс, реализующий бизнес-логику для перевода наличных
public class MoneyTransferLogic : IMoneyTransferLogic public class MoneyTransferLogic : IMoneyTransferLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
@ -23,7 +18,6 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
public readonly ICreditingStorage _creditingStorage; public readonly ICreditingStorage _creditingStorage;
// Конструктор
public MoneyTransferLogic(ILogger<MoneyTransferLogic> logger, IMoneyTransferStorage moneyTransferStorage, ICreditingStorage creditingStorage) public MoneyTransferLogic(ILogger<MoneyTransferLogic> logger, IMoneyTransferStorage moneyTransferStorage, ICreditingStorage creditingStorage)
{ {
_logger = logger; _logger = logger;
@ -31,7 +25,6 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
_creditingStorage = creditingStorage; _creditingStorage = creditingStorage;
} }
// Вывод конкретной операции
public MoneyTransferViewModel? ReadElement(MoneyTransferSearchModel model) public MoneyTransferViewModel? ReadElement(MoneyTransferSearchModel model)
{ {
if (model == null) if (model == null)
@ -56,13 +49,12 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return element; return element;
} }
// Вывод всего списка операций на перевод наличных
public List<MoneyTransferViewModel>? ReadList(MoneyTransferSearchModel? model) public List<MoneyTransferViewModel>? ReadList(MoneyTransferSearchModel? model)
{ {
_logger.LogInformation("ReadElement. AccountSenderId:{AccountSenderId}. AccountPayeeId:{AccountPayeeId}. Sum:{Sum}. Id:{Id}", _logger.LogInformation("ReadElement. AccountSenderId:{AccountSenderId}. AccountPayeeId:{AccountPayeeId}. Sum:{Sum}. Id:{Id}",
model?.AccountSenderId, model?.AccountPayeeId, model?.Sum, model?.Id); model?.AccountSenderId, model?.AccountPayeeId, model?.Sum, model?.Id);
// list хранит весь список в случае, если model пришло со значением null на вход метода //list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _moneyTransferStorage.GetFullList() : _moneyTransferStorage.GetFilteredList(model); var list = model == null ? _moneyTransferStorage.GetFullList() : _moneyTransferStorage.GetFilteredList(model);
if (list == null) if (list == null)
@ -76,7 +68,6 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return list; return list;
} }
// Создание операции на перевод
public bool Create(MoneyTransferBindingModel model) public bool Create(MoneyTransferBindingModel model)
{ {
CheckModel(model); CheckModel(model);
@ -88,12 +79,14 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return false; return false;
} }
// Проверка на то, что это зачисление на карту, а не перевод между счетами //проверка на то, что это зачисление на карту, а не перевод между счетами
if (model.CreditingId.HasValue) if (model.CreditingId.HasValue)
{ {
_creditingStorage.Update(new CreditingBindingModel _creditingStorage.Update(new CreditingBindingModel
{ {
Id = model.CreditingId.Value, Id = model.CreditingId.Value,
DateClose = DateTime.Now,
Status = StatusEnum.Закрыта
}); });
} }
@ -101,7 +94,6 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return true; return true;
} }
// Обновление операции на перевод
public bool Update(MoneyTransferBindingModel model) public bool Update(MoneyTransferBindingModel model)
{ {
CheckModel(model); CheckModel(model);
@ -116,7 +108,6 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return true; return true;
} }
// Удаление операции на перевод
public bool Delete(MoneyTransferBindingModel model) public bool Delete(MoneyTransferBindingModel model)
{ {
CheckModel(model, false); CheckModel(model, false);
@ -133,7 +124,7 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
return true; return true;
} }
// Проверка входного аргумента для методов Insert, Update и Delete //проверка входного аргумента для методов Insert, Update и Delete
private void CheckModel(MoneyTransferBindingModel model, bool withParams = true) private void CheckModel(MoneyTransferBindingModel model, bool withParams = true)
{ {
if (model == null) if (model == null)
@ -141,38 +132,38 @@ namespace BankBusinessLogic.BusinessLogic.Cashier
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
// Так как при удалении передаём как параметр false //так как при удалении передаём как параметр false
if (!withParams) if (!withParams)
{ {
return; return;
} }
// Проверка корректности Id счёта отправителя //проверка корректности Id счёта отправителя
if (model.AccountSenderId < 0) if (model.AccountSenderId < 0)
{ {
throw new ArgumentNullException("Отсутствие Id у счёта отправителя", nameof(model.AccountSenderId)); throw new ArgumentNullException("Отсутствие Id у счёта отправителя", nameof(model.AccountSenderId));
} }
// Проверка корректности Id счёта получателя //проверка корректности Id счёта получателя
if (model.AccountPayeeId < 0) if (model.AccountPayeeId < 0)
{ {
throw new ArgumentNullException("Отсутствие Id у счёта получателя", nameof(model.AccountPayeeId)); throw new ArgumentNullException("Отсутствие Id у счёта получателя", nameof(model.AccountPayeeId));
} }
// Проверка на корректную сумму перевода //проверка на корректную сумму перевода
if (model.Sum <= 0) if (model.Sum <= 0)
{ {
throw new ArgumentNullException("Сумма перевода не может раняться нулю или быть меньше его", nameof(model.Sum)); throw new ArgumentNullException("Сумма перевода не может раняться нулю или быть меньше его", nameof(model.Sum));
} }
// Проверка на корректную дату открытия счёта //проверка на корректную дату открытия счёта
if (model.DateTransfer > DateTime.Now) if (model.DateOperation > DateTime.Now)
{ {
throw new ArgumentNullException("Дата операции не может быть ранее текущей", nameof(model.DateTransfer)); throw new ArgumentNullException("Дата операции не может быть ранее текущей", nameof(model.DateOperation));
} }
_logger.LogInformation("ReadElement. AccountSenderId:{AccountSenderId}. AccountPayeeId:{AccountPayeeId}. Sum:{Sum}. DateTransfer:{DateTransfer}. Id:{Id}", _logger.LogInformation("ReadElement. AccountSenderId:{AccountSenderId}. AccountPayeeId:{AccountPayeeId}. Sum:{Sum}. DateOperation:{DateOperation}. Id:{Id}",
model.AccountSenderId, model.AccountPayeeId, model.Sum, model.DateTransfer, model?.Id); model.AccountSenderId, model.AccountPayeeId, model.Sum, model.DateOperation, model?.Id);
} }
} }
} }

View File

@ -1,36 +1,26 @@
using BankContracts.BindingModels.Client; using Microsoft.Extensions.Logging;
using BankContracts.BusinessLogicsContracts.Cashier; using BankContracts.ViewModels.Client.Diagram;
using BankDataModels.Enums;
using BankContracts.BusinessLogicsContracts.Client; using BankContracts.BusinessLogicsContracts.Client;
using BankContracts.SearchModels.Cashier; using BankContracts.StoragesContracts.Client;
using BankContracts.BusinessLogicsContracts.Cashier;
using BankContracts.BindingModels.Client;
using BankContracts.SearchModels.Client; using BankContracts.SearchModels.Client;
using BankContracts.StoragesModels.Client;
using BankContracts.ViewModels.Client.ViewModels; using BankContracts.ViewModels.Client.ViewModels;
using Microsoft.Extensions.Logging; using BankContracts.SearchModels.Cashier;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.BusinessLogic.Client namespace BankBusinessLogic.BusinessLogics.Client
{ {
// Класс, реализующий бизнес-логику для банковских карт
public class CardLogic : ICardLogic public class CardLogic : ICardLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly ICardStorage _cardStorage; private readonly ICardStorage _cardStorage;
private readonly IAccountLogic _accountLogic; private readonly IAccountLogic _accountLogic;
private readonly IDebitingLogic _debitingLogic; private readonly IDebitingLogic _debitingLogic;
private readonly ICreditingLogic _creditingLogic; private readonly ICreditingLogic _creditingLogic;
// Конструктор
public CardLogic(ILogger<CardLogic> logger, ICardStorage cardStorage, IAccountLogic accountLogic, public CardLogic(ILogger<CardLogic> logger, ICardStorage cardStorage, IAccountLogic accountLogic,
IDebitingLogic debitingLogic, ICreditingLogic creditingLogic) IDebitingLogic debitingLogic, ICreditingLogic creditingLogic) {
{
_logger = logger; _logger = logger;
_cardStorage = cardStorage; _cardStorage = cardStorage;
_accountLogic = accountLogic; _accountLogic = accountLogic;
@ -38,137 +28,122 @@ namespace BankBusinessLogic.BusinessLogic.Client
_creditingLogic = creditingLogic; _creditingLogic = creditingLogic;
} }
// Вывод конкретной банковской карты public bool Create(CardBindingModel model)
{
CheckModel(model);
if (_cardStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Delete(CardBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_cardStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public CardViewModel? ReadElement(CardSearchModel model) public CardViewModel? ReadElement(CardSearchModel model)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
_logger.LogInformation("ReadElement. CardNumber:{Number}.Id:{ Id}", model.Number, model.Id); _logger.LogInformation("ReadElement. CardNumber:{Number}.Id:{ Id}", model.Number, model.Id);
var element = _cardStorage.GetElement(model); var element = _cardStorage.GetElement(model);
if (element == null) if (element == null)
{ {
_logger.LogWarning("ReadElement element not found"); _logger.LogWarning("ReadElement element not found");
return null; return null;
} }
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id); _logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element; return element;
} }
// Вывод всего списка банковских карт
public List<CardViewModel>? ReadList(CardSearchModel? model) public List<CardViewModel>? ReadList(CardSearchModel? model)
{ {
_logger.LogInformation("ReadList. CardId:{Id}", model?.Id); _logger.LogInformation("ReadList. CardId:{Id}", model?.Id);
// list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _cardStorage.GetFullList() : _cardStorage.GetFilteredList(model); var list = model == null ? _cardStorage.GetFullList() : _cardStorage.GetFilteredList(model);
if (list == null) if (list == null)
{ {
_logger.LogWarning("ReadList return null list"); _logger.LogWarning("ReadList return null list");
return null; return null;
} }
_logger.LogInformation("ReadList. Count:{Count}", list.Count); _logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list; return list;
} }
// Создание банковской карты
public bool Create(CardBindingModel model)
{
CheckModel(model);
if (_cardStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
// Обновление банковской карты
public bool Update(CardBindingModel model) public bool Update(CardBindingModel model)
{ {
CheckModel(model); CheckModel(model);
if (_cardStorage.Update(model) == null) if (_cardStorage.Update(model) == null)
{ {
_logger.LogWarning("Update operation failed"); _logger.LogWarning("Update operation failed");
return false; return false;
} }
return true; return true;
} }
// Удаление банковской карты public List<ClientDiagramElementsViewModel> GetMonthInfo(int CardId) {
public bool Delete(CardBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id); Dictionary<(int?, int?), int> debitings = _debitingLogic.ReadList(new DebitingSearchModel()
if (_cardStorage.Delete(model) == null)
{ {
_logger.LogWarning("Delete operation failed"); CardId = CardId,
return false; Status = StatusEnum.Закрыта
}).GroupBy(x => new { x.DateClose?.Month, x.DateClose?.Year })
.Select(x => new { x.Key.Month, x.Key.Year, Sum = x.Select(y => y.Sum).Sum()}).ToDictionary(x => (x.Month, x.Year), x => (x.Sum));
Dictionary<(int?, int?), int> creditings = _creditingLogic.ReadList(new CreditingSearchModel()
{
CardId = CardId,
Status = StatusEnum.Закрыта
}).GroupBy(x => new { x.DateClose?.Month, x.DateClose?.Year })
.Select(x => new { x.Key.Month, x.Key.Year, Sum = x.Select(y => y.Sum).Sum() }).ToDictionary(x => (x.Month, x.Year), x => (x.Sum));
List<ClientDiagramElementsViewModel> result = new();
foreach (var key in debitings.Keys.Union(creditings.Keys).OrderBy(x => x.Item1 * 12 + x.Item2)) {
int sum = 0;
if (debitings.ContainsKey(key)) sum -= debitings.GetValueOrDefault(key);
if (creditings.ContainsKey(key)) sum += creditings.GetValueOrDefault(key);
result.Add(new ClientDiagramElementsViewModel() { Name = Enum.GetName(typeof(Months), key.Item1) + " " + key.Item2.ToString(), Value = sum});
}
return result;
} }
return true;
}
// Проверка входного аргумента для методов Insert, Update и Delete
private void CheckModel(CardBindingModel model, bool withParams = true) private void CheckModel(CardBindingModel model, bool withParams = true)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
// Так как при удалении передаём как параметр false
if (!withParams) if (!withParams)
{ {
return; return;
} }
// Проверка на наличие номера у банковской карты
if (string.IsNullOrEmpty(model.Number) || model.Number.Length != 16) if (string.IsNullOrEmpty(model.Number) || model.Number.Length != 16)
{ {
throw new ArgumentNullException("Неправильный номер карты", nameof(model.Number)); throw new ArgumentNullException("Неправильный номер карты", nameof(model.Number));
} }
if (string.IsNullOrEmpty(model.CVC) || model.CVC.Length != 3)
// Проверка баланса банковской карты (чтобы не было отрицательным)
if (model.Balance < 0)
{ {
throw new ArgumentNullException("Изначальный баланс карты не может быть < 0", nameof(model.Balance)); throw new ArgumentNullException("Неправильный СVC карты", nameof(model.CVC));
} }
// Проверка на конкретный период действия карты
if (model.Period < DateTime.Now) if (model.Period < DateTime.Now)
{ {
throw new ArgumentNullException("Нет периода действия", nameof(model.Period)); throw new ArgumentNullException("Нет периода действия", nameof(model.Period));
} }
// Проверка на наличие id клиента, получившего карту (лишним не будет)
if (model.ClientId < 0)
{
throw new ArgumentNullException("Некорректный Id кассира, открывшего счёт", nameof(model.ClientId));
}
// Для проверка на наличие такой же банковской карты
var cardElement = _cardStorage.GetElement(new CardSearchModel var cardElement = _cardStorage.GetElement(new CardSearchModel
{ {
Number = model.Number, Number = model.Number,
}); });
// Если элемент найден и его Id не совпадает с Id переданного объекта
if (cardElement != null && cardElement.Id != model.Id) if (cardElement != null && cardElement.Id != model.Id)
{ {
throw new InvalidOperationException("Карта с таким ноиером уже есть"); throw new InvalidOperationException("Карта с таким ноиером уже есть");
@ -177,17 +152,16 @@ namespace BankBusinessLogic.BusinessLogic.Client
var accountElement = _accountLogic.ReadElement(new AccountSearchModel var accountElement = _accountLogic.ReadElement(new AccountSearchModel
{ {
Id = model.AccountId, Id = model.AccountId,
ClientId = model.ClientId ClientId = model.ClientID
}); });
// Проверка привязан ли счёт к данному клиенту if (accountElement != null && accountElement.ClientId != model.ClientID)
if (accountElement != null && accountElement.ClientId != model.ClientId)
{ {
throw new InvalidOperationException("Это не счёт данного клиента"); throw new InvalidOperationException("Это не счёт данного клиента");
} }
_logger.LogInformation("Card. Number:{Number}.ClientId:{ClientID}.Patronymic:{Period}.Id:{Id}", _logger.LogInformation("Card. Number:{Number}.CVC:{CVC}.ClientId:{ClientID}.Patronymic:{Period}.Id:{Id}",
model.Number, model.Period.ToString(), model.ClientId, model.Id); model.Number, model.CVC, model.Period.ToString(), model.ClientID, model.Id);
} }
} }
} }

View File

@ -1,186 +1,126 @@
using BankContracts.BindingModels.Client; using BankContracts.BindingModels.Client;
using BankContracts.BusinessLogicsContracts.Client; using BankContracts.BusinessLogicsContracts.Client;
using BankContracts.SearchModels.Client; using BankContracts.SearchModels.Client;
using BankContracts.StoragesModels.Client; using BankContracts.StoragesContracts.Client;
using BankContracts.ViewModels.Client.ViewModels; using BankContracts.ViewModels.Client.ViewModels;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace BankBusinessLogic.BusinessLogic.Client namespace BankBusinessLogic.BusinessLogics.Client
{ {
// Класс, реализующий бизнес-логику для клиентов
public class ClientLogic : IClientLogic public class ClientLogic : IClientLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IClientStorage _clientStorage; private readonly IClientStorage _clientStorage;
// Конструктор public ClientLogic(ILogger<ClientLogic> logger, IClientStorage clientStorage) {
public ClientLogic(ILogger<ClientLogic> logger, IClientStorage clientStorage)
{
_logger = logger; _logger = logger;
_clientStorage = clientStorage; _clientStorage = clientStorage;
} }
// Вывод конкретного клиента public bool Create(ClientBindingModel model)
{
CheckModel(model);
if (_clientStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Delete(ClientBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_clientStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public ClientViewModel? ReadElement(ClientSearchModel model) public ClientViewModel? ReadElement(ClientSearchModel model)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
_logger.LogInformation("ReadElement. Name:{Name}.Surname:{Surname}.Patronymic:{Patronymic}.Id:{ Id}", model.Name, model.Surname, model.Patronymic, model.Id);
_logger.LogInformation("ReadElement. Name:{Name}.Surname:{Surname}.Patronymic:{Patronymic}.Id:{Id}", model.Name, model.Surname, model.Patronymic, model.Id);
var element = _clientStorage.GetElement(model); var element = _clientStorage.GetElement(model);
if (element == null) if (element == null)
{ {
_logger.LogWarning("Read element not found"); _logger.LogWarning("ReadElement element not found");
return null; return null;
} }
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id); _logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element; return element;
} }
// Вывод отфильтрованного списка public List<ClientViewModel>? ReadList(ClientSearchModel? model)
public List<ClientViewModel>? ReadList(ClientSearchModel model)
{ {
_logger.LogInformation("ReadList. ClientId:{Id}", model?.Id); _logger.LogInformation("ReadList. ClientId:{Id}", model?.Id);
// list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model); var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model);
if (list == null) if (list == null)
{ {
_logger.LogWarning("ReadList return null list"); _logger.LogWarning("ReadList return null list");
return null; return null;
} }
_logger.LogInformation("ReadList. Count:{Count}", list.Count); _logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list; return list;
} }
// Создание клиента
public bool Create(ClientBindingModel model)
{
CheckModel(model);
if (_clientStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
// Обновление клиента
public bool Update(ClientBindingModel model) public bool Update(ClientBindingModel model)
{ {
CheckModel(model); CheckModel(model);
if (_clientStorage.Update(model) == null) if (_clientStorage.Update(model) == null)
{ {
_logger.LogWarning("Update operation failed"); _logger.LogWarning("Update operation failed");
return false; return false;
} }
return true; return true;
} }
// Удаление клиента private void CheckModel(ClientBindingModel model, bool withParams = true)
public bool Delete(ClientBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_clientStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
// Проверка входного аргумента для методов Insert, Update и Delete
public void CheckModel(ClientBindingModel model, bool withParams = true)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
// При удалении параметру withParams передаём false
if (!withParams) if (!withParams)
{ {
return; return;
} }
// Проверка на наличие имени клиента
if (string.IsNullOrEmpty(model.Name)) if (string.IsNullOrEmpty(model.Name))
{ {
throw new ArgumentNullException("Нет имени пользователя", nameof(model.Name)); throw new ArgumentNullException("Нет имени пользователя", nameof(model.Name));
} }
// Проверка на наличие фамилии клиента
if (string.IsNullOrEmpty(model.Surname)) if (string.IsNullOrEmpty(model.Surname))
{ {
throw new ArgumentNullException("Нет фамилии пользователя", nameof(model.Surname)); throw new ArgumentNullException("Нет фамилии пользователя", nameof(model.Surname));
} }
// Проверка на наличие отчества клиента
if (string.IsNullOrEmpty(model.Patronymic)) if (string.IsNullOrEmpty(model.Patronymic))
{ {
throw new ArgumentNullException("Нет отчества пользователя", nameof(model.Patronymic)); throw new ArgumentNullException("Нет отчества пользователя", nameof(model.Patronymic));
} }
// Проверка на наличие электронной почты
if (string.IsNullOrEmpty(model.Email)) if (string.IsNullOrEmpty(model.Email))
{ {
throw new ArgumentNullException("Нет почты пользователя", nameof(model.Email)); throw new ArgumentNullException("Нет почты пользователя", nameof(model.Email));
} }
// Проверка на наличие пароля
if (string.IsNullOrEmpty(model.Password)) if (string.IsNullOrEmpty(model.Password))
{ {
throw new ArgumentNullException("Нет пароля пользователя", nameof(model.Password)); throw new ArgumentNullException("Нет пароля пользователя", nameof(model.Password));
} }
if (string.IsNullOrEmpty(model.Telephone))
// Проверка на наличие мобильного телефона
if (string.IsNullOrEmpty(model.MobilePhone))
{ {
throw new ArgumentNullException("Нет моб.телефона пользователя", nameof(model.MobilePhone)); throw new ArgumentNullException("Нет телефона пользователя", nameof(model.Telephone));
} }
_logger.LogInformation("Client. Name:{Name}.Surname:{Surname}.Patronymic:{Patronymic}.Email:{Email}.Password:{Password}.Telephone:{Telephone}.Id:{Id}",
if (!Regex.IsMatch(model.Email, @"^[a-zA-Z0-9.!#$%&*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$", RegexOptions.IgnoreCase)) model.Name, model.Surname, model.Patronymic, model.Email, model.Password, model.Telephone, model.Id);
{
throw new ArgumentException("Некорректная почта", nameof(model.Email));
}
if (!Regex.IsMatch(model.Password, @"^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$", RegexOptions.IgnoreCase)
&& model.Password.Length < 10 && model.Password.Length > 50)
{
throw new ArgumentException("Необходимо придумать другой пароль", nameof(model.Password));
}
_logger.LogInformation("Client. Name:{Name}.Surname:{Surname}.Patronymic:{Patronymic}.Email:{Email}.Password:{Password}.Mobeliphone:{MobilePhone}.Id:{Id}",
model.Name, model.Surname, model.Patronymic, model.Email, model.Password, model.MobilePhone, model.Id);
// Для проверка на наличие такого же аккаунта
var element = _clientStorage.GetElement(new ClientSearchModel var element = _clientStorage.GetElement(new ClientSearchModel
{ {
Email = model.Email, Email = model.Email,
}); });
// Если элемент найден и его Id не совпадает с Id переданного объекта
if (element != null && element.Id != model.Id) if (element != null && element.Id != model.Id)
{ {
throw new InvalidOperationException("Клиент с такой почтой уже есть"); throw new InvalidOperationException("Клиент с такой почтой уже есть");

View File

@ -1,81 +1,38 @@
using BankContracts.BindingModels.Client; using Microsoft.Extensions.Logging;
using BankDataModels.Enums;
using BankContracts.BusinessLogicsContracts.Client; using BankContracts.BusinessLogicsContracts.Client;
using BankContracts.SearchModels.Client; using BankContracts.StoragesContracts.Client;
using BankContracts.StoragesModels.Client; using BankContracts.BindingModels.Client;
using BankContracts.ViewModels.Client.ViewModels; using BankContracts.ViewModels.Client.ViewModels;
using Microsoft.Extensions.Logging; using BankContracts.SearchModels.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.BusinessLogic.Client namespace BankBusinessLogic.BusinessLogics.Client
{ {
// Класс, реализующий бизнес-логику для пополнения карты
public class CreditingLogic : ICreditingLogic public class CreditingLogic : ICreditingLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly ICreditingStorage _creditingStorage; private readonly ICreditingStorage _creditingStorage;
private readonly ICardStorage _cardStorage; private readonly ICardStorage _cardStorage;
// Конструктор public CreditingLogic(ILogger<CreditingLogic> logger, ICreditingStorage creditingStorage, ICardStorage cardStorage) {
public CreditingLogic(ILogger<CreditingLogic> logger, ICreditingStorage creditingStorage, ICardStorage cardStorage)
{
_logger = logger; _logger = logger;
_creditingStorage = creditingStorage; _creditingStorage = creditingStorage;
_cardStorage = cardStorage; _cardStorage = cardStorage;
} }
// Вывод конкретной операции на пополнение
public CreditingViewModel? ReadElement(CreditingSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. CreditingId:{ Id }", model.Id);
var element = _creditingStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
// Вывод всего списка операций на пополнение
public List<CreditingViewModel>? ReadList(CreditingSearchModel? model)
{
_logger.LogInformation("ReadList. CreditingId:{Id}", model?.Id);
// list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _creditingStorage.GetFullList() : _creditingStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
// Создание операции на пополнение
public bool Create(CreditingBindingModel model) public bool Create(CreditingBindingModel model)
{ {
CheckModel(model); CheckModel(model);
if (!CheckCardPeriod(model))
{
model.Status = StatusEnum.Карта_просрочена;
}
else
{
model.Status = StatusEnum.Открыта;
}
if (_creditingStorage.Insert(model) == null) if (_creditingStorage.Insert(model) == null)
{ {
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Insert operation failed");
@ -86,70 +43,98 @@ namespace BankBusinessLogic.BusinessLogic.Client
return true; return true;
} }
// Обновление операции на пополнение
public bool Update(CreditingBindingModel model)
{
CheckModel(model);
if (_creditingStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
// Удаление операции на пополнение
public bool Delete(CreditingBindingModel model) public bool Delete(CreditingBindingModel model)
{ {
CheckModel(model, false); CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id); _logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_creditingStorage.Delete(model) == null) if (_creditingStorage.Delete(model) == null)
{ {
_logger.LogWarning("Delete operation failed"); _logger.LogWarning("Delete operation failed");
return false; return false;
} }
return true; return true;
} }
// Проверка входного аргумента для методов Insert, Update и Delete public CreditingViewModel? ReadElement(CreditingSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. CreditingId:{ Id }", model.Id);
var element = _creditingStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public List<CreditingViewModel>? ReadList(CreditingSearchModel? model)
{
_logger.LogInformation("ReadList. CreditingId:{Id}", model?.Id);
var list = model == null ? _creditingStorage.GetFullList() : _creditingStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool Update(CreditingBindingModel model)
{
CheckModel(model);
if (_creditingStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
private void CheckModel(CreditingBindingModel model, bool withParams = true) private void CheckModel(CreditingBindingModel model, bool withParams = true)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
// Так как при удалении передаём как параметр false
if (!withParams) if (!withParams)
{ {
return; return;
} }
// Проверка на корректность Id клиента банковской карты
if (model.ClientId < 0)
{
throw new ArgumentNullException("Некорректный Id клиента", nameof(model.ClientId));
}
// Проверка на корректность суммы пополнения
if (model.Sum <= 0) if (model.Sum <= 0)
{ {
throw new ArgumentNullException("Сумма операции должна быть больше 0", nameof(model.Sum)); throw new ArgumentNullException("Сумма операции должна быть больше 0", nameof(model.Sum));
} }
if (model.DateOpen > DateTime.Now)
// Проверка на корректную дату операции
if (model.DateCredit > DateTime.Now)
{ {
throw new ArgumentNullException("Дата не может быть меньше текущего времени", nameof(model.DateCredit)); throw new ArgumentNullException("Дата не может быть меньше текущего времени", nameof(model.DateOpen));
} }
_logger.LogInformation("Crediting. Sum:{Sum}.CardId:{CardId}.Date:{date}.Id:{Id}", _logger.LogInformation("Crediting. Sum:{Sum}.CardId:{CardId}.Date:{date}.Id:{Id}",
model.Sum, model.CardId, model.DateCredit.ToString(), model.Id); model.Sum, model.CardId, model.DateOpen.ToString(), model.Id);
}
//проверка карты на просроченность
bool CheckCardPeriod(CreditingBindingModel model)
{
var card = _cardStorage.GetElement(new CardSearchModel
{
Id = model.CardId
});
//если карта просрочена
if (card.Period < DateTime.Now)
{
return false;
}
return true;
} }
} }
} }

View File

@ -1,18 +1,13 @@
using BankContracts.BindingModels.Client; using Microsoft.Extensions.Logging;
using BankDataModels.Enums;
using BankContracts.BusinessLogicsContracts.Client; using BankContracts.BusinessLogicsContracts.Client;
using BankContracts.StoragesContracts.Client;
using BankContracts.BindingModels.Client;
using BankContracts.SearchModels.Client; using BankContracts.SearchModels.Client;
using BankContracts.StoragesModels.Client;
using BankContracts.ViewModels.Client.ViewModels; using BankContracts.ViewModels.Client.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.BusinessLogic.Client namespace BankBusinessLogic.BusinessLogics.Client
{ {
// Класс, реализующий бизнес-логику для снятия наличных с карты
public class DebitingLogic : IDebitingLogic public class DebitingLogic : IDebitingLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
@ -21,61 +16,25 @@ namespace BankBusinessLogic.BusinessLogic.Client
private readonly ICardStorage _cardStorage; private readonly ICardStorage _cardStorage;
// Конструктор public DebitingLogic(ILogger<DebitingLogic> logger, IDebitingStorage debitingStorage, ICardStorage cardStorage) {
public DebitingLogic(ILogger<DebitingLogic> logger, IDebitingStorage debitingStorage, ICardStorage cardStorage)
{
_logger = logger; _logger = logger;
_debitingStorage = debitingStorage; _debitingStorage = debitingStorage;
_cardStorage = cardStorage; _cardStorage = cardStorage;
} }
// Вывод конкретной операции на снятие наличных
public DebitingViewModel? ReadElement(DebitingSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. DebitingId:{ Id }", model.Id);
var element = _debitingStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
// Вывод всего списка операций на снятие наличных
public List<DebitingViewModel>? ReadList(DebitingSearchModel? model)
{
_logger.LogInformation("ReadList. DebitingId:{Id}", model?.Id);
// list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _debitingStorage.GetFullList() : _debitingStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
// Создание операции на снятие наличных
public bool Create(DebitingBindingModel model) public bool Create(DebitingBindingModel model)
{ {
CheckModel(model); CheckModel(model);
if (!CheckCardPeriod(model))
{
model.Status = StatusEnum.Карта_просрочена;
}
else
{
model.Status = StatusEnum.Открыта;
}
if (_debitingStorage.Insert(model) == null) if (_debitingStorage.Insert(model) == null)
{ {
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Insert operation failed");
@ -85,7 +44,48 @@ namespace BankBusinessLogic.BusinessLogic.Client
return true; return true;
} }
// Обновление операции на снятие наличных public bool Delete(DebitingBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_debitingStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public DebitingViewModel? ReadElement(DebitingSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. DebitingId:{ Id }", model.Id);
var element = _debitingStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public List<DebitingViewModel>? ReadList(DebitingSearchModel? model)
{
_logger.LogInformation("ReadList. DebitingId:{Id}", model?.Id);
var list = model == null ? _debitingStorage.GetFullList() : _debitingStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public bool Update(DebitingBindingModel model) public bool Update(DebitingBindingModel model)
{ {
CheckModel(model); CheckModel(model);
@ -100,56 +100,44 @@ namespace BankBusinessLogic.BusinessLogic.Client
return true; return true;
} }
// Удаление операции на снятие наличных
public bool Delete(DebitingBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_debitingStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
// Проверка входного аргумента для методов Insert, Update и Delete
private void CheckModel(DebitingBindingModel model, bool withParams = true) private void CheckModel(DebitingBindingModel model, bool withParams = true)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
// Так как при удалении передаём как параметр false
if (!withParams) if (!withParams)
{ {
return; return;
} }
// Проверка на корректность Id клиента банковской карты
if (model.ClientId < 0)
{
throw new ArgumentNullException("Некорректный Id клиента", nameof(model.ClientId));
}
// Проверка на корректность снятия суммы
if (model.Sum <= 0) if (model.Sum <= 0)
{ {
throw new ArgumentNullException("Сумма операции должна быть больше 0", nameof(model.Sum)); throw new ArgumentNullException("Сумма операции должна быть больше 0", nameof(model.Sum));
} }
if (model.DateClose < model.DateOpen)
// Проверка на корректную дату операции
if (model.DateDebit > DateTime.Now)
{ {
throw new ArgumentNullException("Дата не может быть меньше текущего времени", nameof(model.DateDebit)); throw new ArgumentNullException("Дата закрытия не может быть меньше даты открытия", nameof(model.DateClose));
} }
_logger.LogInformation("Debiting. Sum:{Sum}.CardId:{CardId}.DateDebit:{DateDebit}.Id:{Id}", _logger.LogInformation("Debiting. Sum:{Sum}.CardId:{CardId}.DateOpen:{DateOpen}.DateOpen:{DateOpen}.Id:{Id}",
model.Sum, model.CardId, model.DateDebit.ToString(), model.Id); model.Sum, model.CardId, model.DateOpen.ToString(), model.DateClose.ToString(), model.Id);
}
//проверка карты на просроченность
bool CheckCardPeriod(DebitingBindingModel model)
{
var card = _cardStorage.GetElement(new CardSearchModel
{
Id = model.CardId
});
//если карта просрочена
if (card.Period < DateTime.Now)
{
return false;
}
return true;
} }
} }
} }

View File

@ -1,85 +1,83 @@
using BankBusinessLogic.OfficePackage; using BankBusinessLogic.MailWorker;
using BankBusinessLogic.OfficePackage;
using BankBusinessLogic.OfficePackage.HelperModels; using BankBusinessLogic.OfficePackage.HelperModels;
using BankContracts.BindingModels.Reports; using BankContracts.BindingModels.Reports;
using BankContracts.BusinessLogicsContracts.Reports; using BankContracts.BusinessLogicsContracts.Reports;
using BankContracts.SearchModels.Cashier; using BankContracts.SearchModels.Cashier;
using BankContracts.SearchModels.Client; using BankContracts.SearchModels.Client;
using BankContracts.StoragesModels.Cashier; using BankContracts.StoragesContracts.Cashier;
using BankContracts.StoragesModels.Client; using BankContracts.StoragesContracts.Client;
using BankContracts.ViewModels.Client.ViewModels; using BankContracts.ViewModels.Client.ViewModels;
using BankContracts.ViewModels.Reports.Cashier;
using BankContracts.ViewModels.Reports; using BankContracts.ViewModels.Reports;
using BankDatabaseImplement.Implements.ClientImplements; using BankContracts.ViewModels.Reports.Cashier;
using BankDataModels.Enums; using BankDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.BusinessLogic.Reports namespace BankBusinessLogic.BusinessLogics.Reports
{ {
public class ReportCashierLogic : IReportCashierLogic public class ReportCashierLogic : IReportCashierLogic
{ {
private readonly IMoneyTransferStorage _moneyTransferStorage; private readonly IMoneyTransferStorage _moneyTransferStorage;
private readonly ICashWithdrawalStorage _cashWithdrawalStorage; private readonly ICashWithdrawalStorage _cashWithdrawalStorage;
private readonly IDebitingStorage _debitingStorage;
private readonly IClientStorage _clientStorage; private readonly IClientStorage _clientStorage;
private readonly IDebitingStorage _debitingStorage;
private readonly ICardStorage _cardStorage; private readonly ICardStorage _cardStorage;
private readonly AbstractSaveToExcel _saveToExcel; private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord; private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf; private readonly AbstractSaveToPdf _saveToPdf;
// Конструктор private readonly MailKitWorker _mailKitWorker;
//инициализируем поля класса через контейнер
public ReportCashierLogic(IMoneyTransferStorage moneyTransferStorage, ICashWithdrawalStorage cashWithdrawalStorage, public ReportCashierLogic(IMoneyTransferStorage moneyTransferStorage, ICashWithdrawalStorage cashWithdrawalStorage,
IDebitingStorage debitingStorage, IClientStorage clientStorage, ICardStorage cardStorage, IClientStorage clientStorage, AbstractSaveToExcel saveToExcel,
AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf) AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf,
IDebitingStorage debitingStorage, ICardStorage cardStorage, MailKitWorker mailKitWorker)
{ {
_moneyTransferStorage = moneyTransferStorage; _moneyTransferStorage = moneyTransferStorage;
_cashWithdrawalStorage = cashWithdrawalStorage; _cashWithdrawalStorage = cashWithdrawalStorage;
_debitingStorage = debitingStorage;
_clientStorage = clientStorage;
_cardStorage = cardStorage;
_saveToExcel = saveToExcel; _saveToExcel = saveToExcel;
_saveToWord = saveToWord; _saveToWord = saveToWord;
_saveToPdf = saveToPdf; _saveToPdf = saveToPdf;
_clientStorage = clientStorage;
_debitingStorage = debitingStorage;
_cardStorage = cardStorage;
_mailKitWorker = mailKitWorker;
} }
// Формирование списка переводов между счетами //формирование списка переводов между счетами за период
public List<ReportCashierViewModel>? GetMoneyTransfers(ReportBindingModel model) public List<ReportCashierViewModel>? GetMoneyTransfers(ReportBindingModel model)
{ {
return _moneyTransferStorage.GetFilteredList(new MoneyTransferSearchModel { ClientId = model.ClientId, DateTransfer = model.DateTo }) return _moneyTransferStorage.GetFilteredList(new MoneyTransferSearchModel { ClientId = model.ClientId, DateFrom = model.DateFrom, DateTo = model.DateTo})
.Select(x => new ReportCashierViewModel .Select(x => new ReportCashierViewModel
{ {
OperationId = x.Id, OperationId = x.Id,
DateComplite = x.DateTransfer, DateComplite = x.DateOperation,
AccountSenderNumber = x.AccountPayeeNumber, AccountPayeeNumber = x.AccountPayeeNumber,
AccountPayeeNumber = x.AccountSenderNumber, AccountSenderNumber = x.AccountSenderNumber,
SumOperation = x.Sum SumOperation = x.Sum
}) })
.ToList(); .ToList();
} }
// Формирование списка выдачи наличных со счёта //формирование списка выдаци наличных со счёта за период
public List<ReportCashierViewModel>? GetCashWithrawals(ReportBindingModel model) public List<ReportCashierViewModel>? GetCashWithrawals(ReportBindingModel model)
{ {
return _cashWithdrawalStorage.GetFilteredList(new CashWithdrawalSearchModel { ClientId = model.ClientId, DateWithdrawal = model.DateTo }) return _cashWithdrawalStorage.GetFilteredList(new CashWithdrawalSearchModel { ClientId = model.ClientId, DateFrom = model.DateFrom, DateTo = model.DateTo })
.Select(x => new ReportCashierViewModel .Select(x => new ReportCashierViewModel
{ {
OperationId = x.Id, OperationId = x.Id,
DebitingId = x.DebitingId, DebitingId = x.DebitingId,
AccountPayeeNumber = x.AccountNumber, AccountPayeeNumber = x.AccountNumber,
DateComplite = x.DateWithdrawal, DateComplite = x.DateOperation,
SumOperation = x.Sum SumOperation = x.Sum
}) })
.ToList(); .ToList();
} }
// Формирование списка выдачи наличных со счёта за период //формирование списка выдаци наличных со счёта за период
public List<DebitingViewModel>? GetDebitings(ReportBindingModel model) public List<DebitingViewModel>? GetDebitings(ReportBindingModel model)
{ {
List<int> CardIdList = new(); List<int> CardIdList = new();
@ -89,14 +87,14 @@ namespace BankBusinessLogic.BusinessLogic.Reports
AccountId = model.AccountId AccountId = model.AccountId
}); });
foreach (var index in list) foreach(var index in list)
{ {
CardIdList.Add(index.Id); CardIdList.Add(index.Id);
} }
List<DebitingViewModel> totalList = new(); List<DebitingViewModel> totalList = new();
foreach (var index in CardIdList) foreach(var index in CardIdList)
{ {
var result = _debitingStorage.GetFilteredList(new DebitingSearchModel var result = _debitingStorage.GetFilteredList(new DebitingSearchModel
{ {
@ -109,7 +107,7 @@ namespace BankBusinessLogic.BusinessLogic.Reports
return totalList; return totalList;
} }
// Формирование полного имени клиента для отчёта //формирование полного имени клиента для отчёта
public string GetFullName(ReportBindingModel model) public string GetFullName(ReportBindingModel model)
{ {
var client = _clientStorage.GetElement(new ClientSearchModel var client = _clientStorage.GetElement(new ClientSearchModel
@ -120,22 +118,100 @@ namespace BankBusinessLogic.BusinessLogic.Reports
return client.Surname + " " + client.Name + " " + client.Patronymic; return client.Surname + " " + client.Name + " " + client.Patronymic;
} }
// Сохранение счетов в файл-Word //Сохранение мороженных в файл-Word
public void SaveAccountsToWordFile(ReportBindingModel model) public void SaveAccountsToWordFile(ReportBindingModel model)
{ {
throw new NotImplementedException(); _saveToWord.CreateDoc(new WordInfo
{
FileName = model.FileName,
Title = "Заявки на снятия со счёта",
Debiting = GetDebitings(model)
}, OfficeOperationEnum.Дляассира);
byte[] word = System.IO.File.ReadAllBytes("../BankRestAPI/Отчёт по зявкам на снятие.docx");
File.Delete("../BankRestAPI/Отчёт по зявкам на снятие.docx");
_mailKitWorker.SendMailAsync(new()
{
MailAddress = model.Email,
Subject = "Отчёт по счетам",
Text = $"Отчёт по состоянию на {DateTime.Now.ToString()}",
File = word,
Role = model.Role,
TypeDoc = TypeDocEnum.WORD
});
} }
// Сохранение счетов в файл-Excel //Сохранение заготовок с указаеним изделий в файл-Excel
public void SaveAccountsToExcelFile(ReportBindingModel model) public void SaveAccountsToExcelFile(ReportBindingModel model)
{ {
throw new NotImplementedException(); _saveToExcel.CreateReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Заявки на счёт",
Debiting = GetDebitings(model)
}, OfficeOperationEnum.Дляассира);
byte[] excel = System.IO.File.ReadAllBytes("../BankRestAPI/Отчёт по зявкам на снятие.xlsx");
File.Delete("../BankRestAPI/Отчёт по зявкам на снятие.xlsx");
_mailKitWorker.SendMailAsync(new()
{
MailAddress = model.Email,
Subject = "Отчёт по счетам",
Text = $"Отчёт по состоянию на {DateTime.Now.ToString()}",
File = excel,
Role = model.Role,
TypeDoc = TypeDocEnum.EXCEL
});
} }
// Сохранение счетов в файл-Pdf //Сохранение заказов в файл-Pdf
public ReportCashierViewModelForHTML SaveAccountsToPdfFile(ReportBindingModel model) public ReportCashierViewModelForHTML SaveAccountsToPdfFile(ReportBindingModel model)
{ {
throw new NotImplementedException(); var listMoneyTransfers = GetMoneyTransfers(model);
var listCashWithdrawals = GetCashWithrawals(model);
_saveToPdf.CreateDoc(new PdfInfo
{
ForClient = false,
FileName = model.FileName,
FullClientName = GetFullName(model),
Title = "Отчёт по операциям списаний со счёта и переводов между счетами",
DateFrom = model.DateFrom!.Value,
DateTo = model.DateTo!.Value,
ReportMoneyTransfer = listMoneyTransfers,
ReportCashWithdrawal = listCashWithdrawals
});
byte[] pdf = System.IO.File.ReadAllBytes("../BankRestAPI/Отчёт_по_счетам.pdf");
File.Delete("../BankRestAPI/Отчёт_по_счетам.pdf");
_mailKitWorker.SendMailAsync(new()
{
MailAddress = model.Email,
Subject = "Отчёт по счетам",
Text = $"За период с {model.DateFrom} " +
$"по {model.DateTo}.",
File = pdf,
Role = model.Role,
TypeDoc = TypeDocEnum.PDF
});
//возврат полученных списков для отображения на вебе
return new ReportCashierViewModelForHTML
{
ReportCashWithdrawal = listCashWithdrawals,
ReportMoneyTransfer = listMoneyTransfers
};
} }
} }
} }

View File

@ -1,65 +1,64 @@
using BankBusinessLogic.OfficePackage; using BankBusinessLogic.OfficePackage.HelperModels;
using BankBusinessLogic.OfficePackage.HelperModels; using BankBusinessLogic.OfficePackage;
using BankContracts.BindingModels.Reports; using BankDataModels.Enums;
using BankBusinessLogic.MailWorker;
using BankContracts.BusinessLogicsContracts.Reports; using BankContracts.BusinessLogicsContracts.Reports;
using BankContracts.SearchModels.Cashier; using BankContracts.StoragesContracts.Client;
using BankContracts.StoragesContracts.Cashier;
using BankContracts.ViewModels.Reports.Client;
using BankContracts.BindingModels.Reports;
using BankContracts.SearchModels.Client; using BankContracts.SearchModels.Client;
using BankContracts.StoragesModels.Cashier;
using BankContracts.StoragesModels.Client;
using BankContracts.ViewModels.Cashier.ViewModels; using BankContracts.ViewModels.Cashier.ViewModels;
using BankContracts.SearchModels.Cashier;
using BankContracts.ViewModels.Client.ViewModels; using BankContracts.ViewModels.Client.ViewModels;
using BankContracts.ViewModels.Reports; using BankContracts.ViewModels.Reports;
using BankContracts.ViewModels.Reports.Client;
using BankDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.BusinessLogic.Reports namespace BankBusinessLogic.BusinessLogics.Reports
{ {
public class ReportClientLogic : IReportClientLogic public class ReportClientLogic : IReportClientLogic
{ {
private readonly IMoneyTransferStorage _moneyTransferStorage;
private readonly ICreditingStorage _creditingStorage; private readonly ICreditingStorage _creditingStorage;
private readonly IDebitingStorage _debitingStorage; private readonly IDebitingStorage _debitingStorage;
private readonly IClientStorage _clientStorage;
private readonly ICardStorage _cardStorage; private readonly ICardStorage _cardStorage;
private readonly IMoneyTransferStorage _moneyTransferStorage;
private readonly IClientStorage _clientStorage;
private readonly AbstractSaveToExcel _saveToExcel; private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord; private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf; private readonly AbstractSaveToPdf _saveToPdf;
// Конструктор private readonly MailKitWorker _mailKitWorker;
public ReportClientLogic(IMoneyTransferStorage moneyTransferStorage,ICreditingStorage creditingStorage,
IDebitingStorage debitingStorage, IClientStorage clientStorage, ICardStorage cardStorage, public ReportClientLogic(ICreditingStorage creditingStorage, IDebitingStorage debitingStorage,
AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf) AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf,
ICardStorage cardStorage, IMoneyTransferStorage moneyTransferStorage,
MailKitWorker mailKitWorker, IClientStorage clientStorage)
{ {
_moneyTransferStorage = moneyTransferStorage;
_creditingStorage = creditingStorage; _creditingStorage = creditingStorage;
_debitingStorage = debitingStorage; _debitingStorage = debitingStorage;
_clientStorage = clientStorage;
_cardStorage = cardStorage; _cardStorage = cardStorage;
_moneyTransferStorage = moneyTransferStorage;
_clientStorage = clientStorage;
_saveToExcel = saveToExcel; _saveToExcel = saveToExcel;
_saveToWord = saveToWord; _saveToWord = saveToWord;
_saveToPdf = saveToPdf; _saveToPdf = saveToPdf;
_mailKitWorker = mailKitWorker;
} }
public List<ReportClientViewModel>? GetCrediting(ReportBindingModel model) public List<ReportClientViewModel>? GetCrediting(ReportBindingModel model)
{ {
return _creditingStorage.GetFilteredList(new CreditingSearchModel return _creditingStorage.GetFilteredList(new CreditingSearchModel
{ {
DateCrediting = model.DateFrom, DateFrom = model.DateFrom,
DateTo = model.DateTo,
}).Select(x => new ReportClientViewModel }).Select(x => new ReportClientViewModel
{ {
OperationId = x.Id, OperationId = x.Id,
CardNumber = x.CardNumber, CardNumber = x.CardNumber,
SumOperation = x.Sum, SumOperation = x.Sum,
DateComplite = x.DateCredit DateComplite = x.DateOpen
}).ToList(); }).ToList();
} }
@ -67,25 +66,26 @@ namespace BankBusinessLogic.BusinessLogic.Reports
{ {
return _debitingStorage.GetFilteredList(new DebitingSearchModel return _debitingStorage.GetFilteredList(new DebitingSearchModel
{ {
DateDebit = model.DateFrom, DateTo = model.DateFrom,
DateFrom = model.DateTo,
}).Select(x => new ReportClientViewModel }).Select(x => new ReportClientViewModel
{ {
OperationId = x.Id, OperationId = x.Id,
CardNumber = x.CardNumber, CardNumber = x.CardNumber,
SumOperation = x.Sum, SumOperation = x.Sum,
DateComplite = x.DateDebit DateComplite = x.DateClose
}).ToList(); }).ToList();
} }
// Для Excel отчёта по переводам между счетов //для excel отчёта по переводам между счетов
public List<MoneyTransferViewModel>? GetMoneyTransfer(ReportBindingModel model) public List<MoneyTransferViewModel>? GetMoneyTransfer(ReportBindingModel model)
{ {
// Список счетов по выбранным картам //список счетов по выбранным картам
List<int> accountId = new(); List<int> accountId = new();
foreach (var index in model.CardList) foreach(var index in model.CardList)
{ {
accountId.Add(_cardStorage.GetElement(new CardSearchModel { Id = index }).AccountId); accountId.Add(_cardStorage.GetElement(new CardSearchModel { Id = index}).AccountId);
} }
var list = accountId.ToHashSet().ToList(); var list = accountId.ToHashSet().ToList();
@ -106,7 +106,7 @@ namespace BankBusinessLogic.BusinessLogic.Reports
return totalList; return totalList;
} }
// Для Excel отчёта по пополнениям карты //для excel отчёта по пополнениям карты
public List<CreditingViewModel> GetExcelCrediting(ReportBindingModel model) public List<CreditingViewModel> GetExcelCrediting(ReportBindingModel model)
{ {
List<CreditingViewModel> totalList = new(); List<CreditingViewModel> totalList = new();
@ -124,7 +124,7 @@ namespace BankBusinessLogic.BusinessLogic.Reports
return totalList; return totalList;
} }
// Для Excel отчёта по снятиям с карты //для excel отчёта по снятиям с карты
public List<DebitingViewModel> GetExcelDebiting(ReportBindingModel model) public List<DebitingViewModel> GetExcelDebiting(ReportBindingModel model)
{ {
List<DebitingViewModel> totalList = new(); List<DebitingViewModel> totalList = new();
@ -142,22 +142,158 @@ namespace BankBusinessLogic.BusinessLogic.Reports
return totalList; return totalList;
} }
// Сохранение в файл-Excel для клиентов
public void SaveToExcelFile(ReportBindingModel model, OfficeOperationEnum operationEnum) public void SaveToExcelFile(ReportBindingModel model, OfficeOperationEnum operationEnum)
{ {
throw new NotImplementedException(); byte[] excel = Array.Empty<byte>();
if (operationEnum == OfficeOperationEnum.Между_cчетами)
{
_saveToExcel.CreateReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Отчёт по переводам",
MoneyTransfer = GetMoneyTransfer(model)
}, operationEnum);
excel = System.IO.File.ReadAllBytes("../BankRestAPI/Отчёт по переводам.xlsx");
File.Delete("../BankRestAPI/Отчёт по переводам.xlsx");
}
if (operationEnum == OfficeOperationEnum.Пополнениеарт)
{
_saveToExcel.CreateReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Отчёт по пополнениям (переводам из налички на карту)",
Crediting = GetExcelCrediting(model)
}, operationEnum);
excel = System.IO.File.ReadAllBytes("../BankRestAPI/Отчёт по пополнениям.xlsx");
File.Delete("../BankRestAPI/Отчёт по пополнениям.xlsx");
}
if (operationEnum == OfficeOperationEnum.Cнятие_сарты)
{
_saveToExcel.CreateReport(new ExcelInfo
{
FileName = model.FileName,
Title = "Отчёт по снятиям денежных средств",
Debiting = GetExcelDebiting(model)
}, operationEnum);
excel = System.IO.File.ReadAllBytes("../BankRestAPI/Отчёт по снятиям.xlsx");
File.Delete("../BankRestAPI/Отчёт по снятиям.xlsx");
}
_mailKitWorker.SendMailAsync(new()
{
MailAddress = model.Email,
Subject = "Отчёт по картам",
Text = $"Отчёт по состоянию на {DateTime.Now.ToString()}",
File = excel,
Role = model.Role,
TypeDoc = TypeDocEnum.EXCEL
});
} }
// Сохранение в файл-Word для клиентов
public void SaveToWordFile(ReportBindingModel model, OfficeOperationEnum operationEnum) public void SaveToWordFile(ReportBindingModel model, OfficeOperationEnum operationEnum)
{ {
throw new NotImplementedException(); byte[] word = Array.Empty<byte>();
if (operationEnum == OfficeOperationEnum.Между_cчетами)
{
_saveToWord.CreateDoc(new WordInfo
{
FileName = model.FileName,
Title = "Отчёт по переводам",
MoneyTransfer = GetMoneyTransfer(model)
}, operationEnum);
word = System.IO.File.ReadAllBytes("../BankRestAPI/Отчёт по переводам.docx");
File.Delete("../BankRestAPI/Отчёт по переводам.docx");
} }
// Сохранение в файл-Pdf для клиента if (operationEnum == OfficeOperationEnum.Пополнениеарт)
{
_saveToWord.CreateDoc(new WordInfo
{
FileName = model.FileName,
Title = "Отчёт по пополнениям (переводам из налички на карту)",
Crediting = GetExcelCrediting(model)
}, operationEnum);
word = System.IO.File.ReadAllBytes("../BankRestAPI/Отчёт по пополнениям.docx");
File.Delete("../BankRestAPI/Отчёт по пополнениям.docx");
}
if (operationEnum == OfficeOperationEnum.Cнятие_сарты)
{
_saveToWord.CreateDoc(new WordInfo
{
FileName = model.FileName,
Title = "Отчёт по снятиям денежных средств",
Debiting = GetExcelDebiting(model)
}, operationEnum);
word = System.IO.File.ReadAllBytes("../BankRestAPI/Отчёт по снятиям.docx");
File.Delete("../BankRestAPI/Отчёт по снятиям.docx");
}
_mailKitWorker.SendMailAsync(new()
{
MailAddress = model.Email,
Subject = "Отчёт по картам",
Text = $"Отчёт по состоянию на {DateTime.Now.ToString()}",
File = word,
Role = model.Role,
TypeDoc = TypeDocEnum.WORD
});
}
//отчёт в формате PDF для клиента
public ReportClientViewModelForHTML SaveClientReportToPdfFile(ReportBindingModel model) public ReportClientViewModelForHTML SaveClientReportToPdfFile(ReportBindingModel model)
{ {
throw new NotImplementedException(); var listCreditings = GetCrediting(model);
var listDebitings = GetDebiting(model);
_saveToPdf.CreateDoc(new PdfInfo
{
FileName = model.FileName,
Title = "Отчёт по операциям с картами",
DateFrom = model.DateFrom!.Value,
DateTo = model.DateTo!.Value,
ReportCrediting = listCreditings,
ReportDebiting = listDebitings
});
byte[] pdf = System.IO.File.ReadAllBytes("../BankRestAPI/Отчёт_поартам.pdf");
_mailKitWorker.SendMailAsync(new()
{
MailAddress = model.Email,
Subject = "Отчёт по картам",
Text = $"За период с {model.DateFrom} " +
$"по {model.DateTo}.",
File = pdf,
Role = model.Role,
TypeDoc = TypeDocEnum.PDF
});
File.Delete("../BankRestAPI/Отчёт_поартам.pdf");
//возврат полученных списков для отображения на вебе
return new ReportClientViewModelForHTML
{
ReportCrediting = listCreditings,
ReportDebiting = listDebitings
};
} }
} }
} }

View File

@ -1,17 +1,22 @@
using BankContracts.BindingModels.Messages; using BankContracts.BusinessLogicsContracts;
using BankDataModels.Enums; using BankContracts.BindingModels;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net;
using System.Net.Mail; using System.Net.Mail;
using System.Net;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using MailKit.Net.Pop3;
using MailKit.Security;
using BankDataModels.Enums;
using DocumentFormat.OpenXml.EMMA;
using BankContracts.BindingModels.Messages;
namespace BankBusinessLogic.MailWorker namespace BankBusinessLogic.MailWorker
{ {
// Класс, отвечающий за отправку письма на почту //класс, отвечающий за отправку письма
public class MailKitWorker public class MailKitWorker
{ {
private string _mailLogin = string.Empty; private string _mailLogin = string.Empty;
@ -24,18 +29,17 @@ namespace BankBusinessLogic.MailWorker
private readonly ILogger logger; private readonly ILogger logger;
// Конструктор
public MailKitWorker(ILogger<MailKitWorker> logger) public MailKitWorker(ILogger<MailKitWorker> logger)
{ {
this.logger = logger; this.logger = logger;
} }
public void MailConfig(MailConfigBindingModel model) public void MailConfig(MailConfigBindingModel config)
{ {
_mailLogin = model.MailLogin; _mailLogin = config.MailLogin;
_mailPassword = model.MailPassword; _mailPassword = config.MailPassword;
_smtpClientHost= model.SmtpClientHost; _smtpClientHost = config.SmtpClientHost;
_smtpClientPort = model.SmtpClientPort; _smtpClientPort = config.SmtpClientPort;
} }
public async void SendMailAsync(MailSendInfoBindingModel info) public async void SendMailAsync(MailSendInfoBindingModel info)
@ -52,40 +56,40 @@ namespace BankBusinessLogic.MailWorker
objMailMessage.SubjectEncoding = Encoding.UTF8; objMailMessage.SubjectEncoding = Encoding.UTF8;
objMailMessage.BodyEncoding = Encoding.UTF8; objMailMessage.BodyEncoding = Encoding.UTF8;
MemoryStream memory = new(info.File); MemoryStream ms = new(info.File);
if (info.Role == MailsEnum.Клиент) if(info.Role == MailsEnum.Клиент)
{ {
if (info.TypeDoc == TypeDocEnum.PDF) if(info.TypeDoc == TypeDocEnum.PDF)
{ {
objMailMessage.Attachments.Add(new Attachment(memory, "Отчёт_для_клиента.pdf", "application/pdf")); objMailMessage.Attachments.Add(new Attachment(ms, "Отчёт_для_клиента.pdf", "application/pdf"));
} }
if (info.TypeDoc == TypeDocEnum.EXCEL) if (info.TypeDoc == TypeDocEnum.EXCEL)
{ {
objMailMessage.Attachments.Add(new Attachment(memory, "Отчёт_для_клиента.xlsx", "application/xlsx")); objMailMessage.Attachments.Add(new Attachment(ms, "Отчёт_для_клиента.xlsx", "application/xlsx"));
} }
if (info.TypeDoc == TypeDocEnum.WORD) if (info.TypeDoc == TypeDocEnum.WORD)
{ {
objMailMessage.Attachments.Add(new Attachment(memory, "Отчёт_для_клиента.docx", "application/docx")); objMailMessage.Attachments.Add(new Attachment(ms, "Отчёт_для_клиента.docx", "application/docx"));
} }
} }
else else
{ {
if (info.TypeDoc == TypeDocEnum.PDF) if (info.TypeDoc == TypeDocEnum.PDF)
{ {
objMailMessage.Attachments.Add(new Attachment(memory, "Отчёт_для_кассира.pdf", "application/pdf")); objMailMessage.Attachments.Add(new Attachment(ms, "Отчёт_для_кассира.pdf", "application/pdf"));
} }
if (info.TypeDoc == TypeDocEnum.EXCEL) if (info.TypeDoc == TypeDocEnum.EXCEL)
{ {
objMailMessage.Attachments.Add(new Attachment(memory, "Отчёт_для_кассира.xlsx", "application/xlsx")); objMailMessage.Attachments.Add(new Attachment(ms, "Отчёт_для_кассира.xlsx", "application/xlsx"));
} }
if (info.TypeDoc == TypeDocEnum.WORD) if (info.TypeDoc == TypeDocEnum.WORD)
{ {
objMailMessage.Attachments.Add(new Attachment(memory, "Отчёт_для_кассира.docx", "application/docx")); objMailMessage.Attachments.Add(new Attachment(ms, "Отчёт_для_кассира.docx", "application/docx"));
} }
} }
@ -101,6 +105,5 @@ namespace BankBusinessLogic.MailWorker
throw; throw;
} }
} }
} }
} }

View File

@ -11,10 +11,10 @@ namespace BankBusinessLogic.OfficePackage
{ {
public abstract class AbstractSaveToExcel public abstract class AbstractSaveToExcel
{ {
// Создание отчета. Описание методов ниже //Создание отчета. Описание методов ниже
public void CreateReport(ExcelInfo info, OfficeOperationEnum operationEnum) public void CreateReport(ExcelInfo info, OfficeOperationEnum operationEnum)
{ {
if (operationEnum == OfficeOperationEnum.Между_cчетами) if(operationEnum == OfficeOperationEnum.Между_cчетами)
{ {
CreateMoneyTransferExcel(info); CreateMoneyTransferExcel(info);
} }
@ -39,7 +39,7 @@ namespace BankBusinessLogic.OfficePackage
{ {
CreateExcel(info); CreateExcel(info);
// Вставляет заголовок //вставляет заголовок
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "A", ColumnName = "A",
@ -48,19 +48,19 @@ namespace BankBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.Title StyleInfo = ExcelStyleInfoType.Title
}); });
// Соединяет 3 ячейки для заголовка //соединяет 3 ячейки для заголовка
MergeCells(new ExcelMergeParameters MergeCells(new ExcelMergeParameters
{ {
CellFromName = "A1", CellFromName = "A1",
CellToName = "C1" CellToName = "C1"
}); });
// Номер строчки в докуметне //номер строчки в докуметне
uint rowIndex = 2; uint rowIndex = 2;
foreach (var mt in info.MoneyTransfer) foreach (var mt in info.MoneyTransfer)
{ {
// Вставляет номер перевода //вставляет номер перевода
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "A", ColumnName = "A",
@ -71,7 +71,7 @@ namespace BankBusinessLogic.OfficePackage
rowIndex++; rowIndex++;
// Строчка с номером счёта отправителя //строчка с номером счёта отправителя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "B", ColumnName = "B",
@ -80,7 +80,7 @@ namespace BankBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.TextWithBorder StyleInfo = ExcelStyleInfoType.TextWithBorder
}); });
// Вставка номера отправителя //вставка номера отправителя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "C", ColumnName = "C",
@ -91,7 +91,7 @@ namespace BankBusinessLogic.OfficePackage
rowIndex++; rowIndex++;
// Строчка с номером счёта получателя //строчка с номером счёта получателя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "B", ColumnName = "B",
@ -100,7 +100,7 @@ namespace BankBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.TextWithBorder StyleInfo = ExcelStyleInfoType.TextWithBorder
}); });
// Вставка номера отправителя //вставка номера отправителя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "C", ColumnName = "C",
@ -111,7 +111,7 @@ namespace BankBusinessLogic.OfficePackage
rowIndex++; rowIndex++;
// Вставляет слово "Сумма перевода" //Вставляет слово "Сумма перевода"
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "A", ColumnName = "A",
@ -120,7 +120,7 @@ namespace BankBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.Text StyleInfo = ExcelStyleInfoType.Text
}); });
// Подсчитывает общее кол-во сумму //подсчитывает общее кол-во заготовок в изделии
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "C", ColumnName = "C",
@ -131,7 +131,7 @@ namespace BankBusinessLogic.OfficePackage
rowIndex++; rowIndex++;
// Вставляет слово "Сумма перевода" //Вставляет слово "Сумма перевода"
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "A", ColumnName = "A",
@ -140,12 +140,12 @@ namespace BankBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.Text StyleInfo = ExcelStyleInfoType.Text
}); });
// Подсчитывает общее кол-во переводов //подсчитывает общее кол-во заготовок в изделии
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "C", ColumnName = "C",
RowIndex = rowIndex, RowIndex = rowIndex,
Text = mt.DateTransfer.ToString(), Text = mt.DateOperation.ToString(),
StyleInfo = ExcelStyleInfoType.Text StyleInfo = ExcelStyleInfoType.Text
}); });
@ -183,7 +183,7 @@ namespace BankBusinessLogic.OfficePackage
{ {
CreateExcel(info); CreateExcel(info);
// Вставляет заголовок операции //вставляет заголовок
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "A", ColumnName = "A",
@ -192,19 +192,21 @@ namespace BankBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.Title StyleInfo = ExcelStyleInfoType.Title
}); });
// Соединяет 3 ячейки для заголовка //соединяет 3 ячейки для заголовка
MergeCells(new ExcelMergeParameters MergeCells(new ExcelMergeParameters
{ {
CellFromName = "A1", CellFromName = "A1",
CellToName = "E2" CellToName = "E2"
}); });
// Номер строчки в докуметне //номер строчки в докуметне
uint rowIndex = 3; uint rowIndex = 3;
//string supportNumber = string.Empty;
foreach (var cr in info.Crediting) foreach (var cr in info.Crediting)
{ {
// Вставляет номер перевода //вставляет номер перевода
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "A", ColumnName = "A",
@ -215,7 +217,7 @@ namespace BankBusinessLogic.OfficePackage
rowIndex++; rowIndex++;
// Строчка с номером счёта отправителя //строчка с номером счёта отправителя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "B", ColumnName = "B",
@ -224,7 +226,7 @@ namespace BankBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.TextWithBorder StyleInfo = ExcelStyleInfoType.TextWithBorder
}); });
// Вставка номера отправителя //вставка номера отправителя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "C", ColumnName = "C",
@ -235,7 +237,7 @@ namespace BankBusinessLogic.OfficePackage
rowIndex++; rowIndex++;
// Строчка с номером счёта получателя //строчка с номером счёта получателя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "B", ColumnName = "B",
@ -244,7 +246,7 @@ namespace BankBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.TextWithBorder StyleInfo = ExcelStyleInfoType.TextWithBorder
}); });
// Вставка номера отправителя //вставка номера отправителя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "C", ColumnName = "C",
@ -258,10 +260,10 @@ namespace BankBusinessLogic.OfficePackage
rowIndex++; rowIndex++;
// Формирование списка поступления по каждой карте //формирование списка поступления по каждой карте
var dict = new Dictionary<string, double>(); var dict = new Dictionary<string, int>();
foreach (var elem in info.Crediting) foreach(var elem in info.Crediting)
{ {
if (dict.ContainsKey(elem.CardNumber)) if (dict.ContainsKey(elem.CardNumber))
{ {
@ -273,9 +275,9 @@ namespace BankBusinessLogic.OfficePackage
} }
} }
foreach (var elem in dict) foreach(var elem in dict)
{ {
// Cтрочка с номером счёта получателя //строчка с номером счёта получателя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "B", ColumnName = "B",
@ -284,7 +286,7 @@ namespace BankBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.TextWithBorder StyleInfo = ExcelStyleInfoType.TextWithBorder
}); });
// Вставка номера отправителя //вставка номера отправителя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "C", ColumnName = "C",
@ -327,7 +329,7 @@ namespace BankBusinessLogic.OfficePackage
{ {
CreateExcel(info); CreateExcel(info);
// Вставляет заголовок //вставляет заголовок
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "A", ColumnName = "A",
@ -336,19 +338,19 @@ namespace BankBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.Title StyleInfo = ExcelStyleInfoType.Title
}); });
// Соединяет 3 ячейки для заголовка //соединяет 3 ячейки для заголовка
MergeCells(new ExcelMergeParameters MergeCells(new ExcelMergeParameters
{ {
CellFromName = "A1", CellFromName = "A1",
CellToName = "E2" CellToName = "E2"
}); });
// Номер строчки в докуметне //номер строчки в докуметне
uint rowIndex = 3; uint rowIndex = 3;
foreach (var cr in info.Debiting) foreach (var cr in info.Debiting)
{ {
// Вставляет номер перевода //вставляет номер перевода
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "A", ColumnName = "A",
@ -359,7 +361,7 @@ namespace BankBusinessLogic.OfficePackage
rowIndex++; rowIndex++;
// Строчка с номером счёта отправителя //строчка с номером счёта отправителя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "B", ColumnName = "B",
@ -368,7 +370,7 @@ namespace BankBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.TextWithBorder StyleInfo = ExcelStyleInfoType.TextWithBorder
}); });
// Вставка номера отправителя //вставка номера отправителя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "C", ColumnName = "C",
@ -379,7 +381,7 @@ namespace BankBusinessLogic.OfficePackage
rowIndex++; rowIndex++;
// Строчка с номером счёта получателя //строчка с номером счёта получателя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "B", ColumnName = "B",
@ -388,7 +390,7 @@ namespace BankBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.TextWithBorder StyleInfo = ExcelStyleInfoType.TextWithBorder
}); });
// Вставка номера отправителя //вставка номера отправителя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "C", ColumnName = "C",
@ -402,8 +404,8 @@ namespace BankBusinessLogic.OfficePackage
rowIndex++; rowIndex++;
// Формирование списка поступления по каждой карте //формирование списка поступления по каждой карте
var dict = new Dictionary<string, double>(); var dict = new Dictionary<string, int>();
foreach (var elem in info.Debiting) foreach (var elem in info.Debiting)
{ {
@ -419,7 +421,7 @@ namespace BankBusinessLogic.OfficePackage
foreach (var elem in dict) foreach (var elem in dict)
{ {
// Строчка с номером счёта получателя //строчка с номером счёта получателя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "B", ColumnName = "B",
@ -428,7 +430,7 @@ namespace BankBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.TextWithBorder StyleInfo = ExcelStyleInfoType.TextWithBorder
}); });
// Вставка номера отправителя //вставка номера отправителя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "C", ColumnName = "C",
@ -471,7 +473,7 @@ namespace BankBusinessLogic.OfficePackage
{ {
CreateExcel(info); CreateExcel(info);
// Вставляет заголовок //вставляет заголовок
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "A", ColumnName = "A",
@ -480,19 +482,19 @@ namespace BankBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.Title StyleInfo = ExcelStyleInfoType.Title
}); });
// Соединяет 3 ячейки для заголовка //соединяет 3 ячейки для заголовка
MergeCells(new ExcelMergeParameters MergeCells(new ExcelMergeParameters
{ {
CellFromName = "A1", CellFromName = "A1",
CellToName = "E2" CellToName = "E2"
}); });
// Номер строчки в докуметне //номер строчки в докуметне
uint rowIndex = 3; uint rowIndex = 3;
foreach (var cr in info.Debiting) foreach (var cr in info.Debiting)
{ {
// Вставляет номер перевода //вставляет номер перевода
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "A", ColumnName = "A",
@ -503,7 +505,7 @@ namespace BankBusinessLogic.OfficePackage
rowIndex++; rowIndex++;
// Строчка с номером счёта получателя //строчка с номером счёта получателя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "B", ColumnName = "B",
@ -512,7 +514,7 @@ namespace BankBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.TextWithBorder StyleInfo = ExcelStyleInfoType.TextWithBorder
}); });
// Вставка суммы заявки //вставка суммы заявки
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "C", ColumnName = "C",
@ -523,7 +525,7 @@ namespace BankBusinessLogic.OfficePackage
rowIndex++; rowIndex++;
// Строчка с номером счёта получателя //строчка с номером счёта получателя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "B", ColumnName = "B",
@ -532,7 +534,7 @@ namespace BankBusinessLogic.OfficePackage
StyleInfo = ExcelStyleInfoType.TextWithBorder StyleInfo = ExcelStyleInfoType.TextWithBorder
}); });
// Вставка номера отправителя //вставка номера отправителя
InsertCellInWorksheet(new ExcelCellParameters InsertCellInWorksheet(new ExcelCellParameters
{ {
ColumnName = "C", ColumnName = "C",
@ -557,7 +559,7 @@ namespace BankBusinessLogic.OfficePackage
{ {
ColumnName = "C", ColumnName = "C",
RowIndex = rowIndex, RowIndex = rowIndex,
Text = cr.DateDebit == null ? "В обработке" : cr.DateDebit.ToString(), Text = cr.DateClose == null ? "В обработке" : cr.DateClose.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBorder StyleInfo = ExcelStyleInfoType.TextWithBorder
}); });
@ -584,7 +586,7 @@ namespace BankBusinessLogic.OfficePackage
{ {
ColumnName = "D", ColumnName = "D",
RowIndex = rowIndex, RowIndex = rowIndex,
Text = info.Debiting.Where(x => x.Status == StatusCard.Открыта).Sum(x => x.Sum).ToString(), Text = info.Debiting.Where(x => x.Status == StatusEnum.Открыта).Sum(x => x.Sum).ToString(),
StyleInfo = ExcelStyleInfoType.Text StyleInfo = ExcelStyleInfoType.Text
}); });
@ -608,23 +610,23 @@ namespace BankBusinessLogic.OfficePackage
{ {
ColumnName = "D", ColumnName = "D",
RowIndex = rowIndex, RowIndex = rowIndex,
Text = info.Debiting.Where(x => x.Status == StatusCard.Закрыта).Sum(x => x.Sum).ToString(), Text = info.Debiting.Where(x => x.Status == StatusEnum.Закрыта).Sum(x => x.Sum).ToString(),
StyleInfo = ExcelStyleInfoType.Text StyleInfo = ExcelStyleInfoType.Text
}); });
SaveExcel(info); SaveExcel(info);
} }
// Создание excel-файла //Создание excel-файла
protected abstract void CreateExcel(ExcelInfo info); protected abstract void CreateExcel(ExcelInfo info);
// Добавляем новую ячейку в лист //Добавляем новую ячейку в лист
protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams); protected abstract void InsertCellInWorksheet(ExcelCellParameters excelParams);
// Объединение ячеек //Объединение ячеек
protected abstract void MergeCells(ExcelMergeParameters excelParams); protected abstract void MergeCells(ExcelMergeParameters excelParams);
// Сохранение файла //Сохранение файла
protected abstract void SaveExcel(ExcelInfo info); protected abstract void SaveExcel(ExcelInfo info);
} }
} }

View File

@ -10,10 +10,10 @@ namespace BankBusinessLogic.OfficePackage
{ {
public abstract class AbstractSaveToPdf public abstract class AbstractSaveToPdf
{ {
// Публичный метод создания документа. Описание методов ниже //публичный метод создания документа. Описание методов ниже
public void CreateDoc(PdfInfo info) public void CreateDoc(PdfInfo info)
{ {
if (info.ForClient) if(info.ForClient)
{ {
CreateDocClient(info); CreateDocClient(info);
} }
@ -23,7 +23,7 @@ namespace BankBusinessLogic.OfficePackage
} }
} }
// Отчёт для клиента #region Отчёт для клиента
public void CreateDocClient(PdfInfo info) public void CreateDocClient(PdfInfo info)
{ {
@ -44,7 +44,7 @@ namespace BankBusinessLogic.OfficePackage
ParagraphAlignment = PdfParagraphAlignmentType.Center ParagraphAlignment = PdfParagraphAlignmentType.Center
}); });
// Параграф с отчётом на пополнения //параграф с отчётом на пополнения
CreateParagraph(new PdfParagraph { Text = "Отчёт по пополнениям", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center }); CreateParagraph(new PdfParagraph { Text = "Отчёт по пополнениям", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateTable(new List<string> { "3cm", "3cm", "5cm", "5cm" }); CreateTable(new List<string> { "3cm", "3cm", "5cm", "5cm" });
@ -66,10 +66,10 @@ namespace BankBusinessLogic.OfficePackage
}); });
} }
// Подсчёт суммы операций на пополнение //подсчёт суммы операций на пополнение
CreateParagraph(new PdfParagraph { Text = $"Итоговая сумма поступлений за период: {info.ReportCrediting.Sum(x => x.SumOperation)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right }); CreateParagraph(new PdfParagraph { Text = $"Итоговая сумма поступлений за период: {info.ReportCrediting.Sum(x => x.SumOperation)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right });
// Отчёт с отчётом на снятие //отчёт с отчётом на снятие
CreateParagraph(new PdfParagraph { Text = "Отчёт по снятиям", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center }); CreateParagraph(new PdfParagraph { Text = "Отчёт по снятиям", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateTable(new List<string> { "3cm", "3cm", "5cm", "5cm" }); CreateTable(new List<string> { "3cm", "3cm", "5cm", "5cm" });
@ -91,15 +91,17 @@ namespace BankBusinessLogic.OfficePackage
}); });
} }
// Подсчёт суммы операций на пополнение //подсчёт суммы операций на пополнение
CreateParagraph(new PdfParagraph { Text = $"Итоговая сумма снятий за период: {info.ReportDebiting.Sum(x => x.SumOperation)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right }); CreateParagraph(new PdfParagraph { Text = $"Итоговая сумма снятий за период: {info.ReportDebiting.Sum(x => x.SumOperation)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right });
SavePdf(info); SavePdf(info);
} }
//=== Отчёты для кассира ===// #endregion
// Создание отчёта для кассира #region Отчёт для кассира
//создание отчёта для кассира
public void CreateDocCashier(PdfInfo info) public void CreateDocCashier(PdfInfo info)
{ {
CreatePdf(info); CreatePdf(info);
@ -118,7 +120,7 @@ namespace BankBusinessLogic.OfficePackage
ParagraphAlignment = PdfParagraphAlignmentType.Center ParagraphAlignment = PdfParagraphAlignmentType.Center
}); });
// Параграф с отчётом по выдаче наличных с карт //параграф с отчётом по выдаче наличных с карт
CreateParagraph(new PdfParagraph { Text = "Отчёт по выдаче наличных со счёта", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center }); CreateParagraph(new PdfParagraph { Text = "Отчёт по выдаче наличных со счёта", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateTable(new List<string> { "3.5cm", "3.5cm", "5cm", "5cm" }); CreateTable(new List<string> { "3.5cm", "3.5cm", "5cm", "5cm" });
@ -142,7 +144,7 @@ namespace BankBusinessLogic.OfficePackage
CreateParagraph(new PdfParagraph { Text = $"Итоговая сумма снятий за период: {info.ReportCashWithdrawal.Sum(x => x.SumOperation)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right }); CreateParagraph(new PdfParagraph { Text = $"Итоговая сумма снятий за период: {info.ReportCashWithdrawal.Sum(x => x.SumOperation)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right });
// Параграф с отчётом по переводу денег со счёта на счёт //параграф с отчётом по переводу денег со счёта на счёт
CreateParagraph(new PdfParagraph { Text = "Отчёт по денежным переводам между счетами", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center }); CreateParagraph(new PdfParagraph { Text = "Отчёт по денежным переводам между счетами", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateTable(new List<string> { "3cm", "3cm", "3cm", "4cm", "4cm" }); CreateTable(new List<string> { "3cm", "3cm", "3cm", "4cm", "4cm" });
@ -169,6 +171,8 @@ namespace BankBusinessLogic.OfficePackage
SavePdf(info); SavePdf(info);
} }
#endregion
/// Создание pdf-файла /// Создание pdf-файла
protected abstract void CreatePdf(PdfInfo info); protected abstract void CreatePdf(PdfInfo info);

View File

@ -77,7 +77,7 @@ namespace BankBusinessLogic.OfficePackage
new(transfer.AccountSenderNumber, new WordTextProperties { Size = "20" }), new(transfer.AccountSenderNumber, new WordTextProperties { Size = "20" }),
new(transfer.AccountPayeeNumber, new WordTextProperties { Size = "20" }), new(transfer.AccountPayeeNumber, new WordTextProperties { Size = "20" }),
new(transfer.Sum.ToString(), new WordTextProperties { Size = "20"}), new(transfer.Sum.ToString(), new WordTextProperties { Size = "20"}),
new(transfer.DateTransfer.ToString(), new WordTextProperties { Size = "20"}), new(transfer.DateOperation.ToString(), new WordTextProperties { Size = "20"}),
}; };
rowList.Add(cellList); rowList.Add(cellList);
@ -147,7 +147,7 @@ namespace BankBusinessLogic.OfficePackage
{ {
new(crediting.CardNumber, new WordTextProperties { Size = "24" }), new(crediting.CardNumber, new WordTextProperties { Size = "24" }),
new(crediting.Sum.ToString(), new WordTextProperties { Size = "24" }), new(crediting.Sum.ToString(), new WordTextProperties { Size = "24" }),
new(crediting.DateCredit == null ? "В обработке" : crediting.DateCredit.ToString(), new WordTextProperties { Size = "24" }) new(crediting.DateClose == null ? "В обработке" : crediting.DateClose.ToString(), new WordTextProperties { Size = "24" })
}; };
rowList.Add(cellList); rowList.Add(cellList);
@ -164,7 +164,7 @@ namespace BankBusinessLogic.OfficePackage
} }
//формирование списка поступления по каждой карте //формирование списка поступления по каждой карте
var dict = new Dictionary<string, double>(); var dict = new Dictionary<string, int>();
foreach (var elem in info.Crediting) foreach (var elem in info.Crediting)
{ {
@ -233,7 +233,7 @@ namespace BankBusinessLogic.OfficePackage
{ {
new(crediting.CardNumber, new WordTextProperties { Size = "24" }), new(crediting.CardNumber, new WordTextProperties { Size = "24" }),
new(crediting.Sum.ToString(), new WordTextProperties { Size = "24" }), new(crediting.Sum.ToString(), new WordTextProperties { Size = "24" }),
new(crediting.DateDebit == null ? "В обработке" : crediting.DateDebit.ToString(), new WordTextProperties { Size = "24" }) new(crediting.DateClose == null ? "В обработке" : crediting.DateClose.ToString(), new WordTextProperties { Size = "24" })
}; };
rowList.Add(cellList); rowList.Add(cellList);
@ -250,7 +250,7 @@ namespace BankBusinessLogic.OfficePackage
} }
//формирование списка поступления по каждой карте //формирование списка поступления по каждой карте
var dict = new Dictionary<string, double>(); var dict = new Dictionary<string, int>();
foreach (var elem in info.Debiting) foreach (var elem in info.Debiting)
{ {
@ -318,7 +318,7 @@ namespace BankBusinessLogic.OfficePackage
List<(string, WordTextProperties)> cellList = new() List<(string, WordTextProperties)> cellList = new()
{ {
new(crediting.Sum.ToString(), new WordTextProperties { Size = "24" }), new(crediting.Sum.ToString(), new WordTextProperties { Size = "24" }),
new(crediting.DateDebit.ToString(), new WordTextProperties { Size = "24" }), new(crediting.DateOpen.ToString(), new WordTextProperties { Size = "24" }),
new(crediting.Status.ToString(), new WordTextProperties { Size = "24" }) new(crediting.Status.ToString(), new WordTextProperties { Size = "24" })
}; };
@ -338,16 +338,16 @@ namespace BankBusinessLogic.OfficePackage
SaveWord(info); SaveWord(info);
} }
/// Создание doc-файла // Создание doc-файла
protected abstract void CreateWord(WordInfo info); protected abstract void CreateWord(WordInfo info);
/// Создание абзаца с текстом // Создание абзаца с текстом
protected abstract void CreateParagraph(WordParagraph paragraph); protected abstract void CreateParagraph(WordParagraph paragraph);
/// Создание таблицы //Создание таблицы
protected abstract void CreateTable(WordParagraph paragraph); protected abstract void CreateTable(WordParagraph paragraph);
/// Сохранение файла // Сохранение файла
protected abstract void SaveWord(WordInfo info); protected abstract void SaveWord(WordInfo info);
} }
} }

View File

@ -6,16 +6,16 @@ using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperEnums namespace BankBusinessLogic.OfficePackage.HelperEnums
{ {
// Вспомогательное перечисление для оформления Excel //вспомогательное перечисление для оформления exel
public enum ExcelStyleInfoType public enum ExcelStyleInfoType
{ {
// Заголовок //заголовок
Title, Title,
// Просто текст //просто текст
Text, Text,
// Текст в рамке //текст в рамке
TextWithBorder TextWithBorder
} }
} }

View File

@ -6,16 +6,16 @@ using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperEnums namespace BankBusinessLogic.OfficePackage.HelperEnums
{ {
// Вспомогательное перечисление для оформления pdf документа //вспомогательное перечисление для оформления pdf документа
public enum PdfParagraphAlignmentType public enum PdfParagraphAlignmentType
{ {
// Либо по центру //либо по центру
Center, Center,
// Либо с левого края //либо с левого края
Left, Left,
// Либо с правого края //либо с правого края
Right Right
} }
} }

View File

@ -6,13 +6,13 @@ using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperEnums namespace BankBusinessLogic.OfficePackage.HelperEnums
{ {
// Вспомогательное перечисление для настройки формата word документа //вспомогательное перечисление для настройки формата word документа
public enum WordJustificationType public enum WordJustificationType
{ {
// Выравниваем либо по центру //выравниваем либо по центру
Center, Center,
// Либо на всю ширину //либо на всю ширину
Both Both
} }
} }

View File

@ -7,22 +7,22 @@ using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperModels namespace BankBusinessLogic.OfficePackage.HelperModels
{ {
// Информация по ячейке в таблице Excel //информация по ячейке в таблице excel
public class ExcelCellParameters public class ExcelCellParameters
{ {
// Название колонки //название колонки
public string ColumnName { get; set; } = string.Empty; public string ColumnName { get; set; } = string.Empty;
// Строка //строка
public uint RowIndex { get; set; } public uint RowIndex { get; set; }
// текст в ячейке //тект в ячейке
public string Text { get; set; } = string.Empty; public string Text { get; set; } = string.Empty;
// Геттер для того, чтобы не искать каждый раз //геттер для того, чтобы не искать каждый раз
public string CellReference => $"{ColumnName}{RowIndex}"; public string CellReference => $"{ColumnName}{RowIndex}";
// В каком стиле выводить информацию //в каком стиле выводить информацию
public ExcelStyleInfoType StyleInfo { get; set; } public ExcelStyleInfoType StyleInfo { get; set; }
} }
} }

View File

@ -1,28 +1,23 @@
using BankContracts.ViewModels.Cashier.ViewModels; using BankContracts.ViewModels.Cashier.ViewModels;
using BankContracts.ViewModels.Client.ViewModels; using BankContracts.ViewModels.Client.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperModels namespace BankBusinessLogic.OfficePackage.HelperModels
{ {
// Информация по excel файлу, который хотим создать //информация по excel файлу, который хотим создать
public class ExcelInfo public class ExcelInfo
{ {
// Название файла //название файла
public string FileName { get; set; } = string.Empty; public string FileName { get; set; } = string.Empty;
// Заголовок //заголовок
public string Title { get; set; } = string.Empty; public string Title { get; set; } = string.Empty;
// Списки для отчёта клиента //списки для отчёта клиента
public List<MoneyTransferViewModel> MoneyTransfer { get; set; } = new(); public List<MoneyTransferViewModel> MoneyTransfer { get; set; } = new();
public List<CreditingViewModel> Crediting { get; set; } = new(); public List<CreditingViewModel> Crediting { get; set; } = new();
// Список для отчёта кассира и клиента //список для отчёта кассира и клиента
public List<DebitingViewModel> Debiting { get; set; } = new(); public List<DebitingViewModel> Debiting { get; set; } = new();
} }
} }

View File

@ -6,14 +6,14 @@ using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperModels namespace BankBusinessLogic.OfficePackage.HelperModels
{ {
// Информация для объединения ячеек //информация для объединения ячеек
public class ExcelMergeParameters public class ExcelMergeParameters
{ {
public string CellFromName { get; set; } = string.Empty; public string CellFromName { get; set; } = string.Empty;
public string CellToName { get; set; } = string.Empty; public string CellToName { get; set; } = string.Empty;
// Геттер для указания диапазона для объединения, чтобы каждый раз его не вычислять //гетер для указания диапазона для объединения, чтобы каждый раз его не вычислять
public string Merge => $"{CellFromName}:{CellToName}"; public string Merge => $"{CellFromName}:{CellToName}";
} }
} }

View File

@ -1,14 +1,9 @@
using BankContracts.ViewModels.Reports.Cashier; using BankContracts.ViewModels.Reports.Cashier;
using BankContracts.ViewModels.Reports.Client; using BankContracts.ViewModels.Reports.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperModels namespace BankBusinessLogic.OfficePackage.HelperModels
{ {
// Общая информация по pdf файлу //общая информация по pdf файлу
public class PdfInfo public class PdfInfo
{ {
public string FileName { get; set; } = string.Empty; public string FileName { get; set; } = string.Empty;
@ -19,22 +14,22 @@ namespace BankBusinessLogic.OfficePackage.HelperModels
public DateTime DateTo { get; set; } public DateTime DateTo { get; set; }
// По умолчанию отчёт делается для клиента //по умолчанию отчёт делается для клиента
public bool ForClient { get; set; } = true; public bool ForClient { get; set; } = true;
// Для передачи полного имени клиента в отчёт //для передачи полного имени клиента в отчёт
public string FullClientName { get; set; } = string.Empty; public string FullClientName { get; set; } = string.Empty;
// Перечень заказов за указанный период для вывода/сохранения //перечень заказов за указанный период для вывода/сохранения
public List<ReportClientViewModel> ReportCrediting { get; set; } = new(); public List<ReportClientViewModel> ReportCrediting { get; set; } = new();
// Перечень заказов за указанный период для вывода/сохранения //перечень заказов за указанный период для вывода/сохранения
public List<ReportClientViewModel> ReportDebiting { get; set; } = new(); public List<ReportClientViewModel> ReportDebiting { get; set; } = new();
// Перечень переводов со счёта на счёт //перечень переводов со счёта на счёт
public List<ReportCashierViewModel> ReportMoneyTransfer { get; set; } = new(); public List<ReportCashierViewModel> ReportMoneyTransfer { get; set; } = new();
// Перечень зачислений денежных средств //перечень зачислений денежных средств на карту (т. е. на её счёт)
public List<ReportCashierViewModel> ReportCashWithdrawal { get; set; } = new(); public List<ReportCashierViewModel> ReportCashWithdrawal { get; set; } = new();
} }
} }

View File

@ -7,14 +7,14 @@ using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperModels namespace BankBusinessLogic.OfficePackage.HelperModels
{ {
// Информация по параграфу в pdf документе //информация п параграфу в pdf документе
public class PdfParagraph public class PdfParagraph
{ {
public string Text { get; set; } = string.Empty; public string Text { get; set; } = string.Empty;
public string Style { get; set; } = string.Empty; public string Style { get; set; } = string.Empty;
// Информация по выравниванию текста в параграфе //информация по выравниванию текста в параграфе
public PdfParagraphAlignmentType ParagraphAlignment { get; set; } public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
} }
} }

View File

@ -7,16 +7,16 @@ using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperModels namespace BankBusinessLogic.OfficePackage.HelperModels
{ {
// Информация по параметрам строк таблицы //информация по параметрам строк таблицы
public class PdfRowParameters public class PdfRowParameters
{ {
// Набор текстов //набор текстов
public List<string> Texts { get; set; } = new(); public List<string> Texts { get; set; } = new();
// Стиль к текстам //стиль к текстам
public string Style { get; set; } = string.Empty; public string Style { get; set; } = string.Empty;
// Как выравниваем //как выравниваем
public PdfParagraphAlignmentType ParagraphAlignment { get; set; } public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
} }
} }

View File

@ -1,26 +1,21 @@
using BankContracts.ViewModels.Cashier.ViewModels; using BankContracts.ViewModels.Cashier.ViewModels;
using BankContracts.ViewModels.Client.ViewModels; using BankContracts.ViewModels.Client.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperModels namespace BankBusinessLogic.OfficePackage.HelperModels
{ {
// Общая информация по документу //общая информация по документу
public class WordInfo public class WordInfo
{ {
public string FileName { get; set; } = string.Empty; public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty; public string Title { get; set; } = string.Empty;
// Списки для отчёта клиента //списки для отчёта клиента
public List<MoneyTransferViewModel> MoneyTransfer { get; set; } = new(); public List<MoneyTransferViewModel> MoneyTransfer { get; set; } = new();
public List<CreditingViewModel> Crediting { get; set; } = new(); public List<CreditingViewModel> Crediting { get; set; } = new();
// Список для отчёта кассира и клиента //список для отчёта кассира и клиента
public List<DebitingViewModel> Debiting { get; set; } = new(); public List<DebitingViewModel> Debiting { get; set; } = new();
} }
} }

View File

@ -6,13 +6,13 @@ using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperModels namespace BankBusinessLogic.OfficePackage.HelperModels
{ {
// Модель параграфов, которые есть в тексте //модель параграфов, которые есть в тексте
public class WordParagraph public class WordParagraph
{ {
// Набор текстов в абзаце (для случая, если в абзаце текст разных стилей) //набор текстов в абзаце (для случая, если в абзаце текст разных стилей)
public List<(string, WordTextProperties)> Texts { get; set; } = new(); public List<(string, WordTextProperties)> Texts { get; set; } = new();
// Свойства параграфа, если они есть //свойства параграфа, если они есть
public WordTextProperties? TextProperties { get; set; } public WordTextProperties? TextProperties { get; set; }
public List<List<(string, WordTextProperties)>> RowTexts { get; set; } = new(); public List<List<(string, WordTextProperties)>> RowTexts { get; set; } = new();

View File

@ -7,16 +7,16 @@ using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperModels namespace BankBusinessLogic.OfficePackage.HelperModels
{ {
// Модель свойств текста, которые нам нужны в word документе //модель свойств текста, которые нам нужны в word документе
public class WordTextProperties public class WordTextProperties
{ {
// Размере текста //размере текста
public string Size { get; set; } = string.Empty; public string Size { get; set; } = string.Empty;
// Надо ли делать его жирным //надо ли делать его жирным
public bool Bold { get; set; } public bool Bold { get; set; }
// Выравнивание //выравнивание
public WordJustificationType JustificationType { get; set; } public WordJustificationType JustificationType { get; set; }
} }
} }

View File

@ -1,10 +1,11 @@
using BankBusinessLogic.OfficePackage.HelperEnums; using BankBusinessLogic.OfficePackage.HelperModels;
using BankBusinessLogic.OfficePackage.HelperModels; using BankBusinessLogic.OfficePackage.HelperEnums;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet; using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Office2016.Excel;
using DocumentFormat.OpenXml;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -13,7 +14,6 @@ using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.Implements namespace BankBusinessLogic.OfficePackage.Implements
{ {
// Реализация создания Excel-документа от абстрактного класса
public class SaveToExcel : AbstractSaveToExcel public class SaveToExcel : AbstractSaveToExcel
{ {
private SpreadsheetDocument? _spreadsheetDocument; private SpreadsheetDocument? _spreadsheetDocument;
@ -22,13 +22,13 @@ namespace BankBusinessLogic.OfficePackage.Implements
private Worksheet? _worksheet; private Worksheet? _worksheet;
// Настройка стилей для файла //Настройка стилей для файла
private static void CreateStyles(WorkbookPart workbookpart) private static void CreateStyles(WorkbookPart workbookpart)
{ {
var sp = workbookpart.AddNewPart<WorkbookStylesPart>(); var sp = workbookpart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet(); sp.Stylesheet = new Stylesheet();
// Настройка шрифта простого текста //настройка шрифта простого текста
var fonts = new Fonts() { Count = 2U, KnownFonts = true }; var fonts = new Fonts() { Count = 2U, KnownFonts = true };
var fontUsual = new Font(); var fontUsual = new Font();
@ -38,7 +38,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
fontUsual.Append(new FontFamilyNumbering() { Val = 2 }); fontUsual.Append(new FontFamilyNumbering() { Val = 2 });
fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor }); fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor });
// Настройка шрифта заголока //настройка шрифта заголока
var fontTitle = new Font(); var fontTitle = new Font();
fontTitle.Append(new Bold()); fontTitle.Append(new Bold());
fontTitle.Append(new FontSize() { Val = 14D }); fontTitle.Append(new FontSize() { Val = 14D });
@ -47,11 +47,11 @@ namespace BankBusinessLogic.OfficePackage.Implements
fontTitle.Append(new FontFamilyNumbering() { Val = 2 }); fontTitle.Append(new FontFamilyNumbering() { Val = 2 });
fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor }); fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor });
// Добавление созданных шрифтов //добавление созданных шрифтов
fonts.Append(fontUsual); fonts.Append(fontUsual);
fonts.Append(fontTitle); fonts.Append(fontTitle);
// Создание заливки //создание заливки
var fills = new Fills() { Count = 2U }; var fills = new Fills() { Count = 2U };
var fill1 = new Fill(); var fill1 = new Fill();
@ -69,7 +69,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
fills.Append(fill1); fills.Append(fill1);
fills.Append(fill2); fills.Append(fill2);
// Стиль границ ячейки - незакрашенный (для заголовка) и закрашенный //стиль границ ячейки - незакрашенный (для заголовка) и закрашенный
var borders = new Borders() { Count = 2U }; var borders = new Borders() { Count = 2U };
var borderNoBorder = new Border(); var borderNoBorder = new Border();
@ -88,7 +88,6 @@ namespace BankBusinessLogic.OfficePackage.Implements
{ {
Style = BorderStyleValues.Thin Style = BorderStyleValues.Thin
}; };
rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); rightBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
var topBorder = new TopBorder() { Style = BorderStyleValues.Thin }; var topBorder = new TopBorder() { Style = BorderStyleValues.Thin };
@ -98,7 +97,6 @@ namespace BankBusinessLogic.OfficePackage.Implements
{ {
Style = BorderStyleValues.Thin Style = BorderStyleValues.Thin
}; };
bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U }); bottomBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color() { Indexed = 64U });
borderThin.Append(leftBorder); borderThin.Append(leftBorder);
@ -110,7 +108,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
borders.Append(borderNoBorder); borders.Append(borderNoBorder);
borders.Append(borderThin); borders.Append(borderThin);
// Формирование CellFormat из комбинаций шрифтов, заливок и т. д. //формирование CellFormat из комбинаций шрифтов, заливок и т. д.
var cellStyleFormats = new CellStyleFormats() { Count = 1U }; var cellStyleFormats = new CellStyleFormats() { Count = 1U };
var cellFormatStyle = new CellFormat() var cellFormatStyle = new CellFormat()
@ -162,7 +160,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
ApplyFont = true ApplyFont = true
}; };
// В итоге создали 3 стиля //по итогу создали 3 стиля
cellFormats.Append(cellFormatFont); cellFormats.Append(cellFormatFont);
cellFormats.Append(cellFormatFontAndBorder); cellFormats.Append(cellFormatFontAndBorder);
cellFormats.Append(cellFormatTitle); cellFormats.Append(cellFormatTitle);
@ -223,7 +221,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
sp.Stylesheet.Append(stylesheetExtensionList); sp.Stylesheet.Append(stylesheetExtensionList);
} }
// Получение номера стиля (одного из 3-х нами созданных) из типа //Получение номера стиля (одного из 3-х нами созданных) из типа
private static uint GetStyleValue(ExcelStyleInfoType styleInfo) private static uint GetStyleValue(ExcelStyleInfoType styleInfo)
{ {
return styleInfo switch return styleInfo switch
@ -237,7 +235,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
protected override void CreateExcel(ExcelInfo info) protected override void CreateExcel(ExcelInfo info)
{ {
// Создаём документ Excel //создаём документ Excel
_spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook); _spreadsheetDocument = SpreadsheetDocument.Create(info.FileName, SpreadsheetDocumentType.Workbook);
// Создаем книгу (в ней хранятся листы) // Создаем книгу (в ней хранятся листы)
@ -277,7 +275,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
_worksheet = worksheetPart.Worksheet; _worksheet = worksheetPart.Worksheet;
} }
// Метод вставки в лист книги //метод вставки в лист книги
protected override void InsertCellInWorksheet(ExcelCellParameters excelParams) protected override void InsertCellInWorksheet(ExcelCellParameters excelParams)
{ {
if (_worksheet == null || _shareStringPart == null) if (_worksheet == null || _shareStringPart == null)
@ -315,7 +313,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
else else
{ {
// Все ячейки должны быть последовательно друг за другом расположены // Все ячейки должны быть последовательно друг за другом расположены
// Нужно определить, после какой вставлять // нужно определить, после какой вставлять
Cell? refCell = null; Cell? refCell = null;
foreach (Cell rowCell in row.Elements<Cell>()) foreach (Cell rowCell in row.Elements<Cell>())
@ -336,7 +334,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
cell = newCell; cell = newCell;
} }
// Вставляем новый текст // вставляем новый текст
_shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(excelParams.Text))); _shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new Text(excelParams.Text)));
_shareStringPart.SharedStringTable.Save(); _shareStringPart.SharedStringTable.Save();
@ -345,7 +343,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
cell.StyleIndex = GetStyleValue(excelParams.StyleInfo); cell.StyleIndex = GetStyleValue(excelParams.StyleInfo);
} }
// Метод объединения ячеек //метод объединения ячеек
protected override void MergeCells(ExcelMergeParameters excelParams) protected override void MergeCells(ExcelMergeParameters excelParams)
{ {
if (_worksheet == null) if (_worksheet == null)
@ -389,7 +387,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
} }
_spreadsheetDocument.WorkbookPart!.Workbook.Save(); _spreadsheetDocument.WorkbookPart!.Workbook.Save();
_spreadsheetDocument.Dispose(); _spreadsheetDocument.Close();
} }
} }
} }

View File

@ -11,7 +11,7 @@ using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.Implements namespace BankBusinessLogic.OfficePackage.Implements
{ {
// Реализация создания Pdf-документа от абстрактного класса //реализация астрактного класса создания pdf документа
public class SaveToPdf : AbstractSaveToPdf public class SaveToPdf : AbstractSaveToPdf
{ {
private Document? _document; private Document? _document;
@ -20,7 +20,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
private Table? _table; private Table? _table;
// Преобразование необходимого типа выравнивания в соотвествующее выравнивание в MigraDoc //преобразование необходимого типа выравнивания в соотвествующее выравнивание в MigraDoc
private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type) private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type)
{ {
return type switch return type switch
@ -32,7 +32,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
}; };
} }
// Создание стилей для документа //Создание стилей для документа
private static void DefineStyles(Document document) private static void DefineStyles(Document document)
{ {
var style = document.Styles["Normal"]; var style = document.Styles["Normal"];
@ -46,13 +46,13 @@ namespace BankBusinessLogic.OfficePackage.Implements
protected override void CreatePdf(PdfInfo info) protected override void CreatePdf(PdfInfo info)
{ {
// Создаём документ //создаём документ
_document = new Document(); _document = new Document();
// Передаём для него стили //передаём для него стили
DefineStyles(_document); DefineStyles(_document);
// Получение первой секции документа //получение первой секции документа
_section = _document.AddSection(); _section = _document.AddSection();
} }
@ -76,7 +76,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
return; return;
} }
// Добавляем таблицу в документ как последнюю секцию (?) //добавляем таблицу в документ как последнюю секцию (?)
_table = _document.LastSection.AddTable(); _table = _document.LastSection.AddTable();
foreach (var elem in columns) foreach (var elem in columns)
@ -92,12 +92,12 @@ namespace BankBusinessLogic.OfficePackage.Implements
return; return;
} }
// Добавление строки в таблицу //добавление строки в таблицу
var row = _table.AddRow(); var row = _table.AddRow();
for (int i = 0; i < rowParameters.Texts.Count; ++i) for (int i = 0; i < rowParameters.Texts.Count; ++i)
{ {
// Ячейка добавляется добавлением параграфа //ячейка добавляется добавлением параграфа
row.Cells[i].AddParagraph(rowParameters.Texts[i]); row.Cells[i].AddParagraph(rowParameters.Texts[i]);
if (!string.IsNullOrEmpty(rowParameters.Style)) if (!string.IsNullOrEmpty(rowParameters.Style))

View File

@ -1,27 +1,23 @@
using BankBusinessLogic.OfficePackage.HelperEnums; 
using BankBusinessLogic.OfficePackage.HelperEnums;
using BankBusinessLogic.OfficePackage.HelperModels; using BankBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml; using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing; using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.Implements namespace BankBusinessLogic.OfficePackage.Implements
{ {
// Реализация создания Word-документа от абстрактного класса //реализация абстрактного класса сохранения в word
public class SaveToWord : AbstractSaveToWord public class SaveToWord : AbstractSaveToWord
{ {
private WordprocessingDocument? _wordDocument; private WordprocessingDocument? _wordDocument;
private Body? _docBody; private Body? _docBody;
// Получение типа выравнивания //Получение типа выравнивания
private static JustificationValues GetJustificationValues(WordJustificationType type) private static JustificationValues GetJustificationValues(WordJustificationType type)
{ {
// Выравнивание слева будет в том случае, если передаётся неизвестный тип выравнивания //выравнивание слева будет в том случае, если передаётся неизвестный тип выравнивания
return type switch return type switch
{ {
WordJustificationType.Both => JustificationValues.Both, WordJustificationType.Both => JustificationValues.Both,
@ -30,12 +26,12 @@ namespace BankBusinessLogic.OfficePackage.Implements
}; };
} }
// Настройки страницы //Настройки страницы
private static SectionProperties CreateSectionProperties() private static SectionProperties CreateSectionProperties()
{ {
var properties = new SectionProperties(); var properties = new SectionProperties();
// Прописываем портретную ориентацию //прописываем портретную ориентацию
var pageSize = new PageSize var pageSize = new PageSize
{ {
Orient = PageOrientationValues.Portrait Orient = PageOrientationValues.Portrait
@ -46,7 +42,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
return properties; return properties;
} }
// Задание форматирования для абзаца //Задание форматирования для абзаца
private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties) private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties)
{ {
if (paragraphProperties == null) if (paragraphProperties == null)
@ -56,7 +52,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
var properties = new ParagraphProperties(); var properties = new ParagraphProperties();
// Вытаскиваем выравнивание текста //вытаскиваем выравнивание текста
properties.AppendChild(new Justification() properties.AppendChild(new Justification()
{ {
Val = GetJustificationValues(paragraphProperties.JustificationType) Val = GetJustificationValues(paragraphProperties.JustificationType)
@ -86,21 +82,21 @@ namespace BankBusinessLogic.OfficePackage.Implements
protected override void CreateWord(WordInfo info) protected override void CreateWord(WordInfo info)
{ {
// Создаём документ word //создаём документ word
_wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document); _wordDocument = WordprocessingDocument.Create(info.FileName, WordprocessingDocumentType.Document);
// Вытаскиваем главную часть из вордовского документа //вытаскиваем главную часть из вордовского документа
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart(); MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new Document(); mainPart.Document = new Document();
//Ггенерируем тело основной части документа //генерируем тело основной части документа
_docBody = mainPart.Document.AppendChild(new Body()); _docBody = mainPart.Document.AppendChild(new Body());
} }
protected override void CreateParagraph(WordParagraph paragraph) protected override void CreateParagraph(WordParagraph paragraph)
{ {
// Проверка на то, был ли вызван WordprocessingDocument.Create (создался ли документ) и есть ли вообще параграф для вставки //проверка на то, был ли вызван WordprocessingDocument.Create (создался ли документ) и есть ли вообще параграф для вставки
if (_docBody == null || paragraph == null) if (_docBody == null || paragraph == null)
{ {
return; return;
@ -108,16 +104,16 @@ namespace BankBusinessLogic.OfficePackage.Implements
var docParagraph = new Paragraph(); var docParagraph = new Paragraph();
// Добавляем свойства параграфа //добавляем свойства параграфа
docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties)); docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties));
// Вставляем блоки текста (их называют Run) //вставляем блоки текста (их называют Run)
foreach (var run in paragraph.Texts) foreach (var run in paragraph.Texts)
{ {
var docRun = new Run(); var docRun = new Run();
var properties = new RunProperties(); var properties = new RunProperties();
//Ззадание свойств текста - размер и жирность //задание свойств текста - размер и жирность
properties.AppendChild(new FontSize { Val = run.Item2.Size }); properties.AppendChild(new FontSize { Val = run.Item2.Size });
if (run.Item2.Bold) if (run.Item2.Bold)
@ -139,7 +135,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
_docBody.AppendChild(docParagraph); _docBody.AppendChild(docParagraph);
} }
// Метод, отвечающий за создание таблицы //метод, отвечающий за создание таблицы
protected override void CreateTable(WordParagraph paragraph) protected override void CreateTable(WordParagraph paragraph)
{ {
if (_docBody == null || paragraph == null) if (_docBody == null || paragraph == null)
@ -210,7 +206,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
_docBody.AppendChild(table); _docBody.AppendChild(table);
} }
// Метод сохранения документа //метод сохранения документа
protected override void SaveWord(WordInfo info) protected override void SaveWord(WordInfo info)
{ {
if (_docBody == null || _wordDocument == null) if (_docBody == null || _wordDocument == null)
@ -218,13 +214,13 @@ namespace BankBusinessLogic.OfficePackage.Implements
return; return;
} }
// Вставляем информацию по секциям (смотри, что является входным параметром) //вставляем информацию по секциям (смотри, что является входным параметром)
_docBody.AppendChild(CreateSectionProperties()); _docBody.AppendChild(CreateSectionProperties());
// Сохраняем документ //сохраняем документ
_wordDocument.MainDocumentPart!.Document.Save(); _wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Dispose(); _wordDocument.Close();
} }
} }
} }

View File

@ -1,5 +1,4 @@
using Azure; using BankContracts.ViewModels;
using BankContracts.ViewModels;
using BankContracts.ViewModels.Cashier.ViewModels; using BankContracts.ViewModels.Cashier.ViewModels;
using BankContracts.ViewModels.Client.ViewModels; using BankContracts.ViewModels.Client.ViewModels;
using Newtonsoft.Json; using Newtonsoft.Json;
@ -54,21 +53,21 @@ namespace BankCashierApp
} }
//Post-запрос //Post-запрос
public static async Task PostRequest<T>(string requestUrl, T model) public static void PostRequest<T>(string requestUrl, T model)
{ {
var json = JsonConvert.SerializeObject(model); var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json"); var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _client.PostAsync(requestUrl, data); var response = _client.PostAsync(requestUrl, data);
if (!response.IsSuccessStatusCode) var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{ {
var result = await response.Content.ReadAsStringAsync(); throw new Exception(result);
throw new HttpRequestException($"Request failed with status code {response.StatusCode}: {result}");
} }
} }
//Post-запрос для получения данных //Post-запрос для получения данных
public static T? PostRequestReport<T, U>(string requestUrl, U model) public static T? PostRequestReport<T, U>(string requestUrl, U model)
{ {

View File

@ -6,7 +6,6 @@ using BankContracts.ViewModels.Cashier.ViewModels;
using BankContracts.ViewModels.Client.ViewModels; using BankContracts.ViewModels.Client.ViewModels;
using BankContracts.ViewModels.Reports.Cashier; using BankContracts.ViewModels.Reports.Cashier;
using BankContracts.ViewModels.Reports; using BankContracts.ViewModels.Reports;
using BankContracts.ViewModels;
using BankDataModels.Enums; using BankDataModels.Enums;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Diagnostics; using System.Diagnostics;
@ -74,7 +73,7 @@ namespace BankCashierApp.Controllers
Name = name, Name = name,
Surname = surname, Surname = surname,
Patronymic = patronymic, Patronymic = patronymic,
MobilePhone = telephone, Telephone = telephone,
Email = login, Email = login,
Password = password Password = password
}); });
@ -84,7 +83,7 @@ namespace BankCashierApp.Controllers
APICashier.Cashier.Patronymic = patronymic; APICashier.Cashier.Patronymic = patronymic;
APICashier.Cashier.Email = login; APICashier.Cashier.Email = login;
APICashier.Cashier.Password = password; APICashier.Cashier.Password = password;
APICashier.Cashier.MobilePhone = telephone; APICashier.Cashier.Telephone = telephone;
Response.Redirect("Enter"); Response.Redirect("Enter");
} }
@ -207,7 +206,7 @@ namespace BankCashierApp.Controllers
Patronymic = patronymic, Patronymic = patronymic,
Email = login, Email = login,
Password = password, Password = password,
MobilePhone = telephone Telephone = telephone
}); });
//переход на вкладку "Enter", чтобы пользователь сразу смог зайти //переход на вкладку "Enter", чтобы пользователь сразу смог зайти
@ -257,11 +256,12 @@ namespace BankCashierApp.Controllers
return Redirect("ErrorPage"); return Redirect("ErrorPage");
} }
APICashier.PostRequest("/api/Account/RegisterAccount", new AccountBindingModel APICashier.PostRequest("/api/Account/Register", new AccountBindingModel
{ {
CashierId = APICashier.Cashier.Id, CashierId = APICashier.Cashier.Id,
ClientId = clientId, ClientId = clientId,
AccountNumber = accountNumber, AccountNumber = accountNumber,
PasswordAccount = password,
Balance = balance, Balance = balance,
DateOpen = DateTime.Now DateOpen = DateTime.Now
}); });
@ -588,9 +588,10 @@ namespace BankCashierApp.Controllers
var cashWithdrawals = APICashier.GetRequest<List<CashWithdrawalViewModel>>("api/Account/FindAllCashWithdrawal").Where(x => x.AccountId == int.Parse(accountId)) var cashWithdrawals = APICashier.GetRequest<List<CashWithdrawalViewModel>>("api/Account/FindAllCashWithdrawal").Where(x => x.AccountId == int.Parse(accountId))
.Select(x => new ReportCashierAccountsViewModel .Select(x => new ReportCashierAccountsViewModel
{ {
Sum = (int)x.Sum, CashierSurname = x.SurmaneCashier,
Sum = x.Sum,
AccountSenderNumber = x.AccountNumber, AccountSenderNumber = x.AccountNumber,
DateOperation = x.DateWithdrawal, DateOperation = x.DateOperation,
typeOperation = TypeOperationEnum.Снятие typeOperation = TypeOperationEnum.Снятие
}); });
@ -598,10 +599,10 @@ namespace BankCashierApp.Controllers
.Select(x => new ReportCashierAccountsViewModel .Select(x => new ReportCashierAccountsViewModel
{ {
CashierSurname = x.CashierSurname, CashierSurname = x.CashierSurname,
Sum = (int)x.Sum, Sum = x.Sum,
AccountPayeeNumber = x.AccountPayeeNumber, AccountPayeeNumber = x.AccountPayeeNumber,
AccountSenderNumber = x.AccountSenderNumber != null ? x.AccountSenderNumber : "---", AccountSenderNumber = x.AccountSenderNumber != null ? x.AccountSenderNumber : "---",
DateOperation = x.DateTransfer, DateOperation = x.DateOperation,
typeOperation = x.AccountSenderId.HasValue ? TypeOperationEnum.Перевод : TypeOperationEnum.Пополнение typeOperation = x.AccountSenderId.HasValue ? TypeOperationEnum.Перевод : TypeOperationEnum.Пополнение
}); });

View File

@ -1,5 +1,5 @@
@{ @{
ViewData["Title"] = "Одобрение снятия"; ViewData["Title"] = "Одобрение зачислений";
} }
<div class="text-center"> <div class="text-center">

View File

@ -15,7 +15,7 @@
<div class="row mb-2"> <div class="row mb-2">
<div class="col-4">Номер счёта:</div> <div class="col-4">Номер счёта:</div>
<div class="col-8"> <div class="col-8">
<input type="text" id="accountNumber" class="form-control" name="accountNumber" required /> <input type="text" id="accountNumber" class="form-control" name="accountNumber" required/>
</div> </div>
</div> </div>
<div class="row mb-2"> <div class="row mb-2">
@ -27,7 +27,7 @@
<div class="row mb-2"> <div class="row mb-2">
<div class="col-4">Баланс:</div> <div class="col-4">Баланс:</div>
<div class="col-8"> <div class="col-8">
<input type="number" id="balance" class="form-control" name="balance" value=0 required min=0 /> <input type="number" id="balance" class="form-control" name="balance" value=0 required min=0/>
</div> </div>
</div> </div>
<div class="row mb-2"> <div class="row mb-2">

View File

@ -1,4 +1,5 @@
@using BankContracts.ViewModels.Reports; @using BankContracts.ViewModels;
@using BankContracts.ViewModels.Reports
@model ReportCashierViewModelForHTML @model ReportCashierViewModelForHTML
@ -125,3 +126,51 @@
</div> </div>
} }
</form> </form>
<!--@{
ViewData["Title"] = "Создание отчёта";
}
<div class="text-center">
<h2 class="display-4">Создание отчёта</h2>
</div>
<form method="post">
<div class="container px-4">
<div class="row gx-5">
<div class="col">
<div class="p-3">С</div>
</div>
<div class="col">
<div class="p-3 btn-group">
<button class="btn btn-secondary btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false" padding="10">
Начало периода
</button>
<ul class="dropdown-menu">
...
</ul>
</div>
</div>
<div class="col">
<div class="p-3">по</div>
</div>
<div class="col">
<div class="p-3 btn-group">
<button class="btn btn-secondary btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false" padding="10">
Конец периода
</button>
<ul class="dropdown-menu">
...
</ul>
</div>
</div>
<div class="col">
<div class="p-3">
<button type="button" class="btn btn-primary з-3">Создать</button>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-4">Отчёт:</div>
</div>
</form> -->

View File

@ -33,7 +33,10 @@
Сумма зачисления Сумма зачисления
</th> </th>
<th> <th>
Дата заявки Дата открытия заявки
</th>
<th>
Статус заявки
</th> </th>
</tr> </tr>
</thead> </thead>
@ -51,7 +54,10 @@
@Html.DisplayFor(modelItem => item.Sum) @Html.DisplayFor(modelItem => item.Sum)
</td> </td>
<td> <td>
@Html.DisplayFor(modelItem => item.DateCredit) @Html.DisplayFor(modelItem => item.DateOpen)
</td>
<td>
@Html.DisplayFor(modelItem => item.Status)
</td> </td>
</tr> </tr>
} }

View File

@ -36,6 +36,9 @@
<th> <th>
Дата открытия заявки Дата открытия заявки
</th> </th>
<th>
Статус заявки
</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@ -52,7 +55,10 @@
@Html.DisplayFor(modelItem => item.Sum) @Html.DisplayFor(modelItem => item.Sum)
</td> </td>
<td> <td>
@Html.DisplayFor(modelItem => item.DateDebit) @Html.DisplayFor(modelItem => item.DateOpen)
</td>
<td>
@Html.DisplayFor(modelItem => item.Status)
</td> </td>
</tr> </tr>
} }

View File

@ -28,8 +28,7 @@
<div id="@Model.DiagramName Diagram"> <div id="@Model.DiagramName Diagram">
<canvas id="Chart"></canvas> <canvas id="Chart"></canvas>
<div id="params"> <div id="params">
@foreach (var info in Model.Elements) @foreach (var info in Model.Elements) {
{
<input type="hidden" id="@info.Name" value="@info.Value" /> <input type="hidden" id="@info.Name" value="@info.Value" />
} }
</div> </div>

View File

@ -1,4 +1,4 @@
@using BankContracts.ViewModels @using BankContracts.ViewModels.Cashier.ViewModels
@model List<AccountViewModel> @model List<AccountViewModel>

View File

@ -25,7 +25,7 @@
<div class="row mb-2"> <div class="row mb-2">
<div class="col-4">Сумма перевода:</div> <div class="col-4">Сумма перевода:</div>
<div class="col-8"> <div class="col-8">
<input type="number" id="sumMoneyTransfer" class="form-control" name="sumMoneyTransfer" required min=1 value=1 /> <input type="number" id="sumMoneyTransfer" class="form-control" name="sumMoneyTransfer" required min=1 value=1/>
</div> </div>
</div> </div>
<div class="row mb-2"> <div class="row mb-2">

View File

@ -1,4 +1,5 @@
@using BankContracts.ViewModels.Cashier.ViewModels @using BankContracts.ViewModels
@using BankContracts.ViewModels.Cashier.ViewModels
@model CashierViewModel @model CashierViewModel
@ -28,10 +29,10 @@
</div> </div>
<div class="row mb-2"> <div class="row mb-2">
<div class="col-4">Телефон:</div> <div class="col-4">Телефон:</div>
<input type="text" id="telephone" name="telephone" class="form-control" placeholder="Телефон" value=@Html.DisplayFor(modelItem => Model.MobilePhone) required> <input type="text" id="telephone" name="telephone" class="form-control" placeholder="Телефон" value=@Html.DisplayFor(modelItem => Model.Telephone) required>
</div> </div>
<div class="row mb-2"> <div class="row mb-2">
<button class="btn btn-lg btn-warning btn-block mb-2" type="submit" asp-controller="Home" asp-action="Privacy">Coхранить</button> <button class="btn btn-lg btn-dark btn-block mb-2" type="submit" asp-controller="Home" asp-action="Privacy">Coхранить</button>
<button class="btn btn-lg btn-warning btn-block" type="submit" asp-controller="Home" asp-action="Logout">Выйти из аккаунта</button> <button class="btn btn-lg btn-dark btn-block" type="submit" asp-controller="Home" asp-action="Logout">Выйти из аккаунта</button>
</div> </div>
</form> </form>

View File

@ -6,33 +6,13 @@
<h2 class="display-4">Регистрация</h2> <h2 class="display-4">Регистрация</h2>
</div> </div>
<form class="form-signin text-center" method="post"> <form class="form-signin text-center" method="post">
<input type="email" id="login" name="login" class="form-control short-input mb-2" placeholder="Почта" required> <h1 class="h3 mb-3 font-weight-normal">Регистрация</h1>
<input type="password" id="password" name="password" class="form-control short-input mb-2" placeholder="Пароль" required> <input type="email" id="login" name="login" class="form-control" placeholder="Почта" required>
<input type="text" id="name" name="name" class="form-control short-input mb-2" placeholder="Имя" required> <input type="password" id="password" name="password" class="form-control" placeholder="Пароль" required>
<input type="text" id="surname" name="surname" class="form-control short-input mb-2" placeholder="Фамилия" required> <input type="text" id="name" name="name" class="form-control" placeholder="Имя" required>
<input type="text" id="patronymic" name="patronymic" class="form-control short-input mb-2" placeholder="Отчество" required> <input type="text" id="surname" name="surname" class="form-control" placeholder="Фамилия" required>
<input type="text" id="telephone" name="telephone" class="form-control short-input mb-2" placeholder="Телефон" required> <input type="text" id="patronymic" name="patronymic" class="form-control" placeholder="Отчество" required>
<input type="text" id="telephone" name="telephone" class="form-control" placeholder="Телефон" required>
<button class="btn btn-lg btn-dark btn-block mt-3" type="submit" asp-controller="Home" asp-action="Register">Зарегистрироваться</button> <button class="btn btn-lg btn-dark btn-block" type="submit" asp-controller="Home" asp-action="Register">Регистрация</button>
</form> </form>
<style>
.form-signin {
max-width: 300px;
margin: auto;
}
.short-input {
width: 100%;
padding: 10px;
margin-bottom: 15px;
}
.mb-2 {
margin-bottom: 10px;
}
.mt-3 {
margin-top: 20px;
}
</style>

View File

@ -1,4 +1,5 @@
@using BankContracts.ViewModels.Reports.Cashier @using BankContracts.ViewModels
@using BankContracts.ViewModels.Reports.Cashier
@model List<ReportCashierAccountsViewModel>? @model List<ReportCashierAccountsViewModel>?

View File

@ -1,67 +1,165 @@
<!DOCTYPE html> @using BankCashierApp
<html lang="ru">
@{
bool authenticated = APICashier.Cashier != null;
}
<!DOCTYPE html>
<html lang="en">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - BankCashierApp</title> <title>@ViewData["Title"]</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /> <link rel="stylesheet" href="~/css/site.css" />
<link rel="stylesheet" href="~/BankCashierApp.styles.css" asp-append-version="true" />
<script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<style> <style>
body.MyBody {
background-color: #f8f9fa; body {
margin-bottom: 60px;
background-color: #ececec; /* Измененный цвет фона */
color: #333; /* Основной цвет текста */
}
.nav-main a {
position: relative;
color: #333;
cursor: pointer;
line-height: 1.5;
text-decoration: none;
padding: 10px;
transition: color 0.3s ease-out;
}
.nav-main a:after {
display: block;
position: absolute;
left: 0;
bottom: -5px;
width: 0;
height: 2px;
background-color: #333;
content: "";
transition: width 0.3s ease-out;
}
.nav-main a:hover, .nav-main a:focus {
color: #007bff; /* Цвет при наведении */
}
.nav-main a:hover:after,
.nav-main a:focus:after {
width: 100%;
}
.nav-main .dropdown:hover .dropdown-menu {
display: block;
margin-top: 0;
}
.footer {
position: fixed;
left: 0;
bottom: 0;
width: 100%;
height: 80px;
background-color: #333;
color: #fff;
}
.form-signin {
width: 100%;
max-width: 400px;
padding: 20px;
margin: auto;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.form-signin .form-control {
position: relative;
box-sizing: border-box;
height: auto;
padding: 10px;
font-size: 16px;
}
.form-signin .form-control:focus {
z-index: 2;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-signin input[type="password"] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
table.table tbody tr td,
table.table thead tr th,
table.table thead {
border-left: solid;
border-right: solid;
border-width: 2px;
border-color: #333;
}
table {
vertical-align: middle;
} }
header { header {
background-color: #343a40; background-color: #007bff; /* Цвет фона шапки */
color: #fff; /* Цвет текста шапки */
} }
header a { header a {
color: #fff !important; color: #fff; /* Цвет текста ссылок в шапке */
} }
header .btn-warning { header a:hover {
color: #343a40; color: #ffd700; /* Цвет текста ссылок при наведении */
} }
header .dropdown-menu { .btn-custom {
background-color: #343a40; background-color: #007bff; /* Пользовательский цвет кнопки */
color: #fff; /* Цвет текста кнопки */
border: none;
} }
.nav-link:hover, .dropdown-item:hover { .btn-custom:hover {
background-color: #495057; background-color: #0056b3; /* Цвет кнопки при наведении */
}
footer {
padding: 1rem 0;
} }
</style> </style>
</head> </head>
<body class="MyBody"> <body class="MyBody">
<header class="d-flex flex-wrap align-items-center justify-content-center justify-content-md-between py-3 px-4 mb-4 border-bottom"> <header class="d-flex flex-wrap align-items-center justify-content-between py-3 px-4 mb-4 border-bottom">
<div class="col-md-3 mb-2 mb-md-0"> <div class="col-md-3 mb-2 mb-md-0">
<a asp-controller="Home" asp-action="Enter" class="d-inline-flex link-body-emphasis text-decoration-none"> <a asp-controller="Home" asp-action="Enter" class="d-inline-flex link-body-emphasis text-decoration-none">
<span class="fs-4 text-light">Банк "Вы банкрот"</span> <span class="fs-4">Банк "Вы банкрот"</span>
</a> </a>
</div> </div>
<ul class="nav col-12 col-md-auto mb-2 justify-content-center mb-md-0 nav-main"> <ul class="nav col-12 col-md-auto mb-2 justify-content-center mb-md-0 nav-main">
<li> <li><a class="nav-link px-2" asparea="" asp-controller="Home" asp-action="Index">Счета</a></li>
<a class="nav-link px-2 link-light" asparea="" asp-controller="Home" asp-action="Index">Счета</a>
</li>
<li class="dropdown"> <li class="dropdown">
<a href="#" class="nav-link px-2 link-light dropdown-toggle" id="navbarOperations" role="button" data-bs-toggle="dropdown" aria-expanded="false">Операции</a> <a href="#" class="nav-link px-2">Операции</a>
<ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarOperations"> <ul class="dropdown-menu">
<li><a class="dropdown-item" asp-controller="Home" asp-action="Debiting">Заявки на снятие</a></li> <li><a class="dropdown-item" asp-controller="Home" asp-action="Debiting">Заявки на снятие</a></li>
<li><a class="dropdown-item" asp-controller="Home" asp-action="Crediting">Заявки на начисление</a></li> <li><a class="dropdown-item" asp-controller="Home" asp-action="Crediting">Заявки на начисление</a></li>
<li><a class="dropdown-item" asp-controller="Home" asp-action="MoneyTransfers">Заявки на перевод</a></li> <li><a class="dropdown-item" asp-controller="Home" asp-action="MoneyTransfers">Заявки на перевод</a></li>
</ul> </ul>
</li> </li>
<li class="dropdown"> <li class="dropdown">
<a href="#" class="nav-link px-2 link-light dropdown-toggle" id="navbarReports" role="button" data-bs-toggle="dropdown" aria-expanded="false">Отчеты</a> <a href="#" class="nav-link px-2">Отчеты</a>
<ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarReports"> <ul class="dropdown-menu">
<li><a class="dropdown-item" asp-controller="Home" asp-action="ReportWithAccounts">Отчёт по аккаунтам</a></li> <li><a class="dropdown-item" asp-controller="Home" asp-action="ReportWithAccounts">Отчёт по аккаунтам</a></li>
<li><a class="dropdown-item" asp-controller="Home" asp-action="CreateReport">Отчёт за период</a></li> <li><a class="dropdown-item" asp-controller="Home" asp-action="CreateReport">Отчёт за период</a></li>
<li><a class="dropdown-item" asp-controller="Home" asp-action="Diagram">Диаграмма</a></li> <li><a class="dropdown-item" asp-controller="Home" asp-action="Diagram">Диаграмма</a></li>
@ -72,14 +170,14 @@
if (APICashier.Cashier == null) if (APICashier.Cashier == null)
{ {
<div class="col-md-3 text-end"> <div class="col-md-3 text-end">
<a class="btn btn-warning me-2" asp-controller="Home" asp-action="Login">Войти</a> <a class="btn btn-custom me-2" asp-controller="Home" asp-action="Login">Войти</a>
<a class="btn btn-warning" asp-controller="Home" asp-action="Register">Регистрация</a> <a class="btn btn-custom" asp-controller="Home" asp-action="Register">Регистрация</a>
</div> </div>
} }
else else
{ {
<div class="col-md-3 text-end"> <div class="col-md-3 text-end">
<a class="btn btn-warning me-2" id="exit" name="exit" asp-controller="Home" asp-action="Privacy">@APICashier.Cashier.Surname @APICashier.Cashier.Name</a> <a class="btn btn-custom me-2" id="exit" name="exit" asp-controller="Home" asp-action="Privacy">@APICashier.Cashier.Surname @APICashier.Cashier.Name</a>
</div> </div>
} }
} }
@ -90,7 +188,7 @@
</main> </main>
</div> </div>
<footer class="border-top bg-dark border-dark footer text-light"> <footer class="border-top footer">
<div class="container text-center"> <div class="container text-center">
&copy; 2024 - BankCashierApp &copy; 2024 - BankCashierApp
</div> </div>

View File

@ -26,6 +26,7 @@ a {
.border-top { .border-top {
border-top: 1px solid #e5e5e5; border-top: 1px solid #e5e5e5;
} }
.border-bottom { .border-bottom {
border-bottom: 1px solid #e5e5e5; border-bottom: 1px solid #e5e5e5;
} }

View File

@ -1,10 +1,9 @@
using Azure; using BankContracts.ViewModels.Client.ViewModels;
using BankContracts.ViewModels.Client.ViewModels;
using Newtonsoft.Json; using Newtonsoft.Json;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text; using System.Text;
namespace BankClientApp namespace BankСlientApp
{ {
public class APIClient public class APIClient
{ {
@ -26,7 +25,7 @@ namespace BankClientApp
ErrorMessage = error; ErrorMessage = error;
} }
// Get-запрос //Get-запрос
public static T? GetRequest<T>(string requestUrl) public static T? GetRequest<T>(string requestUrl)
{ {
var response = _client.GetAsync(requestUrl); var response = _client.GetAsync(requestUrl);
@ -43,7 +42,7 @@ namespace BankClientApp
} }
} }
// Post-запрос //Post-запрос
public static void PostRequest<T>(string requestUrl, T model) public static void PostRequest<T>(string requestUrl, T model)
{ {
var json = JsonConvert.SerializeObject(model); var json = JsonConvert.SerializeObject(model);
@ -59,7 +58,7 @@ namespace BankClientApp
} }
} }
// Post-запрос для получения данных //Post-запрос для получения данных
public static T? PostRequestReport<T, U>(string requestUrl, U model) public static T? PostRequestReport<T, U>(string requestUrl, U model)
{ {
var json = JsonConvert.SerializeObject(model); var json = JsonConvert.SerializeObject(model);

View File

@ -11,6 +11,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\BankBusinessLogic\BankBusinessLogic.csproj" />
<ProjectReference Include="..\BankContracts\BankContracts.csproj" /> <ProjectReference Include="..\BankContracts\BankContracts.csproj" />
<ProjectReference Include="..\BankDatabaseImplement\BankDatabaseImplement.csproj" /> <ProjectReference Include="..\BankDatabaseImplement\BankDatabaseImplement.csproj" />
</ItemGroup> </ItemGroup>

View File

@ -1,15 +1,15 @@
using BankClientApp.Models; using BankClientApp.Models;
using BankContracts.ViewModels.Client.Diagram;
using BankDataModels.Enums;
using BankСlientApp;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using BankContracts.BindingModels.Client; using BankContracts.BindingModels.Client;
using BankContracts.BindingModels.Reports; using BankContracts.BindingModels.Reports;
using BankContracts.ViewModels; using BankContracts.ViewModels.Cashier.ViewModels;
using BankContracts.ViewModels.Client.Diagram;
using BankContracts.ViewModels.Client.ViewModels; using BankContracts.ViewModels.Client.ViewModels;
using BankContracts.ViewModels.Reports;
using BankContracts.ViewModels.Reports.Client; using BankContracts.ViewModels.Reports.Client;
using BankDataModels.Enums; using BankContracts.ViewModels.Reports;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.Diagnostics;
namespace BankClientApp.Controllers namespace BankClientApp.Controllers
{ {
@ -22,11 +22,7 @@ namespace BankClientApp.Controllers
_logger = logger; _logger = logger;
} }
// Профиль, вход и регистрация #region Профиль, вход и регистрация
public IActionResult Index()
{
return View();
}
[HttpGet] [HttpGet]
public IActionResult Enter() public IActionResult Enter()
@ -37,19 +33,20 @@ namespace BankClientApp.Controllers
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error() public IActionResult Error()
{ {
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); return View(new ErrorViewModel
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
});
} }
[HttpGet] [HttpGet]
public IActionResult ErrorPage() public IActionResult Login()
{ {
return View(); return View();
} }
// Логин и регистрация
[HttpGet] [HttpGet]
public IActionResult Login() public IActionResult ErrorPage()
{ {
return View(); return View();
} }
@ -68,7 +65,7 @@ namespace BankClientApp.Controllers
if (APIClient.Client == null) if (APIClient.Client == null)
{ {
APIClient.SetErrorMessage("Неверный логин и пароль"); APIClient.SetErrorMessage("Неверный логин или пароль");
return Redirect("ErrorPage"); return Redirect("ErrorPage");
} }
@ -76,17 +73,19 @@ namespace BankClientApp.Controllers
return Redirect("Enter"); return Redirect("Enter");
} }
[HttpGet] [HttpGet]
public IActionResult Register() public IActionResult Register()
{ {
return View(); return View();
} }
[HttpPost] [HttpPost]
public void Register(string login, string password, string name, string surname, string patronymic, string mobilephone) 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) if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(name)
|| string.IsNullOrEmpty(surname) || string.IsNullOrEmpty(patronymic) || string.IsNullOrEmpty(mobilephone)) || string.IsNullOrEmpty(surname) || string.IsNullOrEmpty(patronymic) || string.IsNullOrEmpty(telephone))
{ {
APIClient.SetErrorMessage("Проверьте правильность заполнения полей"); APIClient.SetErrorMessage("Проверьте правильность заполнения полей");
@ -100,7 +99,7 @@ namespace BankClientApp.Controllers
Patronymic = patronymic, Patronymic = patronymic,
Email = login, Email = login,
Password = password, Password = password,
MobilePhone = mobilephone Telephone = telephone
}); });
Response.Redirect("Enter"); Response.Redirect("Enter");
@ -116,6 +115,7 @@ namespace BankClientApp.Controllers
return Redirect("~/Home/Enter"); return Redirect("~/Home/Enter");
} }
[HttpGet]
public IActionResult Privacy() public IActionResult Privacy()
{ {
if (APIClient.Client == null) if (APIClient.Client == null)
@ -127,15 +127,16 @@ namespace BankClientApp.Controllers
} }
[HttpPost] [HttpPost]
public void Privacy(string login, string password, string name, string surname, string patronymic, string mobilephone) public void Privacy(string login, string password, string name, string surname, string patronymic, string telephone)
{ {
if (APIClient.Client == null) if (APIClient.Client == null)
{ {
throw new Exception("Вы как сюда попали? Сюда вход только авторизованным"); throw new Exception("Вы как сюда попали? Суда вход только авторизованным");
} }
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(name) if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(name)
|| string.IsNullOrEmpty(surname) || string.IsNullOrEmpty(patronymic) || string.IsNullOrEmpty(mobilephone)) || string.IsNullOrEmpty(surname) || string.IsNullOrEmpty(patronymic)
|| string.IsNullOrEmpty(telephone))
{ {
APIClient.SetErrorMessage("Проверьте правильность заполнения полей"); APIClient.SetErrorMessage("Проверьте правильность заполнения полей");
@ -148,7 +149,7 @@ namespace BankClientApp.Controllers
Name = name, Name = name,
Surname = surname, Surname = surname,
Patronymic = patronymic, Patronymic = patronymic,
MobilePhone = mobilephone, Telephone = telephone,
Email = login, Email = login,
Password = password Password = password
}); });
@ -158,14 +159,14 @@ namespace BankClientApp.Controllers
APIClient.Client.Patronymic = patronymic; APIClient.Client.Patronymic = patronymic;
APIClient.Client.Email = login; APIClient.Client.Email = login;
APIClient.Client.Password = password; APIClient.Client.Password = password;
APIClient.Client.MobilePhone = mobilephone; APIClient.Client.Telephone = telephone;
Response.Redirect("Enter"); Response.Redirect("Enter");
} }
// Банковские карты, работа с картами // #endregion
#region Карты
[HttpGet] [HttpGet]
public IActionResult CardsList() public IActionResult CardsList()
{ {
@ -174,7 +175,7 @@ namespace BankClientApp.Controllers
return Redirect("~/Home/Enter"); return Redirect("~/Home/Enter");
} }
return View(APIClient.GetRequest<List<CardViewModel>>($"api/Card/GetClientsCardsList?id={APIClient.Client.Id}")); return View(APIClient.GetRequest<List<CardViewModel>>($"api/Card/GetUsersCardsList?id={APIClient.Client.Id}"));
} }
[HttpGet] [HttpGet]
@ -185,12 +186,12 @@ namespace BankClientApp.Controllers
return Redirect("~/Home/Enter"); return Redirect("~/Home/Enter");
} }
ViewBag.Accounts = APIClient.GetRequest<List<AccountViewModel>>($"api/Account/SearchAccountsOfClient?clientId={APIClient.Client.Id}"); ViewBag.Accounts = APIClient.GetRequest<List<AccountViewModel>>($"api/Account/SearchAccountsOfCLient?clientId={APIClient.Client.Id}");
return View(); return View();
} }
[HttpPost] [HttpPost]
public IActionResult CreateCard(string accountId, string number, double balance, DateTime period) public IActionResult CreateCard(string accountId, string number, string cvc, DateTime period)
{ {
if (APIClient.Client == null) if (APIClient.Client == null)
{ {
@ -199,7 +200,7 @@ namespace BankClientApp.Controllers
return Redirect("ErrorPage"); return Redirect("ErrorPage");
} }
if (string.IsNullOrEmpty(accountId) || string.IsNullOrEmpty(number) || balance < 0 if (string.IsNullOrEmpty(accountId) || string.IsNullOrEmpty(number) || string.IsNullOrEmpty(cvc)
|| period.Year == 0001 || period <= DateTime.Now) || period.Year == 0001 || period <= DateTime.Now)
{ {
APIClient.SetErrorMessage("Проверьте корректность параметров создаваемой карты"); APIClient.SetErrorMessage("Проверьте корректность параметров создаваемой карты");
@ -209,18 +210,19 @@ namespace BankClientApp.Controllers
APIClient.PostRequest("api/Card/CreateCard", new CardBindingModel APIClient.PostRequest("api/Card/CreateCard", new CardBindingModel
{ {
Id = APIClient.Client.Id, ClientID = APIClient.Client.Id,
AccountId = int.Parse(accountId), AccountId = int.Parse(accountId),
Number = number, Number = number,
Balance = balance, CVC = cvc,
Period = period, Period = period
}); });
return Redirect("~/Home/CardsList"); return Redirect("~/Home/CardsList");
} }
#endregion
// Снятие средств с банковской карты #region Снятие средств
[HttpGet] [HttpGet]
public IActionResult DebitingList() public IActionResult DebitingList()
@ -266,14 +268,16 @@ namespace BankClientApp.Controllers
{ {
CardId = int.Parse(cardId), CardId = int.Parse(cardId),
Sum = sum, Sum = sum,
//DateOpen = DateTime.Now, DateOpen = DateTime.Now,
//Status = StatusEnum.Открыта Status = StatusEnum.Открыта
}); });
return Redirect("~/Home/DebitingList"); return Redirect("~/Home/DebitingList");
} }
// === Пополнение средств === // #endregion
#region Пополнение средств
[HttpGet] [HttpGet]
public IActionResult CreditingList() public IActionResult CreditingList()
@ -317,14 +321,16 @@ namespace BankClientApp.Controllers
{ {
CardId = int.Parse(cardId), CardId = int.Parse(cardId),
Sum = sum, Sum = sum,
//DateOpen = DateTime.Now, DateOpen = DateTime.Now,
//Status = StatusEnum.Открыта Status = StatusEnum.Открыта
}); });
return Redirect("~/Home/CreditingList"); return Redirect("~/Home/CreditingList");
} }
//=== Получение отчёта PDF ===// #endregion
#region Получение отчёта PDF
[HttpGet] [HttpGet]
public IActionResult CreateReport() public IActionResult CreateReport()
@ -360,9 +366,11 @@ namespace BankClientApp.Controllers
})); }));
} }
//=== Excel отчёты ===// #endregion
// Отчёт клиента по переводам #region Excel отчёты
//отчёт клиента по переводам
[HttpPost] [HttpPost]
public IActionResult CreateExcelReport(List<CheckboxViewModel> cards) public IActionResult CreateExcelReport(List<CheckboxViewModel> cards)
{ {
@ -389,7 +397,7 @@ namespace BankClientApp.Controllers
return Redirect("ReportSuccess"); return Redirect("ReportSuccess");
} }
// Отчёт клиента по пополнениям //отчёт клиента по пополнениям
[HttpPost] [HttpPost]
public IActionResult CreateCreditingExcelReport(List<CheckboxViewModel> cards) public IActionResult CreateCreditingExcelReport(List<CheckboxViewModel> cards)
{ {
@ -416,7 +424,7 @@ namespace BankClientApp.Controllers
return Redirect("ReportSuccess"); return Redirect("ReportSuccess");
} }
// Отчёт клиента по снятиям //отчёт клиента по снятиям
[HttpPost] [HttpPost]
public IActionResult CreateDebitingExcelReport(List<CheckboxViewModel> cards) public IActionResult CreateDebitingExcelReport(List<CheckboxViewModel> cards)
{ {
@ -443,9 +451,11 @@ namespace BankClientApp.Controllers
return Redirect("ReportSuccess"); return Redirect("ReportSuccess");
} }
//=== Word отчёты клиента ===// #endregion
// Отчёт клиента по переводам #region Word отчёты клиента
//отчёт клиента по переводам
[HttpPost] [HttpPost]
public IActionResult CreateWordReport(List<CheckboxViewModel> cards) public IActionResult CreateWordReport(List<CheckboxViewModel> cards)
{ {
@ -472,7 +482,7 @@ namespace BankClientApp.Controllers
return Redirect("ReportSuccess"); return Redirect("ReportSuccess");
} }
// Отчёт клиента по пополнениям //отчёт клиента по пополнениям
[HttpPost] [HttpPost]
public IActionResult CreateCreditingWordReport(List<CheckboxViewModel> cards) public IActionResult CreateCreditingWordReport(List<CheckboxViewModel> cards)
{ {
@ -499,7 +509,7 @@ namespace BankClientApp.Controllers
return Redirect("ReportSuccess"); return Redirect("ReportSuccess");
} }
// Отчёт клиента по снятиям //отчёт клиента по снятиям
[HttpPost] [HttpPost]
public IActionResult CreateDebitingWordReport(List<CheckboxViewModel> cards) public IActionResult CreateDebitingWordReport(List<CheckboxViewModel> cards)
{ {
@ -526,8 +536,9 @@ namespace BankClientApp.Controllers
return Redirect("ReportSuccess"); return Redirect("ReportSuccess");
} }
// === Получение отчета по картам === // #endregion
#region Получение отчета по картам
[HttpGet] [HttpGet]
public IActionResult ReportWithCards() public IActionResult ReportWithCards()
{ {
@ -566,42 +577,43 @@ namespace BankClientApp.Controllers
List<int> cardList = cards.Where(x => x.IsChecked).Select(x => x.Id).ToList(); List<int> cardList = cards.Where(x => x.IsChecked).Select(x => x.Id).ToList();
//List<ReportViewModel> creditings = APIClient.GetRequest<List<CreditingViewModel>>($"api/Client/getUsersCreditings?userId={APIClient.Client.Id}") List<ReportViewModel> creditings = APIClient.GetRequest<List<CreditingViewModel>>($"api/Client/getUsersCreditings?userId={APIClient.Client.Id}")
// .Where(x => cardList.Contains(x.CardId)).Select(x => new ReportViewModel() .Where(x => cardList.Contains(x.CardId)).Select(x => new ReportViewModel()
// { {
// Id = x.Id, Id = x.Id,
// CardId = x.CardId, CardId = x.CardId,
// // DateOpen = x.DateOpen, DateOpen = x.DateOpen,
// // DateClose = x.DateClose, DateClose = x.DateClose,
// CardNumber = x.CardNumber, CardNumber = x.CardNumber,
// //Status = x.Status, Status = x.Status,
// Sum = x.Sum, Sum = x.Sum,
// TypeOperation = TypeOperationEnum.Пополнение TypeOperation = TypeOperationEnum.Пополнение
// }).ToList(); }).ToList();
//List<ReportViewModel> debitings = APIClient.GetRequest<List<DebitingViewModel>>($"api/Client/getUsersDebitings?userId={APIClient.Client.Id}") List<ReportViewModel> debitings = APIClient.GetRequest<List<DebitingViewModel>>($"api/Client/getUsersDebitings?userId={APIClient.Client.Id}")
// .Where(x => cardList.Contains(x.CardId)).Select(x => new ReportViewModel() .Where(x => cardList.Contains(x.CardId)).Select(x => new ReportViewModel()
// { {
// Id = x.Id, Id = x.Id,
// CardId = x.CardId, CardId = x.CardId,
// DateOpen = x.DateOpen, DateOpen = x.DateOpen,
// DateClose = x.DateClose, DateClose = x.DateClose,
// CardNumber = x.CardNumber, CardNumber = x.CardNumber,
// Status = x.Status, Status = x.Status,
// Sum = x.Sum, Sum = x.Sum,
// TypeOperation = TypeOperationEnum.Снятие TypeOperation = TypeOperationEnum.Снятие
// }).ToList(); }).ToList();
//List<ReportViewModel> result = creditings.Concat(debitings).OrderBy(x => x.DateOpen).ToList(); List<ReportViewModel> result = creditings.Concat(debitings).OrderBy(x => x.DateOpen).ToList();
return View(new ReportClientCardsViewModel() return View(new ReportClientCardsViewModel()
{ {
Cards = cards, Cards = cards,
//Operations = result, Operations = result,
}); });
} }
#endregion
// === Диаграмма === // #region Диаграмма
[HttpGet] [HttpGet]
public IActionResult Diagram() public IActionResult Diagram()
@ -635,7 +647,9 @@ namespace BankClientApp.Controllers
}); });
} }
// Сообщение об успешной отправке отчёта на почту #endregion
//сообщение об успешной отправке отчёта на почту
[HttpGet] [HttpGet]
public IActionResult ReportSuccess() public IActionResult ReportSuccess()
{ {

View File

@ -1,4 +1,4 @@
using BankClientApp; using BankÑlientApp;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -26,6 +26,6 @@ app.UseAuthorization();
app.MapControllerRoute( app.MapControllerRoute(
name: "default", name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"); pattern: "{controller=Home}/{action=Enter}/{id?}");
app.Run(); app.Run();

View File

@ -1,19 +1,25 @@
@using BankContracts.ViewModels.Client.ViewModels @using BankContracts.ViewModels.Client.ViewModels
@model List<CardViewModel> @model List<CardViewModel>
@{ @{
ViewData["Title"] = "Cписок банковских карт"; ViewData["Title"] = "Список карт";
} }
<div class="text-center"> <div class="text-center">
<h1 class="display-4">Банковские карты</h1> <h1 class="display-4">Карты</h1>
</div> </div>
<div class="text-center"> <div class="text-center">
@{ @{
if (Model == null)
{
<h3 class="display-4">Сначала авторизируйтесь</h3>
return;
}
<p> <p>
<a asp-action="CreateCard">Оформить банковскую карту</a> <a asp-action="CreateCard">Создать карту</a>
</p> </p>
<table class="table"> <table class="table">
<thead> <thead>
@ -21,17 +27,14 @@
<th> <th>
Номер карты Номер карты
</th> </th>
<th>
Фамилия владельца
</th>
<th>
Имя владельца
</th>
<th> <th>
Баланс Баланс
</th> </th>
<th> <th>
Период CVC
</th>
<th>
Срок действия
</th> </th>
</tr> </tr>
</thead> </thead>
@ -43,17 +46,16 @@
@Html.DisplayFor(modelItem => item.Number) @Html.DisplayFor(modelItem => item.Number)
</td> </td>
<td> <td>
@Html.DisplayFor(modelItem => item.ClientSurname) @Html.DisplayFor(modelItem => item.Sum)
</td> </td>
<td> <td>
@Html.DisplayFor(modelItem => item.Balance) @Html.DisplayFor(modelItem => item.CVC)
</td> </td>
<td> <td>
@Html.DisplayFor(modelItem => item.Period) @Html.DisplayFor(modelItem => item.Period)
</td> </td>
</tr> </tr>
} }
</tbody> </tbody>
</table> </table>
} }

View File

@ -1,43 +1,41 @@
@{ @{
ViewData["Title"] = "Оформление банковской карты"; ViewData["Title"] = "Создание карты";
} }
<div class="text-center"> <div class="text-center">
<h2 class="display-4">Оформление банковской карты</h2> <h2 class="display-4">Создание карты</h2>
</div> </div>
<form method="post"> <form method="post">
<div class="row mb-2"> <div class="row mb-2">
<div class="col-4">Номер счёта:</div> <div class="col-4">Номер счета:</div>
<div class="col-8"> <div class="col-8">
<select id="account" name="accountId" class="form-control" asp-items="@(new SelectList( @ViewBag.Accounts, "Id", "AccountNumber"))"></select> <select id="accountId" name="accountId" class="form-control" asp-items="@(new SelectList( @ViewBag.Accounts, "Id", "AccountNumber"))"></select>
</div> </div>
</div> </div>
<div class="row mb-2"> <div class="row mb-2">
<div class="col-4">Номер карты:</div> <div class="col-4">Номер карты:</div>
<div class="col-8"> <div class="col-8">
<input type="text" id="number" class="form-control" name="number" required /> <input type="text" class="form-control" name="number" id="number" required />
</div> </div>
</div> </div>
<div class="row mb-2"> <div class="row mb-2">
<div class="col-4">Период:</div> <div class="col-4">CVC:</div>
<div class="col-8"> <div class="col-8">
<input type="date" id="period" class="form-control" name="period" required /> <input type="text" class="form-control" name="cvc" id="cvc" required />
</div> </div>
</div> </div>
<div class="row mb-2"> <div class="row mb-2">
<div class="col-4">Баланс:</div> <div class="col-4">Срок действия:</div>
<div class="col-8"> <div class="col-8">
<input type="number" id="balance" class="form-control" name="balance" value=0 required min=0 /> <input type="date" class="form-control" name="period" id="period" required />
</div> </div>
</div> </div>
<div class="row mb-2"> <div class="row mb-2">
<div class="col-8"></div> <input type="submit" value="Создание" style="width: 100%" class="btn btn-warning" />
<div class="col-4">
<input type="submit" value="Создать" class="form-control" class="btn btn-dark" />
</div>
</div> </div>
</form> </form>
<script> <script>
function createNum(len) { function createNum(len) {
chrs = '0123456789'; chrs = '0123456789';
@ -50,6 +48,7 @@
} }
document.getElementById("number").value = createNum(16); document.getElementById("number").value = createNum(16);
document.getElementById("cvc").value = createNum(3);
let year = new Date(); let year = new Date();
year.setFullYear(year.getFullYear() + 5) year.setFullYear(year.getFullYear() + 5)
document.getElementById("period").valueAsDate = new Date(year); document.getElementById("period").valueAsDate = new Date(year);

View File

@ -0,0 +1,24 @@
@{
ViewData["Title"] = "Операция пополнения";
}
<div class="text-center">
<h2 class="display-4">Создание операции</h2>
</div>
<form method="post">
<div class="row mb-2">
<div class="col-4">Номер карты:</div>
<div class="col-8">
<select id="cardId" name="cardId" class="form-control" asp-items="@(new SelectList( @ViewBag.Cards, "Id", "Number"))"></select>
</div>
</div>
<div class="row mb-2">
<div class="col-4">Cумма операции:</div>
<div class="col-8">
<input type="number" class="form-control" name="sum" required autofocus/>
</div>
</div>
<div class="row mb-2">
<input type="submit" value="Создание" style="width: 100%" class="btn btn-warning" />
</div>
</form>

View File

@ -0,0 +1,24 @@
@{
ViewData["Title"] = "Операция снятия";
}
<div class="text-center">
<h2 class="display-4">Создание операции</h2>
</div>
<form method="post">
<div class="row mb-2">
<div class="col-4">Номер карты:</div>
<div class="col-8">
<select id="cardId" name="cardId" class="form-control" asp-items="@(new SelectList( @ViewBag.Cards, "Id", "Number"))"></select>
</div>
</div>
<div class="row mb-2">
<div class="col-4">Cумма операции:</div>
<div class="col-8">
<input type="number" name="sum" class="form-control" required autofocus />
</div>
</div>
<div class="row mb-2">
<input type="submit" style="width: 100%" value="Создание" class="btn btn-warning" />
</div>
</form>

View File

@ -0,0 +1,20 @@
@{
ViewData["Title"] = "Создание Excel отчёта";
}
<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">
<select id="cardId" name="cardId" class="form-control" asp-items="@(new SelectList( @ViewBag.Cards, "Id", "Number"))"></select>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Создание" class="btn btn-warning" />
</div>
</div>
</form>

View File

@ -1,5 +1,118 @@
@* @using BankContracts.ViewModels;
For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 @using BankContracts.ViewModels.Reports
*@ @using BankСlientApp
@model ReportClientViewModelForHTML
@{ @{
ViewData["Title"] = "Создание отчёта";
} }
<div class="text-center">
<h2 class="display-4">Отчёт по картам за выбранный период</h2>
</div>
<form method="post">
<div class="row mb-2">
<div class="col-4">Дата начала периода:</div>
<div class="col-8">
<input id="dateFrom" name="dateFrom" class="form-control" type="date" required />
</div>
</div>
<div class="row mb-2">
<div class="col-4">Дата конца периода:</div>
<div class="col-8">
<input id="dateTo" name="dateTo" class="form-control" type="date" required />
</div>
</div>
<div class="row">
<input id="createReport" style="width:100%;" type="submit" value="Сформировать отчёт" class="btn btn-warning" />
</div>
<hr class="mt-5 mb-3" />
@if (Model != null)
{
<div class="row text-center">
<h3>Отчет отправлен на почту @APIClient.Client.Email</h3>
<hr class="mt-5 mb-3" />
<p>Отчёт по пополнениям</p>
<table class="table">
<thead>
<tr>
<th>
Номер операции
</th>
<th>
Номер карты
</th>
<th>
Сумма
</th>
<th>
Дата операции
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.ReportCrediting)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.OperationId)
</td>
<td>
@Html.DisplayFor(modelItem => item.CardNumber)
</td>
<td>
@Html.DisplayFor(modelItem => item.SumOperation)
</td>
<td>
@Html.DisplayFor(modelItem => item.DateComplite)
</td>
</tr>
}
</tbody>
</table>
</div>
<hr class="my-12" />
<div class="row text-center">
<p>Отчёт по снятиям</p>
<table class="table">
<thead>
<tr>
<th>
Номер операции
</th>
<th>
Номер карты
</th>
<th>
Сумма
</th>
<th>
Дата операции
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.ReportDebiting)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.OperationId)
</td>
<td>
@Html.DisplayFor(modelItem => item.CardNumber)
</td>
<td>
@Html.DisplayFor(modelItem => item.SumOperation)
</td>
<td>
@Html.DisplayFor(modelItem => item.DateComplite)
</td>
</tr>
}
</tbody>
</table>
</div>
}
</form>

View File

@ -0,0 +1,67 @@
@using BankContracts.ViewModels.Client.ViewModels
@model List<CreditingViewModel>
@{
ViewData["Title"] = "Операция пополнения";
}
<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="CreateCrediting">Пополнить средства</a>
</p>
<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.CardNumber)
</td>
<td>
@Html.DisplayFor(modelItem => item.Sum)
</td>
<td>
@item.Status.ToString().Replace("_", " ")
</td>
<td>
@Html.DisplayFor(modelItem => item.DateOpen)
</td>
<td>
@Html.DisplayFor(modelItem => item.DateClose)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -0,0 +1,67 @@
@using BankContracts.ViewModels.Client.ViewModels;
@model List<DebitingViewModel>
@{
ViewData["Title"] = "Операция снятия";
}
<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="CreateDebiting">Снять средства</a>
</p>
<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.CardNumber)
</td>
<td>
@Html.DisplayFor(modelItem => item.Sum)
</td>
<td>
@item.Status.ToString().Replace("_", " ")
</td>
<td>
@Html.DisplayFor(modelItem => item.DateOpen)
</td>
<td>
@Html.DisplayFor(modelItem => item.DateClose)
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -0,0 +1,92 @@
@using BankContracts.ViewModels.Client.Diagram
@model ClientDiagramViewModel
@{
ViewData["Title"] = "Диаграмма";
}
<div class="text-center">
<h1 class="display-4">Диаграмма финансов на карте по месяцам</h1>
</div>
<form method="post">
<div class="row mb-2">
<div class="row">Номер карты:</div>
<div class="col">
<select id="cardId" name="cardId" class="form-control" asp-items="@(new SelectList( @ViewBag.Cards, "Id", "Number"))"></select>
</div>
</div>
<div class="row mb-2">
<div class="col">
<input style="width: 100%" type="submit" value="Выбрать" class="btn btn-warning"/>
</div>
</div>
</form>
@if (Model == null) return;
<div id="Diagrams" class="text-center">
<div id="@Model.DiagramName Diagram">
<canvas id="Chart"></canvas>
<div id="params">
@foreach (var info in Model.Elements) {
<input type="hidden" id="@info.Name" value="@info.Value" />
}
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const diagrams = document.getElementById('Diagrams').childNodes;
let diagram_name = diagrams[1].id;
console.log(diagram_name);
let diagram = document.getElementById(diagram_name).childNodes;
console.log(diagram);
let labels = [];
let data = [];
document.getElementById('params').childNodes.forEach(element => {
if (element.id != undefined) {
labels.push(element.id);
}
});
document.getElementById('params').childNodes.forEach(element => {
if (element.id != undefined) {
data.push(Number(element.value));
}
});
new Chart(diagram.item(1), {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Денег в этом месяце',
data: data,
borderWidth: 6,
backgroundColor: 'rgb(255, 165, 0)'
}]
},
options: {
plugins: {
legend: {
display: false
},
customCanvasBackgroundColor: {
color: 'white',
}
},
scales: {
y: {
suggestedMin: Math.min(data) - Math.min(data) * -0.1,
suggestedMax: Math.max(data) + Math.max(data) * 0.1,
}
}
}
}
);
</script>

View File

@ -1,4 +1,4 @@
@using BankClientApp @using BankСlientApp
@{ @{
ViewData["Title"] = "Страница пользователя"; ViewData["Title"] = "Страница пользователя";
@ -10,7 +10,7 @@
<div class="text-center"> <div class="text-center">
@{ @{
<img src="~/lib/logo.png" style="width: 80%"/> <img src="https://i1.ytimg.com/vi/nNQemfCR9Ms/maxresdefault.jpg" alt="*" class="img-fluid" style="width: 70%; display: block; margin: 0 auto;">
if (APIClient.Client == null) if (APIClient.Client == null)
{ {

View File

@ -0,0 +1,10 @@
@using BankСlientApp
@{
ViewData["Title"] = "Отправка отчета";
}
<div class="text-center p-5">
<h3 class="display-4">Упс, что-то пошло не так...</h3>
<h3 class="display-4">Ошибка: @APIClient.ErrorMessage</h3>
</div>

View File

@ -1,4 +1,5 @@
@{ @using BankСlientApp
@{
ViewData["Title"] = "Добро пожаловать"; ViewData["Title"] = "Добро пожаловать";
} }

View File

@ -6,16 +6,9 @@
<h2 class="display-4">Вход в приложение</h2> <h2 class="display-4">Вход в приложение</h2>
</div> </div>
<form class="form-signin text-center" method="post">
<form class="form-signin text-center w-50 mx-auto" method="post"> <h1 class="h3 mb-3 font-weight-normal">Логин</h1>
<div class="mt-3 mb-3 h3"> <input type="email" id="login" name="login" class="form-control" placeholder="Почта" required autofocus>
<label for="login" class="form-label font-weight-normal">Логин</label> <input type="password" id="password" name="password" class="form-control" placeholder="Пароль" required>
<input type="text" name="login" id="login" class="form-control" placeholder="Логин" required autofocus /> <button class="btn btn-lg btn-warning btn-block" type="submit" asp-controller="Home" asp-action="Login">Войти</button>
</div>
<div class="mb-3 h3">
<label for="password" class="form-label font-weight-normal">Пароль</label>
<input type="password" name="password" id="password" class="form-control" placeholder="Пароль" required />
</div>
<button type="submit" class="btn btn-primary btn-warning btn-block mt-2">Вход</button>
</form> </form>

View File

@ -9,29 +9,28 @@
<div class="text-center"> <div class="text-center">
<h2 class="display-4">Личные данные</h2> <h2 class="display-4">Личные данные</h2>
</div> </div>
<form method="post" class="form-signin">
<form method="post" class="form-signin w-75 mx-auto">
<div class="row"> <div class="row">
<div class="col-4 mt-2">Логин:</div> <div class="col-4">Логин:</div>
<input type="email" id="login" name="login" class="form-control" placeholder="Почта" value=@Html.DisplayFor(modelItem => Model.Email) required> <input type="email" id="login" name="login" class="form-control" placeholder="Почта" value=@Html.DisplayFor(modelItem => Model.Email) required>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4 mt-2">Пароль:</div> <div class="col-4">Пароль:</div>
<input type="password" id="password" name="password" class="form-control" placeholder="Пароль" value=@Html.DisplayFor(modelItem => Model.Password) required> <input type="password" id="password" name="password" class="form-control" placeholder="Пароль" value=@Html.DisplayFor(modelItem => Model.Password) required>
</div> </div>
<div class="row"> <div class="row">
<div class="col-4 mt-2">Имя:</div> <div class="col-4">Имя:</div>
<input type="text" id="name" name="name" class="form-control" placeholder="Имя" value=@Html.DisplayFor(modelItem => Model.Name) required> <input type="text" id="name" name="name" class="form-control" placeholder="Имя" value=@Html.DisplayFor(modelItem => Model.Name) required>
<div class="col-4 mt-2">Фамилия:</div> <div class="col-4">Фамилия:</div>
<input type="text" id="surname" name="surname" class="form-control" placeholder="Фамилия" value=@Html.DisplayFor(modelItem => Model.Surname) required> <input type="text" id="surname" name="surname" class="form-control" placeholder="Фамилия" value=@Html.DisplayFor(modelItem => Model.Surname) required>
<div class="col-4 mt-2">Отчество:</div> <div class="col-4">Отчество:</div>
<input type="text" id="patronymic" name="patronymic" class="form-control" placeholder="Отчество" value=@Html.DisplayFor(modelItem => Model.Patronymic) required> <input type="text" id="patronymic" name="patronymic" class="form-control" placeholder="Отчество" value=@Html.DisplayFor(modelItem => Model.Patronymic) required>
</div> </div>
<div class="row mt-2"> <div class="row mb-2">
<div class="col-4">Телефон:</div> <div class="col-4">Телефон:</div>
<input type="text" id="mobilephone" name="mobilephone" class="form-control" placeholder="Телефон" value=@Html.DisplayFor(modelItem => Model.MobilePhone) required> <input type="text" id="telephone" name="telephone" class="form-control" placeholder="Телефон" value=@Html.DisplayFor(modelItem => Model.Telephone) required>
</div> </div>
<div class="row mt-2 mb-2"> <div class="row mb-2">
<button class="btn btn-lg btn-warning btn-block mb-2" type="submit" asp-controller="Home" asp-action="Privacy">Coхранить</button> <button class="btn btn-lg btn-warning btn-block mb-2" type="submit" asp-controller="Home" asp-action="Privacy">Coхранить</button>
<button class="btn btn-lg btn-warning btn-block" type="submit" asp-controller="Home" asp-action="Logout">Выйти из аккаунта</button> <button class="btn btn-lg btn-warning btn-block" type="submit" asp-controller="Home" asp-action="Logout">Выйти из аккаунта</button>
</div> </div>

View File

@ -3,16 +3,17 @@
} }
<div class="text-center"> <div class="text-center">
<h1 class="display-4">Регистрация</h1> <h2 class="display-4">Регистрация</h2>
</div> </div>
<form class="form-signin text-center w-75 mx-auto" method="post"> <form class="form-signin text-center" method="post">
<input type="email" id="login" name="login" class="form-control mb-2" placeholder="Почта" required> <h1 class="h3 mb-3 font-weight-normal">Регистрация</h1>
<input type="password" id="password" name="password" class="form-control mb-2" placeholder="Пароль" required> <input type="email" id="login" name="login" class="form-control" placeholder="Почта" required>
<input type="text" id="name" name="name" class="form-control mb-2" placeholder="Имя" required> <input type="password" id="password" name="password" class="form-control" placeholder="Пароль" required>
<input type="text" id="surname" name="surname" class="form-control mb-2" placeholder="Фамилия" required> <input type="text" id="name" name="name" class="form-control" placeholder="Имя" required>
<input type="text" id="patronymic" name="patronymic" class="form-control mb-2" placeholder="Отчество" required> <input type="text" id="surname" name="surname" class="form-control" placeholder="Фамилия" required>
<input type="text" id="mobilephone" name="mobilephone" class="form-control mb-2" placeholder="Телефон" required> <input type="text" id="patronymic" name="patronymic" class="form-control" placeholder="Отчество" required>
<input type="text" id="telephone" name="telephone" class="form-control" placeholder="Телефон" required>
<button class="btn btn-lg btn-warning btn-block" type="submit" asp-controller="Home" asp-action="Register">Регистрация</button> <button class="btn btn-lg btn-warning btn-block" type="submit" asp-controller="Home" asp-action="Register">Регистрация</button>
</form> </form>

View File

@ -0,0 +1,16 @@
@using BankСlientApp
@{
ViewData["Title"] = "Отправка отчета";
}
<div class="text-center">
@{
if (APIClient.Client == null)
{
<h3 class="display-4">Сначала авторизируйтесь</h3>
return;
}
}
<h3 class="display-4">Отчeт был отправлен на почту @APIClient.Client.Email</h3>
</div>

View File

@ -0,0 +1,140 @@
@using BankContracts.ViewModels.Reports.Client
@using Microsoft.JSInterop;
@inject IJSRuntime JS
@model ReportClientCardsViewModel
@{
ViewData["Title"] = "Отчет по картам";
}
<div class="text-center">
<h1 class="display-4">Отчет</h1>
</div>
<div class="container" sf-type="container" sf-label="Bootstrap Container" sf-uid="2">
<div class="row" sf-type="container" sf-label="Row" sf-uid="3">
<div class="mb-4 mb-md-0 aos-init aos-animate col-md-3" sf-type="container" sf-label="Column" sf-anim-delay="1.5" data-aos="fade-down" data-aos-delay="400" sf-uid="4">
<div sf-type="container" sf-label="Container" class="py-15 h-100 bg-bg-2" sf-uid="5">
<form method="post">
<h3>Карты:</h3>
@for (var item = 0; item < @Model.Cards.Count(); item++)
{
<div class="form-check form-switch">
<input class="form-check-input" type="checkbox" id="flexSwitchCheckDefault" asp-for="@Model.Cards[item].IsChecked">
<label class="form-check-label" for="flexSwitchCheckDefault">@Model.Cards[item].LabelName</label>
<input type="hidden" asp-for="@Model.Cards[item].Id" />
<input type="hidden" asp-for="@Model.Cards[item].LabelName" />
</div>
}
<hr>
<div class="mb-2">
<button style="width:100%" class="btn btn-lg btn-warning btn-block" type="submit" asp-controller="Home" asp-action="ReportWithCards">Создать отчёт</button>
</div>
<hr/>
<div class="mb-2">
<button type="button" id="ExcelBut" class="btn btn-lg btn-warning btn-block">Excel отчеты</button>
</div>
<div id="ExcelDiv" style="display: none">
<div class="mb-2" >
<button style="width:100%" class="btn btn-lg btn-warning btn-block" type="submit" asp-controller="Home" asp-action="CreateExcelReport">Создать отчёт по переводам (EXCEL)</button>
</div>
<div class="mb-2">
<button style="width:100%" class="btn btn-lg btn-warning btn-block" type="submit" asp-controller="Home" asp-action="CreateCreditingExcelReport">Создать отчёт по пополнениям (EXCEL)</button>
</div>
<div class="mb-2">
<button style="width:100%" class="btn btn-lg btn-warning btn-block" type="submit" asp-controller="Home" asp-action="CreateDebitingExcelReport">Создать отчёт по снятиям (EXCEL)</button>
</div>
</div>
<div class="mb-2">
<button type="button" id="WordBut" class="btn btn-lg btn-warning btn-block">Word отчеты</button>
</div>
<div id="WordDiv" style="display: none">
<div class="mb-2">
<button style="width:100%" class="btn btn-lg btn-warning btn-block" type="submit" asp-controller="Home" asp-action="CreateWordReport">Создать отчёт по переводам (WORD)</button>
</div>
<div class="mb-2">
<button style="width:100%" class="btn btn-lg btn-warning btn-block" type="submit" asp-controller="Home" asp-action="CreateCreditingWordReport">Создать отчёт по пополнениям (WORD)</button>
</div>
<div class="mb-2">
<button style="width:100%" class="btn btn-lg btn-warning btn-block" type="submit" asp-controller="Home" asp-action="CreateDebitingWordReport">Создать отчёт по снятиям (WORD)</button>
</div>
</div>
</form>
</div>
</div>
<div class="aos-init aos-animate col-md" sf-type="container" sf-label="Column" sf-anim-delay="2" data-aos="fade-down" data-aos-delay="500" sf-uid="8">
<div sf-type="container" sf-label="Container" class="py-15 h-100 bg-bg-2" sf-uid="9">
<table class="table">
<thead>
<tr>
<th>
Номер карты
</th>
<th>
Тип операции
</th>
<th>
Сумма
</th>
<th>
Статус
</th>
<th>
Дата открытия
</th>
<th>
Дата закрытия
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Operations)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.CardNumber)
</td>
<td>
@Html.DisplayFor(modelItem => item.TypeOperation)
</td>
<td>
@Html.DisplayFor(modelItem => item.Sum)
</td>
<td>
@item.Status.ToString().Replace("_", " ");
</td>
<td>
@Html.DisplayFor(modelItem => item.DateOpen)
</td>
<td>
@Html.DisplayFor(modelItem => item.DateClose)
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
</div>
<script>
document.getElementById('ExcelBut').addEventListener('click', event => {
if (document.getElementById("ExcelDiv").style.display == "none") {
document.getElementById("ExcelDiv").style.display = "block";
}
else {
document.getElementById("ExcelDiv").style.display = "none";
}
});
document.getElementById('WordBut').addEventListener('click', event => {
if (document.getElementById("WordDiv").style.display == "none") {
document.getElementById("WordDiv").style.display = "block";
}
else {
document.getElementById("WordDiv").style.display = "none";
}
});
</script>

View File

@ -1,4 +1,5 @@
@model ErrorViewModel @model ErrorViewModel
@{ @{
ViewData["Title"] = "Error"; ViewData["Title"] = "Error";
} }

View File

@ -1,65 +1,157 @@
<!DOCTYPE html> @using BankСlientApp
@{
bool authenticated = APIClient.Client != null;
}
<!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - BankClientApp</title> <title>@ViewData["Title"]</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /> <link rel="stylesheet" href="~/css/site.css" />
<link rel="stylesheet" href="~/BankClientApp.styles.css" asp-append-version="true" /> <script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<style>
body {
margin-bottom: 60px;
background-color: white;
}
.nav-main a {
position: relative;
color: #FFFFFF;
cursor: pointer;
line-height: 1;
text-decoration: none;
}
.nav-main a:after {
display: block;
position: absolute;
left: 0;
bottom: 0px;
width: 0;
height: 1px;
background-color: #FFFFFF;
content: "";
transition: width 0.3s ease-out;
}
.nav-main a:hover:after,
.nav-main a:focus:after {
width: 100%;
}
.nav-main .dropdown:hover .dropdown-menu {
display: block;
margin-top: 0;
}
.footer {
position: fixed;
left: 0;
bottom: 0;
width: 100%;
height: 80px;
background-color: #212529
}
.form-signin {
width: 100%;
max-width: 330px;
padding: 15px;
margin: auto;
}
.form-signin .form-control {
position: relative;
box-sizing: border-box;
height: auto;
padding: 10px;
font-size: 16px;
}
.form-signin .form-control:focus {
z-index: 2;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-signin input[type="password"] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
table.table tbody tr td,
table.table thead tr th,
table.table thead {
border-left: solid;
border-right: solid;
border-width: 4px;
border-color: #212529;
}
table {
vertical-align: middle;
}
</style>
</head> </head>
<body> <body class="MyBody">
<header> <header class="d-flex flex-wrap align-items-center justify-content-center justify-content-md-between py-3 px-4 mg-5 mb-4 border-bottom bg-dark ">
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"> <a asp-controller="Home" asp-action="Enter">
<div class="container-fluid">
<a asp-controller="Home" asp-action="Index">
<img src="https://img.icons8.com/?size=80&id=CvryVUzkqqMu&format=png" alt="*" class="navbar-toggler" style="display: block; margin: 0 auto; height:"> <img src="https://img.icons8.com/?size=80&id=CvryVUzkqqMu&format=png" alt="*" class="navbar-toggler" style="display: block; margin: 0 auto; height:">
</a> </a>
<a class="navbar-brand ms-4" asp-area="" asp-controller="Home" asp-action="Index">Банк "Вы Банкрот"</a> <div class="md-4 mb-2 mb-md-0">
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent" <a asp-controller="Home" asp-action="Enter" class="d-inline-flex link-body-emphasis text-decoration-none">
aria-expanded="false" aria-label="Toggle navigation"> <span class="fs-4 text-light ">Банк "Вы банкрот"</span>
<span class="navbar-toggler-icon"></span> </a>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1 me-2">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="CardsList">Банковские карты</a>
</li>
<li class="nav-item dropdown me-2">
<a class="nav-link dropdown-toggle" id="operationsDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">Операции</a>
<ul class="dropdown-menu" aria-labelledby="operationsDropdown">
<li><a class="dropdown-item" asp-controller="Home" asp-action="Crediting">Пополнение карты</a></li>
<li><a class="dropdown-item" asp-controller="Home" asp-action="Debiting">Снятие с карты</a></li>
<li><a class="dropdown-item" asp-controller="Home" asp-action="MoneyTransfers">Заявки на перевод</a></li>
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" id="reportsDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">Отчеты</a>
<ul class="dropdown-menu" aria-labelledby="reportsDropdown">
<li><a class="dropdown-item" asp-controller="Home" asp-action="ReportBankCard">Отчёт по банковским картам</a></li>
<li><a class="dropdown-item" asp-controller="Home" asp-action="CreateReport">Отчёт за период</a></li>
<li><a class="dropdown-item" asp-controller="Home" asp-action="Diagram">Диаграмма</a></li>
</ul>
</li>
</ul>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</li>
<li class="nav-item">
<a class="btn btn-primary ms-2 me-2" asp-controller="Home" asp-action="Login">Вход</a>
</li>
<li class="nav-item">
<a class="btn btn-primary ms-2" asp-controller="Home" asp-action="Register">Регистрация</a>
</li>
</ul>
</div> </div>
<ul class="nav col-md-auto mb-2 justify-content-center mb-md-0 nav-main">
<li>
<a class="nav-link px-2 link-light" asparea="" asp-controller="Home" asp-action="CardsList">Банковские карты</a>
</li>
<li class="dropdown">
<a href="#" class="nav-link px-2 link-light">Операции</a>
<ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarDarkDropdownMenuLink">
<li><a class="dropdown-item" asp-controller="Home" asp-action="DebitingList">Заявки на снятие</a></li>
<li><a class="dropdown-item" asp-controller="Home" asp-action="CreditingList">Заявки на начисление</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="nav-link px-2 link-light">Отчеты</a>
<ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarDarkDropdownMenuLink">
<li><a class="dropdown-item" asp-controller="Home" asp-controller="Home" asp-action="ReportWithCards">Отчёт по банковским картам</a></li>
<li><a class="dropdown-item" asp-controller="Home" asp-controller="Home" asp-action="CreateReport">Отчёт за период</a></li>
<li><a class="dropdown-item" asp-controller="Home" asp-controller="Home" asp-action="Diagram">Диаграмма</a></li>
</ul>
</li>
</ul>
@{
if (APIClient.Client == null)
{
<div class="col-md-3 text-end">
<a class="btn btn-warning me-2" asp-controller="Home" asp-action="Login">Войти</a>
<a class="btn btn-warning" asp-controller="Home" asp-action="Register">Регистрация</a>
</div> </div>
</nav> }
else
{
<div class="col-md-3 text-end">
<a class="btn btn-warning me-2" id="exit" name="exit" asp-controller="Home" asp-action="Privacy">@APIClient.Client.Surname @APIClient.Client.Name</a>
</div>
}
}
</header> </header>
<div class="container"> <div class="container">
<main role="main" class="pb-3"> <main role="main" class="pb-3">
@ -67,8 +159,8 @@
</main> </main>
</div> </div>
<footer class="border-top footer text-muted"> <footer class="border-top footer text-muted mx-auto">
<div class="container"> <div class="container mx-auto text-center mt-4 text-white">
&copy; 2024 - Банк "Вы Банкротищеее" - <a asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a> &copy; 2024 - Банк "Вы Банкротищеее" - <a asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</div> </div>
</footer> </footer>

View File

@ -7,9 +7,6 @@ a.navbar-brand {
word-break: break-all; word-break: break-all;
} }
a {
color: #0077cc;
}
.btn-primary { .btn-primary {
color: #fff; color: #fff;
@ -26,6 +23,7 @@ a {
.border-top { .border-top {
border-top: 1px solid #e5e5e5; border-top: 1px solid #e5e5e5;
} }
.border-bottom { .border-bottom {
border-bottom: 1px solid #e5e5e5; border-bottom: 1px solid #e5e5e5;
} }
@ -46,3 +44,14 @@ button.accept-policy {
white-space: nowrap; white-space: nowrap;
line-height: 60px; line-height: 60px;
} }
.nav-main a {
position: relative;
color: #FFFFFF; /*задаём цвет ссылки*/
cursor: pointer;
line-height: 1; /*задаём высоту строки*/
text-decoration: none; /*убираем подчёркивание*/
}

View File

@ -1,14 +1,7 @@
using BankDataModels.Enums; using BankDataModels.Models.Cashier;
using BankDataModels.Models.Cashier;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BindingModels.Cashier namespace BankContracts.BindingModels.Cashier
{ {
// Реализация сущности "Счёт"
public class AccountBindingModel : IAccountModel public class AccountBindingModel : IAccountModel
{ {
public int Id { get; set; } public int Id { get; set; }
@ -19,10 +12,10 @@ namespace BankContracts.BindingModels.Cashier
public string AccountNumber { get; set; } = string.Empty; public string AccountNumber { get; set; } = string.Empty;
public string PasswordAccount { get; set; } = string.Empty;
public double Balance { get; set; } public double Balance { get; set; }
public DateTime DateOpen { get; set; } = DateTime.Now; public DateTime DateOpen { get; set; } = DateTime.Now;
public StatusAccount StatusAccount { get; set; } = StatusAccount.Закрыт;
} }
} }

View File

@ -1,25 +1,19 @@
using BankDataModels.Models.Cashier; using BankDataModels.Models.Cashier;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BindingModels.Cashier namespace BankContracts.BindingModels.Cashier
{ {
// Реализация сущности "Снятие наличных"
public class CashWithdrawalBindingModel : ICashWithdrawalModel public class CashWithdrawalBindingModel : ICashWithdrawalModel
{ {
public int Id { get; set; } public int Id { get; set; }
public int CashierId { get; set; }
public int DebitingId { get; set; } public int DebitingId { get; set; }
public int AccountId { get; set; } public int AccountId { get; set; }
public double Sum { get; set; } public int CashierId { get; set; }
public DateTime DateWithdrawal { get; set; } public int Sum { get; set; }
public DateTime DateOperation { get; set; } = DateTime.Now;
} }
} }

View File

@ -1,17 +1,13 @@
using BankDataModels.Models.Cashier; using BankDataModels.Models.Cashier;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BindingModels.Cashier namespace BankContracts.BindingModels.Cashier
{ {
// Реализация сущности "Кассир"
public class CashierBindingModel : ICashierModel public class CashierBindingModel : ICashierModel
{ {
public int Id { get; set; } public int Id { get; set; }
public string Password { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
public string Surname { get; set; } = string.Empty; public string Surname { get; set; } = string.Empty;
@ -20,8 +16,6 @@ namespace BankContracts.BindingModels.Cashier
public string Email { get; set; } = string.Empty; public string Email { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty; public string Telephone { get; set; } = string.Empty;
public string MobilePhone { get; set; } = string.Empty;
} }
} }

View File

@ -1,29 +1,21 @@
using BankDataModels.Models.Cashier; using BankDataModels.Models.Cashier;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BindingModels.Cashier namespace BankContracts.BindingModels.Cashier
{ {
// Реализация сущности "Перевод наличных"
public class MoneyTransferBindingModel : IMoneyTransferModel public class MoneyTransferBindingModel : IMoneyTransferModel
{ {
public int Id { get; set; } public int Id { get; set; }
public double Sum { get; set; } public int Sum { get; set; }
public int CashierId { get; set; }
public DateTime DateTransfer { get; set; } = DateTime.Now;
public int? CreditingId { get; set; }
// Для реализации между двумя аккаунтами, (клиента?)
public int? AccountSenderId { get; set; } public int? AccountSenderId { get; set; }
public int AccountPayeeId { get; set; } public int AccountPayeeId { get; set; }
public DateTime DateOperation { get; set; } = DateTime.Now;
public int? CreditingId { get; set; }
public int CashierId { get; set; }
} }
} }

View File

@ -1,29 +1,19 @@
using BankDataModels.Enums; using BankDataModels.Models.Client;
using BankDataModels.Models.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BindingModels.Client namespace BankContracts.BindingModels.Client
{ {
// Реализация сущности "Карта"
public class CardBindingModel : ICardModel public class CardBindingModel : ICardModel
{ {
public int Id { get; set; } public int Id { get; set; }
public int ClientId { get; set; } public int ClientID { get; set; }
public int AccountId { get; set; } public int AccountId { get; set; }
// Номер банковской карты
public string Number { get; set; } = string.Empty; public string Number { get; set; } = string.Empty;
public double Balance { get; set; } public string CVC { get; set; } = string.Empty;
public DateTime Period { get; set; } = DateTime.Now; public DateTime Period { get; set; } = DateTime.Now;
public StatusCard StatusCard { get; set; } = StatusCard.Закрыта;
} }
} }

View File

@ -1,17 +1,13 @@
using BankDataModels.Models.Client; using BankDataModels.Models.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BindingModels.Client namespace BankContracts.BindingModels.Client
{ {
// Реализация сущности "Клиент"
public class ClientBindingModel : IClientModel public class ClientBindingModel : IClientModel
{ {
public int Id { get; set; } public int Id { get; set; }
public string Password { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
public string Surname { get; set; } = string.Empty; public string Surname { get; set; } = string.Empty;
@ -20,8 +16,6 @@ namespace BankContracts.BindingModels.Client
public string Email { get; set; } = string.Empty; public string Email { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty; public string Telephone { get; set; } = string.Empty;
public string MobilePhone { get; set; } = string.Empty;
} }
} }

View File

@ -1,24 +1,20 @@
using BankDataModels.Models.Client; using BankDataModels.Enums;
using System; using BankDataModels.Models.Client;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BindingModels.Client namespace BankContracts.BindingModels.Client
{ {
// Реализация сущности "Пополнение карты"
public class CreditingBindingModel : ICreditingModel public class CreditingBindingModel : ICreditingModel
{ {
public int Id { get; set; } public int Id { get; set; }
// Вот лучше оставим для клиента айдишник
public int ClientId { get; set; }
public int CardId { get; set; } public int CardId { get; set; }
public double Sum { get; set; } public int Sum { get; set; }
public DateTime DateCredit { get; set; } public DateTime DateOpen { get; set; } = DateTime.Now;
public DateTime? DateClose { get; set; }
public StatusEnum Status { get; set; }
} }
} }

View File

@ -1,25 +1,20 @@
using BankDataModels.Models.Client; using BankDataModels.Enums;
using System; using BankDataModels.Models.Client;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BindingModels.Client namespace BankContracts.BindingModels.Client
{ {
// Реализация сущности "Клиент"
public class DebitingBindingModel : IDebitingModel public class DebitingBindingModel : IDebitingModel
{ {
public int Id { get; set; } public int Id { get; set; }
public int CardId { get; set; } public int CardId { get; set; }
// И тут я понял почему ты задавался вопросом про id, надо подумать public int Sum { get; set; }
public int ClientId { get; set; }
public double Sum { get; set; } public DateTime DateOpen { get; set; } = DateTime.Now;
public DateTime DateDebit { get; set; } = DateTime.Now; public DateTime? DateClose { get; set; }
public StatusEnum Status { get; set; } = StatusEnum.Открыта;
} }
} }

View File

@ -1,12 +1,6 @@
using System; namespace BankContracts.BindingModels.Messages
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BindingModels.Messages
{ {
// Класс для передачи данных по почте //один из двух классов для передачи данных по почте
public class MailConfigBindingModel public class MailConfigBindingModel
{ {
public string MailLogin { get; set; } = string.Empty; public string MailLogin { get; set; } = string.Empty;
@ -17,8 +11,10 @@ namespace BankContracts.BindingModels.Messages
public int SmtpClientPort { get; set; } public int SmtpClientPort { get; set; }
//можно без них?
public string PopHost { get; set; } = string.Empty; public string PopHost { get; set; } = string.Empty;
//можно без них?
public int PopPort { get; set; } public int PopPort { get; set; }
} }
} }

View File

@ -1,13 +1,8 @@
using BankDataModels.Enums; using BankDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BindingModels.Messages namespace BankContracts.BindingModels.Messages
{ {
// Класс для обмена информацией по почте //один из двух классов для обмена информацией по почте
public class MailSendInfoBindingModel public class MailSendInfoBindingModel
{ {
public string MailAddress { get; set; } = string.Empty; public string MailAddress { get; set; } = string.Empty;
@ -16,7 +11,7 @@ namespace BankContracts.BindingModels.Messages
public string Text { get; set; } = string.Empty; public string Text { get; set; } = string.Empty;
// Для отправки pdf //для отправки pdf
public byte[] File { get; set; } = Array.Empty<byte>(); public byte[] File { get; set; } = Array.Empty<byte>();
public MailsEnum Role { get; set; } public MailsEnum Role { get; set; }

View File

@ -1,13 +1,7 @@
using BankDataModels.Models; using BankDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BindingModels.Messages namespace BankContracts.BindingModels.Messages
{ {
// Реализация сущности "Сообщение"
public class MessageInfoBindingModel : IMessageInfoModel public class MessageInfoBindingModel : IMessageInfoModel
{ {
public int Id { get; set; } public int Id { get; set; }
@ -24,7 +18,6 @@ namespace BankContracts.BindingModels.Messages
public string Body { get; set; } = string.Empty; public string Body { get; set; } = string.Empty;
// Для ответа
public bool IsRead { get; set; } = false; public bool IsRead { get; set; } = false;
public string? Answer { get; set; } = string.Empty; public string? Answer { get; set; } = string.Empty;

View File

@ -1,9 +1,4 @@
using BankDataModels.Enums; using BankDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BindingModels.Reports namespace BankContracts.BindingModels.Reports
{ {

View File

@ -1,24 +1,17 @@
using System; namespace BankContracts.BindingModels.Reports
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BindingModels.Reports
{ {
// Вспомогательная модель для передачи DateTime при формировании отчёта //вспомогательная модель для передачи DateTime при формировании отчёта
public class ReportSupportBindingModel public class ReportSupportBindingModel
{ {
public int? ClientId { get; set; } public int? ClientId { get; set; }
public int? AccountId { get; set; } public int? AccountId { get; set; }
// Вот для отчётов, чтобы по дате отбирать
public DateTime? DateFrom { get; set; } public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; } public DateTime? DateTo { get; set; }
// Для Excel отчёта клиента //для Excel отчёта клиента
public List<int>? CardList { get; set; } public List<int>? CardList { get; set; }
public string? Email { get; set; } public string? Email { get; set; }

View File

@ -1,15 +1,10 @@
using BankContracts.BindingModels.Cashier; using BankContracts.BindingModels.Cashier;
using BankContracts.SearchModels.Cashier; using BankContracts.SearchModels.Cashier;
using BankContracts.ViewModels; using BankContracts.ViewModels.Cashier.Diagram;
using System; using BankContracts.ViewModels.Cashier.ViewModels;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BusinessLogicsContracts.Cashier namespace BankContracts.BusinessLogicsContracts.Cashier
{ {
// Интерфейс бизнес-логики для счёта
public interface IAccountLogic public interface IAccountLogic
{ {
List<AccountViewModel>? ReadList(AccountSearchModel? model); List<AccountViewModel>? ReadList(AccountSearchModel? model);
@ -23,5 +18,7 @@ namespace BankContracts.BusinessLogicsContracts.Cashier
bool Update(AccountBindingModel model); bool Update(AccountBindingModel model);
bool Delete(AccountBindingModel model); bool Delete(AccountBindingModel model);
public List<CashierDiagramElementsViewModel> GetMonthInfo(int AccountId);
} }
} }

View File

@ -1,15 +1,9 @@
using BankContracts.BindingModels.Cashier; using BankContracts.BindingModels.Cashier;
using BankContracts.SearchModels.Cashier; using BankContracts.SearchModels.Cashier;
using BankContracts.ViewModels.Cashier.ViewModels; using BankContracts.ViewModels.Cashier.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BusinessLogicsContracts.Cashier namespace BankContracts.BusinessLogicsContracts.Cashier
{ {
// Интерфейс бизнес-логики для выдачи наличных
public interface ICashWithdrawalLogic public interface ICashWithdrawalLogic
{ {
List<CashWithdrawalViewModel>? ReadList(CashWithdrawalSearchModel? model); List<CashWithdrawalViewModel>? ReadList(CashWithdrawalSearchModel? model);

View File

@ -1,15 +1,9 @@
using BankContracts.BindingModels.Cashier; using BankContracts.BindingModels.Cashier;
using BankContracts.SearchModels.Cashier; using BankContracts.SearchModels.Cashier;
using BankContracts.ViewModels.Cashier.ViewModels; using BankContracts.ViewModels.Cashier.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BusinessLogicsContracts.Cashier namespace BankContracts.BusinessLogicsContracts.Cashier
{ {
// Интерфейс бизнес-логики для кассира
public interface ICashierLogic public interface ICashierLogic
{ {
List<CashierViewModel>? ReadList(CashierSearchModel? model); List<CashierViewModel>? ReadList(CashierSearchModel? model);

View File

@ -1,15 +1,9 @@
using BankContracts.BindingModels.Cashier; using BankContracts.BindingModels.Cashier;
using BankContracts.SearchModels.Cashier; using BankContracts.SearchModels.Cashier;
using BankContracts.ViewModels.Cashier.ViewModels; using BankContracts.ViewModels.Cashier.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BusinessLogicsContracts.Cashier namespace BankContracts.BusinessLogicsContracts.Cashier
{ {
// Интерфейс бизнес-логики для перевода денег
public interface IMoneyTransferLogic public interface IMoneyTransferLogic
{ {
List<MoneyTransferViewModel>? ReadList(MoneyTransferSearchModel? model); List<MoneyTransferViewModel>? ReadList(MoneyTransferSearchModel? model);

View File

@ -1,15 +1,10 @@
using BankContracts.BindingModels.Client; using BankContracts.BindingModels.Client;
using BankContracts.SearchModels.Client; using BankContracts.SearchModels.Client;
using BankContracts.ViewModels.Client.Diagram;
using BankContracts.ViewModels.Client.ViewModels; using BankContracts.ViewModels.Client.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BusinessLogicsContracts.Client namespace BankContracts.BusinessLogicsContracts.Client
{ {
// Интерфейс бизнес-логики для банковской карты
public interface ICardLogic public interface ICardLogic
{ {
List<CardViewModel>? ReadList(CardSearchModel? model); List<CardViewModel>? ReadList(CardSearchModel? model);
@ -21,5 +16,7 @@ namespace BankContracts.BusinessLogicsContracts.Client
bool Update(CardBindingModel model); bool Update(CardBindingModel model);
bool Delete(CardBindingModel model); bool Delete(CardBindingModel model);
public List<ClientDiagramElementsViewModel> GetMonthInfo(int CardId);
} }
} }

View File

@ -1,15 +1,9 @@
using BankContracts.BindingModels.Client; using BankContracts.BindingModels.Client;
using BankContracts.SearchModels.Client; using BankContracts.SearchModels.Client;
using BankContracts.ViewModels.Client.ViewModels; using BankContracts.ViewModels.Client.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BusinessLogicsContracts.Client namespace BankContracts.BusinessLogicsContracts.Client
{ {
// Интерфейс бизнес-логики для клиента
public interface IClientLogic public interface IClientLogic
{ {
List<ClientViewModel>? ReadList(ClientSearchModel? model); List<ClientViewModel>? ReadList(ClientSearchModel? model);
@ -21,5 +15,6 @@ namespace BankContracts.BusinessLogicsContracts.Client
bool Update(ClientBindingModel model); bool Update(ClientBindingModel model);
bool Delete(ClientBindingModel model); bool Delete(ClientBindingModel model);
} }
} }

View File

@ -1,15 +1,9 @@
using BankContracts.BindingModels.Client; using BankContracts.BindingModels.Client;
using BankContracts.SearchModels.Client; using BankContracts.SearchModels.Client;
using BankContracts.ViewModels.Client.ViewModels; using BankContracts.ViewModels.Client.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BusinessLogicsContracts.Client namespace BankContracts.BusinessLogicsContracts.Client
{ {
// Интерфейс бизнес-логики для пополнения карты
public interface ICreditingLogic public interface ICreditingLogic
{ {
List<CreditingViewModel>? ReadList(CreditingSearchModel? model); List<CreditingViewModel>? ReadList(CreditingSearchModel? model);

View File

@ -1,15 +1,9 @@
using BankContracts.BindingModels.Client; using BankContracts.BindingModels.Client;
using BankContracts.SearchModels.Client; using BankContracts.SearchModels.Client;
using BankContracts.ViewModels.Client.ViewModels; using BankContracts.ViewModels.Client.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BusinessLogicsContracts.Client namespace BankContracts.BusinessLogicsContracts.Client
{ {
// Интерфейс бизнес-логики для получение наличных по карте
public interface IDebitingLogic public interface IDebitingLogic
{ {
List<DebitingViewModel>? ReadList(DebitingSearchModel? model); List<DebitingViewModel>? ReadList(DebitingSearchModel? model);

View File

@ -1,28 +1,22 @@
using BankContracts.BindingModels.Reports; using BankContracts.BindingModels.Reports;
using BankContracts.ViewModels.Reports; using BankContracts.ViewModels.Reports;
using BankContracts.ViewModels.Reports.Cashier; using BankContracts.ViewModels.Reports.Cashier;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BusinessLogicsContracts.Reports namespace BankContracts.BusinessLogicsContracts.Reports
{ {
// Интерфейс бизнес-логики для отчёта (Кассир)
public interface IReportCashierLogic public interface IReportCashierLogic
{ {
List<ReportCashierViewModel>? GetMoneyTransfers(ReportBindingModel model); List<ReportCashierViewModel>? GetMoneyTransfers(ReportBindingModel model);
List<ReportCashierViewModel>? GetCashWithrawals(ReportBindingModel model); List<ReportCashierViewModel>? GetCashWithrawals(ReportBindingModel model);
// Сохранение отчёта по счетам в файл-Word //Сохранение отчёта по счетам в файл-Word
void SaveAccountsToWordFile(ReportBindingModel model); void SaveAccountsToWordFile(ReportBindingModel model);
// Сохранение отчёта по счетам в файл-Excel //Сохранение отчёта по счетам в файл-Excel
void SaveAccountsToExcelFile(ReportBindingModel model); void SaveAccountsToExcelFile(ReportBindingModel model);
// Сохранение отчёта по счетам в файл-Pdf //Сохранение отчёта по счетам в файл-Pdf
ReportCashierViewModelForHTML SaveAccountsToPdfFile(ReportBindingModel model); ReportCashierViewModelForHTML SaveAccountsToPdfFile(ReportBindingModel model);
} }
} }

View File

@ -2,28 +2,22 @@
using BankContracts.ViewModels.Reports; using BankContracts.ViewModels.Reports;
using BankContracts.ViewModels.Reports.Client; using BankContracts.ViewModels.Reports.Client;
using BankDataModels.Enums; using BankDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BusinessLogicsContracts.Reports namespace BankContracts.BusinessLogicsContracts.Reports
{ {
// Интерфейс бизнес-логики для отчёта (Клиент)
public interface IReportClientLogic public interface IReportClientLogic
{ {
List<ReportClientViewModel>? GetCrediting(ReportBindingModel model); List<ReportClientViewModel>? GetCrediting(ReportBindingModel model);
List<ReportClientViewModel>? GetDebiting(ReportBindingModel model); List<ReportClientViewModel>? GetDebiting(ReportBindingModel model);
// Сохранение отчёта по картам в файл-Word //Сохранение отчёта по картам в файл-Word
void SaveToWordFile(ReportBindingModel model, OfficeOperationEnum operationEnum); void SaveToWordFile(ReportBindingModel model, OfficeOperationEnum operationEnum);
// Сохранение отчёта по картам в файл-Excel //Сохранение отчёта по картам в файл-Excel
void SaveToExcelFile(ReportBindingModel model, OfficeOperationEnum operationEnum); void SaveToExcelFile(ReportBindingModel model, OfficeOperationEnum operationEnum);
// Сохранение отчёта по картам в файл-Pdf //Сохранение отчёта по картам в файл-Pdf
ReportClientViewModelForHTML SaveClientReportToPdfFile(ReportBindingModel model); ReportClientViewModelForHTML SaveClientReportToPdfFile(ReportBindingModel model);
} }
} }

View File

@ -1,5 +1,4 @@
using BankDataModels.Enums; using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -7,21 +6,20 @@ using System.Threading.Tasks;
namespace BankContracts.SearchModels.Cashier namespace BankContracts.SearchModels.Cashier
{ {
// Для поиска сущности "Счёт"
public class AccountSearchModel public class AccountSearchModel
{ {
public int? Id { get; set; } public int? Id { get; set; }
public string? AccountNumber { get; set; } = string.Empty;
public int? CashierId { get; set; } public int? CashierId { get; set; }
public int? ClientId { get; set; } public int? ClientId { get; set; }
public string? AccountNumber { get; set; } = string.Empty; public string? PasswordAccount { get; set; } = string.Empty;
public double? Balance { get; set; } public double? Balance { get; set; }
public DateTime? DateOpen { get; set; } public DateTime? DateOpen { get; set; }
public StatusAccount? StatusAccount { get; set; }
} }
} }

View File

@ -6,21 +6,22 @@ using System.Threading.Tasks;
namespace BankContracts.SearchModels.Cashier namespace BankContracts.SearchModels.Cashier
{ {
// Для поиска сущности "Выдача наличных"
public class CashWithdrawalSearchModel public class CashWithdrawalSearchModel
{ {
public int? Id { get; set; } public int? Id { get; set; }
public int? DebitingId { get; set; }
public int? AccountId { get; set; } public int? AccountId { get; set; }
public int? CashierId { get; set; } public int? CashierId { get; set; }
public int? ClientId { get; set; }
public int? Sum { get; set; } public int? Sum { get; set; }
public DateTime? DateWithdrawal { get; set; } public DateTime? DateFrom { get; set; }
public int? DebitingId { get; set; } public DateTime? DateTo { get; set; }
public int? ClientId { get; set; }
} }
} }

View File

@ -6,21 +6,20 @@ using System.Threading.Tasks;
namespace BankContracts.SearchModels.Cashier namespace BankContracts.SearchModels.Cashier
{ {
// Для поиска сущности "Кассир"
public class CashierSearchModel public class CashierSearchModel
{ {
public int? Id { get; set; } public int? Id { get; set; }
public string? Name { get; set; } = string.Empty; public string? Name { get; set; }
public string? Surname { get; set; } = string.Empty; public string? Surname { get; set; }
public string? Patronymic { get; set; } = string.Empty; public string? Patronymic { get; set; }
public string? Email { get; set; } = string.Empty; public string? Email { get; set; }
public string? Password { get; set; } = string.Empty; public string? Password { get; set; }
public string? MobilePhone { get; set; } = string.Empty; public string? Telephone { get; set; }
} }
} }

View File

@ -6,26 +6,22 @@ using System.Threading.Tasks;
namespace BankContracts.SearchModels.Cashier namespace BankContracts.SearchModels.Cashier
{ {
// Для поиска сущности "Перевод денег"
public class MoneyTransferSearchModel public class MoneyTransferSearchModel
{ {
public int? Id { get; set; } public int? Id { get; set; }
public int? Sum { get; set; } public int? Sum { get; set; }
public int? CashierId { get; set; }
public int? AccountId { get; set; }
public DateTime? DateTransfer { get; set; }
public int? Crediting { get; set; }
public int? ClientId { get; set; } public int? ClientId { get; set; }
//это надо :) public int? CashierId { get; set; }
public int? AccountSenderId { get; set; } public int? AccountSenderId { get; set; }
public int? AccountPayeeId { get; set; } public int? AccountPayeeId { get; set; }
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
} }
} }

View File

@ -1,5 +1,4 @@
using BankDataModels.Enums; using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -7,7 +6,6 @@ using System.Threading.Tasks;
namespace BankContracts.SearchModels.Client namespace BankContracts.SearchModels.Client
{ {
// Для поиска сущности "Банковская карта"
public class CardSearchModel public class CardSearchModel
{ {
public int? Id { get; set; } public int? Id { get; set; }
@ -16,13 +14,10 @@ namespace BankContracts.SearchModels.Client
public int? AccountId { get; set; } public int? AccountId { get; set; }
// Номер банковской карты
public string? Number { get; set; } public string? Number { get; set; }
public double Balance { get; set; } public string? CVC { get; set; }
public DateTime Period { get; set; } public DateTime? Period { get; set; }
public StatusCard StatusCard { get; set; }
} }
} }

View File

@ -6,21 +6,18 @@ using System.Threading.Tasks;
namespace BankContracts.SearchModels.Client namespace BankContracts.SearchModels.Client
{ {
// Для поиска сущности "Клиент"
public class ClientSearchModel public class ClientSearchModel
{ {
public int? Id { get; set; } public int? Id { get; set; }
public string? Name { get; set; } = string.Empty; public string? Name { get; set; }
public string? Surname { get; set; } = string.Empty; public string? Surname { get; set; }
public string? Patronymic { get; set; } = string.Empty; public string? Patronymic { get; set; }
public string? Email { get; set; } = string.Empty; public string? Email { get; set; }
public string? Password { get; set; } = string.Empty; public string? Password { get; set; }
public string? MobilePhone { get; set; } = string.Empty;
} }
} }

View File

@ -1,4 +1,5 @@
using System; using BankDataModels.Enums;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -6,7 +7,6 @@ using System.Threading.Tasks;
namespace BankContracts.SearchModels.Client namespace BankContracts.SearchModels.Client
{ {
// Для поиска сущности "Пополнение карты"
public class CreditingSearchModel public class CreditingSearchModel
{ {
public int? Id { get; set; } public int? Id { get; set; }
@ -15,8 +15,12 @@ namespace BankContracts.SearchModels.Client
public int? Sum { get; set; } public int? Sum { get; set; }
public DateTime? DateCrediting { get; set; } public int? UserId { get; set; }
public int? ClientId { get; set; } // ИЛИ лучше ClientId, ClientId будет лучше :) public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public StatusEnum? Status { get; set; }
} }
} }

View File

@ -1,4 +1,5 @@
using System; using BankDataModels.Enums;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -6,17 +7,20 @@ using System.Threading.Tasks;
namespace BankContracts.SearchModels.Client namespace BankContracts.SearchModels.Client
{ {
// Для поиска сущности "Получение наличных"
public class DebitingSearchModel public class DebitingSearchModel
{ {
public int? Id { get; set; } public int? Id { get; set; }
public int? CardId { get; set; } public int? CardId { get; set; }
public int? ClientId { get; set; } // ClientId будет лучше :) public int? UserId { get; set; }
public int? Sum { get; set; } public int? Sum { get; set; }
public DateTime? DateDebit { get; set; } public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public StatusEnum? Status { get; set; }
} }
} }

Some files were not shown because too many files have changed in this diff Show More