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

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,221 +1,241 @@
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 IMoneyTransferLogic _moneyTransferLogic;
private readonly ICashWithdrawalLogic _cashWithdrawalLogic; public AccountLogic(ILogger<AccountLogic> logger, IAccountStorage accountStorage,
ICashWithdrawalLogic cashWithdrawalLogic, IMoneyTransferLogic moneyTransferLogic)
{
_logger = logger;
_accountStorage = accountStorage;
_cashWithdrawalLogic = cashWithdrawalLogic;
_moneyTransferLogic = moneyTransferLogic;
}
private readonly IMoneyTransferLogic _moneyTransferLogic; public AccountViewModel? ReadElement(AccountSearchModel model)
{
// Конструктор if (model == null)
public AccountLogic(ILogger<AccountLogic> logger, IAccountStorage accountStorage,
ICashWithdrawalLogic cashWithdrawalLogic, IMoneyTransferLogic moneyTransferLogic)
{
_logger = logger;
_accountStorage = accountStorage;
_cashWithdrawalLogic = cashWithdrawalLogic;
_moneyTransferLogic = moneyTransferLogic;
}
// Вывод конкретного счёта
public AccountViewModel? ReadElement(AccountSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. AccountNumber:{Name}. Id:{Id}", model.AccountNumber, model?.Id);
var element = _accountStorage.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<AccountViewModel>? ReadList(AccountSearchModel? model)
{
if (model != null)
{
_logger.LogInformation("ReadList. AccountNumber:{AccountNumber}. Id:{Id}", model.AccountNumber, model.Id);
}
else
{
_logger.LogInformation("ReadList without filter model");
}
// list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _accountStorage.GetFullList() : _accountStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
// Метод, отвечающий за изменение баланса счёта
public bool ChangeBalance(AccountSearchModel? model, int sum)
{
// Ищем счёт
var account = ReadElement(model);
if (account == null)
{
throw new ArgumentNullException("Счёт не найден", nameof(account));
}
// Проверяем возможность операции снятия (sum может быть отрицательной)
if (sum + account.Balance < 0)
{
return false;
}
// Обновляем балланс счёта
_accountStorage.Update(new AccountBindingModel
{
Id = account.Id,
Balance = account.Balance + sum
});
return true;
}
// Создание счёта
public bool Create(AccountBindingModel model)
{
CheckModel(model);
if (_accountStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
// Обновление счёта
public bool Update(AccountBindingModel model)
{
CheckModel(model);
if (_accountStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
// Удаление счёта
public bool Delete(AccountBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_accountStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
// Проверка входного аргумента для методов Insert, Update и Delete
private void CheckModel(AccountBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
// Так как при удалении передаём как параметр false
if (!withParams)
{
return;
}
// Проверка на наличие номера счёта
if (string.IsNullOrEmpty(model.AccountNumber))
{
throw new ArgumentNullException("Отсутствие номера у счёта", nameof(model.AccountNumber));
}
// Проверка на наличие id клиента (И всё-таки не будет лишним добавить Id клиента)
if (model.ClientId < 0)
{ {
throw new ArgumentNullException("Некорректный Id клиента", nameof(model.ClientId)); throw new ArgumentNullException(nameof(model));
} }
// Проверка на наличие id кассира, создавшего счёт _logger.LogInformation("ReadElement. AccountNumber:{Name}. Id:{Id}", model.AccountNumber, model?.Id);
if (model.CashierId < 0)
{
throw new ArgumentNullException("Некорректный Id кассира, открывшего счёт", nameof(model.CashierId));
}
if (model.Balance < 0) var element = _accountStorage.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<AccountViewModel>? ReadList(AccountSearchModel? model)
{
//_logger.LogInformation("ReadList. AccountNumber:{AccountNumber}. Id:{Id}", model.AccountNumber, model?.Id);
//list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _accountStorage.GetFullList() : _accountStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
//метод, отвечающий за изменение баланса счёта
public bool ChangeBalance(AccountSearchModel? model, int sum)
{
//ищем счёт
var account = ReadElement(model);
if (account == null)
{
throw new ArgumentNullException("Счёт не найден", nameof(account));
}
//проверяем возможность операции снятия (sum может быть отрицательной)
if (sum + account.Balance < 0)
{
return false;
}
//обновляем балланс счёта
_accountStorage.Update(new AccountBindingModel
{
Id = account.Id,
Balance = account.Balance + sum
});
return true;
}
public bool Create(AccountBindingModel model)
{
CheckModel(model);
if (_accountStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(AccountBindingModel model)
{
CheckModel(model);
if (_accountStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(AccountBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_accountStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
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)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
//так как при удалении передаём как параметр false
if (!withParams)
{
return;
}
//проверка на наличие номера счёта
if (string.IsNullOrEmpty(model.AccountNumber))
{
throw new ArgumentNullException("Отсутствие номера у счёта", nameof(model.AccountNumber));
}
//проверка на наличие id владельца
if (model.CashierId < 0)
{
throw new ArgumentNullException("Некорректный Id владельца счёта", nameof(model.CashierId));
}
//проверка на наличие id кассира, создавшего счёт
if (model.CashierId < 0)
{
throw new ArgumentNullException("Некорректный Id кассира, открывшего счёт", nameof(model.CashierId));
}
//проверка на наличие пароля счёта
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,176 +2,170 @@
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;
private readonly ICashWithdrawalStorage _cashWithdrawalStorage; private readonly ICashWithdrawalStorage _cashWithdrawalStorage;
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) {
{ 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);
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<CashWithdrawalViewModel>? ReadList(CashWithdrawalSearchModel? model)
public List<CashWithdrawalViewModel>? ReadList(CashWithdrawalSearchModel? model) {
{ _logger.LogInformation("ReadElement. AccountId:{AccountId}. Sum:{Sum}. DateOperation:{DateOperation}. Id:{Id}",
_logger.LogInformation("ReadElement. AccountId:{AccountId}. Sum:{Sum}. DateWithdrawal:{DateWithdrawal}. Id:{Id}", model?.AccountId, model?.Sum, model?.DateTo, model?.Id);
model?.AccountId, model?.Sum, model?.DateWithdrawal, 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)
{ {
_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(CashWithdrawalBindingModel model, bool flag)
public bool Create(CashWithdrawalBindingModel model, bool flag) {
{ CheckModel(model);
CheckModel(model);
if (flag) if (flag)
{ {
if (_cashWithdrawalStorage.Insert(model) == null) if (_cashWithdrawalStorage.Insert(model) == null)
{ {
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Insert operation failed");
return false; return false;
} }
_debitingStorage.Update(new DebitingBindingModel _debitingStorage.Update(new DebitingBindingModel
{ {
Id = model.DebitingId, Id = model.DebitingId,
}); DateClose = DateTime.Now,
} Status = StatusEnum.Закрыта
else });
{ }
_debitingStorage.Update(new DebitingBindingModel else
{ {
Id = model.DebitingId, _debitingStorage.Update(new DebitingBindingModel
}); {
} 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);
if (_cashWithdrawalStorage.Update(model) == null) if (_cashWithdrawalStorage.Update(model) == null)
{ {
_logger.LogWarning("Update operation failed"); _logger.LogWarning("Update operation failed");
return false; return false;
} }
return true; return true;
} }
// Удаление операции public bool Delete(CashWithdrawalBindingModel model)
public bool Delete(CashWithdrawalBindingModel model) {
{ CheckModel(model, false);
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id); _logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_cashWithdrawalStorage.Delete(model) == null) if (_cashWithdrawalStorage.Delete(model) == null)
{ {
_logger.LogWarning("Delete operation failed"); _logger.LogWarning("Delete operation failed");
return false; return false;
} }
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)
{ {
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,185 +1,170 @@
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) {
{ throw new ArgumentNullException(nameof(model));
throw new ArgumentNullException(nameof(model)); }
}
_logger.LogInformation("ReadElement. CashierName:{Name}. CashierSurname:{Surname}. CashierPatronymic:{Patronymic}. Id:{Id}", _logger.LogInformation("ReadElement. CashierName:{Name}. CashierSurname:{Surname}. CashierPatronymic:{Patronymic}. Id:{Id}",
model.Name, model.Surname, model.Patronymic, model?.Id); model.Name, model.Surname, model.Patronymic, model?.Id);
var element = _cashierStorage.GetElement(model); var element = _cashierStorage.GetElement(model);
if (element == null) if (element == null)
{ {
_logger.LogWarning("ReadElement element not found"); _logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id); return null;
return element; }
}
// Вывод отфильтрованного списка _logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
public List<CashierViewModel>? ReadList(CashierSearchModel? model)
{
_logger.LogInformation("ReadList. CashierName:{Name}. CashierSurname:{Surname}. CashierPatronymic:{Patronymic}. Id:{Id}",
model.Name, model.Surname, model.Patronymic, model?.Id);
// list хранит весь список в случае, если model пришло со значением null на вход метода return element;
var list = model == null ? _cashierStorage.GetFullList() : _cashierStorage.GetFilteredList(model); }
if (list == null) public List<CashierViewModel>? ReadList(CashierSearchModel? model)
{ {
_logger.LogWarning("ReadList return null list"); _logger.LogInformation("ReadList. CashierName:{Name}. CashierSurname:{Surname}. CashierPatronymic:{Patronymic}. Id:{Id}",
return null; model.Name, model.Surname, model.Patronymic, model?.Id);
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count); //list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _cashierStorage.GetFullList() : _cashierStorage.GetFilteredList(model);
return list; if (list == null)
} {
_logger.LogWarning("ReadList return null list");
return null;
}
// Создание кассира _logger.LogInformation("ReadList. Count:{Count}", list.Count);
public bool Create(CashierBindingModel model)
{
CheckModel(model);
if (_cashierStorage.Insert(model) == null) return list;
{ }
_logger.LogWarning("Insert operation failed");
return false;
}
return true; public bool Create(CashierBindingModel model)
} {
CheckModel(model);
// Обновление кассира if (_cashierStorage.Insert(model) == null)
public bool Update(CashierBindingModel model) {
{ _logger.LogWarning("Insert operation failed");
CheckModel(model);
if (_cashierStorage.Update(model) == null) return false;
{ }
_logger.LogWarning("Update operation failed");
return false;
}
return true; return true;
} }
// Удаление кассира public bool Update(CashierBindingModel model)
public bool Delete(CashierBindingModel model) {
{ CheckModel(model);
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id); if (_cashierStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
if (_cashierStorage.Delete(model) == null) return false;
{ }
_logger.LogWarning("Delete operation failed");
return false; return true;
} }
return true; public bool Delete(CashierBindingModel model)
} {
CheckModel(model, false);
// Проверка входного аргумента для методов Insert, Update и Delete _logger.LogInformation("Delete. Id:{Id}", model.Id);
private void CheckModel(CashierBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
// Так как при удалении передаём как параметр false if (_cashierStorage.Delete(model) == null)
if (!withParams) {
{ _logger.LogWarning("Delete operation failed");
return;
}
// Проверка на наличие имени return false;
if (string.IsNullOrEmpty(model.Name)) }
{
throw new ArgumentNullException("Отсутствие имени в учётной записи", nameof(model.Name));
}
// Проверка на наличие фамилия return true;
if (string.IsNullOrEmpty(model.Surname)) }
{
throw new ArgumentNullException("Отсутствие фамилии в учётной записи", nameof(model.Surname));
}
// Проверка на наличие отчество //проверка входного аргумента для методов Insert, Update и Delete
if (string.IsNullOrEmpty(model.Patronymic)) private void CheckModel(CashierBindingModel model, bool withParams = true)
{ {
throw new ArgumentNullException("Отсутствие отчества в учётной записи", nameof(model.Patronymic)); if (model == null)
} {
throw new ArgumentNullException(nameof(model));
}
// Проверка на наличие почты //так как при удалении передаём как параметр false
if (string.IsNullOrEmpty(model.Email)) if (!withParams)
{ {
throw new ArgumentNullException("Отсутствие почты в учётной записи (логина)", nameof(model.Email)); return;
} }
// Проверка на наличие пароля //проверка на наличие имени
if (string.IsNullOrEmpty(model.Password)) if (string.IsNullOrEmpty(model.Name))
{ {
throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password)); throw new ArgumentNullException("Отсутствие имени в учётной записи", nameof(model.Name));
} }
// Проверка на мобильный телефон //проверка на наличие фамилия
if (string.IsNullOrEmpty(model.MobilePhone)) if (string.IsNullOrEmpty(model.Surname))
{ {
throw new ArgumentNullException("Отсутствие почты в учётной записи (логина)", nameof(model.MobilePhone)); throw new ArgumentNullException("Отсутствие фамилии в учётной записи", nameof(model.Name));
} }
_logger.LogInformation("Cashier. CashierName:{Name}. CashierSurname:{Surname}. CashierPatronymic:{Patronymic}. " + //проверка на наличие отчество
"Email:{Email}. Password:{Password}. MobilePhone:{MobilePhone} Id:{Id}", if (string.IsNullOrEmpty(model.Patronymic))
model.Name, model.Surname, model.Patronymic, model.Email, model.Password, model.MobilePhone, model.Id); {
throw new ArgumentNullException("Отсутствие отчества в учётной записи", nameof(model.Name));
}
// Для проверка на наличие такого же аккаунта //проверка на наличие почты
var element = _cashierStorage.GetElement(new CashierSearchModel if (string.IsNullOrEmpty(model.Email))
{ {
Email = model.Email, throw new ArgumentNullException("Отсутствие почты в учётной записи (логина)", nameof(model.Email));
}); }
// Если элемент найден и его Id не совпадает с Id переданного объекта //проверка на наличие пароля
if (element != null && element.Id != model.Id) if (string.IsNullOrEmpty(model.Password))
{ {
throw new InvalidOperationException("Аккаунт с таким логином уже есть"); throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password));
} }
}
} _logger.LogInformation("Cashier. CashierName:{Name}. CashierSurname:{Surname}. CashierPatronymic:{Patronymic}. " +
"Email:{Email}. Password:{Password}. Id:{Id}",
model.Name, model.Surname, model.Patronymic, model.Email, model.Password, model.Id);
//для проверка на наличие такого же аккаунта
var element = _cashierStorage.GetElement(new CashierSearchModel
{
Email = model.Email,
});
//если элемент найден и его Id не совпадает с Id переданного объекта
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Аккаунт с таким логином уже есть");
}
}
}
} }

View File

@ -2,177 +2,168 @@
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;
private readonly IMoneyTransferStorage _moneyTransferStorage; private readonly IMoneyTransferStorage _moneyTransferStorage;
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; _moneyTransferStorage = moneyTransferStorage;
_moneyTransferStorage = moneyTransferStorage; _creditingStorage = creditingStorage;
_creditingStorage = creditingStorage; }
}
// Вывод конкретной операции public MoneyTransferViewModel? ReadElement(MoneyTransferSearchModel model)
public MoneyTransferViewModel? ReadElement(MoneyTransferSearchModel model) {
{ if (model == null)
if (model == null) {
{ throw new ArgumentNullException(nameof(model));
throw new ArgumentNullException(nameof(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);
var element = _moneyTransferStorage.GetElement(model); var element = _moneyTransferStorage.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<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)
{ {
_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(MoneyTransferBindingModel model)
public bool Create(MoneyTransferBindingModel model) {
{ CheckModel(model);
CheckModel(model);
if (_moneyTransferStorage.Insert(model) == null) if (_moneyTransferStorage.Insert(model) == null)
{ {
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Insert operation failed");
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.Закрыта
});
} }
return true; return true;
} }
// Обновление операции на перевод public bool Update(MoneyTransferBindingModel model)
public bool Update(MoneyTransferBindingModel model) {
{ CheckModel(model);
CheckModel(model);
if (_moneyTransferStorage.Update(model) == null) if (_moneyTransferStorage.Update(model) == null)
{ {
_logger.LogWarning("Update operation failed"); _logger.LogWarning("Update operation failed");
return false; return false;
} }
return true; return true;
} }
// Удаление операции на перевод public bool Delete(MoneyTransferBindingModel model)
public bool Delete(MoneyTransferBindingModel model) {
{ CheckModel(model, false);
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id); _logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_moneyTransferStorage.Delete(model) == null) if (_moneyTransferStorage.Delete(model) == null)
{ {
_logger.LogWarning("Delete operation failed"); _logger.LogWarning("Delete operation failed");
return false; return false;
} }
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)
{ {
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,138 +28,123 @@ 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);
var list = model == null ? _cardStorage.GetFullList() : _cardStorage.GetFilteredList(model);
// list хранит весь список в случае, если model пришло со значением null на вход метода
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 Update(CardBindingModel model)
public bool Create(CardBindingModel model)
{ {
CheckModel(model); CheckModel(model);
if (_cardStorage.Update(model) == null)
if (_cardStorage.Insert(model) == null)
{ {
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Update operation failed");
return false; return false;
} }
return true; return true;
} }
// Обновление банковской карты public List<ClientDiagramElementsViewModel> GetMonthInfo(int CardId) {
public bool Update(CardBindingModel model)
{
CheckModel(model);
if (_cardStorage.Update(model) == null) Dictionary<(int?, int?), int> debitings = _debitingLogic.ReadList(new DebitingSearchModel()
{
_logger.LogWarning("Update 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"); 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));
return true; 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;
} }
// Проверка входного аргумента для методов 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));
} }
if (!withParams)
// Так как при удалении передаём как параметр false
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("Неправильный СVC карты", nameof(model.CVC));
{ }
throw new ArgumentNullException("Изначальный баланс карты не может быть < 0", nameof(model.Balance)); if (model.Period < DateTime.Now)
}
// Проверка на конкретный период действия карты
if (model.Period < DateTime.Now)
{ {
throw new ArgumentNullException("Нет периода действия", nameof(model.Period)); throw new ArgumentNullException("Нет периода действия", nameof(model.Period));
} }
var cardElement = _cardStorage.GetElement(new CardSearchModel
// Проверка на наличие id клиента, получившего карту (лишним не будет)
if (model.ClientId < 0)
{
throw new ArgumentNullException("Некорректный Id кассира, открывшего счёт", nameof(model.ClientId));
}
// Для проверка на наличие такой же банковской карты
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 bool Create(CreditingBindingModel model)
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)
{ {
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");
@ -83,73 +40,101 @@ namespace BankBusinessLogic.BusinessLogic.Client
return false; return false;
} }
return true; return true;
} }
// Обновление операции на пополнение public bool Delete(CreditingBindingModel model)
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)
{ {
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)
private void CheckModel(CreditingBindingModel model, bool withParams = true)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); 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;
}
// Так как при удалении передаём как параметр false public List<CreditingViewModel>? ReadList(CreditingSearchModel? model)
if (!withParams) {
_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)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{ {
return; return;
} }
if (model.Sum <= 0)
// Проверка на корректность Id клиента банковской карты
if (model.ClientId < 0)
{
throw new ArgumentNullException("Некорректный Id клиента", nameof(model.ClientId));
}
// Проверка на корректность суммы пополнения
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,19 +1,14 @@
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,62 +16,26 @@ 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 bool Create(DebitingBindingModel model)
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)
{ {
CheckModel(model); CheckModel(model);
if (_debitingStorage.Insert(model) == null) if (!CheckCardPeriod(model))
{
model.Status = StatusEnum.Карта_просрочена;
}
else
{
model.Status = StatusEnum.Открыта;
}
if (_debitingStorage.Insert(model) == null)
{ {
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Insert operation failed");
return false; return false;
@ -85,71 +44,100 @@ namespace BankBusinessLogic.BusinessLogic.Client
return true; return true;
} }
// Обновление операции на снятие наличных public bool Delete(DebitingBindingModel model)
public bool Update(DebitingBindingModel model)
{
CheckModel(model);
if (_debitingStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
// Удаление операции на снятие наличных
public bool Delete(DebitingBindingModel model)
{ {
CheckModel(model, false); CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id); _logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_debitingStorage.Delete(model) == null) if (_debitingStorage.Delete(model) == null)
{ {
_logger.LogWarning("Delete operation failed"); _logger.LogWarning("Delete operation failed");
return false; 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)
{
CheckModel(model);
if (_debitingStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true; 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));
} }
if (!withParams)
// Так как при удалении передаём как параметр false
if (!withParams)
{ {
return; return;
} }
if (model.Sum <= 0)
// Проверка на корректность Id клиента банковской карты
if (model.ClientId < 0)
{
throw new ArgumentNullException("Некорректный Id клиента", nameof(model.ClientId));
}
// Проверка на корректность снятия суммы
if (model.Sum <= 0)
{ {
throw new ArgumentNullException("Сумма операции должна быть больше 0", nameof(model.Sum)); throw new ArgumentNullException("Сумма операции должна быть больше 0", nameof(model.Sum));
} }
if (model.DateClose < model.DateOpen)
{
throw new ArgumentNullException("Дата закрытия не может быть меньше даты открытия", nameof(model.DateClose));
}
_logger.LogInformation("Debiting. Sum:{Sum}.CardId:{CardId}.DateOpen:{DateOpen}.DateOpen:{DateOpen}.Id:{Id}",
model.Sum, model.CardId, model.DateOpen.ToString(), model.DateClose.ToString(), model.Id);
}
// Проверка на корректную дату операции //проверка карты на просроченность
if (model.DateDebit > DateTime.Now) bool CheckCardPeriod(DebitingBindingModel model)
{
var card = _cardStorage.GetElement(new CardSearchModel
{ {
throw new ArgumentNullException("Дата не может быть меньше текущего времени", nameof(model.DateDebit)); Id = model.CardId
});
//если карта просрочена
if (card.Period < DateTime.Now)
{
return false;
} }
_logger.LogInformation("Debiting. Sum:{Sum}.CardId:{CardId}.DateDebit:{DateDebit}.Id:{Id}", return true;
model.Sum, model.CardId, model.DateDebit.ToString(), model.Id); }
} }
}
} }

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,
IDebitingStorage debitingStorage, IClientStorage clientStorage, ICardStorage cardStorage, //инициализируем поля класса через контейнер
AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf) public ReportCashierLogic(IMoneyTransferStorage moneyTransferStorage, ICashWithdrawalStorage cashWithdrawalStorage,
IClientStorage clientStorage, AbstractSaveToExcel saveToExcel,
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
{ {
@ -104,12 +102,12 @@ namespace BankBusinessLogic.BusinessLogic.Reports
}); });
totalList.AddRange(result); totalList.AddRange(result);
} }
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,114 +1,114 @@
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 ICardStorage _cardStorage;
private readonly IMoneyTransferStorage _moneyTransferStorage;
private readonly IClientStorage _clientStorage;
private readonly IClientStorage _clientStorage; private readonly AbstractSaveToExcel _saveToExcel;
private readonly ICardStorage _cardStorage; private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
private readonly AbstractSaveToExcel _saveToExcel; private readonly MailKitWorker _mailKitWorker;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
// Конструктор public ReportClientLogic(ICreditingStorage creditingStorage, IDebitingStorage debitingStorage,
public ReportClientLogic(IMoneyTransferStorage moneyTransferStorage,ICreditingStorage creditingStorage, AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf,
IDebitingStorage debitingStorage, IClientStorage clientStorage, ICardStorage cardStorage, ICardStorage cardStorage, IMoneyTransferStorage moneyTransferStorage,
AbstractSaveToExcel saveToExcel, AbstractSaveToWord saveToWord, AbstractSaveToPdf saveToPdf) MailKitWorker mailKitWorker, IClientStorage clientStorage)
{ {
_moneyTransferStorage = moneyTransferStorage; _creditingStorage = creditingStorage;
_creditingStorage = creditingStorage; _debitingStorage = debitingStorage;
_debitingStorage = debitingStorage; _cardStorage = cardStorage;
_moneyTransferStorage = moneyTransferStorage;
_clientStorage = clientStorage;
_clientStorage = clientStorage; _saveToExcel = saveToExcel;
_cardStorage = cardStorage; _saveToWord = saveToWord;
_saveToPdf = saveToPdf;
_saveToExcel = saveToExcel; _mailKitWorker = mailKitWorker;
_saveToWord = saveToWord; }
_saveToPdf = saveToPdf;
}
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,
}).Select(x => new ReportClientViewModel DateTo = model.DateTo,
{ }).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();
} }
public List<ReportClientViewModel>? GetDebiting(ReportBindingModel model) public List<ReportClientViewModel>? GetDebiting(ReportBindingModel model)
{ {
return _debitingStorage.GetFilteredList(new DebitingSearchModel return _debitingStorage.GetFilteredList(new DebitingSearchModel
{ {
DateDebit = model.DateFrom, DateTo = model.DateFrom,
}).Select(x => new ReportClientViewModel DateFrom = model.DateTo,
{ }).Select(x => new ReportClientViewModel
OperationId = x.Id, {
CardNumber = x.CardNumber, OperationId = x.Id,
SumOperation = x.Sum, CardNumber = x.CardNumber,
DateComplite = x.DateDebit SumOperation = x.Sum,
}).ToList(); DateComplite = x.DateClose
} }).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();
List<MoneyTransferViewModel> totalList = new(); List<MoneyTransferViewModel> totalList = new();
foreach (var index in list) foreach (var index in list)
{ {
var result = _moneyTransferStorage.GetFilteredList(new MoneyTransferSearchModel var result = _moneyTransferStorage.GetFilteredList(new MoneyTransferSearchModel
{ {
AccountSenderId = index, AccountSenderId = index,
AccountPayeeId = index AccountPayeeId = index
}).OrderBy(x => x.AccountSenderId).ToList(); }).OrderBy(x => x.AccountSenderId).ToList();
totalList.AddRange(result); totalList.AddRange(result);
} }
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();
foreach (var index in model.CardList) foreach (var index in model.CardList)
@ -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) {
{ byte[] excel = Array.Empty<byte>();
throw new NotImplementedException();
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) {
{ byte[] word = Array.Empty<byte>();
throw new NotImplementedException();
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");
}
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 для клиента //отчёт в формате 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,19 +1,24 @@
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;
private string _mailPassword = string.Empty; private string _mailPassword = string.Empty;
@ -24,22 +29,21 @@ 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)
{ {
using var objMailMessage = new MailMessage(); using var objMailMessage = new MailMessage();
using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort);
@ -52,42 +56,42 @@ 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"));
} }
} }
objSmtpClient.UseDefaultCredentials = false; objSmtpClient.UseDefaultCredentials = false;
objSmtpClient.EnableSsl = true; objSmtpClient.EnableSsl = true;
@ -101,6 +105,5 @@ namespace BankBusinessLogic.MailWorker
throw; throw;
} }
} }
}
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -8,169 +8,173 @@ using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage 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);
} }
else else
{ {
CreateDocCashier(info); CreateDocCashier(info);
} }
} }
// Отчёт для клиента #region Отчёт для клиента
public void CreateDocClient(PdfInfo info) public void CreateDocClient(PdfInfo info)
{ {
CreatePdf(info); CreatePdf(info);
CreateParagraph(new PdfParagraph CreateParagraph(new PdfParagraph
{ {
Text = info.Title + $"\nот {DateTime.Now.ToShortDateString()}", Text = info.Title + $"\nот {DateTime.Now.ToShortDateString()}",
Style = "NormalTitle", Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center ParagraphAlignment = PdfParagraphAlignmentType.Center
}); });
CreateParagraph(new PdfParagraph CreateParagraph(new PdfParagraph
{ {
Text = $"Расчётный период: с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}", Text = $"Расчётный период: с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}",
Style = "Normal", Style = "Normal",
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" });
CreateRow(new PdfRowParameters CreateRow(new PdfRowParameters
{ {
Texts = new List<string> { "Номер операции", "Номер карты", "Сумма", "Дата операции" }, Texts = new List<string> { "Номер операции", "Номер карты", "Сумма", "Дата операции" },
Style = "NormalTitle", Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center ParagraphAlignment = PdfParagraphAlignmentType.Center
}); });
foreach (var report in info.ReportCrediting) foreach (var report in info.ReportCrediting)
{ {
CreateRow(new PdfRowParameters CreateRow(new PdfRowParameters
{ {
Texts = new List<string> { report.OperationId.ToString(), report.CardNumber, report.SumOperation.ToString(), report.DateComplite.ToString() }, Texts = new List<string> { report.OperationId.ToString(), report.CardNumber, report.SumOperation.ToString(), report.DateComplite.ToString() },
Style = "Normal", Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left ParagraphAlignment = PdfParagraphAlignmentType.Left
}); });
} }
// Подсчёт суммы операций на пополнение //подсчёт суммы операций на пополнение
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" });
CreateRow(new PdfRowParameters CreateRow(new PdfRowParameters
{ {
Texts = new List<string> { "Номер операции", "Номер карты", "Сумма", "Дата операции" }, Texts = new List<string> { "Номер операции", "Номер карты", "Сумма", "Дата операции" },
Style = "NormalTitle", Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center ParagraphAlignment = PdfParagraphAlignmentType.Center
}); });
foreach (var report in info.ReportDebiting) foreach (var report in info.ReportDebiting)
{ {
CreateRow(new PdfRowParameters CreateRow(new PdfRowParameters
{ {
Texts = new List<string> { report.OperationId.ToString(), report.CardNumber, report.SumOperation.ToString(), report.DateComplite.ToString() }, Texts = new List<string> { report.OperationId.ToString(), report.CardNumber, report.SumOperation.ToString(), report.DateComplite.ToString() },
Style = "Normal", Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left ParagraphAlignment = PdfParagraphAlignmentType.Left
}); });
} }
// Подсчёт суммы операций на пополнение //подсчёт суммы операций на пополнение
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)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph //создание отчёта для кассира
{ public void CreateDocCashier(PdfInfo info)
Text = info.Title + $"\nот {DateTime.Now.ToShortDateString()}\nФИО клиента: {info.FullClientName}", {
Style = "NormalTitle", CreatePdf(info);
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateParagraph(new PdfParagraph CreateParagraph(new PdfParagraph
{ {
Text = $"Расчётный период: с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}", Text = info.Title + $"\nот {DateTime.Now.ToShortDateString()}\nФИО клиента: {info.FullClientName}",
Style = "Normal", Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center ParagraphAlignment = PdfParagraphAlignmentType.Center
}); });
// Параграф с отчётом по выдаче наличных с карт CreateParagraph(new PdfParagraph
CreateParagraph(new PdfParagraph { Text = "Отчёт по выдаче наличных со счёта", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center }); {
Text = $"Расчётный период: с {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateTable(new List<string> { "3.5cm", "3.5cm", "5cm", "5cm" }); //параграф с отчётом по выдаче наличных с карт
CreateParagraph(new PdfParagraph { Text = "Отчёт по выдаче наличных со счёта", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateRow(new PdfRowParameters CreateTable(new List<string> { "3.5cm", "3.5cm", "5cm", "5cm" });
{
Texts = new List<string> { "Номер операции", "Номер счёта", "Сумма операции", "Дата операции" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var report in info.ReportCashWithdrawal) CreateRow(new PdfRowParameters
{ {
CreateRow(new PdfRowParameters Texts = new List<string> { "Номер операции", "Номер счёта", "Сумма операции", "Дата операции" },
{ Style = "NormalTitle",
Texts = new List<string> { report.OperationId.ToString(), report.AccountPayeeNumber, report.SumOperation.ToString(), report.DateComplite.ToShortDateString(), }, ParagraphAlignment = PdfParagraphAlignmentType.Center
Style = "Normal", });
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
CreateParagraph(new PdfParagraph { Text = $"Итоговая сумма снятий за период: {info.ReportCashWithdrawal.Sum(x => x.SumOperation)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right }); foreach (var report in info.ReportCashWithdrawal)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { report.OperationId.ToString(), report.AccountPayeeNumber, report.SumOperation.ToString(), report.DateComplite.ToShortDateString(), },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
// Параграф с отчётом по переводу денег со счёта на счёт 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 });
CreateTable(new List<string> { "3cm", "3cm", "3cm", "4cm", "4cm" }); //параграф с отчётом по переводу денег со счёта на счёт
CreateParagraph(new PdfParagraph { Text = "Отчёт по денежным переводам между счетами", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center });
CreateRow(new PdfRowParameters CreateTable(new List<string> { "3cm", "3cm", "3cm", "4cm", "4cm" });
{
Texts = new List<string> { "Номер операции", "Номер счёта отправителя", "Номер счёта получателя", "Сумма операции", "Дата операции" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var report in info.ReportMoneyTransfer) CreateRow(new PdfRowParameters
{ {
CreateRow(new PdfRowParameters Texts = new List<string> { "Номер операции", "Номер счёта отправителя", "Номер счёта получателя", "Сумма операции", "Дата операции" },
{ Style = "NormalTitle",
Texts = new List<string> { report.OperationId.ToString(), report.AccountSenderNumber, report.AccountPayeeNumber, report.SumOperation.ToString(), report.DateComplite.ToShortDateString(), }, ParagraphAlignment = PdfParagraphAlignmentType.Center
Style = "Normal", });
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
CreateParagraph(new PdfParagraph { Text = $"Итоговая сумма переводов за период: {info.ReportMoneyTransfer.Sum(x => x.SumOperation)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right }); foreach (var report in info.ReportMoneyTransfer)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { report.OperationId.ToString(), report.AccountSenderNumber, report.AccountPayeeNumber, report.SumOperation.ToString(), report.DateComplite.ToShortDateString(), },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
SavePdf(info); CreateParagraph(new PdfParagraph { Text = $"Итоговая сумма переводов за период: {info.ReportMoneyTransfer.Sum(x => x.SumOperation)}\t", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Right });
}
/// Создание pdf-файла SavePdf(info);
protected abstract void CreatePdf(PdfInfo info); }
#endregion
/// Создание pdf-файла
protected abstract void CreatePdf(PdfInfo info);
/// Создание параграфа с текстом /// Создание параграфа с текстом
protected abstract void CreateParagraph(PdfParagraph paragraph); protected abstract void CreateParagraph(PdfParagraph paragraph);

View File

@ -14,340 +14,340 @@ namespace BankBusinessLogic.OfficePackage
//метод создания документа //метод создания документа
public void CreateDoc(WordInfo info, OfficeOperationEnum operationEnum) public void CreateDoc(WordInfo info, OfficeOperationEnum operationEnum)
{ {
if (operationEnum == OfficeOperationEnum.Между_cчетами) if (operationEnum == OfficeOperationEnum.Между_cчетами)
{ {
CreateMoneyTransferWord(info); CreateMoneyTransferWord(info);
} }
if (operationEnum == OfficeOperationEnum.Пополнениеарт) if (operationEnum == OfficeOperationEnum.Пополнениеарт)
{ {
CreateCreditingWord(info); CreateCreditingWord(info);
} }
if (operationEnum == OfficeOperationEnum.Cнятие_сарты) if (operationEnum == OfficeOperationEnum.Cнятие_сарты)
{ {
CreateDebitingWord(info); CreateDebitingWord(info);
} }
if (operationEnum == OfficeOperationEnum.Дляассира) if (operationEnum == OfficeOperationEnum.Дляассира)
{ {
CreateCashierWord(info); CreateCashierWord(info);
} }
} }
private void CreateMoneyTransferWord(WordInfo info) private void CreateMoneyTransferWord(WordInfo info)
{ {
CreateWord(info); CreateWord(info);
CreateParagraph(new WordParagraph CreateParagraph(new WordParagraph
{ {
Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24" }) }, Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24" }) },
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
JustificationType = WordJustificationType.Center JustificationType = WordJustificationType.Center
} }
}); });
foreach (var transfer in info.MoneyTransfer) foreach (var transfer in info.MoneyTransfer)
{ {
List<List<(string, WordTextProperties)>> rowList = new() List<List<(string, WordTextProperties)>> rowList = new()
{ {
new() new()
{ {
new("Номер счёта отправителя", new WordTextProperties { Bold = true, Size = "20" } ), new("Номер счёта отправителя", new WordTextProperties { Bold = true, Size = "20" } ),
new("Номер счёта получателя", new WordTextProperties { Bold = true, Size = "20" } ), new("Номер счёта получателя", new WordTextProperties { Bold = true, Size = "20" } ),
new("Сумма операции", new WordTextProperties { Bold = true, Size = "20" } ), new("Сумма операции", new WordTextProperties { Bold = true, Size = "20" } ),
new("Дата перевода", new WordTextProperties { Bold = true, Size = "20" } ) new("Дата перевода", new WordTextProperties { Bold = true, Size = "20" } )
} }
}; };
CreateParagraph(new WordParagraph CreateParagraph(new WordParagraph
{ {
Texts = new List<(string, WordTextProperties)> { ("Перевод №" + transfer.Id.ToString(), new WordTextProperties { Bold = true, Size = "24" }) }, Texts = new List<(string, WordTextProperties)> { ("Перевод №" + transfer.Id.ToString(), new WordTextProperties { Bold = true, Size = "24" }) },
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
JustificationType = WordJustificationType.Center JustificationType = WordJustificationType.Center
} }
}); });
List<(string, WordTextProperties)> cellList = new() List<(string, WordTextProperties)> cellList = new()
{ {
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);
CreateTable(new WordParagraph CreateTable(new WordParagraph
{ {
RowTexts = rowList, RowTexts = rowList,
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
JustificationType = WordJustificationType.Center JustificationType = WordJustificationType.Center
} }
}); });
} }
CreateParagraph(new WordParagraph CreateParagraph(new WordParagraph
{ {
Texts = new List<(string, WordTextProperties)> { ("Суммарный объём переводов: " + info.MoneyTransfer.Sum(x => x.Sum).ToString(), Texts = new List<(string, WordTextProperties)> { ("Суммарный объём переводов: " + info.MoneyTransfer.Sum(x => x.Sum).ToString(),
new WordTextProperties { Bold = true, Size = "24" }) }, new WordTextProperties { Bold = true, Size = "24" }) },
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
JustificationType = WordJustificationType.Both JustificationType = WordJustificationType.Both
} }
}); });
SaveWord(info); SaveWord(info);
} }
private void CreateCreditingWord(WordInfo info) private void CreateCreditingWord(WordInfo info)
{ {
CreateWord(info); CreateWord(info);
CreateParagraph(new WordParagraph CreateParagraph(new WordParagraph
{ {
Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24" }) }, Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24" }) },
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
JustificationType = WordJustificationType.Center JustificationType = WordJustificationType.Center
} }
}); });
foreach (var crediting in info.Crediting) foreach (var crediting in info.Crediting)
{ {
List<List<(string, WordTextProperties)>> rowList = new() List<List<(string, WordTextProperties)>> rowList = new()
{ {
new() new()
{ {
new("Номер карты", new WordTextProperties { Bold = true, Size = "24" } ), new("Номер карты", new WordTextProperties { Bold = true, Size = "24" } ),
new("Сумма пополнения", new WordTextProperties { Bold = true, Size = "24" } ), new("Сумма пополнения", new WordTextProperties { Bold = true, Size = "24" } ),
new("Дата выполнения", new WordTextProperties { Bold = true, Size = "24" } ) new("Дата выполнения", new WordTextProperties { Bold = true, Size = "24" } )
} }
}; };
CreateParagraph(new WordParagraph CreateParagraph(new WordParagraph
{ {
Texts = new List<(string, WordTextProperties)> { ("Пополнение №" + crediting.Id.ToString(), new WordTextProperties { Bold = true, Size = "24" }) }, Texts = new List<(string, WordTextProperties)> { ("Пополнение №" + crediting.Id.ToString(), new WordTextProperties { Bold = true, Size = "24" }) },
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
JustificationType = WordJustificationType.Center JustificationType = WordJustificationType.Center
} }
}); });
List<(string, WordTextProperties)> cellList = new() List<(string, WordTextProperties)> cellList = new()
{ {
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);
CreateTable(new WordParagraph CreateTable(new WordParagraph
{ {
RowTexts = rowList, RowTexts = rowList,
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
JustificationType = WordJustificationType.Center JustificationType = WordJustificationType.Center
} }
}); });
} }
//формирование списка поступления по каждой карте //формирование списка поступления по каждой карте
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))
{ {
dict[elem.CardNumber] += elem.Sum; dict[elem.CardNumber] += elem.Sum;
} }
else else
{ {
dict[elem.CardNumber] = elem.Sum; dict[elem.CardNumber] = elem.Sum;
} }
} }
foreach (var elem in dict) foreach (var elem in dict)
{ {
CreateParagraph(new WordParagraph CreateParagraph(new WordParagraph
{ {
Texts = new List<(string, WordTextProperties)> { ("Суммарное пополнение на карту №" + elem.Key + ": " + elem.Value.ToString(), new WordTextProperties { Bold = true, Size = "24" }) }, Texts = new List<(string, WordTextProperties)> { ("Суммарное пополнение на карту №" + elem.Key + ": " + elem.Value.ToString(), new WordTextProperties { Bold = true, Size = "24" }) },
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
JustificationType = WordJustificationType.Both JustificationType = WordJustificationType.Both
} }
}); });
} }
SaveWord(info); SaveWord(info);
} }
private void CreateDebitingWord(WordInfo info) private void CreateDebitingWord(WordInfo info)
{ {
CreateWord(info); CreateWord(info);
CreateParagraph(new WordParagraph CreateParagraph(new WordParagraph
{ {
Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24" }) }, Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24" }) },
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
JustificationType = WordJustificationType.Center JustificationType = WordJustificationType.Center
} }
}); });
foreach (var crediting in info.Debiting) foreach (var crediting in info.Debiting)
{ {
List<List<(string, WordTextProperties)>> rowList = new() List<List<(string, WordTextProperties)>> rowList = new()
{ {
new() new()
{ {
new("Номер карты", new WordTextProperties { Bold = true, Size = "24" } ), new("Номер карты", new WordTextProperties { Bold = true, Size = "24" } ),
new("Сумма снятия", new WordTextProperties { Bold = true, Size = "24" } ), new("Сумма снятия", new WordTextProperties { Bold = true, Size = "24" } ),
new("Дата выполнения", new WordTextProperties { Bold = true, Size = "24" } ) new("Дата выполнения", new WordTextProperties { Bold = true, Size = "24" } )
} }
}; };
CreateParagraph(new WordParagraph CreateParagraph(new WordParagraph
{ {
Texts = new List<(string, WordTextProperties)> { ("Снятие №" + crediting.Id.ToString(), new WordTextProperties { Bold = true, Size = "24" }) }, Texts = new List<(string, WordTextProperties)> { ("Снятие №" + crediting.Id.ToString(), new WordTextProperties { Bold = true, Size = "24" }) },
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
JustificationType = WordJustificationType.Center JustificationType = WordJustificationType.Center
} }
}); });
List<(string, WordTextProperties)> cellList = new() List<(string, WordTextProperties)> cellList = new()
{ {
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);
CreateTable(new WordParagraph CreateTable(new WordParagraph
{ {
RowTexts = rowList, RowTexts = rowList,
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
JustificationType = WordJustificationType.Center JustificationType = WordJustificationType.Center
} }
}); });
} }
//формирование списка поступления по каждой карте //формирование списка поступления по каждой карте
var dict = new Dictionary<string, double>(); var dict = new Dictionary<string, int>();
foreach (var elem in info.Debiting) foreach (var elem in info.Debiting)
{ {
if (dict.ContainsKey(elem.CardNumber)) if (dict.ContainsKey(elem.CardNumber))
{ {
dict[elem.CardNumber] += elem.Sum; dict[elem.CardNumber] += elem.Sum;
} }
else else
{ {
dict[elem.CardNumber] = elem.Sum; dict[elem.CardNumber] = elem.Sum;
} }
} }
foreach (var elem in dict) foreach (var elem in dict)
{ {
CreateParagraph(new WordParagraph CreateParagraph(new WordParagraph
{ {
Texts = new List<(string, WordTextProperties)> { ("Суммарное снятие с карты №" + elem.Key + ": " + elem.Value.ToString(), new WordTextProperties { Bold = true, Size = "24" }) }, Texts = new List<(string, WordTextProperties)> { ("Суммарное снятие с карты №" + elem.Key + ": " + elem.Value.ToString(), new WordTextProperties { Bold = true, Size = "24" }) },
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
JustificationType = WordJustificationType.Both JustificationType = WordJustificationType.Both
} }
}); });
} }
SaveWord(info); SaveWord(info);
} }
private void CreateCashierWord(WordInfo info) private void CreateCashierWord(WordInfo info)
{ {
CreateWord(info); CreateWord(info);
CreateParagraph(new WordParagraph CreateParagraph(new WordParagraph
{ {
Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24" }) }, Texts = new List<(string, WordTextProperties)> { (info.Title, new WordTextProperties { Bold = true, Size = "24" }) },
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
JustificationType = WordJustificationType.Center JustificationType = WordJustificationType.Center
} }
}); });
foreach (var crediting in info.Debiting) foreach (var crediting in info.Debiting)
{ {
List<List<(string, WordTextProperties)>> rowList = new() List<List<(string, WordTextProperties)>> rowList = new()
{ {
new() new()
{ {
new("Сумма заявки", new WordTextProperties { Bold = true, Size = "24" } ), new("Сумма заявки", new WordTextProperties { Bold = true, Size = "24" } ),
new("Дата открытия", new WordTextProperties { Bold = true, Size = "24" } ), new("Дата открытия", new WordTextProperties { Bold = true, Size = "24" } ),
new("Статус", new WordTextProperties { Bold = true, Size = "24" } ) new("Статус", new WordTextProperties { Bold = true, Size = "24" } )
} }
}; };
CreateParagraph(new WordParagraph CreateParagraph(new WordParagraph
{ {
Texts = new List<(string, WordTextProperties)> { ("Заявка №" + crediting.Id.ToString(), new WordTextProperties { Bold = true, Size = "24" }) }, Texts = new List<(string, WordTextProperties)> { ("Заявка №" + crediting.Id.ToString(), new WordTextProperties { Bold = true, Size = "24" }) },
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
JustificationType = WordJustificationType.Center JustificationType = WordJustificationType.Center
} }
}); });
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" })
}; };
rowList.Add(cellList); rowList.Add(cellList);
CreateTable(new WordParagraph CreateTable(new WordParagraph
{ {
RowTexts = rowList, RowTexts = rowList,
TextProperties = new WordTextProperties TextProperties = new WordTextProperties
{ {
Size = "24", Size = "24",
JustificationType = WordJustificationType.Center JustificationType = WordJustificationType.Center
} }
}); });
} }
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,40 +1,35 @@
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;
public string Title { get; set; } = string.Empty; public string Title { get; set; } = string.Empty;
public DateTime DateFrom { get; set; } public DateTime DateFrom { get; set; }
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,14 +6,14 @@ 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,22 +14,21 @@ 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;
private SharedStringTablePart? _shareStringPart; private SharedStringTablePart? _shareStringPart;
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,17 +47,17 @@ 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();
fill1.Append(new PatternFill() fill1.Append(new PatternFill()
{ {
PatternType = PatternValues.None PatternType = PatternValues.None
}); });
var fill2 = new Fill(); var fill2 = 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);
@ -203,7 +201,7 @@ namespace BankBusinessLogic.OfficePackage.Implements
}; };
stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"); stylesheetExtension2.AddNamespaceDeclaration("x15", "http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
stylesheetExtension2.Append(new TimelineStyles() stylesheetExtension2.Append(new TimelineStyles()
{ {
DefaultTimelineStyle = "TimeSlicerStyleLight1" DefaultTimelineStyle = "TimeSlicerStyleLight1"
@ -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,16 +11,16 @@ 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;
private Section? _section; private Section? _section;
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,92 +135,92 @@ 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)
{ {
return; return;
} }
Table table = new Table(); Table table = new Table();
var tableProp = new TableProperties(); var tableProp = new TableProperties();
tableProp.AppendChild(new TableLayout { Type = TableLayoutValues.Fixed }); tableProp.AppendChild(new TableLayout { Type = TableLayoutValues.Fixed });
tableProp.AppendChild(new TableBorders( tableProp.AppendChild(new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 }, new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 }, new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 }, new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 }, new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 }, new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 } new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4 }
)); ));
tableProp.AppendChild(new TableWidth { Type = TableWidthUnitValues.Auto }); tableProp.AppendChild(new TableWidth { Type = TableWidthUnitValues.Auto });
table.AppendChild(tableProp); table.AppendChild(tableProp);
TableGrid tableGrid = new TableGrid(); TableGrid tableGrid = new TableGrid();
for (int j = 0; j < paragraph.RowTexts[0].Count; ++j) for (int j = 0; j < paragraph.RowTexts[0].Count; ++j)
{ {
tableGrid.AppendChild(new GridColumn() { Width = "2500" }); tableGrid.AppendChild(new GridColumn() { Width = "2500" });
} }
table.AppendChild(tableGrid); table.AppendChild(tableGrid);
for (int i = 0; i < paragraph.RowTexts.Count; ++i) for (int i = 0; i < paragraph.RowTexts.Count; ++i)
{ {
TableRow docRow = new TableRow(); TableRow docRow = new TableRow();
for (int j = 0; j < paragraph.RowTexts[i].Count; ++j) for (int j = 0; j < paragraph.RowTexts[i].Count; ++j)
{ {
var docParagraph = new Paragraph(); var docParagraph = new Paragraph();
docParagraph.AppendChild(CreateParagraphProperties(paragraph.RowTexts[i][j].Item2)); docParagraph.AppendChild(CreateParagraphProperties(paragraph.RowTexts[i][j].Item2));
var docRun = new Run(); var docRun = new Run();
var properties = new RunProperties(); var properties = new RunProperties();
properties.AppendChild(new FontSize { Val = paragraph.RowTexts[i][j].Item2.Size }); properties.AppendChild(new FontSize { Val = paragraph.RowTexts[i][j].Item2.Size });
if (paragraph.RowTexts[i][j].Item2.Bold) if (paragraph.RowTexts[i][j].Item2.Bold)
{ {
properties.AppendChild(new Bold()); properties.AppendChild(new Bold());
} }
docRun.AppendChild(properties); docRun.AppendChild(properties);
docRun.AppendChild(new Text { Text = paragraph.RowTexts[i][j].Item1, Space = SpaceProcessingModeValues.Preserve }); docRun.AppendChild(new Text { Text = paragraph.RowTexts[i][j].Item1, Space = SpaceProcessingModeValues.Preserve });
docParagraph.AppendChild(docRun); docParagraph.AppendChild(docRun);
TableCell docCell = new TableCell(); TableCell docCell = new TableCell();
docCell.AppendChild(docParagraph); docCell.AppendChild(docParagraph);
docRow.AppendChild(docCell); docRow.AppendChild(docCell);
} }
table.AppendChild(docRow); table.AppendChild(docRow);
} }
_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)
{ {
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;
@ -53,24 +52,24 @@ 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;
{
var result = await response.Content.ReadAsStringAsync();
throw new HttpRequestException($"Request failed with status code {response.StatusCode}: {result}");
}
}
if (!response.Result.IsSuccessStatusCode)
{
throw new Exception(result);
}
}
//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);
var data = new StringContent(json, Encoding.UTF8, "application/json"); var data = new StringContent(json, Encoding.UTF8, "application/json");

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

