Compare commits

..

143 Commits

Author SHA1 Message Date
3891f325fc ФАЙЛЫ СКАЧИВАЮТСЯ ЧЕРЕЗ ИНЕТ!!!!!! 5 МИНУТ АААААААААААААААААААААААААААААААААААААААААААААААААААААААААА 2024-05-28 22:01:25 +04:00
fda82f22ce Ласт коммит 2024-05-27 05:49:12 +04:00
52ce619788 ГГ 2024-05-27 04:17:24 +04:00
7672fd46c6 Pdf работает)))) 2024-05-27 04:16:18 +04:00
ed31093f33 add demonstrating pdf report in view 2024-05-27 03:40:24 +04:00
a4942de30e fix sending pdf report to email 2024-05-27 02:48:42 +04:00
a45f892454 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-27 02:35:04 +04:00
1de0fc1239 add sending pdf report to email 2024-05-27 02:35:01 +04:00
6eda8d6237 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-27 02:03:45 +04:00
8abcc74c43 Фикс 2024-05-27 02:03:42 +04:00
f691fc1512 fix 2024-05-27 02:03:27 +04:00
a44b87601c Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-27 02:01:54 +04:00
b3770d4a65 Фикс 2024-05-27 02:01:45 +04:00
8379870d93 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-27 02:01:35 +04:00
f607e86aab fix 2024-05-27 02:01:32 +04:00
9628e5f442 Фикс 2024-05-27 02:01:31 +04:00
2a9bc25bce Фикс 2024-05-27 01:58:54 +04:00
441b3b8151 fix 2024-05-27 01:58:09 +04:00
7ae39149ce Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-27 01:55:51 +04:00
7cc6f0341c fix 2024-05-27 01:55:45 +04:00
088eaba76b Синхра 2024-05-27 01:51:47 +04:00
3a590e97b7 fix 2024-05-27 01:51:16 +04:00
19aa04168b Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-27 01:38:57 +04:00
758a7143d6 fix 2024-05-27 01:38:55 +04:00
c1bd43b7e1 Слил 2024-05-27 01:38:18 +04:00
685ec452a3 Отчет на почту в процессе 2024-05-27 01:36:49 +04:00
e770ffa984 add mailWorker 2024-05-27 01:36:36 +04:00
9068da1cac start adding pdf report 2024-05-27 01:22:25 +04:00
60688b1147 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-27 00:56:59 +04:00
17c6486d7c Эксель пашет 2024-05-27 00:56:48 +04:00
0c88044384 add excell report 2024-05-27 00:10:56 +04:00
610aae94b1 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 23:49:48 +04:00
12f34ae377 add withdrawal-request logic 2024-05-26 23:49:43 +04:00
68cd7db894 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 23:49:32 +04:00
f7436c0d17 Что то сделал 2024-05-26 23:49:23 +04:00
46a7483dc7 fix footer p.2 2024-05-26 23:34:48 +04:00
216cf24663 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 22:57:04 +04:00
9e3086f33f some minor fixes 2024-05-26 22:56:58 +04:00
0073eb92a4 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 22:56:51 +04:00
d2c8fb0bcd Добавил апдейт статуса 2024-05-26 22:56:41 +04:00
42c493b475 fix footer 2024-05-26 22:43:43 +04:00
a244aa6617 fix withdrawal filtration 2024-05-26 22:38:03 +04:00
34e4891e5f fix word report 2024-05-26 22:37:29 +04:00
1ee37f618c fix filtration of transfers and withdrawals 2024-05-26 22:26:24 +04:00
8c46958f77 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 22:03:28 +04:00
314c2a8a71 some minor fixes 2024-05-26 22:03:20 +04:00
135fde1a80 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 21:59:44 +04:00
583c381d42 Мелкие изменения 2024-05-26 21:59:33 +04:00
b8b4fb24e5 fix Withdrawal.UpdateAccounts 2024-05-26 21:49:18 +04:00
24299f86ce fix word report 2024-05-26 21:21:19 +04:00
70e75c8db3 fix requestListReport view 2024-05-26 21:09:47 +04:00
0ab06cb865 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 20:57:24 +04:00
395654ee04 withdrawal logic in storage p.3 2024-05-26 20:57:20 +04:00
504469416d Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 20:57:00 +04:00
b9eac65ed4 Что то сделал (шучу, много чего) 2024-05-26 20:56:50 +04:00
080aeb4058 fix transfer filtration 2024-05-26 20:48:53 +04:00
85103d6345 private void MakeWithdrawal(BankDatabase context, WithdrawalBindingModel model) 2024-05-26 20:34:43 +04:00
6e9e819b8d Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 19:35:35 +04:00
c95baa32e2 fix withdrawal logic in storage p.1 2024-05-26 19:35:28 +04:00
3906d70eca Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 19:34:05 +04:00
fc176b907a Отчеты начали сохраняться 2024-05-26 19:33:04 +04:00
42c893e105 merge 2024-05-26 18:59:05 +04:00
0d6a189cfc fix TransferStorage 2024-05-26 18:58:39 +04:00
ca859d9bc5 добавил зависимость 2024-05-26 18:18:17 +04:00
bee9621cba Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 18:08:20 +04:00
6454d992ea Поправил IReportLogic 2024-05-26 18:08:09 +04:00
570260e48d fix 2024-05-26 18:04:41 +04:00
fb000dd75c Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 17:55:48 +04:00
f74486a4df Новый контроллер 2024-05-26 17:55:39 +04:00
c77ed0a6e5 [HttpPost] public void RequestsListReport(string format, List<int> accounts) 2024-05-26 17:51:03 +04:00
6a2ff9b373 ГГ 2024-05-26 17:30:15 +04:00
814321996b Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 17:24:43 +04:00
40cb6fef8b В процессе 2024-05-26 17:24:34 +04:00
ba49b79cc6 fix 2024-05-26 17:24:02 +04:00
2f0065e609 fix 2024-05-26 17:14:56 +04:00
9f9a65557d fix 2024-05-26 17:01:24 +04:00
a40975dff5 fix 2024-05-26 16:58:22 +04:00
cb7913100c fix 2024-05-26 16:52:51 +04:00
b4eb8cd606 Фикс 2024-05-26 16:48:57 +04:00
00bb983b8a Абстракция для водра готова 2024-05-26 16:48:11 +04:00
370cbb6699 CreateRequestsDoc(WordInfo info) 2024-05-26 16:48:05 +04:00
3a9eb0de13 Merge 2024-05-26 16:28:49 +04:00
fd1e2ed283 Merge 2024-05-26 16:27:23 +04:00
1cadee7eec fix 2024-05-26 16:26:56 +04:00
682fa772ea fix 2024-05-26 16:24:42 +04:00
ad94885dad Фикс 2024-05-26 16:24:27 +04:00
8ab55a5335 fix 2024-05-26 16:23:56 +04:00
b85d1773bf fix 2024-05-26 16:23:20 +04:00
611652dfd0 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 16:15:39 +04:00
57f1249537 add MakeTransfer method in AccountStorage 2024-05-26 16:15:35 +04:00
af27ce1d36 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 16:08:50 +04:00
b85a9216f9 Фикс 2024-05-26 16:06:57 +04:00
6fffe7f273 fix errors p.2 2024-05-26 15:57:49 +04:00
2538483f76 fix errors 2024-05-26 15:57:16 +04:00
931c363b81 fix errors 2024-05-26 15:56:24 +04:00
f9d725d4b7 ГГ 2024-05-26 15:50:06 +04:00
37dd35b29c Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 15:45:53 +04:00
d08448f7dc Фикс 2024-05-26 15:45:33 +04:00
4dc0725936 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 15:42:36 +04:00
d7a85e2d65 end my part of ReportLogic 2024-05-26 15:42:30 +04:00
7fff7351f4 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 15:32:15 +04:00
296ec5bfde Фикс 2024-05-26 15:32:11 +04:00
0a5f6483e0 fix ReportBindingModel 2024-05-26 15:31:18 +04:00
e0f920010b add ReportBindingModel 2024-05-26 15:26:28 +04:00
899c490626 change report logic; add regions 2024-05-26 15:22:02 +04:00
449fb82fad Мелкие праваки по отчетам 2024-05-26 15:17:06 +04:00
487e595e90 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 14:39:20 +04:00
27f22ee6e4 Чисто фикс 2024-05-26 14:39:14 +04:00
1f9514896b minor refactor 2024-05-26 14:37:46 +04:00
9831008fc4 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 14:35:30 +04:00
db4ddd72ef Чучуть поменял 2024-05-26 14:35:21 +04:00
eda158bcab Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 13:53:30 +04:00
5c0fcb5e39 add getting old value of Withdrawal.Sum for WithdrawalUpdate view 2024-05-26 13:53:26 +04:00
c9922e9522 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 13:49:16 +04:00
37b2d0ef0b Начали отчеты 2024-05-26 13:48:55 +04:00
717d6e9e25 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 13:45:54 +04:00
3bda3fd5de finish Withdrawals (but without some things) 2024-05-26 13:45:50 +04:00
6358f6481b Revert "fix transfer controller p.3"
This reverts commit d7ddf19407.
2024-05-26 12:57:46 +04:00
d7ddf19407 fix transfer controller p.3 2024-05-26 12:54:09 +04:00
de87360d25 Формы добил, остались отчеты 2024-05-26 12:41:35 +04:00
1b12da5d98 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-26 12:10:26 +04:00
3a0491b54d Форма обновления заявок работает 2024-05-26 12:10:15 +04:00
0e74bece33 fix transfer controller p.2 2024-05-26 10:16:35 +04:00
4721aed1c9 fix transfer controller 2024-05-26 00:07:30 +04:00
4b24ac5ae9 fix transfer filtration 2024-05-25 22:53:28 +04:00
5a9ee9e6b6 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-25 22:38:10 +04:00
9ec30179f0 Промежуточный 2024-05-25 22:37:57 +04:00
d853579a48 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-25 22:12:41 +04:00
24637ec066 finish Transfers region 2024-05-25 22:12:22 +04:00
b550f63649 Merge branch 'ManagersApp' of https://git.is.ulstu.ru/Artyom_Yashin/PIbd-23_Yashin_A_Zakharov_R_CourseWork_Bank into ManagersApp 2024-05-25 21:57:18 +04:00
57c5508b9a Осталось обновление заявок и отчеты 2024-05-25 21:57:02 +04:00
879a6536bc Add registration and privacy update for managers 2024-05-25 20:31:18 +04:00
a655f961e7 Формы для операций, кроме связи с переводами, работают 2024-05-24 23:15:36 +04:00
bac9650d98 Работают формы входа, регистрации, редактирования пользователя и круды для карт 2024-05-24 22:15:10 +04:00
6a7b0c75d2 fix BankRestApi.Controllers 2024-05-17 16:53:47 +04:00
235fdade5c fix Accounts 2024-05-17 16:51:11 +04:00
14cbae5dd6 fix navbar p.2 2024-05-17 16:09:49 +04:00
cfaf05ee31 fix ManagerAccounts 2024-05-17 15:42:04 +04:00
1a25fc7b93 fix BankRestApi.Program, add dependency injection 2024-05-17 15:26:15 +04:00
e3c55f7c65 fix BankManagersClientApp.Program, add connection with rest api application 2024-05-17 15:15:45 +04:00
63cce4c4f8 fix BankRestApi.Controllers.ManagerController 2024-05-17 14:58:48 +04:00
29a5b800d0 fix APIClient 2024-05-17 14:55:09 +04:00
62d814e5d0 remove managers registration in managers web app 2024-05-17 14:36:03 +04:00
109 changed files with 4420 additions and 715 deletions

View File

@ -8,6 +8,7 @@
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.0.2" />
<PackageReference Include="MailKit" Version="4.6.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
</ItemGroup>

View File

@ -36,6 +36,18 @@ namespace BankBusinessLogic.BusinessLogic
_logger.LogInformation("ReadList Count: {Count}", list.Count);
return list;
}
public List<int> ReadAccountIdsByWithdrawal(AccountSearchModel model)
{
_logger.LogInformation("ReadAccountIdsByWithdrawal. Number: {Number}, Id: {Id}", model?.Number, model?.Id);
if (model == null)
throw new ArgumentNullException(nameof(model));
var list = _accountStorage.GetAccountIdsByWithdrawal(model);
if (list == null)
return new();
_logger.LogInformation("ReadListByRequestId Count: {Count}", list.Count);
return list;
}
public AccountViewModel? ReadElement(AccountSearchModel model)
{
@ -56,6 +68,8 @@ namespace BankBusinessLogic.BusinessLogic
public bool Create(AccountBindingModel model)
{
CheckModel(model);
model.Money = 0;
model.ReleaseDate = DateTime.Now;
if (_accountStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");

View File

@ -3,6 +3,7 @@ using BankContracts.BusinessLogicsContracts;
using BankContracts.SearchModels;
using BankContracts.StoragesContracts;
using BankContracts.ViewModels;
using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
@ -34,6 +35,18 @@ namespace BankBusinessLogic.BusinessLogic
_logger.LogInformation("ReadList Count: {Count}", list.Count);
return list;
}
public List<int> ReadListByRequestId(CardSearchModel model)
{
_logger.LogInformation("ReadListByRequestId. Number: {Number}, Id: {Id}", model?.Number, model?.Id);
var list = _cardStorage.GetListForRequest(model);
if (list == null)
{
_logger.LogWarning("ReadListByRequestId return null list");
return null;
}
_logger.LogInformation("ReadListByRequestId Count: {Count}", list.Count);
return list;
}
public CardViewModel? ReadElement(CardSearchModel model)
{
_logger.LogInformation("ReadElement Number: {Number}, Id: {Id}", model?.Number, model?.Id);

View File

@ -47,6 +47,19 @@ namespace BankBusinessLogic.BusinessLogic
_logger.LogInformation("ReadElement find. Id: {Id}", element.Id);
return element;
}
public bool LinkOperationTransfer(int operationId, int transferId)
{
if (operationId <= 0 || transferId <= 0)
return false;
if (_operationStorage.LinkOperationTransfer(operationId, transferId))
{
_logger.LogWarning("link operation failed");
return false;
}
return true;
}
public bool Create(OperationBindingModel model)
{
CheckModel(model);

View File

@ -1,4 +1,7 @@
using BankContracts.BusinessLogicsContracts;
using BankBusinessLogic.OfficePackage;
using BankBusinessLogic.OfficePackage.DocumentModels;
using BankContracts.BindingModels;
using BankContracts.BusinessLogicsContracts;
using BankContracts.SearchModels;
using BankContracts.StoragesContracts;
using BankContracts.ViewModels;
@ -13,34 +16,135 @@ namespace BankBusinessLogic.BusinessLogic
{
public class ReportLogic : IReportLogic
{
private readonly ILogger _logger;
private readonly ICardStorage _cardStorage;
private readonly IAccountStorage _accountStorage;
public ReportLogic(ILogger logger, ICardStorage cardStorage, IAccountStorage accountStorage)
private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(
ICardStorage cardStorage,
IAccountStorage accountStorage,
AbstractSaveToExcel saveToExcel,
AbstractSaveToWord saveToWord,
AbstractSaveToPdf saveToPdf)
{
_logger = logger;
_cardStorage = cardStorage;
_accountStorage = accountStorage;
}
public List<ReportOperationsRequestsViewModel> CreateReportOperationsRequests(CardSearchModel model)
{
return _cardStorage.GetReportOperationsRequestsList(model);
}
_saveToExcel = saveToExcel;
_saveToWord = saveToWord;
_saveToPdf = saveToPdf;
}
#region//списки заявок по выбранным счетам в формате word и excel
public List<ReportRequestsViewModel> CreateReportRequests(AccountSearchModel model)
{
return _accountStorage.GetRequestsReport(model);
}
}
public List<ReportTransfersViewModel> CreateReportTransfers(CardSearchModel model)
public void SaveRequestsToWordFile(ReportBindingModel model)
{
_saveToWord.CreateRequestsDoc(new WordInfo
{
FileName = model.FileName,
Title = "Список заявок",
Requests = CreateReportRequests(new AccountSearchModel
{
SelectedAccountIds = model.SelectedAccountIds,
}),
});
}
public void SaveRequestsToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateRequestsDoc(new ExcelInfo
{
FileName = model.FileName,
Title = "Список заявок",
Requests = CreateReportRequests(new AccountSearchModel
{
SelectedAccountIds = model.SelectedAccountIds,
}),
});
}
#endregion
#region//списки переводов по выбранным картам в формате word и excel
public List<ReportTransfersViewModel> CreateReportTransfers(CardSearchModel model)
{
return _cardStorage.GetReportTransfersList(model);
}
public List<ReportTransfersWithdrawalsViewModel> CreateReportTransfersWithdrawals(AccountSearchModel model)
public void SaveTransfersToWordFile(ReportBindingModel model)
{
_saveToWord.CreateTransfersDoc(new WordInfo
{
FileName = model.FileName,
Title = "Список переводов",
Transfers = CreateReportTransfers(new CardSearchModel
{
SelectedCardIds = model.SelectedCardIds
})
});
}
public void SaveTransfersToExcelFile(ReportBindingModel model)
{
_saveToExcel.CreateTransfersDoc(new ExcelInfo
{
FileName = model.FileName,
Title = "Список переводов",
Transfers = CreateReportTransfers(new CardSearchModel
{
SelectedCardIds = model.SelectedCardIds
})
});
}
#endregion
#region//отчеты по картам за период с расшифровкой по заявкам и операциям в формате pdf
public List<ReportOperationsRequestsViewModel> CreateReportOperationsRequests(CardSearchModel model)
{
return _cardStorage.GetReportOperationsRequestsList(model);
}
public void SaveOperationsRequestsToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateOperationsRequestsDoc(new PdfInfo
{
FileName = model.FileName,
Title = "Отчет по картам",
DateFrom = model.DateFrom!.Value,
DateTo = model.DateTo!.Value,
OperationsRequests = CreateReportOperationsRequests(new CardSearchModel
{
DateFrom = model.DateFrom.Value,
DateTo = model.DateTo.Value,
})
});
}
#endregion
#region//отчеты по счетам за период с расшифровкой по переводам и выдачам в формате pdf
public List<ReportTransfersWithdrawalsViewModel> CreateReportTransfersWithdrawals(AccountSearchModel model)
{
return _accountStorage.GetTransfersWithdrawalsReport(model);
}
}
}
public void SaveTransfersWithdrawalsToPdfFile(ReportBindingModel model)
{
_saveToPdf.CreateCreateTransfersDocDoc(new PdfInfo
{
FileName = model.FileName,
Title = "Отчёт по счетам",
DateFrom = model.DateFrom!.Value,
DateTo = model.DateTo!.Value,
TransfersWithdrawals = CreateReportTransfersWithdrawals(new AccountSearchModel
{
DateFrom = model.DateFrom.Value,
DateTo = model.DateTo.Value,
})
});
}
#endregion
}
}

View File

@ -23,10 +23,10 @@ namespace BankBusinessLogic.BusinessLogic
_requestStorage = requestStorage;
}
public List<RequestViewModel>? ReadList(RequestSearchModel? model)
public List<RequestViewModel>? ReadList(RequestSearchModel? model, int? clientId)
{
_logger.LogInformation("ReadList. Id: {Id}", model?.Id);
var list = model == null ? _requestStorage.GetFullList() : _requestStorage.GetFilteredList(model);
var list = model == null ? _requestStorage.GetFullList(clientId) : _requestStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
@ -81,15 +81,7 @@ namespace BankBusinessLogic.BusinessLogic
}
return true;
}
public bool DeclineRequest(RequestBindingModel model)
{
return ChangeStatus(model, RequestStatus.Выполнена);
}
public bool SatisfyRequest(RequestBindingModel model)
{
return ChangeStatus(model, RequestStatus.Отклонена);
}
private void CheckModel(RequestBindingModel model, bool withParams = true)
{
if (model == null)
@ -101,12 +93,5 @@ namespace BankBusinessLogic.BusinessLogic
_logger.LogInformation("Request. Sum:{Sum}. Id: { Id} ", model.Sum, model.Id);
}
private bool ChangeStatus(RequestBindingModel model, RequestStatus status)
{
//todo поменять
model.Status = status;
_requestStorage.Update(model);
return true;
}
}
}

View File

