feat(product): add product label management backend
All checks were successful
Build and Deploy TenantApi / build-and-deploy (push) Successful in 43s

This commit is contained in:
2026-02-21 10:18:48 +08:00
parent 93bc072b8d
commit ad65ef3bf6
21 changed files with 9480 additions and 6 deletions

View File

@@ -0,0 +1,136 @@
namespace TakeoutSaaS.TenantApi.Contracts.Product;
/// <summary>
/// 商品标签列表查询请求。
/// </summary>
public sealed class ProductLabelListRequest
{
/// <summary>
/// 门店 ID。
/// </summary>
public string StoreId { get; set; } = string.Empty;
/// <summary>
/// 关键字。
/// </summary>
public string? Keyword { get; set; }
/// <summary>
/// 状态enabled/disabled
/// </summary>
public string? Status { get; set; }
}
/// <summary>
/// 保存商品标签请求。
/// </summary>
public sealed class SaveProductLabelRequest
{
/// <summary>
/// 门店 ID。
/// </summary>
public string StoreId { get; set; } = string.Empty;
/// <summary>
/// 标签 ID编辑时传
/// </summary>
public string? Id { get; set; }
/// <summary>
/// 标签名称。
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// 标签颜色HEX
/// </summary>
public string Color { get; set; } = "#1890ff";
/// <summary>
/// 排序值。
/// </summary>
public int Sort { get; set; }
/// <summary>
/// 状态enabled/disabled
/// </summary>
public string Status { get; set; } = "enabled";
}
/// <summary>
/// 删除商品标签请求。
/// </summary>
public sealed class DeleteProductLabelRequest
{
/// <summary>
/// 门店 ID。
/// </summary>
public string StoreId { get; set; } = string.Empty;
/// <summary>
/// 标签 ID。
/// </summary>
public string LabelId { get; set; } = string.Empty;
}
/// <summary>
/// 修改商品标签状态请求。
/// </summary>
public sealed class ChangeProductLabelStatusRequest
{
/// <summary>
/// 门店 ID。
/// </summary>
public string StoreId { get; set; } = string.Empty;
/// <summary>
/// 标签 ID。
/// </summary>
public string LabelId { get; set; } = string.Empty;
/// <summary>
/// 状态enabled/disabled
/// </summary>
public string Status { get; set; } = "enabled";
}
/// <summary>
/// 商品标签列表项响应。
/// </summary>
public sealed class ProductLabelItemResponse
{
/// <summary>
/// 标签 ID。
/// </summary>
public string Id { get; set; } = string.Empty;
/// <summary>
/// 标签名称。
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// 标签颜色HEX
/// </summary>
public string Color { get; set; } = "#1890ff";
/// <summary>
/// 排序值。
/// </summary>
public int Sort { get; set; }
/// <summary>
/// 状态enabled/disabled
/// </summary>
public string Status { get; set; } = "enabled";
/// <summary>
/// 关联商品数量。
/// </summary>
public int ProductCount { get; set; }
/// <summary>
/// 更新时间。
/// </summary>
public string UpdatedAt { get; set; } = string.Empty;
}

View File

