feat: 租户审核领单与强制接管

This commit is contained in:
2025-12-15 10:40:50 +08:00
parent f54d4cf405
commit 2339775fcb
21 changed files with 7519 additions and 2 deletions

View File

@@ -108,6 +108,70 @@ public sealed class TenantsController(IMediator mediator) : BaseApiController
return ApiResponse<TenantDto>.Ok(result);
}
/// <summary>
/// 查询当前租户审核领取信息。
/// </summary>
/// <returns>领取信息,未领取返回 null。</returns>
[HttpGet("{tenantId:long}/review/claim")]
[PermissionAuthorize("tenant:review")]
[ProducesResponseType(typeof(ApiResponse<TenantReviewClaimDto?>), StatusCodes.Status200OK)]
public async Task<ApiResponse<TenantReviewClaimDto?>> GetReviewClaim(long tenantId, CancellationToken cancellationToken)
{
// 1. 查询领取信息
var result = await mediator.Send(new GetTenantReviewClaimQuery(tenantId), cancellationToken);
// 2. 返回领取信息
return ApiResponse<TenantReviewClaimDto?>.Ok(result);
}
/// <summary>
/// 领取租户入驻审核(领取后仅领取人可操作审核)。
/// </summary>
/// <returns>领取结果。</returns>
[HttpPost("{tenantId:long}/review/claim")]
[PermissionAuthorize("tenant:review")]
[ProducesResponseType(typeof(ApiResponse<TenantReviewClaimDto>), StatusCodes.Status200OK)]
public async Task<ApiResponse<TenantReviewClaimDto>> ClaimReview(long tenantId, CancellationToken cancellationToken)
{
// 1. 执行领取
var result = await mediator.Send(new ClaimTenantReviewCommand { TenantId = tenantId }, cancellationToken);
// 2. 返回领取结果
return ApiResponse<TenantReviewClaimDto>.Ok(result);
}
/// <summary>
/// 强制接管租户入驻审核(仅超级管理员可用)。
/// </summary>
/// <returns>接管后的领取信息。</returns>
[HttpPost("{tenantId:long}/review/force-claim")]
[PermissionAuthorize("tenant:review:force-claim")]
[ProducesResponseType(typeof(ApiResponse<TenantReviewClaimDto>), StatusCodes.Status200OK)]
public async Task<ApiResponse<TenantReviewClaimDto>> ForceClaimReview(long tenantId, CancellationToken cancellationToken)
{
// 1. 执行强制接管
var result = await mediator.Send(new ForceClaimTenantReviewCommand { TenantId = tenantId }, cancellationToken);
// 2. 返回接管结果
return ApiResponse<TenantReviewClaimDto>.Ok(result);
}
/// <summary>
/// 释放租户入驻审核领取(仅领取人可释放)。
/// </summary>
/// <returns>释放后的领取信息,未领取返回 null。</returns>
[HttpPost("{tenantId:long}/review/release")]
[PermissionAuthorize("tenant:review")]
[ProducesResponseType(typeof(ApiResponse<TenantReviewClaimDto?>), StatusCodes.Status200OK)]
public async Task<ApiResponse<TenantReviewClaimDto?>> ReleaseReview(long tenantId, CancellationToken cancellationToken)
{
// 1. 执行释放
var result = await mediator.Send(new ReleaseTenantReviewClaimCommand { TenantId = tenantId }, cancellationToken);
// 2. 返回释放结果
return ApiResponse<TenantReviewClaimDto?>.Ok(result);
}
/// <summary>
/// 创建或续费租户订阅。
/// </summary>

View File

@@ -73,6 +73,7 @@
"tenant:create",
"tenant:read",
"tenant:review",
"tenant:review:force-claim",
"tenant:subscription",
"tenant:quota:check",
"tenant-package:read",

View File

