feat: 提交后端其余改动

This commit is contained in:
2026-01-01 07:41:57 +08:00
parent fc55003d3d
commit aa42a635e4
34 changed files with 2426 additions and 1208 deletions

View File

@@ -0,0 +1,176 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TakeoutSaaS.Application.Dictionary.Models;
using TakeoutSaaS.Application.Dictionary.Services;
using TakeoutSaaS.Domain.Dictionary.Enums;
using TakeoutSaaS.Module.Authorization.Attributes;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Results;
using TakeoutSaaS.Shared.Abstractions.Security;
using TakeoutSaaS.Shared.Abstractions.Tenancy;
using TakeoutSaaS.Shared.Web.Api;
namespace TakeoutSaaS.AdminApi.Controllers;
/// <summary>
/// 字典标签覆盖管理。
/// </summary>
[ApiVersion("1.0")]
[Authorize]
[Route("api/admin/v{version:apiVersion}/dictionary/label-overrides")]
public sealed class DictionaryLabelOverridesController(
DictionaryLabelOverrideService labelOverrideService,
ITenantProvider tenantProvider,
ICurrentUserAccessor currentUserAccessor)
: BaseApiController
{
private const string TenantIdHeaderName = "X-Tenant-Id";
#region API
/// <summary>
/// 获取当前租户的标签覆盖列表。
/// </summary>
[HttpGet("tenant")]
[PermissionAuthorize("dictionary:override:read")]
[ProducesResponseType(typeof(ApiResponse<IReadOnlyList<LabelOverrideDto>>), StatusCodes.Status200OK)]
public async Task<ApiResponse<IReadOnlyList<LabelOverrideDto>>> ListTenantOverrides(
[FromQuery] OverrideType? overrideType,
CancellationToken cancellationToken)
{
var headerError = EnsureTenantHeader<IReadOnlyList<LabelOverrideDto>>();
if (headerError != null)
{
return headerError;
}
var tenantId = tenantProvider.GetCurrentTenantId();
var result = await labelOverrideService.GetOverridesAsync(tenantId, overrideType, cancellationToken);
return ApiResponse<IReadOnlyList<LabelOverrideDto>>.Ok(result);
}
/// <summary>
/// 租户覆盖系统字典项的标签。
/// </summary>
[HttpPost("tenant")]
[PermissionAuthorize("dictionary:override:update")]
[ProducesResponseType(typeof(ApiResponse<LabelOverrideDto>), StatusCodes.Status200OK)]
public async Task<ApiResponse<LabelOverrideDto>> CreateTenantOverride(
[FromBody] UpsertLabelOverrideRequest request,
CancellationToken cancellationToken)
{
var headerError = EnsureTenantHeader<LabelOverrideDto>();
if (headerError != null)
{
return headerError;
}
var tenantId = tenantProvider.GetCurrentTenantId();
var operatorId = currentUserAccessor.UserId;
var result = await labelOverrideService.UpsertTenantOverrideAsync(tenantId, request, operatorId, cancellationToken);
return ApiResponse<LabelOverrideDto>.Ok(result);
}
/// <summary>
/// 租户删除自己的标签覆盖。
/// </summary>
[HttpDelete("tenant/{dictionaryItemId:long}")]
[PermissionAuthorize("dictionary:override:delete")]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
public async Task<ApiResponse<object>> DeleteTenantOverride(long dictionaryItemId, CancellationToken cancellationToken)
{
var headerError = EnsureTenantHeader<object>();
if (headerError != null)
{
return headerError;
}
var tenantId = tenantProvider.GetCurrentTenantId();
var operatorId = currentUserAccessor.UserId;
var success = await labelOverrideService.DeleteOverrideAsync(
tenantId,
dictionaryItemId,
operatorId,
allowPlatformEnforcement: false,
cancellationToken);
return success
? ApiResponse.Success()
: ApiResponse.Error(ErrorCodes.NotFound, "覆盖配置不存在");
}
#endregion
#region API
/// <summary>
/// 获取指定租户的所有标签覆盖(平台管理员用)。
/// </summary>
[HttpGet("platform/{targetTenantId:long}")]
[PermissionAuthorize("dictionary:override:platform:read")]
[ProducesResponseType(typeof(ApiResponse<IReadOnlyList<LabelOverrideDto>>), StatusCodes.Status200OK)]
public async Task<ApiResponse<IReadOnlyList<LabelOverrideDto>>> ListPlatformOverrides(
long targetTenantId,
[FromQuery] OverrideType? overrideType,
CancellationToken cancellationToken)
{
var result = await labelOverrideService.GetOverridesAsync(targetTenantId, overrideType, cancellationToken);
return ApiResponse<IReadOnlyList<LabelOverrideDto>>.Ok(result);
}
/// <summary>
/// 平台强制覆盖租户字典项的标签。
/// </summary>
[HttpPost("platform/{targetTenantId:long}")]
[PermissionAuthorize("dictionary:override:platform:update")]
[ProducesResponseType(typeof(ApiResponse<LabelOverrideDto>), StatusCodes.Status200OK)]
public async Task<ApiResponse<LabelOverrideDto>> CreatePlatformOverride(
long targetTenantId,
[FromBody] UpsertLabelOverrideRequest request,
CancellationToken cancellationToken)
{
var operatorId = currentUserAccessor.UserId;
var result = await labelOverrideService.UpsertPlatformOverrideAsync(targetTenantId, request, operatorId, cancellationToken);
return ApiResponse<LabelOverrideDto>.Ok(result);
}
/// <summary>
/// 平台删除对租户的强制覆盖。
/// </summary>
[HttpDelete("platform/{targetTenantId:long}/{dictionaryItemId:long}")]
[PermissionAuthorize("dictionary:override:platform:delete")]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
public async Task<ApiResponse<object>> DeletePlatformOverride(
long targetTenantId,
long dictionaryItemId,
CancellationToken cancellationToken)
{
var operatorId = currentUserAccessor.UserId;
var success = await labelOverrideService.DeleteOverrideAsync(
targetTenantId,
dictionaryItemId,
operatorId,
cancellationToken: cancellationToken);
return success
? ApiResponse.Success()
: ApiResponse.Error(ErrorCodes.NotFound, "覆盖配置不存在");
}
#endregion
private ApiResponse<T>? EnsureTenantHeader<T>()
{
if (!Request.Headers.TryGetValue(TenantIdHeaderName, out var tenantHeader) || string.IsNullOrWhiteSpace(tenantHeader))
{
return ApiResponse<T>.Error(StatusCodes.Status400BadRequest, $"缺少租户标识,请在请求头 {TenantIdHeaderName} 指定租户");
}
if (!long.TryParse(tenantHeader.FirstOrDefault(), out _))
{
return ApiResponse<T>.Error(StatusCodes.Status400BadRequest, $"租户标识无效,请在请求头 {TenantIdHeaderName} 指定正确的租户 ID");
}
return null;
}
}

View File

@@ -19,6 +19,7 @@ public static class DictionaryServiceCollectionExtensions
services.AddScoped<DictionaryQueryService>();
services.AddScoped<DictionaryMergeService>();
services.AddScoped<DictionaryOverrideService>();
services.AddScoped<DictionaryLabelOverrideService>();
services.AddScoped<DictionaryImportExportService>();
return services;
}

View File

@@ -0,0 +1,119 @@
using System.Text.Json.Serialization;
using TakeoutSaaS.Domain.Dictionary.Enums;
using TakeoutSaaS.Shared.Abstractions.Serialization;
namespace TakeoutSaaS.Application.Dictionary.Models;
/// <summary>
/// 字典标签覆盖 DTO。
/// </summary>
public sealed class LabelOverrideDto
{
/// <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 DictionaryItemId { get; init; }
/// <summary>
/// 字典项 Key。
/// </summary>
public string DictionaryItemKey { get; init; } = string.Empty;
/// <summary>
/// 原始显示值(多语言)。
/// </summary>
public Dictionary<string, string> OriginalValue { get; init; } = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// 覆盖后的显示值(多语言)。
/// </summary>
public Dictionary<string, string> OverrideValue { get; init; } = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// 覆盖类型。
/// </summary>
public OverrideType OverrideType { get; init; }
/// <summary>
/// 覆盖类型名称。
/// </summary>
public string OverrideTypeName => OverrideType switch
{
OverrideType.TenantCustomization => "租户定制",
OverrideType.PlatformEnforcement => "平台强制",
_ => "未知"
};
/// <summary>
/// 覆盖原因/备注。
/// </summary>
public string? Reason { get; init; }
/// <summary>
/// 创建时间。
/// </summary>
public DateTime CreatedAt { get; init; }
/// <summary>
/// 更新时间。
/// </summary>
public DateTime? UpdatedAt { get; init; }
/// <summary>
/// 创建人 ID。
/// </summary>
[JsonConverter(typeof(SnowflakeIdJsonConverter))]
public long? CreatedBy { get; init; }
/// <summary>
/// 更新人 ID。
/// </summary>
[JsonConverter(typeof(SnowflakeIdJsonConverter))]
public long? UpdatedBy { get; init; }
}
/// <summary>
/// 创建/更新标签覆盖请求。
/// </summary>
public sealed class UpsertLabelOverrideRequest
{
/// <summary>
/// 被覆盖的字典项 ID。
/// </summary>
[JsonConverter(typeof(SnowflakeIdJsonConverter))]
public long DictionaryItemId { get; init; }
/// <summary>
/// 覆盖后的显示值(多语言)。
/// </summary>
public Dictionary<string, string> OverrideValue { get; init; } = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// 覆盖原因/备注(平台强制覆盖时建议填写)。
/// </summary>
public string? Reason { get; init; }
}
/// <summary>
/// 批量覆盖请求。
/// </summary>
public sealed class BatchLabelOverrideRequest
{
/// <summary>
/// 覆盖项列表。
/// </summary>
public List<UpsertLabelOverrideRequest> Items { get; init; } = new();
}