@@ -0,0 +1,135 @@
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TakeoutSaaS.Application.App.Products.Commands;
using TakeoutSaaS.Application.App.Products.Dto;
using TakeoutSaaS.Application.App.Products.Queries;
using TakeoutSaaS.Application.App.Stores.Services;
using TakeoutSaaS.Infrastructure.App.Persistence;
using TakeoutSaaS.Shared.Abstractions.Results;
using TakeoutSaaS.Shared.Web.Api;
using TakeoutSaaS.TenantApi.Contracts.Product;
namespace TakeoutSaaS.TenantApi.Controllers;
/// <summary>
/// 租户端商品标签管理。
/// </summary>
[ApiVersion("1.0")]
[Authorize]
[Route("api/tenant/v{version:apiVersion}/product")]
public sealed class ProductLabelController(
IMediator mediator,
TakeoutAppDbContext dbContext,
StoreContextService storeContextService) : BaseApiController
{
/// <summary>
/// 商品标签列表。
/// </summary>
[HttpGet("label/list")]
[ProducesResponseType(typeof(ApiResponse<IReadOnlyList<ProductLabelItemResponse>>), StatusCodes.Status200OK)]
public async Task<ApiResponse<IReadOnlyList<ProductLabelItemResponse>>> GetLabelList(
[FromQuery] ProductLabelListRequest request,
CancellationToken cancellationToken)
{
var storeId = StoreApiHelpers.ParseRequiredSnowflake(request.StoreId, nameof(request.StoreId));
await EnsureStoreAccessibleAsync(storeId, cancellationToken);
var result = await mediator.Send(new GetProductLabelListQuery
{
StoreId = storeId,
Keyword = request.Keyword,
Status = request.Status
}, cancellationToken);
return ApiResponse<IReadOnlyList<ProductLabelItemResponse>>.Ok(result.Select(MapLabelItem).ToList());
}
/// <summary>
/// 保存商品标签。
/// </summary>
[HttpPost("label/save")]
[ProducesResponseType(typeof(ApiResponse<ProductLabelItemResponse>), StatusCodes.Status200OK)]
public async Task<ApiResponse<ProductLabelItemResponse>> SaveLabel(
[FromBody] SaveProductLabelRequest request,
CancellationToken cancellationToken)
{
var storeId = StoreApiHelpers.ParseRequiredSnowflake(request.StoreId, nameof(request.StoreId));
await EnsureStoreAccessibleAsync(storeId, cancellationToken);
var result = await mediator.Send(new SaveProductLabelCommand
{
StoreId = storeId,
LabelId = StoreApiHelpers.ParseSnowflakeOrNull(request.Id),
Name = request.Name,
Color = request.Color,
Sort = request.Sort,
Status = request.Status
}, cancellationToken);
return ApiResponse<ProductLabelItemResponse>.Ok(MapLabelItem(result));
}
/// <summary>
/// 删除商品标签。
/// </summary>
[HttpPost("label/delete")]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
public async Task<ApiResponse<object>> DeleteLabel(
[FromBody] DeleteProductLabelRequest request,
CancellationToken cancellationToken)
{
var storeId = StoreApiHelpers.ParseRequiredSnowflake(request.StoreId, nameof(request.StoreId));
await EnsureStoreAccessibleAsync(storeId, cancellationToken);
await mediator.Send(new DeleteProductLabelCommand
{
StoreId = storeId,
LabelId = StoreApiHelpers.ParseRequiredSnowflake(request.LabelId, nameof(request.LabelId))
}, cancellationToken);
return ApiResponse<object>.Ok(null);
}
/// <summary>
/// 修改商品标签状态。
/// </summary>
[HttpPost("label/status")]
[ProducesResponseType(typeof(ApiResponse<ProductLabelItemResponse>), StatusCodes.Status200OK)]
public async Task<ApiResponse<ProductLabelItemResponse>> ChangeLabelStatus(
[FromBody] ChangeProductLabelStatusRequest request,
CancellationToken cancellationToken)
{
var storeId = StoreApiHelpers.ParseRequiredSnowflake(request.StoreId, nameof(request.StoreId));
await EnsureStoreAccessibleAsync(storeId, cancellationToken);
var result = await mediator.Send(new ChangeProductLabelStatusCommand
{
StoreId = storeId,
LabelId = StoreApiHelpers.ParseRequiredSnowflake(request.LabelId, nameof(request.LabelId)),
Status = request.Status
}, cancellationToken);
return ApiResponse<ProductLabelItemResponse>.Ok(MapLabelItem(result));
}
private async Task EnsureStoreAccessibleAsync(long storeId, CancellationToken cancellationToken)
{
var (tenantId, merchantId) = StoreApiHelpers.GetTenantMerchantContext(storeContextService);
await StoreApiHelpers.EnsureStoreAccessibleAsync(dbContext, tenantId, merchantId, storeId, cancellationToken);
}
private static ProductLabelItemResponse MapLabelItem(ProductLabelItemDto source)
{
return new ProductLabelItemResponse
{
Id = source.Id.ToString(),
Name = source.Name,
Color = source.Color,
Sort = source.Sort,
Status = source.Status,
ProductCount = source.ProductCount,
UpdatedAt = source.UpdatedAt.ToString("yyyy-MM-dd HH:mm:ss")
};
}
}

View File

@@ -0,0 +1,25 @@
using MediatR;
using TakeoutSaaS.Application.App.Products.Dto;
namespace TakeoutSaaS.Application.App.Products.Commands;
/// <summary>
/// 修改商品标签状态命令。
/// </summary>
public sealed class ChangeProductLabelStatusCommand : IRequest<ProductLabelItemDto>
{
/// <summary>
/// 门店 ID。
/// </summary>
public long StoreId { get; init; }
/// <summary>
/// 标签 ID。
/// </summary>
public long LabelId { get; init; }
/// <summary>
/// 状态enabled/disabled
/// </summary>
public string Status { get; init; } = "enabled";
}

View File

@@ -0,0 +1,19 @@
using MediatR;
namespace TakeoutSaaS.Application.App.Products.Commands;
/// <summary>
/// 删除商品标签命令。
/// </summary>
public sealed class DeleteProductLabelCommand : IRequest
{
/// <summary>
/// 门店 ID。
/// </summary>
public long StoreId { get; init; }
/// <summary>
/// 标签 ID。
/// </summary>
public long LabelId { get; init; }
}

View File

@@ -0,0 +1,40 @@
using MediatR;
using TakeoutSaaS.Application.App.Products.Dto;
namespace TakeoutSaaS.Application.App.Products.Commands;
/// <summary>
/// 保存商品标签命令。
/// </summary>
public sealed class SaveProductLabelCommand : IRequest<ProductLabelItemDto>
{
/// <summary>
/// 门店 ID。
/// </summary>
public long StoreId { get; init; }
/// <summary>
/// 标签 ID编辑时传
/// </summary>
public long? LabelId { get; init; }
/// <summary>
/// 标签名称。
/// </summary>
public string Name { get; init; } = string.Empty;
/// <summary>
/// 标签颜色HEX
/// </summary>
public string Color { get; init; } = "#1890ff";
/// <summary>
/// 排序值。
/// </summary>
public int Sort { get; init; }
/// <summary>
/// 状态enabled/disabled
/// </summary>
public string Status { get; init; } = "enabled";
}

View File

