refactor(console): remove Repository layer, use Manager pattern

- Remove Repositories folder (IUserRepository, UserRepository, IRoleRepository, RoleRepository)
- Remove Managers folder (old TenantManager)
- Remove Datas folder (old ApplicationDbContext)
- Remove Models/Entities folder (old domain entities)
- Remove EntityConfigurations folder
- Update Services to use UserManager/RoleManager/PlatformDbContext directly
- Update DTOs to use Platform's TenantStatus
This commit is contained in:
movingsam 2026-02-21 13:52:37 +08:00
parent f33acacbbc
commit fc8fcc7de2
21 changed files with 130 additions and 870 deletions

View File

@ -1,69 +0,0 @@
using Fengling.Console.Models.Entities;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Reflection;
namespace Fengling.Console.Datas;
public class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: IdentityDbContext<ApplicationUser, ApplicationRole, long>(options)
{
public DbSet<Tenant> Tenants { get; set; }
public DbSet<AccessLog> AccessLogs { get; set; }
public DbSet<AuditLog> AuditLogs { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
builder.Entity<ApplicationUser>(entity =>
{
entity.Property(e => e.RealName).HasMaxLength(100);
entity.Property(e => e.Phone).HasMaxLength(20);
entity.HasIndex(e => e.Phone).IsUnique();
});
builder.Entity<ApplicationRole>(entity => { entity.Property(e => e.Description).HasMaxLength(200); });
builder.Entity<AccessLog>(entity =>
{
entity.HasKey(e => e.Id);
entity.HasIndex(e => e.CreatedAt);
entity.HasIndex(e => e.UserName);
entity.HasIndex(e => e.TenantId);
entity.HasIndex(e => e.Action);
entity.HasIndex(e => e.Status);
entity.Property(e => e.UserName).HasMaxLength(50);
entity.Property(e => e.TenantId).HasMaxLength(50);
entity.Property(e => e.Action).HasMaxLength(20);
entity.Property(e => e.Resource).HasMaxLength(200);
entity.Property(e => e.Method).HasMaxLength(10);
entity.Property(e => e.IpAddress).HasMaxLength(50);
entity.Property(e => e.UserAgent).HasMaxLength(500);
entity.Property(e => e.Status).HasMaxLength(20);
});
builder.Entity<AuditLog>(entity =>
{
entity.HasKey(e => e.Id);
entity.HasIndex(e => e.CreatedAt);
entity.HasIndex(e => e.Operator);
entity.HasIndex(e => e.TenantId);
entity.HasIndex(e => e.Operation);
entity.HasIndex(e => e.Action);
entity.Property(e => e.Operator).HasMaxLength(50);
entity.Property(e => e.TenantId).HasMaxLength(50);
entity.Property(e => e.Operation).HasMaxLength(20);
entity.Property(e => e.Action).HasMaxLength(20);
entity.Property(e => e.TargetType).HasMaxLength(50);
entity.Property(e => e.TargetName).HasMaxLength(100);
entity.Property(e => e.IpAddress).HasMaxLength(50);
entity.Property(e => e.Description).HasMaxLength(500);
entity.Property(e => e.Status).HasMaxLength(20);
});
}
}

View File

@ -1,36 +0,0 @@
namespace Fengling.Console.EntityConfigurations;
using Fengling.Console.Models.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public class TenantEntityTypeConfiguration : IEntityTypeConfiguration<Tenant>
{
public void Configure(EntityTypeBuilder<Tenant> builder)
{
builder.ToTable("Tenants");
builder.HasKey(x => x.Id);
builder.Property(x => x.Id)
.ValueGeneratedOnAdd();
builder.Property(x => x.TenantCode)
.IsRequired()
.HasMaxLength(50);
builder.Property(x => x.Name)
.IsRequired()
.HasMaxLength(100);
builder.Property(x => x.ContactName)
.IsRequired()
.HasMaxLength(50);
builder.Property(x => x.ContactEmail)
.IsRequired()
.HasMaxLength(100);
builder.HasIndex(x => x.TenantCode).IsUnique();
builder.HasIndex(x => x.Name);
}
}

View File

@ -1,88 +0,0 @@
using Fengling.Console.Models.Entities;
using Fengling.Console.Stores;
using Microsoft.AspNetCore.Identity;
namespace Fengling.Console.Managers;
public interface ITenantManager
{
Task<Tenant?> FindByIdAsync(int tenantId, CancellationToken cancellationToken = default);
Task<Tenant?> FindByTenantCodeAsync(string tenantCode, CancellationToken cancellationToken = default);
Task<IList<Tenant>> GetAllAsync(CancellationToken cancellationToken = default);
Task<IList<Tenant>> GetPagedAsync(int page, int pageSize, string? name = null, string? tenantCode = null, TenantStatus? status = null, CancellationToken cancellationToken = default);
Task<int> GetCountAsync(string? name = null, string? tenantCode = null, TenantStatus? status = null, CancellationToken cancellationToken = default);
Task<IdentityResult> CreateAsync(Tenant tenant, CancellationToken cancellationToken = default);
Task<IdentityResult> UpdateAsync(Tenant tenant, CancellationToken cancellationToken = default);
Task<IdentityResult> DeleteAsync(Tenant tenant, CancellationToken cancellationToken = default);
Task<int> GetUserCountAsync(int tenantId, CancellationToken cancellationToken = default);
Task<IdentityResult> SetTenantCodeAsync(Tenant tenant, string code, CancellationToken cancellationToken = default);
}
public class TenantManager : ITenantManager
{
private readonly ITenantStore<Tenant> _store;
public TenantManager(ITenantStore<Tenant> store)
{
_store = store;
}
public virtual async Task<Tenant?> FindByIdAsync(int tenantId, CancellationToken cancellationToken = default)
{
return await _store.FindByIdAsync(tenantId, cancellationToken);
}
public virtual async Task<Tenant?> FindByTenantCodeAsync(string tenantCode, CancellationToken cancellationToken = default)
{
return await _store.FindByTenantCodeAsync(tenantCode, cancellationToken);
}
public virtual async Task<IList<Tenant>> GetAllAsync(CancellationToken cancellationToken = default)
{
return await _store.GetAllAsync(cancellationToken);
}
public virtual async Task<IList<Tenant>> GetPagedAsync(int page, int pageSize, string? name = null,
string? tenantCode = null, TenantStatus? status = null, CancellationToken cancellationToken = default)
{
return await _store.GetPagedAsync(page, pageSize, name, tenantCode, status, cancellationToken);
}
public virtual async Task<int> GetCountAsync(string? name = null, string? tenantCode = null,
TenantStatus? status = null, CancellationToken cancellationToken = default)
{
return await _store.GetCountAsync(name, tenantCode, status, cancellationToken);
}
public virtual async Task<IdentityResult> CreateAsync(Tenant tenant, CancellationToken cancellationToken = default)
{
return await _store.CreateAsync(tenant, cancellationToken);
}
public virtual async Task<IdentityResult> UpdateAsync(Tenant tenant, CancellationToken cancellationToken = default)
{
return await _store.UpdateAsync(tenant, cancellationToken);
}
public virtual async Task<IdentityResult> DeleteAsync(Tenant tenant, CancellationToken cancellationToken = default)
{
return await _store.DeleteAsync(tenant, cancellationToken);
}
public virtual async Task<int> GetUserCountAsync(int tenantId, CancellationToken cancellationToken = default)
{
return await _store.GetUserCountAsync(tenantId, cancellationToken);
}
public virtual async Task<IdentityResult> SetTenantCodeAsync(Tenant tenant, string code, CancellationToken cancellationToken = default)
{
var existing = await _store.FindByTenantCodeAsync(code, cancellationToken);
if (existing != null && existing.Id != tenant.Id)
{
return IdentityResult.Failed(new IdentityError { Description = "租户编码已存在" });
}
await _store.SetTenantCodeAsync(tenant, code, cancellationToken);
return IdentityResult.Success;
}
}