@ -1,5 +1,5 @@
@using BankContracts.ViewModels.Client.ViewModels @using BankContracts.ViewModels.Client.ViewModels
@model List<DebitingViewModel> @model List<DebitingViewModel>
@ -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

@ -3,7 +3,7 @@
@model CashierDiagramViewModel @model CashierDiagramViewModel
@{ @{
ViewData["Title"] = "Диаграмма"; ViewData["Title"] = "Диаграмма";
} }
<div class="text-center"> <div class="text-center">
@ -14,23 +14,22 @@
<div class="row mb-2"> <div class="row mb-2">
<div class="row">Номер счета:</div> <div class="row">Номер счета:</div>
<select id="accountId" name="accountId" class="form-control" asp-items="@(new SelectList( @ViewBag.Accounts, "Id", "AccountNumber"))"> <select id="accountId" name="accountId" class="form-control" asp-items="@(new SelectList( @ViewBag.Accounts, "Id", "AccountNumber"))">
<option disabled selected>Выберите счёт</option> <option disabled selected>Выберите счёт</option>
</select> </select>
</div> </div>
<div class="row mb-2"> <div class="row mb-2">
<input style="width:100%;" type="submit" value="Выбрать" class="btn btn-dark" /> <input style="width:100%;" type="submit" value="Выбрать" class="btn btn-dark" />
</div> </div>
</form> </form>
@if (Model == null) return; @if (Model == null) return;
<div id="Diagrams" class="text-center"> <div id="Diagrams" class="text-center">
<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>
</div> </div>
@ -41,7 +40,7 @@
const diagrams = document.getElementById('Diagrams').childNodes; const diagrams = document.getElementById('Diagrams').childNodes;
let diagram_name = diagrams[1].id; let diagram_name = diagrams[1].id;
console.log(diagram_name); console.log(diagram_name);
let diagram = document.getElementById(diagram_name).childNodes; let diagram = document.getElementById(diagram_name).childNodes;
console.log(diagram); console.log(diagram);
@ -60,15 +59,15 @@
new Chart(diagram.item(1), { new Chart(diagram.item(1), {
type: 'bar', type: 'bar',
data: { data: {
labels: labels, labels: labels,
datasets: [{ datasets: [{
label: 'Денег в этом месяце', label: 'Денег в этом месяце',
data: data, data: data,
borderWidth: 1, borderWidth: 1,
backgroundColor: 'rgb(33, 37, 41)' backgroundColor: 'rgb(33, 37, 41)'
}] }]
}, },
options: { options: {
plugins: { plugins: {
legend: { legend: {
@ -84,5 +83,5 @@
} }
} }
); );
</script> </script>

View File

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

View File

@ -7,7 +7,7 @@
</div> </div>
<form class="form-signin text-center" method="post"> <form class="form-signin text-center" method="post">
<h1 class="h3 mb-3 font-weight-normal">Логин</h1> <h1 class="h3 mb-3 font-weight-normal">Логин</h1>
<input type="email" id="login" name="login" class="form-control" placeholder="Почта" required autofocus> <input type="email" id="login" name="login" class="form-control" placeholder="Почта" required autofocus>
<input type="password" id="password" name="password" class="form-control" placeholder="Пароль" required> <input type="password" id="password" name="password" class="form-control" placeholder="Пароль" required>
<button class="btn btn-lg btn-dark btn-block" type="submit" asp-controller="Home" asp-action="Login">Войти</button> <button class="btn btn-lg btn-dark btn-block" type="submit" asp-controller="Home" asp-action="Login">Войти</button>

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

@ -1,38 +1,18 @@
@{ @{
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 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>?
@ -12,9 +13,9 @@
<div class="container" sf-type="container" sf-label="Bootstrap Container" sf-uid="2"> <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="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 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"> <div sf-type="container" sf-label="Container" class="py-15 h-100 bg-bg-2" sf-uid="5">
<form method="post"> <form method="post">
<select id="accountId" name="accountId" class="form-control mb-2" asp-items="@(new SelectList(ViewBag.Accounts, "Id", "AccountNumber"))"> <select id="accountId" name="accountId" class="form-control mb-2" asp-items="@(new SelectList(ViewBag.Accounts, "Id", "AccountNumber"))">
<option disabled selected>Выберите счёт</option> <option disabled selected>Выберите счёт</option>
@ -29,10 +30,10 @@
<button class="btn btn-lg btn-dark btn-block" style="width: 100%;" type="submit" asp-controller="Home" asp-action="CreateCashierWordReport">Создать отчёт по заявкам снятия (WORD</button> <button class="btn btn-lg btn-dark btn-block" style="width: 100%;" type="submit" asp-controller="Home" asp-action="CreateCashierWordReport">Создать отчёт по заявкам снятия (WORD</button>
</div> </div>
</form> </form>
</div> </div>
</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 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"> <div sf-type="container" sf-label="Container" class="py-15 h-100 bg-bg-2" sf-uid="9">
<table class="table"> <table class="table">
<thead> <thead>
<tr> <tr>
@ -58,31 +59,31 @@
</thead> </thead>
<tbody> <tbody>
@foreach (var item in Model) @foreach (var item in Model)
{ {
<tr> <tr>
<td> <td>
@Html.DisplayFor(modelItem => item.typeOperation) @Html.DisplayFor(modelItem => item.typeOperation)
</td> </td>
<td> <td>
@Html.DisplayFor(modelItem => item.CashierSurname) @Html.DisplayFor(modelItem => item.CashierSurname)
</td> </td>
<td> <td>
@Html.DisplayFor(modelItem => item.AccountSenderNumber) @Html.DisplayFor(modelItem => item.AccountSenderNumber)
</td> </td>
<td> <td>
@Html.DisplayFor(modelItem => item.AccountPayeeNumber) @Html.DisplayFor(modelItem => item.AccountPayeeNumber)
</td> </td>
<td> <td>
@Html.DisplayFor(modelItem => item.Sum) @Html.DisplayFor(modelItem => item.Sum)
</td> </td>
<td> <td>
@Html.DisplayFor(modelItem => item.DateOperation) @Html.DisplayFor(modelItem => item.DateOperation)
</td> </td>
</tr> </tr>
} }
</tbody> </tbody>
</table> </table>
</div> </div>
</div> </div>
</div> </div>
</div> </div>

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 {
background-color: #495057;
} }
footer { .btn-custom:hover {
padding: 1rem 0; background-color: #0056b3; /* Цвет кнопки при наведении */
} }
</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

@ -2,47 +2,48 @@
for details on configuring this project to bundle and minify static web assets. */ for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand { a.navbar-brand {
white-space: normal; white-space: normal;
text-align: center; text-align: center;
word-break: break-all; word-break: break-all;
} }
a { a {
color: #0077cc; color: #0077cc;
} }
.btn-primary { .btn-primary {
color: #fff; color: #fff;
background-color: #1b6ec2; background-color: #1b6ec2;
border-color: #1861ac; border-color: #1861ac;
} }
.nav-pills .nav-link.active, .nav-pills .show > .nav-link { .nav-pills .nav-link.active, .nav-pills .show > .nav-link {
color: #fff; color: #fff;
background-color: #1b6ec2; background-color: #1b6ec2;
border-color: #1861ac; border-color: #1861ac;
} }
.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;
} }
.box-shadow { .box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05); box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
} }
button.accept-policy { button.accept-policy {
font-size: 1rem; font-size: 1rem;
line-height: inherit; line-height: inherit;
} }
.footer { .footer {
position: absolute; position: absolute;
bottom: 0; bottom: 0;
width: 100%; width: 100%;
white-space: nowrap; white-space: nowrap;
line-height: 60px; line-height: 60px;
} }

View File

@ -1,82 +1,81 @@
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
{ {
private static readonly HttpClient _client = new(); private static readonly HttpClient _client = new();
public static ClientViewModel? Client { get; set; } = null; public static ClientViewModel? Client { get; set; } = null;
public static string ErrorMessage = string.Empty; public static string ErrorMessage = string.Empty;
public static void Connect(IConfiguration configuration) public static void Connect(IConfiguration configuration)
{ {
_client.BaseAddress = new Uri(configuration["IPAddress"]); _client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear(); _client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
} }
public static void SetErrorMessage(string error) public static void SetErrorMessage(string error)
{ {
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);
var result = response.Result.Content.ReadAsStringAsync().Result; var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode) if (response.Result.IsSuccessStatusCode)
{ {
return JsonConvert.DeserializeObject<T>(result); return JsonConvert.DeserializeObject<T>(result);
} }
else else
{ {
throw new Exception(result); throw new Exception(result);
} }
} }
// 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);
var data = new StringContent(json, Encoding.UTF8, "application/json"); var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data); var response = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result; var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode) if (!response.Result.IsSuccessStatusCode)
{ {
throw new Exception(result); throw new Exception(result);
} }
} }
// 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);
var data = new StringContent(json, Encoding.UTF8, "application/json"); var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data); var response = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result; var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode) if (response.Result.IsSuccessStatusCode)
{ {
return JsonConvert.DeserializeObject<T>(result); return JsonConvert.DeserializeObject<T>(result);
} }
else else
{ {
throw new Exception(result); throw new Exception(result);
} }
} }
} }
} }

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>

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
using BankClientApp; using BankÑlientApp;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -12,9 +12,9 @@ APIClient.Connect(builder.Configuration);
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment()) if (!app.Environment.IsDevelopment())
{ {
app.UseExceptionHandler("/Home/Error"); app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts(); app.UseHsts();
} }
app.UseHttpsRedirection(); app.UseHttpsRedirection();
@ -25,7 +25,7 @@ app.UseRouting();
app.UseAuthorization(); 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,60 +1,62 @@
@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">
@{ @{
<p> if (Model == null)
<a asp-action="CreateCard">Оформить банковскую карту</a> {
</p> <h3 class="display-4">Сначала авторизируйтесь</h3>
<table class="table"> return;
<thead> }
<tr> <p>
<th> <a asp-action="CreateCard">Создать карту</a>
Номер карты </p>
</th> <table class="table">
<th> <thead>
Фамилия владельца <tr>
</th> <th>
<th> Номер карты
Имя владельца </th>
</th> <th>
<th> Баланс
Баланс </th>
</th> <th>
<th> CVC
Период </th>
</th> <th>
</tr> Срок действия
</thead> </th>
<tbody> </tr>
@foreach (var item in Model) </thead>
{ <tbody>
<tr> @foreach (var item in Model)
<td> {
@Html.DisplayFor(modelItem => item.Number) <tr>
</td> <td>
<td> @Html.DisplayFor(modelItem => item.Number)
@Html.DisplayFor(modelItem => item.ClientSurname) </td>
</td> <td>
<td> @Html.DisplayFor(modelItem => item.Sum)
@Html.DisplayFor(modelItem => item.Balance) </td>
</td> <td>
<td> @Html.DisplayFor(modelItem => item.CVC)
@Html.DisplayFor(modelItem => item.Period) </td>
</td> <td>
</tr> @Html.DisplayFor(modelItem => item.Period)
} </td>
</tr>
</tbody> }
</table> </tbody>
} </table>
</div> }
</div>

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)
{ {
@ -20,4 +20,4 @@
<h3 class="display-4">Здравствуйтe, @APIClient.Client.Name @APIClient.Client.Patronymic</h3> <h3 class="display-4">Здравствуйтe, @APIClient.Client.Name @APIClient.Client.Patronymic</h3>
} }
</div> </div>

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> </form>
<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>