View File

@@ -0,0 +1,20 @@
using Microsoft.AspNetCore.Http;
namespace TakeoutSaaS.Application.Dictionary.Services;
internal static class DictionaryAccessHelper
{
internal static bool IsPlatformAdmin(IHttpContextAccessor httpContextAccessor)
{
var user = httpContextAccessor.HttpContext?.User;
if (user?.Identity?.IsAuthenticated != true)
{
return false;
}
return user.IsInRole("PlatformAdmin") ||
user.IsInRole("platform-admin") ||
user.IsInRole("super-admin") ||
user.IsInRole("SUPER_ADMIN");
}
}

View File

@@ -1,4 +1,5 @@
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using System.Security.Cryptography;
using TakeoutSaaS.Application.Dictionary.Abstractions;
using TakeoutSaaS.Application.Dictionary.Contracts;
@@ -19,6 +20,7 @@ public sealed class DictionaryAppService(
IDictionaryRepository repository,
IDictionaryCache cache,
ITenantProvider tenantProvider,
IHttpContextAccessor httpContextAccessor,
ILogger<DictionaryAppService> logger) : IDictionaryAppService
{
/// <summary>
@@ -354,7 +356,7 @@ public sealed class DictionaryAppService(
private void EnsureScopePermission(DictionaryScope scope)
{
var tenantId = tenantProvider.GetCurrentTenantId();
if (scope == DictionaryScope.System && tenantId != 0)
if (scope == DictionaryScope.System && tenantId != 0 && !DictionaryAccessHelper.IsPlatformAdmin(httpContextAccessor))
{
throw new BusinessException(ErrorCodes.Forbidden, "仅平台管理员可操作系统字典");
}
@@ -362,7 +364,7 @@ public sealed class DictionaryAppService(
private void EnsurePlatformTenant(long tenantId)
{
if (tenantId != 0)
if (tenantId != 0 && !DictionaryAccessHelper.IsPlatformAdmin(httpContextAccessor))
{
throw new BusinessException(ErrorCodes.Forbidden, "仅平台管理员可操作系统字典");
}

View File

@@ -1,5 +1,6 @@
using System.Security.Cryptography;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using TakeoutSaaS.Application.Dictionary.Abstractions;
using TakeoutSaaS.Application.Dictionary.Contracts;
using TakeoutSaaS.Application.Dictionary.Models;
@@ -21,6 +22,7 @@ public sealed class DictionaryCommandService(
IDictionaryItemRepository itemRepository,
IDictionaryHybridCache cache,
ITenantProvider tenantProvider,
IHttpContextAccessor httpContextAccessor,
ILogger<DictionaryCommandService> logger)
{
/// <summary>
@@ -229,7 +231,7 @@ public sealed class DictionaryCommandService(
var tenantId = tenantProvider.GetCurrentTenantId();
if (scope == DictionaryScope.System)
{
if (tenantId != 0)
if (tenantId != 0 && !DictionaryAccessHelper.IsPlatformAdmin(httpContextAccessor))
{
throw new BusinessException(ErrorCodes.Forbidden, "仅平台管理员可创建系统字典");
}
@@ -248,7 +250,7 @@ public sealed class DictionaryCommandService(
private void EnsureGroupAccess(DictionaryGroup group)
{
var tenantId = tenantProvider.GetCurrentTenantId();
if (group.Scope == DictionaryScope.System && tenantId != 0)
if (group.Scope == DictionaryScope.System && tenantId != 0 && !DictionaryAccessHelper.IsPlatformAdmin(httpContextAccessor))
{
throw new BusinessException(ErrorCodes.Forbidden, "仅平台管理员可操作系统字典");
}

View File

@@ -14,6 +14,7 @@ using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Security;
using TakeoutSaaS.Shared.Abstractions.Tenancy;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
namespace TakeoutSaaS.Application.Dictionary.Services;
@@ -29,6 +30,7 @@ public sealed class DictionaryImportExportService(
IDictionaryHybridCache cache,
ITenantProvider tenantProvider,
ICurrentUserAccessor currentUser,
IHttpContextAccessor httpContextAccessor,
ILogger<DictionaryImportExportService> logger)
{
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
@@ -424,7 +426,7 @@ public sealed class DictionaryImportExportService(
private void EnsureGroupAccess(DictionaryGroup group)
{
var tenantId = tenantProvider.GetCurrentTenantId();
if (group.Scope == DictionaryScope.System && tenantId != 0)
if (group.Scope == DictionaryScope.System && tenantId != 0 && !DictionaryAccessHelper.IsPlatformAdmin(httpContextAccessor))
{
throw new BusinessException(ErrorCodes.Forbidden, "仅平台管理员可操作系统字典");
}

View File

@@ -0,0 +1,234 @@
using TakeoutSaaS.Application.Dictionary.Models;
using TakeoutSaaS.Domain.Dictionary.Entities;
using TakeoutSaaS.Domain.Dictionary.Enums;
using TakeoutSaaS.Domain.Dictionary.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
namespace TakeoutSaaS.Application.Dictionary.Services;
/// <summary>
/// 字典标签覆盖服务。
/// </summary>
public sealed class DictionaryLabelOverrideService(
IDictionaryLabelOverrideRepository overrideRepository,
IDictionaryItemRepository itemRepository)
{
/// <summary>
/// 获取租户的所有标签覆盖。
/// </summary>
/// <param name="tenantId">租户 ID。</param>
/// <param name="overrideType">可选的覆盖类型过滤。</param>
/// <param name="cancellationToken">取消标记。</param>
public async Task<IReadOnlyList<LabelOverrideDto>> GetOverridesAsync(
long tenantId,
OverrideType? overrideType = null,
CancellationToken cancellationToken = default)
{
var overrides = await overrideRepository.ListByTenantAsync(tenantId, overrideType, cancellationToken);
return overrides.Select(MapToDto).ToList();
}
/// <summary>
/// 获取指定字典项的覆盖配置。
/// </summary>
/// <param name="tenantId">租户 ID。</param>
/// <param name="dictionaryItemId">字典项 ID。</param>
/// <param name="cancellationToken">取消标记。</param>
public async Task<LabelOverrideDto?> GetOverrideByItemIdAsync(
long tenantId,
long dictionaryItemId,
CancellationToken cancellationToken = default)
{
var entity = await overrideRepository.GetByItemIdAsync(tenantId, dictionaryItemId, cancellationToken);
return entity == null ? null : MapToDto(entity);
}
/// <summary>
/// 创建或更新租户对系统字典的标签覆盖(租户定制)。
/// </summary>
/// <param name="tenantId">租户 ID。</param>
/// <param name="request">覆盖请求。</param>
/// <param name="operatorId">操作人 ID。</param>
/// <param name="cancellationToken">取消标记。</param>
public async Task<LabelOverrideDto> UpsertTenantOverrideAsync(
long tenantId,
UpsertLabelOverrideRequest request,
long operatorId,
CancellationToken cancellationToken = default)
{
// 1. 验证字典项存在且为系统字典
var item = await itemRepository.GetByIdAsync(request.DictionaryItemId, cancellationToken);
if (item == null)
{
throw new BusinessException(ErrorCodes.NotFound, "字典项不存在");
}
if (item.TenantId != 0)
{
throw new BusinessException(ErrorCodes.ValidationFailed, "租户只能覆盖系统字典项");
}
// 2. 查找现有覆盖或创建新记录
var existing = await overrideRepository.GetByItemIdAsync(tenantId, request.DictionaryItemId, cancellationToken);
var now = DateTime.UtcNow;
if (existing != null)
{
if (existing.OverrideType == OverrideType.PlatformEnforcement)
{
throw new BusinessException(ErrorCodes.Forbidden, "平台强制覆盖不可由租户修改");
}
existing.OverrideValue = DictionaryValueConverter.Serialize(request.OverrideValue);
existing.Reason = request.Reason;
existing.UpdatedAt = now;
existing.UpdatedBy = operatorId;
await overrideRepository.UpdateAsync(existing, cancellationToken);
}
else
{
existing = new DictionaryLabelOverride
{
TenantId = tenantId,
DictionaryItemId = request.DictionaryItemId,
OriginalValue = item.Value,
OverrideValue = DictionaryValueConverter.Serialize(request.OverrideValue),
OverrideType = OverrideType.TenantCustomization,
Reason = request.Reason,
CreatedAt = now,
CreatedBy = operatorId
};
await overrideRepository.AddAsync(existing, cancellationToken);
}
await overrideRepository.SaveChangesAsync(cancellationToken);
// 重新加载以获取完整信息
existing.DictionaryItem = item;
return MapToDto(existing);
}
/// <summary>
/// 创建或更新平台对租户字典的强制覆盖(平台强制)。
/// </summary>
/// <param name="targetTenantId">目标租户 ID。</param>
/// <param name="request">覆盖请求。</param>
/// <param name="operatorId">操作人 ID。</param>
/// <param name="cancellationToken">取消标记。</param>
public async Task<LabelOverrideDto> UpsertPlatformOverrideAsync(
long targetTenantId,
UpsertLabelOverrideRequest request,
long operatorId,
CancellationToken cancellationToken = default)
{
// 1. 验证字典项存在
var item = await itemRepository.GetByIdAsync(request.DictionaryItemId, cancellationToken);
if (item == null)
{
throw new BusinessException(ErrorCodes.NotFound, "字典项不存在");
}
// 2. 查找现有覆盖或创建新记录
var existing = await overrideRepository.GetByItemIdAsync(targetTenantId, request.DictionaryItemId, cancellationToken);
var now = DateTime.UtcNow;
if (existing != null)
{
existing.OverrideValue = DictionaryValueConverter.Serialize(request.OverrideValue);
existing.OverrideType = OverrideType.PlatformEnforcement;
existing.Reason = request.Reason;
existing.UpdatedAt = now;
existing.UpdatedBy = operatorId;
await overrideRepository.UpdateAsync(existing, cancellationToken);
}
else
{
existing = new DictionaryLabelOverride
{
TenantId = targetTenantId,
DictionaryItemId = request.DictionaryItemId,
OriginalValue = item.Value,
OverrideValue = DictionaryValueConverter.Serialize(request.OverrideValue),
OverrideType = OverrideType.PlatformEnforcement,
Reason = request.Reason,
CreatedAt = now,
CreatedBy = operatorId
};
await overrideRepository.AddAsync(existing, cancellationToken);
}
await overrideRepository.SaveChangesAsync(cancellationToken);
existing.DictionaryItem = item;
return MapToDto(existing);
}
/// <summary>
/// 删除覆盖配置。
/// </summary>
/// <param name="tenantId">租户 ID。</param>
/// <param name="dictionaryItemId">字典项 ID。</param>
/// <param name="operatorId">操作人 ID。</param>
/// <param name="cancellationToken">取消标记。</param>
public async Task<bool> DeleteOverrideAsync(
long tenantId,
long dictionaryItemId,
long operatorId,
bool allowPlatformEnforcement = true,
CancellationToken cancellationToken = default)
{
var existing = await overrideRepository.GetByItemIdAsync(tenantId, dictionaryItemId, cancellationToken);
if (existing == null)
{
return false;
}
if (!allowPlatformEnforcement && existing.OverrideType == OverrideType.PlatformEnforcement)
{
throw new BusinessException(ErrorCodes.Forbidden, "平台强制覆盖不可由租户删除");
}
existing.DeletedBy = operatorId;
await overrideRepository.DeleteAsync(existing, cancellationToken);
await overrideRepository.SaveChangesAsync(cancellationToken);
return true;
}
/// <summary>
/// 批量获取字典项的覆盖值映射。
/// </summary>
/// <param name="tenantId">租户 ID。</param>
/// <param name="dictionaryItemIds">字典项 ID 列表。</param>
/// <param name="cancellationToken">取消标记。</param>
/// <returns>字典项 ID 到覆盖值的映射。</returns>
public async Task<Dictionary<long, Dictionary<string, string>>> GetOverrideValuesMapAsync(
long tenantId,
IEnumerable<long> dictionaryItemIds,
CancellationToken cancellationToken = default)
{
var overrides = await overrideRepository.GetByItemIdsAsync(tenantId, dictionaryItemIds, cancellationToken);
return overrides.ToDictionary(
x => x.DictionaryItemId,
x => DictionaryValueConverter.Deserialize(x.OverrideValue));
}
private static LabelOverrideDto MapToDto(DictionaryLabelOverride entity)
{
return new LabelOverrideDto
{
Id = entity.Id,
TenantId = entity.TenantId,
DictionaryItemId = entity.DictionaryItemId,
DictionaryItemKey = entity.DictionaryItem?.Key ?? string.Empty,
OriginalValue = DictionaryValueConverter.Deserialize(entity.OriginalValue),
OverrideValue = DictionaryValueConverter.Deserialize(entity.OverrideValue),
OverrideType = entity.OverrideType,
Reason = entity.Reason,
CreatedAt = entity.CreatedAt,
UpdatedAt = entity.UpdatedAt,
CreatedBy = entity.CreatedBy,
UpdatedBy = entity.UpdatedBy
};
}
}

View File

@@ -422,6 +422,12 @@ public sealed class AdminAuthService(
// 1.3 可见性
var required = node.RequiredPermissions ?? [];
if (required.Length == 0 && node.Meta.Permissions.Length > 0)
{
// Fall back to meta permissions when explicit required permissions are missing.
required = node.Meta.Permissions;
}
var visible = required.Length == 0 || required.Any(permissionSet.Contains);
// 1.4 收集

View File

@@ -0,0 +1,75 @@
using TakeoutSaaS.Domain.Dictionary.Enums;
using TakeoutSaaS.Shared.Abstractions.Entities;
namespace TakeoutSaaS.Domain.Dictionary.Entities;
/// <summary>
/// 字典标签覆盖配置。
/// </summary>
public sealed class DictionaryLabelOverride : EntityBase, IMultiTenantEntity, IAuditableEntity
{
/// <summary>
/// 所属租户 ID覆盖目标租户
/// </summary>
public long TenantId { get; set; }
/// <summary>
/// 被覆盖的字典项 ID。
/// </summary>
public long DictionaryItemId { get; set; }
/// <summary>
/// 原始显示值JSON 格式,多语言)。
/// </summary>
public string OriginalValue { get; set; } = "{}";
/// <summary>
/// 覆盖后的显示值JSON 格式,多语言)。
/// </summary>
public string OverrideValue { get; set; } = "{}";
/// <summary>
/// 覆盖类型。
/// </summary>
public OverrideType OverrideType { get; set; }
/// <summary>
/// 覆盖原因/备注。
/// </summary>
public string? Reason { get; set; }
/// <summary>
/// 创建时间UTC
/// </summary>
public DateTime CreatedAt { get; set; }
/// <summary>
/// 最近更新时间UTC
/// </summary>
public DateTime? UpdatedAt { get; set; }
/// <summary>
/// 删除时间UTC
/// </summary>
public DateTime? DeletedAt { get; set; }
/// <summary>
/// 创建人用户标识。
/// </summary>
public long? CreatedBy { get; set; }
/// <summary>
/// 最后更新人用户标识。
/// </summary>
public long? UpdatedBy { get; set; }
/// <summary>
/// 删除人用户标识。
/// </summary>
public long? DeletedBy { get; set; }
/// <summary>
/// 导航属性:被覆盖的字典项。
/// </summary>
public DictionaryItem? DictionaryItem { get; set; }
}

View File

@@ -0,0 +1,17 @@
namespace TakeoutSaaS.Domain.Dictionary.Enums;
/// <summary>
/// 字典覆盖类型。
/// </summary>
public enum OverrideType
{
/// <summary>
/// 租户定制:租户覆盖系统字典的显示值。
/// </summary>
TenantCustomization = 1,
/// <summary>
/// 平台强制:平台管理员强制修正租户字典的显示值。
/// </summary>
PlatformEnforcement = 2
}

View File

@@ -0,0 +1,65 @@
using TakeoutSaaS.Domain.Dictionary.Entities;
using TakeoutSaaS.Domain.Dictionary.Enums;
namespace TakeoutSaaS.Domain.Dictionary.Repositories;
/// <summary>
/// 字典标签覆盖仓储契约。
/// </summary>
public interface IDictionaryLabelOverrideRepository
{
/// <summary>
/// 根据 ID 获取覆盖配置。
/// </summary>
Task<DictionaryLabelOverride?> GetByIdAsync(long id, CancellationToken cancellationToken = default);
/// <summary>
/// 获取指定字典项的覆盖配置。
/// </summary>
/// <param name="tenantId">租户 ID。</param>
/// <param name="dictionaryItemId">字典项 ID。</param>
/// <param name="cancellationToken">取消标记。</param>
Task<DictionaryLabelOverride?> GetByItemIdAsync(long tenantId, long dictionaryItemId, CancellationToken cancellationToken = default);
/// <summary>
/// 获取租户的所有覆盖配置。
/// </summary>
/// <param name="tenantId">租户 ID。</param>
/// <param name="overrideType">可选的覆盖类型过滤。</param>
/// <param name="cancellationToken">取消标记。</param>
Task<IReadOnlyList<DictionaryLabelOverride>> ListByTenantAsync(
long tenantId,
OverrideType? overrideType = null,
CancellationToken cancellationToken = default);
/// <summary>
/// 批量获取多个字典项的覆盖配置。
/// </summary>
/// <param name="tenantId">租户 ID。</param>
/// <param name="dictionaryItemIds">字典项 ID 列表。</param>
/// <param name="cancellationToken">取消标记。</param>
Task<IReadOnlyList<DictionaryLabelOverride>> GetByItemIdsAsync(
long tenantId,
IEnumerable<long> dictionaryItemIds,
CancellationToken cancellationToken = default);
/// <summary>
/// 新增覆盖配置。
/// </summary>
Task AddAsync(DictionaryLabelOverride entity, CancellationToken cancellationToken = default);
/// <summary>
/// 更新覆盖配置。
/// </summary>
Task UpdateAsync(DictionaryLabelOverride entity, CancellationToken cancellationToken = default);
/// <summary>
/// 删除覆盖配置。
/// </summary>
Task DeleteAsync(DictionaryLabelOverride entity, CancellationToken cancellationToken = default);
/// <summary>
/// 持久化更改。
/// </summary>
Task SaveChangesAsync(CancellationToken cancellationToken = default);
}

View File

@@ -1,9 +1,11 @@
using Microsoft.EntityFrameworkCore;
using System.Reflection;
using System.Linq;
using TakeoutSaaS.Shared.Abstractions.Entities;
using TakeoutSaaS.Shared.Abstractions.Ids;
using TakeoutSaaS.Shared.Abstractions.Security;
using TakeoutSaaS.Shared.Abstractions.Tenancy;
using Microsoft.AspNetCore.Http;
namespace TakeoutSaaS.Infrastructure.Common.Persistence;
@@ -14,9 +16,18 @@ public abstract class TenantAwareDbContext(
DbContextOptions options,
ITenantProvider tenantProvider,
ICurrentUserAccessor? currentUserAccessor = null,
IIdGenerator? idGenerator = null) : AppDbContext(options, currentUserAccessor, idGenerator)
IIdGenerator? idGenerator = null,
IHttpContextAccessor? httpContextAccessor = null) : AppDbContext(options, currentUserAccessor, idGenerator)
{
private readonly ITenantProvider _tenantProvider = tenantProvider ?? throw new ArgumentNullException(nameof(tenantProvider));
private readonly IHttpContextAccessor? _httpContextAccessor = httpContextAccessor;
private static readonly string[] PlatformRoleCodes =
{
"super-admin",
"SUPER_ADMIN",
"PlatformAdmin",
"platform-admin"
};
/// <summary>
/// 当前请求租户 ID。
@@ -75,8 +86,22 @@ public abstract class TenantAwareDbContext(
{
if (entry.State == EntityState.Added && entry.Entity.TenantId == 0 && tenantId != 0)
{
entry.Entity.TenantId = tenantId;
if (!IsPlatformAdmin())
{
entry.Entity.TenantId = tenantId;
}
}
}
}
private bool IsPlatformAdmin()
{
var user = _httpContextAccessor?.HttpContext?.User;
if (user?.Identity?.IsAuthenticated != true)
{
return false;
}
return PlatformRoleCodes.Any(user.IsInRole);
}
}

View File

@@ -39,6 +39,7 @@ public static class DictionaryServiceCollectionExtensions
services.AddScoped<IDictionaryGroupRepository, DictionaryGroupRepository>();
services.AddScoped<IDictionaryItemRepository, DictionaryItemRepository>();
services.AddScoped<ITenantDictionaryOverrideRepository, TenantDictionaryOverrideRepository>();
services.AddScoped<IDictionaryLabelOverrideRepository, DictionaryLabelOverrideRepository>();
services.AddScoped<IDictionaryImportLogRepository, DictionaryImportLogRepository>();
services.AddScoped<ICacheInvalidationLogRepository, CacheInvalidationLogRepository>();
services.AddScoped<ISystemParameterRepository, EfSystemParameterRepository>();

View File

@@ -7,6 +7,7 @@ using TakeoutSaaS.Infrastructure.Common.Persistence;
using TakeoutSaaS.Shared.Abstractions.Ids;
using TakeoutSaaS.Shared.Abstractions.Security;
using TakeoutSaaS.Shared.Abstractions.Tenancy;
using Microsoft.AspNetCore.Http;
namespace TakeoutSaaS.Infrastructure.Dictionary.Persistence;
@@ -17,8 +18,9 @@ public sealed class DictionaryDbContext(
DbContextOptions<DictionaryDbContext> options,
ITenantProvider tenantProvider,
ICurrentUserAccessor? currentUserAccessor = null,
IIdGenerator? idGenerator = null)
: TenantAwareDbContext(options, tenantProvider, currentUserAccessor, idGenerator)
IIdGenerator? idGenerator = null,
IHttpContextAccessor? httpContextAccessor = null)
: TenantAwareDbContext(options, tenantProvider, currentUserAccessor, idGenerator, httpContextAccessor)
{
/// <summary>
/// 字典分组集合。
@@ -45,6 +47,11 @@ public sealed class DictionaryDbContext(
/// </summary>
public DbSet<CacheInvalidationLog> CacheInvalidationLogs => Set<CacheInvalidationLog>();
/// <summary>
/// 字典标签覆盖集合。
/// </summary>
public DbSet<DictionaryLabelOverride> DictionaryLabelOverrides => Set<DictionaryLabelOverride>();
/// <summary>
/// 系统参数集合。
/// </summary>
@@ -62,6 +69,7 @@ public sealed class DictionaryDbContext(
ConfigureGroup(modelBuilder.Entity<DictionaryGroup>(), isSqlite);
ConfigureItem(modelBuilder.Entity<DictionaryItem>(), isSqlite);
ConfigureOverride(modelBuilder.Entity<TenantDictionaryOverride>());
ConfigureLabelOverride(modelBuilder.Entity<DictionaryLabelOverride>());
ConfigureImportLog(modelBuilder.Entity<DictionaryImportLog>());
ConfigureCacheInvalidationLog(modelBuilder.Entity<CacheInvalidationLog>());
ConfigureSystemParameter(modelBuilder.Entity<SystemParameter>());
@@ -228,4 +236,34 @@ public sealed class DictionaryDbContext(
builder.HasIndex(x => x.TenantId);
builder.HasIndex(x => new { x.TenantId, x.Key }).IsUnique();
}
/// <summary>
/// 配置字典标签覆盖。
/// </summary>
/// <param name="builder">实体构建器。</param>
private static void ConfigureLabelOverride(EntityTypeBuilder<DictionaryLabelOverride> builder)
{
builder.ToTable("dictionary_label_overrides", t => t.HasComment("字典标签覆盖配置。"));
builder.HasKey(x => x.Id);
builder.Property(x => x.Id).HasComment("实体唯一标识。");
builder.Property(x => x.TenantId).IsRequired().HasComment("所属租户 ID覆盖目标租户。");
builder.Property(x => x.DictionaryItemId).IsRequired().HasComment("被覆盖的字典项 ID。");
builder.Property(x => x.OriginalValue).HasColumnType("jsonb").IsRequired().HasComment("原始显示值JSON 格式,多语言)。");
builder.Property(x => x.OverrideValue).HasColumnType("jsonb").IsRequired().HasComment("覆盖后的显示值JSON 格式,多语言)。");
builder.Property(x => x.OverrideType).HasConversion<int>().IsRequired().HasComment("覆盖类型。");
builder.Property(x => x.Reason).HasMaxLength(512).HasComment("覆盖原因/备注。");
ConfigureAuditableEntity(builder);
ConfigureSoftDeleteEntity(builder);
builder.HasOne(x => x.DictionaryItem)
.WithMany()
.HasForeignKey(x => x.DictionaryItemId)
.OnDelete(DeleteBehavior.Cascade);
builder.HasIndex(x => x.TenantId);
builder.HasIndex(x => new { x.TenantId, x.DictionaryItemId })
.IsUnique()
.HasFilter("\"DeletedAt\" IS NULL");
builder.HasIndex(x => new { x.TenantId, x.OverrideType });
}
}

View File

@@ -155,9 +155,15 @@ public sealed class DictionaryGroupRepository(DictionaryDbContext context) : IDi
if (!string.IsNullOrWhiteSpace(keyword))
{
var trimmed = keyword.Trim();
query = query.Where(group =>
EF.Property<string>(group, "Code").Contains(trimmed) ||
group.Name.Contains(trimmed));
if (DictionaryCode.IsValid(trimmed))
{
var code = new DictionaryCode(trimmed);
query = query.Where(group => group.Code == code || group.Name.Contains(trimmed));
}
else
{
query = query.Where(group => group.Name.Contains(trimmed));
}
}
if (isEnabled.HasValue)

View File

@@ -0,0 +1,115 @@
using Microsoft.EntityFrameworkCore;
using TakeoutSaaS.Domain.Dictionary.Entities;
using TakeoutSaaS.Domain.Dictionary.Enums;
using TakeoutSaaS.Domain.Dictionary.Repositories;
using TakeoutSaaS.Infrastructure.Dictionary.Persistence;
namespace TakeoutSaaS.Infrastructure.Dictionary.Repositories;
/// <summary>
/// 字典标签覆盖仓储实现。
/// </summary>
public sealed class DictionaryLabelOverrideRepository(DictionaryDbContext context) : IDictionaryLabelOverrideRepository
{
/// <summary>
/// 根据 ID 获取覆盖配置。
/// </summary>
public Task<DictionaryLabelOverride?> GetByIdAsync(long id, CancellationToken cancellationToken = default)
{
return context.DictionaryLabelOverrides
.IgnoreQueryFilters()
.Include(x => x.DictionaryItem)
.FirstOrDefaultAsync(x => x.Id == id && x.DeletedAt == null, cancellationToken);
}
/// <summary>
/// 获取指定字典项的覆盖配置。
/// </summary>
public Task<DictionaryLabelOverride?> GetByItemIdAsync(long tenantId, long dictionaryItemId, CancellationToken cancellationToken = default)
{
return context.DictionaryLabelOverrides
.IgnoreQueryFilters()
.FirstOrDefaultAsync(x =>
x.TenantId == tenantId &&
x.DictionaryItemId == dictionaryItemId &&
x.DeletedAt == null,
cancellationToken);
}
/// <summary>
/// 获取租户的所有覆盖配置。
/// </summary>
public async Task<IReadOnlyList<DictionaryLabelOverride>> ListByTenantAsync(
long tenantId,
OverrideType? overrideType = null,
CancellationToken cancellationToken = default)
{
var query = context.DictionaryLabelOverrides
.AsNoTracking()
.IgnoreQueryFilters()
.Include(x => x.DictionaryItem)
.Where(x => x.TenantId == tenantId && x.DeletedAt == null);
if (overrideType.HasValue)
{
query = query.Where(x => x.OverrideType == overrideType.Value);
}
return await query.OrderByDescending(x => x.CreatedAt).ToListAsync(cancellationToken);
}
/// <summary>
/// 批量获取多个字典项的覆盖配置。
/// </summary>
public async Task<IReadOnlyList<DictionaryLabelOverride>> GetByItemIdsAsync(
long tenantId,
IEnumerable<long> dictionaryItemIds,
CancellationToken cancellationToken = default)
{
var ids = dictionaryItemIds.ToArray();
if (ids.Length == 0) return Array.Empty<DictionaryLabelOverride>();
return await context.DictionaryLabelOverrides
.AsNoTracking()
.IgnoreQueryFilters()
.Where(x =>
x.TenantId == tenantId &&
ids.Contains(x.DictionaryItemId) &&
x.DeletedAt == null)
.ToListAsync(cancellationToken);
}
/// <summary>
/// 新增覆盖配置。
/// </summary>
public Task AddAsync(DictionaryLabelOverride entity, CancellationToken cancellationToken = default)
{
context.DictionaryLabelOverrides.Add(entity);
return Task.CompletedTask;
}
/// <summary>
/// 更新覆盖配置。
/// </summary>
public Task UpdateAsync(DictionaryLabelOverride entity, CancellationToken cancellationToken = default)
{
context.DictionaryLabelOverrides.Update(entity);
return Task.CompletedTask;
}
/// <summary>
/// 删除覆盖配置。
/// </summary>
public Task DeleteAsync(DictionaryLabelOverride entity, CancellationToken cancellationToken = default)
{
entity.DeletedAt = DateTime.UtcNow;
context.DictionaryLabelOverrides.Update(entity);
return Task.CompletedTask;
}
/// <summary>
/// 持久化更改。
/// </summary>
public Task SaveChangesAsync(CancellationToken cancellationToken = default)
=> context.SaveChangesAsync(cancellationToken);
}

View File

@@ -6,6 +6,7 @@ using TakeoutSaaS.Infrastructure.Common.Persistence;
using TakeoutSaaS.Shared.Abstractions.Ids;
using TakeoutSaaS.Shared.Abstractions.Security;
using TakeoutSaaS.Shared.Abstractions.Tenancy;
using Microsoft.AspNetCore.Http;
namespace TakeoutSaaS.Infrastructure.Identity.Persistence;
@@ -16,8 +17,9 @@ public sealed class IdentityDbContext(
DbContextOptions<IdentityDbContext> options,
ITenantProvider tenantProvider,
ICurrentUserAccessor? currentUserAccessor = null,
IIdGenerator? idGenerator = null)
: TenantAwareDbContext(options, tenantProvider, currentUserAccessor, idGenerator)
IIdGenerator? idGenerator = null,
IHttpContextAccessor? httpContextAccessor = null)
: TenantAwareDbContext(options, tenantProvider, currentUserAccessor, idGenerator, httpContextAccessor)
{
/// <summary>
/// 管理后台用户集合。

View File

@@ -7,6 +7,7 @@ using TakeoutSaaS.Infrastructure.Common.Persistence;
using TakeoutSaaS.Shared.Abstractions.Ids;
using TakeoutSaaS.Shared.Abstractions.Security;
using TakeoutSaaS.Shared.Abstractions.Tenancy;
using Microsoft.AspNetCore.Http;
namespace TakeoutSaaS.Infrastructure.Logs.Persistence;
@@ -17,8 +18,9 @@ public sealed class TakeoutLogsDbContext(
DbContextOptions<TakeoutLogsDbContext> options,
ITenantProvider tenantProvider,
ICurrentUserAccessor? currentUserAccessor = null,
IIdGenerator? idGenerator = null)
: TenantAwareDbContext(options, tenantProvider, currentUserAccessor, idGenerator)
IIdGenerator? idGenerator = null,
IHttpContextAccessor? httpContextAccessor = null)
: TenantAwareDbContext(options, tenantProvider, currentUserAccessor, idGenerator, httpContextAccessor)
{
/// <summary>
/// 租户审计日志集合。

View File

@@ -20,16 +20,15 @@ namespace TakeoutSaaS.Infrastructure.Migrations.DictionaryDb
name: "IX_dictionary_groups_TenantId_Code",
table: "dictionary_groups");
migrationBuilder.AlterColumn<string>(
name: "Value",
table: "dictionary_items",
type: "jsonb",
nullable: false,
comment: "字典项值。",
oldClrType: typeof(string),
oldType: "character varying(256)",
oldMaxLength: 256,
oldComment: "字典项值。");
// 使用原生 SQL 进行类型转换,确保现有数据被正确转换为 JSONB
migrationBuilder.Sql(
"""
ALTER TABLE dictionary_items
ALTER COLUMN "Value" TYPE jsonb
USING to_jsonb("Value"::text);
COMMENT ON COLUMN dictionary_items."Value" IS '';
""");
migrationBuilder.AlterColumn<string>(
name: "Key",

View File

@@ -0,0 +1,544 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using TakeoutSaaS.Infrastructure.Dictionary.Persistence;
#nullable disable
namespace TakeoutSaaS.Infrastructure.Migrations.DictionaryDb
{
[DbContext(typeof(DictionaryDbContext))]
[Migration("20251230140335_AddCacheInvalidationLogs")]
partial class AddCacheInvalidationLogs
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.1")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.CacheInvalidationLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasComment("实体唯一标识。");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<int>("AffectedCacheKeyCount")
.HasColumnType("integer")
.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<string>("DictionaryCode")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasComment("字典编码。");
b.Property<int>("Operation")
.HasColumnType("integer")
.HasComment("操作类型。");
b.Property<long>("OperatorId")
.HasColumnType("bigint")
.HasComment("操作人用户标识。");
b.Property<int>("Scope")
.HasColumnType("integer")
.HasComment("字典作用域。");
b.Property<long>("TenantId")
.HasColumnType("bigint")
.HasComment("所属租户 ID。");
b.Property<DateTime>("Timestamp")
.HasColumnType("timestamp with time zone")
.HasComment("发生时间UTC。");
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("TenantId", "Timestamp");
b.ToTable("dictionary_cache_invalidation_logs", null, t =>
{
t.HasComment("字典缓存失效日志。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryGroup", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasComment("实体唯一标识。");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<bool>("AllowOverride")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(false)
.HasComment("是否允许租户覆盖。");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
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<string>("Description")
.HasMaxLength(512)
.HasColumnType("character varying(512)")
.HasComment("描述信息。");
b.Property<bool>("IsEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(true)
.HasComment("是否启用。");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)")
.HasComment("分组名称。");
b.Property<byte[]>("RowVersion")
.IsConcurrencyToken()
.IsRequired()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("bytea")
.HasComment("并发控制字段。");
b.Property<int>("Scope")
.HasColumnType("integer")
.HasComment("分组作用域:系统/业务。");
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("TenantId");
b.HasIndex("TenantId", "Code")
.IsUnique()
.HasFilter("\"DeletedAt\" IS NULL");
b.HasIndex("TenantId", "Scope", "IsEnabled");
b.ToTable("dictionary_groups", null, t =>
{
t.HasComment("参数字典分组(系统参数、业务参数)。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryImportLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasComment("实体唯一标识。");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<int>("ConflictMode")
.HasColumnType("integer")
.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<string>("DictionaryGroupCode")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasComment("字典分组编码。");
b.Property<TimeSpan>("Duration")
.HasColumnType("interval")
.HasComment("处理耗时。");
b.Property<string>("ErrorDetails")
.HasColumnType("jsonb")
.HasComment("错误明细JSON。");
b.Property<string>("FileName")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)")
.HasComment("导入文件名。");
b.Property<long>("FileSize")
.HasColumnType("bigint")
.HasComment("文件大小(字节)。");
b.Property<string>("Format")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("character varying(16)")
.HasComment("文件格式CSV/JSON。");
b.Property<long>("OperatorId")
.HasColumnType("bigint")
.HasComment("操作人用户标识。");
b.Property<DateTime>("ProcessedAt")
.HasColumnType("timestamp with time zone")
.HasComment("处理时间UTC。");
b.Property<int>("SkipCount")
.HasColumnType("integer")
.HasComment("跳过数量。");
b.Property<int>("SuccessCount")
.HasColumnType("integer")
.HasComment("成功导入数量。");
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("TenantId", "ProcessedAt");
b.ToTable("dictionary_import_logs", null, t =>
{
t.HasComment("字典导入审计日志。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryItem", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasComment("实体唯一标识。");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
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<string>("Description")
.HasMaxLength(512)
.HasColumnType("character varying(512)")
.HasComment("描述信息。");
b.Property<long>("GroupId")
.HasColumnType("bigint")
.HasComment("关联分组 ID。");
b.Property<bool>("IsDefault")
.HasColumnType("boolean")
.HasComment("是否默认项。");
b.Property<bool>("IsEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(true)
.HasComment("是否启用。");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)")
.HasComment("字典项键。");
b.Property<byte[]>("RowVersion")
.IsConcurrencyToken()
.IsRequired()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("bytea")
.HasComment("并发控制字段。");
b.Property<int>("SortOrder")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(100)
.HasComment("排序值,越小越靠前。");
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.Property<string>("Value")
.IsRequired()
.HasColumnType("jsonb")
.HasComment("字典项值。");
b.HasKey("Id");
b.HasIndex("TenantId");
b.HasIndex("GroupId", "IsEnabled", "SortOrder");
b.HasIndex("TenantId", "GroupId", "Key")
.IsUnique()
.HasFilter("\"DeletedAt\" IS NULL");
b.ToTable("dictionary_items", null, t =>
{
t.HasComment("参数字典项。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.TenantDictionaryOverride", b =>
{
b.Property<long>("TenantId")
.HasColumnType("bigint")
.HasComment("所属租户 ID。");
b.Property<long>("SystemDictionaryGroupId")
.HasColumnType("bigint")
.HasComment("系统字典分组 ID。");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasComment("创建时间UTC。");
b.Property<long?>("CreatedBy")
.HasColumnType("bigint")
.HasComment("创建人用户标识。");
b.Property<string>("CustomSortOrder")
.IsRequired()
.HasColumnType("jsonb")
.HasComment("自定义排序映射JSON。");
b.Property<DateTime?>("DeletedAt")
.HasColumnType("timestamp with time zone")
.HasComment("删除时间UTC。");
b.Property<long?>("DeletedBy")
.HasColumnType("bigint")
.HasComment("删除人用户标识。");
b.PrimitiveCollection<long[]>("HiddenSystemItemIds")
.IsRequired()
.HasColumnType("bigint[]")
.HasComment("隐藏的系统字典项 ID 列表。");
b.Property<bool>("OverrideEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(false)
.HasComment("是否启用覆盖。");
b.Property<DateTime?>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasComment("最近更新时间UTC。");
b.Property<long?>("UpdatedBy")
.HasColumnType("bigint")
.HasComment("最后更新人用户标识。");
b.HasKey("TenantId", "SystemDictionaryGroupId");
b.HasIndex("HiddenSystemItemIds");
NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("HiddenSystemItemIds"), "gin");
b.ToTable("tenant_dictionary_overrides", null, t =>
{
t.HasComment("租户字典覆盖配置。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.SystemParameters.Entities.SystemParameter", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasComment("实体唯一标识。");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
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<string>("Description")
.HasMaxLength(512)
.HasColumnType("character varying(512)")
.HasComment("描述信息。");
b.Property<bool>("IsEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(true)
.HasComment("是否启用。");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)")
.HasComment("参数键,租户内唯一。");
b.Property<int>("SortOrder")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(100)
.HasComment("排序值,越小越靠前。");
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.Property<string>("Value")
.IsRequired()
.HasColumnType("text")
.HasComment("参数值,支持文本或 JSON。");
b.HasKey("Id");
b.HasIndex("TenantId");
b.HasIndex("TenantId", "Key")
.IsUnique();
b.ToTable("system_parameters", null, t =>
{
t.HasComment("系统参数实体:支持按租户维护的键值型配置。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryItem", b =>
{
b.HasOne("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryGroup", "Group")
.WithMany("Items")
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Group");
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryGroup", b =>
{
b.Navigation("Items");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -1,4 +1,4 @@
using System;
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;

View File

@@ -0,0 +1,77 @@
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using TakeoutSaaS.Infrastructure.Dictionary.Persistence;
#nullable disable
namespace TakeoutSaaS.Infrastructure.Migrations.DictionaryDb
{
/// <summary>
/// 为字典表添加 RowVersion 自动生成触发器。
/// </summary>
[DbContext(typeof(DictionaryDbContext))]
[Migration("20251230170000_AddDictionaryRowVersionTriggers")]
public partial class AddDictionaryRowVersionTriggers : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
// 1. 创建通用的 RowVersion 生成函数
migrationBuilder.Sql(
"""
CREATE OR REPLACE FUNCTION public.set_dictionary_row_version()
RETURNS trigger AS $$
BEGIN
NEW."RowVersion" = decode(md5(random()::text || clock_timestamp()::text), 'hex');
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
""");
// 2. 为 dictionary_groups 表创建触发器
migrationBuilder.Sql(
"""
DROP TRIGGER IF EXISTS trg_dictionary_groups_row_version ON dictionary_groups;
CREATE TRIGGER trg_dictionary_groups_row_version
BEFORE INSERT OR UPDATE ON dictionary_groups
FOR EACH ROW EXECUTE FUNCTION public.set_dictionary_row_version();
""");
// 3. 为 dictionary_items 表创建触发器
migrationBuilder.Sql(
"""
DROP TRIGGER IF EXISTS trg_dictionary_items_row_version ON dictionary_items;
CREATE TRIGGER trg_dictionary_items_row_version
BEFORE INSERT OR UPDATE ON dictionary_items
FOR EACH ROW EXECUTE FUNCTION public.set_dictionary_row_version();
""");
// 4. 回填现有 dictionary_groups 数据的 RowVersion
migrationBuilder.Sql(
"""
UPDATE dictionary_groups
SET "RowVersion" = decode(md5(random()::text || clock_timestamp()::text), 'hex')
WHERE "RowVersion" IS NULL OR octet_length("RowVersion") = 0;
""");
// 5. 回填现有 dictionary_items 数据的 RowVersion
migrationBuilder.Sql(
"""
UPDATE dictionary_items
SET "RowVersion" = decode(md5(random()::text || clock_timestamp()::text), 'hex')
WHERE "RowVersion" IS NULL OR octet_length("RowVersion") = 0;
""");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(
"""
DROP TRIGGER IF EXISTS trg_dictionary_groups_row_version ON dictionary_groups;
DROP TRIGGER IF EXISTS trg_dictionary_items_row_version ON dictionary_items;
DROP FUNCTION IF EXISTS public.set_dictionary_row_version();
""");
}
}
}

View File

@@ -0,0 +1,633 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using TakeoutSaaS.Infrastructure.Dictionary.Persistence;
#nullable disable
namespace TakeoutSaaS.Infrastructure.Migrations.DictionaryDb
{
[DbContext(typeof(DictionaryDbContext))]
[Migration("20251230232516_AddDictionaryLabelOverrides")]
partial class AddDictionaryLabelOverrides
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.1")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.CacheInvalidationLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasComment("实体唯一标识。");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<int>("AffectedCacheKeyCount")
.HasColumnType("integer")
.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<string>("DictionaryCode")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasComment("字典编码。");
b.Property<int>("Operation")
.HasColumnType("integer")
.HasComment("操作类型。");
b.Property<long>("OperatorId")
.HasColumnType("bigint")
.HasComment("操作人用户标识。");
b.Property<int>("Scope")
.HasColumnType("integer")
.HasComment("字典作用域。");
b.Property<long>("TenantId")
.HasColumnType("bigint")
.HasComment("所属租户 ID。");
b.Property<DateTime>("Timestamp")
.HasColumnType("timestamp with time zone")
.HasComment("发生时间UTC。");
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("TenantId", "Timestamp");
b.ToTable("dictionary_cache_invalidation_logs", null, t =>
{
t.HasComment("字典缓存失效日志。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryGroup", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasComment("实体唯一标识。");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<bool>("AllowOverride")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(false)
.HasComment("是否允许租户覆盖。");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
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<string>("Description")
.HasMaxLength(512)
.HasColumnType("character varying(512)")
.HasComment("描述信息。");
b.Property<bool>("IsEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(true)
.HasComment("是否启用。");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)")
.HasComment("分组名称。");
b.Property<byte[]>("RowVersion")
.IsConcurrencyToken()
.IsRequired()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("bytea")
.HasComment("并发控制字段。");
b.Property<int>("Scope")
.HasColumnType("integer")
.HasComment("分组作用域:系统/业务。");
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("TenantId");
b.HasIndex("TenantId", "Code")
.IsUnique()
.HasFilter("\"DeletedAt\" IS NULL");
b.HasIndex("TenantId", "Scope", "IsEnabled");
b.ToTable("dictionary_groups", null, t =>
{
t.HasComment("参数字典分组(系统参数、业务参数)。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryImportLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasComment("实体唯一标识。");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<int>("ConflictMode")
.HasColumnType("integer")
.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<string>("DictionaryGroupCode")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasComment("字典分组编码。");
b.Property<TimeSpan>("Duration")
.HasColumnType("interval")
.HasComment("处理耗时。");
b.Property<string>("ErrorDetails")
.HasColumnType("jsonb")
.HasComment("错误明细JSON。");
b.Property<string>("FileName")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)")
.HasComment("导入文件名。");
b.Property<long>("FileSize")
.HasColumnType("bigint")
.HasComment("文件大小(字节)。");
b.Property<string>("Format")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("character varying(16)")
.HasComment("文件格式CSV/JSON。");
b.Property<long>("OperatorId")
.HasColumnType("bigint")
.HasComment("操作人用户标识。");
b.Property<DateTime>("ProcessedAt")
.HasColumnType("timestamp with time zone")
.HasComment("处理时间UTC。");
b.Property<int>("SkipCount")
.HasColumnType("integer")
.HasComment("跳过数量。");
b.Property<int>("SuccessCount")
.HasColumnType("integer")
.HasComment("成功导入数量。");
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("TenantId", "ProcessedAt");
b.ToTable("dictionary_import_logs", null, t =>
{
t.HasComment("字典导入审计日志。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryItem", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasComment("实体唯一标识。");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
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<string>("Description")
.HasMaxLength(512)
.HasColumnType("character varying(512)")
.HasComment("描述信息。");
b.Property<long>("GroupId")
.HasColumnType("bigint")
.HasComment("关联分组 ID。");
b.Property<bool>("IsDefault")
.HasColumnType("boolean")
.HasComment("是否默认项。");
b.Property<bool>("IsEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(true)
.HasComment("是否启用。");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)")
.HasComment("字典项键。");
b.Property<byte[]>("RowVersion")
.IsConcurrencyToken()
.IsRequired()
.ValueGeneratedOnAddOrUpdate()
.HasColumnType("bytea")
.HasComment("并发控制字段。");
b.Property<int>("SortOrder")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(100)
.HasComment("排序值,越小越靠前。");
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.Property<string>("Value")
.IsRequired()
.HasColumnType("jsonb")
.HasComment("字典项值。");
b.HasKey("Id");
b.HasIndex("TenantId");
b.HasIndex("GroupId", "IsEnabled", "SortOrder");
b.HasIndex("TenantId", "GroupId", "Key")
.IsUnique()
.HasFilter("\"DeletedAt\" IS NULL");
b.ToTable("dictionary_items", null, t =>
{
t.HasComment("参数字典项。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryLabelOverride", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasComment("实体唯一标识。");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasComment("创建时间UTC。");
b.Property<long?>("CreatedBy")
.HasColumnType("bigint")
.HasComment("创建人用户标识。");
b.Property<DateTime?>("DeletedAt")
.HasColumnType("timestamp with time zone")
.HasComment("删除时间UTC。");
b.Property<long?>("DeletedBy")
.HasColumnType("bigint")
.HasComment("删除人用户标识。");
b.Property<long>("DictionaryItemId")
.HasColumnType("bigint")
.HasComment("被覆盖的字典项 ID。");
b.Property<string>("OriginalValue")
.IsRequired()
.HasColumnType("jsonb")
.HasComment("原始显示值JSON 格式,多语言)。");
b.Property<int>("OverrideType")
.HasColumnType("integer")
.HasComment("覆盖类型。");
b.Property<string>("OverrideValue")
.IsRequired()
.HasColumnType("jsonb")
.HasComment("覆盖后的显示值JSON 格式,多语言)。");
b.Property<string>("Reason")
.HasMaxLength(512)
.HasColumnType("character varying(512)")
.HasComment("覆盖原因/备注。");
b.Property<long>("TenantId")
.HasColumnType("bigint")
.HasComment("所属租户 ID覆盖目标租户。");
b.Property<DateTime?>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasComment("最近更新时间UTC。");
b.Property<long?>("UpdatedBy")
.HasColumnType("bigint")
.HasComment("最后更新人用户标识。");
b.HasKey("Id");
b.HasIndex("DictionaryItemId");
b.HasIndex("TenantId");
b.HasIndex("TenantId", "DictionaryItemId")
.IsUnique()
.HasFilter("\"DeletedAt\" IS NULL");
b.HasIndex("TenantId", "OverrideType");
b.ToTable("dictionary_label_overrides", null, t =>
{
t.HasComment("字典标签覆盖配置。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.TenantDictionaryOverride", b =>
{
b.Property<long>("TenantId")
.HasColumnType("bigint")
.HasComment("所属租户 ID。");
b.Property<long>("SystemDictionaryGroupId")
.HasColumnType("bigint")
.HasComment("系统字典分组 ID。");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasComment("创建时间UTC。");
b.Property<long?>("CreatedBy")
.HasColumnType("bigint")
.HasComment("创建人用户标识。");
b.Property<string>("CustomSortOrder")
.IsRequired()
.HasColumnType("jsonb")
.HasComment("自定义排序映射JSON。");
b.Property<DateTime?>("DeletedAt")
.HasColumnType("timestamp with time zone")
.HasComment("删除时间UTC。");
b.Property<long?>("DeletedBy")
.HasColumnType("bigint")
.HasComment("删除人用户标识。");
b.PrimitiveCollection<long[]>("HiddenSystemItemIds")
.IsRequired()
.HasColumnType("bigint[]")
.HasComment("隐藏的系统字典项 ID 列表。");
b.Property<bool>("OverrideEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(false)
.HasComment("是否启用覆盖。");
b.Property<DateTime?>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasComment("最近更新时间UTC。");
b.Property<long?>("UpdatedBy")
.HasColumnType("bigint")
.HasComment("最后更新人用户标识。");
b.HasKey("TenantId", "SystemDictionaryGroupId");
b.HasIndex("HiddenSystemItemIds");
NpgsqlIndexBuilderExtensions.HasMethod(b.HasIndex("HiddenSystemItemIds"), "gin");
b.ToTable("tenant_dictionary_overrides", null, t =>
{
t.HasComment("租户字典覆盖配置。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.SystemParameters.Entities.SystemParameter", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasComment("实体唯一标识。");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
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<string>("Description")
.HasMaxLength(512)
.HasColumnType("character varying(512)")
.HasComment("描述信息。");
b.Property<bool>("IsEnabled")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(true)
.HasComment("是否启用。");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)")
.HasComment("参数键,租户内唯一。");
b.Property<int>("SortOrder")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValue(100)
.HasComment("排序值,越小越靠前。");
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.Property<string>("Value")
.IsRequired()
.HasColumnType("text")
.HasComment("参数值,支持文本或 JSON。");
b.HasKey("Id");
b.HasIndex("TenantId");
b.HasIndex("TenantId", "Key")
.IsUnique();
b.ToTable("system_parameters", null, t =>
{
t.HasComment("系统参数实体:支持按租户维护的键值型配置。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryItem", b =>
{
b.HasOne("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryGroup", "Group")
.WithMany("Items")
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Group");
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryLabelOverride", b =>
{
b.HasOne("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryItem", "DictionaryItem")
.WithMany()
.HasForeignKey("DictionaryItemId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("DictionaryItem");
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryGroup", b =>
{
b.Navigation("Items");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,76 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace TakeoutSaaS.Infrastructure.Migrations.DictionaryDb
{
/// <inheritdoc />
public partial class AddDictionaryLabelOverrides : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "dictionary_label_overrides",
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覆盖目标租户。"),
DictionaryItemId = table.Column<long>(type: "bigint", nullable: false, comment: "被覆盖的字典项 ID。"),
OriginalValue = table.Column<string>(type: "jsonb", nullable: false, comment: "原始显示值JSON 格式,多语言)。"),
OverrideValue = table.Column<string>(type: "jsonb", nullable: false, comment: "覆盖后的显示值JSON 格式,多语言)。"),
OverrideType = table.Column<int>(type: "integer", nullable: false, comment: "覆盖类型。"),
Reason = table.Column<string>(type: "character varying(512)", maxLength: 512, nullable: true, comment: "覆盖原因/备注。"),
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。"),
DeletedAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: true, comment: "删除时间UTC。"),
CreatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "创建人用户标识。"),
UpdatedBy = table.Column<long>(type: "bigint", nullable: true, comment: "最后更新人用户标识。"),
DeletedBy = table.Column<long>(type: "bigint", nullable: true, comment: "删除人用户标识。")
},
constraints: table =>
{
table.PrimaryKey("PK_dictionary_label_overrides", x => x.Id);
table.ForeignKey(
name: "FK_dictionary_label_overrides_dictionary_items_DictionaryItemId",
column: x => x.DictionaryItemId,
principalTable: "dictionary_items",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
},
comment: "字典标签覆盖配置。");
migrationBuilder.CreateIndex(
name: "IX_dictionary_label_overrides_DictionaryItemId",
table: "dictionary_label_overrides",
column: "DictionaryItemId");
migrationBuilder.CreateIndex(
name: "IX_dictionary_label_overrides_TenantId",
table: "dictionary_label_overrides",
column: "TenantId");
migrationBuilder.CreateIndex(
name: "IX_dictionary_label_overrides_TenantId_DictionaryItemId",
table: "dictionary_label_overrides",
columns: new[] { "TenantId", "DictionaryItemId" },
unique: true,
filter: "\"DeletedAt\" IS NULL");
migrationBuilder.CreateIndex(
name: "IX_dictionary_label_overrides_TenantId_OverrideType",
table: "dictionary_label_overrides",
columns: new[] { "TenantId", "OverrideType" });
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "dictionary_label_overrides");
}
}
}

View File

@@ -22,6 +22,79 @@ namespace TakeoutSaaS.Infrastructure.Migrations.DictionaryDb
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.CacheInvalidationLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasComment("实体唯一标识。");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<int>("AffectedCacheKeyCount")
.HasColumnType("integer")
.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<string>("DictionaryCode")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasComment("字典编码。");
b.Property<int>("Operation")
.HasColumnType("integer")
.HasComment("操作类型。");
b.Property<long>("OperatorId")
.HasColumnType("bigint")
.HasComment("操作人用户标识。");
b.Property<int>("Scope")
.HasColumnType("integer")
.HasComment("字典作用域。");
b.Property<long>("TenantId")
.HasColumnType("bigint")
.HasComment("所属租户 ID。");
b.Property<DateTime>("Timestamp")
.HasColumnType("timestamp with time zone")
.HasComment("发生时间UTC。");
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("TenantId", "Timestamp");
b.ToTable("dictionary_cache_invalidation_logs", null, t =>
{
t.HasComment("字典缓存失效日志。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryGroup", b =>
{
b.Property<long>("Id")
@@ -211,79 +284,6 @@ namespace TakeoutSaaS.Infrastructure.Migrations.DictionaryDb
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.CacheInvalidationLog", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasComment("实体唯一标识。");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<int>("AffectedCacheKeyCount")
.HasColumnType("integer")
.HasComment("影响的缓存键数量。");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasComment("创建时间UTC。");
b.Property<long?>("CreatedBy")
.HasColumnType("bigint")
.HasComment("创建人用户标识,匿名或系统操作时为 null。");
b.Property<string>("DictionaryCode")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasComment("字典编码。");
b.Property<DateTime?>("DeletedAt")
.HasColumnType("timestamp with time zone")
.HasComment("软删除时间UTC未删除时为 null。");
b.Property<long?>("DeletedBy")
.HasColumnType("bigint")
.HasComment("删除人用户标识(软删除),未删除时为 null。");
b.Property<int>("Operation")
.HasColumnType("integer")
.HasComment("操作类型。");
b.Property<long>("OperatorId")
.HasColumnType("bigint")
.HasComment("操作人用户标识。");
b.Property<int>("Scope")
.HasColumnType("integer")
.HasComment("字典作用域。");
b.Property<long>("TenantId")
.HasColumnType("bigint")
.HasComment("所属租户 ID。");
b.Property<DateTime>("Timestamp")
.HasColumnType("timestamp with time zone")
.HasComment("发生时间UTC。");
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("TenantId", "Timestamp");
b.ToTable("dictionary_cache_invalidation_logs", null, t =>
{
t.HasComment("字典缓存失效日志。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryItem", b =>
{
b.Property<long>("Id")
@@ -380,6 +380,84 @@ namespace TakeoutSaaS.Infrastructure.Migrations.DictionaryDb
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryLabelOverride", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasComment("实体唯一标识。");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone")
.HasComment("创建时间UTC。");
b.Property<long?>("CreatedBy")
.HasColumnType("bigint")
.HasComment("创建人用户标识。");
b.Property<DateTime?>("DeletedAt")
.HasColumnType("timestamp with time zone")
.HasComment("删除时间UTC。");
b.Property<long?>("DeletedBy")
.HasColumnType("bigint")
.HasComment("删除人用户标识。");
b.Property<long>("DictionaryItemId")
.HasColumnType("bigint")
.HasComment("被覆盖的字典项 ID。");
b.Property<string>("OriginalValue")
.IsRequired()
.HasColumnType("jsonb")
.HasComment("原始显示值JSON 格式,多语言)。");
b.Property<int>("OverrideType")
.HasColumnType("integer")
.HasComment("覆盖类型。");
b.Property<string>("OverrideValue")
.IsRequired()
.HasColumnType("jsonb")
.HasComment("覆盖后的显示值JSON 格式,多语言)。");
b.Property<string>("Reason")
.HasMaxLength(512)
.HasColumnType("character varying(512)")
.HasComment("覆盖原因/备注。");
b.Property<long>("TenantId")
.HasColumnType("bigint")
.HasComment("所属租户 ID覆盖目标租户。");
b.Property<DateTime?>("UpdatedAt")
.HasColumnType("timestamp with time zone")
.HasComment("最近更新时间UTC。");
b.Property<long?>("UpdatedBy")
.HasColumnType("bigint")
.HasComment("最后更新人用户标识。");
b.HasKey("Id");
b.HasIndex("DictionaryItemId");
b.HasIndex("TenantId");
b.HasIndex("TenantId", "DictionaryItemId")
.IsUnique()
.HasFilter("\"DeletedAt\" IS NULL");
b.HasIndex("TenantId", "OverrideType");
b.ToTable("dictionary_label_overrides", null, t =>
{
t.HasComment("字典标签覆盖配置。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.TenantDictionaryOverride", b =>
{
b.Property<long>("TenantId")
@@ -531,6 +609,17 @@ namespace TakeoutSaaS.Infrastructure.Migrations.DictionaryDb
b.Navigation("Group");
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryLabelOverride", b =>
{
b.HasOne("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryItem", "DictionaryItem")
.WithMany()
.HasForeignKey("DictionaryItemId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("DictionaryItem");
});
modelBuilder.Entity("TakeoutSaaS.Domain.Dictionary.Entities.DictionaryGroup", b =>
{
b.Navigation("Items");