* Maintain DataModel for User, Role, Function and UserRole

This commit is contained in:
2025-02-20 05:20:30 +01:00
parent c2078d1614
commit cd5990039d
21 changed files with 740 additions and 1 deletions

View File

@@ -0,0 +1,151 @@
@page "/admin/UsersManager"
@using OrdersManagementDataModel.Dtos
@using Syncfusion.Blazor.Grids
@using Action = Syncfusion.Blazor.Grids.Action
@* @inject UserService UserService *@
@* @inject RoleService RoleService *@
@* @inject FunctionService FunctionService *@
<h3>Zarządzanie Użytkownikami i Rolami</h3>
<br />
<!-- Grid dla użytkowników -->
<h4>Użytkownicy</h4>
<SfGrid DataSource="@UserList" AllowPaging="true" ShowColumnMenu="true" Toolbar="@(new List<string> { "Add", "Edit", "Delete", "Cancel", "Update" })">
<GridColumns>
<GridColumn Field="@nameof(UserDto.Id)" IsPrimaryKey="true" HeaderText="ID" Width="70"></GridColumn>
<GridColumn Field="@nameof(UserDto.Login)" HeaderText="Login" Width="100"></GridColumn>
<GridColumn Field="@nameof(UserDto.Email)" HeaderText="Email" Width="150"></GridColumn>
<GridColumn Field="@nameof(UserDto.FirstName)" HeaderText="Imię" Width="100"></GridColumn>
<GridColumn Field="@nameof(UserDto.LastName)" HeaderText="Nazwisko" Width="100"></GridColumn>
<GridColumn Field="@nameof(UserDto.IsActive)" HeaderText="Aktywny" Width="80"></GridColumn>
<GridColumn Field="@nameof(UserDto.CreatedDate)" HeaderText="Utworzono" Format="d" Width="120"></GridColumn>
</GridColumns>
<GridEditSettings AllowDeleting="true" ShowDeleteConfirmDialog="true" AllowAdding="true" AllowEditing="true" Mode="EditMode.Normal"></GridEditSettings>
<GridEvents OnActionBegin="UserActionBegin" OnActionComplete="UserActionComplete" TValue="UserDto"></GridEvents>
</SfGrid>
<br />
<!-- Grid dla ról -->
<h4>Role</h4>
<SfGrid DataSource="@Roles" AllowPaging="true" ShowColumnMenu="true" Toolbar="@(new List<string> { "Add", "Edit", "Delete", "Cancel", "Update" })">
<GridColumns>
<GridColumn Field="@nameof(RoleDto.Id)" IsPrimaryKey="true" HeaderText="ID" Width="70"></GridColumn>
<GridColumn Field="@nameof(RoleDto.Name)" HeaderText="Nazwa" Width="150"></GridColumn>
</GridColumns>
<GridEditSettings AllowDeleting="true" ShowDeleteConfirmDialog="true" AllowAdding="true" AllowEditing="true" Mode="EditMode.Normal"></GridEditSettings>
<GridEvents OnActionBegin="RoleActionBegin" OnActionComplete="RoleActionComplete" TValue="RoleDto"></GridEvents>
</SfGrid>
<br />
<!-- Grid dla funkcji -->
<h4>Funkcje</h4>
<SfGrid DataSource="@Functions" AllowPaging="true" ShowColumnMenu="true" Toolbar="@(new List<string> { "Add", "Edit", "Delete", "Cancel", "Update" })">
<GridColumns>
<GridColumn Field="@nameof(FunctionDto.Id)" IsPrimaryKey="true" HeaderText="ID" Width="70"></GridColumn>
<GridColumn Field="@nameof(FunctionDto.RoleId)" HeaderText="ID Roli" Width="70"></GridColumn>
<GridColumn Field="@nameof(FunctionDto.Name)" HeaderText="Nazwa Funkcji" Width="200"></GridColumn>
</GridColumns>
<GridEditSettings AllowDeleting="true" ShowDeleteConfirmDialog="true" AllowAdding="true" AllowEditing="true" Mode="EditMode.Normal"></GridEditSettings>
<GridEvents OnActionBegin="FunctionActionBegin" OnActionComplete="FunctionActionComplete" TValue="FunctionDto"></GridEvents>
</SfGrid>
@code {
private List<UserDto> UserList { get; set; } = new();
private List<RoleDto> Roles { get; set; } = new();
private List<FunctionDto> Functions { get; set; } = new();
protected override async Task OnInitializedAsync()
{
await LoadUsers();
await LoadRoles();
await LoadFunctions();
}
// Użytkownicy
private async Task UserActionBegin(ActionEventArgs<UserDto> args)
{
// if (args.RequestType.Equals(Action.Delete))
// {
// await UserService.DeleteUserAsync(args.Data.Id);
// }
// else if (args.RequestType.Equals(Action.Add))
// {
// args.Data.RowPointer = Guid.NewGuid();
// }
}
private async Task UserActionComplete(ActionEventArgs<UserDto> args)
{
switch (args.RequestType)
{
case Action.Delete:
case Action.Save:
await LoadUsers();
break;
}
}
private async Task LoadUsers()
{
//Users = (await UserService.GetUsersAsync() ?? Array.Empty<UserDto>()).ToList();
}
// Role
private async Task RoleActionBegin(ActionEventArgs<RoleDto> args)
{
// if (args.RequestType.Equals(Action.Delete))
// {
// await RoleService.DeleteRoleAsync(args.Data.Id);
// }
// else if (args.RequestType.Equals(Action.Add))
// {
// args.Data.RowPointer = Guid.NewGuid();
// }
}
private async Task RoleActionComplete(ActionEventArgs<RoleDto> args)
{
switch (args.RequestType)
{
case Action.Delete:
case Action.Save:
await LoadRoles();
break;
}
}
private async Task LoadRoles()
{
//Roles = (await RoleService.GetRolesAsync() ?? Array.Empty<RoleDto>()).ToList();
}
// Funkcje
private async Task FunctionActionBegin(ActionEventArgs<FunctionDto> args)
{
if (args.RequestType.Equals(Action.Delete))
{
//await FunctionService.DeleteFunctionAsync(args.Data.Id);
}
else if (args.RequestType.Equals(Action.Add))
{
args.Data.RowPointer = Guid.NewGuid();
}
}
private async Task FunctionActionComplete(ActionEventArgs<FunctionDto> args)
{
switch (args.RequestType)
{
case Action.Delete:
case Action.Save:
await LoadFunctions();
break;
}
}
private async Task LoadFunctions()
{
//Functions = (await FunctionService.GetFunctionsAsync() ?? Array.Empty<FunctionDto>()).ToList();
}
}