View File

@ -9,30 +9,29 @@
<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>
</form> </form>

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"> <img src="https://img.icons8.com/?size=80&id=CvryVUzkqqMu&format=png" alt="*" class="navbar-toggler" style="display: block; margin: 0 auto; height:">
<a asp-controller="Home" asp-action="Index"> </a>
<img src="https://img.icons8.com/?size=80&id=CvryVUzkqqMu&format=png" alt="*" class="navbar-toggler" style="display: block; margin: 0 auto; height:"> <div class="md-4 mb-2 mb-md-0">
</a> <a asp-controller="Home" asp-action="Enter" class="d-inline-flex link-body-emphasis text-decoration-none">
<a class="navbar-brand ms-4" asp-area="" asp-controller="Home" asp-action="Index">Банк "Вы Банкрот"</a> <span class="fs-4 text-light ">Банк "Вы банкрот"</span>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent" </a>
aria-expanded="false" aria-label="Toggle navigation"> </div>
<span class="navbar-toggler-icon"></span>
</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"> <ul class="nav col-md-auto mb-2 justify-content-center mb-md-0 nav-main">
<a class="nav-link dropdown-toggle" id="operationsDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">Операции</a> <li>
<ul class="dropdown-menu" aria-labelledby="operationsDropdown"> <a class="nav-link px-2 link-light" asparea="" asp-controller="Home" asp-action="CardsList">Банковские карты</a>
<li><a class="dropdown-item" asp-controller="Home" asp-action="Crediting">Пополнение карты</a></li> </li>
<li><a class="dropdown-item" asp-controller="Home" asp-action="Debiting">Снятие с карты</a></li> <li class="dropdown">
<li><a class="dropdown-item" asp-controller="Home" asp-action="MoneyTransfers">Заявки на перевод</a></li> <a href="#" class="nav-link px-2 link-light">Операции</a>
</ul> <ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarDarkDropdownMenuLink">
</li> <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>
<li class="nav-item dropdown"> </ul>
<a class="nav-link dropdown-toggle" id="reportsDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">Отчеты</a> </li>
<ul class="dropdown-menu" aria-labelledby="reportsDropdown"> <li class="dropdown">
<li><a class="dropdown-item" asp-controller="Home" asp-action="ReportBankCard">Отчёт по банковским картам</a></li> <a href="#" class="nav-link px-2 link-light">Отчеты</a>
<li><a class="dropdown-item" asp-controller="Home" asp-action="CreateReport">Отчёт за период</a></li> <ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarDarkDropdownMenuLink">
<li><a class="dropdown-item" asp-controller="Home" asp-action="Diagram">Диаграмма</a></li> <li><a class="dropdown-item" asp-controller="Home" asp-controller="Home" asp-action="ReportWithCards">Отчёт по банковским картам</a></li>
</ul> <li><a class="dropdown-item" asp-controller="Home" asp-controller="Home" asp-action="CreateReport">Отчёт за период</a></li>
</li> <li><a class="dropdown-item" asp-controller="Home" asp-controller="Home" asp-action="Diagram">Диаграмма</a></li>
</ul>
</ul> </li>
</ul>
<ul class="navbar-nav"> @{
<li class="nav-item"> if (APIClient.Client == null)
<a class="nav-link" asp-controller="Home" asp-action="Privacy">Личные данные</a> {
</li> <div class="col-md-3 text-end">
<li class="nav-item"> <a class="btn btn-warning me-2" asp-controller="Home" asp-action="Login">Войти</a>
<a class="btn btn-primary ms-2 me-2" asp-controller="Home" asp-action="Login">Вход</a> <a class="btn btn-warning" asp-controller="Home" asp-action="Register">Регистрация</a>
</li>
<li class="nav-item">
<a class="btn btn-primary ms-2" asp-controller="Home" asp-action="Register">Регистрация</a>
</li>
</ul>
</div> </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>
@ -77,4 +169,4 @@
<script src="~/js/site.js" asp-append-version="true"></script> <script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false) @await RenderSectionAsync("Scripts", required: false)
</body> </body>
</html> </html>

View File

@ -2,47 +2,56 @@
for details on configuring this project to bundle and minify static web assets. */ for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand { a.navbar-brand {
white-space: normal; white-space: normal;
text-align: center; text-align: center;
word-break: break-all; word-break: break-all;
} }
a {
color: #0077cc;
}
.btn-primary { .btn-primary {
color: #fff; color: #fff;
background-color: #1b6ec2; background-color: #1b6ec2;
border-color: #1861ac; border-color: #1861ac;
} }
.nav-pills .nav-link.active, .nav-pills .show > .nav-link { .nav-pills .nav-link.active, .nav-pills .show > .nav-link {
color: #fff; color: #fff;
background-color: #1b6ec2; background-color: #1b6ec2;
border-color: #1861ac; border-color: #1861ac;
} }
.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;
} }
.box-shadow { .box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05); box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
} }
button.accept-policy { button.accept-policy {
font-size: 1rem; font-size: 1rem;
line-height: inherit; line-height: inherit;
} }
.footer { .footer {
position: absolute; position: absolute;
bottom: 0; bottom: 0;
width: 100%; width: 100%;
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,28 +1,21 @@
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; }
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 AccountNumber { get; set; } = string.Empty;
public double Balance { get; set; } public string PasswordAccount { get; set; } = string.Empty;
public DateTime DateOpen { get; set; } = DateTime.Now; public double Balance { get; set; }
public StatusAccount StatusAccount { get; set; } = StatusAccount.Закрыт; public DateTime DateOpen { get; set; } = DateTime.Now;
} }
} }

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 int CashierId { get; set; }
public double Sum { get; set; } public int Sum { get; set; }
public DateTime DateWithdrawal { get; set; } public DateTime DateOperation { get; set; } = DateTime.Now;
} }
} }