@ -72,9 +72,21 @@ namespace BankBusinessLogic.BusinessLogic
return false;
}
return true;
}
}
public bool Delete(WithdrawalBindingModel model)
public bool LinkToRequest(int withdrawalId, int requestId)
{
if (withdrawalId <= 0 || requestId <= 0)
return false;
if (_withdrawalStorage.LinkToRequest(withdrawalId, requestId) == null)
{
_logger.LogWarning("link operation failed");
return false;
}
return true;
}
public bool Delete(WithdrawalBindingModel model)
{
CheckModel(model, false);
if (_withdrawalStorage.Delete(model) == null)

View File

@ -0,0 +1,51 @@
using BankContracts.BindingModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.MailWorker
{
public abstract class AbstractMailWorker
{
protected string _mailLogin = string.Empty;
protected string _mailPassword = string.Empty;
protected string _smtpClientHost = string.Empty;
protected int _smtpClientPort;
protected string _popHost = string.Empty;
protected int _popPort;
private readonly ILogger _logger;
public AbstractMailWorker(ILogger<AbstractMailWorker> logger)
{
_logger = logger;
}
public void MailConfig(MailConfigBindingModel config)
{
_mailLogin = config.MailLogin;
_mailPassword = config.MailPassword;
_smtpClientHost = config.SmtpClientHost;
_smtpClientPort = config.SmtpClientPort;
_popHost = config.PopHost;
_popPort = config.PopPort;
_logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort);
}
public async void MailSendAsync(MailSendInfoBindingModel info)
{
if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
return;
if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0)
return;
if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text))
return;
_logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject);
await SendMailAsync(info);
}
protected abstract Task SendMailAsync(MailSendInfoBindingModel info);
}
}

View File

@ -0,0 +1,45 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using BankContracts.BindingModels;
namespace BankBusinessLogic.MailWorker
{
public class MailKitWorker : AbstractMailWorker
{
public MailKitWorker(ILogger<MailKitWorker> logger)
: base(logger) { }
protected override async Task SendMailAsync(MailSendInfoBindingModel info)
{
using var objMailMessage = new MailMessage();
using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort);
try
{
objMailMessage.From = new MailAddress(_mailLogin);
objMailMessage.To.Add(new MailAddress(info.MailAddress));
objMailMessage.Subject = info.Subject;
objMailMessage.Body = info.Text;
objMailMessage.SubjectEncoding = Encoding.UTF8;
objMailMessage.BodyEncoding = Encoding.UTF8;
Attachment attachment = new Attachment("C:\\forpdf\\pdffile.pdf", new ContentType(MediaTypeNames.Application.Pdf));
objMailMessage.Attachments.Add(attachment);
objSmtpClient.UseDefaultCredentials = false;
objSmtpClient.EnableSsl = true;
objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword);
await Task.Run(() => objSmtpClient.Send(objMailMessage));
}
catch
{
throw;
}
}
}
}

View File

@ -0,0 +1,243 @@
using BankBusinessLogic.OfficePackage.DocumentModels;
using BankBusinessLogic.OfficePackage.HelperEnums;
using BankBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToExcel
{
public void CreateRequestsDoc(ExcelInfo info)
{
CreateExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "E1"
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 2,
Text = "Номер счёта",
StyleInfo = ExcelStyleInfoType.Title
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = 2,
Text = "Номер заявки",
StyleInfo = ExcelStyleInfoType.Title
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = 2,
Text = "Статус заявки",
StyleInfo = ExcelStyleInfoType.Title
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "D",
RowIndex = 2,
Text = "Сумма заявки",
StyleInfo = ExcelStyleInfoType.Title
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "E",
RowIndex = 2,
Text = "Дата заявки",
StyleInfo = ExcelStyleInfoType.Title
});
uint rowIndex = 3;
foreach (var report in info.Requests)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = report.AccountNumber,
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
foreach (var request in report.Requests)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = request.Id.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBroder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = request.Status.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBroder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "D",
RowIndex = rowIndex,
Text = request.Sum.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBroder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "E",
RowIndex = rowIndex,
Text = request.RequestTime.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBroder
});
rowIndex++;
}
}
SaveExcel(info);
}
public void CreateTransfersDoc(ExcelInfo info)
{
CreateExcel(info);
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 1,
Text = info.Title,
StyleInfo = ExcelStyleInfoType.Title
});
MergeCells(new ExcelMergeParameters
{
CellFromName = "A1",
CellToName = "F1"
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = 2,
Text = "Номер карты",
StyleInfo = ExcelStyleInfoType.Title
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = 2,
Text = "Номер перевода",
StyleInfo = ExcelStyleInfoType.Title
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = 2,
Text = "Сумма",
StyleInfo = ExcelStyleInfoType.Title
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "D",
RowIndex = 2,
Text = "Время перевода",
StyleInfo = ExcelStyleInfoType.Title
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "E",
RowIndex = 2,
Text = "Счет отправителя",
StyleInfo = ExcelStyleInfoType.Title
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "F",
RowIndex = 2,
Text = "Счет получателя",
StyleInfo = ExcelStyleInfoType.Title
});
uint rowIndex = 3;
foreach (var report in info.Transfers)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "A",
RowIndex = rowIndex,
Text = report.CardNumber,
StyleInfo = ExcelStyleInfoType.Text
});
rowIndex++;
foreach (var transfer in report.Transfers)
{
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "B",
RowIndex = rowIndex,
Text = transfer.Id.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBroder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "C",
RowIndex = rowIndex,
Text = transfer.Sum.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBroder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "D",
RowIndex = rowIndex,
Text = transfer.TransferTime.ToString(),
StyleInfo = ExcelStyleInfoType.TextWithBroder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "E",
RowIndex = rowIndex,
Text = transfer.SenderAccountNumber,
StyleInfo = ExcelStyleInfoType.TextWithBroder
});
InsertCellInWorksheet(new ExcelCellParameters
{
ColumnName = "F",
RowIndex = rowIndex,
Text = transfer.RecipientAccountNumber,
StyleInfo = ExcelStyleInfoType.TextWithBroder
});
rowIndex++;
}
}
SaveExcel(info);
}
/// <summary>
/// Создание excel-файла
/// </summary>
/// <param name="info"></param>
protected abstract void CreateExcel(ExcelInfo info);
/// <summary>
/// Добавляем новую ячейку в лист
/// </summary>
/// <param name="cellParameters"></param>
protected abstract void InsertCellInWorksheet(ExcelCellParameters
excelParams);
/// <summary>
/// Объединение ячеек
/// </summary>
/// <param name="mergeParameters"></param>
protected abstract void MergeCells(ExcelMergeParameters excelParams);
/// <summary>
/// Сохранение файла
/// </summary>
/// <param name="info"></param>
protected abstract void SaveExcel(ExcelInfo info);
}
}

View File

