41 Commits

Author SHA1 Message Date
b70143484d fix: добавление надписей методов в котроллере 2025-05-25 23:18:20 +04:00
75c0be18ce fix: добавление названий методов 2025-05-25 11:53:41 +04:00
a26193512c feat: добавление выборки для отчетов 2025-05-24 22:49:10 +04:00
ed2369ed85 fix: небольшие фиксы 2025-05-21 22:13:22 +04:00
b977e76302 Merge branch 'main' into Task_7_UI 2025-05-21 19:24:24 +04:00
4fdc420920 Merge pull request 'Task забыл' (#10) from Task_5_Api into main
Reviewed-on: #10
2025-05-21 19:22:58 +04:00
50e870f28c Merge pull request 'Task_6_Report' (#8) from Task_6_Report into Task_5_Api
Reviewed-on: #8
feat: генерация и отправка отчетов на почту
2025-05-21 19:21:51 +04:00
4068a579c8 feat: готовые отчеты, отправка на почту 2025-05-21 18:23:34 +04:00
8e930475a3 feat: clerk ui, частично не рабочий из-за маппингов 2025-05-21 17:58:54 +04:00
57f878a051 feat: начало вьюхи клерка, готовы три таба, ни один не работает нормально, спасибо автомапперу 2025-05-21 17:43:16 +04:00
58ff192d7c fix: fix 2025-05-21 10:40:01 +04:00
ecff1045b3 feat: отправка почты 2025-05-21 09:52:51 +04:00
b59bdf9f3d feat: подготовка ui для клерка 2025-05-21 01:51:45 +04:00
94f602b0fe fix: правки (заработал первый отчет) 2025-05-20 23:28:39 +04:00
23a5de4e3e fix: изменение нэйминга, добавление тестов для отчетов 2025-05-20 22:45:18 +04:00
f5d5ff4b24 merge 2025-05-20 22:31:55 +04:00
109639617e feat: догика отчетов, начало тестирования 2025-05-20 17:33:09 +04:00
3e48ad4d24 Merge pull request 'Task_5_Api' (#7) from Task_5_Api into main
Reviewed-on: #7
feat: реализация web api, которая скорее всего работает, но чиниться будет уже в следующих тасках
2025-05-20 13:49:59 +04:00
b1e5b7de93 fix: поправил ошибки на формочке кредитных программ 2025-05-20 00:31:38 +04:00
9ed33690cf feat: первая простенькая версия ui для кладовщика 2025-05-20 00:00:45 +04:00
50b507fef3 feat: добавление адаптера, контроллера для отчетов, добавление логики в стораджах, добавление моделей для очетов, добвление бизнес-логики отчетов (неполная:(() 2025-05-19 18:53:24 +04:00
1c0bf1efd2 feat: немного поменял маппинг, сделал отображение нормальное без View модели с фио, для кладовщика основные формы и создание готово, осталось редактирования 2025-05-19 02:21:13 +04:00
e8f493691f feat: авторизация для кладовщика 2025-05-19 00:13:37 +04:00
abeeedaa64 feat: добавление логики(не полной) для создания отчетов и отправки на почту 2025-05-18 14:45:16 +04:00
a201d60ff3 feat: подготовка для отчетов 2025-05-18 12:57:05 +04:00
244b846ef9 feat: добавление некоторых контрактов для отчетов 2025-05-18 12:27:13 +04:00
de879be266 fix: добавил создание кредитных программ, починил по тупому cors и id на клиенте решил генерить 2025-05-18 02:52:11 +04:00
164def1e18 feat: popup формочка для добавления, хуки для загрузки данных 2025-05-18 02:20:03 +04:00
56053a7287 feat: ui для header и footer 2025-05-17 13:21:33 +04:00
24833faba0 feat: два класса тестов + базовый. 2025-05-10 13:13:38 +04:00
1cbde02887 fix: удаление юзинга 2025-05-10 13:12:28 +04:00
f4ad6ba98e feat: модели, адаптеры, контроллеры для кладовщика, валюты, пополнения 2025-05-03 16:26:07 +04:00
fbba161390 fix: изменение названия метода 2025-05-03 15:18:21 +04:00
d827ade763 feat: модели, адаптеры, контроллеры для клиента, вклада, кредитной программы. модели для связей многие ко многим 2025-05-02 14:45:07 +04:00
d6ded9f5e0 fix: убрал не нужные юзинги 2025-05-02 12:36:22 +04:00
bb1432fa4d feat: апи для сроков 2025-05-02 00:56:52 +04:00
5b25dcf976 fix: фикс дат в бизнес логике сроков и названий в контрактах клерка 2025-05-02 00:56:35 +04:00
6273bff7fb feat: добавление swagger документации 2025-05-01 18:06:01 +04:00
fa9dbb3f60 feat!: создание проекта web api
создание проекта для web api, конфигурации бд и тп, была ошибка с чтением конфигурации из json, решилась
2025-05-01 17:25:49 +04:00
1854214aa9 fix: тест Try_GetElementById_WhenHaveRecord_Test
в тесте проходило, что список пустой и это не одно и то же, если он null, для нашей реализации это одно и то же
2025-05-01 15:57:00 +04:00
3552e461fb Merge pull request 'Task_4_Storage' (#5) from Task_4_Storage into main
Reviewed-on: #5
2025-05-01 15:39:29 +04:00
294 changed files with 26199 additions and 65 deletions

View File

@@ -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>

View File

@@ -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();

View 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>"
);
}
}
}

View File

@@ -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));
}

View File

