initial commit
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
@page "/account/access-denied"
|
||||
@using Indotalent.Features.Root
|
||||
@using MudBlazor
|
||||
@layout MainLayout
|
||||
|
||||
<PageTitle>Access Denied - Insufficient Permissions</PageTitle>
|
||||
|
||||
<MudContainer MaxWidth="MaxWidth.Medium" Class="d-flex align-center justify-center" Style="height: calc(100vh - 64px);">
|
||||
|
||||
<div class="text-center">
|
||||
|
||||
<MudIcon Icon="@Icons.Material.Filled.GppBad"
|
||||
Size="Size.Large"
|
||||
Color="Color.Error"
|
||||
Class="mb-6"
|
||||
Style="font-size: 120px;" />
|
||||
|
||||
<MudText Typo="Typo.h3" Class="mb-4" Style="font-weight: 800; color: #1a1a1a;">Access Denied</MudText>
|
||||
|
||||
<MudText Typo="Typo.body1" Class="mb-6" Style="color: #64748b;">
|
||||
Sorry, you do not have the required permissions to access this module.<br />
|
||||
This area is restricted to authorized administrative personnel only.
|
||||
</MudText>
|
||||
|
||||
<MudPaper Elevation="1" Class="pa-4 mb-8 d-inline-block" Style="border-radius: 0px; border: 1px solid #DCEBFA;">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">
|
||||
<strong>Error Code:</strong> <code>AGS_AUTH_INSUFFICIENT_PERMISSIONS</code>
|
||||
</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #94a3b8; font-family: 'Consolas', monospace;">
|
||||
Verification failed for the current security context.
|
||||
</MudText>
|
||||
</MudPaper>
|
||||
|
||||
<div class="d-flex align-center justify-center gap-4">
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
Size="Size.Large"
|
||||
OnClick="GoHome"
|
||||
StartIcon="@Icons.Material.Filled.Home"
|
||||
Style="border-radius: 4px; font-weight: 700;">
|
||||
Back to Home
|
||||
</MudButton>
|
||||
|
||||
<MudButton Variant="Variant.Outlined"
|
||||
Color="Color.Default"
|
||||
Size="Size.Large"
|
||||
OnClick="Logout"
|
||||
StartIcon="@Icons.Material.Filled.Logout"
|
||||
Style="border: 1px solid #e0e0e0; border-radius: 4px; font-weight: 700; border: 2px solid #e2e8f0;">
|
||||
Logout & Switch Account
|
||||
</MudButton>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</MudContainer>
|
||||
|
||||
@code {
|
||||
[Inject] private NavigationManager Nav { get; set; } = default!;
|
||||
|
||||
private void GoHome() => Nav.NavigateTo("/");
|
||||
private void Logout() => Nav.NavigateTo("/account/logout");
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
@inject NavigationManager Navigation
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@using Microsoft.AspNetCore.Components.Authorization
|
||||
@attribute [AllowAnonymous]
|
||||
|
||||
<AuthorizeView>
|
||||
<NotAuthorized>
|
||||
@{
|
||||
var returnUrl = Navigation.ToBaseRelativePath(Navigation.Uri);
|
||||
Navigation.NavigateTo($"/account/login?returnUrl={Uri.EscapeDataString(returnUrl)}", forceLoad: false);
|
||||
}
|
||||
</NotAuthorized>
|
||||
<Authorized>
|
||||
@{
|
||||
Navigation.NavigateTo("/account/access-denied");
|
||||
}
|
||||
</Authorized>
|
||||
</AuthorizeView>
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
using Indotalent.ConfigFrontEnd.Service;
|
||||
using Indotalent.Data.Entities;
|
||||
using Indotalent.Features.Account.ForgotPassword.Cqrs;
|
||||
using Indotalent.Features.Account.Login.Cqrs;
|
||||
using Indotalent.Features.Account.Register.Cqrs;
|
||||
using Indotalent.Features.Account.ResetPassword.Cqrs;
|
||||
using Indotalent.Features.Account.TenantSelection.Cqrs;
|
||||
using Indotalent.Infrastructure.Authentication.Identity;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Indotalent.Features.Account;
|
||||
|
||||
public static class AccountEndPoint
|
||||
{
|
||||
public static IEndpointConventionBuilder MapAccountEndpoints(this IEndpointRouteBuilder endpoints)
|
||||
{
|
||||
var group = endpoints.MapGroup("/account").WithTags("Account");
|
||||
|
||||
group.MapPost("/signin-sso", async ([FromQuery] string email, UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IOptions<JwtSettingsModel> jwtOptions, HttpContext context) =>
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(email)) return Results.Json(new { status = 401, title = "Email is required" }, statusCode: 401);
|
||||
|
||||
var user = await userManager.FindByEmailAsync(email);
|
||||
|
||||
if (user == null || !user.IsActive)
|
||||
{
|
||||
return Results.Json(new { status = 401, title = "Account not found or inactive" }, statusCode: 401);
|
||||
}
|
||||
|
||||
var jwtSettings = jwtOptions.Value;
|
||||
var token = JwtService.GenerateNewJwt(user, jwtSettings);
|
||||
var refreshToken = Guid.NewGuid().ToString().Replace("-", "");
|
||||
|
||||
user.RefreshToken = refreshToken;
|
||||
user.LastLoginAt = DateTime.Now;
|
||||
await userManager.UpdateAsync(user);
|
||||
|
||||
await signInManager.SignInAsync(user, isPersistent: true);
|
||||
|
||||
context.Response.Cookies.Append("X-Auth-Token", token, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = true,
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Expires = DateTimeOffset.UtcNow.AddDays(1)
|
||||
});
|
||||
|
||||
context.Response.Cookies.Append("X-Refresh-Token", refreshToken, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = true,
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Expires = DateTimeOffset.UtcNow.AddDays(7)
|
||||
});
|
||||
|
||||
return Results.Ok(new { status = 200, title = "SSO Login successful" });
|
||||
});
|
||||
|
||||
group.MapGet("/active-user-exists", async ([FromQuery] string email, UserManager<ApplicationUser> userManager) =>
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(email))
|
||||
{
|
||||
return Results.Ok(new { exists = false, isActive = false });
|
||||
}
|
||||
|
||||
var user = await userManager.FindByEmailAsync(email);
|
||||
|
||||
if (user == null)
|
||||
{
|
||||
return Results.Ok(new { exists = false, isActive = false });
|
||||
}
|
||||
|
||||
return Results.Ok(new { exists = true, isActive = user.IsActive });
|
||||
});
|
||||
|
||||
group.MapPost("/signin", async ([FromBody] LoginRequest request, IMediator mediator, HttpContext context, UserManager<ApplicationUser> userManager) =>
|
||||
{
|
||||
var command = new LoginCommand(request);
|
||||
var response = await mediator.Send(command);
|
||||
|
||||
if (response.Succeeded)
|
||||
{
|
||||
var user = await userManager.FindByEmailAsync(request.Email);
|
||||
|
||||
if (user != null)
|
||||
{
|
||||
context.Response.Cookies.Append("X-Auth-Token", response.Token!, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = true,
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Expires = DateTimeOffset.UtcNow.AddDays(1)
|
||||
});
|
||||
|
||||
context.Response.Cookies.Append("X-Refresh-Token", user.RefreshToken!, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = true,
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Expires = DateTimeOffset.UtcNow.AddDays(7)
|
||||
});
|
||||
}
|
||||
|
||||
return Results.Ok(new { status = 200, title = response.Message });
|
||||
}
|
||||
return Results.Json(new { status = 401, title = response.Message }, statusCode: 401);
|
||||
});
|
||||
|
||||
|
||||
|
||||
group.MapPost("/refresh-token", async (HttpContext context) =>
|
||||
{
|
||||
var userManager = context.RequestServices.GetRequiredService<UserManager<ApplicationUser>>();
|
||||
var jwtSettings = context.RequestServices.GetRequiredService<IOptions<JwtSettingsModel>>().Value;
|
||||
|
||||
var refreshToken = context.Request.Headers["X-Refresh-Token"].ToString();
|
||||
|
||||
if (string.IsNullOrEmpty(refreshToken)) return Results.Unauthorized();
|
||||
|
||||
var user = await userManager.Users.FirstOrDefaultAsync(u => u.RefreshToken == refreshToken);
|
||||
|
||||
if (user == null || !user.IsActive) return Results.Unauthorized();
|
||||
|
||||
var newToken = JwtService.GenerateNewJwt(user, jwtSettings);
|
||||
|
||||
context.Response.Cookies.Append("X-Auth-Token", newToken, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = true,
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Expires = DateTimeOffset.UtcNow.AddDays(1)
|
||||
});
|
||||
|
||||
return Results.Ok(new LoginResponse { Succeeded = true, Token = newToken });
|
||||
});
|
||||
|
||||
group.MapPost("/signup", async ([FromBody] CreateUserRequest request, IMediator mediator) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var command = new CreateUserCommand(request);
|
||||
var response = await mediator.Send(command);
|
||||
return Results.Ok(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Results.BadRequest(new { errors = new[] { ex.Message } });
|
||||
}
|
||||
});
|
||||
|
||||
group.MapPost("/signout", async (
|
||||
SignInManager<ApplicationUser> signInManager,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
HttpContext context) =>
|
||||
{
|
||||
var userId = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
|
||||
if (!string.IsNullOrEmpty(userId))
|
||||
{
|
||||
var user = await userManager.FindByIdAsync(userId);
|
||||
if (user != null)
|
||||
{
|
||||
user.RefreshToken = null;
|
||||
await userManager.UpdateAsync(user);
|
||||
}
|
||||
}
|
||||
|
||||
await signInManager.SignOutAsync();
|
||||
|
||||
context.Response.Cookies.Delete("X-Auth-Token");
|
||||
context.Response.Cookies.Delete("X-Refresh-Token");
|
||||
|
||||
return Results.Ok(new { status = 200, title = "Successfully signed out" });
|
||||
|
||||
});
|
||||
|
||||
group.MapPost("/forgot-password", async ([FromBody] ForgotPasswordRequest request, IMediator mediator) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var command = new ForgotPasswordCommand(request);
|
||||
var response = await mediator.Send(command);
|
||||
return Results.Ok(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Results.BadRequest(new { errors = new[] { ex.Message } });
|
||||
}
|
||||
});
|
||||
|
||||
group.MapPost("/logout", async (SignInManager<ApplicationUser> signInManager) =>
|
||||
{
|
||||
await signInManager.SignOutAsync();
|
||||
return Results.Ok(new { title = "Success user logout" });
|
||||
}).RequireAuthorization();
|
||||
|
||||
group.MapPost("/reset-password", async ([FromBody] ResetPasswordRequest request, IMediator mediator) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
var command = new ResetPasswordCommand(request);
|
||||
var response = await mediator.Send(command);
|
||||
return Results.Ok(response);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Results.BadRequest(new { errors = new[] { ex.Message } });
|
||||
}
|
||||
});
|
||||
|
||||
group.MapGet("/my-tenants", async (IMediator mediator, HttpContext context) =>
|
||||
{
|
||||
var userId = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (string.IsNullOrEmpty(userId)) return Results.Unauthorized();
|
||||
|
||||
var query = new GetTenantsQuery(userId);
|
||||
var response = await mediator.Send(query);
|
||||
return Results.Ok(response);
|
||||
}).RequireAuthorization();
|
||||
|
||||
group.MapPost("/confirm-tenant", async (
|
||||
[FromBody] ConfirmTenantRequest request,
|
||||
IMediator mediator,
|
||||
HttpContext context,
|
||||
SignInManager<ApplicationUser> signInManager,
|
||||
UserManager<ApplicationUser> userManager) =>
|
||||
{
|
||||
var userId = context.User.FindFirstValue(ClaimTypes.NameIdentifier);
|
||||
if (string.IsNullOrEmpty(userId)) return Results.Unauthorized();
|
||||
|
||||
var command = new ConfirmTenantCommand(userId, request);
|
||||
var response = await mediator.Send(command);
|
||||
|
||||
if (!response.Success)
|
||||
{
|
||||
return Results.Json(new { success = false, title = response.Message }, statusCode: 400);
|
||||
}
|
||||
|
||||
var user = await userManager.FindByIdAsync(userId);
|
||||
if (user == null) return Results.Unauthorized();
|
||||
|
||||
var principal = await signInManager.CreateUserPrincipalAsync(user);
|
||||
var identity = (ClaimsIdentity?)principal.Identity;
|
||||
|
||||
if (identity != null)
|
||||
{
|
||||
identity.AddClaim(new Claim(ClaimTypes.GroupSid, request.TenantId));
|
||||
var jwtClaims = new List<Claim>
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, user.Id ?? string.Empty),
|
||||
new Claim(ClaimTypes.Name, user.UserName ?? string.Empty),
|
||||
new Claim(ClaimTypes.Email, user.Email ?? string.Empty),
|
||||
new Claim(ClaimTypes.GivenName, user.FullName ?? string.Empty),
|
||||
new Claim(ClaimTypes.GroupSid, request.TenantId)
|
||||
};
|
||||
|
||||
var jwtSettings = context.RequestServices.GetRequiredService<IOptions<JwtSettingsModel>>().Value;
|
||||
var newToken = JwtService.GenerateNewJwtWithClaims(user, jwtClaims, jwtSettings);
|
||||
var newRefreshToken = Guid.NewGuid().ToString().Replace("-", "");
|
||||
|
||||
user.RefreshToken = newRefreshToken;
|
||||
await userManager.UpdateAsync(user);
|
||||
|
||||
context.Response.Cookies.Append("X-Auth-Token", newToken, new CookieOptions
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = true,
|
||||
SameSite = SameSiteMode.Strict,
|
||||
Expires = DateTimeOffset.UtcNow.AddDays(1)
|
||||
});
|
||||
|
||||
return Results.Ok(new { success = true, token = newToken });
|
||||
}
|
||||
|
||||
return Results.Json(new { success = false, title = "Failed to reconstruct security claims" }, statusCode: 400);
|
||||
}).RequireAuthorization();
|
||||
|
||||
return group;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
@using Indotalent.Shared.Consts
|
||||
@inherits LayoutComponentBase
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<MudThemeProvider Theme="_theme" />
|
||||
<MudDialogProvider />
|
||||
<MudSnackbarProvider />
|
||||
<MudPopoverProvider />
|
||||
|
||||
<style>
|
||||
.auth-split-container {
|
||||
display: flex;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.auth-left-panel {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@@media (min-width: 1024px) {
|
||||
.auth-left-panel {
|
||||
display: flex;
|
||||
width: 50%;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 3rem;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
background: linear-gradient(135deg, #3228A0, #594AE2, #7B6FE8);
|
||||
}
|
||||
|
||||
.auth-left-panel::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -80px;
|
||||
right: -80px;
|
||||
width: 300px;
|
||||
height: 300px;
|
||||
border-radius: 50%;
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.auth-left-panel::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
bottom: -60px;
|
||||
left: -60px;
|
||||
width: 200px;
|
||||
height: 200px;
|
||||
border-radius: 50%;
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
.auth-left-content {
|
||||
max-width: 28rem;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.auth-brand-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.auth-brand-icon {
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-radius: 0.75rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
backdrop-filter: blur(8px);
|
||||
color: white;
|
||||
font-size: 2rem;
|
||||
}
|
||||
|
||||
.auth-welcome-title {
|
||||
font-size: 1.875rem;
|
||||
font-weight: 700;
|
||||
color: white;
|
||||
line-height: 1.3;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.auth-welcome-desc {
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
line-height: 1.6;
|
||||
margin-bottom: 2rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.auth-feature-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.auth-feature-item {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.auth-feature-check {
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
border-radius: 0.25rem;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
margin-top: 0.125rem;
|
||||
}
|
||||
|
||||
.auth-feature-check svg {
|
||||
width: 0.75rem;
|
||||
height: 0.75rem;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.auth-feature-label {
|
||||
font-weight: 600;
|
||||
color: white;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.auth-feature-desc {
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
font-size: 0.75rem;
|
||||
margin-top: 0.125rem;
|
||||
}
|
||||
|
||||
.auth-support-card {
|
||||
margin-top: 2.5rem;
|
||||
padding: 1rem;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
backdrop-filter: blur(8px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
border-radius: 0.75rem;
|
||||
}
|
||||
|
||||
.auth-support-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.auth-support-avatar {
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
border-radius: 50%;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.auth-support-avatar svg {
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.auth-support-label {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.auth-support-desc {
|
||||
font-size: 0.75rem;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
}
|
||||
|
||||
.auth-right-panel {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 1.5rem;
|
||||
background: #f8fafc;
|
||||
}
|
||||
|
||||
@@media (min-width: 1024px) {
|
||||
.auth-right-panel {
|
||||
width: 50%;
|
||||
padding: 3rem;
|
||||
}
|
||||
}
|
||||
|
||||
.auth-form-wrapper {
|
||||
width: 100%;
|
||||
max-width: 28rem;
|
||||
}
|
||||
|
||||
.auth-card {
|
||||
border-radius: 0.75rem;
|
||||
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08), 0 1px 2px rgba(0, 0, 0, 0.06);
|
||||
border: 1px solid #e2e8f0 !important;
|
||||
background: white !important;
|
||||
}
|
||||
|
||||
.auth-card-footer {
|
||||
text-align: center;
|
||||
padding-top: 1rem;
|
||||
border-top: 1px solid #e2e8f0;
|
||||
font-size: 0.75rem;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.auth-mobile-brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
padding: 1rem 0;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
@@media (min-width: 1024px) {
|
||||
.auth-mobile-brand {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.auth-mobile-brand-icon {
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
background: #594AE2;
|
||||
border-radius: 0.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.auth-mobile-brand-icon svg {
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.auth-mobile-brand-name {
|
||||
font-weight: 700;
|
||||
font-size: 1.125rem;
|
||||
color: #594AE2;
|
||||
}
|
||||
|
||||
.auth-mobile-brand-tagline {
|
||||
font-size: 0.75rem;
|
||||
color: #64748b;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="auth-split-container">
|
||||
|
||||
<!-- LEFT PANEL - Branding -->
|
||||
<div class="auth-left-panel">
|
||||
<div class="auth-left-content">
|
||||
<div class="auth-brand-row" @onclick="NavigateToHome" style="cursor: pointer;">
|
||||
<div class="auth-brand-icon">
|
||||
<svg fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" style="width: 2rem; height: 2rem;"><path stroke-linecap="round" stroke-linejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" /></svg>
|
||||
</div>
|
||||
<div>
|
||||
<div style="font-size: 1.5rem; font-weight: 700; color: white;">@GlobalConsts.AppName</div>
|
||||
<div style="font-size: 0.875rem; color: rgba(255, 255, 255, 0.7);">@GlobalConsts.AppTagline</div>
|
||||
</div>
|
||||
</div>
|
||||
<h2 class="auth-welcome-title">Smart HR, Simplified</h2>
|
||||
<p class="auth-welcome-desc">Manage your workforce with a complete, production-ready platform built on .NET 10 & Blazor Server.</p>
|
||||
<div class="auth-feature-list">
|
||||
<div class="auth-feature-item">
|
||||
<div class="auth-feature-check">
|
||||
<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"/></svg>
|
||||
</div>
|
||||
<div>
|
||||
<div class="auth-feature-label">Leave & Attendance</div>
|
||||
<div class="auth-feature-desc">Request, approve, and track leave with balance overview</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="auth-feature-item">
|
||||
<div class="auth-feature-check">
|
||||
<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"/></svg>
|
||||
</div>
|
||||
<div>
|
||||
<div class="auth-feature-label">Performance & Appraisal</div>
|
||||
<div class="auth-feature-desc">Evaluations, promotions, and transfer management</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="auth-feature-item">
|
||||
<div class="auth-feature-check">
|
||||
<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="3"><path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5"/></svg>
|
||||
</div>
|
||||
<div>
|
||||
<div class="auth-feature-label">Payroll Processing</div>
|
||||
<div class="auth-feature-desc">Salary grades, income, deduction, and payroll runs</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="auth-support-card">
|
||||
<div class="auth-support-row">
|
||||
<div class="auth-support-avatar">
|
||||
<svg fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.5"><path stroke-linecap="round" stroke-linejoin="round" d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15m3 0l3-3m0 0l-3-3m3 3H9"/></svg>
|
||||
</div>
|
||||
<div>
|
||||
<div class="auth-support-label">Try the Live Demo</div>
|
||||
<div class="auth-support-desc">Explore every feature at blazor-saas-hrm.csharpasp.net</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- RIGHT PANEL - Form -->
|
||||
<div class="auth-right-panel">
|
||||
<div class="auth-form-wrapper">
|
||||
<div class="auth-mobile-brand">
|
||||
<div class="auth-mobile-brand-icon">
|
||||
<svg fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" style="width: 1.25rem; height: 1.25rem;"><path stroke-linecap="round" stroke-linejoin="round" d="M18 18.72a9.094 9.094 0 003.741-.479 3 3 0 00-4.682-2.72m.94 3.198l.001.031c0 .225-.012.447-.037.666A11.944 11.944 0 0112 21c-2.17 0-4.207-.576-5.963-1.584A6.062 6.062 0 016 18.719m12 0a5.971 5.971 0 00-.941-3.197m0 0A5.995 5.995 0 0012 12.75a5.995 5.995 0 00-5.058 2.772m0 0a3 3 0 00-4.681 2.72 8.986 8.986 0 003.74.477m.94-3.197a5.971 5.971 0 00-.94 3.197M15 6.75a3 3 0 11-6 0 3 3 0 016 0zm6 3a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0zm-13.5 0a2.25 2.25 0 11-4.5 0 2.25 2.25 0 014.5 0z" /></svg>
|
||||
</div>
|
||||
<div>
|
||||
<div class="auth-mobile-brand-name">@GlobalConsts.AppName</div>
|
||||
<div class="auth-mobile-brand-tagline">@GlobalConsts.AppTagline</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<MudCard Elevation="0" Class="auth-card pa-4 pa-sm-5">
|
||||
<MudCardContent Class="pa-0 pa-sm-2">
|
||||
@Body
|
||||
</MudCardContent>
|
||||
<div class="auth-card-footer mt-4">
|
||||
© @DateTime.Now.Year @GlobalConsts.AppInitial. ALL RIGHTS RESERVED.
|
||||
</div>
|
||||
</MudCard>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private MudTheme _theme = new MudTheme
|
||||
{
|
||||
PaletteLight = new PaletteLight
|
||||
{
|
||||
Primary = "#594AE2",
|
||||
Secondary = "#7B6FE8",
|
||||
AppbarBackground = "#594AE2",
|
||||
DrawerBackground = "#ffffff",
|
||||
Background = "#f8fafc",
|
||||
Surface = "#ffffff",
|
||||
TextPrimary = "#1e293b",
|
||||
TextSecondary = "#64748b",
|
||||
Divider = "#e2e8f0",
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
private void NavigateToHome()
|
||||
{
|
||||
Navigation.NavigateTo("/", forceLoad: true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
@page "/account/confirm-email"
|
||||
@layout AuthenticationLayout
|
||||
@using Indotalent.Shared.Consts
|
||||
@using Microsoft.AspNetCore.Identity
|
||||
@using Microsoft.AspNetCore.WebUtilities
|
||||
@using System.Text
|
||||
@using Indotalent.Data.Entities
|
||||
@inject UserManager<ApplicationUser> UserManager
|
||||
@inject NavigationManager Navigation
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<PageTitle>Confirming Email - @GlobalConsts.AppInitial</PageTitle>
|
||||
|
||||
<style>
|
||||
.confirm-container {
|
||||
text-align: center;
|
||||
padding: 0.5rem 0;
|
||||
}
|
||||
.confirm-icon-wrapper {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
.confirm-icon-circle {
|
||||
background: #EEECFA;
|
||||
border-radius: 50%;
|
||||
padding: 1.25rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #594AE2;
|
||||
}
|
||||
.confirm-title {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: #1e293b;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
.confirm-desc {
|
||||
font-size: 0.875rem;
|
||||
color: #64748b;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="confirm-container">
|
||||
<div class="confirm-icon-wrapper">
|
||||
<div class="confirm-icon-circle">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Verified" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="confirm-title">Verifying Your Account</div>
|
||||
<div class="confirm-desc">Please wait while we validate your email address...</div>
|
||||
|
||||
<MudProgressCircular Color="Color.Primary" Indeterminate="true" Size="Size.Large" />
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[SupplyParameterFromQuery] public string? userId { get; set; }
|
||||
[SupplyParameterFromQuery] public string? code { get; set; }
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(code))
|
||||
{
|
||||
Snackbar.Add("Invalid or expired confirmation link.", Severity.Error);
|
||||
Navigation.NavigateTo("/account/login");
|
||||
return;
|
||||
}
|
||||
|
||||
var user = await UserManager.FindByIdAsync(userId);
|
||||
if (user == null)
|
||||
{
|
||||
Snackbar.Add("User record not found.", Severity.Error);
|
||||
Navigation.NavigateTo("/account/login");
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var decodedCode = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code));
|
||||
var result = await UserManager.ConfirmEmailAsync(user, decodedCode);
|
||||
await Task.Delay(500);
|
||||
if (result.Succeeded)
|
||||
{
|
||||
Snackbar.Add("Email verified successfully! You can now sign in.", Severity.Success);
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Verification failed. The link may have expired.", Severity.Error);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
Snackbar.Add("An error occurred during verification.", Severity.Error);
|
||||
}
|
||||
|
||||
Navigation.NavigateTo("/account/login");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
@page "/account/forgot-password"
|
||||
@layout AuthenticationLayout
|
||||
@using System.ComponentModel.DataAnnotations
|
||||
@using Indotalent.Shared.Consts
|
||||
@using Microsoft.JSInterop
|
||||
@inject IJSRuntime JSRuntime
|
||||
@inject ISnackbar Snackbar
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<PageTitle>Forgot Password - @GlobalConsts.AppInitial</PageTitle>
|
||||
|
||||
<style>
|
||||
.page-header {
|
||||
text-align: center;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
.page-header h2 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: #1e293b;
|
||||
margin: 0 0 0.25rem 0;
|
||||
}
|
||||
.page-header p {
|
||||
font-size: 0.875rem;
|
||||
color: #64748b;
|
||||
margin: 0;
|
||||
}
|
||||
.form-label {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: #475569;
|
||||
margin-bottom: 0.375rem;
|
||||
margin-left: 0.25rem;
|
||||
}
|
||||
.auth-link {
|
||||
color: #594AE2;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
.auth-link:hover {
|
||||
color: #4235B8;
|
||||
text-decoration: underline;
|
||||
}
|
||||
.btn-submit {
|
||||
text-transform: none;
|
||||
border-radius: 0.5rem;
|
||||
height: 48px;
|
||||
font-weight: 600;
|
||||
font-size: 0.875rem;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="page-header">
|
||||
<h2>Forgot Password?</h2>
|
||||
<p>Enter your email address and we'll send you a link to reset your password.</p>
|
||||
</div>
|
||||
|
||||
<MudForm @ref="form" @bind-IsValid="@success">
|
||||
|
||||
<div class="mb-4">
|
||||
<div class="form-label">Email Address</div>
|
||||
<MudTextField T="string"
|
||||
@bind-Value="model.Email"
|
||||
Variant="Variant.Outlined"
|
||||
Placeholder="name@example.com"
|
||||
Margin="Margin.Dense"
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Email"
|
||||
Required="true"
|
||||
Validation="@(new EmailAddressAttribute() { ErrorMessage = "Invalid email address format" })"
|
||||
For="@(() => model.Email)"
|
||||
Style="border-radius: 0.5rem;" />
|
||||
</div>
|
||||
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
Size="Size.Large"
|
||||
FullWidth="true"
|
||||
Disabled="!success || isProcessing"
|
||||
OnClick="HandleForgotPassword"
|
||||
Class="btn-submit">
|
||||
@if (isProcessing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<span class="ms-2">Sending link...</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span>Send Reset Link</span>
|
||||
}
|
||||
</MudButton>
|
||||
</MudForm>
|
||||
|
||||
<div style="text-align: center; margin-top: 1.5rem;">
|
||||
<MudText Typo="Typo.body2">
|
||||
Remember your password?
|
||||
<a class="auth-link ms-1" href="/account/login">Back to Sign In</a>
|
||||
</MudText>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private MudForm form = default!;
|
||||
private bool success;
|
||||
private bool isProcessing;
|
||||
private ForgotPasswordModel model = new();
|
||||
|
||||
private class ForgotPasswordModel
|
||||
{
|
||||
public string Email { get; set; } = "";
|
||||
}
|
||||
|
||||
private async Task HandleForgotPassword()
|
||||
{
|
||||
await form.Validate();
|
||||
if (!success) return;
|
||||
|
||||
isProcessing = true;
|
||||
StateHasChanged();
|
||||
|
||||
var result = await JSRuntime.InvokeAsync<ApiResponse>("apiForgotPassword", model.Email);
|
||||
|
||||
if (result.Status == 200)
|
||||
{
|
||||
Snackbar.Add("If your email is registered, a reset link has been sent.", Severity.Success);
|
||||
await Task.Delay(500);
|
||||
Navigation.NavigateTo("/account/login");
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add(result.Title ?? "Failed to send reset link", Severity.Error);
|
||||
}
|
||||
|
||||
isProcessing = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private class ApiResponse
|
||||
{
|
||||
public int Status { get; set; }
|
||||
public string? Title { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
<script>
|
||||
window.apiForgotPassword = async (email) => {
|
||||
try {
|
||||
const response = await fetch('/api/account/forgot-password', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email })
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return { status: 200, title: 'Success' };
|
||||
} else {
|
||||
const data = await response.json();
|
||||
let msg = 'Error processing request';
|
||||
if (data.errors && data.errors.length > 0) msg = data.errors[0];
|
||||
return { status: response.status, title: msg };
|
||||
}
|
||||
} catch (error) {
|
||||
return { status: 500, title: 'Network error' };
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,70 @@
|
||||
using Indotalent.Data.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.WebUtilities;
|
||||
using System.Text;
|
||||
|
||||
namespace Indotalent.Features.Account.ForgotPassword.Cqrs;
|
||||
|
||||
public class ForgotPasswordRequest
|
||||
{
|
||||
public string Email { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class ForgotPasswordResponse
|
||||
{
|
||||
public string Message { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public record ForgotPasswordCommand(ForgotPasswordRequest Data) : IRequest<ForgotPasswordResponse>;
|
||||
|
||||
public class ForgotPasswordHandler : IRequestHandler<ForgotPasswordCommand, ForgotPasswordResponse>
|
||||
{
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly IEmailSender<ApplicationUser> _emailSender;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
|
||||
public ForgotPasswordHandler(
|
||||
UserManager<ApplicationUser> userManager,
|
||||
IEmailSender<ApplicationUser> emailSender,
|
||||
IHttpContextAccessor httpContextAccessor)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_emailSender = emailSender;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
}
|
||||
|
||||
public async Task<ForgotPasswordResponse> Handle(ForgotPasswordCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = await _userManager.FindByEmailAsync(request.Data.Email);
|
||||
|
||||
if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
|
||||
{
|
||||
return new ForgotPasswordResponse { Message = "If your email is registered, you will receive a reset link." };
|
||||
}
|
||||
|
||||
var code = await _userManager.GeneratePasswordResetTokenAsync(user);
|
||||
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
|
||||
|
||||
var requestHttp = _httpContextAccessor.HttpContext?.Request;
|
||||
var scheme = requestHttp?.Scheme ?? "https";
|
||||
var host = requestHttp?.Host.Value ?? "localhost:8080";
|
||||
|
||||
var callbackUrl = $"{scheme}://{host}/account/reset-password?userId={user.Id}&code={code}";
|
||||
|
||||
var message = $@"
|
||||
<div style=""font-family: Arial, sans-serif;"">
|
||||
<h3>Password Reset Request</h3>
|
||||
<p>Hello, {user.FullName}!</p>
|
||||
<p>We received a request to reset your password. Click the link below to proceed:</p>
|
||||
<p><a href=""{callbackUrl}"" style=""color: #2196F3; font-weight: bold;"">Reset Password</a></p>
|
||||
<br/>
|
||||
<p style=""font-size: 0.8em; color: #666;"">If you didn't request this, you can safely ignore this email.</p>
|
||||
<p style=""font-size: 0.8em; color: #666;"">{callbackUrl}</p>
|
||||
</div>";
|
||||
|
||||
await _emailSender.SendPasswordResetLinkAsync(user, user.Email!, message);
|
||||
|
||||
return new ForgotPasswordResponse { Message = "Reset link has been sent." };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
@page "/account/login"
|
||||
@layout AuthenticationLayout
|
||||
@using Indotalent.Shared.Consts
|
||||
@using Microsoft.JSInterop
|
||||
@using Indotalent.Infrastructure.Authentication.Identity
|
||||
@using Microsoft.Extensions.Options
|
||||
@inject IJSRuntime JSRuntime
|
||||
@inject IOptions<IdentitySettingsModel> IdentityOptions
|
||||
@inject NavigationManager Navigation
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<PageTitle>Sign In - @GlobalConsts.AppInitial</PageTitle>
|
||||
|
||||
<style>
|
||||
.page-header {
|
||||
text-align: center;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
.page-header h2 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: #1e293b;
|
||||
margin: 0 0 0.25rem 0;
|
||||
}
|
||||
.page-header p {
|
||||
font-size: 0.875rem;
|
||||
color: #64748b;
|
||||
margin: 0;
|
||||
}
|
||||
.form-label {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: #475569;
|
||||
margin-bottom: 0.375rem;
|
||||
margin-left: 0.25rem;
|
||||
}
|
||||
.form-label-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
.forgot-link {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: #594AE2;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
.forgot-link:hover {
|
||||
color: #4235B8;
|
||||
text-decoration: underline;
|
||||
}
|
||||
.remember-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.divider-or {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
margin: 1.25rem 0;
|
||||
}
|
||||
.divider-or::before,
|
||||
.divider-or::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: #e2e8f0;
|
||||
}
|
||||
.divider-or span {
|
||||
font-size: 0.75rem;
|
||||
color: #94a3b8;
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
.auth-link {
|
||||
color: #594AE2;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
.auth-link:hover {
|
||||
color: #4235B8;
|
||||
text-decoration: underline;
|
||||
}
|
||||
.btn-google {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.625rem 1rem;
|
||||
width: 100%;
|
||||
background: white;
|
||||
color: #475569;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
border-radius: 0.5rem;
|
||||
border: 1.5px solid #e2e8f0;
|
||||
transition: all 0.2s;
|
||||
cursor: pointer;
|
||||
text-transform: none;
|
||||
}
|
||||
.btn-google:hover {
|
||||
border-color: #cbd5e1;
|
||||
background: #f8fafc;
|
||||
}
|
||||
.btn-submit {
|
||||
text-transform: none;
|
||||
border-radius: 0.5rem;
|
||||
height: 48px;
|
||||
font-weight: 600;
|
||||
font-size: 0.875rem;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="page-header">
|
||||
<h2>Sign In</h2>
|
||||
<p>Enter your credentials to access your account</p>
|
||||
</div>
|
||||
|
||||
<MudForm @ref="form" @bind-IsValid="@success" Validation="@(new Func<EditContext, Task<bool>>(ValidateForm))" Class="w-100 px-2">
|
||||
|
||||
<div class="mb-3">
|
||||
<div class="form-label">Email Address</div>
|
||||
<MudTextField T="string"
|
||||
@bind-Value="model.Email"
|
||||
Variant="Variant.Outlined"
|
||||
Placeholder="you@company.com"
|
||||
Margin="Margin.Dense"
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Email"
|
||||
Required="true"
|
||||
For="@(() => model.Email)"
|
||||
Style="border-radius: 0.5rem;" />
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<div class="form-label-row">
|
||||
<span class="form-label" style="margin-bottom:0;">Password</span>
|
||||
<a class="forgot-link" href="/account/forgot-password">Forgot password?</a>
|
||||
</div>
|
||||
<MudTextField T="string"
|
||||
@bind-Value="model.Password"
|
||||
Variant="Variant.Outlined"
|
||||
Placeholder="Enter your password"
|
||||
Margin="Margin.Dense"
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Lock"
|
||||
InputType="@(showPassword ? InputType.Text : InputType.Password)"
|
||||
AdornmentEndIcon="@(showPassword? Icons.Material.Filled.Visibility : Icons.Material.Filled.VisibilityOff)"
|
||||
OnAdornmentEndClick="() => showPassword = !showPassword"
|
||||
Required="true"
|
||||
For="@(() => model.Password)"
|
||||
Style="border-radius: 0.5rem;" />
|
||||
</div>
|
||||
|
||||
<div class="remember-row mb-4">
|
||||
<MudCheckBox T="bool"
|
||||
@bind-Value="rememberMe"
|
||||
Label="Remember me"
|
||||
Color="Color.Primary"
|
||||
Dense="true" />
|
||||
</div>
|
||||
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
Size="Size.Large"
|
||||
FullWidth="true"
|
||||
Disabled="!success || isProcessing"
|
||||
OnClick="HandleLogin"
|
||||
Class="btn-submit">
|
||||
@if (isProcessing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<span class="ms-2">Signing in...</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span>Sign In</span>
|
||||
}
|
||||
</MudButton>
|
||||
|
||||
@if (IdentityOptions.Value.SsoFirebase.IsUsed)
|
||||
{
|
||||
<div class="divider-or"><span>Or continue with</span></div>
|
||||
|
||||
<MudButton Variant="Variant.Outlined"
|
||||
FullWidth="true"
|
||||
Size="Size.Large"
|
||||
Disabled="isProcessing"
|
||||
OnClick="HandleFirebaseGoogleLogin"
|
||||
StartIcon="@Icons.Custom.Brands.Google"
|
||||
Class="btn-google">
|
||||
Sign in with Google
|
||||
</MudButton>
|
||||
}
|
||||
</MudForm>
|
||||
|
||||
<div style="text-align: center; margin-top: 1.5rem;">
|
||||
<MudText Typo="Typo.body2">
|
||||
Don't have an account?
|
||||
<a class="auth-link ms-1" href="/account/register">Create one</a>
|
||||
</MudText>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private MudForm form = default!;
|
||||
private bool success;
|
||||
private bool isProcessing;
|
||||
private bool showPassword;
|
||||
private bool rememberMe;
|
||||
private LoginModel model = new();
|
||||
|
||||
private async Task<bool> ValidateForm(EditContext context) => await Task.FromResult(true);
|
||||
|
||||
private async Task HandleLogin()
|
||||
{
|
||||
await form.Validate();
|
||||
if (!success) return;
|
||||
isProcessing = true;
|
||||
StateHasChanged();
|
||||
|
||||
var result = await JSRuntime.InvokeAsync<ApiJSRuntimeResponse>("apiAccountSignIn", model.Email, model.Password, rememberMe);
|
||||
ProcessLoginResult(result);
|
||||
}
|
||||
|
||||
private async Task HandleFirebaseGoogleLogin()
|
||||
{
|
||||
isProcessing = true;
|
||||
StateHasChanged();
|
||||
|
||||
var firebaseUser = await JSRuntime.InvokeAsync<FirebaseUserResponse>("signInWithGoogle");
|
||||
|
||||
if (firebaseUser == null || string.IsNullOrEmpty(firebaseUser.Email))
|
||||
{
|
||||
Snackbar.Add("Google Sign-In failed or cancelled.", Severity.Error);
|
||||
isProcessing = false;
|
||||
return;
|
||||
}
|
||||
|
||||
var checkResult = await JSRuntime.InvokeAsync<ActiveCheckResponse>("apiCheckActiveUser", firebaseUser.Email);
|
||||
bool openForPublic = IdentityOptions.Value.SsoFirebase.OpenForPublic;
|
||||
|
||||
if (checkResult.Exists)
|
||||
{
|
||||
if (checkResult.IsActive)
|
||||
{
|
||||
await ExecuteSsoSignIn(firebaseUser.Email);
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Account is registered but not active.", Severity.Warning);
|
||||
isProcessing = false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var registerResult = await JSRuntime.InvokeAsync<ApiJSRuntimeResponse>(
|
||||
"apiAccountSignUpSso",
|
||||
firebaseUser.Email,
|
||||
firebaseUser.Email,
|
||||
openForPublic
|
||||
);
|
||||
|
||||
if (registerResult.Status == 200)
|
||||
{
|
||||
if (openForPublic)
|
||||
{
|
||||
await ExecuteSsoSignIn(firebaseUser.Email);
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Registration successful. Please wait for admin approval.", Severity.Info);
|
||||
isProcessing = false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Failed to auto-register account.", Severity.Error);
|
||||
isProcessing = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ExecuteSsoSignIn(string email)
|
||||
{
|
||||
var result = await JSRuntime.InvokeAsync<ApiJSRuntimeResponse>("apiAccountSsoSignIn", email);
|
||||
ProcessLoginResult(result);
|
||||
}
|
||||
|
||||
private void ProcessLoginResult(ApiJSRuntimeResponse result)
|
||||
{
|
||||
if (result.Status == 200)
|
||||
{
|
||||
Snackbar.Add(result.Title ?? "Login successful!", Severity.Success);
|
||||
Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(500);
|
||||
Navigation.NavigateTo("/account/tenant-selection", forceLoad: true);
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add(result.Title ?? "Sign in failed.", Severity.Error);
|
||||
isProcessing = false;
|
||||
}
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private class ApiJSRuntimeResponse { public int? Status { get; set; } public string? Title { get; set; } public string? Message { get; set; } }
|
||||
private class FirebaseUserResponse { public string? Email { get; set; } }
|
||||
private class ActiveCheckResponse { public bool Exists { get; set; } public bool IsActive { get; set; } }
|
||||
private class LoginModel { public string Email { get; set; } = ""; public string Password { get; set; } = ""; }
|
||||
}
|
||||
|
||||
<script>
|
||||
window.apiAccountSignIn = async (email, password, rememberMe) => {
|
||||
try {
|
||||
const response = await fetch('/api/account/signin', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password, rememberMe }),
|
||||
credentials: 'include'
|
||||
});
|
||||
const result = await response.json();
|
||||
return { status: response.status, title: result.title };
|
||||
} catch (error) {
|
||||
return { status: 500, title: 'Network error' };
|
||||
}
|
||||
};
|
||||
|
||||
window.apiCheckActiveUser = async (email) => {
|
||||
try {
|
||||
const response = await fetch(`/api/account/active-user-exists?email=${encodeURIComponent(email)}`);
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
return { exists: false, isActive: false };
|
||||
}
|
||||
};
|
||||
|
||||
window.apiAccountSignUpSso = async (email, fullName, isOpenForPublic) => {
|
||||
try {
|
||||
const response = await fetch('/api/account/signup', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
email: email,
|
||||
fullName: fullName,
|
||||
password: 'SSO_AUTO_GENERATED_PASSWORD_123!',
|
||||
isActive: isOpenForPublic,
|
||||
emailConfirmed: isOpenForPublic
|
||||
})
|
||||
});
|
||||
const result = await response.json();
|
||||
return { status: response.status, message: result.message };
|
||||
} catch (error) {
|
||||
return { status: 500 };
|
||||
}
|
||||
};
|
||||
|
||||
window.apiAccountSsoSignIn = async (email) => {
|
||||
try {
|
||||
const response = await fetch(`/api/account/signin-sso?email=${encodeURIComponent(email)}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include'
|
||||
});
|
||||
const result = await response.json();
|
||||
return { status: response.status, title: result.title };
|
||||
} catch (error) {
|
||||
return { status: 500, title: 'SSO Network error' };
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,74 @@
|
||||
using Indotalent.ConfigFrontEnd.Service;
|
||||
using Indotalent.Data.Entities;
|
||||
using Indotalent.Infrastructure.Authentication.Identity;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Indotalent.Features.Account.Login.Cqrs;
|
||||
|
||||
public class LoginRequest
|
||||
{
|
||||
public string Email { get; set; } = string.Empty;
|
||||
public string Password { get; set; } = string.Empty;
|
||||
public bool RememberMe { get; set; }
|
||||
}
|
||||
|
||||
public class LoginResponse
|
||||
{
|
||||
public bool Succeeded { get; set; }
|
||||
public string Message { get; set; } = string.Empty;
|
||||
public bool IsNotAllowed { get; set; }
|
||||
public string? Token { get; set; }
|
||||
public string? RefreshToken { get; set; }
|
||||
}
|
||||
|
||||
public record LoginCommand(LoginRequest Data) : IRequest<LoginResponse>;
|
||||
|
||||
public class LoginHandler : IRequestHandler<LoginCommand, LoginResponse>
|
||||
{
|
||||
private readonly SignInManager<ApplicationUser> _signInManager;
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly JwtSettingsModel _jwtSettings;
|
||||
|
||||
public LoginHandler(
|
||||
SignInManager<ApplicationUser> signInManager,
|
||||
UserManager<ApplicationUser> userManager,
|
||||
IOptions<JwtSettingsModel> jwtSettings)
|
||||
{
|
||||
_signInManager = signInManager;
|
||||
_userManager = userManager;
|
||||
_jwtSettings = jwtSettings.Value;
|
||||
}
|
||||
|
||||
public async Task<LoginResponse> Handle(LoginCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = await _userManager.FindByEmailAsync(request.Data.Email);
|
||||
if (user == null) return new LoginResponse { Succeeded = false, Message = "Invalid credentials" };
|
||||
|
||||
var result = await _signInManager.PasswordSignInAsync(user, request.Data.Password, request.Data.RememberMe, false);
|
||||
|
||||
if (result.Succeeded)
|
||||
{
|
||||
var token = JwtService.GenerateNewJwt(user, _jwtSettings);
|
||||
|
||||
var refreshToken = Guid.NewGuid().ToString().Replace("-", "");
|
||||
|
||||
user.RefreshToken = refreshToken;
|
||||
user.LastLoginAt = DateTime.Now;
|
||||
await _userManager.UpdateAsync(user);
|
||||
|
||||
return new LoginResponse
|
||||
{
|
||||
Succeeded = true,
|
||||
Message = "Login successful",
|
||||
Token = token,
|
||||
RefreshToken = refreshToken
|
||||
};
|
||||
}
|
||||
|
||||
return new LoginResponse { Succeeded = false, Message = "Invalid credentials" };
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
@page "/account/logout"
|
||||
@layout AuthenticationLayout
|
||||
|
||||
@using Indotalent.Shared.Consts
|
||||
@using Microsoft.JSInterop
|
||||
@inject IJSRuntime JSRuntime
|
||||
@inject ISnackbar Snackbar
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<PageTitle>Sign Out - @GlobalConsts.AppInitial</PageTitle>
|
||||
|
||||
<style>
|
||||
.logout-container {
|
||||
text-align: center;
|
||||
padding: 0.5rem 0;
|
||||
}
|
||||
.logout-icon-wrapper {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
.logout-icon-circle {
|
||||
background: #EEECFA;
|
||||
border-radius: 50%;
|
||||
padding: 1.25rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #594AE2;
|
||||
}
|
||||
.logout-icon-circle .mud-icon-root {
|
||||
font-size: 3rem;
|
||||
}
|
||||
.logout-title {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: #1e293b;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
.logout-desc {
|
||||
font-size: 0.875rem;
|
||||
color: #64748b;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
.btn-signout {
|
||||
text-transform: none;
|
||||
border-radius: 0.5rem;
|
||||
height: 48px;
|
||||
font-weight: 600;
|
||||
font-size: 0.875rem;
|
||||
letter-spacing: 0;
|
||||
background-color: #594AE2;
|
||||
color: white;
|
||||
}
|
||||
.btn-signout:hover {
|
||||
background-color: #4235B8;
|
||||
}
|
||||
.btn-cancel {
|
||||
text-transform: none;
|
||||
color: #94a3b8;
|
||||
font-weight: 600;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="logout-container">
|
||||
<div class="logout-icon-wrapper">
|
||||
<div class="logout-icon-circle">
|
||||
<MudIcon Icon="@Icons.Material.Filled.ExitToApp" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="logout-title">Sign Out</div>
|
||||
<div class="logout-desc">Are you sure you want to sign out of your account?</div>
|
||||
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Size="Size.Large"
|
||||
FullWidth="true"
|
||||
Disabled="@isLoggingOut"
|
||||
OnClick="Logout"
|
||||
Class="btn-signout">
|
||||
@if (isLoggingOut)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<span class="ms-2">Processing...</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span>Sign Out</span>
|
||||
}
|
||||
</MudButton>
|
||||
|
||||
<MudButton Variant="Variant.Text"
|
||||
Class="mt-3 btn-cancel"
|
||||
FullWidth="true"
|
||||
Href="/account/tenant-selection"
|
||||
Disabled="@isLoggingOut">
|
||||
Cancel
|
||||
</MudButton>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private bool isLoggingOut;
|
||||
|
||||
private async Task Logout()
|
||||
{
|
||||
isLoggingOut = true;
|
||||
StateHasChanged();
|
||||
|
||||
var result = await JSRuntime.InvokeAsync<ApiJSRuntimeResponse>("apiAccountLogout");
|
||||
|
||||
if (result.Status == 200)
|
||||
{
|
||||
Snackbar.Add("Successfully signed out!", Severity.Success);
|
||||
await Task.Delay(500);
|
||||
Navigation.NavigateTo("/", forceLoad: true);
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add(result.Title ?? "Failed to logout.", Severity.Error);
|
||||
await Task.Delay(500);
|
||||
}
|
||||
|
||||
isLoggingOut = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private class ApiJSRuntimeResponse
|
||||
{
|
||||
public int? Status { get; set; }
|
||||
public string? Title { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
<script>
|
||||
window.apiAccountLogout = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/account/signout', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
credentials: 'include'
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error('Unknown error occurred');
|
||||
}
|
||||
return { status: 200, title: 'Success user logout' };
|
||||
} catch (error) {
|
||||
return { status: 500, title: 'Server / Network error' };
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,232 @@
|
||||
@page "/account/register"
|
||||
@layout AuthenticationLayout
|
||||
|
||||
@using Indotalent.Shared.Consts
|
||||
@using Microsoft.JSInterop
|
||||
@inject IJSRuntime JSRuntime
|
||||
@inject ISnackbar Snackbar
|
||||
@inject NavigationManager Navigation
|
||||
@inject IConfiguration Configuration
|
||||
|
||||
<PageTitle>Sign Up - @GlobalConsts.AppInitial</PageTitle>
|
||||
|
||||
<style>
|
||||
.page-header {
|
||||
text-align: center;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
.page-header h2 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: #1e293b;
|
||||
margin: 0 0 0.25rem 0;
|
||||
}
|
||||
.page-header p {
|
||||
font-size: 0.875rem;
|
||||
color: #64748b;
|
||||
margin: 0;
|
||||
}
|
||||
.form-label {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: #475569;
|
||||
margin-bottom: 0.375rem;
|
||||
margin-left: 0.25rem;
|
||||
}
|
||||
.auth-link {
|
||||
color: #594AE2;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
.auth-link:hover {
|
||||
color: #4235B8;
|
||||
text-decoration: underline;
|
||||
}
|
||||
.btn-submit {
|
||||
text-transform: none;
|
||||
border-radius: 0.5rem;
|
||||
height: 48px;
|
||||
font-weight: 600;
|
||||
font-size: 0.875rem;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="page-header">
|
||||
<h2>Sign Up</h2>
|
||||
<p>Create your account to get started</p>
|
||||
</div>
|
||||
|
||||
<MudForm @ref="form" @bind-IsValid="@success" Validation="@(new Func<EditContext, Task<bool>>(ValidateForm))">
|
||||
|
||||
<div class="mb-3">
|
||||
<div class="form-label">Full Name</div>
|
||||
<MudTextField T="string"
|
||||
@bind-Value="model.FullName"
|
||||
Variant="Variant.Outlined"
|
||||
Placeholder="Enter your full name"
|
||||
Margin="Margin.Dense"
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Person"
|
||||
Required="true"
|
||||
For="@(() => model.FullName)"
|
||||
Style="border-radius: 0.5rem;" />
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<div class="form-label">Email Address</div>
|
||||
<MudTextField T="string"
|
||||
@bind-Value="model.Email"
|
||||
Variant="Variant.Outlined"
|
||||
Placeholder="you@company.com"
|
||||
Margin="Margin.Dense"
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Email"
|
||||
Required="true"
|
||||
For="@(() => model.Email)"
|
||||
Style="border-radius: 0.5rem;" />
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<div class="form-label">Password</div>
|
||||
<MudTextField T="string"
|
||||
@bind-Value="model.Password"
|
||||
Variant="Variant.Outlined"
|
||||
Placeholder="Create a password"
|
||||
Margin="Margin.Dense"
|
||||
InputType="@(showPassword ? InputType.Text : InputType.Password)"
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Lock"
|
||||
AdornmentEndIcon="@(showPassword? Icons.Material.Filled.Visibility : Icons.Material.Filled.VisibilityOff)"
|
||||
OnAdornmentEndClick="() => showPassword = !showPassword"
|
||||
Required="true"
|
||||
For="@(() => model.Password)"
|
||||
Style="border-radius: 0.5rem;" />
|
||||
</div>
|
||||
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
Size="Size.Large"
|
||||
FullWidth="true"
|
||||
Disabled="!success || isProcessing"
|
||||
OnClick="HandleRegister"
|
||||
Class="btn-submit">
|
||||
@if (isProcessing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<span class="ms-2">Creating account...</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span>Create Account</span>
|
||||
}
|
||||
</MudButton>
|
||||
</MudForm>
|
||||
|
||||
<div style="text-align: center; margin-top: 1.5rem;">
|
||||
<MudText Typo="Typo.body2">
|
||||
Already have an account?
|
||||
<a class="auth-link ms-1" href="/account/login">Sign In</a>
|
||||
</MudText>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private MudForm form = default!;
|
||||
private bool success;
|
||||
private bool isProcessing;
|
||||
private bool showPassword;
|
||||
|
||||
private RegisterModel model = new();
|
||||
|
||||
private class RegisterModel
|
||||
{
|
||||
public string FullName { get; set; } = "";
|
||||
public string Email { get; set; } = "";
|
||||
public string Password { get; set; } = "";
|
||||
}
|
||||
|
||||
private async Task<bool> ValidateForm(EditContext context)
|
||||
{
|
||||
return await Task.FromResult(true);
|
||||
}
|
||||
|
||||
private async Task HandleRegister()
|
||||
{
|
||||
await form.Validate();
|
||||
|
||||
if (!success) return;
|
||||
|
||||
isProcessing = true;
|
||||
StateHasChanged();
|
||||
|
||||
var result = await JSRuntime.InvokeAsync<ApiJSRuntimeResponse>("apiAccountRegister", model.FullName, model.Email, model.Password);
|
||||
|
||||
if (result.Status == 200)
|
||||
{
|
||||
var requireConfirmation = Configuration.GetValue<bool>("IdentitySettings:SignIn:RequireConfirmedAccount");
|
||||
|
||||
if (requireConfirmation)
|
||||
{
|
||||
Snackbar.Add("Registration successful! Please check your email to confirm your account.", Severity.Info);
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Registration successful! You can now sign in.", Severity.Success);
|
||||
}
|
||||
|
||||
await Task.Delay(500);
|
||||
Navigation.NavigateTo("/account/login");
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add(result.Title ?? "Registration failed", Severity.Error);
|
||||
}
|
||||
|
||||
isProcessing = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private class ApiJSRuntimeResponse
|
||||
{
|
||||
public int? Status { get; set; }
|
||||
public string? Title { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
<script>
|
||||
window.apiAccountRegister = async (fullName, email, password) => {
|
||||
try {
|
||||
const response = await fetch('/api/account/signup', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ fullName, email, password })
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
return { status: 200, title: 'Success account registration' };
|
||||
} else {
|
||||
let errorMessage = data.title || data.message || 'Registration failed';
|
||||
|
||||
if (data.errors) {
|
||||
if (Array.isArray(data.errors) && data.errors.length > 0) {
|
||||
errorMessage = data.errors[0];
|
||||
} else if (typeof data.errors === 'object') {
|
||||
const firstKey = Object.keys(data.errors)[0];
|
||||
if (firstKey) {
|
||||
errorMessage = data.errors[firstKey][0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { status: response.status, title: errorMessage };
|
||||
}
|
||||
} catch (error) {
|
||||
return { status: 500, title: 'Server / Network error' };
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,131 @@
|
||||
using Indotalent.Data.Entities;
|
||||
using Indotalent.Infrastructure.Authorization.Identity;
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.WebUtilities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.Text;
|
||||
|
||||
namespace Indotalent.Features.Account.Register.Cqrs;
|
||||
|
||||
public class CreateUserRequest
|
||||
{
|
||||
public string FullName { get; set; } = string.Empty;
|
||||
public string Email { get; set; } = string.Empty;
|
||||
public string Password { get; set; } = string.Empty;
|
||||
public bool IsActive { get; set; } = true;
|
||||
public bool EmailConfirmed { get; set; } = false;
|
||||
}
|
||||
|
||||
public class CreateUserResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? Email { get; set; }
|
||||
}
|
||||
|
||||
public record CreateUserCommand(CreateUserRequest Data) : IRequest<CreateUserResponse>;
|
||||
|
||||
public class RegisterHandler : IRequestHandler<CreateUserCommand, CreateUserResponse>
|
||||
{
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
private readonly IEmailSender<ApplicationUser> _emailSender;
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly IHttpContextAccessor _httpContextAccessor;
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public RegisterHandler(
|
||||
UserManager<ApplicationUser> userManager,
|
||||
IEmailSender<ApplicationUser> emailSender,
|
||||
IConfiguration configuration,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
AppDbContext context)
|
||||
{
|
||||
_userManager = userManager;
|
||||
_emailSender = emailSender;
|
||||
_configuration = configuration;
|
||||
_httpContextAccessor = httpContextAccessor;
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task<CreateUserResponse> Handle(CreateUserCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = new ApplicationUser
|
||||
{
|
||||
UserName = request.Data.Email,
|
||||
Email = request.Data.Email,
|
||||
FullName = request.Data.FullName,
|
||||
IsActive = request.Data.IsActive,
|
||||
EmailConfirmed = request.Data.EmailConfirmed,
|
||||
};
|
||||
|
||||
var result = await _userManager.CreateAsync(user, request.Data.Password);
|
||||
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
var errors = result.Errors.Select(x => x.Description).ToList();
|
||||
throw new Exception(string.Join(", ", errors));
|
||||
}
|
||||
|
||||
// Assign default roles: Member and TenantAdmin (but not Admin)
|
||||
var rolesToAdd = new List<string> { ApplicationRoles.Member, ApplicationRoles.TenantAdmin };
|
||||
|
||||
await _userManager.AddToRolesAsync(user, rolesToAdd);
|
||||
|
||||
// Create default tenant for the new user
|
||||
var tenant = new Data.Entities.Tenant
|
||||
{
|
||||
Name = "Default Tenant",
|
||||
Description = $"Default tenant for {request.Data.Email}",
|
||||
EmailAddress = request.Data.Email,
|
||||
IsActive = true
|
||||
};
|
||||
|
||||
_context.Tenant.Add(tenant);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
// Create TenantUser linking the user to the default tenant
|
||||
var tenantUser = new Data.Entities.TenantUser
|
||||
{
|
||||
TenantId = tenant.Id,
|
||||
UserId = user.Id,
|
||||
Summary = $"Default tenant assignment for {request.Data.FullName}",
|
||||
IsActive = true
|
||||
};
|
||||
|
||||
_context.TenantUser.Add(tenantUser);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
var requireConfirmation = _configuration.GetValue<bool>("IdentitySettings:SignIn:RequireConfirmedAccount");
|
||||
|
||||
if (requireConfirmation)
|
||||
{
|
||||
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
|
||||
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
|
||||
|
||||
var requestHttp = _httpContextAccessor.HttpContext?.Request;
|
||||
var scheme = requestHttp?.Scheme ?? "https";
|
||||
var host = requestHttp?.Host.Value ?? "localhost:8080";
|
||||
|
||||
var callbackUrl = $"{scheme}://{host}/account/confirm-email?userId={user.Id}&code={code}";
|
||||
|
||||
var message = $@"
|
||||
<div style=""font-family: Arial, sans-serif;"">
|
||||
<h3>Welcome, {user.FullName}!</h3>
|
||||
<p>Please confirm your account by clicking the link below:</p>
|
||||
<p><a href=""{callbackUrl}"" style=""color: #2196F3; font-weight: bold; text-decoration: underline;"">Confirm Account</a></p>
|
||||
<br/>
|
||||
<p style=""font-size: 0.8em; color: #666;"">If the link doesn't work, copy and paste this URL into your browser:</p>
|
||||
<p style=""font-size: 0.8em; color: #666;"">{callbackUrl}</p>
|
||||
</div>";
|
||||
|
||||
await _emailSender.SendConfirmationLinkAsync(user, user.Email!, message);
|
||||
}
|
||||
|
||||
return new CreateUserResponse
|
||||
{
|
||||
Id = user.Id,
|
||||
Email = user.Email
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
@page "/account/reset-password"
|
||||
@layout AuthenticationLayout
|
||||
@using Indotalent.Shared.Consts
|
||||
@using Microsoft.JSInterop
|
||||
@inject IJSRuntime JSRuntime
|
||||
@inject ISnackbar Snackbar
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<PageTitle>Reset Password - @GlobalConsts.AppInitial</PageTitle>
|
||||
|
||||
<style>
|
||||
.page-header {
|
||||
text-align: center;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
.page-header h2 {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: #1e293b;
|
||||
margin: 0 0 0.25rem 0;
|
||||
}
|
||||
.page-header p {
|
||||
font-size: 0.875rem;
|
||||
color: #64748b;
|
||||
margin: 0;
|
||||
}
|
||||
.form-label {
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
color: #475569;
|
||||
margin-bottom: 0.375rem;
|
||||
margin-left: 0.25rem;
|
||||
}
|
||||
.btn-submit {
|
||||
text-transform: none;
|
||||
border-radius: 0.5rem;
|
||||
height: 48px;
|
||||
font-weight: 600;
|
||||
font-size: 0.875rem;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="page-header">
|
||||
<h2>Create New Password</h2>
|
||||
<p>Please enter your new password below.</p>
|
||||
</div>
|
||||
|
||||
<MudForm @ref="form" @bind-IsValid="@success">
|
||||
<div class="mb-3">
|
||||
<div class="form-label">New Password</div>
|
||||
<MudTextField T="string"
|
||||
@bind-Value="model.NewPassword"
|
||||
Variant="Variant.Outlined"
|
||||
Placeholder="Enter new password"
|
||||
Margin="Margin.Dense"
|
||||
InputType="@(showPassword ? InputType.Text : InputType.Password)"
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Lock"
|
||||
AdornmentEndIcon="@(showPassword? Icons.Material.Filled.Visibility : Icons.Material.Filled.VisibilityOff)"
|
||||
OnAdornmentEndClick="() => showPassword = !showPassword"
|
||||
Required="true"
|
||||
Style="border-radius: 0.5rem;" />
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<div class="form-label">Confirm New Password</div>
|
||||
<MudTextField T="string"
|
||||
@bind-Value="model.ConfirmPassword"
|
||||
Variant="Variant.Outlined"
|
||||
Placeholder="Repeat new password"
|
||||
Margin="Margin.Dense"
|
||||
InputType="@(showPassword ? InputType.Text : InputType.Password)"
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Lock"
|
||||
Required="true"
|
||||
Validation="@(new Func<string, string?>(PasswordMatch))"
|
||||
Style="border-radius: 0.5rem;" />
|
||||
</div>
|
||||
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
Size="Size.Large"
|
||||
FullWidth="true"
|
||||
Disabled="!success || isProcessing"
|
||||
OnClick="HandleResetPassword"
|
||||
Class="btn-submit">
|
||||
@if (isProcessing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<span class="ms-2">Resetting...</span>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span>Reset Password</span>
|
||||
}
|
||||
</MudButton>
|
||||
</MudForm>
|
||||
|
||||
@code {
|
||||
[SupplyParameterFromQuery] public string? userId { get; set; }
|
||||
[SupplyParameterFromQuery] public string? code { get; set; }
|
||||
|
||||
private MudForm form = default!;
|
||||
private bool success;
|
||||
private bool isProcessing;
|
||||
private bool showPassword;
|
||||
private ResetModel model = new();
|
||||
|
||||
private class ResetModel
|
||||
{
|
||||
public string NewPassword { get; set; } = "";
|
||||
public string ConfirmPassword { get; set; } = "";
|
||||
}
|
||||
|
||||
private string? PasswordMatch(string arg)
|
||||
{
|
||||
if (model.NewPassword != arg) return "Passwords do not match";
|
||||
return null;
|
||||
}
|
||||
|
||||
private async Task HandleResetPassword()
|
||||
{
|
||||
await form.Validate();
|
||||
if (!success) return;
|
||||
|
||||
if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(code))
|
||||
{
|
||||
Snackbar.Add("Invalid reset token or user ID.", Severity.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
isProcessing = true;
|
||||
StateHasChanged();
|
||||
|
||||
var result = await JSRuntime.InvokeAsync<ApiResponse>("apiResetPassword", userId, code, model.NewPassword);
|
||||
|
||||
if (result.Status == 200)
|
||||
{
|
||||
Snackbar.Add("Password reset successful! You can now sign in.", Severity.Success);
|
||||
await Task.Delay(500);
|
||||
Navigation.NavigateTo("/account/login");
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add(result.Title ?? "Failed to reset password", Severity.Error);
|
||||
}
|
||||
|
||||
isProcessing = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private class ApiResponse
|
||||
{
|
||||
public int Status { get; set; }
|
||||
public string? Title { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
<script>
|
||||
window.apiResetPassword = async (userId, code, newPassword) => {
|
||||
try {
|
||||
const response = await fetch('/api/account/reset-password', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ userId, code, newPassword })
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
return { status: 200, title: 'Success' };
|
||||
} else {
|
||||
const data = await response.json();
|
||||
let msg = 'Failed to reset password';
|
||||
if (data.errors && data.errors.length > 0) msg = data.errors[0];
|
||||
return { status: response.status, title: msg };
|
||||
}
|
||||
} catch (error) {
|
||||
return { status: 500, title: 'Network error' };
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,51 @@
|
||||
using Indotalent.Data.Entities;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.AspNetCore.WebUtilities;
|
||||
using System.Text;
|
||||
|
||||
namespace Indotalent.Features.Account.ResetPassword.Cqrs;
|
||||
|
||||
public class ResetPasswordRequest
|
||||
{
|
||||
public string UserId { get; set; } = string.Empty;
|
||||
public string Code { get; set; } = string.Empty;
|
||||
public string NewPassword { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class ResetPasswordResponse
|
||||
{
|
||||
public string Message { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public record ResetPasswordCommand(ResetPasswordRequest Data) : IRequest<ResetPasswordResponse>;
|
||||
|
||||
public class ResetPasswordHandler : IRequestHandler<ResetPasswordCommand, ResetPasswordResponse>
|
||||
{
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
|
||||
public ResetPasswordHandler(UserManager<ApplicationUser> userManager)
|
||||
{
|
||||
_userManager = userManager;
|
||||
}
|
||||
|
||||
public async Task<ResetPasswordResponse> Handle(ResetPasswordCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(request.Data.UserId);
|
||||
if (user == null)
|
||||
{
|
||||
throw new Exception("User not found.");
|
||||
}
|
||||
|
||||
var decodedCode = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(request.Data.Code));
|
||||
var result = await _userManager.ResetPasswordAsync(user, decodedCode, request.Data.NewPassword);
|
||||
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
var errors = result.Errors.Select(x => x.Description).ToList();
|
||||
throw new Exception(string.Join(", ", errors));
|
||||
}
|
||||
|
||||
return new ResetPasswordResponse { Message = "Password has been reset successfully." };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
@page "/account/tenant-selection"
|
||||
@layout AuthenticationLayout
|
||||
@using Indotalent.Shared.Consts
|
||||
@attribute [Authorize]
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@using Microsoft.JSInterop
|
||||
@inject NavigationManager Navigation
|
||||
@inject ISnackbar Snackbar
|
||||
@inject IJSRuntime JSRuntime
|
||||
|
||||
<PageTitle>Select Tenant - @GlobalConsts.AppInitial</PageTitle>
|
||||
|
||||
<div class="d-flex flex-column align-center justify-center mb-6 w-100">
|
||||
<MudText Typo="Typo.h5" Align="Align.Center" Style="font-weight: 800; width: 100%;">Select Tenant</MudText>
|
||||
<MudText Typo="Typo.body2" Align="Align.Center" Class="text-muted" Style="width: 100%;">Please select a tenant to continue</MudText>
|
||||
</div>
|
||||
|
||||
<div class="w-100 px-2">
|
||||
@if (isLoading)
|
||||
{
|
||||
<div class="d-flex justify-center my-8">
|
||||
<MudProgressCircular Color="Color.Primary" Indeterminate="true" Size="Size.Large" />
|
||||
</div>
|
||||
}
|
||||
else if (!myTenants.Any())
|
||||
{
|
||||
<MudAlert Severity="Severity.Error" Variant="Variant.Outlined" Class="my-4" Style="border-radius: 8px;">
|
||||
You don't have access to any tenant. Please contact your Administrator.
|
||||
</MudAlert>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div style="max-height: 320px; overflow-y: auto; padding-right: 4px;">
|
||||
<MudList T="TenantDto" Clickable="true" SelectionMode="SelectionMode.SingleSelection" Class="pa-0">
|
||||
@foreach (var item in myTenants)
|
||||
{
|
||||
<MudListItem OnClick="() => HandleSelectTenant(item.TenantId)"
|
||||
Icon="@Icons.Material.Filled.Business"
|
||||
IconColor="Color.Primary"
|
||||
Class="py-3 my-2"
|
||||
Style="border: 1px solid var(--mud-palette-divider); border-radius: 8px; background-color: var(--mud-palette-background-grey); transition: all 0.2s ease-in-out;">
|
||||
<ChildContent>
|
||||
<div class="d-flex flex-column">
|
||||
<MudText Typo="Typo.subtitle1" Style="font-weight: 700; color: var(--mud-palette-text-primary);">
|
||||
@item.TenantName
|
||||
</MudText>
|
||||
@if (!string.IsNullOrEmpty(item.Description))
|
||||
{
|
||||
<MudText Typo="Typo.caption" Style="color: var(--mud-palette-text-secondary);">
|
||||
@item.Description
|
||||
</MudText>
|
||||
}
|
||||
</div>
|
||||
</ChildContent>
|
||||
</MudListItem>
|
||||
}
|
||||
</MudList>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="text-center mt-6">
|
||||
<MudText Typo="Typo.body2">
|
||||
Want to sign in with another account?
|
||||
<MudLink Href="/account/logout" Color="Color.Primary" Style="font-weight: 700;">Sign Out</MudLink>
|
||||
</MudText>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
private bool isLoading = true;
|
||||
private List<TenantDto> myTenants = new();
|
||||
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
if (firstRender)
|
||||
{
|
||||
myTenants = await JSRuntime.InvokeAsync<List<TenantDto>>("apiAccountFetchMyTenants");
|
||||
isLoading = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleSelectTenant(string tenantId)
|
||||
{
|
||||
var result = await JSRuntime.InvokeAsync<ApiResult>("apiAccountConfirmTenant", tenantId);
|
||||
|
||||
if (result.Success)
|
||||
{
|
||||
Snackbar.Add("Tenant workspace loaded successfully.", Severity.Success);
|
||||
Navigation.NavigateTo("/home", forceLoad: true);
|
||||
}
|
||||
else
|
||||
{
|
||||
Snackbar.Add("Failed to assign tenant workspace.", Severity.Error);
|
||||
}
|
||||
}
|
||||
|
||||
public class TenantDto { public string TenantId { get; set; } = ""; public string TenantName { get; set; } = ""; public string? Description { get; set; } }
|
||||
public class ApiResult { public bool Success { get; set; } }
|
||||
}
|
||||
|
||||
<script>
|
||||
window.apiAccountFetchMyTenants = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/account/my-tenants', {
|
||||
method: 'GET',
|
||||
credentials: 'include'
|
||||
});
|
||||
if (response.status === 200) {
|
||||
return await response.json();
|
||||
}
|
||||
return [];
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
window.apiAccountConfirmTenant = async (tenantId) => {
|
||||
try {
|
||||
const response = await fetch('/api/account/confirm-tenant', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ tenantId }),
|
||||
credentials: 'include'
|
||||
});
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
return { success: false };
|
||||
}
|
||||
};
|
||||
</script>
|
||||
@@ -0,0 +1,67 @@
|
||||
using Indotalent.Data.Entities;
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Account.TenantSelection.Cqrs;
|
||||
|
||||
public record GetTenantsQuery(string UserId) : IRequest<List<TenantLookupDto>>;
|
||||
|
||||
public class TenantLookupDto
|
||||
{
|
||||
public string TenantId { get; set; } = string.Empty;
|
||||
public string TenantName { get; set; } = string.Empty;
|
||||
public string? Description { get; set; }
|
||||
}
|
||||
|
||||
public class GetTenantsHandler : IRequestHandler<GetTenantsQuery, List<TenantLookupDto>>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public GetTenantsHandler(AppDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task<List<TenantLookupDto>> Handle(GetTenantsQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _context.Set<TenantUser>()
|
||||
.IgnoreQueryFilters()
|
||||
.Where(tu => tu.UserId == request.UserId && tu.IsActive)
|
||||
.Select(tu => new TenantLookupDto
|
||||
{
|
||||
TenantId = tu.TenantId ?? string.Empty,
|
||||
TenantName = tu.Tenant != null ? (tu.Tenant.Name ?? "Unknown") : "Unknown",
|
||||
Description = tu.Tenant != null ? (tu.Tenant.Description ?? "") : ""
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
public record ConfirmTenantRequest(string TenantId);
|
||||
public record ConfirmTenantResponse(bool Success, string Message);
|
||||
public record ConfirmTenantCommand(string UserId, ConfirmTenantRequest Data) : IRequest<ConfirmTenantResponse>;
|
||||
|
||||
public class ConfirmTenantHandler : IRequestHandler<ConfirmTenantCommand, ConfirmTenantResponse>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public ConfirmTenantHandler(AppDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task<ConfirmTenantResponse> Handle(ConfirmTenantCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var hasAccess = await _context.Set<TenantUser>()
|
||||
.IgnoreQueryFilters()
|
||||
.AnyAsync(tu => tu.UserId == request.UserId && tu.TenantId == request.Data.TenantId && tu.IsActive, cancellationToken);
|
||||
|
||||
if (!hasAccess)
|
||||
{
|
||||
return new ConfirmTenantResponse(false, "Access denied to the selected organization.");
|
||||
}
|
||||
|
||||
return new ConfirmTenantResponse(true, "Tenant authorized.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
@using MudBlazor
|
||||
@using Microsoft.AspNetCore.Components.Forms
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using System.ComponentModel.DataAnnotations
|
||||
|
||||
@inject NavigationManager Navigation
|
||||
@inject ISnackbar Snackbar
|
||||
@@ -0,0 +1,259 @@
|
||||
@page "/appsettings/json"
|
||||
@using Indotalent.Infrastructure.Authentication.Firebase
|
||||
@using Indotalent.Infrastructure.Authentication.Keycloak
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@using Indotalent.Infrastructure.Authorization.Identity
|
||||
@attribute [Authorize(Roles = ApplicationRoles.Admin)]
|
||||
@using Indotalent.Infrastructure.Authentication.Identity
|
||||
@using Indotalent.Infrastructure.Database
|
||||
@using Indotalent.Infrastructure.BackgroundJob
|
||||
@using Indotalent.Infrastructure.Email
|
||||
@using Indotalent.Infrastructure.File
|
||||
@using Indotalent.Infrastructure.Logging
|
||||
@using Indotalent.Infrastructure.Authentication
|
||||
@using MudBlazor
|
||||
@using System.Reflection
|
||||
@inject IdentityService IdentitySvc
|
||||
@inject DatabaseService DbSvc
|
||||
@inject BackgroundJobService JobSvc
|
||||
@inject EmailService EmailSvc
|
||||
@inject FileStorageService StorageSvc
|
||||
@inject LoggingService LogSvc
|
||||
@inject FirebaseService FirebaseSvc
|
||||
@inject KeycloakService KeycloakSvc
|
||||
|
||||
<style>
|
||||
.clean-white-tabs .mud-tabs-toolbar {
|
||||
background-color: white !important;
|
||||
border-bottom: 2px solid #DCEBFA;
|
||||
border-radius: 0px !important;
|
||||
}
|
||||
|
||||
.clean-white-tabs .mud-tab {
|
||||
color: #94a3b8 !important;
|
||||
text-transform: none;
|
||||
font-weight: 500;
|
||||
min-width: 140px;
|
||||
border-radius: 0px !important;
|
||||
}
|
||||
|
||||
.clean-white-tabs .mud-tab-active {
|
||||
color: var(--mud-palette-primary) !important;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.clean-white-tabs .mud-tabs-slider {
|
||||
background-color: var(--mud-palette-primary) !important;
|
||||
height: 3px !important;
|
||||
bottom: 0;
|
||||
}
|
||||
|
||||
.soltemp-info-card {
|
||||
border: 1px solid #DCEBFA !important;
|
||||
border-radius: 0px !important;
|
||||
background-color: #ffffff;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.soltemp-info-header {
|
||||
padding: 12px 16px !important;
|
||||
background-color: #F0F7FF;
|
||||
border-bottom: 1px solid #DCEBFA;
|
||||
}
|
||||
|
||||
.soltemp-row-compact {
|
||||
display: flex;
|
||||
padding: 10px 16px;
|
||||
align-items: center;
|
||||
border-bottom: 1px solid #F0F7FF;
|
||||
}
|
||||
|
||||
.soltemp-label-text {
|
||||
width: 30%;
|
||||
font-weight: 800;
|
||||
color: #1a1a1a;
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.soltemp-value-text {
|
||||
width: 70%;
|
||||
color: #4A5D75;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 500;
|
||||
font-family: 'Consolas', monospace;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.status-chip {
|
||||
font-weight: 900;
|
||||
font-size: 10px;
|
||||
border-radius: 0px !important;
|
||||
}
|
||||
</style>
|
||||
|
||||
<MudContainer MaxWidth="MaxWidth.ExtraLarge" Class="mt-2 mb-8">
|
||||
<div class="clean-white-tabs">
|
||||
<MudTabs Elevation="0" TabPanelsClass="pt-4" Rounded="false" ApplyEffectsToContainer="true">
|
||||
|
||||
<MudTabPanel Text="Identity" Icon="@Icons.Material.Outlined.AdminPanelSettings">
|
||||
@RenderIdentityProperties(IdentitySvc.GetConfiguration(), "Security & Identity")
|
||||
</MudTabPanel>
|
||||
|
||||
<MudTabPanel Text="Database" Icon="@Icons.Material.Outlined.Storage">
|
||||
@RenderObjectProperties(DbSvc.GetConfiguration(), "Database Engine")
|
||||
</MudTabPanel>
|
||||
|
||||
<MudTabPanel Text="Jobs" Icon="@Icons.Material.Outlined.Schedule">
|
||||
@RenderObjectProperties(JobSvc.GetConfiguration(), "Background Job Services")
|
||||
</MudTabPanel>
|
||||
|
||||
<MudTabPanel Text="Email" Icon="@Icons.Material.Outlined.Email">
|
||||
@RenderObjectProperties(EmailSvc.GetConfiguration(), "Email Providers")
|
||||
</MudTabPanel>
|
||||
|
||||
<MudTabPanel Text="Storage" Icon="@Icons.Material.Outlined.CloudUpload">
|
||||
@RenderObjectProperties(StorageSvc.GetConfiguration(), "File Storage Systems")
|
||||
</MudTabPanel>
|
||||
|
||||
<MudTabPanel Text="Logging" Icon="@Icons.Material.Outlined.ListAlt">
|
||||
@RenderObjectProperties(LogSvc.GetConfiguration(), "Diagnostic Logging")
|
||||
</MudTabPanel>
|
||||
|
||||
</MudTabs>
|
||||
</div>
|
||||
</MudContainer>
|
||||
|
||||
@code {
|
||||
private RenderFragment RenderIdentityProperties(IdentitySettingsModel settings, string sectionTitle)
|
||||
{
|
||||
return __builder =>
|
||||
{
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-6 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">@sectionTitle</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b;">Security Policy & Default Credentials</MudText>
|
||||
</div>
|
||||
<div class="d-flex align-center gap-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Home" Size="Size.Small" Color="Color.Default" />
|
||||
<MudText Typo="Typo.caption" Style="color: #94a3b8;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #94a3b8;">System</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #94a3b8;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="font-weight: 600; color: #1a1a1a;">@sectionTitle</MudText>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
if (settings != null)
|
||||
{
|
||||
@RenderSectionCard("Password Policy", settings.Password)
|
||||
@RenderSectionCard("Cookie Settings", settings.Cookies)
|
||||
@RenderSectionCard("Default Admin", settings.DefaultAdmin)
|
||||
@RenderSectionCard("SignIn Policy", settings.SignIn)
|
||||
@RenderSectionCard("SSO Firebase", settings.SsoFirebase)
|
||||
@RenderSectionCard("SSO Keycloak", settings.SsoKeycloak)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private RenderFragment RenderSectionCard(string title, object sectionValue)
|
||||
{
|
||||
return __builder =>
|
||||
{
|
||||
if (sectionValue == null) return;
|
||||
|
||||
<MudCard Elevation="0" Class="soltemp-info-card">
|
||||
<div class="soltemp-info-header d-flex align-center justify-space-between">
|
||||
<MudText Typo="Typo.body1" Style="font-weight: 900; color: #1a1a1a;">@title</MudText>
|
||||
<MudChip T="string" Color="Color.Primary" Size="Size.Small" Variant="Variant.Filled" Class="status-chip">CONFIGURED</MudChip>
|
||||
</div>
|
||||
<MudCardContent Style="padding: 0;">
|
||||
@{
|
||||
var props = sectionValue.GetType().GetProperties();
|
||||
int i = 0;
|
||||
}
|
||||
@foreach (var p in props)
|
||||
{
|
||||
var val = p.GetValue(sectionValue);
|
||||
<div class="soltemp-row-compact" style="background-color: @(i++ % 2 == 0 ? "#ffffff" : "#F9FCFF");">
|
||||
<div class="soltemp-label-text">@p.Name</div>
|
||||
<div class="soltemp-value-text">
|
||||
@(MaskIfSensitive(p.Name, val?.ToString()))
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</MudCardContent>
|
||||
</MudCard>
|
||||
};
|
||||
}
|
||||
|
||||
private RenderFragment RenderObjectProperties(object settingsObj, string sectionTitle)
|
||||
{
|
||||
return __builder =>
|
||||
{
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-6 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">@sectionTitle</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b;">Configuration discovery (Full Inspection Mode)</MudText>
|
||||
</div>
|
||||
<div class="d-flex align-center gap-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Home" Size="Size.Small" Color="Color.Default" />
|
||||
<MudText Typo="Typo.caption" Style="color: #94a3b8;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #94a3b8;">System</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #94a3b8;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="font-weight: 600; color: #1a1a1a;">@sectionTitle</MudText>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
if (settingsObj != null)
|
||||
{
|
||||
var providers = settingsObj.GetType().GetProperties();
|
||||
foreach (var provider in providers)
|
||||
{
|
||||
var providerValue = provider.GetValue(settingsObj);
|
||||
if (providerValue == null) continue;
|
||||
|
||||
<MudCard Elevation="0" Class="soltemp-info-card">
|
||||
<div class="soltemp-info-header d-flex align-center justify-space-between">
|
||||
<MudText Typo="Typo.body1" Style="font-weight: 900; color: #1a1a1a;">@provider.Name</MudText>
|
||||
@{
|
||||
var isUsedProp = providerValue.GetType().GetProperty("IsUsed");
|
||||
bool isUsed = (bool)(isUsedProp?.GetValue(providerValue) ?? false);
|
||||
}
|
||||
<MudChip T="string" Color="@(isUsed? Color.Success: Color.Default)" Size="Size.Small" Variant="Variant.Filled" Class="status-chip">
|
||||
@(isUsed ? "ACTIVE" : "DISABLED")
|
||||
</MudChip>
|
||||
</div>
|
||||
<MudCardContent Style="padding: 0;">
|
||||
@{
|
||||
var props = providerValue.GetType().GetProperties();
|
||||
int i = 0;
|
||||
}
|
||||
@foreach (var p in props)
|
||||
{
|
||||
if (p.Name == "IsUsed") continue;
|
||||
<div class="soltemp-row-compact" style="background-color: @(i++ % 2 == 0 ? "#ffffff" : "#F9FCFF");">
|
||||
<div class="soltemp-label-text">@p.Name</div>
|
||||
<div class="soltemp-value-text">
|
||||
@(MaskIfSensitive(p.Name, p.GetValue(providerValue)?.ToString()))
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</MudCardContent>
|
||||
</MudCard>
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private string MaskIfSensitive(string propertyName, string value)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value)) return "-";
|
||||
var sensitiveKeys = new[] { "Password", "Secret", "Key", "Token", "ApiKey" };
|
||||
if (sensitiveKeys.Any(k => propertyName.Contains(k, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return "•••••••••••••••• (Encrypted)";
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using Indotalent.Features.Leave.LeaveBalance;
|
||||
using Indotalent.Features.Leave.LeaveCategory;
|
||||
using Indotalent.Features.Leave.LeaveRequest;
|
||||
using Indotalent.Features.Multitenant.Tenant;
|
||||
using Indotalent.Features.Multitenant.TenantUser;
|
||||
using Indotalent.Features.Organization.Branch;
|
||||
using Indotalent.Features.Organization.Department;
|
||||
using Indotalent.Features.Organization.Designation;
|
||||
using Indotalent.Features.Organization.Employee;
|
||||
using Indotalent.Features.Payroll.Deduction;
|
||||
using Indotalent.Features.Payroll.Grade;
|
||||
using Indotalent.Features.Payroll.Income;
|
||||
using Indotalent.Features.Payroll.Payrolls;
|
||||
using Indotalent.Features.Performance.Appraisal;
|
||||
using Indotalent.Features.Performance.Evaluation;
|
||||
using Indotalent.Features.Performance.Promotion;
|
||||
using Indotalent.Features.Performance.Transfer;
|
||||
using Indotalent.Features.Profile.Avatar;
|
||||
using Indotalent.Features.Profile.Password;
|
||||
using Indotalent.Features.Profile.PersonalInformation;
|
||||
using Indotalent.Features.Root.Home;
|
||||
using Indotalent.Features.Serilogs;
|
||||
using Indotalent.Features.Setting.AutoNumberSequence;
|
||||
using Indotalent.Features.Setting.Company;
|
||||
using Indotalent.Features.Setting.Currency;
|
||||
using Indotalent.Features.Setting.SystemUser;
|
||||
using Indotalent.Features.Setting.Tax;
|
||||
|
||||
namespace Indotalent.Features;
|
||||
|
||||
public static class FeaturesDI
|
||||
{
|
||||
public static IServiceCollection AddFeaturesDI(this IServiceCollection services)
|
||||
{
|
||||
//Setting
|
||||
services.AddScoped<SerilogsService>();
|
||||
services.AddScoped<CurrencyService>();
|
||||
services.AddScoped<AutoNumberSequenceService>();
|
||||
services.AddScoped<SystemUserService>();
|
||||
services.AddScoped<CompanyService>();
|
||||
services.AddScoped<TaxService>();
|
||||
|
||||
|
||||
//organization
|
||||
services.AddScoped<BranchService>();
|
||||
services.AddScoped<DepartmentService>();
|
||||
services.AddScoped<DesignationService>();
|
||||
services.AddScoped<EmployeeService>();
|
||||
|
||||
//profile
|
||||
services.AddScoped<PersonalInformationService>();
|
||||
services.AddScoped<PasswordService>();
|
||||
services.AddScoped<AvatarService>();
|
||||
|
||||
//leave
|
||||
services.AddScoped<LeaveCategoryService>();
|
||||
services.AddScoped<LeaveRequestService>();
|
||||
services.AddScoped<LeaveBalanceService>();
|
||||
|
||||
//performance
|
||||
services.AddScoped<EvaluationService>();
|
||||
services.AddScoped<AppraisalService>();
|
||||
services.AddScoped<PromotionService>();
|
||||
services.AddScoped<TransferService>();
|
||||
|
||||
//payroll
|
||||
services.AddScoped<IncomeService>();
|
||||
services.AddScoped<DeductionService>();
|
||||
services.AddScoped<GradeService>();
|
||||
services.AddScoped<PayrollsService>();
|
||||
|
||||
//root
|
||||
services.AddScoped<HomeService>();
|
||||
|
||||
//multitenant
|
||||
services.AddScoped<TenantService>();
|
||||
services.AddScoped<TenantUserService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
using Indotalent.Features.Leave.LeaveBalance;
|
||||
using Indotalent.Features.Leave.LeaveCategory;
|
||||
using Indotalent.Features.Leave.LeaveRequest;
|
||||
using Indotalent.Features.Multitenant.Tenant;
|
||||
using Indotalent.Features.Multitenant.TenantUser;
|
||||
using Indotalent.Features.Organization.Branch;
|
||||
using Indotalent.Features.Organization.Department;
|
||||
using Indotalent.Features.Organization.Designation;
|
||||
using Indotalent.Features.Organization.Employee;
|
||||
using Indotalent.Features.Payroll.Deduction;
|
||||
using Indotalent.Features.Payroll.Grade;
|
||||
using Indotalent.Features.Payroll.Income;
|
||||
using Indotalent.Features.Payroll.Payrolls;
|
||||
using Indotalent.Features.Performance.Appraisal;
|
||||
using Indotalent.Features.Performance.Evaluation;
|
||||
using Indotalent.Features.Performance.Promotion;
|
||||
using Indotalent.Features.Performance.Transfer;
|
||||
using Indotalent.Features.Profile.Avatar;
|
||||
using Indotalent.Features.Profile.Password;
|
||||
using Indotalent.Features.Profile.PersonalInformation;
|
||||
using Indotalent.Features.Root.Home;
|
||||
using Indotalent.Features.Serilogs;
|
||||
using Indotalent.Features.Setting.AutoNumberSequence;
|
||||
using Indotalent.Features.Setting.Company;
|
||||
using Indotalent.Features.Setting.Currency;
|
||||
using Indotalent.Features.Setting.SystemUser;
|
||||
using Indotalent.Features.Setting.Tax;
|
||||
|
||||
namespace Indotalent.Features;
|
||||
|
||||
public static class FeaturesEndpointMap
|
||||
{
|
||||
public static IEndpointRouteBuilder MapFeaturesEndpoint(this IEndpointRouteBuilder app)
|
||||
{
|
||||
//setting
|
||||
app.MapSerilogsEndpoints();
|
||||
app.MapCurrencyEndpoints();
|
||||
app.MapAutoNumberSequenceEndpoints();
|
||||
app.MapSystemUserEndpoints();
|
||||
app.MapCompanyEndpoints();
|
||||
app.MapTaxEndpoints();
|
||||
|
||||
//organization
|
||||
app.MapBranchEndpoints();
|
||||
app.MapDepartmentEndpoints();
|
||||
app.MapDesignationEndpoints();
|
||||
app.MapEmployeeEndpoints();
|
||||
|
||||
//profile
|
||||
app.MapPersonalInformationEndpoints();
|
||||
app.MapPasswordEndpoints();
|
||||
app.MapAvatarEndpoints();
|
||||
|
||||
//leave
|
||||
app.MapLeaveCategoryEndpoints();
|
||||
app.MapLeaveRequestEndpoints();
|
||||
app.MapLeaveBalanceEndpoints();
|
||||
|
||||
//performance
|
||||
app.MapEvaluationEndpoints();
|
||||
app.MapAppraisalEndpoints();
|
||||
app.MapPromotionEndpoints();
|
||||
app.MapTransferEndpoints();
|
||||
|
||||
//payroll
|
||||
app.MapIncomeEndpoints();
|
||||
app.MapDeductionEndpoints();
|
||||
app.MapGradeEndpoints();
|
||||
app.MapPayrollsEndpoints();
|
||||
|
||||
//root
|
||||
app.MapHomeEndpoints();
|
||||
|
||||
//multitenant
|
||||
app.MapTenantEndpoints();
|
||||
app.MapTenantUserEndpoints();
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
@page "/leave/leave-balance"
|
||||
@using Indotalent.Features.Leave.LeaveBalance.Components
|
||||
@using Indotalent.Features.Leave.LeaveBalance.Cqrs
|
||||
@using MudBlazor
|
||||
|
||||
@if (_currentView == ViewMode.Create)
|
||||
{
|
||||
<_LeaveBalanceCreateForm OnCancel="BackToTable" OnSuccess="HandleSuccess" />
|
||||
}
|
||||
else if (_currentView == ViewMode.Update || _currentView == ViewMode.View)
|
||||
{
|
||||
<_LeaveBalanceUpdateForm Data="_selectedData!" ReadOnly="@(_currentView == ViewMode.View)" OnCancel="BackToTable" OnSuccess="HandleSuccess" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<_LeaveBalanceDataTable OnAdd="() => ShowCreate()" OnEdit="(item) => ShowUpdate(item, false)" OnView="(item) => ShowUpdate(item, true)" />
|
||||
}
|
||||
|
||||
@code {
|
||||
private enum ViewMode { Table, Create, Update, View }
|
||||
private ViewMode _currentView = ViewMode.Table;
|
||||
private UpdateLeaveBalanceRequest? _selectedData;
|
||||
|
||||
private void ShowCreate()
|
||||
{
|
||||
_currentView = ViewMode.Create;
|
||||
}
|
||||
|
||||
private void ShowUpdate(UpdateLeaveBalanceRequest data, bool isReadOnly)
|
||||
{
|
||||
_selectedData = data;
|
||||
_currentView = isReadOnly ? ViewMode.View : ViewMode.Update;
|
||||
}
|
||||
|
||||
private void BackToTable()
|
||||
{
|
||||
_currentView = ViewMode.Table;
|
||||
_selectedData = null;
|
||||
}
|
||||
|
||||
private void HandleSuccess()
|
||||
{
|
||||
_currentView = ViewMode.Table;
|
||||
_selectedData = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
@using Indotalent.Features.Leave.LeaveBalance
|
||||
@using Indotalent.Features.Leave.LeaveBalance.Cqrs
|
||||
@using Indotalent.Features.Leave.LeaveRequest.Cqrs
|
||||
@using Indotalent.Features.Leave.LeaveRequest
|
||||
@using Indotalent.Features.Leave.LeaveCategory
|
||||
@using Indotalent.Features.Leave.LeaveCategory.Cqrs
|
||||
@using Indotalent.Shared.Utils
|
||||
@using MudBlazor
|
||||
@inject LeaveBalanceService LeaveBalanceService
|
||||
@inject LeaveRequestService LeaveRequestService
|
||||
@inject LeaveCategoryService LeaveCategoryService
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
|
||||
<div class="d-flex align-center gap-4">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">Create Leave Balance</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b;">Initialize new leave quota for an employee.</MudText>
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA;">
|
||||
<MudForm @ref="_form" Model="_model">
|
||||
<MudGrid Spacing="3">
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Employee</MudText>
|
||||
<MudSelect T="string" @bind-Value="_model.EmployeeId" For="@(() => _model.EmployeeId)" Variant="Variant.Outlined" Margin="Margin.Dense" AnchorOrigin="Origin.BottomLeft" TransformOrigin="Origin.TopLeft">
|
||||
@foreach (var emp in _employees)
|
||||
{
|
||||
<MudSelectItem Value="@emp.Id">@emp.FullName (@emp.Code)</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Leave Type</MudText>
|
||||
<MudSelect T="string" @bind-Value="_model.LeaveCategoryId" For="@(() => _model.LeaveCategoryId)" Variant="Variant.Outlined" Margin="Margin.Dense" AnchorOrigin="Origin.BottomLeft" TransformOrigin="Origin.TopLeft">
|
||||
@foreach (var cat in _categories)
|
||||
{
|
||||
<MudSelectItem Value="@cat.Id">@cat.Name</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Year</MudText>
|
||||
<MudNumericField @bind-Value="_model.Year" Variant="Variant.Outlined" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Entitlement (Quota)</MudText>
|
||||
<MudNumericField @bind-Value="_model.Entitlement" Variant="Variant.Outlined" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Carry Forward</MudText>
|
||||
<MudNumericField @bind-Value="_model.CarryForward" Variant="Variant.Outlined" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Valid From</MudText>
|
||||
<MudDatePicker @bind-Date="_validFrom" Variant="Variant.Outlined" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Valid To</MudText>
|
||||
<MudDatePicker @bind-Date="_validTo" Variant="Variant.Outlined" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
<div class="d-flex justify-end gap-2 mt-8">
|
||||
<MudButton OnClick="() => OnCancel.InvokeAsync()" Variant="Variant.Outlined" Disabled="_processing" Style="border: 1px solid #e0e0e0;">Cancel</MudButton>
|
||||
<MudButton Color="Color.Warning" Variant="Variant.Filled" OnClick="Submit" Disabled="_processing" Style="color:white; font-weight:700;">Create Balance</MudButton>
|
||||
</div>
|
||||
</MudForm>
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter] public EventCallback OnCancel { get; set; }
|
||||
[Parameter] public EventCallback OnSuccess { get; set; }
|
||||
private MudForm _form = default!;
|
||||
private CreateLeaveBalanceValidator _validator = new();
|
||||
private CreateLeaveBalanceRequest _model = new() { Year = DateTime.Today.Year, ValidFrom = new DateTime(DateTime.Today.Year, 1, 1), ValidTo = new DateTime(DateTime.Today.Year, 12, 31) };
|
||||
private List<EmployeeLeaveReferenceResponse> _employees = new();
|
||||
private List<GetLeaveCategoryListResponse> _categories = new();
|
||||
private bool _processing = false;
|
||||
private DateTime? _validFrom { get => _model.ValidFrom; set => _model.ValidFrom = value ?? DateTime.Today; }
|
||||
private DateTime? _validTo { get => _model.ValidTo; set => _model.ValidTo = value ?? DateTime.Today; }
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
var empRes = await LeaveRequestService.GetEmployeeReferenceAsync();
|
||||
if (empRes?.IsSuccess == true) _employees = empRes.Value ?? new();
|
||||
var catRes = await LeaveCategoryService.GetLeaveCategoryListAsync();
|
||||
if (catRes?.IsSuccess == true) _categories = catRes.Value ?? new();
|
||||
}
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
await _form.Validate(); if (!_form.IsValid) return;
|
||||
_processing = true;
|
||||
try
|
||||
{
|
||||
_model.Remaining = (_model.Entitlement + _model.CarryForward) - _model.Used;
|
||||
var res = await LeaveBalanceService.CreateLeaveBalanceAsync(_model);
|
||||
await Task.Delay(500);
|
||||
if (res?.IsSuccess == true) { Snackbar.Add("Balance created", Severity.Success); await OnSuccess.InvokeAsync(); }
|
||||
}
|
||||
finally { _processing = false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
@using Indotalent.ConfigBackEnd.Extensions
|
||||
@using Indotalent.Features.Leave.LeaveBalance
|
||||
@using Indotalent.Features.Leave.LeaveBalance.Cqrs
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using Microsoft.JSInterop
|
||||
@using MudBlazor
|
||||
@using Features.Root.Shared
|
||||
@using ClosedXML.Excel
|
||||
@using System.IO
|
||||
@inject LeaveBalanceService LeaveBalanceService
|
||||
@inject IDialogService DialogService
|
||||
@inject ISnackbar Snackbar
|
||||
@inject IJSRuntime JSRuntime
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #E5E7EB; border-radius: 12px;">
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 700; color: #111827;">Leave Balances</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #9CA3AF;">Review employee leave entitlements, usage, and remaining days for the current period.</MudText>
|
||||
</div>
|
||||
<div class="d-flex align-center gap-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Home" Size="Size.Small" Color="Color.Default" />
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">Leave</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="font-weight: 600; color: #111827;">Balance</MudText>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Style="border-radius: 12px; overflow: hidden; background-color: #ffffff; border: 1px solid #E5E7EB;">
|
||||
|
||||
<div style="padding: 20px 24px; border-bottom: 1px solid #E5E7EB; display: flex; justify-content: space-between; align-items: center; background-color: #F8FAFC; min-height: 80px;">
|
||||
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<MudTextField @bind-Value="_searchString"
|
||||
Placeholder="Search..."
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Search"
|
||||
IconSize="Size.Small"
|
||||
Class="mt-0"
|
||||
Variant="Variant.Outlined"
|
||||
Margin="Margin.Dense"
|
||||
Style="background-color: white; width: 280px; border-radius: 8px;"
|
||||
OnKeyDown="@HandleSearchKeyDown" />
|
||||
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
OnClick="OnSearchClick"
|
||||
Size="Size.Small"
|
||||
Style="text-transform: none; font-weight: 500; border-radius: 6px; height: 34px; box-shadow: none;">
|
||||
Search
|
||||
</MudButton>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<MudButton Variant="Variant.Outlined"
|
||||
Color="Color.Success"
|
||||
OnClick="ExportToExcel"
|
||||
Size="Size.Small"
|
||||
Disabled="_isExporting"
|
||||
StartIcon="@(_isExporting ? null : Icons.Custom.FileFormats.FileExcel)"
|
||||
Style="border: 1px solid #D1D5DB; background: white; font-weight: 500; border-radius: 6px; text-transform: none; height: 34px; color: #6B7280;">
|
||||
@if (_isExporting)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText Typo="Typo.button" Style="text-transform: none !important;">Excel</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
|
||||
<MudButton Variant="Variant.Outlined"
|
||||
Color="Color.Primary"
|
||||
OnClick="LoadData"
|
||||
Size="Size.Small"
|
||||
StartIcon="@(_isRefreshing ? null : Icons.Material.Filled.Refresh)"
|
||||
Disabled="_isRefreshing"
|
||||
Style="border: 1px solid #D1D5DB; background: white; font-weight: 500; border-radius: 6px; text-transform: none; height: 34px; color: #6B7280;">
|
||||
@if (_isRefreshing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Refreshing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText Typo="Typo.button" Style="text-transform: none !important;">Refresh</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
|
||||
@if (_selectedBalance != null)
|
||||
{
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Info" StartIcon="@Icons.Material.Filled.Visibility" OnClick="InvokeView" Size="Size.Small" Style="border: 1px solid #D1D5DB; text-transform: none; font-weight: 500; border-radius: 6px; background: white; color: #6B7280;">View</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Info" StartIcon="@Icons.Material.Filled.Edit" OnClick="InvokeEdit" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px;">Adjust Balance</MudButton>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Delete" Color="Color.Error" Size="Size.Small" OnClick="OnDelete" />
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Close" Size="Size.Small" OnClick="() => _selectedBalance = null" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Info" StartIcon="@Icons.Material.Filled.Calculate" OnClick="OnSyncAll" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; height: 34px;">
|
||||
Recalculate All
|
||||
</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Add" OnClick="() => OnAdd.InvokeAsync()" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; height: 34px;">
|
||||
Create Manual Balance
|
||||
</MudButton>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<MudTable Items="@GetPagedData()" Hover="true" Striped="true" Class="mud-table-styled" Elevation="0" CustomHeader="true" Dense="true" T="GetLeaveBalanceListResponse" OnRowClick="@((args) => _selectedBalance = args.Item)" Loading="@_isRefreshing">
|
||||
<HeaderContent>
|
||||
<MudTh Style="width: 50px; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB;"></MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetLeaveBalanceListResponse, object>(x => x.EmployeeName!)">Employee</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetLeaveBalanceListResponse, object>(x => x.LeaveCategoryName!)">Leave Type</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetLeaveBalanceListResponse, object>(x => x.Year)">Year</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; text-align: center;">ENTITLEMENT</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; text-align: center;">USED</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; text-align: center;">PENDING</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; text-align: center;">REMAINING</MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd>
|
||||
<MudCheckBox T="bool" Value="@(_selectedBalance?.Id == context.Id)" Color="Color.Primary" Dense="true" Size="Size.Small" ReadOnly="true" />
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<div class="d-flex align-center">
|
||||
<MudAvatar Color="@GetRandomColor(context.EmployeeName!)" Size="Size.Small" Class="mr-3" Style="font-weight: 600; font-size: 0.7rem;">
|
||||
@(!string.IsNullOrWhiteSpace(context.EmployeeName) ? context.EmployeeName.Substring(0, 2).ToUpper() : "??")
|
||||
</MudAvatar>
|
||||
<div>
|
||||
<MudText Typo="Typo.body2" Style="font-weight: 700;">@context.EmployeeName</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">@context.EmployeeCode</MudText>
|
||||
</div>
|
||||
</div>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudText Typo="Typo.body2" Style="font-size: 0.8rem;">@context.LeaveCategoryName</MudText>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudText Typo="Typo.body2" Style="font-weight: 600;">@context.Year</MudText>
|
||||
</MudTd>
|
||||
<MudTd Style="text-align: center;">
|
||||
<MudText Typo="Typo.body2" Style="font-weight: 600;">@context.Entitlement Days</MudText>
|
||||
</MudTd>
|
||||
<MudTd Style="text-align: center;">
|
||||
<MudText Typo="Typo.body2" Style="color: #ef4444; font-weight: 600;">@context.Used</MudText>
|
||||
</MudTd>
|
||||
<MudTd Style="text-align: center;">
|
||||
<MudText Typo="Typo.body2" Style="color: #f59e0b; font-weight: 600;">@context.Pending</MudText>
|
||||
</MudTd>
|
||||
<MudTd Style="text-align: center;">
|
||||
<MudChip T="string" Size="Size.Small" Variant="Variant.Filled" Color="Color.Success" Style="font-weight: 700; border-radius: 6px; min-width: 60px;">
|
||||
@context.Remaining
|
||||
</MudChip>
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
</MudTable>
|
||||
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; padding: 12px 24px; background-color: #F8FAFC; border-top: 2px solid #E5E7EB;">
|
||||
<div style="display: flex; align-items: center; gap: 12px;">
|
||||
<MudText Typo="Typo.caption" Style="font-weight: 700; color: #1e293b;">Rows per page:</MudText>
|
||||
|
||||
<MudSelect T="int"
|
||||
Value="@_top"
|
||||
ValueChanged="OnPageSizeChanged"
|
||||
Dense="true"
|
||||
Margin="Margin.Dense"
|
||||
Style="width: 80px; background-color: white; font-size: 0.75rem; font-weight: 500;"
|
||||
Variant="Variant.Outlined"
|
||||
Class="mt-0 custom-select-dense">
|
||||
<MudSelectItem Value="5" />
|
||||
<MudSelectItem Value="10" />
|
||||
<MudSelectItem Value="50" />
|
||||
<MudSelectItem Value="500" />
|
||||
<MudSelectItem Value="1000" />
|
||||
</MudSelect>
|
||||
|
||||
<MudText Typo="Typo.caption" Style="color: #64748b; margin-left: 12px;">
|
||||
Showing @(GetFilteredData().Count() == 0 ? 0 : _skip + 1)-@Math.Min(_skip + _top, GetFilteredData().Count()) of @GetFilteredData().Count()
|
||||
</MudText>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.FirstPage" Size="Size.Small" OnClick="@(() => OnPageChanged(1))" Disabled="@(_currentPage == 1)" Style="@(_currentPage == 1 ? "color: #D1D5DB; background: transparent;" : "color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px;")" />
|
||||
<MudButton OnClick="@(() => OnPageChanged(_currentPage - 1))" Disabled="@(_currentPage == 1)" Variant="Variant.Text" StartIcon="@Icons.Material.Filled.ChevronLeft" Size="Size.Small" Style="@(_currentPage == 1 ? "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;" : "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;")">Prev</MudButton>
|
||||
@{
|
||||
var totalPages = _totalPage == 0 ? 1 : _totalPage;
|
||||
var maxVisible = 5;
|
||||
var startPage = Math.Max(1, _currentPage - maxVisible / 2);
|
||||
var endPage = Math.Min(totalPages, startPage + maxVisible - 1);
|
||||
if (endPage - startPage < maxVisible - 1) { startPage = Math.Max(1, endPage - maxVisible + 1); }
|
||||
}
|
||||
@for (int i = startPage; i <= endPage; i++)
|
||||
{
|
||||
var pageNum = i;
|
||||
var isActive = pageNum == _currentPage;
|
||||
<MudButton OnClick="@(() => OnPageChanged(pageNum))"
|
||||
Variant="Variant.Text" Size="Size.Small"
|
||||
Style="@(isActive ? "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 600; background: #3B82F6; color: white; border: 1px solid #3B82F6; border-radius: 6px; text-transform: none;" : "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 500; color: #374151; background: white; border: 1px solid #D1D5DB; border-radius: 6px; text-transform: none;")">@pageNum</MudButton>
|
||||
}
|
||||
<MudButton OnClick="@(() => OnPageChanged(_currentPage + 1))" Disabled="@(_currentPage == _totalPage || _totalPage == 0)" Variant="Variant.Text" EndIcon="@Icons.Material.Filled.ChevronRight" Size="Size.Small" Style="@(_currentPage == _totalPage || _totalPage == 0 ? "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;" : "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;")">Next</MudButton>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.LastPage" Size="Size.Small" OnClick="@(() => OnPageChanged(_totalPage))" Disabled="@(_currentPage == _totalPage || _totalPage == 0)" Style="@(_currentPage == _totalPage || _totalPage == 0 ? "color: #D1D5DB; background: transparent;" : "color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px;")" />
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<script>
|
||||
function downloadFile(fileName, contentType, base64String) {
|
||||
const link = document.createElement('a');
|
||||
link.download = fileName;
|
||||
link.href = `data:${contentType};base64,${base64String}`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.mud-input-outlined-border { border-radius: 8px !important; }
|
||||
.custom-select-dense .mud-input-control { margin-top: 0 !important; }
|
||||
.custom-select-dense .mud-input-slot { padding-top: 4px !important; padding-bottom: 4px !important; padding-left: 8px !important; font-size: 12px !important; }
|
||||
.mud-table-styled .mud-table-row:hover { background-color: #F9FAFB !important; }
|
||||
</style>
|
||||
|
||||
@code {
|
||||
[Parameter] public EventCallback OnAdd { get; set; }
|
||||
[Parameter] public EventCallback<UpdateLeaveBalanceRequest> OnEdit { get; set; }
|
||||
[Parameter] public EventCallback<UpdateLeaveBalanceRequest> OnView { get; set; }
|
||||
|
||||
private List<GetLeaveBalanceListResponse> _balances = new();
|
||||
private GetLeaveBalanceListResponse? _selectedBalance;
|
||||
private string _searchString = "";
|
||||
private int _skip = 0;
|
||||
private int _top = 5;
|
||||
private int _totalPage => GetFilteredData().Count() == 0 ? 0 : (int)Math.Ceiling((double)GetFilteredData().Count() / (_top == 0 ? 1 : _top));
|
||||
private int _currentPage => (_top >= GetFilteredData().Count() || _top == 0) ? 1 : (_skip / _top) + 1;
|
||||
private bool _isRefreshing = false;
|
||||
private bool _isExporting = false;
|
||||
|
||||
protected override async Task OnInitializedAsync() => await LoadData();
|
||||
|
||||
private async Task LoadData()
|
||||
{
|
||||
_isRefreshing = true; _selectedBalance = null;
|
||||
StateHasChanged();
|
||||
try
|
||||
{
|
||||
var response = await LeaveBalanceService.GetLeaveBalanceListAsync();
|
||||
await Task.Delay(800);
|
||||
if (response != null && response.IsSuccess)
|
||||
{
|
||||
_balances = response.Value ?? new();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isRefreshing = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerable<GetLeaveBalanceListResponse> GetFilteredData()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_searchString)) return _balances;
|
||||
return _balances.Where(x =>
|
||||
(x.EmployeeName?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.EmployeeCode?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.LeaveCategoryName?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.Year.ToString().Contains(_searchString))
|
||||
);
|
||||
}
|
||||
|
||||
private IEnumerable<GetLeaveBalanceListResponse> GetPagedData() => GetFilteredData().Skip(_skip).Take(_top);
|
||||
|
||||
private async Task ExportToExcel()
|
||||
{
|
||||
_isExporting = true;
|
||||
StateHasChanged();
|
||||
try
|
||||
{
|
||||
await Task.Delay(1000);
|
||||
using (var workbook = new XLWorkbook())
|
||||
{
|
||||
var worksheet = workbook.Worksheets.Add("LeaveBalances");
|
||||
var currentRow = 1;
|
||||
|
||||
worksheet.Cell(currentRow, 1).Value = "Employee Name";
|
||||
worksheet.Cell(currentRow, 2).Value = "Employee Code";
|
||||
worksheet.Cell(currentRow, 3).Value = "Leave Type";
|
||||
worksheet.Cell(currentRow, 4).Value = "Year";
|
||||
worksheet.Cell(currentRow, 5).Value = "Entitlement";
|
||||
worksheet.Cell(currentRow, 6).Value = "Used";
|
||||
worksheet.Cell(currentRow, 7).Value = "Pending";
|
||||
worksheet.Cell(currentRow, 8).Value = "Remaining";
|
||||
|
||||
var headerRange = worksheet.Range(1, 1, 1, 8);
|
||||
headerRange.Style.Font.Bold = true;
|
||||
headerRange.Style.Fill.BackgroundColor = XLColor.FromHtml("#0D47A1");
|
||||
headerRange.Style.Font.FontColor = XLColor.White;
|
||||
|
||||
foreach (var item in GetFilteredData())
|
||||
{
|
||||
currentRow++;
|
||||
worksheet.Cell(currentRow, 1).Value = item.EmployeeName;
|
||||
worksheet.Cell(currentRow, 2).Value = item.EmployeeCode;
|
||||
worksheet.Cell(currentRow, 3).Value = item.LeaveCategoryName;
|
||||
worksheet.Cell(currentRow, 4).Value = item.Year;
|
||||
worksheet.Cell(currentRow, 5).Value = item.Entitlement;
|
||||
worksheet.Cell(currentRow, 6).Value = item.Used;
|
||||
worksheet.Cell(currentRow, 7).Value = item.Pending;
|
||||
worksheet.Cell(currentRow, 8).Value = item.Remaining;
|
||||
}
|
||||
|
||||
worksheet.Columns().AdjustToContents();
|
||||
|
||||
using (var stream = new MemoryStream())
|
||||
{
|
||||
workbook.SaveAs(stream);
|
||||
var content = Convert.ToBase64String(stream.ToArray());
|
||||
await JSRuntime.InvokeVoidAsync("downloadFile", "Leave_Balance_Report.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", content);
|
||||
Snackbar.Add("Excel exported successfully", Severity.Success);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Export failed: {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isExporting = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnSearchClick()
|
||||
{
|
||||
_skip = 0;
|
||||
_selectedBalance = null;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private void HandleSearchKeyDown(KeyboardEventArgs e)
|
||||
{
|
||||
if (e.Key == "Enter") OnSearchClick();
|
||||
}
|
||||
|
||||
private void OnPageChanged(int page)
|
||||
{
|
||||
if (page >= 1 && page <= _totalPage)
|
||||
{
|
||||
_skip = (page - 1) * _top;
|
||||
_selectedBalance = null;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPageSizeChanged(int size)
|
||||
{
|
||||
_top = size;
|
||||
_skip = 0;
|
||||
_selectedBalance = null;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private Color GetRandomColor(string name)
|
||||
{
|
||||
int hash = name.GetHashCode();
|
||||
var colors = new[] { Color.Primary, Color.Secondary, Color.Tertiary, Color.Info, Color.Success, Color.Warning, Color.Dark };
|
||||
return colors[Math.Abs(hash) % colors.Length];
|
||||
}
|
||||
|
||||
private async Task OnSyncAll()
|
||||
{
|
||||
_isRefreshing = true;
|
||||
StateHasChanged();
|
||||
try
|
||||
{
|
||||
var success = await LeaveBalanceService.SyncAllLeaveBalancesAsync();
|
||||
if (success)
|
||||
{
|
||||
Snackbar.Add("All balances recalculated successfully", Severity.Success);
|
||||
await LoadData();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isRefreshing = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task InvokeEdit()
|
||||
{
|
||||
if (_selectedBalance != null)
|
||||
{
|
||||
var res = await LeaveBalanceService.GetLeaveBalanceByIdAsync(_selectedBalance.Id!);
|
||||
if (res?.Value != null) await OnEdit.InvokeAsync(MapToUpdate(res.Value));
|
||||
}
|
||||
}
|
||||
|
||||
private async Task InvokeView()
|
||||
{
|
||||
if (_selectedBalance != null)
|
||||
{
|
||||
var res = await LeaveBalanceService.GetLeaveBalanceByIdAsync(_selectedBalance.Id!);
|
||||
if (res?.Value != null) await OnView.InvokeAsync(MapToUpdate(res.Value));
|
||||
}
|
||||
}
|
||||
|
||||
private UpdateLeaveBalanceRequest MapToUpdate(GetLeaveBalanceByIdResponse d) => new UpdateLeaveBalanceRequest
|
||||
{
|
||||
Id = d.Id,
|
||||
EmployeeId = d.EmployeeId!,
|
||||
EmployeeName = d.EmployeeName,
|
||||
LeaveCategoryId = d.LeaveCategoryId!,
|
||||
LeaveCategoryName = d.LeaveCategoryName,
|
||||
Entitlement = d.Entitlement,
|
||||
Used = d.Used,
|
||||
Pending = d.Pending,
|
||||
Remaining = d.Remaining,
|
||||
Year = d.Year,
|
||||
ValidFrom = d.ValidFrom,
|
||||
ValidTo = d.ValidTo,
|
||||
CarryForward = d.CarryForward,
|
||||
CreatedAt = d.CreatedAt,
|
||||
CreatedBy = d.CreatedBy,
|
||||
UpdatedAt = d.UpdatedAt,
|
||||
UpdatedBy = d.UpdatedBy
|
||||
};
|
||||
|
||||
private async Task OnDelete()
|
||||
{
|
||||
if (_selectedBalance == null) return;
|
||||
var dialog = await DialogService.ShowAsync<Features.Root.Shared._DeleteConfirmation>("", new DialogParameters<Features.Root.Shared._DeleteConfirmation> { { x => x.ContentText, $"Balance for {_selectedBalance.EmployeeName}" } });
|
||||
if (!(await dialog.Result).Canceled)
|
||||
{
|
||||
if (await LeaveBalanceService.DeleteLeaveBalanceByIdAsync(_selectedBalance.Id!)) { await LoadData(); Snackbar.Add("Balance removed", Severity.Success); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
@using Indotalent.ConfigBackEnd.Extensions
|
||||
@using Indotalent.Features.Leave.LeaveBalance
|
||||
@using Indotalent.Features.Leave.LeaveBalance.Cqrs
|
||||
@using Indotalent.Features.Leave.LeaveRequest
|
||||
@using Indotalent.Features.Leave.LeaveRequest.Cqrs
|
||||
@using Indotalent.Features.Leave.LeaveCategory
|
||||
@using Indotalent.Features.Leave.LeaveCategory.Cqrs
|
||||
@using Indotalent.Shared.Utils
|
||||
@using MudBlazor
|
||||
@inject LeaveBalanceService LeaveBalanceService
|
||||
@inject LeaveRequestService LeaveRequestService
|
||||
@inject LeaveCategoryService LeaveCategoryService
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
|
||||
<div class="d-flex align-center gap-4">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">@(ReadOnly ? "Balance Details" : "Adjust Balance")</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b;">Review or modify employee leave quota for the specified period.</MudText>
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA;">
|
||||
@if (_isInitialLoading)
|
||||
{
|
||||
<div class="d-flex flex-column align-center justify-center pa-10">
|
||||
<MudProgressCircular Color="Color.Info" Indeterminate="true" Size="Size.Large" />
|
||||
<MudText Typo="Typo.body2" Class="mt-4">Loading balance configuration...</MudText>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudForm @ref="_form" Model="_model">
|
||||
<MudGrid Spacing="3">
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Employee</MudText>
|
||||
<MudSelect T="string" @bind-Value="_model.EmployeeId"
|
||||
ReadOnly="ReadOnly"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense"
|
||||
AnchorOrigin="Origin.BottomLeft" TransformOrigin="Origin.TopLeft">
|
||||
@foreach (var emp in _employees)
|
||||
{
|
||||
<MudSelectItem Value="@emp.Id">@emp.FullName (@emp.Code)</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Leave Type</MudText>
|
||||
<MudSelect T="string" @bind-Value="_model.LeaveCategoryId"
|
||||
ReadOnly="ReadOnly"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense"
|
||||
AnchorOrigin="Origin.BottomLeft" TransformOrigin="Origin.TopLeft">
|
||||
@foreach (var cat in _categories)
|
||||
{
|
||||
<MudSelectItem Value="@cat.Id">@cat.Name</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Year</MudText>
|
||||
<MudNumericField @bind-Value="_model.Year" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Entitlement (Base Quota)</MudText>
|
||||
<MudNumericField @bind-Value="_model.Entitlement" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Carry Forward</MudText>
|
||||
<MudNumericField @bind-Value="_model.CarryForward" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Validity Period (From)</MudText>
|
||||
<MudDatePicker @bind-Date="_validFrom" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Validity Period (To)</MudText>
|
||||
<MudDatePicker @bind-Date="_validTo" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" Class="mt-4">
|
||||
<MudText Typo="Typo.button" Color="Color.Info" Style="font-weight: 800;">Calculation Summary</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Used (Days)</MudText>
|
||||
<MudNumericField @bind-Value="_model.Used" ReadOnly="true" Variant="Variant.Filled" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Pending (Days)</MudText>
|
||||
<MudNumericField @bind-Value="_model.Pending" ReadOnly="true" Variant="Variant.Filled" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Remaining Balance</MudText>
|
||||
<MudNumericField Value="@((_model.Entitlement + _model.CarryForward) - _model.Used - _model.Pending)"
|
||||
ReadOnly="true" Variant="Variant.Filled" Margin="Margin.Dense"
|
||||
Style="font-weight: 900; color: #2e7d32;" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" Class="mt-4">
|
||||
<MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">Audit History</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudGrid Spacing="2">
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Created By</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@(!string.IsNullOrEmpty(_model.CreatedBy) ? _model.CreatedBy : "System")</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Updated By</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@(!string.IsNullOrEmpty(_model.UpdatedBy) ? _model.UpdatedBy : "-")</MudText>
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudGrid Spacing="2">
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Created At</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@DateTimeExtensions.ToString(_model.CreatedAt)</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Updated At</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@DateTimeExtensions.ToString(_model.UpdatedAt)</MudText>
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<div class="d-flex justify-end gap-2 mt-10">
|
||||
<MudButton OnClick="() => OnCancel.InvokeAsync()" Variant="Variant.Outlined" Disabled="_processing" Style="border: 1px solid #e0e0e0; border-radius: 4px; text-transform: none; font-weight: 700;">@(ReadOnly ? "Back to List" : "Cancel")</MudButton>
|
||||
@if (!ReadOnly)
|
||||
{
|
||||
<MudButton Color="Color.Info" Variant="Variant.Filled" OnClick="Submit" Disabled="_processing" Style="border-radius: 4px; text-transform: none; font-weight: 700; color: white;">
|
||||
@if (_processing)
|
||||
{
|
||||
<MudProgressCircular Size="Size.Small" Indeterminate="true" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText>Save Adjustments</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
}
|
||||
</div>
|
||||
</MudForm>
|
||||
}
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter] public UpdateLeaveBalanceRequest Data { get; set; } = new();
|
||||
[Parameter] public bool ReadOnly { get; set; } = false;
|
||||
[Parameter] public EventCallback OnCancel { get; set; }
|
||||
[Parameter] public EventCallback OnSuccess { get; set; }
|
||||
|
||||
private MudForm _form = default!;
|
||||
private UpdateLeaveBalanceValidator _validator = new();
|
||||
private UpdateLeaveBalanceRequest _model = new();
|
||||
private List<EmployeeLeaveReferenceResponse> _employees = new();
|
||||
private List<GetLeaveCategoryListResponse> _categories = new();
|
||||
private bool _processing = false;
|
||||
private bool _isInitialLoading = true;
|
||||
|
||||
private DateTime? _validFrom { get => _model.ValidFrom; set => _model.ValidFrom = value ?? DateTime.Today; }
|
||||
private DateTime? _validTo { get => _model.ValidTo; set => _model.ValidTo = value ?? DateTime.Today; }
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
_isInitialLoading = true;
|
||||
try
|
||||
{
|
||||
_model = Data;
|
||||
var empRes = await LeaveRequestService.GetEmployeeReferenceAsync();
|
||||
if (empRes?.IsSuccess == true) _employees = empRes.Value ?? new();
|
||||
var catRes = await LeaveCategoryService.GetLeaveCategoryListAsync();
|
||||
if (catRes?.IsSuccess == true) _categories = catRes.Value ?? new();
|
||||
}
|
||||
finally { _isInitialLoading = false; }
|
||||
}
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
if (ReadOnly) return;
|
||||
await _form.Validate(); if (!_form.IsValid) return;
|
||||
_processing = true;
|
||||
try
|
||||
{
|
||||
_model.Remaining = (_model.Entitlement + _model.CarryForward) - _model.Used - _model.Pending;
|
||||
var response = await LeaveBalanceService.UpdateLeaveBalanceAsync(_model);
|
||||
await Task.Delay(500);
|
||||
if (response?.IsSuccess == true) { Snackbar.Add("Balance adjusted successfully", Severity.Success); await OnSuccess.InvokeAsync(); }
|
||||
}
|
||||
finally { _processing = false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
using Indotalent.ConfigBackEnd.Exceptions;
|
||||
using Indotalent.ConfigBackEnd.Extensions;
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveBalance.Cqrs;
|
||||
|
||||
public class CreateLeaveBalanceRequest
|
||||
{
|
||||
public string EmployeeId { get; set; } = string.Empty;
|
||||
public string LeaveCategoryId { get; set; } = string.Empty;
|
||||
public int Entitlement { get; set; }
|
||||
public int Used { get; set; }
|
||||
public int Pending { get; set; }
|
||||
public int Remaining { get; set; }
|
||||
public int Year { get; set; }
|
||||
public DateTime ValidFrom { get; set; }
|
||||
public DateTime ValidTo { get; set; }
|
||||
public int CarryForward { get; set; }
|
||||
}
|
||||
|
||||
public class CreateLeaveBalanceResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
}
|
||||
|
||||
public record CreateLeaveBalanceCommand(CreateLeaveBalanceRequest Data) : IRequest<CreateLeaveBalanceResponse>;
|
||||
|
||||
public class CreateLeaveBalanceHandler : IRequestHandler<CreateLeaveBalanceCommand, CreateLeaveBalanceResponse>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public CreateLeaveBalanceHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<CreateLeaveBalanceResponse> Handle(CreateLeaveBalanceCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var isExists = await _context.LeaveBalance
|
||||
.AnyAsync(x => x.EmployeeId == request.Data.EmployeeId &&
|
||||
x.LeaveCategoryId == request.Data.LeaveCategoryId &&
|
||||
x.Year == request.Data.Year, cancellationToken);
|
||||
|
||||
if (isExists)
|
||||
{
|
||||
throw new AlreadyExistsException("Leave Balance", $"{request.Data.EmployeeId} for Year {request.Data.Year}");
|
||||
}
|
||||
|
||||
var entityName = nameof(Data.Entities.LeaveBalance);
|
||||
|
||||
var autoNo = await _context.GenerateAutoNumberAsync(
|
||||
entityName: entityName,
|
||||
prefixTemplate: $"{entityName.ToShortNameConsonant(3)}/{{Year}}/",
|
||||
ct: cancellationToken
|
||||
);
|
||||
|
||||
var entity = new Data.Entities.LeaveBalance
|
||||
{
|
||||
AutoNumber = autoNo,
|
||||
EmployeeId = request.Data.EmployeeId,
|
||||
LeaveCategoryId = request.Data.LeaveCategoryId,
|
||||
Entitlement = request.Data.Entitlement,
|
||||
Used = request.Data.Used,
|
||||
Pending = request.Data.Pending,
|
||||
Remaining = request.Data.Remaining,
|
||||
Year = request.Data.Year,
|
||||
ValidFrom = request.Data.ValidFrom,
|
||||
ValidTo = request.Data.ValidTo,
|
||||
CarryForward = request.Data.CarryForward
|
||||
};
|
||||
|
||||
_context.LeaveBalance.Add(entity);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return new CreateLeaveBalanceResponse
|
||||
{
|
||||
Id = entity.Id,
|
||||
AutoNumber = entity.AutoNumber
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveBalance.Cqrs;
|
||||
|
||||
public class CreateLeaveBalanceValidator : AbstractValidator<CreateLeaveBalanceRequest>
|
||||
{
|
||||
public CreateLeaveBalanceValidator()
|
||||
{
|
||||
RuleFor(x => x.EmployeeId).NotEmpty().WithMessage("Employee is required");
|
||||
RuleFor(x => x.LeaveCategoryId).NotEmpty().WithMessage("Leave Category is required");
|
||||
RuleFor(x => x.Year).GreaterThan(2000);
|
||||
RuleFor(x => x.Entitlement).GreaterThanOrEqualTo(0);
|
||||
RuleFor(x => x.ValidFrom).NotEmpty();
|
||||
RuleFor(x => x.ValidTo).NotEmpty().GreaterThanOrEqualTo(x => x.ValidFrom);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveBalance.Cqrs;
|
||||
|
||||
public record DeleteLeaveBalanceByIdRequest(string Id);
|
||||
|
||||
public record DeleteLeaveBalanceByIdCommand(DeleteLeaveBalanceByIdRequest Data) : IRequest<bool>;
|
||||
|
||||
public class DeleteLeaveBalanceByIdHandler : IRequestHandler<DeleteLeaveBalanceByIdCommand, bool>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public DeleteLeaveBalanceByIdHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<bool> Handle(DeleteLeaveBalanceByIdCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = await _context.LeaveBalance
|
||||
.FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);
|
||||
|
||||
if (entity == null) return false;
|
||||
|
||||
_context.LeaveBalance.Remove(entity);
|
||||
return await _context.SaveChangesAsync(cancellationToken) > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveBalance.Cqrs;
|
||||
|
||||
public class GetLeaveBalanceByIdResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? EmployeeId { get; set; }
|
||||
public string? EmployeeName { get; set; }
|
||||
public string? LeaveCategoryId { get; set; }
|
||||
public string? LeaveCategoryName { get; set; }
|
||||
public int Entitlement { get; set; }
|
||||
public int Used { get; set; }
|
||||
public int Pending { get; set; }
|
||||
public int Remaining { get; set; }
|
||||
public int Year { get; set; }
|
||||
public DateTime ValidFrom { get; set; }
|
||||
public DateTime ValidTo { get; set; }
|
||||
public int CarryForward { get; set; }
|
||||
public DateTimeOffset? CreatedAt { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
public DateTimeOffset? UpdatedAt { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
}
|
||||
|
||||
public record GetLeaveBalanceByIdQuery(string Id) : IRequest<GetLeaveBalanceByIdResponse?>;
|
||||
|
||||
public class GetLeaveBalanceByIdHandler : IRequestHandler<GetLeaveBalanceByIdQuery, GetLeaveBalanceByIdResponse?>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public GetLeaveBalanceByIdHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<GetLeaveBalanceByIdResponse?> Handle(GetLeaveBalanceByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _context.LeaveBalance
|
||||
.AsNoTracking()
|
||||
.Include(x => x.Employee)
|
||||
.Include(x => x.LeaveCategory)
|
||||
.Where(x => x.Id == request.Id)
|
||||
.Select(x => new GetLeaveBalanceByIdResponse
|
||||
{
|
||||
Id = x.Id,
|
||||
AutoNumber = x.AutoNumber,
|
||||
EmployeeId = x.EmployeeId,
|
||||
EmployeeName = x.Employee != null ? $"{x.Employee.FirstName} {x.Employee.LastName}" : string.Empty,
|
||||
LeaveCategoryId = x.LeaveCategoryId,
|
||||
LeaveCategoryName = x.LeaveCategory != null ? x.LeaveCategory.Name : string.Empty,
|
||||
Entitlement = x.Entitlement,
|
||||
Used = x.Used,
|
||||
Pending = x.Pending,
|
||||
Remaining = x.Remaining,
|
||||
Year = x.Year,
|
||||
ValidFrom = x.ValidFrom,
|
||||
ValidTo = x.ValidTo,
|
||||
CarryForward = x.CarryForward,
|
||||
CreatedAt = x.CreatedAt,
|
||||
CreatedBy = x.CreatedBy,
|
||||
UpdatedAt = x.UpdatedAt,
|
||||
UpdatedBy = x.UpdatedBy
|
||||
})
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using Indotalent.ConfigBackEnd.Extensions;
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveBalance.Cqrs;
|
||||
|
||||
public class GetLeaveBalanceListResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? EmployeeId { get; set; }
|
||||
public string? EmployeeName { get; set; }
|
||||
public string? EmployeeCode { get; set; }
|
||||
public string? LeaveCategoryId { get; set; }
|
||||
public string? LeaveCategoryName { get; set; }
|
||||
public int Entitlement { get; set; }
|
||||
public int Used { get; set; }
|
||||
public int Pending { get; set; }
|
||||
public int Remaining { get; set; }
|
||||
public int Year { get; set; }
|
||||
}
|
||||
|
||||
public record GetLeaveBalanceListQuery() : IRequest<List<GetLeaveBalanceListResponse>>;
|
||||
|
||||
public class GetLeaveBalanceListHandler : IRequestHandler<GetLeaveBalanceListQuery, List<GetLeaveBalanceListResponse>>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public GetLeaveBalanceListHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<List<GetLeaveBalanceListResponse>> Handle(GetLeaveBalanceListQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _context.LeaveBalance
|
||||
.AsNoTracking()
|
||||
.NotDeletedOnly()
|
||||
.Include(x => x.Employee)
|
||||
.Include(x => x.LeaveCategory)
|
||||
.OrderByDescending(x => x.Year)
|
||||
.ThenBy(x => x.Employee!.FirstName)
|
||||
.Select(x => new GetLeaveBalanceListResponse
|
||||
{
|
||||
Id = x.Id,
|
||||
AutoNumber = x.AutoNumber,
|
||||
EmployeeId = x.EmployeeId,
|
||||
EmployeeName = x.Employee != null ? $"{x.Employee.FirstName} {x.Employee.LastName}" : string.Empty,
|
||||
EmployeeCode = x.Employee != null ? $"{x.Employee.Code}" : string.Empty,
|
||||
LeaveCategoryId = x.LeaveCategoryId,
|
||||
LeaveCategoryName = x.LeaveCategory != null ? x.LeaveCategory.Name : string.Empty,
|
||||
Entitlement = x.Entitlement,
|
||||
Used = x.Used,
|
||||
Pending = x.Pending,
|
||||
Remaining = x.Remaining,
|
||||
Year = x.Year
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveBalance.Cqrs;
|
||||
|
||||
public record SyncLeaveBalanceCommand() : IRequest<bool>;
|
||||
|
||||
public class SyncLeaveBalanceHandler : IRequestHandler<SyncLeaveBalanceCommand, bool>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public SyncLeaveBalanceHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<bool> Handle(SyncLeaveBalanceCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var balances = await _context.LeaveBalance.ToListAsync(cancellationToken);
|
||||
|
||||
if (!balances.Any()) return true;
|
||||
|
||||
var allRequests = await _context.LeaveRequest
|
||||
.AsNoTracking()
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
foreach (var balance in balances)
|
||||
{
|
||||
var empRequests = allRequests
|
||||
.Where(x => x.EmployeeId == balance.EmployeeId &&
|
||||
x.LeaveCategoryId == balance.LeaveCategoryId &&
|
||||
x.StartDate.Year == balance.Year)
|
||||
.ToList();
|
||||
|
||||
balance.Used = (int)empRequests.Where(x => x.Status == "Approved").Sum(x => x.Days);
|
||||
balance.Pending = (int)empRequests.Where(x => x.Status == "Pending").Sum(x => x.Days);
|
||||
balance.Remaining = (balance.Entitlement + balance.CarryForward) - balance.Used;
|
||||
}
|
||||
|
||||
return await _context.SaveChangesAsync(cancellationToken) > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveBalance.Cqrs;
|
||||
|
||||
public class UpdateLeaveBalanceRequest : CreateLeaveBalanceRequest
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? EmployeeName { get; set; }
|
||||
public string? LeaveCategoryName { get; set; }
|
||||
public DateTimeOffset? CreatedAt { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
public DateTimeOffset? UpdatedAt { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
}
|
||||
|
||||
public class UpdateLeaveBalanceResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public bool Success { get; set; }
|
||||
}
|
||||
|
||||
public record UpdateLeaveBalanceCommand(UpdateLeaveBalanceRequest Data) : IRequest<UpdateLeaveBalanceResponse>;
|
||||
|
||||
public class UpdateLeaveBalanceHandler : IRequestHandler<UpdateLeaveBalanceCommand, UpdateLeaveBalanceResponse>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public UpdateLeaveBalanceHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<UpdateLeaveBalanceResponse> Handle(UpdateLeaveBalanceCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = await _context.LeaveBalance
|
||||
.FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);
|
||||
|
||||
if (entity == null)
|
||||
{
|
||||
return new UpdateLeaveBalanceResponse { Id = request.Data.Id, Success = false };
|
||||
}
|
||||
|
||||
entity.EmployeeId = request.Data.EmployeeId;
|
||||
entity.LeaveCategoryId = request.Data.LeaveCategoryId;
|
||||
entity.Entitlement = request.Data.Entitlement;
|
||||
entity.Used = request.Data.Used;
|
||||
entity.Pending = request.Data.Pending;
|
||||
entity.Remaining = request.Data.Remaining;
|
||||
entity.Year = request.Data.Year;
|
||||
entity.ValidFrom = request.Data.ValidFrom;
|
||||
entity.ValidTo = request.Data.ValidTo;
|
||||
entity.CarryForward = request.Data.CarryForward;
|
||||
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return new UpdateLeaveBalanceResponse
|
||||
{
|
||||
Id = entity.Id,
|
||||
Success = true
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveBalance.Cqrs;
|
||||
|
||||
public class UpdateLeaveBalanceValidator : AbstractValidator<UpdateLeaveBalanceRequest>
|
||||
{
|
||||
public UpdateLeaveBalanceValidator()
|
||||
{
|
||||
RuleFor(x => x.Id).NotEmpty().WithMessage("ID is required for update");
|
||||
RuleFor(x => x.EmployeeId).NotEmpty().WithMessage("Employee is required");
|
||||
RuleFor(x => x.LeaveCategoryId).NotEmpty().WithMessage("Leave Category is required");
|
||||
RuleFor(x => x.Year).GreaterThan(2000);
|
||||
RuleFor(x => x.Entitlement).GreaterThanOrEqualTo(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using Indotalent.ConfigBackEnd.Extensions;
|
||||
using Indotalent.Features.Leave.LeaveBalance.Cqrs;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveBalance;
|
||||
|
||||
public static class LeaveBalanceEndpoint
|
||||
{
|
||||
public static void MapLeaveBalanceEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
var group = app.MapGroup("/leave-balance").WithTags("Leave Balances")
|
||||
.RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
|
||||
.RequireAuthenticatedUser());
|
||||
|
||||
group.MapGet("/", async (IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new GetLeaveBalanceListQuery());
|
||||
return result.ToApiResponse("Data leave balance retrieved successfully");
|
||||
})
|
||||
.WithName("GetLeaveBalanceList");
|
||||
|
||||
group.MapGet("/{id}", async (string id, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new GetLeaveBalanceByIdQuery(id));
|
||||
return result.ToApiResponse(result is not null
|
||||
? "Leave balance detail retrieved successfully"
|
||||
: $"Leave balance with ID {id} not found");
|
||||
})
|
||||
.WithName("GetLeaveBalanceById");
|
||||
|
||||
group.MapPost("/", async (CreateLeaveBalanceRequest request, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new CreateLeaveBalanceCommand(request));
|
||||
return result.ToApiResponse("Leave balance has been created successfully", StatusCodes.Status201Created);
|
||||
})
|
||||
.WithName("CreateLeaveBalance");
|
||||
|
||||
group.MapPost("/update", async (UpdateLeaveBalanceRequest request, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new UpdateLeaveBalanceCommand(request));
|
||||
if (!result.Success) return ((object?)null).ToApiResponse("Update failed.");
|
||||
return result.ToApiResponse("Leave balance has been updated successfully");
|
||||
})
|
||||
.WithName("UpdateLeaveBalance");
|
||||
|
||||
group.MapPost("/sync", async (IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new SyncLeaveBalanceCommand());
|
||||
return result.ToApiResponse("All leave balances recalculated successfully");
|
||||
})
|
||||
.WithName("SyncLeaveBalance");
|
||||
|
||||
group.MapPost("/delete/{id}", async (string id, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new DeleteLeaveBalanceByIdCommand(new DeleteLeaveBalanceByIdRequest(id)));
|
||||
if (!result) return ((object?)null).ToApiResponse("Delete failed.");
|
||||
return true.ToApiResponse("Leave balance has been deleted successfully");
|
||||
})
|
||||
.WithName("DeleteLeaveBalanceById");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using Indotalent.ConfigBackEnd.Interfaces;
|
||||
using Indotalent.ConfigFrontEnd.Common;
|
||||
using Indotalent.Features.Leave.LeaveBalance.Cqrs;
|
||||
using Indotalent.Infrastructure.Authentication.Identity;
|
||||
using Indotalent.Shared.Models;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using MudBlazor;
|
||||
using RestSharp;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveBalance;
|
||||
|
||||
public class LeaveBalanceService : BaseService
|
||||
{
|
||||
private readonly RestClient _client;
|
||||
|
||||
public LeaveBalanceService(IHttpClientFactory clientFactory, NavigationManager nav, ISnackbar snackbar, ICurrentUserService currentUserService, TokenProvider tokenProvider)
|
||||
: base(clientFactory, nav, snackbar, currentUserService, tokenProvider)
|
||||
{
|
||||
_client = new RestClient(nav.BaseUri);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<List<GetLeaveBalanceListResponse>>?> GetLeaveBalanceListAsync()
|
||||
{
|
||||
var request = new RestRequest("api/leave-balance", Method.Get);
|
||||
return await ExecuteWithResponseAsync<List<GetLeaveBalanceListResponse>>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<GetLeaveBalanceByIdResponse>?> GetLeaveBalanceByIdAsync(string id)
|
||||
{
|
||||
var request = new RestRequest($"api/leave-balance/{id}", Method.Get);
|
||||
return await ExecuteWithResponseAsync<GetLeaveBalanceByIdResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<CreateLeaveBalanceResponse>?> CreateLeaveBalanceAsync(CreateLeaveBalanceRequest data)
|
||||
{
|
||||
var request = new RestRequest("api/leave-balance", Method.Post);
|
||||
request.AddJsonBody(data);
|
||||
return await ExecuteWithResponseAsync<CreateLeaveBalanceResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<UpdateLeaveBalanceResponse>?> UpdateLeaveBalanceAsync(UpdateLeaveBalanceRequest data)
|
||||
{
|
||||
var request = new RestRequest("api/leave-balance/update", Method.Post);
|
||||
request.AddJsonBody(data);
|
||||
return await ExecuteWithResponseAsync<UpdateLeaveBalanceResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<bool> SyncAllLeaveBalancesAsync()
|
||||
{
|
||||
var request = new RestRequest("api/leave-balance/sync", Method.Post);
|
||||
var response = await ExecuteWithResponseAsync<object>(_client, request);
|
||||
return response?.IsSuccess ?? false;
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteLeaveBalanceByIdAsync(string id)
|
||||
{
|
||||
var request = new RestRequest($"api/leave-balance/delete/{id}", Method.Post);
|
||||
var response = await ExecuteWithResponseAsync<object>(_client, request);
|
||||
return response?.IsSuccess ?? false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
@page "/leave/leave-category"
|
||||
@using Indotalent.Features.Leave.LeaveCategory.Components
|
||||
@using Indotalent.Features.Leave.LeaveCategory.Cqrs
|
||||
@using MudBlazor
|
||||
|
||||
@if (_currentView == ViewMode.Create)
|
||||
{
|
||||
<_LeaveCategoryCreateForm OnCancel="BackToTable" OnSuccess="HandleSuccess" />
|
||||
}
|
||||
else if (_currentView == ViewMode.Update || _currentView == ViewMode.View)
|
||||
{
|
||||
<_LeaveCategoryUpdateForm Data="_selectedData!" ReadOnly="@(_currentView == ViewMode.View)" OnCancel="BackToTable" OnSuccess="HandleSuccess" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<_LeaveCategoryDataTable OnAdd="() => ShowCreate()" OnEdit="(item) => ShowUpdate(item, false)" OnView="(item) => ShowUpdate(item, true)" />
|
||||
}
|
||||
|
||||
@code {
|
||||
private enum ViewMode { Table, Create, Update, View }
|
||||
private ViewMode _currentView = ViewMode.Table;
|
||||
private UpdateLeaveCategoryRequest? _selectedData;
|
||||
|
||||
private void ShowCreate() => _currentView = ViewMode.Create;
|
||||
|
||||
private void ShowUpdate(UpdateLeaveCategoryRequest data, bool isReadOnly)
|
||||
{
|
||||
_selectedData = data;
|
||||
_currentView = isReadOnly ? ViewMode.View : ViewMode.Update;
|
||||
}
|
||||
|
||||
private void BackToTable() { _currentView = ViewMode.Table; _selectedData = null; }
|
||||
|
||||
private void HandleSuccess() { _currentView = ViewMode.Table; _selectedData = null; }
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
@using Indotalent.Features.Leave.LeaveCategory
|
||||
@using Indotalent.Features.Leave.LeaveCategory.Cqrs
|
||||
@using Indotalent.Shared.Utils
|
||||
@using MudBlazor
|
||||
@inject LeaveCategoryService LeaveCategoryService
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
|
||||
<div class="d-flex align-center gap-4">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">Add Leave Category</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b;">Define new leave type and its entitlement rules.</MudText>
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA;">
|
||||
<MudForm @ref="_form" Model="_model">
|
||||
<MudGrid Spacing="3">
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Category Code</MudText>
|
||||
<MudTextField @bind-Value="_model.Code"
|
||||
For="@(() => _model.Code)"
|
||||
Validation="@(_validator.ValidateValue())"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Placeholder="e.g. LV-AL" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="8">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Category Name</MudText>
|
||||
<MudTextField @bind-Value="_model.Name"
|
||||
For="@(() => _model.Name)"
|
||||
Validation="@(_validator.ValidateValue())"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Placeholder="e.g. Annual Leave" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Quota (Days)</MudText>
|
||||
<MudNumericField @bind-Value="_model.Quota" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Min="0" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Status</MudText>
|
||||
<MudSelect @bind-Value="_model.Status" Variant="Variant.Outlined" Margin="Margin.Dense" AnchorOrigin="Origin.BottomCenter">
|
||||
<MudSelectItem Value="@("Active")">Active</MudSelectItem>
|
||||
<MudSelectItem Value="@("Inactive")">Inactive</MudSelectItem>
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4" Class="d-flex align-center">
|
||||
<MudCheckBox @bind-Value="_model.IsPaidLeave" Label="Paid Leave" Color="Color.Success" />
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Description</MudText>
|
||||
<MudTextField @bind-Value="_model.Description" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Lines="2" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudCheckBox @bind-Value="_model.AllowCarryForward" Label="Allow Carry Forward" Color="Color.Primary" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Max Carry Forward</MudText>
|
||||
<MudNumericField @bind-Value="_model.MaxCarryForward" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Disabled="!_model.AllowCarryForward" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Min Service (Months)</MudText>
|
||||
<MudNumericField @bind-Value="_model.MinServiceMonths" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<div class="d-flex justify-end gap-2 mt-8">
|
||||
<MudButton OnClick="() => OnCancel.InvokeAsync()" Variant="Variant.Outlined" Disabled="_processing" Style="border: 1px solid #e0e0e0; border-radius: 4px; text-transform: none; font-weight: 700;">Cancel</MudButton>
|
||||
<MudButton Color="Color.Success" Variant="Variant.Filled" OnClick="Submit" Disabled="_processing" Style="border-radius: 4px; text-transform: none; font-weight: 700; color: white;">
|
||||
@if (_processing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText>Create Category</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
</div>
|
||||
</MudForm>
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter] public EventCallback OnCancel { get; set; }
|
||||
[Parameter] public EventCallback OnSuccess { get; set; }
|
||||
|
||||
private MudForm _form = default!;
|
||||
private CreateLeaveCategoryValidator _validator = new();
|
||||
private CreateLeaveCategoryRequest _model = new() { Status = "Active", IsPaidLeave = true };
|
||||
private bool _processing = false;
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
await _form.Validate();
|
||||
if (!_form.IsValid) return;
|
||||
|
||||
_processing = true;
|
||||
try
|
||||
{
|
||||
var response = await LeaveCategoryService.CreateLeaveCategoryAsync(_model);
|
||||
await Task.Delay(500);
|
||||
if (response != null && response.IsSuccess)
|
||||
{
|
||||
Snackbar.Add("Leave category created successfully", Severity.Success);
|
||||
await OnSuccess.InvokeAsync();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Error: {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_processing = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
@using Indotalent.ConfigBackEnd.Extensions
|
||||
@using Indotalent.Features.Leave.LeaveCategory
|
||||
@using Indotalent.Features.Leave.LeaveCategory.Cqrs
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using Microsoft.JSInterop
|
||||
@using MudBlazor
|
||||
@using Features.Root.Shared
|
||||
@using ClosedXML.Excel
|
||||
@using System.IO
|
||||
@inject LeaveCategoryService LeaveCategoryService
|
||||
@inject IDialogService DialogService
|
||||
@inject ISnackbar Snackbar
|
||||
@inject IJSRuntime JSRuntime
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #E5E7EB; border-radius: 12px;">
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 700; color: #111827;">Leave Categories</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #9CA3AF;">Manage leave types, quotas, and entitlement rules for employees.</MudText>
|
||||
</div>
|
||||
<div class="d-flex align-center gap-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Home" Size="Size.Small" Color="Color.Default" />
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">Leave</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="font-weight: 600; color: #111827;">Category</MudText>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Style="border-radius: 12px; overflow: hidden; background-color: #ffffff; border: 1px solid #E5E7EB;">
|
||||
|
||||
<div style="padding: 20px 24px; border-bottom: 1px solid #E5E7EB; display: flex; justify-content: space-between; align-items: center; background-color: #F0FDF4; min-height: 80px;">
|
||||
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<MudTextField @bind-Value="_searchString"
|
||||
Placeholder="Search..."
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Search"
|
||||
IconSize="Size.Small"
|
||||
Class="mt-0"
|
||||
Variant="Variant.Outlined"
|
||||
Margin="Margin.Dense"
|
||||
Style="background-color: white; width: 280px; border-radius: 8px;"
|
||||
OnKeyDown="@HandleSearchKeyDown" />
|
||||
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
OnClick="OnSearchClick"
|
||||
Size="Size.Small"
|
||||
Style="text-transform: none; font-weight: 500; border-radius: 6px; height: 34px; box-shadow: none;">
|
||||
Search
|
||||
</MudButton>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<MudButton Variant="Variant.Outlined"
|
||||
Color="Color.Success"
|
||||
OnClick="ExportToExcel"
|
||||
Size="Size.Small"
|
||||
Disabled="_isExporting"
|
||||
StartIcon="@(_isExporting ? null : Icons.Custom.FileFormats.FileExcel)"
|
||||
Style="border: 1px solid #D1D5DB; background: white; font-weight: 500; border-radius: 6px; text-transform: none; height: 34px; color: #6B7280;">
|
||||
@if (_isExporting)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText Typo="Typo.button" Style="text-transform: none !important;">Excel</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
|
||||
<MudButton Variant="Variant.Outlined"
|
||||
Color="Color.Primary"
|
||||
OnClick="LoadData"
|
||||
Size="Size.Small"
|
||||
StartIcon="@(_isRefreshing ? null : Icons.Material.Filled.Refresh)"
|
||||
Disabled="_isRefreshing"
|
||||
Style="border: 1px solid #D1D5DB; background: white; font-weight: 500; border-radius: 6px; text-transform: none; height: 34px; color: #6B7280;">
|
||||
@if (_isRefreshing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Refreshing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText Typo="Typo.button" Style="text-transform: none !important;">Refresh</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
|
||||
@if (_selectedCategory != null)
|
||||
{
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Info" StartIcon="@Icons.Material.Filled.Visibility" OnClick="InvokeView" Size="Size.Small" Style="border: 1px solid #D1D5DB; text-transform: none; font-weight: 500; border-radius: 6px; background: white; color: #6B7280;">View</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Edit" OnClick="InvokeEdit" Size="Size.Small" Style="border: 1px solid #D1D5DB; text-transform: none; font-weight: 500; border-radius: 6px; background: white; color: #6B7280;">Edit</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Error" StartIcon="@Icons.Material.Filled.Delete" OnClick="OnDelete" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; border: 1px solid #FCA5A5; color: #EF4444; background: white;">Remove</MudButton>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Close" Size="Size.Small" OnClick="() => _selectedCategory = null" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Success" StartIcon="@Icons.Material.Filled.AddCircle" OnClick="() => OnAdd.InvokeAsync()" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; color: white; height: 34px;">
|
||||
Create Leave Category
|
||||
</MudButton>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<MudTable Items="@GetPagedData()" Hover="true" Striped="true" Class="mud-table-styled" Elevation="0" CustomHeader="true" Dense="true" T="GetLeaveCategoryListResponse" OnRowClick="@((args) => _selectedCategory = args.Item)" Loading="@_isRefreshing">
|
||||
<HeaderContent>
|
||||
<MudTh Style="width: 50px; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB;"></MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetLeaveCategoryListResponse, object>(x => x.Code!)">Code</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetLeaveCategoryListResponse, object>(x => x.Name!)">Category Name</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetLeaveCategoryListResponse, object>(x => x.Quota)">Quota</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetLeaveCategoryListResponse, object>(x => x.IsPaidLeave)">Paid Leave</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetLeaveCategoryListResponse, object>(x => x.Description!)">Description</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetLeaveCategoryListResponse, object>(x => x.Status!)">Status</MudTableSortLabel>
|
||||
</MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd>
|
||||
<MudCheckBox T="bool" Value="@(_selectedCategory?.Id == context.Id)" Color="Color.Success" Dense="true" Size="Size.Small" ReadOnly="true" />
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudChip T="string" Size="Size.Small" Variant="Variant.Text" Style="background-color: #F0FDF4; color: #166534; font-weight: 600; border-radius: 0px;">@context.Code</MudChip>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudText Typo="Typo.body2" Style="font-weight: 600; color: #374151;">@context.Name</MudText>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudText Typo="Typo.body2" Style="font-weight: 600; color: #374151;">@context.Quota Days</MudText>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudIcon Icon="@(context.IsPaidLeave? Icons.Material.Filled.AttachMoney : Icons.Material.Filled.MoneyOff)" Color="@(context.IsPaidLeave? Color.Success: Color.Error)" Size="Size.Small" />
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b; font-size: 0.8rem;">@context.Description</MudText>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudChip T="string" Color="@(context.Status == "Active" ? Color.Success : Color.Default)" Size="Size.Small" Variant="Variant.Text" Style="font-weight: 600; border-radius: 0px; text-transform: uppercase; background-color: #f5f5f5; height: 20px; font-size: 0.7rem;">@context.Status</MudChip>
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
</MudTable>
|
||||
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; padding: 12px 24px; background-color: #F8FAFC; border-top: 2px solid #E5E7EB;">
|
||||
<div style="display: flex; align-items: center; gap: 12px;">
|
||||
<MudText Typo="Typo.caption" Style="font-weight: 700; color: #1e293b;">Rows per page:</MudText>
|
||||
|
||||
<MudSelect T="int"
|
||||
Value="@_top"
|
||||
ValueChanged="OnPageSizeChanged"
|
||||
Dense="true"
|
||||
Margin="Margin.Dense"
|
||||
Style="width: 80px; background-color: white; font-size: 0.75rem; font-weight: 500;"
|
||||
Variant="Variant.Outlined"
|
||||
Class="mt-0 custom-select-dense">
|
||||
<MudSelectItem Value="5" />
|
||||
<MudSelectItem Value="10" />
|
||||
<MudSelectItem Value="50" />
|
||||
<MudSelectItem Value="500" />
|
||||
<MudSelectItem Value="1000" />
|
||||
</MudSelect>
|
||||
|
||||
<MudText Typo="Typo.caption" Style="color: #64748b; margin-left: 12px;">
|
||||
Showing @(GetFilteredData().Count() == 0 ? 0 : _skip + 1)-@Math.Min(_skip + _top, GetFilteredData().Count()) of @GetFilteredData().Count()
|
||||
</MudText>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.FirstPage" Size="Size.Small" OnClick="@(() => OnPageChanged(1))" Disabled="@(_currentPage == 1)" Style="@(_currentPage == 1 ? "color: #D1D5DB; background: transparent;" : "color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px;")" />
|
||||
<MudButton OnClick="@(() => OnPageChanged(_currentPage - 1))" Disabled="@(_currentPage == 1)" Variant="Variant.Text" StartIcon="@Icons.Material.Filled.ChevronLeft" Size="Size.Small" Style="@(_currentPage == 1 ? "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;" : "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;")">Prev</MudButton>
|
||||
@{
|
||||
var totalPages = _totalPage == 0 ? 1 : _totalPage;
|
||||
var maxVisible = 5;
|
||||
var startPage = Math.Max(1, _currentPage - maxVisible / 2);
|
||||
var endPage = Math.Min(totalPages, startPage + maxVisible - 1);
|
||||
if (endPage - startPage < maxVisible - 1) { startPage = Math.Max(1, endPage - maxVisible + 1); }
|
||||
}
|
||||
@for (int i = startPage; i <= endPage; i++)
|
||||
{
|
||||
var pageNum = i;
|
||||
var isActive = pageNum == _currentPage;
|
||||
<MudButton OnClick="@(() => OnPageChanged(pageNum))"
|
||||
Variant="Variant.Text" Size="Size.Small"
|
||||
Style="@(isActive ? "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 600; background: #3B82F6; color: white; border: 1px solid #3B82F6; border-radius: 6px; text-transform: none;" : "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 500; color: #374151; background: white; border: 1px solid #D1D5DB; border-radius: 6px; text-transform: none;")">@pageNum</MudButton>
|
||||
}
|
||||
<MudButton OnClick="@(() => OnPageChanged(_currentPage + 1))" Disabled="@(_currentPage == _totalPage || _totalPage == 0)" Variant="Variant.Text" EndIcon="@Icons.Material.Filled.ChevronRight" Size="Size.Small" Style="@(_currentPage == _totalPage || _totalPage == 0 ? "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;" : "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;")">Next</MudButton>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.LastPage" Size="Size.Small" OnClick="@(() => OnPageChanged(_totalPage))" Disabled="@(_currentPage == _totalPage || _totalPage == 0)" Style="@(_currentPage == _totalPage || _totalPage == 0 ? "color: #D1D5DB; background: transparent;" : "color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px;")" />
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<script>
|
||||
function downloadFile(fileName, contentType, base64String) {
|
||||
const link = document.createElement('a');
|
||||
link.download = fileName;
|
||||
link.href = `data:${contentType};base64,${base64String}`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.mud-input-outlined-border { border-radius: 8px !important; }
|
||||
.custom-select-dense .mud-input-control { margin-top: 0 !important; }
|
||||
.custom-select-dense .mud-input-slot { padding-top: 4px !important; padding-bottom: 4px !important; padding-left: 8px !important; font-size: 12px !important; }
|
||||
.mud-table-styled .mud-table-row:hover { background-color: #F9FAFB !important; }
|
||||
</style>
|
||||
|
||||
@code {
|
||||
[Parameter] public EventCallback OnAdd { get; set; }
|
||||
[Parameter] public EventCallback<UpdateLeaveCategoryRequest> OnEdit { get; set; }
|
||||
[Parameter] public EventCallback<UpdateLeaveCategoryRequest> OnView { get; set; }
|
||||
|
||||
private List<GetLeaveCategoryListResponse> _categories = new();
|
||||
private GetLeaveCategoryListResponse? _selectedCategory;
|
||||
private string _searchString = "";
|
||||
private int _skip = 0;
|
||||
private int _top = 5;
|
||||
private int _totalPage => GetFilteredData().Count() == 0 ? 0 : (int)Math.Ceiling((double)GetFilteredData().Count() / (_top == 0 ? 1 : _top));
|
||||
private int _currentPage => (_top >= GetFilteredData().Count() || _top == 0) ? 1 : (_skip / _top) + 1;
|
||||
private bool _isRefreshing = false;
|
||||
private bool _isExporting = false;
|
||||
|
||||
protected override async Task OnInitializedAsync() => await LoadData();
|
||||
|
||||
private async Task LoadData()
|
||||
{
|
||||
_isRefreshing = true;
|
||||
_selectedCategory = null;
|
||||
StateHasChanged();
|
||||
|
||||
try
|
||||
{
|
||||
var response = await LeaveCategoryService.GetLeaveCategoryListAsync();
|
||||
await Task.Delay(500);
|
||||
|
||||
if (response != null && response.IsSuccess)
|
||||
{
|
||||
_categories = response.Value ?? new();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isRefreshing = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerable<GetLeaveCategoryListResponse> GetFilteredData()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_searchString)) return _categories;
|
||||
return _categories.Where(x =>
|
||||
(x.Name?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.Code?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.Description?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.Status?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false)
|
||||
);
|
||||
}
|
||||
|
||||
private IEnumerable<GetLeaveCategoryListResponse> GetPagedData() => GetFilteredData().Skip(_skip).Take(_top);
|
||||
|
||||
private async Task ExportToExcel()
|
||||
{
|
||||
_isExporting = true;
|
||||
StateHasChanged();
|
||||
try
|
||||
{
|
||||
await Task.Delay(1000);
|
||||
using (var workbook = new XLWorkbook())
|
||||
{
|
||||
var worksheet = workbook.Worksheets.Add("LeaveCategories");
|
||||
var currentRow = 1;
|
||||
|
||||
worksheet.Cell(currentRow, 1).Value = "Code";
|
||||
worksheet.Cell(currentRow, 2).Value = "Name";
|
||||
worksheet.Cell(currentRow, 3).Value = "Quota";
|
||||
worksheet.Cell(currentRow, 4).Value = "Is Paid Leave";
|
||||
worksheet.Cell(currentRow, 5).Value = "Status";
|
||||
worksheet.Cell(currentRow, 6).Value = "Description";
|
||||
|
||||
var headerRange = worksheet.Range(1, 1, 1, 6);
|
||||
headerRange.Style.Font.Bold = true;
|
||||
headerRange.Style.Fill.BackgroundColor = XLColor.FromHtml("#166534");
|
||||
headerRange.Style.Font.FontColor = XLColor.White;
|
||||
|
||||
foreach (var item in GetFilteredData())
|
||||
{
|
||||
currentRow++;
|
||||
worksheet.Cell(currentRow, 1).Value = item.Code;
|
||||
worksheet.Cell(currentRow, 2).Value = item.Name;
|
||||
worksheet.Cell(currentRow, 3).Value = item.Quota;
|
||||
worksheet.Cell(currentRow, 4).Value = item.IsPaidLeave ? "Yes" : "No";
|
||||
worksheet.Cell(currentRow, 5).Value = item.Status;
|
||||
worksheet.Cell(currentRow, 6).Value = item.Description;
|
||||
}
|
||||
|
||||
worksheet.Columns().AdjustToContents();
|
||||
|
||||
using (var stream = new MemoryStream())
|
||||
{
|
||||
workbook.SaveAs(stream);
|
||||
var content = Convert.ToBase64String(stream.ToArray());
|
||||
await JSRuntime.InvokeVoidAsync("downloadFile", "Leave_Category_Registry.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", content);
|
||||
Snackbar.Add("Excel exported successfully", Severity.Success);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Export failed: {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isExporting = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnSearchClick()
|
||||
{
|
||||
_skip = 0;
|
||||
_selectedCategory = null;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private void HandleSearchKeyDown(KeyboardEventArgs e)
|
||||
{
|
||||
if (e.Key == "Enter") OnSearchClick();
|
||||
}
|
||||
|
||||
private void OnPageChanged(int page)
|
||||
{
|
||||
if (page >= 1 && page <= _totalPage)
|
||||
{
|
||||
_skip = (page - 1) * _top;
|
||||
_selectedCategory = null;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPageSizeChanged(int size)
|
||||
{
|
||||
_top = size;
|
||||
_skip = 0;
|
||||
_selectedCategory = null;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private async Task InvokeEdit() { if (_selectedCategory != null) { var res = await LeaveCategoryService.GetLeaveCategoryByIdAsync(_selectedCategory.Id!); if (res?.Value != null) await OnEdit.InvokeAsync(MapToUpdate(res.Value)); } }
|
||||
|
||||
private async Task InvokeView() { if (_selectedCategory != null) { var res = await LeaveCategoryService.GetLeaveCategoryByIdAsync(_selectedCategory.Id!); if (res?.Value != null) await OnView.InvokeAsync(MapToUpdate(res.Value)); } }
|
||||
|
||||
private UpdateLeaveCategoryRequest MapToUpdate(GetLeaveCategoryByIdResponse d) => new UpdateLeaveCategoryRequest
|
||||
{
|
||||
Id = d.Id,
|
||||
Code = d.Code,
|
||||
Name = d.Name,
|
||||
Quota = d.Quota,
|
||||
IsPaidLeave = d.IsPaidLeave,
|
||||
Description = d.Description ?? "",
|
||||
Status = d.Status ?? "Active",
|
||||
AllowCarryForward = d.AllowCarryForward,
|
||||
MaxCarryForward = d.MaxCarryForward,
|
||||
MinServiceMonths = d.MinServiceMonths,
|
||||
CreatedAt = d.CreatedAt,
|
||||
CreatedBy = d.CreatedBy,
|
||||
UpdatedAt = d.UpdatedAt,
|
||||
UpdatedBy = d.UpdatedBy
|
||||
};
|
||||
|
||||
private async Task OnDelete()
|
||||
{
|
||||
if (_selectedCategory == null) return;
|
||||
var dialog = await DialogService.ShowAsync<Features.Root.Shared._DeleteConfirmation>("", new DialogParameters<Features.Root.Shared._DeleteConfirmation> { { x => x.ContentText, _selectedCategory.Name } });
|
||||
if (!(await dialog.Result).Canceled)
|
||||
{
|
||||
if (await LeaveCategoryService.DeleteLeaveCategoryByIdAsync(_selectedCategory.Id!)) { await LoadData(); Snackbar.Add("Category deleted", Severity.Success); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
@using Indotalent.ConfigBackEnd.Extensions
|
||||
@using Indotalent.Features.Leave.LeaveCategory
|
||||
@using Indotalent.Features.Leave.LeaveCategory.Cqrs
|
||||
@using Indotalent.Shared.Utils
|
||||
@using MudBlazor
|
||||
@inject LeaveCategoryService LeaveCategoryService
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
|
||||
<div class="d-flex align-center gap-4">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">@(ReadOnly ? "Category Details" : "Edit Category")</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b;">@(ReadOnly ? "Viewing policy configuration." : "Modify existing leave entitlement rules.")</MudText>
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA;">
|
||||
<MudForm @ref="_form" Model="_model">
|
||||
<MudGrid Spacing="3">
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Category Code</MudText>
|
||||
<MudTextField @bind-Value="_model.Code" For="@(() => _model.Code)" Validation="@(_validator.ValidateValue())" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="8">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Category Name</MudText>
|
||||
<MudTextField @bind-Value="_model.Name" For="@(() => _model.Name)" Validation="@(_validator.ValidateValue())" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Quota (Days)</MudText>
|
||||
<MudNumericField @bind-Value="_model.Quota" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Status</MudText>
|
||||
<MudSelect @bind-Value="_model.Status" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" AnchorOrigin="Origin.BottomCenter">
|
||||
<MudSelectItem Value="@("Active")">Active</MudSelectItem>
|
||||
<MudSelectItem Value="@("Inactive")">Inactive</MudSelectItem>
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4" Class="d-flex align-center">
|
||||
<MudCheckBox @bind-Value="_model.IsPaidLeave" Label="Paid Leave" Color="Color.Success" ReadOnly="ReadOnly" />
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Description</MudText>
|
||||
<MudTextField @bind-Value="_model.Description" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Lines="2" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudCheckBox @bind-Value="_model.AllowCarryForward" Label="Allow Carry Forward" Color="Color.Primary" ReadOnly="ReadOnly" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Max Carry Forward</MudText>
|
||||
<MudNumericField @bind-Value="_model.MaxCarryForward" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" ReadOnly="ReadOnly" Disabled="!_model.AllowCarryForward" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Min Service (Months)</MudText>
|
||||
<MudNumericField @bind-Value="_model.MinServiceMonths" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" ReadOnly="ReadOnly" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" Class="mt-4">
|
||||
<MudText Typo="Typo.button" Color="Color.Success" Style="font-weight: 800;">Audit History</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Created At</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@DateTimeExtensions.ToString(_model.CreatedAt)</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Created By</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@(!string.IsNullOrEmpty(_model.CreatedBy) ? _model.CreatedBy : "System")</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Last Updated At</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@DateTimeExtensions.ToString(_model.UpdatedAt)</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Last Updated By</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@(!string.IsNullOrEmpty(_model.UpdatedBy) ? _model.UpdatedBy : "System")</MudText>
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<div class="d-flex justify-end gap-2 mt-10">
|
||||
<MudButton OnClick="() => OnCancel.InvokeAsync()" Variant="Variant.Outlined" Disabled="_processing" Style="border: 1px solid #e0e0e0; border-radius: 4px; text-transform: none; font-weight: 700;">@(ReadOnly ? "Back to List" : "Cancel")</MudButton>
|
||||
@if (!ReadOnly)
|
||||
{
|
||||
<MudButton Color="Color.Success" Variant="Variant.Filled" OnClick="Submit" Disabled="_processing" Style="border-radius: 4px; text-transform: none; font-weight: 700; color: white;">
|
||||
@if (_processing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2">Updating...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText>Save Changes</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
}
|
||||
</div>
|
||||
</MudForm>
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter] public UpdateLeaveCategoryRequest Data { get; set; } = new();
|
||||
[Parameter] public bool ReadOnly { get; set; } = false;
|
||||
[Parameter] public EventCallback OnCancel { get; set; }
|
||||
[Parameter] public EventCallback OnSuccess { get; set; }
|
||||
|
||||
private MudForm _form = default!;
|
||||
private UpdateLeaveCategoryValidator _validator = new();
|
||||
private UpdateLeaveCategoryRequest _model = new();
|
||||
private bool _processing = false;
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
_model = new UpdateLeaveCategoryRequest
|
||||
{
|
||||
Id = Data.Id,
|
||||
Code = Data.Code,
|
||||
Name = Data.Name,
|
||||
Quota = Data.Quota,
|
||||
IsPaidLeave = Data.IsPaidLeave,
|
||||
Description = Data.Description,
|
||||
Status = Data.Status,
|
||||
AllowCarryForward = Data.AllowCarryForward,
|
||||
MaxCarryForward = Data.MaxCarryForward,
|
||||
MinServiceMonths = Data.MinServiceMonths,
|
||||
CreatedAt = Data.CreatedAt,
|
||||
CreatedBy = Data.CreatedBy,
|
||||
UpdatedAt = Data.UpdatedAt,
|
||||
UpdatedBy = Data.UpdatedBy
|
||||
};
|
||||
}
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
if (ReadOnly) return;
|
||||
await _form.Validate();
|
||||
if (!_form.IsValid) return;
|
||||
_processing = true;
|
||||
try
|
||||
{
|
||||
var response = await LeaveCategoryService.UpdateLeaveCategoryAsync(_model);
|
||||
await Task.Delay(500);
|
||||
if (response != null && response.IsSuccess)
|
||||
{
|
||||
Snackbar.Add("Category updated successfully", Severity.Success);
|
||||
await OnSuccess.InvokeAsync();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Error: {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_processing = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
using Indotalent.ConfigBackEnd.Exceptions;
|
||||
using Indotalent.ConfigBackEnd.Extensions;
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveCategory.Cqrs;
|
||||
|
||||
public class CreateLeaveCategoryRequest
|
||||
{
|
||||
public string? Code { get; set; }
|
||||
public string? Name { get; set; }
|
||||
public int Quota { get; set; }
|
||||
public bool IsPaidLeave { get; set; }
|
||||
public string Description { get; set; } = string.Empty;
|
||||
public string Status { get; set; } = string.Empty;
|
||||
public bool AllowCarryForward { get; set; }
|
||||
public int MaxCarryForward { get; set; }
|
||||
public int MinServiceMonths { get; set; }
|
||||
}
|
||||
|
||||
public class CreateLeaveCategoryResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? Code { get; set; }
|
||||
}
|
||||
|
||||
public record CreateLeaveCategoryCommand(CreateLeaveCategoryRequest Data) : IRequest<CreateLeaveCategoryResponse>;
|
||||
|
||||
public class CreateLeaveCategoryHandler : IRequestHandler<CreateLeaveCategoryCommand, CreateLeaveCategoryResponse>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public CreateLeaveCategoryHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<CreateLeaveCategoryResponse> Handle(CreateLeaveCategoryCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var isExists = await _context.LeaveCategory
|
||||
.AnyAsync(x => x.Code == request.Data.Code, cancellationToken);
|
||||
|
||||
if (isExists)
|
||||
{
|
||||
throw new AlreadyExistsException("Leave Category", request.Data.Code ?? string.Empty);
|
||||
}
|
||||
|
||||
var entityName = nameof(Data.Entities.LeaveCategory);
|
||||
|
||||
var autoNo = await _context.GenerateAutoNumberAsync(
|
||||
entityName: entityName,
|
||||
prefixTemplate: $"{entityName.ToShortNameConsonant(3)}/{{Year}}/",
|
||||
ct: cancellationToken
|
||||
);
|
||||
|
||||
var entity = new Data.Entities.LeaveCategory
|
||||
{
|
||||
AutoNumber = autoNo,
|
||||
Code = request.Data.Code,
|
||||
Name = request.Data.Name,
|
||||
Quota = request.Data.Quota,
|
||||
IsPaidLeave = request.Data.IsPaidLeave,
|
||||
Description = request.Data.Description,
|
||||
Status = request.Data.Status,
|
||||
AllowCarryForward = request.Data.AllowCarryForward,
|
||||
MaxCarryForward = request.Data.MaxCarryForward,
|
||||
MinServiceMonths = request.Data.MinServiceMonths
|
||||
};
|
||||
|
||||
_context.LeaveCategory.Add(entity);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return new CreateLeaveCategoryResponse
|
||||
{
|
||||
Id = entity.Id,
|
||||
Code = entity.Code
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using FluentValidation;
|
||||
using Indotalent.Shared.Consts;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveCategory.Cqrs;
|
||||
|
||||
public class CreateLeaveCategoryValidator : AbstractValidator<CreateLeaveCategoryRequest>
|
||||
{
|
||||
public CreateLeaveCategoryValidator()
|
||||
{
|
||||
RuleFor(x => x.Code)
|
||||
.NotEmpty().WithMessage("Category Code is required")
|
||||
.MaximumLength(GlobalConsts.StringLengthShort);
|
||||
|
||||
RuleFor(x => x.Name)
|
||||
.NotEmpty().WithMessage("Category Name is required")
|
||||
.MaximumLength(GlobalConsts.StringLengthShort);
|
||||
|
||||
RuleFor(x => x.Quota)
|
||||
.GreaterThanOrEqualTo(0).WithMessage("Quota cannot be negative");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveCategory.Cqrs;
|
||||
|
||||
public record DeleteLeaveCategoryByIdRequest(string Id);
|
||||
|
||||
public record DeleteLeaveCategoryByIdCommand(DeleteLeaveCategoryByIdRequest Data) : IRequest<bool>;
|
||||
|
||||
public class DeleteLeaveCategoryByIdHandler : IRequestHandler<DeleteLeaveCategoryByIdCommand, bool>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public DeleteLeaveCategoryByIdHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<bool> Handle(DeleteLeaveCategoryByIdCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = await _context.LeaveCategory
|
||||
.FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);
|
||||
|
||||
if (entity == null) return false;
|
||||
|
||||
_context.LeaveCategory.Remove(entity);
|
||||
return await _context.SaveChangesAsync(cancellationToken) > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveCategory.Cqrs;
|
||||
|
||||
public class GetLeaveCategoryByIdResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? Code { get; set; }
|
||||
public string? Name { get; set; }
|
||||
public int Quota { get; set; }
|
||||
public bool IsPaidLeave { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? Status { get; set; }
|
||||
public bool AllowCarryForward { get; set; }
|
||||
public int MaxCarryForward { get; set; }
|
||||
public int MinServiceMonths { get; set; }
|
||||
public DateTimeOffset? CreatedAt { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
public DateTimeOffset? UpdatedAt { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
}
|
||||
|
||||
public record GetLeaveCategoryByIdQuery(string Id) : IRequest<GetLeaveCategoryByIdResponse?>;
|
||||
|
||||
public class GetLeaveCategoryByIdHandler : IRequestHandler<GetLeaveCategoryByIdQuery, GetLeaveCategoryByIdResponse?>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public GetLeaveCategoryByIdHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<GetLeaveCategoryByIdResponse?> Handle(GetLeaveCategoryByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _context.LeaveCategory
|
||||
.AsNoTracking()
|
||||
.Where(x => x.Id == request.Id)
|
||||
.Select(x => new GetLeaveCategoryByIdResponse
|
||||
{
|
||||
Id = x.Id,
|
||||
AutoNumber = x.AutoNumber,
|
||||
Code = x.Code,
|
||||
Name = x.Name,
|
||||
Quota = x.Quota,
|
||||
IsPaidLeave = x.IsPaidLeave,
|
||||
Description = x.Description,
|
||||
Status = x.Status,
|
||||
AllowCarryForward = x.AllowCarryForward,
|
||||
MaxCarryForward = x.MaxCarryForward,
|
||||
MinServiceMonths = x.MinServiceMonths,
|
||||
CreatedAt = x.CreatedAt,
|
||||
CreatedBy = x.CreatedBy,
|
||||
UpdatedAt = x.UpdatedAt,
|
||||
UpdatedBy = x.UpdatedBy
|
||||
})
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using Indotalent.ConfigBackEnd.Extensions;
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveCategory.Cqrs;
|
||||
|
||||
public class GetLeaveCategoryListResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? Code { get; set; }
|
||||
public string? Name { get; set; }
|
||||
public int Quota { get; set; }
|
||||
public bool IsPaidLeave { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? Status { get; set; }
|
||||
}
|
||||
|
||||
public record GetLeaveCategoryListQuery() : IRequest<List<GetLeaveCategoryListResponse>>;
|
||||
|
||||
public class GetLeaveCategoryListHandler : IRequestHandler<GetLeaveCategoryListQuery, List<GetLeaveCategoryListResponse>>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public GetLeaveCategoryListHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<List<GetLeaveCategoryListResponse>> Handle(GetLeaveCategoryListQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _context.LeaveCategory
|
||||
.AsNoTracking()
|
||||
.NotDeletedOnly()
|
||||
.OrderBy(x => x.Code)
|
||||
.Select(x => new GetLeaveCategoryListResponse
|
||||
{
|
||||
Id = x.Id,
|
||||
AutoNumber = x.AutoNumber,
|
||||
Code = x.Code,
|
||||
Name = x.Name,
|
||||
Quota = x.Quota,
|
||||
IsPaidLeave = x.IsPaidLeave,
|
||||
Description = x.Description,
|
||||
Status = x.Status
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Indotalent.ConfigBackEnd.Exceptions;
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveCategory.Cqrs;
|
||||
|
||||
public class UpdateLeaveCategoryRequest : CreateLeaveCategoryRequest
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public DateTimeOffset? CreatedAt { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
public DateTimeOffset? UpdatedAt { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
}
|
||||
|
||||
public class UpdateLeaveCategoryResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public bool Success { get; set; }
|
||||
}
|
||||
|
||||
public record UpdateLeaveCategoryCommand(UpdateLeaveCategoryRequest Data) : IRequest<UpdateLeaveCategoryResponse>;
|
||||
|
||||
public class UpdateLeaveCategoryHandler : IRequestHandler<UpdateLeaveCategoryCommand, UpdateLeaveCategoryResponse>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public UpdateLeaveCategoryHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<UpdateLeaveCategoryResponse> Handle(UpdateLeaveCategoryCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var isExists = await _context.LeaveCategory
|
||||
.AnyAsync(x => x.Code == request.Data.Code && x.Id != request.Data.Id, cancellationToken);
|
||||
|
||||
if (isExists)
|
||||
{
|
||||
throw new AlreadyExistsException("Leave Category", request.Data.Code ?? string.Empty);
|
||||
}
|
||||
|
||||
var entity = await _context.LeaveCategory
|
||||
.FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);
|
||||
|
||||
if (entity == null)
|
||||
{
|
||||
return new UpdateLeaveCategoryResponse { Id = request.Data.Id, Success = false };
|
||||
}
|
||||
|
||||
entity.Code = request.Data.Code;
|
||||
entity.Name = request.Data.Name;
|
||||
entity.Quota = request.Data.Quota;
|
||||
entity.IsPaidLeave = request.Data.IsPaidLeave;
|
||||
entity.Description = request.Data.Description;
|
||||
entity.Status = request.Data.Status;
|
||||
entity.AllowCarryForward = request.Data.AllowCarryForward;
|
||||
entity.MaxCarryForward = request.Data.MaxCarryForward;
|
||||
entity.MinServiceMonths = request.Data.MinServiceMonths;
|
||||
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return new UpdateLeaveCategoryResponse
|
||||
{
|
||||
Id = entity.Id,
|
||||
Success = true
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using FluentValidation;
|
||||
using Indotalent.Shared.Consts;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveCategory.Cqrs;
|
||||
|
||||
public class UpdateLeaveCategoryValidator : AbstractValidator<UpdateLeaveCategoryRequest>
|
||||
{
|
||||
public UpdateLeaveCategoryValidator()
|
||||
{
|
||||
RuleFor(x => x.Id)
|
||||
.NotEmpty().WithMessage("ID is required for update");
|
||||
|
||||
RuleFor(x => x.Code)
|
||||
.NotEmpty().WithMessage("Category Code is required")
|
||||
.MaximumLength(GlobalConsts.StringLengthShort);
|
||||
|
||||
RuleFor(x => x.Name)
|
||||
.NotEmpty().WithMessage("Category Name is required")
|
||||
.MaximumLength(GlobalConsts.StringLengthShort);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using Indotalent.ConfigBackEnd.Extensions;
|
||||
using Indotalent.Features.Leave.LeaveCategory.Cqrs;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveCategory;
|
||||
|
||||
public static class LeaveCategoryEndpoint
|
||||
{
|
||||
public static void MapLeaveCategoryEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
var group = app.MapGroup("/leave-category").WithTags("Leave Categories")
|
||||
.RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
|
||||
.RequireAuthenticatedUser());
|
||||
|
||||
group.MapGet("/", async (IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new GetLeaveCategoryListQuery());
|
||||
return result.ToApiResponse("Data leave category retrieved successfully");
|
||||
})
|
||||
.WithName("GetLeaveCategoryList");
|
||||
|
||||
group.MapGet("/{id}", async (string id, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new GetLeaveCategoryByIdQuery(id));
|
||||
return result.ToApiResponse(result is not null
|
||||
? "Leave category detail retrieved successfully"
|
||||
: $"Leave category with ID {id} not found");
|
||||
})
|
||||
.WithName("GetLeaveCategoryById");
|
||||
|
||||
group.MapPost("/", async (CreateLeaveCategoryRequest request, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new CreateLeaveCategoryCommand(request));
|
||||
return result.ToApiResponse("Leave category has been created successfully", StatusCodes.Status201Created);
|
||||
})
|
||||
.WithName("CreateLeaveCategory");
|
||||
|
||||
group.MapPost("/update", async (UpdateLeaveCategoryRequest request, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new UpdateLeaveCategoryCommand(request));
|
||||
if (!result.Success) return ((object?)null).ToApiResponse("Update failed.");
|
||||
return result.ToApiResponse("Leave category has been updated successfully");
|
||||
})
|
||||
.WithName("UpdateLeaveCategory");
|
||||
|
||||
group.MapPost("/delete/{id}", async (string id, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new DeleteLeaveCategoryByIdCommand(new DeleteLeaveCategoryByIdRequest(id)));
|
||||
if (!result) return ((object?)null).ToApiResponse("Delete failed.");
|
||||
return true.ToApiResponse("Leave category has been deleted successfully");
|
||||
})
|
||||
.WithName("DeleteLeaveCategoryById");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using Indotalent.ConfigBackEnd.Interfaces;
|
||||
using Indotalent.ConfigFrontEnd.Common;
|
||||
using Indotalent.Features.Leave.LeaveCategory.Cqrs;
|
||||
using Indotalent.Infrastructure.Authentication.Identity;
|
||||
using Indotalent.Shared.Models;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using MudBlazor;
|
||||
using RestSharp;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveCategory;
|
||||
|
||||
public class LeaveCategoryService : BaseService
|
||||
{
|
||||
private readonly RestClient _client;
|
||||
|
||||
public LeaveCategoryService(IHttpClientFactory clientFactory, NavigationManager nav, ISnackbar snackbar, ICurrentUserService currentUserService, TokenProvider tokenProvider)
|
||||
: base(clientFactory, nav, snackbar, currentUserService, tokenProvider)
|
||||
{
|
||||
_client = new RestClient(nav.BaseUri);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<List<GetLeaveCategoryListResponse>>?> GetLeaveCategoryListAsync()
|
||||
{
|
||||
var request = new RestRequest("api/leave-category", Method.Get);
|
||||
return await ExecuteWithResponseAsync<List<GetLeaveCategoryListResponse>>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<GetLeaveCategoryByIdResponse>?> GetLeaveCategoryByIdAsync(string id)
|
||||
{
|
||||
var request = new RestRequest($"api/leave-category/{id}", Method.Get);
|
||||
return await ExecuteWithResponseAsync<GetLeaveCategoryByIdResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<CreateLeaveCategoryResponse>?> CreateLeaveCategoryAsync(CreateLeaveCategoryRequest data)
|
||||
{
|
||||
var request = new RestRequest("api/leave-category", Method.Post);
|
||||
request.AddJsonBody(data);
|
||||
return await ExecuteWithResponseAsync<CreateLeaveCategoryResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteLeaveCategoryByIdAsync(string id)
|
||||
{
|
||||
var request = new RestRequest($"api/leave-category/delete/{id}", Method.Post);
|
||||
var response = await ExecuteWithResponseAsync<object>(_client, request);
|
||||
return response?.IsSuccess ?? false;
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<UpdateLeaveCategoryResponse>?> UpdateLeaveCategoryAsync(UpdateLeaveCategoryRequest data)
|
||||
{
|
||||
var request = new RestRequest("api/leave-category/update", Method.Post);
|
||||
request.AddJsonBody(data);
|
||||
return await ExecuteWithResponseAsync<UpdateLeaveCategoryResponse>(_client, request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
@page "/leave"
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@using Indotalent.Infrastructure.Authorization.Identity
|
||||
@attribute [Authorize(Roles = $"{ApplicationRoles.Admin},{ApplicationRoles.Member}")]
|
||||
@using Indotalent.Features.Leave.LeaveBalance.Components
|
||||
@using Indotalent.Features.Leave.LeaveCategory
|
||||
@using Indotalent.Features.Leave.LeaveCategory.Components
|
||||
@using Indotalent.Features.Leave.LeaveRequest
|
||||
@using Indotalent.Features.Leave.LeaveBalance
|
||||
@using Indotalent.Features.Leave.LeaveRequest.Components
|
||||
@using MudBlazor
|
||||
@inject NavigationManager NavigationManager
|
||||
|
||||
<style>
|
||||
.clean-white-tabs .mud-tabs-toolbar {
|
||||
background-color: white !important;
|
||||
border-bottom: 2px solid #DCEBFA;
|
||||
border-radius: 0px !important;
|
||||
}
|
||||
|
||||
.clean-white-tabs .mud-tab {
|
||||
color: #94a3b8 !important;
|
||||
text-transform: none;
|
||||
font-weight: 500;
|
||||
min-width: 180px;
|
||||
border-radius: 0px !important;
|
||||
}
|
||||
|
||||
.clean-white-tabs .mud-tab-active {
|
||||
color: var(--mud-palette-primary) !important;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.clean-white-tabs .mud-tabs-slider {
|
||||
background-color: var(--mud-palette-primary) !important;
|
||||
height: 3px !important;
|
||||
bottom: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
<MudContainer MaxWidth="MaxWidth.ExtraLarge" Class="mt-2 mb-8">
|
||||
<div class="clean-white-tabs">
|
||||
<MudTabs Elevation="0"
|
||||
ActivePanelIndex="@_activeTabIndex"
|
||||
ActivePanelIndexChanged="OnTabChanged"
|
||||
ApplyEffectsToContainer="true"
|
||||
TabPanelsClass="pt-4">
|
||||
|
||||
<MudTabPanel Text="Leave Requests" Icon="@Icons.Material.Outlined.EventNote">
|
||||
<LeaveRequestPage />
|
||||
</MudTabPanel>
|
||||
|
||||
<MudTabPanel Text="Leave Categories" Icon="@Icons.Material.Outlined.Category">
|
||||
<LeaveCategoryPage />
|
||||
</MudTabPanel>
|
||||
|
||||
<MudTabPanel Text="Leave Balance" Icon="@Icons.Material.Outlined.AccountBalanceWallet">
|
||||
<LeaveBalancePage />
|
||||
</MudTabPanel>
|
||||
|
||||
</MudTabs>
|
||||
</div>
|
||||
</MudContainer>
|
||||
|
||||
@code {
|
||||
private int _activeTabIndex = 0;
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
var uri = NavigationManager.ToAbsoluteUri(NavigationManager.Uri);
|
||||
if (Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query).TryGetValue("tab", out var tabValue))
|
||||
{
|
||||
_activeTabIndex = tabValue.ToString().ToLower() switch
|
||||
{
|
||||
"request" => 0,
|
||||
"category" => 1,
|
||||
"balance" => 2,
|
||||
_ => 0
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private void OnTabChanged(int index)
|
||||
{
|
||||
_activeTabIndex = index;
|
||||
string tabName = index switch
|
||||
{
|
||||
0 => "request",
|
||||
1 => "category",
|
||||
2 => "balance",
|
||||
_ => "request"
|
||||
};
|
||||
|
||||
NavigationManager.NavigateTo($"/leave?tab={tabName}", replace: false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
@page "/leave/leave-request"
|
||||
@using Indotalent.Features.Leave.LeaveRequest.Components
|
||||
@using Indotalent.Features.Leave.LeaveRequest.Cqrs
|
||||
@using MudBlazor
|
||||
|
||||
@if (_currentView == ViewMode.Create)
|
||||
{
|
||||
<_LeaveRequestCreateForm OnCancel="BackToTable" OnSuccess="HandleSuccess" />
|
||||
}
|
||||
else if (_currentView == ViewMode.Update || _currentView == ViewMode.View)
|
||||
{
|
||||
<_LeaveRequestUpdateForm Data="_selectedData!" ReadOnly="@(_currentView == ViewMode.View)" OnCancel="BackToTable" OnSuccess="HandleSuccess" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<_LeaveRequestDataTable OnAdd="() => ShowCreate()" OnEdit="(item) => ShowUpdate(item, false)" OnView="(item) => ShowUpdate(item, true)" />
|
||||
}
|
||||
|
||||
@code {
|
||||
private enum ViewMode { Table, Create, Update, View }
|
||||
private ViewMode _currentView = ViewMode.Table;
|
||||
private UpdateLeaveRequestRequest? _selectedData;
|
||||
|
||||
private void ShowCreate() => _currentView = ViewMode.Create;
|
||||
|
||||
private void ShowUpdate(UpdateLeaveRequestRequest data, bool isReadOnly)
|
||||
{
|
||||
_selectedData = data;
|
||||
_currentView = isReadOnly ? ViewMode.View : ViewMode.Update;
|
||||
}
|
||||
|
||||
private void BackToTable() { _currentView = ViewMode.Table; _selectedData = null; }
|
||||
|
||||
private void HandleSuccess() { _currentView = ViewMode.Table; _selectedData = null; }
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
@using Indotalent.Features.Leave.LeaveRequest
|
||||
@using Indotalent.Features.Leave.LeaveRequest.Cqrs
|
||||
@using Indotalent.Features.Leave.LeaveCategory
|
||||
@using Indotalent.Features.Leave.LeaveCategory.Cqrs
|
||||
@using Indotalent.Shared.Utils
|
||||
@using MudBlazor
|
||||
@inject LeaveRequestService LeaveRequestService
|
||||
@inject LeaveCategoryService LeaveCategoryService
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
|
||||
<div class="d-flex align-center gap-4">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">Apply for Leave</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b;">Submit a new leave application for approval.</MudText>
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA;">
|
||||
<MudForm @ref="_form" Model="_model">
|
||||
<MudGrid Spacing="3">
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Select Employee</MudText>
|
||||
<MudSelect T="string" @bind-Value="_model.EmployeeId"
|
||||
For="@(() => _model.EmployeeId)"
|
||||
Validation="@(_validator.ValidateValue())"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense"
|
||||
AnchorOrigin="Origin.BottomLeft" TransformOrigin="Origin.TopLeft">
|
||||
@foreach (var emp in _employees)
|
||||
{
|
||||
<MudSelectItem Value="@emp.Id">@emp.FullName (@emp.Code)</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Leave Type</MudText>
|
||||
<MudSelect T="string" @bind-Value="_model.LeaveCategoryId"
|
||||
For="@(() => _model.LeaveCategoryId)"
|
||||
Validation="@(_validator.ValidateValue())"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense"
|
||||
AnchorOrigin="Origin.BottomLeft" TransformOrigin="Origin.TopLeft">
|
||||
@foreach (var cat in _categories)
|
||||
{
|
||||
<MudSelectItem Value="@cat.Id">@cat.Name</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="3">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Start Date</MudText>
|
||||
<MudDatePicker @bind-Date="_startDate" Variant="Variant.Outlined" Margin="Margin.Dense" Editable="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="3">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">End Date</MudText>
|
||||
<MudDatePicker @bind-Date="_endDate" Variant="Variant.Outlined" Margin="Margin.Dense" Editable="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Total Days</MudText>
|
||||
<MudNumericField @bind-Value="_model.Days" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" ReadOnly="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Reason</MudText>
|
||||
<MudTextField @bind-Value="_model.Reason"
|
||||
For="@(() => _model.Reason)"
|
||||
Validation="@(_validator.ValidateValue())"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Lines="3" />
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<div class="d-flex justify-end gap-2 mt-8">
|
||||
<MudButton OnClick="() => OnCancel.InvokeAsync()" Variant="Variant.Outlined" Disabled="_processing" Style="border: 1px solid #e0e0e0; border-radius: 4px; text-transform: none; font-weight: 700;">Cancel</MudButton>
|
||||
<MudButton Color="Color.Primary" Variant="Variant.Filled" OnClick="Submit" Disabled="_processing" Style="border-radius: 4px; text-transform: none; font-weight: 700;">
|
||||
@if (_processing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2">Submitting...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText>Submit Application</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
</div>
|
||||
</MudForm>
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter] public EventCallback OnCancel { get; set; }
|
||||
[Parameter] public EventCallback OnSuccess { get; set; }
|
||||
|
||||
private MudForm _form = default!;
|
||||
private CreateLeaveRequestValidator _validator = new();
|
||||
private CreateLeaveRequestRequest _model = new() { StartDate = DateTime.Today, EndDate = DateTime.Today };
|
||||
private List<GetLeaveCategoryListResponse> _categories = new();
|
||||
private List<EmployeeLeaveReferenceResponse> _employees = new();
|
||||
private bool _processing = false;
|
||||
|
||||
private DateTime? _startDate { get => _model.StartDate; set { _model.StartDate = value ?? DateTime.Today; CalculateDays(); } }
|
||||
private DateTime? _endDate { get => _model.EndDate; set { _model.EndDate = value ?? DateTime.Today; CalculateDays(); } }
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
var catRes = await LeaveCategoryService.GetLeaveCategoryListAsync();
|
||||
if (catRes != null && catRes.IsSuccess) _categories = catRes.Value ?? new();
|
||||
|
||||
var empRes = await LeaveRequestService.GetEmployeeReferenceAsync();
|
||||
if (empRes != null && empRes.IsSuccess) _employees = empRes.Value ?? new();
|
||||
|
||||
CalculateDays();
|
||||
}
|
||||
|
||||
private void CalculateDays()
|
||||
{
|
||||
_model.Days = (_model.EndDate - _model.StartDate).TotalDays + 1;
|
||||
if (_model.Days < 0) _model.Days = 0;
|
||||
}
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
await _form.Validate();
|
||||
if (!_form.IsValid) return;
|
||||
_processing = true;
|
||||
try
|
||||
{
|
||||
var response = await LeaveRequestService.CreateLeaveRequestAsync(_model);
|
||||
await Task.Delay(500);
|
||||
if (response != null && response.IsSuccess)
|
||||
{
|
||||
Snackbar.Add("Leave request submitted", Severity.Success);
|
||||
await OnSuccess.InvokeAsync();
|
||||
}
|
||||
}
|
||||
finally { _processing = false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
@using Indotalent.ConfigBackEnd.Extensions
|
||||
@using Indotalent.Features.Leave.LeaveRequest
|
||||
@using Indotalent.Features.Leave.LeaveRequest.Cqrs
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using Microsoft.JSInterop
|
||||
@using MudBlazor
|
||||
@using Features.Root.Shared
|
||||
@using ClosedXML.Excel
|
||||
@using System.IO
|
||||
@inject LeaveRequestService LeaveRequestService
|
||||
@inject IDialogService DialogService
|
||||
@inject ISnackbar Snackbar
|
||||
@inject IJSRuntime JSRuntime
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #E5E7EB; border-radius: 12px;">
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 700; color: #111827;">Leave Requests</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #9CA3AF;">Track and manage employee leave applications and their approval status.</MudText>
|
||||
</div>
|
||||
<div class="d-flex align-center gap-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Home" Size="Size.Small" Color="Color.Default" />
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">Leave</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="font-weight: 600; color: #111827;">Request</MudText>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Style="border-radius: 12px; overflow: hidden; background-color: #ffffff; border: 1px solid #E5E7EB;">
|
||||
|
||||
<div style="padding: 20px 24px; border-bottom: 1px solid #E5E7EB; display: flex; justify-content: space-between; align-items: center; background-color: #F8FAFC; min-height: 80px;">
|
||||
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<MudTextField @bind-Value="_searchString"
|
||||
Placeholder="Search..."
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Search"
|
||||
IconSize="Size.Small"
|
||||
Class="mt-0"
|
||||
Variant="Variant.Outlined"
|
||||
Margin="Margin.Dense"
|
||||
Style="background-color: white; width: 280px; border-radius: 8px;"
|
||||
OnKeyDown="@HandleSearchKeyDown" />
|
||||
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
OnClick="OnSearchClick"
|
||||
Size="Size.Small"
|
||||
Style="text-transform: none; font-weight: 500; border-radius: 6px; height: 34px; box-shadow: none;">
|
||||
Search
|
||||
</MudButton>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<MudButton Variant="Variant.Outlined"
|
||||
Color="Color.Success"
|
||||
OnClick="ExportToExcel"
|
||||
Size="Size.Small"
|
||||
Disabled="_isExporting"
|
||||
StartIcon="@(_isExporting ? null : Icons.Custom.FileFormats.FileExcel)"
|
||||
Style="border: 1px solid #D1D5DB; background: white; font-weight: 500; border-radius: 6px; text-transform: none; height: 34px; color: #6B7280;">
|
||||
@if (_isExporting)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText Typo="Typo.button" Style="text-transform: none !important;">Excel</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
|
||||
<MudButton Variant="Variant.Outlined"
|
||||
Color="Color.Primary"
|
||||
OnClick="LoadData"
|
||||
Size="Size.Small"
|
||||
StartIcon="@(_isRefreshing ? null : Icons.Material.Filled.Refresh)"
|
||||
Disabled="_isRefreshing"
|
||||
Style="border: 1px solid #D1D5DB; background: white; font-weight: 500; border-radius: 6px; text-transform: none; height: 34px; color: #6B7280;">
|
||||
@if (_isRefreshing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Refreshing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText Typo="Typo.button" Style="text-transform: none !important;">Refresh</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
|
||||
@if (_selectedRequest != null)
|
||||
{
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Info" StartIcon="@Icons.Material.Filled.Visibility" OnClick="InvokeView" Size="Size.Small" Style="border: 1px solid #D1D5DB; text-transform: none; font-weight: 500; border-radius: 6px; background: white; color: #6B7280;">View Details</MudButton>
|
||||
@if (_selectedRequest.Status == "Pending")
|
||||
{
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Edit" OnClick="InvokeEdit" Size="Size.Small" Style="border: 1px solid #D1D5DB; text-transform: none; font-weight: 500; border-radius: 6px; background: white; color: #6B7280;">Edit</MudButton>
|
||||
}
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Error" StartIcon="@Icons.Material.Filled.Delete" OnClick="OnDelete" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; border: 1px solid #FCA5A5; color: #EF4444; background: white;">Remove</MudButton>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Close" Size="Size.Small" OnClick="() => _selectedRequest = null" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Add" OnClick="() => OnAdd.InvokeAsync()" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; height: 34px;">
|
||||
Apply for Leave
|
||||
</MudButton>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<MudTable Items="@GetPagedData()" Hover="true" Striped="true" Class="mud-table-styled" Elevation="0" CustomHeader="true" Dense="true" T="GetLeaveRequestListResponse" OnRowClick="@((args) => _selectedRequest = args.Item)" Loading="@_isRefreshing">
|
||||
<HeaderContent>
|
||||
<MudTh Style="width: 50px; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB;"></MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetLeaveRequestListResponse, object>(x => x.EmployeeName!)">Employee</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetLeaveRequestListResponse, object>(x => x.LeaveType!)">Leave Type</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetLeaveRequestListResponse, object>(x => x.StartDate)">Period</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetLeaveRequestListResponse, object>(x => x.Days)">Days</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetLeaveRequestListResponse, object>(x => x.Reason!)">Reason</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetLeaveRequestListResponse, object>(x => x.Status!)">Status</MudTableSortLabel>
|
||||
</MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd>
|
||||
<MudCheckBox T="bool" Value="@(_selectedRequest?.Id == context.Id)" Color="Color.Primary" Dense="true" Size="Size.Small" ReadOnly="true" />
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<div class="d-flex align-center">
|
||||
<MudAvatar Color="@GetRandomColor(context.EmployeeName!)" Size="Size.Small" Class="mr-3" Style="font-weight: 600; font-size: 0.7rem;">@context.EmployeeName!.ToInitial()</MudAvatar>
|
||||
<div>
|
||||
<MudText Typo="Typo.body2" Style="font-weight: 700;">@context.EmployeeName</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">@context.EmployeeId</MudText>
|
||||
</div>
|
||||
</div>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudChip T="string" Size="Size.Small" Variant="Variant.Text" Style="background-color: #F0F9FF; color: #0369a1; font-weight: 600; border-radius: 0px;">@context.LeaveType</MudChip>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudText Typo="Typo.body2" Style="font-size: 0.8rem; font-weight: 600;">@context.StartDate.ToString("dd MMM yyyy")</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">to @context.EndDate.ToString("dd MMM yyyy")</MudText>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudText Typo="Typo.body2" Style="font-weight: 600; color: #1e293b;">@context.Days</MudText>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b; font-size: 0.8rem;" Class="text-truncate">@context.Reason</MudText>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudChip T="string" Color="@GetStatusColor(context.Status!)" Size="Size.Small" Variant="Variant.Filled" Style="font-weight: 600; border-radius: 6px; text-transform: uppercase; font-size: 0.65rem;">@context.Status</MudChip>
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
</MudTable>
|
||||
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; padding: 12px 24px; background-color: #F8FAFC; border-top: 2px solid #E5E7EB;">
|
||||
<div style="display: flex; align-items: center; gap: 12px;">
|
||||
<MudText Typo="Typo.caption" Style="font-weight: 700; color: #1e293b;">Rows per page:</MudText>
|
||||
|
||||
<MudSelect T="int"
|
||||
Value="@_top"
|
||||
ValueChanged="OnPageSizeChanged"
|
||||
Dense="true"
|
||||
Margin="Margin.Dense"
|
||||
Style="width: 80px; background-color: white; font-size: 0.75rem; font-weight: 500;"
|
||||
Variant="Variant.Outlined"
|
||||
Class="mt-0 custom-select-dense">
|
||||
<MudSelectItem Value="5" />
|
||||
<MudSelectItem Value="10" />
|
||||
<MudSelectItem Value="50" />
|
||||
<MudSelectItem Value="500" />
|
||||
<MudSelectItem Value="1000" />
|
||||
</MudSelect>
|
||||
|
||||
<MudText Typo="Typo.caption" Style="color: #64748b; margin-left: 12px;">
|
||||
Showing @(GetFilteredData().Count() == 0 ? 0 : _skip + 1)-@Math.Min(_skip + _top, GetFilteredData().Count()) of @GetFilteredData().Count()
|
||||
</MudText>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.FirstPage" Size="Size.Small" OnClick="@(() => OnPageChanged(1))" Disabled="@(_currentPage == 1)" Style="@(_currentPage == 1 ? "color: #D1D5DB; background: transparent;" : "color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px;")" />
|
||||
<MudButton OnClick="@(() => OnPageChanged(_currentPage - 1))" Disabled="@(_currentPage == 1)" Variant="Variant.Text" StartIcon="@Icons.Material.Filled.ChevronLeft" Size="Size.Small" Style="@(_currentPage == 1 ? "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;" : "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;")">Prev</MudButton>
|
||||
@{
|
||||
var totalPages = _totalPage == 0 ? 1 : _totalPage;
|
||||
var maxVisible = 5;
|
||||
var startPage = Math.Max(1, _currentPage - maxVisible / 2);
|
||||
var endPage = Math.Min(totalPages, startPage + maxVisible - 1);
|
||||
if (endPage - startPage < maxVisible - 1) { startPage = Math.Max(1, endPage - maxVisible + 1); }
|
||||
}
|
||||
@for (int i = startPage; i <= endPage; i++)
|
||||
{
|
||||
var pageNum = i;
|
||||
var isActive = pageNum == _currentPage;
|
||||
<MudButton OnClick="@(() => OnPageChanged(pageNum))"
|
||||
Variant="Variant.Text" Size="Size.Small"
|
||||
Style="@(isActive ? "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 600; background: #3B82F6; color: white; border: 1px solid #3B82F6; border-radius: 6px; text-transform: none;" : "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 500; color: #374151; background: white; border: 1px solid #D1D5DB; border-radius: 6px; text-transform: none;")">@pageNum</MudButton>
|
||||
}
|
||||
<MudButton OnClick="@(() => OnPageChanged(_currentPage + 1))" Disabled="@(_currentPage == _totalPage || _totalPage == 0)" Variant="Variant.Text" EndIcon="@Icons.Material.Filled.ChevronRight" Size="Size.Small" Style="@(_currentPage == _totalPage || _totalPage == 0 ? "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;" : "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;")">Next</MudButton>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.LastPage" Size="Size.Small" OnClick="@(() => OnPageChanged(_totalPage))" Disabled="@(_currentPage == _totalPage || _totalPage == 0)" Style="@(_currentPage == _totalPage || _totalPage == 0 ? "color: #D1D5DB; background: transparent;" : "color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px;")" />
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<script>
|
||||
function downloadFile(fileName, contentType, base64String) {
|
||||
const link = document.createElement('a');
|
||||
link.download = fileName;
|
||||
link.href = `data:${contentType};base64,${base64String}`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.mud-input-outlined-border { border-radius: 8px !important; }
|
||||
.custom-select-dense .mud-input-control { margin-top: 0 !important; }
|
||||
.custom-select-dense .mud-input-slot { padding-top: 4px !important; padding-bottom: 4px !important; padding-left: 8px !important; font-size: 12px !important; }
|
||||
.mud-table-styled .mud-table-row:hover { background-color: #F9FAFB !important; }
|
||||
</style>
|
||||
|
||||
@code {
|
||||
[Parameter] public EventCallback OnAdd { get; set; }
|
||||
[Parameter] public EventCallback<UpdateLeaveRequestRequest> OnEdit { get; set; }
|
||||
[Parameter] public EventCallback<UpdateLeaveRequestRequest> OnView { get; set; }
|
||||
|
||||
private List<GetLeaveRequestListResponse> _requests = new();
|
||||
private GetLeaveRequestListResponse? _selectedRequest;
|
||||
private string _searchString = "";
|
||||
private int _skip = 0;
|
||||
private int _top = 5;
|
||||
private int _totalPage => GetFilteredData().Count() == 0 ? 0 : (int)Math.Ceiling((double)GetFilteredData().Count() / (_top == 0 ? 1 : _top));
|
||||
private int _currentPage => (_top >= GetFilteredData().Count() || _top == 0) ? 1 : (_skip / _top) + 1;
|
||||
private bool _isRefreshing = false;
|
||||
private bool _isExporting = false;
|
||||
|
||||
protected override async Task OnInitializedAsync() => await LoadData();
|
||||
|
||||
private async Task LoadData()
|
||||
{
|
||||
_isRefreshing = true; _selectedRequest = null;
|
||||
StateHasChanged();
|
||||
try
|
||||
{
|
||||
var response = await LeaveRequestService.GetLeaveRequestListAsync();
|
||||
await Task.Delay(1000);
|
||||
if (response != null && response.IsSuccess)
|
||||
{
|
||||
_requests = response.Value ?? new();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isRefreshing = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerable<GetLeaveRequestListResponse> GetFilteredData()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_searchString)) return _requests;
|
||||
return _requests.Where(x =>
|
||||
(x.EmployeeName?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.EmployeeId?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.LeaveType?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.Reason?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.Status?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false)
|
||||
);
|
||||
}
|
||||
|
||||
private IEnumerable<GetLeaveRequestListResponse> GetPagedData() => GetFilteredData().Skip(_skip).Take(_top);
|
||||
|
||||
private async Task ExportToExcel()
|
||||
{
|
||||
_isExporting = true;
|
||||
StateHasChanged();
|
||||
try
|
||||
{
|
||||
await Task.Delay(1000);
|
||||
using (var workbook = new XLWorkbook())
|
||||
{
|
||||
var worksheet = workbook.Worksheets.Add("LeaveRequests");
|
||||
var currentRow = 1;
|
||||
|
||||
worksheet.Cell(currentRow, 1).Value = "Employee Name";
|
||||
worksheet.Cell(currentRow, 2).Value = "Leave Type";
|
||||
worksheet.Cell(currentRow, 3).Value = "Start Date";
|
||||
worksheet.Cell(currentRow, 4).Value = "End Date";
|
||||
worksheet.Cell(currentRow, 5).Value = "Days";
|
||||
worksheet.Cell(currentRow, 6).Value = "Reason";
|
||||
worksheet.Cell(currentRow, 7).Value = "Status";
|
||||
|
||||
var headerRange = worksheet.Range(1, 1, 1, 7);
|
||||
headerRange.Style.Font.Bold = true;
|
||||
headerRange.Style.Fill.BackgroundColor = XLColor.FromHtml("#0D47A1");
|
||||
headerRange.Style.Font.FontColor = XLColor.White;
|
||||
|
||||
foreach (var item in GetFilteredData())
|
||||
{
|
||||
currentRow++;
|
||||
worksheet.Cell(currentRow, 1).Value = item.EmployeeName;
|
||||
worksheet.Cell(currentRow, 2).Value = item.LeaveType;
|
||||
worksheet.Cell(currentRow, 3).Value = item.StartDate.ToString("dd-MMM-yyyy");
|
||||
worksheet.Cell(currentRow, 4).Value = item.EndDate.ToString("dd-MMM-yyyy");
|
||||
worksheet.Cell(currentRow, 5).Value = item.Days;
|
||||
worksheet.Cell(currentRow, 6).Value = item.Reason;
|
||||
worksheet.Cell(currentRow, 7).Value = item.Status;
|
||||
}
|
||||
|
||||
worksheet.Columns().AdjustToContents();
|
||||
|
||||
using (var stream = new MemoryStream())
|
||||
{
|
||||
workbook.SaveAs(stream);
|
||||
var content = Convert.ToBase64String(stream.ToArray());
|
||||
await JSRuntime.InvokeVoidAsync("downloadFile", "Leave_Request_Registry.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", content);
|
||||
Snackbar.Add("Excel exported successfully", Severity.Success);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Export failed: {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isExporting = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnSearchClick()
|
||||
{
|
||||
_skip = 0;
|
||||
_selectedRequest = null;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private void HandleSearchKeyDown(KeyboardEventArgs e)
|
||||
{
|
||||
if (e.Key == "Enter") OnSearchClick();
|
||||
}
|
||||
|
||||
private void OnPageChanged(int page)
|
||||
{
|
||||
if (page >= 1 && page <= _totalPage)
|
||||
{
|
||||
_skip = (page - 1) * _top;
|
||||
_selectedRequest = null;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPageSizeChanged(int size)
|
||||
{
|
||||
_top = size;
|
||||
_skip = 0;
|
||||
_selectedRequest = null;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private Color GetRandomColor(string name) { int hash = name.GetHashCode(); var colors = new[] { Color.Primary, Color.Secondary, Color.Tertiary, Color.Info, Color.Success, Color.Warning, Color.Dark }; return colors[Math.Abs(hash) % colors.Length]; }
|
||||
private Color GetStatusColor(string status) => status switch { "Approved" => Color.Success, "Pending" => Color.Warning, "Rejected" => Color.Error, _ => Color.Default };
|
||||
|
||||
private async Task InvokeEdit() { if (_selectedRequest != null) { var res = await LeaveRequestService.GetLeaveRequestByIdAsync(_selectedRequest.Id!); if (res?.Value != null) await OnEdit.InvokeAsync(MapToUpdate(res.Value)); } }
|
||||
private async Task InvokeView() { if (_selectedRequest != null) { var res = await LeaveRequestService.GetLeaveRequestByIdAsync(_selectedRequest.Id!); if (res?.Value != null) await OnView.InvokeAsync(MapToUpdate(res.Value)); } }
|
||||
|
||||
private UpdateLeaveRequestRequest MapToUpdate(GetLeaveRequestByIdResponse d) => new UpdateLeaveRequestRequest
|
||||
{
|
||||
Id = d.Id,
|
||||
EmployeeId = d.EmployeeId!,
|
||||
LeaveCategoryId = d.LeaveCategoryId!,
|
||||
StartDate = d.StartDate,
|
||||
EndDate = d.EndDate,
|
||||
Days = d.Days,
|
||||
Reason = d.Reason ?? "",
|
||||
Status = d.Status ?? "Pending",
|
||||
AttachmentPath = d.AttachmentPath,
|
||||
ApproverId = d.ApproverId,
|
||||
ActionDate = d.ActionDate,
|
||||
RejectReason = d.RejectReason,
|
||||
CreatedAt = d.CreatedAt,
|
||||
CreatedBy = d.CreatedBy,
|
||||
UpdatedAt = d.UpdatedAt,
|
||||
UpdatedBy = d.UpdatedBy
|
||||
};
|
||||
|
||||
private async Task OnDelete()
|
||||
{
|
||||
if (_selectedRequest == null) return;
|
||||
var dialog = await DialogService.ShowAsync<Features.Root.Shared._DeleteConfirmation>("", new DialogParameters<Features.Root.Shared._DeleteConfirmation> { { x => x.ContentText, $"Request for {_selectedRequest.EmployeeName}" } });
|
||||
if (!(await dialog.Result).Canceled)
|
||||
{
|
||||
if (await LeaveRequestService.DeleteLeaveRequestByIdAsync(_selectedRequest.Id!)) { await LoadData(); Snackbar.Add("Request deleted", Severity.Success); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
@using Indotalent.ConfigBackEnd.Extensions
|
||||
@using Indotalent.Features.Leave.LeaveRequest
|
||||
@using Indotalent.Features.Leave.LeaveRequest.Cqrs
|
||||
@using Indotalent.Features.Leave.LeaveCategory
|
||||
@using Indotalent.Features.Leave.LeaveCategory.Cqrs
|
||||
@using Indotalent.Shared.Utils
|
||||
@using MudBlazor
|
||||
@inject LeaveRequestService LeaveRequestService
|
||||
@inject LeaveCategoryService LeaveCategoryService
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
|
||||
<div class="d-flex align-center gap-4">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">@(ReadOnly ? "Request Details" : "Edit Request")</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b;">Reviewing leave application details and status.</MudText>
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA;">
|
||||
@if (_isInitialLoading)
|
||||
{
|
||||
<div class="d-flex flex-column align-center justify-center pa-10">
|
||||
<MudProgressCircular Color="Color.Primary" Indeterminate="true" Size="Size.Large" />
|
||||
<MudText Typo="Typo.body2" Class="mt-4">Loading application data...</MudText>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudForm @ref="_form" Model="_model">
|
||||
<MudGrid Spacing="3">
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Employee</MudText>
|
||||
<MudSelect T="string" @bind-Value="_model.EmployeeId"
|
||||
ReadOnly="ReadOnly"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense"
|
||||
AnchorOrigin="Origin.BottomLeft" TransformOrigin="Origin.TopLeft">
|
||||
@foreach (var emp in _employees)
|
||||
{
|
||||
<MudSelectItem Value="@emp.Id">@emp.FullName (@emp.Code)</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Leave Type</MudText>
|
||||
<MudSelect T="string" @bind-Value="_model.LeaveCategoryId"
|
||||
ReadOnly="ReadOnly"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense"
|
||||
AnchorOrigin="Origin.BottomLeft" TransformOrigin="Origin.TopLeft">
|
||||
@foreach (var cat in _categories)
|
||||
{
|
||||
<MudSelectItem Value="@cat.Id">@cat.Name</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Start Date</MudText>
|
||||
<MudDatePicker @bind-Date="_startDate" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">End Date</MudText>
|
||||
<MudDatePicker @bind-Date="_endDate" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Total Days</MudText>
|
||||
<MudNumericField @bind-Value="_model.Days" ReadOnly="true" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Reason</MudText>
|
||||
<MudTextField @bind-Value="_model.Reason" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Lines="2" />
|
||||
</MudItem>
|
||||
|
||||
@if (!ReadOnly && _model.Status == "Pending")
|
||||
{
|
||||
<MudItem xs="12" Class="mt-4">
|
||||
<MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">Approval Action</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Decision Status</MudText>
|
||||
<MudSelect @bind-Value="_model.Status"
|
||||
Variant="Variant.Outlined"
|
||||
Margin="Margin.Dense"
|
||||
AnchorOrigin="Origin.BottomLeft"
|
||||
TransformOrigin="Origin.TopLeft">
|
||||
<MudSelectItem Value="@("Pending")">Pending</MudSelectItem>
|
||||
<MudSelectItem Value="@("Approved")">Approved</MudSelectItem>
|
||||
<MudSelectItem Value="@("Rejected")">Rejected</MudSelectItem>
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Notes / Reject Reason</MudText>
|
||||
<MudTextField @bind-Value="_model.RejectReason"
|
||||
Variant="Variant.Outlined"
|
||||
Margin="Margin.Dense"
|
||||
FullWidth="true"
|
||||
Placeholder="Provide reason if rejected..." />
|
||||
</MudItem>
|
||||
}
|
||||
|
||||
<MudItem xs="12" Class="mt-4">
|
||||
<MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">Audit & Action History</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Created At</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@DateTimeExtensions.ToString(_model.CreatedAt)</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Created By</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@(!string.IsNullOrEmpty(_model.CreatedBy) ? _model.CreatedBy : "System")</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Action By</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@(!string.IsNullOrEmpty(_model.ApproverId) ? _model.ApproverId : "-")</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Action Date</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@(_model.ActionDate.HasValue? _model.ActionDate.Value.ToString("dd MMM yyyy HH:mm") : "-")</MudText>
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<div class="d-flex justify-end gap-2 mt-10">
|
||||
<MudButton OnClick="() => OnCancel.InvokeAsync()" Variant="Variant.Outlined" Disabled="_processing" Style="border: 1px solid #e0e0e0; border-radius: 4px; text-transform: none; font-weight: 700;">@(ReadOnly ? "Back to List" : "Cancel")</MudButton>
|
||||
@if (!ReadOnly)
|
||||
{
|
||||
<MudButton Color="Color.Primary" Variant="Variant.Filled" OnClick="Submit" Disabled="_processing" Style="border-radius: 4px; text-transform: none; font-weight: 700;">
|
||||
@if (_processing)
|
||||
{
|
||||
<MudProgressCircular Size="Size.Small" Indeterminate="true" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText>Save Changes</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
}
|
||||
</div>
|
||||
</MudForm>
|
||||
}
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter] public UpdateLeaveRequestRequest Data { get; set; } = new();
|
||||
[Parameter] public bool ReadOnly { get; set; } = false;
|
||||
[Parameter] public EventCallback OnCancel { get; set; }
|
||||
[Parameter] public EventCallback OnSuccess { get; set; }
|
||||
|
||||
private MudForm _form = default!;
|
||||
private UpdateLeaveRequestValidator _validator = new();
|
||||
private UpdateLeaveRequestRequest _model = new();
|
||||
private List<EmployeeLeaveReferenceResponse> _employees = new();
|
||||
private List<GetLeaveCategoryListResponse> _categories = new();
|
||||
private bool _processing = false;
|
||||
private bool _isInitialLoading = true;
|
||||
|
||||
private DateTime? _startDate { get => _model.StartDate; set { _model.StartDate = value ?? DateTime.Today; CalculateDays(); } }
|
||||
private DateTime? _endDate { get => _model.EndDate; set { _model.EndDate = value ?? DateTime.Today; CalculateDays(); } }
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
_isInitialLoading = true;
|
||||
try
|
||||
{
|
||||
_model = new UpdateLeaveRequestRequest
|
||||
{
|
||||
Id = Data.Id,
|
||||
EmployeeId = Data.EmployeeId,
|
||||
EmployeeName = Data.EmployeeName,
|
||||
LeaveCategoryId = Data.LeaveCategoryId,
|
||||
LeaveType = Data.LeaveType,
|
||||
StartDate = Data.StartDate,
|
||||
EndDate = Data.EndDate,
|
||||
Days = Data.Days,
|
||||
Reason = Data.Reason,
|
||||
Status = Data.Status,
|
||||
AttachmentPath = Data.AttachmentPath,
|
||||
ApproverId = Data.ApproverId,
|
||||
ActionDate = Data.ActionDate,
|
||||
RejectReason = Data.RejectReason,
|
||||
CreatedAt = Data.CreatedAt,
|
||||
CreatedBy = Data.CreatedBy,
|
||||
UpdatedAt = Data.UpdatedAt,
|
||||
UpdatedBy = Data.UpdatedBy
|
||||
};
|
||||
|
||||
var empRes = await LeaveRequestService.GetEmployeeReferenceAsync();
|
||||
if (empRes != null && empRes.IsSuccess) _employees = empRes.Value ?? new();
|
||||
|
||||
var catRes = await LeaveCategoryService.GetLeaveCategoryListAsync();
|
||||
if (catRes != null && catRes.IsSuccess) _categories = catRes.Value ?? new();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isInitialLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void CalculateDays()
|
||||
{
|
||||
_model.Days = (_model.EndDate - _model.StartDate).TotalDays + 1;
|
||||
if (_model.Days < 0) _model.Days = 0;
|
||||
}
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
if (ReadOnly) return;
|
||||
await _form.Validate();
|
||||
if (!_form.IsValid) return;
|
||||
_processing = true;
|
||||
try
|
||||
{
|
||||
var response = await LeaveRequestService.UpdateLeaveRequestAsync(_model);
|
||||
await Task.Delay(500);
|
||||
if (response != null && response.IsSuccess)
|
||||
{
|
||||
Snackbar.Add("Request updated successfully", Severity.Success);
|
||||
await OnSuccess.InvokeAsync();
|
||||
}
|
||||
}
|
||||
finally { _processing = false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using Indotalent.ConfigBackEnd.Extensions;
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveRequest.Cqrs;
|
||||
|
||||
public class CreateLeaveRequestRequest
|
||||
{
|
||||
public string EmployeeId { get; set; } = string.Empty;
|
||||
public string LeaveCategoryId { get; set; } = string.Empty;
|
||||
public DateTime StartDate { get; set; }
|
||||
public DateTime EndDate { get; set; }
|
||||
public double Days { get; set; }
|
||||
public string Reason { get; set; } = string.Empty;
|
||||
public string Status { get; set; } = "Pending";
|
||||
public string? AttachmentPath { get; set; }
|
||||
}
|
||||
|
||||
public class CreateLeaveRequestResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
}
|
||||
|
||||
public record CreateLeaveRequestCommand(CreateLeaveRequestRequest Data) : IRequest<CreateLeaveRequestResponse>;
|
||||
|
||||
public class CreateLeaveRequestHandler : IRequestHandler<CreateLeaveRequestCommand, CreateLeaveRequestResponse>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public CreateLeaveRequestHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<CreateLeaveRequestResponse> Handle(CreateLeaveRequestCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var entityName = nameof(Data.Entities.LeaveRequest);
|
||||
|
||||
var autoNo = await _context.GenerateAutoNumberAsync(
|
||||
entityName: entityName,
|
||||
prefixTemplate: $"{entityName.ToShortNameConsonant(3)}/{{Year}}/",
|
||||
ct: cancellationToken
|
||||
);
|
||||
|
||||
var entity = new Data.Entities.LeaveRequest
|
||||
{
|
||||
AutoNumber = autoNo,
|
||||
EmployeeId = request.Data.EmployeeId,
|
||||
LeaveCategoryId = request.Data.LeaveCategoryId,
|
||||
StartDate = request.Data.StartDate,
|
||||
EndDate = request.Data.EndDate,
|
||||
Days = request.Data.Days,
|
||||
Reason = request.Data.Reason,
|
||||
Status = request.Data.Status,
|
||||
AttachmentPath = request.Data.AttachmentPath
|
||||
};
|
||||
|
||||
_context.LeaveRequest.Add(entity);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return new CreateLeaveRequestResponse
|
||||
{
|
||||
Id = entity.Id,
|
||||
AutoNumber = entity.AutoNumber
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveRequest.Cqrs;
|
||||
|
||||
public class CreateLeaveRequestValidator : AbstractValidator<CreateLeaveRequestRequest>
|
||||
{
|
||||
public CreateLeaveRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.EmployeeId).NotEmpty().WithMessage("Employee is required");
|
||||
RuleFor(x => x.LeaveCategoryId).NotEmpty().WithMessage("Leave Type is required");
|
||||
RuleFor(x => x.StartDate).NotEmpty();
|
||||
RuleFor(x => x.EndDate).NotEmpty().GreaterThanOrEqualTo(x => x.StartDate).WithMessage("End Date cannot be before Start Date");
|
||||
RuleFor(x => x.Reason).NotEmpty().WithMessage("Reason is required");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveRequest.Cqrs;
|
||||
|
||||
public record DeleteLeaveRequestByIdRequest(string Id);
|
||||
|
||||
public record DeleteLeaveRequestByIdCommand(DeleteLeaveRequestByIdRequest Data) : IRequest<bool>;
|
||||
|
||||
public class DeleteLeaveRequestByIdHandler : IRequestHandler<DeleteLeaveRequestByIdCommand, bool>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public DeleteLeaveRequestByIdHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<bool> Handle(DeleteLeaveRequestByIdCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = await _context.LeaveRequest
|
||||
.FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);
|
||||
|
||||
if (entity == null) return false;
|
||||
|
||||
_context.LeaveRequest.Remove(entity);
|
||||
return await _context.SaveChangesAsync(cancellationToken) > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveRequest.Cqrs;
|
||||
|
||||
public class EmployeeLeaveReferenceResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? Code { get; set; }
|
||||
public string? FullName { get; set; }
|
||||
}
|
||||
|
||||
public record GetEmployeeLeaveReferenceQuery() : IRequest<List<EmployeeLeaveReferenceResponse>>;
|
||||
|
||||
public class GetEmployeeLeaveReferenceHandler : IRequestHandler<GetEmployeeLeaveReferenceQuery, List<EmployeeLeaveReferenceResponse>>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public GetEmployeeLeaveReferenceHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<List<EmployeeLeaveReferenceResponse>> Handle(GetEmployeeLeaveReferenceQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _context.Employee
|
||||
.AsNoTracking()
|
||||
.Where(x => x.EmployeeStatus == "Active")
|
||||
.Select(x => new EmployeeLeaveReferenceResponse
|
||||
{
|
||||
Id = x.Id,
|
||||
Code = x.Code,
|
||||
FullName = $"{x.FirstName} {x.LastName}"
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveRequest.Cqrs;
|
||||
|
||||
public class GetLeaveRequestByIdResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? EmployeeId { get; set; }
|
||||
public string? EmployeeName { get; set; }
|
||||
public string? LeaveCategoryId { get; set; }
|
||||
public string? LeaveType { get; set; }
|
||||
public DateTime StartDate { get; set; }
|
||||
public DateTime EndDate { get; set; }
|
||||
public double Days { get; set; }
|
||||
public string? Reason { get; set; }
|
||||
public string? Status { get; set; }
|
||||
public string? AttachmentPath { get; set; }
|
||||
public string? ApproverId { get; set; }
|
||||
public DateTime? ActionDate { get; set; }
|
||||
public string? RejectReason { get; set; }
|
||||
public DateTimeOffset? CreatedAt { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
public DateTimeOffset? UpdatedAt { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
}
|
||||
|
||||
public record GetLeaveRequestByIdQuery(string Id) : IRequest<GetLeaveRequestByIdResponse?>;
|
||||
|
||||
public class GetLeaveRequestByIdHandler : IRequestHandler<GetLeaveRequestByIdQuery, GetLeaveRequestByIdResponse?>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public GetLeaveRequestByIdHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<GetLeaveRequestByIdResponse?> Handle(GetLeaveRequestByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _context.LeaveRequest
|
||||
.AsNoTracking()
|
||||
.Include(x => x.Employee)
|
||||
.Include(x => x.LeaveCategory)
|
||||
.Where(x => x.Id == request.Id)
|
||||
.Select(x => new GetLeaveRequestByIdResponse
|
||||
{
|
||||
Id = x.Id,
|
||||
AutoNumber = x.AutoNumber,
|
||||
EmployeeId = x.EmployeeId,
|
||||
EmployeeName = x.Employee != null ? $"{x.Employee.FirstName} {x.Employee.LastName}" : string.Empty,
|
||||
LeaveCategoryId = x.LeaveCategoryId,
|
||||
LeaveType = x.LeaveCategory != null ? x.LeaveCategory.Name : string.Empty,
|
||||
StartDate = x.StartDate,
|
||||
EndDate = x.EndDate,
|
||||
Days = x.Days,
|
||||
Reason = x.Reason,
|
||||
Status = x.Status,
|
||||
AttachmentPath = x.AttachmentPath,
|
||||
ApproverId = x.ApproverId,
|
||||
ActionDate = x.ActionDate,
|
||||
RejectReason = x.RejectReason,
|
||||
CreatedAt = x.CreatedAt,
|
||||
CreatedBy = x.CreatedBy,
|
||||
UpdatedAt = x.UpdatedAt,
|
||||
UpdatedBy = x.UpdatedBy
|
||||
})
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
using Indotalent.ConfigBackEnd.Extensions;
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveRequest.Cqrs;
|
||||
|
||||
public class GetLeaveRequestListResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? AutoNumber { get; set; }
|
||||
public string? EmployeeId { get; set; }
|
||||
public string? EmployeeName { get; set; }
|
||||
public string? LeaveType { get; set; }
|
||||
public DateTime StartDate { get; set; }
|
||||
public DateTime EndDate { get; set; }
|
||||
public double Days { get; set; }
|
||||
public string? Reason { get; set; }
|
||||
public string? Status { get; set; }
|
||||
}
|
||||
|
||||
public record GetLeaveRequestListQuery() : IRequest<List<GetLeaveRequestListResponse>>;
|
||||
|
||||
public class GetLeaveRequestListHandler : IRequestHandler<GetLeaveRequestListQuery, List<GetLeaveRequestListResponse>>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public GetLeaveRequestListHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<List<GetLeaveRequestListResponse>> Handle(GetLeaveRequestListQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _context.LeaveRequest
|
||||
.AsNoTracking()
|
||||
.NotDeletedOnly()
|
||||
.Include(x => x.Employee)
|
||||
.Include(x => x.LeaveCategory)
|
||||
.OrderByDescending(x => x.CreatedAt)
|
||||
.Select(x => new GetLeaveRequestListResponse
|
||||
{
|
||||
Id = x.Id,
|
||||
AutoNumber = x.AutoNumber,
|
||||
EmployeeId = x.Employee != null ? x.Employee.Code : string.Empty,
|
||||
EmployeeName = x.Employee != null ? $"{x.Employee.FirstName} {x.Employee.LastName}" : string.Empty,
|
||||
LeaveType = x.LeaveCategory != null ? x.LeaveCategory.Name : string.Empty,
|
||||
StartDate = x.StartDate,
|
||||
EndDate = x.EndDate,
|
||||
Days = x.Days,
|
||||
Reason = x.Reason,
|
||||
Status = x.Status
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveRequest.Cqrs;
|
||||
|
||||
public class UpdateLeaveRequestRequest : CreateLeaveRequestRequest
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? EmployeeName { get; set; }
|
||||
public string? LeaveType { get; set; }
|
||||
public DateTimeOffset? CreatedAt { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
public DateTimeOffset? UpdatedAt { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
public string? RejectReason { get; set; }
|
||||
public string? ApproverId { get; set; }
|
||||
public DateTime? ActionDate { get; set; }
|
||||
}
|
||||
|
||||
public class UpdateLeaveRequestResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public bool Success { get; set; }
|
||||
}
|
||||
|
||||
public record UpdateLeaveRequestCommand(UpdateLeaveRequestRequest Data) : IRequest<UpdateLeaveRequestResponse>;
|
||||
|
||||
public class UpdateLeaveRequestHandler : IRequestHandler<UpdateLeaveRequestCommand, UpdateLeaveRequestResponse>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public UpdateLeaveRequestHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<UpdateLeaveRequestResponse> Handle(UpdateLeaveRequestCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = await _context.LeaveRequest
|
||||
.FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);
|
||||
|
||||
if (entity == null)
|
||||
{
|
||||
return new UpdateLeaveRequestResponse { Id = request.Data.Id, Success = false };
|
||||
}
|
||||
|
||||
entity.EmployeeId = request.Data.EmployeeId;
|
||||
entity.LeaveCategoryId = request.Data.LeaveCategoryId;
|
||||
entity.StartDate = request.Data.StartDate;
|
||||
entity.EndDate = request.Data.EndDate;
|
||||
entity.Days = request.Data.Days;
|
||||
entity.Reason = request.Data.Reason;
|
||||
entity.Status = request.Data.Status;
|
||||
entity.AttachmentPath = request.Data.AttachmentPath;
|
||||
entity.RejectReason = request.Data.RejectReason;
|
||||
entity.ApproverId = request.Data.ApproverId;
|
||||
entity.ActionDate = request.Data.ActionDate;
|
||||
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return new UpdateLeaveRequestResponse
|
||||
{
|
||||
Id = entity.Id,
|
||||
Success = true
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveRequest.Cqrs;
|
||||
|
||||
public class UpdateLeaveRequestValidator : AbstractValidator<UpdateLeaveRequestRequest>
|
||||
{
|
||||
public UpdateLeaveRequestValidator()
|
||||
{
|
||||
RuleFor(x => x.Id)
|
||||
.NotEmpty().WithMessage("ID is required for update");
|
||||
|
||||
RuleFor(x => x.EmployeeId)
|
||||
.NotEmpty().WithMessage("Employee is required");
|
||||
|
||||
RuleFor(x => x.LeaveCategoryId)
|
||||
.NotEmpty().WithMessage("Leave Type is required");
|
||||
|
||||
RuleFor(x => x.StartDate)
|
||||
.NotEmpty().WithMessage("Start Date is required");
|
||||
|
||||
RuleFor(x => x.EndDate)
|
||||
.NotEmpty()
|
||||
.GreaterThanOrEqualTo(x => x.StartDate).WithMessage("End Date cannot be before Start Date");
|
||||
|
||||
RuleFor(x => x.Reason)
|
||||
.NotEmpty().WithMessage("Reason is required");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using Indotalent.ConfigBackEnd.Extensions;
|
||||
using Indotalent.Features.Leave.LeaveRequest.Cqrs;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveRequest;
|
||||
|
||||
public static class LeaveRequestEndpoint
|
||||
{
|
||||
public static void MapLeaveRequestEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
var group = app.MapGroup("/leave-request").WithTags("Leave Requests")
|
||||
.RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
|
||||
.RequireAuthenticatedUser());
|
||||
|
||||
group.MapGet("/", async (IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new GetLeaveRequestListQuery());
|
||||
return result.ToApiResponse("Data leave request retrieved successfully");
|
||||
})
|
||||
.WithName("GetLeaveRequestList");
|
||||
|
||||
group.MapGet("/{id}", async (string id, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new GetLeaveRequestByIdQuery(id));
|
||||
return result.ToApiResponse(result is not null
|
||||
? "Leave request detail retrieved successfully"
|
||||
: $"Leave request with ID {id} not found");
|
||||
})
|
||||
.WithName("GetLeaveRequestById");
|
||||
|
||||
group.MapPost("/", async (CreateLeaveRequestRequest request, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new CreateLeaveRequestCommand(request));
|
||||
return result.ToApiResponse("Leave request has been submitted successfully", StatusCodes.Status201Created);
|
||||
})
|
||||
.WithName("CreateLeaveRequest");
|
||||
|
||||
group.MapPost("/update", async (UpdateLeaveRequestRequest request, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new UpdateLeaveRequestCommand(request));
|
||||
if (!result.Success) return ((object?)null).ToApiResponse("Update failed.");
|
||||
return result.ToApiResponse("Leave request has been updated successfully");
|
||||
})
|
||||
.WithName("UpdateLeaveRequest");
|
||||
|
||||
group.MapPost("/delete/{id}", async (string id, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new DeleteLeaveRequestByIdCommand(new DeleteLeaveRequestByIdRequest(id)));
|
||||
if (!result) return ((object?)null).ToApiResponse("Delete failed.");
|
||||
return true.ToApiResponse("Leave request has been deleted successfully");
|
||||
})
|
||||
.WithName("DeleteLeaveRequestById");
|
||||
|
||||
|
||||
group.MapGet("/employee-reference", async (IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new GetEmployeeLeaveReferenceQuery());
|
||||
return result.ToApiResponse("Employee reference retrieved successfully");
|
||||
})
|
||||
.WithName("GetEmployeeLeaveReference");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using Indotalent.ConfigBackEnd.Interfaces;
|
||||
using Indotalent.ConfigFrontEnd.Common;
|
||||
using Indotalent.Features.Leave.LeaveRequest.Cqrs;
|
||||
using Indotalent.Infrastructure.Authentication.Identity;
|
||||
using Indotalent.Shared.Models;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using MudBlazor;
|
||||
using RestSharp;
|
||||
|
||||
namespace Indotalent.Features.Leave.LeaveRequest;
|
||||
|
||||
public class LeaveRequestService : BaseService
|
||||
{
|
||||
private readonly RestClient _client;
|
||||
|
||||
public LeaveRequestService(IHttpClientFactory clientFactory, NavigationManager nav, ISnackbar snackbar, ICurrentUserService currentUserService, TokenProvider tokenProvider)
|
||||
: base(clientFactory, nav, snackbar, currentUserService, tokenProvider)
|
||||
{
|
||||
_client = new RestClient(nav.BaseUri);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<List<GetLeaveRequestListResponse>>?> GetLeaveRequestListAsync()
|
||||
{
|
||||
var request = new RestRequest("api/leave-request", Method.Get);
|
||||
return await ExecuteWithResponseAsync<List<GetLeaveRequestListResponse>>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<GetLeaveRequestByIdResponse>?> GetLeaveRequestByIdAsync(string id)
|
||||
{
|
||||
var request = new RestRequest($"api/leave-request/{id}", Method.Get);
|
||||
return await ExecuteWithResponseAsync<GetLeaveRequestByIdResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<CreateLeaveRequestResponse>?> CreateLeaveRequestAsync(CreateLeaveRequestRequest data)
|
||||
{
|
||||
var request = new RestRequest("api/leave-request", Method.Post);
|
||||
request.AddJsonBody(data);
|
||||
return await ExecuteWithResponseAsync<CreateLeaveRequestResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<UpdateLeaveRequestResponse>?> UpdateLeaveRequestAsync(UpdateLeaveRequestRequest data)
|
||||
{
|
||||
var request = new RestRequest("api/leave-request/update", Method.Post);
|
||||
request.AddJsonBody(data);
|
||||
return await ExecuteWithResponseAsync<UpdateLeaveRequestResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteLeaveRequestByIdAsync(string id)
|
||||
{
|
||||
var request = new RestRequest($"api/leave-request/delete/{id}", Method.Post);
|
||||
var response = await ExecuteWithResponseAsync<object>(_client, request);
|
||||
return response?.IsSuccess ?? false;
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<List<EmployeeLeaveReferenceResponse>>?> GetEmployeeReferenceAsync()
|
||||
{
|
||||
var request = new RestRequest("api/leave-request/employee-reference", Method.Get);
|
||||
return await ExecuteWithResponseAsync<List<EmployeeLeaveReferenceResponse>>(_client, request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
@page "/multitenant"
|
||||
@using Indotalent.Features.Multitenant.Tenant.Components
|
||||
@using Indotalent.Features.Multitenant.TenantUser.Components
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@using Indotalent.Infrastructure.Authorization.Identity
|
||||
@using MudBlazor
|
||||
@inject NavigationManager NavigationManager
|
||||
|
||||
@implements IDisposable
|
||||
|
||||
@attribute [Authorize(Roles = $"{ApplicationRoles.Admin},{ApplicationRoles.Member}")]
|
||||
|
||||
<style>
|
||||
.clean-white-tabs .mud-tabs-toolbar {
|
||||
background-color: white !important;
|
||||
border-bottom: 2px solid #DCEBFA;
|
||||
border-radius: 0px !important;
|
||||
}
|
||||
|
||||
.clean-white-tabs .mud-tab {
|
||||
color: #94a3b8 !important;
|
||||
text-transform: none;
|
||||
font-weight: 500;
|
||||
min-width: 160px;
|
||||
border-radius: 0px !important;
|
||||
}
|
||||
|
||||
.clean-white-tabs .mud-tab-active {
|
||||
color: var(--mud-palette-primary) !important;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.clean-white-tabs .mud-tabs-slider {
|
||||
background-color: var(--mud-palette-primary) !important;
|
||||
height: 3px !important;
|
||||
bottom: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
<MudContainer MaxWidth="MaxWidth.ExtraLarge" Class="mt-2 mb-8">
|
||||
<div class="clean-white-tabs">
|
||||
<MudTabs Elevation="0"
|
||||
ActivePanelIndex="@_activeTabIndex"
|
||||
ActivePanelIndexChanged="OnTabChanged"
|
||||
ApplyEffectsToContainer="true"
|
||||
TabPanelsClass="pt-4"
|
||||
ScrollButtons="ScrollButtons.Always">
|
||||
|
||||
<MudTabPanel Text="Tenant" Icon="@Icons.Material.Outlined.Business">
|
||||
<TenantPage />
|
||||
</MudTabPanel>
|
||||
|
||||
<MudTabPanel Text="Tenant User" Icon="@Icons.Material.Outlined.Person">
|
||||
<TenantUserPage />
|
||||
</MudTabPanel>
|
||||
|
||||
</MudTabs>
|
||||
</div>
|
||||
</MudContainer>
|
||||
|
||||
@code {
|
||||
private int _activeTabIndex = 0;
|
||||
|
||||
private readonly Dictionary<int, string> _tabMapping = new()
|
||||
{
|
||||
{ 0, "tenant" },
|
||||
{ 1, "tenant-user" }
|
||||
};
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
var uri = NavigationManager.ToAbsoluteUri(NavigationManager.Uri);
|
||||
if (Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query).TryGetValue("tab", out var tabValue))
|
||||
{
|
||||
var tabStr = tabValue.ToString().ToLower();
|
||||
var match = _tabMapping.FirstOrDefault(x => x.Value == tabStr);
|
||||
_activeTabIndex = match.Value != null ? match.Key : 0;
|
||||
}
|
||||
|
||||
NavigationManager.LocationChanged += OnLocationChanged;
|
||||
}
|
||||
|
||||
private void OnLocationChanged(object? sender, Microsoft.AspNetCore.Components.Routing.LocationChangedEventArgs e)
|
||||
{
|
||||
var uri = NavigationManager.ToAbsoluteUri(e.Location);
|
||||
if (Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query).TryGetValue("tab", out var tabValue))
|
||||
{
|
||||
var tabStr = tabValue.ToString().ToLower();
|
||||
var match = _tabMapping.FirstOrDefault(x => x.Value == tabStr);
|
||||
if (match.Value != null)
|
||||
{
|
||||
_activeTabIndex = match.Key;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnTabChanged(int index)
|
||||
{
|
||||
_activeTabIndex = index;
|
||||
_tabMapping.TryGetValue(index, out var tabName);
|
||||
|
||||
NavigationManager.NavigateTo($"/multitenant?tab={tabName ?? "tenant"}", replace: false);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
NavigationManager.LocationChanged -= OnLocationChanged;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
@page "/multitenant/tenant"
|
||||
@using Indotalent.Features.Multitenant.Tenant
|
||||
@using Indotalent.Features.Multitenant.Tenant.Cqrs
|
||||
@using Indotalent.Features.Multitenant.Tenant.Components
|
||||
@using MudBlazor
|
||||
|
||||
@if (_currentView == ViewMode.Create)
|
||||
{
|
||||
<_TenantCreateForm OnCancel="BackToTable" OnSuccess="HandleSuccess" />
|
||||
}
|
||||
else if (_currentView == ViewMode.Update || _currentView == ViewMode.View)
|
||||
{
|
||||
<_TenantUpdateForm Data="_selectedData!" ReadOnly="@(_currentView == ViewMode.View)" OnCancel="BackToTable" OnSuccess="HandleSuccess" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<_TenantDataTable OnAdd="() => ShowCreate()" OnEdit="(item) => ShowUpdate(item, false)" OnView="(item) => ShowUpdate(item, true)" />
|
||||
}
|
||||
|
||||
@code {
|
||||
private enum ViewMode { Table, Create, Update, View }
|
||||
private ViewMode _currentView = ViewMode.Table;
|
||||
private UpdateTenantRequest? _selectedData;
|
||||
private void ShowCreate() => _currentView = ViewMode.Create;
|
||||
private void ShowUpdate(UpdateTenantRequest data, bool isReadOnly) { _selectedData = data; _currentView = isReadOnly ? ViewMode.View : ViewMode.Update; }
|
||||
private void BackToTable() { _currentView = ViewMode.Table; _selectedData = null; }
|
||||
private void HandleSuccess() { _currentView = ViewMode.Table; _selectedData = null; }
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
@using Indotalent.Features.Multitenant.Tenant.Cqrs
|
||||
@using Indotalent.Shared.Utils
|
||||
@using MudBlazor
|
||||
@inject TenantService TenantService
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
|
||||
<div class="d-flex align-center gap-4">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">Add New Tenant</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b;">Register a new multi-tenant organization.</MudText>
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA;">
|
||||
<MudForm @ref="_form" Model="_model">
|
||||
<MudGrid Spacing="3">
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">General Information</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Tenant Name</MudText>
|
||||
<MudTextField @bind-Value="_model.Name" For="@(() => _model.Name)" Validation="@(_validator.ValidateValue())" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Phone Number</MudText>
|
||||
<MudTextField @bind-Value="_model.PhoneNumber" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Fax Number</MudText>
|
||||
<MudTextField @bind-Value="_model.FaxNumber" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Email Address</MudText>
|
||||
<MudTextField @bind-Value="_model.EmailAddress" For="@(() => _model.EmailAddress)" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Website</MudText>
|
||||
<MudTextField @bind-Value="_model.Website" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" Class="mt-4">
|
||||
<MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">Address Information</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Street</MudText>
|
||||
<MudTextField @bind-Value="_model.Street" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">City</MudText>
|
||||
<MudTextField @bind-Value="_model.City" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">State</MudText>
|
||||
<MudTextField @bind-Value="_model.State" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Zip Code</MudText>
|
||||
<MudTextField @bind-Value="_model.ZipCode" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Country</MudText>
|
||||
<MudTextField @bind-Value="_model.Country" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" Class="mt-4">
|
||||
<MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">Status</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Is Active</MudText>
|
||||
<MudSwitch @bind-Value="_model.IsActive" Color="Color.Success" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" Class="mt-4">
|
||||
<MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">Additional Notes</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Description</MudText>
|
||||
<MudTextField @bind-Value="_model.Description" Variant="Variant.Outlined" Margin="Margin.Dense" Lines="3" FullWidth="true" />
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<div class="d-flex justify-end gap-2 mt-8">
|
||||
<MudButton OnClick="() => OnCancel.InvokeAsync()" Variant="Variant.Outlined" Disabled="_processing" Style="border-radius: 4px; border: 1px solid #e0e0e0; text-transform: none; font-weight: 700;">Cancel</MudButton>
|
||||
<MudButton Color="Color.Primary" Variant="Variant.Filled" OnClick="Submit" Disabled="_processing" Style="border-radius: 4px; text-transform: none; font-weight: 700;">
|
||||
@if (_processing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText>Create Tenant</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
</div>
|
||||
</MudForm>
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter] public EventCallback OnCancel { get; set; }
|
||||
[Parameter] public EventCallback OnSuccess { get; set; }
|
||||
private MudForm _form = default!;
|
||||
private CreateTenantValidator _validator = new();
|
||||
private CreateTenantRequest _model = new();
|
||||
private bool _processing = false;
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
await _form.Validate();
|
||||
if (!_form.IsValid) return;
|
||||
_processing = true;
|
||||
try
|
||||
{
|
||||
var response = await TenantService.CreateTenantAsync(_model);
|
||||
await Task.Delay(500);
|
||||
if (response != null && response.IsSuccess) { Snackbar.Add("Tenant created successfully", Severity.Success); await OnSuccess.InvokeAsync(); }
|
||||
}
|
||||
finally { _processing = false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
@using Indotalent.ConfigBackEnd.Extensions
|
||||
@using Indotalent.Features.Multitenant.Tenant
|
||||
@using Indotalent.Features.Multitenant.Tenant.Cqrs
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using Microsoft.JSInterop
|
||||
@using MudBlazor
|
||||
@using Features.Root.Shared
|
||||
@using ClosedXML.Excel
|
||||
@using System.IO
|
||||
@inject TenantService TenantService
|
||||
@inject IDialogService DialogService
|
||||
@inject ISnackbar Snackbar
|
||||
@inject IJSRuntime JSRuntime
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #E5E7EB; border-radius: 12px;">
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 700; color: #111827;">Tenant</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #9CA3AF;">Manage multi-tenant organizations and their configuration.</MudText>
|
||||
</div>
|
||||
<div class="d-flex align-center gap-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Home" Size="Size.Small" Color="Color.Default" />
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">Multitenant</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="font-weight: 600; color: #111827;">Tenant</MudText>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Style="border-radius: 12px; overflow: hidden; background-color: #ffffff; border: 1px solid #E5E7EB;">
|
||||
|
||||
<div style="padding: 20px 24px; border-bottom: 1px solid #E5E7EB; display: flex; justify-content: space-between; align-items: center; background-color: #ffffff; min-height: 80px;">
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<MudTextField @bind-Value="_searchString"
|
||||
Placeholder="Search..."
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Search"
|
||||
IconSize="Size.Small"
|
||||
Class="mt-0"
|
||||
Variant="Variant.Outlined"
|
||||
Margin="Margin.Dense"
|
||||
Style="background-color: white; width: 280px; border-radius: 8px;"
|
||||
OnKeyDown="@HandleSearchKeyDown" />
|
||||
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
OnClick="OnSearchClick"
|
||||
Size="Size.Small"
|
||||
Style="text-transform: none; font-weight: 500; border-radius: 6px; height: 34px; box-shadow: none;">
|
||||
Search
|
||||
</MudButton>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Success" OnClick="ExportToExcel" Size="Size.Small" Disabled="_isExporting" StartIcon="@(_isExporting ? null : Icons.Custom.FileFormats.FileExcel)" Style="background: white; font-weight: 500; border-radius: 6px; text-transform: none; height: 34px; border: 1px solid #D1D5DB;">
|
||||
@if (_isExporting)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText Typo="Typo.button" Style="text-transform: none !important;">Excel</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Primary" OnClick="LoadData" Size="Size.Small" StartIcon="@(_isRefreshing ? null : Icons.Material.Filled.Refresh)" Disabled="_isRefreshing" Style="background: white; font-weight: 500; border-radius: 6px; text-transform: none; height: 34px; border: 1px solid #D1D5DB;">
|
||||
@if (_isRefreshing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Refreshing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText Typo="Typo.button" Style="text-transform: none !important;">Refresh</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
|
||||
@if (_selectedItem != null)
|
||||
{
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Info" StartIcon="@Icons.Material.Filled.Visibility" OnClick="InvokeView" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; background-color: white; border: 1px solid #D1D5DB;">View</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Edit" OnClick="InvokeEdit" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; background-color: white; border: 1px solid #D1D5DB;">Edit</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Error" StartIcon="@Icons.Material.Filled.Delete" OnClick="OnDelete" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; border: 1px solid #FCA5A5; color: #EF4444; background: white;">Remove</MudButton>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Close" Size="Size.Small" OnClick="() => _selectedItem = null" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Add" OnClick="() => OnAdd.InvokeAsync()" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; height: 34px;">
|
||||
Add New Tenant
|
||||
</MudButton>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<MudTable Items="@GetPagedData()" Hover="true" Striped="true" Class="mud-table-styled" Elevation="0" CustomHeader="true" Dense="true" T="GetTenantListResponse" OnRowClick="@((args) => _selectedItem = args.Item)" Loading="@_isRefreshing">
|
||||
<HeaderContent>
|
||||
<MudTh Style="width: 50px; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB;"></MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">TenantId</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetTenantListResponse, object>(x => x.Name!)">Tenant Name</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">Email</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">Phone</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">City</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">Status</MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd>
|
||||
<MudCheckBox T="bool" Value="@(_selectedItem?.Id == context.Id)" Color="Color.Primary" Dense="true" Size="Size.Small" ReadOnly="true" />
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudText Typo="Typo.caption" Style="font-family: monospace; font-size: 0.65rem;">@context.Id</MudText>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudText Typo="Typo.body2" Style="font-weight: 700;">@context.Name</MudText>
|
||||
</MudTd>
|
||||
<MudTd>@context.EmailAddress</MudTd>
|
||||
<MudTd>@context.PhoneNumber</MudTd>
|
||||
<MudTd>@context.City</MudTd>
|
||||
<MudTd>
|
||||
@if (context.IsActive)
|
||||
{
|
||||
<MudChip T="string" Color="Color.Success" Size="Size.Small" Variant="Variant.Text" Style="font-weight: 600;">ACTIVE</MudChip>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudChip T="string" Color="Color.Error" Size="Size.Small" Variant="Variant.Text" Style="font-weight: 600;">INACTIVE</MudChip>
|
||||
}
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
</MudTable>
|
||||
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; padding: 12px 24px; background-color: #F9FAFB; border-top: 1px solid #E5E7EB;">
|
||||
<div style="display: flex; align-items: center; gap: 12px;">
|
||||
<MudText Typo="Typo.caption" Style="font-weight: 500; color: #9CA3AF; font-size: 0.75rem;">Rows per page:</MudText>
|
||||
<MudSelect T="int" Value="@_top" ValueChanged="OnPageSizeChanged" Dense="true" Margin="Margin.Dense" Style="width: 80px; background-color: white; font-size: 0.75rem; font-weight: 500;" Variant="Variant.Outlined" Class="mt-0 custom-select-dense">
|
||||
<MudSelectItem Value="5" />
|
||||
<MudSelectItem Value="10" />
|
||||
<MudSelectItem Value="50" />
|
||||
<MudSelectItem Value="500" />
|
||||
<MudSelectItem Value="1000" />
|
||||
</MudSelect>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF; font-size: 0.75rem; font-weight: 500; margin-left: 12px;">
|
||||
Showing @(GetFilteredData().Count() == 0 ? 0 : _skip + 1)-@Math.Min(_skip + _top, GetFilteredData().Count()) of @GetFilteredData().Count()
|
||||
</MudText>
|
||||
</div>
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.FirstPage" Size="Size.Small" OnClick="@(() => OnPageChanged(1))" Disabled="@(_currentPage == 1)" Style="@(_currentPage == 1 ? "color: #D1D5DB; background: transparent;" : "color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px;")" />
|
||||
<MudButton OnClick="@(() => OnPageChanged(_currentPage - 1))" Disabled="@(_currentPage == 1)" Variant="Variant.Text" StartIcon="@Icons.Material.Filled.ChevronLeft" Size="Size.Small" Style="@(_currentPage == 1 ? "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;" : "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;")">Prev</MudButton>
|
||||
@{
|
||||
var totalPages = _totalPage == 0 ? 1 : _totalPage;
|
||||
var maxVisible = 5;
|
||||
var startPage = Math.Max(1, _currentPage - maxVisible / 2);
|
||||
var endPage = Math.Min(totalPages, startPage + maxVisible - 1);
|
||||
if (endPage - startPage < maxVisible - 1) { startPage = Math.Max(1, endPage - maxVisible + 1); }
|
||||
}
|
||||
@for (int i = startPage; i <= endPage; i++)
|
||||
{
|
||||
var pageNum = i;
|
||||
var isActive = pageNum == _currentPage;
|
||||
<MudButton OnClick="@(() => OnPageChanged(pageNum))"
|
||||
Variant="Variant.Text" Size="Size.Small"
|
||||
Style="@(isActive ? "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 600; background: #3B82F6; color: white; border: 1px solid #3B82F6; border-radius: 6px; text-transform: none;" : "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 500; color: #374151; background: white; border: 1px solid #D1D5DB; border-radius: 6px; text-transform: none;")">@pageNum</MudButton>
|
||||
}
|
||||
<MudButton OnClick="@(() => OnPageChanged(_currentPage + 1))" Disabled="@(_currentPage == _totalPage || _totalPage == 0)" Variant="Variant.Text" EndIcon="@Icons.Material.Filled.ChevronRight" Size="Size.Small" Style="@(_currentPage == _totalPage || _totalPage == 0 ? "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;" : "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;")">Next</MudButton>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.LastPage" Size="Size.Small" OnClick="@(() => OnPageChanged(_totalPage))" Disabled="@(_currentPage == _totalPage || _totalPage == 0)" Style="@(_currentPage == _totalPage || _totalPage == 0 ? "color: #D1D5DB; background: transparent;" : "color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px;")" />
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter] public EventCallback OnAdd { get; set; }
|
||||
[Parameter] public EventCallback<UpdateTenantRequest> OnEdit { get; set; }
|
||||
[Parameter] public EventCallback<UpdateTenantRequest> OnView { get; set; }
|
||||
|
||||
private List<GetTenantListResponse> _items = new();
|
||||
private GetTenantListResponse? _selectedItem;
|
||||
private string _searchString = "";
|
||||
private bool _isRefreshing = false;
|
||||
private bool _isExporting = false;
|
||||
|
||||
private int _skip = 0;
|
||||
private int _top = 5;
|
||||
private int _totalPage => GetFilteredData().Count() == 0 ? 0 : (int)Math.Ceiling((double)GetFilteredData().Count() / (_top == 0 ? 1 : _top));
|
||||
private int _currentPage => (_top >= GetFilteredData().Count() || _top == 0) ? 1 : (_skip / _top) + 1;
|
||||
|
||||
protected override async Task OnInitializedAsync() => await LoadData();
|
||||
|
||||
private async Task LoadData()
|
||||
{
|
||||
_isRefreshing = true;
|
||||
_selectedItem = null;
|
||||
StateHasChanged();
|
||||
try
|
||||
{
|
||||
var response = await TenantService.GetTenantListAsync();
|
||||
await Task.Delay(500);
|
||||
if (response != null && response.IsSuccess) { _items = response.Value ?? new(); }
|
||||
}
|
||||
finally { _isRefreshing = false; StateHasChanged(); }
|
||||
}
|
||||
|
||||
private IEnumerable<GetTenantListResponse> GetFilteredData()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_searchString)) return _items;
|
||||
return _items.Where(x =>
|
||||
(x.Id?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.Name?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.EmailAddress?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.PhoneNumber?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false)
|
||||
);
|
||||
}
|
||||
|
||||
private IEnumerable<GetTenantListResponse> GetPagedData() => GetFilteredData().Skip(_skip).Take(_top);
|
||||
private void OnSearchClick() { _skip = 0; _selectedItem = null; StateHasChanged(); }
|
||||
private void HandleSearchKeyDown(KeyboardEventArgs e) { if (e.Key == "Enter") OnSearchClick(); }
|
||||
|
||||
private async Task ExportToExcel()
|
||||
{
|
||||
_isExporting = true;
|
||||
try
|
||||
{
|
||||
using (var workbook = new XLWorkbook())
|
||||
{
|
||||
var worksheet = workbook.Worksheets.Add("Tenants");
|
||||
worksheet.Cell(1, 1).Value = "TenantId";
|
||||
worksheet.Cell(1, 2).Value = "Tenant Name";
|
||||
worksheet.Cell(1, 3).Value = "Email";
|
||||
worksheet.Cell(1, 4).Value = "Phone";
|
||||
worksheet.Cell(1, 5).Value = "City";
|
||||
worksheet.Cell(1, 6).Value = "Status";
|
||||
worksheet.Range(1, 1, 1, 6).Style.Font.Bold = true;
|
||||
var currentRow = 1;
|
||||
foreach (var item in GetFilteredData())
|
||||
{
|
||||
currentRow++;
|
||||
worksheet.Cell(currentRow, 1).Value = item.Id;
|
||||
worksheet.Cell(currentRow, 2).Value = item.Name;
|
||||
worksheet.Cell(currentRow, 3).Value = item.EmailAddress;
|
||||
worksheet.Cell(currentRow, 4).Value = item.PhoneNumber;
|
||||
worksheet.Cell(currentRow, 5).Value = item.City;
|
||||
worksheet.Cell(currentRow, 6).Value = item.IsActive ? "Active" : "Inactive";
|
||||
}
|
||||
worksheet.Columns().AdjustToContents();
|
||||
using (var stream = new MemoryStream())
|
||||
{
|
||||
workbook.SaveAs(stream);
|
||||
var content = Convert.ToBase64String(stream.ToArray());
|
||||
await JSRuntime.InvokeVoidAsync("downloadFile", "Tenant_List.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", content);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally { _isExporting = false; StateHasChanged(); }
|
||||
}
|
||||
|
||||
private void OnPageChanged(int page) { if (page >= 1 && page <= _totalPage) { _skip = (page - 1) * _top; _selectedItem = null; StateHasChanged(); } }
|
||||
private void OnPageSizeChanged(int size) { _top = size; _skip = 0; _selectedItem = null; StateHasChanged(); }
|
||||
|
||||
private async Task InvokeEdit() { if (_selectedItem != null) { var req = await MapToUpdateRequest(_selectedItem.Id); if (req != null) await OnEdit.InvokeAsync(req); } }
|
||||
private async Task InvokeView() { if (_selectedItem != null) { var req = await MapToUpdateRequest(_selectedItem.Id); if (req != null) await OnView.InvokeAsync(req); } }
|
||||
|
||||
private async Task<UpdateTenantRequest?> MapToUpdateRequest(string id)
|
||||
{
|
||||
var response = await TenantService.GetTenantByIdAsync(id);
|
||||
if (response != null && response.IsSuccess && response.Value != null)
|
||||
{
|
||||
var d = response.Value;
|
||||
return new UpdateTenantRequest
|
||||
{
|
||||
Id = d.Id,
|
||||
Name = d.Name,
|
||||
Description = d.Description,
|
||||
Street = d.Street,
|
||||
City = d.City,
|
||||
State = d.State,
|
||||
ZipCode = d.ZipCode,
|
||||
Country = d.Country,
|
||||
PhoneNumber = d.PhoneNumber,
|
||||
FaxNumber = d.FaxNumber,
|
||||
EmailAddress = d.EmailAddress,
|
||||
Website = d.Website,
|
||||
IsActive = d.IsActive,
|
||||
CreatedAt = d.CreatedAt,
|
||||
CreatedBy = d.CreatedBy,
|
||||
UpdatedAt = d.UpdatedAt,
|
||||
UpdatedBy = d.UpdatedBy
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async Task OnDelete()
|
||||
{
|
||||
if (_selectedItem == null) return;
|
||||
var parameters = new DialogParameters<_DeleteConfirmation> { { x => x.ContentText, _selectedItem.Name } };
|
||||
var dialog = await DialogService.ShowAsync<_DeleteConfirmation>("", parameters, new DialogOptions { MaxWidth = MaxWidth.ExtraSmall, FullWidth = true });
|
||||
var result = await dialog.Result;
|
||||
if (result != null && !result.Canceled)
|
||||
{
|
||||
var success = await TenantService.DeleteTenantByIdAsync(_selectedItem.Id);
|
||||
if (success) { _selectedItem = null; await LoadData(); Snackbar.Add("Deleted successfully", Severity.Success); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
@using Indotalent.ConfigBackEnd.Extensions
|
||||
@using Indotalent.Features.Multitenant.Tenant.Cqrs
|
||||
@using Indotalent.Features.Multitenant.Tenant.Components
|
||||
@using Indotalent.Shared.Utils
|
||||
@using MudBlazor
|
||||
@inject TenantService TenantService
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
|
||||
<div class="d-flex align-center gap-4">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">@(ReadOnly ? "Tenant Details" : "Edit Tenant")</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b;">@(ReadOnly ? "Viewing tenant information." : "Modify tenant details and manage users.")</MudText>
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA;">
|
||||
@if (_isDataLoading)
|
||||
{
|
||||
<div class="d-flex justify-center pa-10"><MudProgressCircular Color="Color.Primary" Indeterminate="true" /></div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudForm @ref="_form" Model="_model">
|
||||
<MudGrid Spacing="3">
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">General Information</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Tenant Name</MudText>
|
||||
<MudTextField @bind-Value="_model.Name" For="@(() => _model.Name)" Validation="@(_validator.ValidateValue())" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Phone Number</MudText>
|
||||
<MudTextField @bind-Value="_model.PhoneNumber" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Fax Number</MudText>
|
||||
<MudTextField @bind-Value="_model.FaxNumber" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Email Address</MudText>
|
||||
<MudTextField @bind-Value="_model.EmailAddress" For="@(() => _model.EmailAddress)" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Website</MudText>
|
||||
<MudTextField @bind-Value="_model.Website" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" Class="mt-4">
|
||||
<MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">Address Information</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Street</MudText>
|
||||
<MudTextField @bind-Value="_model.Street" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">City</MudText>
|
||||
<MudTextField @bind-Value="_model.City" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">State</MudText>
|
||||
<MudTextField @bind-Value="_model.State" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Zip Code</MudText>
|
||||
<MudTextField @bind-Value="_model.ZipCode" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Country</MudText>
|
||||
<MudTextField @bind-Value="_model.Country" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" Class="mt-4">
|
||||
<MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">Status</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Is Active</MudText>
|
||||
<MudSwitch @bind-Value="_model.IsActive" ReadOnly="ReadOnly" Color="Color.Success" Disabled="ReadOnly" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" Class="mt-4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Description</MudText>
|
||||
<MudTextField @bind-Value="_model.Description" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" Lines="2" FullWidth="true" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" Class="mt-6">
|
||||
<_TenantUserDataTable Users="_model.Users" TenantId="@(_model.Id ?? string.Empty)" ReadOnly="ReadOnly" OnChanged="RefreshData" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" Class="mt-4">
|
||||
<MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">Audit History</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Created At</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@DateTimeExtensions.ToString(_model.CreatedAt)</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Created By</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@(!string.IsNullOrEmpty(_model.CreatedBy) ? _model.CreatedBy : "System")</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Last Updated At</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@DateTimeExtensions.ToString(_model.UpdatedAt)</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Last Updated By</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@(!string.IsNullOrEmpty(_model.UpdatedBy) ? _model.UpdatedBy : "System")</MudText>
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<div class="d-flex justify-end gap-2 mt-10">
|
||||
<MudButton OnClick="() => OnCancel.InvokeAsync()" Variant="Variant.Outlined" Disabled="_processing" Style="border-radius: 4px; border: 1px solid #e0e0e0; text-transform: none; font-weight: 700;">@(ReadOnly ? "Back to List" : "Cancel")</MudButton>
|
||||
@if (!ReadOnly)
|
||||
{
|
||||
<MudButton Color="Color.Primary" Variant="Variant.Filled" OnClick="Submit" Disabled="_processing" Style="border-radius: 4px; text-transform: none; font-weight: 700;">
|
||||
@if (_processing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Updating...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText>Save Changes</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
}
|
||||
</div>
|
||||
</MudForm>
|
||||
}
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter] public UpdateTenantRequest Data { get; set; } = new();
|
||||
[Parameter] public bool ReadOnly { get; set; } = false;
|
||||
[Parameter] public EventCallback OnCancel { get; set; }
|
||||
[Parameter] public EventCallback OnSuccess { get; set; }
|
||||
|
||||
private MudForm _form = default!;
|
||||
private UpdateTenantValidator _validator = new();
|
||||
private GetTenantByIdResponse _model = new();
|
||||
private bool _processing = false;
|
||||
private bool _isDataLoading = true;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await RefreshData();
|
||||
}
|
||||
|
||||
private async Task RefreshData()
|
||||
{
|
||||
_isDataLoading = true;
|
||||
try
|
||||
{
|
||||
var tenant = await TenantService.GetTenantByIdAsync(Data.Id!);
|
||||
if (tenant != null && tenant.IsSuccess) { _model = tenant.Value!; }
|
||||
}
|
||||
finally { _isDataLoading = false; }
|
||||
}
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
if (ReadOnly) return;
|
||||
|
||||
await _form.Validate();
|
||||
if (!_form.IsValid) return;
|
||||
|
||||
_processing = true;
|
||||
StateHasChanged();
|
||||
|
||||
try
|
||||
{
|
||||
var updateRequest = new UpdateTenantRequest
|
||||
{
|
||||
Id = _model.Id,
|
||||
Name = _model.Name,
|
||||
Description = _model.Description,
|
||||
Street = _model.Street,
|
||||
City = _model.City,
|
||||
State = _model.State,
|
||||
ZipCode = _model.ZipCode,
|
||||
Country = _model.Country,
|
||||
PhoneNumber = _model.PhoneNumber,
|
||||
FaxNumber = _model.FaxNumber,
|
||||
EmailAddress = _model.EmailAddress,
|
||||
Website = _model.Website,
|
||||
IsActive = _model.IsActive,
|
||||
CreatedAt = _model.CreatedAt,
|
||||
CreatedBy = _model.CreatedBy,
|
||||
UpdatedAt = _model.UpdatedAt,
|
||||
UpdatedBy = _model.UpdatedBy
|
||||
};
|
||||
|
||||
var response = await TenantService.UpdateTenantAsync(updateRequest);
|
||||
await Task.Delay(500);
|
||||
|
||||
if (response != null && response.IsSuccess)
|
||||
{
|
||||
Snackbar.Add("Updated successfully", Severity.Success);
|
||||
await OnSuccess.InvokeAsync();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Error: {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_processing = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
@using Indotalent.Features.Multitenant.Tenant.Cqrs
|
||||
@using Indotalent.Features.Multitenant.TenantUser.Cqrs
|
||||
@using MudBlazor
|
||||
@inject TenantService TenantService
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudDialog>
|
||||
<DialogContent>
|
||||
<MudForm @ref="_form" Model="_model">
|
||||
<MudGrid>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">User ID</MudText>
|
||||
<MudTextField @bind-Value="_model.UserId" Required="true" Variant="Variant.Outlined" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Summary</MudText>
|
||||
<MudTextField @bind-Value="_model.Summary" Required="true" Variant="Variant.Outlined" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Is Active</MudText>
|
||||
<MudSwitch @bind-Value="_model.IsActive" Color="Color.Success" />
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
</MudForm>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton OnClick="Cancel" Variant="Variant.Text">Cancel</MudButton>
|
||||
<MudButton Color="Color.Primary" OnClick="Submit" Variant="Variant.Filled" Disabled="_processing" Style="text-transform: none; font-weight: 700; border-radius: 4px;">
|
||||
@if (_processing)
|
||||
{
|
||||
<MudProgressCircular Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText>Add User</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
|
||||
@code {
|
||||
[CascadingParameter] IMudDialogInstance MudDialog { get; set; } = default!;
|
||||
[Parameter] public string TenantId { get; set; } = string.Empty;
|
||||
private MudForm _form = default!;
|
||||
private CreateTenantUserRequest _model = new();
|
||||
private bool _processing = false;
|
||||
|
||||
private void Cancel() => MudDialog.Cancel();
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
await _form.Validate();
|
||||
if (!_form.IsValid) return;
|
||||
_processing = true;
|
||||
_model.TenantId = TenantId;
|
||||
try
|
||||
{
|
||||
var response = await TenantService.CreateTenantUserAsync(_model);
|
||||
await Task.Delay(500);
|
||||
if (response != null && response.IsSuccess)
|
||||
{
|
||||
Snackbar.Add("User added successfully", Severity.Success);
|
||||
MudDialog.Close(DialogResult.Ok(true));
|
||||
}
|
||||
}
|
||||
finally { _processing = false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
@using Indotalent.Features.Multitenant.Tenant
|
||||
@using Indotalent.Features.Multitenant.Tenant.Cqrs
|
||||
@using MudBlazor
|
||||
@using Features.Root.Shared
|
||||
@inject TenantService TenantService
|
||||
@inject IDialogService DialogService
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Style="border-radius: 0px; border: 1px solid #E5E7EB;">
|
||||
<div style="padding: 16px; border-bottom: 1px solid #E5E7EB; display: flex; justify-content: space-between; align-items: center; background-color: #F8FAFC;">
|
||||
<MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 600;">Tenant Users</MudText>
|
||||
@if (!ReadOnly)
|
||||
{
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Add" OnClick="OnAddClick" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px;">
|
||||
Add User
|
||||
</MudButton>
|
||||
}
|
||||
</div>
|
||||
|
||||
<MudTable Items="Users" Hover="true" Striped="true" Class="mud-table-styled" Elevation="0" Dense="true" T="TenantUserItemResponse">
|
||||
<HeaderContent>
|
||||
<MudTh Style="font-weight: 700;">User ID</MudTh>
|
||||
<MudTh Style="font-weight: 700;">Summary</MudTh>
|
||||
<MudTh Style="font-weight: 700; text-align: center;">Is Active</MudTh>
|
||||
@if (!ReadOnly)
|
||||
{
|
||||
<MudTh Style="width: 100px; text-align: right; font-weight: 700;">Actions</MudTh>
|
||||
}
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd DataLabel="UserId">@context.UserId</MudTd>
|
||||
<MudTd DataLabel="Summary">@context.Summary</MudTd>
|
||||
<MudTd DataLabel="IsActive" Style="text-align: center;">
|
||||
@if (context.IsActive)
|
||||
{
|
||||
<MudChip T="string" Color="Color.Success" Size="Size.Small" Variant="Variant.Text" Style="font-weight: 600;">ACTIVE</MudChip>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudChip T="string" Color="Color.Error" Size="Size.Small" Variant="Variant.Text" Style="font-weight: 600;">INACTIVE</MudChip>
|
||||
}
|
||||
</MudTd>
|
||||
@if (!ReadOnly)
|
||||
{
|
||||
<MudTd Style="text-align: right;">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Edit" Size="Size.Small" Color="Color.Primary" OnClick="@(() => OnEditClick(context))" />
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Delete" Size="Size.Small" Color="Color.Error" OnClick="@(() => OnDeleteClick(context))" />
|
||||
</MudTd>
|
||||
}
|
||||
</RowTemplate>
|
||||
</MudTable>
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter] public string TenantId { get; set; } = string.Empty;
|
||||
[Parameter] public List<TenantUserItemResponse> Users { get; set; } = new();
|
||||
[Parameter] public bool ReadOnly { get; set; } = false;
|
||||
[Parameter] public EventCallback OnChanged { get; set; }
|
||||
|
||||
private async Task OnAddClick()
|
||||
{
|
||||
var parameters = new DialogParameters { ["TenantId"] = TenantId };
|
||||
var options = new DialogOptions { MaxWidth = MaxWidth.Small, FullWidth = true, CloseButton = true };
|
||||
var dialog = await DialogService.ShowAsync<_TenantUserCreateForm>("Add Tenant User", parameters, options);
|
||||
var result = await dialog.Result;
|
||||
if (result != null && !result.Canceled) await OnChanged.InvokeAsync();
|
||||
}
|
||||
|
||||
private async Task OnEditClick(TenantUserItemResponse item)
|
||||
{
|
||||
var parameters = new DialogParameters { ["Data"] = item };
|
||||
var options = new DialogOptions { MaxWidth = MaxWidth.Small, FullWidth = true, CloseButton = true };
|
||||
var dialog = await DialogService.ShowAsync<_TenantUserUpdateForm>("Edit Tenant User", parameters, options);
|
||||
var result = await dialog.Result;
|
||||
if (result != null && !result.Canceled) await OnChanged.InvokeAsync();
|
||||
}
|
||||
|
||||
private async Task OnDeleteClick(TenantUserItemResponse item)
|
||||
{
|
||||
var parameters = new DialogParameters { ["ContentText"] = $"Are you sure you want to remove this user?" };
|
||||
var dialog = await DialogService.ShowAsync<_DeleteConfirmation>("Delete Confirmation", parameters, new DialogOptions { MaxWidth = MaxWidth.ExtraSmall, FullWidth = true });
|
||||
var result = await dialog.Result;
|
||||
if (result != null && !result.Canceled)
|
||||
{
|
||||
var success = await TenantService.DeleteTenantUserAsync(item.Id!);
|
||||
if (success)
|
||||
{
|
||||
Snackbar.Add("User removed successfully", Severity.Success);
|
||||
await OnChanged.InvokeAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
@using Indotalent.Features.Multitenant.Tenant.Cqrs
|
||||
@using Indotalent.Features.Multitenant.TenantUser.Cqrs
|
||||
@using MudBlazor
|
||||
@inject TenantService TenantService
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudDialog>
|
||||
<DialogContent>
|
||||
<MudForm @ref="_form" Model="_model">
|
||||
<MudGrid>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">User ID</MudText>
|
||||
<MudTextField @bind-Value="_model.UserId" Required="true" Variant="Variant.Outlined" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Summary</MudText>
|
||||
<MudTextField @bind-Value="_model.Summary" Required="true" Variant="Variant.Outlined" Margin="Margin.Dense" />
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Is Active</MudText>
|
||||
<MudSwitch @bind-Value="_model.IsActive" Color="Color.Success" />
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
</MudForm>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<MudButton OnClick="Cancel" Variant="Variant.Text">Cancel</MudButton>
|
||||
<MudButton Color="Color.Primary" OnClick="Submit" Variant="Variant.Filled" Disabled="_processing" Style="text-transform: none; font-weight: 700; border-radius: 4px;">
|
||||
@if (_processing)
|
||||
{
|
||||
<MudProgressCircular Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText>Save Changes</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
</DialogActions>
|
||||
</MudDialog>
|
||||
|
||||
@code {
|
||||
[CascadingParameter] IMudDialogInstance MudDialog { get; set; } = default!;
|
||||
[Parameter] public TenantUserItemResponse Data { get; set; } = new();
|
||||
private MudForm _form = default!;
|
||||
private UpdateTenantUserRequest _model = new();
|
||||
private bool _processing = false;
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
_model.Id = Data.Id;
|
||||
_model.UserId = Data.UserId;
|
||||
_model.Summary = Data.Summary;
|
||||
_model.IsActive = Data.IsActive;
|
||||
}
|
||||
|
||||
private void Cancel() => MudDialog.Cancel();
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
await _form.Validate();
|
||||
if (!_form.IsValid) return;
|
||||
_processing = true;
|
||||
try
|
||||
{
|
||||
var response = await TenantService.UpdateTenantUserAsync(_model);
|
||||
await Task.Delay(500);
|
||||
if (response != null && response.Value!.Success)
|
||||
{
|
||||
Snackbar.Add("User updated successfully", Severity.Success);
|
||||
MudDialog.Close(DialogResult.Ok(true));
|
||||
}
|
||||
}
|
||||
finally { _processing = false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
using Indotalent.ConfigBackEnd.Exceptions;
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.Tenant.Cqrs;
|
||||
|
||||
public class CreateTenantRequest
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? Street { get; set; }
|
||||
public string? City { get; set; }
|
||||
public string? State { get; set; }
|
||||
public string? ZipCode { get; set; }
|
||||
public string? Country { get; set; }
|
||||
public string? PhoneNumber { get; set; }
|
||||
public string? FaxNumber { get; set; }
|
||||
public string? EmailAddress { get; set; }
|
||||
public string? Website { get; set; }
|
||||
public bool IsActive { get; set; } = true;
|
||||
}
|
||||
|
||||
public class CreateTenantResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? Name { get; set; }
|
||||
}
|
||||
|
||||
public record CreateTenantCommand(CreateTenantRequest Data) : IRequest<CreateTenantResponse>;
|
||||
|
||||
public class CreateTenantHandler : IRequestHandler<CreateTenantCommand, CreateTenantResponse>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public CreateTenantHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<CreateTenantResponse> Handle(CreateTenantCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var isExists = await _context.Tenant
|
||||
.AnyAsync(x => x.Name == request.Data.Name, cancellationToken);
|
||||
|
||||
if (isExists)
|
||||
{
|
||||
throw new AlreadyExistsException("Tenant", request.Data.Name ?? string.Empty);
|
||||
}
|
||||
|
||||
var entity = new Data.Entities.Tenant
|
||||
{
|
||||
Name = request.Data.Name,
|
||||
Description = request.Data.Description,
|
||||
Street = request.Data.Street,
|
||||
City = request.Data.City,
|
||||
State = request.Data.State,
|
||||
ZipCode = request.Data.ZipCode,
|
||||
Country = request.Data.Country,
|
||||
PhoneNumber = request.Data.PhoneNumber,
|
||||
FaxNumber = request.Data.FaxNumber,
|
||||
EmailAddress = request.Data.EmailAddress,
|
||||
Website = request.Data.Website,
|
||||
IsActive = request.Data.IsActive
|
||||
};
|
||||
|
||||
_context.Tenant.Add(entity);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return new CreateTenantResponse
|
||||
{
|
||||
Id = entity.Id,
|
||||
Name = entity.Name
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using FluentValidation;
|
||||
using Indotalent.Shared.Consts;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.Tenant.Cqrs;
|
||||
|
||||
public class CreateTenantValidator : AbstractValidator<CreateTenantRequest>
|
||||
{
|
||||
public CreateTenantValidator()
|
||||
{
|
||||
RuleFor(x => x.Name)
|
||||
.NotEmpty().WithMessage("Tenant Name is required")
|
||||
.MaximumLength(GlobalConsts.StringLengthShort);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.Tenant.Cqrs;
|
||||
|
||||
public record DeleteTenantByIdRequest(string Id);
|
||||
|
||||
public record DeleteTenantByIdCommand(DeleteTenantByIdRequest Data) : IRequest<bool>;
|
||||
|
||||
public class DeleteTenantByIdHandler : IRequestHandler<DeleteTenantByIdCommand, bool>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public DeleteTenantByIdHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<bool> Handle(DeleteTenantByIdCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = await _context.Tenant
|
||||
.FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);
|
||||
|
||||
if (entity == null) return false;
|
||||
|
||||
_context.Tenant.Remove(entity);
|
||||
return await _context.SaveChangesAsync(cancellationToken) > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.Tenant.Cqrs;
|
||||
|
||||
public class TenantUserItemResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? UserId { get; set; }
|
||||
public string? Summary { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
}
|
||||
|
||||
public class GetTenantByIdResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? Street { get; set; }
|
||||
public string? City { get; set; }
|
||||
public string? State { get; set; }
|
||||
public string? ZipCode { get; set; }
|
||||
public string? Country { get; set; }
|
||||
public string? PhoneNumber { get; set; }
|
||||
public string? FaxNumber { get; set; }
|
||||
public string? EmailAddress { get; set; }
|
||||
public string? Website { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
public DateTimeOffset? CreatedAt { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
public DateTimeOffset? UpdatedAt { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
public List<TenantUserItemResponse> Users { get; set; } = new();
|
||||
}
|
||||
|
||||
public record GetTenantByIdQuery(string Id) : IRequest<GetTenantByIdResponse?>;
|
||||
|
||||
public class GetTenantByIdHandler : IRequestHandler<GetTenantByIdQuery, GetTenantByIdResponse?>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public GetTenantByIdHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<GetTenantByIdResponse?> Handle(GetTenantByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _context.Tenant
|
||||
.AsNoTracking()
|
||||
.Include(x => x.TenantUserList)
|
||||
.Where(x => x.Id == request.Id)
|
||||
.Select(x => new GetTenantByIdResponse
|
||||
{
|
||||
Id = x.Id,
|
||||
Name = x.Name,
|
||||
Description = x.Description,
|
||||
Street = x.Street,
|
||||
City = x.City,
|
||||
State = x.State,
|
||||
ZipCode = x.ZipCode,
|
||||
Country = x.Country,
|
||||
PhoneNumber = x.PhoneNumber,
|
||||
FaxNumber = x.FaxNumber,
|
||||
EmailAddress = x.EmailAddress,
|
||||
Website = x.Website,
|
||||
IsActive = x.IsActive,
|
||||
CreatedAt = x.CreatedAt,
|
||||
CreatedBy = x.CreatedBy,
|
||||
UpdatedAt = x.UpdatedAt,
|
||||
UpdatedBy = x.UpdatedBy,
|
||||
Users = x.TenantUserList
|
||||
.OrderBy(u => u.Summary)
|
||||
.Select(u => new TenantUserItemResponse
|
||||
{
|
||||
Id = u.Id,
|
||||
UserId = u.UserId,
|
||||
Summary = u.Summary,
|
||||
IsActive = u.IsActive
|
||||
}).ToList()
|
||||
})
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.Tenant.Cqrs;
|
||||
|
||||
public class GetTenantListResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? Name { get; set; }
|
||||
public string? PhoneNumber { get; set; }
|
||||
public string? EmailAddress { get; set; }
|
||||
public string? City { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
}
|
||||
|
||||
public record GetTenantListQuery() : IRequest<List<GetTenantListResponse>>;
|
||||
|
||||
public class GetTenantListHandler : IRequestHandler<GetTenantListQuery, List<GetTenantListResponse>>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public GetTenantListHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<List<GetTenantListResponse>> Handle(GetTenantListQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _context.Tenant
|
||||
.AsNoTracking()
|
||||
.OrderBy(x => x.Name)
|
||||
.Select(x => new GetTenantListResponse
|
||||
{
|
||||
Id = x.Id,
|
||||
Name = x.Name,
|
||||
PhoneNumber = x.PhoneNumber,
|
||||
EmailAddress = x.EmailAddress,
|
||||
City = x.City,
|
||||
IsActive = x.IsActive
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.Tenant.Cqrs;
|
||||
|
||||
public class LookupTenantResponse
|
||||
{
|
||||
public List<LookupItem> Tenants { get; set; } = new();
|
||||
}
|
||||
|
||||
public class LookupItem
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? Name { get; set; }
|
||||
}
|
||||
|
||||
public record LookupTenantQuery() : IRequest<LookupTenantResponse>;
|
||||
|
||||
public class LookupTenantHandler : IRequestHandler<LookupTenantQuery, LookupTenantResponse>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public LookupTenantHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<LookupTenantResponse> Handle(LookupTenantQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = new LookupTenantResponse();
|
||||
|
||||
result.Tenants = await _context.Tenant
|
||||
.AsNoTracking()
|
||||
.OrderBy(x => x.Name)
|
||||
.Select(x => new LookupItem { Id = x.Id, Name = x.Name })
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using Indotalent.ConfigBackEnd.Exceptions;
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.Tenant.Cqrs;
|
||||
|
||||
public class UpdateTenantRequest
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? Name { get; set; }
|
||||
public string? Description { get; set; }
|
||||
public string? Street { get; set; }
|
||||
public string? City { get; set; }
|
||||
public string? State { get; set; }
|
||||
public string? ZipCode { get; set; }
|
||||
public string? Country { get; set; }
|
||||
public string? PhoneNumber { get; set; }
|
||||
public string? FaxNumber { get; set; }
|
||||
public string? EmailAddress { get; set; }
|
||||
public string? Website { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
public DateTimeOffset? CreatedAt { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
public DateTimeOffset? UpdatedAt { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
}
|
||||
|
||||
public class UpdateTenantResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public bool Success { get; set; }
|
||||
}
|
||||
|
||||
public record UpdateTenantCommand(UpdateTenantRequest Data) : IRequest<UpdateTenantResponse>;
|
||||
|
||||
public class UpdateTenantHandler : IRequestHandler<UpdateTenantCommand, UpdateTenantResponse>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public UpdateTenantHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<UpdateTenantResponse> Handle(UpdateTenantCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var isExists = await _context.Tenant
|
||||
.AnyAsync(x => x.Name == request.Data.Name && x.Id != request.Data.Id, cancellationToken);
|
||||
|
||||
if (isExists)
|
||||
{
|
||||
throw new AlreadyExistsException("Tenant", request.Data.Name ?? string.Empty);
|
||||
}
|
||||
|
||||
var entity = await _context.Tenant
|
||||
.FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);
|
||||
|
||||
if (entity == null)
|
||||
{
|
||||
return new UpdateTenantResponse { Id = request.Data.Id, Success = false };
|
||||
}
|
||||
|
||||
entity.Name = request.Data.Name;
|
||||
entity.Description = request.Data.Description;
|
||||
entity.Street = request.Data.Street;
|
||||
entity.City = request.Data.City;
|
||||
entity.State = request.Data.State;
|
||||
entity.ZipCode = request.Data.ZipCode;
|
||||
entity.Country = request.Data.Country;
|
||||
entity.PhoneNumber = request.Data.PhoneNumber;
|
||||
entity.FaxNumber = request.Data.FaxNumber;
|
||||
entity.EmailAddress = request.Data.EmailAddress;
|
||||
entity.Website = request.Data.Website;
|
||||
entity.IsActive = request.Data.IsActive;
|
||||
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return new UpdateTenantResponse
|
||||
{
|
||||
Id = entity.Id,
|
||||
Success = true
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using FluentValidation;
|
||||
using Indotalent.Shared.Consts;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.Tenant.Cqrs;
|
||||
|
||||
public class UpdateTenantValidator : AbstractValidator<UpdateTenantRequest>
|
||||
{
|
||||
public UpdateTenantValidator()
|
||||
{
|
||||
RuleFor(x => x.Id)
|
||||
.NotEmpty().WithMessage("ID is required for update");
|
||||
|
||||
RuleFor(x => x.Name)
|
||||
.NotEmpty().WithMessage("Tenant Name is required")
|
||||
.MaximumLength(GlobalConsts.StringLengthShort);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
using Indotalent.ConfigBackEnd.Extensions;
|
||||
using Indotalent.Features.Multitenant.Tenant.Cqrs;
|
||||
using Indotalent.Features.Multitenant.TenantUser.Cqrs;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.Tenant;
|
||||
|
||||
public static class TenantEndpoint
|
||||
{
|
||||
public static void MapTenantEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
var group = app.MapGroup("/tenant").WithTags("Tenants")
|
||||
.RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
|
||||
.RequireAuthenticatedUser());
|
||||
|
||||
group.MapGet("/", async (IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new GetTenantListQuery());
|
||||
return result.ToApiResponse("Tenant list retrieved successfully");
|
||||
})
|
||||
.WithName("GetTenantList")
|
||||
.WithTags("Tenants");
|
||||
|
||||
group.MapGet("/{id}", async (string id, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new GetTenantByIdQuery(id));
|
||||
return result.ToApiResponse(result is not null
|
||||
? "Tenant detail retrieved successfully"
|
||||
: $"Tenant with ID {id} not found");
|
||||
})
|
||||
.WithName("GetTenantById")
|
||||
.WithTags("Tenants");
|
||||
|
||||
group.MapGet("/lookup", async (IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new LookupTenantQuery());
|
||||
return result.ToApiResponse("Lookup data retrieved successfully");
|
||||
})
|
||||
.WithName("GetTenantLookup")
|
||||
.WithTags("Tenants");
|
||||
|
||||
group.MapPost("/", async (CreateTenantRequest request, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new CreateTenantCommand(request));
|
||||
return result.ToApiResponse("Tenant has been created successfully", StatusCodes.Status201Created);
|
||||
})
|
||||
.WithName("CreateTenant")
|
||||
.WithTags("Tenants");
|
||||
|
||||
group.MapPost("/update", async (UpdateTenantRequest request, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new UpdateTenantCommand(request));
|
||||
if (!result.Success)
|
||||
{
|
||||
return ((object?)null).ToApiResponse("Update failed. The tenant data could not be found.");
|
||||
}
|
||||
return result.ToApiResponse("Tenant has been updated successfully");
|
||||
})
|
||||
.WithName("UpdateTenant")
|
||||
.WithTags("Tenants");
|
||||
|
||||
group.MapPost("/delete/{id}", async (string id, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new DeleteTenantByIdCommand(new DeleteTenantByIdRequest(id)));
|
||||
if (!result)
|
||||
{
|
||||
return ((object?)null).ToApiResponse("Delete failed. The tenant data could not be found.");
|
||||
}
|
||||
return true.ToApiResponse("Tenant has been deleted successfully");
|
||||
})
|
||||
.WithName("DeleteTenantById")
|
||||
.WithTags("Tenants");
|
||||
|
||||
group.MapPost("/tenant-user", async (CreateTenantUserRequest request, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new CreateTenantUserCommand(request));
|
||||
return result.ToApiResponse("Tenant user has been added successfully");
|
||||
})
|
||||
.WithName("CreateTenantUserChild")
|
||||
.WithTags("Tenants");
|
||||
|
||||
group.MapPost("/tenant-user/update", async (UpdateTenantUserRequest request, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new UpdateTenantUserCommand(request));
|
||||
if (!result.Success)
|
||||
{
|
||||
return ((object?)null).ToApiResponse("Update failed. Tenant user not found.");
|
||||
}
|
||||
return result.ToApiResponse("Tenant user has been updated successfully");
|
||||
})
|
||||
.WithName("UpdateTenantUserChild")
|
||||
.WithTags("Tenants");
|
||||
|
||||
group.MapPost("/tenant-user/delete/{id}", async (string id, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new DeleteTenantUserByIdCommand(new DeleteTenantUserByIdRequest(id)));
|
||||
if (!result)
|
||||
{
|
||||
return ((object?)null).ToApiResponse("Delete failed. Tenant user not found.");
|
||||
}
|
||||
return true.ToApiResponse("Tenant user has been removed successfully");
|
||||
})
|
||||
.WithName("DeleteTenantUserChild")
|
||||
.WithTags("Tenants");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using Indotalent.ConfigBackEnd.Interfaces;
|
||||
using Indotalent.ConfigFrontEnd.Common;
|
||||
using Indotalent.Features.Multitenant.Tenant.Cqrs;
|
||||
using Indotalent.Features.Multitenant.TenantUser.Cqrs;
|
||||
using Indotalent.Infrastructure.Authentication.Identity;
|
||||
using Indotalent.Shared.Models;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using MudBlazor;
|
||||
using RestSharp;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.Tenant;
|
||||
|
||||
public class TenantService : BaseService
|
||||
{
|
||||
private readonly RestClient _client;
|
||||
|
||||
public TenantService(
|
||||
IHttpClientFactory clientFactory,
|
||||
NavigationManager nav,
|
||||
ISnackbar snackbar,
|
||||
ICurrentUserService currentUserService,
|
||||
TokenProvider tokenProvider)
|
||||
: base(clientFactory, nav, snackbar, currentUserService, tokenProvider)
|
||||
{
|
||||
_client = new RestClient(nav.BaseUri);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<List<GetTenantListResponse>>?> GetTenantListAsync()
|
||||
{
|
||||
var request = new RestRequest("api/tenant", Method.Get);
|
||||
return await ExecuteWithResponseAsync<List<GetTenantListResponse>>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<GetTenantByIdResponse>?> GetTenantByIdAsync(string id)
|
||||
{
|
||||
var request = new RestRequest($"api/tenant/{id}", Method.Get);
|
||||
return await ExecuteWithResponseAsync<GetTenantByIdResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<LookupTenantResponse>?> GetTenantLookupAsync()
|
||||
{
|
||||
var request = new RestRequest("api/tenant/lookup", Method.Get);
|
||||
return await ExecuteWithResponseAsync<LookupTenantResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<CreateTenantResponse>?> CreateTenantAsync(CreateTenantRequest data)
|
||||
{
|
||||
var request = new RestRequest("api/tenant", Method.Post);
|
||||
request.AddJsonBody(data);
|
||||
return await ExecuteWithResponseAsync<CreateTenantResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteTenantByIdAsync(string id)
|
||||
{
|
||||
var request = new RestRequest($"api/tenant/delete/{id}", Method.Post);
|
||||
var response = await ExecuteWithResponseAsync<object>(_client, request);
|
||||
return response?.IsSuccess ?? false;
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<UpdateTenantResponse>?> UpdateTenantAsync(UpdateTenantRequest data)
|
||||
{
|
||||
var request = new RestRequest("api/tenant/update", Method.Post);
|
||||
request.AddJsonBody(data);
|
||||
return await ExecuteWithResponseAsync<UpdateTenantResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<CreateTenantUserResponse>?> CreateTenantUserAsync(CreateTenantUserRequest data)
|
||||
{
|
||||
var request = new RestRequest("api/tenant/tenant-user", Method.Post);
|
||||
request.AddJsonBody(data);
|
||||
return await ExecuteWithResponseAsync<CreateTenantUserResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<UpdateTenantUserResponse>?> UpdateTenantUserAsync(UpdateTenantUserRequest data)
|
||||
{
|
||||
var request = new RestRequest("api/tenant/tenant-user/update", Method.Post);
|
||||
request.AddJsonBody(data);
|
||||
return await ExecuteWithResponseAsync<UpdateTenantUserResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteTenantUserAsync(string id)
|
||||
{
|
||||
var request = new RestRequest($"api/tenant/tenant-user/delete/{id}", Method.Post);
|
||||
var response = await ExecuteWithResponseAsync<object>(_client, request);
|
||||
return response?.IsSuccess ?? false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
@page "/multitenant/tenant-user"
|
||||
@using Indotalent.Features.Multitenant.TenantUser
|
||||
@using Indotalent.Features.Multitenant.TenantUser.Cqrs
|
||||
@using Indotalent.Features.Multitenant.TenantUser.Components
|
||||
@using MudBlazor
|
||||
|
||||
@if (_currentView == ViewMode.Create)
|
||||
{
|
||||
<_TenantUserCreateForm OnCancel="BackToTable" OnSuccess="HandleSuccess" />
|
||||
}
|
||||
else if (_currentView == ViewMode.Update || _currentView == ViewMode.View)
|
||||
{
|
||||
<_TenantUserUpdateForm Data="_selectedData!" ReadOnly="@(_currentView == ViewMode.View)" OnCancel="BackToTable" OnSuccess="HandleSuccess" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<_TenantUserDataTable OnAdd="() => ShowCreate()" OnEdit="(item) => ShowUpdate(item, false)" OnView="(item) => ShowUpdate(item, true)" />
|
||||
}
|
||||
|
||||
@code {
|
||||
private enum ViewMode { Table, Create, Update, View }
|
||||
private ViewMode _currentView = ViewMode.Table;
|
||||
private UpdateTenantUserRequest? _selectedData;
|
||||
private void ShowCreate() => _currentView = ViewMode.Create;
|
||||
private void ShowUpdate(UpdateTenantUserRequest data, bool isReadOnly) { _selectedData = data; _currentView = isReadOnly ? ViewMode.View : ViewMode.Update; }
|
||||
private void BackToTable() { _currentView = ViewMode.Table; _selectedData = null; }
|
||||
private void HandleSuccess() { _currentView = ViewMode.Table; _selectedData = null; }
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
@using Indotalent.Features.Multitenant.TenantUser
|
||||
@using Indotalent.Features.Multitenant.TenantUser.Cqrs
|
||||
@using Indotalent.Shared.Utils
|
||||
@using MudBlazor
|
||||
@inject TenantUserService TenantUserService
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
|
||||
<div class="d-flex align-center gap-4">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">Add New Tenant User</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b;">Assign a system user to a tenant organization.</MudText>
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA;">
|
||||
<MudForm @ref="_form" Model="_model">
|
||||
<MudGrid Spacing="3">
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">User Assignment</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Tenant</MudText>
|
||||
<MudSelect @bind-Value="_model.TenantId" For="@(() => _model.TenantId)" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Dense="true" AnchorOrigin="Origin.BottomCenter" TransformOrigin="Origin.TopCenter">
|
||||
@foreach (var item in _lookupData.Tenants)
|
||||
{
|
||||
<MudSelectItem Value="@item.Id">@item.Name</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">System User</MudText>
|
||||
<MudSelect @bind-Value="_model.UserId" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Dense="true" AnchorOrigin="Origin.BottomCenter" TransformOrigin="Origin.TopCenter">
|
||||
@foreach (var item in _lookupData.SystemUsers)
|
||||
{
|
||||
<MudSelectItem Value="@item.Id">@item.Name</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Summary</MudText>
|
||||
<MudTextField @bind-Value="_model.Summary" For="@(() => _model.Summary)" Validation="@(_validator.ValidateValue())" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Is Active</MudText>
|
||||
<MudSwitch @bind-Value="_model.IsActive" Color="Color.Success" />
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<div class="d-flex justify-end gap-2 mt-8">
|
||||
<MudButton OnClick="() => OnCancel.InvokeAsync()" Variant="Variant.Outlined" Disabled="_processing" Style="border-radius: 4px; border: 1px solid #e0e0e0; text-transform: none; font-weight: 700;">Cancel</MudButton>
|
||||
<MudButton Color="Color.Primary" Variant="Variant.Filled" OnClick="Submit" Disabled="_processing" Style="border-radius: 4px; text-transform: none; font-weight: 700;">
|
||||
@if (_processing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText>Create User</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
</div>
|
||||
</MudForm>
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter] public EventCallback OnCancel { get; set; }
|
||||
[Parameter] public EventCallback OnSuccess { get; set; }
|
||||
private MudForm _form = default!;
|
||||
private CreateTenantUserValidator _validator = new();
|
||||
private CreateTenantUserRequest _model = new();
|
||||
private LookupTenantUserResponse _lookupData = new();
|
||||
private bool _processing = false;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
var response = await TenantUserService.GetTenantUserLookupAsync();
|
||||
if (response != null && response.IsSuccess) { _lookupData = response.Value!; }
|
||||
}
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
await _form.Validate();
|
||||
if (!_form.IsValid) return;
|
||||
_processing = true;
|
||||
try
|
||||
{
|
||||
var response = await TenantUserService.CreateTenantUserAsync(_model);
|
||||
await Task.Delay(500);
|
||||
if (response != null && response.IsSuccess) { Snackbar.Add("User created successfully", Severity.Success); await OnSuccess.InvokeAsync(); }
|
||||
}
|
||||
finally { _processing = false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
@using Indotalent.ConfigBackEnd.Extensions
|
||||
@using Indotalent.Features.Multitenant.TenantUser
|
||||
@using Indotalent.Features.Multitenant.TenantUser.Cqrs
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using Microsoft.JSInterop
|
||||
@using MudBlazor
|
||||
@using Features.Root.Shared
|
||||
@using ClosedXML.Excel
|
||||
@using System.IO
|
||||
@inject TenantUserService TenantUserService
|
||||
@inject IDialogService DialogService
|
||||
@inject ISnackbar Snackbar
|
||||
@inject IJSRuntime JSRuntime
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #E5E7EB; border-radius: 12px;">
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 700; color: #111827;">Tenant User</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #9CA3AF;">Manage user assignments across tenant organizations.</MudText>
|
||||
</div>
|
||||
<div class="d-flex align-center gap-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Home" Size="Size.Small" Color="Color.Default" />
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">Multitenant</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="font-weight: 600; color: #111827;">Tenant User</MudText>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Style="border-radius: 12px; overflow: hidden; background-color: #ffffff; border: 1px solid #E5E7EB;">
|
||||
<div style="padding: 20px 24px; border-bottom: 1px solid #E5E7EB; display: flex; justify-content: space-between; align-items: center; background-color: #ffffff; min-height: 80px;">
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<MudTextField @bind-Value="_searchString"
|
||||
Placeholder="Search..."
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Search"
|
||||
IconSize="Size.Small"
|
||||
Class="mt-0"
|
||||
Variant="Variant.Outlined"
|
||||
Margin="Margin.Dense"
|
||||
Style="background-color: white; width: 280px; border-radius: 8px;"
|
||||
OnKeyDown="@HandleSearchKeyDown" />
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
OnClick="OnSearchClick"
|
||||
Size="Size.Small"
|
||||
Style="text-transform: none; font-weight: 500; border-radius: 6px; height: 34px; box-shadow: none;">
|
||||
Search
|
||||
</MudButton>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Success" OnClick="ExportToExcel" Size="Size.Small" Disabled="_isExporting" StartIcon="@(_isExporting ? null : Icons.Custom.FileFormats.FileExcel)" Style="background: white; font-weight: 500; border-radius: 6px; text-transform: none; height: 34px; border: 1px solid #D1D5DB;">
|
||||
@if (_isExporting)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText Typo="Typo.button" Style="text-transform: none !important;">Excel</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Primary" OnClick="LoadData" Size="Size.Small" StartIcon="@(_isRefreshing ? null : Icons.Material.Filled.Refresh)" Disabled="_isRefreshing" Style="background: white; font-weight: 500; border-radius: 6px; text-transform: none; height: 34px; border: 1px solid #D1D5DB;">
|
||||
@if (_isRefreshing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Refreshing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText Typo="Typo.button" Style="text-transform: none !important;">Refresh</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
|
||||
@if (_selectedItem != null)
|
||||
{
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Info" StartIcon="@Icons.Material.Filled.Visibility" OnClick="InvokeView" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; background-color: white; border: 1px solid #D1D5DB;">View</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Edit" OnClick="InvokeEdit" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; background-color: white; border: 1px solid #D1D5DB;">Edit</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Error" StartIcon="@Icons.Material.Filled.Delete" OnClick="OnDelete" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; border: 1px solid #FCA5A5; color: #EF4444; background: white;">Remove</MudButton>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Close" Size="Size.Small" OnClick="() => _selectedItem = null" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Add" OnClick="() => OnAdd.InvokeAsync()" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; height: 34px;">
|
||||
Add New User
|
||||
</MudButton>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<MudTable Items="@GetPagedData()" Hover="true" Striped="true" Class="mud-table-styled" Elevation="0" CustomHeader="true" Dense="true" T="GetTenantUserListResponse" OnRowClick="@((args) => _selectedItem = args.Item)" Loading="@_isRefreshing">
|
||||
<HeaderContent>
|
||||
<MudTh Style="width: 50px; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB;"></MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetTenantUserListResponse, object>(x => x.FullName!)">Full Name</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">Email</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">Tenant</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">TenantId</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">Status</MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd>
|
||||
<MudCheckBox T="bool" Value="@(_selectedItem?.Id == context.Id)" Color="Color.Primary" Dense="true" Size="Size.Small" ReadOnly="true" />
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudText Typo="Typo.body2" Style="font-weight: 700;">@context.FullName</MudText>
|
||||
</MudTd>
|
||||
<MudTd>@context.Email</MudTd>
|
||||
<MudTd>@context.TenantName</MudTd>
|
||||
<MudTd>
|
||||
<MudText Typo="Typo.caption" Style="font-family: monospace; font-size: 0.65rem;">@context.TenantId</MudText>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
@if (context.IsActive)
|
||||
{
|
||||
<MudChip T="string" Color="Color.Success" Size="Size.Small" Variant="Variant.Text" Style="font-weight: 600;">ACTIVE</MudChip>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudChip T="string" Color="Color.Error" Size="Size.Small" Variant="Variant.Text" Style="font-weight: 600;">INACTIVE</MudChip>
|
||||
}
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
</MudTable>
|
||||
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; padding: 12px 24px; background-color: #F9FAFB; border-top: 1px solid #E5E7EB;">
|
||||
<div style="display: flex; align-items: center; gap: 12px;">
|
||||
<MudText Typo="Typo.caption" Style="font-weight: 500; color: #9CA3AF; font-size: 0.75rem;">Rows per page:</MudText>
|
||||
<MudSelect T="int" Value="@_top" ValueChanged="OnPageSizeChanged" Dense="true" Margin="Margin.Dense" Style="width: 80px; background-color: white; font-size: 0.75rem; font-weight: 500;" Variant="Variant.Outlined" Class="mt-0 custom-select-dense">
|
||||
<MudSelectItem Value="5" />
|
||||
<MudSelectItem Value="10" />
|
||||
<MudSelectItem Value="50" />
|
||||
<MudSelectItem Value="500" />
|
||||
<MudSelectItem Value="1000" />
|
||||
</MudSelect>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF; font-size: 0.75rem; font-weight: 500; margin-left: 12px;">
|
||||
Showing @(GetFilteredData().Count() == 0 ? 0 : _skip + 1)-@Math.Min(_skip + _top, GetFilteredData().Count()) of @GetFilteredData().Count()
|
||||
</MudText>
|
||||
</div>
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.FirstPage" Size="Size.Small" OnClick="@(() => OnPageChanged(1))" Disabled="@(_currentPage == 1)" Style="@(_currentPage == 1 ? "color: #D1D5DB; background: transparent;" : "color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px;")" />
|
||||
<MudButton OnClick="@(() => OnPageChanged(_currentPage - 1))" Disabled="@(_currentPage == 1)" Variant="Variant.Text" StartIcon="@Icons.Material.Filled.ChevronLeft" Size="Size.Small" Style="@(_currentPage == 1 ? "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;" : "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;")">Prev</MudButton>
|
||||
@{
|
||||
var totalPages = _totalPage == 0 ? 1 : _totalPage;
|
||||
var maxVisible = 5;
|
||||
var startPage = Math.Max(1, _currentPage - maxVisible / 2);
|
||||
var endPage = Math.Min(totalPages, startPage + maxVisible - 1);
|
||||
if (endPage - startPage < maxVisible - 1) { startPage = Math.Max(1, endPage - maxVisible + 1); }
|
||||
}
|
||||
@for (int i = startPage; i <= endPage; i++)
|
||||
{
|
||||
var pageNum = i;
|
||||
var isActive = pageNum == _currentPage;
|
||||
<MudButton OnClick="@(() => OnPageChanged(pageNum))"
|
||||
Variant="Variant.Text" Size="Size.Small"
|
||||
Style="@(isActive ? "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 600; background: #3B82F6; color: white; border: 1px solid #3B82F6; border-radius: 6px; text-transform: none;" : "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 500; color: #374151; background: white; border: 1px solid #D1D5DB; border-radius: 6px; text-transform: none;")">@pageNum</MudButton>
|
||||
}
|
||||
<MudButton OnClick="@(() => OnPageChanged(_currentPage + 1))" Disabled="@(_currentPage == _totalPage || _totalPage == 0)" Variant="Variant.Text" EndIcon="@Icons.Material.Filled.ChevronRight" Size="Size.Small" Style="@(_currentPage == _totalPage || _totalPage == 0 ? "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;" : "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;")">Next</MudButton>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.LastPage" Size="Size.Small" OnClick="@(() => OnPageChanged(_totalPage))" Disabled="@(_currentPage == _totalPage || _totalPage == 0)" Style="@(_currentPage == _totalPage || _totalPage == 0 ? "color: #D1D5DB; background: transparent;" : "color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px;")" />
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter] public EventCallback OnAdd { get; set; }
|
||||
[Parameter] public EventCallback<UpdateTenantUserRequest> OnEdit { get; set; }
|
||||
[Parameter] public EventCallback<UpdateTenantUserRequest> OnView { get; set; }
|
||||
|
||||
private List<GetTenantUserListResponse> _items = new();
|
||||
private GetTenantUserListResponse? _selectedItem;
|
||||
private string _searchString = "";
|
||||
private bool _isRefreshing = false;
|
||||
private bool _isExporting = false;
|
||||
|
||||
private int _skip = 0;
|
||||
private int _top = 5;
|
||||
private int _totalPage => GetFilteredData().Count() == 0 ? 0 : (int)Math.Ceiling((double)GetFilteredData().Count() / (_top == 0 ? 1 : _top));
|
||||
private int _currentPage => (_top >= GetFilteredData().Count() || _top == 0) ? 1 : (_skip / _top) + 1;
|
||||
|
||||
protected override async Task OnInitializedAsync() => await LoadData();
|
||||
|
||||
private async Task LoadData()
|
||||
{
|
||||
_isRefreshing = true;
|
||||
_selectedItem = null;
|
||||
StateHasChanged();
|
||||
try
|
||||
{
|
||||
var response = await TenantUserService.GetTenantUserListAsync();
|
||||
await Task.Delay(500);
|
||||
if (response != null && response.IsSuccess) { _items = response.Value ?? new(); }
|
||||
}
|
||||
finally { _isRefreshing = false; StateHasChanged(); }
|
||||
}
|
||||
|
||||
private IEnumerable<GetTenantUserListResponse> GetFilteredData()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_searchString)) return _items;
|
||||
return _items.Where(x =>
|
||||
(x.FullName?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.Email?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.Summary?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.UserId?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.TenantName?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.TenantId?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false)
|
||||
);
|
||||
}
|
||||
|
||||
private IEnumerable<GetTenantUserListResponse> GetPagedData() => GetFilteredData().Skip(_skip).Take(_top);
|
||||
private void OnSearchClick() { _skip = 0; _selectedItem = null; StateHasChanged(); }
|
||||
private void HandleSearchKeyDown(KeyboardEventArgs e) { if (e.Key == "Enter") OnSearchClick(); }
|
||||
|
||||
private async Task ExportToExcel()
|
||||
{
|
||||
_isExporting = true;
|
||||
try
|
||||
{
|
||||
using (var workbook = new XLWorkbook())
|
||||
{
|
||||
var worksheet = workbook.Worksheets.Add("TenantUsers");
|
||||
worksheet.Cell(1, 1).Value = "Full Name";
|
||||
worksheet.Cell(1, 2).Value = "Email";
|
||||
worksheet.Cell(1, 3).Value = "Tenant";
|
||||
worksheet.Cell(1, 4).Value = "TenantId";
|
||||
worksheet.Cell(1, 5).Value = "Status";
|
||||
worksheet.Range(1, 1, 1, 5).Style.Font.Bold = true;
|
||||
var currentRow = 1;
|
||||
foreach (var item in GetFilteredData())
|
||||
{
|
||||
currentRow++;
|
||||
worksheet.Cell(currentRow, 1).Value = item.FullName;
|
||||
worksheet.Cell(currentRow, 2).Value = item.Email;
|
||||
worksheet.Cell(currentRow, 3).Value = item.TenantName;
|
||||
worksheet.Cell(currentRow, 4).Value = item.TenantId;
|
||||
worksheet.Cell(currentRow, 5).Value = item.IsActive ? "Active" : "Inactive";
|
||||
}
|
||||
worksheet.Columns().AdjustToContents();
|
||||
using (var stream = new MemoryStream())
|
||||
{
|
||||
workbook.SaveAs(stream);
|
||||
var content = Convert.ToBase64String(stream.ToArray());
|
||||
await JSRuntime.InvokeVoidAsync("downloadFile", "TenantUser_List.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", content);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally { _isExporting = false; StateHasChanged(); }
|
||||
}
|
||||
|
||||
private void OnPageChanged(int page) { if (page >= 1 && page <= _totalPage) { _skip = (page - 1) * _top; _selectedItem = null; StateHasChanged(); } }
|
||||
private void OnPageSizeChanged(int size) { _top = size; _skip = 0; _selectedItem = null; StateHasChanged(); }
|
||||
|
||||
private async Task InvokeEdit() { if (_selectedItem != null) { var req = await MapToUpdateRequest(_selectedItem.Id); if (req != null) await OnEdit.InvokeAsync(req); } }
|
||||
private async Task InvokeView() { if (_selectedItem != null) { var req = await MapToUpdateRequest(_selectedItem.Id); if (req != null) await OnView.InvokeAsync(req); } }
|
||||
|
||||
private async Task<UpdateTenantUserRequest?> MapToUpdateRequest(string id)
|
||||
{
|
||||
var response = await TenantUserService.GetTenantUserByIdAsync(id);
|
||||
if (response != null && response.IsSuccess && response.Value != null)
|
||||
{
|
||||
var d = response.Value;
|
||||
return new UpdateTenantUserRequest { Id = d.Id, TenantId = d.TenantId, UserId = d.UserId, Summary = d.Summary, IsActive = d.IsActive, CreatedAt = d.CreatedAt, CreatedBy = d.CreatedBy, UpdatedAt = d.UpdatedAt, UpdatedBy = d.UpdatedBy };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private async Task OnDelete()
|
||||
{
|
||||
if (_selectedItem == null) return;
|
||||
var parameters = new DialogParameters<_DeleteConfirmation> { { x => x.ContentText, _selectedItem.Summary } };
|
||||
var dialog = await DialogService.ShowAsync<_DeleteConfirmation>("", parameters, new DialogOptions { MaxWidth = MaxWidth.ExtraSmall, FullWidth = true });
|
||||
var result = await dialog.Result;
|
||||
if (result != null && !result.Canceled)
|
||||
{
|
||||
var success = await TenantUserService.DeleteTenantUserByIdAsync(_selectedItem.Id);
|
||||
if (success) { _selectedItem = null; await LoadData(); Snackbar.Add("Deleted successfully", Severity.Success); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
@using Indotalent.ConfigBackEnd.Extensions
|
||||
@using Indotalent.Features.Multitenant.TenantUser
|
||||
@using Indotalent.Features.Multitenant.TenantUser.Cqrs
|
||||
@using Indotalent.Shared.Utils
|
||||
@using MudBlazor
|
||||
@inject TenantUserService TenantUserService
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
|
||||
<div class="d-flex align-center gap-4">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">@(ReadOnly ? "User Details" : "Edit User")</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b;">@(ReadOnly ? "Viewing tenant user assignment." : "Modify tenant user assignment.")</MudText>
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA;">
|
||||
@if (_isDataLoading)
|
||||
{
|
||||
<div class="d-flex justify-center pa-10"><MudProgressCircular Color="Color.Primary" Indeterminate="true" /></div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudForm @ref="_form" Model="_model">
|
||||
<MudGrid Spacing="3">
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">User Assignment</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Tenant</MudText>
|
||||
<MudSelect @bind-Value="_model.TenantId" For="@(() => _model.TenantId)" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Dense="true" AnchorOrigin="Origin.BottomCenter" TransformOrigin="Origin.TopCenter">
|
||||
@foreach (var item in _lookupData.Tenants)
|
||||
{
|
||||
<MudSelectItem Value="@item.Id">@item.Name</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">System User</MudText>
|
||||
<MudSelect @bind-Value="_model.UserId" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Dense="true" AnchorOrigin="Origin.BottomCenter" TransformOrigin="Origin.TopCenter">
|
||||
@foreach (var item in _lookupData.SystemUsers)
|
||||
{
|
||||
<MudSelectItem Value="@item.Id">@item.Name</MudSelectItem>
|
||||
}
|
||||
</MudSelect>
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Summary</MudText>
|
||||
<MudTextField @bind-Value="_model.Summary" For="@(() => _model.Summary)" Validation="@(_validator.ValidateValue())" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Is Active</MudText>
|
||||
<MudSwitch @bind-Value="_model.IsActive" ReadOnly="ReadOnly" Color="Color.Success" Disabled="ReadOnly" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" Class="mt-4">
|
||||
<MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">Audit History</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Created At</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@DateTimeExtensions.ToString(_model.CreatedAt)</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Created By</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@(!string.IsNullOrEmpty(_model.CreatedBy) ? _model.CreatedBy : "System")</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Last Updated At</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@DateTimeExtensions.ToString(_model.UpdatedAt)</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Last Updated By</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@(!string.IsNullOrEmpty(_model.UpdatedBy) ? _model.UpdatedBy : "System")</MudText>
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<div class="d-flex justify-end gap-2 mt-10">
|
||||
<MudButton OnClick="() => OnCancel.InvokeAsync()" Variant="Variant.Outlined" Disabled="_processing" Style="border-radius: 4px; border: 1px solid #e0e0e0; text-transform: none; font-weight: 700;">@(ReadOnly ? "Back to List" : "Cancel")</MudButton>
|
||||
@if (!ReadOnly)
|
||||
{
|
||||
<MudButton Color="Color.Primary" Variant="Variant.Filled" OnClick="Submit" Disabled="_processing" Style="border-radius: 4px; text-transform: none; font-weight: 700;">
|
||||
@if (_processing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Updating...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText>Save Changes</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
}
|
||||
</div>
|
||||
</MudForm>
|
||||
}
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter] public UpdateTenantUserRequest Data { get; set; } = new();
|
||||
[Parameter] public bool ReadOnly { get; set; } = false;
|
||||
[Parameter] public EventCallback OnCancel { get; set; }
|
||||
[Parameter] public EventCallback OnSuccess { get; set; }
|
||||
private MudForm _form = default!;
|
||||
private UpdateTenantUserValidator _validator = new();
|
||||
private UpdateTenantUserRequest _model = new();
|
||||
private LookupTenantUserResponse _lookupData = new();
|
||||
private bool _processing = false;
|
||||
private bool _isDataLoading = true;
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
_isDataLoading = true;
|
||||
try
|
||||
{
|
||||
var response = await TenantUserService.GetTenantUserLookupAsync();
|
||||
if (response != null && response.IsSuccess) { _lookupData = response.Value!; }
|
||||
_model = Data;
|
||||
}
|
||||
finally { _isDataLoading = false; }
|
||||
}
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
if (ReadOnly) return;
|
||||
await _form.Validate();
|
||||
if (!_form.IsValid) return;
|
||||
_processing = true;
|
||||
try
|
||||
{
|
||||
var response = await TenantUserService.UpdateTenantUserAsync(_model);
|
||||
await Task.Delay(500);
|
||||
if (response != null && response.IsSuccess) { Snackbar.Add("User updated successfully", Severity.Success); await OnSuccess.InvokeAsync(); }
|
||||
}
|
||||
finally { _processing = false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.TenantUser.Cqrs;
|
||||
|
||||
public class CreateTenantUserRequest
|
||||
{
|
||||
public string? TenantId { get; set; }
|
||||
public string? UserId { get; set; }
|
||||
public string? Summary { get; set; }
|
||||
public bool IsActive { get; set; } = true;
|
||||
}
|
||||
|
||||
public class CreateTenantUserResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? Summary { get; set; }
|
||||
}
|
||||
|
||||
public record CreateTenantUserCommand(CreateTenantUserRequest Data) : IRequest<CreateTenantUserResponse>;
|
||||
|
||||
public class CreateTenantUserHandler : IRequestHandler<CreateTenantUserCommand, CreateTenantUserResponse>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public CreateTenantUserHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<CreateTenantUserResponse> Handle(CreateTenantUserCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = new Data.Entities.TenantUser
|
||||
{
|
||||
TenantId = request.Data.TenantId,
|
||||
UserId = request.Data.UserId,
|
||||
Summary = request.Data.Summary,
|
||||
IsActive = request.Data.IsActive
|
||||
};
|
||||
|
||||
_context.TenantUser.Add(entity);
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return new CreateTenantUserResponse
|
||||
{
|
||||
Id = entity.Id,
|
||||
Summary = entity.Summary
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using FluentValidation;
|
||||
using Indotalent.Shared.Consts;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.TenantUser.Cqrs;
|
||||
|
||||
public class CreateTenantUserValidator : AbstractValidator<CreateTenantUserRequest>
|
||||
{
|
||||
public CreateTenantUserValidator()
|
||||
{
|
||||
RuleFor(x => x.Summary)
|
||||
.NotEmpty().WithMessage("Summary is required")
|
||||
.MaximumLength(GlobalConsts.StringLengthShort);
|
||||
|
||||
RuleFor(x => x.TenantId)
|
||||
.NotEmpty().WithMessage("Tenant is required");
|
||||
|
||||
RuleFor(x => x.UserId)
|
||||
.NotEmpty().WithMessage("User is required");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.TenantUser.Cqrs;
|
||||
|
||||
public record DeleteTenantUserByIdRequest(string Id);
|
||||
|
||||
public record DeleteTenantUserByIdCommand(DeleteTenantUserByIdRequest Data) : IRequest<bool>;
|
||||
|
||||
public class DeleteTenantUserByIdHandler : IRequestHandler<DeleteTenantUserByIdCommand, bool>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public DeleteTenantUserByIdHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<bool> Handle(DeleteTenantUserByIdCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = await _context.TenantUser
|
||||
.FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);
|
||||
|
||||
if (entity == null) return false;
|
||||
|
||||
_context.TenantUser.Remove(entity);
|
||||
return await _context.SaveChangesAsync(cancellationToken) > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.TenantUser.Cqrs;
|
||||
|
||||
public class GetTenantUserByIdResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? TenantId { get; set; }
|
||||
public string? UserId { get; set; }
|
||||
public string? Summary { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
public DateTimeOffset? CreatedAt { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
public DateTimeOffset? UpdatedAt { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
}
|
||||
|
||||
public record GetTenantUserByIdQuery(string Id) : IRequest<GetTenantUserByIdResponse?>;
|
||||
|
||||
public class GetTenantUserByIdHandler : IRequestHandler<GetTenantUserByIdQuery, GetTenantUserByIdResponse?>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public GetTenantUserByIdHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<GetTenantUserByIdResponse?> Handle(GetTenantUserByIdQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
return await _context.TenantUser
|
||||
.AsNoTracking()
|
||||
.Where(x => x.Id == request.Id)
|
||||
.Select(x => new GetTenantUserByIdResponse
|
||||
{
|
||||
Id = x.Id,
|
||||
TenantId = x.TenantId,
|
||||
UserId = x.UserId,
|
||||
Summary = x.Summary,
|
||||
IsActive = x.IsActive,
|
||||
CreatedAt = x.CreatedAt,
|
||||
CreatedBy = x.CreatedBy,
|
||||
UpdatedAt = x.UpdatedAt,
|
||||
UpdatedBy = x.UpdatedBy,
|
||||
})
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Indotalent.Data.Entities;
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.TenantUser.Cqrs;
|
||||
|
||||
public class GetTenantUserListResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? UserId { get; set; }
|
||||
public string? FullName { get; set; }
|
||||
public string? Email { get; set; }
|
||||
public string? Summary { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
public string? TenantName { get; set; }
|
||||
public string? TenantId { get; set; }
|
||||
}
|
||||
|
||||
public record GetTenantUserListQuery() : IRequest<List<GetTenantUserListResponse>>;
|
||||
|
||||
public class GetTenantUserListHandler : IRequestHandler<GetTenantUserListQuery, List<GetTenantUserListResponse>>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
private readonly UserManager<ApplicationUser> _userManager;
|
||||
|
||||
public GetTenantUserListHandler(AppDbContext context, UserManager<ApplicationUser> userManager)
|
||||
{
|
||||
_context = context;
|
||||
_userManager = userManager;
|
||||
}
|
||||
|
||||
public async Task<List<GetTenantUserListResponse>> Handle(GetTenantUserListQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var tenantUsers = await _context.TenantUser
|
||||
.AsNoTracking()
|
||||
.Include(x => x.Tenant)
|
||||
.OrderBy(x => x.Summary)
|
||||
.Select(x => new GetTenantUserListResponse
|
||||
{
|
||||
Id = x.Id,
|
||||
UserId = x.UserId,
|
||||
Summary = x.Summary,
|
||||
IsActive = x.IsActive,
|
||||
TenantName = x.Tenant != null ? x.Tenant.Name : string.Empty,
|
||||
TenantId = x.TenantId
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
// Populate FullName and Email from ApplicationUser
|
||||
foreach (var item in tenantUsers)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(item.UserId))
|
||||
{
|
||||
var user = await _userManager.FindByIdAsync(item.UserId);
|
||||
if (user != null)
|
||||
{
|
||||
item.FullName = user.FullName;
|
||||
item.Email = user.Email;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return tenantUsers;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.TenantUser.Cqrs;
|
||||
|
||||
public class LookupTenantUserResponse
|
||||
{
|
||||
public List<LookupItem> Tenants { get; set; } = new();
|
||||
public List<LookupItem> SystemUsers { get; set; } = new();
|
||||
}
|
||||
|
||||
public class LookupItem
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? Name { get; set; }
|
||||
}
|
||||
|
||||
public record LookupTenantUserQuery() : IRequest<LookupTenantUserResponse>;
|
||||
|
||||
public class LookupTenantUserHandler : IRequestHandler<LookupTenantUserQuery, LookupTenantUserResponse>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public LookupTenantUserHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<LookupTenantUserResponse> Handle(LookupTenantUserQuery request, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = new LookupTenantUserResponse();
|
||||
|
||||
result.Tenants = await _context.Tenant
|
||||
.AsNoTracking()
|
||||
.OrderBy(x => x.Name)
|
||||
.Select(x => new LookupItem { Id = x.Id, Name = x.Name })
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
result.SystemUsers = await _context.Users
|
||||
.AsNoTracking()
|
||||
.OrderBy(x => x.FullName)
|
||||
.Select(x => new LookupItem { Id = x.Id, Name = x.FullName })
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using Indotalent.Infrastructure.Database;
|
||||
using MediatR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.TenantUser.Cqrs;
|
||||
|
||||
public class UpdateTenantUserRequest
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public string? TenantId { get; set; }
|
||||
public string? UserId { get; set; }
|
||||
public string? Summary { get; set; }
|
||||
public bool IsActive { get; set; }
|
||||
public DateTimeOffset? CreatedAt { get; set; }
|
||||
public string? CreatedBy { get; set; }
|
||||
public DateTimeOffset? UpdatedAt { get; set; }
|
||||
public string? UpdatedBy { get; set; }
|
||||
}
|
||||
|
||||
public class UpdateTenantUserResponse
|
||||
{
|
||||
public string? Id { get; set; }
|
||||
public bool Success { get; set; }
|
||||
}
|
||||
|
||||
public record UpdateTenantUserCommand(UpdateTenantUserRequest Data) : IRequest<UpdateTenantUserResponse>;
|
||||
|
||||
public class UpdateTenantUserHandler : IRequestHandler<UpdateTenantUserCommand, UpdateTenantUserResponse>
|
||||
{
|
||||
private readonly AppDbContext _context;
|
||||
|
||||
public UpdateTenantUserHandler(AppDbContext context) => _context = context;
|
||||
|
||||
public async Task<UpdateTenantUserResponse> Handle(UpdateTenantUserCommand request, CancellationToken cancellationToken)
|
||||
{
|
||||
var entity = await _context.TenantUser
|
||||
.FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);
|
||||
|
||||
if (entity == null)
|
||||
{
|
||||
return new UpdateTenantUserResponse { Id = request.Data.Id, Success = false };
|
||||
}
|
||||
|
||||
entity.TenantId = request.Data.TenantId;
|
||||
entity.UserId = request.Data.UserId;
|
||||
entity.Summary = request.Data.Summary;
|
||||
entity.IsActive = request.Data.IsActive;
|
||||
|
||||
await _context.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return new UpdateTenantUserResponse
|
||||
{
|
||||
Id = entity.Id,
|
||||
Success = true
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using FluentValidation;
|
||||
using Indotalent.Shared.Consts;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.TenantUser.Cqrs;
|
||||
|
||||
public class UpdateTenantUserValidator : AbstractValidator<UpdateTenantUserRequest>
|
||||
{
|
||||
public UpdateTenantUserValidator()
|
||||
{
|
||||
RuleFor(x => x.Id)
|
||||
.NotEmpty().WithMessage("ID is required for update");
|
||||
|
||||
RuleFor(x => x.Summary)
|
||||
.NotEmpty().WithMessage("Summary is required")
|
||||
.MaximumLength(GlobalConsts.StringLengthShort);
|
||||
|
||||
RuleFor(x => x.TenantId)
|
||||
.NotEmpty().WithMessage("Tenant is required");
|
||||
|
||||
RuleFor(x => x.UserId)
|
||||
.NotEmpty().WithMessage("User is required");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
using Indotalent.ConfigBackEnd.Extensions;
|
||||
using Indotalent.Features.Multitenant.TenantUser.Cqrs;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.TenantUser;
|
||||
|
||||
public static class TenantUserEndpoint
|
||||
{
|
||||
public static void MapTenantUserEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
var group = app.MapGroup("/tenant-user").WithTags("TenantUsers")
|
||||
.RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
|
||||
.RequireAuthenticatedUser());
|
||||
|
||||
group.MapGet("/", async (IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new GetTenantUserListQuery());
|
||||
return result.ToApiResponse("Tenant user list retrieved successfully");
|
||||
})
|
||||
.WithName("GetTenantUserList")
|
||||
.WithTags("TenantUsers");
|
||||
|
||||
group.MapGet("/{id}", async (string id, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new GetTenantUserByIdQuery(id));
|
||||
return result.ToApiResponse(result is not null
|
||||
? "Tenant user detail retrieved successfully"
|
||||
: $"Tenant user with ID {id} not found");
|
||||
})
|
||||
.WithName("GetTenantUserById")
|
||||
.WithTags("TenantUsers");
|
||||
|
||||
group.MapGet("/lookup", async (IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new LookupTenantUserQuery());
|
||||
return result.ToApiResponse("Lookup data retrieved successfully");
|
||||
})
|
||||
.WithName("GetTenantUserLookup")
|
||||
.WithTags("TenantUsers");
|
||||
|
||||
group.MapPost("/", async (CreateTenantUserRequest request, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new CreateTenantUserCommand(request));
|
||||
return result.ToApiResponse("Tenant user has been created successfully", StatusCodes.Status201Created);
|
||||
})
|
||||
.WithName("CreateTenantUser")
|
||||
.WithTags("TenantUsers");
|
||||
|
||||
group.MapPost("/update", async (UpdateTenantUserRequest request, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new UpdateTenantUserCommand(request));
|
||||
if (!result.Success)
|
||||
{
|
||||
return ((object?)null).ToApiResponse("Update failed. The tenant user data could not be found.");
|
||||
}
|
||||
return result.ToApiResponse("Tenant user has been updated successfully");
|
||||
})
|
||||
.WithName("UpdateTenantUser")
|
||||
.WithTags("TenantUsers");
|
||||
|
||||
group.MapPost("/delete/{id}", async (string id, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new DeleteTenantUserByIdCommand(new DeleteTenantUserByIdRequest(id)));
|
||||
if (!result)
|
||||
{
|
||||
return ((object?)null).ToApiResponse("Delete failed. The tenant user data could not be found.");
|
||||
}
|
||||
return true.ToApiResponse("Tenant user has been deleted successfully");
|
||||
})
|
||||
.WithName("DeleteTenantUserById")
|
||||
.WithTags("TenantUsers");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using Indotalent.ConfigBackEnd.Interfaces;
|
||||
using Indotalent.ConfigFrontEnd.Common;
|
||||
using Indotalent.Features.Multitenant.TenantUser.Cqrs;
|
||||
using Indotalent.Infrastructure.Authentication.Identity;
|
||||
using Indotalent.Shared.Models;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using MudBlazor;
|
||||
using RestSharp;
|
||||
|
||||
namespace Indotalent.Features.Multitenant.TenantUser;
|
||||
|
||||
public class TenantUserService : BaseService
|
||||
{
|
||||
private readonly RestClient _client;
|
||||
|
||||
public TenantUserService(
|
||||
IHttpClientFactory clientFactory,
|
||||
NavigationManager nav,
|
||||
ISnackbar snackbar,
|
||||
ICurrentUserService currentUserService,
|
||||
TokenProvider tokenProvider)
|
||||
: base(clientFactory, nav, snackbar, currentUserService, tokenProvider)
|
||||
{
|
||||
_client = new RestClient(nav.BaseUri);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<List<GetTenantUserListResponse>>?> GetTenantUserListAsync()
|
||||
{
|
||||
var request = new RestRequest("api/tenant-user", Method.Get);
|
||||
return await ExecuteWithResponseAsync<List<GetTenantUserListResponse>>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<GetTenantUserByIdResponse>?> GetTenantUserByIdAsync(string id)
|
||||
{
|
||||
var request = new RestRequest($"api/tenant-user/{id}", Method.Get);
|
||||
return await ExecuteWithResponseAsync<GetTenantUserByIdResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<LookupTenantUserResponse>?> GetTenantUserLookupAsync()
|
||||
{
|
||||
var request = new RestRequest("api/tenant-user/lookup", Method.Get);
|
||||
return await ExecuteWithResponseAsync<LookupTenantUserResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<CreateTenantUserResponse>?> CreateTenantUserAsync(CreateTenantUserRequest data)
|
||||
{
|
||||
var request = new RestRequest("api/tenant-user", Method.Post);
|
||||
request.AddJsonBody(data);
|
||||
return await ExecuteWithResponseAsync<CreateTenantUserResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteTenantUserByIdAsync(string id)
|
||||
{
|
||||
var request = new RestRequest($"api/tenant-user/delete/{id}", Method.Post);
|
||||
var response = await ExecuteWithResponseAsync<object>(_client, request);
|
||||
return response?.IsSuccess ?? false;
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<UpdateTenantUserResponse>?> UpdateTenantUserAsync(UpdateTenantUserRequest data)
|
||||
{
|
||||
var request = new RestRequest("api/tenant-user/update", Method.Post);
|
||||
request.AddJsonBody(data);
|
||||
return await ExecuteWithResponseAsync<UpdateTenantUserResponse>(_client, request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using Indotalent.ConfigBackEnd.Extensions;
|
||||
using Indotalent.Features.Organization.Branch.Cqrs;
|
||||
using MediatR;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
|
||||
namespace Indotalent.Features.Organization.Branch;
|
||||
|
||||
public static class BranchEndpoint
|
||||
{
|
||||
public static void MapBranchEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
var group = app.MapGroup("/branch").WithTags("Branches")
|
||||
.RequireAuthorization(policy => policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
|
||||
.RequireAuthenticatedUser());
|
||||
|
||||
group.MapGet("/", async (IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new GetBranchListQuery());
|
||||
return result.ToApiResponse("Data branch retrieved successfully");
|
||||
})
|
||||
.WithName("GetBranchList");
|
||||
|
||||
group.MapGet("/{id}", async (string id, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new GetBranchByIdQuery(id));
|
||||
return result.ToApiResponse(result is not null
|
||||
? "Branch detail retrieved successfully"
|
||||
: $"Branch with ID {id} not found");
|
||||
})
|
||||
.WithName("GetBranchById");
|
||||
|
||||
group.MapPost("/", async (CreateBranchRequest request, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new CreateBranchCommand(request));
|
||||
return result.ToApiResponse("Branch has been created successfully", StatusCodes.Status201Created);
|
||||
})
|
||||
.WithName("CreateBranch");
|
||||
|
||||
group.MapPost("/update", async (UpdateBranchRequest request, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new UpdateBranchCommand(request));
|
||||
if (!result.Success) return ((object?)null).ToApiResponse("Update failed.");
|
||||
return result.ToApiResponse("Branch has been updated successfully");
|
||||
})
|
||||
.WithName("UpdateBranch");
|
||||
|
||||
group.MapPost("/delete/{id}", async (string id, IMediator mediator) =>
|
||||
{
|
||||
var result = await mediator.Send(new DeleteBranchByIdCommand(new DeleteBranchByIdRequest(id)));
|
||||
if (!result) return ((object?)null).ToApiResponse("Delete failed.");
|
||||
return true.ToApiResponse("Branch has been deleted successfully");
|
||||
})
|
||||
.WithName("DeleteBranchById");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using Indotalent.ConfigBackEnd.Interfaces;
|
||||
using Indotalent.ConfigFrontEnd.Common;
|
||||
using Indotalent.Features.Organization.Branch.Cqrs;
|
||||
using Indotalent.Infrastructure.Authentication.Identity;
|
||||
using Indotalent.Shared.Models;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using MudBlazor;
|
||||
using RestSharp;
|
||||
|
||||
namespace Indotalent.Features.Organization.Branch;
|
||||
|
||||
public class BranchService : BaseService
|
||||
{
|
||||
private readonly RestClient _client;
|
||||
|
||||
public BranchService(IHttpClientFactory clientFactory, NavigationManager nav, ISnackbar snackbar, ICurrentUserService currentUserService, TokenProvider tokenProvider)
|
||||
: base(clientFactory, nav, snackbar, currentUserService, tokenProvider)
|
||||
{
|
||||
_client = new RestClient(nav.BaseUri);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<List<GetBranchListResponse>>?> GetBranchListAsync()
|
||||
{
|
||||
var request = new RestRequest("api/branch", Method.Get);
|
||||
return await ExecuteWithResponseAsync<List<GetBranchListResponse>>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<GetBranchByIdResponse>?> GetBranchByIdAsync(string id)
|
||||
{
|
||||
var request = new RestRequest($"api/branch/{id}", Method.Get);
|
||||
return await ExecuteWithResponseAsync<GetBranchByIdResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<CreateBranchResponse>?> CreateBranchAsync(CreateBranchRequest data)
|
||||
{
|
||||
var request = new RestRequest("api/branch", Method.Post);
|
||||
request.AddJsonBody(data);
|
||||
return await ExecuteWithResponseAsync<CreateBranchResponse>(_client, request);
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteBranchByIdAsync(string id)
|
||||
{
|
||||
var request = new RestRequest($"api/branch/delete/{id}", Method.Post);
|
||||
var response = await ExecuteWithResponseAsync<object>(_client, request);
|
||||
return response?.IsSuccess ?? false;
|
||||
}
|
||||
|
||||
public async Task<ApiResponse<UpdateBranchResponse>?> UpdateBranchAsync(UpdateBranchRequest data)
|
||||
{
|
||||
var request = new RestRequest("api/branch/update", Method.Post);
|
||||
request.AddJsonBody(data);
|
||||
return await ExecuteWithResponseAsync<UpdateBranchResponse>(_client, request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
@page "/organization/branch"
|
||||
@using Indotalent.Features.Organization.Branch
|
||||
@using Indotalent.Features.Organization.Branch.Cqrs
|
||||
@using MudBlazor
|
||||
|
||||
@if (_currentView == ViewMode.Create)
|
||||
{
|
||||
<_BranchCreateForm OnCancel="BackToTable"
|
||||
OnSuccess="HandleSuccess" />
|
||||
}
|
||||
else if (_currentView == ViewMode.Update || _currentView == ViewMode.View)
|
||||
{
|
||||
<_BranchUpdateForm Data="_selectedData!"
|
||||
ReadOnly="@(_currentView == ViewMode.View)"
|
||||
OnCancel="BackToTable"
|
||||
OnSuccess="HandleSuccess" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<_BranchDataTable OnAdd="() => ShowCreate()"
|
||||
OnEdit="(item) => ShowUpdate(item, false)"
|
||||
OnView="(item) => ShowUpdate(item, true)" />
|
||||
}
|
||||
|
||||
@code {
|
||||
private enum ViewMode { Table, Create, Update, View }
|
||||
private ViewMode _currentView = ViewMode.Table;
|
||||
private UpdateBranchRequest? _selectedData;
|
||||
|
||||
private void ShowCreate()
|
||||
{
|
||||
_currentView = ViewMode.Create;
|
||||
}
|
||||
|
||||
private void ShowUpdate(UpdateBranchRequest data, bool isReadOnly)
|
||||
{
|
||||
_selectedData = data;
|
||||
_currentView = isReadOnly ? ViewMode.View : ViewMode.Update;
|
||||
}
|
||||
|
||||
private void BackToTable()
|
||||
{
|
||||
_currentView = ViewMode.Table;
|
||||
_selectedData = null;
|
||||
}
|
||||
|
||||
private void HandleSuccess()
|
||||
{
|
||||
_currentView = ViewMode.Table;
|
||||
_selectedData = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
@using Indotalent.Features.Organization.Branch
|
||||
@using Indotalent.Features.Organization.Branch.Cqrs
|
||||
@using Indotalent.Shared.Utils
|
||||
@using MudBlazor
|
||||
@inject BranchService BranchService
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
|
||||
<div class="d-flex align-center gap-4">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">Add New Branch</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b;">Configure new office or warehouse location.</MudText>
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA;">
|
||||
<MudForm @ref="_form" Model="_model">
|
||||
<MudGrid Spacing="3">
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Branch Code</MudText>
|
||||
<MudTextField @bind-Value="_model.Code"
|
||||
For="@(() => _model.Code)"
|
||||
Validation="@(_validator.ValidateValue())"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Placeholder="e.g. HQ-JKT" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="8">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Branch Name</MudText>
|
||||
<MudTextField @bind-Value="_model.Name"
|
||||
For="@(() => _model.Name)"
|
||||
Validation="@(_validator.ValidateValue())"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Placeholder="e.g. Central Office" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">City</MudText>
|
||||
<MudTextField @bind-Value="_model.City"
|
||||
For="@(() => _model.City)"
|
||||
Validation="@(_validator.ValidateValue())"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" Placeholder="e.g. Jakarta" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="8">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Street Address</MudText>
|
||||
<MudTextField @bind-Value="_model.StreetAddress"
|
||||
For="@(() => _model.StreetAddress)"
|
||||
Validation="@(_validator.ValidateValue())"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">State/Province</MudText>
|
||||
<MudTextField @bind-Value="_model.StateProvince" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">ZIP Code</MudText>
|
||||
<MudTextField @bind-Value="_model.ZipCode" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Phone</MudText>
|
||||
<MudTextField @bind-Value="_model.Phone" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Email</MudText>
|
||||
<MudTextField @bind-Value="_model.Email"
|
||||
For="@(() => _model.Email)"
|
||||
Validation="@(_validator.ValidateValue())"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Description</MudText>
|
||||
<MudTextField @bind-Value="_model.Description" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Other Information 1</MudText>
|
||||
<MudTextField @bind-Value="_model.OtherInformation1" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Other Information 2</MudText>
|
||||
<MudTextField @bind-Value="_model.OtherInformation2" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Other Information 3</MudText>
|
||||
<MudTextField @bind-Value="_model.OtherInformation3" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<div class="d-flex justify-end gap-2 mt-8">
|
||||
<MudButton OnClick="() => OnCancel.InvokeAsync()"
|
||||
Variant="Variant.Outlined"
|
||||
Disabled="_processing"
|
||||
Style="border: 1px solid #e0e0e0; border-radius: 4px; text-transform: none; font-weight: 700;">
|
||||
Cancel
|
||||
</MudButton>
|
||||
<MudButton Color="Color.Primary"
|
||||
Variant="Variant.Filled"
|
||||
OnClick="Submit"
|
||||
Disabled="_processing"
|
||||
Style="border-radius: 4px; text-transform: none; font-weight: 700;">
|
||||
@if (_processing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText>Create Branch</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
</div>
|
||||
</MudForm>
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter] public EventCallback OnCancel { get; set; }
|
||||
[Parameter] public EventCallback OnSuccess { get; set; }
|
||||
|
||||
private MudForm _form = default!;
|
||||
private CreateBranchValidator _validator = new();
|
||||
private CreateBranchRequest _model = new();
|
||||
private bool _processing = false;
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
await _form.Validate();
|
||||
if (!_form.IsValid) return;
|
||||
|
||||
_processing = true;
|
||||
try
|
||||
{
|
||||
var response = await BranchService.CreateBranchAsync(_model);
|
||||
await Task.Delay(500);
|
||||
|
||||
if (response != null && response.IsSuccess)
|
||||
{
|
||||
Snackbar.Add("Branch created successfully", Severity.Success);
|
||||
await OnSuccess.InvokeAsync();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Error: {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_processing = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
@using Indotalent.ConfigBackEnd.Extensions
|
||||
@using Indotalent.Features.Organization.Branch
|
||||
@using Indotalent.Features.Organization.Branch.Cqrs
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using Microsoft.JSInterop
|
||||
@using MudBlazor
|
||||
@using Features.Root.Shared
|
||||
@using ClosedXML.Excel
|
||||
@using System.IO
|
||||
@inject BranchService BranchService
|
||||
@inject IDialogService DialogService
|
||||
@inject ISnackbar Snackbar
|
||||
@inject IJSRuntime JSRuntime
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #E5E7EB; border-radius: 12px;">
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 700; color: #111827;">Branch Management</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #9CA3AF;">Manage physical office locations, regional branches, and site operational details.</MudText>
|
||||
</div>
|
||||
|
||||
<div class="d-flex align-center gap-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Home" Size="Size.Small" Color="Color.Default" />
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">Organization</MudText>
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF;">/</MudText>
|
||||
<MudText Typo="Typo.caption" Style="font-weight: 600; color: #111827;">Branch</MudText>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Style="border-radius: 12px; overflow: hidden; background-color: #ffffff; border: 1px solid #E5E7EB;">
|
||||
|
||||
<div style="padding: 20px 24px; border-bottom: 1px solid #E5E7EB; display: flex; justify-content: space-between; align-items: center; background-color: #ffffff; min-height: 80px;">
|
||||
|
||||
<div style="display: flex; align-items: center; gap: 8px;">
|
||||
<MudTextField @bind-Value="_searchString"
|
||||
Placeholder="Search..."
|
||||
Adornment="Adornment.Start"
|
||||
AdornmentIcon="@Icons.Material.Filled.Search"
|
||||
IconSize="Size.Small"
|
||||
Class="mt-0"
|
||||
Variant="Variant.Outlined"
|
||||
Margin="Margin.Dense"
|
||||
Style="background-color: white; width: 280px; border-radius: 8px;"
|
||||
OnKeyDown="@HandleSearchKeyDown" />
|
||||
|
||||
<MudButton Variant="Variant.Filled"
|
||||
Color="Color.Primary"
|
||||
OnClick="OnSearchClick"
|
||||
Size="Size.Small"
|
||||
Style="text-transform: none; font-weight: 500; border-radius: 6px; height: 34px; box-shadow: none;">
|
||||
Search
|
||||
</MudButton>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<MudButton Variant="Variant.Outlined"
|
||||
Color="Color.Success"
|
||||
OnClick="ExportToExcel"
|
||||
Size="Size.Small"
|
||||
Disabled="_isExporting"
|
||||
StartIcon="@(_isExporting ? null : Icons.Custom.FileFormats.FileExcel)"
|
||||
Style="border: 1px solid #D1D5DB; background: white; font-weight: 500; border-radius: 6px; text-transform: none; height: 34px; color: #6B7280;">
|
||||
@if (_isExporting)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Processing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText Typo="Typo.button" Style="text-transform: none !important;">Excel</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
|
||||
<MudButton Variant="Variant.Outlined"
|
||||
Color="Color.Primary"
|
||||
OnClick="LoadData"
|
||||
Size="Size.Small"
|
||||
StartIcon="@(_isRefreshing ? null : Icons.Material.Filled.Refresh)"
|
||||
Disabled="_isRefreshing"
|
||||
Style="border: 1px solid #D1D5DB; background: white; font-weight: 500; border-radius: 6px; text-transform: none; height: 34px; color: #6B7280;">
|
||||
@if (_isRefreshing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2" Typo="Typo.button" Style="text-transform: none !important;">Refreshing...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText Typo="Typo.button" Style="text-transform: none !important;">Refresh</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
|
||||
@if (_selectedBranch != null)
|
||||
{
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Info" StartIcon="@Icons.Material.Filled.Visibility" OnClick="InvokeView" Size="Size.Small" Style="border: 1px solid #D1D5DB; text-transform: none; font-weight: 500; border-radius: 6px; background: white; color: #6B7280;">View</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Edit" OnClick="InvokeEdit" Size="Size.Small" Style="border: 1px solid #D1D5DB; text-transform: none; font-weight: 500; border-radius: 6px; background: white; color: #6B7280;">Edit</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Color="Color.Error" StartIcon="@Icons.Material.Filled.Delete" OnClick="OnDelete" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; border: 1px solid #FCA5A5; color: #EF4444; background: white;">Remove</MudButton>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Close" Size="Size.Small" OnClick="() => _selectedBranch = null" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" StartIcon="@Icons.Material.Filled.Add" OnClick="() => OnAdd.InvokeAsync()" Size="Size.Small" Style="text-transform: none; font-weight: 500; border-radius: 6px; height: 34px;">
|
||||
Add New Branch
|
||||
</MudButton>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<MudTable Items="@GetPagedData()" Hover="true" Striped="true" Class="mud-table-styled" Elevation="0" CustomHeader="true" Dense="true" T="GetBranchListResponse" OnRowClick="@((args) => _selectedBranch = args.Item)" Loading="@_isRefreshing">
|
||||
<HeaderContent>
|
||||
<MudTh Style="width: 50px; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB;"></MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetBranchListResponse, object>(x => x.Code)">Branch ID</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetBranchListResponse, object>(x => x.Name)">Branch Name</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetBranchListResponse, object>(x => x.City)">City / Region</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetBranchListResponse, object>(x => x.StreetAddress)">Full Address</MudTableSortLabel>
|
||||
</MudTh>
|
||||
<MudTh Style="font-weight: 600; color: #6B7280; text-transform: uppercase; font-size: 0.6875rem; letter-spacing: 0.05em; background-color: #F9FAFB; border-bottom: 1px solid #E5E7EB; white-space: nowrap;">
|
||||
<MudTableSortLabel SortBy="new Func<GetBranchListResponse, object>(x => x.Phone)">Contact Number</MudTableSortLabel>
|
||||
</MudTh>
|
||||
</HeaderContent>
|
||||
<RowTemplate>
|
||||
<MudTd>
|
||||
<MudCheckBox T="bool" Value="@(_selectedBranch?.Id == context.Id)" Color="Color.Primary" Dense="true" Size="Size.Small" ReadOnly="true" />
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudChip T="string" Size="Size.Small" Variant="Variant.Text" Style="background-color: #F3F4F6; color: #374151; font-weight: 600; border-radius: 4px;">
|
||||
@context.Code
|
||||
</MudChip>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<div class="d-flex align-center gap-2">
|
||||
<MudAvatar Color="Color.Primary" Size="Size.Small" Style="width: 32px; height: 32px; font-weight: 700; font-size: 12px;">@(!string.IsNullOrWhiteSpace(context.Name) ? context.Name.ToInitial() : "?")</MudAvatar>
|
||||
<MudText Typo="Typo.body2" Style="font-weight: 600; color: #374151;">@context.Name</MudText>
|
||||
</div>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudText Typo="Typo.body2" Style="font-weight: 600; color: #374151;">@context.City</MudText>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudText Typo="Typo.body2" Style="color: #9CA3AF;">@context.StreetAddress</MudText>
|
||||
</MudTd>
|
||||
<MudTd>
|
||||
<MudText Typo="Typo.body2" Style="font-family: monospace;">@context.Phone</MudText>
|
||||
</MudTd>
|
||||
</RowTemplate>
|
||||
</MudTable>
|
||||
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; padding: 12px 24px; background-color: #F9FAFB; border-top: 1px solid #E5E7EB;">
|
||||
<div style="display: flex; align-items: center; gap: 12px;">
|
||||
<MudText Typo="Typo.caption" Style="font-weight: 500; color: #9CA3AF; font-size: 0.75rem;">Rows per page:</MudText>
|
||||
|
||||
<MudSelect T="int"
|
||||
Value="@_top"
|
||||
ValueChanged="OnPageSizeChanged"
|
||||
Dense="true"
|
||||
Margin="Margin.Dense"
|
||||
Style="width: 80px; background-color: white; font-size: 0.75rem; font-weight: 500;"
|
||||
Variant="Variant.Outlined"
|
||||
Class="mt-0 custom-select-dense">
|
||||
<MudSelectItem Value="5" />
|
||||
<MudSelectItem Value="10" />
|
||||
<MudSelectItem Value="50" />
|
||||
<MudSelectItem Value="500" />
|
||||
<MudSelectItem Value="1000" />
|
||||
</MudSelect>
|
||||
|
||||
<MudText Typo="Typo.caption" Style="color: #9CA3AF; font-size: 0.75rem; font-weight: 500; margin-left: 12px;">
|
||||
Showing @(GetFilteredData().Count() == 0 ? 0 : _skip + 1)-@Math.Min(_skip + _top, GetFilteredData().Count()) of @GetFilteredData().Count()
|
||||
</MudText>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 8px; align-items: center;">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.FirstPage" Size="Size.Small" OnClick="@(() => OnPageChanged(1))" Disabled="@(_currentPage == 1)" Style="@(_currentPage == 1 ? "color: #D1D5DB; background: transparent;" : "color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px;")" />
|
||||
<MudButton OnClick="@(() => OnPageChanged(_currentPage - 1))" Disabled="@(_currentPage == 1)" Variant="Variant.Text" StartIcon="@Icons.Material.Filled.ChevronLeft" Size="Size.Small" Style="@(_currentPage == 1 ? "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;" : "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;")">Prev</MudButton>
|
||||
@{
|
||||
var totalPages = _totalPage == 0 ? 1 : _totalPage;
|
||||
var maxVisible = 5;
|
||||
var startPage = Math.Max(1, _currentPage - maxVisible / 2);
|
||||
var endPage = Math.Min(totalPages, startPage + maxVisible - 1);
|
||||
if (endPage - startPage < maxVisible - 1) { startPage = Math.Max(1, endPage - maxVisible + 1); }
|
||||
}
|
||||
@for (int i = startPage; i <= endPage; i++)
|
||||
{
|
||||
var pageNum = i;
|
||||
var isActive = pageNum == _currentPage;
|
||||
<MudButton OnClick="@(() => OnPageChanged(pageNum))"
|
||||
Variant="Variant.Text" Size="Size.Small"
|
||||
Style="@(isActive ? "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 600; background: #3B82F6; color: white; border: 1px solid #3B82F6; border-radius: 6px; text-transform: none;" : "min-width: 34px; padding: 4px 8px; font-size: 0.75rem; font-weight: 500; color: #374151; background: white; border: 1px solid #D1D5DB; border-radius: 6px; text-transform: none;")">@pageNum</MudButton>
|
||||
}
|
||||
<MudButton OnClick="@(() => OnPageChanged(_currentPage + 1))" Disabled="@(_currentPage == _totalPage || _totalPage == 0)" Variant="Variant.Text" EndIcon="@Icons.Material.Filled.ChevronRight" Size="Size.Small" Style="@(_currentPage == _totalPage || _totalPage == 0 ? "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;" : "text-transform: none; font-weight: 500; background: white; border: 1px solid #D1D5DB; border-radius: 6px; height: 34px; color: #6B7280;")">Next</MudButton>
|
||||
<MudIconButton Icon="@Icons.Material.Filled.LastPage" Size="Size.Small" OnClick="@(() => OnPageChanged(_totalPage))" Disabled="@(_currentPage == _totalPage || _totalPage == 0)" Style="@(_currentPage == _totalPage || _totalPage == 0 ? "color: #D1D5DB; background: transparent;" : "color: #6B7280; background: white; border: 1px solid #D1D5DB; border-radius: 6px;")" />
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<script>
|
||||
function downloadFile(fileName, contentType, base64String) {
|
||||
const link = document.createElement('a');
|
||||
link.download = fileName;
|
||||
link.href = `data:${contentType};base64,${base64String}`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.mud-input-outlined-border { border-radius: 8px !important; }
|
||||
.custom-select-dense .mud-input-control { margin-top: 0 !important; }
|
||||
.custom-select-dense .mud-input-slot { padding-top: 4px !important; padding-bottom: 4px !important; padding-left: 8px !important; font-size: 12px !important; }
|
||||
.mud-table-styled .mud-table-row:hover { background-color: #F9FAFB !important; }
|
||||
</style>
|
||||
|
||||
@code {
|
||||
[Parameter] public EventCallback OnAdd { get; set; }
|
||||
[Parameter] public EventCallback<UpdateBranchRequest> OnEdit { get; set; }
|
||||
[Parameter] public EventCallback<UpdateBranchRequest> OnView { get; set; }
|
||||
|
||||
private List<GetBranchListResponse> _branches = new();
|
||||
private GetBranchListResponse? _selectedBranch;
|
||||
private string _searchString = "";
|
||||
private int _skip = 0;
|
||||
private int _top = 5;
|
||||
private int _totalPage => GetFilteredData().Count() == 0 ? 0 : (int)Math.Ceiling((double)GetFilteredData().Count() / (_top == 0 ? 1 : _top));
|
||||
private int _currentPage => (_top >= GetFilteredData().Count() || _top == 0) ? 1 : (_skip / _top) + 1;
|
||||
private bool _isRefreshing = false;
|
||||
private bool _isExporting = false;
|
||||
|
||||
protected override async Task OnInitializedAsync() => await LoadData();
|
||||
|
||||
private async Task LoadData()
|
||||
{
|
||||
_isRefreshing = true; _selectedBranch = null;
|
||||
StateHasChanged();
|
||||
try
|
||||
{
|
||||
var response = await BranchService.GetBranchListAsync();
|
||||
await Task.Delay(500);
|
||||
if (response != null && response.IsSuccess)
|
||||
{
|
||||
_branches = response.Value ?? new();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isRefreshing = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerable<GetBranchListResponse> GetFilteredData()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_searchString)) return _branches;
|
||||
return _branches.Where(x =>
|
||||
(x.Name?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.Code?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.City?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false) ||
|
||||
(x.StreetAddress?.Contains(_searchString, StringComparison.OrdinalIgnoreCase) ?? false)
|
||||
);
|
||||
}
|
||||
|
||||
private IEnumerable<GetBranchListResponse> GetPagedData() => GetFilteredData().Skip(_skip).Take(_top);
|
||||
|
||||
private async Task ExportToExcel()
|
||||
{
|
||||
_isExporting = true;
|
||||
StateHasChanged();
|
||||
try
|
||||
{
|
||||
await Task.Delay(1000);
|
||||
using (var workbook = new XLWorkbook())
|
||||
{
|
||||
var worksheet = workbook.Worksheets.Add("Branches");
|
||||
var currentRow = 1;
|
||||
|
||||
worksheet.Cell(currentRow, 1).Value = "Branch Code";
|
||||
worksheet.Cell(currentRow, 2).Value = "Branch Name";
|
||||
worksheet.Cell(currentRow, 3).Value = "City";
|
||||
worksheet.Cell(currentRow, 4).Value = "Full Address";
|
||||
worksheet.Cell(currentRow, 5).Value = "Phone";
|
||||
|
||||
var headerRange = worksheet.Range(1, 1, 1, 5);
|
||||
headerRange.Style.Font.Bold = true;
|
||||
headerRange.Style.Fill.BackgroundColor = XLColor.FromHtml("#0D47A1");
|
||||
headerRange.Style.Font.FontColor = XLColor.White;
|
||||
|
||||
foreach (var item in GetFilteredData())
|
||||
{
|
||||
currentRow++;
|
||||
worksheet.Cell(currentRow, 1).Value = item.Code;
|
||||
worksheet.Cell(currentRow, 2).Value = item.Name;
|
||||
worksheet.Cell(currentRow, 3).Value = item.City;
|
||||
worksheet.Cell(currentRow, 4).Value = item.StreetAddress;
|
||||
worksheet.Cell(currentRow, 5).Value = item.Phone;
|
||||
}
|
||||
|
||||
worksheet.Columns().AdjustToContents();
|
||||
|
||||
using (var stream = new MemoryStream())
|
||||
{
|
||||
workbook.SaveAs(stream);
|
||||
var content = Convert.ToBase64String(stream.ToArray());
|
||||
await JSRuntime.InvokeVoidAsync("downloadFile", "Branch_Registry.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", content);
|
||||
Snackbar.Add("Excel exported successfully", Severity.Success);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Export failed: {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isExporting = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnSearchClick()
|
||||
{
|
||||
_skip = 0;
|
||||
_selectedBranch = null;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private void HandleSearchKeyDown(KeyboardEventArgs e)
|
||||
{
|
||||
if (e.Key == "Enter") OnSearchClick();
|
||||
}
|
||||
|
||||
private void OnPageChanged(int page)
|
||||
{
|
||||
if (page >= 1 && page <= _totalPage)
|
||||
{
|
||||
_skip = (page - 1) * _top;
|
||||
_selectedBranch = null;
|
||||
StateHasChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnPageSizeChanged(int size)
|
||||
{
|
||||
_top = size;
|
||||
_skip = 0;
|
||||
_selectedBranch = null;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private async Task InvokeEdit()
|
||||
{
|
||||
if (_selectedBranch == null) return;
|
||||
var res = await BranchService.GetBranchByIdAsync(_selectedBranch.Id);
|
||||
if (res?.Value != null) await OnEdit.InvokeAsync(MapToUpdate(res.Value));
|
||||
}
|
||||
|
||||
private async Task InvokeView()
|
||||
{
|
||||
if (_selectedBranch == null) return;
|
||||
var res = await BranchService.GetBranchByIdAsync(_selectedBranch.Id);
|
||||
if (res?.Value != null) await OnView.InvokeAsync(MapToUpdate(res.Value));
|
||||
}
|
||||
|
||||
private UpdateBranchRequest MapToUpdate(GetBranchByIdResponse d) => new UpdateBranchRequest
|
||||
{
|
||||
Id = d.Id,
|
||||
Code = d.Code,
|
||||
Name = d.Name,
|
||||
Description = d.Description,
|
||||
StreetAddress = d.StreetAddress,
|
||||
City = d.City,
|
||||
StateProvince = d.StateProvince,
|
||||
ZipCode = d.ZipCode,
|
||||
Phone = d.Phone,
|
||||
Email = d.Email,
|
||||
OtherInformation1 = d.OtherInformation1,
|
||||
OtherInformation2 = d.OtherInformation2,
|
||||
OtherInformation3 = d.OtherInformation3,
|
||||
CreatedAt = d.CreatedAt,
|
||||
CreatedBy = d.CreatedBy,
|
||||
UpdatedAt = d.UpdatedAt,
|
||||
UpdatedBy = d.UpdatedBy
|
||||
};
|
||||
|
||||
private async Task OnDelete()
|
||||
{
|
||||
if (_selectedBranch == null) return;
|
||||
var dialog = await DialogService.ShowAsync<_DeleteConfirmation>("", new DialogParameters<_DeleteConfirmation> { { x => x.ContentText, _selectedBranch.Name } });
|
||||
if (!(await dialog.Result).Canceled)
|
||||
{
|
||||
if (await BranchService.DeleteBranchByIdAsync(_selectedBranch.Id))
|
||||
{
|
||||
await LoadData(); Snackbar.Add("Branch deleted successfully", Severity.Success);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
@using Indotalent.ConfigBackEnd.Extensions
|
||||
@using Indotalent.Features.Organization.Branch
|
||||
@using Indotalent.Features.Organization.Branch.Cqrs
|
||||
@using Indotalent.Shared.Utils
|
||||
@using MudBlazor
|
||||
@inject BranchService BranchService
|
||||
@inject ISnackbar Snackbar
|
||||
|
||||
<MudPaper Elevation="0" Square="true" Class="pa-6 mb-3 d-flex align-center justify-space-between" Style="border: 1px solid #DCEBFA;">
|
||||
<div class="d-flex align-center gap-4">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.ArrowBack" OnClick="() => OnCancel.InvokeAsync()" />
|
||||
<div>
|
||||
<MudText Typo="Typo.h5" Style="font-weight: 900; color: #1a1a1a;">@(ReadOnly ? "Branch Details" : "Edit Branch")</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #64748b;">@(ReadOnly ? "Viewing office location profile." : "Modify existing branch information.")</MudText>
|
||||
</div>
|
||||
</div>
|
||||
</MudPaper>
|
||||
|
||||
<MudPaper Elevation="0" Outlined="true" Class="pa-8" Style="border-radius: 0px; border: 1px solid #DCEBFA;">
|
||||
<MudForm @ref="_form" Model="_model">
|
||||
<MudGrid Spacing="3">
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Branch Code</MudText>
|
||||
<MudTextField @bind-Value="_model.Code"
|
||||
For="@(() => _model.Code)"
|
||||
Validation="@(_validator.ValidateValue())"
|
||||
ReadOnly="ReadOnly"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="8">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Branch Name</MudText>
|
||||
<MudTextField @bind-Value="_model.Name"
|
||||
For="@(() => _model.Name)"
|
||||
Validation="@(_validator.ValidateValue())"
|
||||
ReadOnly="ReadOnly"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">City</MudText>
|
||||
<MudTextField @bind-Value="_model.City"
|
||||
For="@(() => _model.City)"
|
||||
Validation="@(_validator.ValidateValue())"
|
||||
ReadOnly="ReadOnly"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="8">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Street Address</MudText>
|
||||
<MudTextField @bind-Value="_model.StreetAddress"
|
||||
For="@(() => _model.StreetAddress)"
|
||||
Validation="@(_validator.ValidateValue())"
|
||||
ReadOnly="ReadOnly"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Phone</MudText>
|
||||
<MudTextField @bind-Value="_model.Phone" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="8">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Email</MudText>
|
||||
<MudTextField @bind-Value="_model.Email"
|
||||
For="@(() => _model.Email)"
|
||||
Validation="@(_validator.ValidateValue())"
|
||||
ReadOnly="ReadOnly"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Description</MudText>
|
||||
<MudTextField @bind-Value="_model.Description" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Other Information 1</MudText>
|
||||
<MudTextField @bind-Value="_model.OtherInformation1" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Other Information 2</MudText>
|
||||
<MudTextField @bind-Value="_model.OtherInformation2" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="4">
|
||||
<MudText Typo="Typo.subtitle2" Class="mb-1">Other Information 3</MudText>
|
||||
<MudTextField @bind-Value="_model.OtherInformation3" ReadOnly="ReadOnly" Variant="Variant.Outlined" Margin="Margin.Dense" FullWidth="true" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" Class="mt-4">
|
||||
<MudText Typo="Typo.button" Color="Color.Primary" Style="font-weight: 800;">Audit History</MudText>
|
||||
<MudDivider Class="mt-2 mb-4" />
|
||||
</MudItem>
|
||||
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Created At</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@DateTimeExtensions.ToString(_model.CreatedAt)</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Created By</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@(!string.IsNullOrEmpty(_model.CreatedBy) ? _model.CreatedBy : "System")</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Last Updated At</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@DateTimeExtensions.ToString(_model.UpdatedAt)</MudText>
|
||||
</MudItem>
|
||||
<MudItem xs="12" sm="6">
|
||||
<MudText Typo="Typo.subtitle2">Last Updated By</MudText>
|
||||
<MudText Typo="Typo.body2" Style="color: #1a1a1a; font-weight: 600;">@(!string.IsNullOrEmpty(_model.UpdatedBy) ? _model.UpdatedBy : "System")</MudText>
|
||||
</MudItem>
|
||||
</MudGrid>
|
||||
|
||||
<div class="d-flex justify-end gap-2 mt-10">
|
||||
<MudButton OnClick="() => OnCancel.InvokeAsync()"
|
||||
Variant="Variant.Outlined"
|
||||
Disabled="_processing"
|
||||
Style="border: 1px solid #e0e0e0; border-radius: 4px; text-transform: none; font-weight: 700;">
|
||||
@(ReadOnly ? "Back to List" : "Cancel")
|
||||
</MudButton>
|
||||
@if (!ReadOnly)
|
||||
{
|
||||
<MudButton Color="Color.Primary"
|
||||
Variant="Variant.Filled"
|
||||
OnClick="Submit"
|
||||
Disabled="_processing"
|
||||
Style="border-radius: 4px; text-transform: none; font-weight: 700;">
|
||||
@if (_processing)
|
||||
{
|
||||
<MudProgressCircular Class="ms-n1" Size="Size.Small" Indeterminate="true" />
|
||||
<MudText Class="ms-2">Updating...</MudText>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudText>Save Changes</MudText>
|
||||
}
|
||||
</MudButton>
|
||||
}
|
||||
</div>
|
||||
</MudForm>
|
||||
</MudPaper>
|
||||
|
||||
@code {
|
||||
[Parameter] public UpdateBranchRequest Data { get; set; } = new();
|
||||
[Parameter] public bool ReadOnly { get; set; } = false;
|
||||
[Parameter] public EventCallback OnCancel { get; set; }
|
||||
[Parameter] public EventCallback OnSuccess { get; set; }
|
||||
|
||||
private MudForm _form = default!;
|
||||
private UpdateBranchValidator _validator = new();
|
||||
private UpdateBranchRequest _model = new();
|
||||
private bool _processing = false;
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
_model = new UpdateBranchRequest
|
||||
{
|
||||
Id = Data.Id,
|
||||
Code = Data.Code,
|
||||
Name = Data.Name,
|
||||
Description = Data.Description,
|
||||
StreetAddress = Data.StreetAddress,
|
||||
City = Data.City,
|
||||
StateProvince = Data.StateProvince,
|
||||
ZipCode = Data.ZipCode,
|
||||
Phone = Data.Phone,
|
||||
Email = Data.Email,
|
||||
OtherInformation1 = Data.OtherInformation1,
|
||||
OtherInformation2 = Data.OtherInformation2,
|
||||
OtherInformation3 = Data.OtherInformation3,
|
||||
CreatedAt = Data.CreatedAt,
|
||||
CreatedBy = Data.CreatedBy,
|
||||
UpdatedAt = Data.UpdatedAt,
|
||||
UpdatedBy = Data.UpdatedBy
|
||||
};
|
||||
}
|
||||
|
||||
private async Task Submit()
|
||||
{
|
||||
if (ReadOnly) return;
|
||||
|
||||
await _form.Validate();
|
||||
if (!_form.IsValid) return;
|
||||
|
||||
_processing = true;
|
||||
try
|
||||
{
|
||||
var response = await BranchService.UpdateBranchAsync(_model);
|
||||
await Task.Delay(500);
|
||||
|
||||
if (response != null && response.IsSuccess)
|
||||
{
|
||||
Snackbar.Add("Branch updated successfully", Severity.Success);
|
||||
await OnSuccess.InvokeAsync();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Snackbar.Add($"Error: {ex.Message}", Severity.Error);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_processing = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user