@@ -0,0 +1,42 @@
namespace TakeoutSaaS.Application.App.Products.Dto;
/// <summary>
/// 商品标签列表项 DTO。
/// </summary>
public sealed class ProductLabelItemDto
{
/// <summary>
/// 标签 ID。
/// </summary>
public long Id { get; init; }
/// <summary>
/// 标签名称。
/// </summary>
public string Name { get; init; } = string.Empty;
/// <summary>
/// 标签颜色HEX
/// </summary>
public string Color { get; init; } = "#1890ff";
/// <summary>
/// 排序值。
/// </summary>
public int Sort { get; init; }
/// <summary>
/// 状态enabled/disabled
/// </summary>
public string Status { get; init; } = "enabled";
/// <summary>
/// 关联商品数量。
/// </summary>
public int ProductCount { get; init; }
/// <summary>
/// 更新时间。
/// </summary>
public DateTime UpdatedAt { get; init; }
}

View File

@@ -0,0 +1,48 @@
using MediatR;
using TakeoutSaaS.Application.App.Products.Commands;
using TakeoutSaaS.Application.App.Products.Dto;
using TakeoutSaaS.Domain.Products.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;
namespace TakeoutSaaS.Application.App.Products.Handlers;
/// <summary>
/// 修改商品标签状态命令处理器。
/// </summary>
public sealed class ChangeProductLabelStatusCommandHandler(
IProductRepository productRepository,
ITenantProvider tenantProvider)
: IRequestHandler<ChangeProductLabelStatusCommand, ProductLabelItemDto>
{
/// <inheritdoc />
public async Task<ProductLabelItemDto> Handle(ChangeProductLabelStatusCommand request, CancellationToken cancellationToken)
{
// 1. 解析状态并校验标签归属。
if (!ProductLabelMapping.TryParseStatus(request.Status, out var isEnabled))
{
throw new BusinessException(ErrorCodes.BadRequest, "status 参数不合法");
}
var tenantId = tenantProvider.GetCurrentTenantId();
var existing = await productRepository.FindLabelByIdAsync(request.LabelId, tenantId, cancellationToken);
if (existing is null || existing.StoreId != request.StoreId)
{
throw new BusinessException(ErrorCodes.NotFound, "标签不存在");
}
// 2. 保存状态变更。
existing.IsEnabled = isEnabled;
await productRepository.UpdateLabelAsync(existing, cancellationToken);
await productRepository.SaveChangesAsync(cancellationToken);
// 3. 返回最新快照。
var productCounts = await productRepository.CountLabelProductsByLabelIdsAsync(
tenantId,
request.StoreId,
[existing.Id],
cancellationToken);
return ProductLabelDtoFactory.ToDto(existing, productCounts);
}
}

View File

@@ -0,0 +1,34 @@
using MediatR;
using TakeoutSaaS.Application.App.Products.Commands;
using TakeoutSaaS.Domain.Products.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;
namespace TakeoutSaaS.Application.App.Products.Handlers;
/// <summary>
/// 删除商品标签命令处理器。
/// </summary>
public sealed class DeleteProductLabelCommandHandler(
IProductRepository productRepository,
ITenantProvider tenantProvider)
: IRequestHandler<DeleteProductLabelCommand>
{
/// <inheritdoc />
public async Task Handle(DeleteProductLabelCommand request, CancellationToken cancellationToken)
{
// 1. 校验标签存在且归属当前门店。
var tenantId = tenantProvider.GetCurrentTenantId();
var existing = await productRepository.FindLabelByIdAsync(request.LabelId, tenantId, cancellationToken);
if (existing is null || existing.StoreId != request.StoreId)
{
throw new BusinessException(ErrorCodes.NotFound, "标签不存在");
}
// 2. 删除关联与标签主记录。
await productRepository.RemoveLabelProductsAsync(existing.Id, tenantId, request.StoreId, cancellationToken);
await productRepository.DeleteLabelAsync(existing.Id, tenantId, cancellationToken);
await productRepository.SaveChangesAsync(cancellationToken);
}
}

View File

@@ -0,0 +1,68 @@
using MediatR;
using TakeoutSaaS.Application.App.Products.Dto;
using TakeoutSaaS.Application.App.Products.Queries;
using TakeoutSaaS.Domain.Products.Entities;
using TakeoutSaaS.Domain.Products.Repositories;
using TakeoutSaaS.Shared.Abstractions.Tenancy;
namespace TakeoutSaaS.Application.App.Products.Handlers;
/// <summary>
/// 商品标签列表查询处理器。
/// </summary>
public sealed class GetProductLabelListQueryHandler(
IProductRepository productRepository,
ITenantProvider tenantProvider)
: IRequestHandler<GetProductLabelListQuery, IReadOnlyList<ProductLabelItemDto>>
{
/// <inheritdoc />
public async Task<IReadOnlyList<ProductLabelItemDto>> Handle(GetProductLabelListQuery request, CancellationToken cancellationToken)
{
// 1. 读取门店标签。
var tenantId = tenantProvider.GetCurrentTenantId();
var labels = await productRepository.GetLabelsByStoreAsync(tenantId, request.StoreId, cancellationToken);
if (labels.Count == 0)
{
return [];
}
// 2. 按状态与关键字过滤。
IEnumerable<ProductLabel> filtered = labels;
if (!string.IsNullOrWhiteSpace(request.Status))
{
if (!ProductLabelMapping.TryParseStatus(request.Status, out var isEnabled))
{
return [];
}
filtered = filtered.Where(item => item.IsEnabled == isEnabled);
}
var normalizedKeyword = request.Keyword?.Trim().ToLowerInvariant();
if (!string.IsNullOrWhiteSpace(normalizedKeyword))
{
filtered = filtered.Where(item => item.Name.ToLower().Contains(normalizedKeyword));
}
var filteredList = filtered
.OrderBy(item => item.SortOrder)
.ThenBy(item => item.Id)
.ToList();
if (filteredList.Count == 0)
{
return [];
}
// 3. 统计关联商品数量并映射 DTO。
var labelIds = filteredList.Select(item => item.Id).ToList();
var productCounts = await productRepository.CountLabelProductsByLabelIdsAsync(
tenantId,
request.StoreId,
labelIds,
cancellationToken);
return filteredList
.Select(label => ProductLabelDtoFactory.ToDto(label, productCounts))
.ToList();
}
}