@ -0,0 +1,388 @@
using BankBusinessLogic.OfficePackage.DocumentModels;
using BankBusinessLogic.OfficePackage.HelperEnums;
using BankBusinessLogic.OfficePackage.HelperModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToPdf
{
public void CreateCreateTransfersDocDoc(PdfInfo info)
{
CreatePdf(info);
//title
CreateParagraph(new PdfParagraph
{
Text = info.Title,
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateParagraph(new PdfParagraph
{
Text = $"с{ info.DateFrom.ToShortDateString() } по { info.DateTo.ToShortDateString() }", Style = "Normal", ParagraphAlignment = PdfParagraphAlignmentType.Center
});
//sender transfers
CreateParagraph(new PdfParagraph
{
Text = "Переводы на другие счета",
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
CreateTable(new List<string> { "2cm", "3cm", "6cm", "3cm", "3cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Номер счёта", "Номер перевода", "Время перевода", "Сумма", "Номер счёта получателя" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var report in info.TransfersWithdrawals)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string>
{
report.AccountNumber.ToString(),
"",
"",
"",
"",
},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
foreach(var senderTransfer in report.SenderTransfers)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string>
{
"",
senderTransfer.Id.ToString(),
senderTransfer.TransferTime.ToString(),
senderTransfer.Sum.ToString(),
senderTransfer.RecipientAccountNumber.ToString(),
},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
}
CreateParagraph(new PdfParagraph
{
Text = "",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Right
});
//recipient transfers
CreateParagraph(new PdfParagraph
{
Text = "Переводы с других счетов",
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
CreateTable(new List<string> { "2cm", "3cm", "6cm", "3cm", "3cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Номер счёта", "Номер перевода", "Время перевода", "Сумма", "Номер счёта отправителя" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var report in info.TransfersWithdrawals)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string>
{
report.AccountNumber.ToString(),
"",
"",
"",
"",
},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
foreach (var recipientTransfer in report.RecipientTransfers)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string>
{
"",
recipientTransfer.Id.ToString(),
recipientTransfer.TransferTime.ToString(),
recipientTransfer.Sum.ToString(),
recipientTransfer.SenderAccountNumber,
},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
}
CreateParagraph(new PdfParagraph
{
Text = "",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Right
});
//withdrawals
CreateParagraph(new PdfParagraph
{
Text = "Выдачи наличных",
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
CreateTable(new List<string> { "2cm", "3cm", "6cm", "3cm", "3cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Номер счёта", "Номер выдачи", "Время выдачи", "Сумма" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var report in info.TransfersWithdrawals)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string>
{
report.AccountNumber.ToString(),
"",
"",
"",
},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
foreach (var withdrawal in report.Withdrawals)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string>
{
"",
withdrawal.Id.ToString(),
withdrawal.WithdrawalTime.ToString(),
withdrawal.Sum.ToString(),
},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
}
CreateParagraph(new PdfParagraph
{
Text = "",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Right
});
//
SavePdf(info);
}
public void CreateOperationsRequestsDoc(PdfInfo info)
{
CreatePdf(info);
//title
CreateParagraph(new PdfParagraph
{
Text = info.Title,
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateParagraph(new PdfParagraph
{
Text = $"с{info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
//sender operations
CreateParagraph(new PdfParagraph
{
Text = "Операции на другие карты",
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
CreateTable(new List<string> { "2cm", "3cm", "6cm", "3cm", "3cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Номер карты", "Номер перевода", "Время перевода", "Сумма", "Карта получателя" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var report in info.OperationsRequests)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> {
report.CardNumber.ToString(),
"",
"",
"",
"",
},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
foreach (var senderOperation in report.SenderOperations)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string>
{
"",
senderOperation.Id.ToString(),
senderOperation.OperationTime.ToString(),
senderOperation.Sum.ToString(),
senderOperation.RecipientCardNumber,
},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
}
CreateParagraph(new PdfParagraph
{
Text = "",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Right
});
//recipient operations
CreateParagraph(new PdfParagraph
{
Text = "Операции на другие карты",
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
CreateTable(new List<string> { "2cm", "3cm", "6cm", "3cm", "3cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Номер карты", "Номер перевода", "Время перевода", "Сумма", "Карта отправителя" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var report in info.OperationsRequests)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> {
report.CardNumber.ToString(),
"",
"",
"",
"",
},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
foreach (var recipientOperation in report.RecipientOperations)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string>
{
"",
recipientOperation.Id.ToString(),
recipientOperation.OperationTime.ToString(),
recipientOperation.Sum.ToString(),
recipientOperation.SenderCardNumber,
},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
}
CreateParagraph(new PdfParagraph
{
Text = "",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Right
});
//requests
CreateParagraph(new PdfParagraph
{
Text = "Заявки",
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
CreateTable(new List<string> { "2cm", "3cm", "6cm", "3cm", "3cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Номер карты", "Номер заявки", "Время создания", "Сумма", "Статус" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var report in info.OperationsRequests)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> {
report.CardNumber.ToString(),
"",
"",
"",
"",
},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
foreach (var request in report.Requests)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string>
{
"",
request.Id.ToString(),
request.RequestTime.ToString(),
request.Sum.ToString(),
request.Status.ToString(),
},
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
}
CreateParagraph(new PdfParagraph
{
Text = "",
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Right
});
SavePdf(info);
}
/// <summary>
/// Создание doc-файла
/// </summary>
/// <param name="info"></param>
protected abstract void CreatePdf(PdfInfo info);
/// <summary>
/// Создание параграфа с текстом
/// </summary>
/// <param name="title"></param>
/// <param name="style"></param>
protected abstract void CreateParagraph(PdfParagraph paragraph);
/// <summary>
/// Создание таблицы
/// </summary>
/// <param name="title"></param>
/// <param name="style"></param>
protected abstract void CreateTable(List<string> columns);
/// <summary>
/// Создание и заполнение строки
/// </summary>
/// <param name="rowParameters"></param>
protected abstract void CreateRow(PdfRowParameters rowParameters);
/// <summary>
/// Сохранение файла
/// </summary>
/// <param name="info"></param>
protected abstract void SavePdf(PdfInfo info);
}
}

View File

@ -0,0 +1,128 @@
using BankBusinessLogic.OfficePackage.DocumentModels;
using BankBusinessLogic.OfficePackage.HelperEnums;
using BankBusinessLogic.OfficePackage.HelperModels;
using BankContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToWord
{
public void CreateRequestsDoc(WordInfo info)
{
CreateWord(info);
List<List<string>> table = new List<List<string>>();
List<ReportRequestsViewModel> reports = info.Requests;
foreach (ReportRequestsViewModel report in reports)
{
List<string> header = new List<string>
{
report.AccountNumber,
"",
"",
"",
"",
};
table.Add(header);
foreach (RequestViewModel request in report.Requests)
{
List<string> row = new List<string>
{
"",
request.Id.ToString(),
request.Status.ToString(),
request.Sum.ToString(),
request.RequestTime.ToString(),
};
table.Add(row);
}
}
var wordTable = new WordTable
{
Headers = new List<string> {
"Номер счёта",
"Номер заявки",
"Статус заявки",
"Сумма заявки",
"Дата заявки"},
Columns = 5,
RowText = table
};
CreateTable(wordTable);
SaveWord(info);
}
public void CreateTransfersDoc(WordInfo info)
{
CreateWord(info);
List<List<string>> table = new List<List<string>>();
List<ReportTransfersViewModel> reports = info.Transfers;
foreach (ReportTransfersViewModel report in reports)
{
List<string> header = new List<string>
{
report.CardNumber,
"",
"",
"",
"",
"",
};
table.Add(header);
foreach(TransferViewModel transfer in report.Transfers)
{
List<string> row = new List<string>
{
"",
transfer.Id.ToString(),
transfer.Sum.ToString(),
transfer.TransferTime.ToString(),
transfer.SenderAccountNumber,
transfer.RecipientAccountNumber,
};
table.Add(row);
}
}
var wordTable = new WordTable
{
Headers = new List<string> {
"Номер карты",
"Номер перевода",
"Сумма",
"Время перевода",
"Счет отправителя",
"Счет получателя",
},
Columns = 6,
RowText = table
};
CreateTable(wordTable);
SaveWord(info);
}
/// <summary>
/// Создание doc-файла
/// </summary>
/// <param name="info"></param>
protected abstract void CreateWord(WordInfo info);
/// <summary>
/// Создание абзаца с текстом
/// </summary>
/// <param name="paragraph"></param>
/// <returns></returns>
protected abstract void CreateParagraph(WordParagraph paragraph);
/// <summary>
/// Сохранение файла
/// </summary>
/// <param name="info"></param>
protected abstract void SaveWord(WordInfo info);
/// <summary>
/// Создание doc-файла с таблицей
/// </summary>
/// <param name="info"></param>
protected abstract void CreateTable(WordTable table);
}
}

View File

@ -0,0 +1,17 @@
using BankContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.DocumentModels
{
public class ExcelInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportTransfersViewModel> Transfers { get; set; } = new();
public List<ReportRequestsViewModel> Requests { get; set; } = new();
}
}

View File

@ -0,0 +1,19 @@
using BankContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.DocumentModels
{
public class PdfInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<ReportOperationsRequestsViewModel> OperationsRequests { get; set; } = new();
public List<ReportTransfersWithdrawalsViewModel> TransfersWithdrawals { get; set; } = new();
}
}

View File

@ -0,0 +1,17 @@
using BankContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.DocumentModels
{
public class WordInfo
{
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<ReportTransfersViewModel> Transfers { get; set; } = new();
public List<ReportRequestsViewModel> Requests { get; set; } = new();
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperEnums
{
public enum ExcelStyleInfoType
{
Title,
Text,
TextWithBroder
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperEnums
{
public enum PdfParagraphAlignmentType
{
Center,
Left,
Right
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperEnums
{
public enum WordJustificationType
{
Center,
Both
}
}

View File

@ -0,0 +1,18 @@
using BankBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperModels
{
public class ExcelCellParameters
{
public string ColumnName { get; set; } = string.Empty;
public uint RowIndex { get; set; }
public string Text { get; set; } = string.Empty;
public string CellReference => $"{ColumnName}{RowIndex}";
public ExcelStyleInfoType StyleInfo { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperModels
{
public class ExcelMergeParameters
{
public string CellFromName { get; set; } = string.Empty;
public string CellToName { get; set; } = string.Empty;
public string Merge => $"{CellFromName}:{CellToName}";
}
}

View File

@ -0,0 +1,16 @@
using BankBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperModels
{
public class PdfParagraph
{
public string Text { get; set; } = string.Empty;
public string Style { get; set; } = string.Empty;
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using BankBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperModels
{
public class PdfRowParameters
{
public List<string> Texts { get; set; } = new();
public string Style { get; set; } = string.Empty;
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperModels
{
public class WordParagraph
{
public List<(string, WordTextProperties)> Texts { get; set; } = new();
public WordTextProperties? TextProperties { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperModels
{
public class WordTable
{
public List<string> Headers { get; set; } = new();
public List<List<string>> RowText { get; set; } = new();
public int Columns { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using BankBusinessLogic.OfficePackage.HelperEnums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.HelperModels
{
public class WordTextProperties
{
public string Size { get; set; } = string.Empty;
public bool Bold { get; set; }
public WordJustificationType JustificationType { get; set; }
}
}

View File

@ -0,0 +1,357 @@
using BankBusinessLogic.OfficePackage.HelperEnums;
using BankBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml.Office2010.Excel;
using DocumentFormat.OpenXml.Office2013.Excel;
using DocumentFormat.OpenXml.Office2016.Excel;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BankBusinessLogic.OfficePackage.DocumentModels;
namespace BankBusinessLogic.OfficePackage.Implements
{
public class SaveToExcel : AbstractSaveToExcel
{
private SpreadsheetDocument? _spreadsheetDocument;
private SharedStringTablePart? _shareStringPart;
private Worksheet? _worksheet;
/// <summary>
/// Настройка стилей для файла
/// </summary>
/// <param name="workbookpart"></param>
private static void CreateStyles(WorkbookPart workbookpart)
{
var sp = workbookpart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet();
var fonts = new Fonts() { Count = 2U, KnownFonts = true };
var fontUsual = new Font();
fontUsual.Append(new FontSize() { Val = 12D });
fontUsual.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Theme = 1U });
fontUsual.Append(new FontName() { Val = "Times New Roman" });
fontUsual.Append(new FontFamilyNumbering() { Val = 2 });
fontUsual.Append(new FontScheme() { Val = FontSchemeValues.Minor });
var fontTitle = new Font();
fontTitle.Append(new Bold());
fontTitle.Append(new FontSize() { Val = 14D });
fontTitle.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Theme = 1U });
fontTitle.Append(new FontName() { Val = "Times New Roman" });
fontTitle.Append(new FontFamilyNumbering() { Val = 2 });
fontTitle.Append(new FontScheme() { Val = FontSchemeValues.Minor });
fonts.Append(fontUsual);
fonts.Append(fontTitle);
var fills = new Fills() { Count = 2U };
var fill1 = new Fill();
fill1.Append(new PatternFill() { PatternType = PatternValues.None });
var fill2 = new Fill();
fill2.Append(new PatternFill()
{
PatternType = PatternValues.Gray125
});
fills.Append(fill1);
fills.Append(fill2);
var borders = new Borders() { Count = 2U };
var borderNoBorder = new Border();
borderNoBorder.Append(new LeftBorder());
borderNoBorder.Append(new RightBorder());
borderNoBorder.Append(new TopBorder());
borderNoBorder.Append(new BottomBorder());
borderNoBorder.Append(new DiagonalBorder());
var borderThin = new Border();
var leftBorder = new LeftBorder() { Style = BorderStyleValues.Thin };
leftBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Indexed = 64U });
var rightBorder = new RightBorder()
{
Style = BorderStyleValues.Thin
};
rightBorder.Append(new
DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Indexed = 64U });
var topBorder = new TopBorder() { Style = BorderStyleValues.Thin };
topBorder.Append(new DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Indexed = 64U });
var bottomBorder = new BottomBorder()
{
Style =
BorderStyleValues.Thin
};
bottomBorder.Append(new
DocumentFormat.OpenXml.Office2010.Excel.Color()
{ Indexed = 64U });
borderThin.Append(leftBorder);
borderThin.Append(rightBorder);
borderThin.Append(topBorder);
borderThin.Append(bottomBorder);
borderThin.Append(new DiagonalBorder());
borders.Append(borderNoBorder);
borders.Append(borderThin);
var cellStyleFormats = new CellStyleFormats() { Count = 1U };
var cellFormatStyle = new CellFormat()
{
NumberFormatId = 0U,
FontId
= 0U,
FillId = 0U,
BorderId = 0U
};
cellStyleFormats.Append(cellFormatStyle);
var cellFormats = new CellFormats() { Count = 3U };
var cellFormatFont = new CellFormat()
{
NumberFormatId = 0U,
FontId =
0U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
ApplyFont = true
};
var cellFormatFontAndBorder = new CellFormat()
{
NumberFormatId = 0U,
FontId = 0U,
FillId = 0U,
BorderId = 1U,
FormatId = 0U,
ApplyFont = true,
ApplyBorder = true
};
var cellFormatTitle = new CellFormat()
{
NumberFormatId = 0U,
FontId
= 1U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
Alignment = new Alignment()
{
Vertical = VerticalAlignmentValues.Center,
WrapText = true,
Horizontal =
HorizontalAlignmentValues.Center
},
ApplyFont = true
};
cellFormats.Append(cellFormatFont);
cellFormats.Append(cellFormatFontAndBorder);
cellFormats.Append(cellFormatTitle);
var cellStyles = new CellStyles() { Count = 1U };
cellStyles.Append(new CellStyle()
{
Name = "Normal",
FormatId = 0U,
BuiltinId = 0U
});
var differentialFormats = new
DocumentFormat.OpenXml.Office2013.Excel.DifferentialFormats()
{ Count = 0U };
var tableStyles = new TableStyles()
{
Count = 0U,
DefaultTableStyle =
"TableStyleMedium2",
DefaultPivotStyle = "PivotStyleLight16"
};
var stylesheetExtensionList = new StylesheetExtensionList();
var stylesheetExtension1 = new StylesheetExtension()
{
Uri =
"{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}"
};
stylesheetExtension1.AddNamespaceDeclaration("x14",
"http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
stylesheetExtension1.Append(new SlicerStyles()
{
DefaultSlicerStyle =
"SlicerStyleLight1"
});
var stylesheetExtension2 = new StylesheetExtension()
{
Uri =
"{9260A510-F301-46a8-8635-F512D64BE5F5}"
};
stylesheetExtension2.AddNamespaceDeclaration("x15",
"http://schemas.microsoft.com/office/spreadsheetml/2010/11/main");
stylesheetExtension2.Append(new TimelineStyles()
{
DefaultTimelineStyle = "TimeSlicerStyleLight1"
});
stylesheetExtensionList.Append(stylesheetExtension1);
stylesheetExtensionList.Append(stylesheetExtension2);
sp.Stylesheet.Append(fonts);
sp.Stylesheet.Append(fills);
sp.Stylesheet.Append(borders);
sp.Stylesheet.Append(cellStyleFormats);
sp.Stylesheet.Append(cellFormats);
sp.Stylesheet.Append(cellStyles);
sp.Stylesheet.Append(differentialFormats);
sp.Stylesheet.Append(tableStyles);
sp.Stylesheet.Append(stylesheetExtensionList);
}
/// <summary>
/// Получение номера стиля из типа
/// </summary>
/// <param name="styleInfo"></param>
/// <returns></returns>
private static uint GetStyleValue(ExcelStyleInfoType styleInfo)
{
return styleInfo switch
{
ExcelStyleInfoType.Title => 2U,
ExcelStyleInfoType.TextWithBroder => 1U,
ExcelStyleInfoType.Text => 0U,
_ => 0U,
};
}
protected override void CreateExcel(ExcelInfo info)
{
_spreadsheetDocument = SpreadsheetDocument.Create(info.FileName,
SpreadsheetDocumentType.Workbook);
// Создаем книгу (в ней хранятся листы)
var workbookpart = _spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
CreateStyles(workbookpart);
// Получаем/создаем хранилище текстов для книги
_shareStringPart =
_spreadsheetDocument.WorkbookPart!.GetPartsOfType<SharedStringTablePart>().Any()
?
_spreadsheetDocument.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First()
:
_spreadsheetDocument.WorkbookPart.AddNewPart<SharedStringTablePart>();
// Создаем SharedStringTable, если его нет
if (_shareStringPart.SharedStringTable == null)
{
_shareStringPart.SharedStringTable = new SharedStringTable();
}
// Создаем лист в книгу
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Добавляем лист в книгу
var sheets =
_spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id =
_spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист"
};
sheets.Append(sheet);
_worksheet = worksheetPart.Worksheet;
}
protected override void InsertCellInWorksheet(ExcelCellParameters
excelParams)
{
if (_worksheet == null || _shareStringPart == null)
{
return;
}
var sheetData = _worksheet.GetFirstChild<SheetData>();
if (sheetData == null)
{
return;
}
// Ищем строку, либо добавляем ее
Row row;
if (sheetData.Elements<Row>().Where(r => r.RowIndex! ==
excelParams.RowIndex).Any())
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex! ==
excelParams.RowIndex).First();
}
else
{
row = new Row() { RowIndex = excelParams.RowIndex };
sheetData.Append(row);
}
// Ищем нужную ячейку
Cell cell;
if (row.Elements<Cell>().Where(c => c.CellReference!.Value ==
excelParams.CellReference).Any())
{
cell = row.Elements<Cell>().Where(c => c.CellReference!.Value ==
excelParams.CellReference).First();
}
else
{
// Все ячейки должны быть последовательно друг за другом расположены
// нужно определить, после какой вставлять
Cell? refCell = null;
foreach (Cell rowCell in row.Elements<Cell>())
{
if (string.Compare(rowCell.CellReference!.Value,
excelParams.CellReference, true) > 0)
{
refCell = rowCell;
break;
}
}
var newCell = new Cell()
{
CellReference =
excelParams.CellReference
};
row.InsertBefore(newCell, refCell);
cell = newCell;
}
// вставляем новый текст
_shareStringPart.SharedStringTable.AppendChild(new
SharedStringItem(new Text(excelParams.Text)));
_shareStringPart.SharedStringTable.Save();
cell.CellValue = new
CellValue((_shareStringPart.SharedStringTable.Elements<SharedStringItem>().Count(
) - 1).ToString());
cell.DataType = new EnumValue<CellValues>(CellValues.SharedString);
cell.StyleIndex = GetStyleValue(excelParams.StyleInfo);
}
protected override void MergeCells(ExcelMergeParameters excelParams)
{
if (_worksheet == null)
{
return;
}
MergeCells mergeCells;
if (_worksheet.Elements<MergeCells>().Any())
{
mergeCells = _worksheet.Elements<MergeCells>().First();
}
else
{
mergeCells = new MergeCells();
if (_worksheet.Elements<CustomSheetView>().Any())
{
_worksheet.InsertAfter(mergeCells,
_worksheet.Elements<CustomSheetView>().First());
}
else
{
_worksheet.InsertAfter(mergeCells,
_worksheet.Elements<SheetData>().First());
}
}
var mergeCell = new MergeCell()
{
Reference = new StringValue(excelParams.Merge)
};
mergeCells.Append(mergeCell);
}
protected override void SaveExcel(ExcelInfo info)
{
if (_spreadsheetDocument == null)
{
return;
}
_spreadsheetDocument.WorkbookPart!.Workbook.Save();
_spreadsheetDocument.Dispose();
}
}
}

View File

@ -0,0 +1,107 @@
using BankBusinessLogic.OfficePackage.DocumentModels;
using BankBusinessLogic.OfficePackage.HelperEnums;
using BankBusinessLogic.OfficePackage.HelperModels;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.Implements
{
public class SaveToPdf : AbstractSaveToPdf
{
private Document? _document;
private Section? _section;
private Table? _table;
private static ParagraphAlignment
GetParagraphAlignment(PdfParagraphAlignmentType type)
{
return type switch
{
PdfParagraphAlignmentType.Center => ParagraphAlignment.Center,
PdfParagraphAlignmentType.Left => ParagraphAlignment.Left,
PdfParagraphAlignmentType.Right => ParagraphAlignment.Right,
_ => ParagraphAlignment.Justify,
};
}
/// <summary>
/// Создание стилей для документа
/// </summary>
/// <param name="document"></param>
private static void DefineStyles(Document document)
{
var style = document.Styles["Normal"];
style.Font.Name = "Times New Roman";
style.Font.Size = 14;
style = document.Styles.AddStyle("NormalTitle", "Normal");
style.Font.Bold = true;
}
protected override void CreatePdf(PdfInfo info)
{
_document = new Document();
DefineStyles(_document);
_section = _document.AddSection();
}
protected override void CreateParagraph(PdfParagraph pdfParagraph)
{
if (_section == null)
{
return;
}
var paragraph = _section.AddParagraph(pdfParagraph.Text);
paragraph.Format.SpaceAfter = "1cm";
paragraph.Format.Alignment =
GetParagraphAlignment(pdfParagraph.ParagraphAlignment);
paragraph.Style = pdfParagraph.Style;
}
protected override void CreateTable(List<string> columns)
{
if (_document == null)
{
return;
}
_table = _document.LastSection.AddTable();
foreach (var elem in columns)
{
_table.AddColumn(elem);
}
}
protected override void CreateRow(PdfRowParameters rowParameters)
{
if (_table == null)
{
return;
}
var row = _table.AddRow();
for (int i = 0; i < rowParameters.Texts.Count; ++i)
{
row.Cells[i].AddParagraph(rowParameters.Texts[i]);
if (!string.IsNullOrEmpty(rowParameters.Style))
{
row.Cells[i].Style = rowParameters.Style;
}
Unit borderWidth = 0.5;
row.Cells[i].Borders.Left.Width = borderWidth;
row.Cells[i].Borders.Right.Width = borderWidth;
row.Cells[i].Borders.Top.Width = borderWidth;
row.Cells[i].Borders.Bottom.Width = borderWidth;
row.Cells[i].Format.Alignment =
GetParagraphAlignment(rowParameters.ParagraphAlignment);
row.Cells[i].VerticalAlignment = VerticalAlignment.Center;
}
}
protected override void SavePdf(PdfInfo info)
{
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName);
}
}
}

View File

@ -0,0 +1,215 @@
using BankBusinessLogic.OfficePackage.DocumentModels;
using BankBusinessLogic.OfficePackage.HelperEnums;
using BankBusinessLogic.OfficePackage.HelperModels;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankBusinessLogic.OfficePackage.Implements
{
public class SaveToWord : AbstractSaveToWord
{
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
/// <summary>
/// Получение типа выравнивания
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private static JustificationValues GetJustificationValues(WordJustificationType type)
{
return type switch
{
WordJustificationType.Both => JustificationValues.Both,
WordJustificationType.Center => JustificationValues.Center,
_ => JustificationValues.Left,
};
}
/// <summary>
/// Настройки страницы
/// </summary>
/// <returns></returns>
private static SectionProperties CreateSectionProperties()
{
var properties = new SectionProperties();
var pageSize = new PageSize
{
Orient = PageOrientationValues.Portrait
};
properties.AppendChild(pageSize);
return properties;
}
/// <summary>
/// Задание форматирования для абзаца
/// </summary>
/// <param name="paragraphProperties"></param>
/// <returns></returns>
private static ParagraphProperties? CreateParagraphProperties(WordTextProperties? paragraphProperties)
{
if (paragraphProperties == null)
{
return null;
}
var properties = new ParagraphProperties();
properties.AppendChild(new Justification()
{
Val =
GetJustificationValues(paragraphProperties.JustificationType)
});
properties.AppendChild(new SpacingBetweenLines
{
LineRule = LineSpacingRuleValues.Auto
});
properties.AppendChild(new Indentation());
var paragraphMarkRunProperties = new ParagraphMarkRunProperties();
if (!string.IsNullOrEmpty(paragraphProperties.Size))
{
paragraphMarkRunProperties.AppendChild(new FontSize
{
Val =
paragraphProperties.Size
});
}
properties.AppendChild(paragraphMarkRunProperties);
return properties;
}
protected override void CreateWord(WordInfo info)
{
_wordDocument = WordprocessingDocument.Create(info.FileName,
WordprocessingDocumentType.Document);
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
_docBody = mainPart.Document.AppendChild(new Body());
}
protected override void CreateParagraph(WordParagraph paragraph)
{
if (_docBody == null || paragraph == null)
{
return;
}
var docParagraph = new Paragraph();
docParagraph.AppendChild(CreateParagraphProperties(paragraph.TextProperties));
foreach (var run in paragraph.Texts)
{
var docRun = new Run();
var properties = new RunProperties();
properties.AppendChild(new FontSize { Val = run.Item2.Size });
if (run.Item2.Bold)
{
properties.AppendChild(new Bold());
}
docRun.AppendChild(properties);
docRun.AppendChild(new Text
{
Text = run.Item1,
Space =
SpaceProcessingModeValues.Preserve
});
docParagraph.AppendChild(docRun);
}
_docBody.AppendChild(docParagraph);
}
protected override void SaveWord(WordInfo info)
{
if (_docBody == null || _wordDocument == null)
{
return;
}
_docBody.AppendChild(CreateSectionProperties());
_wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Dispose();
}
protected override void CreateTable(WordTable table)
{
if (_docBody == null || table == null)
{
return;
}
Table docTable = new Table();
TableProperties tableProps = new TableProperties(
new TableBorders(
new TopBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new BottomBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new LeftBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new RightBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideHorizontalBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
},
new InsideVerticalBorder
{
Val = new EnumValue<BorderValues>(BorderValues.Single),
Size = 12
}
)
);
docTable.AppendChild(tableProps);
TableGrid tableGrid = new TableGrid();
for (int i = 0; i < table.Columns; i++)
{
tableGrid.AppendChild(new GridColumn());
}
docTable.AppendChild(tableGrid);
TableRow tableRow = new TableRow();
foreach (var text in table.Headers)
{
tableRow.AppendChild(CreateTableCell(text));
}
int height = table.RowText.Count;
int width = table.Columns;
docTable.AppendChild(tableRow);
for (int i = 0; i < height; i++)
{
tableRow = new TableRow();
for (int j = 0; j < width; j++)
{
var element = table.RowText[i][j];
tableRow.AppendChild(CreateTableCell(element));
}
docTable.AppendChild(tableRow);
}
_docBody.AppendChild(docTable);
}
private TableCell CreateTableCell(string element)
{
var tableParagraph = new Paragraph();
var run = new Run();
run.AppendChild(new Text { Text = element });
tableParagraph.AppendChild(run);
var tableCell = new TableCell();
tableCell.AppendChild(tableParagraph);
return tableCell;
}
}
}

View File

@ -1,5 +1,7 @@
using BankContracts.ViewModels;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
namespace BankClientApp
{
@ -14,5 +16,31 @@ namespace BankClientApp
_client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
}
public static T? GetRequest<T>(string requestUrl)
{
var response = _client.GetAsync(requestUrl);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>(result);
}
else
{
throw new Exception(result);
}
}
public static void PostRequest<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
throw new Exception(result);
}
}
}
}

View File

@ -1,8 +1,14 @@
using BankClientApp.Models;
using BankContracts.BindingModels;
using BankContracts.SearchModels;
using BankContracts.ViewModels;
using BankDatabaseImplement.Models;
using BankDataModels.Models;
using DocumentFormat.OpenXml.Spreadsheet;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Diagnostics;
using System.Globalization;
namespace BankClientApp.Controllers
{
@ -15,13 +21,39 @@ namespace BankClientApp.Controllers
_logger = logger;
}
public IActionResult Index()
{
return View(new List<CardViewModel>());
}
#region//Клиенты
[HttpGet]
public IActionResult Privacy()
{
return View(new ClientViewModel());
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.Client);
}
[HttpPost]
public void Privacy(string login, string password, string fio)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{
throw new Exception("Введите логин, пароль и ФИО");
}
APIClient.PostRequest("api/client/updateclient", new ClientBindingModel
{
Id = APIClient.Client.Id,
Fio = fio,
Email = login,
Password = password
});
APIClient.Client.Fio = fio;
APIClient.Client.Email = login;
APIClient.Client.Password = password;
Response.Redirect("Index");
}
[HttpGet]
@ -30,111 +62,672 @@ namespace BankClientApp.Controllers
return View();
}
[HttpPost]
public void Enter(string login, string password)
{
if (string.IsNullOrEmpty(login) ||
string.IsNullOrEmpty(password))
{
throw new Exception("Введите логин и пароль");
}
APIClient.Client = APIClient.GetRequest<ClientViewModel>($"api/client/login?login={login}&password={password}");
if (APIClient.Client == null)
{
throw new Exception("Неверный логин/пароль");
}
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public void Register(string login, string password, string fio)
{
if (string.IsNullOrEmpty(login) ||
string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{
throw new Exception("Введите логин, пароль и ФИО");
}
APIClient.PostRequest("api/client/register", new ClientBindingModel
{
Fio = fio,
Email = login,
Password = password
});
Response.Redirect("Enter");
return;
}
#endregion
#region//работа с картами
public IActionResult Index()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<CardViewModel>>($"api/card/getcardlist?clientid={APIClient.Client.Id}"));
}
[HttpGet]
public IActionResult CardCreate()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
[HttpPost]
public void CardCreate(string number, string cvv, string pin)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest("api/card/createcard", new
CardBindingModel
{
ClientId = APIClient.Client.Id,
Number = number,
Cvv = cvv,
Pin = pin
});
Response.Redirect("Index");
}
[HttpGet]
public IActionResult CardUpdate()
{
ViewBag.Cards = new List<CardViewModel>();
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Cards = APIClient.GetRequest<List<CardViewModel>>($"api/card/getcardlist?clientid={APIClient.Client.Id}");
return View();
}
[HttpPost]
public void CardUpdate(int card, string number, string cvv, string pin, DateTime expirationdate)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest("api/card/updatecard", new
CardBindingModel
{
Id = card,
ClientId = APIClient.Client.Id,
Number = number,
Cvv = cvv,
Pin = pin,
ExpirationDate = expirationdate
});
Response.Redirect("Index");
}
[HttpGet]
public CardViewModel? GetCard(int cardId)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
var result = APIClient.GetRequest<CardViewModel>($"api/card/getcard?cardid={cardId}");
if (result == null)
{
return default;
}
return result;
}
[HttpGet]
public List<int> GetCards(int requestId)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
var result = APIClient.GetRequest<List<int>>($"api/card/getcards?requestid={requestId}");
if (result == null)
{
return default;
}
return result;
}
[HttpGet]
public IActionResult CardDelete()
{
ViewBag.Cards = new List<CardViewModel>();
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Cards = APIClient.GetRequest<List<CardViewModel>>($"api/card/getcardlist?clientid={APIClient.Client.Id}");
return View();
}
[HttpPost]
public void CardDelete(int card)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest("api/card/deletecard", new
CardBindingModel
{
Id = card,
});
Response.Redirect("Index");
}
#endregion
#region//работа с операциями
[HttpGet]
public IActionResult Operation()
{
return View(new List<OperationViewModel>());
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<OperationViewModel>>($"api/operation/getoperationlist?clientid={APIClient.Client.Id}"));
}
[HttpGet]
public IActionResult OperationCreate()
{
ViewBag.Cards = new List<CardViewModel>();
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.SenderCards = APIClient.GetRequest<List<CardViewModel>>($"api/card/getcardlist?clientid={APIClient.Client.Id}");
ViewBag.RecipientCards = APIClient.GetRequest<List<CardViewModel>>($"api/card/getcardlist?clientid={null}");
return View();
}
[HttpPost]
public void OperationCreate(int sum, int? sendercard, int recipientcard)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (sendercard == recipientcard)
throw new Exception("Зачем в отправителе и получателе одну и ту же карту указали??? Думаете нам в банке заняться нечем?");
APIClient.PostRequest("api/operation/createoperation", new
OperationBindingModel
{
Sum = sum,
SenderCardId = sendercard,
RecipientCardId = recipientcard,
});
Response.Redirect("Operation");
}
[HttpGet]
public IActionResult OperationUpdate()
{
ViewBag.Operations = new List<OperationViewModel>();
ViewBag.Cards = new List<CardViewModel>();
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Operations = APIClient.GetRequest<List<OperationViewModel>>($"api/operation/getoperationlist?clientid={APIClient.Client.Id}");
ViewBag.SenderCards = APIClient.GetRequest<List<CardViewModel>>($"api/card/getcardlist?clientid={APIClient.Client.Id}");
ViewBag.RecipientCards = APIClient.GetRequest<List<CardViewModel>>($"api/card/getcardlist?clientid={null}");
return View();
}
[HttpPost]
public void OperationUpdate(int operation, int sum, int? sendercard, int recipientcard)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (sendercard == recipientcard)
{
throw new Exception("Зачем в отправителе и получателе одну и ту же карту указали??? Думаете нам в банке заняться нечем?");
}
APIClient.PostRequest("api/operation/updateoperation", new
OperationBindingModel
{
Id = operation,
Sum = sum,
SenderCardId = sendercard,
RecipientCardId = recipientcard,
});
Response.Redirect("Operation");
}
[HttpGet]
public OperationViewModel? GetOperation(int operationId)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
var result = APIClient.GetRequest<OperationViewModel>($"api/operation/getoperation?operationid={operationId}");
if (result == null)
{
return default;
}
return result;
}
[HttpGet]
public IActionResult OperationDelete()
{
ViewBag.Operations = new List<OperationViewModel>();
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Operations = APIClient.GetRequest<List<OperationViewModel>>($"api/operation/getoperationlist?clientid={APIClient.Client.Id}");
return View();
}
[HttpPost]
public void OperationDelete(int operation)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest("api/operation/deleteoperation", new
OperationBindingModel
{
Id = operation,
});
Response.Redirect("Operation");
}
[HttpGet]
public IActionResult OperationTransfer()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Operations = APIClient.GetRequest<List<OperationViewModel>>($"api/operation/getoperationlist?clientid={APIClient.Client.Id}");
ViewBag.Transfers = APIClient.GetRequest<List<TransferViewModel>>($"api/transfer/getfulltransferlist");
return View();
}
[HttpPost]
public void OperationTransfer(int operation, int transfer)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest("api/operation/linkoperationtransfer", new OperationBindingModel
{
Id = operation,
TransferId = transfer,
});
Response.Redirect("Operation");
}
#endregion
#region//работа с заявками
[HttpGet]
public IActionResult Request()
{
return View(new List<RequestViewModel>());
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<RequestViewModel>>($"api/request/getrequestlist?clientid={APIClient.Client.Id}"));
}
[HttpGet]
public IActionResult RequestCreate()
{
ViewBag.Cards = new List<CardViewModel>();
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Cards = APIClient.GetRequest<List<CardViewModel>>($"api/card/getcardlist?clientid={APIClient.Client.Id}");
return View();
}
[HttpPost]
public void RequestCreate(int sum, List<int> cards)
{
if (APIClient.Client == null)
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
Dictionary<int, ICardModel> a = new Dictionary<int, ICardModel>();
foreach(int card in cards)
{
a.Add(card, null);
}
APIClient.PostRequest("/api/request/createrequest", new RequestBindingModel
{
Sum = sum,
CardRequests = a,
Status = RequestStatus.Неизвестен
});
Response.Redirect("Request");
}
[HttpGet]
public IActionResult RequestUpdate()
{
ViewBag.Requests = new List<RequestViewModel>();
ViewBag.Cards = new List<CardViewModel>();
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Requests = APIClient.GetRequest<List<RequestViewModel>>($"api/request/getrequestlist?clientid={APIClient.Client.Id}");
ViewBag.Cards = APIClient.GetRequest<List<CardViewModel>>($"api/card/getcardlist?clientid={APIClient.Client.Id}");
return View();
}
[HttpPost]
public void RequestUpdate(int request, int sum, List<int> cards)
{
if (APIClient.Client == null)
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
Dictionary<int, ICardModel> a = new Dictionary<int, ICardModel>();
foreach (int card in cards)
{
a.Add(card, null);
}
APIClient.PostRequest("/api/request/updaterequest", new RequestBindingModel
{
Id = request,
Sum = sum,
CardRequests = a,
});
Response.Redirect("Request");
}
[HttpGet]
public IActionResult RequestDelete()
{
ViewBag.Requests = new List<RequestViewModel>();
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Requests = APIClient.GetRequest<List<RequestViewModel>>($"api/request/getrequestlist?clientid={APIClient.Client.Id}");
return View();
}
[HttpPost]
public void RequestDelete(int request)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest("api/request/deleterequest", new
RequestBindingModel
{
Id = request,
});
Response.Redirect("Request");
}
[HttpGet]
public RequestViewModel? GetRequest(int requestId)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
var result = APIClient.GetRequest<RequestViewModel>($"api/request/getrequest?requestid={requestId}");
if (result == null)
{
return default;
}
return result;
}
#endregion
#region//работа с отчетами
[HttpGet]
public IActionResult Report()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
[HttpPost]
public void Report(DateTime dateFrom, DateTime dateTo)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest("api/report/sendoperationsRequeststoemail", new ReportBindingModel
{
FileName = "C:\\forpdf\\pdffile.pdf",
DateFrom = dateFrom,
DateTo = dateTo,
Email = APIClient.Client.Email
});
Response.Redirect("Report");
}
[HttpGet]
public string GetOperationsRequests(DateTime dateFrom, DateTime dateTo)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
List<ReportOperationsRequestsViewModel>? result;
try
{
string dateFromS = dateFrom.ToString("s", CultureInfo.InvariantCulture);
string dateToS = dateTo.ToString("s", CultureInfo.InvariantCulture);
result = APIClient.GetRequest<List<ReportOperationsRequestsViewModel>?>($"api/report/getoperationsrequests?datefroms={dateFromS}&datetos={dateToS}");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания отчета");
throw;
}
//title
string tables = "";
tables += "<h2 class=\"text-custom-color-1\">Отчет по картам</h2>";
tables += $"<div class=\"text-custom-color-1 text-center\">c {dateFrom.ToShortDateString()} по {dateTo.ToShortDateString()}</div>";
//sender operations
string senderOperationsTable = "";
senderOperationsTable += "<h2 class=\"text-custom-color-1\">Операции на счета</h2>";
senderOperationsTable += "<div class=\" table-responsive\">";
senderOperationsTable += "<table class=\"table table-striped table-bordered table-hover\">";
senderOperationsTable += "<thead class=\"table-dark\">";
senderOperationsTable += "<tr>";
senderOperationsTable += "<th scope=\"col\">Номер счета</th>";
senderOperationsTable += "<th scope=\"col\">Номер перевода</th>";
senderOperationsTable += "<th scope=\"col\">Время перевода</th>";
senderOperationsTable += "<th scope=\"col\">Сумма</th>";
senderOperationsTable += "<th scope=\"col\">Карта получателя</th>";
senderOperationsTable += "</tr>";
senderOperationsTable += "</thead>";
senderOperationsTable += "<tbody>";
foreach (var report in result)
{
senderOperationsTable += "<tr>";
senderOperationsTable += $"<td>{report.CardNumber}</td>";
senderOperationsTable += $"<td></td>";
senderOperationsTable += $"<td></td>";
senderOperationsTable += $"<td></td>";
senderOperationsTable += $"<td></td>";
senderOperationsTable += "</tr>";
foreach (var senderOperation in report.SenderOperations)
{
senderOperationsTable += "<tr>";
senderOperationsTable += $"<td></td>";
senderOperationsTable += $"<td>{senderOperation.Id}</td>";
senderOperationsTable += $"<td>{senderOperation.OperationTime}</td>";
senderOperationsTable += $"<td>{senderOperation.Sum}</td>";
senderOperationsTable += $"<td>{senderOperation.RecipientCardNumber}</td>";
senderOperationsTable += "</tr>";
}
}
senderOperationsTable += "</tbody>";
senderOperationsTable += "</table>";
senderOperationsTable += "</div>";
tables += senderOperationsTable;
//sender operations
string recipientOperationsTable = "";
recipientOperationsTable += "<h2 class=\"text-custom-color-1\">Операции со счетов</h2>";
recipientOperationsTable += "<div class=\" table-responsive\">";
recipientOperationsTable += "<table class=\"table table-striped table-bordered table-hover\">";
recipientOperationsTable += "<thead class=\"table-dark\">";
recipientOperationsTable += "<tr>";
recipientOperationsTable += "<th scope=\"col\">Номер счета</th>";
recipientOperationsTable += "<th scope=\"col\">Номер перевода</th>";
recipientOperationsTable += "<th scope=\"col\">Время перевода</th>";
recipientOperationsTable += "<th scope=\"col\">Сумма</th>";
recipientOperationsTable += "<th scope=\"col\">Карта получателя</th>";
recipientOperationsTable += "</tr>";
recipientOperationsTable += "</thead>";
recipientOperationsTable += "<tbody>";
foreach (var report in result)
{
recipientOperationsTable += "<tr>";
recipientOperationsTable += $"<td>{report.CardNumber}</td>";
recipientOperationsTable += $"<td></td>";
recipientOperationsTable += $"<td></td>";
recipientOperationsTable += $"<td></td>";
recipientOperationsTable += $"<td></td>";
recipientOperationsTable += "</tr>";
foreach (var recipientOperation in report.RecipientOperations)
{
recipientOperationsTable += "<tr>";
recipientOperationsTable += $"<td></td>";
recipientOperationsTable += $"<td>{recipientOperation.Id}</td>";
recipientOperationsTable += $"<td>{recipientOperation.OperationTime}</td>";
recipientOperationsTable += $"<td>{recipientOperation.Sum}</td>";
recipientOperationsTable += $"<td>{recipientOperation.SenderCardNumber}</td>";
recipientOperationsTable += "</tr>";
}
}
recipientOperationsTable += "</tbody>";
recipientOperationsTable += "</table>";
recipientOperationsTable += "</div>";
tables += recipientOperationsTable;
//requests
string requestsTable = "";
requestsTable += "<h2 class=\"text-custom-color-1\">Заявки</h2>";
requestsTable += "<div class=\" table-responsive\">";
requestsTable += "<table class=\"table table-striped table-bordered table-hover\">";
requestsTable += "<thead class=\"table-dark\">";
requestsTable += "<tr>";
requestsTable += "<th scope=\"col\">Номер счета</th>";
requestsTable += "<th scope=\"col\">Номер заявки</th>";
requestsTable += "<th scope=\"col\">Время создания</th>";
requestsTable += "<th scope=\"col\">Сумма</th>";
requestsTable += "<th scope=\"col\">Статус</th>";
requestsTable += "</tr>";
requestsTable += "</thead>";
requestsTable += "<tbody>";
foreach (var report in result)
{
requestsTable += "<tr>";
requestsTable += $"<td>{report.CardNumber}</td>";
requestsTable += $"<td></td>";
requestsTable += $"<td></td>";
requestsTable += $"<td></td>";
requestsTable += $"<td></td>";
requestsTable += "</tr>";
foreach (var request in report.Requests)
{
requestsTable += "<tr>";
requestsTable += $"<td></td>";
requestsTable += $"<td>{request.Id}</td>";
requestsTable += $"<td>{request.RequestTime}</td>";
requestsTable += $"<td>{request.Sum}</td>";
requestsTable += $"<td>{request.Status}</td>";
requestsTable += "</tr>";
}
}
requestsTable += "</tbody>";
requestsTable += "</table>";
requestsTable += "</div>";
tables += requestsTable;
return tables;
}
[HttpGet]
public IActionResult TransferListReport()
{
ViewBag.Cards = new List<CardViewModel>();
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Cards = APIClient.GetRequest<List<CardViewModel>>($"api/card/getcardlist?clientid={APIClient.Client.Id}");
return View();
}
[HttpPost]
public void TransferListReport(List<int> cards, string format)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
switch (format)
{
case "word":
APIClient.PostRequest($"api/report/savetransferstoword", new ReportBindingModel
{
FileName = "C:\\forpdf\\wordfile.docx",
SelectedCardIds = cards,
});
Response.Redirect("ReportWord");
break;
case "excel":
APIClient.PostRequest($"api/report/savetransferstoexcel", new ReportBindingModel
{
FileName = "C:\\forpdf\\excelfile.xlsx",
SelectedCardIds = cards,
});
Response.Redirect("ReportExcel");
break;
default: break;
}
}
[HttpGet]
public IActionResult ReportWord()
{
return new PhysicalFileResult("C:\\forpdf\\wordfile.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
}
[HttpGet]
public IActionResult ReportExcel()
{
return new PhysicalFileResult("C:\\forpdf\\excelfile.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
#endregion
#region//ошибки
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
#endregion
}
}

View File

@ -4,7 +4,9 @@ var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
APIClient.Connect(builder.Configuration);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{

View File

@ -46,10 +46,10 @@
url: "/Home/GetCard",
data: { cardId: card },
success: function (result) {
$('#number').val(result.item1.number);
$('#cvv').val(result.item1.cvv);
$('#pin').val(result.item1.pin);
$('#expirationdate').val(result.item1.expirationDate);
$('#number').val(result.number);
$('#cvv').val(result.cvv);
$('#pin').val(result.pin);
$('#expirationdate').val(result.expirationDate);
}
});
};