View File

@@ -57,7 +57,9 @@
AllowSelection="true" AllowSelection="true"
TValue="ScheduleOrderDetailDetailDto" TValue="ScheduleOrderDetailDetailDto"
DataSource="@_scheduleOrderDetailsDetails" DataSource="@_scheduleOrderDetailsDetails"
EnableAdaptiveUI="true"> EnableAdaptiveUI="true"
AdaptiveUIMode="AdaptiveMode.Both">
<GridEvents TValue="ScheduleOrderDetailDetailDto" RowDataBound="OnRowDataBound" />
<GridTemplates> <GridTemplates>
<DetailTemplate> <DetailTemplate>
@{ @{
@@ -136,4 +138,11 @@
SelectOrderDetail(scheduleOrderDetail); SelectOrderDetail(scheduleOrderDetail);
} }
private void OnRowDataBound(RowDataBoundEventArgs<ScheduleOrderDetailDetailDto> args)
{
if (args.Data.QtyType == "83" || args.Data.QtyType == "84")
{
args.Row.AddClass(["highlight-red"]);
}
}
} }

View File

@@ -63420,3 +63420,12 @@ html, body {
height: calc(100vh - 150px) !important; height: calc(100vh - 150px) !important;
} }
} }
.e-grid .e-row.highlight-red {
background-color: #ffcccc !important; /* Jasnoczerwone tło */
color: #333; /* Kontrastowy kolor tekstu */
}
/* Opcjonalnie, jeśli chcesz zmienić kolor tekstu w komórkach */
.e-grid .e-row.highlight-red .e-rowcell {
background-color: #ffcccc !important;
}