View File

@@ -0,0 +1,97 @@
using MediatR;
using TakeoutSaaS.Application.App.Products.Commands;
using TakeoutSaaS.Application.App.Products.Dto;
using TakeoutSaaS.Domain.Products.Entities;
using TakeoutSaaS.Domain.Products.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;
namespace TakeoutSaaS.Application.App.Products.Handlers;
/// <summary>
/// 保存商品标签命令处理器。
/// </summary>
public sealed class SaveProductLabelCommandHandler(
IProductRepository productRepository,
ITenantProvider tenantProvider)
: IRequestHandler<SaveProductLabelCommand, ProductLabelItemDto>
{
/// <inheritdoc />
public async Task<ProductLabelItemDto> Handle(SaveProductLabelCommand request, CancellationToken cancellationToken)
{
// 1. 归一化并校验输入。
var tenantId = tenantProvider.GetCurrentTenantId();
var normalizedName = request.Name.Trim();
if (string.IsNullOrWhiteSpace(normalizedName))
{
throw new BusinessException(ErrorCodes.BadRequest, "标签名称不能为空");
}
if (!ProductLabelMapping.TryParseStatus(request.Status, out var isEnabled))
{
throw new BusinessException(ErrorCodes.BadRequest, "status 参数不合法");
}
if (!ProductLabelMapping.TryNormalizeColor(request.Color, out var normalizedColor))
{
throw new BusinessException(ErrorCodes.BadRequest, "标签颜色格式不合法");
}
var normalizedSort = Math.Max(0, request.Sort);
// 2. 校验门店内名称唯一。
var isDuplicate = await productRepository.ExistsLabelNameAsync(
tenantId,
request.StoreId,
normalizedName,
request.LabelId,
cancellationToken);
if (isDuplicate)
{
throw new BusinessException(ErrorCodes.Conflict, "标签名称已存在");
}
// 3. 创建或更新标签。
ProductLabel label;
if (!request.LabelId.HasValue)
{
label = new ProductLabel
{
StoreId = request.StoreId,
Name = normalizedName,
Color = normalizedColor,
SortOrder = normalizedSort,
IsEnabled = isEnabled
};
await productRepository.AddLabelAsync(label, cancellationToken);
await productRepository.SaveChangesAsync(cancellationToken);
}
else
{
var existing = await productRepository.FindLabelByIdAsync(request.LabelId.Value, tenantId, cancellationToken);
if (existing is null || existing.StoreId != request.StoreId)
{
throw new BusinessException(ErrorCodes.NotFound, "标签不存在");
}
existing.Name = normalizedName;
existing.Color = normalizedColor;
existing.SortOrder = normalizedSort;
existing.IsEnabled = isEnabled;
label = existing;
await productRepository.UpdateLabelAsync(label, cancellationToken);
await productRepository.SaveChangesAsync(cancellationToken);
}
// 4. 回读关联数量并返回快照。
var productCounts = await productRepository.CountLabelProductsByLabelIdsAsync(
tenantId,
request.StoreId,
[label.Id],
cancellationToken);
return ProductLabelDtoFactory.ToDto(label, productCounts);
}
}

View File

@@ -0,0 +1,33 @@
using TakeoutSaaS.Application.App.Products.Dto;
using TakeoutSaaS.Domain.Products.Entities;
namespace TakeoutSaaS.Application.App.Products;
/// <summary>
/// 商品标签 DTO 映射工厂。
/// </summary>
internal static class ProductLabelDtoFactory
{
/// <summary>
/// 将标签实体映射为页面 DTO。
/// </summary>
public static ProductLabelItemDto ToDto(
ProductLabel label,
IReadOnlyDictionary<long, int> productCounts)
{
var productCount = productCounts.TryGetValue(label.Id, out var count)
? count
: 0;
return new ProductLabelItemDto
{
Id = label.Id,
Name = label.Name,
Color = label.Color,
Sort = label.SortOrder,
Status = ProductLabelMapping.ToStatusText(label.IsEnabled),
ProductCount = productCount,
UpdatedAt = label.UpdatedAt ?? label.CreatedAt
};
}
}

View File

