feat(后管): 京东数据库商品目录恢复一级/二级/末级层级树(2026-11-26 晚客户口径「怎么都没有分类一级二级分类」「管理员要分类时候那么多怎么看」)

- 新纯函数 jd-category-hierarchy.ts:京麦授权类目真树(GET /api/jd-shop-category-tree,
  按平台 node_id 并集)× /categories 末级名计数,名称精确等值挂接;计数按去重名字集合
  求和(同名跨支不重复计)、零计数分支剪枝、树外历史名进「平台树外」兜底组;
  树空=退化末级平铺(上一窗行为逐字相同),没有内置快照——第二份树不再存在
- 新 jd-shop-category-api.ts:只剩服务端真树一条路,失败/空静默回空数组
- 侧栏层级渲染:展开/收起、点父级=整棵子树末级名集合过滤(11-18 口径恢复)、
  挂载即展开选中行祖先链;同名跨支按路径核选中态
- filter/api:categoryPath(只喂回显展开)+categoryNames(选中那一刻展开好的过滤集合)
  复活,下发走后端既有 category IN 多值;清选时两者一起清,不留幽灵谓词
- 判据:jd-category-hierarchy.test.ts(挂接/去重/剪枝/兜底/平铺退化)+
  sidebar/database-page mount(真树层级、父级点选下发集合、树空平铺、回显展开)