View File

@ -8,11 +8,11 @@
</div>
<div class="text-center">
@{
// if (Model == null)
// {
// <h3 class="display-4">Авторизируйтесь</h3>
// return;
// }
if (Model == null)
{
<h3 class="display-4">авторизируйтесь</h3>
return;
}
<p>
<a asp-action="CardCreate">Создать карту</a>
<a asp-action="CardUpdate">Обновить карту</a>
@ -39,9 +39,6 @@
<th>
Держатель карты
</th>
<th>
Номер счета
</th>
</tr>
</thead>
<tbody>
@ -72,10 +69,6 @@
@Html.DisplayFor(modelItem =>
item.ClientName)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.AccountNumber)
</td>
</tr>
}
</tbody>

View File

@ -17,6 +17,7 @@
<a asp-action="OperationCreate">Создать операцию</a>
<a asp-action="OperationUpdate">Обновить операцию</a>
<a asp-action="OperationDelete">Удалить операцию</a>
<a asp-action="OperationTransfer">Привязать перевод</a>
</p>
<table class="table">
<thead>
@ -36,6 +37,9 @@
<th>
Получатель
</th>
<th>
Номер перевода
</th>
</tr>
</thead>
<tbody>
@ -62,6 +66,10 @@
@Html.DisplayFor(modelItem =>
item.RecipientCardNumber)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.TransferId)
</td>
</tr>
}
</tbody>

View File

@ -8,19 +8,19 @@
<div class="row">
<div class="col-4">Сумма:</div>
<div class="col-8">
<input type="text" name="sum" id="sum" />
<input type="number" name="sum" id="sum" />
</div>
</div>
<div class="row">
<div class="col-4">Отправитель:</div>
<div class="col-8">
<select id="sendercard" name="sendercard" class="form-control" asp-items="@(new SelectList(@ViewBag.Cards, "Id", "Number"))"></select>
<select id="sendercard" name="sendercard" class="form-control" asp-items="@(new SelectList(@ViewBag.SenderCards, "Id", "Number"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Получатель:</div>
<div class="col-8">
<select id="recipientcard" name="recipientcard" class="form-control" asp-items="@(new SelectList(@ViewBag.Cards, "Id", "Number"))"></select>
<select id="recipientcard" name="recipientcard" class="form-control" asp-items="@(new SelectList(@ViewBag.RecipientCards, "Id", "Number"))"></select>
</div>
</div>
<div class="row">

View File

@ -1,6 +1,4 @@
//todo выводить список только для выбранного клиента
@{
@{
ViewData["Title"] = "OperationTransfer";
}
<div class="text-center">
@ -20,110 +18,8 @@
</div>
</div>
<div class="text-center">
<h4 class="display-4">Перевод</h4>
</div>
<div class="row">
<div class="col-4">Сумма:</div>
<div class="col-8">
<input type="number" readonly name="transfersum" id="transfersum" />
</div>
</div>
<div class="row">
<div class="col-4">Номер счета отправителя:</div>
<div class="col-8">
<input type="text" readonly name="transfersender-number" id="transfersender-number" />
</div>
</div>
<div class="row">
<div class="col-4">Номер счета получателя:</div>
<div class="col-8">
<input type="text" readonly name="treansferrecipient-number" id="transferrecipient-number" />
</div>
</div>
<div class="row">
<div class="col-4">Дата:</div>
<div class="col-8">
<input type="datetime-local" readonly name="transferdate" id="transferdate" />
</div>
</div>
<div class="text-center">
<h4 class="display-4">Операция</h4>
</div>
<div class="row">
<div class="col-4">Сумма:</div>
<div class="col-8">
<input type="text" readonly name="operationsum" id="operationsum" />
</div>
</div>
<div class="row">
<div class="col-4">Отправитель:</div>
<div class="col-8">
<input type="text" readonly name="operationrecipient-number" id="operationrecipient-number" />
</div>
</div>
<div class="row">
<div class="col-4">Получатель:</div>
<div class="col-8">
<input type="text" readonly name="operationrecipient-number" id="operationrecipient-number" />
</div>
</div>
<div class="row">
<div class="col-4">Дата:</div>
<div class="col-8">
<input type="datetime-local" readonly name="operationdate" id="operationdate" />
</div>
</div>
<div class="row">
<div class="col-4"></div>
<div class="col-8"><input type="submit" value="Связать" class="btn btn-danger" /></div>
<div class="col-8"><input type="submit" value="Связать" class="btn btn-success" /></div>
</div>
</form>
@section Scripts
{
<script>
function checkTrensfer() {
var transfer = $('#transfer').val();
if (transfer) {
$.ajax({
method: "GET",
url: "/Home/GetTransfer",
data: { transferId: transfer },
success: function (result) {
$('#sum').val(result.item1.Sum);
$('#transfersender-number').val(result.item1.senderAccountNumber);
$('#transferrecipient-number').val(result.item1.recipientAccountNumber);
$('#transferdate').val(result.item1.transferTime);
}
});
};
}
function checkOperation() {
var operation = $('#operation').val();
if (operation) {
$.ajax({
method: "GET",
url: "/Home/GetOperation",
data: { operationId: operation },
success: function (result) {
$('#sum').val(result.item1.Sum);
$('#operationsender-number').val(result.item1.senderCardNumber);
$('#operationrecipient-number').val(result.item1.recipientCardNumber);
$('#operationdate').val(result.item1.transferTime);
}
});
};
}
checkTransfer();
checkOperation();
$('#transfer').on('change', function () {
checkTransfer();
});
$('#operation').on('change', function () {
checkOperation();
});
</script>
}
</form>

View File

@ -9,7 +9,7 @@
<div class="row">
<div class="col-4">Операция:</div>
<div class="col-8">
<select id="operation" name="operation" class="form-control" asp-items="@(new SelectList(@ViewBag.Operations, "Id", "Id"))"></select>
<select id="operation" name="operation" class="form-control" asp-items="@(new SelectList(@ViewBag.Operations, "Id", "Id" ))"></select>
</div>
</div>
<div class="row">
@ -21,17 +21,42 @@
<div class="row">
<div class="col-4">Отправитель:</div>
<div class="col-8">
<select id="sendercard" name="sendercard" class="form-control" asp-items="@(new SelectList(@ViewBag.Cards, "Id", "Number"))"></select>
<select id="sendercard" name="sendercard" class="form-control" asp-items="@(new SelectList(@ViewBag.SenderCards, "Id", "Number"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Получатель:</div>
<div class="col-8">
<select id="recipientcard" name="recipientcard" class="form-control" asp-items="@(new SelectList(@ViewBag.Cards, "Id", "Number"))"></select>
<select id="recipientcard" name="recipientcard" class="form-control" asp-items="@(new SelectList(@ViewBag.RecipientCards, "Id", "Number"))"></select>
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Сохранить" class="btn btn-primary" /></div>
</div>
</form>
</form>
@section Scripts
{
<script>
function check() {
var operation = $('#operation').val();
if (operation) {
$.ajax({
method: "GET",
url: "/Home/GetOperation",
data: { operationId: operation },
success: function (result) {
$('#sum').val(result.sum);
$('#sendercard').val(result.senderCardId);
$('#recipientcard').val(result.recipientCardId);
}
});
};
}
check();
$('#operation').on('change', function () {
check();
});
</script>
}

View File

@ -7,8 +7,8 @@
</div>
<form method="post">
<div class="row">
<div class="col-4">Email:</div>
<div class="col-8"><input type="text" name="email" /></div>
<div class="col-4">Логин:</div>
<div class="col-8"><input type="text" name="login" /></div>
</div>
<div class="row">
<div class="col-4">Пароль:</div>

View File

@ -2,58 +2,55 @@
ViewData["Title"] = "Report";
}
<div class="text-center">
<h3 class="display-4">Список карт с расшифровкой по операциям и заявкам</h3>
<h3 class="display-4">Список карт с расшифровкой по операциям и заявкам за период</h3>
</div>
<div class="text-center">
@{
// if (Model == null)
// {
// <h4 class="display-4">Авторизуйтесь!</h4>
// return;
// }
<div class="row mb-5">
<div class="col-4">Начальная дата:</div>
<div class="col-8">
<input type="date" id="startDate" name="startDate" class="form-control">
<div class="text-center" >
<form method="post">
@{
<div class="row mb-5">
<div class="col-4">Начальная дата:</div>
<div class="col-8">
<input type="date" id="dateFrom" name="dateFrom" class="form-control">
</div>
</div>
</div>
<div class="row mb-5">
<div class="col-4">Конечная дата:</div>
<div class="col-8">
<input type="date" id="endDate" name="endDate" class="form-control">
<div class="row mb-5">
<div class="col-4">Конечная дата:</div>
<div class="col-8">
<input type="date" id="dateTo" name="dateTo" class="form-control">
</div>
</div>
</div>
<table class="table">
<thead>
<tr>
<th>
Номер
</th>
<th>
Дата
</th>
<th>
Карта
</th>
<th>
Операция
</th>
<th>
Заявка
</th>
</tr>
</thead>
<tbody>
будет заполняться вьюшками отчета
</tbody>
</table>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Создать отчет" class="btn btn-primary" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Отправить на почту" class="btn btn-primary" /></div>
</div>
}
</div>
<div class="row mb-2">
<div class="col-8"></div>
<div class="col-4"><input id="demonstrate" type="button" value="Создать отчет" class="btn btn-primary" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Отправить на почту" class="btn btn-primary" /></div>
</div>
<div id="report"></div>
}
</form>
</div>
@section Scripts {
<script>
function check() {
var dateFrom = $('#dateFrom').val();
var dateTo = $('#dateTo').val();
if (dateFrom && dateTo) {
$.ajax({
method: "GET",
url: "/Home/GetOperationsRequests",
data: { dateFrom: dateFrom, dateTo: dateTo },
success: function (result) {
if (result != null) {
$('#report').html(result);
}
}
});
};
}
check();
$('#demonstrate').on('click', (e) => check());
</script>
}