@@ -0,0 +1,76 @@
using System.Text.RegularExpressions;
namespace TakeoutSaaS.Application.App.Products;
/// <summary>
/// 商品标签映射辅助。
/// </summary>
internal static partial class ProductLabelMapping
{
/// <summary>
/// 解析状态字符串。
/// </summary>
public static bool TryParseStatus(string? status, out bool isEnabled)
{
var normalized = status?.Trim().ToLowerInvariant();
switch (normalized)
{
case "enabled":
isEnabled = true;
return true;
case "disabled":
isEnabled = false;
return true;
default:
isEnabled = true;
return false;
}
}
/// <summary>
/// 状态转字符串。
/// </summary>
public static string ToStatusText(bool isEnabled)
{
return isEnabled ? "enabled" : "disabled";
}
/// <summary>
/// 归一化颜色值。
/// </summary>
public static bool TryNormalizeColor(string? color, out string normalized)
{
var candidate = (color ?? string.Empty).Trim().ToLowerInvariant();
if (string.IsNullOrWhiteSpace(candidate))
{
normalized = "#1890ff";
return true;
}
if (!candidate.StartsWith('#'))
{
candidate = $"#{candidate}";
}
if (ShortHexColorRegex().IsMatch(candidate))
{
normalized = $"#{candidate[1]}{candidate[1]}{candidate[2]}{candidate[2]}{candidate[3]}{candidate[3]}";
return true;
}
if (LongHexColorRegex().IsMatch(candidate))
{
normalized = candidate;
return true;
}
normalized = "#1890ff";
return false;
}
[GeneratedRegex("^#[0-9a-f]{3}$", RegexOptions.Compiled)]
private static partial Regex ShortHexColorRegex();
[GeneratedRegex("^#[0-9a-f]{6}$", RegexOptions.Compiled)]
private static partial Regex LongHexColorRegex();
}

View File

@@ -0,0 +1,25 @@
using MediatR;
using TakeoutSaaS.Application.App.Products.Dto;
namespace TakeoutSaaS.Application.App.Products.Queries;
/// <summary>
/// 查询商品标签列表。
/// </summary>
public sealed class GetProductLabelListQuery : IRequest<IReadOnlyList<ProductLabelItemDto>>
{
/// <summary>
/// 门店 ID。
/// </summary>
public long StoreId { get; init; }
/// <summary>
/// 关键字。
/// </summary>
public string? Keyword { get; init; }
/// <summary>
/// 状态enabled/disabled
/// </summary>
public string? Status { get; init; }
}

View File

@@ -0,0 +1,34 @@
using TakeoutSaaS.Shared.Abstractions.Entities;
namespace TakeoutSaaS.Domain.Products.Entities;
/// <summary>
/// 商品标签模板(门店维度)。
/// </summary>
public sealed class ProductLabel : MultiTenantEntityBase
{
/// <summary>
/// 所属门店。
/// </summary>
public long StoreId { get; set; }
/// <summary>
/// 标签名称。
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// 标签颜色HEX
/// </summary>
public string Color { get; set; } = "#1890ff";
/// <summary>
/// 排序值。
/// </summary>
public int SortOrder { get; set; }
/// <summary>
/// 是否启用。
/// </summary>
public bool IsEnabled { get; set; } = true;
}

View File

@@ -0,0 +1,24 @@
using TakeoutSaaS.Shared.Abstractions.Entities;
namespace TakeoutSaaS.Domain.Products.Entities;
/// <summary>
/// 标签与商品关联关系。
/// </summary>
public sealed class ProductLabelProduct : MultiTenantEntityBase
{
/// <summary>
/// 所属门店。
/// </summary>
public long StoreId { get; set; }
/// <summary>
/// 标签 ID。
/// </summary>
public long LabelId { get; set; }
/// <summary>
/// 商品 ID。
/// </summary>
public long ProductId { get; set; }
}

View File

@@ -53,6 +53,11 @@ public interface IProductRepository
/// </summary>
Task<IReadOnlyList<ProductSpecTemplate>> GetAddonTemplatesByStoreAsync(long tenantId, long storeId, CancellationToken cancellationToken = default);
/// <summary>
/// 按门店读取商品标签。
/// </summary>
Task<IReadOnlyList<ProductLabel>> GetLabelsByStoreAsync(long tenantId, long storeId, CancellationToken cancellationToken = default);
/// <summary>
/// 依据标识读取规格做法模板。
/// </summary>
@@ -63,6 +68,11 @@ public interface IProductRepository
/// </summary>
Task<ProductSpecTemplate?> FindAddonTemplateByIdAsync(long templateId, long tenantId, CancellationToken cancellationToken = default);
/// <summary>
/// 依据标识读取商品标签。
/// </summary>
Task<ProductLabel?> FindLabelByIdAsync(long labelId, long tenantId, CancellationToken cancellationToken = default);
/// <summary>
/// 判断门店内模板名称是否已存在。
/// </summary>
@@ -73,6 +83,11 @@ public interface IProductRepository
/// </summary>
Task<bool> ExistsAddonTemplateNameAsync(long tenantId, long storeId, string name, long? excludeTemplateId = null, CancellationToken cancellationToken = default);
/// <summary>
/// 判断门店内商品标签名称是否已存在。
/// </summary>
Task<bool> ExistsLabelNameAsync(long tenantId, long storeId, string name, long? excludeLabelId = null, CancellationToken cancellationToken = default);
/// <summary>
/// 按模板读取规格做法选项。
/// </summary>
@@ -83,6 +98,11 @@ public interface IProductRepository
/// </summary>
Task<IReadOnlyList<ProductSpecTemplateProduct>> GetSpecTemplateProductsByTemplateIdsAsync(IReadOnlyCollection<long> templateIds, long tenantId, long storeId, CancellationToken cancellationToken = default);
/// <summary>
/// 统计标签关联商品数量。
/// </summary>
Task<Dictionary<long, int>> CountLabelProductsByLabelIdsAsync(long tenantId, long storeId, IReadOnlyCollection<long> labelIds, CancellationToken cancellationToken = default);
/// <summary>
/// 过滤门店内真实存在的商品 ID。
/// </summary>
@@ -220,6 +240,11 @@ public interface IProductRepository
/// </summary>
Task AddSpecTemplateProductsAsync(IEnumerable<ProductSpecTemplateProduct> relations, CancellationToken cancellationToken = default);
/// <summary>
/// 新增商品标签。
/// </summary>
Task AddLabelAsync(ProductLabel label, CancellationToken cancellationToken = default);
/// <summary>
/// 新增商品。
/// </summary>
@@ -307,6 +332,11 @@ public interface IProductRepository
/// </summary>
Task UpdateSpecTemplateAsync(ProductSpecTemplate template, CancellationToken cancellationToken = default);
/// <summary>
/// 更新商品标签。
/// </summary>
Task UpdateLabelAsync(ProductLabel label, CancellationToken cancellationToken = default);
/// <summary>
/// 删除分类。
/// </summary>
@@ -321,6 +351,11 @@ public interface IProductRepository
/// </summary>
Task DeleteSpecTemplateAsync(long templateId, long tenantId, CancellationToken cancellationToken = default);
/// <summary>
/// 删除商品标签。
/// </summary>
Task DeleteLabelAsync(long labelId, long tenantId, CancellationToken cancellationToken = default);
/// <summary>
/// 删除商品下的 SKU。
/// </summary>
@@ -340,6 +375,11 @@ public interface IProductRepository
/// </summary>
Task RemoveSpecTemplateProductsAsync(long templateId, long tenantId, long storeId, CancellationToken cancellationToken = default);
/// <summary>
/// 删除标签关联商品。
/// </summary>
Task RemoveLabelProductsAsync(long labelId, long tenantId, long storeId, CancellationToken cancellationToken = default);
/// <summary>
/// 删除商品下的加料组及选项。
/// </summary>