View File

@ -1,27 +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 CashierBindingModel : ICashierModel public class CashierBindingModel : ICashierModel
{ {
public int Id { get; set; } public int Id { get; set; }
public string Name { get; set; } = string.Empty; public string Password { get; set; } = string.Empty;
public string Surname { get; set; } = string.Empty; public string Name { get; set; } = string.Empty;
public string Patronymic { get; set; } = string.Empty; public string Surname { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty; public string Patronymic { get; set; } = string.Empty;
public string Password { get; set; } = string.Empty; public string Email { get; set; } = string.Empty;
public string MobilePhone { get; set; } = string.Empty; public string Telephone { 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,27 +1,21 @@
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;
public string Patronymic { get; set; } = string.Empty; public string Patronymic { get; set; } = string.Empty;
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 CardId { get; set; }
public int ClientId { get; set; }
public int CardId { get; set; } public int Sum { get; set; }
public double Sum { get; set; } public DateTime DateOpen { get; set; } = DateTime.Now;
public DateTime DateCredit { get; set; } 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,24 +1,20 @@
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;
public string MailPassword { get; set; } = string.Empty; public string MailPassword { get; set; } = string.Empty;
public string SmtpClientHost { get; set; } = string.Empty; public string SmtpClientHost { get; set; } = string.Empty;
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,26 +1,21 @@
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;
public string Subject { get; set; } = string.Empty; public string Subject { get; set; } = string.Empty;
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; }
public TypeDocEnum TypeDoc { get; set; } public TypeDocEnum TypeDoc { get; set; }
} }
} }