@@ -0,0 +1,420 @@
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 = ["Валюта", "Кредитная программа", "Макс. сумма", "Ставка", "Срок"];
/// <summary>
/// Получения данных для отчета Клиента по Кредитным программам
/// </summary>
/// <param name="creditProgramIds"></param>
/// <param name="ct"></param>
/// <returns></returns>
public async Task<List<ClientsByCreditProgramDataModel>> GetDataClientsByCreditProgramAsync(List<string>? creditProgramIds, 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);
var filteredPrograms = creditPrograms
.Where(cp => cp.Currencies.Any()) // Проверяем, что у кредитной программы есть связанные валюты
.Where(cp => creditProgramIds == null || creditProgramIds.Contains(cp.Id));
return filteredPrograms
.Select(cp => new ClientsByCreditProgramDataModel
{
CreditProgramId = cp.Id,
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();
}
/// <summary>
/// Создание word отчета Клиента по Кредитным программам
/// </summary>
/// <param name="creditProgramIds"></param>
/// <param name="ct"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public async Task<Stream> CreateDocumentClientsByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct)
{
_logger.LogInformation("Create report ClientsByCreditProgram");
var data = await GetDataClientsByCreditProgramAsync(creditProgramIds, 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();
}
/// <summary>
/// Создание excel отчета Клиенты по Кредитным программам
/// </summary>
/// <param name="creditProgramIds"></param>
/// <param name="ct"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public async Task<Stream> CreateExcelDocumentClientsByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct)
{
_logger.LogInformation("Create Excel report ClientsByCreditProgram");
var data = await GetDataClientsByCreditProgramAsync(creditProgramIds, 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();
}
/// <summary>
/// Получение данных для отчета Клиента по Депозитам
/// </summary>
/// <param name="dateStart"></param>
/// <param name="dateFinish"></param>
/// <param name="ct"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="InvalidOperationException"></exception>
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;
}
/// <summary>
/// Создание pdf отчета Клиента по Депозитам
/// </summary>
/// <param name="dateStart"></param>
/// <param name="dateFinish"></param>
/// <param name="ct"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
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();
}
/// <summary>
/// Получение данных для отчета Депозиты и Кредитные программы по Валютам
/// </summary>
/// <param name="dateStart"></param>
/// <param name="dateFinish"></param>
/// <param name="ct"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
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();
}
/// <summary>
/// Создание pdf отчета Депозиты и Кредитные программы по Валютам
/// </summary>
/// <param name="dateStart"></param>
/// <param name="dateFinish"></param>
/// <param name="ct"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
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();
}
/// <summary>
/// Получение данных для отчета Депозиты по Кредитным программам
/// </summary>
/// <param name="creditProgramIds"></param>
/// <param name="ct"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public async Task<List<DepositByCreditProgramDataModel>> GetDataDepositByCreditProgramAsync(List<string>? creditProgramIds, 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");
}
var filteredPrograms = creditPrograms
.Where(cp => creditProgramIds == null || creditProgramIds.Contains(cp.Id));
return filteredPrograms.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();
}
/// <summary>
/// Создание word отчета Депозиты по Кредитным программам
/// </summary>
/// <param name="creditProgramIds"></param>
/// <param name="ct"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public async Task<Stream> CreateDocumentDepositByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct)
{
_logger.LogInformation("Create report DepositByCreditProgram");
var data = await GetDataDepositByCreditProgramAsync(creditProgramIds, 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();
}
/// <summary>
/// Создание excel отчета Депозиты по Кредитным программам
/// </summary>
/// <param name="creditProgramIds"></param>
/// <param name="ct"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public async Task<Stream> CreateExcelDocumentDepositByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct)
{
_logger.LogInformation("Create Excel report DepositByCreditProgram");
var data = await GetDataDepositByCreditProgramAsync(creditProgramIds, 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();
}
}

View File

@@ -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();
}

View File

@@ -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();
}

View File

@@ -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();
}

View 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);
}
}

View 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;
}
}

View File

@@ -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;
}
}

View File

@@ -0,0 +1,20 @@
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);
ClerkOperationResponse Login(LoginBindingModel clerkModel, out string token);
}

View 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);
}

View File

@@ -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);
}

View 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);
}

View 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);
}

View 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);
}

View File

@@ -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);
}

View File

@@ -0,0 +1,18 @@
using BankContracts.AdapterContracts.OperationResponses;
namespace BankContracts.AdapterContracts;
public interface IReportAdapter
{
Task<ReportOperationResponse> GetDataClientsByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct);
Task<ReportOperationResponse> GetDataClientsByDepositAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<ReportOperationResponse> GetDataDepositByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct);
Task<ReportOperationResponse> GetDataDepositAndCreditProgramByCurrencyAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<ReportOperationResponse> CreateDocumentClientsByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct);
Task<ReportOperationResponse> CreateExcelDocumentClientsByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct);
Task<ReportOperationResponse> CreateDocumentClientsByDepositAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<ReportOperationResponse> CreateDocumentDepositByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct);
Task<ReportOperationResponse> CreateExcelDocumentDepositByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct);
Task<ReportOperationResponse> CreateDocumentDepositAndCreditProgramByCurrencyAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
}

View File

@@ -0,0 +1,20 @@
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);
StorekeeperOperationResponse Login(LoginBindingModel storekeeperModel, out string token);
}

View File

@@ -0,0 +1,27 @@
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);
public static ClerkOperationResponse Unauthorized(string message) =>
Unauthorized<ClerkOperationResponse>(message);
}

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -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);
}

View File

@@ -0,0 +1,30 @@
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(string token) =>
OK<StorekeeperOperationResponse, string>(token);
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);
public static StorekeeperOperationResponse Unauthorized(string message) =>
Unauthorized<StorekeeperOperationResponse>(message);
}

View File

@@ -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>

View 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; }
}

View 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; }
}

View File

