fix(product): 修复属性更新时字典名称处理逻辑

当更新产品属性时,调整字典名称的处理逻辑:
1. 当提供 id 时不强制要求 dictName
2. 未提供 id 时需要 dictName 和 title/name
3. 使用传入的 dictName 或查询到的 item.dict.name 作为替换键
This commit is contained in:
tikkhun 2025-11-28 18:11:21 +08:00
parent 64b8468df8
commit a7d5db33f3
1 changed files with 11 additions and 4 deletions

View File

@ -210,12 +210,14 @@ export class ProductService {
// 解析属性输入(中文注释:按 id 或 dictName 创建/关联字典项)
const resolvedAttributes: DictItem[] = [];
for (const attr of attributes) {
if (!attr?.dictName) throw new Error('属性项缺少字典名称');
let item: DictItem | null = null;
if (attr.id) {
// 中文注释:如果传入了 id直接查找字典项并使用不强制要求 dictName
item = await this.dictItemModel.findOne({ where: { id: attr.id }, relations: ['dict'] });
if (!item) throw new Error(`字典项 ID ${attr.id} 不存在`);
} else {
// 中文注释:当未提供 id 时,需要 dictName 与 title/name 信息创建或获取字典项
if (!attr?.dictName) throw new Error('属性项缺少字典名称');
const titleOrName = attr.title || attr.name;
if (!titleOrName) throw new Error('新建字典项需要提供 title 或 name');
item = await this.getOrCreateAttribute(attr.dictName, titleOrName, attr.name);
@ -315,17 +317,22 @@ export class ProductService {
};
for (const attr of updateProductDTO.attributes) {
if (!attr?.dictName) throw new Error('属性项缺少字典名称');
let item: DictItem | null = null;
if (attr.id) {
// 中文注释:当提供 id 时直接查询字典项,不强制要求 dictName
item = await this.dictItemModel.findOne({ where: { id: attr.id }, relations: ['dict'] });
if (!item) throw new Error(`字典项 ID ${attr.id} 不存在`);
} else {
// 中文注释:未提供 id 则需要 dictName 与 title/name 信息
if (!attr?.dictName) throw new Error('属性项缺少字典名称');
const titleOrName = attr.title || attr.name;
if (!titleOrName) throw new Error('新建字典项需要提供 title 或 name');
item = await this.getOrCreateAttribute(attr.dictName, titleOrName, attr.name);
}
replaceAttr(attr.dictName, item);
// 中文注释:以传入的 dictName 或查询到的 item.dict.name 作为替换键
const dictKey = attr.dictName || item?.dict?.name;
if (!dictKey) throw new Error('无法确定字典名称用于替换属性');
replaceAttr(dictKey, item);
}
product.attributes = nextAttributes;