@@ -0,0 +1,17 @@
using MediatR;
using System.ComponentModel.DataAnnotations;
using TakeoutSaaS.Application.App.Tenants.Dto;
namespace TakeoutSaaS.Application.App.Tenants.Commands;
/// <summary>
/// 领取租户入驻审核命令。
/// </summary>
public sealed record ClaimTenantReviewCommand : IRequest<TenantReviewClaimDto>
{
/// <summary>
/// 租户 ID雪花算法
/// </summary>
[Required]
public long TenantId { get; init; }
}

View File

@@ -0,0 +1,17 @@
using MediatR;
using System.ComponentModel.DataAnnotations;
using TakeoutSaaS.Application.App.Tenants.Dto;
namespace TakeoutSaaS.Application.App.Tenants.Commands;
/// <summary>
/// 强制接管租户入驻审核命令(仅超级管理员可用)。
/// </summary>
public sealed record ForceClaimTenantReviewCommand : IRequest<TenantReviewClaimDto>
{
/// <summary>
/// 租户 ID雪花算法
/// </summary>
[Required]
public long TenantId { get; init; }
}

View File

@@ -0,0 +1,17 @@
using MediatR;
using System.ComponentModel.DataAnnotations;
using TakeoutSaaS.Application.App.Tenants.Dto;
namespace TakeoutSaaS.Application.App.Tenants.Commands;
/// <summary>
/// 释放租户入驻审核领取命令。
/// </summary>
public sealed record ReleaseTenantReviewClaimCommand : IRequest<TenantReviewClaimDto?>
{
/// <summary>
/// 租户 ID雪花算法
/// </summary>
[Required]
public long TenantId { get; init; }
}

View File

@@ -0,0 +1,38 @@
using System.Text.Json.Serialization;
using TakeoutSaaS.Shared.Abstractions.Serialization;
namespace TakeoutSaaS.Application.App.Tenants.Dto;
/// <summary>
/// 租户审核领取信息 DTO。
/// </summary>
public sealed class TenantReviewClaimDto
{
/// <summary>
/// 领取记录 ID。
/// </summary>
[JsonConverter(typeof(SnowflakeIdJsonConverter))]
public long Id { get; init; }
/// <summary>
/// 租户 ID。
/// </summary>
[JsonConverter(typeof(SnowflakeIdJsonConverter))]
public long TenantId { get; init; }
/// <summary>
/// 领取人用户 ID。
/// </summary>
[JsonConverter(typeof(SnowflakeIdJsonConverter))]
public long ClaimedBy { get; init; }
/// <summary>
/// 领取人名称。
/// </summary>
public string ClaimedByName { get; init; } = string.Empty;
/// <summary>
/// 领取时间。
/// </summary>
public DateTime ClaimedAt { get; init; }
}

View File

