Compare commits
22 Commits
Task_4_Sto
...
Task_6_Rep
| Author | SHA1 | Date | |
|---|---|---|---|
| 4068a579c8 | |||
| 58ff192d7c | |||
| ecff1045b3 | |||
| 94f602b0fe | |||
| 23a5de4e3e | |||
| 109639617e | |||
| 50b507fef3 | |||
| abeeedaa64 | |||
| a201d60ff3 | |||
| 244b846ef9 | |||
| 24833faba0 | |||
| 1cbde02887 | |||
| f4ad6ba98e | |||
| fbba161390 | |||
| d827ade763 | |||
| d6ded9f5e0 | |||
| bb1432fa4d | |||
| 5b25dcf976 | |||
| 6273bff7fb | |||
| fa9dbb3f60 | |||
| 1854214aa9 | |||
| 3552e461fb |
@@ -7,11 +7,19 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="DocumentFormat.OpenXml" Version="3.3.0" />
|
||||
<PackageReference Include="MailKit" Version="4.12.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.4" />
|
||||
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\BankContracts\BankContracts.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="BankWebApi" />
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -22,7 +22,7 @@ internal class CurrencyBusinessLogicContract(
|
||||
|
||||
private readonly ILogger _logger = logger;
|
||||
|
||||
public List<CurrencyDataModel> GetAllCurrencys()
|
||||
public List<CurrencyDataModel> GetAllCurrencies()
|
||||
{
|
||||
_logger.LogInformation("get all currencys programs");
|
||||
return _currencyStorageContract.GetList();
|
||||
|
||||
69
TheBank/BankBusinessLogic/Implementations/EmailService.cs
Normal file
69
TheBank/BankBusinessLogic/Implementations/EmailService.cs
Normal file
@@ -0,0 +1,69 @@
|
||||
using MailKit.Net.Smtp;
|
||||
using MailKit.Security;
|
||||
using MimeKit;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BankBusinessLogic.Implementations
|
||||
{
|
||||
public class EmailService
|
||||
{
|
||||
private readonly string _smtpServer;
|
||||
private readonly int _smtpPort;
|
||||
private readonly string _smtpUsername;
|
||||
private readonly string _smtpPassword;
|
||||
|
||||
public EmailService(string smtpServer, int smtpPort, string smtpUsername, string smtpPassword)
|
||||
{
|
||||
_smtpServer = smtpServer;
|
||||
_smtpPort = smtpPort;
|
||||
_smtpUsername = smtpUsername;
|
||||
_smtpPassword = smtpPassword;
|
||||
}
|
||||
|
||||
public static EmailService CreateYandexService()
|
||||
{
|
||||
return new EmailService(
|
||||
smtpServer: "smtp.yandex.ru",
|
||||
smtpPort: 465,
|
||||
smtpUsername: "egoffevgeny@yandex.com",
|
||||
smtpPassword: "mpaffjmvyulsdpev"
|
||||
);
|
||||
}
|
||||
|
||||
public async Task SendReportAsync(string toEmail, string subject, string body, string attachmentPath = null)
|
||||
{
|
||||
var email = new MimeMessage();
|
||||
email.From.Add(new MailboxAddress("Bank System", _smtpUsername));
|
||||
email.To.Add(new MailboxAddress("", toEmail));
|
||||
email.Subject = subject;
|
||||
|
||||
var builder = new BodyBuilder();
|
||||
builder.HtmlBody = body;
|
||||
|
||||
if (!string.IsNullOrEmpty(attachmentPath))
|
||||
{
|
||||
builder.Attachments.Add(attachmentPath);
|
||||
}
|
||||
|
||||
email.Body = builder.ToMessageBody();
|
||||
|
||||
using (var smtp = new SmtpClient())
|
||||
{
|
||||
await smtp.ConnectAsync(_smtpServer, _smtpPort, SecureSocketOptions.SslOnConnect);
|
||||
await smtp.AuthenticateAsync(_smtpUsername, _smtpPassword);
|
||||
await smtp.SendAsync(email);
|
||||
await smtp.DisconnectAsync(true);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task SendTestEmailAsync(string toEmail)
|
||||
{
|
||||
await SendReportAsync(
|
||||
toEmail: toEmail,
|
||||
subject: "Тестовое письмо от банковской системы",
|
||||
body: "<h1>Тестовое письмо</h1><p>Это тестовое письмо отправлено для проверки работы системы.</p>"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,24 +27,19 @@ internal class PeriodBusinessLogicContract(
|
||||
_logger.LogInformation("get all periods");
|
||||
return _periodStorageContract.GetList();
|
||||
}
|
||||
|
||||
public List<PeriodDataModel> GetAllPeriodsByEndTime(DateTime fromDate, DateTime toDate)
|
||||
public List<PeriodDataModel> GetAllPeriodsByStartTime(DateTime fromDate)
|
||||
{
|
||||
if (toDate.IsDateNotOlder(toDate))
|
||||
if (fromDate.IsDateNotOlder(DateTime.UtcNow))
|
||||
{
|
||||
throw new IncorrectDatesException(fromDate, toDate);
|
||||
throw new IncorrectDatesException(fromDate, DateTime.UtcNow);
|
||||
}
|
||||
return _periodStorageContract.GetList(fromDate, toDate).OrderBy(x => x.EndTime).ToList()
|
||||
return _periodStorageContract.GetList(startDate: fromDate).OrderBy(x => x.StartTime).ToList()
|
||||
?? throw new NullListException(nameof(PeriodDataModel));
|
||||
}
|
||||
|
||||
public List<PeriodDataModel> GetAllPeriodsByStartTime(DateTime fromDate, DateTime toDate)
|
||||
public List<PeriodDataModel> GetAllPeriodsByEndTime(DateTime toDate)
|
||||
{
|
||||
if (toDate.IsDateNotOlder(toDate))
|
||||
{
|
||||
throw new IncorrectDatesException(fromDate, toDate);
|
||||
}
|
||||
return _periodStorageContract.GetList(fromDate, toDate).OrderBy(x => x.StartTime).ToList()
|
||||
return _periodStorageContract.GetList(endDate: toDate).OrderBy(x => x.EndTime).ToList()
|
||||
?? throw new NullListException(nameof(PeriodDataModel));
|
||||
}
|
||||
|
||||
|
||||
334
TheBank/BankBusinessLogic/Implementations/ReportContract.cs
Normal file
334
TheBank/BankBusinessLogic/Implementations/ReportContract.cs
Normal file
@@ -0,0 +1,334 @@
|
||||
using BankBusinessLogic.OfficePackage;
|
||||
using BankContracts.BusinessLogicContracts;
|
||||
using BankContracts.DataModels;
|
||||
using BankContracts.StorageContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace BankBusinessLogic.Implementations;
|
||||
|
||||
public class ReportContract(IClientStorageContract clientStorage, ICurrencyStorageContract currencyStorage,
|
||||
ICreditProgramStorageContract creditProgramStorage, IDepositStorageContract depositStorage,
|
||||
BaseWordBuilder baseWordBuilder, BaseExcelBuilder baseExcelBuilder, BasePdfBuilder basePdfBuilder, ILogger logger) : IReportContract
|
||||
{
|
||||
private readonly IClientStorageContract _clientStorage = clientStorage;
|
||||
private readonly ICurrencyStorageContract _currencyStorage = currencyStorage;
|
||||
private readonly ICreditProgramStorageContract _creditProgramStorage = creditProgramStorage;
|
||||
private readonly IDepositStorageContract _depositStorage = depositStorage;
|
||||
private readonly BaseWordBuilder _baseWordBuilder = baseWordBuilder;
|
||||
private readonly BaseExcelBuilder _baseExcelBuilder = baseExcelBuilder;
|
||||
private readonly BasePdfBuilder _basePdfBuilder = basePdfBuilder;
|
||||
private readonly ILogger _logger = logger;
|
||||
|
||||
private static readonly string[] documentHeader = ["Название программы", "Фамилия", "Имя", "Баланс"];
|
||||
private static readonly string[] depositHeader = ["Название программы", "Ставка", "Сумма", "Срок"];
|
||||
private static readonly string[] clientsByDepositHeader = ["Фамилия", "Имя", "Баланс", "Ставка", "Срок", "Период"];
|
||||
private static readonly string[] currencyHeader = ["Валюта", "Кредитная программа", "Макс. сумма", "Ставка", "Срок"];
|
||||
|
||||
public async Task<List<ClientsByCreditProgramDataModel>> GetDataClientsByCreditProgramAsync(CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Get data ClientsByCreditProgram");
|
||||
var clients = await Task.Run(() => _clientStorage.GetList(), ct);
|
||||
var creditPrograms = await Task.Run(() => _creditProgramStorage.GetList(), ct);
|
||||
var currencies = await Task.Run(() => _currencyStorage.GetList(), ct);
|
||||
|
||||
return creditPrograms
|
||||
.Where(cp => cp.Currencies.Any()) // Проверяем, что у кредитной программы есть связанные валюты
|
||||
.Select(cp => new ClientsByCreditProgramDataModel
|
||||
{
|
||||
CreditProgramName = cp.Name,
|
||||
ClientSurname = clients.Where(c => c.CreditProgramClients.Any(cpc => cpc.CreditProgramId == cp.Id))
|
||||
.Select(c => c.Surname).ToList(),
|
||||
ClientName = clients.Where(c => c.CreditProgramClients.Any(cpc => cpc.CreditProgramId == cp.Id))
|
||||
.Select(c => c.Name).ToList(),
|
||||
ClientBalance = clients.Where(c => c.CreditProgramClients.Any(cpc => cpc.CreditProgramId == cp.Id))
|
||||
.Select(c => c.Balance).ToList()
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
public async Task<Stream> CreateDocumentClientsByCreditProgramAsync(CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Create report ClientsByCreditProgram");
|
||||
var data = await GetDataClientsByCreditProgramAsync(ct) ?? throw new InvalidOperationException("No found data");
|
||||
|
||||
var tableRows = new List<string[]>
|
||||
{
|
||||
documentHeader
|
||||
};
|
||||
|
||||
foreach (var program in data)
|
||||
{
|
||||
for (int i = 0; i < program.ClientSurname.Count; i++)
|
||||
{
|
||||
tableRows.Add(new string[]
|
||||
{
|
||||
program.CreditProgramName,
|
||||
program.ClientSurname[i],
|
||||
program.ClientName[i],
|
||||
program.ClientBalance[i].ToString("N2")
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return _baseWordBuilder
|
||||
.AddHeader("Клиенты по кредитным программам")
|
||||
.AddParagraph($"Сформировано на дату {DateTime.Now}")
|
||||
.AddTable([3000, 3000, 3000, 3000], tableRows)
|
||||
.Build();
|
||||
}
|
||||
|
||||
public async Task<Stream> CreateExcelDocumentClientsByCreditProgramAsync(CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Create Excel report ClientsByCreditProgram");
|
||||
var data = await GetDataClientsByCreditProgramAsync(ct) ?? throw new InvalidOperationException("No found data");
|
||||
|
||||
var tableRows = new List<string[]>
|
||||
{
|
||||
documentHeader
|
||||
};
|
||||
|
||||
foreach (var program in data)
|
||||
{
|
||||
for (int i = 0; i < program.ClientSurname.Count; i++)
|
||||
{
|
||||
tableRows.Add(new string[]
|
||||
{
|
||||
program.CreditProgramName,
|
||||
program.ClientSurname[i],
|
||||
program.ClientName[i],
|
||||
program.ClientBalance[i].ToString("N2")
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return _baseExcelBuilder
|
||||
.AddHeader("Клиенты по кредитным программам", 0, 4)
|
||||
.AddParagraph($"Сформировано на дату {DateTime.Now}", 0)
|
||||
.AddTable([3000, 3000, 3000, 3000], tableRows)
|
||||
.Build();
|
||||
}
|
||||
|
||||
public async Task<List<ClientsByDepositDataModel>> GetDataClientsByDepositAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Get data ClientsByDeposit from {dateStart} to {dateFinish}", dateStart, dateFinish);
|
||||
if (dateStart > dateFinish)
|
||||
{
|
||||
throw new ArgumentException("Start date cannot be later than finish date");
|
||||
}
|
||||
|
||||
var clients = await Task.Run(() => _clientStorage.GetList(), ct);
|
||||
var deposits = await Task.Run(() => _depositStorage.GetList(), ct);
|
||||
|
||||
var result = new List<ClientsByDepositDataModel>();
|
||||
foreach (var client in clients)
|
||||
{
|
||||
if (client.DepositClients == null || !client.DepositClients.Any())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var depositClient in client.DepositClients)
|
||||
{
|
||||
var deposit = deposits.FirstOrDefault(d => d.Id == depositClient.DepositId);
|
||||
if (deposit == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
result.Add(new ClientsByDepositDataModel
|
||||
{
|
||||
ClientSurname = client.Surname,
|
||||
ClientName = client.Name,
|
||||
ClientBalance = client.Balance,
|
||||
DepositRate = deposit.InterestRate,
|
||||
DepositPeriod = deposit.Period,
|
||||
FromPeriod = dateStart,
|
||||
ToPeriod = dateFinish
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (!result.Any())
|
||||
{
|
||||
throw new InvalidOperationException("No clients with deposits found");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<Stream> CreateDocumentClientsByDepositAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Create report ClientsByDeposit from {dateStart} to {dateFinish}", dateStart, dateFinish);
|
||||
var data = await GetDataClientsByDepositAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException("No found data");
|
||||
|
||||
// Двухуровневый заголовок
|
||||
var tableRows = new List<string[]>
|
||||
{
|
||||
new string[] { "Клиент", "Клиент", "Клиент", "Вклад", "Вклад", "Период" },
|
||||
new string[] { "Фамилия", "Имя", "Баланс", "Ставка", "Срок", "" }
|
||||
};
|
||||
|
||||
foreach (var client in data)
|
||||
{
|
||||
tableRows.Add(new string[]
|
||||
{
|
||||
client.ClientSurname,
|
||||
client.ClientName,
|
||||
client.ClientBalance.ToString("N2"),
|
||||
client.DepositRate.ToString("N2"),
|
||||
$"{client.DepositPeriod} мес.",
|
||||
$"{client.FromPeriod.ToShortDateString()} - {client.ToPeriod.ToShortDateString()}"
|
||||
});
|
||||
}
|
||||
|
||||
return _basePdfBuilder
|
||||
.AddHeader("Клиенты по вкладам")
|
||||
.AddParagraph($"за период с {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}")
|
||||
.AddTable([80, 80, 80, 80, 80, 80], tableRows)
|
||||
.Build();
|
||||
}
|
||||
|
||||
public async Task<List<CreditProgramAndDepositByCurrencyDataModel>> GetDataDepositAndCreditProgramByCurrencyAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Get data DepositAndCreditProgramByCurrency from {dateStart} to {dateFinish}", dateStart, dateFinish);
|
||||
if (dateStart > dateFinish)
|
||||
{
|
||||
throw new ArgumentException("Start date cannot be later than finish date");
|
||||
}
|
||||
|
||||
var currencies = await Task.Run(() => _currencyStorage.GetList(), ct);
|
||||
var creditPrograms = await Task.Run(() => _creditProgramStorage.GetList(), ct);
|
||||
var deposits = await Task.Run(() => _depositStorage.GetList(), ct);
|
||||
|
||||
return currencies.Select(c => new CreditProgramAndDepositByCurrencyDataModel
|
||||
{
|
||||
CurrencyName = c.Name,
|
||||
CreditProgramName = creditPrograms.Where(cp => cp.Currencies.Any(cc => cc.CurrencyId == c.Id))
|
||||
.Select(cp => cp.Name).ToList(),
|
||||
CreditProgramMaxCost = creditPrograms.Where(cp => cp.Currencies.Any(cc => cc.CurrencyId == c.Id))
|
||||
.Select(cp => (int)cp.MaxCost).ToList(),
|
||||
DepositRate = deposits.Where(d => d.Currencies.Any(dc => dc.CurrencyId == c.Id))
|
||||
.Select(d => d.InterestRate).ToList(),
|
||||
DepositPeriod = deposits.Where(d => d.Currencies.Any(dc => dc.CurrencyId == c.Id))
|
||||
.Select(d => d.Period).ToList(),
|
||||
FromPeriod = dateStart,
|
||||
ToPeriod = dateFinish
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
public async Task<Stream> CreateDocumentDepositAndCreditProgramByCurrencyAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Create report DepositAndCreditProgramByCurrency from {dateStart} to {dateFinish}", dateStart, dateFinish);
|
||||
var data = await GetDataDepositAndCreditProgramByCurrencyAsync(dateStart, dateFinish, ct) ?? throw new InvalidOperationException("No found data");
|
||||
|
||||
// Двухуровневый заголовок
|
||||
var tableRows = new List<string[]>
|
||||
{
|
||||
new string[] { "Наименование валюты", "Кредитная программа", "Кредитная программа", "Вклад", "Вклад" },
|
||||
new string[] { "", "Название", "Максимальная сумма", "Процентная ставка", "Срок" }
|
||||
};
|
||||
|
||||
foreach (var currency in data)
|
||||
{
|
||||
for (int i = 0; i < currency.CreditProgramName.Count; i++)
|
||||
{
|
||||
tableRows.Add(new string[]
|
||||
{
|
||||
currency.CurrencyName,
|
||||
currency.CreditProgramName[i],
|
||||
currency.CreditProgramMaxCost[i].ToString("N2"),
|
||||
currency.DepositRate[i].ToString("N2"),
|
||||
$"{currency.DepositPeriod[i]} мес."
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return _basePdfBuilder
|
||||
.AddHeader("Вклады и кредитные программы по валютам")
|
||||
.AddParagraph($"за период с {dateStart.ToShortDateString()} по {dateFinish.ToShortDateString()}")
|
||||
.AddTable([80, 100, 80, 80, 80], tableRows)
|
||||
.Build();
|
||||
}
|
||||
|
||||
public async Task<List<DepositByCreditProgramDataModel>> GetDataDepositByCreditProgramAsync(CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Get data DepositByCreditProgram");
|
||||
var deposits = await Task.Run(() => _depositStorage.GetList(), ct);
|
||||
var creditPrograms = await Task.Run(() => _creditProgramStorage.GetList(), ct);
|
||||
|
||||
// Проверяем, что у вкладов есть связанные валюты
|
||||
if (!deposits.Any(d => d.Currencies.Any()))
|
||||
{
|
||||
throw new InvalidOperationException("No deposits with currencies found");
|
||||
}
|
||||
|
||||
return creditPrograms.Select(cp => new DepositByCreditProgramDataModel
|
||||
{
|
||||
CreditProgramName = cp.Name,
|
||||
DepositRate = deposits.Select(d => d.InterestRate).ToList(),
|
||||
DepositCost = deposits.Select(d => d.Cost).ToList(),
|
||||
DepositPeriod = deposits.Select(d => d.Period).ToList()
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
public async Task<Stream> CreateDocumentDepositByCreditProgramAsync(CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Create report DepositByCreditProgram");
|
||||
var data = await GetDataDepositByCreditProgramAsync(ct) ?? throw new InvalidOperationException("No found data");
|
||||
|
||||
var tableRows = new List<string[]>
|
||||
{
|
||||
depositHeader
|
||||
};
|
||||
|
||||
foreach (var program in data)
|
||||
{
|
||||
for (int i = 0; i < program.DepositRate.Count; i++)
|
||||
{
|
||||
tableRows.Add(new string[]
|
||||
{
|
||||
program.CreditProgramName,
|
||||
program.DepositRate[i].ToString("N2"),
|
||||
program.DepositCost[i].ToString("N2"),
|
||||
program.DepositPeriod[i].ToString()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return _baseWordBuilder
|
||||
.AddHeader("Вклады по кредитным программам")
|
||||
.AddParagraph($"Сформировано на дату {DateTime.Now}")
|
||||
.AddTable([3000, 3000, 3000, 3000], tableRows)
|
||||
.Build();
|
||||
}
|
||||
|
||||
public async Task<Stream> CreateExcelDocumentDepositByCreditProgramAsync(CancellationToken ct)
|
||||
{
|
||||
_logger.LogInformation("Create Excel report DepositByCreditProgram");
|
||||
var data = await GetDataDepositByCreditProgramAsync(ct) ?? throw new InvalidOperationException("No found data");
|
||||
|
||||
var tableRows = new List<string[]>
|
||||
{
|
||||
depositHeader
|
||||
};
|
||||
|
||||
foreach (var program in data)
|
||||
{
|
||||
for (int i = 0; i < program.DepositRate.Count; i++)
|
||||
{
|
||||
tableRows.Add(new string[]
|
||||
{
|
||||
program.CreditProgramName,
|
||||
program.DepositRate[i].ToString("N2"),
|
||||
program.DepositCost[i].ToString("N2"),
|
||||
program.DepositPeriod[i].ToString()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return _baseExcelBuilder
|
||||
.AddHeader("Вклады по кредитным программам", 0, 4)
|
||||
.AddParagraph($"Сформировано на дату {DateTime.Now}", 0)
|
||||
.AddTable([3000, 3000, 3000, 3000], tableRows)
|
||||
.Build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace BankBusinessLogic.OfficePackage;
|
||||
|
||||
public abstract class BaseExcelBuilder
|
||||
{
|
||||
public abstract BaseExcelBuilder AddHeader(string header, int startIndex, int count);
|
||||
public abstract BaseExcelBuilder AddParagraph(string text, int columnIndex);
|
||||
public abstract BaseExcelBuilder AddTable(int[] columnsWidths, List<string[]> data);
|
||||
public abstract Stream Build();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace BankBusinessLogic.OfficePackage;
|
||||
|
||||
public abstract class BasePdfBuilder
|
||||
{
|
||||
public abstract BasePdfBuilder AddHeader(string header);
|
||||
public abstract BasePdfBuilder AddParagraph(string text);
|
||||
public abstract BasePdfBuilder AddTable(int[] columnsWidths, List<string[]> data);
|
||||
public abstract Stream Build();
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace BankBusinessLogic.OfficePackage;
|
||||
|
||||
public abstract class BaseWordBuilder
|
||||
{
|
||||
public abstract BaseWordBuilder AddHeader(string header);
|
||||
public abstract BaseWordBuilder AddParagraph(string text);
|
||||
public abstract BaseWordBuilder AddTable(int[] widths, List<string[]> data);
|
||||
public abstract Stream Build();
|
||||
}
|
||||
155
TheBank/BankBusinessLogic/OfficePackage/MigraDocPdfBuilder.cs
Normal file
155
TheBank/BankBusinessLogic/OfficePackage/MigraDocPdfBuilder.cs
Normal file
@@ -0,0 +1,155 @@
|
||||
using MigraDoc.DocumentObjectModel;
|
||||
using MigraDoc.DocumentObjectModel.Tables;
|
||||
using MigraDoc.Rendering;
|
||||
using System.Text;
|
||||
|
||||
namespace BankBusinessLogic.OfficePackage;
|
||||
|
||||
public class MigraDocPdfBuilder : BasePdfBuilder
|
||||
{
|
||||
private readonly Document _document;
|
||||
|
||||
public MigraDocPdfBuilder()
|
||||
{
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
_document = new Document();
|
||||
_document.Info.Title = "Bank Report";
|
||||
_document.DefaultPageSetup.LeftMargin = Unit.FromCentimeter(2);
|
||||
_document.DefaultPageSetup.RightMargin = Unit.FromCentimeter(2);
|
||||
_document.DefaultPageSetup.TopMargin = Unit.FromCentimeter(2);
|
||||
_document.DefaultPageSetup.BottomMargin = Unit.FromCentimeter(2);
|
||||
DefineStyles();
|
||||
}
|
||||
|
||||
public override BasePdfBuilder AddHeader(string header)
|
||||
{
|
||||
var section = _document.AddSection();
|
||||
var paragraph = section.AddParagraph(header, "Heading1");
|
||||
paragraph.Format.SpaceAfter = Unit.FromPoint(10);
|
||||
return this;
|
||||
}
|
||||
|
||||
public override BasePdfBuilder AddParagraph(string text)
|
||||
{
|
||||
var section = _document.LastSection ?? _document.AddSection();
|
||||
var paragraph = section.AddParagraph(text, "Normal");
|
||||
paragraph.Format.SpaceAfter = Unit.FromPoint(10);
|
||||
return this;
|
||||
}
|
||||
|
||||
public override BasePdfBuilder AddTable(int[] columnsWidths, List<string[]> data)
|
||||
{
|
||||
if (columnsWidths == null || columnsWidths.Length == 0)
|
||||
throw new ArgumentNullException(nameof(columnsWidths));
|
||||
if (data == null || data.Count == 0)
|
||||
throw new ArgumentNullException(nameof(data));
|
||||
if (data.Any(x => x.Length != columnsWidths.Length))
|
||||
throw new InvalidOperationException("widths.Length != data.Length");
|
||||
|
||||
var section = _document.LastSection ?? _document.AddSection();
|
||||
var table = section.AddTable();
|
||||
table.Style = "Table";
|
||||
table.Borders.Width = 0.75;
|
||||
table.Borders.Color = Colors.Black;
|
||||
table.Rows.LeftIndent = 0;
|
||||
|
||||
// Добавляем столбцы с заданной шириной
|
||||
foreach (var width in columnsWidths)
|
||||
{
|
||||
var widthInCm = width / 28.35;
|
||||
var column = table.AddColumn(Unit.FromCentimeter(widthInCm));
|
||||
column.Format.Alignment = ParagraphAlignment.Left;
|
||||
}
|
||||
|
||||
// Первая строка — объединённый заголовок
|
||||
var headerRow1 = table.AddRow();
|
||||
headerRow1.HeadingFormat = true;
|
||||
headerRow1.Format.Font.Bold = true;
|
||||
headerRow1.Format.Alignment = ParagraphAlignment.Center;
|
||||
headerRow1.VerticalAlignment = VerticalAlignment.Center;
|
||||
headerRow1.Shading.Color = Colors.White;
|
||||
for (int j = 0; j < data[0].Length; j++)
|
||||
{
|
||||
var cell = headerRow1.Cells[j];
|
||||
cell.AddParagraph(data[0][j]);
|
||||
cell.Format.Alignment = ParagraphAlignment.Center;
|
||||
cell.VerticalAlignment = VerticalAlignment.Center;
|
||||
cell.Borders.Width = 0.5;
|
||||
}
|
||||
// Объединяем ячейки: "Кредитная программа" (j=1,2), "Вклад" (j=3,4)
|
||||
headerRow1.Cells[1].MergeRight = 1;
|
||||
headerRow1.Cells[3].MergeRight = 1;
|
||||
|
||||
// Вторая строка — подзаголовки
|
||||
var headerRow2 = table.AddRow();
|
||||
headerRow2.HeadingFormat = true;
|
||||
headerRow2.Format.Font.Bold = true;
|
||||
headerRow2.Format.Alignment = ParagraphAlignment.Center;
|
||||
headerRow2.VerticalAlignment = VerticalAlignment.Center;
|
||||
headerRow2.Shading.Color = Colors.White;
|
||||
for (int j = 0; j < data[1].Length; j++)
|
||||
{
|
||||
var cell = headerRow2.Cells[j];
|
||||
cell.AddParagraph(data[1][j]);
|
||||
cell.Format.Alignment = ParagraphAlignment.Center;
|
||||
cell.VerticalAlignment = VerticalAlignment.Center;
|
||||
cell.Borders.Width = 0.5;
|
||||
}
|
||||
|
||||
// Данные — обычные строки, без жирности и заливки, выравнивание по левому краю
|
||||
for (int i = 2; i < data.Count; i++)
|
||||
{
|
||||
var row = table.AddRow();
|
||||
row.Format.Font.Bold = false;
|
||||
row.Format.Alignment = ParagraphAlignment.Left;
|
||||
row.VerticalAlignment = VerticalAlignment.Center;
|
||||
row.Shading.Color = Colors.White;
|
||||
for (int j = 0; j < data[i].Length; j++)
|
||||
{
|
||||
var cell = row.Cells[j];
|
||||
cell.AddParagraph(data[i][j]);
|
||||
cell.Format.Alignment = ParagraphAlignment.Left;
|
||||
cell.VerticalAlignment = VerticalAlignment.Center;
|
||||
cell.Borders.Width = 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
section.AddParagraph();
|
||||
return this;
|
||||
}
|
||||
|
||||
public override Stream Build()
|
||||
{
|
||||
var stream = new MemoryStream();
|
||||
var renderer = new PdfDocumentRenderer(true)
|
||||
{
|
||||
Document = _document
|
||||
};
|
||||
renderer.RenderDocument();
|
||||
renderer.PdfDocument.Save(stream);
|
||||
stream.Position = 0; // Важно установить позицию в начало потока
|
||||
return stream;
|
||||
}
|
||||
|
||||
private void DefineStyles()
|
||||
{
|
||||
// Определяем стиль для обычного текста
|
||||
var style = _document.Styles["Normal"];
|
||||
style.Font.Name = "Times New Roman";
|
||||
style.Font.Size = 12;
|
||||
style.ParagraphFormat.SpaceAfter = Unit.FromPoint(10);
|
||||
|
||||
// Определяем стиль для заголовка
|
||||
style = _document.Styles.AddStyle("Heading1", "Normal");
|
||||
style.Font.Bold = true;
|
||||
style.Font.Size = 14;
|
||||
style.ParagraphFormat.SpaceAfter = Unit.FromPoint(10);
|
||||
style.ParagraphFormat.Alignment = ParagraphAlignment.Center;
|
||||
|
||||
// Определяем стиль для таблицы
|
||||
style = _document.Styles.AddStyle("Table", "Normal");
|
||||
style.Font.Name = "Times New Roman";
|
||||
style.Font.Size = 10;
|
||||
style.ParagraphFormat.SpaceAfter = Unit.FromPoint(5);
|
||||
}
|
||||
}
|
||||
297
TheBank/BankBusinessLogic/OfficePackage/OpenXmlExcelBuilder.cs
Normal file
297
TheBank/BankBusinessLogic/OfficePackage/OpenXmlExcelBuilder.cs
Normal file
@@ -0,0 +1,297 @@
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml.Spreadsheet;
|
||||
using DocumentFormat.OpenXml;
|
||||
|
||||
namespace BankBusinessLogic.OfficePackage;
|
||||
|
||||
public class OpenXmlExcelBuilder : BaseExcelBuilder
|
||||
{
|
||||
private readonly SheetData _sheetData;
|
||||
|
||||
private readonly MergeCells _mergeCells;
|
||||
|
||||
private readonly Columns _columns;
|
||||
|
||||
private uint _rowIndex = 0;
|
||||
|
||||
public OpenXmlExcelBuilder()
|
||||
{
|
||||
_sheetData = new SheetData();
|
||||
_mergeCells = new MergeCells();
|
||||
_columns = new Columns();
|
||||
_rowIndex = 1;
|
||||
}
|
||||
|
||||
public override BaseExcelBuilder AddHeader(string header, int startIndex, int count)
|
||||
{
|
||||
CreateCell(startIndex, _rowIndex, header, StyleIndex.BoldTextWithoutBorder);
|
||||
for (int i = startIndex + 1; i < startIndex + count; ++i)
|
||||
{
|
||||
CreateCell(i, _rowIndex, "", StyleIndex.SimpleTextWithoutBorder);
|
||||
}
|
||||
|
||||
_mergeCells.Append(new MergeCell()
|
||||
{
|
||||
Reference =
|
||||
new StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:{GetExcelColumnName(startIndex + count - 1)}{_rowIndex}")
|
||||
});
|
||||
|
||||
_rowIndex++;
|
||||
return this;
|
||||
}
|
||||
|
||||
public override BaseExcelBuilder AddParagraph(string text, int columnIndex)
|
||||
{
|
||||
CreateCell(columnIndex, _rowIndex++, text, StyleIndex.SimpleTextWithoutBorder);
|
||||
return this;
|
||||
}
|
||||
|
||||
public override BaseExcelBuilder AddTable(int[] columnsWidths, List<string[]> data)
|
||||
{
|
||||
if (columnsWidths == null || columnsWidths.Length == 0)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(columnsWidths));
|
||||
}
|
||||
|
||||
if (data == null || data.Count == 0)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(data));
|
||||
}
|
||||
|
||||
if (data.Any(x => x.Length != columnsWidths.Length))
|
||||
{
|
||||
throw new InvalidOperationException("widths.Length != data.Length");
|
||||
}
|
||||
|
||||
uint counter = 1;
|
||||
int coef = 1;
|
||||
_columns.Append(columnsWidths.Select(x => new Column
|
||||
{
|
||||
Min = counter,
|
||||
Max = counter++,
|
||||
Width = x * coef,
|
||||
CustomWidth = true
|
||||
}));
|
||||
|
||||
for (var j = 0; j < data.First().Length; ++j)
|
||||
{
|
||||
CreateCell(j, _rowIndex, data.First()[j], StyleIndex.BoldTextWithBorder);
|
||||
}
|
||||
|
||||
_rowIndex++;
|
||||
for (var i = 1; i < data.Count; ++i)
|
||||
{
|
||||
for (var j = 0; j < data[i].Length; ++j)
|
||||
{
|
||||
CreateCell(j, _rowIndex, data[i][j], StyleIndex.SimpleTextWithBorder);
|
||||
}
|
||||
|
||||
_rowIndex++;
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public override Stream Build()
|
||||
{
|
||||
var stream = new MemoryStream();
|
||||
using var spreadsheetDocument = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook);
|
||||
var workbookpart = spreadsheetDocument.AddWorkbookPart();
|
||||
GenerateStyle(workbookpart);
|
||||
workbookpart.Workbook = new Workbook();
|
||||
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
|
||||
worksheetPart.Worksheet = new Worksheet();
|
||||
if (_columns.HasChildren)
|
||||
{
|
||||
worksheetPart.Worksheet.Append(_columns);
|
||||
}
|
||||
|
||||
worksheetPart.Worksheet.Append(_sheetData);
|
||||
var sheets = spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets());
|
||||
var sheet = new Sheet()
|
||||
{
|
||||
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
|
||||
SheetId = 1,
|
||||
Name = "Лист 1"
|
||||
};
|
||||
|
||||
sheets.Append(sheet);
|
||||
if (_mergeCells.HasChildren)
|
||||
{
|
||||
worksheetPart.Worksheet.InsertAfter(_mergeCells, worksheetPart.Worksheet.Elements<SheetData>().First());
|
||||
}
|
||||
return stream;
|
||||
}
|
||||
|
||||
private static void GenerateStyle(WorkbookPart workbookPart)
|
||||
{
|
||||
var workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
|
||||
workbookStylesPart.Stylesheet = new Stylesheet();
|
||||
|
||||
var fonts = new Fonts() { Count = 2, KnownFonts = BooleanValue.FromBoolean(true) };
|
||||
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
|
||||
{
|
||||
FontSize = new FontSize() { Val = 11 },
|
||||
FontName = new FontName() { Val = "Calibri" },
|
||||
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
|
||||
FontScheme = new FontScheme() { Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor) }
|
||||
});
|
||||
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
|
||||
{
|
||||
FontSize = new FontSize() { Val = 11 },
|
||||
FontName = new FontName() { Val = "Calibri" },
|
||||
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
|
||||
FontScheme = new FontScheme() { Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor) },
|
||||
Bold = new Bold()
|
||||
});
|
||||
workbookStylesPart.Stylesheet.Append(fonts);
|
||||
|
||||
// Default Fill
|
||||
var fills = new Fills() { Count = 1 };
|
||||
fills.Append(new Fill
|
||||
{
|
||||
PatternFill = new PatternFill() { PatternType = new EnumValue<PatternValues>(PatternValues.None) }
|
||||
});
|
||||
workbookStylesPart.Stylesheet.Append(fills);
|
||||
|
||||
// Default Border
|
||||
var borders = new Borders() { Count = 2 };
|
||||
borders.Append(new Border
|
||||
{
|
||||
LeftBorder = new LeftBorder(),
|
||||
RightBorder = new RightBorder(),
|
||||
TopBorder = new TopBorder(),
|
||||
BottomBorder = new BottomBorder(),
|
||||
DiagonalBorder = new DiagonalBorder()
|
||||
});
|
||||
borders.Append(new Border
|
||||
{
|
||||
LeftBorder = new LeftBorder() { Style = BorderStyleValues.Thin },
|
||||
RightBorder = new RightBorder() { Style = BorderStyleValues.Thin },
|
||||
TopBorder = new TopBorder() { Style = BorderStyleValues.Thin },
|
||||
BottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin }
|
||||
});
|
||||
workbookStylesPart.Stylesheet.Append(borders);
|
||||
|
||||
// Default cell format and a date cell format
|
||||
var cellFormats = new CellFormats() { Count = 4 };
|
||||
cellFormats.Append(new CellFormat
|
||||
{
|
||||
NumberFormatId = 0,
|
||||
FormatId = 0,
|
||||
FontId = 0,
|
||||
BorderId = 0,
|
||||
FillId = 0,
|
||||
Alignment = new Alignment()
|
||||
{
|
||||
Horizontal = HorizontalAlignmentValues.Left,
|
||||
Vertical = VerticalAlignmentValues.Center,
|
||||
WrapText = true
|
||||
}
|
||||
});
|
||||
cellFormats.Append(new CellFormat
|
||||
{
|
||||
NumberFormatId = 0,
|
||||
FormatId = 0,
|
||||
FontId = 0,
|
||||
BorderId = 1,
|
||||
FillId = 0,
|
||||
Alignment = new Alignment()
|
||||
{
|
||||
Horizontal = HorizontalAlignmentValues.Left,
|
||||
Vertical = VerticalAlignmentValues.Center,
|
||||
WrapText = true
|
||||
}
|
||||
});
|
||||
cellFormats.Append(new CellFormat
|
||||
{
|
||||
NumberFormatId = 0,
|
||||
FormatId = 0,
|
||||
FontId = 1,
|
||||
BorderId = 0,
|
||||
FillId = 0,
|
||||
Alignment = new Alignment()
|
||||
{
|
||||
Horizontal = HorizontalAlignmentValues.Center,
|
||||
Vertical = VerticalAlignmentValues.Center,
|
||||
WrapText = true
|
||||
}
|
||||
});
|
||||
cellFormats.Append(new CellFormat
|
||||
{
|
||||
NumberFormatId = 0,
|
||||
FormatId = 0,
|
||||
FontId = 1,
|
||||
BorderId = 1,
|
||||
FillId = 0,
|
||||
Alignment = new Alignment()
|
||||
{
|
||||
Horizontal = HorizontalAlignmentValues.Center,
|
||||
Vertical = VerticalAlignmentValues.Center,
|
||||
WrapText = true
|
||||
}
|
||||
});
|
||||
workbookStylesPart.Stylesheet.Append(cellFormats);
|
||||
}
|
||||
|
||||
private enum StyleIndex
|
||||
{
|
||||
SimpleTextWithoutBorder = 0,
|
||||
SimpleTextWithBorder = 1,
|
||||
BoldTextWithoutBorder = 2,
|
||||
BoldTextWithBorder = 3
|
||||
}
|
||||
|
||||
private void CreateCell(int columnIndex, uint rowIndex, string text, StyleIndex styleIndex)
|
||||
{
|
||||
var columnName = GetExcelColumnName(columnIndex);
|
||||
var cellReference = columnName + rowIndex;
|
||||
var row = _sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex! == rowIndex);
|
||||
if (row == null)
|
||||
{
|
||||
row = new Row() { RowIndex = rowIndex };
|
||||
_sheetData.Append(row);
|
||||
}
|
||||
|
||||
var newCell = row.Elements<Cell>()
|
||||
.FirstOrDefault(c => c.CellReference != null && c.CellReference.Value == columnName + rowIndex);
|
||||
if (newCell == null)
|
||||
{
|
||||
Cell? refCell = null;
|
||||
foreach (Cell cell in row.Elements<Cell>())
|
||||
{
|
||||
if (cell.CellReference?.Value != null && cell.CellReference.Value.Length == cellReference.Length)
|
||||
{
|
||||
if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
|
||||
{
|
||||
refCell = cell;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
newCell = new Cell() { CellReference = cellReference };
|
||||
row.InsertBefore(newCell, refCell);
|
||||
}
|
||||
|
||||
newCell.CellValue = new CellValue(text);
|
||||
newCell.DataType = CellValues.String;
|
||||
newCell.StyleIndex = (uint)styleIndex;
|
||||
}
|
||||
|
||||
private static string GetExcelColumnName(int columnNumber)
|
||||
{
|
||||
columnNumber += 1;
|
||||
int dividend = columnNumber;
|
||||
string columnName = string.Empty;
|
||||
int modulo;
|
||||
|
||||
while (dividend > 0)
|
||||
{
|
||||
modulo = (dividend - 1) % 26;
|
||||
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
|
||||
dividend = (dividend - modulo) / 26;
|
||||
}
|
||||
|
||||
return columnName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml.Wordprocessing;
|
||||
using DocumentFormat.OpenXml;
|
||||
|
||||
namespace BankBusinessLogic.OfficePackage;
|
||||
|
||||
public class OpenXmlWordBuilder : BaseWordBuilder
|
||||
{
|
||||
private readonly Document _document;
|
||||
|
||||
private readonly Body _body;
|
||||
|
||||
public OpenXmlWordBuilder()
|
||||
{
|
||||
_document = new Document();
|
||||
_body = _document.AppendChild(new Body());
|
||||
}
|
||||
|
||||
public override BaseWordBuilder AddHeader(string header)
|
||||
{
|
||||
var paragraph = _body.AppendChild(new Paragraph());
|
||||
var run = paragraph.AppendChild(new Run());
|
||||
run.AppendChild(new RunProperties(new Bold()));
|
||||
run.AppendChild(new Text(header));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public override BaseWordBuilder AddParagraph(string text)
|
||||
{
|
||||
var paragraph = _body.AppendChild(new Paragraph());
|
||||
var run = paragraph.AppendChild(new Run());
|
||||
run.AppendChild(new Text(text));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public override BaseWordBuilder AddTable(int[] widths, List<string[]> data)
|
||||
{
|
||||
if (widths == null || widths.Length == 0)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(widths));
|
||||
}
|
||||
|
||||
if (data == null || data.Count == 0)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(data));
|
||||
}
|
||||
|
||||
if (data.Any(x => x.Length != widths.Length))
|
||||
{
|
||||
throw new InvalidOperationException("widths.Length != data.Length");
|
||||
}
|
||||
|
||||
var table = new Table();
|
||||
table.AppendChild(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 }
|
||||
)
|
||||
));
|
||||
|
||||
// Заголовок
|
||||
var tr = new TableRow();
|
||||
for (var j = 0; j < widths.Length; ++j)
|
||||
{
|
||||
tr.Append(new TableCell(
|
||||
new TableCellProperties(new TableCellWidth() { Width = widths[j].ToString() }),
|
||||
new Paragraph(new Run(new RunProperties(new Bold()), new Text(data.First()[j])))));
|
||||
}
|
||||
table.Append(tr);
|
||||
|
||||
// Данные
|
||||
table.Append(data.Skip(1).Select(x =>
|
||||
new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y))))))));
|
||||
|
||||
_body.Append(table);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public override Stream Build()
|
||||
{
|
||||
var stream = new MemoryStream();
|
||||
using var wordDocument = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document);
|
||||
var mainPart = wordDocument.AddMainDocumentPart();
|
||||
mainPart.Document = _document;
|
||||
return stream;
|
||||
}
|
||||
}
|
||||
18
TheBank/BankContracts/AdapterContracts/IClerkAdapter.cs
Normal file
18
TheBank/BankContracts/AdapterContracts/IClerkAdapter.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
|
||||
namespace BankContracts.AdapterContracts;
|
||||
|
||||
/// <summary>
|
||||
/// контракт адаптера для клерка
|
||||
/// </summary>
|
||||
public interface IClerkAdapter
|
||||
{
|
||||
ClerkOperationResponse GetList();
|
||||
|
||||
ClerkOperationResponse GetElement(string data);
|
||||
|
||||
ClerkOperationResponse RegisterClerk(ClerkBindingModel clerkModel);
|
||||
|
||||
ClerkOperationResponse ChangeClerkInfo(ClerkBindingModel clerkModel);
|
||||
}
|
||||
25
TheBank/BankContracts/AdapterContracts/IClientAdapter.cs
Normal file
25
TheBank/BankContracts/AdapterContracts/IClientAdapter.cs
Normal file
@@ -0,0 +1,25 @@
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BankContracts.AdapterContracts;
|
||||
|
||||
/// <summary>
|
||||
/// контракт адаптера для клиента
|
||||
/// </summary>
|
||||
public interface IClientAdapter
|
||||
{
|
||||
ClientOperationResponse GetList();
|
||||
|
||||
ClientOperationResponse GetElement(string data);
|
||||
|
||||
ClientOperationResponse GetListByClerk(string clerkId);
|
||||
|
||||
ClientOperationResponse RegisterClient(ClientBindingModel clientModel);
|
||||
|
||||
ClientOperationResponse ChangeClientInfo(ClientBindingModel clientModel);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
|
||||
namespace BankContracts.AdapterContracts;
|
||||
|
||||
public interface ICreditProgramAdapter
|
||||
{
|
||||
CreditProgramOperationResponse GetList();
|
||||
|
||||
CreditProgramOperationResponse GetElement(string data);
|
||||
|
||||
CreditProgramOperationResponse GetListByStorekeeper(string storekeeperId);
|
||||
|
||||
CreditProgramOperationResponse GetListByPeriod(string periodId);
|
||||
|
||||
CreditProgramOperationResponse RegisterCreditProgram(CreditProgramBindingModel creditProgramModel);
|
||||
|
||||
CreditProgramOperationResponse ChangeCreditProgramInfo(CreditProgramBindingModel creditProgramModel);
|
||||
}
|
||||
20
TheBank/BankContracts/AdapterContracts/ICurrencyAdapter.cs
Normal file
20
TheBank/BankContracts/AdapterContracts/ICurrencyAdapter.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
|
||||
namespace BankContracts.AdapterContracts;
|
||||
|
||||
/// <summary>
|
||||
/// контракт адаптера для валюыты
|
||||
/// </summary>
|
||||
public interface ICurrencyAdapter
|
||||
{
|
||||
CurrencyOperationResponse GetList();
|
||||
|
||||
CurrencyOperationResponse GetElement(string data);
|
||||
|
||||
CurrencyOperationResponse GetListByStorekeeper(string storekeeperId);
|
||||
|
||||
CurrencyOperationResponse MakeCurrency(CurrencyBindingModel currencyModel);
|
||||
|
||||
CurrencyOperationResponse ChangeCurrencyInfo(CurrencyBindingModel currencyModel);
|
||||
}
|
||||
20
TheBank/BankContracts/AdapterContracts/IDepositAdapter.cs
Normal file
20
TheBank/BankContracts/AdapterContracts/IDepositAdapter.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
|
||||
namespace BankContracts.AdapterContracts;
|
||||
|
||||
/// <summary>
|
||||
/// контракт адаптера для вклада
|
||||
/// </summary>
|
||||
public interface IDepositAdapter
|
||||
{
|
||||
DepositOperationResponse GetList();
|
||||
|
||||
DepositOperationResponse GetElement(string data);
|
||||
|
||||
DepositOperationResponse GetListByClerk(string clerkId);
|
||||
|
||||
DepositOperationResponse MakeDeposit(DepositBindingModel depositModel);
|
||||
|
||||
DepositOperationResponse ChangeDepositInfo(DepositBindingModel depositModel);
|
||||
}
|
||||
21
TheBank/BankContracts/AdapterContracts/IPeriodAdapter.cs
Normal file
21
TheBank/BankContracts/AdapterContracts/IPeriodAdapter.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
|
||||
namespace BankContracts.AdapterContracts;
|
||||
|
||||
public interface IPeriodAdapter
|
||||
{
|
||||
PeriodOperationResponse GetList();
|
||||
|
||||
PeriodOperationResponse GetElement(string data);
|
||||
|
||||
PeriodOperationResponse GetListByStorekeeper(string storekeeperId);
|
||||
|
||||
PeriodOperationResponse GetListByStartTime(DateTime fromDate);
|
||||
|
||||
PeriodOperationResponse GetListByEndTime(DateTime toDate);
|
||||
|
||||
PeriodOperationResponse RegisterPeriod(PeriodBindingModel periodModel);
|
||||
|
||||
PeriodOperationResponse ChangePeriodInfo(PeriodBindingModel periodModel);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
|
||||
namespace BankContracts.AdapterContracts;
|
||||
|
||||
public interface IReplenishmentAdapter
|
||||
{
|
||||
ReplenishmentOperationResponse GetList();
|
||||
|
||||
ReplenishmentOperationResponse GetElement(string data);
|
||||
|
||||
ReplenishmentOperationResponse GetListByClerk(string clerkId);
|
||||
|
||||
ReplenishmentOperationResponse GetListByDeposit(string depositId);
|
||||
|
||||
ReplenishmentOperationResponse GetListByDate(DateTime fromDate, DateTime toDate);
|
||||
|
||||
ReplenishmentOperationResponse RegisterReplenishment(ReplenishmentBindingModel replenishmentModel);
|
||||
|
||||
ReplenishmentOperationResponse ChangeReplenishmentInfo(ReplenishmentBindingModel replenishmentModel);
|
||||
}
|
||||
18
TheBank/BankContracts/AdapterContracts/IReportAdapter.cs
Normal file
18
TheBank/BankContracts/AdapterContracts/IReportAdapter.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
namespace BankContracts.AdapterContracts;
|
||||
|
||||
public interface IReportAdapter
|
||||
{
|
||||
Task<ReportOperationResponse> GetDataClientsByCreditProgramAsync(CancellationToken ct);
|
||||
Task<ReportOperationResponse> GetDataClientsByDepositAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
Task<ReportOperationResponse> GetDataDepositByCreditProgramAsync(CancellationToken ct);
|
||||
Task<ReportOperationResponse> GetDataDepositAndCreditProgramByCurrencyAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
|
||||
Task<ReportOperationResponse> CreateDocumentClientsByCreditProgramAsync(CancellationToken ct);
|
||||
Task<ReportOperationResponse> CreateExcelDocumentClientsByCreditProgramAsync(CancellationToken ct);
|
||||
Task<ReportOperationResponse> CreateDocumentClientsByDepositAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
Task<ReportOperationResponse> CreateDocumentDepositByCreditProgramAsync(CancellationToken ct);
|
||||
Task<ReportOperationResponse> CreateExcelDocumentDepositByCreditProgramAsync(CancellationToken ct);
|
||||
Task<ReportOperationResponse> CreateDocumentDepositAndCreditProgramByCurrencyAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
|
||||
namespace BankContracts.AdapterContracts;
|
||||
|
||||
/// <summary>
|
||||
/// контракт адаптера для кладовщика
|
||||
/// </summary>
|
||||
public interface IStorekeeperAdapter
|
||||
{
|
||||
StorekeeperOperationResponse GetList();
|
||||
|
||||
StorekeeperOperationResponse GetElement(string data);
|
||||
|
||||
StorekeeperOperationResponse RegisterStorekeeper(StorekeeperBindingModel storekeeperModel);
|
||||
|
||||
StorekeeperOperationResponse ChangeStorekeeperInfo(StorekeeperBindingModel storekeeperModel);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using BankContracts.Infrastructure;
|
||||
using BankContracts.ViewModels;
|
||||
|
||||
namespace BankContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class ClerkOperationResponse : OperationResponse
|
||||
{
|
||||
public static ClerkOperationResponse OK(List<ClerkViewModel> data) =>
|
||||
OK<ClerkOperationResponse, List<ClerkViewModel>>(data);
|
||||
|
||||
public static ClerkOperationResponse OK(ClerkViewModel data) =>
|
||||
OK<ClerkOperationResponse, ClerkViewModel>(data);
|
||||
|
||||
public static ClerkOperationResponse NoContent() => NoContent<ClerkOperationResponse>();
|
||||
|
||||
public static ClerkOperationResponse NotFound(string message) =>
|
||||
NotFound<ClerkOperationResponse>(message);
|
||||
|
||||
public static ClerkOperationResponse BadRequest(string message) =>
|
||||
BadRequest<ClerkOperationResponse>(message);
|
||||
|
||||
public static ClerkOperationResponse InternalServerError(string message) =>
|
||||
InternalServerError<ClerkOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using BankContracts.Infrastructure;
|
||||
using BankContracts.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BankContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class ClientOperationResponse : OperationResponse
|
||||
{
|
||||
public static ClientOperationResponse OK(List<ClientViewModel> data) =>
|
||||
OK<ClientOperationResponse, List<ClientViewModel>>(data);
|
||||
|
||||
public static ClientOperationResponse OK(ClientViewModel data) =>
|
||||
OK<ClientOperationResponse, ClientViewModel>(data);
|
||||
|
||||
public static ClientOperationResponse NoContent() => NoContent<ClientOperationResponse>();
|
||||
|
||||
public static ClientOperationResponse NotFound(string message) =>
|
||||
NotFound<ClientOperationResponse>(message);
|
||||
|
||||
public static ClientOperationResponse BadRequest(string message) =>
|
||||
BadRequest<ClientOperationResponse>(message);
|
||||
|
||||
public static ClientOperationResponse InternalServerError(string message) =>
|
||||
InternalServerError<ClientOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using BankContracts.Infrastructure;
|
||||
using BankContracts.ViewModels;
|
||||
|
||||
namespace BankContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class CreditProgramOperationResponse : OperationResponse
|
||||
{
|
||||
public static CreditProgramOperationResponse OK(List<CreditProgramViewModel> data) =>
|
||||
OK<CreditProgramOperationResponse, List<CreditProgramViewModel>>(data);
|
||||
|
||||
public static CreditProgramOperationResponse OK(CreditProgramViewModel data) =>
|
||||
OK<CreditProgramOperationResponse, CreditProgramViewModel>(data);
|
||||
|
||||
public static CreditProgramOperationResponse NoContent() => NoContent<CreditProgramOperationResponse>();
|
||||
|
||||
public static CreditProgramOperationResponse NotFound(string message) =>
|
||||
NotFound<CreditProgramOperationResponse>(message);
|
||||
|
||||
public static CreditProgramOperationResponse BadRequest(string message) =>
|
||||
BadRequest<CreditProgramOperationResponse>(message);
|
||||
|
||||
public static CreditProgramOperationResponse InternalServerError(string message) =>
|
||||
InternalServerError<CreditProgramOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using BankContracts.Infrastructure;
|
||||
using BankContracts.ViewModels;
|
||||
|
||||
namespace BankContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class CurrencyOperationResponse : OperationResponse
|
||||
{
|
||||
public static CurrencyOperationResponse OK(List<CurrencyViewModel> data) =>
|
||||
OK<CurrencyOperationResponse, List<CurrencyViewModel>>(data);
|
||||
|
||||
public static CurrencyOperationResponse OK(CurrencyViewModel data) =>
|
||||
OK<CurrencyOperationResponse, CurrencyViewModel>(data);
|
||||
|
||||
public static CurrencyOperationResponse NoContent() => NoContent<CurrencyOperationResponse>();
|
||||
|
||||
public static CurrencyOperationResponse NotFound(string message) =>
|
||||
NotFound<CurrencyOperationResponse>(message);
|
||||
|
||||
public static CurrencyOperationResponse BadRequest(string message) =>
|
||||
BadRequest<CurrencyOperationResponse>(message);
|
||||
|
||||
public static CurrencyOperationResponse InternalServerError(string message) =>
|
||||
InternalServerError<CurrencyOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using BankContracts.Infrastructure;
|
||||
using BankContracts.ViewModels;
|
||||
|
||||
namespace BankContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class DepositOperationResponse : OperationResponse
|
||||
{
|
||||
public static DepositOperationResponse OK(List<DepositViewModel> data) =>
|
||||
OK<DepositOperationResponse, List<DepositViewModel>>(data);
|
||||
|
||||
public static DepositOperationResponse OK(DepositViewModel data) =>
|
||||
OK<DepositOperationResponse, DepositViewModel>(data);
|
||||
|
||||
public static DepositOperationResponse NoContent() => NoContent<DepositOperationResponse>();
|
||||
|
||||
public static DepositOperationResponse NotFound(string message) =>
|
||||
NotFound<DepositOperationResponse>(message);
|
||||
|
||||
public static DepositOperationResponse BadRequest(string message) =>
|
||||
BadRequest<DepositOperationResponse>(message);
|
||||
|
||||
public static DepositOperationResponse InternalServerError(string message) =>
|
||||
InternalServerError<DepositOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using BankContracts.Infrastructure;
|
||||
using BankContracts.ViewModels;
|
||||
|
||||
namespace BankContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class PeriodOperationResponse : OperationResponse
|
||||
{
|
||||
public static PeriodOperationResponse OK(List<PeriodViewModel> data) =>
|
||||
OK<PeriodOperationResponse, List<PeriodViewModel>>(data);
|
||||
|
||||
public static PeriodOperationResponse OK(PeriodViewModel data) =>
|
||||
OK<PeriodOperationResponse, PeriodViewModel>(data);
|
||||
|
||||
public static PeriodOperationResponse NoContent() => NoContent<PeriodOperationResponse>();
|
||||
|
||||
public static PeriodOperationResponse NotFound(string message) =>
|
||||
NotFound<PeriodOperationResponse>(message);
|
||||
|
||||
public static PeriodOperationResponse BadRequest(string message) =>
|
||||
BadRequest<PeriodOperationResponse>(message);
|
||||
|
||||
public static PeriodOperationResponse InternalServerError(string message) =>
|
||||
InternalServerError<PeriodOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using BankContracts.Infrastructure;
|
||||
using BankContracts.ViewModels;
|
||||
|
||||
namespace BankContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class ReplenishmentOperationResponse : OperationResponse
|
||||
{
|
||||
public static ReplenishmentOperationResponse OK(List<ReplenishmentViewModel> data) =>
|
||||
OK<ReplenishmentOperationResponse, List<ReplenishmentViewModel>>(data);
|
||||
|
||||
public static ReplenishmentOperationResponse OK(ReplenishmentViewModel data) =>
|
||||
OK<ReplenishmentOperationResponse, ReplenishmentViewModel>(data);
|
||||
|
||||
public static ReplenishmentOperationResponse NoContent() => NoContent<ReplenishmentOperationResponse>();
|
||||
|
||||
public static ReplenishmentOperationResponse NotFound(string message) =>
|
||||
NotFound<ReplenishmentOperationResponse>(message);
|
||||
|
||||
public static ReplenishmentOperationResponse BadRequest(string message) =>
|
||||
BadRequest<ReplenishmentOperationResponse>(message);
|
||||
|
||||
public static ReplenishmentOperationResponse InternalServerError(string message) =>
|
||||
InternalServerError<ReplenishmentOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using BankContracts.Infrastructure;
|
||||
using BankContracts.ViewModels;
|
||||
|
||||
namespace BankContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class ReportOperationResponse : OperationResponse
|
||||
{
|
||||
public static ReportOperationResponse OK(List<ClientsByCreditProgramViewModel> data) => OK<ReportOperationResponse, List<ClientsByCreditProgramViewModel>>(data);
|
||||
|
||||
public static ReportOperationResponse OK(List<ClientsByDepositViewModel> data) => OK<ReportOperationResponse, List<ClientsByDepositViewModel>>(data);
|
||||
|
||||
public static ReportOperationResponse OK(List<DepositByCreditProgramViewModel> data) => OK<ReportOperationResponse, List<DepositByCreditProgramViewModel>>(data);
|
||||
|
||||
public static ReportOperationResponse OK(List<CreditProgramAndDepositByCurrencyViewModel> data) => OK<ReportOperationResponse, List<CreditProgramAndDepositByCurrencyViewModel>>(data);
|
||||
|
||||
public static ReportOperationResponse OK(Stream data, string fileName) => OK<ReportOperationResponse, Stream>(data, fileName);
|
||||
|
||||
public static ReportOperationResponse BadRequest(string message) => BadRequest<ReportOperationResponse>(message);
|
||||
|
||||
public static ReportOperationResponse InternalServerError(string message) => InternalServerError<ReportOperationResponse>(message);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using BankContracts.Infrastructure;
|
||||
using BankContracts.ViewModels;
|
||||
|
||||
namespace BankContracts.AdapterContracts.OperationResponses;
|
||||
|
||||
public class StorekeeperOperationResponse : OperationResponse
|
||||
{
|
||||
public static StorekeeperOperationResponse OK(List<StorekeeperViewModel> data) =>
|
||||
OK<StorekeeperOperationResponse, List<StorekeeperViewModel>>(data);
|
||||
|
||||
public static StorekeeperOperationResponse OK(StorekeeperViewModel data) =>
|
||||
OK<StorekeeperOperationResponse, StorekeeperViewModel>(data);
|
||||
|
||||
public static StorekeeperOperationResponse NoContent() => NoContent<StorekeeperOperationResponse>();
|
||||
|
||||
public static StorekeeperOperationResponse NotFound(string message) =>
|
||||
NotFound<StorekeeperOperationResponse>(message);
|
||||
|
||||
public static StorekeeperOperationResponse BadRequest(string message) =>
|
||||
BadRequest<StorekeeperOperationResponse>(message);
|
||||
|
||||
public static StorekeeperOperationResponse InternalServerError(string message) =>
|
||||
InternalServerError<StorekeeperOperationResponse>(message);
|
||||
}
|
||||
@@ -6,4 +6,10 @@
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.3.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.3.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
23
TheBank/BankContracts/BindingModels/ClerkBindingModel.cs
Normal file
23
TheBank/BankContracts/BindingModels/ClerkBindingModel.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
namespace BankContracts.BindingModels;
|
||||
|
||||
/// <summary>
|
||||
/// модель ответа от клиента для клерка
|
||||
/// </summary>
|
||||
public class ClerkBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? Name { get; set; }
|
||||
|
||||
public string? Surname { get; set; }
|
||||
|
||||
public string? MiddleName { get; set; }
|
||||
|
||||
public string? Login { get; set; }
|
||||
|
||||
public string? Password { get; set; }
|
||||
|
||||
public string? Email { get; set; }
|
||||
|
||||
public string? PhoneNumber { get; set; }
|
||||
}
|
||||
18
TheBank/BankContracts/BindingModels/ClientBindingModel.cs
Normal file
18
TheBank/BankContracts/BindingModels/ClientBindingModel.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
namespace BankContracts.BindingModels;
|
||||
|
||||
public class ClientBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? Name { get; set; }
|
||||
|
||||
public string? Surname { get; set; }
|
||||
|
||||
public decimal Balance { get; set; }
|
||||
|
||||
public string? ClerkId { get; set; }
|
||||
|
||||
public List<DepositClientBindingModel>? DepositClients { get; set; }
|
||||
|
||||
public List<ClientCreditProgramBindingModel>? CreditProgramClients { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace BankContracts.BindingModels;
|
||||
|
||||
public class ClientCreditProgramBindingModel
|
||||
{
|
||||
public string? CreditProgramId { get; set; }
|
||||
|
||||
public string? ClientId { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace BankContracts.BindingModels;
|
||||
|
||||
public class CreditProgramBindingModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string Name { get; set; }
|
||||
|
||||
public decimal Cost { get; set; }
|
||||
|
||||
public decimal MaxCost { get; set; }
|
||||
|
||||
public required string StorekeeperId { get; set; }
|
||||
|
||||
public required string PeriodId { get; set; }
|
||||
|
||||
public List<CreditProgramCurrencyBindingModel>? CurrencyCreditPrograms { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace BankContracts.BindingModels;
|
||||
|
||||
public class CreditProgramCurrencyBindingModel
|
||||
{
|
||||
public string? CreditProgramId { get; set; }
|
||||
|
||||
public string? CurrencyId { get; set; }
|
||||
}
|
||||
16
TheBank/BankContracts/BindingModels/CurrencyBindingModel.cs
Normal file
16
TheBank/BankContracts/BindingModels/CurrencyBindingModel.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
using System.Xml.Linq;
|
||||
|
||||
namespace BankContracts.BindingModels;
|
||||
|
||||
public class CurrencyBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? Name { get; set; }
|
||||
|
||||
public string? Abbreviation { get; set; }
|
||||
|
||||
public decimal Cost { get; set; }
|
||||
|
||||
public string? StorekeeperId { get; set; }
|
||||
}
|
||||
17
TheBank/BankContracts/BindingModels/DepositBindingModel.cs
Normal file
17
TheBank/BankContracts/BindingModels/DepositBindingModel.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
namespace BankContracts.BindingModels;
|
||||
|
||||
|
||||
public class DepositBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public float InterestRate { get; set; }
|
||||
|
||||
public decimal Cost { get; set; }
|
||||
|
||||
public int Period { get; set; }
|
||||
|
||||
public string? ClerkId { get; set; }
|
||||
|
||||
public List<DepositCurrencyBindingModel>? DepositCurrencies { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace BankContracts.BindingModels;
|
||||
|
||||
public class DepositClientBindingModel
|
||||
{
|
||||
public string? DepositId { get; set; }
|
||||
|
||||
public string? ClientId { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace BankContracts.BindingModels;
|
||||
|
||||
public class DepositCurrencyBindingModel
|
||||
{
|
||||
public string? DepositId { get; set; }
|
||||
|
||||
public string? CurrencyId { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
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; }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
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;
|
||||
public MemoryStream Attachment { get; set; } = new MemoryStream();
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
}
|
||||
15
TheBank/BankContracts/BindingModels/PeriodBindingModel.cs
Normal file
15
TheBank/BankContracts/BindingModels/PeriodBindingModel.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
namespace BankContracts.BindingModels;
|
||||
|
||||
/// <summary>
|
||||
/// модель ответа от клиента для срока
|
||||
/// </summary>
|
||||
public class PeriodBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public DateTime StartTime { get; set; }
|
||||
|
||||
public DateTime EndTime { get; set; }
|
||||
|
||||
public string? StorekeeperId { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace BankContracts.BindingModels;
|
||||
|
||||
public class ReplenishmentBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
public DateTime Date { get; set; }
|
||||
|
||||
public string? DepositId { get; set; }
|
||||
|
||||
public string? ClerkId { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace BankContracts.BindingModels;
|
||||
|
||||
public class StorekeeperBindingModel
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
|
||||
public string? Name { get; set; }
|
||||
|
||||
public string? Surname { get; set; }
|
||||
|
||||
public string? MiddleName { get; set; }
|
||||
|
||||
public string? Login { get; set; }
|
||||
|
||||
public string? Password { get; set; }
|
||||
|
||||
public string? Email { get; set; }
|
||||
|
||||
public string? PhoneNumber { get; set; }
|
||||
}
|
||||
@@ -3,7 +3,7 @@ namespace BankContracts.BusinessLogicContracts;
|
||||
|
||||
public interface ICurrencyBusinessLogicContract
|
||||
{
|
||||
List<CurrencyDataModel> GetAllCurrencys();
|
||||
List<CurrencyDataModel> GetAllCurrencies();
|
||||
|
||||
List<CurrencyDataModel> GetCurrencyByStorekeeper(string storekeeperId);
|
||||
|
||||
|
||||
@@ -10,9 +10,9 @@ public interface IPeriodBusinessLogicContract
|
||||
|
||||
List<PeriodDataModel> GetAllPeriodsByStorekeeper(string storekeeperId);
|
||||
|
||||
List<PeriodDataModel> GetAllPeriodsByStartTime(DateTime fromDate, DateTime toDate);
|
||||
List<PeriodDataModel> GetAllPeriodsByStartTime(DateTime fromDate);
|
||||
|
||||
List<PeriodDataModel> GetAllPeriodsByEndTime(DateTime fromDate, DateTime toDate);
|
||||
List<PeriodDataModel> GetAllPeriodsByEndTime(DateTime toDate);
|
||||
|
||||
void InsertPeriod(PeriodDataModel periodataModel);
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
using BankContracts.DataModels;
|
||||
|
||||
namespace BankContracts.BusinessLogicContracts;
|
||||
|
||||
public interface IReportContract
|
||||
{
|
||||
Task<List<ClientsByCreditProgramDataModel>> GetDataClientsByCreditProgramAsync(CancellationToken ct);
|
||||
Task<Stream> CreateDocumentClientsByCreditProgramAsync(CancellationToken ct);
|
||||
Task<Stream> CreateExcelDocumentClientsByCreditProgramAsync(CancellationToken ct);
|
||||
|
||||
Task<List<ClientsByDepositDataModel>> GetDataClientsByDepositAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
Task<Stream> CreateDocumentClientsByDepositAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
|
||||
Task<List<DepositByCreditProgramDataModel>> GetDataDepositByCreditProgramAsync(CancellationToken ct);
|
||||
Task<Stream> CreateDocumentDepositByCreditProgramAsync(CancellationToken ct);
|
||||
Task<Stream> CreateExcelDocumentDepositByCreditProgramAsync(CancellationToken ct);
|
||||
|
||||
Task<List<CreditProgramAndDepositByCurrencyDataModel>> GetDataDepositAndCreditProgramByCurrencyAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
Task<Stream> CreateDocumentDepositAndCreditProgramByCurrencyAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace BankContracts.DataModels;
|
||||
|
||||
public class ClientsByCreditProgramDataModel
|
||||
{
|
||||
public required string CreditProgramName { get; set; }
|
||||
public required List<string> ClientSurname { get; set; }
|
||||
public required List<string> ClientName { get; set; }
|
||||
public required List<decimal> ClientBalance { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace BankContracts.DataModels;
|
||||
|
||||
public class ClientsByDepositDataModel
|
||||
{
|
||||
public required string ClientSurname { get; set; }
|
||||
public required string ClientName { get; set; }
|
||||
public required decimal ClientBalance { get; set; }
|
||||
public required float DepositRate { get; set; }
|
||||
public required int DepositPeriod { get; set; }
|
||||
public DateTime FromPeriod { get; set; }
|
||||
public DateTime ToPeriod { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace BankContracts.DataModels;
|
||||
|
||||
public class CreditProgramAndDepositByCurrencyDataModel
|
||||
{
|
||||
public required string CurrencyName { get; set; }
|
||||
public required List<string> CreditProgramName { get; set; }
|
||||
public required List<int> CreditProgramMaxCost { get; set; }
|
||||
public required List<float> DepositRate { get; set; }
|
||||
public required List<int> DepositPeriod { get; set; }
|
||||
public DateTime FromPeriod { get; set; }
|
||||
public DateTime ToPeriod { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace BankContracts.DataModels;
|
||||
|
||||
public class DepositByCreditProgramDataModel
|
||||
{
|
||||
public required string CreditProgramName { get; set; }
|
||||
public required List<float> DepositRate { get; set; }
|
||||
public required List<decimal> DepositCost { get; set; }
|
||||
public required List<int> DepositPeriod { get; set; }
|
||||
}
|
||||
61
TheBank/BankContracts/Infrastructure/OperationResponse.cs
Normal file
61
TheBank/BankContracts/Infrastructure/OperationResponse.cs
Normal file
@@ -0,0 +1,61 @@
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace BankContracts.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// класс для http ответов
|
||||
/// </summary>
|
||||
public class OperationResponse
|
||||
{
|
||||
protected HttpStatusCode StatusCode { get; set; }
|
||||
|
||||
protected object? Result { get; set; }
|
||||
|
||||
protected string? FileName { get; set; }
|
||||
|
||||
public IActionResult GetResponse(HttpRequest request, HttpResponse response)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
ArgumentNullException.ThrowIfNull(response);
|
||||
|
||||
response.StatusCode = (int)StatusCode;
|
||||
|
||||
if (Result is null)
|
||||
{
|
||||
return new StatusCodeResult((int)StatusCode);
|
||||
}
|
||||
if (Result is Stream stream)
|
||||
{
|
||||
return new FileStreamResult(stream, "application/octetstream")
|
||||
{
|
||||
FileDownloadName = FileName
|
||||
};
|
||||
}
|
||||
|
||||
return new ObjectResult(Result);
|
||||
}
|
||||
|
||||
protected static TResult OK<TResult, TData>(TData data)
|
||||
where TResult : OperationResponse, new() =>
|
||||
new() { StatusCode = HttpStatusCode.OK, Result = data };
|
||||
|
||||
protected static TResult OK<TResult, TData>(TData data, string fileName) where TResult : OperationResponse,
|
||||
new() => new() { StatusCode = HttpStatusCode.OK, Result = data, FileName = fileName };
|
||||
|
||||
protected static TResult NoContent<TResult>()
|
||||
where TResult : OperationResponse, new() => new() { StatusCode = HttpStatusCode.NoContent };
|
||||
|
||||
protected static TResult BadRequest<TResult>(string? errorMessage = null)
|
||||
where TResult : OperationResponse, new() =>
|
||||
new() { StatusCode = HttpStatusCode.BadRequest, Result = errorMessage };
|
||||
|
||||
protected static TResult NotFound<TResult>(string? errorMessage = null)
|
||||
where TResult : OperationResponse, new() =>
|
||||
new() { StatusCode = HttpStatusCode.NotFound, Result = errorMessage };
|
||||
|
||||
protected static TResult InternalServerError<TResult>(string? errorMessage = null)
|
||||
where TResult : OperationResponse, new() =>
|
||||
new() { StatusCode = HttpStatusCode.InternalServerError, Result = errorMessage };
|
||||
}
|
||||
@@ -6,6 +6,8 @@ public interface IClientStorageContract
|
||||
{
|
||||
List<ClientDataModel> GetList(string? clerkId = null);
|
||||
|
||||
Task<List<ClientDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
|
||||
|
||||
ClientDataModel? GetElementById(string id);
|
||||
|
||||
ClientDataModel? GetElementByName(string name);
|
||||
|
||||
@@ -6,6 +6,8 @@ public interface ICreditProgramStorageContract
|
||||
{
|
||||
List<CreditProgramDataModel> GetList(string? storekeeperId = null, string? periodId = null);
|
||||
|
||||
Task<List<CreditProgramDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
|
||||
|
||||
CreditProgramDataModel? GetElementById(string id);
|
||||
|
||||
void AddElement(CreditProgramDataModel creditProgramDataModel);
|
||||
|
||||
@@ -6,6 +6,8 @@ public interface ICurrencyStorageContract
|
||||
{
|
||||
List<CurrencyDataModel> GetList(string? storekeeperId = null);
|
||||
|
||||
Task<List<CurrencyDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
|
||||
|
||||
CurrencyDataModel? GetElementById(string id);
|
||||
|
||||
CurrencyDataModel? GetElementByAbbreviation(string abbreviation);
|
||||
|
||||
@@ -6,6 +6,8 @@ public interface IDepositStorageContract
|
||||
{
|
||||
List<DepositDataModel> GetList(string? clerkId = null);
|
||||
|
||||
Task<List<DepositDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct);
|
||||
|
||||
DepositDataModel? GetElementById(string id);
|
||||
|
||||
DepositDataModel? GetElementByInterestRate(float interestRate);
|
||||
|
||||
23
TheBank/BankContracts/ViewModels/ClerkViewModel.cs
Normal file
23
TheBank/BankContracts/ViewModels/ClerkViewModel.cs
Normal file
@@ -0,0 +1,23 @@
|
||||
namespace BankContracts.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// модель представления для клерка
|
||||
/// </summary>
|
||||
public class ClerkViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string Name { get; set; }
|
||||
|
||||
public required string Surname { get; set; }
|
||||
|
||||
public required string MiddleName { get; set; }
|
||||
|
||||
public required string Login { get; set; }
|
||||
|
||||
public required string Password { get; set; }
|
||||
|
||||
public required string Email { get; set; }
|
||||
|
||||
public required string PhoneNumber { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace BankContracts.ViewModels;
|
||||
|
||||
public class ClientCreditProgramViewModel
|
||||
{
|
||||
public required string? CreditProgramId { get; set; }
|
||||
|
||||
public required string? ClientId { get; set; }
|
||||
}
|
||||
18
TheBank/BankContracts/ViewModels/ClientViewModel.cs
Normal file
18
TheBank/BankContracts/ViewModels/ClientViewModel.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
namespace BankContracts.ViewModels;
|
||||
|
||||
public class ClientViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string Name { get; set; }
|
||||
|
||||
public required string Surname { get; set; }
|
||||
|
||||
public required decimal Balance { get; set; }
|
||||
|
||||
public required string ClerkId { get; set; }
|
||||
|
||||
public required List<DepositClientViewModel> DepositClients { get; set; }
|
||||
|
||||
public required List<ClientCreditProgramViewModel>? CreditProgramClients { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace BankContracts.ViewModels;
|
||||
|
||||
public class ClientsByCreditProgramViewModel
|
||||
{
|
||||
public required string CreditProgramName { get; set; }
|
||||
public required List<string> ClientSurname { get; set; }
|
||||
public required List<string> ClientName { get; set; }
|
||||
public required List<decimal> ClientBalance { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace BankContracts.ViewModels;
|
||||
|
||||
public class ClientsByDepositViewModel
|
||||
{
|
||||
public required string ClientSurname { get; set; }
|
||||
public required string ClientName { get; set; }
|
||||
public required decimal ClientBalance { get; set; }
|
||||
public required float DepositRate { get; set; }
|
||||
public required int DepositPeriod { get; set; }
|
||||
public DateTime FromPeriod { get; set; }
|
||||
public DateTime ToPeriod { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace BankContracts.ViewModels;
|
||||
|
||||
public class CreditProgramAndDepositByCurrencyViewModel
|
||||
{
|
||||
public required string CurrencyName { get; set; }
|
||||
public required List<string> CreditProgramName { get; set; }
|
||||
public required List<int> CreditProgramMaxCost { get; set; }
|
||||
public required List<float> DepositRate { get; set; }
|
||||
public required List<int> DepositPeriod { get; set; }
|
||||
public DateTime FromPeriod { get; set; }
|
||||
public DateTime ToPeriod { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace BankContracts.ViewModels;
|
||||
|
||||
public class CreditProgramCurrencyViewModel
|
||||
{
|
||||
public required string CreditProgramId { get; set; }
|
||||
|
||||
public required string CurrencyId { get; set; }
|
||||
}
|
||||
21
TheBank/BankContracts/ViewModels/CreditProgramViewModel.cs
Normal file
21
TheBank/BankContracts/ViewModels/CreditProgramViewModel.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
namespace BankContracts.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// модель представления для кредитной программы
|
||||
/// </summary>
|
||||
public class CreditProgramViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string Name { get; set; }
|
||||
|
||||
public decimal Cost { get; set; }
|
||||
|
||||
public decimal MaxCost { get; set; }
|
||||
|
||||
public required string StorekeeperId { get; set; }
|
||||
|
||||
public required string PeriodId { get; set; }
|
||||
|
||||
public required List<CreditProgramCurrencyViewModel>? CurrencyCreditPrograms { get; set; }
|
||||
}
|
||||
14
TheBank/BankContracts/ViewModels/CurrencyViewModel.cs
Normal file
14
TheBank/BankContracts/ViewModels/CurrencyViewModel.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
namespace BankContracts.ViewModels;
|
||||
|
||||
public class CurrencyViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string Name { get; set; }
|
||||
|
||||
public required string Abbreviation { get; set; }
|
||||
|
||||
public required decimal Cost { get; set; }
|
||||
|
||||
public required string StorekeeperId { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace BankContracts.ViewModels;
|
||||
|
||||
public class DepositByCreditProgramViewModel
|
||||
{
|
||||
public required string CreditProgramName { get; set; }
|
||||
public required List<float> DepositRate { get; set; }
|
||||
public required List<decimal> DepositCost { get; set; }
|
||||
public required List<int> DepositPeriod { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace BankContracts.ViewModels;
|
||||
|
||||
public class DepositClientViewModel
|
||||
{
|
||||
public required string DepositId { get; set; }
|
||||
|
||||
public required string ClientId { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace BankContracts.ViewModels;
|
||||
|
||||
public class DepositCurrencyViewModel
|
||||
{
|
||||
public required string DepositId { get; set; }
|
||||
|
||||
public required string CurrencyId { get; set; }
|
||||
}
|
||||
22
TheBank/BankContracts/ViewModels/DepositViewModel.cs
Normal file
22
TheBank/BankContracts/ViewModels/DepositViewModel.cs
Normal file
@@ -0,0 +1,22 @@
|
||||
using BankContracts.BindingModels;
|
||||
|
||||
namespace BankContracts.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// модель представления для вклада
|
||||
/// </summary>
|
||||
public class DepositViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required float InterestRate { get; set; }
|
||||
|
||||
public required decimal Cost { get; set; }
|
||||
|
||||
public required int Period { get; set; }
|
||||
|
||||
public required string ClerkId { get; set; }
|
||||
|
||||
public required List<DepositCurrencyBindingModel>? DepositCurrencies { get; set; }
|
||||
|
||||
}
|
||||
15
TheBank/BankContracts/ViewModels/PeriodViewModel.cs
Normal file
15
TheBank/BankContracts/ViewModels/PeriodViewModel.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
namespace BankContracts.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// модель представления для срока
|
||||
/// </summary>
|
||||
public class PeriodViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public DateTime StartTime { get; set; }
|
||||
|
||||
public DateTime EndTime { get; set; }
|
||||
|
||||
public required string StorekeeperId { get; set; }
|
||||
}
|
||||
14
TheBank/BankContracts/ViewModels/ReplenishmentViewModel.cs
Normal file
14
TheBank/BankContracts/ViewModels/ReplenishmentViewModel.cs
Normal file
@@ -0,0 +1,14 @@
|
||||
namespace BankContracts.ViewModels;
|
||||
|
||||
public class ReplenishmentViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required decimal Amount { get; set; }
|
||||
|
||||
public required DateTime Date { get; set; }
|
||||
|
||||
public required string DepositId { get; set; }
|
||||
|
||||
public required string ClerkId { get; set; }
|
||||
}
|
||||
20
TheBank/BankContracts/ViewModels/StorekeeperViewModel.cs
Normal file
20
TheBank/BankContracts/ViewModels/StorekeeperViewModel.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
namespace BankContracts.ViewModels;
|
||||
|
||||
public class StorekeeperViewModel
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
public required string Name { get; set; }
|
||||
|
||||
public required string Surname { get; set; }
|
||||
|
||||
public required string MiddleName { get; set; }
|
||||
|
||||
public required string Login { get; set; }
|
||||
|
||||
public required string Password { get; set; }
|
||||
|
||||
public required string Email { get; set; }
|
||||
|
||||
public required string PhoneNumber { get; set; }
|
||||
}
|
||||
@@ -20,4 +20,8 @@
|
||||
<InternalsVisibleTo Include="BankTests" />
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<InternalsVisibleTo Include="BankWebApi" />
|
||||
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -57,7 +57,11 @@ internal class ClientStorageContract : IClientStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Clients.Include(x => x.Clerk).AsQueryable();
|
||||
var query = _dbContext.Clients
|
||||
.Include(x => x.Clerk)
|
||||
.Include(x => x.CreditProgramClients)
|
||||
.Include(x => x.DepositClients)
|
||||
.AsQueryable();
|
||||
if (clerkId is not null)
|
||||
{
|
||||
query = query.Where(x => x.ClerkId == clerkId);
|
||||
@@ -139,6 +143,23 @@ internal class ClientStorageContract : IClientStorageContract
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<List<ClientDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var clients = await _dbContext.Clients
|
||||
.Include(x => x.Clerk)
|
||||
.ToListAsync(ct);
|
||||
|
||||
return clients.Select(x => _mapper.Map<ClientDataModel>(x)).ToList();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public void UpdElement(ClientDataModel clientDataModel)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -42,7 +42,9 @@ internal class CreditProgramStorageContract : ICreditProgramStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.CreditPrograms.AsQueryable();
|
||||
var query = _dbContext.CreditPrograms
|
||||
.Include(x => x.CurrencyCreditPrograms)
|
||||
.AsQueryable();
|
||||
if (storekeeperId is not null)
|
||||
{
|
||||
query = query.Where(x => x.StorekeeperId == storekeeperId);
|
||||
@@ -60,6 +62,23 @@ internal class CreditProgramStorageContract : ICreditProgramStorageContract
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<List<CreditProgramDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.CreditPrograms.AsQueryable();
|
||||
//query = query.Where(x => x.CreatedDate >= startDate && x.CreatedDate <= endDate);
|
||||
|
||||
var creditPrograms = await query.ToListAsync(ct);
|
||||
return creditPrograms.Select(x => _mapper.Map<CreditProgramDataModel>(x)).ToList();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public CreditProgramDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -46,6 +46,23 @@ internal class CurrencyStorageContract : ICurrencyStorageContract
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<List<CurrencyDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Currencies.AsQueryable();
|
||||
// query = query.Where(x => x.CreatedDate >= startDate && x.CreatedDate <= endDate);
|
||||
|
||||
var currencies = await query.ToListAsync(ct);
|
||||
return currencies.Select(x => _mapper.Map<CurrencyDataModel>(x)).ToList();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public CurrencyDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -19,8 +19,18 @@ internal class DepositStorageContract : IDepositStorageContract
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<Clerk, ClerkDataModel>();
|
||||
cfg.CreateMap<Deposit, DepositDataModel>();
|
||||
cfg.CreateMap<DepositDataModel, Deposit>();
|
||||
cfg.CreateMap<Deposit, DepositDataModel>()
|
||||
.ForMember(dest => dest.Currencies, opt => opt.MapFrom(src => src.DepositCurrencies));
|
||||
cfg.CreateMap<DepositDataModel, Deposit>()
|
||||
.ForMember(dest => dest.DepositCurrencies, opt => opt.MapFrom(src => src.Currencies));
|
||||
cfg.CreateMap<DepositCurrency, DepositCurrencyDataModel>()
|
||||
.ForMember(dest => dest.DepositId, opt => opt.MapFrom(src => src.DepositId))
|
||||
.ForMember(dest => dest.CurrencyId, opt => opt.MapFrom(src => src.CurrencyId));
|
||||
cfg.CreateMap<DepositCurrencyDataModel, DepositCurrency>()
|
||||
.ForMember(dest => dest.DepositId, opt => opt.MapFrom(src => src.DepositId))
|
||||
.ForMember(dest => dest.CurrencyId, opt => opt.MapFrom(src => src.CurrencyId))
|
||||
.ForMember(dest => dest.Deposit, opt => opt.Ignore())
|
||||
.ForMember(dest => dest.Currency, opt => opt.Ignore());
|
||||
cfg.CreateMap<Replenishment, ReplenishmentDataModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
@@ -29,7 +39,10 @@ internal class DepositStorageContract : IDepositStorageContract
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Deposits.Include(x => x.Clerk).AsQueryable();
|
||||
var query = _dbContext.Deposits
|
||||
.Include(x => x.Clerk)
|
||||
.Include(x => x.DepositCurrencies)
|
||||
.AsQueryable();
|
||||
if (clerkId is not null)
|
||||
{
|
||||
query = query.Where(x => x.ClerkId == clerkId);
|
||||
@@ -43,6 +56,23 @@ internal class DepositStorageContract : IDepositStorageContract
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<List<DepositDataModel>> GetListAsync(DateTime startDate, DateTime endDate, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var query = _dbContext.Deposits.Include(x => x.Clerk).AsQueryable();
|
||||
// Например: query = query.Where(x => x.CreatedDate >= startDate && x.CreatedDate <= endDate);
|
||||
|
||||
var deposits = await query.ToListAsync(ct);
|
||||
return deposits.Select(x => _mapper.Map<DepositDataModel>(x)).ToList();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_dbContext.ChangeTracker.Clear();
|
||||
throw new StorageException(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public DepositDataModel? GetElementById(string id)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BankDatabase.Models;
|
||||
namespace BankDatabase.Models;
|
||||
|
||||
class DepositCurrency
|
||||
{
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using BankContracts.DataModels;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace BankDatabase.Models;
|
||||
|
||||
|
||||
@@ -12,15 +12,19 @@
|
||||
<PackageReference Include="coverlet.collector" Version="6.0.2" />
|
||||
<PackageReference Include="EntityFramework" Version="5.0.0" />
|
||||
<PackageReference Include="EntityFramework.ru" Version="5.0.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="NUnit" Version="4.2.2" />
|
||||
<PackageReference Include="NUnit.Analyzers" Version="4.4.0" />
|
||||
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
|
||||
<PackageReference Include="Serilog" Version="4.2.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\BankContracts\BankContracts.csproj" />
|
||||
<ProjectReference Include="..\BankDatabase\BankDatabase.csproj" />
|
||||
<ProjectReference Include="..\BankWebApi\BankWebApi.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
using BankBusinessLogic.Implementations;
|
||||
using BankBusinessLogic.OfficePackage;
|
||||
using BankContracts.DataModels;
|
||||
using BankContracts.StorageContracts;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using System.Text;
|
||||
|
||||
namespace BankTests.BusinessLogicContractTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ReportContractTestss
|
||||
{
|
||||
private ReportContract _reportContract;
|
||||
private Mock<IClientStorageContract> _clientStorage;
|
||||
private Mock<ICurrencyStorageContract> _currencyStorage;
|
||||
private Mock<ICreditProgramStorageContract> _creditProgramStorage;
|
||||
private Mock<IDepositStorageContract> _depositStorage;
|
||||
private Mock<BaseWordBuilder> _baseWordBuilder;
|
||||
private Mock<BaseExcelBuilder> _baseExcelBuilder;
|
||||
private Mock<BasePdfBuilder> _basePdfBuilder;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_clientStorage = new Mock<IClientStorageContract>();
|
||||
_currencyStorage = new Mock<ICurrencyStorageContract>();
|
||||
_creditProgramStorage = new Mock<ICreditProgramStorageContract>();
|
||||
_depositStorage = new Mock<IDepositStorageContract>();
|
||||
_baseWordBuilder = new Mock<BaseWordBuilder>();
|
||||
_baseExcelBuilder = new Mock<BaseExcelBuilder>();
|
||||
_basePdfBuilder = new Mock<BasePdfBuilder>();
|
||||
_reportContract = new ReportContract(_clientStorage.Object, _currencyStorage.Object, _creditProgramStorage.Object, _depositStorage.Object,
|
||||
_baseWordBuilder.Object, _baseExcelBuilder.Object, _basePdfBuilder.Object, new Mock<ILogger>().Object);
|
||||
}
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_clientStorage.Reset();
|
||||
_currencyStorage.Reset();
|
||||
_creditProgramStorage.Reset();
|
||||
_depositStorage.Reset();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetDataDepositByCreditProgramAsync_ReturnsData()
|
||||
{
|
||||
var ct = CancellationToken.None;
|
||||
_creditProgramStorage.Setup(x => x.GetList(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(new List<CreditProgramDataModel>
|
||||
{
|
||||
new CreditProgramDataModel("1", "Кредит 1", 100, 200, "sk", "p", new List<CreditProgramCurrencyDataModel>())
|
||||
});
|
||||
_depositStorage.Setup(x => x.GetList(It.IsAny<string>()))
|
||||
.Returns(new List<DepositDataModel>
|
||||
{
|
||||
new DepositDataModel("d1", 5, 1000, 12, "cl", new List<DepositCurrencyDataModel>())
|
||||
});
|
||||
|
||||
var result = await _reportContract.GetDataDepositByCreditProgramAsync(ct);
|
||||
|
||||
Assert.That(result, Is.Not.Null);
|
||||
Assert.That(result.Count, Is.GreaterThanOrEqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateDocumentDepositByCreditProgramAsync_CallsWordBuilder()
|
||||
{
|
||||
var ct = CancellationToken.None;
|
||||
_creditProgramStorage.Setup(x => x.GetList(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(new List<CreditProgramDataModel>
|
||||
{
|
||||
new CreditProgramDataModel("1", "Кредит 1", 100, 200, "sk", "p", new List<CreditProgramCurrencyDataModel>())
|
||||
});
|
||||
_depositStorage.Setup(x => x.GetList(It.IsAny<string>()))
|
||||
.Returns(new List<DepositDataModel>
|
||||
{
|
||||
new DepositDataModel("d1", 5, 1000, 12, "cl", new List<DepositCurrencyDataModel>())
|
||||
});
|
||||
|
||||
_baseWordBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_baseWordBuilder.Object);
|
||||
_baseWordBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>())).Returns(_baseWordBuilder.Object);
|
||||
_baseWordBuilder.Setup(x => x.Build()).Returns(new MemoryStream(Encoding.UTF8.GetBytes("test")));
|
||||
|
||||
var stream = await _reportContract.CreateDocumentDepositByCreditProgramAsync(ct);
|
||||
|
||||
Assert.That(stream, Is.Not.Null);
|
||||
_baseWordBuilder.Verify(x => x.AddHeader(It.IsAny<string>()), Times.Once);
|
||||
_baseWordBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
|
||||
_baseWordBuilder.Verify(x => x.Build(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateDocumentClientsByDepositAsync_CallsPdfBuilder()
|
||||
{
|
||||
var ct = CancellationToken.None;
|
||||
var dateStart = new DateTime(2024, 1, 1);
|
||||
var dateFinish = new DateTime(2024, 12, 31);
|
||||
|
||||
_clientStorage.Setup(x => x.GetList(It.IsAny<string>()))
|
||||
.Returns(new List<ClientDataModel>
|
||||
{
|
||||
new("1", "Иван", "Иванов", 1000, "cl", new(), new())
|
||||
});
|
||||
_depositStorage.Setup(x => x.GetListAsync(dateStart, dateFinish, ct))
|
||||
.ReturnsAsync(new List<DepositDataModel>
|
||||
{
|
||||
new("d1", 5, 1000, 12, "cl", new())
|
||||
});
|
||||
|
||||
_basePdfBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_basePdfBuilder.Object);
|
||||
_basePdfBuilder.Setup(x => x.AddParagraph(It.IsAny<string>())).Returns(_basePdfBuilder.Object);
|
||||
_basePdfBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>())).Returns(_basePdfBuilder.Object);
|
||||
_basePdfBuilder.Setup(x => x.Build()).Returns(new MemoryStream(Encoding.UTF8.GetBytes("test")));
|
||||
|
||||
var stream = await _reportContract.CreateDocumentClientsByDepositAsync(dateStart, dateFinish, ct);
|
||||
|
||||
Assert.That(stream, Is.Not.Null);
|
||||
_basePdfBuilder.Verify(x => x.AddHeader(It.IsAny<string>()), Times.Once);
|
||||
_basePdfBuilder.Verify(x => x.AddParagraph(It.IsAny<string>()), Times.Once);
|
||||
_basePdfBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
|
||||
_basePdfBuilder.Verify(x => x.Build(), Times.Once);
|
||||
}
|
||||
}
|
||||
@@ -89,7 +89,7 @@ internal static class BankDbContextExtension
|
||||
string? name = "bankrot",
|
||||
decimal cost = 1_000_000,
|
||||
decimal maxCost = 10_000_000,
|
||||
string? storeleeperId = null,
|
||||
string? storekeeperId = null,
|
||||
string? periodId = null,
|
||||
List<(string currencyId, string creditProgramId)>? creditProgramCurrency = null // Item1 = ClientId Item2 = CreditProgramId
|
||||
)
|
||||
@@ -100,7 +100,7 @@ internal static class BankDbContextExtension
|
||||
Name = name,
|
||||
Cost = cost,
|
||||
MaxCost = maxCost,
|
||||
StorekeeperId = storeleeperId ?? Guid.NewGuid().ToString(),
|
||||
StorekeeperId = storekeeperId ?? Guid.NewGuid().ToString(),
|
||||
PeriodId = periodId ?? Guid.NewGuid().ToString(),
|
||||
};
|
||||
dbContext.CreditPrograms.Add(creditProgram);
|
||||
|
||||
@@ -5,5 +5,5 @@ namespace BankTests.Infrastructure;
|
||||
internal class ConfigurationDatabase : IConfigurationDatabase
|
||||
{
|
||||
public string ConnectionString =>
|
||||
"Host=127.0.0.1;Port=5432;Database=TitanicTest;Username=postgres;Password=admin123;Include Error Detail=true";
|
||||
"Host=127.0.0.1;Port=5432;Database=TitanicTest;Username=postgres;Password=postgres;Include Error Detail=true";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
using BankContracts.Infrastructure;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace BankTests.Infrastructure;
|
||||
|
||||
internal class CustomWebApplicationFactory<TProgram> : WebApplicationFactory<TProgram>
|
||||
where TProgram : class
|
||||
{
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
var databaseConfig = services.SingleOrDefault(x => x.ServiceType == typeof(IConfigurationDatabase));
|
||||
if (databaseConfig is not null)
|
||||
services.Remove(databaseConfig);
|
||||
|
||||
var loggerFactory = services.SingleOrDefault(x => x.ServiceType == typeof(LoggerFactory));
|
||||
if (loggerFactory is not null)
|
||||
services.Remove(loggerFactory);
|
||||
|
||||
services.AddSingleton<IConfigurationDatabase, ConfigurationDatabase>();
|
||||
});
|
||||
|
||||
builder.UseEnvironment("Development");
|
||||
|
||||
base.ConfigureWebHost(builder);
|
||||
}
|
||||
}
|
||||
192
TheBank/BankTests/ReportContractTests/ReportContractTests.cs
Normal file
192
TheBank/BankTests/ReportContractTests/ReportContractTests.cs
Normal file
@@ -0,0 +1,192 @@
|
||||
using BankBusinessLogic.Implementations;
|
||||
using BankBusinessLogic.OfficePackage;
|
||||
using BankContracts.BusinessLogicContracts;
|
||||
using BankContracts.DataModels;
|
||||
using BankContracts.StorageContracts;
|
||||
using BankDatabase.Implementations;
|
||||
using BankTests.Infrastructure;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
using System.Text;
|
||||
|
||||
namespace BankTests.ReportContractTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ReportContractTestss
|
||||
{
|
||||
private ReportContract _reportContract;
|
||||
private Mock<IClientStorageContract> _clientStorage;
|
||||
private Mock<ICurrencyStorageContract> _currencyStorage;
|
||||
private Mock<ICreditProgramStorageContract> _creditProgramStorage;
|
||||
private Mock<IDepositStorageContract> _depositStorage;
|
||||
private Mock<BaseWordBuilder> _baseWordBuilder;
|
||||
private Mock<BaseExcelBuilder> _baseExcelBuilder;
|
||||
private Mock<BasePdfBuilder> _basePdfBuilder;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_clientStorage = new Mock<IClientStorageContract>();
|
||||
_currencyStorage = new Mock<ICurrencyStorageContract>();
|
||||
_creditProgramStorage = new Mock<ICreditProgramStorageContract>();
|
||||
_depositStorage = new Mock<IDepositStorageContract>();
|
||||
_baseWordBuilder = new Mock<BaseWordBuilder>();
|
||||
_baseExcelBuilder = new Mock<BaseExcelBuilder>();
|
||||
_basePdfBuilder = new Mock<BasePdfBuilder>();
|
||||
_reportContract = new ReportContract(_clientStorage.Object, _currencyStorage.Object, _creditProgramStorage.Object, _depositStorage.Object,
|
||||
_baseWordBuilder.Object, _baseExcelBuilder.Object, _basePdfBuilder.Object, new Mock<ILogger>().Object);
|
||||
}
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_clientStorage.Reset();
|
||||
_currencyStorage.Reset();
|
||||
_creditProgramStorage.Reset();
|
||||
_depositStorage.Reset();
|
||||
_baseWordBuilder.Reset();
|
||||
_baseExcelBuilder.Reset();
|
||||
_basePdfBuilder.Reset();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetDataDepositByCreditProgramAsync_ReturnsData()
|
||||
{
|
||||
var ct = CancellationToken.None;
|
||||
_creditProgramStorage.Setup(x => x.GetList(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(new List<CreditProgramDataModel>
|
||||
{
|
||||
new CreditProgramDataModel("1", "Программа 1", 100, 200, "sk", "p", new List<CreditProgramCurrencyDataModel>())
|
||||
});
|
||||
_depositStorage.Setup(x => x.GetList(It.IsAny<string>()))
|
||||
.Returns(new List<DepositDataModel>
|
||||
{
|
||||
new DepositDataModel("d1", 5, 1000, 12, "cl", new List<DepositCurrencyDataModel>())
|
||||
});
|
||||
|
||||
var result = await _reportContract.GetDataDepositByCreditProgramAsync(ct);
|
||||
|
||||
Assert.That(result, Is.Not.Null);
|
||||
Assert.That(result.Count, Is.GreaterThanOrEqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateDocumentDepositByCreditProgramAsync_CallsWordBuilder()
|
||||
{
|
||||
var ct = CancellationToken.None;
|
||||
_creditProgramStorage.Setup(x => x.GetList(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(new List<CreditProgramDataModel>
|
||||
{
|
||||
new CreditProgramDataModel("1", "Программа 1", 100, 200, "sk", "p", new List<CreditProgramCurrencyDataModel>())
|
||||
});
|
||||
_depositStorage.Setup(x => x.GetList(It.IsAny<string>()))
|
||||
.Returns(new List<DepositDataModel>
|
||||
{
|
||||
new DepositDataModel("d1", 5, 1000, 12, "cl", new List<DepositCurrencyDataModel>())
|
||||
});
|
||||
|
||||
_baseWordBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_baseWordBuilder.Object);
|
||||
_baseWordBuilder.Setup(x => x.AddParagraph(It.IsAny<string>())).Returns(_baseWordBuilder.Object);
|
||||
_baseWordBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>())).Returns(_baseWordBuilder.Object);
|
||||
_baseWordBuilder.Setup(x => x.Build()).Returns(new MemoryStream(Encoding.UTF8.GetBytes("test")));
|
||||
|
||||
var stream = await _reportContract.CreateDocumentDepositByCreditProgramAsync(ct);
|
||||
|
||||
Assert.That(stream, Is.Not.Null);
|
||||
_baseWordBuilder.Verify(x => x.AddHeader(It.IsAny<string>()), Times.Once);
|
||||
_baseWordBuilder.Verify(x => x.AddParagraph(It.IsAny<string>()), Times.Once);
|
||||
_baseWordBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
|
||||
_baseWordBuilder.Verify(x => x.Build(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateDocumentClientsByDepositAsync_CallsPdfBuilder()
|
||||
{
|
||||
var ct = CancellationToken.None;
|
||||
var dateStart = new DateTime(2024, 1, 1);
|
||||
var dateFinish = new DateTime(2024, 12, 31);
|
||||
|
||||
_clientStorage.Setup(x => x.GetList(It.IsAny<string>()))
|
||||
.Returns(new List<ClientDataModel>
|
||||
{
|
||||
new("1", "Иван", "Иванов", 1000, "cl", new(), new())
|
||||
});
|
||||
_depositStorage.Setup(x => x.GetListAsync(dateStart, dateFinish, ct))
|
||||
.ReturnsAsync(new List<DepositDataModel>
|
||||
{
|
||||
new("d1", 5, 1000, 12, "cl", new())
|
||||
});
|
||||
|
||||
_basePdfBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_basePdfBuilder.Object);
|
||||
_basePdfBuilder.Setup(x => x.AddParagraph(It.IsAny<string>())).Returns(_basePdfBuilder.Object);
|
||||
_basePdfBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>())).Returns(_basePdfBuilder.Object);
|
||||
_basePdfBuilder.Setup(x => x.Build()).Returns(new MemoryStream(Encoding.UTF8.GetBytes("test")));
|
||||
|
||||
var stream = await _reportContract.CreateDocumentClientsByDepositAsync(dateStart, dateFinish, ct);
|
||||
|
||||
Assert.That(stream, Is.Not.Null);
|
||||
_basePdfBuilder.Verify(x => x.AddHeader(It.IsAny<string>()), Times.Once);
|
||||
_basePdfBuilder.Verify(x => x.AddParagraph(It.IsAny<string>()), Times.Once);
|
||||
_basePdfBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
|
||||
_basePdfBuilder.Verify(x => x.Build(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateExcelDocumentClientsByCreditProgramAsync_CallsExcelBuilder()
|
||||
{
|
||||
var ct = CancellationToken.None;
|
||||
_clientStorage.Setup(x => x.GetList(It.IsAny<string>()))
|
||||
.Returns(new List<ClientDataModel>
|
||||
{
|
||||
new("1", "Иван", "Иванов", 1000, "cl", new(), new())
|
||||
});
|
||||
_creditProgramStorage.Setup(x => x.GetList(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(new List<CreditProgramDataModel>
|
||||
{
|
||||
new CreditProgramDataModel("1", "Программа 1", 100, 200, "sk", "p", new List<CreditProgramCurrencyDataModel>())
|
||||
});
|
||||
|
||||
_baseExcelBuilder.Setup(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).Returns(_baseExcelBuilder.Object);
|
||||
_baseExcelBuilder.Setup(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>())).Returns(_baseExcelBuilder.Object);
|
||||
_baseExcelBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>())).Returns(_baseExcelBuilder.Object);
|
||||
_baseExcelBuilder.Setup(x => x.Build()).Returns(new MemoryStream(Encoding.UTF8.GetBytes("test")));
|
||||
|
||||
var stream = await _reportContract.CreateExcelDocumentClientsByCreditProgramAsync(ct);
|
||||
|
||||
Assert.That(stream, Is.Not.Null);
|
||||
_baseExcelBuilder.Verify(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()), Times.Once);
|
||||
_baseExcelBuilder.Verify(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>()), Times.Once);
|
||||
_baseExcelBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
|
||||
_baseExcelBuilder.Verify(x => x.Build(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateExcelDocumentDepositByCreditProgramAsync_CallsExcelBuilder()
|
||||
{
|
||||
var ct = CancellationToken.None;
|
||||
_creditProgramStorage.Setup(x => x.GetList(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(new List<CreditProgramDataModel>
|
||||
{
|
||||
new CreditProgramDataModel("1", "Программа 1", 100, 200, "sk", "p", new List<CreditProgramCurrencyDataModel>())
|
||||
});
|
||||
_depositStorage.Setup(x => x.GetList(It.IsAny<string>()))
|
||||
.Returns(new List<DepositDataModel>
|
||||
{
|
||||
new DepositDataModel("d1", 5, 1000, 12, "cl", new List<DepositCurrencyDataModel>())
|
||||
});
|
||||
|
||||
_baseExcelBuilder.Setup(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).Returns(_baseExcelBuilder.Object);
|
||||
_baseExcelBuilder.Setup(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>())).Returns(_baseExcelBuilder.Object);
|
||||
_baseExcelBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>())).Returns(_baseExcelBuilder.Object);
|
||||
_baseExcelBuilder.Setup(x => x.Build()).Returns(new MemoryStream(Encoding.UTF8.GetBytes("test")));
|
||||
|
||||
var stream = await _reportContract.CreateExcelDocumentDepositByCreditProgramAsync(ct);
|
||||
|
||||
Assert.That(stream, Is.Not.Null);
|
||||
_baseExcelBuilder.Verify(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()), Times.Once);
|
||||
_baseExcelBuilder.Verify(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>()), Times.Once);
|
||||
_baseExcelBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
|
||||
_baseExcelBuilder.Verify(x => x.Build(), Times.Once);
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ internal class ClientStorageContractTests : BaseStorageContractTest
|
||||
_periodId = BankDbContext.InsertPeriodToDatabaseAndReturn(storekeeperId: _storekeeperId).Id;
|
||||
_creditProgramId = BankDbContext
|
||||
.InsertCreditProgramToDatabaseAndReturn(
|
||||
storeleeperId: _storekeeperId,
|
||||
storekeeperId: _storekeeperId,
|
||||
periodId: _periodId
|
||||
)
|
||||
.Id;
|
||||
|
||||
@@ -42,18 +42,18 @@ internal class CreditProgramStorageContractTests : BaseStorageContractTest
|
||||
{
|
||||
var creditProgramId = Guid.NewGuid().ToString();
|
||||
var creditProgram = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
storeleeperId: _storekeeperId,
|
||||
storekeeperId: _storekeeperId,
|
||||
periodId: _periodId,
|
||||
creditProgramCurrency: [( _currenyId, creditProgramId )]
|
||||
);
|
||||
BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
name: "bankrot2",
|
||||
storeleeperId: _storekeeperId,
|
||||
storekeeperId: _storekeeperId,
|
||||
periodId: _periodId
|
||||
);
|
||||
BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
name: "bankrot3",
|
||||
storeleeperId: _storekeeperId,
|
||||
storekeeperId: _storekeeperId,
|
||||
periodId: _periodId
|
||||
);
|
||||
|
||||
@@ -75,7 +75,7 @@ internal class CreditProgramStorageContractTests : BaseStorageContractTest
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
var creditProgram = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
storeleeperId: _storekeeperId,
|
||||
storekeeperId: _storekeeperId,
|
||||
periodId: _periodId
|
||||
);
|
||||
AssertElement(_storageContract.GetElementById(creditProgram.Id), creditProgram);
|
||||
@@ -100,7 +100,7 @@ internal class CreditProgramStorageContractTests : BaseStorageContractTest
|
||||
BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
name: "1",
|
||||
periodId: _periodId,
|
||||
storeleeperId: _storekeeperId,
|
||||
storekeeperId: _storekeeperId,
|
||||
creditProgramCurrency: [(_currenyId, credit.Id)]
|
||||
);
|
||||
Assert.That(
|
||||
@@ -120,7 +120,7 @@ internal class CreditProgramStorageContractTests : BaseStorageContractTest
|
||||
BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
credit.Id,
|
||||
periodId: _periodId,
|
||||
storeleeperId: _storekeeperId,
|
||||
storekeeperId: _storekeeperId,
|
||||
creditProgramCurrency: [(_currenyId, credit.Id)]
|
||||
);
|
||||
_storageContract.UpdElement(credit);
|
||||
@@ -170,7 +170,7 @@ internal class CreditProgramStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.StorekeeperId, Is.EqualTo(expected.StorekeeperId));
|
||||
Assert.That(actual.PeriodId, Is.EqualTo(expected.PeriodId));
|
||||
});
|
||||
if (actual.Currencies is not null)
|
||||
if (actual.Currencies is not null && actual.Currencies.Count > 0)
|
||||
{
|
||||
Assert.That(expected.CurrencyCreditPrograms, Is.Not.Null);
|
||||
Assert.That(
|
||||
@@ -210,7 +210,7 @@ internal class CreditProgramStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(actual.StorekeeperId, Is.EqualTo(expected.StorekeeperId));
|
||||
Assert.That(actual.PeriodId, Is.EqualTo(expected.PeriodId));
|
||||
});
|
||||
if (actual.CurrencyCreditPrograms is not null)
|
||||
if (actual.CurrencyCreditPrograms is not null && actual.CurrencyCreditPrograms.Count > 0)
|
||||
{
|
||||
Assert.That(expected.Currencies, Is.Not.Null);
|
||||
Assert.That(
|
||||
@@ -234,7 +234,7 @@ internal class CreditProgramStorageContractTests : BaseStorageContractTest
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.That(expected.Currencies, Is.Null);
|
||||
Assert.That(expected.Currencies, Is.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
using BankDatabase;
|
||||
using BankTests.Infrastructure;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace BankTests.WebApiControllersTests;
|
||||
|
||||
internal class BaseWebApiControllerTest
|
||||
{
|
||||
private WebApplicationFactory<Program> _webApplication;
|
||||
|
||||
protected HttpClient HttpClient { get; private set; }
|
||||
|
||||
protected BankDbContext BankDbContext { get; private set; }
|
||||
|
||||
protected static readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
_webApplication = new CustomWebApplicationFactory<Program>();
|
||||
HttpClient = _webApplication
|
||||
.WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.ConfigureTestServices(services =>
|
||||
{
|
||||
using var loggerFactory = new LoggerFactory();
|
||||
loggerFactory.AddSerilog(new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(new ConfigurationBuilder()
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile("appsettings.json")
|
||||
.Build())
|
||||
.CreateLogger());
|
||||
services.AddSingleton(loggerFactory);
|
||||
});
|
||||
})
|
||||
.CreateClient();
|
||||
|
||||
var request = HttpClient.GetAsync("/login/user").GetAwaiter().GetResult();
|
||||
var data = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
|
||||
HttpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {data}");
|
||||
|
||||
BankDbContext = _webApplication.Services.GetRequiredService<BankDbContext>();
|
||||
BankDbContext.Database.EnsureDeleted();
|
||||
BankDbContext.Database.EnsureCreated();
|
||||
}
|
||||
|
||||
[OneTimeTearDown]
|
||||
public void OneTimeTearDown()
|
||||
{
|
||||
BankDbContext?.Database.EnsureDeleted();
|
||||
BankDbContext?.Dispose();
|
||||
HttpClient?.Dispose();
|
||||
_webApplication?.Dispose();
|
||||
}
|
||||
|
||||
protected static async Task<T?> GetModelFromResponseAsync<T>(HttpResponseMessage response) =>
|
||||
JsonSerializer.Deserialize<T>(await response.Content.ReadAsStringAsync(), JsonSerializerOptions);
|
||||
|
||||
protected static StringContent MakeContent(object model) =>
|
||||
new(JsonSerializer.Serialize(model), Encoding.UTF8, "application/json");
|
||||
}
|
||||
177
TheBank/BankTests/WebApiControllersTests/ClerkControllerTests.cs
Normal file
177
TheBank/BankTests/WebApiControllersTests/ClerkControllerTests.cs
Normal file
@@ -0,0 +1,177 @@
|
||||
using BankContracts.BindingModels;
|
||||
using BankContracts.ViewModels;
|
||||
using BankDatabase.Models;
|
||||
using BankTests.Infrastructure;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
|
||||
namespace BankTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ClerkControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
BankDbContext.RemoveClerksFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetAllRecords_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var clerk1 = BankDbContext.InsertClerkToDatabaseAndReturn(name: "Иван", surname: "Иванов", email: "ivanov1@mail.com", login: "zal***", phone: "+7-777-777-78-90");
|
||||
var clerk2 = BankDbContext.InsertClerkToDatabaseAndReturn(name: "Петр", surname: "Петров", email: "petrov2@mail.com", login: "nepupkin", phone: "+7-777-777-78-91");
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync("/api/clerks");
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ClerkViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
AssertElement(data.First(x => x.Id == clerk1.Id), clerk1);
|
||||
AssertElement(data.First(x => x.Id == clerk2.Id), clerk2);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetAllRecords_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync("/api/clerks");
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ClerkViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetRecord_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var clerk = BankDbContext.InsertClerkToDatabaseAndReturn();
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync($"/api/clerks/{clerk.Id}");
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<ClerkViewModel>(response), clerk);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetRecord_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync($"/api/clerks/{Guid.NewGuid()}");
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var model = CreateModel();
|
||||
// Act
|
||||
var response = await HttpClient.PostAsJsonAsync("/api/clerks", model);
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(BankDbContext.GetClerkFromDatabase(model.Id!), model);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
// Arrange
|
||||
var model = CreateModel();
|
||||
BankDbContext.InsertClerkToDatabaseAndReturn(id: model.Id);
|
||||
// Act
|
||||
var response = await HttpClient.PostAsJsonAsync("/api/clerks", model);
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
// Act
|
||||
var response = await HttpClient.PostAsync("/api/clerks", MakeContent(string.Empty));
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var model = CreateModel();
|
||||
BankDbContext.InsertClerkToDatabaseAndReturn(id: model.Id);
|
||||
// Act
|
||||
var response = await HttpClient.PutAsJsonAsync("/api/clerks", model);
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
BankDbContext.ChangeTracker.Clear();
|
||||
AssertElement(BankDbContext.GetClerkFromDatabase(model.Id!), model);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
// Arrange
|
||||
var model = CreateModel();
|
||||
// Act
|
||||
var response = await HttpClient.PutAsJsonAsync("/api/clerks", model);
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(ClerkViewModel? actual, Clerk expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.Name, Is.EqualTo(expected.Name));
|
||||
Assert.That(actual.Surname, Is.EqualTo(expected.Surname));
|
||||
Assert.That(actual.MiddleName, Is.EqualTo(expected.MiddleName));
|
||||
Assert.That(actual.Login, Is.EqualTo(expected.Login));
|
||||
Assert.That(actual.Email, Is.EqualTo(expected.Email));
|
||||
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
|
||||
});
|
||||
}
|
||||
|
||||
private static ClerkBindingModel CreateModel(
|
||||
string? id = null,
|
||||
string name = "Иван",
|
||||
string surname = "Иванов",
|
||||
string middleName = "Иванович",
|
||||
string login = "ivanov",
|
||||
string password = "password",
|
||||
string email = "ivanov@mail.com",
|
||||
string phoneNumber = "+79999999999")
|
||||
=> new()
|
||||
{
|
||||
Id = id ?? Guid.NewGuid().ToString(),
|
||||
Name = name,
|
||||
Surname = surname,
|
||||
MiddleName = middleName,
|
||||
Login = login,
|
||||
Password = password,
|
||||
Email = email,
|
||||
PhoneNumber = phoneNumber
|
||||
};
|
||||
|
||||
private static void AssertElement(Clerk? actual, ClerkBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.Name, Is.EqualTo(expected.Name));
|
||||
Assert.That(actual.Surname, Is.EqualTo(expected.Surname));
|
||||
Assert.That(actual.MiddleName, Is.EqualTo(expected.MiddleName));
|
||||
Assert.That(actual.Login, Is.EqualTo(expected.Login));
|
||||
Assert.That(actual.Email, Is.EqualTo(expected.Email));
|
||||
Assert.That(actual.PhoneNumber, Is.EqualTo(expected.PhoneNumber));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
using BankContracts.BindingModels;
|
||||
using BankContracts.ViewModels;
|
||||
using BankDatabase;
|
||||
using BankDatabase.Models;
|
||||
using BankTests.Infrastructure;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
|
||||
namespace BankTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ClientControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
private Clerk _clerk;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_clerk = BankDbContext.InsertClerkToDatabaseAndReturn();
|
||||
}
|
||||
|
||||
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
BankDbContext.RemoveClientsFromDatabase();
|
||||
BankDbContext.RemoveClerksFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var client1 = BankDbContext.InsertClientToDatabaseAndReturn(name: "Иван", surname: "Иванов", clerkId: _clerk.Id);
|
||||
var client2 = BankDbContext.InsertClientToDatabaseAndReturn(name: "Петр", surname: "Петров", clerkId: _clerk.Id);
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync("/api/clients/getrecords");
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ClientViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(2));
|
||||
AssertElement(data.First(x => x.Id == client1.Id), client1);
|
||||
AssertElement(data.First(x => x.Id == client2.Id), client2);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync("/api/clients/getrecords");
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ClientViewModel>>(response);
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data, Has.Count.EqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenHaveRecord_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var client = BankDbContext.InsertClientToDatabaseAndReturn(clerkId: _clerk.Id);
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync($"/api/clients/getrecord/{client.Id}");
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
AssertElement(await GetModelFromResponseAsync<ClientViewModel>(response), client);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetElement_ById_WhenNoRecord_ShouldNotFound_Test()
|
||||
{
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync($"/api/clients/getrecord/{Guid.NewGuid()}");
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var model = CreateModel();
|
||||
// Act
|
||||
var response = await HttpClient.PostAsJsonAsync("/api/clients/register", model);
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(BankDbContext.GetClientFromDatabase(model.Id!), model);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenHaveRecordWithSameId_ShouldBadRequest_Test()
|
||||
{
|
||||
// Arrange
|
||||
var model = CreateModel();
|
||||
BankDbContext.InsertClientToDatabaseAndReturn(id: model.Id,clerkId: _clerk.Id);
|
||||
// Act
|
||||
var response = await HttpClient.PostAsJsonAsync("/api/clients/register", model);
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
// Act
|
||||
var response = await HttpClient.PostAsync("/api/clients/register", MakeContent(string.Empty));
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var model = CreateModel();
|
||||
BankDbContext.InsertClientToDatabaseAndReturn(id: model.Id, clerkId: _clerk.Id);
|
||||
// Act
|
||||
var response = await HttpClient.PutAsJsonAsync("/api/clients/changeinfo", model);
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
BankDbContext.ChangeTracker.Clear();
|
||||
AssertElement(BankDbContext.GetClientFromDatabase(model.Id!), model);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ChangeInfo_WhenNoFoundRecord_ShouldBadRequest_Test()
|
||||
{
|
||||
// Arrange
|
||||
var model = CreateModel();
|
||||
// Act
|
||||
var response = await HttpClient.PutAsJsonAsync("/api/clients/changeinfo", model);
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
private static void AssertElement(ClientViewModel? actual, Client expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.Name, Is.EqualTo(expected.Name));
|
||||
Assert.That(actual.Surname, Is.EqualTo(expected.Surname));
|
||||
Assert.That(actual.Balance, Is.EqualTo(expected.Balance));
|
||||
Assert.That(actual.ClerkId, Is.EqualTo(expected.ClerkId));
|
||||
});
|
||||
}
|
||||
|
||||
private static ClientBindingModel CreateModel(string? id = null, string name = "Иван", string surname = "Иванов", decimal balance = 1000, string? clerkId = null)
|
||||
=> new()
|
||||
{
|
||||
Id = id ?? Guid.NewGuid().ToString(),
|
||||
Name = name,
|
||||
Surname = surname,
|
||||
Balance = balance,
|
||||
ClerkId = clerkId
|
||||
};
|
||||
|
||||
private static void AssertElement(Client? actual, ClientBindingModel expected)
|
||||
{
|
||||
Assert.That(actual, Is.Not.Null);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(actual.Id, Is.EqualTo(expected.Id));
|
||||
Assert.That(actual.Name, Is.EqualTo(expected.Name));
|
||||
Assert.That(actual.Surname, Is.EqualTo(expected.Surname));
|
||||
Assert.That(actual.Balance, Is.EqualTo(expected.Balance));
|
||||
Assert.That(actual.ClerkId, Is.EqualTo(expected.ClerkId));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,594 @@
|
||||
using BankContracts.ViewModels;
|
||||
using BankDatabase.Models;
|
||||
using BankTests.Infrastructure;
|
||||
using System.Net;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace BankTests.WebApiControllersTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ReportControllerTests : BaseWebApiControllerTest
|
||||
{
|
||||
[TearDown]
|
||||
public void TearDown()
|
||||
{
|
||||
BankDbContext.RemoveClientsFromDatabase();
|
||||
BankDbContext.RemoveCreditProgramsFromDatabase();
|
||||
BankDbContext.RemoveDepositsFromDatabase();
|
||||
BankDbContext.RemoveCurrenciesFromDatabase();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetDepositByCreditProgram_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var storekeeper = BankDbContext.InsertStorekeeperToDatabaseAndReturn(
|
||||
email: $"storekeeper_{Guid.NewGuid()}@email.com",
|
||||
login: $"storekeeper_{Guid.NewGuid()}",
|
||||
phone: $"+7-{Guid.NewGuid():N}"
|
||||
);
|
||||
var period = BankDbContext.InsertPeriodToDatabaseAndReturn(storekeeperId: storekeeper.Id);
|
||||
|
||||
// Создаем валюты
|
||||
var currency1 = BankDbContext.InsertCurrencyToDatabaseAndReturn(
|
||||
name: "Рубль",
|
||||
abbreviation: "RUB",
|
||||
storekeeperId: storekeeper.Id
|
||||
);
|
||||
var currency2 = BankDbContext.InsertCurrencyToDatabaseAndReturn(
|
||||
name: "Доллар",
|
||||
abbreviation: "USD",
|
||||
storekeeperId: storekeeper.Id
|
||||
);
|
||||
|
||||
// Создаем кредитные программы и связываем их с валютами
|
||||
var creditProgram1 = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
name: "Credit Program 1",
|
||||
storekeeperId: storekeeper.Id,
|
||||
periodId: period.Id,
|
||||
creditProgramCurrency: [(currency1.Id, Guid.NewGuid().ToString())]
|
||||
);
|
||||
var creditProgram2 = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
name: "Credit Program 2",
|
||||
storekeeperId: storekeeper.Id,
|
||||
periodId: period.Id,
|
||||
creditProgramCurrency: [(currency2.Id, Guid.NewGuid().ToString())]
|
||||
);
|
||||
|
||||
var clerk = BankDbContext.InsertClerkToDatabaseAndReturn(
|
||||
email: $"clerk_{Guid.NewGuid()}@email.com",
|
||||
login: $"clerk_{Guid.NewGuid()}",
|
||||
phone: $"+7-{Guid.NewGuid():N}"
|
||||
);
|
||||
|
||||
// Создаем вклады и связываем их с валютами
|
||||
var deposit1 = BankDbContext.InsertDepositToDatabaseAndReturn(
|
||||
interestRate: 5.5f,
|
||||
cost: 10000,
|
||||
period: 12,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
var deposit2 = BankDbContext.InsertDepositToDatabaseAndReturn(
|
||||
interestRate: 6.5f,
|
||||
cost: 20000,
|
||||
period: 24,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
|
||||
// Связываем вклады с валютами
|
||||
BankDbContext.DepositCurrencies.Add(new DepositCurrency { DepositId = deposit1.Id, CurrencyId = currency1.Id });
|
||||
BankDbContext.DepositCurrencies.Add(new DepositCurrency { DepositId = deposit2.Id, CurrencyId = currency2.Id });
|
||||
BankDbContext.SaveChanges();
|
||||
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/report/getdepositbycreditprogram");
|
||||
var result = await GetModelFromResponseAsync<List<DepositByCreditProgramViewModel>>(response);
|
||||
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
Assert.That(result, Is.Not.Null);
|
||||
Assert.That(result, Has.Count.EqualTo(2));
|
||||
|
||||
var firstProgram = result.First(x => x.CreditProgramName == "Credit Program 1");
|
||||
Assert.That(firstProgram.DepositRate, Has.Count.EqualTo(1));
|
||||
Assert.That(firstProgram.DepositRate[0], Is.EqualTo(5.5f));
|
||||
Assert.That(firstProgram.DepositCost[0], Is.EqualTo(10000));
|
||||
Assert.That(firstProgram.DepositPeriod[0], Is.EqualTo(12));
|
||||
|
||||
var secondProgram = result.First(x => x.CreditProgramName == "Credit Program 2");
|
||||
Assert.That(secondProgram.DepositRate, Has.Count.EqualTo(1));
|
||||
Assert.That(secondProgram.DepositRate[0], Is.EqualTo(6.5f));
|
||||
Assert.That(secondProgram.DepositCost[0], Is.EqualTo(20000));
|
||||
Assert.That(secondProgram.DepositPeriod[0], Is.EqualTo(24));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LoadDepositByCreditProgram_WhenNoData_ShouldBadRequest_Test()
|
||||
{
|
||||
//Arrange
|
||||
var storekeeper = BankDbContext.InsertStorekeeperToDatabaseAndReturn(
|
||||
email: $"storekeeper_{Guid.NewGuid()}@email.com",
|
||||
login: $"storekeeper_{Guid.NewGuid()}",
|
||||
phone: $"+7-{Guid.NewGuid():N}"
|
||||
);
|
||||
var period = BankDbContext.InsertPeriodToDatabaseAndReturn(storekeeperId: storekeeper.Id);
|
||||
|
||||
// Создаем валюты
|
||||
var currency = BankDbContext.InsertCurrencyToDatabaseAndReturn(
|
||||
name: "Рубль",
|
||||
abbreviation: "RUB",
|
||||
storekeeperId: storekeeper.Id
|
||||
);
|
||||
|
||||
// Создаем кредитную программу и связываем её с валютой
|
||||
var creditProgram = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
name: "Credit Program 1",
|
||||
storekeeperId: storekeeper.Id,
|
||||
periodId: period.Id,
|
||||
creditProgramCurrency: [(currency.Id, Guid.NewGuid().ToString())]
|
||||
);
|
||||
|
||||
var clerk = BankDbContext.InsertClerkToDatabaseAndReturn(
|
||||
email: $"clerk_{Guid.NewGuid()}@email.com",
|
||||
login: $"clerk_{Guid.NewGuid()}",
|
||||
phone: $"+7-{Guid.NewGuid():N}"
|
||||
);
|
||||
|
||||
// Создаем вклад, но НЕ связываем его с валютой
|
||||
var deposit = BankDbContext.InsertDepositToDatabaseAndReturn(
|
||||
interestRate: 5.5f,
|
||||
cost: 10000,
|
||||
period: 12,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
|
||||
BankDbContext.SaveChanges();
|
||||
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/report/loaddepositbycreditprogram");
|
||||
|
||||
//Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LoadDepositByCreditProgram_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var storekeeper = BankDbContext.InsertStorekeeperToDatabaseAndReturn(
|
||||
email: $"storekeeper_{Guid.NewGuid()}@email.com",
|
||||
login: $"storekeeper_{Guid.NewGuid()}",
|
||||
phone: $"+7-{Guid.NewGuid():N}"
|
||||
);
|
||||
var period = BankDbContext.InsertPeriodToDatabaseAndReturn(storekeeperId: storekeeper.Id);
|
||||
|
||||
// Создаем валюты
|
||||
var currency1 = BankDbContext.InsertCurrencyToDatabaseAndReturn(
|
||||
name: "Рубль",
|
||||
abbreviation: "RUB",
|
||||
storekeeperId: storekeeper.Id
|
||||
);
|
||||
var currency2 = BankDbContext.InsertCurrencyToDatabaseAndReturn(
|
||||
name: "Доллар",
|
||||
abbreviation: "USD",
|
||||
storekeeperId: storekeeper.Id
|
||||
);
|
||||
|
||||
// Создаем кредитные программы и связываем их с валютами
|
||||
var creditProgram1 = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
name: "Credit Program 1",
|
||||
storekeeperId: storekeeper.Id,
|
||||
periodId: period.Id,
|
||||
creditProgramCurrency: [(currency1.Id, Guid.NewGuid().ToString())]
|
||||
);
|
||||
var creditProgram2 = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
name: "Credit Program 2",
|
||||
storekeeperId: storekeeper.Id,
|
||||
periodId: period.Id,
|
||||
creditProgramCurrency: [(currency2.Id, Guid.NewGuid().ToString())]
|
||||
);
|
||||
|
||||
var clerk = BankDbContext.InsertClerkToDatabaseAndReturn(
|
||||
email: $"clerk_{Guid.NewGuid()}@email.com",
|
||||
login: $"clerk_{Guid.NewGuid()}",
|
||||
phone: $"+7-{Guid.NewGuid():N}"
|
||||
);
|
||||
|
||||
// Создаем вклады и связываем их с валютами
|
||||
var deposit1 = BankDbContext.InsertDepositToDatabaseAndReturn(
|
||||
interestRate: 5.5f,
|
||||
cost: 10000,
|
||||
period: 12,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
var deposit2 = BankDbContext.InsertDepositToDatabaseAndReturn(
|
||||
interestRate: 6.5f,
|
||||
cost: 20000,
|
||||
period: 24,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
|
||||
// Связываем вклады с валютами
|
||||
BankDbContext.DepositCurrencies.Add(new DepositCurrency { DepositId = deposit1.Id, CurrencyId = currency1.Id });
|
||||
BankDbContext.DepositCurrencies.Add(new DepositCurrency { DepositId = deposit2.Id, CurrencyId = currency2.Id });
|
||||
BankDbContext.SaveChanges();
|
||||
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/report/loaddepositbycreditprogram");
|
||||
|
||||
//Assert
|
||||
await AssertStreamAsync(response, "deposit_by_credit_program.docx");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LoadClientsByCreditProgram_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var storekeeper = BankDbContext.InsertStorekeeperToDatabaseAndReturn(
|
||||
email: $"storekeeper_{Guid.NewGuid()}@email.com",
|
||||
login: $"storekeeper_{Guid.NewGuid()}",
|
||||
phone: $"+7-{Guid.NewGuid():N}"
|
||||
);
|
||||
var clerk = BankDbContext.InsertClerkToDatabaseAndReturn(
|
||||
email: $"clerk_{Guid.NewGuid()}@email.com",
|
||||
login: $"clerk_{Guid.NewGuid()}",
|
||||
phone: $"+7-{Guid.NewGuid():N}"
|
||||
);
|
||||
var period = BankDbContext.InsertPeriodToDatabaseAndReturn(storekeeperId: storekeeper.Id);
|
||||
|
||||
// Создаем валюты
|
||||
var currency1 = BankDbContext.InsertCurrencyToDatabaseAndReturn(
|
||||
name: "Рубль",
|
||||
abbreviation: "RUB",
|
||||
storekeeperId: storekeeper.Id
|
||||
);
|
||||
var currency2 = BankDbContext.InsertCurrencyToDatabaseAndReturn(
|
||||
name: "Доллар",
|
||||
abbreviation: "USD",
|
||||
storekeeperId: storekeeper.Id
|
||||
);
|
||||
|
||||
// Создаем кредитные программы и связываем их с валютами
|
||||
var creditProgram1 = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
name: "Credit Program 1",
|
||||
storekeeperId: storekeeper.Id,
|
||||
periodId: period.Id,
|
||||
creditProgramCurrency: [(currency1.Id, Guid.NewGuid().ToString())]
|
||||
);
|
||||
var creditProgram2 = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
name: "Credit Program 2",
|
||||
storekeeperId: storekeeper.Id,
|
||||
periodId: period.Id,
|
||||
creditProgramCurrency: [(currency2.Id, Guid.NewGuid().ToString())]
|
||||
);
|
||||
|
||||
// Создаем клиентов
|
||||
var client1 = BankDbContext.InsertClientToDatabaseAndReturn(
|
||||
surname: "Ivanov",
|
||||
name: "Ivan",
|
||||
balance: 10000,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
var client2 = BankDbContext.InsertClientToDatabaseAndReturn(
|
||||
surname: "Petrov",
|
||||
name: "Petr",
|
||||
balance: 20000,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
|
||||
// Связываем клиентов с кредитными программами
|
||||
BankDbContext.CreditProgramClients.Add(new ClientCreditProgram { ClientId = client1.Id, CreditProgramId = creditProgram1.Id });
|
||||
BankDbContext.CreditProgramClients.Add(new ClientCreditProgram { ClientId = client2.Id, CreditProgramId = creditProgram2.Id });
|
||||
BankDbContext.SaveChanges();
|
||||
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/report/loadclientsbycreditprogram");
|
||||
|
||||
//Assert
|
||||
await AssertStreamAsync(response, "clients_by_credit_program.docx");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LoadClientsByDeposit_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var storekeeper = BankDbContext.InsertStorekeeperToDatabaseAndReturn(
|
||||
email: $"storekeeper_{Guid.NewGuid()}@email.com",
|
||||
login: $"storekeeper_{Guid.NewGuid()}",
|
||||
phone: $"+7-{Guid.NewGuid():N}"
|
||||
);
|
||||
var clerk = BankDbContext.InsertClerkToDatabaseAndReturn(
|
||||
email: $"clerk_{Guid.NewGuid()}@email.com",
|
||||
login: $"clerk_{Guid.NewGuid()}",
|
||||
phone: $"+7-{Guid.NewGuid():N}"
|
||||
);
|
||||
|
||||
// Создаем клиентов
|
||||
var client1 = BankDbContext.InsertClientToDatabaseAndReturn(
|
||||
surname: "Ivanov",
|
||||
name: "Ivan",
|
||||
balance: 10000,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
var client2 = BankDbContext.InsertClientToDatabaseAndReturn(
|
||||
surname: "Petrov",
|
||||
name: "Petr",
|
||||
balance: 20000,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
|
||||
// Создаем вклады
|
||||
var deposit1 = BankDbContext.InsertDepositToDatabaseAndReturn(
|
||||
interestRate: 5.5f,
|
||||
cost: 10000,
|
||||
period: 12,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
var deposit2 = BankDbContext.InsertDepositToDatabaseAndReturn(
|
||||
interestRate: 6.5f,
|
||||
cost: 20000,
|
||||
period: 24,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
|
||||
// Связываем клиентов с вкладами
|
||||
BankDbContext.DepositClients.Add(new DepositClient { ClientId = client1.Id, DepositId = deposit1.Id });
|
||||
BankDbContext.DepositClients.Add(new DepositClient { ClientId = client2.Id, DepositId = deposit2.Id });
|
||||
BankDbContext.SaveChanges();
|
||||
|
||||
// Проверяем, что связи созданы
|
||||
var client1After = BankDbContext.Clients
|
||||
.Include(x => x.DepositClients)
|
||||
.First(x => x.Id == client1.Id);
|
||||
var client2After = BankDbContext.Clients
|
||||
.Include(x => x.DepositClients)
|
||||
.First(x => x.Id == client2.Id);
|
||||
|
||||
Assert.That(client1After.DepositClients, Is.Not.Null);
|
||||
Assert.That(client1After.DepositClients, Has.Count.EqualTo(1));
|
||||
Assert.That(client2After.DepositClients, Is.Not.Null);
|
||||
Assert.That(client2After.DepositClients, Has.Count.EqualTo(1));
|
||||
|
||||
var dateStart = DateTime.UtcNow.AddDays(-1);
|
||||
var dateFinish = DateTime.UtcNow.AddDays(1);
|
||||
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/report/loadclientsbydeposit?fromDate={dateStart:yyyy-MM-dd}&toDate={dateFinish:yyyy-MM-dd}");
|
||||
|
||||
//Assert
|
||||
await AssertStreamAsync(response, "clients_by_deposit.pdf");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task LoadDepositAndCreditProgramByCurrency_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var storekeeper = BankDbContext.InsertStorekeeperToDatabaseAndReturn(
|
||||
email: $"storekeeper_{Guid.NewGuid()}@email.com",
|
||||
login: $"storekeeper_{Guid.NewGuid()}",
|
||||
phone: $"+7-{Guid.NewGuid():N}"
|
||||
);
|
||||
var period = BankDbContext.InsertPeriodToDatabaseAndReturn(storekeeperId: storekeeper.Id);
|
||||
|
||||
// Создаем валюты
|
||||
var currency1 = BankDbContext.InsertCurrencyToDatabaseAndReturn(
|
||||
name: "Рубль",
|
||||
abbreviation: "RUB",
|
||||
storekeeperId: storekeeper.Id
|
||||
);
|
||||
var currency2 = BankDbContext.InsertCurrencyToDatabaseAndReturn(
|
||||
name: "Доллар",
|
||||
abbreviation: "USD",
|
||||
storekeeperId: storekeeper.Id
|
||||
);
|
||||
|
||||
// Создаем кредитные программы и связываем их с валютами
|
||||
var creditProgram1 = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
name: "Credit Program 1",
|
||||
storekeeperId: storekeeper.Id,
|
||||
periodId: period.Id,
|
||||
creditProgramCurrency: [(currency1.Id, Guid.NewGuid().ToString())]
|
||||
);
|
||||
var creditProgram2 = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
name: "Credit Program 2",
|
||||
storekeeperId: storekeeper.Id,
|
||||
periodId: period.Id,
|
||||
creditProgramCurrency: [(currency2.Id, Guid.NewGuid().ToString())]
|
||||
);
|
||||
|
||||
var clerk = BankDbContext.InsertClerkToDatabaseAndReturn(
|
||||
email: $"clerk_{Guid.NewGuid()}@email.com",
|
||||
login: $"clerk_{Guid.NewGuid()}",
|
||||
phone: $"+7-{Guid.NewGuid():N}"
|
||||
);
|
||||
|
||||
// Создаем вклады и связываем их с валютами
|
||||
var deposit1 = BankDbContext.InsertDepositToDatabaseAndReturn(
|
||||
interestRate: 5.5f,
|
||||
cost: 10000,
|
||||
period: 12,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
var deposit2 = BankDbContext.InsertDepositToDatabaseAndReturn(
|
||||
interestRate: 6.5f,
|
||||
cost: 20000,
|
||||
period: 24,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
|
||||
// Связываем вклады с валютами
|
||||
BankDbContext.DepositCurrencies.Add(new DepositCurrency { DepositId = deposit1.Id, CurrencyId = currency1.Id });
|
||||
BankDbContext.DepositCurrencies.Add(new DepositCurrency { DepositId = deposit2.Id, CurrencyId = currency2.Id });
|
||||
BankDbContext.SaveChanges();
|
||||
|
||||
var dateStart = DateTime.UtcNow.AddDays(-1);
|
||||
var dateFinish = DateTime.UtcNow.AddDays(1);
|
||||
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync($"/api/report/loaddepositandcreditprogrambycurrency?fromDate={dateStart:yyyy-MM-dd}&toDate={dateFinish:yyyy-MM-dd}");
|
||||
|
||||
//Assert
|
||||
await AssertStreamAsync(response, "deposit_and_credit_program_by_currency.pdf");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ExcelClientByCreditProgram_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var storekeeper = BankDbContext.InsertStorekeeperToDatabaseAndReturn(
|
||||
email: $"storekeeper_{Guid.NewGuid()}@email.com",
|
||||
login: $"storekeeper_{Guid.NewGuid()}",
|
||||
phone: $"+7-{Guid.NewGuid():N}"
|
||||
);
|
||||
var clerk = BankDbContext.InsertClerkToDatabaseAndReturn(
|
||||
email: $"clerk_{Guid.NewGuid()}@email.com",
|
||||
login: $"clerk_{Guid.NewGuid()}",
|
||||
phone: $"+7-{Guid.NewGuid():N}"
|
||||
);
|
||||
var period = BankDbContext.InsertPeriodToDatabaseAndReturn(storekeeperId: storekeeper.Id);
|
||||
|
||||
// Создаем валюты
|
||||
var currency1 = BankDbContext.InsertCurrencyToDatabaseAndReturn(
|
||||
name: "Рубль",
|
||||
abbreviation: "RUB",
|
||||
storekeeperId: storekeeper.Id
|
||||
);
|
||||
var currency2 = BankDbContext.InsertCurrencyToDatabaseAndReturn(
|
||||
name: "Доллар",
|
||||
abbreviation: "USD",
|
||||
storekeeperId: storekeeper.Id
|
||||
);
|
||||
|
||||
// Создаем кредитные программы и связываем их с валютами
|
||||
var creditProgram1 = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
name: "Credit Program 1",
|
||||
storekeeperId: storekeeper.Id,
|
||||
periodId: period.Id,
|
||||
creditProgramCurrency: [(currency1.Id, Guid.NewGuid().ToString())]
|
||||
);
|
||||
var creditProgram2 = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
name: "Credit Program 2",
|
||||
storekeeperId: storekeeper.Id,
|
||||
periodId: period.Id,
|
||||
creditProgramCurrency: [(currency2.Id, Guid.NewGuid().ToString())]
|
||||
);
|
||||
|
||||
// Создаем клиентов
|
||||
var client1 = BankDbContext.InsertClientToDatabaseAndReturn(
|
||||
surname: "Ivanov",
|
||||
name: "Ivan",
|
||||
balance: 10000,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
var client2 = BankDbContext.InsertClientToDatabaseAndReturn(
|
||||
surname: "Petrov",
|
||||
name: "Petr",
|
||||
balance: 20000,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
|
||||
// Связываем клиентов с кредитными программами
|
||||
BankDbContext.CreditProgramClients.Add(new ClientCreditProgram { ClientId = client1.Id, CreditProgramId = creditProgram1.Id });
|
||||
BankDbContext.CreditProgramClients.Add(new ClientCreditProgram { ClientId = client2.Id, CreditProgramId = creditProgram2.Id });
|
||||
BankDbContext.SaveChanges();
|
||||
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/report/loadexcelclientbycreditprogram");
|
||||
|
||||
//Assert
|
||||
await AssertStreamAsync(response, "clients_by_credit_program.xlsx");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ExcelDepositByCreditProgram_WhenHaveRecords_ShouldSuccess_Test()
|
||||
{
|
||||
//Arrange
|
||||
var storekeeper = BankDbContext.InsertStorekeeperToDatabaseAndReturn(
|
||||
email: $"storekeeper_{Guid.NewGuid()}@email.com",
|
||||
login: $"storekeeper_{Guid.NewGuid()}",
|
||||
phone: $"+7-{Guid.NewGuid():N}"
|
||||
);
|
||||
var period = BankDbContext.InsertPeriodToDatabaseAndReturn(storekeeperId: storekeeper.Id);
|
||||
|
||||
// Создаем валюты
|
||||
var currency1 = BankDbContext.InsertCurrencyToDatabaseAndReturn(
|
||||
name: "Рубль",
|
||||
abbreviation: "RUB",
|
||||
storekeeperId: storekeeper.Id
|
||||
);
|
||||
var currency2 = BankDbContext.InsertCurrencyToDatabaseAndReturn(
|
||||
name: "Доллар",
|
||||
abbreviation: "USD",
|
||||
storekeeperId: storekeeper.Id
|
||||
);
|
||||
|
||||
// Создаем кредитные программы и связываем их с валютами
|
||||
var creditProgram1 = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
name: "Credit Program 1",
|
||||
storekeeperId: storekeeper.Id,
|
||||
periodId: period.Id,
|
||||
creditProgramCurrency: [(currency1.Id, Guid.NewGuid().ToString())]
|
||||
);
|
||||
var creditProgram2 = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
name: "Credit Program 2",
|
||||
storekeeperId: storekeeper.Id,
|
||||
periodId: period.Id,
|
||||
creditProgramCurrency: [(currency2.Id, Guid.NewGuid().ToString())]
|
||||
);
|
||||
|
||||
var clerk = BankDbContext.InsertClerkToDatabaseAndReturn(
|
||||
email: $"clerk_{Guid.NewGuid()}@email.com",
|
||||
login: $"clerk_{Guid.NewGuid()}",
|
||||
phone: $"+7-{Guid.NewGuid():N}"
|
||||
);
|
||||
|
||||
// Создаем вклады и связываем их с валютами
|
||||
var deposit1 = BankDbContext.InsertDepositToDatabaseAndReturn(
|
||||
interestRate: 5.5f,
|
||||
cost: 10000,
|
||||
period: 12,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
var deposit2 = BankDbContext.InsertDepositToDatabaseAndReturn(
|
||||
interestRate: 6.5f,
|
||||
cost: 20000,
|
||||
period: 24,
|
||||
clerkId: clerk.Id
|
||||
);
|
||||
|
||||
// Связываем вклады с валютами
|
||||
BankDbContext.DepositCurrencies.Add(new DepositCurrency { DepositId = deposit1.Id, CurrencyId = currency1.Id });
|
||||
BankDbContext.DepositCurrencies.Add(new DepositCurrency { DepositId = deposit2.Id, CurrencyId = currency2.Id });
|
||||
BankDbContext.SaveChanges();
|
||||
|
||||
//Act
|
||||
var response = await HttpClient.GetAsync("/api/report/loadexceldepositbycreditprogram");
|
||||
|
||||
//Assert
|
||||
await AssertStreamAsync(response, "deposit_by_credit_program.xlsx");
|
||||
}
|
||||
|
||||
private static async Task AssertStreamAsync(HttpResponseMessage response, string fileNameForSave = "")
|
||||
{
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
using var data = await response.Content.ReadAsStreamAsync();
|
||||
Assert.That(data, Is.Not.Null);
|
||||
Assert.That(data.Length, Is.GreaterThan(0));
|
||||
await SaveStreamAsync(data, fileNameForSave);
|
||||
}
|
||||
private static async Task SaveStreamAsync(Stream stream, string fileName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(fileName))
|
||||
{
|
||||
return;
|
||||
}
|
||||
var path = Path.Combine(Directory.GetCurrentDirectory(), fileName);
|
||||
if (File.Exists(path))
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
stream.Position = 0;
|
||||
using var fileStream = new FileStream(path, FileMode.OpenOrCreate);
|
||||
await stream.CopyToAsync(fileStream);
|
||||
}
|
||||
}
|
||||
173
TheBank/BankWebApi/Adapters/ClerkAdapter.cs
Normal file
173
TheBank/BankWebApi/Adapters/ClerkAdapter.cs
Normal file
@@ -0,0 +1,173 @@
|
||||
using AutoMapper;
|
||||
using BankContracts.AdapterContracts;
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
using BankContracts.BusinessLogicContracts;
|
||||
using BankContracts.DataModels;
|
||||
using BankContracts.Exceptions;
|
||||
using BankContracts.ViewModels;
|
||||
|
||||
namespace BankWebApi.Adapters;
|
||||
|
||||
public class ClerkAdapter : IClerkAdapter
|
||||
{
|
||||
private readonly IClerkBusinessLogicContract _clerkBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ClerkAdapter(IClerkBusinessLogicContract clerkBusinessLogicContract, ILogger logger)
|
||||
{
|
||||
_clerkBusinessLogicContract = clerkBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<ClerkBindingModel, ClerkDataModel>();
|
||||
cfg.CreateMap<ClerkDataModel, ClerkViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public ClerkOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return ClerkOperationResponse.OK(
|
||||
[
|
||||
.. _clerkBusinessLogicContract
|
||||
.GetAllClerks()
|
||||
.Select(x => _mapper.Map<ClerkViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ClerkOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ClerkOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ClerkOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ClerkOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ClerkOperationResponse.OK(
|
||||
_mapper.Map<ClerkViewModel>(_clerkBusinessLogicContract.GetClerkByData(data))
|
||||
);
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ClerkOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ClerkOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ClerkOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ClerkOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ClerkOperationResponse RegisterClerk(ClerkBindingModel clerkModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_clerkBusinessLogicContract.InsertClerk(_mapper.Map<ClerkDataModel>(clerkModel));
|
||||
return ClerkOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ClerkOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ClerkOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return ClerkOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ClerkOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ClerkOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ClerkOperationResponse ChangeClerkInfo(ClerkBindingModel clerkModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_clerkBusinessLogicContract.UpdateClerk(_mapper.Map<ClerkDataModel>(clerkModel));
|
||||
return ClerkOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ClerkOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ClerkOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ClerkOperationResponse.BadRequest(
|
||||
$"Not found element by Id {clerkModel.Id}"
|
||||
);
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return ClerkOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ClerkOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ClerkOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
209
TheBank/BankWebApi/Adapters/ClientAdapter.cs
Normal file
209
TheBank/BankWebApi/Adapters/ClientAdapter.cs
Normal file
@@ -0,0 +1,209 @@
|
||||
using AutoMapper;
|
||||
using BankBusinessLogic.Implementations;
|
||||
using BankContracts.AdapterContracts;
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
using BankContracts.BusinessLogicContracts;
|
||||
using BankContracts.DataModels;
|
||||
using BankContracts.Exceptions;
|
||||
using BankContracts.ViewModels;
|
||||
|
||||
namespace BankWebApi.Adapters;
|
||||
|
||||
public class ClientAdapter : IClientAdapter
|
||||
{
|
||||
private readonly IClientBusinessLogicContract _clientBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ClientAdapter(IClientBusinessLogicContract clientBusinessLogicContract, ILogger logger)
|
||||
{
|
||||
_clientBusinessLogicContract = clientBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<ClientBindingModel, ClientDataModel>();
|
||||
cfg.CreateMap<DepositDataModel, DepositViewModel>();
|
||||
cfg.CreateMap<ClientCreditProgramBindingModel, ClientCreditProgramDataModel>();
|
||||
cfg.CreateMap<ClientCreditProgramDataModel, ClientCreditProgramViewModel>();
|
||||
cfg.CreateMap<DepositClientBindingModel, DepositClientDataModel>();
|
||||
cfg.CreateMap<DepositClientDataModel, DepositClientViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public ClientOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return ClientOperationResponse.OK(
|
||||
[
|
||||
.. _clientBusinessLogicContract
|
||||
.GetAllClients()
|
||||
.Select(x => _mapper.Map<ClientViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ClientOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ClientOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ClientOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ClientOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ClientOperationResponse.OK(
|
||||
_mapper.Map<ClientViewModel>(_clientBusinessLogicContract.GetClientByData(data))
|
||||
);
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ClientOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ClientOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ClientOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ClientOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ClientOperationResponse RegisterClient(ClientBindingModel clientModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_clientBusinessLogicContract.InsertClient(_mapper.Map<ClientDataModel>(clientModel));
|
||||
return ClientOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ClientOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ClientOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return ClientOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ClientOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ClientOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ClientOperationResponse ChangeClientInfo(ClientBindingModel clientModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_clientBusinessLogicContract.UpdateClient(_mapper.Map<ClientDataModel>(clientModel));
|
||||
return ClientOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ClientOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ClientOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ClientOperationResponse.BadRequest(
|
||||
$"Not found element by Id {clientModel.Id}"
|
||||
);
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return ClientOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ClientOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ClientOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ClientOperationResponse GetListByClerk(string clerkId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ClientOperationResponse.OK(
|
||||
[
|
||||
.. _clientBusinessLogicContract
|
||||
.GetClientByClerk(clerkId)
|
||||
.Select(x => _mapper.Map<ClientViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ClientOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ClientOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ClientOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
238
TheBank/BankWebApi/Adapters/CreditProgramAdapter.cs
Normal file
238
TheBank/BankWebApi/Adapters/CreditProgramAdapter.cs
Normal file
@@ -0,0 +1,238 @@
|
||||
using AutoMapper;
|
||||
using BankBusinessLogic.Implementations;
|
||||
using BankContracts.AdapterContracts;
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
using BankContracts.BusinessLogicContracts;
|
||||
using BankContracts.DataModels;
|
||||
using BankContracts.Exceptions;
|
||||
using BankContracts.ViewModels;
|
||||
using BankDatabase.Models;
|
||||
|
||||
namespace BankWebApi.Adapters;
|
||||
|
||||
public class CreditProgramAdapter : ICreditProgramAdapter
|
||||
{
|
||||
private readonly ICreditProgramBusinessLogicContract _creditProgramBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public CreditProgramAdapter(ICreditProgramBusinessLogicContract creditProgramBusinessLogicContract, ILogger logger)
|
||||
{
|
||||
_creditProgramBusinessLogicContract = creditProgramBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<CreditProgramBindingModel, CreditProgramDataModel>();
|
||||
cfg.CreateMap<CreditProgramDataModel, CreditProgramViewModel>();
|
||||
cfg.CreateMap<CreditProgramCurrencyBindingModel, CreditProgramCurrencyDataModel>();
|
||||
cfg.CreateMap<CreditProgramCurrencyDataModel, CreditProgramCurrencyViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public CreditProgramOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return CreditProgramOperationResponse.OK(
|
||||
[
|
||||
.. _creditProgramBusinessLogicContract
|
||||
.GetAllCreditPrograms()
|
||||
.Select(x => _mapper.Map<CreditProgramViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return CreditProgramOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CreditProgramOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CreditProgramOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public CreditProgramOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return CreditProgramOperationResponse.OK(
|
||||
_mapper.Map<CreditProgramViewModel>(_creditProgramBusinessLogicContract.GetCreditProgramByData(data))
|
||||
);
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return CreditProgramOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return CreditProgramOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CreditProgramOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CreditProgramOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public CreditProgramOperationResponse RegisterCreditProgram(CreditProgramBindingModel creditProgramModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_creditProgramBusinessLogicContract.InsertCreditProgram(_mapper.Map<CreditProgramDataModel>(creditProgramModel));
|
||||
return CreditProgramOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return CreditProgramOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return CreditProgramOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return CreditProgramOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CreditProgramOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CreditProgramOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
public CreditProgramOperationResponse ChangeCreditProgramInfo(CreditProgramBindingModel creditProgramModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_creditProgramBusinessLogicContract.UpdateCreditProgram(_mapper.Map<CreditProgramDataModel>(creditProgramModel));
|
||||
return CreditProgramOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return CreditProgramOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return CreditProgramOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return CreditProgramOperationResponse.BadRequest(
|
||||
$"Not found element by Id {creditProgramModel.Id}"
|
||||
);
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return CreditProgramOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CreditProgramOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CreditProgramOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public CreditProgramOperationResponse GetListByPeriod(string periodId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return CreditProgramOperationResponse.OK(
|
||||
[
|
||||
.. _creditProgramBusinessLogicContract
|
||||
.GetCreditProgramByPeriod(periodId)
|
||||
.Select(x => _mapper.Map<CreditProgramViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return CreditProgramOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CreditProgramOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CreditProgramOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public CreditProgramOperationResponse GetListByStorekeeper(string storekeeperId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return CreditProgramOperationResponse.OK(
|
||||
[
|
||||
.. _creditProgramBusinessLogicContract
|
||||
.GetCreditProgramByStorekeeper(storekeeperId)
|
||||
.Select(x => _mapper.Map<CreditProgramViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return CreditProgramOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CreditProgramOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CreditProgramOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
206
TheBank/BankWebApi/Adapters/CurrencyAdapter.cs
Normal file
206
TheBank/BankWebApi/Adapters/CurrencyAdapter.cs
Normal file
@@ -0,0 +1,206 @@
|
||||
using AutoMapper;
|
||||
using BankBusinessLogic.Implementations;
|
||||
using BankContracts.AdapterContracts;
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
using BankContracts.BusinessLogicContracts;
|
||||
using BankContracts.DataModels;
|
||||
using BankContracts.Exceptions;
|
||||
using BankContracts.ViewModels;
|
||||
using BankDatabase.Models;
|
||||
|
||||
namespace BankWebApi.Adapters;
|
||||
|
||||
public class CurrencyAdapter : ICurrencyAdapter
|
||||
{
|
||||
private readonly ICurrencyBusinessLogicContract _currencyBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public CurrencyAdapter(ICurrencyBusinessLogicContract currencyBusinessLogicContract, ILogger logger)
|
||||
{
|
||||
_currencyBusinessLogicContract = currencyBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<CurrencyBindingModel, CurrencyDataModel>();
|
||||
cfg.CreateMap<CurrencyDataModel, CurrencyViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public CurrencyOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return CurrencyOperationResponse.OK(
|
||||
[
|
||||
.. _currencyBusinessLogicContract
|
||||
.GetAllCurrencies()
|
||||
.Select(x => _mapper.Map<CurrencyViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return CurrencyOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CurrencyOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CurrencyOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public CurrencyOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return CurrencyOperationResponse.OK(
|
||||
_mapper.Map<CurrencyViewModel>(_currencyBusinessLogicContract.GetCurrencyByData(data))
|
||||
);
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return CurrencyOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return CurrencyOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CurrencyOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CurrencyOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public CurrencyOperationResponse MakeCurrency(CurrencyBindingModel currencyModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_currencyBusinessLogicContract.InsertCurrency(_mapper.Map<CurrencyDataModel>(currencyModel));
|
||||
return CurrencyOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return CurrencyOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return CurrencyOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return CurrencyOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CurrencyOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CurrencyOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public CurrencyOperationResponse ChangeCurrencyInfo(CurrencyBindingModel currencyModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_currencyBusinessLogicContract.UpdateCurrency(_mapper.Map<CurrencyDataModel>(currencyModel));
|
||||
return CurrencyOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return CurrencyOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return CurrencyOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return CurrencyOperationResponse.BadRequest(
|
||||
$"Not found element by Id {currencyModel.Id}"
|
||||
);
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return CurrencyOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CurrencyOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CurrencyOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public CurrencyOperationResponse GetListByStorekeeper(string storekeeperId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return CurrencyOperationResponse.OK(
|
||||
[
|
||||
.. _currencyBusinessLogicContract
|
||||
.GetCurrencyByStorekeeper(storekeeperId)
|
||||
.Select(x => _mapper.Map<CurrencyViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return CurrencyOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CurrencyOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return CurrencyOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
203
TheBank/BankWebApi/Adapters/DepositAdapter.cs
Normal file
203
TheBank/BankWebApi/Adapters/DepositAdapter.cs
Normal file
@@ -0,0 +1,203 @@
|
||||
using AutoMapper;
|
||||
using BankContracts.AdapterContracts;
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
using BankContracts.BusinessLogicContracts;
|
||||
using BankContracts.DataModels;
|
||||
using BankContracts.Exceptions;
|
||||
using BankContracts.ViewModels;
|
||||
|
||||
namespace BankWebApi.Adapters;
|
||||
|
||||
public class DepositAdapter : IDepositAdapter
|
||||
{
|
||||
private readonly IDepositBusinessLogicContract _depositBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public DepositAdapter(IDepositBusinessLogicContract depositBusinessLogicContract, ILogger logger)
|
||||
{
|
||||
_depositBusinessLogicContract = depositBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<DepositBindingModel, DepositDataModel>();
|
||||
cfg.CreateMap<DepositDataModel, DepositViewModel>();
|
||||
cfg.CreateMap<DepositCurrencyBindingModel, DepositCurrencyDataModel>();
|
||||
cfg.CreateMap<DepositCurrencyDataModel, DepositCurrencyViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
public DepositOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return DepositOperationResponse.OK(
|
||||
[
|
||||
.. _depositBusinessLogicContract
|
||||
.GetAllDeposits()
|
||||
.Select(x => _mapper.Map<DepositViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return DepositOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return DepositOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return DepositOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
public DepositOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return DepositOperationResponse.OK(
|
||||
_mapper.Map<DepositViewModel>(_depositBusinessLogicContract.GetDepositByData(data))
|
||||
);
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return DepositOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return DepositOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return DepositOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return DepositOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
public DepositOperationResponse MakeDeposit(DepositBindingModel depositModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_depositBusinessLogicContract.InsertDeposit(_mapper.Map<DepositDataModel>(depositModel));
|
||||
return DepositOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return DepositOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return DepositOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return DepositOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return DepositOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return DepositOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public DepositOperationResponse ChangeDepositInfo(DepositBindingModel depositModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_depositBusinessLogicContract.UpdateDeposit(_mapper.Map<DepositDataModel>(depositModel));
|
||||
return DepositOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return DepositOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return DepositOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return DepositOperationResponse.BadRequest(
|
||||
$"Not found element by Id {depositModel.Id}"
|
||||
);
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return DepositOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return DepositOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return DepositOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public DepositOperationResponse GetListByClerk(string clerkId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return DepositOperationResponse.OK(
|
||||
[
|
||||
.. _depositBusinessLogicContract
|
||||
.GetDepositByClerk(clerkId)
|
||||
.Select(x => _mapper.Map<DepositViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return DepositOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return DepositOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return DepositOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
275
TheBank/BankWebApi/Adapters/PeriodAdapter.cs
Normal file
275
TheBank/BankWebApi/Adapters/PeriodAdapter.cs
Normal file
@@ -0,0 +1,275 @@
|
||||
using AutoMapper;
|
||||
using BankContracts.AdapterContracts;
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
using BankContracts.BusinessLogicContracts;
|
||||
using BankContracts.DataModels;
|
||||
using BankContracts.Exceptions;
|
||||
using BankContracts.ViewModels;
|
||||
|
||||
namespace BankWebApi.Adapters;
|
||||
|
||||
public class PeriodAdapter : IPeriodAdapter
|
||||
{
|
||||
private readonly IPeriodBusinessLogicContract _periodBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public PeriodAdapter(IPeriodBusinessLogicContract periodBusinessLogicContract, ILogger logger)
|
||||
{
|
||||
_periodBusinessLogicContract = periodBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<PeriodBindingModel, PeriodDataModel>();
|
||||
cfg.CreateMap<PeriodDataModel, PeriodViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public PeriodOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return PeriodOperationResponse.OK(
|
||||
[
|
||||
.. _periodBusinessLogicContract
|
||||
.GetAllPeriods()
|
||||
.Select(x => _mapper.Map<PeriodViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return PeriodOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PeriodOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PeriodOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
public PeriodOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return PeriodOperationResponse.OK(
|
||||
_mapper.Map<PeriodViewModel>(_periodBusinessLogicContract.GetPeriodByData(data))
|
||||
);
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PeriodOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PeriodOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PeriodOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PeriodOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PeriodOperationResponse GetListByStorekeeper(string storekeeperId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return PeriodOperationResponse.OK(
|
||||
[
|
||||
.. _periodBusinessLogicContract
|
||||
.GetAllPeriodsByStorekeeper(storekeeperId)
|
||||
.Select(x => _mapper.Map<PeriodViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return PeriodOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PeriodOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PeriodOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PeriodOperationResponse GetListByStartTime(DateTime fromDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return PeriodOperationResponse.OK(
|
||||
[
|
||||
.. _periodBusinessLogicContract
|
||||
.GetAllPeriodsByStartTime(fromDate)
|
||||
.Select(x => _mapper.Map<PeriodViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return PeriodOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (IncorrectDatesException)
|
||||
{
|
||||
_logger.LogError("IncorrectDatesException");
|
||||
return PeriodOperationResponse.BadRequest("Incorrect dates");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PeriodOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PeriodOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PeriodOperationResponse GetListByEndTime(DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return PeriodOperationResponse.OK(
|
||||
[
|
||||
.. _periodBusinessLogicContract
|
||||
.GetAllPeriodsByStartTime(toDate)
|
||||
.Select(x => _mapper.Map<PeriodViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return PeriodOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (IncorrectDatesException)
|
||||
{
|
||||
_logger.LogError("IncorrectDatesException");
|
||||
return PeriodOperationResponse.BadRequest("Incorrect dates");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PeriodOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PeriodOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PeriodOperationResponse RegisterPeriod(PeriodBindingModel periodModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_periodBusinessLogicContract.InsertPeriod(_mapper.Map<PeriodDataModel>(periodModel));
|
||||
return PeriodOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PeriodOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PeriodOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return PeriodOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PeriodOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PeriodOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public PeriodOperationResponse ChangePeriodInfo(PeriodBindingModel periodModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_periodBusinessLogicContract.UpdatePeriod(_mapper.Map<PeriodDataModel>(periodModel));
|
||||
return PeriodOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return PeriodOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return PeriodOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return PeriodOperationResponse.BadRequest(
|
||||
$"Not found element by Id {periodModel.Id}"
|
||||
);
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return PeriodOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return PeriodOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return PeriodOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
272
TheBank/BankWebApi/Adapters/ReplenishmentAdapter.cs
Normal file
272
TheBank/BankWebApi/Adapters/ReplenishmentAdapter.cs
Normal file
@@ -0,0 +1,272 @@
|
||||
using AutoMapper;
|
||||
using BankBusinessLogic.Implementations;
|
||||
using BankContracts.AdapterContracts;
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
using BankContracts.BusinessLogicContracts;
|
||||
using BankContracts.DataModels;
|
||||
using BankContracts.Exceptions;
|
||||
using BankContracts.ViewModels;
|
||||
|
||||
namespace BankWebApi.Adapters;
|
||||
|
||||
public class ReplenishmentAdapter : IReplenishmentAdapter
|
||||
{
|
||||
private readonly IReplenishmentBusinessLogicContract _replenishmentBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ReplenishmentAdapter(IReplenishmentBusinessLogicContract replenishmentBusinessLogicContract, ILogger logger)
|
||||
{
|
||||
_replenishmentBusinessLogicContract = replenishmentBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<ReplenishmentBindingModel, ReplenishmentDataModel>();
|
||||
cfg.CreateMap<ReplenishmentDataModel, ReplenishmentViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public ReplenishmentOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReplenishmentOperationResponse.OK(
|
||||
[
|
||||
.. _replenishmentBusinessLogicContract
|
||||
.GetAllReplenishments()
|
||||
.Select(x => _mapper.Map<ReplenishmentViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ReplenishmentOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReplenishmentOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ReplenishmentOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ReplenishmentOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReplenishmentOperationResponse.OK(
|
||||
_mapper.Map<ReplenishmentViewModel>(_replenishmentBusinessLogicContract.GetReplenishmentByData(data))
|
||||
);
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ReplenishmentOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ReplenishmentOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReplenishmentOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ReplenishmentOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ReplenishmentOperationResponse GetListByClerk(string clerkId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReplenishmentOperationResponse.OK(
|
||||
[
|
||||
.. _replenishmentBusinessLogicContract
|
||||
.GetAllReplenishmentsByClerk(clerkId)
|
||||
.Select(x => _mapper.Map<ReplenishmentViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ReplenishmentOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReplenishmentOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ReplenishmentOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ReplenishmentOperationResponse GetListByDeposit(string depositId)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReplenishmentOperationResponse.OK(
|
||||
[
|
||||
.. _replenishmentBusinessLogicContract
|
||||
.GetAllReplenishmentsByDeposit(depositId)
|
||||
.Select(x => _mapper.Map<ReplenishmentViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ReplenishmentOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReplenishmentOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ReplenishmentOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ReplenishmentOperationResponse GetListByDate(DateTime fromDate, DateTime toDate)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReplenishmentOperationResponse.OK(
|
||||
[
|
||||
.. _replenishmentBusinessLogicContract
|
||||
.GetAllReplenishmentsByDate(fromDate, toDate)
|
||||
.Select(x => _mapper.Map<ReplenishmentViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return ReplenishmentOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (IncorrectDatesException)
|
||||
{
|
||||
_logger.LogError("IncorrectDatesException");
|
||||
return ReplenishmentOperationResponse.BadRequest("Incorrect dates");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReplenishmentOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ReplenishmentOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ReplenishmentOperationResponse RegisterReplenishment(ReplenishmentBindingModel replenishmentModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_replenishmentBusinessLogicContract.InsertReplenishment(_mapper.Map<ReplenishmentDataModel>(replenishmentModel));
|
||||
return ReplenishmentOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ReplenishmentOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ReplenishmentOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return ReplenishmentOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReplenishmentOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ReplenishmentOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ReplenishmentOperationResponse ChangeReplenishmentInfo(ReplenishmentBindingModel replenishmentModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_replenishmentBusinessLogicContract.UpdateReplenishment(_mapper.Map<ReplenishmentDataModel>(replenishmentModel));
|
||||
return ReplenishmentOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return ReplenishmentOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return ReplenishmentOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return ReplenishmentOperationResponse.BadRequest(
|
||||
$"Not found element by Id {replenishmentModel.Id}"
|
||||
);
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return ReplenishmentOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReplenishmentOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ReplenishmentOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
341
TheBank/BankWebApi/Adapters/ReportAdapter.cs
Normal file
341
TheBank/BankWebApi/Adapters/ReportAdapter.cs
Normal file
@@ -0,0 +1,341 @@
|
||||
using AutoMapper;
|
||||
using BankContracts.AdapterContracts;
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BusinessLogicContracts;
|
||||
using BankContracts.DataModels;
|
||||
using BankContracts.Exceptions;
|
||||
using BankContracts.ViewModels;
|
||||
|
||||
namespace BankWebApi.Adapters;
|
||||
|
||||
public class ReportAdapter : IReportAdapter
|
||||
{
|
||||
private readonly IReportContract _reportContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ReportAdapter(IReportContract reportContract, ILogger logger)
|
||||
{
|
||||
_reportContract = reportContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<ClientsByCreditProgramDataModel, ClientsByCreditProgramViewModel>();
|
||||
cfg.CreateMap<ClientsByDepositDataModel, ClientsByDepositViewModel>();
|
||||
cfg.CreateMap<DepositByCreditProgramDataModel, DepositByCreditProgramViewModel>();
|
||||
cfg.CreateMap<CreditProgramAndDepositByCurrencyDataModel, CreditProgramAndDepositByCurrencyViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
private static ReportOperationResponse SendStream(Stream stream, string fileName)
|
||||
{
|
||||
stream.Position = 0;
|
||||
return ReportOperationResponse.OK(stream, fileName);
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> CreateDocumentClientsByCreditProgramAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SendStream(await _reportContract.CreateDocumentClientsByCreditProgramAsync(ct), "clientbycreditprogram.docx");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> CreateExcelDocumentClientsByCreditProgramAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SendStream(await _reportContract.CreateExcelDocumentClientsByCreditProgramAsync(ct), "clientbycreditprogram.xlsx");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> CreateDocumentClientsByDepositAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SendStream(await _reportContract.CreateDocumentClientsByDepositAsync(dateStart, dateFinish, ct),
|
||||
"clientbydeposit.pdf");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> CreateDocumentDepositAndCreditProgramByCurrencyAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SendStream(await _reportContract.CreateDocumentDepositAndCreditProgramByCurrencyAsync(dateStart, dateFinish, ct),
|
||||
"depositandcreditprogrambycurrency.pdf");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> CreateDocumentDepositByCreditProgramAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SendStream(await _reportContract.CreateDocumentDepositByCreditProgramAsync(ct), "depositbycreditprogram.docx");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (InvalidOperationException ex) when (ex.Message == "No deposits with currencies found")
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse.BadRequest("No deposits with currencies found");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> CreateExcelDocumentDepositByCreditProgramAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SendStream(await _reportContract.CreateExcelDocumentDepositByCreditProgramAsync(ct), "depositbycreditprogram.xlsx");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (InvalidOperationException ex) when (ex.Message == "No deposits with currencies found")
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse.BadRequest("No deposits with currencies found");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> GetDataClientsByCreditProgramAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReportOperationResponse.OK([.. (await _reportContract.GetDataClientsByCreditProgramAsync(ct)).Select(x => _mapper.Map<ClientsByCreditProgramViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> GetDataClientsByDepositAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReportOperationResponse.OK((await _reportContract.GetDataClientsByDepositAsync(dateStart, dateFinish, ct))
|
||||
.Select(x => _mapper.Map<ClientsByDepositViewModel>(x)).ToList());
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> GetDataDepositAndCreditProgramByCurrencyAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReportOperationResponse.OK((await _reportContract.GetDataDepositAndCreditProgramByCurrencyAsync(dateStart, dateFinish, ct))
|
||||
.Select(x => _mapper.Map<CreditProgramAndDepositByCurrencyViewModel>(x)).ToList());
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> GetDataDepositByCreditProgramAsync(CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReportOperationResponse.OK([.. (await _reportContract.GetDataDepositByCreditProgramAsync(ct)).Select(x => _mapper.Map<DepositByCreditProgramViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "InvalidOperationException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return ReportOperationResponse.InternalServerError($"Error while working with data storage: {ex.InnerException!.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
174
TheBank/BankWebApi/Adapters/StorekeeperAdapter.cs
Normal file
174
TheBank/BankWebApi/Adapters/StorekeeperAdapter.cs
Normal file
@@ -0,0 +1,174 @@
|
||||
using AutoMapper;
|
||||
using BankBusinessLogic.Implementations;
|
||||
using BankContracts.AdapterContracts;
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
using BankContracts.BusinessLogicContracts;
|
||||
using BankContracts.DataModels;
|
||||
using BankContracts.Exceptions;
|
||||
using BankContracts.ViewModels;
|
||||
|
||||
namespace BankWebApi.Adapters;
|
||||
|
||||
public class StorekeeperAdapter : IStorekeeperAdapter
|
||||
{
|
||||
private readonly IStorekeeperBusinessLogicContract _storekeeperBusinessLogicContract;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public StorekeeperAdapter(IStorekeeperBusinessLogicContract storekeeperBusinessLogicContract, ILogger logger)
|
||||
{
|
||||
_storekeeperBusinessLogicContract = storekeeperBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<StorekeeperBindingModel, StorekeeperDataModel>();
|
||||
cfg.CreateMap<StorekeeperDataModel, StorekeeperViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
public StorekeeperOperationResponse GetList()
|
||||
{
|
||||
try
|
||||
{
|
||||
return StorekeeperOperationResponse.OK(
|
||||
[
|
||||
.. _storekeeperBusinessLogicContract
|
||||
.GetAllStorekeepers()
|
||||
.Select(x => _mapper.Map<StorekeeperViewModel>(x)),
|
||||
]
|
||||
);
|
||||
}
|
||||
catch (NullListException)
|
||||
{
|
||||
_logger.LogError("NullListException");
|
||||
return StorekeeperOperationResponse.NotFound("The list is not initialized");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return StorekeeperOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return StorekeeperOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public StorekeeperOperationResponse GetElement(string data)
|
||||
{
|
||||
try
|
||||
{
|
||||
return StorekeeperOperationResponse.OK(
|
||||
_mapper.Map<StorekeeperViewModel>(_storekeeperBusinessLogicContract.GetStorekeeperByData(data))
|
||||
);
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return StorekeeperOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return StorekeeperOperationResponse.NotFound($"Not found element by data {data}");
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return StorekeeperOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return StorekeeperOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public StorekeeperOperationResponse RegisterStorekeeper(StorekeeperBindingModel storekeeperModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_storekeeperBusinessLogicContract.InsertStorekeeper(_mapper.Map<StorekeeperDataModel>(storekeeperModel));
|
||||
return StorekeeperOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return StorekeeperOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return StorekeeperOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return StorekeeperOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return StorekeeperOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return StorekeeperOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public StorekeeperOperationResponse ChangeStorekeeperInfo(StorekeeperBindingModel storekeeperModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
_storekeeperBusinessLogicContract.UpdateStorekeeper(_mapper.Map<StorekeeperDataModel>(storekeeperModel));
|
||||
return StorekeeperOperationResponse.NoContent();
|
||||
}
|
||||
catch (ArgumentNullException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ArgumentNullException");
|
||||
return StorekeeperOperationResponse.BadRequest("Data is empty");
|
||||
}
|
||||
catch (ValidationException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ValidationException");
|
||||
return StorekeeperOperationResponse.BadRequest($"Incorrect data transmitted: {ex.Message}");
|
||||
}
|
||||
catch (ElementNotFoundException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementNotFoundException");
|
||||
return StorekeeperOperationResponse.BadRequest(
|
||||
$"Not found element by Id {storekeeperModel.Id}"
|
||||
);
|
||||
}
|
||||
catch (ElementExistsException ex)
|
||||
{
|
||||
_logger.LogError(ex, "ElementExistsException");
|
||||
return StorekeeperOperationResponse.BadRequest(ex.Message);
|
||||
}
|
||||
catch (StorageException ex)
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return StorekeeperOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return StorekeeperOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user