View File

@ -2,7 +2,7 @@
ViewData["Title"] = "RequestCreate";
}
<div class="text-center">
<h2 class="display-4">Создание заапроса</h2>
<h2 class="display-4">Создание запроса</h2>
</div>
<form method="post">
<div class="row">

View File

@ -40,23 +40,26 @@
{
<script>
function check() {
var cards = $('#cards').val();
var request = $('#request').val();
$("#cards option:selected").removeAttr("selected");
if (cards) {
if (request) {
$.ajax({
method: "GET",
url: "/Home/GetCards",
data: { serviceId: service },
data: { requestId: request },
success: function (result) {
console.log(result.item2);
$('#name').val(result.item1.serviceName);
$('#price').val(result.item1.price);
$.map(result.item2, function (n) {
console.log("#" + n);
$(`option[data-name=${n}]`).attr("selected", "selected")
$.map(result, function (n) {
$(`#cards option[value=${n}]`).attr("selected", "selected")
});
}
});
$.ajax({
method: "GET",
url: "/Home/GetRequest",
data: {requestId: request},
success: function (result) {
$('#sum').val(result.sum)
}
});
};
}

View File

@ -19,9 +19,16 @@
</select>
</div>
</div>
<div>
<input id="word" type="radio" name="format" value="word" checked/>
<label for="word">Получать в формате Word</label>
</div>
<div>
<input id="excel" type="radio" name="format" value="excel" />
<label for="excel">Получать в формате Excel</label>
</div>
<div class="row">
<div class="col-9"></div>
<div class="col-1"><input type="submit" value="Word" class="btn btn-primary" /></div>
<div class="col-1"><input type="submit" value="Excel" class="btn btn-primary" /></div>
<div class="col-1"><input type="submit" value="Получить список" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -13,12 +13,12 @@
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bgwhite border-bottom box-shadow mb-3">
<div class="container">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Компьютерный магазин</a>
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Банк</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-smrow-reverse">
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Enter">Вход</a>
@ -56,7 +56,7 @@
</div>
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2020 - Абстрактный магазин - <a asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
&copy; 2024 - Банк - <a asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</div>
</footer>
<script src="~/js/site.js" asp-append-version="true"></script>

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BindingModels
{
public class MailConfigBindingModel
{
public string MailLogin { get; set; } = string.Empty;
public string MailPassword { get; set; } = string.Empty;
public string SmtpClientHost { get; set; } = string.Empty;
public int SmtpClientPort { get; set; }
public string PopHost { get; set; } = string.Empty;
public int PopPort { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BindingModels
{
public class MailSendInfoBindingModel
{
public string MailAddress { get; set; } = string.Empty;
public string Subject { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty;
}
}

View File

@ -14,5 +14,6 @@ namespace BankContracts.BindingModels
public DateTime OperationTime { get; set; }
public int? SenderCardId { get; set; }
public int RecipientCardId { get; set; }
public int? TransferId { get; set; }
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankContracts.BindingModels
{
public class ReportBindingModel
{
public string FileName { get; set; } = string.Empty;
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public List<int>? SelectedAccountIds { get; set; }
public List<int>? SelectedCardIds { get; set; }
public string? Email { get; set; }
}
}

View File

@ -12,6 +12,7 @@ namespace BankContracts.BindingModels
public int Id { get; set; }
public DateTime WithdrawalTime { get; set; } = DateTime.Now;
public int? RequestId { get; set; }
public int Sum { get; set; }
public Dictionary<int, (IAccountModel, int)> WithdrawalAccounts { get; set; } = new();
}
}

View File

@ -12,6 +12,7 @@ namespace BankContracts.BusinessLogicsContracts
public interface IAccountLogic
{
List<AccountViewModel>? ReadList(AccountSearchModel? model);
List<int> ReadAccountIdsByWithdrawal(AccountSearchModel model);
AccountViewModel? ReadElement(AccountSearchModel model);
bool Create(AccountBindingModel model);
bool Update(AccountBindingModel model);

View File

@ -13,6 +13,7 @@ namespace BankContracts.BusinessLogicsContracts
{
List<CardViewModel>? ReadList(CardSearchModel? model);
CardViewModel? ReadElement(CardSearchModel model);
List<int> ReadListByRequestId(CardSearchModel model);
bool Create(CardBindingModel model);
bool Update(CardBindingModel model);
bool Delete(CardBindingModel model);

View File

@ -13,6 +13,7 @@ namespace BankContracts.BusinessLogicsContracts
{
List<OperationViewModel>? ReadList(OperationSearchModel? model);
OperationViewModel? ReadElement(OperationSearchModel model);
bool LinkOperationTransfer(int operationId, int transferId);
bool Create(OperationBindingModel model);
bool Update(OperationBindingModel model);
bool Delete(OperationBindingModel model);

View File

@ -1,8 +1,10 @@
using BankContracts.SearchModels;
using BankContracts.BindingModels;
using BankContracts.SearchModels;
using BankContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
@ -14,5 +16,11 @@ namespace BankContracts.BusinessLogicsContracts
List<ReportOperationsRequestsViewModel> CreateReportOperationsRequests(CardSearchModel model);
List<ReportRequestsViewModel> CreateReportRequests(AccountSearchModel model);
List<ReportTransfersWithdrawalsViewModel> CreateReportTransfersWithdrawals(AccountSearchModel model);
}
void SaveRequestsToExcelFile(ReportBindingModel model);
void SaveRequestsToWordFile(ReportBindingModel model);
void SaveTransfersToWordFile(ReportBindingModel model);
void SaveTransfersToExcelFile(ReportBindingModel model);
void SaveOperationsRequestsToPdfFile(ReportBindingModel model);
void SaveTransfersWithdrawalsToPdfFile(ReportBindingModel model);
}
}

View File

@ -11,12 +11,11 @@ namespace BankContracts.BusinessLogicsContracts
{
public interface IRequestLogic
{
List<RequestViewModel>? ReadList(RequestSearchModel? model);
List<RequestViewModel>? ReadList(RequestSearchModel? model, int? clientId);
RequestViewModel? ReadElement(RequestSearchModel model);
bool Create(RequestBindingModel model);
bool Update(RequestBindingModel model);
bool Delete(RequestBindingModel model);
bool DeclineRequest(RequestBindingModel model);
bool SatisfyRequest(RequestBindingModel model);
}
}

View File

@ -15,6 +15,7 @@ namespace BankContracts.BusinessLogicsContracts
WithdrawalViewModel? ReadElement(WithdrawalSearchModel model);
bool Create(WithdrawalBindingModel model);
bool Update(WithdrawalBindingModel model);
bool LinkToRequest(int withdrawalId, int requestId);
bool Delete(WithdrawalBindingModel model);
}
}

View File

@ -13,6 +13,7 @@ namespace BankContracts.SearchModels
public DateTime? DateTo { get; set; }
public DateTime? DateFrom { get; set; }
public int? ManagerId { get; set; }
public int? WithdrawalId { get; set; }
public List<int>? SelectedAccountIds { get; set; }
}
}

View File

@ -14,5 +14,6 @@ namespace BankContracts.SearchModels
public DateTime? DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public List<int>? SelectedCardIds { get; set; }
public int? RequestId { get; set; }
}
}

View File

@ -14,5 +14,6 @@ namespace BankContracts.SearchModels
public int? SenderCardId { get; set; }
public int? RecipientCardId { get; set; }
public int? CardId { get; set; }
public int? clientId { get; set; }
}
}

View File

@ -14,5 +14,6 @@ namespace BankContracts.SearchModels
public int? OperationId { get; set; }
public int? SenderAccountId { get; set; }
public int? RecipientAccountId { get; set; }
public int? ManagerId { get; set; }
}
}

View File

@ -12,5 +12,6 @@ namespace BankContracts.SearchModels
public DateTime? DateTo { get; set; }
public DateTime? DateFrom { get; set; }
public int? RequestId { get; set; }
public int? ManagerId { get; set; }
}
}

View File

@ -13,7 +13,8 @@ namespace BankContracts.StoragesContracts
{
List<AccountViewModel> GetFullList();
List<AccountViewModel> GetFilteredList(AccountSearchModel model);
List<ReportRequestsViewModel> GetRequestsReport(AccountSearchModel model);
List<int> GetAccountIdsByWithdrawal(AccountSearchModel model);
List<ReportRequestsViewModel> GetRequestsReport(AccountSearchModel model);
List<ReportTransfersWithdrawalsViewModel> GetTransfersWithdrawalsReport(AccountSearchModel model);
AccountViewModel? GetElement(AccountSearchModel model);
AccountViewModel? Insert(AccountBindingModel model);

View File

@ -13,6 +13,7 @@ namespace BankContracts.StoragesContracts
{
List<CardViewModel> GetFullList();
List<CardViewModel> GetFilteredList(CardSearchModel model);
List<int> GetListForRequest(CardSearchModel model);
List<ReportTransfersViewModel> GetReportTransfersList(CardSearchModel model);
List<ReportOperationsRequestsViewModel> GetReportOperationsRequestsList(CardSearchModel model);
CardViewModel? GetElement(CardSearchModel model);

View File

@ -17,5 +17,7 @@ namespace BankContracts.StoragesContracts
OperationViewModel? Insert(OperationBindingModel model);
OperationViewModel? Update(OperationBindingModel model);
OperationViewModel? Delete(OperationBindingModel model);
bool LinkOperationTransfer(int oprationId, int transferId);
}
}

View File

@ -11,7 +11,7 @@ namespace BankContracts.StoragesContracts
{
public interface IRequestStorage
{
List<RequestViewModel> GetFullList();
List<RequestViewModel> GetFullList(int? clientId);
List<RequestViewModel> GetFilteredList(RequestSearchModel model);
RequestViewModel? GetElement(RequestSearchModel model);
RequestViewModel? Insert(RequestBindingModel model);

View File

@ -16,6 +16,7 @@ namespace BankContracts.StoragesContracts
WithdrawalViewModel? GetElement(WithdrawalSearchModel model);
WithdrawalViewModel? Insert(WithdrawalBindingModel model);
WithdrawalViewModel? Update(WithdrawalBindingModel model);
WithdrawalViewModel? Delete(WithdrawalBindingModel model);
WithdrawalViewModel? LinkToRequest(int withdrawalId, int requestId);
WithdrawalViewModel? Delete(WithdrawalBindingModel model);
}
}

View File

@ -24,8 +24,5 @@ namespace BankContracts.ViewModels
public int ClientId { get; set; }
[DisplayName("Держатель карты")]
public string ClientName { get; set; } = string.Empty;
public int? AccountId { get; set; }
[DisplayName("Номер счета")]
public string AccountNumber { get; set; } = string.Empty;
}
}

View File

@ -22,5 +22,6 @@ namespace BankContracts.ViewModels
public int RecipientCardId { get; set; }
[DisplayName("Номер карты получателя")]
public string RecipientCardNumber { get; set; } = string.Empty;
public int? TransferId { get; set; }
}
}

View File

@ -17,7 +17,7 @@ namespace BankContracts.ViewModels
[DisplayName("Номер заявки")]
public int? RequestId { get; set; }
[DisplayName("Сумма")]
public int? Sum { get; set; }
public int Sum { get; set; }
public Dictionary<int, (IAccountModel, int)> WithdrawalAccounts { get; set; } = new();
}
}

View File

@ -10,6 +10,7 @@ namespace BankDataModels.Models
{
DateTime WithdrawalTime { get; set; }
int? RequestId { get; set; }
int Sum { get; }
Dictionary<int, (IAccountModel, int)> WithdrawalAccounts { get; }
}
}

View File

@ -12,41 +12,49 @@ using System.Threading.Tasks;
namespace BankDatabaseImplement.Implements
{
internal class AccountStorage : IAccountStorage
public class AccountStorage : IAccountStorage
{
public List<AccountViewModel> GetFullList()
{
using var context = new BankDatabase();
return context.Accounts
.Include(x => x.ManagerId)
.Include(x => x.Manager)
.Include(x => x.AccountWithdrawals)
.Include(x => x.SenderTransfers)
.Include(x => x.RecipientTransfers)
.Select(x => x.GetViewModel).ToList();
.Select(x => x.GetViewModel)
.ToList();
}
public List<AccountViewModel> GetFilteredList(AccountSearchModel model)
{
using var context = new BankDatabase();
return context.Accounts
.Include(x => x.ManagerId)
.Include(x => x.Manager)
.Include(x => x.AccountWithdrawals)
.Include(x => x.SenderTransfers)
.Include(x => x.RecipientTransfers)
.Where(x =>
(!model.Id.HasValue || x.Id == model.Id) &&
(!model.ManagerId.HasValue || x.ManagerId == model.ManagerId) &&
(string.IsNullOrEmpty(model.Number) || x.Number == model.Number)
)
(string.IsNullOrEmpty(model.Number) || x.Number == model.Number))
.Select(x => x.GetViewModel)
.ToList();
}
}
public List<int> GetAccountIdsByWithdrawal(AccountSearchModel model)
{
using var context = new BankDatabase();
return context.AccountWithdrawals
.Where(x => !model.WithdrawalId.HasValue || x.WithdrawalId == model.WithdrawalId)
.Select(x => x.AccountId)
.ToList();
}
public AccountViewModel? GetElement(AccountSearchModel model)
public AccountViewModel? GetElement(AccountSearchModel model)
{
using var context = new BankDatabase();
return context.Accounts
.Include(x => x.ManagerId)
.Include(x => x.Manager)
.Include(x => x.AccountWithdrawals)
.Include(x => x.SenderTransfers)
.Include(x => x.RecipientTransfers)
@ -73,7 +81,7 @@ namespace BankDatabaseImplement.Implements
{
using var context = new BankDatabase();
var account = context.Accounts
.Include(x => x.ManagerId)
.Include(x => x.Manager)
.Include(x => x.AccountWithdrawals)
.Include(x => x.SenderTransfers)
.Include(x => x.RecipientTransfers)
@ -91,7 +99,7 @@ namespace BankDatabaseImplement.Implements
{
using var context = new BankDatabase();
var account = context.Accounts
.Include(x => x.ManagerId)
.Include(x => x.Manager)
.Include(x => x.AccountWithdrawals)
.Include(x => x.SenderTransfers).Include(x => x.RecipientTransfers)
.FirstOrDefault(rec => rec.Id == model.Id);
@ -109,18 +117,18 @@ namespace BankDatabaseImplement.Implements
using var context = new BankDatabase();
return context.Accounts
.Where(a => model.SelectedAccountIds == null || model.SelectedAccountIds.Contains(a.Id))
.Select(a => new ReportRequestsViewModel()
.Select(account => new ReportRequestsViewModel()
{
AccountNumber = a.Number,
Requests = context.Requests
.Include(x => x.Withdrawal)
.ThenInclude(x => x.Accounts)
.Where(x => x.Withdrawal != null && x.Withdrawal.Accounts
.Select(x => x.AccountId)
.ToList()
.Contains(a.Id))
.Select (r => r.GetViewModel)
.ToList()
AccountNumber = account.Number,
Requests = context.AccountWithdrawals
.Include(x => x.Withdrawal)
.ThenInclude(x => x.Request)
.Where(x => x.AccountId == account.Id)
.Select(x => x.Withdrawal)
.Where(x => x.RequestId != null)
.Select(x => x.Request)
.Select(r => r.GetViewModel)
.ToList(),
})
.ToList();
}
@ -129,31 +137,34 @@ namespace BankDatabaseImplement.Implements
{
using var context = new BankDatabase();
return context.Accounts
.Select(a => new ReportTransfersWithdrawalsViewModel()
.Select(account => new ReportTransfersWithdrawalsViewModel()
{
AccountNumber = a.Number,
AccountNumber = account.Number,
SenderTransfers = context.Transfers
.Include(x => x.RecipientAccount)
.Where(t => t.TransferTime <= model.DateTo &&
t.TransferTime >= model.DateFrom &&
t.SenderAccountId == a.Id)
t.SenderAccountId == account.Id)
.Select(t => t.GetViewModel)
.ToList(),
RecipientTransfers = context.Transfers
.Where(t => t.TransferTime <= model.DateTo &&
.Include(x => x.SenderAccount)
.Where(t => t.TransferTime <= model.DateTo &&
t.TransferTime >= model.DateFrom &&
t.RecipientAccountId == a.Id)
t.RecipientAccountId == account.Id)
.Select(t => t.GetViewModel)
.ToList(),
Withdrawals = context.Withdrawals
.Include(w => w.Accounts)
.Where(w => w.WithdrawalTime <= model.DateTo &&
w.WithdrawalTime >= model.DateFrom && w.Accounts
.Select(x => x.AccountId)
.ToList()
.Contains(a.Id))
.Select(w => w.GetViewModel)
.ToList()
})
Withdrawals = context.AccountWithdrawals
.Include(x => x.Withdrawal)
.ThenInclude(x => x.Accounts)
.Where(x => x.AccountId == account.Id)
.Select(x => x.Withdrawal)
.Where(w =>
w.WithdrawalTime <= model.DateTo &&
w.WithdrawalTime >= model.DateFrom)
.Select(w => w.GetViewModel)
.ToList(),
})
.ToList();
}
}

View File

@ -4,6 +4,7 @@ using BankContracts.StoragesContracts;
using BankContracts.ViewModels;
using BankDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System.Linq;
namespace BankDatabaseImplement.Implements
{
@ -30,6 +31,15 @@ namespace BankDatabaseImplement.Implements
.ToList();
}
public List<int> GetListForRequest(CardSearchModel model)
{
using var context = new BankDatabase();
return context.CardRequests
.Include(x => x.Card).Include(x => x.Request)
.Where(x => x.RequestId==model.RequestId)
.Select(x => x.Card.Id).Distinct().ToList();
}
public List<ReportTransfersViewModel> GetReportTransfersList(CardSearchModel model)
{
using var context = new BankDatabase();
@ -41,8 +51,8 @@ namespace BankDatabaseImplement.Implements
{
CardNumber = t.Number,
Transfers = context.Transfers
.Include(c => c.Operation)
.Where(x => x.Operation == null || x.Operation.SenderCardId == model.Id || x.Operation.RecipientCardId == model.Id)
.Include(c => c.Operation).Include(c => c.RecipientAccount).Include(c => c.SenderAccount)
.Where(x => (x.Operation == null || x.Operation.SenderCardId == t.Id || x.Operation.RecipientCardId == t.Id) && (x.OperationId != null))
.Select(t => t.GetViewModel)
.ToList()
}).ToList();
@ -52,23 +62,30 @@ namespace BankDatabaseImplement.Implements
{
using var context = new BankDatabase();
return context.Cards
.Select(c => new ReportOperationsRequestsViewModel()
.Select(card => new ReportOperationsRequestsViewModel()
{
CardNumber = c.Number,
CardNumber = card.Number,
SenderOperations = context.Operations
.Where(x => x.OperationTime >= model.DateFrom && x.OperationTime <= model.DateTo && x.SenderCardId == model.Id)
.Include(x => x.RecipientCard)
.Where(x => x.OperationTime >= model.DateFrom && x.OperationTime <= model.DateTo && x.SenderCardId == card.Id)
.Select(t => t.GetViewModel)
.ToList(),
RecipientOperations = context.Operations
.Where(x => x.OperationTime >= model.DateFrom && x.OperationTime <= model.DateTo && x.RecipientCardId == model.Id)
.Include(x => x.SenderCard)
.Where(x => x.OperationTime >= model.DateFrom && x.OperationTime <= model.DateTo && x.RecipientCardId == card.Id)
.Select(t => t.GetViewModel)
.ToList(),
Requests = context.Requests
.Include(x => x.CardRequests)
.Where(x => x.Cards.Select(x => x.CardId).ToList().Contains(c.Id) && x.RequestTime >= model.DateFrom && x.RequestTime <= model.DateTo)
Requests = context.CardRequests
.Include(x => x.Request)
.ThenInclude(x => x.Cards)
.Where(x => x.CardId == card.Id)
.Select(x => x.Request)
.Where(x =>
x.RequestTime >= model.DateFrom &&
x.RequestTime <= model.DateTo)
.Select(r => r.GetViewModel)
.ToList(),
}).ToList();
}).ToList();
}
public CardViewModel? GetElement(CardSearchModel model)

View File