@@ -0,0 +1,92 @@
using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Application.Identity.Abstractions;
using TakeoutSaaS.Domain.Tenants.Entities;
using TakeoutSaaS.Domain.Tenants.Enums;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Security;
namespace TakeoutSaaS.Application.App.Tenants.Handlers;
/// <summary>
/// 领取租户入驻审核处理器。
/// </summary>
public sealed class ClaimTenantReviewCommandHandler(
ITenantRepository tenantRepository,
ICurrentUserAccessor currentUserAccessor,
IAdminAuthService adminAuthService)
: IRequestHandler<ClaimTenantReviewCommand, TenantReviewClaimDto>
{
/// <inheritdoc />
public async Task<TenantReviewClaimDto> Handle(ClaimTenantReviewCommand request, CancellationToken cancellationToken)
{
// 1. 校验租户存在
var tenant = await tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
?? throw new BusinessException(ErrorCodes.NotFound, "租户不存在");
// 2. 查询是否已领取
var existingClaim = await tenantRepository.GetActiveReviewClaimAsync(request.TenantId, cancellationToken);
if (existingClaim != null)
{
if (existingClaim.ClaimedBy == currentUserAccessor.UserId)
{
return existingClaim.ToDto();
}
throw new BusinessException(ErrorCodes.Conflict, $"该审核已被 {existingClaim.ClaimedByName} 领取");
}
// 3. (空行后) 获取当前用户显示名(用于展示快照)
var profile = await adminAuthService.GetProfileAsync(currentUserAccessor.UserId, cancellationToken);
var displayName = string.IsNullOrWhiteSpace(profile.DisplayName)
? $"user:{currentUserAccessor.UserId}"
: profile.DisplayName;
// 4. (空行后) 构造领取记录与审计日志
var now = DateTime.UtcNow;
var claim = new TenantReviewClaim
{
TenantId = request.TenantId,
ClaimedBy = currentUserAccessor.UserId,
ClaimedByName = displayName,
ClaimedAt = now,
ReleasedAt = null
};
var auditLog = new TenantAuditLog
{
TenantId = tenant.Id,
Action = TenantAuditAction.ReviewClaimed,
Title = "领取审核",
Description = $"领取人:{displayName}",
OperatorId = currentUserAccessor.UserId,
OperatorName = displayName,
PreviousStatus = tenant.Status,
CurrentStatus = tenant.Status
};
// 5. (空行后) 写入领取记录(处理并发领取冲突)
var success = await tenantRepository.TryAddReviewClaimAsync(claim, auditLog, cancellationToken);
if (!success)
{
var current = await tenantRepository.GetActiveReviewClaimAsync(request.TenantId, cancellationToken);
if (current == null)
{
throw new BusinessException(ErrorCodes.Conflict, "审核领取失败,请刷新后重试");
}
if (current.ClaimedBy == currentUserAccessor.UserId)
{
return current.ToDto();
}
throw new BusinessException(ErrorCodes.Conflict, $"该审核已被 {current.ClaimedByName} 领取");
}
// 6. (空行后) 返回领取结果
return claim.ToDto();
}
}

View File

@@ -0,0 +1,106 @@
using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Application.Identity.Abstractions;
using TakeoutSaaS.Domain.Tenants.Entities;
using TakeoutSaaS.Domain.Tenants.Enums;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Security;
namespace TakeoutSaaS.Application.App.Tenants.Handlers;
/// <summary>
/// 强制接管租户入驻审核处理器。
/// </summary>
public sealed class ForceClaimTenantReviewCommandHandler(
ITenantRepository tenantRepository,
ICurrentUserAccessor currentUserAccessor,
IAdminAuthService adminAuthService)
: IRequestHandler<ForceClaimTenantReviewCommand, TenantReviewClaimDto>
{
/// <inheritdoc />
public async Task<TenantReviewClaimDto> Handle(ForceClaimTenantReviewCommand request, CancellationToken cancellationToken)
{
// 1. 校验租户存在
var tenant = await tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
?? throw new BusinessException(ErrorCodes.NotFound, "租户不存在");
// 2. 获取当前用户显示名(用于展示快照)
var profile = await adminAuthService.GetProfileAsync(currentUserAccessor.UserId, cancellationToken);
var displayName = string.IsNullOrWhiteSpace(profile.DisplayName)
? $"user:{currentUserAccessor.UserId}"
: profile.DisplayName;
// 3. (空行后) 读取当前领取记录(可跟踪用于更新)
var claim = await tenantRepository.FindActiveReviewClaimAsync(request.TenantId, cancellationToken);
if (claim == null)
{
// 4. 未领取则直接创建(记录强制接管动作)
var now = DateTime.UtcNow;
var created = new TenantReviewClaim
{
TenantId = request.TenantId,
ClaimedBy = currentUserAccessor.UserId,
ClaimedByName = displayName,
ClaimedAt = now,
ReleasedAt = null
};
var auditLog = new TenantAuditLog
{
TenantId = tenant.Id,
Action = TenantAuditAction.ReviewForceClaimed,
Title = "强制接管审核",
Description = $"接管人:{displayName}",
OperatorId = currentUserAccessor.UserId,
OperatorName = displayName,
PreviousStatus = tenant.Status,
CurrentStatus = tenant.Status
};
var success = await tenantRepository.TryAddReviewClaimAsync(created, auditLog, cancellationToken);
if (!success)
{
var current = await tenantRepository.GetActiveReviewClaimAsync(request.TenantId, cancellationToken);
if (current != null)
{
return current.ToDto();
}
throw new BusinessException(ErrorCodes.Conflict, "审核接管失败,请刷新后重试");
}
return created.ToDto();
}
// 5. (空行后) 已由自己领取则直接返回
if (claim.ClaimedBy == currentUserAccessor.UserId)
{
return claim.ToDto();
}
// 6. (空行后) 更新领取人并记录审计
var previousOwner = claim.ClaimedByName;
claim.ClaimedBy = currentUserAccessor.UserId;
claim.ClaimedByName = displayName;
claim.ClaimedAt = DateTime.UtcNow;
await tenantRepository.UpdateReviewClaimAsync(claim, cancellationToken);
await tenantRepository.AddAuditLogAsync(new TenantAuditLog
{
TenantId = tenant.Id,
Action = TenantAuditAction.ReviewForceClaimed,
Title = "强制接管审核",
Description = $"原领取人:{previousOwner},接管人:{displayName}",
OperatorId = currentUserAccessor.UserId,
OperatorName = displayName,
PreviousStatus = tenant.Status,
CurrentStatus = tenant.Status
}, cancellationToken);
await tenantRepository.SaveChangesAsync(cancellationToken);
return claim.ToDto();
}
}