View File

@ -1,10 +1,10 @@
using Fengling.Console.Models.Entities; using Fengling.Platform.Domain.AggregatesModel.TenantAggregate;
namespace Fengling.Console.Models.Dtos; namespace Fengling.Console.Models.Dtos;
public class TenantDto public class TenantDto
{ {
public int Id { get; set; } public long Id { get; set; }
public string TenantCode { get; set; } = ""; public string TenantCode { get; set; } = "";
public string Name { get; set; } = ""; public string Name { get; set; } = "";
public string ContactName { get; set; } = ""; public string ContactName { get; set; } = "";
@ -12,7 +12,7 @@ public class TenantDto
public string? ContactPhone { get; set; } public string? ContactPhone { get; set; }
public int? MaxUsers { get; set; } public int? MaxUsers { get; set; }
public int UserCount { get; set; } public int UserCount { get; set; }
public TenantStatus Status { get; set; } = TenantStatus.Active; public TenantStatus Status { get; set; } = TenantStatus.Active;
public DateTime? ExpiresAt { get; set; } public DateTime? ExpiresAt { get; set; }
public string? Description { get; set; } public string? Description { get; set; }
public DateTime CreatedAt { get; set; } public DateTime CreatedAt { get; set; }

View File

@ -1,4 +1,4 @@
using Fengling.Console.Models.Entities; using Fengling.Platform.Domain.AggregatesModel.TenantAggregate;
namespace Fengling.Console.Models.Dtos; namespace Fengling.Console.Models.Dtos;

View File

@ -1,43 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace Fengling.Console.Models.Entities;
public class AccessLog
{
[Key]
public long Id { get; set; }
[MaxLength(50)]
public string? UserName { get; set; }
[MaxLength(50)]
public string? TenantId { get; set; }
[MaxLength(20)]
public string Action { get; set; } = string.Empty;
[MaxLength(200)]
public string? Resource { get; set; }
[MaxLength(10)]
public string? Method { get; set; }
[MaxLength(50)]
public string? IpAddress { get; set; }
[MaxLength(500)]
public string? UserAgent { get; set; }
[MaxLength(20)]
public string Status { get; set; } = "success";
public int Duration { get; set; }
public string? RequestData { get; set; }
public string? ResponseData { get; set; }
public string? ErrorMessage { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}

View File

@ -1,13 +0,0 @@
using Microsoft.AspNetCore.Identity;
namespace Fengling.Console.Models.Entities;
public class ApplicationRole : IdentityRole<long>
{
public string? Description { get; set; }
public DateTime CreatedTime { get; set; } = DateTime.UtcNow;
public int? TenantId { get; set; }
public bool IsSystem { get; set; }
public string? DisplayName { get; set; }
public List<string>? Permissions { get; set; }
}

View File

@ -1,13 +0,0 @@
using Microsoft.AspNetCore.Identity;
namespace Fengling.Console.Models.Entities;
public class ApplicationUser : IdentityUser<long>
{
public string? RealName { get; set; }
public string? Phone { get; set; }
public int TenantId { get; set; }
public DateTime CreatedTime { get; set; } = DateTime.UtcNow;
public DateTime? UpdatedTime { get; set; }
public bool IsDeleted { get; set; }
}

View File

@ -1,47 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace Fengling.Console.Models.Entities;
public class AuditLog
{
[Key]
public long Id { get; set; }
[MaxLength(50)]
[Required]
public string Operator { get; set; } = string.Empty;
[MaxLength(50)]
public string? TenantId { get; set; }
[MaxLength(20)]
public string Operation { get; set; } = string.Empty;
[MaxLength(20)]
public string Action { get; set; } = string.Empty;
[MaxLength(50)]
public string? TargetType { get; set; }
public long? TargetId { get; set; }
[MaxLength(100)]
public string? TargetName { get; set; }
[MaxLength(50)]
public string IpAddress { get; set; } = string.Empty;
[MaxLength(500)]
public string? Description { get; set; }
public string? OldValue { get; set; }
public string? NewValue { get; set; }
public string? ErrorMessage { get; set; }
[MaxLength(20)]
public string Status { get; set; } = "success";
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}

View File

@ -1,25 +0,0 @@
namespace Fengling.Console.Models.Entities;
public class Tenant
{
public int Id { get; set; }
public string TenantCode { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string ContactName { get; set; } = string.Empty;
public string ContactEmail { get; set; } = string.Empty;
public string? ContactPhone { get; set; }
public int? MaxUsers { get; set; }
public string? Description { get; set; }
public TenantStatus Status { get; set; } = TenantStatus.Active;
public DateTime? ExpiresAt { get; set; }
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime? UpdatedAt { get; set; }
public bool IsDeleted { get; set; }
}
public enum TenantStatus
{
Active = 1,
Inactive = 2,
Frozen = 3
}

View File

@ -98,11 +98,6 @@ builder.Services.AddSwaggerGen(c =>
builder.Services.AddRepositories(typeof(PlatformDbContext).Assembly); builder.Services.AddRepositories(typeof(PlatformDbContext).Assembly);
builder.Services.AddMediatR(cfg =>
cfg.RegisterServicesFromAssemblies(
Assembly.GetExecutingAssembly(),
typeof(PlatformDbContext).Assembly
));
var app = builder.Build(); var app = builder.Build();

View File

@ -1,15 +0,0 @@
using Fengling.Console.Models.Entities;
namespace Fengling.Console.Repositories;
public interface IRoleRepository
{
Task<ApplicationRole?> GetByIdAsync(long id);
Task<ApplicationRole?> GetByNameAsync(string name);
Task<IEnumerable<ApplicationRole>> GetAllAsync();
Task<IEnumerable<ApplicationRole>> GetPagedAsync(int page, int pageSize, string? name = null, string? tenantId = null);
Task<int> CountAsync(string? name = null, string? tenantId = null);
Task AddAsync(ApplicationRole role);
Task UpdateAsync(ApplicationRole role);
Task DeleteAsync(ApplicationRole role);
}

View File

@ -1,15 +0,0 @@
using Fengling.Console.Models.Entities;
namespace Fengling.Console.Repositories;
public interface IUserRepository
{
Task<ApplicationUser?> GetByIdAsync(long id);
Task<ApplicationUser?> GetByUserNameAsync(string userName);
Task<IEnumerable<ApplicationUser>> GetAllAsync();
Task<IEnumerable<ApplicationUser>> GetPagedAsync(int page, int pageSize, string? userName = null, string? email = null, string? tenantId = null);
Task<int> CountAsync(string? userName = null, string? email = null, string? tenantId = null);
Task AddAsync(ApplicationUser user);
Task UpdateAsync(ApplicationUser user);
Task DeleteAsync(ApplicationUser user);
}

View File

@ -1,80 +0,0 @@
using Fengling.Console.Datas;
using Fengling.Console.Models.Entities;
using Microsoft.EntityFrameworkCore;
namespace Fengling.Console.Repositories;
public class RoleRepository(ApplicationDbContext context) : IRoleRepository
{
public async Task<ApplicationRole?> GetByIdAsync(long id)
{
return await context.Roles.FindAsync(id);
}
public async Task<ApplicationRole?> GetByNameAsync(string name)
{
return await context.Roles.FirstOrDefaultAsync(r => r.Name == name);
}
public async Task<IEnumerable<ApplicationRole>> GetAllAsync()
{
return await context.Roles.ToListAsync();
}
public async Task<IEnumerable<ApplicationRole>> GetPagedAsync(int page, int pageSize, string? name = null,
string? tenantId = null)
{
var query = context.Roles.AsQueryable();
if (!string.IsNullOrEmpty(name))
{
query = query.Where(r => r.Name != null && r.Name.Contains(name));
}
if (!string.IsNullOrEmpty(tenantId))
{
query = query.Where(r => r.TenantId.ToString() == tenantId);
}
return await query
.OrderByDescending(r => r.CreatedTime)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
}
public async Task<int> CountAsync(string? name = null, string? tenantId = null)
{
var query = context.Roles.AsQueryable();
if (!string.IsNullOrEmpty(name))
{
query = query.Where(r => r.Name != null && r.Name.Contains(name));
}
if (!string.IsNullOrEmpty(tenantId))
{
query = query.Where(r => r.TenantId.ToString() == tenantId);
}
return await query.CountAsync();
}
public async Task AddAsync(ApplicationRole role)
{
context.Roles.Add(role);
await context.SaveChangesAsync();
}
public async Task UpdateAsync(ApplicationRole role)
{
context.Roles.Update(role);
await context.SaveChangesAsync();
}
public async Task DeleteAsync(ApplicationRole role)
{
context.Roles.Remove(role);
await context.SaveChangesAsync();
}
}

View File

@ -1,97 +0,0 @@
using Fengling.Console.Datas;
using Fengling.Console.Models.Entities;
using Microsoft.EntityFrameworkCore;
namespace Fengling.Console.Repositories;
public class UserRepository : IUserRepository
{
private readonly ApplicationDbContext _context;
public UserRepository(ApplicationDbContext context)
{
_context = context;
}
public async Task<ApplicationUser?> GetByIdAsync(long id)
{
return await _context.Users.FindAsync(id);
}
public async Task<ApplicationUser?> GetByUserNameAsync(string userName)
{
return await _context.Users.FirstOrDefaultAsync(u => u.UserName == userName);
}
public async Task<IEnumerable<ApplicationUser>> GetAllAsync()
{
return await _context.Users.ToListAsync();
}
public async Task<IEnumerable<ApplicationUser>> GetPagedAsync(int page, int pageSize, string? userName = null,
string? email = null, string? tenantCode = null)
{
var query = _context.Users.AsQueryable();
if (!string.IsNullOrEmpty(userName))
{
query = query.Where(u => u.UserName != null && u.UserName.Contains(userName));
}
if (!string.IsNullOrEmpty(email))
{
query = query.Where(u => u.Email != null && u.Email.Contains(email));
}
if (!string.IsNullOrEmpty(tenantCode))
{
query = query.Where(u => u.TenantId.ToString().Contains(tenantCode));
}
return await query
.OrderByDescending(u => u.CreatedTime)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
}
public async Task<int> CountAsync(string? userName = null, string? email = null, string? tenantCode = null)
{
var query = _context.Users.AsQueryable();
if (!string.IsNullOrEmpty(userName))
{
query = query.Where(u => u.UserName != null && u.UserName.Contains(userName));
}
if (!string.IsNullOrEmpty(email))
{
query = query.Where(u => u.Email != null && u.Email.Contains(email));
}
if (!string.IsNullOrEmpty(tenantCode))
{
query = query.Where(u => u.TenantId.ToString().Contains(tenantCode));
}
return await query.CountAsync();
}
public async Task AddAsync(ApplicationUser user)
{
_context.Users.Add(user);
await _context.SaveChangesAsync();
}
public async Task UpdateAsync(ApplicationUser user)
{
_context.Users.Update(user);
await _context.SaveChangesAsync();
}
public async Task DeleteAsync(ApplicationUser user)
{
_context.Users.Remove(user);
await _context.SaveChangesAsync();
}
}

View File

@ -1,8 +1,6 @@
using Fengling.Console.Models.Entities; using Fengling.Platform.Infrastructure;
using Fengling.Console.Managers;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using QRCoder; using QRCoder;
using Tenant = Fengling.Console.Models.Entities.Tenant;
namespace Fengling.Console.Services; namespace Fengling.Console.Services;
@ -43,7 +41,7 @@ public class H5LinkService : IH5LinkService
}; };
} }
private string GenerateLink(Tenant tenant) private string GenerateLink(Fengling.Platform.Domain.AggregatesModel.TenantAggregate.Tenant tenant)
{ {
var baseUrl = _configuration["AppSettings:DefaultH5BaseUrl"] ?? "https://h5.example.com"; var baseUrl = _configuration["AppSettings:DefaultH5BaseUrl"] ?? "https://h5.example.com";
return $"{baseUrl.TrimEnd('/')}/{tenant.TenantCode}"; return $"{baseUrl.TrimEnd('/')}/{tenant.TenantCode}";

View File

@ -1,10 +1,10 @@
using Fengling.Console.Models.Dtos; using Fengling.Console.Models.Dtos;
using Fengling.Console.Repositories; using Fengling.Platform.Domain.AggregatesModel.UserAggregate;
using Fengling.Console.Managers; using Fengling.Platform.Domain.AggregatesModel.RoleAggregate;
using Fengling.Platform.Infrastructure;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims; using System.Security.Claims;
using Fengling.Console.Datas;
using Fengling.Console.Models.Entities;
namespace Fengling.Console.Services; namespace Fengling.Console.Services;
@ -24,22 +24,19 @@ public interface IRoleService
public class RoleService : IRoleService public class RoleService : IRoleService
{ {
private readonly IRoleRepository _repository;
private readonly ITenantManager _tenantManager; private readonly ITenantManager _tenantManager;
private readonly UserManager<ApplicationUser> _userManager; private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager; private readonly RoleManager<ApplicationRole> _roleManager;
private readonly ApplicationDbContext _context; private readonly PlatformDbContext _context;
private readonly IHttpContextAccessor _httpContextAccessor; private readonly IHttpContextAccessor _httpContextAccessor;
public RoleService( public RoleService(
IRoleRepository repository,
ITenantManager tenantManager, ITenantManager tenantManager,
UserManager<ApplicationUser> userManager, UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager, RoleManager<ApplicationRole> roleManager,
ApplicationDbContext context, PlatformDbContext context,
IHttpContextAccessor httpContextAccessor) IHttpContextAccessor httpContextAccessor)
{ {
_repository = repository;
_tenantManager = tenantManager; _tenantManager = tenantManager;
_userManager = userManager; _userManager = userManager;
_roleManager = roleManager; _roleManager = roleManager;
@ -50,8 +47,24 @@ public class RoleService : IRoleService
public async Task<(IEnumerable<RoleDto> Items, int TotalCount)> GetRolesAsync(int page, int pageSize, public async Task<(IEnumerable<RoleDto> Items, int TotalCount)> GetRolesAsync(int page, int pageSize,
string? name = null, string? tenantId = null) string? name = null, string? tenantId = null)
{ {
var roles = await _repository.GetPagedAsync(page, pageSize, name, tenantId); var query = _context.Roles.AsQueryable();
var totalCount = await _repository.CountAsync(name, tenantId);
if (!string.IsNullOrEmpty(name))
{
query = query.Where(r => r.Name != null && r.Name.Contains(name));
}
if (!string.IsNullOrEmpty(tenantId))
{
query = query.Where(r => r.TenantId.HasValue && r.TenantId.Value.ToString().Contains(tenantId));
}
var totalCount = await query.CountAsync();
var roles = await query
.OrderByDescending(r => r.CreatedTime)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
var roleDtos = new List<RoleDto>(); var roleDtos = new List<RoleDto>();
foreach (var role in roles) foreach (var role in roles)
@ -76,7 +89,7 @@ public class RoleService : IRoleService
public async Task<RoleDto?> GetRoleAsync(long id) public async Task<RoleDto?> GetRoleAsync(long id)
{ {
var role = await _repository.GetByIdAsync(id); var role = await _context.Roles.FindAsync(id);
if (role == null) return null; if (role == null) return null;
return new RoleDto return new RoleDto
@ -95,7 +108,7 @@ public class RoleService : IRoleService
public async Task<IEnumerable<UserDto>> GetRoleUsersAsync(long id) public async Task<IEnumerable<UserDto>> GetRoleUsersAsync(long id)
{ {
var role = await _repository.GetByIdAsync(id); var role = await _context.Roles.FindAsync(id);
if (role == null) if (role == null)
{ {
throw new KeyNotFoundException($"Role with ID {id} not found"); throw new KeyNotFoundException($"Role with ID {id} not found");
@ -107,14 +120,14 @@ public class RoleService : IRoleService
foreach (var user in users) foreach (var user in users)
{ {
var roles = await _userManager.GetRolesAsync(user); var roles = await _userManager.GetRolesAsync(user);
var tenant = user.TenantId > 0 ? await _tenantManager.FindByIdAsync(user.TenantId) : null; var tenant = user.TenantInfo.TenantId > 0 ? await _tenantManager.FindByIdAsync(user.TenantInfo.TenantId) : null;
userDtos.Add(new UserDto userDtos.Add(new UserDto
{ {
Id = user.Id, Id = user.Id,
UserName = user.UserName, UserName = user.UserName,
Email = user.Email, Email = user.Email,
RealName = user.RealName, RealName = user.RealName,
TenantCode = user.TenantId.ToString(), TenantCode = user.TenantInfo.TenantId.ToString(),
TenantName = tenant?.Name ?? "", TenantName = tenant?.Name ?? "",
Roles = roles.ToList(), Roles = roles.ToList(),
EmailConfirmed = user.EmailConfirmed, EmailConfirmed = user.EmailConfirmed,
@ -133,7 +146,7 @@ public class RoleService : IRoleService
Name = dto.Name, Name = dto.Name,
DisplayName = dto.DisplayName, DisplayName = dto.DisplayName,
Description = dto.Description, Description = dto.Description,
TenantId = dto.TenantId.HasValue ? (int?)dto.TenantId.Value : null, TenantId = dto.TenantId.HasValue ? dto.TenantId.Value : null,
Permissions = dto.Permissions, Permissions = dto.Permissions,
IsSystem = false, IsSystem = false,
CreatedTime = DateTime.UtcNow CreatedTime = DateTime.UtcNow
@ -164,7 +177,7 @@ public class RoleService : IRoleService
public async Task<RoleDto> UpdateRoleAsync(long id, UpdateRoleDto dto) public async Task<RoleDto> UpdateRoleAsync(long id, UpdateRoleDto dto)
{ {
var role = await _repository.GetByIdAsync(id); var role = await _context.Roles.FindAsync(id);
if (role == null) if (role == null)
{ {
throw new KeyNotFoundException($"Role with ID {id} not found"); throw new KeyNotFoundException($"Role with ID {id} not found");
@ -181,7 +194,7 @@ public class RoleService : IRoleService
role.Description = dto.Description; role.Description = dto.Description;
role.Permissions = dto.Permissions; role.Permissions = dto.Permissions;
await _repository.UpdateAsync(role); await _roleManager.UpdateAsync(role);
await CreateAuditLog("role", "update", "Role", role.Id, role.DisplayName, oldValue, await CreateAuditLog("role", "update", "Role", role.Id, role.DisplayName, oldValue,
System.Text.Json.JsonSerializer.Serialize(role)); System.Text.Json.JsonSerializer.Serialize(role));
@ -203,7 +216,7 @@ public class RoleService : IRoleService
public async Task DeleteRoleAsync(long id) public async Task DeleteRoleAsync(long id)
{ {
var role = await _repository.GetByIdAsync(id); var role = await _context.Roles.FindAsync(id);
if (role == null) if (role == null)
{ {
throw new KeyNotFoundException($"Role with ID {id} not found"); throw new KeyNotFoundException($"Role with ID {id} not found");
@ -222,14 +235,14 @@ public class RoleService : IRoleService
await _userManager.RemoveFromRoleAsync(user, role.Name!); await _userManager.RemoveFromRoleAsync(user, role.Name!);
} }
await _repository.DeleteAsync(role); await _roleManager.DeleteAsync(role);
await CreateAuditLog("role", "delete", "Role", role.Id, role.DisplayName, oldValue); await CreateAuditLog("role", "delete", "Role", role.Id, role.DisplayName, oldValue);
} }
public async Task AddUserToRoleAsync(long roleId, long userId) public async Task AddUserToRoleAsync(long roleId, long userId)
{ {
var role = await _repository.GetByIdAsync(roleId); var role = await _context.Roles.FindAsync(roleId);
if (role == null) if (role == null)
{ {
throw new KeyNotFoundException($"Role with ID {roleId} not found"); throw new KeyNotFoundException($"Role with ID {roleId} not found");
@ -252,7 +265,7 @@ public class RoleService : IRoleService
public async Task RemoveUserFromRoleAsync(long roleId, long userId) public async Task RemoveUserFromRoleAsync(long roleId, long userId)
{ {
var role = await _repository.GetByIdAsync(roleId); var role = await _context.Roles.FindAsync(roleId);
if (role == null) if (role == null)
{ {
throw new KeyNotFoundException($"Role with ID {roleId} not found"); throw new KeyNotFoundException($"Role with ID {roleId} not found");
@ -300,4 +313,4 @@ public class RoleService : IRoleService
_context.AuditLogs.Add(log); _context.AuditLogs.Add(log);
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
} }
} }

View File

@ -1,11 +1,12 @@
using Fengling.Console.Managers;
using Fengling.Console.Models.Dtos; using Fengling.Console.Models.Dtos;
using Fengling.Console.Repositories; using Fengling.Platform.Domain.AggregatesModel.UserAggregate;
using Fengling.Platform.Domain.AggregatesModel.RoleAggregate;
using Fengling.Platform.Domain.AggregatesModel.TenantAggregate;
using Fengling.Platform.Infrastructure;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims; using System.Security.Claims;
using Fengling.Console.Datas; using TenantStatus = Fengling.Platform.Domain.AggregatesModel.TenantAggregate.TenantStatus;
using Fengling.Console.Models.Entities;
using TenantStatus = Fengling.Console.Models.Entities.TenantStatus;
namespace Fengling.Console.Services; namespace Fengling.Console.Services;
@ -13,22 +14,21 @@ public interface ITenantService
{ {
Task<(IEnumerable<TenantDto> Items, int TotalCount)> GetTenantsAsync(int page, int pageSize, string? name = null, Task<(IEnumerable<TenantDto> Items, int TotalCount)> GetTenantsAsync(int page, int pageSize, string? name = null,
string? tenantCode = null, TenantStatus? status = null); string? tenantCode = null, TenantStatus? status = null);
Task<TenantDto?> GetTenantAsync(int id); Task<TenantDto?> GetTenantAsync(long id);
Task<IEnumerable<UserDto>> GetTenantUsersAsync(int tenantId); Task<IEnumerable<UserDto>> GetTenantUsersAsync(long tenantId);
Task<IEnumerable<object>> GetTenantRolesAsync(int tenantId); Task<IEnumerable<object>> GetTenantRolesAsync(long tenantId);
Task<TenantSettingsDto> GetTenantSettingsAsync(int id); Task<TenantSettingsDto> GetTenantSettingsAsync(long id);
Task UpdateTenantSettingsAsync(int id, TenantSettingsDto settings); Task UpdateTenantSettingsAsync(long id, TenantSettingsDto settings);
Task<TenantDto> CreateTenantAsync(CreateTenantDto dto); Task<TenantDto> CreateTenantAsync(CreateTenantDto dto);
Task<TenantDto> UpdateTenantAsync(int id, UpdateTenantDto dto); Task<TenantDto> UpdateTenantAsync(long id, UpdateTenantDto dto);
Task DeleteTenantAsync(int id); Task DeleteTenantAsync(long id);
} }
public class TenantService( public class TenantService(
ITenantManager tenantManager, ITenantManager tenantManager,
IUserRepository userRepository,
IRoleRepository roleRepository,
UserManager<ApplicationUser> userManager, UserManager<ApplicationUser> userManager,
ApplicationDbContext context, RoleManager<ApplicationRole> roleManager,
PlatformDbContext context,
IHttpContextAccessor httpContextAccessor) IHttpContextAccessor httpContextAccessor)
: ITenantService : ITenantService
{ {
@ -62,7 +62,7 @@ public class TenantService(
return (tenantDtos, totalCount); return (tenantDtos, totalCount);
} }
public async Task<TenantDto?> GetTenantAsync(int id) public async Task<TenantDto?> GetTenantAsync(long id)
{ {
var tenant = await tenantManager.FindByIdAsync(id); var tenant = await tenantManager.FindByIdAsync(id);
if (tenant == null) return null; if (tenant == null) return null;
@ -84,7 +84,7 @@ public class TenantService(
}; };
} }
public async Task<IEnumerable<UserDto>> GetTenantUsersAsync(int tenantId) public async Task<IEnumerable<UserDto>> GetTenantUsersAsync(long tenantId)
{ {
var tenant = await tenantManager.FindByIdAsync(tenantId); var tenant = await tenantManager.FindByIdAsync(tenantId);
if (tenant == null) if (tenant == null)
@ -92,7 +92,10 @@ public class TenantService(
throw new KeyNotFoundException($"Tenant with ID {tenantId} not found"); throw new KeyNotFoundException($"Tenant with ID {tenantId} not found");
} }
var users = await userRepository.GetPagedAsync(1, int.MaxValue, null, null, tenantId.ToString()); var users = await context.Users
.Where(u => u.TenantInfo.TenantId == tenantId)
.ToListAsync();
var userDtos = new List<UserDto>(); var userDtos = new List<UserDto>();
foreach (var user in users) foreach (var user in users)
@ -104,7 +107,7 @@ public class TenantService(
UserName = user.UserName, UserName = user.UserName,
Email = user.Email, Email = user.Email,
RealName = user.RealName, RealName = user.RealName,
TenantCode = user.TenantId.ToString(), TenantCode = user.TenantInfo.TenantId.ToString(),
TenantName = tenant?.Name ?? "", TenantName = tenant?.Name ?? "",
Roles = roles.ToList(), Roles = roles.ToList(),
EmailConfirmed = user.EmailConfirmed, EmailConfirmed = user.EmailConfirmed,
@ -116,7 +119,7 @@ public class TenantService(
return userDtos; return userDtos;
} }
public async Task<IEnumerable<object>> GetTenantRolesAsync(int tenantId) public async Task<IEnumerable<object>> GetTenantRolesAsync(long tenantId)
{ {
var tenant = await tenantManager.FindByIdAsync(tenantId); var tenant = await tenantManager.FindByIdAsync(tenantId);
if (tenant == null) if (tenant == null)
@ -124,7 +127,10 @@ public class TenantService(
throw new KeyNotFoundException($"Tenant with ID {tenantId} not found"); throw new KeyNotFoundException($"Tenant with ID {tenantId} not found");
} }
var roles = await roleRepository.GetPagedAsync(1, int.MaxValue, null, tenantId.ToString()); var roles = await context.Roles
.Where(r => r.TenantId == tenantId)
.ToListAsync();
return roles.Select(r => new return roles.Select(r => new
{ {
id = r.Id, id = r.Id,
@ -133,7 +139,7 @@ public class TenantService(
}); });
} }
public async Task<TenantSettingsDto> GetTenantSettingsAsync(int id) public async Task<TenantSettingsDto> GetTenantSettingsAsync(long id)
{ {
var tenant = await tenantManager.FindByIdAsync(id); var tenant = await tenantManager.FindByIdAsync(id);
if (tenant == null) if (tenant == null)
@ -152,7 +158,7 @@ public class TenantService(
}; };
} }
public async Task UpdateTenantSettingsAsync(int id, TenantSettingsDto settings) public async Task UpdateTenantSettingsAsync(long id, TenantSettingsDto settings)
{ {
var tenant = await tenantManager.FindByIdAsync(id); var tenant = await tenantManager.FindByIdAsync(id);
if (tenant == null) if (tenant == null)
@ -207,7 +213,7 @@ public class TenantService(
}; };
} }
public async Task<TenantDto> UpdateTenantAsync(int id, UpdateTenantDto dto) public async Task<TenantDto> UpdateTenantAsync(long id, UpdateTenantDto dto)
{ {
var tenant = await tenantManager.FindByIdAsync(id); var tenant = await tenantManager.FindByIdAsync(id);
if (tenant == null) if (tenant == null)
@ -251,7 +257,7 @@ public class TenantService(
}; };
} }
public async Task DeleteTenantAsync(int id) public async Task DeleteTenantAsync(long id)
{ {
var tenant = await tenantManager.FindByIdAsync(id); var tenant = await tenantManager.FindByIdAsync(id);
if (tenant == null) if (tenant == null)
@ -261,13 +267,16 @@ public class TenantService(
var oldValue = System.Text.Json.JsonSerializer.Serialize(tenant); var oldValue = System.Text.Json.JsonSerializer.Serialize(tenant);
var users = await userRepository.GetPagedAsync(1, int.MaxValue, null, null, id.ToString()); var users = await context.Users
.Where(u => u.TenantInfo.TenantId == id)
.ToListAsync();
foreach (var user in users) foreach (var user in users)
{ {
user.IsDeleted = true; user.IsDeleted = true;
user.UpdatedTime = DateTime.UtcNow; user.UpdatedTime = DateTime.UtcNow;
await context.SaveChangesAsync();
} }
await context.SaveChangesAsync();
tenant.IsDeleted = true; tenant.IsDeleted = true;
var result = await tenantManager.UpdateAsync(tenant); var result = await tenantManager.UpdateAsync(tenant);
@ -281,7 +290,7 @@ public class TenantService(
await CreateAuditLog("tenant", "delete", "Tenant", tenant.Id, tenant.Name, oldValue); await CreateAuditLog("tenant", "delete", "Tenant", tenant.Id, tenant.Name, oldValue);
} }
private async Task CreateAuditLog(string operation, string action, string targetType, int? targetId, string? targetName, string? oldValue = null, string? newValue = null) private async Task CreateAuditLog(string operation, string action, string targetType, long? targetId, string? targetName, string? oldValue = null, string? newValue = null)
{ {
var httpContext = httpContextAccessor.HttpContext; var httpContext = httpContextAccessor.HttpContext;
var userName = httpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier) ?? httpContext?.User?.Identity?.Name ?? "system"; var userName = httpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier) ?? httpContext?.User?.Identity?.Name ?? "system";
@ -294,7 +303,7 @@ public class TenantService(
Operation = operation, Operation = operation,
Action = action, Action = action,
TargetType = targetType, TargetType = targetType,
TargetId = targetId.HasValue ? (long)targetId.Value : null, TargetId = targetId,
TargetName = targetName, TargetName = targetName,
IpAddress = httpContext?.Connection?.RemoteIpAddress?.ToString() ?? "unknown", IpAddress = httpContext?.Connection?.RemoteIpAddress?.ToString() ?? "unknown",
Status = "success", Status = "success",

View File

@ -1,11 +1,11 @@
using Fengling.Console.Models.Dtos; using Fengling.Console.Models.Dtos;
using Fengling.Console.Repositories; using Fengling.Platform.Domain.AggregatesModel.UserAggregate;
using Fengling.Console.Managers; using Fengling.Platform.Domain.AggregatesModel.RoleAggregate;
using Fengling.Platform.Domain.AggregatesModel.TenantAggregate;
using Fengling.Platform.Infrastructure;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims; using System.Security.Claims;
using Fengling.Console.Datas;
using Fengling.Console.Models.Entities;
using Tenant = Fengling.Console.Models.Entities.Tenant;
namespace Fengling.Console.Services; namespace Fengling.Console.Services;
@ -20,24 +20,44 @@ public interface IUserService
} }
public class UserService( public class UserService(
IUserRepository repository,
ITenantManager tenantManager, ITenantManager tenantManager,
UserManager<ApplicationUser> userManager, UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager, RoleManager<ApplicationRole> roleManager,
ApplicationDbContext context, PlatformDbContext context,
IHttpContextAccessor httpContextAccessor) IHttpContextAccessor httpContextAccessor)
: IUserService : IUserService
{ {
public async Task<(IEnumerable<UserDto> Items, int TotalCount)> GetUsersAsync(int page, int pageSize, string? userName = null, string? email = null, string? tenantId = null) public async Task<(IEnumerable<UserDto> Items, int TotalCount)> GetUsersAsync(int page, int pageSize, string? userName = null, string? email = null, string? tenantId = null)
{ {
var users = await repository.GetPagedAsync(page, pageSize, userName, email, tenantId); var query = context.Users.AsQueryable();
var totalCount = await repository.CountAsync(userName, email, tenantId);
if (!string.IsNullOrEmpty(userName))
{
query = query.Where(u => u.UserName != null && u.UserName.Contains(userName));
}
if (!string.IsNullOrEmpty(email))
{
query = query.Where(u => u.Email != null && u.Email.Contains(email));
}
if (!string.IsNullOrEmpty(tenantId))
{
query = query.Where(u => u.TenantInfo.TenantId.ToString().Contains(tenantId));
}
var totalCount = await query.CountAsync();
var users = await query
.OrderByDescending(u => u.CreatedTime)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
var userDtos = new List<UserDto>(); var userDtos = new List<UserDto>();
foreach (var user in users) foreach (var user in users)
{ {
var roles = await userManager.GetRolesAsync(user); var roles = await userManager.GetRolesAsync(user);
var tenant = user.TenantId > 0 ? await tenantManager.FindByIdAsync(user.TenantId) : null; var tenant = user.TenantInfo.TenantId > 0 ? await tenantManager.FindByIdAsync(user.TenantInfo.TenantId) : null;
userDtos.Add(new UserDto userDtos.Add(new UserDto
{ {
Id = user.Id, Id = user.Id,
@ -45,7 +65,7 @@ public class UserService(
Email = user.Email, Email = user.Email,
RealName = user.RealName, RealName = user.RealName,
Phone = user.Phone, Phone = user.Phone,
TenantCode = user.TenantId.ToString(), TenantCode = user.TenantInfo.TenantId.ToString(),
TenantName = tenant?.Name ?? "", TenantName = tenant?.Name ?? "",
Roles = roles.ToList(), Roles = roles.ToList(),
EmailConfirmed = user.EmailConfirmed, EmailConfirmed = user.EmailConfirmed,
@ -59,11 +79,11 @@ public class UserService(
public async Task<UserDto?> GetUserAsync(long id) public async Task<UserDto?> GetUserAsync(long id)
{ {
var user = await repository.GetByIdAsync(id); var user = await context.Users.FindAsync(id);
if (user == null) return null; if (user == null) return null;
var roles = await userManager.GetRolesAsync(user); var roles = await userManager.GetRolesAsync(user);
var tenant = user.TenantId > 0 ? await tenantManager.FindByIdAsync(user.TenantId) : null; var tenant = user.TenantInfo.TenantId > 0 ? await tenantManager.FindByIdAsync(user.TenantInfo.TenantId) : null;
return new UserDto return new UserDto
{ {
Id = user.Id, Id = user.Id,
@ -71,7 +91,7 @@ public class UserService(
Email = user.Email, Email = user.Email,
RealName = user.RealName, RealName = user.RealName,
Phone = user.Phone, Phone = user.Phone,
TenantCode = user.TenantId.ToString(), TenantCode = user.TenantInfo.TenantId.ToString(),
TenantName = tenant?.Name ?? "", TenantName = tenant?.Name ?? "",
Roles = roles.ToList(), Roles = roles.ToList(),
EmailConfirmed = user.EmailConfirmed, EmailConfirmed = user.EmailConfirmed,
@ -82,25 +102,28 @@ public class UserService(
public async Task<UserDto> CreateUserAsync(CreateUserDto dto) public async Task<UserDto> CreateUserAsync(CreateUserDto dto)
{ {
var tenantId = dto.TenantId.HasValue ? (int)dto.TenantId.Value : 0;
Tenant? tenant = null; Tenant? tenant = null;
if (tenantId != 0) if (dto.TenantId.HasValue && dto.TenantId.Value > 0)
{ {
tenant = await tenantManager.FindByIdAsync(tenantId); tenant = await tenantManager.FindByIdAsync(dto.TenantId.Value);
if (tenant == null) if (tenant == null)
{ {
throw new InvalidOperationException("Invalid tenant ID"); throw new InvalidOperationException("Invalid tenant ID");
} }
} }
var tenantInfo = tenant != null
? new TenantInfo(tenant.Id, tenant.TenantCode, tenant.Name)
: new TenantInfo(0, "", "");
var user = new ApplicationUser var user = new ApplicationUser
{ {
UserName = dto.UserName, UserName = dto.UserName,
Email = dto.Email, Email = dto.Email,
RealName = dto.RealName, RealName = dto.RealName,
Phone = dto.Phone, Phone = dto.Phone,
TenantId = tenant?.Id ?? 0, TenantInfo = tenantInfo,
EmailConfirmed = dto.EmailConfirmed, EmailConfirmed = dto.EmailConfirmed,
CreatedTime = DateTime.UtcNow CreatedTime = DateTime.UtcNow
}; };
@ -139,7 +162,7 @@ public class UserService(
Email = user.Email, Email = user.Email,
RealName = user.RealName, RealName = user.RealName,
Phone = user.Phone, Phone = user.Phone,
TenantCode = user.TenantId.ToString(), TenantCode = user.TenantInfo.TenantId.ToString(),
TenantName = tenant?.Name ?? "", TenantName = tenant?.Name ?? "",
Roles = roles.ToList(), Roles = roles.ToList(),
EmailConfirmed = user.EmailConfirmed, EmailConfirmed = user.EmailConfirmed,
@ -150,7 +173,7 @@ public class UserService(
public async Task<UserDto> UpdateUserAsync(long id, UpdateUserDto dto) public async Task<UserDto> UpdateUserAsync(long id, UpdateUserDto dto)
{ {
var user = await repository.GetByIdAsync(id); var user = await context.Users.FindAsync(id);
if (user == null) if (user == null)
{ {
throw new KeyNotFoundException($"User with ID {id} not found"); throw new KeyNotFoundException($"User with ID {id} not found");
@ -164,6 +187,8 @@ public class UserService(
user.EmailConfirmed = dto.EmailConfirmed; user.EmailConfirmed = dto.EmailConfirmed;
user.UpdatedTime = DateTime.UtcNow; user.UpdatedTime = DateTime.UtcNow;
await userManager.UpdateAsync(user);
if (dto.IsActive) if (dto.IsActive)
{ {
await userManager.SetLockoutEnabledAsync(user, false); await userManager.SetLockoutEnabledAsync(user, false);
@ -175,9 +200,7 @@ public class UserService(
await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.MaxValue); await userManager.SetLockoutEndDateAsync(user, DateTimeOffset.MaxValue);
} }
await context.SaveChangesAsync(); var tenant = user.TenantInfo.TenantId > 0 ? await tenantManager.FindByIdAsync(user.TenantInfo.TenantId) : null;
var tenant = user.TenantId > 0 ? await tenantManager.FindByIdAsync(user.TenantId) : null;
await CreateAuditLog("user", "update", "User", user.Id, user.UserName, oldValue, System.Text.Json.JsonSerializer.Serialize(user)); await CreateAuditLog("user", "update", "User", user.Id, user.UserName, oldValue, System.Text.Json.JsonSerializer.Serialize(user));
@ -189,7 +212,7 @@ public class UserService(
Email = user.Email, Email = user.Email,
RealName = user.RealName, RealName = user.RealName,
Phone = user.Phone, Phone = user.Phone,
TenantCode = user.TenantId.ToString(), TenantCode = user.TenantInfo.TenantId.ToString(),
TenantName = tenant?.Name ?? "", TenantName = tenant?.Name ?? "",
Roles = roles.ToList(), Roles = roles.ToList(),
EmailConfirmed = user.EmailConfirmed, EmailConfirmed = user.EmailConfirmed,
@ -219,7 +242,7 @@ public class UserService(
public async Task DeleteUserAsync(long id) public async Task DeleteUserAsync(long id)
{ {
var user = await repository.GetByIdAsync(id); var user = await context.Users.FindAsync(id);
if (user == null) if (user == null)
{ {
throw new KeyNotFoundException($"User with ID {id} not found"); throw new KeyNotFoundException($"User with ID {id} not found");
@ -237,12 +260,12 @@ public class UserService(
{ {
var httpContext = httpContextAccessor.HttpContext; var httpContext = httpContextAccessor.HttpContext;
var userName = httpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier) ?? httpContext?.User?.Identity?.Name ?? "system"; var userName = httpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier) ?? httpContext?.User?.Identity?.Name ?? "system";
var tenantId = httpContext?.User?.FindFirstValue("TenantId"); var tenantIdClaim = httpContext?.User?.FindFirstValue("TenantId");
var log = new AuditLog var log = new AuditLog
{ {
Operator = userName, Operator = userName,
TenantId = tenantId, TenantId = tenantIdClaim,
Operation = operation, Operation = operation,
Action = action, Action = action,
TargetType = targetType, TargetType = targetType,

View File

@ -1,41 +0,0 @@
using Fengling.Console.Models.Entities;
using Microsoft.AspNetCore.Identity;
namespace Fengling.Console.Stores;
public interface ITenantStore<TTenant> : IDisposable where TTenant : class
{
Task<TTenant?> FindByIdAsync(int tenantId, CancellationToken cancellationToken = default);
Task<TTenant?> FindByTenantCodeAsync(string tenantCode, CancellationToken cancellationToken = default);
Task<IList<TTenant>> GetAllAsync(CancellationToken cancellationToken = default);
Task<IList<TTenant>> GetPagedAsync(int page, int pageSize, string? name = null, string? tenantCode = null, TenantStatus? status = null, CancellationToken cancellationToken = default);
Task<int> GetCountAsync(string? name = null, string? tenantCode = null, TenantStatus? status = null, CancellationToken cancellationToken = default);
Task<IdentityResult> CreateAsync(TTenant tenant, CancellationToken cancellationToken = default);
Task<IdentityResult> UpdateAsync(TTenant tenant, CancellationToken cancellationToken = default);
Task<IdentityResult> DeleteAsync(TTenant tenant, CancellationToken cancellationToken = default);
Task<int> GetUserCountAsync(int tenantId, CancellationToken cancellationToken = default);
Task<string> GetTenantCodeAsync(TTenant tenant, CancellationToken cancellationToken = default);
Task<string> GetNameAsync(TTenant tenant, CancellationToken cancellationToken = default);
Task<string> GetContactNameAsync(TTenant tenant, CancellationToken cancellationToken = default);
Task<string> GetContactEmailAsync(TTenant tenant, CancellationToken cancellationToken = default);
Task<string?> GetContactPhoneAsync(TTenant tenant, CancellationToken cancellationToken = default);
Task<int?> GetMaxUsersAsync(TTenant tenant, CancellationToken cancellationToken = default);
Task<string?> GetDescriptionAsync(TTenant tenant, CancellationToken cancellationToken = default);
Task<TenantStatus> GetStatusAsync(TTenant tenant, CancellationToken cancellationToken = default);
Task<DateTime?> GetExpiresAtAsync(TTenant tenant, CancellationToken cancellationToken = default);
Task<DateTime> GetCreatedAtAsync(TTenant tenant, CancellationToken cancellationToken = default);
Task<DateTime?> GetUpdatedAtAsync(TTenant tenant, CancellationToken cancellationToken = default);
Task<bool> GetIsDeletedAsync(TTenant tenant, CancellationToken cancellationToken = default);
Task SetTenantCodeAsync(TTenant tenant, string code, CancellationToken cancellationToken = default);
Task SetNameAsync(TTenant tenant, string name, CancellationToken cancellationToken = default);
Task SetContactNameAsync(TTenant tenant, string name, CancellationToken cancellationToken = default);
Task SetContactEmailAsync(TTenant tenant, string email, CancellationToken cancellationToken = default);
Task SetContactPhoneAsync(TTenant tenant, string? phone, CancellationToken cancellationToken = default);
Task SetMaxUsersAsync(TTenant tenant, int? maxUsers, CancellationToken cancellationToken = default);
Task SetDescriptionAsync(TTenant tenant, string? description, CancellationToken cancellationToken = default);
Task SetStatusAsync(TTenant tenant, TenantStatus status, CancellationToken cancellationToken = default);
Task SetExpiresAtAsync(TTenant tenant, DateTime? expiresAt, CancellationToken cancellationToken = default);
Task SetIsDeletedAsync(TTenant tenant, bool isDeleted, CancellationToken cancellationToken = default);
}

View File

@ -1,196 +0,0 @@
using Fengling.Console.Datas;
using Fengling.Console.Models.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
namespace Fengling.Console.Stores;
public class TenantStore : ITenantStore<Tenant>
{
private readonly ApplicationDbContext _context;
private readonly DbSet<Tenant> _tenants;
public TenantStore(ApplicationDbContext context)
{
_context = context;
_tenants = context.Tenants;
}
public void Dispose() { }
public virtual Task<Tenant?> FindByIdAsync(int tenantId, CancellationToken cancellationToken = default)
{
return _tenants.FirstOrDefaultAsync(t => t.Id == tenantId, cancellationToken);
}
public virtual Task<Tenant?> FindByTenantCodeAsync(string tenantCode, CancellationToken cancellationToken = default)
{
return _tenants.FirstOrDefaultAsync(t => t.TenantCode == tenantCode, cancellationToken);
}
public virtual async Task<IList<Tenant>> GetAllAsync(CancellationToken cancellationToken = default)
{
return (IList<Tenant>)await _tenants.ToListAsync(cancellationToken);
}
public virtual async Task<IList<Tenant>> GetPagedAsync(int page, int pageSize, string? name = null,
string? tenantCode = null, TenantStatus? status = null, CancellationToken cancellationToken = default)
{
var query = _tenants.AsQueryable();
if (!string.IsNullOrEmpty(name))
query = query.Where(t => t.Name.Contains(name));
if (!string.IsNullOrEmpty(tenantCode))
query = query.Where(t => t.TenantCode.Contains(tenantCode));
if (status.HasValue)
query = query.Where(t => t.Status == status);
return await query
.OrderByDescending(t => t.CreatedAt)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync(cancellationToken);
}
public virtual async Task<int> GetCountAsync(string? name = null, string? tenantCode = null,
TenantStatus? status = null, CancellationToken cancellationToken = default)
{
var query = _tenants.AsQueryable();
if (!string.IsNullOrEmpty(name))
query = query.Where(t => t.Name.Contains(name));
if (!string.IsNullOrEmpty(tenantCode))
query = query.Where(t => t.TenantCode.Contains(tenantCode));
if (status.HasValue)
query = query.Where(t => t.Status == status);
return await query.CountAsync(cancellationToken);
}
public virtual async Task<IdentityResult> CreateAsync(Tenant tenant, CancellationToken cancellationToken = default)
{
_tenants.Add(tenant);
await _context.SaveChangesAsync(cancellationToken);
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> UpdateAsync(Tenant tenant, CancellationToken cancellationToken = default)
{
tenant.UpdatedAt = DateTime.UtcNow;
_tenants.Update(tenant);
await _context.SaveChangesAsync(cancellationToken);
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> DeleteAsync(Tenant tenant, CancellationToken cancellationToken = default)
{
_tenants.Remove(tenant);
await _context.SaveChangesAsync(cancellationToken);
return IdentityResult.Success;
}
public virtual async Task<int> GetUserCountAsync(int tenantId, CancellationToken cancellationToken = default)
{
return await _context.Users.CountAsync(u => u.TenantId == tenantId && !u.IsDeleted, cancellationToken);
}
public virtual Task<string> GetTenantCodeAsync(Tenant tenant, CancellationToken cancellationToken = default)
=> Task.FromResult(tenant.TenantCode);
public virtual Task<string> GetNameAsync(Tenant tenant, CancellationToken cancellationToken = default)
=> Task.FromResult(tenant.Name);
public virtual Task<string> GetContactNameAsync(Tenant tenant, CancellationToken cancellationToken = default)
=> Task.FromResult(tenant.ContactName);
public virtual Task<string> GetContactEmailAsync(Tenant tenant, CancellationToken cancellationToken = default)
=> Task.FromResult(tenant.ContactEmail);
public virtual Task<string?> GetContactPhoneAsync(Tenant tenant, CancellationToken cancellationToken = default)
=> Task.FromResult(tenant.ContactPhone);
public virtual Task<int?> GetMaxUsersAsync(Tenant tenant, CancellationToken cancellationToken = default)
=> Task.FromResult(tenant.MaxUsers);
public virtual Task<string?> GetDescriptionAsync(Tenant tenant, CancellationToken cancellationToken = default)
=> Task.FromResult(tenant.Description);
public virtual Task<TenantStatus> GetStatusAsync(Tenant tenant, CancellationToken cancellationToken = default)
=> Task.FromResult(tenant.Status);
public virtual Task<DateTime?> GetExpiresAtAsync(Tenant tenant, CancellationToken cancellationToken = default)
=> Task.FromResult(tenant.ExpiresAt);
public virtual Task<DateTime> GetCreatedAtAsync(Tenant tenant, CancellationToken cancellationToken = default)
=> Task.FromResult(tenant.CreatedAt);
public virtual Task<DateTime?> GetUpdatedAtAsync(Tenant tenant, CancellationToken cancellationToken = default)
=> Task.FromResult(tenant.UpdatedAt);
public virtual Task<bool> GetIsDeletedAsync(Tenant tenant, CancellationToken cancellationToken = default)
=> Task.FromResult(tenant.IsDeleted);
public virtual Task SetTenantCodeAsync(Tenant tenant, string code, CancellationToken cancellationToken = default)
{
tenant.TenantCode = code;
return Task.CompletedTask;
}
public virtual Task SetNameAsync(Tenant tenant, string name, CancellationToken cancellationToken = default)
{
tenant.Name = name;
return Task.CompletedTask;
}
public virtual Task SetContactNameAsync(Tenant tenant, string name, CancellationToken cancellationToken = default)
{
tenant.ContactName = name;
return Task.CompletedTask;
}
public virtual Task SetContactEmailAsync(Tenant tenant, string email, CancellationToken cancellationToken = default)
{
tenant.ContactEmail = email;
return Task.CompletedTask;
}
public virtual Task SetContactPhoneAsync(Tenant tenant, string? phone, CancellationToken cancellationToken = default)
{
tenant.ContactPhone = phone;
return Task.CompletedTask;
}
public virtual Task SetMaxUsersAsync(Tenant tenant, int? maxUsers, CancellationToken cancellationToken = default)
{
tenant.MaxUsers = maxUsers;
return Task.CompletedTask;
}
public virtual Task SetDescriptionAsync(Tenant tenant, string? description, CancellationToken cancellationToken = default)
{
tenant.Description = description;
return Task.CompletedTask;
}
public virtual Task SetStatusAsync(Tenant tenant, TenantStatus status, CancellationToken cancellationToken = default)
{
tenant.Status = status;
return Task.CompletedTask;
}
public virtual Task SetExpiresAtAsync(Tenant tenant, DateTime? expiresAt, CancellationToken cancellationToken = default)
{
tenant.ExpiresAt = expiresAt;
return Task.CompletedTask;
}
public virtual Task SetIsDeletedAsync(Tenant tenant, bool isDeleted, CancellationToken cancellationToken = default)
{
tenant.IsDeleted = isDeleted;
return Task.CompletedTask;
}
}