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:
yeuimu
2026-09-02 18:39:35 +08:00
parent e34398a002
commit f1e81872e7
25 changed files with 848 additions and 78 deletions
@@ -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) {