@ -18,23 +18,24 @@ namespace BankDatabaseImplement.Implements
{
using var context = new BankDatabase();
return context.Operations.Include(x => x.SenderCard).Include(x => x.RecipientCard)
.Select(x => x.GetViewModel).ToList();
.Select(x => x.GetViewModel).ToList();
}
public List<OperationViewModel> GetFilteredList(OperationSearchModel model)
{
using var context = new BankDatabase();
return context.Operations.Include(x => x.SenderCard).Include(x => x.RecipientCard)
return context.Operations.Include(x => x.SenderCard).Include(x => x.RecipientCard).Include(x => x.Transfer)
.Where(x => (
(!model.Id.HasValue || x.Id == model.Id) &&
(!model.DateFrom.HasValue || x.OperationTime >= model.DateFrom ) &&
(!model.DateTo.HasValue || x.OperationTime <= model.DateTo)
(!model.DateTo.HasValue || x.OperationTime <= model.DateTo) &&
(x.SenderCard == null || x.SenderCard.ClientId == model.clientId)
)).Select(x => x.GetViewModel).ToList();
}
public OperationViewModel? GetElement(OperationSearchModel model)
{
if (!model.Id.HasValue) return null;
using var context = new BankDatabase();
return context.Operations.Include(x => x.SenderCard).Include(x => x.RecipientCard)
return context.Operations.Include(x => x.SenderCard).Include(x => x.RecipientCard).Include(x => x.Transfer)
.FirstOrDefault(x => ((model.Id.HasValue && x.Id == model.Id)
))?.GetViewModel;
}
@ -53,7 +54,12 @@ namespace BankDatabaseImplement.Implements
public OperationViewModel? Update(OperationBindingModel model)
{
using var context = new BankDatabase();
var operation = context.Operations.Include(x => x.SenderCard).Include(x => x.RecipientCard).FirstOrDefault(x => x.Id == model.Id);
var operation = context.Operations.Include(x => x.SenderCard).Include(x => x.RecipientCard).Include(x => x.Transfer).FirstOrDefault(x => x.Id == model.Id);
var transfer = context.Transfers.FirstOrDefault(x => x.OperationId == model.Id);
if (transfer != null)
{
throw new InvalidOperationException("Обновление невозможно");
}
if (operation == null)
{
return null;
@ -65,7 +71,12 @@ namespace BankDatabaseImplement.Implements
public OperationViewModel? Delete(OperationBindingModel model)
{
using var context = new BankDatabase();
var operation = context.Operations.Include(x => x.SenderCard).Include(x => x.RecipientCard).FirstOrDefault(rec => rec.Id == model.Id);
var operation = context.Operations.Include(x => x.SenderCard).Include(x => x.RecipientCard).Include(x => x.Transfer).FirstOrDefault(rec => rec.Id == model.Id);
var transfer = context.Transfers.FirstOrDefault(x => x.OperationId == model.Id);
if (transfer != null)
{
throw new InvalidOperationException("Удаление невозможно");
}
if (operation != null)
{
context.Operations.Remove(operation);
@ -74,5 +85,30 @@ namespace BankDatabaseImplement.Implements
}
return null;
}
public bool LinkOperationTransfer(int operationId, int transferId)
{
using var context = new BankDatabase();
var transfer = context.Transfers.Include(x => x.SenderAccount).Include(x => x.RecipientAccount).Include(x => x.Operation).FirstOrDefault(rec => rec.Id == transferId);
if (transfer == null || operationId <= 0 )
{
return false;
}
if (transfer.OperationId != null || context.Transfers.Where(x => x.OperationId == operationId).Count() > 0 )
{
throw new Exception("Невозможно связать выбранные сущности");
}
var newTransfer = new TransferBindingModel
{
Sum = transfer.Sum,
TransferTime = transfer.TransferTime,
OperationId = operationId,
SenderAccountId = transfer.SenderAccountId,
RecipientAccountId = transfer.RecipientAccountId,
};
transfer.Update(newTransfer);
context.SaveChanges();
return true;
}
}
}

View File

@ -3,6 +3,7 @@ using BankContracts.SearchModels;
using BankContracts.StoragesContracts;
using BankContracts.ViewModels;
using BankDatabaseImplement.Models;
using BankDataModels.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections;
@ -15,14 +16,23 @@ namespace BankDatabaseImplement.Implements
{
public class RequestStorage : IRequestStorage
{
public List<RequestViewModel> GetFullList()
public List<RequestViewModel> GetFullList(int? clientId)
{
using var context = new BankDatabase();
return context.Requests
.Include(x => x.Cards)
.ThenInclude(x => x.Card)
.ToList()
.Select(x => x.GetViewModel)
if (clientId == null)
{
return context.Requests
.Include(x => x.Cards)
.ThenInclude(x => x.Card)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
return context.CardRequests
.Include(x => x.Card)
.Include(x => x.Request)
.Where(x => x.Card.ClientId == clientId)
.Select(x => x.Request.GetViewModel).Distinct()
.ToList();
}
public List<RequestViewModel> GetFilteredList(RequestSearchModel model)
@ -39,7 +49,7 @@ namespace BankDatabaseImplement.Implements
{
if (!model.Id.HasValue) return null;
using var context = new BankDatabase();
return context.Requests.Include(x => x.Cards).ThenInclude(x => x.Card)
return context.Requests.Include(x => x.Cards).ThenInclude(x => x.Card).ToList()
.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public RequestViewModel? Insert(RequestBindingModel model)
@ -60,11 +70,14 @@ namespace BankDatabaseImplement.Implements
using var transaction = context.Database.BeginTransaction();
try
{
var Request = context.Requests.FirstOrDefault(rec =>
rec.Id == model.Id);
var Request = context.Requests.FirstOrDefault(rec => rec.Id == model.Id);
if (Request == null)
{
return null;
throw new Exception("Заявка не найдена");
}
if (Request.Status != RequestStatus.Принята)
{
throw new InvalidOperationException("Заявка уже выполнена");
}
Request.Update(model);
context.SaveChanges();
@ -84,6 +97,10 @@ namespace BankDatabaseImplement.Implements
var element = context.Requests
.Include(x => x.Cards)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element?.Status != RequestStatus.Принята)
{
throw new InvalidOperationException("Заявка уже выполнена");
}
if (element != null)
{
context.Requests.Remove(element);

View File

@ -33,6 +33,7 @@ namespace BankDatabaseImplement.Implements
.Include(x => x.Operation)
.Where(x =>
(!model.Id.HasValue || x.Id == model.Id) &&
(!model.ManagerId.HasValue || (x.SenderAccount != null && x.SenderAccount.ManagerId == model.ManagerId)) &&
(!model.SenderAccountId.HasValue || x.SenderAccountId == model.SenderAccountId) &&
(!model.RecipientAccountId.HasValue || x.RecipientAccountId == model.RecipientAccountId) &&
(!model.OperationId.HasValue || x.OperationId == model.OperationId) &&
@ -54,51 +55,119 @@ namespace BankDatabaseImplement.Implements
.GetViewModel;
}
public TransferViewModel? Insert(TransferBindingModel model)
{
var newTransfer = Transfer.Create(model);
if (newTransfer == null)
{
return null;
}
using var context = new BankDatabase();
context.Transfers.Add(newTransfer);
context.SaveChanges();
return newTransfer.GetViewModel;
}
public TransferViewModel? Insert(TransferBindingModel model)
{
var newTransfer = Transfer.Create(model);
if (newTransfer == null)
return null;
using var context = new BankDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
MakeTransfer(context, model);
context.Transfers.Add(newTransfer);
context.SaveChanges();
}
catch
{
transaction.Rollback();
throw;
}
transaction.Commit();
return newTransfer.GetViewModel;
}
public TransferViewModel? Update(TransferBindingModel model)
public TransferViewModel? Update(TransferBindingModel model)
{
using var context = new BankDatabase();
var operation = context.Transfers
.Include(x => x.SenderAccount)
.Include(x => x.RecipientAccount)
.Include(x => x.Operation)
.FirstOrDefault(x => x.Id == model.Id);
if (operation == null)
{
var oldTransfer = context.Transfers.FirstOrDefault(x => x.Id == model.Id);
if (oldTransfer == null)
return null;
}
operation.Update(model);
context.SaveChanges();
return operation.GetViewModel;
using var transaction = context.Database.BeginTransaction();
try
{
RejectTransfer(context, new TransferBindingModel
{
RecipientAccountId = oldTransfer.RecipientAccountId,
SenderAccountId = oldTransfer.SenderAccountId,
Sum = oldTransfer.Sum,
});
MakeTransfer(context, model);
oldTransfer.Update(model);
context.SaveChanges();
}
catch
{
transaction.Rollback();
throw;
}
transaction.Commit();
return oldTransfer.GetViewModel;
}
public TransferViewModel? Delete(TransferBindingModel model)
{
using var context = new BankDatabase();
var transfer = context.Transfers
.Include(x => x.SenderAccount)
.Include(x => x.RecipientAccount)
.Include(x => x.Operation)
.FirstOrDefault(rec => rec.Id == model.Id);
if (transfer != null)
{
context.Transfers.Remove(transfer);
context.SaveChanges();
return transfer.GetViewModel;
}
return null;
}
}
var oldTransfer = context.Transfers.FirstOrDefault(rec => rec.Id == model.Id);
if (oldTransfer == null)
return null;
using var transaction = context.Database.BeginTransaction();
try
{
RejectTransfer(context, new TransferBindingModel
{
RecipientAccountId = oldTransfer.RecipientAccountId,
SenderAccountId = oldTransfer.SenderAccountId,
Sum = oldTransfer.Sum,
});
context.Transfers.Remove(oldTransfer);
context.SaveChanges();
}
catch
{
transaction.Rollback();
throw;
}
transaction.Commit();
return oldTransfer.GetViewModel;
}
private void MakeTransfer(BankDatabase context, TransferBindingModel model)
{
TransferMoney(context, model.RecipientAccountId, model.SenderAccountId, model.Sum);
}
private void RejectTransfer(BankDatabase context, TransferBindingModel model)
{
TransferMoney(context, model.SenderAccountId, model.RecipientAccountId, model.Sum);
}
private void TransferMoney(BankDatabase context, int recipientId, int senderId, int sum)
{
Account? sender = context.Accounts.FirstOrDefault(x => x.Id == senderId);
if (sender == null)
throw new InvalidOperationException("Sender account was not found");
if (sender.Money < sum)
throw new InvalidOperationException("Sender account did not have enough money");
Account? recipient = context.Accounts.FirstOrDefault(x => x.Id == recipientId);
if (recipient == null)
throw new InvalidOperationException("Recipient account was not found");
sender.Update(new AccountBindingModel
{
Id = sender.Id,
Number = sender.Number,
ReleaseDate = sender.ReleaseDate,
ManagerId = sender.ManagerId,
Money = sender.Money - sum,
});
recipient.Update(new AccountBindingModel
{
Id = recipient.Id,
Number = recipient.Number,
ReleaseDate = recipient.ReleaseDate,
ManagerId = recipient.ManagerId,
Money = recipient.Money + sum,
});
}
}
}

View File

@ -3,6 +3,7 @@ using BankContracts.SearchModels;
using BankContracts.StoragesContracts;
using BankContracts.ViewModels;
using BankDatabaseImplement.Models;
using BankDataModels.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
@ -21,7 +22,6 @@ namespace BankDatabaseImplement.Implements
.Include(x => x.Request)
.Include(x => x.Accounts)
.ThenInclude(x => x.Account)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
@ -29,19 +29,33 @@ namespace BankDatabaseImplement.Implements
public List<WithdrawalViewModel> GetFilteredList(WithdrawalSearchModel model)
{
using var context = new BankDatabase();
return context.Withdrawals
.Include(x => x.Request)
.Include(x => x.Accounts)
.ThenInclude(x => x.Account)
.Where(x =>
(!model.Id.HasValue || x.Id == model.Id) &&
(!model.RequestId.HasValue || x.RequestId == model.RequestId) &&
(!model.DateFrom.HasValue || x.WithdrawalTime >= model.DateFrom) &&
(!model.DateTo.HasValue || x.WithdrawalTime <= model.DateTo))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
if (model.ManagerId == null)
return context.Withdrawals
.Include(x => x.Request)
.Include(x => x.Accounts)
.ThenInclude(x => x.Account)
.Where(x =>
(!model.Id.HasValue || x.Id == model.Id) &&
(!model.RequestId.HasValue || x.RequestId == model.RequestId) &&
(!model.DateFrom.HasValue || x.WithdrawalTime >= model.DateFrom) &&
(!model.DateTo.HasValue || x.WithdrawalTime <= model.DateTo))
.Select(x => x.GetViewModel)
.ToList();
return context.AccountWithdrawals
.Include(x => x.Account)
.Include (x => x.Withdrawal)
.ThenInclude(x => x.Accounts)
.Where(x => x.Account.ManagerId == model.ManagerId)
.Select(x => x.Withdrawal)
.Distinct()
.Where(x =>
(!model.Id.HasValue || x.Id == model.Id) &&
(!model.RequestId.HasValue || x.RequestId == model.RequestId) &&
(!model.DateFrom.HasValue || x.WithdrawalTime >= model.DateFrom) &&
(!model.DateTo.HasValue || x.WithdrawalTime <= model.DateTo))
.Select(x => x.GetViewModel)
.ToList();
}
public WithdrawalViewModel? GetElement(WithdrawalSearchModel model)
{
@ -59,56 +73,139 @@ namespace BankDatabaseImplement.Implements
public WithdrawalViewModel? Insert(WithdrawalBindingModel model)
{
using var context = new BankDatabase();
var newWithdrawal = Withdrawal.Create(context, model);
if (newWithdrawal == null)
using var transaction = context.Database.BeginTransaction();
Withdrawal? newWithdrawal;
try
{
return null;
newWithdrawal = Withdrawal.Create(context, model);
if (newWithdrawal == null)
throw new InvalidOperationException("Error during creating new withdrawal");
context.Withdrawals.Add(newWithdrawal);
context.SaveChanges();
}
context.Withdrawals.Add(newWithdrawal);
context.SaveChanges();
return newWithdrawal.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
transaction.Commit();
return newWithdrawal.GetViewModel;
}
public WithdrawalViewModel? Update(WithdrawalBindingModel model)
{
using var context = new BankDatabase();
using var transaction = context.Database.BeginTransaction();
Withdrawal? withdrawal;
try
{
var Withdrawal = context.Withdrawals.FirstOrDefault(rec =>
rec.Id == model.Id);
if (Withdrawal == null)
{
return null;
}
Withdrawal.Update(model);
withdrawal = context.Withdrawals.FirstOrDefault(x => x.Id == model.Id);
if (withdrawal == null)
throw new InvalidOperationException("Updating withdrawal was not found");
if (withdrawal.RequestId != null)
throw new InvalidOperationException("Update was rejected: withdrawal was done");
withdrawal.Update(model);
withdrawal.UpdateAccounts(context, model);
context.SaveChanges();
Withdrawal.UpdateAccounts(context, model);
transaction.Commit();
return Withdrawal.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
transaction.Commit();
return withdrawal.GetViewModel;
}
public WithdrawalViewModel? Delete(WithdrawalBindingModel model)
public WithdrawalViewModel? LinkToRequest(int withdrawalId, int requestId)
{
if (requestId <= 0 || withdrawalId <= 0)
throw new InvalidOperationException("Id must be positive number");
using var context = new BankDatabase();
using var transaction = context.Database.BeginTransaction();
Withdrawal? withdrawal;
try
{
withdrawal = context.Withdrawals.Include(x => x.Accounts).FirstOrDefault(x => x.Id == withdrawalId);
if (withdrawal == null)
throw new InvalidOperationException("Withdrawal was not found");
var request = context.Requests.FirstOrDefault(x => x.Id == requestId);
if (request == null)
throw new InvalidOperationException("Request was not found");
WithdrawalBindingModel model = new WithdrawalBindingModel
{
Id = withdrawal.Id,
WithdrawalAccounts = withdrawal.WithdrawalAccounts,
Sum = request.Sum,
};
MakeWithdrawal(context, model);
withdrawal.LinkToRequest(requestId);
if (!request.Execute())
throw new InvalidOperationException("Request was not executed");
withdrawal.UpdateAccounts(context, model);
context.SaveChanges();
}
catch
{
transaction.Rollback();
throw;
}
transaction.Commit();
return withdrawal.GetViewModel;
}
public WithdrawalViewModel? Delete(WithdrawalBindingModel model)
{
using var context = new BankDatabase();
var element = context.Withdrawals
var withdrawal = context.Withdrawals
.Include(x => x.Request)
.Include(x => x.Accounts)
.ThenInclude(x => x.Account)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Withdrawals.Remove(element);
if (withdrawal != null)
{
if (withdrawal.RequestId != null)
throw new InvalidOperationException("Deletion was rejected: withdrawal was done");
context.Withdrawals.Remove(withdrawal);
context.SaveChanges();
return element.GetViewModel;
return withdrawal.GetViewModel;
}
return null;
}
}
}
private void MakeWithdrawal(BankDatabase context, WithdrawalBindingModel model)
{
if (model == null)
throw new ArgumentNullException(nameof(model));
int count = model.Sum;
if (count == 0)
return;
var dictionary = model.WithdrawalAccounts;
var keys = dictionary.Keys;
foreach (int key in keys)
{
var value = dictionary[key];
Account account = context.Accounts.FirstOrDefault(x => x.Id == key) ??
throw new InvalidOperationException("Needed account was not found");
int dif = count;
if (account.Money < dif)
dif = account.Money;
value.Item2 = dif;
dictionary[key] = value;
count -= dif;
account.Update(new AccountBindingModel
{
Id = account.Id,
Number = account.Number,
ReleaseDate = account.ReleaseDate,
ManagerId = account.ManagerId,
Money = account.Money - dif,
});
if (count == 0)
break;
}
if (count > 0)
throw new InvalidOperationException("The accounts did not have enough money");
}
}
}

View File

@ -47,7 +47,7 @@ namespace BankDatabaseImplement.Migrations
b.HasIndex("ManagerId");
b.ToTable("Accounts");
b.ToTable("Accounts", (string)null);
});
modelBuilder.Entity("BankDatabaseImplement.Models.AccountWithdrawal", b =>
@ -73,7 +73,7 @@ namespace BankDatabaseImplement.Migrations
b.HasIndex("WithdrawalId");
b.ToTable("AccountWithdrawals");
b.ToTable("AccountWithdrawals", (string)null);
});
modelBuilder.Entity("BankDatabaseImplement.Models.Card", b =>
@ -109,7 +109,7 @@ namespace BankDatabaseImplement.Migrations
b.HasIndex("ClientId");
b.ToTable("Cards");
b.ToTable("Cards", (string)null);
});
modelBuilder.Entity("BankDatabaseImplement.Models.CardRequest", b =>
@ -132,7 +132,7 @@ namespace BankDatabaseImplement.Migrations
b.HasIndex("RequestId");
b.ToTable("CardRequests");
b.ToTable("CardRequests", (string)null);
});
modelBuilder.Entity("BankDatabaseImplement.Models.Client", b =>
@ -157,7 +157,7 @@ namespace BankDatabaseImplement.Migrations
b.HasKey("Id");
b.ToTable("Clients");
b.ToTable("Clients", (string)null);
});
modelBuilder.Entity("BankDatabaseImplement.Models.Manager", b =>
@ -182,7 +182,7 @@ namespace BankDatabaseImplement.Migrations
b.HasKey("Id");
b.ToTable("Managers");
b.ToTable("Managers", (string)null);
});
modelBuilder.Entity("BankDatabaseImplement.Models.Operation", b =>
@ -212,7 +212,7 @@ namespace BankDatabaseImplement.Migrations
b.HasIndex("SenderCardId");
b.ToTable("Operations");
b.ToTable("Operations", (string)null);
});
modelBuilder.Entity("BankDatabaseImplement.Models.Request", b =>
@ -234,7 +234,7 @@ namespace BankDatabaseImplement.Migrations
b.HasKey("Id");
b.ToTable("Requests");
b.ToTable("Requests", (string)null);
});
modelBuilder.Entity("BankDatabaseImplement.Models.Transfer", b =>
@ -270,7 +270,7 @@ namespace BankDatabaseImplement.Migrations
b.HasIndex("SenderAccountId");
b.ToTable("Transfers");
b.ToTable("Transfers", (string)null);
});
modelBuilder.Entity("BankDatabaseImplement.Models.Withdrawal", b =>
@ -293,7 +293,7 @@ namespace BankDatabaseImplement.Migrations
.IsUnique()
.HasFilter("[RequestId] IS NOT NULL");
b.ToTable("Withdrawals");
b.ToTable("Withdrawals", (string)null);
});
modelBuilder.Entity("BankDatabaseImplement.Models.Account", b =>

View File

@ -40,14 +40,15 @@ namespace BankDatabaseImplement.Models
public static Card? Create(CardBindingModel model)
{
if (model == null) return null;
DateTime tmp = DateTime.Now;
return new Card
{
Id = model.Id,
Number = model.Number,
Cvv = model.Cvv,
Pin = model.Pin,
ReleaseDate = DateTime.Now,
ExpirationDate = DateTime.Now.AddYears(3),
ReleaseDate = new DateTime(tmp.Year, tmp.Month, tmp.Day, tmp.Hour, tmp.Minute, 0, tmp.Kind),
ExpirationDate = new DateTime(tmp.Year + 3, tmp.Month, tmp.Day, tmp.Hour, tmp.Minute, 0, tmp.Kind),
ClientId = model.ClientId,
};
}
@ -58,7 +59,6 @@ namespace BankDatabaseImplement.Models
Number = model.Number;
Cvv = model.Cvv;
Pin = model.Pin;
ReleaseDate = model.ReleaseDate;
ExpirationDate = model.ExpirationDate;
ClientId = model.ClientId;
}