View File

@@ -0,0 +1,9 @@
namespace OrdersManagementDataModel.Dtos;
public class FunctionDto
{
public int Id { get; set; }
public int RoleId { get; set; }
public string Name { get; set; }
public Guid RowPointer { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace OrdersManagementDataModel.Dtos;
public class RoleDto
{
public int Id { get; set; }
public string Name { get; set; }
public Guid RowPointer { get; set; }
}

View File

@@ -0,0 +1,23 @@
namespace OrdersManagementDataModel.Dtos;
public class UserDto
{
public int Id { get; set; }
public string Login { get; set; }
public string PasswordHash { get; set; }
public bool IsTemporaryPassword { get; set; }
public bool IsActive { get; set; }
public DateTime? ActiveFrom { get; set; }
public DateTime? ActiveTo { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime? LastLoginDate { get; set; }
public int FailedLoginAttempts { get; set; }
public bool IsLocked { get; set; }
public DateTime? LockoutEndDate { get; set; }
public Guid RowPointer { get; set; }
public ICollection<UserRoleDto> UserRoles { get; set; } = new List<UserRoleDto>();
}

View File

@@ -0,0 +1,12 @@
namespace OrdersManagementDataModel.Dtos;
public class UserRoleDto
{
public int UserId { get; set; }
public int RoleId { get; set; }
public Guid RowPointer { get; set; }
public virtual UserDto User { get; set; }
public virtual RoleDto Role { get; set; }
}

View File

@@ -0,0 +1,11 @@
namespace OrdersManagementDataModel.Entities;
public class Function
{
public int Id { get; set; }
public int RoleId { get; set; }
public string Name { get; set; }
public Guid RowPointer { get; set; }
public Role Role { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace OrdersManagementDataModel.Entities;
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
public Guid RowPointer { get; set; }
}

View File

@@ -0,0 +1,23 @@
namespace OrdersManagementDataModel.Entities;
public class User
{
public int Id { get; set; }
public string Login { get; set; }
public string PasswordHash { get; set; }
public bool IsTemporaryPassword { get; set; }
public bool IsActive { get; set; }
public DateTime? ActiveFrom { get; set; }
public DateTime? ActiveTo { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime? LastLoginDate { get; set; }
public int FailedLoginAttempts { get; set; }
public bool IsLocked { get; set; }
public DateTime? LockoutEndDate { get; set; }
public Guid RowPointer { get; set; }
public ICollection<UserRole> UserRoles { get; set; } = new List<UserRole>();
}

View File

@@ -0,0 +1,11 @@
namespace OrdersManagementDataModel.Entities;
public class UserRole
{
public int UserId { get; set; }
public int RoleId { get; set; }
public Guid RowPointer { get; set; }
public virtual User User { get; set; }
public virtual Role Role { get; set; }
}

View File

@@ -11,5 +11,9 @@ public class MappingProfile : Profile
{ {
CreateMap<TaskScheduler, TaskSchedulerDto>().ReverseMap(); CreateMap<TaskScheduler, TaskSchedulerDto>().ReverseMap();
CreateMap<TaskSchedulerDetail, TaskSchedulerDetailDto>().ReverseMap(); CreateMap<TaskSchedulerDetail, TaskSchedulerDetailDto>().ReverseMap();
CreateMap<User, UserDto>().ReverseMap();
CreateMap<Role, RoleDto>().ReverseMap();
CreateMap<Function, FunctionDto>().ReverseMap();
CreateMap<UserRole, UserRoleDto>().ReverseMap();
} }
} }

View File

@@ -25,6 +25,11 @@ public class OrdersManagementDbContext : DbContext
public DbSet<TaskScheduler> TaskSchedulers { get; set; } public DbSet<TaskScheduler> TaskSchedulers { get; set; }
public DbSet<TaskSchedulerDetail> TaskSchedulerDetails { get; set; } public DbSet<TaskSchedulerDetail> TaskSchedulerDetails { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<Function> Functions { get; set; }
public DbSet<UserRole> UserRoles { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
@@ -67,5 +72,80 @@ public class OrdersManagementDbContext : DbContext
.HasForeignKey(d => d.FkTaskScheduler) .HasForeignKey(d => d.FkTaskScheduler)
.HasConstraintName("FK_TaskSchedulerDetails_TaskScheduler"); .HasConstraintName("FK_TaskSchedulerDetails_TaskScheduler");
}); });
modelBuilder.Entity<User>(entity =>
{
entity.ToTable("User");
entity.HasKey(e => e.Id);
entity.Property(e => e.Id).HasColumnName("Id");
entity.Property(e => e.Login).HasColumnName("Login").HasMaxLength(50).IsRequired();
entity.Property(e => e.PasswordHash).HasColumnName("PasswordHash").HasMaxLength(256).IsRequired();
entity.Property(e => e.IsTemporaryPassword).HasColumnName("IsTemporaryPassword").IsRequired();
entity.Property(e => e.IsActive).HasColumnName("IsActive").IsRequired();
entity.Property(e => e.ActiveFrom).HasColumnName("ActiveFrom");
entity.Property(e => e.ActiveTo).HasColumnName("ActiveTo");
entity.Property(e => e.Email).HasColumnName("Email").HasMaxLength(100);
entity.Property(e => e.FirstName).HasColumnName("FirstName").HasMaxLength(50);
entity.Property(e => e.LastName).HasColumnName("LastName").HasMaxLength(50);
entity.Property(e => e.CreatedDate).HasColumnName("CreatedDate").IsRequired();
entity.Property(e => e.LastLoginDate).HasColumnName("LastLoginDate");
entity.Property(e => e.FailedLoginAttempts).HasColumnName("FailedLoginAttempts").IsRequired();
entity.Property(e => e.IsLocked).HasColumnName("IsLocked").IsRequired();
entity.Property(e => e.LockoutEndDate).HasColumnName("LockoutEndDate");
entity.Property(e => e.RowPointer).HasColumnName("RowPointer").IsRequired();
});
// Konfiguracja dla Role (już zdefiniowana wcześniej)
modelBuilder.Entity<Role>(entity =>
{
entity.ToTable("Role");
entity.HasKey(e => e.Id);
entity.Property(e => e.Id).HasColumnName("Id");
entity.Property(e => e.Name).HasColumnName("Name").HasMaxLength(50).IsRequired();
entity.Property(e => e.RowPointer).HasColumnName("RowPointer").IsRequired();
});
// Konfiguracja dla Function (już zdefiniowana wcześniej)
modelBuilder.Entity<Function>(entity =>
{
entity.ToTable("Function");
entity.HasKey(e => e.Id);
entity.Property(e => e.Id).HasColumnName("Id");
entity.Property(e => e.RoleId).HasColumnName("RoleId").IsRequired();
entity.Property(e => e.Name).HasColumnName("Name").HasMaxLength(100).IsRequired();
entity.Property(e => e.RowPointer).HasColumnName("RowPointer").IsRequired();
entity.HasOne(e => e.Role)
.WithMany()
.HasForeignKey(e => e.RoleId)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_Function_Role");
});
// Konfiguracja dla UserRole
modelBuilder.Entity<UserRole>(entity =>
{
entity.ToTable("UserRole");
entity.HasKey(e => new { e.UserId, e.RoleId });
entity.Property(e => e.UserId).HasColumnName("UserId").IsRequired();
entity.Property(e => e.RoleId).HasColumnName("RoleId").IsRequired();
entity.Property(e => e.RowPointer).HasColumnName("RowPointer").IsRequired();
entity.HasOne(e => e.User)
.WithMany()
.HasForeignKey(e => e.UserId)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_UserRole_User");
entity.HasOne(e => e.Role)
.WithMany()
.HasForeignKey(e => e.RoleId)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_UserRole_Role");
});
} }
} }

