feat: 新增加料管理接口与模板能力
All checks were successful
Build and Deploy TenantApi / build-and-deploy (push) Successful in 43s

This commit is contained in:
2026-02-21 08:44:26 +08:00
parent 848778b8b5
commit 93bc072b8d
27 changed files with 1605 additions and 6 deletions

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 BindProductAddonGroupProductsCommand : IRequest<ProductAddonTemplateItemDto>
{
/// <summary>
/// 门店 ID。
/// </summary>
public long StoreId { get; init; }
/// <summary>
/// 加料组 ID。
/// </summary>
public long GroupId { get; init; }
/// <summary>
/// 商品 ID 列表。
/// </summary>
public IReadOnlyList<long> ProductIds { get; init; } = [];
}

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 ChangeProductAddonGroupStatusCommand : IRequest<ProductAddonTemplateItemDto>
{
/// <summary>
/// 门店 ID。
/// </summary>
public long StoreId { get; init; }
/// <summary>
/// 加料组 ID。
/// </summary>
public long GroupId { 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 DeleteProductAddonGroupCommand : IRequest
{
/// <summary>
/// 门店 ID。
/// </summary>
public long StoreId { get; init; }
/// <summary>
/// 加料组 ID。
/// </summary>
public long GroupId { get; init; }
}

View File

@@ -0,0 +1,65 @@
using MediatR;
using TakeoutSaaS.Application.App.Products.Dto;
namespace TakeoutSaaS.Application.App.Products.Commands;
/// <summary>
/// 保存加料组命令。
/// </summary>
public sealed class SaveProductAddonGroupCommand : IRequest<ProductAddonTemplateItemDto>
{
/// <summary>
/// 门店 ID。
/// </summary>
public long StoreId { get; init; }
/// <summary>
/// 加料组 ID编辑时传
/// </summary>
public long? GroupId { get; init; }
/// <summary>
/// 加料组名称。
/// </summary>
public string Name { get; init; } = string.Empty;
/// <summary>
/// 描述。
/// </summary>
public string Description { get; init; } = string.Empty;
/// <summary>
/// 是否必选。
/// </summary>
public bool Required { get; init; }
/// <summary>
/// 最小可选数量。
/// </summary>
public int MinSelect { get; init; }
/// <summary>
/// 最大可选数量。
/// </summary>
public int MaxSelect { get; init; }
/// <summary>
/// 排序值。
/// </summary>
public int Sort { get; init; }
/// <summary>
/// 状态enabled/disabled
/// </summary>
public string Status { get; init; } = "enabled";
/// <summary>
/// 关联商品 ID。
/// </summary>
public IReadOnlyList<long> ProductIds { get; init; } = [];
/// <summary>
/// 加料项列表。
/// </summary>
public IReadOnlyList<SaveProductAddonItemCommand> Items { get; init; } = [];
}

View File

@@ -0,0 +1,37 @@
namespace TakeoutSaaS.Application.App.Products.Commands;
/// <summary>
/// 保存加料项命令。
/// </summary>
public sealed class SaveProductAddonItemCommand
{
/// <summary>
/// 加料项 ID编辑时可传
/// </summary>
public long? Id { get; init; }
/// <summary>
/// 加料项名称。
/// </summary>
public string Name { get; init; } = string.Empty;
/// <summary>
/// 加价金额。
/// </summary>
public decimal Price { get; init; }
/// <summary>
/// 库存数量。
/// </summary>
public int Stock { get; init; } = 999;
/// <summary>
/// 排序值。
/// </summary>
public int Sort { get; init; }
/// <summary>
/// 状态enabled/disabled
/// </summary>
public string Status { get; init; } = "enabled";
}

View File

@@ -0,0 +1,67 @@
namespace TakeoutSaaS.Application.App.Products.Dto;
/// <summary>
/// 加料模板列表项 DTO。
/// </summary>
public sealed class ProductAddonTemplateItemDto
{
/// <summary>
/// 模板 ID。
/// </summary>
public long Id { get; init; }
/// <summary>
/// 模板名称。
/// </summary>
public string Name { get; init; } = string.Empty;
/// <summary>
/// 模板描述。
/// </summary>
public string Description { get; init; } = string.Empty;
/// <summary>
/// 是否必选。
/// </summary>
public bool Required { get; init; }
/// <summary>
/// 最小可选数。
/// </summary>
public int MinSelect { get; init; }
/// <summary>
/// 最大可选数。
/// </summary>
public int MaxSelect { get; init; }
/// <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>
/// 关联商品 ID 列表。
/// </summary>
public IReadOnlyList<long> ProductIds { get; init; } = [];
/// <summary>
/// 加料项列表。
/// </summary>
public IReadOnlyList<ProductAddonTemplateOptionDto> Items { get; init; } = [];
/// <summary>
/// 更新时间。
/// </summary>
public DateTime UpdatedAt { get; init; }
}

View File

@@ -0,0 +1,37 @@
namespace TakeoutSaaS.Application.App.Products.Dto;
/// <summary>
/// 加料模板选项 DTO。
/// </summary>
public sealed class ProductAddonTemplateOptionDto
{
/// <summary>
/// 选项 ID。
/// </summary>
public long Id { get; init; }
/// <summary>
/// 选项名称。
/// </summary>
public string Name { get; init; } = string.Empty;
/// <summary>
/// 加价金额。
/// </summary>
public decimal Price { get; init; }
/// <summary>
/// 库存数量。
/// </summary>
public int Stock { get; init; }
/// <summary>
/// 排序值。
/// </summary>
public int Sort { get; init; }
/// <summary>
/// 状态enabled/disabled
/// </summary>
public string Status { get; init; } = "enabled";
}

View File

@@ -0,0 +1,71 @@
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 BindProductAddonGroupProductsCommandHandler(
IProductRepository productRepository,
ITenantProvider tenantProvider)
: IRequestHandler<BindProductAddonGroupProductsCommand, ProductAddonTemplateItemDto>
{
/// <inheritdoc />
public async Task<ProductAddonTemplateItemDto> Handle(BindProductAddonGroupProductsCommand request, CancellationToken cancellationToken)
{
// 1. 校验加料组是否存在且归属当前门店。
var tenantId = tenantProvider.GetCurrentTenantId();
var existing = await productRepository.FindAddonTemplateByIdAsync(request.GroupId, tenantId, cancellationToken);
if (existing is null || existing.StoreId != request.StoreId)
{
throw new BusinessException(ErrorCodes.NotFound, "加料组不存在");
}
// 2. 过滤有效商品并替换关联关系。
var normalizedProductIds = request.ProductIds
.Where(item => item > 0)
.Distinct()
.ToList();
var validProductIds = await productRepository.FilterExistingProductIdsAsync(
tenantId,
request.StoreId,
normalizedProductIds,
cancellationToken);
await productRepository.RemoveSpecTemplateProductsAsync(existing.Id, tenantId, request.StoreId, cancellationToken);
var relations = validProductIds
.Select(productId => new ProductSpecTemplateProduct
{
StoreId = request.StoreId,
TemplateId = existing.Id,
ProductId = productId
})
.ToList();
if (relations.Count > 0)
{
await productRepository.AddSpecTemplateProductsAsync(relations, cancellationToken);
}
await productRepository.SaveChangesAsync(cancellationToken);
// 3. 返回最新快照。
var options = await productRepository.GetSpecTemplateOptionsByTemplateIdsAsync([existing.Id], tenantId, cancellationToken);
var latestRelations = await productRepository.GetSpecTemplateProductsByTemplateIdsAsync([existing.Id], tenantId, request.StoreId, cancellationToken);
var optionsLookup = options
.GroupBy(x => x.TemplateId)
.ToDictionary(group => group.Key, group => group.OrderBy(item => item.SortOrder).ThenBy(item => item.Id).ToList());
var productIdsLookup = latestRelations
.GroupBy(x => x.TemplateId)
.ToDictionary(group => group.Key, group => group.Select(item => item.ProductId).ToList());
return ProductAddonTemplateDtoFactory.ToDto(existing, optionsLookup, productIdsLookup);
}
}

View File

@@ -0,0 +1,52 @@
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 ChangeProductAddonGroupStatusCommandHandler(
IProductRepository productRepository,
ITenantProvider tenantProvider)
: IRequestHandler<ChangeProductAddonGroupStatusCommand, ProductAddonTemplateItemDto>
{
/// <inheritdoc />
public async Task<ProductAddonTemplateItemDto> Handle(ChangeProductAddonGroupStatusCommand request, CancellationToken cancellationToken)
{
// 1. 解析状态并验证加料组归属。
if (!ProductAddonTemplateMapping.TryParseStatus(request.Status, out var isEnabled))
{
throw new BusinessException(ErrorCodes.BadRequest, "status 参数不合法");
}
var tenantId = tenantProvider.GetCurrentTenantId();
var existing = await productRepository.FindAddonTemplateByIdAsync(request.GroupId, tenantId, cancellationToken);
if (existing is null || existing.StoreId != request.StoreId)
{
throw new BusinessException(ErrorCodes.NotFound, "加料组不存在");
}
// 2. 保存状态变更。
existing.IsEnabled = isEnabled;
await productRepository.UpdateSpecTemplateAsync(existing, cancellationToken);
await productRepository.SaveChangesAsync(cancellationToken);
// 3. 返回完整快照。
var options = await productRepository.GetSpecTemplateOptionsByTemplateIdsAsync([existing.Id], tenantId, cancellationToken);
var relations = await productRepository.GetSpecTemplateProductsByTemplateIdsAsync([existing.Id], tenantId, request.StoreId, cancellationToken);
var optionsLookup = options
.GroupBy(x => x.TemplateId)
.ToDictionary(group => group.Key, group => group.OrderBy(item => item.SortOrder).ThenBy(item => item.Id).ToList());
var productIdsLookup = relations
.GroupBy(x => x.TemplateId)
.ToDictionary(group => group.Key, group => group.Select(item => item.ProductId).ToList());
return ProductAddonTemplateDtoFactory.ToDto(existing, optionsLookup, productIdsLookup);
}
}

View File

@@ -0,0 +1,35 @@
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 DeleteProductAddonGroupCommandHandler(
IProductRepository productRepository,
ITenantProvider tenantProvider)
: IRequestHandler<DeleteProductAddonGroupCommand>
{
/// <inheritdoc />
public async Task Handle(DeleteProductAddonGroupCommand request, CancellationToken cancellationToken)
{
// 1. 校验加料组是否存在且归属当前门店。
var tenantId = tenantProvider.GetCurrentTenantId();
var existing = await productRepository.FindAddonTemplateByIdAsync(request.GroupId, tenantId, cancellationToken);
if (existing is null || existing.StoreId != request.StoreId)
{
throw new BusinessException(ErrorCodes.NotFound, "加料组不存在");
}
// 2. 删除选项、关联商品和模板主记录。
await productRepository.RemoveSpecTemplateOptionsAsync(existing.Id, tenantId, cancellationToken);
await productRepository.RemoveSpecTemplateProductsAsync(existing.Id, tenantId, request.StoreId, cancellationToken);
await productRepository.DeleteSpecTemplateAsync(existing.Id, tenantId, cancellationToken);
await productRepository.SaveChangesAsync(cancellationToken);
}
}

View File

@@ -0,0 +1,75 @@
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 GetProductAddonGroupListQueryHandler(
IProductRepository productRepository,
ITenantProvider tenantProvider)
: IRequestHandler<GetProductAddonGroupListQuery, IReadOnlyList<ProductAddonTemplateItemDto>>
{
/// <inheritdoc />
public async Task<IReadOnlyList<ProductAddonTemplateItemDto>> Handle(GetProductAddonGroupListQuery request, CancellationToken cancellationToken)
{
// 1. 读取门店下的加料模板。
var tenantId = tenantProvider.GetCurrentTenantId();
var templates = await productRepository.GetAddonTemplatesByStoreAsync(tenantId, request.StoreId, cancellationToken);
if (templates.Count == 0)
{
return [];
}
// 2. 按状态与关键字过滤。
IEnumerable<ProductSpecTemplate> filtered = templates;
if (!string.IsNullOrWhiteSpace(request.Status))
{
if (!ProductAddonTemplateMapping.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) ||
item.Description.ToLower().Contains(normalizedKeyword));
}
// 3. 批量读取选项与关联商品。
var filteredList = filtered
.OrderBy(item => item.SortOrder)
.ThenBy(item => item.Id)
.ToList();
if (filteredList.Count == 0)
{
return [];
}
var templateIds = filteredList.Select(item => item.Id).ToList();
var options = await productRepository.GetSpecTemplateOptionsByTemplateIdsAsync(templateIds, tenantId, cancellationToken);
var relations = await productRepository.GetSpecTemplateProductsByTemplateIdsAsync(templateIds, tenantId, request.StoreId, cancellationToken);
// 4. 构建字典并映射 DTO。
var optionsLookup = options
.GroupBy(x => x.TemplateId)
.ToDictionary(group => group.Key, group => group.OrderBy(item => item.SortOrder).ThenBy(item => item.Id).ToList());
var productIdsLookup = relations
.GroupBy(x => x.TemplateId)
.ToDictionary(group => group.Key, group => group.Select(item => item.ProductId).ToList());
return filteredList
.Select(template => ProductAddonTemplateDtoFactory.ToDto(template, optionsLookup, productIdsLookup))
.ToList();
}
}

View File

@@ -0,0 +1,241 @@
using MediatR;
using TakeoutSaaS.Application.App.Products.Commands;
using TakeoutSaaS.Application.App.Products.Dto;
using TakeoutSaaS.Domain.Products.Entities;
using TakeoutSaaS.Domain.Products.Enums;
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 SaveProductAddonGroupCommandHandler(
IProductRepository productRepository,
ITenantProvider tenantProvider)
: IRequestHandler<SaveProductAddonGroupCommand, ProductAddonTemplateItemDto>
{
/// <inheritdoc />
public async Task<ProductAddonTemplateItemDto> Handle(SaveProductAddonGroupCommand request, CancellationToken cancellationToken)
{
// 1. 校验基础输入并归一化参数。
var tenantId = tenantProvider.GetCurrentTenantId();
var normalizedName = request.Name.Trim();
if (string.IsNullOrWhiteSpace(normalizedName))
{
throw new BusinessException(ErrorCodes.BadRequest, "加料组名称不能为空");
}
if (!ProductAddonTemplateMapping.TryParseStatus(request.Status, out var isEnabled))
{
throw new BusinessException(ErrorCodes.BadRequest, "status 参数不合法");
}
var normalizedDescription = request.Description.Trim();
var normalizedMinSelect = Math.Max(0, request.MinSelect);
var normalizedMaxSelect = Math.Max(1, request.MaxSelect);
if (normalizedMaxSelect < normalizedMinSelect)
{
normalizedMaxSelect = normalizedMinSelect;
}
if (request.Required && normalizedMinSelect == 0)
{
normalizedMinSelect = 1;
if (normalizedMaxSelect < 1)
{
normalizedMaxSelect = 1;
}
}
var normalizedItems = NormalizeItems(request.Items);
if (normalizedItems.Count == 0)
{
throw new BusinessException(ErrorCodes.BadRequest, "请至少添加一个加料项");
}
// 2. 校验同门店名称唯一。
var isDuplicate = await productRepository.ExistsAddonTemplateNameAsync(
tenantId,
request.StoreId,
normalizedName,
request.GroupId,
cancellationToken);
if (isDuplicate)
{
throw new BusinessException(ErrorCodes.Conflict, "加料组名称已存在");
}
// 3. 过滤有效商品并创建或更新模板主记录。
var normalizedProductIds = request.ProductIds
.Where(id => id > 0)
.Distinct()
.ToList();
var validProductIds = await productRepository.FilterExistingProductIdsAsync(
tenantId,
request.StoreId,
normalizedProductIds,
cancellationToken);
ProductSpecTemplate template;
var isCreate = !request.GroupId.HasValue;
if (isCreate)
{
template = new ProductSpecTemplate
{
StoreId = request.StoreId,
Name = normalizedName,
Description = normalizedDescription,
TemplateType = ProductSpecTemplateType.Addon,
SelectionType = ProductAddonTemplateMapping.ToSelectionType(normalizedMaxSelect),
IsRequired = request.Required,
MinSelect = normalizedMinSelect,
MaxSelect = normalizedMaxSelect,
SortOrder = Math.Max(1, request.Sort),
IsEnabled = isEnabled
};
await productRepository.AddSpecTemplateAsync(template, cancellationToken);
await productRepository.SaveChangesAsync(cancellationToken);
}
else
{
var groupId = request.GroupId
?? throw new BusinessException(ErrorCodes.BadRequest, "加料组标识不能为空");
var existing = await productRepository.FindAddonTemplateByIdAsync(
groupId,
tenantId,
cancellationToken);
if (existing is null || existing.StoreId != request.StoreId)
{
throw new BusinessException(ErrorCodes.NotFound, "加料组不存在");
}
template = existing;
template.Name = normalizedName;
template.Description = normalizedDescription;
template.SelectionType = ProductAddonTemplateMapping.ToSelectionType(normalizedMaxSelect);
template.IsRequired = request.Required;
template.MinSelect = normalizedMinSelect;
template.MaxSelect = normalizedMaxSelect;
template.SortOrder = Math.Max(1, request.Sort);
template.IsEnabled = isEnabled;
await productRepository.UpdateSpecTemplateAsync(template, cancellationToken);
}
// 4. 替换选项与关联商品。
await productRepository.RemoveSpecTemplateOptionsAsync(template.Id, tenantId, cancellationToken);
await productRepository.RemoveSpecTemplateProductsAsync(template.Id, tenantId, request.StoreId, cancellationToken);
var optionEntities = normalizedItems
.Select(item => new ProductSpecTemplateOption
{
TemplateId = template.Id,
Name = item.Name,
ExtraPrice = item.Price,
Stock = item.Stock,
IsEnabled = item.IsEnabled,
SortOrder = item.Sort
})
.ToList();
if (optionEntities.Count > 0)
{
await productRepository.AddSpecTemplateOptionsAsync(optionEntities, cancellationToken);
}
var relationEntities = validProductIds
.Select(productId => new ProductSpecTemplateProduct
{
StoreId = request.StoreId,
TemplateId = template.Id,
ProductId = productId
})
.ToList();
if (relationEntities.Count > 0)
{
await productRepository.AddSpecTemplateProductsAsync(relationEntities, cancellationToken);
}
await productRepository.SaveChangesAsync(cancellationToken);
// 5. 回读并返回最新快照。
return await LoadAddonTemplateSnapshotAsync(template, tenantId, request.StoreId, cancellationToken);
}
private static IReadOnlyList<NormalizedAddonItem> NormalizeItems(IReadOnlyList<SaveProductAddonItemCommand>? items)
{
var source = items ?? [];
var normalized = source
.Select((item, index) =>
{
if (!ProductAddonTemplateMapping.TryParseStatus(item.Status, out var isEnabled))
{
throw new BusinessException(ErrorCodes.BadRequest, "加料项状态不合法");
}
return new NormalizedAddonItem
{
Name = item.Name.Trim(),
Price = item.Price,
Stock = Math.Max(0, item.Stock),
Sort = item.Sort > 0 ? item.Sort : index + 1,
IsEnabled = isEnabled
};
})
.Where(item => !string.IsNullOrWhiteSpace(item.Name))
.OrderBy(item => item.Sort)
.ToList();
var duplicate = normalized
.GroupBy(item => item.Name, StringComparer.OrdinalIgnoreCase)
.Any(group => group.Count() > 1);
if (duplicate)
{
throw new BusinessException(ErrorCodes.Conflict, "加料项名称重复");
}
for (var index = 0; index < normalized.Count; index++)
{
normalized[index].Sort = index + 1;
}
return normalized;
}
private async Task<ProductAddonTemplateItemDto> LoadAddonTemplateSnapshotAsync(
ProductSpecTemplate template,
long tenantId,
long storeId,
CancellationToken cancellationToken)
{
var options = await productRepository.GetSpecTemplateOptionsByTemplateIdsAsync([template.Id], tenantId, cancellationToken);
var relations = await productRepository.GetSpecTemplateProductsByTemplateIdsAsync([template.Id], tenantId, storeId, cancellationToken);
var optionsLookup = options
.GroupBy(x => x.TemplateId)
.ToDictionary(group => group.Key, group => group.OrderBy(item => item.SortOrder).ThenBy(item => item.Id).ToList());
var productIdsLookup = relations
.GroupBy(x => x.TemplateId)
.ToDictionary(group => group.Key, group => group.Select(item => item.ProductId).ToList());
return ProductAddonTemplateDtoFactory.ToDto(template, optionsLookup, productIdsLookup);
}
private sealed class NormalizedAddonItem
{
public bool IsEnabled { get; init; }
public string Name { get; init; } = string.Empty;
public decimal Price { get; init; }
public int Sort { get; set; }
public int Stock { get; init; }
}
}

View File

@@ -2,6 +2,7 @@ using MediatR;
using TakeoutSaaS.Application.App.Products.Commands;
using TakeoutSaaS.Application.App.Products.Dto;
using TakeoutSaaS.Domain.Products.Entities;
using TakeoutSaaS.Domain.Products.Enums;
using TakeoutSaaS.Domain.Products.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
@@ -49,6 +50,11 @@ public sealed class SaveProductSpecTemplateCommandHandler(
throw new BusinessException(ErrorCodes.BadRequest, "请至少添加一个选项");
}
var normalizedMinSelect = request.IsRequired ? 1 : 0;
var normalizedMaxSelect = selectionType == AttributeSelectionType.Single
? 1
: Math.Max(1, normalizedValues.Count);
// 2. 校验同门店模板名称唯一。
var isDuplicate = await productRepository.ExistsSpecTemplateNameAsync(
tenantId,
@@ -80,9 +86,12 @@ public sealed class SaveProductSpecTemplateCommandHandler(
{
StoreId = request.StoreId,
Name = normalizedName,
Description = string.Empty,
TemplateType = templateType,
SelectionType = selectionType,
IsRequired = request.IsRequired,
MinSelect = normalizedMinSelect,
MaxSelect = normalizedMaxSelect,
SortOrder = Math.Max(1, request.Sort),
IsEnabled = isEnabled
};
@@ -105,6 +114,8 @@ public sealed class SaveProductSpecTemplateCommandHandler(
template.TemplateType = templateType;
template.SelectionType = selectionType;
template.IsRequired = request.IsRequired;
template.MinSelect = normalizedMinSelect;
template.MaxSelect = normalizedMaxSelect;
template.SortOrder = Math.Max(1, request.Sort);
template.IsEnabled = isEnabled;
await productRepository.UpdateSpecTemplateAsync(template, cancellationToken);
@@ -120,6 +131,8 @@ public sealed class SaveProductSpecTemplateCommandHandler(
TemplateId = template.Id,
Name = value.Name,
ExtraPrice = value.ExtraPrice,
Stock = 999,
IsEnabled = true,
SortOrder = value.Sort
})
.ToList();

View File

@@ -0,0 +1,55 @@
using TakeoutSaaS.Application.App.Products.Dto;
using TakeoutSaaS.Domain.Products.Entities;
namespace TakeoutSaaS.Application.App.Products;
/// <summary>
/// 加料模板 DTO 映射工厂。
/// </summary>
internal static class ProductAddonTemplateDtoFactory
{
/// <summary>
/// 将模板实体映射为页面 DTO。
/// </summary>
public static ProductAddonTemplateItemDto ToDto(
ProductSpecTemplate template,
IReadOnlyDictionary<long, List<ProductSpecTemplateOption>> optionsLookup,
IReadOnlyDictionary<long, List<long>> productIdsLookup)
{
var options = optionsLookup.TryGetValue(template.Id, out var optionList)
? optionList
: [];
var productIds = productIdsLookup.TryGetValue(template.Id, out var ids)
? ids
: [];
return new ProductAddonTemplateItemDto
{
Id = template.Id,
Name = template.Name,
Description = template.Description,
Required = template.IsRequired,
MinSelect = template.MinSelect,
MaxSelect = template.MaxSelect,
Sort = template.SortOrder,
Status = ProductAddonTemplateMapping.ToStatusText(template.IsEnabled),
ProductCount = productIds.Count,
ProductIds = productIds,
Items = options
.OrderBy(x => x.SortOrder)
.ThenBy(x => x.Id)
.Select(option => new ProductAddonTemplateOptionDto
{
Id = option.Id,
Name = option.Name,
Price = option.ExtraPrice,
Stock = option.Stock,
Sort = option.SortOrder,
Status = ProductAddonTemplateMapping.ToStatusText(option.IsEnabled)
})
.ToList(),
UpdatedAt = template.UpdatedAt ?? template.CreatedAt
};
}
}

View File

@@ -0,0 +1,45 @@
using TakeoutSaaS.Domain.Products.Enums;
namespace TakeoutSaaS.Application.App.Products;
/// <summary>
/// 加料模板映射辅助。
/// </summary>
internal static class ProductAddonTemplateMapping
{
/// <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 AttributeSelectionType ToSelectionType(int maxSelect)
{
return maxSelect <= 1 ? AttributeSelectionType.Single : AttributeSelectionType.Multiple;
}
}

View File

@@ -56,7 +56,12 @@ internal static class ProductSpecTemplateMapping
/// </summary>
public static string ToTemplateTypeText(ProductSpecTemplateType templateType)
{
return templateType == ProductSpecTemplateType.Method ? "method" : "spec";
return templateType switch
{
ProductSpecTemplateType.Method => "method",
ProductSpecTemplateType.Addon => "addon",
_ => "spec"
};
}
/// <summary>

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 GetProductAddonGroupListQuery : IRequest<IReadOnlyList<ProductAddonTemplateItemDto>>
{
/// <summary>
/// 门店 ID。
/// </summary>
public long StoreId { get; init; }
/// <summary>
/// 关键字。
/// </summary>
public string? Keyword { get; init; }
/// <summary>
/// 状态enabled/disabled
/// </summary>
public string? Status { get; init; }
}