View File

@@ -213,6 +213,14 @@ public sealed class TakeoutAppDbContext(
/// </summary>
public DbSet<ProductSpecTemplateProduct> ProductSpecTemplateProducts => Set<ProductSpecTemplateProduct>();
/// <summary>
/// 商品标签。
/// </summary>
public DbSet<ProductLabel> ProductLabels => Set<ProductLabel>();
/// <summary>
/// 标签与商品关联。
/// </summary>
public DbSet<ProductLabelProduct> ProductLabelProducts => Set<ProductLabelProduct>();
/// <summary>
/// SKU 实体。
/// </summary>
public DbSet<ProductSku> ProductSkus => Set<ProductSku>();
@@ -456,6 +464,8 @@ public sealed class TakeoutAppDbContext(
ConfigureProductSpecTemplate(modelBuilder.Entity<ProductSpecTemplate>());
ConfigureProductSpecTemplateOption(modelBuilder.Entity<ProductSpecTemplateOption>());
ConfigureProductSpecTemplateProduct(modelBuilder.Entity<ProductSpecTemplateProduct>());
ConfigureProductLabel(modelBuilder.Entity<ProductLabel>());
ConfigureProductLabelProduct(modelBuilder.Entity<ProductLabelProduct>());
ConfigureProductSku(modelBuilder.Entity<ProductSku>());
ConfigureProductAddonGroup(modelBuilder.Entity<ProductAddonGroup>());
ConfigureProductAddonOption(modelBuilder.Entity<ProductAddonOption>());
@@ -1221,6 +1231,30 @@ public sealed class TakeoutAppDbContext(
builder.HasIndex(x => new { x.TenantId, x.StoreId, x.ProductId });
}
private static void ConfigureProductLabel(EntityTypeBuilder<ProductLabel> builder)
{
builder.ToTable("product_labels");
builder.HasKey(x => x.Id);
builder.Property(x => x.StoreId).IsRequired();
builder.Property(x => x.Name).HasMaxLength(64).IsRequired();
builder.Property(x => x.Color).HasMaxLength(32).IsRequired();
builder.Property(x => x.SortOrder).IsRequired();
builder.Property(x => x.IsEnabled).IsRequired();
builder.HasIndex(x => new { x.TenantId, x.StoreId, x.Name }).IsUnique();
builder.HasIndex(x => new { x.TenantId, x.StoreId, x.IsEnabled, x.SortOrder });
}
private static void ConfigureProductLabelProduct(EntityTypeBuilder<ProductLabelProduct> builder)
{
builder.ToTable("product_label_products");
builder.HasKey(x => x.Id);
builder.Property(x => x.StoreId).IsRequired();
builder.Property(x => x.LabelId).IsRequired();
builder.Property(x => x.ProductId).IsRequired();
builder.HasIndex(x => new { x.TenantId, x.StoreId, x.LabelId, x.ProductId }).IsUnique();
builder.HasIndex(x => new { x.TenantId, x.StoreId, x.ProductId });
}
private static void ConfigureProductSku(EntityTypeBuilder<ProductSku> builder)
{
builder.ToTable("product_skus");

View File

@@ -161,6 +161,17 @@ public sealed class EfProductRepository(TakeoutAppDbContext context) : IProductR
.ToListAsync(cancellationToken);
}
/// <inheritdoc />
public async Task<IReadOnlyList<ProductLabel>> GetLabelsByStoreAsync(long tenantId, long storeId, CancellationToken cancellationToken = default)
{
return await context.ProductLabels
.AsNoTracking()
.Where(x => x.TenantId == tenantId && x.StoreId == storeId)
.OrderBy(x => x.SortOrder)
.ThenBy(x => x.Id)
.ToListAsync(cancellationToken);
}
/// <inheritdoc />
public Task<ProductSpecTemplate?> FindSpecTemplateByIdAsync(long templateId, long tenantId, CancellationToken cancellationToken = default)
{
@@ -183,6 +194,14 @@ public sealed class EfProductRepository(TakeoutAppDbContext context) : IProductR
.FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc />
public Task<ProductLabel?> FindLabelByIdAsync(long labelId, long tenantId, CancellationToken cancellationToken = default)
{
return context.ProductLabels
.Where(x => x.TenantId == tenantId && x.Id == labelId)
.FirstOrDefaultAsync(cancellationToken);
}
/// <inheritdoc />
public Task<bool> ExistsSpecTemplateNameAsync(long tenantId, long storeId, string name, long? excludeTemplateId = null, CancellationToken cancellationToken = default)
{
@@ -225,6 +244,26 @@ public sealed class EfProductRepository(TakeoutAppDbContext context) : IProductR
return query.AnyAsync(cancellationToken);
}
/// <inheritdoc />
public Task<bool> ExistsLabelNameAsync(long tenantId, long storeId, string name, long? excludeLabelId = null, CancellationToken cancellationToken = default)
{
var normalizedName = (name ?? string.Empty).Trim();
var normalizedLower = normalizedName.ToLowerInvariant();
var query = context.ProductLabels
.AsNoTracking()
.Where(x =>
x.TenantId == tenantId &&
x.StoreId == storeId &&
x.Name.ToLower() == normalizedLower);
if (excludeLabelId.HasValue)
{
query = query.Where(x => x.Id != excludeLabelId.Value);
}
return query.AnyAsync(cancellationToken);
}
/// <inheritdoc />
public async Task<IReadOnlyList<ProductSpecTemplateOption>> GetSpecTemplateOptionsByTemplateIdsAsync(IReadOnlyCollection<long> templateIds, long tenantId, CancellationToken cancellationToken = default)
{
@@ -260,6 +299,25 @@ public sealed class EfProductRepository(TakeoutAppDbContext context) : IProductR
.ToListAsync(cancellationToken);
}
/// <inheritdoc />
public async Task<Dictionary<long, int>> CountLabelProductsByLabelIdsAsync(long tenantId, long storeId, IReadOnlyCollection<long> labelIds, CancellationToken cancellationToken = default)
{
if (labelIds.Count == 0)
{
return [];
}
return await context.ProductLabelProducts
.AsNoTracking()
.Where(x =>
x.TenantId == tenantId &&
x.StoreId == storeId &&
labelIds.Contains(x.LabelId))
.GroupBy(x => x.LabelId)
.Select(group => new { LabelId = group.Key, Count = group.Count() })
.ToDictionaryAsync(item => item.LabelId, item => item.Count, cancellationToken);
}
/// <inheritdoc />
public async Task<IReadOnlyList<long>> FilterExistingProductIdsAsync(long tenantId, long storeId, IReadOnlyCollection<long> productIds, CancellationToken cancellationToken = default)
{
@@ -585,6 +643,12 @@ public sealed class EfProductRepository(TakeoutAppDbContext context) : IProductR
return context.ProductSpecTemplateProducts.AddRangeAsync(relations, cancellationToken);
}
/// <inheritdoc />
public Task AddLabelAsync(ProductLabel label, CancellationToken cancellationToken = default)
{
return context.ProductLabels.AddAsync(label, cancellationToken).AsTask();
}
/// <inheritdoc />
public Task AddProductAsync(Product product, CancellationToken cancellationToken = default)
{
@@ -673,6 +737,13 @@ public sealed class EfProductRepository(TakeoutAppDbContext context) : IProductR
return Task.CompletedTask;
}
/// <inheritdoc />
public Task UpdateLabelAsync(ProductLabel label, CancellationToken cancellationToken = default)
{
context.ProductLabels.Update(label);
return Task.CompletedTask;
}
/// <inheritdoc />
public async Task DeleteCategoryAsync(long categoryId, long tenantId, CancellationToken cancellationToken = default)
{
@@ -705,6 +776,23 @@ public sealed class EfProductRepository(TakeoutAppDbContext context) : IProductR
.ExecuteDeleteAsync(cancellationToken);
}
/// <inheritdoc />
public async Task DeleteLabelAsync(long labelId, long tenantId, CancellationToken cancellationToken = default)
{
var existing = await context.ProductLabels
.Where(x => x.TenantId == tenantId && x.Id == labelId)
.FirstOrDefaultAsync(cancellationToken);
if (existing is null)
{
return;
}
await context.ProductLabels
.Where(x => x.TenantId == tenantId && x.Id == labelId)
.ExecuteDeleteAsync(cancellationToken);
}
/// <inheritdoc />
public async Task RemoveSkusAsync(long productId, long tenantId, CancellationToken cancellationToken = default)
{
@@ -739,6 +827,17 @@ public sealed class EfProductRepository(TakeoutAppDbContext context) : IProductR
.ExecuteDeleteAsync(cancellationToken);
}
/// <inheritdoc />
public async Task RemoveLabelProductsAsync(long labelId, long tenantId, long storeId, CancellationToken cancellationToken = default)
{
await context.ProductLabelProducts
.Where(x =>
x.TenantId == tenantId &&
x.StoreId == storeId &&
x.LabelId == labelId)
.ExecuteDeleteAsync(cancellationToken);
}
/// <inheritdoc />
public async Task RemoveAddonGroupsAsync(long productId, long tenantId, CancellationToken cancellationToken = default)
{

View File

@@ -0,0 +1,96 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace TakeoutSaaS.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AddProductLabels : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "product_label_products",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false, comment: "实体唯一标识。")
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
StoreId = table.Column<long>(type: "bigint", nullable: false, comment: "所属门店。"),
LabelId = table.Column<long>(type: "bigint", nullable: false, comment: "标签 ID。"),
ProductId = table.Column<long>(type: "bigint", nullable: false, comment: "商品 ID。"),
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。"),
TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "所属租户 ID。")
},
constraints: table =>
{
table.PrimaryKey("PK_product_label_products", x => x.Id);
},
comment: "标签与商品关联关系。");
migrationBuilder.CreateTable(
name: "product_labels",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false, comment: "实体唯一标识。")
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
StoreId = table.Column<long>(type: "bigint", nullable: false, comment: "所属门店。"),
Name = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false, comment: "标签名称。"),
Color = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false, comment: "标签颜色HEX。"),
SortOrder = table.Column<int>(type: "integer", nullable: false, comment: "排序值。"),
IsEnabled = table.Column<bool>(type: "boolean", nullable: false, 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从未更新时为 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。"),
TenantId = table.Column<long>(type: "bigint", nullable: false, comment: "所属租户 ID。")
},
constraints: table =>
{
table.PrimaryKey("PK_product_labels", x => x.Id);
},
comment: "商品标签模板(门店维度)。");
migrationBuilder.CreateIndex(
name: "IX_product_label_products_TenantId_StoreId_LabelId_ProductId",
table: "product_label_products",
columns: new[] { "TenantId", "StoreId", "LabelId", "ProductId" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_product_label_products_TenantId_StoreId_ProductId",
table: "product_label_products",
columns: new[] { "TenantId", "StoreId", "ProductId" });
migrationBuilder.CreateIndex(
name: "IX_product_labels_TenantId_StoreId_IsEnabled_SortOrder",
table: "product_labels",
columns: new[] { "TenantId", "StoreId", "IsEnabled", "SortOrder" });
migrationBuilder.CreateIndex(
name: "IX_product_labels_TenantId_StoreId_Name",
table: "product_labels",
columns: new[] { "TenantId", "StoreId", "Name" },
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "product_label_products");
migrationBuilder.DropTable(
name: "product_labels");
}
}
}