View File

@@ -0,0 +1,95 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using OrdersManagementDataModel.Dtos;
using OrdersManagementDataModel.Entities;
namespace OrdersManagementDataModel.Services;
public class FunctionService(OrdersManagementDbContext context, IMapper mapper) : IFunctionService
{
public async Task<IEnumerable<FunctionDto>> GetFunctions()
{
IList<FunctionDto> functions = await context.Functions.Select(x => mapper.Map<FunctionDto>(x)).ToListAsync();
return functions;
}
public async Task<FunctionDto?> GetFunctionById(Guid id)
{
FunctionDto? function = await context.Functions.Where(x => x.RowPointer == id)
.Select(x => mapper.Map<FunctionDto>(x)).FirstOrDefaultAsync();
return function;
}
public async Task<FunctionDto?> GetFunctionByName(string name)
{
FunctionDto? function = await context.Functions.Where(x => x.Name == name)
.Select(x => mapper.Map<FunctionDto>(x)).FirstOrDefaultAsync();
return function;
}
public async Task<int> AddFunction(FunctionDto functionDto)
{
Function function = new Function
{
Name = functionDto.Name,
RowPointer = Guid.NewGuid()
};
context.Functions.Add(function);
return await context.SaveChangesAsync();
}
public async Task<int> DeleteFunction(Guid id)
{
Function? function = await context.Functions.Where(x => x.RowPointer == id).FirstOrDefaultAsync() ?? null;
if (function == null) return 0;
context.Functions.Remove(function);
return await context.SaveChangesAsync();
}
public async Task<int> UpdateFunction(FunctionDto functionDto)
{
Function function = mapper.Map<Function>(functionDto);
context.Functions.Update(function);
return await context.SaveChangesAsync();
}
public async Task<IEnumerable<FunctionDto>> GetFunctionsByRoleId(Guid roleId)
{
Role? role = await context.Roles.FirstOrDefaultAsync(x => x.RowPointer == roleId);
IList<FunctionDto> functions = await context.Functions.Where(x => role != null && x.RoleId == role.Id)
.Select(x => mapper.Map<FunctionDto>(x)).ToListAsync();
return functions;
}
public async Task<int> AddFunctionToRole(Guid roleId, Guid functionId)
{
Role? role = await context.Roles.FirstOrDefaultAsync(x => x.RowPointer == roleId);
Function? function = await context.Functions.FirstOrDefaultAsync(x => x.RowPointer == functionId);
if (role == null || function == null) return 0;
function.RoleId = role.Id;
context.Functions.Update(function);
return await context.SaveChangesAsync();
}
public async Task<int> RemoveFunctionFromRole(Guid roleId, Guid functionId)
{
Role? role = await context.Roles.FirstOrDefaultAsync(x => x.RowPointer == roleId);
Function? function = await context.Functions.FirstOrDefaultAsync(x => x.RowPointer == functionId);
if (role == null || function == null) return 0;
function.RoleId = 0;
context.Functions.Update(function);
return await context.SaveChangesAsync();
}
}

