Compare commits
18 Commits
Task_5_Api
...
Task_7_UI
| Author | SHA1 | Date | |
|---|---|---|---|
| b70143484d | |||
| 75c0be18ce | |||
| a26193512c | |||
| ed2369ed85 | |||
| b977e76302 | |||
| 4fdc420920 | |||
| 8e930475a3 | |||
| 57f878a051 | |||
| b59bdf9f3d | |||
| f5d5ff4b24 | |||
| 3e48ad4d24 | |||
| b1e5b7de93 | |||
| 9ed33690cf | |||
| 1c0bf1efd2 | |||
| e8f493691f | |||
| de879be266 | |||
| 164def1e18 | |||
| 56053a7287 |
@@ -24,17 +24,27 @@ public class ReportContract(IClientStorageContract clientStorage, ICurrencyStora
|
||||
private static readonly string[] clientsByDepositHeader = ["Фамилия", "Имя", "Баланс", "Ставка", "Срок", "Период"];
|
||||
private static readonly string[] currencyHeader = ["Валюта", "Кредитная программа", "Макс. сумма", "Ставка", "Срок"];
|
||||
|
||||
public async Task<List<ClientsByCreditProgramDataModel>> GetDataClientsByCreditProgramAsync(CancellationToken ct)
|
||||
/// <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);
|
||||
|
||||
return creditPrograms
|
||||
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(),
|
||||
@@ -45,10 +55,17 @@ public class ReportContract(IClientStorageContract clientStorage, ICurrencyStora
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
public async Task<Stream> CreateDocumentClientsByCreditProgramAsync(CancellationToken ct)
|
||||
/// <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(ct) ?? throw new InvalidOperationException("No found data");
|
||||
var data = await GetDataClientsByCreditProgramAsync(creditProgramIds, ct) ?? throw new InvalidOperationException("No found data");
|
||||
|
||||
var tableRows = new List<string[]>
|
||||
{
|
||||
@@ -76,10 +93,17 @@ public class ReportContract(IClientStorageContract clientStorage, ICurrencyStora
|
||||
.Build();
|
||||
}
|
||||
|
||||
public async Task<Stream> CreateExcelDocumentClientsByCreditProgramAsync(CancellationToken ct)
|
||||
/// <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(ct) ?? throw new InvalidOperationException("No found data");
|
||||
var data = await GetDataClientsByCreditProgramAsync(creditProgramIds, ct) ?? throw new InvalidOperationException("No found data");
|
||||
|
||||
var tableRows = new List<string[]>
|
||||
{
|
||||
@@ -107,6 +131,15 @@ public class ReportContract(IClientStorageContract clientStorage, ICurrencyStora
|
||||
.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);
|
||||
@@ -155,6 +188,15 @@ public class ReportContract(IClientStorageContract clientStorage, ICurrencyStora
|
||||
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);
|
||||
@@ -187,6 +229,15 @@ public class ReportContract(IClientStorageContract clientStorage, ICurrencyStora
|
||||
.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);
|
||||
@@ -215,6 +266,15 @@ public class ReportContract(IClientStorageContract clientStorage, ICurrencyStora
|
||||
}).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);
|
||||
@@ -249,7 +309,15 @@ public class ReportContract(IClientStorageContract clientStorage, ICurrencyStora
|
||||
.Build();
|
||||
}
|
||||
|
||||
public async Task<List<DepositByCreditProgramDataModel>> GetDataDepositByCreditProgramAsync(CancellationToken ct)
|
||||
|
||||
/// <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);
|
||||
@@ -261,7 +329,10 @@ public class ReportContract(IClientStorageContract clientStorage, ICurrencyStora
|
||||
throw new InvalidOperationException("No deposits with currencies found");
|
||||
}
|
||||
|
||||
return creditPrograms.Select(cp => new DepositByCreditProgramDataModel
|
||||
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(),
|
||||
@@ -270,10 +341,18 @@ public class ReportContract(IClientStorageContract clientStorage, ICurrencyStora
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
public async Task<Stream> CreateDocumentDepositByCreditProgramAsync(CancellationToken ct)
|
||||
|
||||
/// <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(ct) ?? throw new InvalidOperationException("No found data");
|
||||
var data = await GetDataDepositByCreditProgramAsync(creditProgramIds, ct) ?? throw new InvalidOperationException("No found data");
|
||||
|
||||
var tableRows = new List<string[]>
|
||||
{
|
||||
@@ -301,10 +380,17 @@ public class ReportContract(IClientStorageContract clientStorage, ICurrencyStora
|
||||
.Build();
|
||||
}
|
||||
|
||||
public async Task<Stream> CreateExcelDocumentDepositByCreditProgramAsync(CancellationToken ct)
|
||||
/// <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(ct) ?? throw new InvalidOperationException("No found data");
|
||||
var data = await GetDataDepositByCreditProgramAsync(creditProgramIds, ct) ?? throw new InvalidOperationException("No found data");
|
||||
|
||||
var tableRows = new List<string[]>
|
||||
{
|
||||
|
||||
@@ -15,4 +15,6 @@ public interface IClerkAdapter
|
||||
ClerkOperationResponse RegisterClerk(ClerkBindingModel clerkModel);
|
||||
|
||||
ClerkOperationResponse ChangeClerkInfo(ClerkBindingModel clerkModel);
|
||||
|
||||
ClerkOperationResponse Login(LoginBindingModel clerkModel, out string token);
|
||||
}
|
||||
|
||||
@@ -4,15 +4,15 @@ namespace BankContracts.AdapterContracts;
|
||||
|
||||
public interface IReportAdapter
|
||||
{
|
||||
Task<ReportOperationResponse> GetDataClientsByCreditProgramAsync(CancellationToken ct);
|
||||
Task<ReportOperationResponse> GetDataClientsByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct);
|
||||
Task<ReportOperationResponse> GetDataClientsByDepositAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
Task<ReportOperationResponse> GetDataDepositByCreditProgramAsync(CancellationToken ct);
|
||||
Task<ReportOperationResponse> GetDataDepositByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct);
|
||||
Task<ReportOperationResponse> GetDataDepositAndCreditProgramByCurrencyAsync(DateTime dateStart, DateTime dateFinish, CancellationToken ct);
|
||||
|
||||
Task<ReportOperationResponse> CreateDocumentClientsByCreditProgramAsync(CancellationToken ct);
|
||||
Task<ReportOperationResponse> CreateExcelDocumentClientsByCreditProgramAsync(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(CancellationToken ct);
|
||||
Task<ReportOperationResponse> CreateExcelDocumentDepositByCreditProgramAsync(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);
|
||||
}
|
||||
|
||||
@@ -15,4 +15,6 @@ public interface IStorekeeperAdapter
|
||||
StorekeeperOperationResponse RegisterStorekeeper(StorekeeperBindingModel storekeeperModel);
|
||||
|
||||
StorekeeperOperationResponse ChangeStorekeeperInfo(StorekeeperBindingModel storekeeperModel);
|
||||
|
||||
StorekeeperOperationResponse Login(LoginBindingModel storekeeperModel, out string token);
|
||||
}
|
||||
|
||||
@@ -21,4 +21,7 @@ public class ClerkOperationResponse : OperationResponse
|
||||
|
||||
public static ClerkOperationResponse InternalServerError(string message) =>
|
||||
InternalServerError<ClerkOperationResponse>(message);
|
||||
|
||||
public static ClerkOperationResponse Unauthorized(string message) =>
|
||||
Unauthorized<ClerkOperationResponse>(message);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,9 @@ 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);
|
||||
|
||||
@@ -21,4 +24,7 @@ public class StorekeeperOperationResponse : OperationResponse
|
||||
|
||||
public static StorekeeperOperationResponse InternalServerError(string message) =>
|
||||
InternalServerError<StorekeeperOperationResponse>(message);
|
||||
|
||||
public static StorekeeperOperationResponse Unauthorized(string message) =>
|
||||
Unauthorized<StorekeeperOperationResponse>(message);
|
||||
}
|
||||
|
||||
8
TheBank/BankContracts/BindingModels/LoginBindingModel.cs
Normal file
8
TheBank/BankContracts/BindingModels/LoginBindingModel.cs
Normal file
@@ -0,0 +1,8 @@
|
||||
namespace BankContracts.BindingModels;
|
||||
|
||||
public class LoginBindingModel
|
||||
{
|
||||
public required string Login { get; set; }
|
||||
|
||||
public required string Password { get; set; }
|
||||
}
|
||||
@@ -2,9 +2,11 @@
|
||||
|
||||
public class MailSendInfoBindingModel
|
||||
{
|
||||
public string MailAddress { get; set; } = string.Empty;
|
||||
public string ToEmail { get; set; } = string.Empty;
|
||||
|
||||
public string Subject { get; set; } = string.Empty;
|
||||
public string Text { get; set; } = string.Empty;
|
||||
public MemoryStream Attachment { get; set; } = new MemoryStream();
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
|
||||
public string Body { get; set; } = string.Empty;
|
||||
|
||||
public string? AttachmentPath { get; set; }
|
||||
}
|
||||
|
||||
@@ -4,16 +4,16 @@ namespace BankContracts.BusinessLogicContracts;
|
||||
|
||||
public interface IReportContract
|
||||
{
|
||||
Task<List<ClientsByCreditProgramDataModel>> GetDataClientsByCreditProgramAsync(CancellationToken ct);
|
||||
Task<Stream> CreateDocumentClientsByCreditProgramAsync(CancellationToken ct);
|
||||
Task<Stream> CreateExcelDocumentClientsByCreditProgramAsync(CancellationToken ct);
|
||||
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(CancellationToken ct);
|
||||
Task<Stream> CreateDocumentDepositByCreditProgramAsync(CancellationToken ct);
|
||||
Task<Stream> CreateExcelDocumentDepositByCreditProgramAsync(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);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
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; }
|
||||
|
||||
@@ -58,4 +58,8 @@ public class OperationResponse
|
||||
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 };
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -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; }
|
||||
|
||||
17
TheBank/BankDatabase/DesignTimeDbContextFactory.cs
Normal file
17
TheBank/BankDatabase/DesignTimeDbContextFactory.cs
Normal 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;";
|
||||
}
|
||||
@@ -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}");
|
||||
|
||||
562
TheBank/BankDatabase/Migrations/20250518195627_InitialCreate.Designer.cs
generated
Normal file
562
TheBank/BankDatabase/Migrations/20250518195627_InitialCreate.Designer.cs
generated
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
433
TheBank/BankDatabase/Migrations/20250518195627_InitialCreate.cs
Normal file
433
TheBank/BankDatabase/Migrations/20250518195627_InitialCreate.cs
Normal 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
559
TheBank/BankDatabase/Migrations/BankDbContextModelSnapshot.cs
Normal file
559
TheBank/BankDatabase/Migrations/BankDbContextModelSnapshot.cs
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace BankDatabase.Models;
|
||||
|
||||
class Clerk
|
||||
public class Clerk
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace BankDatabase.Models;
|
||||
|
||||
class Client
|
||||
public class Client
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
|
||||
@@ -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; }
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace BankDatabase.Models;
|
||||
|
||||
class CreditProgram
|
||||
public class CreditProgram
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace BankDatabase.Models;
|
||||
|
||||
class CreditProgramCurrency
|
||||
public class CreditProgramCurrency
|
||||
{
|
||||
public required string CreditProgramId { get; set; }
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace BankDatabase.Models;
|
||||
|
||||
class Currency
|
||||
public class Currency
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace BankDatabase.Models;
|
||||
|
||||
class Deposit
|
||||
public class Deposit
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
|
||||
@@ -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; }
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
namespace BankDatabase.Models;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
class DepositCurrency
|
||||
namespace BankDatabase.Models;
|
||||
|
||||
public class DepositCurrency
|
||||
{
|
||||
public required string DepositId { get; set; }
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace BankDatabase.Models;
|
||||
|
||||
class Period
|
||||
public class Period
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace BankDatabase.Models;
|
||||
|
||||
class Replenishment
|
||||
public class Replenishment
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
namespace BankDatabase.Models;
|
||||
|
||||
class Storekeeper
|
||||
public class Storekeeper
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ using System.Text;
|
||||
namespace BankTests.ReportContractTests;
|
||||
|
||||
[TestFixture]
|
||||
internal class ReportContractTestss
|
||||
internal class ReportContractTests
|
||||
{
|
||||
private ReportContract _reportContract;
|
||||
private Mock<IClientStorageContract> _clientStorage;
|
||||
@@ -65,12 +65,37 @@ internal class ReportContractTestss
|
||||
new DepositDataModel("d1", 5, 1000, 12, "cl", new List<DepositCurrencyDataModel>())
|
||||
});
|
||||
|
||||
var result = await _reportContract.GetDataDepositByCreditProgramAsync(ct);
|
||||
var result = await _reportContract.GetDataDepositByCreditProgramAsync(null, ct);
|
||||
|
||||
Assert.That(result, Is.Not.Null);
|
||||
Assert.That(result.Count, Is.GreaterThanOrEqualTo(0));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetDataDepositByCreditProgramAsync_WithFilter_ReturnsFilteredData()
|
||||
{
|
||||
var ct = CancellationToken.None;
|
||||
var creditProgramIds = new List<string> { "1" };
|
||||
|
||||
_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> { new() { CurrencyId = "1" } }),
|
||||
new CreditProgramDataModel("2", "Программа 2", 100, 200, "sk", "p", new List<CreditProgramCurrencyDataModel> { new() { CurrencyId = "1" } })
|
||||
});
|
||||
_depositStorage.Setup(x => x.GetList(It.IsAny<string>()))
|
||||
.Returns(new List<DepositDataModel>
|
||||
{
|
||||
new DepositDataModel("d1", 5, 1000, 12, "cl", new List<DepositCurrencyDataModel> { new() { CurrencyId = "1" } })
|
||||
});
|
||||
|
||||
var result = await _reportContract.GetDataDepositByCreditProgramAsync(creditProgramIds, ct);
|
||||
|
||||
Assert.That(result, Is.Not.Null);
|
||||
Assert.That(result.Count, Is.EqualTo(1));
|
||||
Assert.That(result[0].CreditProgramName, Is.EqualTo("Программа 1"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CreateDocumentDepositByCreditProgramAsync_CallsWordBuilder()
|
||||
{
|
||||
@@ -78,12 +103,12 @@ internal class ReportContractTestss
|
||||
_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>())
|
||||
new CreditProgramDataModel("1", "Программа 1", 100, 200, "sk", "p", new List<CreditProgramCurrencyDataModel> { new() { CurrencyId = "1" } })
|
||||
});
|
||||
_depositStorage.Setup(x => x.GetList(It.IsAny<string>()))
|
||||
.Returns(new List<DepositDataModel>
|
||||
{
|
||||
new DepositDataModel("d1", 5, 1000, 12, "cl", new List<DepositCurrencyDataModel>())
|
||||
new DepositDataModel("d1", 5, 1000, 12, "cl", new List<DepositCurrencyDataModel> { new() { CurrencyId = "1" } })
|
||||
});
|
||||
|
||||
_baseWordBuilder.Setup(x => x.AddHeader(It.IsAny<string>())).Returns(_baseWordBuilder.Object);
|
||||
@@ -91,7 +116,7 @@ internal class ReportContractTestss
|
||||
_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);
|
||||
var stream = await _reportContract.CreateDocumentDepositByCreditProgramAsync(new List<string> { "1" }, ct);
|
||||
|
||||
Assert.That(stream, Is.Not.Null);
|
||||
_baseWordBuilder.Verify(x => x.AddHeader(It.IsAny<string>()), Times.Once);
|
||||
@@ -163,6 +188,35 @@ internal class ReportContractTestss
|
||||
|
||||
[Test]
|
||||
public async Task CreateExcelDocumentDepositByCreditProgramAsync_CallsExcelBuilder()
|
||||
{
|
||||
var ct = CancellationToken.None;
|
||||
_creditProgramStorage.Setup(x => x.GetList(It.IsAny<string>(), It.IsAny<string>()))
|
||||
.Returns(new List<CreditProgramDataModel>
|
||||
{
|
||||
new CreditProgramDataModel("1", "Программа 1", 100, 200, "sk", "p", new List<CreditProgramCurrencyDataModel> { new() { CurrencyId = "1" } })
|
||||
});
|
||||
_depositStorage.Setup(x => x.GetList(It.IsAny<string>()))
|
||||
.Returns(new List<DepositDataModel>
|
||||
{
|
||||
new DepositDataModel("d1", 5, 1000, 12, "cl", new List<DepositCurrencyDataModel> { new() { CurrencyId = "1" } })
|
||||
});
|
||||
|
||||
_baseExcelBuilder.Setup(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).Returns(_baseExcelBuilder.Object);
|
||||
_baseExcelBuilder.Setup(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>())).Returns(_baseExcelBuilder.Object);
|
||||
_baseExcelBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>())).Returns(_baseExcelBuilder.Object);
|
||||
_baseExcelBuilder.Setup(x => x.Build()).Returns(new MemoryStream(Encoding.UTF8.GetBytes("test")));
|
||||
|
||||
var stream = await _reportContract.CreateExcelDocumentDepositByCreditProgramAsync(new List<string> { "1" }, ct);
|
||||
|
||||
Assert.That(stream, Is.Not.Null);
|
||||
_baseExcelBuilder.Verify(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()), Times.Once);
|
||||
_baseExcelBuilder.Verify(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>()), Times.Once);
|
||||
_baseExcelBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
|
||||
_baseExcelBuilder.Verify(x => x.Build(), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GetDataDepositByCreditProgramAsync_NoCurrencies_ThrowsException()
|
||||
{
|
||||
var ct = CancellationToken.None;
|
||||
_creditProgramStorage.Setup(x => x.GetList(It.IsAny<string>(), It.IsAny<string>()))
|
||||
@@ -176,17 +230,7 @@ internal class ReportContractTestss
|
||||
new DepositDataModel("d1", 5, 1000, 12, "cl", new List<DepositCurrencyDataModel>())
|
||||
});
|
||||
|
||||
_baseExcelBuilder.Setup(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>())).Returns(_baseExcelBuilder.Object);
|
||||
_baseExcelBuilder.Setup(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>())).Returns(_baseExcelBuilder.Object);
|
||||
_baseExcelBuilder.Setup(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>())).Returns(_baseExcelBuilder.Object);
|
||||
_baseExcelBuilder.Setup(x => x.Build()).Returns(new MemoryStream(Encoding.UTF8.GetBytes("test")));
|
||||
|
||||
var stream = await _reportContract.CreateExcelDocumentDepositByCreditProgramAsync(ct);
|
||||
|
||||
Assert.That(stream, Is.Not.Null);
|
||||
_baseExcelBuilder.Verify(x => x.AddHeader(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>()), Times.Once);
|
||||
_baseExcelBuilder.Verify(x => x.AddParagraph(It.IsAny<string>(), It.IsAny<int>()), Times.Once);
|
||||
_baseExcelBuilder.Verify(x => x.AddTable(It.IsAny<int[]>(), It.IsAny<List<string[]>>()), Times.Once);
|
||||
_baseExcelBuilder.Verify(x => x.Build(), Times.Once);
|
||||
Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
_reportContract.GetDataDepositByCreditProgramAsync(null, ct));
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ internal class BaseStorageContractTest
|
||||
[OneTimeSetUp]
|
||||
public void OneTimeSetUp()
|
||||
{
|
||||
BankDbContext = new BankDbContext(new ConfigurationDatabase());
|
||||
BankDbContext = new BankDbContext(new Infrastructure.ConfigurationDatabase());
|
||||
|
||||
BankDbContext.Database.EnsureDeleted();
|
||||
BankDbContext.Database.EnsureCreated();
|
||||
|
||||
@@ -71,6 +71,186 @@ internal class CreditProgramStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WithCurrencyRelations_Test()
|
||||
{
|
||||
// Создаем storekeeper и сохраняем его
|
||||
var uniqueId = Guid.NewGuid();
|
||||
var storekeeper = BankDbContext.InsertStorekeeperToDatabaseAndReturn(
|
||||
login: $"storekeeper_{uniqueId}",
|
||||
email: $"storekeeper_{uniqueId}@email.com",
|
||||
phone: $"+7-777-777-{uniqueId.ToString().Substring(0, 4)}"
|
||||
);
|
||||
BankDbContext.SaveChanges();
|
||||
|
||||
// Проверяем, что storekeeper действительно сохранен
|
||||
var savedStorekeeper = BankDbContext.Storekeepers.FirstOrDefault(s => s.Id == storekeeper.Id);
|
||||
Assert.That(savedStorekeeper, Is.Not.Null, "Storekeeper не был сохранен в базе данных");
|
||||
var storekeeperId = savedStorekeeper.Id;
|
||||
|
||||
// Создаем несколько валют
|
||||
var currency1Id = BankDbContext.InsertCurrencyToDatabaseAndReturn(storekeeperId: storekeeperId, abbreviation: "USD").Id;
|
||||
var currency2Id = BankDbContext.InsertCurrencyToDatabaseAndReturn(storekeeperId: storekeeperId, abbreviation: "EUR").Id;
|
||||
|
||||
// Создаем кредитную программу с двумя валютами
|
||||
var creditProgram = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
storekeeperId: storekeeperId,
|
||||
periodId: _periodId,
|
||||
creditProgramCurrency: [
|
||||
(currency1Id, Guid.NewGuid().ToString()),
|
||||
(currency2Id, Guid.NewGuid().ToString())
|
||||
]
|
||||
);
|
||||
|
||||
var list = _storageContract.GetList();
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(1));
|
||||
|
||||
var result = list.First();
|
||||
Assert.That(result.Currencies, Is.Not.Null);
|
||||
Assert.That(result.Currencies, Has.Count.EqualTo(2));
|
||||
Assert.That(result.Currencies.Select(c => c.CurrencyId), Does.Contain(currency1Id));
|
||||
Assert.That(result.Currencies.Select(c => c.CurrencyId), Does.Contain(currency2Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WithCurrencyRelations_Test()
|
||||
{
|
||||
// Создаем storekeeper и сохраняем его
|
||||
var uniqueId = Guid.NewGuid();
|
||||
var storekeeper = BankDbContext.InsertStorekeeperToDatabaseAndReturn(
|
||||
login: $"storekeeper_{uniqueId}",
|
||||
email: $"storekeeper_{uniqueId}@email.com",
|
||||
phone: $"+7-777-777-{uniqueId.ToString().Substring(0, 4)}"
|
||||
);
|
||||
BankDbContext.SaveChanges();
|
||||
|
||||
// Проверяем, что storekeeper действительно сохранен
|
||||
var savedStorekeeper = BankDbContext.Storekeepers.FirstOrDefault(s => s.Id == storekeeper.Id);
|
||||
Assert.That(savedStorekeeper, Is.Not.Null, "Storekeeper не был сохранен в базе данных");
|
||||
var storekeeperId = savedStorekeeper.Id;
|
||||
|
||||
// Создаем валюту
|
||||
var currencyId = BankDbContext.InsertCurrencyToDatabaseAndReturn(storekeeperId: storekeeperId).Id;
|
||||
|
||||
// Создаем модель с валютой
|
||||
var creditProgram = CreateModel(
|
||||
name: "unique name",
|
||||
periodId: _periodId,
|
||||
storekeeperId: storekeeperId,
|
||||
currency: [
|
||||
new CreditProgramCurrencyDataModel(Guid.NewGuid().ToString(), currencyId)
|
||||
]
|
||||
);
|
||||
|
||||
_storageContract.AddElement(creditProgram);
|
||||
|
||||
var result = BankDbContext.GetCreditProgramFromDatabase(creditProgram.Id);
|
||||
Assert.That(result, Is.Not.Null);
|
||||
Assert.That(result.CurrencyCreditPrograms, Is.Not.Null);
|
||||
Assert.That(result.CurrencyCreditPrograms, Has.Count.EqualTo(1));
|
||||
Assert.That(result.CurrencyCreditPrograms.First().CurrencyId, Is.EqualTo(currencyId));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WithCurrencyRelations_Test()
|
||||
{
|
||||
// Создаем storekeeper и сохраняем его
|
||||
var uniqueId = Guid.NewGuid();
|
||||
var storekeeper = BankDbContext.InsertStorekeeperToDatabaseAndReturn(
|
||||
login: $"storekeeper_{uniqueId}",
|
||||
email: $"storekeeper_{uniqueId}@email.com",
|
||||
phone: $"+7-777-777-{uniqueId.ToString().Substring(0, 4)}"
|
||||
);
|
||||
BankDbContext.SaveChanges();
|
||||
|
||||
// Проверяем, что storekeeper действительно сохранен
|
||||
var savedStorekeeper = BankDbContext.Storekeepers.FirstOrDefault(s => s.Id == storekeeper.Id);
|
||||
Assert.That(savedStorekeeper, Is.Not.Null, "Storekeeper не был сохранен в базе данных");
|
||||
var storekeeperId = savedStorekeeper.Id;
|
||||
|
||||
// Создаем две валюты
|
||||
var currency1Id = BankDbContext.InsertCurrencyToDatabaseAndReturn(storekeeperId: storekeeperId).Id;
|
||||
var currency2Id = BankDbContext.InsertCurrencyToDatabaseAndReturn(storekeeperId: storekeeperId).Id;
|
||||
|
||||
// Создаем кредитную программу с одной валютой
|
||||
var creditProgram = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
storekeeperId: storekeeperId,
|
||||
periodId: _periodId,
|
||||
creditProgramCurrency: [(currency1Id, Guid.NewGuid().ToString())]
|
||||
);
|
||||
|
||||
// Обновляем программу, добавляя вторую валюту
|
||||
var updatedModel = CreateModel(
|
||||
id: creditProgram.Id,
|
||||
name: creditProgram.Name,
|
||||
periodId: _periodId,
|
||||
storekeeperId: storekeeperId,
|
||||
currency: [
|
||||
new CreditProgramCurrencyDataModel(creditProgram.Id, currency1Id),
|
||||
new CreditProgramCurrencyDataModel(creditProgram.Id, currency2Id)
|
||||
]
|
||||
);
|
||||
|
||||
_storageContract.UpdElement(updatedModel);
|
||||
|
||||
var result = BankDbContext.GetCreditProgramFromDatabase(creditProgram.Id);
|
||||
Assert.That(result, Is.Not.Null);
|
||||
Assert.That(result.CurrencyCreditPrograms, Is.Not.Null);
|
||||
Assert.That(result.CurrencyCreditPrograms, Has.Count.EqualTo(2));
|
||||
Assert.That(result.CurrencyCreditPrograms.Select(c => c.CurrencyId), Does.Contain(currency1Id));
|
||||
Assert.That(result.CurrencyCreditPrograms.Select(c => c.CurrencyId), Does.Contain(currency2Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_RemoveCurrencyRelations_Test()
|
||||
{
|
||||
// Создаем storekeeper и сохраняем его
|
||||
var uniqueId = Guid.NewGuid();
|
||||
var storekeeper = BankDbContext.InsertStorekeeperToDatabaseAndReturn(
|
||||
login: $"storekeeper_{uniqueId}",
|
||||
email: $"storekeeper_{uniqueId}@email.com",
|
||||
phone: $"+7-777-777-{uniqueId.ToString().Substring(0, 4)}"
|
||||
);
|
||||
BankDbContext.SaveChanges();
|
||||
|
||||
// Проверяем, что storekeeper действительно сохранен
|
||||
var savedStorekeeper = BankDbContext.Storekeepers.FirstOrDefault(s => s.Id == storekeeper.Id);
|
||||
Assert.That(savedStorekeeper, Is.Not.Null, "Storekeeper не был сохранен в базе данных");
|
||||
var storekeeperId = savedStorekeeper.Id;
|
||||
|
||||
// Создаем две валюты
|
||||
var currency1Id = BankDbContext.InsertCurrencyToDatabaseAndReturn(storekeeperId: storekeeperId).Id;
|
||||
var currency2Id = BankDbContext.InsertCurrencyToDatabaseAndReturn(storekeeperId: storekeeperId).Id;
|
||||
|
||||
// Создаем кредитную программу с двумя валютами
|
||||
var creditProgram = BankDbContext.InsertCreditProgramToDatabaseAndReturn(
|
||||
storekeeperId: storekeeperId,
|
||||
periodId: _periodId,
|
||||
creditProgramCurrency: [
|
||||
(currency1Id, Guid.NewGuid().ToString()),
|
||||
(currency2Id, Guid.NewGuid().ToString())
|
||||
]
|
||||
);
|
||||
|
||||
// Обновляем программу, оставляя только одну валюту
|
||||
var updatedModel = CreateModel(
|
||||
id: creditProgram.Id,
|
||||
name: creditProgram.Name,
|
||||
periodId: _periodId,
|
||||
storekeeperId: storekeeperId,
|
||||
currency: [new CreditProgramCurrencyDataModel(creditProgram.Id, currency1Id)]
|
||||
);
|
||||
|
||||
_storageContract.UpdElement(updatedModel);
|
||||
|
||||
var result = BankDbContext.GetCreditProgramFromDatabase(creditProgram.Id);
|
||||
Assert.That(result, Is.Not.Null);
|
||||
Assert.That(result.CurrencyCreditPrograms, Is.Not.Null);
|
||||
Assert.That(result.CurrencyCreditPrograms, Has.Count.EqualTo(1));
|
||||
Assert.That(result.CurrencyCreditPrograms.First().CurrencyId, Is.EqualTo(currency1Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
|
||||
@@ -18,7 +18,12 @@ internal class DepositStorageContractTests : BaseStorageContractTest
|
||||
public void SetUp()
|
||||
{
|
||||
_storageContract = new DepositStorageContract(BankDbContext);
|
||||
_clerkId = BankDbContext.InsertClerkToDatabaseAndReturn().Id;
|
||||
var uniqueId = Guid.NewGuid();
|
||||
_clerkId = BankDbContext.InsertClerkToDatabaseAndReturn(
|
||||
login: $"clerk_{uniqueId}",
|
||||
email: $"clerk_{uniqueId}@email.com",
|
||||
phone: $"+7-777-777-{uniqueId.ToString().Substring(0, 4)}"
|
||||
).Id;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
@@ -93,6 +98,131 @@ internal class DepositStorageContractTests : BaseStorageContractTest
|
||||
);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_ByClerkId_Test()
|
||||
{
|
||||
var uniqueId1 = Guid.NewGuid();
|
||||
var uniqueId2 = Guid.NewGuid();
|
||||
var clerkId1 = BankDbContext.InsertClerkToDatabaseAndReturn(
|
||||
email: $"clerk1_{uniqueId1}@email.com",
|
||||
login: $"clerk1_{uniqueId1}",
|
||||
phone: $"+7-777-777-{uniqueId1.ToString().Substring(0, 4)}"
|
||||
).Id;
|
||||
var clerkId2 = BankDbContext.InsertClerkToDatabaseAndReturn(
|
||||
email: $"clerk2_{uniqueId2}@email.com",
|
||||
login: $"clerk2_{uniqueId2}",
|
||||
phone: $"+7-777-777-{uniqueId2.ToString().Substring(0, 4)}"
|
||||
).Id;
|
||||
|
||||
BankDbContext.InsertDepositToDatabaseAndReturn(clerkId: clerkId1);
|
||||
BankDbContext.InsertDepositToDatabaseAndReturn(clerkId: clerkId1);
|
||||
BankDbContext.InsertDepositToDatabaseAndReturn(clerkId: clerkId2);
|
||||
|
||||
var list = _storageContract.GetList(clerkId1);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(2));
|
||||
Assert.That(list.All(x => x.ClerkId == clerkId1), Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByInterestRate_WhenHaveRecord_Test()
|
||||
{
|
||||
var deposit = BankDbContext.InsertDepositToDatabaseAndReturn(clerkId: _clerkId, interestRate: 15.5f);
|
||||
var result = _storageContract.GetElementByInterestRate(15.5f);
|
||||
Assert.That(result, Is.Not.Null);
|
||||
AssertElement(result, deposit);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementByInterestRate_WhenNoRecord_Test()
|
||||
{
|
||||
var result = _storageContract.GetElementByInterestRate(15.5f);
|
||||
Assert.That(result, Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenHaveRecordWithSameInterestRate_Test()
|
||||
{
|
||||
// Создаем первый депозит с определенной процентной ставкой
|
||||
var deposit1 = CreateModel(clerkId: _clerkId, interestRate: 10.5f);
|
||||
_storageContract.AddElement(deposit1);
|
||||
|
||||
// Создаем второй депозит с такой же процентной ставкой
|
||||
var deposit2 = CreateModel(clerkId: _clerkId, interestRate: 10.5f);
|
||||
|
||||
// Проверяем, что можно добавить депозит с такой же процентной ставкой
|
||||
_storageContract.AddElement(deposit2);
|
||||
var result = BankDbContext.GetDepositFromDatabase(deposit2.Id);
|
||||
Assert.That(result, Is.Not.Null);
|
||||
AssertElement(result, deposit2);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_UpdElement_WithCurrencies_Test()
|
||||
{
|
||||
// Создаем валюты
|
||||
var storekeeperId = BankDbContext.InsertStorekeeperToDatabaseAndReturn(
|
||||
login: $"storekeeper_{Guid.NewGuid()}",
|
||||
email: $"storekeeper_{Guid.NewGuid()}@email.com",
|
||||
phone: $"+7-777-777-{Guid.NewGuid().ToString().Substring(0, 4)}"
|
||||
).Id;
|
||||
|
||||
var currency1 = BankDbContext.InsertCurrencyToDatabaseAndReturn(
|
||||
abbreviation: "USD",
|
||||
storekeeperId: storekeeperId
|
||||
);
|
||||
var currency2 = BankDbContext.InsertCurrencyToDatabaseAndReturn(
|
||||
abbreviation: "EUR",
|
||||
storekeeperId: storekeeperId
|
||||
);
|
||||
|
||||
// Создаем депозит
|
||||
var deposit = BankDbContext.InsertDepositToDatabaseAndReturn(clerkId: _clerkId);
|
||||
|
||||
// Обновляем депозит с валютами
|
||||
var updatedDeposit = CreateModel(
|
||||
id: deposit.Id,
|
||||
clerkId: _clerkId,
|
||||
deposits: new List<DepositCurrencyDataModel>
|
||||
{
|
||||
new(deposit.Id, currency1.Id),
|
||||
new(deposit.Id, currency2.Id)
|
||||
}
|
||||
);
|
||||
|
||||
_storageContract.UpdElement(updatedDeposit);
|
||||
var result = BankDbContext.GetDepositFromDatabase(deposit.Id);
|
||||
Assert.That(result.DepositCurrencies, Has.Count.EqualTo(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Try_GetListAsync_ByDateRange_Test()
|
||||
{
|
||||
var startDate = DateTime.Now.AddDays(-1);
|
||||
var endDate = DateTime.Now.AddDays(1);
|
||||
|
||||
var deposit = BankDbContext.InsertDepositToDatabaseAndReturn(clerkId: _clerkId);
|
||||
|
||||
var list = await _storageContract.GetListAsync(startDate, endDate, CancellationToken.None);
|
||||
Assert.That(list, Is.Not.Null);
|
||||
Assert.That(list, Has.Count.EqualTo(1));
|
||||
AssertElement(list.First(), deposit);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_AddElement_WhenDatabaseError_Test()
|
||||
{
|
||||
var deposit = CreateModel(clerkId: _clerkId);
|
||||
// Симулируем ошибку базы данных, пытаясь добавить депозит с несуществующим ID клерка
|
||||
var nonExistentClerkId = Guid.NewGuid().ToString();
|
||||
var depositWithInvalidClerk = CreateModel(clerkId: nonExistentClerkId);
|
||||
|
||||
Assert.That(
|
||||
() => _storageContract.AddElement(depositWithInvalidClerk),
|
||||
Throws.TypeOf<StorageException>()
|
||||
);
|
||||
}
|
||||
|
||||
private static DepositDataModel CreateModel(
|
||||
string? id = null,
|
||||
float interestRate = 10,
|
||||
|
||||
@@ -20,7 +20,12 @@ internal class ReplenishmentStorageContractTests : BaseStorageContractTest
|
||||
public void SetUp()
|
||||
{
|
||||
_storageContract = new ReplenishmentStorageContract(BankDbContext);
|
||||
_clerkId = BankDbContext.InsertClerkToDatabaseAndReturn().Id;
|
||||
var uniqueId = Guid.NewGuid();
|
||||
_clerkId = BankDbContext.InsertClerkToDatabaseAndReturn(
|
||||
login: $"clerk_{uniqueId}",
|
||||
email: $"clerk_{uniqueId}@email.com",
|
||||
phone: $"+7-777-777-{uniqueId.ToString().Substring(0, 4)}"
|
||||
).Id;
|
||||
_depositId = BankDbContext.InsertDepositToDatabaseAndReturn(clerkId: _clerkId).Id;
|
||||
}
|
||||
|
||||
@@ -62,6 +67,120 @@ internal class ReplenishmentStorageContractTests : BaseStorageContractTest
|
||||
Assert.That(list, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WithDateFilters_Test()
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
var pastDate = now.AddDays(-1);
|
||||
var futureDate = now.AddDays(1);
|
||||
|
||||
// Insert replenishments with different dates
|
||||
var pastReplenishment = BankDbContext.InsertReplenishmentToDatabaseAndReturn(
|
||||
clerkId: _clerkId,
|
||||
depositId: _depositId,
|
||||
date: pastDate
|
||||
);
|
||||
var currentReplenishment = BankDbContext.InsertReplenishmentToDatabaseAndReturn(
|
||||
clerkId: _clerkId,
|
||||
depositId: _depositId,
|
||||
date: now
|
||||
);
|
||||
var futureReplenishment = BankDbContext.InsertReplenishmentToDatabaseAndReturn(
|
||||
clerkId: _clerkId,
|
||||
depositId: _depositId,
|
||||
date: futureDate
|
||||
);
|
||||
|
||||
// Test date range filter
|
||||
var filteredList = _storageContract.GetList(fromDate: pastDate, toDate: now);
|
||||
Assert.That(filteredList, Has.Count.EqualTo(2));
|
||||
Assert.That(filteredList.Select(x => x.Id), Does.Contain(pastReplenishment.Id));
|
||||
Assert.That(filteredList.Select(x => x.Id), Does.Contain(currentReplenishment.Id));
|
||||
Assert.That(filteredList.Select(x => x.Id), Does.Not.Contain(futureReplenishment.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WithClerkIdFilter_Test()
|
||||
{
|
||||
var otherClerkId = BankDbContext.InsertClerkToDatabaseAndReturn(
|
||||
login: $"clerk_other",
|
||||
email: "clerk_other@email.com",
|
||||
phone: "+7-777-777-0000"
|
||||
).Id;
|
||||
|
||||
// Insert replenishments for different clerks
|
||||
var replenishment1 = BankDbContext.InsertReplenishmentToDatabaseAndReturn(
|
||||
clerkId: _clerkId,
|
||||
depositId: _depositId
|
||||
);
|
||||
var replenishment2 = BankDbContext.InsertReplenishmentToDatabaseAndReturn(
|
||||
clerkId: otherClerkId,
|
||||
depositId: _depositId
|
||||
);
|
||||
|
||||
var filteredList = _storageContract.GetList(clerkId: _clerkId);
|
||||
Assert.That(filteredList, Has.Count.EqualTo(1));
|
||||
Assert.That(filteredList.First().Id, Is.EqualTo(replenishment1.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WithDepositIdFilter_Test()
|
||||
{
|
||||
var otherDepositId = BankDbContext.InsertDepositToDatabaseAndReturn(clerkId: _clerkId).Id;
|
||||
|
||||
// Insert replenishments for different deposits
|
||||
var replenishment1 = BankDbContext.InsertReplenishmentToDatabaseAndReturn(
|
||||
clerkId: _clerkId,
|
||||
depositId: _depositId
|
||||
);
|
||||
var replenishment2 = BankDbContext.InsertReplenishmentToDatabaseAndReturn(
|
||||
clerkId: _clerkId,
|
||||
depositId: otherDepositId
|
||||
);
|
||||
|
||||
var filteredList = _storageContract.GetList(depositId: _depositId);
|
||||
Assert.That(filteredList, Has.Count.EqualTo(1));
|
||||
Assert.That(filteredList.First().Id, Is.EqualTo(replenishment1.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetList_WithCombinedFilters_Test()
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
var otherClerkId = BankDbContext.InsertClerkToDatabaseAndReturn(
|
||||
login: $"clerk_other",
|
||||
email: "clerk_other@email.com",
|
||||
phone: "+7-777-777-0000"
|
||||
).Id;
|
||||
var otherDepositId = BankDbContext.InsertDepositToDatabaseAndReturn(clerkId: _clerkId).Id;
|
||||
|
||||
// Insert replenishments with different combinations
|
||||
var replenishment1 = BankDbContext.InsertReplenishmentToDatabaseAndReturn(
|
||||
clerkId: _clerkId,
|
||||
depositId: _depositId,
|
||||
date: now
|
||||
);
|
||||
var replenishment2 = BankDbContext.InsertReplenishmentToDatabaseAndReturn(
|
||||
clerkId: otherClerkId,
|
||||
depositId: _depositId,
|
||||
date: now
|
||||
);
|
||||
var replenishment3 = BankDbContext.InsertReplenishmentToDatabaseAndReturn(
|
||||
clerkId: _clerkId,
|
||||
depositId: otherDepositId,
|
||||
date: now
|
||||
);
|
||||
|
||||
var filteredList = _storageContract.GetList(
|
||||
fromDate: now,
|
||||
toDate: now,
|
||||
clerkId: _clerkId,
|
||||
depositId: _depositId
|
||||
);
|
||||
Assert.That(filteredList, Has.Count.EqualTo(1));
|
||||
Assert.That(filteredList.First().Id, Is.EqualTo(replenishment1.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Try_GetElementById_WhenHaveRecord_Test()
|
||||
{
|
||||
|
||||
@@ -72,7 +72,7 @@ internal class ClerkControllerTests : BaseWebApiControllerTest
|
||||
// Arrange
|
||||
var model = CreateModel();
|
||||
// Act
|
||||
var response = await HttpClient.PostAsJsonAsync("/api/clerks", model);
|
||||
var response = await HttpClient.PostAsJsonAsync("/api/clerks/register", model);
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
AssertElement(BankDbContext.GetClerkFromDatabase(model.Id!), model);
|
||||
@@ -85,7 +85,7 @@ internal class ClerkControllerTests : BaseWebApiControllerTest
|
||||
var model = CreateModel();
|
||||
BankDbContext.InsertClerkToDatabaseAndReturn(id: model.Id);
|
||||
// Act
|
||||
var response = await HttpClient.PostAsJsonAsync("/api/clerks", model);
|
||||
var response = await HttpClient.PostAsJsonAsync("/api/clerks/register", model);
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
@@ -94,7 +94,7 @@ internal class ClerkControllerTests : BaseWebApiControllerTest
|
||||
public async Task Post_WhenSendEmptyData_ShouldBadRequest_Test()
|
||||
{
|
||||
// Act
|
||||
var response = await HttpClient.PostAsync("/api/clerks", MakeContent(string.Empty));
|
||||
var response = await HttpClient.PostAsync("/api/clerks/register", MakeContent(string.Empty));
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ internal class ClientControllerTests : BaseWebApiControllerTest
|
||||
var client1 = BankDbContext.InsertClientToDatabaseAndReturn(name: "Иван", surname: "Иванов", clerkId: _clerk.Id);
|
||||
var client2 = BankDbContext.InsertClientToDatabaseAndReturn(name: "Петр", surname: "Петров", clerkId: _clerk.Id);
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync("/api/clients/getrecords");
|
||||
var response = await HttpClient.GetAsync("/api/clients/getallrecords");
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ClientViewModel>>(response);
|
||||
@@ -48,7 +48,7 @@ internal class ClientControllerTests : BaseWebApiControllerTest
|
||||
public async Task GetList_WhenNoRecords_ShouldSuccess_Test()
|
||||
{
|
||||
// Act
|
||||
var response = await HttpClient.GetAsync("/api/clients/getrecords");
|
||||
var response = await HttpClient.GetAsync("/api/clients/getallrecords");
|
||||
// Assert
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var data = await GetModelFromResponseAsync<List<ClientViewModel>>(response);
|
||||
@@ -81,7 +81,7 @@ internal class ClientControllerTests : BaseWebApiControllerTest
|
||||
public async Task Post_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var model = CreateModel();
|
||||
var model = CreateModel(clerkId: _clerk.Id);
|
||||
// Act
|
||||
var response = await HttpClient.PostAsJsonAsync("/api/clients/register", model);
|
||||
// Assert
|
||||
@@ -114,7 +114,7 @@ internal class ClientControllerTests : BaseWebApiControllerTest
|
||||
public async Task Put_ShouldSuccess_Test()
|
||||
{
|
||||
// Arrange
|
||||
var model = CreateModel();
|
||||
var model = CreateModel(name: "slava", surname: "fomichev", balance: 1_000_000, clerkId: _clerk.Id);
|
||||
BankDbContext.InsertClientToDatabaseAndReturn(id: model.Id, clerkId: _clerk.Id);
|
||||
// Act
|
||||
var response = await HttpClient.PutAsJsonAsync("/api/clients/changeinfo", model);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using AutoMapper;
|
||||
using BankBusinessLogic.Implementations;
|
||||
using BankContracts.AdapterContracts;
|
||||
using BankContracts.AdapterContracts.OperationResponses;
|
||||
using BankContracts.BindingModels;
|
||||
@@ -6,6 +7,7 @@ using BankContracts.BusinessLogicContracts;
|
||||
using BankContracts.DataModels;
|
||||
using BankContracts.Exceptions;
|
||||
using BankContracts.ViewModels;
|
||||
using BankWebApi.Infrastructure;
|
||||
|
||||
namespace BankWebApi.Adapters;
|
||||
|
||||
@@ -13,11 +15,13 @@ public class ClerkAdapter : IClerkAdapter
|
||||
{
|
||||
private readonly IClerkBusinessLogicContract _clerkBusinessLogicContract;
|
||||
|
||||
private readonly IJwtProvider _jwtProvider;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public ClerkAdapter(IClerkBusinessLogicContract clerkBusinessLogicContract, ILogger logger)
|
||||
public ClerkAdapter(IClerkBusinessLogicContract clerkBusinessLogicContract, ILogger logger, IJwtProvider jwtProvider)
|
||||
{
|
||||
_clerkBusinessLogicContract = clerkBusinessLogicContract;
|
||||
_logger = logger;
|
||||
@@ -27,6 +31,7 @@ public class ClerkAdapter : IClerkAdapter
|
||||
cfg.CreateMap<ClerkDataModel, ClerkViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
_jwtProvider = jwtProvider;
|
||||
}
|
||||
|
||||
public ClerkOperationResponse GetList()
|
||||
@@ -170,4 +175,30 @@ public class ClerkAdapter : IClerkAdapter
|
||||
return ClerkOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public ClerkOperationResponse Login(LoginBindingModel clerkModel, out string token)
|
||||
{
|
||||
token = string.Empty;
|
||||
try
|
||||
{
|
||||
var clerk = _clerkBusinessLogicContract.GetClerkByData(clerkModel.Login);
|
||||
|
||||
|
||||
var result = clerkModel.Password == clerk.Password;
|
||||
|
||||
if (!result)
|
||||
{
|
||||
return ClerkOperationResponse.Unauthorized("Password are incorrect");
|
||||
}
|
||||
|
||||
token = _jwtProvider.GenerateToken(clerk);
|
||||
|
||||
return ClerkOperationResponse.OK(_mapper.Map<ClerkViewModel>(clerk));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception in Login");
|
||||
return ClerkOperationResponse.InternalServerError($"Exception in Login {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,13 +24,25 @@ public class ClientAdapter : IClientAdapter
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
// Mapping for Client
|
||||
cfg.CreateMap<ClientBindingModel, ClientDataModel>();
|
||||
cfg.CreateMap<DepositDataModel, DepositViewModel>();
|
||||
cfg.CreateMap<ClientDataModel, ClientViewModel>()
|
||||
.ForMember(dest => dest.DepositClients, opt => opt.MapFrom(src => src.DepositClients))
|
||||
.ForMember(dest => dest.CreditProgramClients, opt => opt.MapFrom(src => src.CreditProgramClients));
|
||||
|
||||
// Mapping for Deposit
|
||||
cfg.CreateMap<DepositDataModel, DepositViewModel>()
|
||||
.ForMember(dest => dest.DepositCurrencies, opt => opt.MapFrom(src => src.Currencies)); // Adjust if Currencies is meant to map to DepositClients
|
||||
|
||||
// Mapping for ClientCreditProgram
|
||||
cfg.CreateMap<ClientCreditProgramBindingModel, ClientCreditProgramDataModel>();
|
||||
cfg.CreateMap<ClientCreditProgramDataModel, ClientCreditProgramViewModel>();
|
||||
|
||||
// Mapping for DepositClient
|
||||
cfg.CreateMap<DepositClientBindingModel, DepositClientDataModel>();
|
||||
cfg.CreateMap<DepositClientDataModel, DepositClientViewModel>();
|
||||
});
|
||||
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ public class CreditProgramAdapter : ICreditProgramAdapter
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CreditProgramOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
$"Error while working with data storage:{ex.InnerException?.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -86,7 +86,7 @@ public class CreditProgramAdapter : ICreditProgramAdapter
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CreditProgramOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
$"Error while working with data storage: {ex.InnerException?.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -122,7 +122,7 @@ public class CreditProgramAdapter : ICreditProgramAdapter
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CreditProgramOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
$"Error while working with data storage: {ex.InnerException?.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -164,7 +164,7 @@ public class CreditProgramAdapter : ICreditProgramAdapter
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CreditProgramOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
$"Error while working with data storage: {ex.InnerException?.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -195,7 +195,7 @@ public class CreditProgramAdapter : ICreditProgramAdapter
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CreditProgramOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
$"Error while working with data storage:{ex.InnerException?.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -226,7 +226,7 @@ public class CreditProgramAdapter : ICreditProgramAdapter
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return CreditProgramOperationResponse.InternalServerError(
|
||||
$"Error while working with data storage:{ex.InnerException!.Message}"
|
||||
$"Error while working with data storage:{ex.InnerException?.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -27,6 +27,8 @@ public class DepositAdapter : IDepositAdapter
|
||||
cfg.CreateMap<DepositDataModel, DepositViewModel>();
|
||||
cfg.CreateMap<DepositCurrencyBindingModel, DepositCurrencyDataModel>();
|
||||
cfg.CreateMap<DepositCurrencyDataModel, DepositCurrencyViewModel>();
|
||||
cfg.CreateMap<DepositClientBindingModel, DepositClientDataModel>()
|
||||
.ConstructUsing(src => new DepositClientDataModel(src.DepositId, src.ClientId));
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
}
|
||||
@@ -117,7 +119,7 @@ public class DepositAdapter : IDepositAdapter
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return DepositOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
$"Error while working with data storage: {ex.InnerException?.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -21,9 +21,17 @@ public class PeriodAdapter : IPeriodAdapter
|
||||
{
|
||||
_periodBusinessLogicContract = periodBusinessLogicContract;
|
||||
_logger = logger;
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
var config = new MapperConfiguration(cfg =>
|
||||
{
|
||||
cfg.CreateMap<PeriodBindingModel, PeriodDataModel>();
|
||||
cfg.CreateMap<PeriodBindingModel, PeriodDataModel>()
|
||||
.ConstructUsing(src => new PeriodDataModel(
|
||||
src.Id,
|
||||
src.StartTime,
|
||||
src.EndTime,
|
||||
src.StorekeeperId
|
||||
));
|
||||
|
||||
// Маппинг PeriodDataModel -> PeriodViewModel
|
||||
cfg.CreateMap<PeriodDataModel, PeriodViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
|
||||
@@ -36,16 +36,12 @@ public class ReportAdapter : IReportAdapter
|
||||
return ReportOperationResponse.OK(stream, fileName);
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> CreateDocumentClientsByCreditProgramAsync(CancellationToken ct)
|
||||
public async Task<ReportOperationResponse> CreateDocumentClientsByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SendStream(await _reportContract.CreateDocumentClientsByCreditProgramAsync(ct), "clientbycreditprogram.docx");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
return SendStream(await _reportContract.CreateDocumentClientsByCreditProgramAsync(creditProgramIds, ct),
|
||||
"clientsbycreditprogram.docx");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
@@ -60,21 +56,16 @@ public class ReportAdapter : IReportAdapter
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
return ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> CreateExcelDocumentClientsByCreditProgramAsync(CancellationToken ct)
|
||||
public async Task<ReportOperationResponse> CreateExcelDocumentClientsByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SendStream(await _reportContract.CreateExcelDocumentClientsByCreditProgramAsync(ct), "clientbycreditprogram.xlsx");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
return SendStream(await _reportContract.CreateExcelDocumentClientsByCreditProgramAsync(creditProgramIds, ct),
|
||||
"clientsbycreditprogram.xlsx");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
@@ -89,8 +80,7 @@ public class ReportAdapter : IReportAdapter
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
return ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,11 +144,11 @@ public class ReportAdapter : IReportAdapter
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> CreateDocumentDepositByCreditProgramAsync(CancellationToken ct)
|
||||
public async Task<ReportOperationResponse> CreateDocumentDepositByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SendStream(await _reportContract.CreateDocumentDepositByCreditProgramAsync(ct), "depositbycreditprogram.docx");
|
||||
return SendStream(await _reportContract.CreateDocumentDepositByCreditProgramAsync(creditProgramIds, ct), "depositbycreditprogram.docx");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
@@ -187,11 +177,11 @@ public class ReportAdapter : IReportAdapter
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> CreateExcelDocumentDepositByCreditProgramAsync(CancellationToken ct)
|
||||
public async Task<ReportOperationResponse> CreateExcelDocumentDepositByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return SendStream(await _reportContract.CreateExcelDocumentDepositByCreditProgramAsync(ct), "depositbycreditprogram.xlsx");
|
||||
return SendStream(await _reportContract.CreateExcelDocumentDepositByCreditProgramAsync(creditProgramIds, ct), "depositbycreditprogram.xlsx");
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
@@ -216,21 +206,16 @@ public class ReportAdapter : IReportAdapter
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
return ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> GetDataClientsByCreditProgramAsync(CancellationToken ct)
|
||||
public async Task<ReportOperationResponse> GetDataClientsByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReportOperationResponse.OK([.. (await _reportContract.GetDataClientsByCreditProgramAsync(ct)).Select(x => _mapper.Map<ClientsByCreditProgramViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
_logger.LogError(ex, "IncorrectDatesException");
|
||||
return ReportOperationResponse.BadRequest($"Incorrect dates: {ex.Message}");
|
||||
return ReportOperationResponse.OK((await _reportContract.GetDataClientsByCreditProgramAsync(creditProgramIds, ct))
|
||||
.Select(x => _mapper.Map<ClientsByCreditProgramViewModel>(x)).ToList());
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
@@ -245,8 +230,7 @@ public class ReportAdapter : IReportAdapter
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
return ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,11 +294,11 @@ public class ReportAdapter : IReportAdapter
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<ReportOperationResponse> GetDataDepositByCreditProgramAsync(CancellationToken ct)
|
||||
public async Task<ReportOperationResponse> GetDataDepositByCreditProgramAsync(List<string>? creditProgramIds, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ReportOperationResponse.OK([.. (await _reportContract.GetDataDepositByCreditProgramAsync(ct)).Select(x => _mapper.Map<DepositByCreditProgramViewModel>(x))]);
|
||||
return ReportOperationResponse.OK([.. (await _reportContract.GetDataDepositByCreditProgramAsync(creditProgramIds, ct)).Select(x => _mapper.Map<DepositByCreditProgramViewModel>(x))]);
|
||||
}
|
||||
catch (IncorrectDatesException ex)
|
||||
{
|
||||
@@ -334,8 +318,7 @@ public class ReportAdapter : IReportAdapter
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception");
|
||||
return
|
||||
ReportOperationResponse.InternalServerError(ex.Message);
|
||||
return ReportOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ using BankContracts.BusinessLogicContracts;
|
||||
using BankContracts.DataModels;
|
||||
using BankContracts.Exceptions;
|
||||
using BankContracts.ViewModels;
|
||||
using BankWebApi.Infrastructure;
|
||||
using System.Buffers;
|
||||
|
||||
namespace BankWebApi.Adapters;
|
||||
|
||||
@@ -14,11 +16,13 @@ public class StorekeeperAdapter : IStorekeeperAdapter
|
||||
{
|
||||
private readonly IStorekeeperBusinessLogicContract _storekeeperBusinessLogicContract;
|
||||
|
||||
private readonly IJwtProvider _jwtProvider;
|
||||
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly Mapper _mapper;
|
||||
|
||||
public StorekeeperAdapter(IStorekeeperBusinessLogicContract storekeeperBusinessLogicContract, ILogger logger)
|
||||
public StorekeeperAdapter(IStorekeeperBusinessLogicContract storekeeperBusinessLogicContract, IJwtProvider jwtProvider, ILogger logger)
|
||||
{
|
||||
_storekeeperBusinessLogicContract = storekeeperBusinessLogicContract;
|
||||
_logger = logger;
|
||||
@@ -28,6 +32,7 @@ public class StorekeeperAdapter : IStorekeeperAdapter
|
||||
cfg.CreateMap<StorekeeperDataModel, StorekeeperViewModel>();
|
||||
});
|
||||
_mapper = new Mapper(config);
|
||||
_jwtProvider = jwtProvider;
|
||||
}
|
||||
|
||||
public StorekeeperOperationResponse GetList()
|
||||
@@ -119,7 +124,7 @@ public class StorekeeperAdapter : IStorekeeperAdapter
|
||||
{
|
||||
_logger.LogError(ex, "StorageException");
|
||||
return StorekeeperOperationResponse.BadRequest(
|
||||
$"Error while working with data storage: {ex.InnerException!.Message}"
|
||||
$"Error while working with data storage: {ex.InnerException?.Message}"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -170,5 +175,31 @@ public class StorekeeperAdapter : IStorekeeperAdapter
|
||||
_logger.LogError(ex, "Exception");
|
||||
return StorekeeperOperationResponse.InternalServerError(ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public StorekeeperOperationResponse Login(LoginBindingModel storekeeperAuth, out string token)
|
||||
{
|
||||
token = string.Empty;
|
||||
try
|
||||
{
|
||||
var storekeeper = _storekeeperBusinessLogicContract.GetStorekeeperByData(storekeeperAuth.Login);
|
||||
|
||||
|
||||
var result = storekeeperAuth.Password == storekeeper.Password;
|
||||
|
||||
if (!result)
|
||||
{
|
||||
return StorekeeperOperationResponse.Unauthorized("Password are incorrect");
|
||||
}
|
||||
|
||||
token = _jwtProvider.GenerateToken(storekeeper);
|
||||
|
||||
return StorekeeperOperationResponse.OK(_mapper.Map<StorekeeperViewModel>(storekeeper));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Exception in Login");
|
||||
return StorekeeperOperationResponse.InternalServerError($"Exception in Login {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ namespace BankWebApi;
|
||||
/// </summary>
|
||||
public class AuthOptions
|
||||
{
|
||||
public const string CookieName = "bank";
|
||||
public const string ISSUER = "Bank_AuthServer"; // издатель токена
|
||||
public const string AUDIENCE = "Bank_AuthClient"; // потребитель токена
|
||||
const string KEY = "banksuperpupersecret_secretsecretsecretkey!"; // ключ для шифрации
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.4" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.1" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.4" />
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
using BankContracts.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace BankWebApi.Controllers;
|
||||
|
||||
@@ -39,7 +40,8 @@ public class ClerksController(IClerkAdapter adapter) : ControllerBase
|
||||
/// </summary>
|
||||
/// <param name="model">модель от пользователя</param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
[HttpPost("register")]
|
||||
[AllowAnonymous]
|
||||
public IActionResult Register([FromBody] ClerkBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterClerk(model).GetResponse(Request, Response);
|
||||
@@ -55,4 +57,58 @@ public class ClerksController(IClerkAdapter adapter) : ControllerBase
|
||||
{
|
||||
return _adapter.ChangeClerkInfo(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// вход для клерка
|
||||
/// </summary>
|
||||
/// <param name="model">модель с логином и паролем</param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("login")]
|
||||
[AllowAnonymous]
|
||||
public IActionResult Login([FromBody] LoginBindingModel model)
|
||||
{
|
||||
var res = _adapter.Login(model, out string token);
|
||||
if (string.IsNullOrEmpty(token))
|
||||
{
|
||||
return res.GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
Response.Cookies.Append(AuthOptions.CookieName, token, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
SameSite = SameSiteMode.None,
|
||||
Secure = true,
|
||||
Expires = DateTime.UtcNow.AddDays(2)
|
||||
});
|
||||
|
||||
return res.GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получение данных текущего клерка
|
||||
/// </summary>
|
||||
/// <returns>Данные кладовщика</returns>
|
||||
[HttpGet("me")]
|
||||
public IActionResult GetCurrentUser()
|
||||
{
|
||||
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
if (string.IsNullOrEmpty(userId))
|
||||
{
|
||||
return Unauthorized();
|
||||
}
|
||||
|
||||
var response = _adapter.GetElement(userId);
|
||||
return response.GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Выход клерка
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpPost("logout")]
|
||||
public IActionResult Logout()
|
||||
{
|
||||
Response.Cookies.Delete(AuthOptions.CookieName);
|
||||
return Ok();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using BankContracts.AdapterContracts;
|
||||
using BankContracts.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace BankWebApi.Controllers;
|
||||
@@ -10,7 +9,7 @@ namespace BankWebApi.Controllers;
|
||||
[Route("api/[controller]/[action]")]
|
||||
[ApiController]
|
||||
[Produces("application/json")]
|
||||
public class PeriodController(IPeriodAdapter adapter) : ControllerBase
|
||||
public class PeriodsController(IPeriodAdapter adapter) : ControllerBase
|
||||
{
|
||||
private readonly IPeriodAdapter _adapter = adapter;
|
||||
|
||||
@@ -18,32 +18,51 @@ public class ReportController : ControllerBase
|
||||
_adapter = adapter;
|
||||
_emailService = EmailService.CreateYandexService();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получение данных Клиента по Кредитным программам
|
||||
/// </summary>
|
||||
/// <param name="creditProgramIds"></param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
[Consumes("application/json")]
|
||||
public async Task<IActionResult> GetClientByCreditProgram(CancellationToken ct)
|
||||
public async Task<IActionResult> GetClientByCreditProgram([FromQuery] List<string>? creditProgramIds, CancellationToken ct)
|
||||
{
|
||||
return (await
|
||||
_adapter.GetDataClientsByCreditProgramAsync(ct)).GetResponse(Request, Response);
|
||||
return (await _adapter.GetDataClientsByCreditProgramAsync(creditProgramIds, ct)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Отчет word Клиента по Кредитным программам
|
||||
/// </summary>
|
||||
/// <param name="creditProgramIds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
[Consumes("application/octet-stream")]
|
||||
public async Task<IActionResult> LoadClientsByCreditProgram(CancellationToken cancellationToken)
|
||||
public async Task<IActionResult> LoadClientsByCreditProgram([FromQuery] List<string>? creditProgramIds, CancellationToken cancellationToken)
|
||||
{
|
||||
return (await
|
||||
_adapter.CreateDocumentClientsByCreditProgramAsync(cancellationToken)).GetResponse(Request, Response);
|
||||
return (await _adapter.CreateDocumentClientsByCreditProgramAsync(creditProgramIds, cancellationToken)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Отчет excel Клиента по Кредитным программам
|
||||
/// </summary>
|
||||
/// <param name="creditProgramIds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
[Consumes("application/octet-stream")]
|
||||
public async Task<IActionResult> LoadExcelClientByCreditProgram(CancellationToken cancellationToken)
|
||||
public async Task<IActionResult> LoadExcelClientByCreditProgram([FromQuery] List<string>? creditProgramIds, CancellationToken cancellationToken)
|
||||
{
|
||||
return (await
|
||||
_adapter.CreateExcelDocumentClientsByCreditProgramAsync(cancellationToken)).GetResponse(Request, Response);
|
||||
return (await _adapter.CreateExcelDocumentClientsByCreditProgramAsync(creditProgramIds, cancellationToken)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получение данных Клиента по Вкладам
|
||||
/// </summary>
|
||||
/// <param name="fromDate"></param>
|
||||
/// <param name="toDate"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
[Consumes("application/json")]
|
||||
public async Task<IActionResult> GetClientByDeposit(DateTime fromDate, DateTime toDate, CancellationToken cancellationToken)
|
||||
@@ -51,6 +70,13 @@ public class ReportController : ControllerBase
|
||||
return (await _adapter.GetDataClientsByDepositAsync(fromDate, toDate, cancellationToken)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Отчет word Клиента по Вкладам
|
||||
/// </summary>
|
||||
/// <param name="fromDate"></param>
|
||||
/// <param name="toDate"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
[Consumes("application/octet-stream")]
|
||||
public async Task<IActionResult> LoadClientsByDeposit(DateTime fromDate, DateTime toDate, CancellationToken cancellationToken)
|
||||
@@ -59,27 +85,52 @@ public class ReportController : ControllerBase
|
||||
toDate, cancellationToken)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получение данных Вклада по Кредитным программам
|
||||
/// </summary>
|
||||
/// <param name="creditProgramIds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
[Consumes("application/json")]
|
||||
public async Task<IActionResult> GetDepositByCreditProgram(CancellationToken cancellationToken)
|
||||
public async Task<IActionResult> GetDepositByCreditProgram([FromQuery] List<string>? creditProgramIds, CancellationToken cancellationToken)
|
||||
{
|
||||
return (await _adapter.GetDataDepositByCreditProgramAsync(cancellationToken)).GetResponse(Request, Response);
|
||||
return (await _adapter.GetDataDepositByCreditProgramAsync(creditProgramIds, cancellationToken)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Отчет word Вклада по Кредитным программам
|
||||
/// </summary>
|
||||
/// <param name="creditProgramIds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
[Consumes("application/octet-stream")]
|
||||
public async Task<IActionResult> LoadDepositByCreditProgram(CancellationToken cancellationToken)
|
||||
public async Task<IActionResult> LoadDepositByCreditProgram([FromQuery] List<string>? creditProgramIds, CancellationToken cancellationToken)
|
||||
{
|
||||
return (await _adapter.CreateDocumentDepositByCreditProgramAsync(cancellationToken)).GetResponse(Request, Response);
|
||||
return (await _adapter.CreateDocumentDepositByCreditProgramAsync(creditProgramIds, cancellationToken)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Отчет excel Вклада по Кредитным программам
|
||||
/// </summary>
|
||||
/// <param name="creditProgramIds"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
[Consumes("application/octet-stream")]
|
||||
public async Task<IActionResult> LoadExcelDepositByCreditProgram(CancellationToken cancellationToken)
|
||||
public async Task<IActionResult> LoadExcelDepositByCreditProgram([FromQuery] List<string>? creditProgramIds, CancellationToken cancellationToken)
|
||||
{
|
||||
return (await _adapter.CreateExcelDocumentDepositByCreditProgramAsync(cancellationToken)).GetResponse(Request, Response);
|
||||
return (await _adapter.CreateExcelDocumentDepositByCreditProgramAsync(creditProgramIds, cancellationToken)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получение данных Вклада и Кредитных программам по Валютам
|
||||
/// </summary>
|
||||
/// <param name="fromDate"></param>
|
||||
/// <param name="toDate"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
[Consumes("application/json")]
|
||||
public async Task<IActionResult> GetDepositAndCreditProgramByCurrency(DateTime fromDate, DateTime toDate, CancellationToken cancellationToken)
|
||||
@@ -88,6 +139,13 @@ public class ReportController : ControllerBase
|
||||
cancellationToken)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Отчет pdf Вклада и Кредитных программам по Валютам
|
||||
/// </summary>
|
||||
/// <param name="fromDate"></param>
|
||||
/// <param name="toDate"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
[Consumes("application/octet-stream")]
|
||||
public async Task<IActionResult> LoadDepositAndCreditProgramByCurrency(DateTime fromDate, DateTime toDate, CancellationToken cancellationToken)
|
||||
@@ -95,12 +153,19 @@ public class ReportController : ControllerBase
|
||||
return (await _adapter.CreateDocumentDepositAndCreditProgramByCurrencyAsync(fromDate, toDate, cancellationToken)).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Отправка word отчета Клиентов по Кредитным программам
|
||||
/// </summary>
|
||||
/// <param name="email"></param>
|
||||
/// <param name="creditProgramIds"></param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> SendReportByCreditProgram(string email, CancellationToken ct)
|
||||
public async Task<IActionResult> SendReportByCreditProgram(string email, [FromQuery] List<string>? creditProgramIds, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var report = await _adapter.CreateDocumentClientsByCreditProgramAsync(ct);
|
||||
var report = await _adapter.CreateDocumentClientsByCreditProgramAsync(creditProgramIds, ct);
|
||||
var response = report.GetResponse(Request, Response);
|
||||
|
||||
if (response is FileStreamResult fileResult)
|
||||
@@ -130,6 +195,14 @@ public class ReportController : ControllerBase
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Отправка pdf отчета Клиентов по Валютам
|
||||
/// </summary>
|
||||
/// <param name="email"></param>
|
||||
/// <param name="fromDate"></param>
|
||||
/// <param name="toDate"></param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> SendReportByDeposit(string email, DateTime fromDate, DateTime toDate, CancellationToken ct)
|
||||
{
|
||||
@@ -165,6 +238,14 @@ public class ReportController : ControllerBase
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Отправка pdf отчета Вкладов и Кредитных программ по Валютам
|
||||
/// </summary>
|
||||
/// <param name="email"></param>
|
||||
/// <param name="fromDate"></param>
|
||||
/// <param name="toDate"></param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> SendReportByCurrency(string email, DateTime fromDate, DateTime toDate, CancellationToken ct)
|
||||
{
|
||||
@@ -200,12 +281,19 @@ public class ReportController : ControllerBase
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Отправка excel отчета Клиентов по Кредитных программ
|
||||
/// </summary>
|
||||
/// <param name="email"></param>
|
||||
/// <param name="creditProgramIds"></param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> SendExcelReportByCreditProgram(string email, CancellationToken ct)
|
||||
public async Task<IActionResult> SendExcelReportByCreditProgram(string email, [FromQuery] List<string>? creditProgramIds, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var report = await _adapter.CreateExcelDocumentClientsByCreditProgramAsync(ct);
|
||||
var report = await _adapter.CreateExcelDocumentClientsByCreditProgramAsync(creditProgramIds, ct);
|
||||
var response = report.GetResponse(Request, Response);
|
||||
|
||||
if (response is FileStreamResult fileResult)
|
||||
@@ -235,12 +323,19 @@ public class ReportController : ControllerBase
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Отправка word отчета Вкладов по Кредитных программ
|
||||
/// </summary>
|
||||
/// <param name="email"></param>
|
||||
/// <param name="creditProgramIds"></param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> SendReportDepositByCreditProgram(string email, CancellationToken ct)
|
||||
public async Task<IActionResult> SendReportDepositByCreditProgram(string email, [FromQuery] List<string>? creditProgramIds, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var report = await _adapter.CreateDocumentDepositByCreditProgramAsync(ct);
|
||||
var report = await _adapter.CreateDocumentDepositByCreditProgramAsync(creditProgramIds, ct);
|
||||
var response = report.GetResponse(Request, Response);
|
||||
|
||||
if (response is FileStreamResult fileResult)
|
||||
@@ -270,12 +365,19 @@ public class ReportController : ControllerBase
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Отправка excel отчета Вкладов по Кредитных программ
|
||||
/// </summary>
|
||||
/// <param name="email"></param>
|
||||
/// <param name="creditProgramIds"></param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> SendExcelReportDepositByCreditProgram(string email, CancellationToken ct)
|
||||
public async Task<IActionResult> SendExcelReportDepositByCreditProgram(string email, [FromQuery] List<string>? creditProgramIds, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var report = await _adapter.CreateExcelDocumentDepositByCreditProgramAsync(ct);
|
||||
var report = await _adapter.CreateExcelDocumentDepositByCreditProgramAsync(creditProgramIds, ct);
|
||||
var response = report.GetResponse(Request, Response);
|
||||
|
||||
if (response is FileStreamResult fileResult)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
using BankContracts.BindingModels;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace BankWebApi.Controllers;
|
||||
|
||||
@@ -39,7 +40,8 @@ public class StorekeepersController(IStorekeeperAdapter adapter) : ControllerBas
|
||||
/// </summary>
|
||||
/// <param name="model">модель от пользователя</param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
[HttpPost("register")]
|
||||
[AllowAnonymous]
|
||||
public IActionResult Register([FromBody] StorekeeperBindingModel model)
|
||||
{
|
||||
return _adapter.RegisterStorekeeper(model).GetResponse(Request, Response);
|
||||
@@ -55,4 +57,58 @@ public class StorekeepersController(IStorekeeperAdapter adapter) : ControllerBas
|
||||
{
|
||||
return _adapter.ChangeStorekeeperInfo(model).GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// вход для кладовщика
|
||||
/// </summary>
|
||||
/// <param name="model">модель с логином и паролем</param>
|
||||
/// <returns></returns>
|
||||
[HttpPost("login")]
|
||||
[AllowAnonymous]
|
||||
public IActionResult Login([FromBody] LoginBindingModel model)
|
||||
{
|
||||
var res = _adapter.Login(model, out string token);
|
||||
if (string.IsNullOrEmpty(token))
|
||||
{
|
||||
return res.GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
Response.Cookies.Append(AuthOptions.CookieName, token, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
SameSite = SameSiteMode.None,
|
||||
Secure = true,
|
||||
Expires = DateTime.UtcNow.AddDays(2)
|
||||
});
|
||||
|
||||
return res.GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получение данных текущего кладовщика
|
||||
/// </summary>
|
||||
/// <returns>Данные кладовщика</returns>
|
||||
[HttpGet("me")]
|
||||
public IActionResult GetCurrentUser()
|
||||
{
|
||||
var userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
||||
if (string.IsNullOrEmpty(userId))
|
||||
{
|
||||
return Unauthorized();
|
||||
}
|
||||
|
||||
var response = _adapter.GetElement(userId);
|
||||
return response.GetResponse(Request, Response);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Выход кладовщика
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
[HttpPost("logout")]
|
||||
public IActionResult Logout()
|
||||
{
|
||||
Response.Cookies.Delete(AuthOptions.CookieName);
|
||||
return Ok();
|
||||
}
|
||||
}
|
||||
|
||||
10
TheBank/BankWebApi/Infrastructure/IJwtProvider.cs
Normal file
10
TheBank/BankWebApi/Infrastructure/IJwtProvider.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
using BankContracts.DataModels;
|
||||
|
||||
namespace BankWebApi.Infrastructure;
|
||||
|
||||
public interface IJwtProvider
|
||||
{
|
||||
string GenerateToken(StorekeeperDataModel dataModel);
|
||||
|
||||
string GenerateToken(ClerkDataModel dataModel);
|
||||
}
|
||||
31
TheBank/BankWebApi/Infrastructure/JwtProvider.cs
Normal file
31
TheBank/BankWebApi/Infrastructure/JwtProvider.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using BankContracts.DataModels;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace BankWebApi.Infrastructure;
|
||||
|
||||
public class JwtProvider : IJwtProvider
|
||||
{
|
||||
public string GenerateToken(StorekeeperDataModel dataModel)
|
||||
{
|
||||
return GenerateToken(dataModel.Id);
|
||||
}
|
||||
|
||||
public string GenerateToken(ClerkDataModel dataModel)
|
||||
{
|
||||
return GenerateToken(dataModel.Id);
|
||||
}
|
||||
|
||||
private static string GenerateToken(string id)
|
||||
{
|
||||
var token = new JwtSecurityToken(
|
||||
issuer: AuthOptions.ISSUER,
|
||||
audience: AuthOptions.AUDIENCE,
|
||||
claims: [new(ClaimTypes.NameIdentifier, id)],
|
||||
expires: DateTime.UtcNow.Add(TimeSpan.FromDays(2)),
|
||||
signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
}
|
||||
10
TheBank/BankWebApi/Infrastructure/PasswordHelper.cs
Normal file
10
TheBank/BankWebApi/Infrastructure/PasswordHelper.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
namespace BankWebApi.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// да пох на это
|
||||
/// </summary>
|
||||
public class PasswordHelper
|
||||
{
|
||||
public static string HashPassword(string password) => BCrypt.Net.BCrypt.HashPassword(password);
|
||||
public static bool VerifyPassword(string password, string hash) => BCrypt.Net.BCrypt.Verify(password, hash);
|
||||
}
|
||||
@@ -29,12 +29,11 @@ builder.Services.AddSwaggerGen(c =>
|
||||
{
|
||||
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Bank API", Version = "v1" });
|
||||
|
||||
// <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> XML-<2D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> (<28><><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD>)
|
||||
// Включение XML-комментариев (если они есть)
|
||||
var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
|
||||
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
|
||||
c.IncludeXmlComments(xmlPath, includeControllerXmlComments: true);
|
||||
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> JWT-<2D><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> Swagger UI
|
||||
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
|
||||
{
|
||||
Description = "JWT Authorization header using the Bearer scheme. Example: 'Bearer {token}'",
|
||||
@@ -79,13 +78,33 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(),
|
||||
|
||||
ValidateIssuerSigningKey = true,
|
||||
|
||||
};
|
||||
options.Events = new JwtBearerEvents
|
||||
{
|
||||
OnMessageReceived = context =>
|
||||
{
|
||||
context.Token = context.Request.Cookies[AuthOptions.CookieName];
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy("AllowFrontend", policy =>
|
||||
{
|
||||
policy.WithOrigins("http://localhost:26312", "http://localhost:3654")
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader()
|
||||
.AllowCredentials();
|
||||
});
|
||||
});
|
||||
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
|
||||
builder.Services.AddOpenApi();
|
||||
builder.Services.AddSingleton<IConfigurationDatabase, ConfigurationDatabase>();
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
builder.Services.AddSingleton<IConfigurationDatabase, BankWebApi.Infrastructure.ConfigurationDatabase>();
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
builder.Services.AddTransient<IClerkBusinessLogicContract, ClerkBusinessLogicContract>();
|
||||
builder.Services.AddTransient<IPeriodBusinessLogicContract, PeriodBusinessLogicContract>();
|
||||
builder.Services.AddTransient<IDepositBusinessLogicContract, DepositBusinessLogicContract>();
|
||||
@@ -94,7 +113,7 @@ builder.Services.AddTransient<ICreditProgramBusinessLogicContract, CreditProgram
|
||||
builder.Services.AddTransient<ICurrencyBusinessLogicContract, CurrencyBusinessLogicContract>();
|
||||
builder.Services.AddTransient<IStorekeeperBusinessLogicContract, StorekeeperBusinessLogicContract>();
|
||||
builder.Services.AddTransient<IReplenishmentBusinessLogicContract, ReplenishmentBusinessLogicContract>();
|
||||
// <20><>
|
||||
// <20><>
|
||||
builder.Services.AddTransient<BankDbContext>();
|
||||
builder.Services.AddTransient<IClerkStorageContract, ClerkStorageContract>();
|
||||
builder.Services.AddTransient<IPeriodStorageContract, PeriodStorageContract>();
|
||||
@@ -104,7 +123,7 @@ builder.Services.AddTransient<ICreditProgramStorageContract, CreditProgramStorag
|
||||
builder.Services.AddTransient<ICurrencyStorageContract, CurrencyStorageContract>();
|
||||
builder.Services.AddTransient<IStorekeeperStorageContract, StorekeeperStorageContract>();
|
||||
builder.Services.AddTransient<IReplenishmentStorageContract, ReplenishmentStorageContract>();
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
||||
builder.Services.AddTransient<IClerkAdapter, ClerkAdapter>();
|
||||
builder.Services.AddTransient<IPeriodAdapter, PeriodAdapter>();
|
||||
builder.Services.AddTransient<IDepositAdapter, DepositAdapter>();
|
||||
@@ -118,6 +137,8 @@ builder.Services.AddTransient<IReportAdapter, ReportAdapter>();
|
||||
builder.Services.AddTransient<BaseWordBuilder, OpenXmlWordBuilder>();
|
||||
builder.Services.AddTransient<BaseExcelBuilder, OpenXmlExcelBuilder>();
|
||||
builder.Services.AddTransient<BasePdfBuilder, MigraDocPdfBuilder>();
|
||||
// shit
|
||||
builder.Services.AddTransient<IJwtProvider, JwtProvider>();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
@@ -129,7 +150,7 @@ if (app.Environment.IsDevelopment())
|
||||
app.UseSwaggerUI(c =>
|
||||
{
|
||||
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Bank API V1");
|
||||
c.RoutePrefix = "swagger"; // Swagger UI <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> /swagger
|
||||
c.RoutePrefix = "swagger"; // Swagger UI <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> /swagger
|
||||
});
|
||||
}
|
||||
if (app.Environment.IsProduction())
|
||||
@@ -141,11 +162,19 @@ if (app.Environment.IsProduction())
|
||||
dbContext.Database.Migrate();
|
||||
}
|
||||
}
|
||||
|
||||
app.UseCors("AllowFrontend");
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseCookiePolicy(new CookiePolicyOptions
|
||||
{
|
||||
HttpOnly = Microsoft.AspNetCore.CookiePolicy.HttpOnlyPolicy.Always,
|
||||
Secure = app.Environment.IsProduction() ? CookieSecurePolicy.Always : CookieSecurePolicy.None
|
||||
});
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
|
||||
// это для тестов
|
||||
app.Map("/login/{username}", (string username) =>
|
||||
{
|
||||
return new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
|
||||
|
||||
@@ -13,6 +13,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BankTests", "BankTests\Bank
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BankWebApi", "BankWebApi\BankWebApi.csproj", "{C8A3A3BB-A096-429F-A763-5465C5CB735F}"
|
||||
EndProject
|
||||
Project("{54A90642-561A-4BB1-A94E-469ADEE60C69}") = "bankui", "BankUI\bankui.esproj", "{12D5DDAD-F24A-41B0-9FBC-BEFBFB01067D}"
|
||||
EndProject
|
||||
Project("{54A90642-561A-4BB1-A94E-469ADEE60C69}") = "bankuiclerk", "BankUIClerk\bankuiclerk.esproj", "{FD37483B-1D73-44B8-9D8B-38FE8F039E48}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -39,6 +43,18 @@ Global
|
||||
{C8A3A3BB-A096-429F-A763-5465C5CB735F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C8A3A3BB-A096-429F-A763-5465C5CB735F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C8A3A3BB-A096-429F-A763-5465C5CB735F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{12D5DDAD-F24A-41B0-9FBC-BEFBFB01067D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{12D5DDAD-F24A-41B0-9FBC-BEFBFB01067D}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{12D5DDAD-F24A-41B0-9FBC-BEFBFB01067D}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
|
||||
{12D5DDAD-F24A-41B0-9FBC-BEFBFB01067D}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{12D5DDAD-F24A-41B0-9FBC-BEFBFB01067D}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{12D5DDAD-F24A-41B0-9FBC-BEFBFB01067D}.Release|Any CPU.Deploy.0 = Release|Any CPU
|
||||
{FD37483B-1D73-44B8-9D8B-38FE8F039E48}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{FD37483B-1D73-44B8-9D8B-38FE8F039E48}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{FD37483B-1D73-44B8-9D8B-38FE8F039E48}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
|
||||
{FD37483B-1D73-44B8-9D8B-38FE8F039E48}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{FD37483B-1D73-44B8-9D8B-38FE8F039E48}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{FD37483B-1D73-44B8-9D8B-38FE8F039E48}.Release|Any CPU.Deploy.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
2
TheBank/bankui/.env
Normal file
2
TheBank/bankui/.env
Normal file
@@ -0,0 +1,2 @@
|
||||
VITE_API_URL=https://localhost:7204
|
||||
# VITE_API_URL=http://localhost:5189
|
||||
24
TheBank/bankui/.gitignore
vendored
Normal file
24
TheBank/bankui/.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
7
TheBank/bankui/.prettierrc
Normal file
7
TheBank/bankui/.prettierrc
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"semi": true,
|
||||
"jsxSingleQuote": false,
|
||||
"tabWidth": 2,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all"
|
||||
}
|
||||
12
TheBank/bankui/CHANGELOG.md
Normal file
12
TheBank/bankui/CHANGELOG.md
Normal file
@@ -0,0 +1,12 @@
|
||||
This file explains how Visual Studio created the project.
|
||||
|
||||
The following tools were used to generate this project:
|
||||
- create-vite
|
||||
|
||||
The following steps were used to generate this project:
|
||||
- Create react project with create-vite: `npm init --yes vite@latest bankui -- --template=react-ts`.
|
||||
- Updating vite.config.ts with port.
|
||||
- Create project file (`bankui.esproj`).
|
||||
- Create `launch.json` to enable debugging.
|
||||
- Add project to solution.
|
||||
- Write this file.
|
||||
54
TheBank/bankui/README.md
Normal file
54
TheBank/bankui/README.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
|
||||
```js
|
||||
export default tseslint.config({
|
||||
extends: [
|
||||
// Remove ...tseslint.configs.recommended and replace with this
|
||||
...tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
...tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
...tseslint.configs.stylisticTypeChecked,
|
||||
],
|
||||
languageOptions: {
|
||||
// other options...
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
|
||||
export default tseslint.config({
|
||||
plugins: {
|
||||
// Add the react-x and react-dom plugins
|
||||
'react-x': reactX,
|
||||
'react-dom': reactDom,
|
||||
},
|
||||
rules: {
|
||||
// other rules...
|
||||
// Enable its recommended typescript rules
|
||||
...reactX.configs['recommended-typescript'].rules,
|
||||
...reactDom.configs.recommended.rules,
|
||||
},
|
||||
})
|
||||
```
|
||||
11
TheBank/bankui/bankui.esproj
Normal file
11
TheBank/bankui/bankui.esproj
Normal file
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.VisualStudio.JavaScript.Sdk/1.0.1738743">
|
||||
<PropertyGroup>
|
||||
<StartupCommand>npm run dev</StartupCommand>
|
||||
<JavaScriptTestRoot>src\</JavaScriptTestRoot>
|
||||
<JavaScriptTestFramework>Jest</JavaScriptTestFramework>
|
||||
<!-- Allows the build (or compile) script located on package.json to run on Build -->
|
||||
<ShouldRunBuildScript>false</ShouldRunBuildScript>
|
||||
<!-- Folder where production build objects will be placed -->
|
||||
<BuildOutputFolder>$(MSBuildProjectDirectory)\dist</BuildOutputFolder>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
BIN
TheBank/bankui/bun.lockb
Normal file
BIN
TheBank/bankui/bun.lockb
Normal file
Binary file not shown.
21
TheBank/bankui/components.json
Normal file
21
TheBank/bankui/components.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/index.css",
|
||||
"baseColor": "slate",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
28
TheBank/bankui/eslint.config.js
Normal file
28
TheBank/bankui/eslint.config.js
Normal file
@@ -0,0 +1,28 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ['dist'] },
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
plugins: {
|
||||
'react-hooks': reactHooks,
|
||||
'react-refresh': reactRefresh,
|
||||
},
|
||||
rules: {
|
||||
...reactHooks.configs.recommended.rules,
|
||||
'react-refresh/only-export-components': [
|
||||
'warn',
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
13
TheBank/bankui/index.html
Normal file
13
TheBank/bankui/index.html
Normal file
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Шрек</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root" class="roboto"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
962
TheBank/bankui/package-lock.json
generated
962
TheBank/bankui/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
59
TheBank/bankui/package.json
Normal file
59
TheBank/bankui/package.json
Normal file
@@ -0,0 +1,59 @@
|
||||
{
|
||||
"name": "bankui",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^5.0.1",
|
||||
"@radix-ui/react-avatar": "^1.1.9",
|
||||
"@radix-ui/react-checkbox": "^1.3.1",
|
||||
"@radix-ui/react-dialog": "^1.1.13",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.14",
|
||||
"@radix-ui/react-label": "^2.1.6",
|
||||
"@radix-ui/react-menubar": "^1.1.14",
|
||||
"@radix-ui/react-popover": "^1.1.13",
|
||||
"@radix-ui/react-select": "^2.2.4",
|
||||
"@radix-ui/react-separator": "^1.1.6",
|
||||
"@radix-ui/react-slot": "^1.2.2",
|
||||
"@radix-ui/react-tabs": "^1.1.11",
|
||||
"@radix-ui/react-tooltip": "^1.2.6",
|
||||
"@tailwindcss/vite": "^4.1.7",
|
||||
"@tanstack/react-query": "^5.76.1",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"lucide-react": "^0.511.0",
|
||||
"next-themes": "^0.4.6",
|
||||
"react": "^19.1.0",
|
||||
"react-day-picker": "8.10.1",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-hook-form": "^7.56.4",
|
||||
"react-router-dom": "^7.6.0",
|
||||
"sonner": "^2.0.3",
|
||||
"tailwind-merge": "^3.3.0",
|
||||
"tailwindcss": "^4.1.7",
|
||||
"tw-animate-css": "^1.3.0",
|
||||
"zod": "^3.24.4",
|
||||
"zustand": "^5.0.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.25.0",
|
||||
"@types/node": "^22.15.18",
|
||||
"@types/react": "^19.1.2",
|
||||
"@types/react-dom": "^19.1.2",
|
||||
"@vitejs/plugin-react": "^4.4.1",
|
||||
"eslint": "^9.25.0",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.19",
|
||||
"globals": "^16.0.0",
|
||||
"typescript": "~5.8.3",
|
||||
"typescript-eslint": "^8.30.1",
|
||||
"vite": "^6.3.5"
|
||||
}
|
||||
}
|
||||
1
TheBank/bankui/public/vite.svg
Normal file
1
TheBank/bankui/public/vite.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
33
TheBank/bankui/src/App.tsx
Normal file
33
TheBank/bankui/src/App.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import { useAuthCheck } from '@/hooks/useAuthCheck';
|
||||
import { useAuthStore } from '@/store/workerStore';
|
||||
import { Navigate, Outlet, useLocation } from 'react-router-dom';
|
||||
import { Header } from '@/components/layout/Header';
|
||||
import { Footer } from '@/components/layout/Footer';
|
||||
import { Suspense } from 'react';
|
||||
|
||||
function App() {
|
||||
const user = useAuthStore((store) => store.user);
|
||||
const { isLoading } = useAuthCheck();
|
||||
const location = useLocation();
|
||||
|
||||
if (isLoading) {
|
||||
return <div>Loading...</div>;
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
const redirect = encodeURIComponent(location.pathname + location.search);
|
||||
return <Navigate to={`/auth?redirect=${redirect}`} replace />;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Header />
|
||||
<Suspense fallback={<p>Loading...</p>}>
|
||||
<Outlet />
|
||||
</Suspense>
|
||||
<Footer />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
131
TheBank/bankui/src/api/api.ts
Normal file
131
TheBank/bankui/src/api/api.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
import {
|
||||
getData,
|
||||
getSingleData,
|
||||
postData,
|
||||
postLoginData,
|
||||
putData,
|
||||
} from './client';
|
||||
import type {
|
||||
ClientBindingModel,
|
||||
ClerkBindingModel,
|
||||
CreditProgramBindingModel,
|
||||
CurrencyBindingModel,
|
||||
DepositBindingModel,
|
||||
PeriodBindingModel,
|
||||
ReplenishmentBindingModel,
|
||||
StorekeeperBindingModel,
|
||||
LoginBindingModel,
|
||||
} from '../types/types';
|
||||
|
||||
// Clients API
|
||||
export const clientsApi = {
|
||||
getAll: () => getData<ClientBindingModel>('api/Clients/GetAllRecords'),
|
||||
getById: (id: string) =>
|
||||
getData<ClientBindingModel>(`api/Clients/GetRecord/${id}`),
|
||||
getByClerk: (clerkId: string) =>
|
||||
getData<ClientBindingModel>(`api/Clients/GetRecordByClerk/${clerkId}`),
|
||||
create: (data: ClientBindingModel) => postData('api/Clients/Register', data),
|
||||
update: (data: ClientBindingModel) => putData('api/Clients/ChangeInfo', data),
|
||||
};
|
||||
|
||||
// Clerks API
|
||||
export const clerksApi = {
|
||||
getAll: () => getData<ClerkBindingModel>('api/Clerks/GetAllRecords'),
|
||||
getById: (id: string) =>
|
||||
getData<ClerkBindingModel>(`api/Clerks/GetRecord/${id}`),
|
||||
create: (data: ClerkBindingModel) => postData('api/Clerks/Register', data),
|
||||
update: (data: ClerkBindingModel) => putData('api/Clerks/ChangeInfo', data),
|
||||
};
|
||||
|
||||
// Credit Programs API
|
||||
export const creditProgramsApi = {
|
||||
getAll: () =>
|
||||
getData<CreditProgramBindingModel>('api/CreditPrograms/GetAllRecords'),
|
||||
getById: (id: string) =>
|
||||
getData<CreditProgramBindingModel>(`api/CreditPrograms/GetRecord/${id}`),
|
||||
getByStorekeeper: (storekeeperId: string) =>
|
||||
getData<CreditProgramBindingModel>(
|
||||
`api/CreditPrograms/GetRecordByStorekeeper/${storekeeperId}`,
|
||||
),
|
||||
create: (data: CreditProgramBindingModel) =>
|
||||
postData('api/CreditPrograms/Register', data),
|
||||
update: (data: CreditProgramBindingModel) =>
|
||||
putData('api/CreditPrograms/ChangeInfo', data),
|
||||
};
|
||||
|
||||
// Currencies API
|
||||
export const currenciesApi = {
|
||||
getAll: () => getData<CurrencyBindingModel>('api/Currencies/GetAllRecords'),
|
||||
getById: (id: string) =>
|
||||
getData<CurrencyBindingModel>(`api/Currencies/GetRecord/${id}`),
|
||||
getByStorekeeper: (storekeeperId: string) =>
|
||||
getData<CurrencyBindingModel>(
|
||||
`api/Currencies/GetRecordByStorekeeper/${storekeeperId}`,
|
||||
),
|
||||
create: (data: CurrencyBindingModel) =>
|
||||
postData('api/Currencies/Register', data),
|
||||
update: (data: CurrencyBindingModel) =>
|
||||
putData('api/Currencies/ChangeInfo', data),
|
||||
};
|
||||
|
||||
// Deposits API
|
||||
export const depositsApi = {
|
||||
getAll: () => getData<DepositBindingModel>('api/Deposits/GetAllRecords'),
|
||||
getById: (id: string) =>
|
||||
getData<DepositBindingModel>(`api/Deposits/GetRecord/${id}`),
|
||||
getByClerk: (clerkId: string) =>
|
||||
getData<DepositBindingModel>(`api/Deposits/GetRecordByClerk/${clerkId}`),
|
||||
create: (data: DepositBindingModel) =>
|
||||
postData('api/Deposits/Register', data),
|
||||
update: (data: DepositBindingModel) =>
|
||||
putData('api/Deposits/ChangeInfo', data),
|
||||
};
|
||||
|
||||
// Periods API
|
||||
export const periodsApi = {
|
||||
getAll: () => getData<PeriodBindingModel>('api/Periods/GetAllRecords'),
|
||||
getById: (id: string) =>
|
||||
getData<PeriodBindingModel>(`api/Periods/GetRecord/${id}`),
|
||||
getByStorekeeper: (storekeeperId: string) =>
|
||||
getData<PeriodBindingModel>(
|
||||
`api/Period/GetRecordByStorekeeper/${storekeeperId}`,
|
||||
),
|
||||
create: (data: PeriodBindingModel) => postData('api/Periods/Register', data),
|
||||
update: (data: PeriodBindingModel) => putData('api/Periods/ChangeInfo', data),
|
||||
};
|
||||
|
||||
// Replenishments API
|
||||
export const replenishmentsApi = {
|
||||
getAll: () =>
|
||||
getData<ReplenishmentBindingModel>('api/Replenishments/GetAllRecords'),
|
||||
getById: (id: string) =>
|
||||
getData<ReplenishmentBindingModel>(`api/Replenishments/GetRecord/${id}`),
|
||||
getByDeposit: (depositId: string) =>
|
||||
getData<ReplenishmentBindingModel>(
|
||||
`api/Replenishments/GetRecordByDeposit/${depositId}`,
|
||||
),
|
||||
getByClerk: (clerkId: string) =>
|
||||
getData<ReplenishmentBindingModel>(
|
||||
`api/Replenishments/GetRecordByClerk/${clerkId}`,
|
||||
),
|
||||
create: (data: ReplenishmentBindingModel) =>
|
||||
postData('api/Replenishments/Register', data),
|
||||
update: (data: ReplenishmentBindingModel) =>
|
||||
putData('api/Replenishments/ChangeInfo', data),
|
||||
};
|
||||
|
||||
// Storekeepers API
|
||||
export const storekeepersApi = {
|
||||
getAll: () => getData<StorekeeperBindingModel>('api/storekeepers'),
|
||||
getById: (id: string) =>
|
||||
getData<StorekeeperBindingModel>(`api/Storekeepers/GetRecord/${id}`),
|
||||
create: (data: StorekeeperBindingModel) =>
|
||||
postData('api/Storekeepers/Register', data),
|
||||
update: (data: StorekeeperBindingModel) => putData('api/Storekeepers', data),
|
||||
// auth
|
||||
login: (data: LoginBindingModel) =>
|
||||
postLoginData('api/Storekeepers/login', data),
|
||||
logout: () => postData('api/storekeepers/logout', {}),
|
||||
getCurrentUser: () =>
|
||||
getSingleData<StorekeeperBindingModel>('api/storekeepers/me'),
|
||||
};
|
||||
71
TheBank/bankui/src/api/client.ts
Normal file
71
TheBank/bankui/src/api/client.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { ConfigManager } from '@/lib/config';
|
||||
|
||||
const API_URL = ConfigManager.loadUrl();
|
||||
|
||||
export async function getData<T>(path: string): Promise<T[]> {
|
||||
const res = await fetch(`${API_URL}/${path}`, {
|
||||
credentials: 'include',
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`Не получается загрузить ${path}: ${res.statusText}`);
|
||||
}
|
||||
const data = (await res.json()) as T[];
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function postData<T>(path: string, data: T) {
|
||||
const res = await fetch(`${API_URL}/${path}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
// mode: 'no-cors',
|
||||
},
|
||||
credentials: 'include',
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`Не получается загрузить ${path}: ${res.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getSingleData<T>(path: string): Promise<T> {
|
||||
const res = await fetch(`${API_URL}/${path}`, {
|
||||
credentials: 'include',
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`Не получается загрузить ${path}: ${res.statusText}`);
|
||||
}
|
||||
const data = (await res.json()) as T;
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function postLoginData<T>(path: string, data: T): Promise<T> {
|
||||
const res = await fetch(`${API_URL}/${path}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
credentials: 'include',
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`Не получается загрузить ${path}: ${await res.text()}`);
|
||||
}
|
||||
|
||||
const userData = (await res.json()) as T;
|
||||
return userData;
|
||||
}
|
||||
|
||||
export async function putData<T>(path: string, data: T) {
|
||||
const res = await fetch(`${API_URL}/${path}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
credentials: 'include',
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (!res.ok) {
|
||||
throw new Error(`Не получается загрузить ${path}: ${res.statusText}`);
|
||||
}
|
||||
}
|
||||
1
TheBank/bankui/src/assets/react.svg
Normal file
1
TheBank/bankui/src/assets/react.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
281
TheBank/bankui/src/components/features/CreditProgramForm.tsx
Normal file
281
TheBank/bankui/src/components/features/CreditProgramForm.tsx
Normal file
@@ -0,0 +1,281 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { CreditProgramBindingModel } from '@/types/types';
|
||||
import { useAuthStore } from '@/store/workerStore';
|
||||
import { usePeriods } from '@/hooks/usePeriods';
|
||||
|
||||
type BaseFormValues = {
|
||||
id?: string;
|
||||
name: string;
|
||||
cost: number;
|
||||
maxCost: number;
|
||||
periodId: string;
|
||||
};
|
||||
|
||||
type EditFormValues = Partial<BaseFormValues>;
|
||||
|
||||
const baseSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
name: z.string().min(1, 'Название обязательно'),
|
||||
cost: z.coerce.number().min(0, 'Стоимость не может быть отрицательной'),
|
||||
maxCost: z.coerce
|
||||
.number()
|
||||
.min(0, 'Максимальная стоимость не может быть отрицательной'),
|
||||
periodId: z.string().min(1, 'Выберите период'),
|
||||
});
|
||||
|
||||
const addSchema = baseSchema;
|
||||
|
||||
const editSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
name: z.string().min(1, 'Название обязательно').optional(),
|
||||
cost: z.coerce
|
||||
.number()
|
||||
.min(0, 'Стоимость не может быть отрицательной')
|
||||
.optional(),
|
||||
maxCost: z.coerce
|
||||
.number()
|
||||
.min(0, 'Максимальная стоимость не может быть отрицательной')
|
||||
.optional(),
|
||||
periodId: z.string().min(1, 'Выберите период').optional(),
|
||||
});
|
||||
|
||||
interface BaseCreditProgramFormProps {
|
||||
onSubmit: (data: CreditProgramBindingModel) => void;
|
||||
schema: z.ZodType<BaseFormValues | EditFormValues>;
|
||||
defaultValues?: Partial<BaseFormValues>;
|
||||
}
|
||||
|
||||
const BaseCreditProgramForm = ({
|
||||
onSubmit,
|
||||
schema,
|
||||
defaultValues,
|
||||
}: BaseCreditProgramFormProps): React.JSX.Element => {
|
||||
const form = useForm<BaseFormValues | EditFormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: defaultValues
|
||||
? {
|
||||
id: defaultValues.id ?? '',
|
||||
name: defaultValues.name ?? '',
|
||||
cost: defaultValues.cost ?? 0,
|
||||
maxCost: defaultValues.maxCost ?? 0,
|
||||
periodId: defaultValues.periodId ?? '',
|
||||
}
|
||||
: {
|
||||
id: '',
|
||||
name: '',
|
||||
cost: 0,
|
||||
maxCost: 0,
|
||||
periodId: '',
|
||||
},
|
||||
});
|
||||
|
||||
const { periods } = usePeriods();
|
||||
|
||||
useEffect(() => {
|
||||
if (defaultValues) {
|
||||
form.reset({
|
||||
id: defaultValues.id ?? '',
|
||||
name: defaultValues.name ?? '',
|
||||
cost: defaultValues.cost ?? 0,
|
||||
maxCost: defaultValues.maxCost ?? 0,
|
||||
periodId: defaultValues.periodId ?? '',
|
||||
});
|
||||
}
|
||||
}, [defaultValues, form]);
|
||||
|
||||
const storekeeper = useAuthStore((store) => store.user);
|
||||
|
||||
const handleSubmit = (data: BaseFormValues | EditFormValues) => {
|
||||
if (!storekeeper?.id) {
|
||||
console.error('Storekeeper ID is not available.');
|
||||
return;
|
||||
}
|
||||
|
||||
let payload: CreditProgramBindingModel;
|
||||
|
||||
if (schema === addSchema) {
|
||||
const addData = data as BaseFormValues;
|
||||
payload = {
|
||||
id: addData.id || crypto.randomUUID(),
|
||||
storekeeperId: storekeeper.id,
|
||||
name: addData.name,
|
||||
cost: addData.cost,
|
||||
maxCost: addData.maxCost,
|
||||
periodId: addData.periodId,
|
||||
};
|
||||
} else {
|
||||
const editData = data as EditFormValues;
|
||||
const currentDefaultValues = defaultValues as Partial<BaseFormValues>;
|
||||
|
||||
const changedData: Partial<CreditProgramBindingModel> = {};
|
||||
|
||||
if (editData.id !== undefined && editData.id !== currentDefaultValues?.id)
|
||||
changedData.id = editData.id;
|
||||
if (
|
||||
editData.name !== undefined &&
|
||||
editData.name !== currentDefaultValues?.name
|
||||
)
|
||||
changedData.name = editData.name;
|
||||
if (
|
||||
editData.cost !== undefined &&
|
||||
editData.cost !== currentDefaultValues?.cost
|
||||
)
|
||||
changedData.cost = editData.cost;
|
||||
if (
|
||||
editData.maxCost !== undefined &&
|
||||
editData.maxCost !== currentDefaultValues?.maxCost
|
||||
)
|
||||
changedData.maxCost = editData.maxCost;
|
||||
if (
|
||||
editData.periodId !== undefined &&
|
||||
editData.periodId !== currentDefaultValues?.periodId
|
||||
)
|
||||
changedData.periodId = editData.periodId;
|
||||
|
||||
if (currentDefaultValues?.id) changedData.id = currentDefaultValues.id;
|
||||
changedData.storekeeperId = storekeeper.id;
|
||||
|
||||
payload = {
|
||||
...(defaultValues as CreditProgramBindingModel),
|
||||
...changedData,
|
||||
};
|
||||
}
|
||||
|
||||
onSubmit(payload);
|
||||
};
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(handleSubmit)}
|
||||
className="space-y-4 max-w-md mx-auto p-4"
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="id"
|
||||
render={({ field }) => <input type="hidden" {...field} />}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Название</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Название" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="cost"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Стоимость</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" placeholder="Стоимость" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="maxCost"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Максимальная стоимость</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="Максимальная стоимость"
|
||||
{...field}
|
||||
/>
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="periodId"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Период</FormLabel>
|
||||
<Select onValueChange={field.onChange} value={field.value || ''}>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Выберите период" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
{periods &&
|
||||
periods?.map((period) => (
|
||||
<SelectItem key={period.id} value={period.id}>
|
||||
{`${new Date(
|
||||
period.startTime,
|
||||
).toLocaleDateString()} - ${new Date(
|
||||
period.endTime,
|
||||
).toLocaleDateString()}`}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Button type="submit" className="w-full">
|
||||
Сохранить
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
|
||||
export const CreditProgramFormAdd = ({
|
||||
onSubmit,
|
||||
}: {
|
||||
onSubmit: (data: CreditProgramBindingModel) => void;
|
||||
}): React.JSX.Element => {
|
||||
return <BaseCreditProgramForm onSubmit={onSubmit} schema={addSchema} />;
|
||||
};
|
||||
|
||||
export const CreditProgramFormEdit = ({
|
||||
onSubmit,
|
||||
defaultValues,
|
||||
}: {
|
||||
onSubmit: (data: CreditProgramBindingModel) => void;
|
||||
defaultValues: Partial<BaseFormValues>;
|
||||
}): React.JSX.Element => {
|
||||
return (
|
||||
<BaseCreditProgramForm
|
||||
onSubmit={onSubmit}
|
||||
schema={editSchema}
|
||||
defaultValues={defaultValues}
|
||||
/>
|
||||
);
|
||||
};
|
||||
180
TheBank/bankui/src/components/features/CurrencyForm.tsx
Normal file
180
TheBank/bankui/src/components/features/CurrencyForm.tsx
Normal file
@@ -0,0 +1,180 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { CurrencyBindingModel } from '@/types/types';
|
||||
import { useAuthStore } from '@/store/workerStore';
|
||||
|
||||
type BaseFormValues = {
|
||||
id?: string;
|
||||
name: string;
|
||||
abbreviation: string;
|
||||
cost: number;
|
||||
};
|
||||
|
||||
type EditFormValues = {
|
||||
id?: string;
|
||||
name?: string;
|
||||
abbreviation?: string;
|
||||
cost?: number;
|
||||
};
|
||||
|
||||
const baseSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
name: z.string({ message: 'Введите название' }),
|
||||
abbreviation: z.string({ message: 'Введите аббревиатуру' }),
|
||||
cost: z.coerce.number({ message: 'Введите стоимость' }),
|
||||
});
|
||||
|
||||
const addSchema = baseSchema;
|
||||
|
||||
const editSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
name: z.string().min(1, 'Укажите название валюты').optional(),
|
||||
abbreviation: z.string().min(1, 'Укажите аббревиатуру').optional(),
|
||||
cost: z.coerce
|
||||
.number()
|
||||
.min(0, 'Стоимость не может быть отрицательной')
|
||||
.optional(),
|
||||
});
|
||||
|
||||
interface BaseCurrencyFormProps {
|
||||
onSubmit: (data: CurrencyBindingModel) => void;
|
||||
schema: z.ZodType<BaseFormValues | EditFormValues>;
|
||||
defaultValues?: Partial<BaseFormValues | EditFormValues>;
|
||||
}
|
||||
|
||||
const BaseCurrencyForm = ({
|
||||
onSubmit,
|
||||
schema,
|
||||
defaultValues,
|
||||
}: BaseCurrencyFormProps): React.JSX.Element => {
|
||||
const form = useForm<BaseFormValues | EditFormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
id: defaultValues?.id || '',
|
||||
name: defaultValues?.name || '',
|
||||
abbreviation: defaultValues?.abbreviation || '',
|
||||
cost: defaultValues?.cost || 0,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (defaultValues) {
|
||||
form.reset({
|
||||
id: defaultValues.id || '',
|
||||
name: defaultValues.name || '',
|
||||
abbreviation: defaultValues.abbreviation || '',
|
||||
cost: defaultValues.cost || 0,
|
||||
});
|
||||
}
|
||||
}, [defaultValues, form]);
|
||||
|
||||
const storekeeper = useAuthStore((store) => store.user);
|
||||
|
||||
const handleSubmit = (data: BaseFormValues | EditFormValues) => {
|
||||
const payload: CurrencyBindingModel = {
|
||||
id: data.id || crypto.randomUUID(),
|
||||
storekeeperId: storekeeper?.id,
|
||||
name: 'name' in data && data.name !== undefined ? data.name : '',
|
||||
abbreviation:
|
||||
'abbreviation' in data && data.abbreviation !== undefined
|
||||
? data.abbreviation
|
||||
: '',
|
||||
cost: 'cost' in data && data.cost !== undefined ? data.cost : 0,
|
||||
};
|
||||
|
||||
onSubmit(payload);
|
||||
};
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(handleSubmit)}
|
||||
className="space-y-4 max-w-md mx-auto p-4"
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="id"
|
||||
render={({ field }) => <input type="hidden" {...field} />}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Название</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Например, Доллар США" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="abbreviation"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Аббревиатура</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Например, USD" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="cost"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Стоимость</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" placeholder="Например, 1.0" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button type="submit" className="w-full">
|
||||
Сохранить
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
|
||||
export const CurrencyFormAdd = ({
|
||||
onSubmit,
|
||||
}: {
|
||||
onSubmit: (data: CurrencyBindingModel) => void;
|
||||
}): React.JSX.Element => {
|
||||
return <BaseCurrencyForm onSubmit={onSubmit} schema={addSchema} />;
|
||||
};
|
||||
|
||||
export const CurrencyFormEdit = ({
|
||||
onSubmit,
|
||||
defaultValues,
|
||||
}: {
|
||||
onSubmit: (data: CurrencyBindingModel) => void;
|
||||
defaultValues: Partial<BaseFormValues>;
|
||||
}): React.JSX.Element => {
|
||||
return (
|
||||
<BaseCurrencyForm
|
||||
onSubmit={onSubmit}
|
||||
schema={editSchema}
|
||||
defaultValues={defaultValues}
|
||||
/>
|
||||
);
|
||||
};
|
||||
82
TheBank/bankui/src/components/features/LoginForm.tsx
Normal file
82
TheBank/bankui/src/components/features/LoginForm.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
import type { LoginBindingModel } from '@/types/types';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '../ui/form';
|
||||
import { Input } from '../ui/input';
|
||||
import { Button } from '../ui/button';
|
||||
|
||||
interface LoginFormProps {
|
||||
onSubmit: (data: LoginBindingModel) => void;
|
||||
defaultValues?: Partial<LoginBindingModel>;
|
||||
}
|
||||
const loginFormSchema = z.object({
|
||||
login: z.string().min(3, 'Логин должен быть не короче 3 символов'),
|
||||
password: z.string().min(6, 'Пароль должен быть не короче 6 символов'),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof loginFormSchema>;
|
||||
|
||||
export const LoginForm = ({
|
||||
onSubmit,
|
||||
defaultValues,
|
||||
}: LoginFormProps): React.JSX.Element => {
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(loginFormSchema),
|
||||
defaultValues: {
|
||||
login: defaultValues?.login || '',
|
||||
password: defaultValues?.password || '',
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = (data: FormValues) => {
|
||||
const payload: LoginBindingModel = {
|
||||
...data,
|
||||
};
|
||||
onSubmit(payload);
|
||||
};
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="login"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Логин</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Логин" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Пароль</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="password" placeholder="Пароль" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button type="submit" className="w-full">
|
||||
Войти
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
235
TheBank/bankui/src/components/features/PeriodForm.tsx
Normal file
235
TheBank/bankui/src/components/features/PeriodForm.tsx
Normal file
@@ -0,0 +1,235 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { PeriodBindingModel } from '@/types/types';
|
||||
import { Calendar } from '@/components/ui/calendar';
|
||||
import { format } from 'date-fns';
|
||||
import { CalendarIcon } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import { useAuthStore } from '@/store/workerStore';
|
||||
|
||||
type BaseFormValues = {
|
||||
id?: string;
|
||||
startTime: Date;
|
||||
endTime: Date;
|
||||
};
|
||||
|
||||
type EditFormValues = {
|
||||
id?: string;
|
||||
startTime?: Date;
|
||||
endTime?: Date;
|
||||
};
|
||||
|
||||
const baseSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
startTime: z.date({
|
||||
required_error: 'Укажите время начала',
|
||||
invalid_type_error: 'Неверный формат даты',
|
||||
}),
|
||||
endTime: z.date({
|
||||
required_error: 'Укажите время окончания',
|
||||
invalid_type_error: 'Неверный формат даты',
|
||||
}),
|
||||
});
|
||||
|
||||
const addSchema = baseSchema;
|
||||
|
||||
const editSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
startTime: z
|
||||
.date({
|
||||
required_error: 'Укажите время начала',
|
||||
invalid_type_error: 'Неверный формат даты',
|
||||
})
|
||||
.optional(),
|
||||
endTime: z
|
||||
.date({
|
||||
required_error: 'Укажите время окончания',
|
||||
invalid_type_error: 'Неверный формат даты',
|
||||
})
|
||||
.optional(),
|
||||
});
|
||||
|
||||
interface BasePeriodFormProps {
|
||||
onSubmit: (data: PeriodBindingModel) => void;
|
||||
schema: z.ZodType<BaseFormValues | EditFormValues>;
|
||||
defaultValues?: Partial<BaseFormValues | EditFormValues>;
|
||||
}
|
||||
|
||||
const BasePeriodForm = ({
|
||||
onSubmit,
|
||||
schema,
|
||||
defaultValues,
|
||||
}: BasePeriodFormProps): React.JSX.Element => {
|
||||
const form = useForm<BaseFormValues | EditFormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
id: defaultValues?.id || '',
|
||||
startTime: defaultValues?.startTime || new Date(),
|
||||
endTime: defaultValues?.endTime || new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (defaultValues) {
|
||||
form.reset({
|
||||
id: defaultValues.id || '',
|
||||
startTime: defaultValues.startTime || new Date(),
|
||||
endTime: defaultValues.endTime || new Date(),
|
||||
});
|
||||
}
|
||||
}, [defaultValues, form]);
|
||||
|
||||
const storekeeper = useAuthStore((store) => store.user);
|
||||
|
||||
const handleSubmit = (data: BaseFormValues | EditFormValues) => {
|
||||
const payload: PeriodBindingModel = {
|
||||
id: data.id || crypto.randomUUID(),
|
||||
storekeeperId: storekeeper?.id,
|
||||
startTime:
|
||||
'startTime' in data && data.startTime !== undefined
|
||||
? data.startTime
|
||||
: new Date(),
|
||||
endTime:
|
||||
'endTime' in data && data.endTime !== undefined
|
||||
? data.endTime
|
||||
: new Date(),
|
||||
};
|
||||
|
||||
onSubmit(payload);
|
||||
};
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(handleSubmit)}
|
||||
className="space-y-4 max-w-md mx-auto p-4"
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="id"
|
||||
render={({ field }) => <input type="hidden" {...field} />}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="startTime"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-col">
|
||||
<FormLabel>Время начала</FormLabel>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<FormControl>
|
||||
<Button
|
||||
variant={'outline'}
|
||||
className={cn(
|
||||
'w-full pl-3 text-left font-normal',
|
||||
!field.value && 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{field.value ? (
|
||||
format(field.value, 'PPP')
|
||||
) : (
|
||||
<span>Выберите дату</span>
|
||||
)}
|
||||
<CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
|
||||
</Button>
|
||||
</FormControl>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={field.value}
|
||||
onSelect={field.onChange}
|
||||
initialFocus
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="endTime"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-col">
|
||||
<FormLabel>Время окончания</FormLabel>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<FormControl>
|
||||
<Button
|
||||
variant={'outline'}
|
||||
className={cn(
|
||||
'w-full pl-3 text-left font-normal',
|
||||
!field.value && 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{field.value ? (
|
||||
format(field.value, 'PPP')
|
||||
) : (
|
||||
<span>Выберите дату</span>
|
||||
)}
|
||||
<CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
|
||||
</Button>
|
||||
</FormControl>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={field.value}
|
||||
onSelect={field.onChange}
|
||||
initialFocus
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<Button type="submit" className="w-full">
|
||||
Сохранить
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
|
||||
export const PeriodFormAdd = ({
|
||||
onSubmit,
|
||||
}: {
|
||||
onSubmit: (data: PeriodBindingModel) => void;
|
||||
}): React.JSX.Element => {
|
||||
return <BasePeriodForm onSubmit={onSubmit} schema={addSchema} />;
|
||||
};
|
||||
|
||||
export const PeriodFormEdit = ({
|
||||
onSubmit,
|
||||
defaultValues,
|
||||
}: {
|
||||
onSubmit: (data: PeriodBindingModel) => void;
|
||||
defaultValues: Partial<BaseFormValues>;
|
||||
}): React.JSX.Element => {
|
||||
return (
|
||||
<BasePeriodForm
|
||||
onSubmit={onSubmit}
|
||||
schema={editSchema}
|
||||
defaultValues={defaultValues}
|
||||
/>
|
||||
);
|
||||
};
|
||||
180
TheBank/bankui/src/components/features/ProfileForm.tsx
Normal file
180
TheBank/bankui/src/components/features/ProfileForm.tsx
Normal file
@@ -0,0 +1,180 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { StorekeeperBindingModel } from '@/types/types';
|
||||
|
||||
// Схема для редактирования профиля (все поля опциональны)
|
||||
const profileEditSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
surname: z.string().optional(),
|
||||
middleName: z.string().optional(),
|
||||
login: z.string().optional(),
|
||||
email: z.string().email('Неверный формат email').optional(),
|
||||
phoneNumber: z.string().optional(),
|
||||
// Пароль, вероятно, должен редактироваться отдельно, но добавим опционально
|
||||
password: z.string().optional(),
|
||||
});
|
||||
|
||||
type ProfileFormValues = z.infer<typeof profileEditSchema>;
|
||||
|
||||
interface ProfileFormProps {
|
||||
onSubmit: (data: Partial<StorekeeperBindingModel>) => void;
|
||||
defaultValues: ProfileFormValues;
|
||||
}
|
||||
|
||||
export const ProfileForm = ({
|
||||
onSubmit,
|
||||
defaultValues,
|
||||
}: ProfileFormProps): React.JSX.Element => {
|
||||
const form = useForm<ProfileFormValues>({
|
||||
resolver: zodResolver(profileEditSchema),
|
||||
defaultValues: defaultValues,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (defaultValues) {
|
||||
form.reset(defaultValues);
|
||||
}
|
||||
}, [defaultValues, form]);
|
||||
|
||||
const handleSubmit = (data: ProfileFormValues) => {
|
||||
const changedData: ProfileFormValues = {};
|
||||
(Object.keys(data) as (keyof ProfileFormValues)[]).forEach((key) => {
|
||||
changedData[key] = data[key];
|
||||
if (data[key] !== defaultValues[key]) {
|
||||
changedData[key] = data[key];
|
||||
}
|
||||
});
|
||||
|
||||
if (defaultValues.id) {
|
||||
changedData.id = defaultValues.id;
|
||||
}
|
||||
|
||||
onSubmit(changedData);
|
||||
};
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form
|
||||
onSubmit={form.handleSubmit(handleSubmit)}
|
||||
className="space-y-4 max-w-md mx-auto p-4"
|
||||
>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="id"
|
||||
render={({ field }) => <input type="hidden" {...field} />}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Имя</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Имя" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="surname"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Фамилия</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Фамилия" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="middleName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Отчество</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Отчество" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="login"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Логин</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Логин" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Email" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="phoneNumber"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Номер телефона</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Номер телефона" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
{/* Поле пароля можно добавить здесь, если требуется его редактирование */}
|
||||
{/*
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Новый пароль (оставьте пустым, если не меняете)</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="password" placeholder="Пароль" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
*/}
|
||||
|
||||
<Button type="submit" className="w-full">
|
||||
Сохранить изменения
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
166
TheBank/bankui/src/components/features/RegisterForm.tsx
Normal file
166
TheBank/bankui/src/components/features/RegisterForm.tsx
Normal file
@@ -0,0 +1,166 @@
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { z } from 'zod';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
FormField,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from '@/components/ui/form';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import type { StorekeeperBindingModel } from '@/types/types';
|
||||
|
||||
interface RegisterFormProps {
|
||||
onSubmit: (data: StorekeeperBindingModel) => void;
|
||||
defaultValues?: Partial<StorekeeperBindingModel>;
|
||||
}
|
||||
|
||||
const registerFormSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
name: z.string().min(1, 'Имя обязательно'),
|
||||
surname: z.string().min(1, 'Фамилия обязательна'),
|
||||
middleName: z.string().min(1, 'Отчество обязательно'),
|
||||
login: z.string().min(3, 'Логин должен быть не короче 3 символов'),
|
||||
password: z.string().min(6, 'Пароль должен быть не короче 6 символов'),
|
||||
email: z.string().email('Введите корректный email'),
|
||||
phoneNumber: z.string().min(10, 'Введите корректный номер телефона'),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof registerFormSchema>;
|
||||
|
||||
export const RegisterForm = ({
|
||||
onSubmit,
|
||||
defaultValues,
|
||||
}: RegisterFormProps): React.JSX.Element => {
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(registerFormSchema),
|
||||
defaultValues: {
|
||||
id: defaultValues?.id || crypto.randomUUID(),
|
||||
name: defaultValues?.name || '',
|
||||
surname: defaultValues?.surname || '',
|
||||
middleName: defaultValues?.middleName || '',
|
||||
login: defaultValues?.login || '',
|
||||
password: defaultValues?.password || '',
|
||||
email: defaultValues?.email || '',
|
||||
phoneNumber: defaultValues?.phoneNumber || '',
|
||||
},
|
||||
});
|
||||
|
||||
const handleSubmit = (data: FormValues) => {
|
||||
const payload: StorekeeperBindingModel = {
|
||||
...data,
|
||||
id: data.id || crypto.randomUUID(),
|
||||
};
|
||||
onSubmit(payload);
|
||||
};
|
||||
|
||||
return (
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="id"
|
||||
render={({ field }) => <input type="hidden" {...field} />}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Имя</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Имя" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="surname"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Фамилия</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Фамилия" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="middleName"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Отчество</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Отчество" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="login"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Логин</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Логин" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="password"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Пароль</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="password" placeholder="Пароль" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="email" placeholder="Email" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="phoneNumber"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Номер телефона</FormLabel>
|
||||
<FormControl>
|
||||
<Input placeholder="Номер телефона" {...field} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<Button type="submit" className="w-full">
|
||||
Зарегистрировать
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
);
|
||||
};
|
||||
86
TheBank/bankui/src/components/layout/DataTable.tsx
Normal file
86
TheBank/bankui/src/components/layout/DataTable.tsx
Normal file
@@ -0,0 +1,86 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '../ui/table';
|
||||
import { Checkbox } from '../ui/checkbox';
|
||||
|
||||
type DataTableProps<T> = {
|
||||
data: T[];
|
||||
columns: ColumnDef<T>[];
|
||||
selectedRow?: string;
|
||||
onRowSelected: (id: string | undefined) => void;
|
||||
};
|
||||
|
||||
export type ColumnDef<T> = {
|
||||
accessorKey: keyof T | string;
|
||||
header: string;
|
||||
renderCell?: (item: T) => React.ReactNode;
|
||||
};
|
||||
|
||||
export const DataTable = <T extends {}>({
|
||||
data,
|
||||
columns,
|
||||
selectedRow,
|
||||
onRowSelected,
|
||||
}: DataTableProps<T>): React.JSX.Element => {
|
||||
const handleRowSelect = (id: string) => {
|
||||
onRowSelected(selectedRow === id ? undefined : id);
|
||||
};
|
||||
return (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[50px]"></TableHead>
|
||||
{columns.map((column) => (
|
||||
<TableHead key={column.accessorKey as string}>
|
||||
{column.header}
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{data.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell
|
||||
colSpan={columns.length + 1}
|
||||
className="h-24 text-center"
|
||||
>
|
||||
Нет данных
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
data.map((item, index) => (
|
||||
<TableRow
|
||||
key={(item as any).id || index}
|
||||
data-state={
|
||||
selectedRow === (item as any).id ? 'selected' : undefined
|
||||
}
|
||||
>
|
||||
<TableCell>
|
||||
<Checkbox
|
||||
checked={selectedRow === (item as any).id}
|
||||
onCheckedChange={() => handleRowSelect((item as any).id)}
|
||||
aria-label="Select row"
|
||||
/>
|
||||
</TableCell>
|
||||
{columns.map((column) => (
|
||||
<TableCell key={column.accessorKey as string}>
|
||||
{column.renderCell
|
||||
? column.renderCell(item)
|
||||
: (item as any)[column.accessorKey] ?? 'N/A'}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
44
TheBank/bankui/src/components/layout/DialogForm.tsx
Normal file
44
TheBank/bankui/src/components/layout/DialogForm.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '../ui/dialog';
|
||||
|
||||
type DialogFormProps<T> = {
|
||||
children: React.ReactElement<{ onSubmit: (data: T) => void }>;
|
||||
title: string;
|
||||
description: string;
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSubmit: (data: T) => void;
|
||||
};
|
||||
|
||||
export const DialogForm = <T,>({
|
||||
title,
|
||||
description,
|
||||
children,
|
||||
isOpen,
|
||||
onClose,
|
||||
onSubmit,
|
||||
}: DialogFormProps<T>): React.JSX.Element => {
|
||||
console.log(onSubmit);
|
||||
const wrappedSubmit = (data: T) => {
|
||||
onSubmit(data);
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
<DialogDescription>{description}</DialogDescription>
|
||||
</DialogHeader>
|
||||
{React.cloneElement(children, { onSubmit: wrappedSubmit })}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
9
TheBank/bankui/src/components/layout/Footer.tsx
Normal file
9
TheBank/bankui/src/components/layout/Footer.tsx
Normal file
@@ -0,0 +1,9 @@
|
||||
import React from 'react';
|
||||
|
||||
export const Footer = (): React.JSX.Element => {
|
||||
return (
|
||||
<footer className="w-full flex border-t border-black shadow-lg p-2">
|
||||
<div className="text-black">Банк "Вы банкрот" 2025</div>
|
||||
</footer>
|
||||
);
|
||||
};
|
||||
164
TheBank/bankui/src/components/layout/Header.tsx
Normal file
164
TheBank/bankui/src/components/layout/Header.tsx
Normal file
@@ -0,0 +1,164 @@
|
||||
import React from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import {
|
||||
Menubar,
|
||||
MenubarContent,
|
||||
MenubarItem,
|
||||
MenubarMenu,
|
||||
MenubarSeparator,
|
||||
MenubarTrigger,
|
||||
} from '../ui/menubar';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '../ui/dropdown-menu';
|
||||
import { Avatar, AvatarFallback } from '../ui/avatar';
|
||||
import { Button } from '../ui/button';
|
||||
import { useAuthStore } from '@/store/workerStore';
|
||||
import { useStorekeepers } from '@/hooks/useStorekeepers';
|
||||
|
||||
type NavOptionValue = {
|
||||
name: string;
|
||||
link: string;
|
||||
id: number;
|
||||
};
|
||||
|
||||
type NavOption = {
|
||||
name: string;
|
||||
options: NavOptionValue[];
|
||||
};
|
||||
|
||||
const navOptions = [
|
||||
{
|
||||
name: 'Валюты',
|
||||
options: [
|
||||
{
|
||||
id: 1,
|
||||
name: 'Просмотреть',
|
||||
link: '/currencies',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Кредитные программы',
|
||||
options: [
|
||||
{
|
||||
id: 1,
|
||||
name: 'Просмотреть',
|
||||
link: '/credit-programs',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Сроки',
|
||||
options: [
|
||||
{
|
||||
id: 1,
|
||||
name: 'Просмотреть',
|
||||
link: '/periods',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Кладовщики',
|
||||
options: [
|
||||
{
|
||||
id: 1,
|
||||
name: 'Просмотреть',
|
||||
link: '/storekeepers',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export const Header = (): React.JSX.Element => {
|
||||
const user = useAuthStore((store) => store.user);
|
||||
const logout = useAuthStore((store) => store.logout);
|
||||
const { logout: serverLogout } = useAuthStore();
|
||||
const loggedOut = () => {
|
||||
serverLogout();
|
||||
logout();
|
||||
};
|
||||
const fullName = `${user?.name ?? ''} ${user?.surname ?? ''}`;
|
||||
return (
|
||||
<header className="flex w-full p-2 justify-between">
|
||||
<nav className="text-black">
|
||||
<Menubar className="flex gap-10">
|
||||
{navOptions.map((item) => (
|
||||
<MenuOption item={item} key={item.name} />
|
||||
))}
|
||||
</Menubar>
|
||||
</nav>
|
||||
<div>
|
||||
<ProfileIcon name={fullName || 'Евгений Эгов'} logout={loggedOut} />
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
};
|
||||
|
||||
const MenuOption = ({ item }: { item: NavOption }) => {
|
||||
return (
|
||||
<MenubarMenu>
|
||||
<MenubarTrigger className="">{item.name}</MenubarTrigger>
|
||||
<MenubarContent className="">
|
||||
{item.options.map((x, i) => (
|
||||
<React.Fragment key={x.id}>
|
||||
{i == 1 && item.options.length > 1 && <MenubarSeparator />}
|
||||
<MenubarItem className="">
|
||||
<Link className="" to={x.link}>
|
||||
{x.name}
|
||||
</Link>
|
||||
</MenubarItem>
|
||||
</React.Fragment>
|
||||
))}
|
||||
<MenubarSeparator />
|
||||
</MenubarContent>
|
||||
</MenubarMenu>
|
||||
);
|
||||
};
|
||||
|
||||
type ProfileIconProps = {
|
||||
name: string;
|
||||
logout: () => void;
|
||||
};
|
||||
|
||||
export const ProfileIcon = ({
|
||||
name,
|
||||
logout,
|
||||
}: ProfileIconProps): React.JSX.Element => {
|
||||
return (
|
||||
<div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Avatar className="h-9 w-9">
|
||||
<AvatarFallback>{name[0]}</AvatarFallback>
|
||||
</Avatar>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-56">
|
||||
<DropdownMenuItem className="font-bold text-lg">
|
||||
{name}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<Link to="/profile" className="block w-full text-left">
|
||||
Профиль
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<Button
|
||||
onClick={logout}
|
||||
variant="outline"
|
||||
className="block w-full text-left"
|
||||
>
|
||||
Выйти
|
||||
</Button>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
64
TheBank/bankui/src/components/layout/Sidebar.tsx
Normal file
64
TheBank/bankui/src/components/layout/Sidebar.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarGroupContent,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarProvider,
|
||||
SidebarTrigger,
|
||||
} from '@/components/ui/sidebar';
|
||||
|
||||
import { Plus, Pencil } from 'lucide-react';
|
||||
|
||||
import { Link } from 'react-router-dom';
|
||||
type SidebarProps = {
|
||||
onAddClick: () => void;
|
||||
onEditClick: () => void;
|
||||
};
|
||||
|
||||
const availableTasks = [
|
||||
{
|
||||
name: 'Добавить',
|
||||
link: '',
|
||||
},
|
||||
{
|
||||
name: 'Редактировать',
|
||||
link: '',
|
||||
},
|
||||
];
|
||||
|
||||
export const AppSidebar = ({
|
||||
onAddClick,
|
||||
onEditClick,
|
||||
}: SidebarProps): React.JSX.Element => {
|
||||
return (
|
||||
<SidebarProvider>
|
||||
<Sidebar variant="floating" collapsible="icon">
|
||||
<SidebarTrigger />
|
||||
<SidebarContent />
|
||||
<SidebarGroupContent className="">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton asChild onClick={onAddClick}>
|
||||
<Link to={availableTasks[0].link}>
|
||||
<Plus />
|
||||
<span>{availableTasks[0].name}</span>
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton asChild onClick={onEditClick}>
|
||||
<Link to={availableTasks[1].link}>
|
||||
<Pencil />
|
||||
<span>{availableTasks[1].name}</span>
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</Sidebar>
|
||||
</SidebarProvider>
|
||||
);
|
||||
};
|
||||
76
TheBank/bankui/src/components/pages/AuthStorekeeper.tsx
Normal file
76
TheBank/bankui/src/components/pages/AuthStorekeeper.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import { useStorekeepers } from '@/hooks/useStorekeepers';
|
||||
import React from 'react';
|
||||
import { Tabs, TabsList, TabsTrigger, TabsContent } from '../ui/tabs';
|
||||
import { RegisterForm } from '../features/RegisterForm';
|
||||
import { LoginForm } from '../features/LoginForm';
|
||||
import { toast } from 'sonner';
|
||||
import type { LoginBindingModel, StorekeeperBindingModel } from '@/types/types';
|
||||
|
||||
type Forms = 'login' | 'register';
|
||||
|
||||
export const AuthStorekeeper = (): React.JSX.Element => {
|
||||
const {
|
||||
createStorekeeper,
|
||||
loginStorekeeper,
|
||||
isLoginError,
|
||||
loginError,
|
||||
isCreateError,
|
||||
} = useStorekeepers();
|
||||
|
||||
const [currentForm, setCurrentForm] = React.useState<Forms>('login');
|
||||
|
||||
const handleRegister = (data: StorekeeperBindingModel) => {
|
||||
createStorekeeper(data, {
|
||||
onSuccess: () => {
|
||||
toast('Регистрация успешна! Войдите в систему.');
|
||||
},
|
||||
onError: (error) => {
|
||||
toast(`Ошибка регистрации: ${error.message}`);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handleLogin = (data: LoginBindingModel) => {
|
||||
loginStorekeeper(data);
|
||||
};
|
||||
|
||||
React.useEffect(() => {
|
||||
if (isLoginError) {
|
||||
toast(`Ошибка входа: ${loginError?.message}`);
|
||||
}
|
||||
if (isCreateError) {
|
||||
toast('Ошибка при регистрации');
|
||||
}
|
||||
}, [isLoginError, loginError, isCreateError]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<main className="flex flex-col justify-center items-center">
|
||||
<div>
|
||||
<Tabs defaultValue="login" className="w-[400px]">
|
||||
<TabsList>
|
||||
<TabsTrigger
|
||||
onClick={() => setCurrentForm('login')}
|
||||
value="login"
|
||||
>
|
||||
Вход
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
onClick={() => setCurrentForm('register')}
|
||||
value="register"
|
||||
>
|
||||
Регистрация
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value={currentForm}>
|
||||
<LoginForm onSubmit={handleLogin} />
|
||||
</TabsContent>
|
||||
<TabsContent value="register">
|
||||
<RegisterForm onSubmit={handleRegister} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
};
|
||||
181
TheBank/bankui/src/components/pages/CreditPrograms.tsx
Normal file
181
TheBank/bankui/src/components/pages/CreditPrograms.tsx
Normal file
@@ -0,0 +1,181 @@
|
||||
import React from 'react';
|
||||
import { AppSidebar } from '../layout/Sidebar';
|
||||
import { useCreditPrograms } from '@/hooks/useCreditPrograms';
|
||||
import { DialogForm } from '../layout/DialogForm';
|
||||
import { DataTable } from '../layout/DataTable';
|
||||
import {
|
||||
CreditProgramFormAdd,
|
||||
CreditProgramFormEdit,
|
||||
} from '../features/CreditProgramForm';
|
||||
import type { CreditProgramBindingModel } from '@/types/types';
|
||||
import type { ColumnDef } from '../layout/DataTable';
|
||||
import { toast } from 'sonner';
|
||||
import { usePeriods } from '@/hooks/usePeriods';
|
||||
import { useStorekeepers } from '@/hooks/useStorekeepers';
|
||||
|
||||
interface CreditProgramTableData extends CreditProgramBindingModel {
|
||||
formattedPeriod: string;
|
||||
storekeeperFullName: string;
|
||||
}
|
||||
|
||||
const columns: ColumnDef<CreditProgramTableData>[] = [
|
||||
{
|
||||
accessorKey: 'id',
|
||||
header: 'ID',
|
||||
},
|
||||
{
|
||||
accessorKey: 'name',
|
||||
header: 'Название',
|
||||
},
|
||||
{
|
||||
accessorKey: 'cost',
|
||||
header: 'Стоимость',
|
||||
},
|
||||
{
|
||||
accessorKey: 'maxCost',
|
||||
header: 'Макс. стоимость',
|
||||
},
|
||||
{
|
||||
accessorKey: 'storekeeperFullName',
|
||||
header: 'Кладовщик',
|
||||
},
|
||||
{
|
||||
accessorKey: 'formattedPeriod',
|
||||
header: 'Период',
|
||||
},
|
||||
];
|
||||
|
||||
export const CreditPrograms = (): React.JSX.Element => {
|
||||
const {
|
||||
isLoading,
|
||||
isError,
|
||||
error,
|
||||
creditPrograms,
|
||||
createCreditProgram,
|
||||
updateCreditProgram,
|
||||
} = useCreditPrograms();
|
||||
const { periods } = usePeriods();
|
||||
const { storekeepers } = useStorekeepers();
|
||||
|
||||
const finalData = React.useMemo(() => {
|
||||
if (!creditPrograms || !periods || !storekeepers) return [];
|
||||
|
||||
return creditPrograms.map((program) => {
|
||||
const period = periods?.find((p) => p.id === program.periodId);
|
||||
const storekeeper = storekeepers?.find(
|
||||
(s) => s.id === program.storekeeperId,
|
||||
);
|
||||
|
||||
const formattedPeriod = period
|
||||
? `${new Date(period.startTime).toLocaleDateString()} - ${new Date(
|
||||
period.endTime,
|
||||
).toLocaleDateString()}`
|
||||
: 'Неизвестный период';
|
||||
|
||||
const storekeeperFullName = storekeeper
|
||||
? [storekeeper.surname, storekeeper.name, storekeeper.middleName]
|
||||
.filter(Boolean)
|
||||
.join(' ') || 'Неизвестный кладовщик'
|
||||
: 'Неизвестный кладовщик';
|
||||
|
||||
return {
|
||||
...program,
|
||||
formattedPeriod,
|
||||
storekeeperFullName,
|
||||
};
|
||||
});
|
||||
}, [creditPrograms, periods, storekeepers]);
|
||||
|
||||
const [isAddDialogOpen, setIsAddDialogOpen] = React.useState<boolean>(false);
|
||||
const [isEditDialogOpen, setIsEditDialogOpen] =
|
||||
React.useState<boolean>(false);
|
||||
const [selectedItem, setSelectedItem] = React.useState<
|
||||
CreditProgramBindingModel | undefined
|
||||
>();
|
||||
|
||||
const handleAdd = (data: CreditProgramBindingModel) => {
|
||||
createCreditProgram(data);
|
||||
setIsAddDialogOpen(false);
|
||||
};
|
||||
|
||||
const handleEdit = (data: CreditProgramBindingModel) => {
|
||||
if (selectedItem) {
|
||||
updateCreditProgram({
|
||||
...selectedItem,
|
||||
...data,
|
||||
});
|
||||
setIsEditDialogOpen(false);
|
||||
setSelectedItem(undefined);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelectItem = (id: string | undefined) => {
|
||||
const item = creditPrograms?.find((cp) => cp.id === id);
|
||||
setSelectedItem(item);
|
||||
};
|
||||
|
||||
const openEditForm = () => {
|
||||
if (!selectedItem) {
|
||||
toast('Выберите элемент для редактирования');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsEditDialogOpen(true);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <main className="container mx-auto py-10">Загрузка...</main>;
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<main className="container mx-auto py-10">
|
||||
Ошибка загрузки: {error?.message}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex-1 flex relative">
|
||||
<AppSidebar
|
||||
onAddClick={() => {
|
||||
setIsAddDialogOpen(true);
|
||||
}}
|
||||
onEditClick={() => {
|
||||
openEditForm();
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className="flex-1 p-4">
|
||||
<DialogForm<CreditProgramBindingModel>
|
||||
title="Форма кредитной программы"
|
||||
description="Добавить новую кредитную программу"
|
||||
isOpen={isAddDialogOpen}
|
||||
onClose={() => setIsAddDialogOpen(false)}
|
||||
onSubmit={handleAdd}
|
||||
>
|
||||
<CreditProgramFormAdd />
|
||||
</DialogForm>
|
||||
{selectedItem && (
|
||||
<DialogForm<CreditProgramBindingModel>
|
||||
title="Форма кредитной программы"
|
||||
description="Изменить кредитную программу"
|
||||
isOpen={isEditDialogOpen}
|
||||
onClose={() => setIsEditDialogOpen(false)}
|
||||
onSubmit={handleEdit}
|
||||
>
|
||||
<CreditProgramFormEdit defaultValues={selectedItem} />
|
||||
</DialogForm>
|
||||
)}
|
||||
<div className="">
|
||||
<DataTable
|
||||
data={finalData}
|
||||
columns={columns}
|
||||
onRowSelected={(id) => handleSelectItem(id)}
|
||||
selectedRow={selectedItem?.id}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
160
TheBank/bankui/src/components/pages/Currencies.tsx
Normal file
160
TheBank/bankui/src/components/pages/Currencies.tsx
Normal file
@@ -0,0 +1,160 @@
|
||||
import React from 'react';
|
||||
import { AppSidebar } from '../layout/Sidebar';
|
||||
import { DialogForm } from '../layout/DialogForm';
|
||||
import { DataTable } from '../layout/DataTable';
|
||||
import { useCurrencies } from '@/hooks/useCurrencies';
|
||||
import { useStorekeepers } from '@/hooks/useStorekeepers';
|
||||
import type { CurrencyBindingModel } from '@/types/types';
|
||||
import type { ColumnDef } from '../layout/DataTable';
|
||||
import { CurrencyFormAdd, CurrencyFormEdit } from '../features/CurrencyForm';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
interface CurrencyTableData extends CurrencyBindingModel {
|
||||
storekeeperName: string;
|
||||
}
|
||||
|
||||
const columns: ColumnDef<CurrencyTableData>[] = [
|
||||
{
|
||||
accessorKey: 'id',
|
||||
header: 'ID',
|
||||
},
|
||||
{
|
||||
accessorKey: 'name',
|
||||
header: 'Название',
|
||||
},
|
||||
{
|
||||
accessorKey: 'abbreviation',
|
||||
header: 'Аббревиатура',
|
||||
},
|
||||
{
|
||||
accessorKey: 'cost',
|
||||
header: 'Стоимость',
|
||||
},
|
||||
{
|
||||
accessorKey: 'storekeeperName',
|
||||
header: 'Кладовщик',
|
||||
},
|
||||
];
|
||||
|
||||
export const Currencies = (): React.JSX.Element => {
|
||||
const {
|
||||
isLoading,
|
||||
isError,
|
||||
error,
|
||||
currencies,
|
||||
createCurrency,
|
||||
updateCurrency,
|
||||
} = useCurrencies();
|
||||
const { storekeepers } = useStorekeepers();
|
||||
|
||||
const finalData = React.useMemo(() => {
|
||||
if (!currencies || !storekeepers) return [];
|
||||
|
||||
return currencies.map((currency) => {
|
||||
const storekeeper = storekeepers.find(
|
||||
(s) => s.id === currency.storekeeperId,
|
||||
);
|
||||
const storekeeperName = storekeeper
|
||||
? [storekeeper.surname, storekeeper.name, storekeeper.middleName]
|
||||
.filter(Boolean)
|
||||
.join(' ') || 'Неизвестный кладовщик'
|
||||
: 'Неизвестный кладовщик';
|
||||
|
||||
return {
|
||||
...currency,
|
||||
storekeeperName,
|
||||
};
|
||||
});
|
||||
}, [currencies, storekeepers]);
|
||||
|
||||
const [isAddDialogOpen, setIsAddDialogOpen] = React.useState<boolean>(false);
|
||||
const [isEditDialogOpen, setIsEditDialogOpen] =
|
||||
React.useState<boolean>(false);
|
||||
const [selectedItem, setSelectedItem] = React.useState<
|
||||
CurrencyBindingModel | undefined
|
||||
>();
|
||||
|
||||
const handleAdd = (data: CurrencyBindingModel) => {
|
||||
createCurrency(data);
|
||||
setIsAddDialogOpen(false);
|
||||
};
|
||||
|
||||
const handleEdit = (data: CurrencyBindingModel) => {
|
||||
if (selectedItem) {
|
||||
updateCurrency({
|
||||
...selectedItem,
|
||||
...data,
|
||||
});
|
||||
setIsEditDialogOpen(false);
|
||||
setSelectedItem(undefined);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelectItem = (id: string | undefined) => {
|
||||
const item = currencies?.find((c) => c.id === id);
|
||||
setSelectedItem(item);
|
||||
};
|
||||
|
||||
const openEditForm = () => {
|
||||
if (!selectedItem) {
|
||||
toast('Выберите элемент для редактирования');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsEditDialogOpen(true);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <main className="container mx-auto py-10">Загрузка...</main>;
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<main className="container mx-auto py-10">
|
||||
Ошибка загрузки: {error?.message}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex-1 flex relative">
|
||||
<AppSidebar
|
||||
onAddClick={() => {
|
||||
setIsAddDialogOpen(true);
|
||||
}}
|
||||
onEditClick={() => {
|
||||
openEditForm();
|
||||
}}
|
||||
/>
|
||||
<div className="flex-1 p-4">
|
||||
<DialogForm<CurrencyBindingModel>
|
||||
title="Форма валюты"
|
||||
description="Добавьте новую валюту"
|
||||
isOpen={isAddDialogOpen}
|
||||
onClose={() => setIsAddDialogOpen(false)}
|
||||
>
|
||||
<CurrencyFormAdd onSubmit={handleAdd} />
|
||||
</DialogForm>
|
||||
{selectedItem && (
|
||||
<DialogForm<CurrencyBindingModel>
|
||||
title="Форма валюты"
|
||||
description="Измените валюту"
|
||||
isOpen={isEditDialogOpen}
|
||||
onClose={() => setIsEditDialogOpen(false)}
|
||||
onSubmit={handleEdit}
|
||||
>
|
||||
<CurrencyFormEdit defaultValues={selectedItem} />
|
||||
</DialogForm>
|
||||
)}
|
||||
<div>
|
||||
<DataTable
|
||||
data={finalData}
|
||||
columns={columns}
|
||||
onRowSelected={(id) => handleSelectItem(id)}
|
||||
selectedRow={selectedItem?.id}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
166
TheBank/bankui/src/components/pages/Periods.tsx
Normal file
166
TheBank/bankui/src/components/pages/Periods.tsx
Normal file
@@ -0,0 +1,166 @@
|
||||
import React from 'react';
|
||||
import { AppSidebar } from '../layout/Sidebar';
|
||||
import { DialogForm } from '../layout/DialogForm';
|
||||
import { DataTable } from '../layout/DataTable';
|
||||
import { usePeriods } from '@/hooks/usePeriods';
|
||||
import { useStorekeepers } from '@/hooks/useStorekeepers';
|
||||
import type { PeriodBindingModel } from '@/types/types';
|
||||
import type { ColumnDef } from '../layout/DataTable';
|
||||
import { PeriodFormAdd, PeriodFormEdit } from '../features/PeriodForm';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
interface PeriodTableData extends PeriodBindingModel {
|
||||
storekeeperName: string;
|
||||
}
|
||||
|
||||
const columns: ColumnDef<PeriodTableData>[] = [
|
||||
{
|
||||
accessorKey: 'id',
|
||||
header: 'ID',
|
||||
},
|
||||
{
|
||||
accessorKey: 'startTime',
|
||||
header: 'Время начала',
|
||||
renderCell: (item) => new Date(item.startTime).toLocaleDateString(),
|
||||
},
|
||||
{
|
||||
accessorKey: 'endTime',
|
||||
header: 'Время окончания',
|
||||
renderCell: (item) => new Date(item.endTime).toLocaleDateString(),
|
||||
},
|
||||
{
|
||||
accessorKey: 'storekeeperName',
|
||||
header: 'Кладовщик',
|
||||
},
|
||||
];
|
||||
|
||||
export const Periods = (): React.JSX.Element => {
|
||||
const { isLoading, isError, error, periods, createPeriod, updatePeriod } =
|
||||
usePeriods();
|
||||
const { storekeepers } = useStorekeepers();
|
||||
|
||||
const finalData = React.useMemo(() => {
|
||||
if (!periods || !storekeepers) return [];
|
||||
|
||||
return periods.map((period) => {
|
||||
const storekeeper = storekeepers.find(
|
||||
(s) => s.id === period.storekeeperId,
|
||||
);
|
||||
const storekeeperName = storekeeper
|
||||
? [storekeeper.surname, storekeeper.name, storekeeper.middleName]
|
||||
.filter(Boolean)
|
||||
.join(' ') || 'Неизвестный кладовщик'
|
||||
: 'Неизвестный кладовщик';
|
||||
|
||||
return {
|
||||
...period,
|
||||
storekeeperName,
|
||||
};
|
||||
});
|
||||
}, [periods, storekeepers]);
|
||||
|
||||
const [isAddDialogOpen, setIsAddDialogOpen] = React.useState<boolean>(false);
|
||||
const [isEditDialogOpen, setIsEditDialogOpen] =
|
||||
React.useState<boolean>(false);
|
||||
const [selectedItem, setSelectedItem] = React.useState<
|
||||
PeriodBindingModel | undefined
|
||||
>();
|
||||
|
||||
const handleAdd = (data: PeriodBindingModel) => {
|
||||
createPeriod(data);
|
||||
setIsAddDialogOpen(false);
|
||||
};
|
||||
|
||||
const handleEdit = (data: PeriodBindingModel) => {
|
||||
if (selectedItem) {
|
||||
updatePeriod({
|
||||
...selectedItem,
|
||||
...data,
|
||||
});
|
||||
setIsEditDialogOpen(false);
|
||||
setSelectedItem(undefined);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelectItem = (id: string | undefined) => {
|
||||
const item = periods?.find((p) => p.id === id);
|
||||
if (item) {
|
||||
setSelectedItem({
|
||||
...item,
|
||||
startTime: new Date(item.startTime),
|
||||
endTime: new Date(item.endTime),
|
||||
});
|
||||
} else {
|
||||
setSelectedItem(undefined);
|
||||
}
|
||||
};
|
||||
|
||||
const openEditForm = () => {
|
||||
if (!selectedItem) {
|
||||
toast('Выберите элемент для редактирования');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsEditDialogOpen(true);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <main className="container mx-auto py-10">Загрузка...</main>;
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return (
|
||||
<main className="container mx-auto py-10">
|
||||
Ошибка загрузки: {error?.message}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="flex-1 flex relative">
|
||||
<AppSidebar
|
||||
onAddClick={() => {
|
||||
setIsAddDialogOpen(true);
|
||||
}}
|
||||
onEditClick={() => {
|
||||
openEditForm();
|
||||
}}
|
||||
/>
|
||||
<div className="flex-1 p-4">
|
||||
{!selectedItem &&
|
||||
<DialogForm<PeriodBindingModel>
|
||||
title="Форма сроков"
|
||||
description="Добавить сроки"
|
||||
isOpen={isAddDialogOpen}
|
||||
onClose={() => setIsAddDialogOpen(false)}
|
||||
onSubmit={handleAdd}
|
||||
>
|
||||
<PeriodFormAdd />
|
||||
</DialogForm>
|
||||
|
||||
}
|
||||
{selectedItem && (
|
||||
<DialogForm<PeriodBindingModel>
|
||||
title="Форма сроков"
|
||||
description="Изменить сроки"
|
||||
isOpen={isEditDialogOpen}
|
||||
onClose={() => setIsEditDialogOpen(false)}
|
||||
onSubmit={handleEdit}
|
||||
>
|
||||
<PeriodFormEdit
|
||||
defaultValues={selectedItem}
|
||||
/>
|
||||
</DialogForm>
|
||||
)}
|
||||
<div>
|
||||
<DataTable
|
||||
data={finalData}
|
||||
columns={columns}
|
||||
onRowSelected={(id) => handleSelectItem(id)}
|
||||
selectedRow={selectedItem?.id}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
38
TheBank/bankui/src/components/pages/Profile.tsx
Normal file
38
TheBank/bankui/src/components/pages/Profile.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
import React from 'react';
|
||||
import { useAuthStore } from '@/store/workerStore';
|
||||
import { ProfileForm } from '../features/ProfileForm';
|
||||
import type { StorekeeperBindingModel } from '@/types/types';
|
||||
import { useStorekeepers } from '@/hooks/useStorekeepers';
|
||||
import { toast } from 'sonner';
|
||||
|
||||
export const Profile = (): React.JSX.Element => {
|
||||
const { user, updateUser } = useAuthStore();
|
||||
const { updateStorekeeper, isUpdateError, updateError } = useStorekeepers();
|
||||
|
||||
React.useEffect(() => {
|
||||
if (isUpdateError) {
|
||||
toast(updateError?.message);
|
||||
}
|
||||
}, [isUpdateError, updateError]);
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<main className="container mx-auto py-10">
|
||||
Загрузка данных пользователя...
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
const handleUpdate = (data: Partial<StorekeeperBindingModel>) => {
|
||||
console.log(data);
|
||||
updateUser(data);
|
||||
updateStorekeeper(data);
|
||||
};
|
||||
|
||||
return (
|
||||
<main className="container mx-auto py-10">
|
||||
<h1 className="text-2xl font-bold mb-6">Профиль пользователя</h1>
|
||||
<ProfileForm defaultValues={user} onSubmit={handleUpdate} />
|
||||
</main>
|
||||
);
|
||||
};
|
||||
63
TheBank/bankui/src/components/pages/Storekeepers.tsx
Normal file
63
TheBank/bankui/src/components/pages/Storekeepers.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
import React from 'react';
|
||||
import { DataTable } from '../layout/DataTable';
|
||||
import type { ColumnDef } from '../layout/DataTable';
|
||||
import { useStorekeepers } from '@/hooks/useStorekeepers';
|
||||
import type { StorekeeperBindingModel } from '@/types/types';
|
||||
|
||||
const columns: ColumnDef<StorekeeperBindingModel>[] = [
|
||||
{
|
||||
accessorKey: 'id',
|
||||
header: 'ID',
|
||||
},
|
||||
{
|
||||
accessorKey: 'name',
|
||||
header: 'Имя',
|
||||
},
|
||||
{
|
||||
accessorKey: 'surname',
|
||||
header: 'Фамилия',
|
||||
},
|
||||
{
|
||||
accessorKey: 'middleName',
|
||||
header: 'Отчество',
|
||||
},
|
||||
{
|
||||
accessorKey: 'login',
|
||||
header: 'Логин',
|
||||
},
|
||||
{
|
||||
accessorKey: 'email',
|
||||
header: 'Email',
|
||||
},
|
||||
{
|
||||
accessorKey: 'phoneNumber',
|
||||
header: 'Телефон',
|
||||
},
|
||||
];
|
||||
|
||||
export const Storekeepers = (): React.JSX.Element => {
|
||||
const { storekeepers, isLoading, error } = useStorekeepers();
|
||||
|
||||
if (isLoading) {
|
||||
return <main className="container mx-auto py-10">Загрузка...</main>;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<main className="container mx-auto py-10">
|
||||
Ошибка загрузки данных: {error.message}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="container mx-auto py-10">
|
||||
<h1 className="text-2xl font-bold mb-6">Кладовщики</h1>
|
||||
<DataTable
|
||||
data={storekeepers || []}
|
||||
columns={columns}
|
||||
onRowSelected={console.log}
|
||||
/>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
51
TheBank/bankui/src/components/ui/avatar.tsx
Normal file
51
TheBank/bankui/src/components/ui/avatar.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
import * as React from "react"
|
||||
import * as AvatarPrimitive from "@radix-ui/react-avatar"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Avatar({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
|
||||
return (
|
||||
<AvatarPrimitive.Root
|
||||
data-slot="avatar"
|
||||
className={cn(
|
||||
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarImage({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
||||
return (
|
||||
<AvatarPrimitive.Image
|
||||
data-slot="avatar-image"
|
||||
className={cn("aspect-square size-full", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function AvatarFallback({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
||||
return (
|
||||
<AvatarPrimitive.Fallback
|
||||
data-slot="avatar-fallback"
|
||||
className={cn(
|
||||
"bg-muted flex size-full items-center justify-center rounded-full",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Avatar, AvatarImage, AvatarFallback }
|
||||
59
TheBank/bankui/src/components/ui/button.tsx
Normal file
59
TheBank/bankui/src/components/ui/button.tsx
Normal file
@@ -0,0 +1,59 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
73
TheBank/bankui/src/components/ui/calendar.tsx
Normal file
73
TheBank/bankui/src/components/ui/calendar.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
import * as React from "react"
|
||||
import { ChevronLeft, ChevronRight } from "lucide-react"
|
||||
import { DayPicker } from "react-day-picker"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { buttonVariants } from "@/components/ui/button"
|
||||
|
||||
function Calendar({
|
||||
className,
|
||||
classNames,
|
||||
showOutsideDays = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayPicker>) {
|
||||
return (
|
||||
<DayPicker
|
||||
showOutsideDays={showOutsideDays}
|
||||
className={cn("p-3", className)}
|
||||
classNames={{
|
||||
months: "flex flex-col sm:flex-row gap-2",
|
||||
month: "flex flex-col gap-4",
|
||||
caption: "flex justify-center pt-1 relative items-center w-full",
|
||||
caption_label: "text-sm font-medium",
|
||||
nav: "flex items-center gap-1",
|
||||
nav_button: cn(
|
||||
buttonVariants({ variant: "outline" }),
|
||||
"size-7 bg-transparent p-0 opacity-50 hover:opacity-100"
|
||||
),
|
||||
nav_button_previous: "absolute left-1",
|
||||
nav_button_next: "absolute right-1",
|
||||
table: "w-full border-collapse space-x-1",
|
||||
head_row: "flex",
|
||||
head_cell:
|
||||
"text-muted-foreground rounded-md w-8 font-normal text-[0.8rem]",
|
||||
row: "flex w-full mt-2",
|
||||
cell: cn(
|
||||
"relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-range-end)]:rounded-r-md",
|
||||
props.mode === "range"
|
||||
? "[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md"
|
||||
: "[&:has([aria-selected])]:rounded-md"
|
||||
),
|
||||
day: cn(
|
||||
buttonVariants({ variant: "ghost" }),
|
||||
"size-8 p-0 font-normal aria-selected:opacity-100"
|
||||
),
|
||||
day_range_start:
|
||||
"day-range-start aria-selected:bg-primary aria-selected:text-primary-foreground",
|
||||
day_range_end:
|
||||
"day-range-end aria-selected:bg-primary aria-selected:text-primary-foreground",
|
||||
day_selected:
|
||||
"bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
|
||||
day_today: "bg-accent text-accent-foreground",
|
||||
day_outside:
|
||||
"day-outside text-muted-foreground aria-selected:text-muted-foreground",
|
||||
day_disabled: "text-muted-foreground opacity-50",
|
||||
day_range_middle:
|
||||
"aria-selected:bg-accent aria-selected:text-accent-foreground",
|
||||
day_hidden: "invisible",
|
||||
...classNames,
|
||||
}}
|
||||
components={{
|
||||
IconLeft: ({ className, ...props }) => (
|
||||
<ChevronLeft className={cn("size-4", className)} {...props} />
|
||||
),
|
||||
IconRight: ({ className, ...props }) => (
|
||||
<ChevronRight className={cn("size-4", className)} {...props} />
|
||||
),
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Calendar }
|
||||
30
TheBank/bankui/src/components/ui/checkbox.tsx
Normal file
30
TheBank/bankui/src/components/ui/checkbox.tsx
Normal file
@@ -0,0 +1,30 @@
|
||||
import * as React from "react"
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
import { CheckIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="flex items-center justify-center text-current transition-none"
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
export { Checkbox }
|
||||
133
TheBank/bankui/src/components/ui/dialog.tsx
Normal file
133
TheBank/bankui/src/components/ui/dialog.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
import * as React from "react"
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content>) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
255
TheBank/bankui/src/components/ui/dropdown-menu.tsx
Normal file
255
TheBank/bankui/src/components/ui/dropdown-menu.tsx
Normal file
@@ -0,0 +1,255 @@
|
||||
import * as React from "react"
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
className,
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
data-slot="dropdown-menu-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
}
|
||||
165
TheBank/bankui/src/components/ui/form.tsx
Normal file
165
TheBank/bankui/src/components/ui/form.tsx
Normal file
@@ -0,0 +1,165 @@
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import {
|
||||
Controller,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
useFormState,
|
||||
type ControllerProps,
|
||||
type FieldPath,
|
||||
type FieldValues,
|
||||
} from "react-hook-form"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Label } from "@/components/ui/label"
|
||||
|
||||
const Form = FormProvider
|
||||
|
||||
type FormFieldContextValue<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
> = {
|
||||
name: TName
|
||||
}
|
||||
|
||||
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
||||
{} as FormFieldContextValue
|
||||
)
|
||||
|
||||
const FormField = <
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
>({
|
||||
...props
|
||||
}: ControllerProps<TFieldValues, TName>) => {
|
||||
return (
|
||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||
<Controller {...props} />
|
||||
</FormFieldContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
const useFormField = () => {
|
||||
const fieldContext = React.useContext(FormFieldContext)
|
||||
const itemContext = React.useContext(FormItemContext)
|
||||
const { getFieldState } = useFormContext()
|
||||
const formState = useFormState({ name: fieldContext.name })
|
||||
const fieldState = getFieldState(fieldContext.name, formState)
|
||||
|
||||
if (!fieldContext) {
|
||||
throw new Error("useFormField should be used within <FormField>")
|
||||
}
|
||||
|
||||
const { id } = itemContext
|
||||
|
||||
return {
|
||||
id,
|
||||
name: fieldContext.name,
|
||||
formItemId: `${id}-form-item`,
|
||||
formDescriptionId: `${id}-form-item-description`,
|
||||
formMessageId: `${id}-form-item-message`,
|
||||
...fieldState,
|
||||
}
|
||||
}
|
||||
|
||||
type FormItemContextValue = {
|
||||
id: string
|
||||
}
|
||||
|
||||
const FormItemContext = React.createContext<FormItemContextValue>(
|
||||
{} as FormItemContextValue
|
||||
)
|
||||
|
||||
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const id = React.useId()
|
||||
|
||||
return (
|
||||
<FormItemContext.Provider value={{ id }}>
|
||||
<div
|
||||
data-slot="form-item"
|
||||
className={cn("grid gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
</FormItemContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function FormLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
const { error, formItemId } = useFormField()
|
||||
|
||||
return (
|
||||
<Label
|
||||
data-slot="form-label"
|
||||
data-error={!!error}
|
||||
className={cn("data-[error=true]:text-destructive", className)}
|
||||
htmlFor={formItemId}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
|
||||
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
|
||||
|
||||
return (
|
||||
<Slot
|
||||
data-slot="form-control"
|
||||
id={formItemId}
|
||||
aria-describedby={
|
||||
!error
|
||||
? `${formDescriptionId}`
|
||||
: `${formDescriptionId} ${formMessageId}`
|
||||
}
|
||||
aria-invalid={!!error}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { formDescriptionId } = useFormField()
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-description"
|
||||
id={formDescriptionId}
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { error, formMessageId } = useFormField()
|
||||
const body = error ? String(error?.message ?? "") : props.children
|
||||
|
||||
if (!body) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-message"
|
||||
id={formMessageId}
|
||||
className={cn("text-destructive text-sm", className)}
|
||||
{...props}
|
||||
>
|
||||
{body}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
useFormField,
|
||||
Form,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
FormField,
|
||||
}
|
||||
21
TheBank/bankui/src/components/ui/input.tsx
Normal file
21
TheBank/bankui/src/components/ui/input.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
24
TheBank/bankui/src/components/ui/label.tsx
Normal file
24
TheBank/bankui/src/components/ui/label.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Label({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
274
TheBank/bankui/src/components/ui/menubar.tsx
Normal file
274
TheBank/bankui/src/components/ui/menubar.tsx
Normal file
@@ -0,0 +1,274 @@
|
||||
import * as React from 'react';
|
||||
import * as MenubarPrimitive from '@radix-ui/react-menubar';
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react';
|
||||
|
||||
import { cn } from '../../lib/utils';
|
||||
|
||||
function Menubar({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Root>) {
|
||||
return (
|
||||
<MenubarPrimitive.Root
|
||||
data-slot="menubar"
|
||||
className={cn(
|
||||
'bg-background flex h-9 items-center gap-1 rounded-md border p-1 shadow-xs',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function MenubarMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Menu>) {
|
||||
return <MenubarPrimitive.Menu data-slot="menubar-menu" {...props} />;
|
||||
}
|
||||
|
||||
function MenubarGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Group>) {
|
||||
return <MenubarPrimitive.Group data-slot="menubar-group" {...props} />;
|
||||
}
|
||||
|
||||
function MenubarPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Portal>) {
|
||||
return <MenubarPrimitive.Portal data-slot="menubar-portal" {...props} />;
|
||||
}
|
||||
|
||||
function MenubarRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<MenubarPrimitive.RadioGroup data-slot="menubar-radio-group" {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function MenubarTrigger({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Trigger>) {
|
||||
return (
|
||||
<MenubarPrimitive.Trigger
|
||||
data-slot="menubar-trigger"
|
||||
className={cn(
|
||||
'focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex items-center rounded-sm px-2 py-1 text-sm font-medium outline-hidden select-none',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function MenubarContent({
|
||||
className,
|
||||
align = 'start',
|
||||
alignOffset = -4,
|
||||
sideOffset = 8,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Content>) {
|
||||
return (
|
||||
<MenubarPortal>
|
||||
<MenubarPrimitive.Content
|
||||
data-slot="menubar-content"
|
||||
align={align}
|
||||
alignOffset={alignOffset}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[12rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-md',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</MenubarPortal>
|
||||
);
|
||||
}
|
||||
|
||||
function MenubarItem({
|
||||
className,
|
||||
inset,
|
||||
variant = 'default',
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Item> & {
|
||||
inset?: boolean;
|
||||
variant?: 'default' | 'destructive';
|
||||
}) {
|
||||
return (
|
||||
<MenubarPrimitive.Item
|
||||
data-slot="menubar-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function MenubarCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<MenubarPrimitive.CheckboxItem
|
||||
data-slot="menubar-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<MenubarPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</MenubarPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</MenubarPrimitive.CheckboxItem>
|
||||
);
|
||||
}
|
||||
|
||||
function MenubarRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.RadioItem>) {
|
||||
return (
|
||||
<MenubarPrimitive.RadioItem
|
||||
data-slot="menubar-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-xs py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<MenubarPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</MenubarPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</MenubarPrimitive.RadioItem>
|
||||
);
|
||||
}
|
||||
|
||||
function MenubarLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Label> & {
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<MenubarPrimitive.Label
|
||||
data-slot="menubar-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
'px-2 py-1.5 text-sm font-medium data-[inset]:pl-8',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function MenubarSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Separator>) {
|
||||
return (
|
||||
<MenubarPrimitive.Separator
|
||||
data-slot="menubar-separator"
|
||||
className={cn('bg-border -mx-1 my-1 h-px', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function MenubarShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<'span'>) {
|
||||
return (
|
||||
<span
|
||||
data-slot="menubar-shortcut"
|
||||
className={cn(
|
||||
'text-muted-foreground ml-auto text-xs tracking-widest',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function MenubarSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.Sub>) {
|
||||
return <MenubarPrimitive.Sub data-slot="menubar-sub" {...props} />;
|
||||
}
|
||||
|
||||
function MenubarSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.SubTrigger> & {
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<MenubarPrimitive.SubTrigger
|
||||
data-slot="menubar-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
'focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-none select-none data-[inset]:pl-8',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto h-4 w-4" />
|
||||
</MenubarPrimitive.SubTrigger>
|
||||
);
|
||||
}
|
||||
|
||||
function MenubarSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof MenubarPrimitive.SubContent>) {
|
||||
return (
|
||||
<MenubarPrimitive.SubContent
|
||||
data-slot="menubar-sub-content"
|
||||
className={cn(
|
||||
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-menubar-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Menubar,
|
||||
MenubarPortal,
|
||||
MenubarMenu,
|
||||
MenubarTrigger,
|
||||
MenubarContent,
|
||||
MenubarGroup,
|
||||
MenubarSeparator,
|
||||
MenubarLabel,
|
||||
MenubarItem,
|
||||
MenubarShortcut,
|
||||
MenubarCheckboxItem,
|
||||
MenubarRadioGroup,
|
||||
MenubarRadioItem,
|
||||
MenubarSub,
|
||||
MenubarSubTrigger,
|
||||
MenubarSubContent,
|
||||
};
|
||||
46
TheBank/bankui/src/components/ui/popover.tsx
Normal file
46
TheBank/bankui/src/components/ui/popover.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import * as React from "react"
|
||||
import * as PopoverPrimitive from "@radix-ui/react-popover"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Popover({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
|
||||
return <PopoverPrimitive.Root data-slot="popover" {...props} />
|
||||
}
|
||||
|
||||
function PopoverTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
|
||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
|
||||
}
|
||||
|
||||
function PopoverContent({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||
return (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
data-slot="popover-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function PopoverAnchor({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
|
||||
}
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user