View File

@@ -4424,6 +4424,142 @@ namespace TakeoutSaaS.Infrastructure.Migrations
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Products.Entities.ProductLabel", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint")
.HasComment("实体唯一标识。");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id"));
b.Property<string>("Color")
.IsRequired()
.HasMaxLength(32)
.HasColumnType("character varying(32)")
.HasComment("标签颜色HEX。");
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<bool>("IsEnabled")
.HasColumnType("boolean")
.HasComment("是否启用。");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasComment("标签名称。");
b.Property<int>("SortOrder")
.HasColumnType("integer")
.HasComment("排序值。");
b.Property<long>("StoreId")
.HasColumnType("bigint")
.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", "StoreId", "Name")
.IsUnique();
b.HasIndex("TenantId", "StoreId", "IsEnabled", "SortOrder");
b.ToTable("product_labels", null, t =>
{
t.HasComment("商品标签模板(门店维度)。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Products.Entities.ProductLabelProduct", 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<long>("LabelId")
.HasColumnType("bigint")
.HasComment("标签 ID。");
b.Property<long>("ProductId")
.HasColumnType("bigint")
.HasComment("商品 ID。");
b.Property<long>("StoreId")
.HasColumnType("bigint")
.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", "StoreId", "ProductId");
b.HasIndex("TenantId", "StoreId", "LabelId", "ProductId")
.IsUnique();
b.ToTable("product_label_products", null, t =>
{
t.HasComment("标签与商品关联关系。");
});
});
modelBuilder.Entity("TakeoutSaaS.Domain.Products.Entities.ProductMediaAsset", b =>
{
b.Property<long>("Id")
@@ -4707,16 +4843,16 @@ namespace TakeoutSaaS.Infrastructure.Migrations
.HasColumnType("integer")
.HasComment("最大可选数。");
b.Property<int>("MinSelect")
.HasColumnType("integer")
.HasComment("最小可选数。");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)")
.HasComment("模板名称。");
b.Property<int>("MinSelect")
.HasColumnType("integer")
.HasComment("最小可选数。");
b.Property<int>("SelectionType")
.HasColumnType("integer")
.HasComment("选择方式。");
@@ -4747,11 +4883,11 @@ namespace TakeoutSaaS.Infrastructure.Migrations
b.HasKey("Id");
b.HasIndex("TenantId", "StoreId", "TemplateType", "IsEnabled");
b.HasIndex("TenantId", "StoreId", "TemplateType", "Name")
.IsUnique();
b.HasIndex("TenantId", "StoreId", "TemplateType", "IsEnabled");
b.ToTable("product_spec_templates", null, t =>
{
t.HasComment("门店规格做法模板。");