View File

@@ -0,0 +1,16 @@
using OrdersManagementDataModel.Dtos;
namespace OrdersManagementDataModel.Services;
public interface IFunctionService
{
Task<IEnumerable<FunctionDto>> GetFunctions();
Task<FunctionDto?> GetFunctionById(Guid id);
Task<FunctionDto?> GetFunctionByName(string name);
Task<int> AddFunction(FunctionDto functionDto);
Task<int> DeleteFunction(Guid id);
Task<int> UpdateFunction(FunctionDto functionDto);
Task<IEnumerable<FunctionDto>> GetFunctionsByRoleId(Guid roleId);
Task<int> AddFunctionToRole(Guid roleId, Guid functionId);
Task<int> RemoveFunctionFromRole(Guid roleId, Guid functionId);
}

View File

@@ -0,0 +1,12 @@
using OrdersManagementDataModel.Dtos;
namespace OrdersManagementDataModel.Services;
public interface IRoleService
{
Task<IEnumerable<RoleDto>> GetRoles();
Task<RoleDto?> GetRoleById(Guid id);
Task<RoleDto?> GetRoleByName(string name);
Task<int> AddRole(RoleDto roleDto);
Task<int> DeleteRole(Guid id);
}

View File

@@ -0,0 +1,15 @@
using OrdersManagementDataModel.Dtos;
namespace OrdersManagementDataModel.Services;
public interface IUserRoleService
{
Task<IEnumerable<UserRoleDto>> GetUserRoles();
Task<UserRoleDto?> GetUserRoleById(Guid id);
Task<int> AddUserRole(UserRoleDto userRoleDto);
Task<int> DeleteUserRole(Guid id);
Task<int> UpdateUserRole(UserRoleDto userRoleDto);
Task<IEnumerable<UserRoleDto>> GetUserRolesByUserId(Guid userId);
Task<IEnumerable<UserRoleDto>> GetUserRolesByRoleId(Guid roleId);
Task<int> AddRoleToUser(Guid userId, Guid roleId);
}