@@ -0,0 +1,8 @@
namespace BankContracts.BindingModels;
public class ClientCreditProgramBindingModel
{
public string? CreditProgramId { get; set; }
public string? ClientId { get; set; }
}

View File

@@ -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; }
}

View File

@@ -0,0 +1,8 @@
namespace BankContracts.BindingModels;
public class CreditProgramCurrencyBindingModel
{
public string? CreditProgramId { get; set; }
public string? CurrencyId { get; set; }
}

View 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; }
}

View 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; }
}

View File

@@ -0,0 +1,8 @@
namespace BankContracts.BindingModels;
public class DepositClientBindingModel
{
public string? DepositId { get; set; }
public string? ClientId { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace BankContracts.BindingModels;
public class DepositCurrencyBindingModel
{
public string? DepositId { get; set; }
public string? CurrencyId { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace BankContracts.BindingModels;
public class LoginBindingModel
{
public required string Login { get; set; }
public required string Password { get; set; }
}

View File

@@ -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; }
}

View File

@@ -0,0 +1,12 @@
namespace BankContracts.BindingModels;
public class MailSendInfoBindingModel
{
public string ToEmail { get; set; } = string.Empty;
public string Subject { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public string? AttachmentPath { get; set; }
}

View 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; }
}

View File

@@ -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; }
}

View File

@@ -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; }
}

View File

@@ -3,7 +3,7 @@ namespace BankContracts.BusinessLogicContracts;
public interface ICurrencyBusinessLogicContract
{
List<CurrencyDataModel> GetAllCurrencys();
List<CurrencyDataModel> GetAllCurrencies();
List<CurrencyDataModel> GetCurrencyByStorekeeper(string storekeeperId);

View File

@@ -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);

View File

@@ -0,0 +1,20 @@
using BankContracts.DataModels;
namespace BankContracts.BusinessLogicContracts;
public interface IReportContract
{
Task<List<ClientsByCreditProgramDataModel>> GetDataClientsByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct);
Task<Stream> CreateDocumentClientsByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct);
Task<Stream> CreateExcelDocumentClientsByCreditProgramAsync(List<string>? creditProgramIds, 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(List<string>? creditProgramIds, CancellationToken ct);
Task<Stream> CreateDocumentDepositByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct);
Task<Stream> CreateExcelDocumentDepositByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct);
Task<List<CreditProgramAndDepositByCurrencyDataModel>> GetDataDepositAndCreditProgramByCurrencyAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
Task<Stream> CreateDocumentDepositAndCreditProgramByCurrencyAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
}

View File

@@ -0,0 +1,10 @@
namespace BankContracts.DataModels;
public class ClientsByCreditProgramDataModel
{
public required string CreditProgramId { get; set; }
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; }
}

View File

@@ -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; }
}

View File

@@ -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; }
}

View File

@@ -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; }
}

View File

@@ -0,0 +1,65 @@
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 };
protected static TResult Unauthorized<TResult>(string? errorMessage = null)
where TResult : OperationResponse, new() =>
new() { StatusCode = HttpStatusCode.Unauthorized, Result = errorMessage };
}

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View File

@@ -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);

View 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; }
}

View File

@@ -0,0 +1,8 @@
namespace BankContracts.ViewModels;
public class ClientCreditProgramViewModel
{
public required string? CreditProgramId { get; set; }
public required string? ClientId { get; set; }
}

View 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; }
}

View File

@@ -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; }
}

View File

@@ -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; }
}

View File

@@ -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; }
}

View File

@@ -0,0 +1,8 @@
namespace BankContracts.ViewModels;
public class CreditProgramCurrencyViewModel
{
public required string CreditProgramId { get; set; }
public required string CurrencyId { get; set; }
}

View 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; }
}

View 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; }
}

View File

@@ -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; }
}

View File

@@ -0,0 +1,8 @@
namespace BankContracts.ViewModels;
public class DepositClientViewModel
{
public required string DepositId { get; set; }
public required string ClientId { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace BankContracts.ViewModels;
public class DepositCurrencyViewModel
{
public required string DepositId { get; set; }
public required string CurrencyId { get; set; }
}

View 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; }
}

View 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; }
}

View 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; }
}

View 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; }
}

View File

@@ -9,6 +9,10 @@
<ItemGroup>
<PackageReference Include="AutoMapper" Version="14.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.4">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.4" />
</ItemGroup>
@@ -20,4 +24,8 @@
<InternalsVisibleTo Include="BankTests" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="BankWebApi" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" />
</ItemGroup>
</Project>

View File

@@ -33,7 +33,7 @@ internal class BankDbContext(IConfigurationDatabase configurationDatabase) : DbC
modelBuilder.Entity<CreditProgram>()
.HasIndex(x => x.Name)
.IsUnique();
modelBuilder.Entity<Currency>()
.HasIndex(x => x.Abbreviation)
.IsUnique();
@@ -80,17 +80,17 @@ internal class BankDbContext(IConfigurationDatabase configurationDatabase) : DbC
public DbSet<Clerk> Clerks { get; set; }
public DbSet<Client> Clients { get; set; }
public DbSet<CreditProgram> CreditPrograms { get; set; }
public DbSet<Currency> Currencies { get; set; }
public DbSet<Deposit> Deposits { get; set; }
public DbSet<Period> Periods { get; set; }
public DbSet<Replenishment> Replenishments { get; set; }
public DbSet<Storekeeper> Storekeepers { get; set; }
public DbSet<DepositCurrency> DepositCurrencies { get; set; }

View File