View File

@ -25,7 +25,7 @@ namespace BankDatabaseImplement.Models
[Required]
public int RecipientCardId { get; set; }
public virtual Card? RecipientCard { get; private set; }
public virtual Transfer? Transfer { get; private set; }
public virtual Transfer? Transfer { get; private set; } = null;
public static Operation? Create(OperationBindingModel model)
{
@ -44,10 +44,9 @@ namespace BankDatabaseImplement.Models
{
if (model == null) return;
Sum = model.Sum;
OperationTime = model.OperationTime;
SenderCardId = model.SenderCardId;
RecipientCardId = model.RecipientCardId;
}
}
public OperationViewModel GetViewModel => new()
{
@ -58,6 +57,7 @@ namespace BankDatabaseImplement.Models
RecipientCardId = RecipientCardId,
SenderCardNumber = SenderCard?.Number ?? string.Empty,
RecipientCardNumber = RecipientCard?.Number ?? string.Empty,
TransferId = Transfer?.Id,
};
}
}

View File

@ -31,7 +31,7 @@ namespace BankDatabaseImplement.Models
{
if (_cardRequests == null)
{
_cardRequests = Cards.ToDictionary(recPC => recPC.CardId, recPC => recPC.Card as ICardModel);
_cardRequests = Cards.ToDictionary(card => card.CardId, card => card.Card as ICardModel);
}
return _cardRequests;
}
@ -55,8 +55,16 @@ namespace BankDatabaseImplement.Models
public void Update(RequestBindingModel model)
{
Sum = model.Sum;
RequestTime = model.RequestTime;
Status = model.Status;
}
public bool Execute()
{
if(Status == RequestStatus.Принята)
{
Status = RequestStatus.Выполнена;
return true;
}
return false;
}
public RequestViewModel GetViewModel => new()
@ -70,11 +78,16 @@ namespace BankDatabaseImplement.Models
public void UpdateCards(BankDatabase context, RequestBindingModel model)
{
var CardRequests = context.CardRequests.Where(rec => rec.RequestId == model.Id).ToList();
var CardRequests = context.CardRequests.Where(rec => rec.RequestId == model.Id).Distinct().ToList();
if (CardRequests != null && CardRequests.Count > 0)
{ // удалили те, которых нет в модели
context.CardRequests.RemoveRange(CardRequests.Where(rec => !model.CardRequests.ContainsKey(rec.CardId)));
context.SaveChanges();
foreach (var updateCards in CardRequests)
{
model.CardRequests.Remove(updateCards.CardId);
}
context.SaveChanges();
}
var Request = context.Requests.First(x => x.Id == Id);
foreach (var request in model.CardRequests)

View File

@ -36,7 +36,19 @@ namespace BankDatabaseImplement.Models
return _withdrawalAccounts;
}
}
[NotMapped]
public int Sum
{
get
{
int sum = 0;
foreach (var account in Accounts)
{
sum += account.Sum;
}
return sum;
}
}
public static Withdrawal Create(BankDatabase context, WithdrawalBindingModel model)
{
return new Withdrawal
@ -53,7 +65,11 @@ namespace BankDatabaseImplement.Models
public void Update(WithdrawalBindingModel model)
{
WithdrawalTime = model.WithdrawalTime;
RequestId = model.RequestId;
}
public void LinkToRequest(int requestId)
{
RequestId = requestId;
}
public WithdrawalViewModel GetViewModel => new()
@ -62,7 +78,7 @@ namespace BankDatabaseImplement.Models
WithdrawalTime = WithdrawalTime,
WithdrawalAccounts = WithdrawalAccounts,
RequestId = RequestId,
Sum = Request?.Sum,
Sum = Sum,
};
public void UpdateAccounts(BankDatabase context, WithdrawalBindingModel model)
@ -72,13 +88,20 @@ namespace BankDatabaseImplement.Models
{
context.AccountWithdrawals.RemoveRange(WithdrawalAccounts.Where(rec => !model.WithdrawalAccounts.ContainsKey(rec.AccountId)));
context.SaveChanges();
}
var Withdrawal = context.Withdrawals.First(x => x.Id == Id);
WithdrawalAccounts = context.AccountWithdrawals.Where(rec => rec.WithdrawalId == model.Id).ToList();
foreach (var wa in WithdrawalAccounts)
{
wa.Sum = model.WithdrawalAccounts[wa.AccountId].Item2;
model.WithdrawalAccounts.Remove(wa.AccountId);
}
context.SaveChanges();
}
var withdrawal = context.Withdrawals.First(x => x.Id == Id);
foreach (var account in model.WithdrawalAccounts)
{
context.AccountWithdrawals.Add(new AccountWithdrawal
{
Withdrawal = Withdrawal,
Withdrawal = withdrawal,
Account = context.Accounts.First(x => x.Id == account.Key),
Sum = account.Value.Item2,
});

View File

@ -1,18 +1,48 @@
using BankContracts.ViewModels;
using BankDatabaseImplement.Models;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
namespace BankManagersClientApp
{
public static class APIClient
{
private static readonly HttpClient _manager = new();
public static ManagerViewModel? Manager { get; set; } = null;
private static readonly HttpClient _client = new();
public static ManagerViewModel? Client { get; set; } = null;
public static void Connect(IConfiguration configuration)
{
_manager.BaseAddress = new Uri(configuration["IPAddress"]);
_manager.DefaultRequestHeaders.Accept.Clear();
_manager.DefaultRequestHeaders.Accept.Add(new
_client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
}
public static T? GetRequest<T>(string requestUrl)
{
var response = _client.GetAsync(requestUrl);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>(result);
}
else
{
throw new Exception(result);
}
}
public static void PostRequest<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode)
{
throw new Exception(result);
}
}
}
}

View File

@ -6,6 +6,10 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BankContracts\BankContracts.csproj" />
<ProjectReference Include="..\BankRestApi\BankRestApi.csproj" />

View File