View File

@@ -0,0 +1,15 @@
using OrdersManagementDataModel.Dtos;
namespace OrdersManagementDataModel.Services;
public interface IUserService
{
Task<IEnumerable<UserDto>> GetUsers();
Task<UserDto?> GetUserById(Guid id);
Task<UserDto?> GetUserByUsername(string username);
Task<int> AddUser(UserDto userDto);
Task<int> UpdateUser(UserDto userDto);
Task<int> DeleteUser(Guid id);
Task<IList<UserRoleDto>> GetUserRoles(Guid userId);
Task<UserDto?> GetUserByLoginAndPassword(string login, string password);
}

View File

@@ -0,0 +1,54 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using OrdersManagementDataModel.Dtos;
using OrdersManagementDataModel.Entities;
namespace OrdersManagementDataModel.Services;
public class RoleService(OrdersManagementDbContext context, IMapper mapper) : IRoleService
{
public async Task<IEnumerable<RoleDto>> GetRoles()
{
IList<RoleDto> roles = await context.Roles.Select(x => mapper.Map<RoleDto>(x)).ToListAsync();
return roles;
}
public async Task<RoleDto?> GetRoleById(Guid id)
{
RoleDto? role = await context.Roles.Where(x => x.RowPointer == id)
.Select(x => mapper.Map<RoleDto>(x)).FirstOrDefaultAsync();
return role;
}
public async Task<RoleDto?> GetRoleByName(string name)
{
RoleDto? role = await context.Roles.Where(x => x.Name == name)
.Select(x => mapper.Map<RoleDto>(x)).FirstOrDefaultAsync();
return role;
}
public async Task<int> AddRole(RoleDto roleDto)
{
Role role = new Role
{
Name = roleDto.Name,
RowPointer = Guid.NewGuid()
};
context.Roles.Add(role);
return await context.SaveChangesAsync();
}
public async Task<int> DeleteRole(Guid id)
{
Role? role = await context.Roles.Where(x => x.RowPointer == id).FirstOrDefaultAsync() ?? null;
if (role == null) return 0;
context.Roles.Remove(role);
return await context.SaveChangesAsync();
}
}

View File