View File

@ -1,32 +1,25 @@
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; }
public string MessageId { get; set; } = string.Empty; public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; } public int? ClientId { get; set; }
public string SenderName { get; set; } = string.Empty; public string SenderName { get; set; } = string.Empty;
public DateTime DateDelivery { get; set; } = DateTime.Now; public DateTime DateDelivery { get; set; } = DateTime.Now;
public string Subject { get; set; } = string.Empty; public string Subject { get; set; } = string.Empty;
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,30 +1,25 @@
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
{ {
public class ReportBindingModel public class ReportBindingModel
{ {
public string FileName { get; set; } = string.Empty; public string FileName { get; set; } = string.Empty;
public int? ClientId { get; set; } public int? ClientId { get; set; }
public int? AccountId { get; set; } public int? AccountId { get; set; }
public List<int>? CardList { get; set; } public List<int>? CardList { get; set; }
public string? ClientFullName { get; set; } = string.Empty; public string? ClientFullName { get; set; } = string.Empty;
public DateTime? DateFrom { get; set; } public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public DateTime? DateTo { get; set; } public MailsEnum Role { get; set; }
public MailsEnum Role { get; set; } public string? Email { get; set; }
}
public string? Email { get; set; }
}
} }

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,27 +1,24 @@
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);
AccountViewModel? ReadElement(AccountSearchModel model); AccountViewModel? ReadElement(AccountSearchModel model);
bool ChangeBalance(AccountSearchModel? model, int sum); bool ChangeBalance(AccountSearchModel? model, int sum);
bool Create(AccountBindingModel model); bool Create(AccountBindingModel model);
bool Update(AccountBindingModel model); bool Update(AccountBindingModel model);
bool Delete(AccountBindingModel model);
public List<CashierDiagramElementsViewModel> GetMonthInfo(int AccountId);
bool Delete(AccountBindingModel model);
} }
} }

