using System.Collections; using BasicDotnetTemplate.MainProject.Core.Database; using BasicDotnetTemplate.MainProject.Models.Api.Data.Role; using BasicDotnetTemplate.MainProject.Models.Database.SqlServer; using Microsoft.EntityFrameworkCore; namespace BasicDotnetTemplate.MainProject.Services; public interface IRoleService { Task GetRoleByIdAsync(int id); Task GetRoleByGuidAsync(string guid); Task CheckIfNameIsValid(string name, string? guid = ""); Task CreateRole(CreateRoleRequestData data); Task GetRoleForUser(string? guid); } public class RoleService : BaseService, IRoleService { public RoleService( IHttpContextAccessor httpContextAccessor, IConfiguration configuration, SqlServerContext sqlServerContext ) : base(httpContextAccessor, configuration, sqlServerContext) { } private IQueryable GetRolesQueryable() { return this._sqlServerContext.Roles.Where(x => !x.IsDeleted); } private IQueryable GetRoleByNameQueryable(string name) { return this.GetRolesQueryable().Where(x => x.Name.ToString() == name.ToString() ); } private Role CreateRoleData(CreateRoleRequestData data) { Role role = new() { CreationTime = DateTime.UtcNow, CreationUserId = this.GetCurrentUserId(), IsDeleted = false, Guid = Guid.NewGuid().ToString(), Name = data.Name, IsNotEditable = data.IsNotEditable }; return role; } public async Task GetRoleByIdAsync(int id) { return await this.GetRolesQueryable().Where(x => x.Id == id).FirstOrDefaultAsync(); } public async Task GetRoleByGuidAsync(string guid) { return await this.GetRolesQueryable().Where(x => x.Guid == guid).FirstOrDefaultAsync(); } public async Task CheckIfNameIsValid(string name, string? guid = "") { var valid = false; Role? role = await this.GetRoleByNameQueryable(name).FirstOrDefaultAsync(); if (role != null) { if (!String.IsNullOrEmpty(guid)) { valid = role.Guid == guid && role.Name == name; } } else { valid = true; } return valid; } public async Task CreateRole(CreateRoleRequestData data) { Role? role = null; using (var transaction = _sqlServerContext.Database.BeginTransactionAsync()) { var tempRole = this.CreateRoleData(data); await _sqlServerContext.Roles.AddAsync(tempRole); await _sqlServerContext.SaveChangesAsync(); await (await transaction).CommitAsync(); role = tempRole; } return role; } public async Task GetRoleForUser(string? guid) { Role? role = null; if (String.IsNullOrEmpty(guid)) { role = await this.GetRoleByNameQueryable("Default").FirstOrDefaultAsync(); } else { role = await this.GetRoleByGuidAsync(guid); } return role; } }