This commit is contained in:
2026-11-26 17:59:43 +08:00
parent 9092849ae9
commit 2aa05398f9
10 changed files with 971 additions and 126 deletions
@@ -1,22 +1,33 @@
<script setup lang="ts"> <script setup lang="ts">
/** 京东数据库页左侧栏: /** 京东数据库页左侧栏:
* 双 Tab=商品目录(<b>京东平台类目平铺</b>:后端 `/categories` 的 DISTINCT `category_path` * 双 Tab=商品目录(<b>京东平台类目层级树</b>:一级/二级/末级可展开,末级名+商品数)/
* 末级类目名+商品数)/店铺分类(当前数据权限分组的分类平铺+计数+新建分类+分类管理入口)。 * 店铺分类(当前数据权限分组的分类平铺+计数+新建分类+分类管理入口)。
* *
* 纯展示组件:取数与失败兜底全在页面(props 流入、emit 流出),本组件不发请求、 * 纯展示组件:取数与失败兜底全在页面(props 流入、emit 流出),本组件不发请求、
* 不 import api——mount 测试免 mock;内部状态只有双 Tab 切换与新建输入框。 * 不 import api——mount 测试免 mock;内部状态只有双 Tab 切换、目录展开态与新建输入框。
* *
* 2026-11-26 客户口径(「京东分类是百分百有的,京东内分类就不需要」):商品目录改用 * 2026-11-26 客户口径(「怎么都没有分类一级二级分类」「管理员要分类时候那么多怎么看」):
* **京东平台类目**,不再依赖按店铺上报的授权类目树 `biz_jd_shop_category_tree`,也不再 * 商品目录=**京麦授权类目真树**(页面取 `GET /api/jd-shop-category-tree`,客户端按店铺
* 回落内置快照 `JD_CATEGORY_TREE`(那是 2026-11-16 一家店的历史取证,换店必整树零命中, * 上报、服务端并集)× **末级名商品数**(`/api/admin/jd-products/categories`)。层级、计数、
* 此前靠「零命中剪枝+树外兜底组」打补丁)。平铺一层后点行=该末级类目名等值过滤, * 零计数剪枝、树外兜底全在纯函数 `jd-category-hierarchy.ts`;本组件只画。
* 与后端 `p.category_path IN (...)` 单元素集合逐字同形。 */ * 没有内置快照树了(那是一家店的历史取证,换店必整树零命中);树空时纯函数退化为平铺,
import { computed, ref } from 'vue' * 与上一窗行为逐字相同。 */
import { computed, onMounted, ref, watch } from 'vue'
import type { JdProductCategoryOption, JdProductGroup } from './jd-product-api.ts' import type { JdProductCategoryOption, JdProductGroup } from './jd-product-api.ts'
import {
buildJdCatalogTree,
findJdCatalogPath,
flattenJdCatalogRows,
jdCatalogPathIndex,
type JdCatalogRow,
type JdCategoryNode,
} from './jd-category-hierarchy.ts'
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
/** /categories 计数行(京麦末级类目+商品数;页面持有,失败静默回空数组)。 */ /** /categories 计数行(京麦末级类目+商品数;页面持有,失败静默回空数组)。 */
categoryOptions: JdProductCategoryOption[] categoryOptions: JdProductCategoryOption[]
/** 京麦授权类目树(服务端按店铺上报的并集森林;空数组=还没上报过,退化为末级平铺)。 */
categoryTree?: JdCategoryNode[]
/** 当前数据权限分组的分类(V203 归属口径,带 productCount 徽标;v1.7 每行可带 /** 当前数据权限分组的分类(V203 归属口径,带 productCount 徽标;v1.7 每行可带
* shops 店铺名单——铺开渲染店铺行点选过滤,空分类也常驻「添加店铺」入口)。 */ * shops 店铺名单——铺开渲染店铺行点选过滤,空分类也常驻「添加店铺」入口)。 */
categories: JdProductGroup[] categories: JdProductGroup[]
@@ -24,15 +35,16 @@ const props = withDefaults(defineProps<{
* hover 改名/删除与「添加店铺」入口;「分类管理」入口对所有人渲染(同组普通号只读可看, * hover 改名/删除与「添加店铺」入口;「分类管理」入口对所有人渲染(同组普通号只读可看,
* V203,写控件由对话框分档)。 */ * V203,写控件由对话框分档)。 */
editable: boolean editable: boolean
/** 当前类目选中(name+完整名称路径;树外历史名 path 为空数组;null=全部商品)。 */ /** 当前类目选中(name=回显名;path=一级到本行的名称链,用于挂载即展开;names=实际
selectedCategory?: { name: string; path: string[] } | null * 下发的末级名集合,父级选中时是整棵子树;null=全部商品)。 */
selectedCategory?: { name: string; path: string[]; names?: string[] } | null
/** 当前分类选中 id(null=全部分类)。 */ /** 当前分类选中 id(null=全部分类)。 */
selectedGroupId?: number | null selectedGroupId?: number | null
/** 当前店铺筛选(v1.7 店铺名单点选;空/缺省=未按店铺过滤)。 */ /** 当前店铺筛选(v1.7 店铺名单点选;空/缺省=未按店铺过滤)。 */
selectedShopName?: string | null selectedShopName?: string | null
/** 类目计数行是否已取过(页面 loading 态投影;缺省/true=已就绪)。首帧未就绪时侧栏 /** 类目计数行是否已取过(页面 loading 态投影;缺省/true=已就绪)。首帧未就绪时侧栏
* 不画树:否则会先把回落快照整棵树(别店类目、徽标全 0、「全部商品 0」)画出来,计数 * 不画树:否则会先画一棵「全部商品 0」的空树,计数到达后再跳成有数据——用户肉眼
* 到达后再收成「本店无匹配」一行——用户肉眼看到一次「过一会变了」的闪变。 */ * 看到一次「过一会变了」的闪变。 */
categoriesReady?: boolean categoriesReady?: boolean
}>(), { }>(), {
// Vue 的 Boolean prop 缺省会被强转成 false(不看 TS 可选性):不显式给默认值, // Vue 的 Boolean prop 缺省会被强转成 false(不看 TS 可选性):不显式给默认值,
@@ -41,9 +53,10 @@ const props = withDefaults(defineProps<{
}) })
const emit = defineEmits<{ const emit = defineEmits<{
/** 选类目:京东平台类目末级名,path 恒为空数组(页面按单名集合 IN 下发); /** 选类目:末级行 = 单名;一级/二级行 = 整棵子树的末级名集合(`names`,页面直接
* 序列化成后端 `category` 多值 IN)。`path` 只用于页面回显展开,不参与过滤。
* null=「全部商品」清选重查。 */ * null=「全部商品」清选重查。 */
(event: 'select-category', value: { name: string; path: string[] } | null): void (event: 'select-category', value: { name: string; path: string[]; names: string[] } | null): void
/** 选分类:分类 id;再点已选中的=清选(emit null,回全部分类)。 */ /** 选分类:分类 id;再点已选中的=清选(emit null,回全部分类)。 */
(event: 'select-group', id: number | null): void (event: 'select-group', id: number | null): void
/** 选店铺(v1.7 名单点选):分类+店铺名成对下发(点店铺=该分类归属 ∩ 该店铺, /** 选店铺(v1.7 名单点选):分类+店铺名成对下发(点店铺=该分类归属 ∩ 该店铺,
@@ -69,30 +82,82 @@ const emit = defineEmits<{
/** 左 Tab 内置展示态:出厂停在「商品目录」(首屏主筛选面)。 */ /** 左 Tab 内置展示态:出厂停在「商品目录」(首屏主筛选面)。 */
const activeTab = ref<'catalog' | 'custom'>('catalog') const activeTab = ref<'catalog' | 'custom'>('catalog')
// ---------------- 商品目录(京东平台类目平铺) ---------------- // ---------------- 商品目录(京东平台类目层级树) ----------------
/** 类目计数就绪(页面首帧未回时只留加载行,总数显示「—」)。 */ /** 类目计数就绪(页面首帧未回时只留加载行,总数显示「—」)。 */
const catalogReady = computed(() => props.categoriesReady !== false) const catalogReady = computed(() => props.categoriesReady !== false)
/** 「全部商品」徽标=全部计数行求和(有类目名的商品总数;无类目名的行不在任何类目筛选的 /** 层级 + 计数 + 树外兜底:口径全部在纯函数里(`jd-category-hierarchy.ts`,node --test 直测),
* 命中集里,不计进任何徽标)。 */ * 本组件只负责画与展开态。树没上报过时纯函数自己退化为平铺,行为与上一窗逐字相同。 */
const totalCount = computed(() => const catalog = computed(() =>
(props.categoryOptions ?? []).reduce((sum, row) => sum + (row.productCount || 0), 0)) buildJdCatalogTree(props.categoryTree ?? [], props.categoryOptions ?? []))
/** 商品目录行:后端 `/categories` 已按类目名升序 DISTINCT,这里只归一脏数据 /** 「全部商品」徽标=全部计数行按名字去重求和(同名跨支不重复计,见纯函数口径 1)。 */
* (空名/负计数),一列平铺——没有树、没有展开折叠、没有「树外兜底」分组。 */ const totalCount = computed(() => catalog.value.totalCount)
const catalogRows = computed(() =>
(props.categoryOptions ?? [])
.filter((row) => !!row.name && !!row.name.trim())
.map((row) => ({ name: row.name, productCount: row.productCount || 0 })))
/** 点一行=按该末级类目名等值过滤(path 空数组,页面按单名集合下发,不静默丢筛选)。 */ /** 展开态(行键集合):默认全收起——一级之下先让管理员看清有哪些大类,别一进来四百行。 */
function pickCatalogRow(name: string): void { const expandedKeys = ref<string[]>([])
emit('select-category', { name, path: [] })
/** 可见行(折叠节点的子孙不进列表)。 */
const visibleCatalogRows = computed(() =>
flattenJdCatalogRows(catalog.value.roots, expandedKeys.value))
/** 行键 → 祖先名链(点行时算 path、回显时展开祖先链,两处同一份)。 */
const catalogPathIndex = computed(() => jdCatalogPathIndex(catalog.value.roots))
function toggleCatalogRow(key: string): void {
const set = new Set(expandedKeys.value)
if (set.has(key)) set.delete(key)
else set.add(key)
expandedKeys.value = [...set]
} }
/** 选中回显:当前筛选的类目名与行名逐字相同即高亮。 */ /** 展开到选中行(挂载、切换选中、树/计数异步到达后都要重算一次)。
const isSelectedCatalogRow = (name: string): boolean => * 只在「祖先链还没展开」时补,不折叠用户手动展开的其它分支。 */
function revealSelectedCatalogRow(): void {
const name = (props.selectedCategory?.name ?? '').trim()
if (!name) return
const chain = findJdCatalogPath(catalog.value.roots, name)
if (!chain.length) return
const set = new Set(expandedKeys.value)
let changed = false
// 链上除自身都要展开(自身是末级,展开无意义;父级选中也展开它自己好看清子树)。
for (const row of chain.slice(0, -1)) {
if (row.children.length && !set.has(row.key)) {
set.add(row.key)
changed = true
}
}
if (changed) expandedKeys.value = [...set]
}
onMounted(revealSelectedCatalogRow)
watch(() => [props.selectedCategory?.name, catalog.value.roots] as const, revealSelectedCatalogRow)
/** 点一行:末级=单名过滤,父级=整棵子树的末级名集合(2026-11-18 口径「一级/二级也能选」)。
* `path` 是从一级到本行的名称链,页面只拿它展开回显,过滤值看 `names`。 */
function pickCatalogRow(row: JdCatalogRow): void {
const path = catalogPathIndex.value.get(row.key) ?? [row.name]
emit('select-category', { name: row.name, path, names: row.names })
}
/** 树外兜底行(历史类目/别店未上报):只有名字,按单名过滤。 */
function pickOrphanRow(name: string): void {
emit('select-category', { name, path: [], names: [name] })
}
/** 选中回显:按名称命中;有路径信息时再核一遍祖先链,避免同名跨支把两支一起点亮。 */
const isSelectedCatalogRow = (row: JdCatalogRow): boolean => {
const selected = props.selectedCategory
if (!selected || selected.name !== row.name) return false
const wanted = (selected.path ?? []).filter((seg) => !!seg)
if (!wanted.length) return true
const actual = catalogPathIndex.value.get(row.key) ?? [row.name]
return wanted.join('/') === actual.join('/')
}
/** 树外兜底行是否选中(同名单行,无路径)。 */
const isSelectedOrphanRow = (name: string): boolean =>
!!props.selectedCategory && props.selectedCategory.name === name !!props.selectedCategory && props.selectedCategory.name === name
// ---------------- 店铺分类 Tab(当前分组分类平铺+店铺名单 v1.7) ---------------- // ---------------- 店铺分类 Tab(当前分组分类平铺+店铺名单 v1.7) ----------------
@@ -190,8 +255,9 @@ function cancelShopRename(): void {
>店铺分类</button> >店铺分类</button>
</div> </div>
<!-- 商品目录(2026-11-26):全部商品 + 京东平台类目平铺(category_path 末级名+计数)。 <!-- 商品目录(2026-11-26 客户口径「怎么都没有分类一级二级分类」):全部商品 + 京麦
不再依赖授权类目树/店铺内分类——客户口径「京东分类是百分百有的,京东内分类不需要」。 --> 授权类目**层级树**(一级/二级/末级可展开,末级名+该节点商品数)。树空=退化为
末级平铺(上一窗行为)。 -->
<div v-show="activeTab === 'catalog'" class="jd-sidebar-body jd-side-catalog"> <div v-show="activeTab === 'catalog'" class="jd-sidebar-body jd-side-catalog">
<button <button
type="button" type="button"
@@ -205,20 +271,52 @@ function cancelShopRename(): void {
<!-- 类目计数未就绪(页面首帧):只留一行加载提示,不画列表(先画空列表再跳成有数据会闪变)。 --> <!-- 类目计数未就绪(页面首帧):只留一行加载提示,不画列表(先画空列表再跳成有数据会闪变)。 -->
<p v-if="!catalogReady" class="jd-side-loading">类目加载中…</p> <p v-if="!catalogReady" class="jd-side-loading">类目加载中…</p>
<div v-else class="jd-side-tree"> <div v-else class="jd-side-tree">
<button <!-- 层级行(div role=button:行内要嵌展开箭头——button 嵌 button 非法 HTML)。
v-for="row in catalogRows" 有子级=一级/二级:点名字按整棵子树过滤,点箭头只展开/收起;末级=单名过滤。 -->
:key="row.name" <div
type="button" v-for="row in visibleCatalogRows"
class="jd-side-row depth-0" :key="row.key"
:class="{ selected: isSelectedCatalogRow(row.name) }" class="jd-side-row"
:title="row.name" :class="[`depth-${row.depth}`, { selected: isSelectedCatalogRow(row), branch: !row.isLeaf }]"
@click="pickCatalogRow(row.name)" role="button"
tabindex="0"
:title="row.isLeaf ? row.name : `${row.name}(含下级类目 ${row.names.length} 个)`"
@click="pickCatalogRow(row)"
@keydown.enter="pickCatalogRow(row)"
> >
<span class="jd-side-leaf-dot" /> <button
v-if="!row.isLeaf"
type="button"
class="jd-side-arrow"
:aria-label="`${expandedKeys.includes(row.key) ? '收起' : '展开'} ${row.name}`"
:aria-expanded="expandedKeys.includes(row.key)"
@click.stop="toggleCatalogRow(row.key)"
>{{ expandedKeys.includes(row.key) ? '▾' : '▸' }}</button>
<span v-else class="jd-side-leaf-dot" />
<span class="jd-side-name">{{ row.name }}</span> <span class="jd-side-name">{{ row.name }}</span>
<span class="jd-side-count">{{ row.productCount }}</span> <span class="jd-side-count">{{ row.productCount }}</span>
</button> </div>
<p v-if="!catalogRows.length" class="jd-side-empty"> <!-- 树外兜底:授权树里搜不到的历史末级名(别店未上报 / 京麦改过类目体系)。
不藏——藏了这些商品就点不到;也不冒充树内节点,单列一组说清来路。 -->
<template v-if="catalog.orphans.length">
<p class="jd-side-group-head">平台树外(历史类目)</p>
<div
v-for="row in catalog.orphans"
:key="`orphan:${row.name}`"
class="jd-side-row jd-side-orphan depth-1"
:class="{ selected: isSelectedOrphanRow(row.name) }"
role="button"
tabindex="0"
:title="row.name"
@click="pickOrphanRow(row.name)"
@keydown.enter="pickOrphanRow(row.name)"
>
<span class="jd-side-leaf-dot" />
<span class="jd-side-name">{{ row.name }}</span>
<span class="jd-side-count">{{ row.productCount }}</span>
</div>
</template>
<p v-if="!visibleCatalogRows.length && !catalog.orphans.length" class="jd-side-empty">
还没有采集到类目数据(先采集一次店铺即有) 还没有采集到类目数据(先采集一次店铺即有)
</p> </p>
</div> </div>
@@ -445,7 +543,45 @@ function cancelShopRename(): void {
font-weight: 600; font-weight: 600;
} }
/* 层级缩进(2026-11-26):一级贴着侧栏,每下一级 +14px。京麦授权树现状最深 4 级,
depth-4/5 是护栏(脏数据超出也不至于把文字挤出侧栏)。depth-1 与店铺名单行同档。 */
.jd-side-row.depth-0 { padding-left: 8px; }
.jd-side-row.depth-1 { padding-left: 22px; } .jd-side-row.depth-1 { padding-left: 22px; }
.jd-side-row.depth-2 { padding-left: 36px; }
.jd-side-row.depth-3 { padding-left: 50px; }
.jd-side-row.depth-4 { padding-left: 64px; }
.jd-side-row.depth-5 { padding-left: 78px; }
/* 一级/二级的父级行:字重略沉,与末级行区分「这是分组不是可点的叶子」。 */
.jd-side-row.branch > .jd-side-name {
color: #606266;
font-weight: 600;
}
.jd-side-arrow {
width: 14px;
flex-shrink: 0;
padding: 0;
border: none;
background: transparent;
cursor: pointer;
font-size: 10px;
line-height: 1;
color: #909399;
text-align: center;
}
.jd-side-arrow:hover {
color: #409eff;
}
/* 「平台树外(历史类目)」分组头:单列一条,不冒充树内节点。 */
.jd-side-group-head {
margin: 8px 0 2px;
padding: 0 8px;
font-size: 12px;
color: #909399;
}
.jd-side-leaf-dot { .jd-side-leaf-dot {
width: 14px; width: 14px;
@@ -46,6 +46,8 @@ import {
JD_PRODUCT_PAGE_SIZE_OPTIONS, JD_PRODUCT_PAGE_SIZE_OPTIONS,
} from './jd-product-filter.ts' } from './jd-product-filter.ts'
import { JD_PRODUCT_DEFAULT_SIZE, type JdProductItem } from './jd-product-model.ts' import { JD_PRODUCT_DEFAULT_SIZE, type JdProductItem } from './jd-product-model.ts'
import { fetchJdShopCategoryTree } from './jd-shop-category-api.ts'
import type { JdCategoryNode } from './jd-category-hierarchy.ts'
import JdCategorySidebar from './JdCategorySidebar.vue' import JdCategorySidebar from './JdCategorySidebar.vue'
import JdProductCard from './JdProductCard.vue' import JdProductCard from './JdProductCard.vue'
import JdProductDetailModal from './JdProductDetailModal.vue' import JdProductDetailModal from './JdProductDetailModal.vue'
@@ -97,9 +99,12 @@ const groupOptions = ref<JdProductGroup[]>([])
/** 类目计数行(京麦末级类目+商品数):侧栏商品目录树的徽标数据源;失败静默回空。 */ /** 类目计数行(京麦末级类目+商品数):侧栏商品目录树的徽标数据源;失败静默回空。 */
const categoryOptions = ref<JdProductCategoryOption[]>([]) const categoryOptions = ref<JdProductCategoryOption[]>([])
/** 类目计数是否已取过(成功或失败回空都算就绪):侧栏据此区分「还没到」与「确实没有」, /** 类目计数是否已取过(成功或失败回空都算就绪):侧栏据此区分「还没到」与「确实没有」,
* 首帧未就绪时不画树——否则先把回落快照的别店类目整棵树(徽标全 0、「全部商品 0」) * 首帧未就绪时不画树——否则先画一棵「全部商品 0」的空树,计数到达后再跳成有数据,
* 画出来,计数到达后再收成「本店无匹配」一行,用户会看到一次莫名的闪变。 */ * 用户会看到一次莫名的闪变。 */
const categoryOptionsReady = ref(false) const categoryOptionsReady = ref(false)
/** 京麦授权类目树(服务端按店铺上报的并集森林):侧栏一级/二级层级的骨架;失败静默回空
* (空树=侧栏退化为末级平铺,不会整块空掉)。 */
const categoryTree = ref<JdCategoryNode[]>([])
const detailItem = ref<JdProductItem | null>(null) const detailItem = ref<JdProductItem | null>(null)
const detailVisible = ref(false) const detailVisible = ref(false)
/** 归类对话框(2026-17 替代下线的店铺分类弹窗,工具栏「归入分类」打开)。 */ /** 归类对话框(2026-17 替代下线的店铺分类弹窗,工具栏「归入分类」打开)。 */
@@ -125,9 +130,16 @@ const canManageCategories = computed(() => currentGroupOption.value?.editable ==
* 弹窗右栏的勾选面 ⇒ 勾选面对「本组可写」放开,否则管理人员没有归类入口。 */ * 弹窗右栏的勾选面 ⇒ 勾选面对「本组可写」放开,否则管理人员没有归类入口。 */
const hasSelection = computed(() => canWriteProducts.value || canManageCategories.value) const hasSelection = computed(() => canWriteProducts.value || canManageCategories.value)
/** 侧栏选中回显:类目(京东平台末级类目名;path 恒空——平铺列表没有层级)与分类 id。 */ /** 侧栏选中回显:类目(节点名+一级到本行的名称链,侧栏据此展开祖先)与分类 id。
* names(实际下发的末级名集合)也带上——侧栏只把它原样透传,不再自己算。 */
const selectedCategoryInfo = computed(() => const selectedCategoryInfo = computed(() =>
filter.category ? { name: filter.category, path: [] } : null) filter.category
? {
name: filter.category,
path: filter.categoryPath ?? [],
names: filter.categoryNames ?? [],
}
: null)
const selectedGroupIdNum = computed(() => { const selectedGroupIdNum = computed(() => {
const id = Number.parseInt(filter.groupId, 10) const id = Number.parseInt(filter.groupId, 10)
return Number.isFinite(id) && id > 0 ? id : null return Number.isFinite(id) && id > 0 ? id : null
@@ -166,8 +178,12 @@ const activeFilterChips = computed(() => {
* 左栏「商品目录」=后端 `/categories` 的 DISTINCT `category_path`(京麦末级类目名+计数), * 左栏「商品目录」=后端 `/categories` 的 DISTINCT `category_path`(京麦末级类目名+计数),
* 点一行=按该末级类目名**等值**过滤(后端 `p.category_path IN (...)`,单元素集合); * 点一行=按该末级类目名**等值**过滤(后端 `p.category_path IN (...)`,单元素集合);
* null=「全部商品」清选重查。不再有授权类目树/内置快照,也就没有父级展开集合。 */ * null=「全部商品」清选重查。不再有授权类目树/内置快照,也就没有父级展开集合。 */
function onSelectCategory(value: { name: string; path: string[] } | null): void { function onSelectCategory(value: { name: string; path: string[]; names: string[] } | null): void {
filter.category = value?.name || '' filter.category = value?.name || ''
// 名称链只喂回显展开;过滤值看 names(父级点选=整棵子树的末级名集合)。清选时两者一起清,
// 否则会留下一条「名字已清、集合还在」的幽灵谓词。
filter.categoryPath = value?.path ?? []
filter.categoryNames = value?.names ?? []
apply() apply()
} }
@@ -389,6 +405,17 @@ async function loadCategoryOptions(): Promise<void> {
} }
} }
/** 京麦授权类目树(层级树的数据源):与计数行并行取,失败静默回空——树空时侧栏退化为
* 末级平铺(上一窗行为),分层只是增益,绝不因为这一路抖动把商品目录整块拿掉。 */
async function loadCategoryTree(): Promise<void> {
try {
const result = await fetchJdShopCategoryTree()
categoryTree.value = result.nodes
} catch {
categoryTree.value = []
}
}
/** 切换「分组」下拉:分类筛选(属于上一组的分类)清空,分类选项换成本组,回第一页重取。 /** 切换「分组」下拉:分类筛选(属于上一组的分类)清空,分类选项换成本组,回第一页重取。
* 勾选集是按商品 id 记的(跨页累计),切组不清——归类的落点组随 ownerGroupId 走, * 勾选集是按商品 id 记的(跨页累计),切组不清——归类的落点组随 ownerGroupId 走,
* 误跨组批量归类由归类对话框里的组名标注防住。 */ * 误跨组批量归类由归类对话框里的组名标注防住。 */
@@ -466,6 +493,8 @@ async function load(): Promise<void> {
pageSize: pageSize.value, pageSize: pageSize.value,
keyword: filter.keyword, keyword: filter.keyword,
category: filter.category, category: filter.category,
categoryPath: filter.categoryPath ?? [],
categoryNames: filter.categoryNames ?? [],
shopName: filter.shopName, shopName: filter.shopName,
groupId: filter.groupId, groupId: filter.groupId,
classified: filter.classified, classified: filter.classified,
@@ -642,6 +671,8 @@ onMounted(async () => {
// 不要先发一条不带 owner_group_id 的列表请求再补,两次请求会落在不同默认组上)。 // 不要先发一条不带 owner_group_id 的列表请求再补,两次请求会落在不同默认组上)。
await loadCategoryScope() await loadCategoryScope()
void loadCategoryOptions() void loadCategoryOptions()
// 授权树与计数行并行(互不依赖):侧栏拿到两份都齐才画得出层级,任何一路慢都不挡首屏行集。
void loadCategoryTree()
await load() await load()
}) })
</script> </script>
@@ -835,6 +866,7 @@ onMounted(async () => {
取数在页面,侧栏纯展示。 --> 取数在页面,侧栏纯展示。 -->
<JdCategorySidebar <JdCategorySidebar
:category-options="categoryOptions" :category-options="categoryOptions"
:category-tree="categoryTree"
:categories="groupOptions" :categories="groupOptions"
:editable="canManageCategories" :editable="canManageCategories"
:selected-category="selectedCategoryInfo" :selected-category="selectedCategoryInfo"
@@ -0,0 +1,267 @@
/** 商品目录层级(2026-11-26 客户口径「怎么都没有分类一级二级分类」「管理员要分类时候
* 那么多怎么看」):把 `/categories` 的**末级类目名+商品数**挂到**京麦授权类目真树**
* 上,还原一级 / 二级 / 末级三层可展开浏览。
*
* 数据来源两处,各自口径固定(不互相冒充):
* - 树:`GET /api/jd-shop-category-tree`(客户端采集窗口顺手收的 `getVenderLicenseCategory`,
* 按店铺上报、服务端按平台 node_id 并集去重)。**不再有内置硬编码快照**——那是
* 2026-11-16 一家店的历史取证,换店必整树零命中。
* - 计数:`GET /api/admin/jd-products/categories`(`biz_jd_product.category_path` DISTINCT
* 的末级名+行数)。落库的 `category_path` =京麦列表 `categoryDetailVO.lastCategoryName`,
* 与树节点名同词 ⇒ 用**名称精确等值**挂接,不做模糊匹配(2026-11-26 生产实测:本店
* 264 行全部精确命中,模糊匹配只会制造假命中)。
*
* 两条口径要钉死,避免回到旧病:
* 1. **计数按「去重后的名字集合」求和**——同一末级名在树里可能跨支出现(如「吊带/背心」
* 在「内衣」「女装」两处),父级徽标若按「子节点逐个相加」会把同名行算两遍,界面
* 出现「一级 20、点开全是 10」。
* 2. **零计数分支剪掉**——授权树是「本店可卖什么」,不是「本店有什么」;不剪就会把
* 24 个一级 / 四百多个节点全铺出来,管理员反而更看不清(客户这句抱怨的原形)。
* 剪完仍需保底:树里搜不到的历史末级名进「平台树外」组,绝不让商品点不到。
*
* 纯函数、零依赖(`node --test` 直测);请求与装配在 `jd-shop-category-api.ts`。 */
/** 授权树节点(服务端 `GET /api/jd-shop-category-tree` 的 `nodes[]` 递归形状,
* 与京麦 `getVenderLicenseCategory` 一致:`{name, value, children}`)。 */
export interface JdCategoryNode {
name: string
value: string
children?: JdCategoryNode[]
}
/** 递归解析服务端下发的树:脏值归一,空名节点自身丢弃但子级仍展开(不丢整支);
* value 缺失按空串;超过 8 层截断(京麦现状最深 4 级,护栏只防脏数据递归炸栈)。 */
export function parseJdCategoryNodeTree(raw: unknown, depth = 0): JdCategoryNode[] {
if (!Array.isArray(raw) || depth > 8) return []
const out: JdCategoryNode[] = []
for (const item of raw) {
if (!item || typeof item !== 'object') continue
const record = item as Record<string, unknown>
const name = typeof record.name === 'string' ? record.name.trim() : ''
const value = record.value == null ? '' : String(record.value).trim()
if (!name) {
out.push(...parseJdCategoryNodeTree(record.children, depth + 1))
continue
}
const node: JdCategoryNode = { name, value }
const children = parseJdCategoryNodeTree(record.children, depth + 1)
if (children.length) node.children = children
out.push(node)
}
return out
}
/** 可渲染的一行(层级已展开成扁平的祖先链,深度 0=一级)。 */
export interface JdCatalogRow {
/** 行键:平台类目 id 优先,缺失退回「名称路径」——同名跨支(两条「吊带/背心」)靠它区分,
* 展开态/选中态都按它记,别用 name(同名会互相带动)。 */
key: string
name: string
/** 0=一级,1=二级…… */
depth: number
/** 本节点及其子树命中的商品数(按去重名字集合求和,见文件头口径 1)。 */
productCount: number
/** 无子级(=末级):点它是单名过滤;有子级时点它=按整棵子树的名字集合过滤。 */
isLeaf: boolean
/** 选中本行时下发给后端的类目名集合:本节点名+全部子孙节点名(去重保序)。
* 主体是末级名(落库 `category_path` 的词表),父级名一并带上当兜底——京麦列表的
* `lastCategoryName` 偶尔可能停在非末级节点上,少带一个名字就是「点得到、查不到」。 */
names: string[]
children: JdCatalogRow[]
}
/** 构建结果:树 + 树外兜底 + 总数。 */
export interface JdCatalogTree {
/** 一级行(零计数分支已剪;服务端 sort_order 顺序原样保留)。 */
roots: JdCatalogRow[]
/** 树里找不到的名字(别店未上报 / 京麦改过类目体系的历史行),按行数降序;空=全命中。 */
orphans: { name: string; productCount: number }[]
/** 「全部商品」徽标:全部计数行按名字去重后求和(不按树求和——同名跨支不重复计)。 */
totalCount: number
}
/** 计数行(`/categories` 的 `{name, productCount}`)。 */
export interface JdCategoryCount {
name: string
productCount: number
}
/** 名称 → 商品数(同名重复行累加,脏名/负值丢弃)。 */
function countMapOf(options: readonly JdCategoryCount[]): Map<string, number> {
const map = new Map<string, number>()
for (const row of options) {
const name = (row?.name ?? '').trim()
if (!name) continue
const count = Number.isFinite(row.productCount) && row.productCount > 0
? Math.floor(row.productCount)
: 0
map.set(name, (map.get(name) ?? 0) + count)
}
return map
}
/** 树里出现过的全部节点名(任意层级)——树外兜底的判据。 */
function nodeNamesOf(nodes: readonly JdCategoryNode[], into: Set<string>): Set<string> {
for (const node of nodes) {
into.add(node.name)
if (node.children?.length) nodeNamesOf(node.children, into)
}
return into
}
/** 节点 → 行(剪枝+计数都在这一个递归里,避免两遍遍历口径漂移)。 */
function buildRow(
node: JdCategoryNode,
depth: number,
parentKey: string,
counts: Map<string, number>,
): JdCatalogRow | null {
const key = node.value || `${parentKey}/${node.name}`
const names = new Set<string>([node.name])
const children: JdCatalogRow[] = []
for (const child of node.children ?? []) {
const row = buildRow(child, depth + 1, key, counts)
if (!row) continue
children.push(row)
for (const name of row.names) names.add(name)
}
const nameList = [...names]
let productCount = 0
for (const name of nameList) productCount += counts.get(name) ?? 0
// 零计数整支剪掉(含「自己是末级且 0 行」与「子级全被剪」两种形状)。
if (productCount <= 0) return null
return {
key,
name: node.name,
depth,
productCount,
isLeaf: children.length === 0,
names: nameList,
children,
}
}
/** 树为空时的退化形状:把计数行当一级末级平铺(=上一窗 2026-11-26「平台类目平铺」的
* 行为逐字不变)。没有树不等于没有数据,绝不能因此让左栏空掉。 */
function flatRows(options: readonly JdCategoryCount[]): JdCatalogRow[] {
const rows: JdCatalogRow[] = []
for (const [name, productCount] of countMapOf(options)) {
if (productCount <= 0) continue
rows.push({
key: name,
name,
depth: 0,
productCount,
isLeaf: true,
names: [name],
children: [],
})
}
return rows
}
/** 主入口:授权树 + 计数行 → 可渲染层级。
*
* @param tree 服务端并集森林(空数组=还没有任何店铺上报过,退化为平铺)
* @param options `/categories` 的末级名+行数
*/
export function buildJdCatalogTree(
tree: readonly JdCategoryNode[],
options: readonly JdCategoryCount[],
): JdCatalogTree {
const counts = countMapOf(options)
let totalCount = 0
for (const count of counts.values()) totalCount += count
const nodes = parseJdCategoryNodeTree(tree)
if (!nodes.length) return { roots: flatRows(options), orphans: [], totalCount }
const roots: JdCatalogRow[] = []
for (const node of nodes) {
const row = buildRow(node, 0, '', counts)
if (row) roots.push(row)
}
const covered = nodeNamesOf(nodes, new Set<string>())
const orphans: { name: string; productCount: number }[] = []
for (const [name, productCount] of counts) {
// 计数 0 的名字不进兜底(点了只会得到空列表,占地方还误导)。
if (productCount > 0 && !covered.has(name)) orphans.push({ name, productCount })
}
orphans.sort((a, b) => b.productCount - a.productCount || a.name.localeCompare(b.name, 'zh'))
return { roots, orphans, totalCount }
}
/** 展开态 → 可见行(折叠节点的子孙不进列表;顺序=原树顺序)。 */
export function flattenJdCatalogRows(
roots: readonly JdCatalogRow[],
expandedKeys: Iterable<string>,
): JdCatalogRow[] {
const expanded = new Set(expandedKeys)
const out: JdCatalogRow[] = []
const walk = (rows: readonly JdCatalogRow[]): void => {
for (const row of rows) {
out.push(row)
if (row.children.length && expanded.has(row.key)) walk(row.children)
}
}
walk(roots)
return out
}
/** 按行键找从一级到该行的祖先链(含自身);找不到回空数组。
* 点行时用它算下发的 `path`(同名跨支按 key 定位,不会挑错那一支)。 */
export function findJdCatalogPathByKey(
roots: readonly JdCatalogRow[],
key: string,
): JdCatalogRow[] {
if (!key) return []
const walk = (rows: readonly JdCatalogRow[], prefix: JdCatalogRow[]): JdCatalogRow[] => {
for (const row of rows) {
const chain = [...prefix, row]
if (row.key === key) return chain
if (row.children.length) {
const hit = walk(row.children, chain)
if (hit.length) return hit
}
}
return []
}
return walk(roots, [])
}
/** 全部行键 → 祖先链(挂载时按它把选中行的祖先链一次性展开)。 */
export function jdCatalogPathIndex(
roots: readonly JdCatalogRow[],
): Map<string, string[]> {
const index = new Map<string, string[]>()
const walk = (rows: readonly JdCatalogRow[], prefix: string[]): void => {
for (const row of rows) {
const names = [...prefix, row.name]
index.set(row.key, names)
if (row.children.length) walk(row.children, names)
}
}
walk(roots, [])
return index
}
/** 按名称找从一级到命中行的祖先链(含自身);找不到回空数组。
* 同名跨支时返回**第一条**命中链——过滤按名字集合下发,两条同名行点哪个都等价,
* 这里只为「挂载即把选中行露出来」挑一条链展开。 */
export function findJdCatalogPath(
roots: readonly JdCatalogRow[],
name: string,
): JdCatalogRow[] {
const needle = (name ?? '').trim()
if (!needle) return []
const walk = (rows: readonly JdCatalogRow[], prefix: JdCatalogRow[]): JdCatalogRow[] => {
for (const row of rows) {
const chain = [...prefix, row]
if (row.name === needle) return chain
if (row.children.length) {
const hit = walk(row.children, chain)
if (hit.length) return hit
}
}
return []
}
return walk(roots, [])
}
@@ -28,6 +28,8 @@ export async function fetchJdProductList(
{ {
keyword: params.keyword ?? '', keyword: params.keyword ?? '',
category: params.category ?? '', category: params.category ?? '',
categoryPath: params.categoryPath ?? [],
categoryNames: params.categoryNames ?? [],
shopName: params.shopName ?? '', shopName: params.shopName ?? '',
groupId: params.groupId ?? '', groupId: params.groupId ?? '',
classified: (params.classified ?? '') as '' | 'classified' | 'ungrouped', classified: (params.classified ?? '') as '' | 'classified' | 'ungrouped',
@@ -46,11 +46,17 @@ export interface JdProductFilterState {
/** 合并搜索词(v1.7 对齐原型:一个框同时搜商品编码与标题,OR 语义在后端 SQL)。 /** 合并搜索词(v1.7 对齐原型:一个框同时搜商品编码与标题,OR 语义在后端 SQL)。
* 旧 productCode/titleKeyword 两框随 v1.7 前端下线(后端参数保留兼容在飞请求)。 */ * 旧 productCode/titleKeyword 两框随 v1.7 前端下线(后端参数保留兼容在飞请求)。 */
keyword: string keyword: string
/** 类目(京麦末级类目名=后端 `category_path` DISTINCT 值;选项来自侧栏商品目录平铺), /** 类目(回显用的节点名:末级名=`category_path` 词表,或一级/二级的父级名;空串=全部)。
* 空串=全部类目。2026-11-26 客户口径「京东分类是百分百有的,京东内分类就不需要」: * 真正的过滤值在 `categoryNames`,这里只喂芯片与选中态显示。 */
* 只按末级类目名等值过滤,不再有「父级点选→子树展开集合」这一层(旧 categoryPath/
* categoryNames 两个字段随内置花屿巷快照树一并退役)。 */
category: string category: string
/** 选中节点的名称路径(从一级到本节点、含自身;空=「全部商品」)。
* 只用于「挂载即展开祖先链露出选中行」,不参与过滤。 */
categoryPath?: string[]
/** 选中节点展开好的末级类目名集合(后端 `p.category_path IN (...)`):末级行=单元素、
* 父级行=整棵子树的末级名(2026-11-18 客户口径「一级/二级类目也要能选来搜索」)。
* 2026-11-26 随商品目录层级树恢复:展开在**选中那一刻**按当前生效授权树算好放这里,
* 纯函数层不持有树——树换版也不会让一个旧选中悄悄变成另一批类目。 */
categoryNames?: string[]
/** 店铺名(v1.7 店铺名单维度:侧栏点店铺行下发,精确 eq;空串不限)。 */ /** 店铺名(v1.7 店铺名单维度:侧栏点店铺行下发,精确 eq;空串不限)。 */
shopName: string shopName: string
/** 分类 id 文本(侧栏店铺分类 Tab 里那一行),空串=全部分类。 */ /** 分类 id 文本(侧栏店铺分类 Tab 里那一行),空串=全部分类。 */
@@ -79,6 +85,8 @@ export function createJdProductFilterState(): JdProductFilterState {
return { return {
keyword: '', keyword: '',
category: '', category: '',
categoryPath: [],
categoryNames: [],
shopName: '', shopName: '',
groupId: '', groupId: '',
classified: JD_PRODUCT_DEFAULT_CLASSIFIED, classified: JD_PRODUCT_DEFAULT_CLASSIFIED,
@@ -135,6 +143,9 @@ export interface JdProductListParams {
pageSize: number pageSize: number
keyword?: string keyword?: string
category?: string category?: string
/** 选中节点路径与展开好的末级名集合(见 JdProductFilterState;父级点选走 categoryNames)。 */
categoryPath?: string[]
categoryNames?: string[]
shopName?: string shopName?: string
groupId?: string groupId?: string
/** 分类状态快筛(''/缺省=全部,'classified'/'ungrouped' 见 JdProductFilterState)。 */ /** 分类状态快筛(''/缺省=全部,'classified'/'ungrouped' 见 JdProductFilterState)。 */
@@ -156,10 +167,15 @@ function toJdProductFilterQuery(state: JdProductFilterState): Omit<JdProductQuer
const keyword = (state.keyword || '').trim() const keyword = (state.keyword || '').trim()
if (keyword) query.keyword = keyword if (keyword) query.keyword = keyword
const category = (state.category || '').trim() const category = (state.category || '').trim()
if (category) { const categoryNames = (state.categoryNames ?? [])
// 末级类目名等值:单元素集合下发,后端 `p.category_path IN (...)` 单值等价 eq。 .map((name) => (name ?? '').trim())
// 2026-11-26 起左栏商品目录=京东平台类目平铺(category_path DISTINCT), .filter((name) => !!name)
// 不再有「父级点选→子树展开集合」这条链。 if (categoryNames.length) {
// 父级点选:按选中那一刻展开好的子树末级名集合下发(后端 `p.category_path IN (...)`
// 多值)。单元素时与末级点选逐字同形,两条路不各写一套参数。
query.category = [...new Set(categoryNames)]
} else if (category) {
// 兜底:只有节点名(树未就绪/树外行/buildJdCatalogTree 之前的旧调用点)=单名等值。
query.category = [category] query.category = [category]
} }
const shopName = (state.shopName || '').trim() const shopName = (state.shopName || '').trim()
@@ -0,0 +1,56 @@
/** 京麦授权类目树读取(`GET /api/jd-shop-category-tree`):商品目录层级的数据源。
*
* 数据来源=客户端采集窗口顺手收到的 `getVenderLicenseCategory`(按店铺上报、服务端按平台
* node_id 并集去重),节点形状 `{name, value, children}` 与京麦一致。
*
* 失败/空一律返回空节点数组:页面据此退化为「末级类目平铺」(上一窗行为),绝不让接口
* 抖动把左栏变成错误块——树只是分层浏览的增益,过滤能力不依赖它。
*
* ⚠ 2026-11-23 曾按「内置花屿巷快照优先、服务端树覆盖」共用过一份,2026-11-26 快照整份
* 删除(它是一家店的取证,换店必整树零命中,正是客户「品类怎么全不对」的老病根)。
* 这里只剩服务端真树一条路,没有第二份树。 */
import { http } from '@/api/http'
import { unwrap } from '../../api/envelope.ts'
import { parseJdCategoryNodeTree, type JdCategoryNode } from './jd-category-hierarchy.ts'
export { parseJdCategoryNodeTree }
export const JD_SHOP_CATEGORY_TREE_ENDPOINT = '/api/jd-shop-category-tree'
/** 已上报店铺(仅用于排查展示,不参与渲染判据)。 */
export interface JdShopCategoryTreeShop {
shopId: string
shopName: string | null
capturedAt: string | null
nodeCount: number
}
export interface JdShopCategoryTreeResult {
/** 并集森林;空数组=服务端还没有任何店铺上报过(页面退化为平铺)。 */
nodes: JdCategoryNode[]
shops: JdShopCategoryTreeShop[]
}
/** 递归解析已在 `jd-category-hierarchy.ts`(零依赖、node --test 可直测),这里只做请求与装配。 */
export async function fetchJdShopCategoryTree(): Promise<JdShopCategoryTreeResult> {
const { data } = await http.get<unknown>(JD_SHOP_CATEGORY_TREE_ENDPOINT)
const core = unwrap<unknown>(data)
if (!core || typeof core !== 'object') return { nodes: [], shops: [] }
const record = core as Record<string, unknown>
const shops: JdShopCategoryTreeShop[] = []
for (const raw of Array.isArray(record.shops) ? record.shops : []) {
if (!raw || typeof raw !== 'object') continue
const row = raw as Record<string, unknown>
const shopId = row.shopId == null ? '' : String(row.shopId).trim()
if (!shopId) continue
shops.push({
shopId,
shopName: typeof row.shopName === 'string' ? row.shopName : null,
capturedAt: typeof row.capturedAt === 'string' ? row.capturedAt : null,
nodeCount: typeof row.nodeCount === 'number' && Number.isFinite(row.nodeCount)
? Math.max(0, Math.floor(row.nodeCount))
: 0,
})
}
return { nodes: parseJdCategoryNodeTree(record.nodes), shops }
}
@@ -0,0 +1,182 @@
/**
* 商品目录层级纯函数契约(2026-11-26 客户口径「怎么都没有分类一级二级分类」「管理员要
* 分类时候那么多怎么看」)——node --test 直跑(纯函数零依赖)。
*
* 覆盖:
* 1. `parseJdCategoryNodeTree` 脏值归一(空名节点丢自身保子级、value 缺失空串、超深截断);
* 2. `buildJdCatalogTree` 三个口径:计数按**去重名字集合**求和(同名跨支不重复计)、
* 零计数分支剪枝(但保底「树外兜底」)、树空退化为末级平铺(上一窗行为逐字不变);
* 3. `flattenJdCatalogRows` 折叠语义(折叠节点的子孙不出现);
* 4. `findJdCatalogPath` / `jdCatalogPathIndex` / `findJdCatalogPathByKey` 的定位口径
* (点行下发 path、挂载展开祖先链都靠它)。
*/
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
buildJdCatalogTree,
findJdCatalogPath,
findJdCatalogPathByKey,
flattenJdCatalogRows,
jdCatalogPathIndex,
parseJdCategoryNodeTree,
type JdCategoryNode,
} from '../src/pages/jd/jd-category-hierarchy.ts'
/** 本店真机形状的缩影(生产实测:商品末级名 100% 精确命中树节点名)。 */
const TREE: JdCategoryNode[] = [
{
name: '厨房卫浴',
value: '1',
children: [
{
name: '厨卫挂件',
value: '11',
children: [
{ name: '其他收纳架', value: '111' },
{ name: '牙刷架/牙具座', value: '112' },
],
},
{ name: '沐浴桶', value: '12', children: [{ name: '泡脚桶/袋/盆', value: '121' }] },
],
},
{
name: '家居饰品',
value: '2',
children: [
{ name: '摆件', value: '21', children: [{ name: '桌面摆件', value: '211' }] },
],
},
// 零计数整支:授权树里本店可卖、但这批采集没采到的类目。
{
name: '服饰内衣',
value: '3',
children: [{ name: '女装', value: '31', children: [{ name: '连衣裙', value: '311' }] }],
},
]
test('parseJdCategoryNodeTree:空名节点丢自身保子级、value 缺失按空串、超深截断', () => {
const parsed = parseJdCategoryNodeTree([
{ name: ' ', value: '9', children: [{ name: '子级', value: '91' }] },
{ value: '8', children: [{ name: '孤儿', value: '81' }] },
{ name: '有值', value: 7 },
'not-an-object',
])
assert.deepEqual(parsed.map((node) => node.name), ['子级', '孤儿', '有值'])
assert.equal(parsed[2].value, '7', '数字 value 归一成字符串')
assert.equal(parseJdCategoryNodeTree([{ name: 'x' }])[0].value, '', 'value 缺失按空串')
assert.deepEqual(parseJdCategoryNodeTree('bad'), [], '非数组回空')
// 深度护栏:9 层嵌套只保留前 9 层(depth > 8 起截断),不抛栈。
let deep: unknown = { name: 'L9', value: '9' }
for (let level = 8; level >= 1; level -= 1) deep = { name: `L${level}`, value: `${level}`, children: [deep] }
let node: JdCategoryNode | undefined = parseJdCategoryNodeTree([deep])[0]
let depth = 0
while (node) {
depth += 1
node = node.children?.[0]
}
assert.ok(depth >= 1 && depth <= 9, `深度应被截断在 9 层内,实际 ${depth}`)
})
test('buildJdCatalogTree:父级徽标=子树命中行数,末级=自身名行数,总数=全部行求和', () => {
const catalog = buildJdCatalogTree(TREE, [
{ name: '其他收纳架', productCount: 17 },
{ name: '牙刷架/牙具座', productCount: 2 },
{ name: '泡脚桶/袋/盆', productCount: 32 },
{ name: '桌面摆件', productCount: 9 },
])
const kitchen = catalog.roots.find((row) => row.name === '厨房卫浴')!
assert.equal(kitchen.productCount, 51, '一级=51(17+2+32)')
assert.equal(kitchen.isLeaf, false)
assert.deepEqual(kitchen.names.slice().sort(),
['厨房卫浴', '厨卫挂件', '其他收纳架', '牙刷架/牙具座', '沐浴桶', '泡脚桶/袋/盆'].sort(),
'父级点选下发的名字集合=整棵子树的节点名(主体是末级,父级名带上兜底)')
const hook = kitchen.children.find((row) => row.name === '厨卫挂件')!
assert.equal(hook.productCount, 19, '二级=19(17+2)')
assert.equal(hook.depth, 1)
const leaf = hook.children.find((row) => row.name === '其他收纳架')!
assert.equal(leaf.productCount, 17)
assert.equal(leaf.isLeaf, true, '无子级=末级(单名过滤)')
assert.equal(leaf.depth, 2)
assert.deepEqual(leaf.names, ['其他收纳架'])
assert.equal(catalog.totalCount, 60, '「全部商品」=全部计数行求和')
assert.deepEqual(catalog.orphans, [], '全部命中树,无兜底行')
})
test('buildJdCatalogTree:零计数分支剪掉(授权树≠有货树),整树都被剪时回空根', () => {
const catalog = buildJdCatalogTree(TREE, [{ name: '桌面摆件', productCount: 9 }])
assert.deepEqual(catalog.roots.map((row) => row.name), ['家居饰品'],
'「厨房卫浴」「服饰内衣」两支全 0 ⇒ 不出现(否则四百多节点铺满侧栏,反而看不清)')
assert.equal(catalog.roots[0].productCount, 9)
assert.deepEqual(buildJdCatalogTree(TREE, []).roots, [], '一行都没有 ⇒ 空根(侧栏走空态)')
})
test('buildJdCatalogTree:同名跨支按去重名字集合求和,父级徽标不重复计', () => {
const tree: JdCategoryNode[] = [
{ name: '内衣', value: 'a', children: [{ name: '吊带/背心', value: 'a1' }] },
{ name: '女装', value: 'b', children: [{ name: '吊带/背心', value: 'b1' }] },
]
const catalog = buildJdCatalogTree(tree, [{ name: '吊带/背心', productCount: 5 }])
assert.deepEqual(catalog.roots.map((row) => row.productCount), [5, 5],
'两个一级各自 5(同一批行按名字命中两支),不是各 2.5 也不是 10')
assert.equal(catalog.totalCount, 5, '「全部商品」只算一次')
})
test('buildJdCatalogTree:树外的历史末级名进兜底组(不藏、按行数降序)', () => {
const catalog = buildJdCatalogTree(TREE, [
{ name: '其他收纳架', productCount: 17 },
{ name: '已下架历史类目', productCount: 12 },
{ name: '另一个历史类目', productCount: 3 },
])
assert.deepEqual(catalog.orphans.map((row) => row.name), ['已下架历史类目', '另一个历史类目'],
'树里搜不到的名字单列一组,按行数降序——藏了这些商品就点不到')
assert.equal(catalog.totalCount, 32, '兜底行的行数照样进「全部商品」')
})
test('buildJdCatalogTree:树为空 ⇒ 退化为末级平铺(上一窗行为逐字不变)', () => {
const catalog = buildJdCatalogTree([], [
{ name: '连衣裙', productCount: 7 },
{ name: ' ', productCount: 4 },
{ name: '短裤', productCount: -1 },
])
assert.deepEqual(catalog.roots.map((row) => [row.name, row.productCount, row.depth, row.isLeaf]), [
['连衣裙', 7, 0, true],
], '空名/非正计数不进列表;平铺行 depth 0、按末级处理')
assert.deepEqual(catalog.orphans, [], '没有树就没有「树外」这个概念')
assert.equal(catalog.totalCount, 7)
})
test('flattenJdCatalogRows:折叠节点的子孙不进列表;展开哪个只影响那个分支', () => {
const catalog = buildJdCatalogTree(TREE, [
{ name: '其他收纳架', productCount: 17 },
{ name: '桌面摆件', productCount: 9 },
])
assert.deepEqual(flattenJdCatalogRows(catalog.roots, []).map((row) => row.name),
['厨房卫浴', '家居饰品'], '默认全收起:先看清有哪些大类')
const kitchen = catalog.roots.find((row) => row.name === '厨房卫浴')!
const opened = flattenJdCatalogRows(catalog.roots, [kitchen.key])
assert.deepEqual(opened.map((row) => row.name), ['厨房卫浴', '厨卫挂件', '家居饰品'],
'只展开一级 ⇒ 出它的二级,别的分支不动')
const fully = flattenJdCatalogRows(catalog.roots, [kitchen.key, '11'])
assert.deepEqual(fully.map((row) => row.name), ['厨房卫浴', '厨卫挂件', '其他收纳架', '家居饰品'])
})
test('路径定位:点行下发一级到本行的名称链;挂载按选中行展开祖先', () => {
const catalog = buildJdCatalogTree(TREE, [
{ name: '其他收纳架', productCount: 17 },
{ name: '桌面摆件', productCount: 9 },
])
const leaf = findJdCatalogPathByKey(catalog.roots, '111')
assert.deepEqual(leaf.map((row) => row.name), ['厨房卫浴', '厨卫挂件', '其他收纳架'])
assert.deepEqual(findJdCatalogPath(catalog.roots, '桌面摆件').map((row) => row.name),
['家居饰品', '摆件', '桌面摆件'])
assert.deepEqual(findJdCatalogPath(catalog.roots, '不存在的类目'), [],
'选中名不在树里(树外兜底行)⇒ 空链,侧栏不展开任何分支')
assert.deepEqual(findJdCatalogPathByKey(catalog.roots, ''), [])
const index = jdCatalogPathIndex(catalog.roots)
assert.deepEqual(index.get('21'), ['家居饰品', '摆件'], '索引供点行时算 path')
})
@@ -97,25 +97,37 @@ test('列表行价格:BigDecimal 的 JSON number 形状与字符串形状都
assert.equal(jdPriceRange(missing), '', '两侧都空回空串(列表显示 -)') assert.equal(jdPriceRange(missing), '', '两侧都空回空串(列表显示 -)')
}) })
/** 类目筛选(2026-11-26 客户口径「京东分类是百分百有的,京东内分类就不需要」): /** 类目筛选(2026-11-26 客户口径「怎么都没有分类一级二级分类」「管理员要分类时候那么多
* 左栏商品目录=京东平台类目(`category_path` DISTINCT 末级名)平铺,点行=单名等值; * 怎么看」):左栏商品目录=京麦授权类目**层级树**+`category_path` 末级名计数。
* 空串不下发。旧「父级点选→按授权树/内置快照展开子树集合」那一层随之退役。 */ * 末级行=单名等值;一级/二级行=整棵子树的节点名集合(后端 `category_path IN (...)` 多值)。
test('类目筛选参数序列化:空串不下发、选中末级类目=单元素集合(等值)', async () => { * 展开集合由侧栏在选中那一刻算好(`names`),筛选层只负责序列化,不持有树。 */
test('类目筛选参数序列化:末级单名/父级集合/空串不下发', async () => {
const { createJdProductFilterState, toJdProductListParams, jdProductFilterActive } = const { createJdProductFilterState, toJdProductListParams, jdProductFilterActive } =
await import('../src/pages/jd/jd-product-filter.ts') await import('../src/pages/jd/jd-product-filter.ts')
const empty = createJdProductFilterState() const empty = createJdProductFilterState()
assert.equal('category' in toJdProductListParams(empty, 1, 20), false, '全部类目不下发 category') assert.equal('category' in toJdProductListParams(empty, 1, 20), false, '全部类目不下发 category')
assert.equal(jdProductFilterActive(empty), false) assert.equal(jdProductFilterActive(empty), false)
const leaf = { ...empty, category: ' 艺考形体服 ' } const leaf = { ...empty, category: ' 艺考形体服 ', categoryNames: ['艺考形体服'] }
assert.deepEqual(toJdProductListParams(leaf, 1, 20).category, ['艺考形体服'], assert.deepEqual(toJdProductListParams(leaf, 1, 20).category, ['艺考形体服'],
'末级类目名 trim 后单元素集合(后端 IN 单值等价 eq)') '末级类目:单元素集合(后端 IN 单值等价 eq)')
assert.equal(jdProductFilterActive(leaf), true, '选中类目算激活筛选') assert.equal(jdProductFilterActive(leaf), true, '选中类目算激活筛选')
// 历史「父级路径展开」字段已随内置快照树退役:带上也不影响序列化结果(不会凭空多出集合)。 const parent = {
const legacy = { ...empty, category: '女装', categoryPath: ['服饰内衣', '女装'] } ...empty,
assert.deepEqual(toJdProductListParams(legacy, 1, 20).category, ['女装'], category: '服饰内衣',
'没有子树展开集合这一层:父级路径就算传进来也只按单名等值下发') categoryPath: ['服饰内衣'],
categoryNames: ['服饰内衣', '女装', '连衣裙', '连衣裙 '],
}
assert.deepEqual(toJdProductListParams(parent, 1, 20).category,
['服饰内衣', '女装', '连衣裙'],
'父级点选:整棵子树的节点名集合(trim+去重),后端按多值 IN 命中')
assert.deepEqual(toJdProductListParams(parent, 1, 20).page, 1, '类目筛选不动分页')
// 只有节点名、没有展开集合(树未就绪 / 树外兜底行 / 老调用点):退化为单名等值,不丢筛选。
const single = { ...empty, category: ' 女装 ' }
assert.deepEqual(toJdProductListParams(single, 1, 20).category, ['女装'],
'没有展开集合时按节点名单名下发')
}) })
test('自定义分类使用 group_id,不发送分类状态参数', async () => { test('自定义分类使用 group_id,不发送分类状态参数', async () => {
@@ -2,9 +2,10 @@
* 京东数据库侧栏(JdCategorySidebar)的挂载契约。 * 京东数据库侧栏(JdCategorySidebar)的挂载契约。
* *
* 纯展示组件:取数与失败兜底全在页面(props 流入、emit 流出),本文件零 api mock—— * 纯展示组件:取数与失败兜底全在页面(props 流入、emit 流出),本文件零 api mock——
* 钉的是双 Tab 切换、商品目录「京东平台类目平铺」口径(2026-11-26 客户口径「京东分类 * 钉的是双 Tab 切换、商品目录「京东平台类目层级树」口径(2026-11-26 客户口径
* 百分百有,京东内分类不需要」:平铺一层、点行=末级类目名等值、path 恒空、无授权树/ * 「怎么都没有分类一级二级分类」「管理员要分类时候那么多怎么看」:一级/二级可展开、
* 无内置快照/无「树外兜底」分组)、可写档分档入口。 * 默认全收起只露大类、零计数分支不出现、父级点选=整棵子树名字集合、树外历史名单列
* 兜底组)、可写档分档入口。
* *
* 跑法:`npx vitest run tests/mount/jd-category-sidebar.mount.test.ts` * 跑法:`npx vitest run tests/mount/jd-category-sidebar.mount.test.ts`
*/ */
@@ -14,9 +15,10 @@ import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import JdCategorySidebar from '@/pages/jd/JdCategorySidebar.vue' import JdCategorySidebar from '@/pages/jd/JdCategorySidebar.vue'
import type { JdProductCategoryOption, JdProductGroup } from '@/pages/jd/jd-product-api.ts' import type { JdProductCategoryOption, JdProductGroup } from '@/pages/jd/jd-product-api.ts'
import type { JdCategoryNode } from '@/pages/jd/jd-category-hierarchy.ts'
/** 类目计数夹具:树内名(连衣裙支+同名跨支短裤)+树外历史名,读数与 Phase 1 /** 类目计数夹具:树内名(服饰内衣/女装/连衣裙支+艺考形体服支)+树外历史名,
* 纯函数测试同源——服饰内衣根徽标 20(子树去重)、全部商品 37、兜底 12。 */ * 读数=全部商品 37、服饰内衣 20(7+4+9)、运动户外 5、树外兜底 12。 */
const CATEGORY_OPTIONS: JdProductCategoryOption[] = [ const CATEGORY_OPTIONS: JdProductCategoryOption[] = [
{ name: '连衣裙', productCount: 7 }, { name: '连衣裙', productCount: 7 },
{ name: '短袖连衣裙', productCount: 4 }, { name: '短袖连衣裙', productCount: 4 },
@@ -25,6 +27,42 @@ const CATEGORY_OPTIONS: JdProductCategoryOption[] = [
{ name: '已下架历史类目', productCount: 12 }, { name: '已下架历史类目', productCount: 12 },
] ]
/** 授权树夹具(京麦 `{name, value, children}` 形状;生产真机最深 4 级,这里两层足够)。 */
const CATEGORY_TREE: JdCategoryNode[] = [
{
name: '服饰内衣',
value: '1',
children: [
{
name: '女装',
value: '11',
children: [
{ name: '连衣裙', value: '111' },
{ name: '短袖连衣裙', value: '112' },
{ name: '短裤', value: '113' },
],
},
],
},
{
name: '运动户外',
value: '2',
children: [
{
name: '舞蹈体操鞋服/装备',
value: '21',
children: [{ name: '艺考形体服', value: '211' }],
},
],
},
// 授权树里本店可卖、但这批采集 0 行:零计数整支必须被剪掉。
{
name: '母婴',
value: '3',
children: [{ name: '童装', value: '31', children: [{ name: '儿童礼服', value: '311' }] }],
},
]
const CATEGORIES: JdProductGroup[] = [ const CATEGORIES: JdProductGroup[] = [
{ id: 7, name: '裙装', ownerGroupId: 11, sortOrder: 0, productCount: 3 }, { id: 7, name: '裙装', ownerGroupId: 11, sortOrder: 0, productCount: 3 },
{ id: 8, name: '裤装', ownerGroupId: 11, sortOrder: 1, productCount: 1 }, { id: 8, name: '裤装', ownerGroupId: 11, sortOrder: 1, productCount: 1 },
@@ -38,16 +76,19 @@ const CATEGORIES_WITH_SHOPS: JdProductGroup[] = [
interface MountOptions { interface MountOptions {
editable?: boolean editable?: boolean
selectedCategory?: { name: string; path: string[] } | null selectedCategory?: { name: string; path: string[]; names?: string[] } | null
selectedGroupId?: number | null selectedGroupId?: number | null
selectedShopName?: string | null selectedShopName?: string | null
categories?: JdProductGroup[] categories?: JdProductGroup[]
categoryOptions?: JdProductCategoryOption[]
categoryTree?: JdCategoryNode[]
} }
function mountSidebar(options: MountOptions = {}): VueWrapper<Element> { function mountSidebar(options: MountOptions = {}): VueWrapper<Element> {
return mount(JdCategorySidebar, { return mount(JdCategorySidebar, {
props: { props: {
categoryOptions: CATEGORY_OPTIONS, categoryOptions: options.categoryOptions ?? CATEGORY_OPTIONS,
categoryTree: options.categoryTree ?? CATEGORY_TREE,
categories: options.categories ?? CATEGORIES, categories: options.categories ?? CATEGORIES,
editable: options.editable ?? true, editable: options.editable ?? true,
selectedCategory: options.selectedCategory ?? null, selectedCategory: options.selectedCategory ?? null,
@@ -64,47 +105,96 @@ function rowByText(scope: VueWrapper<Element>, text: string) {
return row! return row!
} }
describe('商品目录 Tab(京东平台类目平铺,2026-11-26)', () => { describe('商品目录 Tab(京东平台类目层级树,2026-11-26)', () => {
it('出厂停在商品目录 Tab;「全部商品」徽标=计数行求和;一类目一行平铺(无树层级/无分组头)', () => { it('出厂全收起:只露一级大类(零计数分支不出现),父级徽标=子树命中行数', () => {
const wrapper = mountSidebar() const wrapper = mountSidebar()
const catalog = wrapper.get('.jd-side-catalog') const catalog = wrapper.get('.jd-side-catalog')
const all = catalog.get('.jd-side-all') const all = catalog.get('.jd-side-all')
expect(all.text()).toContain('全部商品') expect(all.text()).toContain('全部商品')
expect(all.text()).toContain('37', '全部商品徽标=5 条计数行求和(7+4+5+9+12)') expect(all.text()).toContain('37', '全部商品徽标=5 条计数行求和(7+4+5+9+12,树外兜底行也算)')
const rows = catalog.findAll('.jd-side-tree .jd-side-row') const rows = catalog.findAll('.jd-side-tree .jd-side-row:not(.jd-side-orphan)')
expect(rows.map((row) => row.findAll('.jd-side-name').at(0)!.text())).toEqual([ expect(rows.map((row) => row.findAll('.jd-side-name').at(0)!.text())).toEqual([
'连衣裙', '服饰内衣',
'短袖连衣裙', '运动户外',
'艺考形体服', ], '默认只露一级:母婴整支 0 行被剪掉,女装/末级都要点开才出来')
'短裤', expect(rows.map((row) => row.find('.jd-side-count').text())).toEqual(['20', '5'],
'已下架历史类目', '一级徽标=整棵子树命中行数(服饰内衣=7+4+9)')
], '按后端给的类目名顺序平铺,一行一个末级类目名')
expect(rows.map((row) => row.find('.jd-side-count').text())).toEqual(['7', '4', '5', '9', '12'],
'每行徽标=该类目的商品数(后端 productCount 原样)')
// 平铺形状:没有层级缩进类、没有箭头、没有「授权树外的类目」分组头、没有展开操作行。
expect(rows.every((row) => row.classes().includes('depth-0'))).toBe(true) expect(rows.every((row) => row.classes().includes('depth-0'))).toBe(true)
expect(catalog.find('.jd-side-arrow').exists()).toBe(false, '平铺列表没有展开箭头') expect(rows.every((row) => row.classes().includes('branch'))).toBe(true, '一级有下级=可展开行')
expect(catalog.find('.jd-side-tree-ops').exists()).toBe(false, '平铺列表没有展开/收起操作行') expect(catalog.findAll('.jd-side-arrow')).toHaveLength(2, '每个有下级的行一个展开箭头')
expect(catalog.text()).not.toContain('授权树外的类目', '不再有树外兜底分组(客户口径:京东分类百分百有)')
wrapper.unmount() wrapper.unmount()
}) })
it('点类目行 emit {name, path: []}(页面按单名集合 IN 下发);选中态按类目名高亮', async () => { it('点箭头只展开/收起(不触发筛选),展开后按层级缩进露出下一级', async () => {
const wrapper = mountSidebar() const wrapper = mountSidebar()
const catalog = wrapper.get('.jd-side-catalog') const catalog = wrapper.get('.jd-side-catalog')
await rowByText(catalog, '连衣裙').trigger('click') const first = catalog.findAll('.jd-side-tree .jd-side-row:not(.jd-side-orphan)')[0]
await first.get('.jd-side-arrow').trigger('click')
await flushPromises() await flushPromises()
expect(wrapper.emitted('select-category')).toEqual([[{ name: '连衣裙', path: [] }]], expect(wrapper.emitted('select-category')).toBeUndefined('点箭头是展开态,不是筛选')
'平铺行不带路径:path 空=单名等值,与本页旧「树外名」同形')
await wrapper.setProps({ selectedCategory: { name: '短裤', path: [] } }) const rows = catalog.findAll('.jd-side-tree .jd-side-row:not(.jd-side-orphan)')
expect(rowByText(catalog, '短裤').classes()).toContain('selected') expect(rows.map((row) => row.findAll('.jd-side-name').at(0)!.text()))
expect(rowByText(catalog, '连衣裙').classes()).not.toContain('selected') .toEqual(['服饰内衣', '女装', '运动户外'], '只展开这一个分支,运动户外不动')
expect(rows[1].classes()).toContain('depth-1')
expect(rows[1].find('.jd-side-count').text()).toBe('20', '二级徽标=自身子树(7+4+9)')
expect(first.get('.jd-side-arrow').attributes('aria-expanded')).toBe('true')
// 再点一次收起:子孙行消失。
await first.get('.jd-side-arrow').trigger('click')
await flushPromises()
expect(catalog.findAll('.jd-side-tree .jd-side-row:not(.jd-side-orphan)')).toHaveLength(2)
wrapper.unmount()
})
it('点一级行 emit 整棵子树的名字集合(父级也能选来批量分类)', async () => {
const wrapper = mountSidebar()
const catalog = wrapper.get('.jd-side-catalog')
await rowByText(catalog, '服饰内衣').trigger('click')
await flushPromises()
expect(wrapper.emitted('select-category')).toEqual([[
{
name: '服饰内衣',
path: ['服饰内衣'],
names: ['服饰内衣', '女装', '连衣裙', '短袖连衣裙', '短裤'],
},
]], 'names=本节点名+全部子孙名(末级为主,父级名兜底),页面按 IN 集合下发')
wrapper.unmount()
})
it('点末级行 emit 单名集合(与旧平铺行同形);选中态按名称+祖先链高亮', async () => {
const wrapper = mountSidebar({
categoryTree: CATEGORY_TREE,
selectedCategory: { name: '短裤', path: ['服饰内衣', '女装', '短裤'] },
})
await flushPromises()
const catalog = wrapper.get('.jd-side-catalog')
const leaf = catalog.findAll('.jd-side-tree .jd-side-row:not(.jd-side-orphan)')
.find((row) => row.text().includes('短裤'))!
expect(leaf.classes()).toContain('selected', '挂载即按选中行展开祖先链')
expect(leaf.classes()).toContain('depth-2')
await leaf.trigger('click')
await flushPromises()
expect(wrapper.emitted('select-category')).toEqual([[
{ name: '短裤', path: ['服饰内衣', '女装', '短裤'], names: ['短裤'] },
]], '末级行单名过滤')
expect(catalog.get('.jd-side-all').classes()).not.toContain('selected', '选了类目就不再是全选态') expect(catalog.get('.jd-side-all').classes()).not.toContain('selected', '选了类目就不再是全选态')
wrapper.unmount() wrapper.unmount()
}) })
it('树里搜不到的历史末级名:单列「平台树外」组,点了按单名过滤(不藏、不冒充树内节点)', async () => {
const wrapper = mountSidebar()
const catalog = wrapper.get('.jd-side-catalog')
expect(catalog.get('.jd-side-group-head').text()).toContain('平台树外')
await rowByText(catalog, '已下架历史类目').trigger('click')
await flushPromises()
expect(wrapper.emitted('select-category')).toEqual([[
{ name: '已下架历史类目', path: [], names: ['已下架历史类目'] },
]])
wrapper.unmount()
})
it('「全部商品」行 emit null(页面清类目筛选重查)', async () => { it('「全部商品」行 emit null(页面清类目筛选重查)', async () => {
const wrapper = mountSidebar() const wrapper = mountSidebar()
const catalog = wrapper.get('.jd-side-catalog') const catalog = wrapper.get('.jd-side-catalog')
@@ -114,11 +204,19 @@ describe('商品目录 Tab(京东平台类目平铺,2026-11-26)', () => {
wrapper.unmount() wrapper.unmount()
}) })
it('挂载即带选中态:对应行直接高亮(平铺无祖先链,无需自动展开)', () => { it('树没上报过(空树)⇒ 退化为末级平铺,行为与上一窗逐字相同', () => {
const wrapper = mountSidebar({ selectedCategory: { name: '已下架历史类目', path: [] } }) const wrapper = mountSidebar({ categoryTree: [] })
const catalog = wrapper.get('.jd-side-catalog') const catalog = wrapper.get('.jd-side-catalog')
expect(rowByText(catalog, '已下架历史类目').classes()).toContain('selected') const rows = catalog.findAll('.jd-side-tree .jd-side-row:not(.jd-side-orphan)')
expect(catalog.get('.jd-side-all').classes()).not.toContain('selected') expect(rows.map((row) => row.findAll('.jd-side-name').at(0)!.text())).toEqual([
'连衣裙',
'短袖连衣裙',
'艺考形体服',
'短裤',
'已下架历史类目',
], '没有树就没有层级概念:计数行按后端顺序平铺')
expect(catalog.find('.jd-side-arrow').exists()).toBe(false, '平铺行没有展开箭头')
expect(catalog.find('.jd-side-group-head').exists()).toBe(false, '没有树也就没有「树外」')
wrapper.unmount() wrapper.unmount()
}) })
}) })
@@ -128,6 +226,7 @@ describe('类目计数未就绪(首帧加载态)', () => {
const wrapper = mount(JdCategorySidebar, { const wrapper = mount(JdCategorySidebar, {
props: { props: {
categoryOptions: CATEGORY_OPTIONS, categoryOptions: CATEGORY_OPTIONS,
categoryTree: CATEGORY_TREE,
categories: CATEGORIES, categories: CATEGORIES,
editable: true, editable: true,
selectedCategory: null, selectedCategory: null,
@@ -142,7 +241,7 @@ describe('类目计数未就绪(首帧加载态)', () => {
wrapper.unmount() wrapper.unmount()
}) })
it('数据到达(就绪)后同一实例切出列表与计数,加载行消失', async () => { it('数据到达(就绪)后同一实例切出层级与计数,加载行消失', async () => {
const wrapper = mount(JdCategorySidebar, { const wrapper = mount(JdCategorySidebar, {
props: { props: {
categoryOptions: [], categoryOptions: [],
@@ -153,18 +252,29 @@ describe('类目计数未就绪(首帧加载态)', () => {
categoriesReady: false, categoriesReady: false,
}, },
}) })
await wrapper.setProps({ categoryOptions: CATEGORY_OPTIONS, categoriesReady: true }) await wrapper.setProps({
categoryOptions: CATEGORY_OPTIONS,
categoryTree: CATEGORY_TREE,
categoriesReady: true,
})
await flushPromises() await flushPromises()
const catalog = wrapper.get('.jd-side-catalog') const catalog = wrapper.get('.jd-side-catalog')
expect(catalog.find('.jd-side-loading').exists()).toBe(false) expect(catalog.find('.jd-side-loading').exists()).toBe(false)
expect(catalog.get('.jd-side-all').text()).toContain('37') expect(catalog.get('.jd-side-all').text()).toContain('37')
expect(catalog.findAll('.jd-side-tree .jd-side-row')).toHaveLength(5) expect(catalog.findAll('.jd-side-tree .jd-side-row:not(.jd-side-orphan)')).toHaveLength(2, '一级两个(默认收起)')
wrapper.unmount() wrapper.unmount()
}) })
it('计数为空(从未采集过)⇒ 空态一句话,不是空白列表', () => { it('计数为空(从未采集过)⇒ 空态一句话,不是空白列表', () => {
const wrapper = mount(JdCategorySidebar, { const wrapper = mount(JdCategorySidebar, {
props: { categoryOptions: [], categories: [], editable: true, selectedCategory: null, selectedGroupId: null }, props: {
categoryOptions: [],
categoryTree: CATEGORY_TREE,
categories: [],
editable: true,
selectedCategory: null,
selectedGroupId: null,
},
}) })
const catalog = wrapper.get('.jd-side-catalog') const catalog = wrapper.get('.jd-side-catalog')
expect(catalog.get('.jd-side-empty').text()).toContain('还没有采集到类目数据') expect(catalog.get('.jd-side-empty').text()).toContain('还没有采集到类目数据')
@@ -57,7 +57,14 @@ const groupApi = vi.hoisted(() => ({
createShopGroup: vi.fn(), createShopGroup: vi.fn(),
})) }))
/** 授权类目树 API(2026-11-26 恢复层级:页面取 `GET /api/jd-shop-category-tree`)。
* 必须 mock——不 mock 就真发请求(jsdom 里静默失败 ⇒ 树恒空 ⇒ 层级用例假绿)。 */
const treeApi = vi.hoisted(() => ({
fetchJdShopCategoryTree: vi.fn(),
}))
vi.mock('@/pages/jd/jd-product-api.ts', () => jdApi) vi.mock('@/pages/jd/jd-product-api.ts', () => jdApi)
vi.mock('@/pages/jd/jd-shop-category-api.ts', () => treeApi)
vi.mock('@/pages/account/shop-group-api.ts', () => groupApi) vi.mock('@/pages/account/shop-group-api.ts', () => groupApi)
vi.mock('@/components/admin-confirm', () => ({ openAdminConfirm: confirmMock })) vi.mock('@/components/admin-confirm', () => ({ openAdminConfirm: confirmMock }))
@@ -129,6 +136,9 @@ beforeEach(() => {
jdApi.fetchJdCategoryScope.mockResolvedValue(singleGroupScope()) jdApi.fetchJdCategoryScope.mockResolvedValue(singleGroupScope())
jdApi.fetchJdProductGroups.mockResolvedValue([]) jdApi.fetchJdProductGroups.mockResolvedValue([])
jdApi.fetchJdProductCategories.mockResolvedValue([]) jdApi.fetchJdProductCategories.mockResolvedValue([])
// 授权类目树:默认「还没上报过」(树空 ⇒ 侧栏退化为末级平铺,保持既有用例的行集不变);
// 层级用例显式给树。
treeApi.fetchJdShopCategoryTree.mockResolvedValue({ nodes: [], shops: [] })
// 店铺名单(v1.7)默认空回执:只有名单用例显式变形。 // 店铺名单(v1.7)默认空回执:只有名单用例显式变形。
jdApi.removeJdGroupShop.mockResolvedValue(undefined) jdApi.removeJdGroupShop.mockResolvedValue(undefined)
jdApi.renameJdGroupShop.mockResolvedValue(undefined) jdApi.renameJdGroupShop.mockResolvedValue(undefined)
@@ -319,55 +329,77 @@ describe('布局:筛选行+工具栏上移顶部通栏(2026-11-21 用户
}) })
}) })
describe('侧栏商品目录(京东平台类目平铺,2026-11-26)', () => { /** 授权树夹具(2026-11-26 恢复层级):与 CATEGORY_OPTIONS 同源,父级徽标=子树命中行数。 */
it('类目行点选=末级类目名等值下发(category+path 空),「全部商品」清选重查', async () => { const CATEGORY_TREE = [
{
name: '服饰内衣',
value: '1',
children: [
{
name: '女装',
value: '11',
children: [
{ name: '连衣裙', value: '111' },
{ name: '艺考形体服', value: '112' },
],
},
],
},
]
describe('侧栏商品目录(京东平台类目层级树,2026-11-26)', () => {
it('页面取授权树画一级/二级;点一级=整棵子树名字集合下发(父级也能选来批量分类)', async () => {
jdApi.fetchJdProductCategories.mockResolvedValue(CATEGORY_OPTIONS) jdApi.fetchJdProductCategories.mockResolvedValue(CATEGORY_OPTIONS)
treeApi.fetchJdShopCategoryTree.mockResolvedValue({ nodes: CATEGORY_TREE, shops: [] })
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 50 }) const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 50 })
expect(jdApi.fetchJdProductCategories).toHaveBeenCalledWith() expect(jdApi.fetchJdProductCategories).toHaveBeenCalledWith()
expect(treeApi.fetchJdShopCategoryTree).toHaveBeenCalled()
const catalog = wrapper.get('.jd-side-catalog') const catalog = wrapper.get('.jd-side-catalog')
// 一类目一行平铺:末级类目名直接点,不再有「一级/二级下钻」与展开箭头。 // 默认收起:只露一级(「服饰内衣」),但有展开箭头;末级要展开才出来。
expect(catalog.find('.jd-side-arrow').exists()).toBe(false, '平铺列表没有展开箭头') expect(catalog.find('.jd-side-arrow').exists()).toBe(true, '有下级的一级行带展开箭头')
expect(catalog.findAll('.jd-side-tree .jd-side-row').length).toBeGreaterThan(0) expect(sideRowBy(catalog, '服饰内衣').find('.jd-side-count').text()).toBe('12',
'一级徽标=子树命中行数(连衣裙 7+艺考形体服 5)')
expect(catalog.text()).toContain('平台树外', '「已下架历史类目」不在树里 ⇒ 进兜底组')
await sideRowBy(catalog, '艺考形体服').trigger('click') await sideRowBy(catalog, '服饰内衣').trigger('click')
await flushPromises() await flushPromises()
const leaf = jdApi.fetchJdProductList.mock.calls.at(-1)![0] const parent = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
expect(leaf).toMatchObject({ category: '艺考形体服', page: 1 }, expect(parent).toMatchObject({ category: '服饰内衣', page: 1 },
'末级类目名等值过滤(后端 category_path IN 单元素集合)') '父级点选:category 存回显名')
expect('categoryPath' in leaf, '父级路径这一层已退役:api 入参不再有 categoryPath').toBe(false) expect(parent.categoryNames).toEqual(['服饰内衣', '女装', '连衣裙', '艺考形体服'],
expect('categoryNames' in leaf, '子树展开集合同样退役:入参不再有 categoryNames').toBe(false) '整棵子树的节点名集合(后端 category_path IN 多值)')
expect(parent.categoryPath).toEqual(['服饰内衣'], '路径只供侧栏展开回显,不参与过滤')
// 点「全部商品」行=清选重查(category 回空、query 层不下发,回第一页)。 // 点「全部商品」行=清选重查(名字与集合一起清干净,不留幽灵谓词)。
const callsBefore = jdApi.fetchJdProductList.mock.calls.length const callsBefore = jdApi.fetchJdProductList.mock.calls.length
await catalog.get('.jd-side-all').trigger('click') await catalog.get('.jd-side-all').trigger('click')
await flushPromises() await flushPromises()
expect(jdApi.fetchJdProductList.mock.calls.length).toBe(callsBefore + 1, '清选也要重查') expect(jdApi.fetchJdProductList.mock.calls.length).toBe(callsBefore + 1, '清选也要重查')
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0].category).toBe('') const cleared = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
expect('categoryPath' in jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toBe(false) expect(cleared.category).toBe('')
expect(cleared.categoryNames).toEqual([])
expect(cleared.categoryPath).toEqual([])
wrapper.unmount() wrapper.unmount()
}) })
it('2026-11-26:商品目录只读京东平台类目,页面不再取授权类目树(/jd-shop-category-tree)', async () => { it('点末级行=单名集合;树未上报(空树)时退化为末级平铺(上一窗行为不变)', async () => {
jdApi.fetchJdProductCategories.mockResolvedValue([ jdApi.fetchJdProductCategories.mockResolvedValue([
{ name: '收纳盒', productCount: 23 }, { name: '收纳盒', productCount: 23 },
{ name: '收纳篮', productCount: 14 }, { name: '收纳篮', productCount: 14 },
]) ])
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 50 }) const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 50 })
// 客户口径「京东分类是百分百有的,京东内分类就不需要」:左栏直接是 category_path // 默认 beforeEach 给的是空树:没有层级,一行一个末级名,点行=单名额。
// 平铺,不再有按店铺上报的授权树、也不再有内置花屿巷快照/树外兜底分组。
const catalog = wrapper.get('.jd-side-catalog') const catalog = wrapper.get('.jd-side-catalog')
expect(catalog.find('.jd-side-arrow').exists()).toBe(false, '没有树就没有展开箭头')
expect(sideRowBy(catalog, '收纳盒').text()).toContain('23') expect(sideRowBy(catalog, '收纳盒').text()).toContain('23')
expect(catalog.text()).not.toContain('授权树外的类目')
expect(catalog.text()).not.toContain('本店无匹配')
await sideRowBy(catalog, '收纳盒').trigger('click') await sideRowBy(catalog, '收纳盒').trigger('click')
await flushPromises() await flushPromises()
const last = jdApi.fetchJdProductList.mock.calls.at(-1)![0] const last = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
expect(last).toMatchObject({ category: '收纳盒', page: 1 }) expect(last).toMatchObject({ category: '收纳盒', page: 1 })
expect('categoryNames' in last, '不再有「页面按树展开的集合」这层:平铺行单名等值').toBe(false) expect(last.categoryNames).toEqual(['收纳盒'], '平铺行按单名集合下发(与父级同一参数面)')
expect('categoryPath' in last, '也不再传类目路径').toBe(false)
wrapper.unmount() wrapper.unmount()
}) })
}) })