View File

@@ -0,0 +1,21 @@
using MediatR;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Application.App.Tenants.Queries;
using TakeoutSaaS.Domain.Tenants.Repositories;
namespace TakeoutSaaS.Application.App.Tenants.Handlers;
/// <summary>
/// 获取租户审核领取信息查询处理器。
/// </summary>
public sealed class GetTenantReviewClaimQueryHandler(ITenantRepository tenantRepository)
: IRequestHandler<GetTenantReviewClaimQuery, TenantReviewClaimDto?>
{
/// <inheritdoc />
public async Task<TenantReviewClaimDto?> Handle(GetTenantReviewClaimQuery request, CancellationToken cancellationToken)
{
// 1. 查询当前领取信息(未领取返回 null
var claim = await tenantRepository.GetActiveReviewClaimAsync(request.TenantId, cancellationToken);
return claim?.ToDto();
}
}

View File

@@ -0,0 +1,67 @@
using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Application.Identity.Abstractions;
using TakeoutSaaS.Domain.Tenants.Entities;
using TakeoutSaaS.Domain.Tenants.Enums;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Security;
namespace TakeoutSaaS.Application.App.Tenants.Handlers;
/// <summary>
/// 释放租户入驻审核领取处理器。
/// </summary>
public sealed class ReleaseTenantReviewClaimCommandHandler(
ITenantRepository tenantRepository,
ICurrentUserAccessor currentUserAccessor,
IAdminAuthService adminAuthService)
: IRequestHandler<ReleaseTenantReviewClaimCommand, TenantReviewClaimDto?>
{
/// <inheritdoc />
public async Task<TenantReviewClaimDto?> Handle(ReleaseTenantReviewClaimCommand request, CancellationToken cancellationToken)
{
// 1. 校验租户存在
var tenant = await tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
?? throw new BusinessException(ErrorCodes.NotFound, "租户不存在");
// 2. 查询当前领取记录
var claim = await tenantRepository.FindActiveReviewClaimAsync(request.TenantId, cancellationToken);
if (claim == null)
{
return null;
}
// 3. (空行后) 非领取人不允许释放(如需接管请使用强制接管)
if (claim.ClaimedBy != currentUserAccessor.UserId)
{
throw new BusinessException(ErrorCodes.Conflict, $"该审核已被 {claim.ClaimedByName} 领取");
}
// 4. (空行后) 释放领取并记录审计
var profile = await adminAuthService.GetProfileAsync(currentUserAccessor.UserId, cancellationToken);
var displayName = string.IsNullOrWhiteSpace(profile.DisplayName)
? $"user:{currentUserAccessor.UserId}"
: profile.DisplayName;
claim.ReleasedAt = DateTime.UtcNow;
await tenantRepository.UpdateReviewClaimAsync(claim, cancellationToken);
await tenantRepository.AddAuditLogAsync(new TenantAuditLog
{
TenantId = tenant.Id,
Action = TenantAuditAction.ReviewClaimReleased,
Title = "释放审核",
Description = $"释放人:{displayName}",
OperatorId = currentUserAccessor.UserId,
OperatorName = displayName,
PreviousStatus = tenant.Status,
CurrentStatus = tenant.Status
}, cancellationToken);
await tenantRepository.SaveChangesAsync(cancellationToken);
return claim.ToDto();
}
}