@ -1,6 +1,12 @@
using BankManagersClientApp.Models;
using BankContracts.BindingModels;
using BankContracts.SearchModels;
using BankContracts.ViewModels;
using BankDatabaseImplement.Models;
using BankDataModels.Models;
using BankManagersClientApp.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Globalization;
namespace BankManagersClientApp.Controllers
{
@ -13,173 +19,674 @@ namespace BankManagersClientApp.Controllers
_logger = logger;
}
#region//работа с аккаунтом
#region//Managers
[HttpGet]
public IActionResult Privacy()
{
if (APIClient.Manager == null)
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.Manager);
return View(APIClient.Client);
}
public IActionResult Register()
[HttpPost]
public void Privacy(string login, string password, string fio)
{
return View();
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{
throw new Exception("Введите логин, пароль и ФИО");
}
APIClient.PostRequest("api/manager/updatemanager", new ManagerBindingModel
{
Id = APIClient.Client.Id,
Fio = fio,
Email = login,
Password = password
});
APIClient.Client.Fio = fio;
APIClient.Client.Email = login;
APIClient.Client.Password = password;
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public void Register(string login, string password, string fio)
{
if (string.IsNullOrEmpty(login) ||
string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
{
throw new Exception("Введите логин, пароль и ФИО");
}
APIClient.PostRequest("api/manager/createmanager", new ManagerBindingModel
{
Fio = fio,
Email = login,
Password = password
});
Response.Redirect("Enter");
return;
}
[HttpGet]
public IActionResult Enter()
{
return View();
}
[HttpPost]
public void Enter(string login, string password)
{
if (string.IsNullOrEmpty(login) ||
string.IsNullOrEmpty(password))
{
throw new Exception("Введите логин и пароль");
}
APIClient.Client = APIClient.GetRequest<ManagerViewModel>($"api/manager/login?login={login}&password={password}");
if (APIClient.Client == null)
{
throw new Exception("Неверный логин/пароль");
}
Response.Redirect("Index");
}
#endregion
#region//работа со счетами
#region//Accounts
[HttpGet]
public IActionResult Index()
{
if (APIClient.Manager == null)
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<AccountViewModel>>($"api/account/getaccountlist?managerid={APIClient.Client.Id}"));
}
[HttpGet]
public IActionResult AccountCreate()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
public IActionResult AccountCreate()
{
if (APIClient.Manager == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
[HttpPost]
public void AccountCreate(string number)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest("api/account/createaccount", new
AccountBindingModel
{
ManagerId = APIClient.Client.Id,
Number = number
});
Response.Redirect("Index");
}
[HttpGet]
public IActionResult AccountUpdate()
{
if (APIClient.Manager == null)
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Accounts = APIClient.GetRequest<List<AccountViewModel>>($"api/account/getaccountlist?managerid={APIClient.Client.Id}");
return View();
}
[HttpPost]
public void AccountUpdate(int account, string number, int money)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest("api/account/updateaccount", new
AccountBindingModel
{
Id = account,
ManagerId = APIClient.Client.Id,
Number = number,
Money = money
});
Response.Redirect("Index");
}
[HttpGet]
public AccountViewModel? GetAccount(int accountId)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
var result = APIClient.GetRequest<AccountViewModel>($"api/account/getaccount?accountid={accountId}");
if (result == null)
{
return default;
}
return result;
}
[HttpGet]
public IActionResult AccountDelete()
{
if (APIClient.Manager == null)
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Accounts = APIClient.GetRequest<List<AccountViewModel>>($"api/account/getaccountlist?managerid={APIClient.Client.Id}");
return View();
}
[HttpPost]
public void AccountDelete(int account)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest("api/account/deleteaccount", new
AccountBindingModel
{
Id = account,
});
Response.Redirect("Index");
}
#endregion
#region//работа с переводами
#region//Transfers
[HttpGet]
public IActionResult Transfers()
{
if (APIClient.Manager == null)
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<TransferViewModel>>($"api/transfer/gettransferlist?managerid={APIClient.Client.Id}"));
}
[HttpGet]
public IActionResult TransferCreate()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.SenderAccounts = APIClient.GetRequest<List<AccountViewModel>>($"api/account/getaccountlist?managerid={APIClient.Client.Id}");
ViewBag.RecipientAccounts = APIClient.GetRequest<List<AccountViewModel>>("api/account/getaccountlist");
return View();
}
[HttpPost]
public void TransferCreate(int sum, int senderaccount, int recipientaccount)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (senderaccount == recipientaccount)
throw new Exception("Зачем в отправителе и получателе один и тот же счёт указали??? Думаете нам в банке заняться нечем?");
APIClient.PostRequest("api/transfer/createtransfer", new TransferBindingModel
{
Sum = sum,
SenderAccountId = senderaccount,
RecipientAccountId = recipientaccount,
});
Response.Redirect("Transfers");
}
[HttpGet]
public IActionResult TransferUpdate()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Transfers = APIClient.GetRequest<List<TransferViewModel>>($"api/transfer/gettransferlist?managerid={APIClient.Client.Id}");
ViewBag.SenderAccounts = APIClient.GetRequest<List<AccountViewModel>>($"api/account/getaccountlist?managerid={APIClient.Client.Id}");
ViewBag.RecipientAccounts = APIClient.GetRequest<List<AccountViewModel>>("api/account/getaccountlist");
return View();
}
[HttpPost]
public void TransferUpdate(int transfer, int sum, int senderaccount, int recipientaccount)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
if (senderaccount == recipientaccount)
{
throw new Exception("Зачем в отправителе и получателе один и тот же счёт указали??? Думаете нам в банке заняться нечем?");
}
APIClient.PostRequest("api/transfer/updatetransfer", new TransferBindingModel
{
Id = transfer,
Sum = sum,
SenderAccountId = senderaccount,
RecipientAccountId = recipientaccount,
});
Response.Redirect("Transfers");
}
[HttpGet]
public TransferViewModel? GetTransfer(int transferId)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
var result = APIClient.GetRequest<TransferViewModel>($"api/transfer/gettransfer?transferid={transferId}");
if (result == null)
{
return default;
}
return result;
}
[HttpGet]
public IActionResult TransferDelete()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Transfers = APIClient.GetRequest<List<TransferViewModel>>($"api/transfer/gettransferlist?managerid={APIClient.Client.Id}");
return View();
}
[HttpPost]
public void TransferDelete(int transfer)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest("api/transfer/deletetransfer", new TransferBindingModel
{
Id = transfer,
});
Response.Redirect("Transfers");
}
#endregion
#region//Withdrawals
[HttpGet]
public IActionResult Withdrawals()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequest<List<WithdrawalViewModel>>($"api/withdrawal/getwithdrawallist?managerid={APIClient.Client.Id}"));
}
[HttpGet]
public IActionResult WithdrawalCreate()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Accounts = APIClient.GetRequest<List<AccountViewModel>>($"api/account/getaccountlist?managerid={APIClient.Client.Id}");
return View();
}
public IActionResult TransferCreate()
[HttpPost]
public void WithdrawalCreate(List<int> accounts)
{
if (APIClient.Manager == null)
if (APIClient.Client == null)
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
Dictionary<int, (IAccountModel, int)> accountsDictionary = new();
foreach (int account in accounts)
{
accountsDictionary.Add(account, (new AccountBindingModel { Id = account }, 0));
}
APIClient.PostRequest("/api/withdrawal/createwithdrawal", new WithdrawalBindingModel
{
Sum = 0,
WithdrawalAccounts = accountsDictionary,
});
Response.Redirect("Withdrawals");
}
[HttpGet]
public IActionResult WithdrawalUpdate()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Withdrawals = APIClient.GetRequest<List<WithdrawalViewModel>>($"api/withdrawal/getwithdrawallist?managerid={APIClient.Client.Id}");
ViewBag.Accounts = APIClient.GetRequest<List<AccountViewModel>>($"api/account/getaccountlist?managerid={APIClient.Client.Id}");
return View();
}
[HttpPost]
public void WithdrawalUpdate(int withdrawal, List<int> accounts)
{
if (APIClient.Client == null)
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
Dictionary<int, (IAccountModel, int)> dictionary = new();
foreach (int account in accounts)
{
dictionary.Add(account, (new AccountBindingModel
{
Id = account,
}, 0));
}
APIClient.PostRequest("/api/withdrawal/updatewithdrawal", new WithdrawalBindingModel
{
Id = withdrawal,
Sum = 0,
WithdrawalAccounts = dictionary,
});
Response.Redirect("Withdrawals");
}
[HttpGet]
public WithdrawalViewModel? GetWithdrawal(int withdrawalId)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
var result = APIClient.GetRequest<WithdrawalViewModel>($"api/withdrawal/getwithdrawal?withdrawalid={withdrawalId}");
if (result == null)
{
return default;
}
return result;
}
[HttpGet]
public List<int> GetAccounts(int withdrawalId)
{
if (APIClient.Client == null)
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
return APIClient.GetRequest<List<int>>($"api/account/getaccounts?withdrawalId={withdrawalId}") ?? new();
}
[HttpGet]
public IActionResult WithdrawalDelete()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
ViewBag.Withdrawals = APIClient.GetRequest<List<WithdrawalViewModel>>($"api/withdrawal/getwithdrawallist?managerid={APIClient.Client.Id}");
return View();
}
[HttpPost]
public void WithdrawalDelete(int withdrawal)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
APIClient.PostRequest("api/withdrawal/deletewithdrawal", new WithdrawalBindingModel
{
Id = withdrawal,
});
Response.Redirect("Withdrawals");
}
[HttpGet]
public IActionResult WithdrawalRequest(int? withdrawal, int? request)
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
public IActionResult TransferUpdate()
{
if (APIClient.Manager == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
public IActionResult TransferDelete()
{
if (APIClient.Manager == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
#endregion
#region//работа с выдачами
public IActionResult Withdrawals()
{
if (APIClient.Manager == null)
if (request != null && withdrawal != null)
{
return Redirect("~/Home/Enter");
APIClient.GetRequest<bool>($"api/withdrawal/linkwithdrawalrequest?withdrawalid={withdrawal}&requestid={request}");
return Redirect("Withdrawals");
}
ViewBag.Withdrawals = APIClient.GetRequest<List<WithdrawalViewModel>>($"api/withdrawal/getwithdrawallist?managerid={APIClient.Client.Id}");
ViewBag.Requests = APIClient.GetRequest<List<RequestViewModel>>($"api/request/getrequestlist");
return View();
}
}
#endregion
public IActionResult WithdrawalCreate()
#region//Reports
[HttpGet]
public IActionResult RequestsListReport()
{
if (APIClient.Manager == null)
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
ViewBag.Accounts = APIClient.GetRequest<List<AccountViewModel>>($"api/account/getaccountlist?managerid={APIClient.Client.Id}");
return View();
}
public IActionResult WithdrawalUpdate()
{
if (APIClient.Manager == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
public IActionResult WithdrawalDelete()
{
if (APIClient.Manager == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
public IActionResult WithdrawalRequest()
[HttpPost]
public void RequestsListReport(string format, List<int> accounts)
{
if (APIClient.Manager == null)
if (APIClient.Client == null)
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
switch (format)
{
return Redirect("~/Home/Enter");
case "word":
APIClient.PostRequest("/api/report/saverequeststoword", new ReportBindingModel
{
SelectedAccountIds = accounts,
FileName = "C:\\forpdf\\wordfile.docx",
});
Response.Redirect("ReportWord");
break;
case "excel":
APIClient.PostRequest("/api/report/saverequeststoexcel", new ReportBindingModel
{
SelectedAccountIds = accounts,
FileName = "C:\\forpdf\\excelfile.xlsx",
});
Response.Redirect("ReportExcel");
break;
default:
break;
}
return View();
}
#endregion
}
#region//работа с отчётами
public IActionResult RequestsListReport()
[HttpGet]
public IActionResult ReportWord()
{
return new PhysicalFileResult("C:\\forpdf\\wordfile.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
}
[HttpGet]
public IActionResult ReportExcel()
{
return new PhysicalFileResult("C:\\forpdf\\excelfile.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
[HttpGet]
public IActionResult TransfersWithdrawalsListReport()
{
if (APIClient.Manager == null)
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
public IActionResult TransfersWithdrawalsListReport()
[HttpPost]
public void TransfersWithdrawalsListReport(DateTime dateFrom, DateTime dateTo)
{
if (APIClient.Manager == null)
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
return View();
}
#endregion
APIClient.PostRequest("api/report/sendtransferswithdrawalstoemail", new ReportBindingModel
{
FileName = "C:\\forpdf\\pdffile.pdf",
DateFrom = dateFrom,
DateTo = dateTo,
Email = APIClient.Client.Email,
});
Response.Redirect("Index");
}
#region//ошибка
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[HttpGet]
public string GetTransfersWithdrawals(DateTime dateFrom, DateTime dateTo)
{
if (APIClient.Client == null)
{
throw new Exception("Вы как суда попали? Суда вход только авторизованным");
}
List<ReportTransfersWithdrawalsViewModel> result;
try
{
string dateFromS = dateFrom.ToString("s", CultureInfo.InvariantCulture);
string dateToS = dateTo.ToString("s", CultureInfo.InvariantCulture);
result = APIClient.GetRequest<List<ReportTransfersWithdrawalsViewModel>>
($"api/report/gettransferswithdrawals?datefrom={dateFromS}&dateto={dateToS}")!;
}
catch
{
_logger.LogError("Ошибка создания отчета");
throw;
}
//sender transfers
string senderTransfersTable = "";
senderTransfersTable += "<h2 class=\"text-custom-color-1\">Переводы на другие счета</h2>";
senderTransfersTable += "<div class=\"table-responsive\">";
senderTransfersTable += "<table class=\"table table-striped table-bordered table-hover\">";
senderTransfersTable += "<thead class=\"table-dark\">";
senderTransfersTable += "<tr>";
senderTransfersTable += "<th scope=\"col\">Номер счёта</th>";
senderTransfersTable += "<th scope=\"col\">Номер перевода</th>";
senderTransfersTable += "<th scope=\"col\">Время перевода</th>";
senderTransfersTable += "<th scope=\"col\">Сумма</th>";
senderTransfersTable += "<th scope=\"col\">Номер счёта получателя</th>";
senderTransfersTable += "</tr>";
senderTransfersTable += "</thead>";
senderTransfersTable += "<tbody>";
foreach (var report in result)
{
senderTransfersTable += "<tr>";
senderTransfersTable += $"<td>{report.AccountNumber}</td>";
senderTransfersTable += $"<td></td>";
senderTransfersTable += $"<td></td>";
senderTransfersTable += $"<td></td>";
senderTransfersTable += $"<td></td>";
senderTransfersTable += "</tr>";
foreach (var senderTransfer in report.SenderTransfers)
{
senderTransfersTable += "<tr>";
senderTransfersTable += $"<td></td>";
senderTransfersTable += $"<td>{senderTransfer.Id}</td>";
senderTransfersTable += $"<td>{senderTransfer.TransferTime}</td>";
senderTransfersTable += $"<td>{senderTransfer.Sum}</td>";
senderTransfersTable += $"<td>{senderTransfer.RecipientAccountNumber}</td>";
senderTransfersTable += "</tr>";
}
}
senderTransfersTable += "</tbody>";
senderTransfersTable += "</table>";
senderTransfersTable += "</div>";
//recipient transfers
string recipientTransfersTable = "";
recipientTransfersTable += "<h2 class=\"text-custom-color-1\">Переводы с других счетов</h2>";
recipientTransfersTable += "<div class=\"table-responsive\">";
recipientTransfersTable += "<table class=\"table table-striped table-bordered table-hover\">";
recipientTransfersTable += "<thead class=\"table-dark\">";
recipientTransfersTable += "<tr>";
recipientTransfersTable += "<th scope=\"col\">Номер счёта</th>";
recipientTransfersTable += "<th scope=\"col\">Номер перевода</th>";
recipientTransfersTable += "<th scope=\"col\">Время перевода</th>";
recipientTransfersTable += "<th scope=\"col\">Сумма</th>";
recipientTransfersTable += "<th scope=\"col\">Номер счёта отправителя</th>";
recipientTransfersTable += "</tr>";
recipientTransfersTable += "</thead>";
recipientTransfersTable += "<tbody>";
foreach (var report in result)
{
recipientTransfersTable += "<tr>";
recipientTransfersTable += $"<td>{report.AccountNumber}</td>";
recipientTransfersTable += $"<td></td>";
recipientTransfersTable += $"<td></td>";
recipientTransfersTable += $"<td></td>";
recipientTransfersTable += $"<td></td>";
recipientTransfersTable += "</tr>";
foreach (var recipientTransfer in report.RecipientTransfers)
{
recipientTransfersTable += "<tr>";
recipientTransfersTable += $"<td></td>";
recipientTransfersTable += $"<td>{recipientTransfer.Id}</td>";
recipientTransfersTable += $"<td>{recipientTransfer.TransferTime}</td>";
recipientTransfersTable += $"<td>{recipientTransfer.Sum}</td>";
recipientTransfersTable += $"<td>{recipientTransfer.SenderAccountNumber}</td>";
recipientTransfersTable += "</tr>";
}
}
recipientTransfersTable += "</tbody>";
recipientTransfersTable += "</table>";
recipientTransfersTable += "</div>";
//withdrawals
string withdrawalsTable = "";
withdrawalsTable += "<h2 class=\"text-custom-color-1\">Выдачи наличных</h2>";
withdrawalsTable += "<div class=\"table-responsive\">";
withdrawalsTable += "<table class=\"table table-striped table-bordered table-hover\">";
withdrawalsTable += "<thead class=\"table-dark\">";
withdrawalsTable += "<tr>";
withdrawalsTable += "<th scope=\"col\">Номер счёта</th>";
withdrawalsTable += "<th scope=\"col\">Номер выдачи</th>";
withdrawalsTable += "<th scope=\"col\">Время выдачи</th>";
withdrawalsTable += "<th scope=\"col\">Сумма</th>";
withdrawalsTable += "</tr>";
withdrawalsTable += "</thead>";
withdrawalsTable += "<tbody>";
foreach (var report in result)
{
withdrawalsTable += "<tr>";
withdrawalsTable += $"<td>{report.AccountNumber}</td>";
withdrawalsTable += $"<td></td>";
withdrawalsTable += $"<td></td>";
withdrawalsTable += $"<td></td>";
withdrawalsTable += "</tr>";
foreach (var withdrawal in report.Withdrawals)
{
withdrawalsTable += "<tr>";
withdrawalsTable += $"<td></td>";
withdrawalsTable += $"<td>{withdrawal.Id}</td>";
withdrawalsTable += $"<td>{withdrawal.WithdrawalTime}</td>";
withdrawalsTable += $"<td>{withdrawal.Sum}</td>";
withdrawalsTable += "</tr>";
}
}
withdrawalsTable += "</tbody>";
withdrawalsTable += "</table>";
withdrawalsTable += "</div>";
//title
string tables = "";
tables += "<h2 class=\"text-custom-color-1\">Отчет по счетам</h2>";
tables += $"<div class=\"text-custom-color-1\">с {dateFrom.ToShortDateString()} по {dateTo.ToShortDateString()}</div>";
tables += senderTransfersTable;
tables += recipientTransfersTable;
tables += withdrawalsTable;
return tables;
}
#endregion
#region//Error
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });

View File

@ -6,11 +6,13 @@ namespace BankManagersClientApp
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
APIClient.Connect(builder.Configuration);
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{

View File

@ -7,14 +7,18 @@
</div>
<form method="post">
<div class="row">
<div class="col-4">Карта:</div>
<div class="col-4">Счёт:</div>
<div class="col-8">
<select id="account" name="account" class="form-control" asp-items="@(new SelectList(@ViewBag.Accounts, "Id", "Number"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Номер:</div>
<div class="col-8"><input type="text" name="number" id="number" class="form-control" /></div>
<div class="col-8"><input type="text" name="number" id="number" class="form-control" readonly /></div>
</div>
<div class="row">
<div class="col-4">Деньги:</div>
<div class="col-8"><input type="number" name="money" id="money" class="form-control" /></div>
</div>
<div class="row">
<div class="col-8"></div>
@ -33,7 +37,8 @@
url: "/Home/GetAccount",
data: { accountId: account },
success: function (result) {
$('#number').val(result.item1.number);
$('#number').val(result.number);
$('#money').val(result.money);
}
});
};

View File

@ -8,11 +8,6 @@
</div>
<div class="text-center">
@{
if (Model == null)
{
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<p>
<a asp-action="AccountCreate">Создать счет</a>
<a asp-action="AccountUpdate">Обновить счет</a>
@ -24,7 +19,6 @@
<th>Номер</th>
<th>Деньги на счёте</th>
<th>Дата открытия</th>
<th>Менеджер</th>
</tr>
</thead>
<tbody>
@ -43,10 +37,6 @@
@Html.DisplayFor(modelItem =>
item.ReleaseDate)
</td>
<td>
@Html.DisplayFor(modelItem =>
item.ManagerName)
</td>
</tr>
}
</tbody>

View File

@ -17,7 +17,7 @@
<div class="row">
<div class="col-4">Пароль:</div>
<div class="col-8">
<input type="password" name="password"
<input type="text" name="password"
value="@Model.Password" />
</div>
</div>

View File

@ -25,4 +25,4 @@
class="btn btn-primary" />
</div>
</div>
</form>
</form>

View File

@ -5,7 +5,7 @@
}
<div class="text-center">
<h2 class="display-4">Список заяыок по счетам</h2>
<h2 class="display-4">Список заявок по счетам</h2>
</div>
<form method="post">
<div class="row">
@ -19,9 +19,16 @@
</select>
</div>
</div>
<div>
<input id="word" type="radio" name="format" value="word" checked />
<label for="word">Получать в формате Word</label>
</div>
<div>
<input id="excel" type="radio" name="format" value="excel" />
<label for="excel">Получать в формате Excel</label>
</div>
<div class="row">
<div class="col-9"></div>
<div class="col-1"><input type="submit" value="Получить в формате Word" class="btn btn-primary" /></div>
<div class="col-1"><input type="submit" value="Получить в формате Excel" class="btn btn-primary" /></div>
<div class="col-1"><input type="submit" value="Получить список" class="btn btn-primary" /></div>
</div>
</form>

View File

@ -2,7 +2,7 @@
ViewData["Title"] = "TransferCreate";
}
<div class="text-center">
<h2 class="display-4">Создание счёта</h2>
<h2 class="display-4">Создание перевода</h2>
</div>
<form method="post">
<div class="row">
@ -14,15 +14,15 @@
<div class="row">
<div class="col-4">Номер счета отправителя:</div>
<div class="col-8">
<select name="sender-number" id="sender-number" class="form-control"
asp-items="@(new SelectList(@ViewBag.Accounts, "Id", "Number"))"></select>
<select name="senderaccount" id="senderaccount" class="form-control"
asp-items="@(new SelectList(@ViewBag.SenderAccounts, "Id", "Number"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Номер счета получателя:</div>
<div class="col-8">
<select name="recipient-number" id="recipient-number" class="form-control"
asp-items="@(new SelectList(@ViewBag.Accounts, "Id", "Number"))"></select>
<select name="recipientaccount" id="recipientaccount" class="form-control"
asp-items="@(new SelectList(@ViewBag.RecipientAccounts, "Id", "Number"))"></select>
</div>
</div>
<div class="row">

View File

@ -8,7 +8,12 @@
<div class="row">
<div class="col-4">Перевод:</div>
<div class="col-8">
<select id="transfer" name="transfer" class="form-control" asp-items="@(new SelectList(@ViewBag.Transfers, "Id", "Id"))"></select>
<select id="transfer" name="transfer" class="form-control">
@foreach (var transfer in ViewBag.Transfers)
{
<option value="@transfer.Id">@transfer.Id: @transfer.TransferTime, @transfer.SenderAccountNumber -> @transfer.RecipientAccountNumber, @transfer.Sum рублей</option>
}
</select>
</div>
</div>
<div class="row">

View File

@ -8,7 +8,12 @@
<div class="row">
<div class="col-4">Перевод:</div>
<div class="col-8">
<select id="transfer" name="transfer" class="form-control" asp-items="@(new SelectList(@ViewBag.Transfers, "Id", "Id"))"></select>
<select id="transfer" name="transfer" class="form-control">
@foreach (var transfer in ViewBag.Transfers)
{
<option value="@transfer.Id">@transfer.Id: @transfer.TransferTime, @transfer.SenderAccountNumber -> @transfer.RecipientAccountNumber, @transfer.Sum рублей</option>
}
</select>
</div>
</div>
<div class="row">
@ -20,17 +25,42 @@
<div class="row">
<div class="col-4">Отправитель:</div>
<div class="col-8">
<select id="sender-account" name="sender-account" class="form-control" asp-items="@(new SelectList(@ViewBag.Accounts, "Id", "Number"))"></select>
<select id="senderaccount" name="senderaccount" class="form-control" asp-items="@(new SelectList(@ViewBag.SenderAccounts, "Id", "Number"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Получатель:</div>
<div class="col-8">
<select id="recipient-account" name="recipient-account" class="form-control" asp-items="@(new SelectList(@ViewBag.Accounts, "Id", "Number"))"></select>
<select id="recipientaccount" name="recipientaccount" class="form-control" asp-items="@(new SelectList(@ViewBag.RecipientAccounts, "Id", "Number"))"></select>
</div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Сохранить" class="btn btn-primary" /></div>
</div>
</form>
</form>
@section Scripts
{
<script>
function check() {
var transfer = $('#transfer').val();
if (transfer) {
$.ajax({
method: "GET",
url: "/Home/GetTransfer",
data: { transferId: transfer },
success: function (result) {
$('#sum').val(result.sum);
$('#senderaccount').val(result.senderAccountId);
$('#recipientaccount').val(result.recipientAccountId);
}
});
};
}
check();
$('#transfer').on('change', function () {
check();
});
</script>
}

View File

@ -2,41 +2,51 @@
ViewData["Title"] = "TransfersWithdrawalsListReport";
}
<div class="text-center">
<h3 class="display-4">Список счетов с расшифровкой по переводам и выдачам</h3>
<h3 class="display-4">Список счетов с расшифровкой по переводам и выдачам по периоду</h3>
</div>
<div class="text-center">
@{
<div class="row mb-5">
<div class="col-4">Начальная дата:</div>
<div class="col-8">
<input type="date" id="startDate" name="startDate" class="form-control">
</div>
<form method="post">
<div class="row mb-5">
<div class="col-4">Начальная дата:</div>
<div class="col-8">
<input type="date" id="dateFrom" name="dateFrom" class="form-control">
</div>
<div class="row mb-5">
<div class="col-4">Конечная дата:</div>
<div class="col-8">
<input type="date" id="endDate" name="endDate" class="form-control">
</div>
</div>
<div class="row mb-5">
<div class="col-4">Конечная дата:</div>
<div class="col-8">
<input type="date" id="dateTo" name="dateTo" class="form-control">
</div>
<table class="table">
<thead>
<tr>
<th>Номер</th>
<th>Дата/th>
<th>Счёт</th>
<th>Перевод</th>
<th>Выдача</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Создать отчет" class="btn btn-primary" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Отправить на почту" class="btn btn-primary" /></div>
</div>
}
</div>
</div>
<div class="row mb-2">
<div class="col-8"></div>
<div class="col-4"><input id="demonstrate" value="Создать отчет" class="btn btn-primary" /></div>
</div>
<div class="row">
<div class="col-8"></div>
<div class="col-4"><input type="submit" value="Отправить на почту" class="btn btn-primary" /></div>
</div>
<div id="report"></div>
</form>
@section Scripts {
<script>
function check() {
var dateFrom = $('#dateFrom').val();
var dateTo = $('#dateTo').val();
if (dateFrom && dateTo) {
$.ajax({
method: "GET",
url: "/Home/GetTransfersWithdrawals",
data: { dateFrom: dateFrom, dateTo: dateTo },
success: function (result) {
if (result != null) {
$('#report').html(result);
}
}
});
};
}
check();
$('#demonstrate').on('click', (e) => check());
</script>
}

View File

@ -5,12 +5,6 @@
<h2 class="display-4">Создание выдачи</h2>
</div>
<form method="post">
<div class="row">
<div class="col-4">Сумма:</div>
<div class="col-8">
<input type="number" name="sum" id="sum" />
</div>
</div>
<div class="row">
<div class="col-4">Счета:</div>
<div class="col-8">

View File

@ -8,7 +8,12 @@
<div class="row">
<div class="col-4">Выдача:</div>
<div class="col-8">
<select id="withdrawal" name="withdrawal" class="form-control" asp-items="@(new SelectList(@ViewBag.Withdrawals, "Id", "Id"))"></select>
<select id="withdrawal" name="withdrawal" class="form-control">
@foreach (var withdrawal in ViewBag.Withdrawals)
{
<option value="@withdrawal.Id">@withdrawal.Id: @withdrawal.WithdrawalTime, @withdrawal.Sum рублей</option>
}
</select>
</div>
</div>
<div class="row">

View File

@ -4,19 +4,27 @@
<div class="text-center">
<h2 class="display-4">Привязывание выдачи к заявке</h2>
</div>
<form method="post">
<form method="get">
<div class="row">
<div class="col-4">Выдача:</div>
<div class="col-8">
<select name="request" id="request" class="form-control"
asp-items="@(new SelectList(@ViewBag.Withdrawals, "Id", "Id"))"></select>
<select id="withdrawal" name="withdrawal" class="form-control">
@foreach (var withdrawal in ViewBag.Withdrawals)
{
<option value="@withdrawal.Id">@withdrawal.Id: @withdrawal.WithdrawalTime, @withdrawal.Sum рублей</option>
}
</select>
</div>
</div>
<div class="row">
<div class="col-4">Заявка:</div>
<div class="col-8">
<select name="request" id="request" class="form-control"
asp-items="@(new SelectList(@ViewBag.Requests, "Id", "Id"))"></select>
<select id="request" name="request" class="form-control">
@foreach (var request in ViewBag.Requests)
{
<option value="@request.Id">@request.Id: @request.RequestTime, @request.Sum рублей, @request.Status</option>
}
</select>
</div>
</div>
<div class="row">

View File

@ -8,13 +8,12 @@
<div class="row">
<div class="col-4">Выдача:</div>
<div class="col-8">
<select id="withdrawal" name="withdrawal" class="form-control" asp-items="@(new SelectList(@ViewBag.Withdrawals, "Id", "Id"))"></select>
</div>
</div>
<div class="row">
<div class="col-4">Сумма:</div>
<div class="col-8">
<input type="number" name="sum" id="sum" />
<select id="withdrawal" name="withdrawal" class="form-control">
@foreach (var withdrawal in ViewBag.Withdrawals)
{
<option value="@withdrawal.Id">@withdrawal.Id: @withdrawal.WithdrawalTime, @withdrawal.Sum рублей</option>
}
</select>
</div>
</div>
<div class="row">
@ -31,7 +30,41 @@
<div class="row">
<div class="col-8"></div>
<div class="col-4">
<input type="submit" value="Создать" class="btn btn-primary" />
<input type="submit" value="Обновить" class="btn btn-primary" />
</div>
</div>
</form>
@section Scripts
{
<script>
function check() {
var withdrawal = $('#withdrawal').val();
$("#accounts option:selected").removeAttr("selected");
if (withdrawal) {
$.ajax({
method: "GET",
url: "/Home/GetAccounts",
data: { withdrawalId: withdrawal },
success: function (result) {
$.map(result, function (n) {
$(`#accounts option[value=${n}]`).attr("selected", "selected")
});
}
});
$.ajax({
method: "GET",
url: "/Home/GetWithdrawal",
data: { withdrawalId: withdrawal },
success: function (result) {
$('#sum').val(result.sum)
}
})
};
}
check();
$('#withdrawal').on('change', function () {
check();
});
</script>
}

View File

@ -3,7 +3,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - BankManagersClientApp</title>
<title>@ViewData["Title"] - BankManagersApp</title>
<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="~/BankManagersClientApp.styles.css" asp-append-version="true" />
@ -12,7 +12,7 @@
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container-fluid">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">BankManagersClientApp</a>
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Банк</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
@ -25,6 +25,7 @@
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Enter">Вход</a>
</li>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Register">Регистрация</a>
</li>
@ -59,7 +60,7 @@
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2024 - BankManagersClientApp - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
&copy; 2024 - Банк - <a asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>

View File

@ -21,20 +21,40 @@ namespace BankRestApi.Controllers
}
[HttpGet]
public List<AccountViewModel>? GetAccountList()
public List<AccountViewModel>? GetAccountList(int? managerId)
{
try
{
return _logic.ReadList(null);
return _logic.ReadList(new AccountSearchModel
{
ManagerId = managerId,
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка счетов");
throw;
}
}
}
[HttpGet]
[HttpGet]
public List<int> GetAccounts(int withdrawalId)
{
try
{
return _logic.ReadAccountIdsByWithdrawal(new AccountSearchModel
{
WithdrawalId = withdrawalId,
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка менеджеров");
throw;
}
}
[HttpGet]
public AccountViewModel? GetAccount(int AccountId)
{
try
@ -65,7 +85,7 @@ namespace BankRestApi.Controllers
}
}
[HttpPut]
[HttpPost]
public void UpdateAccount(AccountBindingModel model)
{
try
@ -79,7 +99,7 @@ namespace BankRestApi.Controllers
}
}
[HttpDelete]
[HttpPost]
public void DeleteAccount(AccountBindingModel model)
{
try

View File

@ -2,6 +2,7 @@
using BankContracts.BusinessLogicsContracts;
using BankContracts.SearchModels;
using BankContracts.ViewModels;
using BankDatabaseImplement.Models;
using Microsoft.AspNetCore.Mvc;
namespace BankRestApi.Controllers
@ -19,11 +20,14 @@ namespace BankRestApi.Controllers
_logic = Card;
}
[HttpGet]
public List<CardViewModel>? GetCardList()
public List<CardViewModel>? GetCardList(int? clientId)
{
try
{
return _logic.ReadList(null);
return _logic.ReadList(new CardSearchModel
{
ClientId = clientId,
});
}
catch (Exception ex)
{
@ -33,18 +37,35 @@ namespace BankRestApi.Controllers
}
[HttpGet]
public CardViewModel? GetCard(int CardId)
public List<int> GetCards(int requestId)
{
try
{
return _logic.ReadListByRequestId(new CardSearchModel
{
RequestId = requestId,
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка менеджеров");
throw;
}
}
[HttpGet]
public CardViewModel? GetCard(int cardId)
{
try
{
return _logic.ReadElement(new CardSearchModel
{
Id = CardId
Id = cardId
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения менеджера по Id={Id}", CardId);
_logger.LogError(ex, "Ошибка получения менеджера по Id={Id}", cardId);
throw;
}
}
@ -63,7 +84,7 @@ namespace BankRestApi.Controllers
}
}
[HttpPut]
[HttpPost]
public void UpdateCard(CardBindingModel model)
{
try
@ -77,7 +98,7 @@ namespace BankRestApi.Controllers
}
}
[HttpDelete]
[HttpPost]
public void DeleteCard(CardBindingModel model)
{
try

View File

@ -81,7 +81,7 @@ namespace BankRestApi.Controllers
}
}
[HttpPut]
[HttpPost]
public void UpdateClient(ClientBindingModel model)
{
try
@ -95,7 +95,7 @@ namespace BankRestApi.Controllers
}
}
[HttpDelete]
[HttpPost]
public void DeleteClient(ClientBindingModel model)
{
try

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