feat(product-family): auto-derive logistics/craft tags from family members

This commit is contained in:
yeuimu
2026-08-28 14:57:25 +08:00
parent a13931c84c
commit eedfbb344e
6 changed files with 340 additions and 13 deletions
@@ -289,5 +289,94 @@ export class FamilyRecomputeService {
data: { stale: true },
});
}
// 派生标签同步(无论是否锁定:标签是派生数据而非人工策展)
await this.syncFamilyTags(family.id, members);
}
/**
* 族 → 商品标签同步:物流/工艺/印刷位置类标签组(组名含「物流」「工艺」或「位置」,
* 与官网筛选维度一致)下的标签由族成员的 logisticsLabel/craftLabel 派生;
* 标签名与链接标签存在词尾差异(单面印花 ↔ 单面印),采用前缀匹配并取最长命中。
* 其他分组保持人工管理。仅更新发生变化的商品,幂等。
*/
async syncFamilyTags(
familyId: bigint,
preloadedMembers?: Member[],
): Promise<{ goodsUpdated: number }> {
const members =
preloadedMembers ??
(await this.prisma.originGood.findMany({
where: { familyId, delisted: false },
select: { logisticsLabel: true, craftLabel: true },
}));
const labels = members
.flatMap((m) => [m.logisticsLabel, m.craftLabel])
.filter((l): l is string => !!l);
const autoGroups = await this.prisma.tagGroup.findMany({
where: {
OR: [
{ groupName: { contains: '物流' } },
{ groupName: { contains: '工艺' } },
{ groupName: { contains: '位置' } },
],
},
select: { id: true },
});
const autoGroupIds = new Set(autoGroups.map((g) => g.id.toString()));
if (!autoGroupIds.size || !labels.length) {
return { goodsUpdated: 0 };
}
const candidates = await this.prisma.tag.findMany({
where: { tagGroupId: { in: autoGroups.map((g) => g.id) } },
select: { id: true, tagName: true },
});
// 每个链接标签取「最长前缀命中」的标签(避免短名误吃长名场景)
const derivedIds = new Set<bigint>();
for (const label of new Set(labels)) {
let best: { id: bigint; name: string } | null = null;
for (const tag of candidates) {
if (label === tag.tagName || label.startsWith(tag.tagName)) {
if (!best || tag.tagName.length > best.name.length) {
best = { id: tag.id, name: tag.tagName };
}
}
}
if (best) derivedIds.add(best.id);
}
const goods = await this.prisma.good.findMany({
where: { familyId },
include: { goodTags: { include: { tag: { select: { id: true, tagGroupId: true } } } } },
});
let goodsUpdated = 0;
for (const good of goods) {
// 保留:非自动分组的既有标签(人工管理)∪ 派生标签
const keep = good.goodTags
.filter((gt) => !autoGroupIds.has(gt.tag.tagGroupId?.toString() ?? ''))
.map((gt) => gt.tagId);
const target = [...new Set([...keep, ...derivedIds])].sort((a, b) =>
Number(a - b),
);
const current = good.goodTags.map((gt) => gt.tagId).sort((a, b) => Number(a - b));
const same =
target.length === current.length && target.every((id, i) => id === current[i]);
if (same) continue;
await this.prisma.$transaction([
this.prisma.goodTag.deleteMany({ where: { goodId: good.id } }),
...(!target.length
? []
: [
this.prisma.goodTag.createMany({
data: target.map((tagId) => ({ goodId: good.id, tagId })),
}),
]),
]);
goodsUpdated += 1;
}
return { goodsUpdated };
}
}