View File

@@ -24,6 +24,14 @@ public sealed class ReviewTenantCommandHandler(
var tenant = await tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
?? throw new BusinessException(ErrorCodes.NotFound, "租户不存在");
var reviewClaim = await tenantRepository.FindActiveReviewClaimAsync(request.TenantId, cancellationToken)
?? throw new BusinessException(ErrorCodes.Conflict, "请先领取审核");
if (reviewClaim.ClaimedBy != currentUserAccessor.UserId)
{
throw new BusinessException(ErrorCodes.Conflict, $"该审核已被 {reviewClaim.ClaimedByName} 领取");
}
var verification = await tenantRepository.GetVerificationProfileAsync(request.TenantId, cancellationToken)
?? throw new BusinessException(ErrorCodes.BadRequest, "请先提交实名认证资料");
@@ -83,7 +91,22 @@ public sealed class ReviewTenantCommandHandler(
CurrentStatus = tenant.Status
}, cancellationToken);
// 7. 保存并返回 DTO
// 7. (空行后) 审核完成自动释放领取
reviewClaim.ReleasedAt = DateTime.UtcNow;
await tenantRepository.UpdateReviewClaimAsync(reviewClaim, cancellationToken);
await tenantRepository.AddAuditLogAsync(new Domain.Tenants.Entities.TenantAuditLog
{
TenantId = tenant.Id,
Action = TenantAuditAction.ReviewClaimReleased,
Title = "审核完成释放",
Description = $"释放人:{actorName}",
OperatorId = currentUserAccessor.UserId == 0 ? null : currentUserAccessor.UserId,
OperatorName = actorName,
PreviousStatus = tenant.Status,
CurrentStatus = tenant.Status
}, cancellationToken);
// 8. 保存并返回 DTO
await tenantRepository.SaveChangesAsync(cancellationToken);
return TenantMapping.ToDto(tenant, subscription, verification);

View File

@@ -0,0 +1,9 @@
using MediatR;
using TakeoutSaaS.Application.App.Tenants.Dto;
namespace TakeoutSaaS.Application.App.Tenants.Queries;
/// <summary>
/// 获取租户审核领取信息查询。
/// </summary>
public sealed record GetTenantReviewClaimQuery(long TenantId) : IRequest<TenantReviewClaimDto?>;

View File

@@ -102,6 +102,21 @@ internal static class TenantMapping
CreatedAt = log.CreatedAt
};
/// <summary>
/// 将审核领取实体映射为 DTO。
/// </summary>
/// <param name="claim">领取实体。</param>
/// <returns>领取 DTO。</returns>
public static TenantReviewClaimDto ToDto(this TenantReviewClaim claim)
=> new()
{
Id = claim.Id,
TenantId = claim.TenantId,
ClaimedBy = claim.ClaimedBy,
ClaimedByName = claim.ClaimedByName,
ClaimedAt = claim.ClaimedAt
};
/// <summary>
/// 将套餐实体映射为 DTO。
/// </summary>

