fix(product-family): auto-merge SKUs after manual tag edits; fix session cookie path
问题2(SKU 无法自动合并,GBIU017 案例)四处叠加根因修复: - 人工标签旧词「热转印」被封闭词表静默踢出合并矩阵 → CRAFT_TAG_ALIASES 别名归一为「烫画」(矩阵归因与 CUSTOM 标签同路径生效) - updateTags 缺任一定价维度组即整链掉出矩阵且人工接管后永不恢复 → 缺啥补啥(按链接名派生补齐,人工勾选值不动,响应带 filledDimensionTags) - autoGroup 只建新族从不并入已有族(产生 USIU005-2 类碎片)→ 并入已有 autoManaged 同款族优先,无匹配才新建;同款仅人工锁定族则跳过并报告 - 名称回退分组键含物流备注,包邮/不包邮永不同组 → 新增族语义键 familyNameKey(国家+品名+SKU),api/admin 两侧同构,合并默认勾选随之修复 附加: - updateTags 后未归族链接自动并入匹配族(attachToMatchingFamily,响应带 attachedFamilyId) - 整理新增碎片族合并 consolidateFragments:纯碎片族并入带商品族并删除 (保公开 goodId=族ID 稳定),带商品/覆盖价/人工锁定进人工复审报告 - admin:保存标签提示补齐明细,整理完成消息含并入/碎片合并/待人工数 问题1(后台频繁 Unauthorized 掉线): - refresh cookie path '/auth' 与代理前缀(/api、/v2-api)不匹配导致浏览器 永远带不上 refresh cookie → 两 cookie path 统一为 '/' - v2 构建基址带尾斜杠 + 手工拼接产生 /v2-api//auth/refresh 双斜杠 404 → request.ts 规范拼接 测试:api jest 187/187、admin vitest 22/22、双侧 tsc 0 错误; public.service 夹具改为自包含(不依赖共享库既有数据)。
This commit is contained in:
@@ -17,6 +17,18 @@ export function isAutoTagGroupName(name: string): boolean {
|
||||
return /物流|工艺|位置|印花数量/.test(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* 工艺旧词 → 封闭词表别名:人工标签历史上建过「热转印」(= 烫画,热转印工艺),
|
||||
* 归一后才能进价格矩阵 —— 别名只影响矩阵归因,不改标签字典本身。
|
||||
*/
|
||||
export const CRAFT_TAG_ALIASES: Record<string, string> = {
|
||||
热转印: '烫画',
|
||||
};
|
||||
|
||||
export function normalizeCraftTag(name: string): string {
|
||||
return CRAFT_TAG_ALIASES[name] ?? name;
|
||||
}
|
||||
|
||||
export interface DerivedTagGroupSpec {
|
||||
/** 标签组名(查找用 includes 匹配,缺失时自动建组) */
|
||||
group: string;
|
||||
|
||||
@@ -265,6 +265,38 @@ describe('FamilyRecomputeService', () => {
|
||||
expect(matrix.rows[0].logistics).toBe('不包邮');
|
||||
});
|
||||
|
||||
it('价格矩阵:人工标签旧词「热转印」归一为「烫画」进矩阵(不再被封闭词表踢出)', async () => {
|
||||
const a = await mkOriginGood({
|
||||
goodName: '英国(不包邮)测试毯-PM2-单面印花',
|
||||
variants: [
|
||||
{ sdsVariantId: 'v1', sku: 'PM2-S', sizeId: 'size_S', sizeName: 'S', colorId: 'color_w', colorName: '白色', price: 30 },
|
||||
],
|
||||
});
|
||||
// 人工勾了旧词表里的 热转印(历史上人工建的标签),其余维度齐全
|
||||
const tagIds: bigint[] = [];
|
||||
for (const [groupName, tagName] of [['印花数量', '单面印花'], ['印刷工艺', '热转印'], ['物流渠道', '不包邮']] as const) {
|
||||
const group = await prisma.tagGroup.findFirst({ where: { groupName } });
|
||||
const g = group ?? (await prisma.tagGroup.create({ data: { groupName } }));
|
||||
if (!group) createdTagGroupIds.push(g.id);
|
||||
const existing = await prisma.tag.findFirst({ where: { tagName } });
|
||||
const t = existing ?? (await prisma.tag.create({ data: { tagName, tagGroupId: g.id } }));
|
||||
if (!existing) createdTagIds.push(t.id);
|
||||
tagIds.push(t.id);
|
||||
}
|
||||
await prisma.originGoodTag.createMany({
|
||||
data: tagIds.map((tagId) => ({ originGoodId: a.id, tagId, manual: true })),
|
||||
});
|
||||
const family = await mkFamily({ primaryOriginGoodId: a.id, memberIds: [a.id] });
|
||||
|
||||
await service.recomputeFamily(family.id);
|
||||
|
||||
const after = await prisma.productFamily.findUniqueOrThrow({ where: { id: family.id } });
|
||||
const matrix = after.priceMatrix as any;
|
||||
expect(matrix.rows).toHaveLength(1);
|
||||
expect(matrix.rows[0].craft).toBe('烫画'); // 归一后的封闭词表值
|
||||
expect(matrix.crafts).toEqual(['烫画']);
|
||||
});
|
||||
|
||||
it('覆盖:命中改价 manual=true,未命中新增行并扩充选项', async () => {
|
||||
const a = await mkOriginGood({
|
||||
goodName: '美国(包邮)测试O-PO1-单面印花',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { isAutoTagGroupName } from './auto-tag-rules';
|
||||
import { isAutoTagGroupName, normalizeCraftTag } from './auto-tag-rules';
|
||||
|
||||
/**
|
||||
* 产品族重算:并集尺码表/包装规则 + 五维价格矩阵物化。
|
||||
@@ -88,14 +88,16 @@ export function memberMatrixCombos(input: {
|
||||
tagNames: string[];
|
||||
customLabels?: { craft?: string | null; logistics?: string | null };
|
||||
}): MatrixCombo[] {
|
||||
// 旧词别名归一(热转印→烫画):只影响矩阵归因,封闭词表本身不变
|
||||
const tagNames = input.tagNames.map(normalizeCraftTag);
|
||||
const values = (dim: DimKey): string[] =>
|
||||
DIM_VALUES[dim].filter((v) => input.tagNames.includes(v));
|
||||
DIM_VALUES[dim].filter((v) => tagNames.includes(v));
|
||||
|
||||
let printCounts = values('printCount');
|
||||
let crafts = values('craft');
|
||||
let logistics = values('logistics');
|
||||
// CUSTOM 成员:管理员显式标签是唯一来源(craftLabel/logisticsLabel,自由文本)
|
||||
const craftLabel = input.customLabels?.craft ?? '';
|
||||
const craftLabel = normalizeCraftTag(input.customLabels?.craft ?? '');
|
||||
const logisticsLabel = input.customLabels?.logistics ?? '';
|
||||
if (!crafts.length && craftLabel) crafts = [craftLabel];
|
||||
if (!logistics.length && logisticsLabel) logistics = [logisticsLabel];
|
||||
|
||||
@@ -58,12 +58,12 @@ describe('链接级标签:派生 / 人工接管 / 商品镜像', () => {
|
||||
|
||||
async function goodTagNames(goodId: bigint): Promise<string[]> {
|
||||
const rows = await prisma.goodTag.findMany({ where: { goodId }, include: { tag: true } });
|
||||
return rows.map((r) => r.tag.tagName);
|
||||
return rows.map((r) => r.tag.tagName).sort();
|
||||
}
|
||||
|
||||
async function linkTagNames(ogId: bigint): Promise<string[]> {
|
||||
const rows = await prisma.originGoodTag.findMany({ where: { originGoodId: ogId }, include: { tag: true } });
|
||||
return rows.map((r) => r.tag.tagName);
|
||||
return rows.map((r) => r.tag.tagName).sort();
|
||||
}
|
||||
|
||||
it('链接派生标签落在链接上,商品镜像链接标签;旧自动组标签剔除、人工分组保留', async () => {
|
||||
@@ -128,7 +128,7 @@ describe('链接级标签:派生 / 人工接管 / 商品镜像', () => {
|
||||
expect(r1.goodsUpdated).toBe(2);
|
||||
|
||||
// 链接级:og1 → 单面印花/烫画/包邮;og2 → 不打印(光板归并为不打印)/不包邮
|
||||
expect(await linkTagNames(og1.id)).toEqual(['包邮', '烫画', '单面印花']);
|
||||
expect(await linkTagNames(og1.id)).toEqual(['包邮', '单面印花', '烫画']);
|
||||
expect(await linkTagNames(og2.id)).toEqual(['不包邮', '不打印']);
|
||||
|
||||
// 商品级:镜像各自链接(+人工分组保留,旧自动组剔除)
|
||||
@@ -173,28 +173,30 @@ describe('链接级标签:派生 / 人工接管 / 商品镜像', () => {
|
||||
ids.good.push(good.id);
|
||||
|
||||
await organize.deriveFamilyTags(family.id);
|
||||
expect(await linkTagNames(og.id)).toEqual(['包邮', '烫画', '单面印花']);
|
||||
expect(await linkTagNames(og.id)).toEqual(['包邮', '单面印花', '烫画']);
|
||||
|
||||
// 人工接管:解析错了(实际是直喷)→ 改成 直喷
|
||||
const zhpena = await prisma.tag.findFirst({ where: { tagName: '直喷' } });
|
||||
const baoyou = await prisma.tag.findFirst({ where: { tagName: '包邮' } });
|
||||
const result = await originGoods.updateTags(og.id, [Number(zhpena!.id), Number(baoyou!.id)]);
|
||||
expect(result.tagsManual).toBe(true);
|
||||
expect(result.tags.map((t) => t.tagName)).toEqual(['包邮', '直喷']);
|
||||
// 人工勾了 直喷/包邮,缺印花数量维度 → 按名称自动补「单面印花」(缺啥补啥)
|
||||
expect(result.tags.map((t) => t.tagName).sort()).toEqual(['包邮', '单面印花', '直喷']);
|
||||
expect(result.filledDimensionTags).toEqual(['单面印花']);
|
||||
expect(result.tags.every((t) => t.manual)).toBe(true);
|
||||
// 商品镜像跟随人工修正
|
||||
expect(await goodTagNames(good.id)).toEqual(['包邮', '直喷']);
|
||||
// 商品镜像跟随人工修正(含补齐维度)
|
||||
expect(await goodTagNames(good.id)).toEqual(['包邮', '单面印花', '直喷']);
|
||||
|
||||
// 再次族同步:人工行不被覆盖
|
||||
// 再次族同步:人工行(含补齐行)不被覆盖
|
||||
await organize.deriveFamilyTags(family.id);
|
||||
expect(await linkTagNames(og.id)).toEqual(['包邮', '直喷']);
|
||||
expect(await goodTagNames(good.id)).toEqual(['包邮', '直喷']);
|
||||
expect(await linkTagNames(og.id)).toEqual(['包邮', '单面印花', '直喷']);
|
||||
expect(await goodTagNames(good.id)).toEqual(['包邮', '单面印花', '直喷']);
|
||||
|
||||
// 恢复自动 → 回到名称派生结果
|
||||
const reset = await originGoods.resetTags(og.id);
|
||||
expect(reset.tagsManual).toBe(false);
|
||||
expect(reset.tags.map((t) => t.tagName)).toEqual(['包邮', '烫画', '单面印花']);
|
||||
expect(await goodTagNames(good.id)).toEqual(['包邮', '烫画', '单面印花']);
|
||||
expect(reset.tags.map((t) => t.tagName)).toEqual(['包邮', '单面印花', '烫画']);
|
||||
expect(await goodTagNames(good.id)).toEqual(['包邮', '单面印花', '烫画']);
|
||||
});
|
||||
|
||||
it('自定义来源链接不派生标签,仅镜像人工配置', async () => {
|
||||
@@ -259,7 +261,7 @@ describe('链接级标签:派生 / 人工接管 / 商品镜像', () => {
|
||||
await organize.deriveFamilyTags(family.id);
|
||||
await recompute.recomputeFamily(family.id);
|
||||
const tagsBefore = await linkTagNames(og.id);
|
||||
expect(tagsBefore).toEqual(['包邮', '烫画', '单面印花']);
|
||||
expect(tagsBefore).toEqual(['包邮', '单面印花', '烫画']);
|
||||
let fam = await prisma.productFamily.findUniqueOrThrow({ where: { id: family.id } });
|
||||
expect((fam.priceMatrix as any).rows).toHaveLength(1);
|
||||
|
||||
@@ -283,4 +285,68 @@ describe('链接级标签:派生 / 人工接管 / 商品镜像', () => {
|
||||
expect(refreshed).toHaveLength(3);
|
||||
expect(refreshed).toEqual(expect.arrayContaining(['包邮', '双面印花', '直喷']));
|
||||
});
|
||||
|
||||
it('整理碎片合并:纯碎片族并入带商品族(保公开 goodId 稳定)并删除;多族带商品进人工复审', async () => {
|
||||
const cat = `cat-frag-${stamp}`;
|
||||
const mkFrag = async (suffix: string) => {
|
||||
const og = await prisma.originGood.create({
|
||||
data: { sdsGoodId: `frag-${stamp}-${suffix}`, goodName: `美国(包邮)碎片测试-FG1-单面印花-${suffix}`, sdsCategoryId: cat },
|
||||
});
|
||||
ids.originGood.push(og.id);
|
||||
const f = await prisma.productFamily.create({
|
||||
data: { familyName: `碎片族${stamp}-${suffix}`, primaryOriginGoodId: og.id },
|
||||
});
|
||||
ids.family.push(f.id);
|
||||
await prisma.originGood.update({ where: { id: og.id }, data: { familyId: f.id } });
|
||||
return { og, f };
|
||||
};
|
||||
const loose = await mkFrag('a'); // 纯碎片(无商品/无覆盖价)
|
||||
const curated = await mkFrag('b'); // 带商品 → keeper(公开 goodId=族ID)
|
||||
const good = await prisma.good.create({
|
||||
data: {
|
||||
goodName: `碎片商品${stamp}`,
|
||||
originGoodId: curated.og.id,
|
||||
familyId: curated.f.id,
|
||||
countryId: ids.country[0],
|
||||
categoryId: ids.category[0],
|
||||
},
|
||||
});
|
||||
ids.good.push(good.id);
|
||||
// 另一个也带商品的族 → 不自动动,进人工复审
|
||||
const curated2 = await mkFrag('c');
|
||||
const good2 = await prisma.good.create({
|
||||
data: {
|
||||
goodName: `碎片商品2${stamp}`,
|
||||
originGoodId: curated2.og.id,
|
||||
familyId: curated2.f.id,
|
||||
countryId: ids.country[0],
|
||||
categoryId: ids.category[0],
|
||||
},
|
||||
});
|
||||
ids.good.push(good2.id);
|
||||
|
||||
try {
|
||||
const result = await organize.consolidateFragments();
|
||||
// 纯碎片族成员并入带商品族,碎片族被删除
|
||||
const moved = await prisma.originGood.findUniqueOrThrow({ where: { id: loose.og.id } });
|
||||
expect(moved.familyId).toBe(curated.f.id);
|
||||
const gone = await prisma.productFamily.findUnique({ where: { id: loose.f.id } });
|
||||
expect(gone).toBeNull();
|
||||
// 带商品的族保留;两个带商品族互为碎片 → 较新的进人工复审
|
||||
const kept = await prisma.productFamily.findUniqueOrThrow({ where: { id: curated.f.id } });
|
||||
expect(kept).toBeTruthy();
|
||||
const review = (result.manualReview ?? []).find((r: any) => r.fragmentFamilyId === String(curated2.f.id));
|
||||
expect(review).toBeTruthy();
|
||||
expect(review?.keeperFamilyId).toBe(String(curated.f.id));
|
||||
expect(review?.reason).toContain('has-goods');
|
||||
} finally {
|
||||
await prisma.goodTag.deleteMany({ where: { goodId: { in: ids.good } } }).catch(() => undefined);
|
||||
await prisma.good.deleteMany({ where: { id: { in: ids.good } } }).catch(() => undefined);
|
||||
ids.good = [];
|
||||
await prisma.productFamily.deleteMany({ where: { id: { in: ids.family } } }).catch(() => undefined);
|
||||
ids.family = [];
|
||||
await prisma.originGood.deleteMany({ where: { id: { in: ids.originGood } } }).catch(() => undefined);
|
||||
ids.originGood = [];
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
DERIVED_TAG_GROUP_SPECS,
|
||||
deriveLinkTagNames,
|
||||
isAutoTagGroupName,
|
||||
normalizeCraftTag,
|
||||
} from './auto-tag-rules';
|
||||
|
||||
/**
|
||||
@@ -33,6 +34,7 @@ export class OrganizeService {
|
||||
const labels = await this.backfillLabels();
|
||||
const tags = await this.deriveAllTags();
|
||||
const grouped = await this.families.autoGroup(true);
|
||||
const fragments = await this.consolidateFragments();
|
||||
const families = await this.prisma.productFamily.findMany({ select: { id: true } });
|
||||
for (const f of families) {
|
||||
await this.recompute.recomputeFamily(f.id);
|
||||
@@ -43,12 +45,121 @@ export class OrganizeService {
|
||||
linksUpdated: tags.linksUpdated,
|
||||
goodsUpdated: tags.goodsUpdated,
|
||||
familiesCreated: grouped.applied,
|
||||
familiesMerged: grouped.merged,
|
||||
familiesSkipped: grouped.skipped?.length ?? 0,
|
||||
fragmentsConsolidated: fragments.consolidated,
|
||||
fragmentsManualReview: fragments.manualReview.length,
|
||||
familiesRecomputed: families.length,
|
||||
};
|
||||
this.logger.log(`organize done: ${JSON.stringify(result)}`);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 碎片族合并:同一 SDS 分类出现多个族时(历史 autoGroup 只建不并所致),
|
||||
* 把「纯碎片族」(autoManaged、无商品、无覆盖价)的成员并入最老族并删除空族;
|
||||
* 带商品/覆盖价或人工锁定的碎片族保留,写进人工复审报告(由后台手动移动成员)。
|
||||
* keeper 选择:同簇中最早带商品的族,否则最老的 autoManaged 族。
|
||||
*/
|
||||
async consolidateFragments(): Promise<{
|
||||
consolidated: number;
|
||||
manualReview: Array<{ keeperFamilyId: string; fragmentFamilyId: string; reason: string }>;
|
||||
}> {
|
||||
const families = await this.prisma.productFamily.findMany({
|
||||
select: { id: true, autoManaged: true },
|
||||
orderBy: { id: 'asc' },
|
||||
});
|
||||
const members = await this.prisma.originGood.findMany({
|
||||
where: { familyId: { not: null }, delisted: false },
|
||||
select: { familyId: true, sdsCategoryId: true },
|
||||
});
|
||||
const goodCounts = await this.prisma.good.groupBy({
|
||||
by: ['familyId'],
|
||||
_count: { _all: true },
|
||||
where: { familyId: { not: null } },
|
||||
});
|
||||
const goodsByFamily = new Map(goodCounts.map((g) => [g.familyId!.toString(), g._count._all]));
|
||||
const overrideCounts = await this.prisma.familyPriceOverride.groupBy({
|
||||
by: ['familyId'],
|
||||
_count: { _all: true },
|
||||
});
|
||||
const overridesByFamily = new Map(
|
||||
overrideCounts.map((o) => [o.familyId.toString(), o._count._all]),
|
||||
);
|
||||
const autoManagedById = new Map(families.map((f) => [f.id.toString(), f.autoManaged]));
|
||||
const familyCatIds = new Map<string, Set<string>>();
|
||||
for (const m of members) {
|
||||
if (!m.sdsCategoryId) continue;
|
||||
const key = m.familyId!.toString();
|
||||
familyCatIds.set(key, (familyCatIds.get(key) ?? new Set()).add(m.sdsCategoryId));
|
||||
}
|
||||
|
||||
// 按 SDS 分类聚簇:同分类的多个族互为碎片
|
||||
const clusterByFamily = new Map<string, Set<string>>();
|
||||
const catOwners = new Map<string, string[]>();
|
||||
for (const f of families) {
|
||||
const cats = familyCatIds.get(f.id.toString()) ?? new Set();
|
||||
for (const cat of cats) {
|
||||
const owners = catOwners.get(cat) ?? [];
|
||||
owners.push(f.id.toString());
|
||||
catOwners.set(cat, owners);
|
||||
}
|
||||
}
|
||||
for (const owners of catOwners.values()) {
|
||||
if (owners.length < 2) continue;
|
||||
for (const id of owners) {
|
||||
const cluster = clusterByFamily.get(id) ?? new Set();
|
||||
owners.forEach((o) => cluster.add(o));
|
||||
clusterByFamily.set(id, cluster);
|
||||
}
|
||||
}
|
||||
|
||||
let consolidated = 0;
|
||||
const manualReview: Array<{ keeperFamilyId: string; fragmentFamilyId: string; reason: string }> = [];
|
||||
const processedClusters = new Set<string>();
|
||||
for (const [familyIdStr, cluster] of clusterByFamily) {
|
||||
const sorted = [...cluster].sort((a, b) => Number(BigInt(a) - BigInt(b)));
|
||||
const clusterKey = sorted.join(',');
|
||||
if (processedClusters.has(clusterKey)) continue;
|
||||
processedClusters.add(clusterKey);
|
||||
// keeper:最早带商品的族,否则最老的 autoManaged 族
|
||||
const withGoods = sorted.find((id) => (goodsByFamily.get(id) ?? 0) > 0);
|
||||
const keeper =
|
||||
withGoods ??
|
||||
sorted.find((id) => autoManagedById.get(id) === true) ??
|
||||
sorted[0];
|
||||
for (const id of sorted) {
|
||||
if (id === keeper) continue;
|
||||
const reasons: string[] = [];
|
||||
if ((goodsByFamily.get(id) ?? 0) > 0) reasons.push('has-goods');
|
||||
if ((overridesByFamily.get(id) ?? 0) > 0) reasons.push('has-overrides');
|
||||
if (autoManagedById.get(id) !== true) reasons.push('manual-locked');
|
||||
if (reasons.length) {
|
||||
manualReview.push({
|
||||
keeperFamilyId: keeper,
|
||||
fragmentFamilyId: id,
|
||||
reason: reasons.join(','),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
// 纯碎片:成员并入 keeper,删除空族
|
||||
const keeperId = BigInt(keeper);
|
||||
await this.prisma.originGood.updateMany({
|
||||
where: { familyId: BigInt(id) },
|
||||
data: { familyId: keeperId },
|
||||
});
|
||||
await this.prisma.good.updateMany({
|
||||
where: { familyId: BigInt(id) },
|
||||
data: { familyId: keeperId },
|
||||
});
|
||||
await this.prisma.productFamily.delete({ where: { id: BigInt(id) } });
|
||||
consolidated += 1;
|
||||
}
|
||||
await this.recompute.recomputeFamily(BigInt(keeper));
|
||||
}
|
||||
return { consolidated, manualReview };
|
||||
}
|
||||
|
||||
/**
|
||||
* 回填结构化解析列(skuCode/logisticsLabel/craftLabel/warehouseLabel)。
|
||||
* 只补 NULL 列——存量正确数据不覆盖(同步已不再写入这些列)。
|
||||
@@ -267,6 +378,36 @@ export class OrganizeService {
|
||||
return { linksUpdated };
|
||||
}
|
||||
|
||||
/**
|
||||
* 人工标签缺维补齐:三个定价维度组(印花数量/工艺/物流)任一组在当前标签里
|
||||
* 没有封闭词表取值时,按链接名称派生补上;工艺维度经别名归一后判断(热转印≈烫画)。
|
||||
* 人工已勾的维度永不覆盖;名称派生不出该维度时不补(由调用方提示)。
|
||||
*/
|
||||
async fillMissingDimTags(
|
||||
goodName: string | null,
|
||||
currentTagIds: bigint[],
|
||||
): Promise<{ tagIds: bigint[]; names: string[] }> {
|
||||
const tagMap = await this.ensureDerivedTagMap();
|
||||
const current = currentTagIds.length
|
||||
? await this.prisma.tag.findMany({
|
||||
where: { id: { in: currentTagIds } },
|
||||
select: { tagName: true },
|
||||
})
|
||||
: [];
|
||||
const currentNames = new Set(current.map((t) => normalizeCraftTag(t.tagName)));
|
||||
const derivedNames = deriveLinkTagNames(goodName);
|
||||
const missingNames: string[] = [];
|
||||
for (const spec of DERIVED_TAG_GROUP_SPECS) {
|
||||
if (spec.tags.some((name) => currentNames.has(name))) continue;
|
||||
const fromName = spec.tags.find((name) => derivedNames.includes(name));
|
||||
if (fromName) missingNames.push(fromName);
|
||||
}
|
||||
const tagIds = missingNames
|
||||
.map((name) => tagMap.get(name))
|
||||
.filter((id): id is bigint => id !== undefined);
|
||||
return { tagIds, names: missingNames };
|
||||
}
|
||||
|
||||
private async autoGroupIds(): Promise<{ autoGroupIds: Set<string> }> {
|
||||
const groups = await this.prisma.tagGroup.findMany({
|
||||
select: { id: true, groupName: true },
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { parseOriginName, originGroupKey } from './origin-name.parser';
|
||||
import { parseOriginName, originGroupKey, familyNameKey } from './origin-name.parser';
|
||||
|
||||
describe('parseOriginName', () => {
|
||||
it('解析完整四段名(含仓库)', () => {
|
||||
@@ -102,3 +102,41 @@ describe('originGroupKey', () => {
|
||||
expect(originGroupKey('')).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('familyNameKey(族语义分组键)', () => {
|
||||
it('物流差异同键:包邮/不包邮归一族', () => {
|
||||
expect(familyNameKey('英国(不包邮)鼠标垫-GBIU017-单面印花')).toBe(
|
||||
familyNameKey('英国(包邮*运费订单结算时支付)鼠标垫-GBIU017-单面印花'),
|
||||
);
|
||||
expect(familyNameKey('英国(不包邮)鼠标垫-GBIU017-单面印花')).toBe('英国鼠标垫-GBIU017');
|
||||
});
|
||||
|
||||
it('工艺/仓库段不参与:跨工艺归一族', () => {
|
||||
expect(familyNameKey('美国(包邮)T恤-DG001-单面印花-美西一仓')).toBe(
|
||||
familyNameKey('美国(不包邮)T恤-DG001-双面印花'),
|
||||
);
|
||||
});
|
||||
|
||||
it('不同 SKU / 不同国家不同键', () => {
|
||||
expect(familyNameKey('美国(包邮)T恤-DG001-单面印花')).not.toBe(
|
||||
familyNameKey('美国(包邮)T恤-DG002-单面印花'),
|
||||
);
|
||||
expect(familyNameKey('美国(包邮)T恤-DG001-单面印花')).not.toBe(
|
||||
familyNameKey('英国(包邮)T恤-DG001-单面印花'),
|
||||
);
|
||||
});
|
||||
|
||||
it('半角/全角括号混用与无括号都能出键', () => {
|
||||
expect(familyNameKey('美国(不包邮)T恤-DG001-单面印花')).toBe('美国T恤-DG001');
|
||||
expect(familyNameKey('美国T恤-DG001-单面印花')).toBe('美国T恤-DG001');
|
||||
});
|
||||
|
||||
it('无 SKU 段时仅用品名段', () => {
|
||||
expect(familyNameKey('美国(包邮)T恤')).toBe('美国T恤');
|
||||
});
|
||||
|
||||
it('空名返回空串', () => {
|
||||
expect(familyNameKey(null)).toBe('');
|
||||
expect(familyNameKey('')).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -63,3 +63,29 @@ export function originGroupKey(name: string | null | undefined): string {
|
||||
if (!name) return '';
|
||||
return name.split('-').slice(0, 3).join('-');
|
||||
}
|
||||
|
||||
/**
|
||||
* 族语义分组键(自动建族/归族的回退键):第 1 段剥离(物流备注)括号内容,
|
||||
* 保留 国家+品名,拼接 SKU 段,丢弃工艺/仓库段 —— 物流、工艺、印花是价格矩阵
|
||||
* 维度而非分族维度,同款链接(同国家+品名+SKU)必须归一族。
|
||||
*/
|
||||
export function familyNameKey(name: string | null | undefined): string {
|
||||
if (!name) return '';
|
||||
const segs = name.split('-').map((s) => s.trim());
|
||||
const head = segs[0] ?? '';
|
||||
if (!head) return '';
|
||||
// 半角/全角括号混用先归一(与 splitSegment1 一致)
|
||||
const normalized = head.replace(/\(/g, '(').replace(/\)/g, ')');
|
||||
const openAt = normalized.indexOf('(');
|
||||
let stripped = normalized;
|
||||
if (openAt >= 0) {
|
||||
const closeAt = normalized.indexOf(')', openAt);
|
||||
if (closeAt > openAt) {
|
||||
stripped = normalized.slice(0, openAt) + normalized.slice(closeAt + 1);
|
||||
}
|
||||
}
|
||||
stripped = stripped.trim();
|
||||
const sku = segs[1] ?? '';
|
||||
if (!stripped) return sku || '';
|
||||
return sku ? `${stripped}-${sku}` : stripped;
|
||||
}
|
||||
|
||||
@@ -108,19 +108,20 @@ describe('ProductFamiliesService', () => {
|
||||
await service.patch(BigInt(f.id), { autoManaged: true });
|
||||
});
|
||||
|
||||
it('auto-group:无分类时按名称键分组;预览不写库;apply 幂等', async () => {
|
||||
it('auto-group:无分类时按族语义键分组(物流/工艺不分族);预览不写库;apply 幂等', async () => {
|
||||
const g1a = await mkOriginGood(`自动组${stamp}(包邮)卫衣-ZZ${stamp}-单面印花`);
|
||||
const g1b = await mkOriginGood(`自动组${stamp}(包邮)卫衣-ZZ${stamp}-单面印花-某仓`);
|
||||
const g2 = await mkOriginGood(`自动组${stamp}(不包邮)卫衣-ZZ${stamp}-单面印花`);
|
||||
|
||||
const preview = (await service.autoGroup(false)) as any;
|
||||
expect(preview.applied).toBe(0);
|
||||
const hit = preview.groups.find((g: any) => g.groupKey.includes(`ZZ${stamp}`) && g.memberCount === 2);
|
||||
const hit = preview.groups.find((g: any) => g.groupKey.includes(`ZZ${stamp}`) && g.memberCount === 3);
|
||||
expect(hit).toBeTruthy();
|
||||
expect(hit.familyName).toContain('卫衣');
|
||||
expect(hit.action).toBe('create');
|
||||
|
||||
const applied = (await service.autoGroup(true)) as any;
|
||||
expect(applied.applied).toBeGreaterThanOrEqual(2); // 包邮组 + 不包邮组(物流不同不同组)
|
||||
expect(applied.applied).toBeGreaterThanOrEqual(1); // 同款三链接一族(物流是矩阵维度)
|
||||
const families = await prisma.productFamily.findMany({
|
||||
where: { familyName: { contains: `自动组${stamp}` } },
|
||||
});
|
||||
@@ -130,8 +131,9 @@ describe('ProductFamiliesService', () => {
|
||||
select: { familyId: true },
|
||||
});
|
||||
expect(grouped.every((g) => g.familyId !== null)).toBe(true);
|
||||
expect(grouped[0].familyId).toBe(grouped[1].familyId); // 同组同族
|
||||
expect(grouped[2].familyId).not.toBe(grouped[0].familyId); // 物流不同不同族
|
||||
// 物流/工艺差异不拆族:三条链接同一族
|
||||
expect(grouped[0].familyId).toBe(grouped[1].familyId);
|
||||
expect(grouped[2].familyId).toBe(grouped[0].familyId);
|
||||
|
||||
// 幂等:候选已清空
|
||||
const again = (await service.autoGroup(true)) as any;
|
||||
@@ -139,6 +141,59 @@ describe('ProductFamiliesService', () => {
|
||||
expect(hitAgain).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('auto-group:已有同款族时并入而非新建(不再产生 -2 碎片族)', async () => {
|
||||
const cat = `cat-merge-${stamp}`;
|
||||
const a = await mkOriginGood(`美国(包邮)测试M-MG1-单面印花`, { sdsCategoryId: cat });
|
||||
const b = await mkOriginGood(`美国(不包邮)测试M-MG1-双面印花`, { sdsCategoryId: cat });
|
||||
// 先给 a 建族(模拟早先整理只见到 a)
|
||||
const family = await service.create({
|
||||
familyName: `测试M族${stamp}`,
|
||||
originGoodIds: [a.id.toString()],
|
||||
primaryOriginGoodId: a.id.toString(),
|
||||
});
|
||||
createdFamilyIds.push(BigInt(family.id));
|
||||
try {
|
||||
const result = (await service.autoGroup(true)) as any;
|
||||
const after = await prisma.originGood.findUniqueOrThrow({ where: { id: b.id } });
|
||||
expect(after.familyId).toBe(BigInt(family.id)); // b 并入已有族
|
||||
expect(result.merged).toBeGreaterThanOrEqual(1);
|
||||
// 该分类没有产生第二个族
|
||||
const dup = await prisma.productFamily.findMany({
|
||||
where: { familyName: { contains: `测试M族${stamp}` } },
|
||||
});
|
||||
expect(dup).toHaveLength(1);
|
||||
} finally {
|
||||
await prisma.originGoodTag.deleteMany({ where: { originGoodId: { in: [a.id, b.id] } } }).catch(() => undefined);
|
||||
await prisma.originGood.deleteMany({ where: { id: { in: [a.id, b.id] } } }).catch(() => undefined);
|
||||
await prisma.productFamily.deleteMany({ where: { id: BigInt(family.id) } }).catch(() => undefined);
|
||||
}
|
||||
});
|
||||
|
||||
it('auto-group:同款已有族但为人工锁定(autoManaged=false)时不并入也不新建', async () => {
|
||||
const cat = `cat-manual-${stamp}`;
|
||||
const a = await mkOriginGood(`美国(包邮)测试M-MG2-单面印花`, { sdsCategoryId: cat });
|
||||
const b = await mkOriginGood(`美国(不包邮)测试M-MG2-单面印花`, { sdsCategoryId: cat });
|
||||
const family = await service.create({
|
||||
familyName: `测试M锁定族${stamp}`,
|
||||
originGoodIds: [a.id.toString()],
|
||||
primaryOriginGoodId: a.id.toString(),
|
||||
});
|
||||
createdFamilyIds.push(BigInt(family.id));
|
||||
try {
|
||||
await prisma.productFamily.update({ where: { id: BigInt(family.id) }, data: { autoManaged: false } });
|
||||
const result = (await service.autoGroup(true)) as any;
|
||||
const after = await prisma.originGood.findUniqueOrThrow({ where: { id: b.id } });
|
||||
expect(after.familyId).toBeNull(); // 不并入人工族
|
||||
const sameCat = await prisma.productFamily.findMany({ where: { familyName: { contains: `测试M锁定族${stamp}` } } });
|
||||
expect(sameCat).toHaveLength(1); // 也不新建平行族
|
||||
expect((result.skipped ?? []).length).toBeGreaterThanOrEqual(0); // 报告字段存在
|
||||
} finally {
|
||||
await prisma.originGoodTag.deleteMany({ where: { originGoodId: { in: [a.id, b.id] } } }).catch(() => undefined);
|
||||
await prisma.originGood.deleteMany({ where: { id: { in: [a.id, b.id] } } }).catch(() => undefined);
|
||||
await prisma.productFamily.deleteMany({ where: { id: BigInt(family.id) } }).catch(() => undefined);
|
||||
}
|
||||
});
|
||||
|
||||
it('auto-group:同 SDS 分类(产品模型)跨工艺/编码归一族,族名取分类名', async () => {
|
||||
const cat = await prisma.category.create({
|
||||
data: { categoryName: `ZZF${stamp} 180G纯棉T恤(ZZA${stamp})`, sdsCategoryId: `cat-hook-${stamp}` },
|
||||
|
||||
@@ -2,7 +2,7 @@ import { BadRequestException, Injectable, NotFoundException } from '@nestjs/comm
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { FamilyRecomputeService, PriceMatrix } from './family-recompute.service';
|
||||
import { originGroupKey, parseOriginName } from './origin-name.parser';
|
||||
import { originGroupKey, parseOriginName, familyNameKey } from './origin-name.parser';
|
||||
import {
|
||||
CreateCustomMemberDto,
|
||||
CreateProductFamilyDto,
|
||||
@@ -147,7 +147,11 @@ export class ProductFamiliesService {
|
||||
}
|
||||
|
||||
/** 自动成族:SDS 叶子分类即产品模型(如 "DG001 180G纯棉T恤(JSA002)"),
|
||||
* 同分类链接归一族(跨工艺/物流/仓库/编码);无分类回退名称 3 段键;apply=false 仅预览 */
|
||||
* 同分类链接归一族(跨工艺/物流/仓库/编码);无分类回退族语义名称键
|
||||
* (国家+品名+SKU,物流/工艺是矩阵维度不分族)。
|
||||
* 已有同款 autoManaged 族时并入(不再新建 -2 碎片族);同款仅有
|
||||
* 人工锁定族(autoManaged=false)时跳过该组,不并入也不新建。
|
||||
* apply=false 仅预览(action 标注 create/merge/skip)。 */
|
||||
async autoGroup(apply: boolean) {
|
||||
const candidates = await this.prisma.originGood.findMany({
|
||||
where: { familyId: null, delisted: false },
|
||||
@@ -160,64 +164,184 @@ export class ProductFamiliesService {
|
||||
});
|
||||
const catName = new Map(categories.map((c) => [c.sdsCategoryId as string, c.categoryName]));
|
||||
|
||||
// 已有族的成员指纹:分类/名称键 → 候选族 id(用于"并入而非新建")
|
||||
const familyMembers = await this.prisma.originGood.findMany({
|
||||
where: { familyId: { not: null }, delisted: false },
|
||||
select: { familyId: true, sdsCategoryId: true, goodName: true },
|
||||
});
|
||||
const catFamilies = new Map<string, bigint[]>();
|
||||
const nameFamilies = new Map<string, bigint[]>();
|
||||
const push = (map: Map<string, bigint[]>, key: string, id: bigint) => {
|
||||
map.set(key, [...(map.get(key) ?? []), id]);
|
||||
};
|
||||
for (const m of familyMembers) {
|
||||
if (m.sdsCategoryId) push(catFamilies, m.sdsCategoryId, m.familyId!);
|
||||
const nk = familyNameKey(m.goodName);
|
||||
if (nk) push(nameFamilies, nk, m.familyId!);
|
||||
}
|
||||
const autoFamilyIds = new Set(
|
||||
(
|
||||
await this.prisma.productFamily.findMany({
|
||||
where: { autoManaged: true },
|
||||
select: { id: true },
|
||||
})
|
||||
).map((f) => f.id),
|
||||
);
|
||||
/** 匹配可并入的已有族:分类优先,回退名称键;仅 autoManaged,多候选取最老 */
|
||||
const matchAutoFamily = (cat: string | null, nameKey: string): bigint | null => {
|
||||
const pool = [
|
||||
...new Set([...(cat ? (catFamilies.get(cat) ?? []) : []), ...(nameKey ? (nameFamilies.get(nameKey) ?? []) : [])]),
|
||||
]
|
||||
.filter((id) => autoFamilyIds.has(id))
|
||||
.sort((a, b) => Number(a - b));
|
||||
return pool[0] ?? null;
|
||||
};
|
||||
/** 该组是否已有同款族(含人工锁定族,用于 skip 判断) */
|
||||
const hasAnyFamily = (cat: string | null, nameKey: string): boolean =>
|
||||
Boolean(cat && catFamilies.has(cat)) || Boolean(nameKey && nameFamilies.has(nameKey));
|
||||
|
||||
const groups = new Map<string, typeof candidates>();
|
||||
const groupKeys = new Map<string, { cat: string | null; nameKey: string }>();
|
||||
for (const og of candidates) {
|
||||
const nameKey = originGroupKey(og.goodName);
|
||||
const nameKey = familyNameKey(og.goodName);
|
||||
const key = og.sdsCategoryId ? `cat:${og.sdsCategoryId}` : nameKey ? `name:${nameKey}` : '';
|
||||
if (!key) continue;
|
||||
groupKeys.set(key, { cat: og.sdsCategoryId ?? null, nameKey });
|
||||
const arr = groups.get(key);
|
||||
if (arr) arr.push(og);
|
||||
else groups.set(key, [og]);
|
||||
}
|
||||
|
||||
const preview = [...groups.values()].map((members) => {
|
||||
const resolveGroup = (key: string) => {
|
||||
const members = groups.get(key)!;
|
||||
const { cat, nameKey } = groupKeys.get(key)!;
|
||||
const parsed = parseOriginName(members[0].goodName);
|
||||
const categoryName = members[0].sdsCategoryId
|
||||
? (catName.get(members[0].sdsCategoryId) ?? null)
|
||||
: null;
|
||||
const categoryName = cat ? (catName.get(cat) ?? null) : null;
|
||||
return {
|
||||
groupKey: members[0].sdsCategoryId ? `cat:${members[0].sdsCategoryId}` : `name:${originGroupKey(members[0].goodName)}`,
|
||||
familyName:
|
||||
categoryName ?? parsed.productName ?? originGroupKey(members[0].goodName),
|
||||
familyCode: codeFromCategoryName(categoryName) ?? parsed.skuCode ?? null,
|
||||
memberCount: members.length,
|
||||
sampleNames: members.slice(0, 3).map((m) => m.goodName ?? ''),
|
||||
members,
|
||||
cat,
|
||||
nameKey,
|
||||
parsed,
|
||||
categoryName,
|
||||
familyName: categoryName ?? parsed.productName ?? nameKey,
|
||||
};
|
||||
};
|
||||
|
||||
const preview = [...groups.keys()].map((key) => {
|
||||
const g = resolveGroup(key);
|
||||
const target = g.cat || g.nameKey ? matchAutoFamily(g.cat, g.nameKey) : null;
|
||||
const skip = !target && hasAnyFamily(g.cat, g.nameKey);
|
||||
return {
|
||||
groupKey: key,
|
||||
familyName: g.familyName,
|
||||
familyCode: codeFromCategoryName(g.categoryName) ?? g.parsed.skuCode ?? null,
|
||||
memberCount: g.members.length,
|
||||
sampleNames: g.members.slice(0, 3).map((m) => m.goodName ?? ''),
|
||||
action: target ? ('merge' as const) : skip ? ('skip' as const) : ('create' as const),
|
||||
targetFamilyId: target ? target.toString() : null,
|
||||
};
|
||||
});
|
||||
|
||||
if (!apply) return { applied: 0, groups: preview };
|
||||
if (!apply) return { applied: 0, merged: 0, skipped: [] as string[], groups: preview };
|
||||
|
||||
let applied = 0;
|
||||
for (const members of groups.values()) {
|
||||
const parsed = parseOriginName(members[0].goodName);
|
||||
const categoryName = members[0].sdsCategoryId
|
||||
? (catName.get(members[0].sdsCategoryId) ?? null)
|
||||
: null;
|
||||
let merged = 0;
|
||||
const skipped: string[] = [];
|
||||
for (const key of groups.keys()) {
|
||||
const g = resolveGroup(key);
|
||||
const memberIds = g.members.map((m) => m.id);
|
||||
const target = g.cat || g.nameKey ? matchAutoFamily(g.cat, g.nameKey) : null;
|
||||
if (target) {
|
||||
// 并入已有 autoManaged 族:不再新建 -2 碎片族
|
||||
await this.attachMembers(target, memberIds, { strict: false });
|
||||
await this.prisma.good.updateMany({
|
||||
where: { originGoodId: { in: memberIds } },
|
||||
data: { familyId: target },
|
||||
});
|
||||
await this.recompute.recomputeFamily(target);
|
||||
merged += memberIds.length;
|
||||
continue;
|
||||
}
|
||||
if (hasAnyFamily(g.cat, g.nameKey)) {
|
||||
// 同款仅有人工锁定族:不并入也不新建,留在候选里等人工处理
|
||||
skipped.push(key);
|
||||
continue;
|
||||
}
|
||||
const fallbackCode =
|
||||
members[0].source === 'CUSTOM' ? `CUSTOM-${members[0].id}` : null;
|
||||
g.members[0].source === 'CUSTOM' ? `CUSTOM-${g.members[0].id}` : null;
|
||||
const family = await this.prisma.productFamily.create({
|
||||
data: {
|
||||
familyName: categoryName ?? parsed.productName ?? originGroupKey(members[0].goodName),
|
||||
familyName: g.familyName,
|
||||
familyCode:
|
||||
codeFromCategoryName(categoryName) ?? parsed.skuCode ?? fallbackCode
|
||||
codeFromCategoryName(g.categoryName) ?? g.parsed.skuCode ?? fallbackCode
|
||||
? await this.ensureUniqueCode(
|
||||
(codeFromCategoryName(categoryName) ?? parsed.skuCode ?? fallbackCode)!,
|
||||
(codeFromCategoryName(g.categoryName) ?? g.parsed.skuCode ?? fallbackCode)!,
|
||||
)
|
||||
: null,
|
||||
familyImage: members[0].goodImage ?? null,
|
||||
primaryOriginGoodId: members[0].id,
|
||||
familyImage: g.members[0].goodImage ?? null,
|
||||
primaryOriginGoodId: g.members[0].id,
|
||||
},
|
||||
});
|
||||
// 宽容挂载:并行环境下成员可能在候选查询后消失(如测试清理),跳过即可
|
||||
await this.attachMembers(
|
||||
family.id,
|
||||
members.map((m) => m.id),
|
||||
memberIds,
|
||||
{ strict: false },
|
||||
);
|
||||
await this.prisma.good.updateMany({
|
||||
where: { originGoodId: { in: memberIds } },
|
||||
data: { familyId: family.id },
|
||||
});
|
||||
await this.recompute.recomputeFamily(family.id);
|
||||
applied += 1;
|
||||
}
|
||||
return { applied, groups: preview };
|
||||
return { applied, merged, skipped, groups: preview };
|
||||
}
|
||||
|
||||
/**
|
||||
* 单链接自动归族:同 SDS 分类优先,回退族语义名称键(国家+品名+SKU,物流/工艺
|
||||
* 是矩阵维度不分族);只并入 autoManaged 族(人工锁定族不动),多候选取最老
|
||||
* (id 最小)。返回并入的族 id,无匹配返回 null。
|
||||
*/
|
||||
async attachToMatchingFamily(originGoodId: bigint): Promise<bigint | null> {
|
||||
const og = await this.prisma.originGood.findUnique({
|
||||
where: { id: originGoodId },
|
||||
select: { id: true, sdsCategoryId: true, goodName: true, delisted: true, familyId: true },
|
||||
});
|
||||
if (!og || og.familyId || og.delisted) return null;
|
||||
const members = await this.prisma.originGood.findMany({
|
||||
where: { familyId: { not: null }, delisted: false },
|
||||
select: { familyId: true, sdsCategoryId: true, goodName: true },
|
||||
});
|
||||
let candidates: bigint[] = [];
|
||||
if (og.sdsCategoryId) {
|
||||
candidates = members
|
||||
.filter((m) => m.sdsCategoryId === og.sdsCategoryId)
|
||||
.map((m) => m.familyId!);
|
||||
}
|
||||
if (!candidates.length) {
|
||||
const key = familyNameKey(og.goodName);
|
||||
if (key) {
|
||||
candidates = members
|
||||
.filter((m) => familyNameKey(m.goodName) === key)
|
||||
.map((m) => m.familyId!);
|
||||
}
|
||||
}
|
||||
if (!candidates.length) return null;
|
||||
const families = await this.prisma.productFamily.findMany({
|
||||
where: { id: { in: [...new Set(candidates)] }, autoManaged: true },
|
||||
orderBy: { id: 'asc' },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!families.length) return null;
|
||||
const target = families[0];
|
||||
await this.attachMembers(target.id, [og.id]);
|
||||
await this.prisma.good.updateMany({
|
||||
where: { originGoodId: og.id },
|
||||
data: { familyId: target.id },
|
||||
});
|
||||
await this.recompute.recomputeFamily(target.id);
|
||||
return target.id;
|
||||
}
|
||||
|
||||
async updateMembers(id: bigint, dto: UpdateFamilyMembersDto) {
|
||||
|
||||
Reference in New Issue
Block a user