View File

@ -1,25 +1,19 @@
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);
CashWithdrawalViewModel? ReadElement(CashWithdrawalSearchModel model); CashWithdrawalViewModel? ReadElement(CashWithdrawalSearchModel model);
bool Create(CashWithdrawalBindingModel model, bool flag); bool Create(CashWithdrawalBindingModel model, bool flag);
bool Update(CashWithdrawalBindingModel model); bool Update(CashWithdrawalBindingModel model);
bool Delete(CashWithdrawalBindingModel model); bool Delete(CashWithdrawalBindingModel model);
} }
} }

View File

@ -1,25 +1,19 @@
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);
CashierViewModel? ReadElement(CashierSearchModel model); CashierViewModel? ReadElement(CashierSearchModel model);
bool Create(CashierBindingModel model); bool Create(CashierBindingModel model);
bool Update(CashierBindingModel model); bool Update(CashierBindingModel model);
bool Delete(CashierBindingModel model); bool Delete(CashierBindingModel model);
} }
} }

View File

@ -1,25 +1,19 @@
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);
MoneyTransferViewModel? ReadElement(MoneyTransferSearchModel model); MoneyTransferViewModel? ReadElement(MoneyTransferSearchModel model);
bool Create(MoneyTransferBindingModel model); bool Create(MoneyTransferBindingModel model);
bool Update(MoneyTransferBindingModel model); bool Update(MoneyTransferBindingModel model);
bool Delete(MoneyTransferBindingModel model); bool Delete(MoneyTransferBindingModel model);
} }
} }

View File

@ -1,16 +1,11 @@
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,16 +1,10 @@
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,16 +1,10 @@
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,16 +1,10 @@
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 int? CashierId { get; set; } public string? AccountNumber { get; set; } = string.Empty;
public int? ClientId { get; set; } public int? CashierId { get; set; }
public string? AccountNumber { get; set; } = string.Empty; public int? ClientId { get; set; }
public double? Balance { get; set; } public string? PasswordAccount { get; set; } = string.Empty;
public DateTime? DateOpen { get; set; } public double? Balance { get; set; }
public StatusAccount? StatusAccount { get; set; } public DateTime? DateOpen { 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? AccountId { get; set; } public int? DebitingId { get; set; }
public int? CashierId { get; set; } public int? AccountId { get; set; }
public int? Sum { get; set; } public int? CashierId { get; set; }
public DateTime? DateWithdrawal { get; set; } public int? ClientId { get; set; }
public int? DebitingId { get; set; } public int? Sum { get; set; }
public int? ClientId { get; set; } public DateTime? DateFrom { get; set; }
}
public DateTime? DateTo { 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? ClientId { get; set; }
public int? CashierId { 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? 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; }
} }
} }

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