View File

@@ -0,0 +1,34 @@
using TakeoutSaaS.Shared.Abstractions.Entities;
namespace TakeoutSaaS.Domain.Tenants.Entities;
/// <summary>
/// 租户入驻审核领取记录(防止多管理员并发审核)。
/// </summary>
public sealed class TenantReviewClaim : AuditableEntityBase
{
/// <summary>
/// 被领取的租户 ID。
/// </summary>
public long TenantId { get; set; }
/// <summary>
/// 领取人用户 ID。
/// </summary>
public long ClaimedBy { get; set; }
/// <summary>
/// 领取人名称(展示用快照)。
/// </summary>
public string ClaimedByName { get; set; } = string.Empty;
/// <summary>
/// 领取时间UTC
/// </summary>
public DateTime ClaimedAt { get; set; }
/// <summary>
/// 释放时间UTC未释放时为 null。
/// </summary>
public DateTime? ReleasedAt { get; set; }
}

View File

@@ -38,5 +38,20 @@ public enum TenantAuditAction
/// <summary>
/// 租户状态变更(启用/停用/到期等)。
/// </summary>
StatusChanged = 7
StatusChanged = 7,
/// <summary>
/// 领取入驻审核。
/// </summary>
ReviewClaimed = 8,
/// <summary>
/// 强制接管入驻审核。
/// </summary>
ReviewForceClaimed = 9,
/// <summary>
/// 释放入驻审核(审核完成或手动释放)。
/// </summary>
ReviewClaimReleased = 10
}

View File

@@ -118,6 +118,38 @@ public interface ITenantRepository
/// <returns>异步任务。</returns>
Task UpsertVerificationProfileAsync(TenantVerificationProfile profile, CancellationToken cancellationToken = default);
/// <summary>
/// 获取当前审核领取信息(仅返回未释放的记录)。
/// </summary>
/// <param name="tenantId">租户 ID雪花算法。</param>
/// <param name="cancellationToken">取消标记。</param>
/// <returns>领取记录,未领取返回 null。</returns>
Task<TenantReviewClaim?> GetActiveReviewClaimAsync(long tenantId, CancellationToken cancellationToken = default);
/// <summary>
/// 查询当前审核领取信息(用于更新,返回可跟踪实体)。
/// </summary>
/// <param name="tenantId">租户 ID雪花算法。</param>
/// <param name="cancellationToken">取消标记。</param>
/// <returns>领取记录,未领取返回 null。</returns>
Task<TenantReviewClaim?> FindActiveReviewClaimAsync(long tenantId, CancellationToken cancellationToken = default);
/// <summary>
/// 新增审核领取记录。
/// </summary>
/// <param name="claim">领取记录。</param>
/// <param name="auditLog">领取动作审计日志。</param>
/// <param name="cancellationToken">取消标记。</param>
/// <returns>新增成功返回 true若已被其他人领取导致冲突则返回 false。</returns>
Task<bool> TryAddReviewClaimAsync(TenantReviewClaim claim, TenantAuditLog auditLog, CancellationToken cancellationToken = default);
/// <summary>
/// 更新审核领取记录。
/// </summary>
/// <param name="claim">领取记录。</param>
/// <param name="cancellationToken">取消标记。</param>
Task UpdateReviewClaimAsync(TenantReviewClaim claim, CancellationToken cancellationToken = default);
/// <summary>
/// 获取当前订阅。
/// </summary>

View File