@@ -0,0 +1,86 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using OrdersManagementDataModel.Dtos;
using OrdersManagementDataModel.Entities;
namespace OrdersManagementDataModel.Services;
public class UserRoleService(OrdersManagementDbContext context, IMapper mapper) : IUserRoleService
{
public async Task<IEnumerable<UserRoleDto>> GetUserRoles()
{
IList<UserRoleDto> userRoles = await context.UserRoles.Select(x => mapper.Map<UserRoleDto>(x)).ToListAsync();
return userRoles;
}
public async Task<UserRoleDto?> GetUserRoleById(Guid id)
{
UserRoleDto? userRole = await context.UserRoles.Where(x => x.RowPointer == id)
.Select(x => mapper.Map<UserRoleDto>(x)).FirstOrDefaultAsync();
return userRole;
}
public Task<int> AddUserRole(UserRoleDto userRoleDto)
{
UserRole userRole = mapper.Map<UserRole>(userRoleDto);
context.UserRoles.Add(userRole);
return context.SaveChangesAsync();
}
public async Task<int> DeleteUserRole(Guid id)
{
UserRole? userRole = await context.UserRoles.Where(x => x.RowPointer == id).FirstOrDefaultAsync() ?? null;
if (userRole == null) return 0;
context.UserRoles.Remove(userRole);
return await context.SaveChangesAsync();
}
public async Task<int> UpdateUserRole(UserRoleDto userRoleDto)
{
UserRole userRole = mapper.Map<UserRole>(userRoleDto);
context.UserRoles.Update(userRole);
return await context.SaveChangesAsync();
}
public async Task<IEnumerable<UserRoleDto>> GetUserRolesByUserId(Guid userId)
{
IList<UserRoleDto> userRoles = await context.UserRoles
.Where(x => x.User.RowPointer == userId)
.Select(x => mapper.Map<UserRoleDto>(x))
.ToListAsync();
return userRoles;
}
public async Task<IEnumerable<UserRoleDto>> GetUserRolesByRoleId(Guid roleId)
{
IList<UserRoleDto> userRoles = await context.UserRoles
.Where(x => x.Role.RowPointer == roleId)
.Select(x => mapper.Map<UserRoleDto>(x))
.ToListAsync();
return userRoles;
}
public async Task<int> AddRoleToUser(Guid userId, Guid roleId)
{
User? user = await context.Users.FirstOrDefaultAsync(x => x.RowPointer == userId);
Role? role = await context.Roles.FirstOrDefaultAsync(x => x.RowPointer == roleId);
if (user == null || role == null) return 0;
UserRole userRole = new UserRole
{
User = user,
Role = role,
RowPointer = Guid.NewGuid()
};
context.UserRoles.Add(userRole);
return await context.SaveChangesAsync();
}
}

View File

@@ -0,0 +1,88 @@
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using OrdersManagementDataModel.Dtos;
using OrdersManagementDataModel.Entities;
namespace OrdersManagementDataModel.Services;
public class UserService(OrdersManagementDbContext context, IMapper mapper) : IUserService
{
public async Task<IEnumerable<UserDto>> GetUsers()
{
IList<UserDto> users = await context.Users.Select(x => mapper.Map<UserDto>(x)).ToListAsync();
return users;
}
public async Task<UserDto?> GetUserById(Guid id)
{
UserDto? user = await context.Users.Where(x => x.RowPointer == id)
.Select(x => mapper.Map<UserDto>(x)).FirstOrDefaultAsync();
return user;
}
public async Task<UserDto?> GetUserByUsername(string username)
{
UserDto? user = await context.Users.Where(x => x.Login == username)
.Select(x => mapper.Map<UserDto>(x)).FirstOrDefaultAsync();
return user;
}
public async Task<int> AddUser(UserDto userDto)
{
User user = new User
{
Login = userDto.Login,
PasswordHash = userDto.PasswordHash,
IsTemporaryPassword = true,
IsActive = true,
Email = userDto.Email,
RowPointer = Guid.NewGuid(),
CreatedDate = DateTime.Now,
ActiveFrom = DateTime.Now,
FirstName = userDto.FirstName,
LastName = userDto.LastName
};
context.Users.Add(user);
return await context.SaveChangesAsync();
}
public async Task<int> UpdateUser(UserDto userDto)
{
User user = mapper.Map<User>(userDto);
context.Users.Update(user);
return await context.SaveChangesAsync();
}
public async Task<int> DeleteUser(Guid id)
{
User? user = await context.Users.Where(x => x.RowPointer == id).FirstOrDefaultAsync() ?? null;
if (user == null) return 0;
context.Users.Remove(user);
return await context.SaveChangesAsync();
}
public async Task<IList<UserRoleDto>> GetUserRoles(Guid userId)
{
List<UserRoleDto> userRoles = await context.Users
.Where(x => x.RowPointer == userId)
.SelectMany(x => x.UserRoles)
.Select(x => mapper.Map<UserRoleDto>(x))
.ToListAsync();
return userRoles;
}
public async Task<UserDto?> GetUserByLoginAndPassword(string login, string password)
{
UserDto? user = await context.Users.Where(x => x.Login == login && x.PasswordHash == password)
.Select(x => mapper.Map<UserDto>(x)).FirstOrDefaultAsync();
return user;
}
}