@@ -0,0 +1,17 @@
using BankContracts.Infrastructure;
using Microsoft.EntityFrameworkCore.Design;
namespace BankDatabase;
//public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<BankDbContext>
//{
// //public BankDbContext CreateDbContext(string[] args)
// //{
// // return new BankDbContext(new ConfigurationDatabase());
// //}
//}
internal class ConfigurationDatabase : IConfigurationDatabase
{
public string ConnectionString => "Host=127.0.0.1;Port=5432;Database=BankTest;Username=postgres;Password=admin123;";
}

View File

@@ -85,7 +85,7 @@ internal class ClerkStorageContract : IClerkStorageContract
_dbContext.Clerks.Add(_mapper.Map<Clerk>(clerkDataModel));
_dbContext.SaveChanges();
}
catch (InvalidOperationException ex) when (ex.TargetSite?.Name == "ThrowIdentityConflict")
catch (DbUpdateException ex) when (ex.InnerException is PostgresException { ConstraintName: "PK_Clerks" })
{
_dbContext.ChangeTracker.Clear();
throw new ElementExistsException($"Id {clerkDataModel.Id}");

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -0,0 +1,562 @@
// <auto-generated />
using System;
using BankDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace BankDatabase.Migrations
{
[DbContext(typeof(BankDbContext))]
[Migration("20250518195627_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("BankDatabase.Models.Clerk", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Login")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MiddleName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Surname")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Email")
.IsUnique();
b.HasIndex("Login")
.IsUnique();
b.HasIndex("PhoneNumber")
.IsUnique();
b.ToTable("Clerks");
});
modelBuilder.Entity("BankDatabase.Models.Client", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<decimal>("Balance")
.HasColumnType("numeric");
b.Property<string>("ClerkId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Surname")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ClerkId");
b.ToTable("Clients");
});
modelBuilder.Entity("BankDatabase.Models.ClientCreditProgram", b =>
{
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<string>("CreditProgramId")
.HasColumnType("text");
b.HasKey("ClientId", "CreditProgramId");
b.HasIndex("CreditProgramId");
b.ToTable("CreditProgramClients");
});
modelBuilder.Entity("BankDatabase.Models.CreditProgram", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<decimal>("Cost")
.HasColumnType("numeric");
b.Property<decimal>("MaxCost")
.HasColumnType("numeric");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PeriodId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("StorekeeperId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.HasIndex("PeriodId");
b.HasIndex("StorekeeperId");
b.ToTable("CreditPrograms");
});
modelBuilder.Entity("BankDatabase.Models.CreditProgramCurrency", b =>
{
b.Property<string>("CreditProgramId")
.HasColumnType("text");
b.Property<string>("CurrencyId")
.HasColumnType("text");
b.HasKey("CreditProgramId", "CurrencyId");
b.HasIndex("CurrencyId");
b.ToTable("CurrencyCreditPrograms");
});
modelBuilder.Entity("BankDatabase.Models.Currency", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Abbreviation")
.IsRequired()
.HasColumnType("text");
b.Property<decimal>("Cost")
.HasColumnType("numeric");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("StorekeeperId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Abbreviation")
.IsUnique();
b.HasIndex("StorekeeperId");
b.ToTable("Currencies");
});
modelBuilder.Entity("BankDatabase.Models.Deposit", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ClerkId")
.IsRequired()
.HasColumnType("text");
b.Property<decimal>("Cost")
.HasColumnType("numeric");
b.Property<float>("InterestRate")
.HasColumnType("real");
b.Property<int>("Period")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ClerkId");
b.ToTable("Deposits");
});
modelBuilder.Entity("BankDatabase.Models.DepositClient", b =>
{
b.Property<string>("DepositId")
.HasColumnType("text");
b.Property<string>("ClientId")
.HasColumnType("text");
b.HasKey("DepositId", "ClientId");
b.HasIndex("ClientId");
b.ToTable("DepositClients");
});
modelBuilder.Entity("BankDatabase.Models.DepositCurrency", b =>
{
b.Property<string>("DepositId")
.HasColumnType("text");
b.Property<string>("CurrencyId")
.HasColumnType("text");
b.HasKey("DepositId", "CurrencyId");
b.HasIndex("CurrencyId");
b.ToTable("DepositCurrencies");
});
modelBuilder.Entity("BankDatabase.Models.Period", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("EndTime")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("StartTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("StorekeeperId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("StorekeeperId");
b.ToTable("Periods");
});
modelBuilder.Entity("BankDatabase.Models.Replenishment", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<decimal>("Amount")
.HasColumnType("numeric");
b.Property<string>("ClerkId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("Date")
.HasColumnType("timestamp with time zone");
b.Property<string>("DepositId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ClerkId");
b.HasIndex("DepositId");
b.ToTable("Replenishments");
});
modelBuilder.Entity("BankDatabase.Models.Storekeeper", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Login")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MiddleName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Surname")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Email")
.IsUnique();
b.HasIndex("Login")
.IsUnique();
b.HasIndex("PhoneNumber")
.IsUnique();
b.ToTable("Storekeepers");
});
modelBuilder.Entity("BankDatabase.Models.Client", b =>
{
b.HasOne("BankDatabase.Models.Clerk", "Clerk")
.WithMany("Clients")
.HasForeignKey("ClerkId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Clerk");
});
modelBuilder.Entity("BankDatabase.Models.ClientCreditProgram", b =>
{
b.HasOne("BankDatabase.Models.Client", "Client")
.WithMany("CreditProgramClients")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BankDatabase.Models.CreditProgram", "CreditProgram")
.WithMany("CreditProgramClients")
.HasForeignKey("CreditProgramId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("CreditProgram");
});
modelBuilder.Entity("BankDatabase.Models.CreditProgram", b =>
{
b.HasOne("BankDatabase.Models.Period", "Period")
.WithMany("CreditPrograms")
.HasForeignKey("PeriodId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BankDatabase.Models.Storekeeper", "Storekeeper")
.WithMany("CreditPrograms")
.HasForeignKey("StorekeeperId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Period");
b.Navigation("Storekeeper");
});
modelBuilder.Entity("BankDatabase.Models.CreditProgramCurrency", b =>
{
b.HasOne("BankDatabase.Models.CreditProgram", "CreditProgram")
.WithMany("CurrencyCreditPrograms")
.HasForeignKey("CreditProgramId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BankDatabase.Models.Currency", "Currency")
.WithMany("CurrencyCreditPrograms")
.HasForeignKey("CurrencyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreditProgram");
b.Navigation("Currency");
});
modelBuilder.Entity("BankDatabase.Models.Currency", b =>
{
b.HasOne("BankDatabase.Models.Storekeeper", "Storekeeper")
.WithMany("Currencies")
.HasForeignKey("StorekeeperId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Storekeeper");
});
modelBuilder.Entity("BankDatabase.Models.Deposit", b =>
{
b.HasOne("BankDatabase.Models.Clerk", "Clerk")
.WithMany("Deposits")
.HasForeignKey("ClerkId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Clerk");
});
modelBuilder.Entity("BankDatabase.Models.DepositClient", b =>
{
b.HasOne("BankDatabase.Models.Client", "Client")
.WithMany("DepositClients")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BankDatabase.Models.Deposit", "Deposit")
.WithMany("DepositClients")
.HasForeignKey("DepositId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Deposit");
});
modelBuilder.Entity("BankDatabase.Models.DepositCurrency", b =>
{
b.HasOne("BankDatabase.Models.Currency", "Currency")
.WithMany("DepositCurrencies")
.HasForeignKey("CurrencyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BankDatabase.Models.Deposit", "Deposit")
.WithMany("DepositCurrencies")
.HasForeignKey("DepositId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Currency");
b.Navigation("Deposit");
});
modelBuilder.Entity("BankDatabase.Models.Period", b =>
{
b.HasOne("BankDatabase.Models.Storekeeper", "Storekeeper")
.WithMany("Periods")
.HasForeignKey("StorekeeperId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Storekeeper");
});
modelBuilder.Entity("BankDatabase.Models.Replenishment", b =>
{
b.HasOne("BankDatabase.Models.Clerk", "Clerk")
.WithMany("Replenishments")
.HasForeignKey("ClerkId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("BankDatabase.Models.Deposit", "Deposit")
.WithMany("Replenishments")
.HasForeignKey("DepositId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Clerk");
b.Navigation("Deposit");
});
modelBuilder.Entity("BankDatabase.Models.Clerk", b =>
{
b.Navigation("Clients");
b.Navigation("Deposits");
b.Navigation("Replenishments");
});
modelBuilder.Entity("BankDatabase.Models.Client", b =>
{
b.Navigation("CreditProgramClients");
b.Navigation("DepositClients");
});
modelBuilder.Entity("BankDatabase.Models.CreditProgram", b =>
{
b.Navigation("CreditProgramClients");
b.Navigation("CurrencyCreditPrograms");
});
modelBuilder.Entity("BankDatabase.Models.Currency", b =>
{
b.Navigation("CurrencyCreditPrograms");
b.Navigation("DepositCurrencies");
});
modelBuilder.Entity("BankDatabase.Models.Deposit", b =>
{
b.Navigation("DepositClients");
b.Navigation("DepositCurrencies");
b.Navigation("Replenishments");
});
modelBuilder.Entity("BankDatabase.Models.Period", b =>
{
b.Navigation("CreditPrograms");
});
modelBuilder.Entity("BankDatabase.Models.Storekeeper", b =>
{
b.Navigation("CreditPrograms");
b.Navigation("Currencies");
b.Navigation("Periods");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,433 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BankDatabase.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Clerks",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
Surname = table.Column<string>(type: "text", nullable: false),
MiddleName = table.Column<string>(type: "text", nullable: false),
Login = table.Column<string>(type: "text", nullable: false),
Password = table.Column<string>(type: "text", nullable: false),
Email = table.Column<string>(type: "text", nullable: false),
PhoneNumber = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Clerks", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Storekeepers",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
Surname = table.Column<string>(type: "text", nullable: false),
MiddleName = table.Column<string>(type: "text", nullable: false),
Login = table.Column<string>(type: "text", nullable: false),
Password = table.Column<string>(type: "text", nullable: false),
Email = table.Column<string>(type: "text", nullable: false),
PhoneNumber = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Storekeepers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Clients",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
Surname = table.Column<string>(type: "text", nullable: false),
Balance = table.Column<decimal>(type: "numeric", nullable: false),
ClerkId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Clients", x => x.Id);
table.ForeignKey(
name: "FK_Clients_Clerks_ClerkId",
column: x => x.ClerkId,
principalTable: "Clerks",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Deposits",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
InterestRate = table.Column<float>(type: "real", nullable: false),
Cost = table.Column<decimal>(type: "numeric", nullable: false),
Period = table.Column<int>(type: "integer", nullable: false),
ClerkId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Deposits", x => x.Id);
table.ForeignKey(
name: "FK_Deposits_Clerks_ClerkId",
column: x => x.ClerkId,
principalTable: "Clerks",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Currencies",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
Abbreviation = table.Column<string>(type: "text", nullable: false),
Cost = table.Column<decimal>(type: "numeric", nullable: false),
StorekeeperId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Currencies", x => x.Id);
table.ForeignKey(
name: "FK_Currencies_Storekeepers_StorekeeperId",
column: x => x.StorekeeperId,
principalTable: "Storekeepers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Periods",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
StartTime = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
EndTime = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
StorekeeperId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Periods", x => x.Id);
table.ForeignKey(
name: "FK_Periods_Storekeepers_StorekeeperId",
column: x => x.StorekeeperId,
principalTable: "Storekeepers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "DepositClients",
columns: table => new
{
DepositId = table.Column<string>(type: "text", nullable: false),
ClientId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DepositClients", x => new { x.DepositId, x.ClientId });
table.ForeignKey(
name: "FK_DepositClients_Clients_ClientId",
column: x => x.ClientId,
principalTable: "Clients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_DepositClients_Deposits_DepositId",
column: x => x.DepositId,
principalTable: "Deposits",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Replenishments",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
Amount = table.Column<decimal>(type: "numeric", nullable: false),
Date = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
DepositId = table.Column<string>(type: "text", nullable: false),
ClerkId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Replenishments", x => x.Id);
table.ForeignKey(
name: "FK_Replenishments_Clerks_ClerkId",
column: x => x.ClerkId,
principalTable: "Clerks",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Replenishments_Deposits_DepositId",
column: x => x.DepositId,
principalTable: "Deposits",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "DepositCurrencies",
columns: table => new
{
DepositId = table.Column<string>(type: "text", nullable: false),
CurrencyId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DepositCurrencies", x => new { x.DepositId, x.CurrencyId });
table.ForeignKey(
name: "FK_DepositCurrencies_Currencies_CurrencyId",
column: x => x.CurrencyId,
principalTable: "Currencies",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_DepositCurrencies_Deposits_DepositId",
column: x => x.DepositId,
principalTable: "Deposits",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "CreditPrograms",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
Cost = table.Column<decimal>(type: "numeric", nullable: false),
MaxCost = table.Column<decimal>(type: "numeric", nullable: false),
StorekeeperId = table.Column<string>(type: "text", nullable: false),
PeriodId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CreditPrograms", x => x.Id);
table.ForeignKey(
name: "FK_CreditPrograms_Periods_PeriodId",
column: x => x.PeriodId,
principalTable: "Periods",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_CreditPrograms_Storekeepers_StorekeeperId",
column: x => x.StorekeeperId,
principalTable: "Storekeepers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "CreditProgramClients",
columns: table => new
{
ClientId = table.Column<string>(type: "text", nullable: false),
CreditProgramId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CreditProgramClients", x => new { x.ClientId, x.CreditProgramId });
table.ForeignKey(
name: "FK_CreditProgramClients_Clients_ClientId",
column: x => x.ClientId,
principalTable: "Clients",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_CreditProgramClients_CreditPrograms_CreditProgramId",
column: x => x.CreditProgramId,
principalTable: "CreditPrograms",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "CurrencyCreditPrograms",
columns: table => new
{
CreditProgramId = table.Column<string>(type: "text", nullable: false),
CurrencyId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CurrencyCreditPrograms", x => new { x.CreditProgramId, x.CurrencyId });
table.ForeignKey(
name: "FK_CurrencyCreditPrograms_CreditPrograms_CreditProgramId",
column: x => x.CreditProgramId,
principalTable: "CreditPrograms",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_CurrencyCreditPrograms_Currencies_CurrencyId",
column: x => x.CurrencyId,
principalTable: "Currencies",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Clerks_Email",
table: "Clerks",
column: "Email",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Clerks_Login",
table: "Clerks",
column: "Login",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Clerks_PhoneNumber",
table: "Clerks",
column: "PhoneNumber",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Clients_ClerkId",
table: "Clients",
column: "ClerkId");
migrationBuilder.CreateIndex(
name: "IX_CreditProgramClients_CreditProgramId",
table: "CreditProgramClients",
column: "CreditProgramId");
migrationBuilder.CreateIndex(
name: "IX_CreditPrograms_Name",
table: "CreditPrograms",
column: "Name",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_CreditPrograms_PeriodId",
table: "CreditPrograms",
column: "PeriodId");
migrationBuilder.CreateIndex(
name: "IX_CreditPrograms_StorekeeperId",
table: "CreditPrograms",
column: "StorekeeperId");
migrationBuilder.CreateIndex(
name: "IX_Currencies_Abbreviation",
table: "Currencies",
column: "Abbreviation",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Currencies_StorekeeperId",
table: "Currencies",
column: "StorekeeperId");
migrationBuilder.CreateIndex(
name: "IX_CurrencyCreditPrograms_CurrencyId",
table: "CurrencyCreditPrograms",
column: "CurrencyId");
migrationBuilder.CreateIndex(
name: "IX_DepositClients_ClientId",
table: "DepositClients",
column: "ClientId");
migrationBuilder.CreateIndex(
name: "IX_DepositCurrencies_CurrencyId",
table: "DepositCurrencies",
column: "CurrencyId");
migrationBuilder.CreateIndex(
name: "IX_Deposits_ClerkId",
table: "Deposits",
column: "ClerkId");
migrationBuilder.CreateIndex(
name: "IX_Periods_StorekeeperId",
table: "Periods",
column: "StorekeeperId");
migrationBuilder.CreateIndex(
name: "IX_Replenishments_ClerkId",
table: "Replenishments",
column: "ClerkId");
migrationBuilder.CreateIndex(
name: "IX_Replenishments_DepositId",
table: "Replenishments",
column: "DepositId");
migrationBuilder.CreateIndex(
name: "IX_Storekeepers_Email",
table: "Storekeepers",
column: "Email",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Storekeepers_Login",
table: "Storekeepers",
column: "Login",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Storekeepers_PhoneNumber",
table: "Storekeepers",
column: "PhoneNumber",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "CreditProgramClients");
migrationBuilder.DropTable(
name: "CurrencyCreditPrograms");
migrationBuilder.DropTable(
name: "DepositClients");
migrationBuilder.DropTable(
name: "DepositCurrencies");
migrationBuilder.DropTable(
name: "Replenishments");
migrationBuilder.DropTable(
name: "CreditPrograms");
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "Currencies");
migrationBuilder.DropTable(
name: "Deposits");
migrationBuilder.DropTable(
name: "Periods");
migrationBuilder.DropTable(
name: "Clerks");
migrationBuilder.DropTable(
name: "Storekeepers");
}
}
}

View File

@@ -0,0 +1,559 @@
// <auto-generated />
using System;
using BankDatabase;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace BankDatabase.Migrations
{
[DbContext(typeof(BankDbContext))]
partial class BankDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("BankDatabase.Models.Clerk", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Login")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MiddleName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Surname")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Email")
.IsUnique();
b.HasIndex("Login")
.IsUnique();
b.HasIndex("PhoneNumber")
.IsUnique();
b.ToTable("Clerks");
});
modelBuilder.Entity("BankDatabase.Models.Client", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<decimal>("Balance")
.HasColumnType("numeric");
b.Property<string>("ClerkId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Surname")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ClerkId");
b.ToTable("Clients");
});
modelBuilder.Entity("BankDatabase.Models.ClientCreditProgram", b =>
{
b.Property<string>("ClientId")
.HasColumnType("text");
b.Property<string>("CreditProgramId")
.HasColumnType("text");
b.HasKey("ClientId", "CreditProgramId");
b.HasIndex("CreditProgramId");
b.ToTable("CreditProgramClients");
});
modelBuilder.Entity("BankDatabase.Models.CreditProgram", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<decimal>("Cost")
.HasColumnType("numeric");
b.Property<decimal>("MaxCost")
.HasColumnType("numeric");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PeriodId")
.IsRequired()
.HasColumnType("text");
b.Property<string>("StorekeeperId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Name")
.IsUnique();
b.HasIndex("PeriodId");
b.HasIndex("StorekeeperId");
b.ToTable("CreditPrograms");
});
modelBuilder.Entity("BankDatabase.Models.CreditProgramCurrency", b =>
{
b.Property<string>("CreditProgramId")
.HasColumnType("text");
b.Property<string>("CurrencyId")
.HasColumnType("text");
b.HasKey("CreditProgramId", "CurrencyId");
b.HasIndex("CurrencyId");
b.ToTable("CurrencyCreditPrograms");
});
modelBuilder.Entity("BankDatabase.Models.Currency", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Abbreviation")
.IsRequired()
.HasColumnType("text");
b.Property<decimal>("Cost")
.HasColumnType("numeric");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("StorekeeperId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Abbreviation")
.IsUnique();
b.HasIndex("StorekeeperId");
b.ToTable("Currencies");
});
modelBuilder.Entity("BankDatabase.Models.Deposit", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ClerkId")
.IsRequired()
.HasColumnType("text");
b.Property<decimal>("Cost")
.HasColumnType("numeric");
b.Property<float>("InterestRate")
.HasColumnType("real");
b.Property<int>("Period")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("ClerkId");
b.ToTable("Deposits");
});
modelBuilder.Entity("BankDatabase.Models.DepositClient", b =>
{
b.Property<string>("DepositId")
.HasColumnType("text");
b.Property<string>("ClientId")
.HasColumnType("text");
b.HasKey("DepositId", "ClientId");
b.HasIndex("ClientId");
b.ToTable("DepositClients");
});
modelBuilder.Entity("BankDatabase.Models.DepositCurrency", b =>
{
b.Property<string>("DepositId")
.HasColumnType("text");
b.Property<string>("CurrencyId")
.HasColumnType("text");
b.HasKey("DepositId", "CurrencyId");
b.HasIndex("CurrencyId");
b.ToTable("DepositCurrencies");
});
modelBuilder.Entity("BankDatabase.Models.Period", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<DateTime>("EndTime")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("StartTime")
.HasColumnType("timestamp with time zone");
b.Property<string>("StorekeeperId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("StorekeeperId");
b.ToTable("Periods");
});
modelBuilder.Entity("BankDatabase.Models.Replenishment", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<decimal>("Amount")
.HasColumnType("numeric");
b.Property<string>("ClerkId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("Date")
.HasColumnType("timestamp with time zone");
b.Property<string>("DepositId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("ClerkId");
b.HasIndex("DepositId");
b.ToTable("Replenishments");
});
modelBuilder.Entity("BankDatabase.Models.Storekeeper", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Login")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MiddleName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Surname")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("Email")
.IsUnique();
b.HasIndex("Login")
.IsUnique();
b.HasIndex("PhoneNumber")
.IsUnique();
b.ToTable("Storekeepers");
});
modelBuilder.Entity("BankDatabase.Models.Client", b =>
{
b.HasOne("BankDatabase.Models.Clerk", "Clerk")
.WithMany("Clients")
.HasForeignKey("ClerkId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Clerk");
});
modelBuilder.Entity("BankDatabase.Models.ClientCreditProgram", b =>
{
b.HasOne("BankDatabase.Models.Client", "Client")
.WithMany("CreditProgramClients")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BankDatabase.Models.CreditProgram", "CreditProgram")
.WithMany("CreditProgramClients")
.HasForeignKey("CreditProgramId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("CreditProgram");
});
modelBuilder.Entity("BankDatabase.Models.CreditProgram", b =>
{
b.HasOne("BankDatabase.Models.Period", "Period")
.WithMany("CreditPrograms")
.HasForeignKey("PeriodId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BankDatabase.Models.Storekeeper", "Storekeeper")
.WithMany("CreditPrograms")
.HasForeignKey("StorekeeperId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Period");
b.Navigation("Storekeeper");
});
modelBuilder.Entity("BankDatabase.Models.CreditProgramCurrency", b =>
{
b.HasOne("BankDatabase.Models.CreditProgram", "CreditProgram")
.WithMany("CurrencyCreditPrograms")
.HasForeignKey("CreditProgramId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BankDatabase.Models.Currency", "Currency")
.WithMany("CurrencyCreditPrograms")
.HasForeignKey("CurrencyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreditProgram");
b.Navigation("Currency");
});
modelBuilder.Entity("BankDatabase.Models.Currency", b =>
{
b.HasOne("BankDatabase.Models.Storekeeper", "Storekeeper")
.WithMany("Currencies")
.HasForeignKey("StorekeeperId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Storekeeper");
});
modelBuilder.Entity("BankDatabase.Models.Deposit", b =>
{
b.HasOne("BankDatabase.Models.Clerk", "Clerk")
.WithMany("Deposits")
.HasForeignKey("ClerkId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Clerk");
});
modelBuilder.Entity("BankDatabase.Models.DepositClient", b =>
{
b.HasOne("BankDatabase.Models.Client", "Client")
.WithMany("DepositClients")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BankDatabase.Models.Deposit", "Deposit")
.WithMany("DepositClients")
.HasForeignKey("DepositId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Deposit");
});
modelBuilder.Entity("BankDatabase.Models.DepositCurrency", b =>
{
b.HasOne("BankDatabase.Models.Currency", "Currency")
.WithMany("DepositCurrencies")
.HasForeignKey("CurrencyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BankDatabase.Models.Deposit", "Deposit")
.WithMany("DepositCurrencies")
.HasForeignKey("DepositId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Currency");
b.Navigation("Deposit");
});
modelBuilder.Entity("BankDatabase.Models.Period", b =>
{
b.HasOne("BankDatabase.Models.Storekeeper", "Storekeeper")
.WithMany("Periods")
.HasForeignKey("StorekeeperId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Storekeeper");
});
modelBuilder.Entity("BankDatabase.Models.Replenishment", b =>
{
b.HasOne("BankDatabase.Models.Clerk", "Clerk")
.WithMany("Replenishments")
.HasForeignKey("ClerkId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("BankDatabase.Models.Deposit", "Deposit")
.WithMany("Replenishments")
.HasForeignKey("DepositId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Clerk");
b.Navigation("Deposit");
});
modelBuilder.Entity("BankDatabase.Models.Clerk", b =>
{
b.Navigation("Clients");
b.Navigation("Deposits");
b.Navigation("Replenishments");
});
modelBuilder.Entity("BankDatabase.Models.Client", b =>
{
b.Navigation("CreditProgramClients");
b.Navigation("DepositClients");
});
modelBuilder.Entity("BankDatabase.Models.CreditProgram", b =>
{
b.Navigation("CreditProgramClients");
b.Navigation("CurrencyCreditPrograms");
});
modelBuilder.Entity("BankDatabase.Models.Currency", b =>
{
b.Navigation("CurrencyCreditPrograms");
b.Navigation("DepositCurrencies");
});
modelBuilder.Entity("BankDatabase.Models.Deposit", b =>
{
b.Navigation("DepositClients");
b.Navigation("DepositCurrencies");
b.Navigation("Replenishments");
});
modelBuilder.Entity("BankDatabase.Models.Period", b =>
{
b.Navigation("CreditPrograms");
});
modelBuilder.Entity("BankDatabase.Models.Storekeeper", b =>
{
b.Navigation("CreditPrograms");
b.Navigation("Currencies");
b.Navigation("Periods");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -2,7 +2,7 @@
namespace BankDatabase.Models;
class Clerk
public class Clerk
{
public required string Id { get; set; }

View File

@@ -2,7 +2,7 @@
namespace BankDatabase.Models;
class Client
public class Client
{
public required string Id { get; set; }

View File

@@ -1,6 +1,8 @@
namespace BankDatabase.Models;
using System.ComponentModel.DataAnnotations.Schema;
class ClientCreditProgram
namespace BankDatabase.Models;
public class ClientCreditProgram
{
public required string ClientId { get; set; }

View File

@@ -2,7 +2,7 @@
namespace BankDatabase.Models;
class CreditProgram
public class CreditProgram
{
public required string Id { get; set; }

View File

@@ -1,6 +1,6 @@
namespace BankDatabase.Models;
class CreditProgramCurrency
public class CreditProgramCurrency
{
public required string CreditProgramId { get; set; }

View File

@@ -2,7 +2,7 @@
namespace BankDatabase.Models;
class Currency
public class Currency
{
public required string Id { get; set; }

View File

@@ -2,7 +2,7 @@
namespace BankDatabase.Models;
class Deposit
public class Deposit
{
public required string Id { get; set; }

View File

@@ -1,6 +1,8 @@
namespace BankDatabase.Models;
using System.ComponentModel.DataAnnotations.Schema;
class DepositClient
namespace BankDatabase.Models;
public class DepositClient
{
public required string DepositId { get; set; }

View File

@@ -1,12 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations.Schema;
namespace BankDatabase.Models;
class DepositCurrency
public class DepositCurrency
{
public required string DepositId { get; set; }

View File

@@ -2,7 +2,7 @@
namespace BankDatabase.Models;
class Period
public class Period
{
public required string Id { get; set; }

View File

@@ -2,7 +2,7 @@
namespace BankDatabase.Models;
class Replenishment
public class Replenishment
{
public required string Id { get; set; }

View File

@@ -1,9 +1,8 @@
using BankContracts.DataModels;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations.Schema;
namespace BankDatabase.Models;
class Storekeeper
public class Storekeeper
{
public required string Id { get; set; }

View File

@@ -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>

View File

@@ -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);
}
}

View File

@@ -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);

View File

@@ -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";
}

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