@@ -81,6 +81,10 @@ public sealed class TakeoutAppDbContext(
/// </summary>
public DbSet<TenantAuditLog> TenantAuditLogs => Set<TenantAuditLog>();
/// <summary>
/// 租户审核领取记录。
/// </summary>
public DbSet<TenantReviewClaim> TenantReviewClaims => Set<TenantReviewClaim>();
/// <summary>
/// 商户实体。
/// </summary>
public DbSet<Merchant> Merchants => Set<Merchant>();
@@ -374,6 +378,7 @@ public sealed class TakeoutAppDbContext(
ConfigureTenantAnnouncementRead(modelBuilder.Entity<TenantAnnouncementRead>());
ConfigureTenantVerificationProfile(modelBuilder.Entity<TenantVerificationProfile>());
ConfigureTenantAuditLog(modelBuilder.Entity<TenantAuditLog>());
ConfigureTenantReviewClaim(modelBuilder.Entity<TenantReviewClaim>());
ConfigureMerchantDocument(modelBuilder.Entity<MerchantDocument>());
ConfigureMerchantContract(modelBuilder.Entity<MerchantContract>());
ConfigureMerchantStaff(modelBuilder.Entity<MerchantStaff>());
@@ -491,6 +496,20 @@ public sealed class TakeoutAppDbContext(
builder.HasIndex(x => x.TenantId);
}
private static void ConfigureTenantReviewClaim(EntityTypeBuilder<TenantReviewClaim> builder)
{
builder.ToTable("tenant_review_claims");
builder.HasKey(x => x.Id);
builder.Property(x => x.TenantId).IsRequired();
builder.Property(x => x.ClaimedBy).IsRequired();
builder.Property(x => x.ClaimedByName).HasMaxLength(64).IsRequired();
builder.Property(x => x.ClaimedAt).IsRequired();
builder.Property(x => x.ReleasedAt);
builder.HasIndex(x => x.TenantId);
builder.HasIndex(x => x.ClaimedBy);
builder.HasIndex(x => x.TenantId).IsUnique().HasFilter("\"ReleasedAt\" IS NULL AND \"DeletedAt\" IS NULL");
}
private static void ConfigureTenantSubscriptionHistory(EntityTypeBuilder<TenantSubscriptionHistory> builder)
{
builder.ToTable("tenant_subscription_histories");

View File

@@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore;
using Npgsql;
using TakeoutSaaS.Domain.Tenants.Entities;
using TakeoutSaaS.Domain.Tenants.Enums;
using TakeoutSaaS.Domain.Tenants.Repositories;
@@ -214,6 +215,54 @@ public sealed class EfTenantRepository(TakeoutAppDbContext context) : ITenantRep
context.Entry(existing).CurrentValues.SetValues(profile);
}
/// <inheritdoc />
public Task<TenantReviewClaim?> GetActiveReviewClaimAsync(long tenantId, CancellationToken cancellationToken = default)
{
return context.TenantReviewClaims
.AsNoTracking()
.Where(x => x.TenantId == tenantId && x.ReleasedAt == null)
.OrderByDescending(x => x.ClaimedAt)
.FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc />
public Task<TenantReviewClaim?> FindActiveReviewClaimAsync(long tenantId, CancellationToken cancellationToken = default)
{
return context.TenantReviewClaims
.Where(x => x.TenantId == tenantId && x.ReleasedAt == null)
.OrderByDescending(x => x.ClaimedAt)
.FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc />
public async Task<bool> TryAddReviewClaimAsync(
TenantReviewClaim claim,
TenantAuditLog auditLog,
CancellationToken cancellationToken = default)
{
try
{
await context.TenantReviewClaims.AddAsync(claim, cancellationToken);
await context.TenantAuditLogs.AddAsync(auditLog, cancellationToken);
await context.SaveChangesAsync(cancellationToken);
return true;
}
catch (DbUpdateException ex) when (ex.InnerException is PostgresException pg && pg.SqlState == PostgresErrorCodes.UniqueViolation)
{
context.Entry(claim).State = EntityState.Detached;
context.Entry(auditLog).State = EntityState.Detached;
return false;
}
}
/// <inheritdoc />
public Task UpdateReviewClaimAsync(TenantReviewClaim claim, CancellationToken cancellationToken = default)
{
context.TenantReviewClaims.Update(claim);
return Task.CompletedTask;
}
/// <inheritdoc />
public Task<TenantSubscription?> GetActiveSubscriptionAsync(long tenantId, CancellationToken cancellationToken = default)
{

View File

@@ -0,0 +1,59 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace TakeoutSaaS.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AddTenantReviewClaim : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "tenant_review_claims",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false, comment: "实体唯一标识。")
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "被领取的租户 ID。"),
ClaimedBy = table.Column<long>(type: "bigint", nullable: false, comment: "领取人用户 ID。"),
ClaimedByName = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false, comment: "领取人名称(展示用快照)。"),
ClaimedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "领取时间UTC。"),
ReleasedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "释放时间UTC未释放时为 null。"),
CreatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false, comment: "创建时间UTC。"),
UpdatedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "最近一次更新时间UTC从未更新时为 null。"),
DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "软删除时间UTC未删除时为 null。"),
CreatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "创建人用户标识,匿名或系统操作时为 null。"),
UpdatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "最后更新人用户标识,匿名或系统操作时为 null。"),
DeletedBy = table.Column<long>(type: "bigint", nullable: true, comment: "删除人用户标识(软删除),未删除时为 null。")
},
constraints: table =>
{
table.PrimaryKey("PK_tenant_review_claims", x => x.Id);
},
comment: "租户入驻审核领取记录(防止多管理员并发审核)。");
migrationBuilder.CreateIndex(
name: "IX_tenant_review_claims_ClaimedBy",
table: "tenant_review_claims",
column: "ClaimedBy");
migrationBuilder.CreateIndex(
name: "IX_tenant_review_claims_TenantId",
table: "tenant_review_claims",
column: "TenantId",
unique: true,
filter: "\"ReleasedAt\" IS NULL AND \"DeletedAt\" IS NULL");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "tenant_review_claims");
}
}
}

View File

@@ -6380,6 +6380,75 @@ namespace TakeoutSaaS.Infrastructure.Migrations
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Tenants.Entities.TenantReviewClaim", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasComment("实体唯一标识。");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTime>("ClaimedAt")
.HasColumnType("timestamp with time zone")
.HasComment("领取时间UTC。");
b.Property<long>("ClaimedBy")
.HasColumnType("bigint")
.HasComment("领取人用户 ID。");
b.Property<string>("ClaimedByName")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasComment("领取人名称(展示用快照)。");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasComment("创建时间UTC。");
b.Property<long?>("CreatedBy")
.HasColumnType("bigint")
.HasComment("创建人用户标识,匿名或系统操作时为 null。");
b.Property<DateTime?>("DeletedAt")
.HasColumnType("timestamp with time zone")
.HasComment("软删除时间UTC未删除时为 null。");
b.Property<long?>("DeletedBy")
.HasColumnType("bigint")
.HasComment("删除人用户标识(软删除),未删除时为 null。");
b.Property<DateTime?>("ReleasedAt")
.HasColumnType("timestamp with time zone")
.HasComment("释放时间UTC未释放时为 null。");
b.Property<long>("TenantId")
.HasColumnType("bigint")
.HasComment("被领取的租户 ID。");
b.Property<DateTime?>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasComment("最近一次更新时间UTC从未更新时为 null。");
b.Property<long?>("UpdatedBy")
.HasColumnType("bigint")
.HasComment("最后更新人用户标识,匿名或系统操作时为 null。");
b.HasKey("Id");
b.HasIndex("ClaimedBy");
b.HasIndex("TenantId")
.IsUnique()
.HasFilter("\"ReleasedAt\" IS NULL AND \"DeletedAt\" IS NULL");
b.ToTable("tenant_review_claims", null, t =>
{
t.HasComment("租户入驻审核领取记录(防止多管理员并发审核)。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Tenants.Entities.TenantSubscription", b =>
{
b.Property<long>("Id")