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">
/** 京东数据库页左侧栏:
* 双 Tab=商品目录(<b>京东平台类目平铺</b>:后端 `/categories` 的 DISTINCT `category_path`
* 末级类目名+商品数)/店铺分类(当前数据权限分组的分类平铺+计数+新建分类+分类管理入口)。
* 双 Tab=商品目录(<b>京东平台类目层级树</b>:一级/二级/末级可展开,末级名+商品数)/
* 店铺分类(当前数据权限分组的分类平铺+计数+新建分类+分类管理入口)。
*
* 纯展示组件:取数与失败兜底全在页面(props 流入、emit 流出),本组件不发请求、
* 不 import api——mount 测试免 mock;内部状态只有双 Tab 切换与新建输入框。
* 不 import api——mount 测试免 mock;内部状态只有双 Tab 切换、目录展开态与新建输入框。
*
* 2026-11-26 客户口径(「京东分类是百分百有的,京东内分类就不需要」):商品目录改用
* **京东平台类目**,不再依赖按店铺上报的授权类目树 `biz_jd_shop_category_tree`,也不再
* 回落内置快照 `JD_CATEGORY_TREE`(那是 2026-11-16 一家店的历史取证,换店必整树零命中,
* 此前靠「零命中剪枝+树外兜底组」打补丁)。平铺一层后点行=该末级类目名等值过滤,
* 与后端 `p.category_path IN (...)` 单元素集合逐字同形。 */
import { computed, ref } from 'vue'
* 2026-11-26 客户口径(「怎么都没有分类一级二级分类」「管理员要分类时候那么多怎么看」):
* 商品目录=**京麦授权类目真树**(页面取 `GET /api/jd-shop-category-tree`,客户端按店铺
* 上报、服务端并集)× **末级名商品数**(`/api/admin/jd-products/categories`)。层级、计数、
* 零计数剪枝、树外兜底全在纯函数 `jd-category-hierarchy.ts`;本组件只画。
* 没有内置快照树了(那是一家店的历史取证,换店必整树零命中);树空时纯函数退化为平铺,
* 与上一窗行为逐字相同。 */
import { computed, onMounted, ref, watch } from 'vue'
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<{
/** /categories 计数行(京麦末级类目+商品数;页面持有,失败静默回空数组)。 */
categoryOptions: JdProductCategoryOption[]
/** 京麦授权类目树(服务端按店铺上报的并集森林;空数组=还没上报过,退化为末级平铺)。 */
categoryTree?: JdCategoryNode[]
/** 当前数据权限分组的分类(V203 归属口径,带 productCount 徽标;v1.7 每行可带
* shops 店铺名单——铺开渲染店铺行点选过滤,空分类也常驻「添加店铺」入口)。 */
categories: JdProductGroup[]
@@ -24,15 +35,16 @@ const props = withDefaults(defineProps<{
* hover 改名/删除与「添加店铺」入口;「分类管理」入口对所有人渲染(同组普通号只读可看,
* V203,写控件由对话框分档)。 */
editable: boolean
/** 当前类目选中(name+完整名称路径;树外历史名 path 为空数组;null=全部商品)。 */
selectedCategory?: { name: string; path: string[] } | null
/** 当前类目选中(name=回显名;path=一级到本行的名称链,用于挂载即展开;names=实际
* 下发的末级名集合,父级选中时是整棵子树;null=全部商品)。 */
selectedCategory?: { name: string; path: string[]; names?: string[] } | null
/** 当前分类选中 id(null=全部分类)。 */
selectedGroupId?: number | null
/** 当前店铺筛选(v1.7 店铺名单点选;空/缺省=未按店铺过滤)。 */
selectedShopName?: string | null
/** 类目计数行是否已取过(页面 loading 态投影;缺省/true=已就绪)。首帧未就绪时侧栏
* 不画树:否则会先把回落快照整棵树(别店类目、徽标全 0、「全部商品 0」)画出来,计数
* 到达后再收成「本店无匹配」一行——用户肉眼看到一次「过一会变了」的闪变。 */
* 不画树:否则会先画一棵「全部商品 0」的空树,计数到达后再跳成有数据——用户肉眼
* 看到一次「过一会变了」的闪变。 */
categoriesReady?: boolean
}>(), {
// Vue 的 Boolean prop 缺省会被强转成 false(不看 TS 可选性):不显式给默认值,
@@ -41,9 +53,10 @@ const props = withDefaults(defineProps<{
})
const emit = defineEmits<{
/** 选类目:京东平台类目末级名,path 恒为空数组(页面按单名集合 IN 下发);
/** 选类目:末级行 = 单名;一级/二级行 = 整棵子树的末级名集合(`names`,页面直接
* 序列化成后端 `category` 多值 IN)。`path` 只用于页面回显展开,不参与过滤。
* 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,回全部分类)。 */
(event: 'select-group', id: number | null): void
/** 选店铺(v1.7 名单点选):分类+店铺名成对下发(点店铺=该分类归属 ∩ 该店铺,
@@ -69,30 +82,82 @@ const emit = defineEmits<{
/** 左 Tab 内置展示态:出厂停在「商品目录」(首屏主筛选面)。 */
const activeTab = ref<'catalog' | 'custom'>('catalog')
// ---------------- 商品目录(京东平台类目平铺) ----------------
// ---------------- 商品目录(京东平台类目层级树) ----------------
/** 类目计数就绪(页面首帧未回时只留加载行,总数显示「—」)。 */
const catalogReady = computed(() => props.categoriesReady !== false)
/** 「全部商品」徽标=全部计数行求和(有类目名的商品总数;无类目名的行不在任何类目筛选的
* 命中集里,不计进任何徽标)。 */
const totalCount = computed(() =>
(props.categoryOptions ?? []).reduce((sum, row) => sum + (row.productCount || 0), 0))
/** 层级 + 计数 + 树外兜底:口径全部在纯函数里(`jd-category-hierarchy.ts`,node --test 直测),
* 本组件只负责画与展开态。树没上报过时纯函数自己退化为平铺,行为与上一窗逐字相同。 */
const catalog = computed(() =>
buildJdCatalogTree(props.categoryTree ?? [], props.categoryOptions ?? []))
/** 商品目录行:后端 `/categories` 已按类目名升序 DISTINCT,这里只归一脏数据
* (空名/负计数),一列平铺——没有树、没有展开折叠、没有「树外兜底」分组。 */
const catalogRows = computed(() =>
(props.categoryOptions ?? [])
.filter((row) => !!row.name && !!row.name.trim())
.map((row) => ({ name: row.name, productCount: row.productCount || 0 })))
/** 「全部商品」徽标=全部计数行按名字去重求和(同名跨支不重复计,见纯函数口径 1)。 */
const totalCount = computed(() => catalog.value.totalCount)
/** 点一行=按该末级类目名等值过滤(path 空数组,页面按单名集合下发,不静默丢筛选)。 */
function pickCatalogRow(name: string): void {
emit('select-category', { name, path: [] })
/** 展开态(行键集合):默认全收起——一级之下先让管理员看清有哪些大类,别一进来四百行。 */
const expandedKeys = ref<string[]>([])
/** 可见行(折叠节点的子孙不进列表)。 */
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
// ---------------- 店铺分类 Tab(当前分组分类平铺+店铺名单 v1.7) ----------------
@@ -190,8 +255,9 @@ function cancelShopRename(): void {
>店铺分类</button>
</div>
<!-- 商品目录(2026-11-26):全部商品 + 京东平台类目平铺(category_path 末级名+计数)。
不再依赖授权类目树/店铺内分类——客户口径「京东分类是百分百有的,京东内分类不需要」。 -->
<!-- 商品目录(2026-11-26 客户口径「怎么都没有分类一级二级分类」):全部商品 + 京麦
授权类目**层级树**(一级/二级/末级可展开,末级名+该节点商品数)。树空=退化为
末级平铺(上一窗行为)。 -->
<div v-show="activeTab === 'catalog'" class="jd-sidebar-body jd-side-catalog">
<button
type="button"
@@ -205,20 +271,52 @@ function cancelShopRename(): void {
<!-- 类目计数未就绪(页面首帧):只留一行加载提示,不画列表(先画空列表再跳成有数据会闪变)。 -->
<p v-if="!catalogReady" class="jd-side-loading">类目加载中…</p>
<div v-else class="jd-side-tree">
<button
v-for="row in catalogRows"
:key="row.name"
type="button"
class="jd-side-row depth-0"
:class="{ selected: isSelectedCatalogRow(row.name) }"
:title="row.name"
@click="pickCatalogRow(row.name)"
<!-- 层级行(div role=button:行内要嵌展开箭头——button 嵌 button 非法 HTML)。
有子级=一级/二级:点名字按整棵子树过滤,点箭头只展开/收起;末级=单名过滤。 -->
<div
v-for="row in visibleCatalogRows"
:key="row.key"
class="jd-side-row"
:class="[`depth-${row.depth}`, { selected: isSelectedCatalogRow(row), branch: !row.isLeaf }]"
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-count">{{ row.productCount }}</span>
</button>
<p v-if="!catalogRows.length" class="jd-side-empty">
</div>
<!-- 树外兜底:授权树里搜不到的历史末级名(别店未上报 / 京麦改过类目体系)。
不藏——藏了这些商品就点不到;也不冒充树内节点,单列一组说清来路。 -->
<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>
</div>
@@ -445,7 +543,45 @@ function cancelShopRename(): void {
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-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 {
width: 14px;
@@ -46,6 +46,8 @@ import {
JD_PRODUCT_PAGE_SIZE_OPTIONS,
} from './jd-product-filter.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 JdProductCard from './JdProductCard.vue'
import JdProductDetailModal from './JdProductDetailModal.vue'
@@ -97,9 +99,12 @@ const groupOptions = ref<JdProductGroup[]>([])
/** 类目计数行(京麦末级类目+商品数):侧栏商品目录树的徽标数据源;失败静默回空。 */
const categoryOptions = ref<JdProductCategoryOption[]>([])
/** 类目计数是否已取过(成功或失败回空都算就绪):侧栏据此区分「还没到」与「确实没有」,
* 首帧未就绪时不画树——否则先把回落快照的别店类目整棵树(徽标全 0、「全部商品 0」)
* 画出来,计数到达后再收成「本店无匹配」一行,用户会看到一次莫名的闪变。 */
* 首帧未就绪时不画树——否则先画一棵「全部商品 0」的空树,计数到达后再跳成有数据,
* 用户会看到一次莫名的闪变。 */
const categoryOptionsReady = ref(false)
/** 京麦授权类目树(服务端按店铺上报的并集森林):侧栏一级/二级层级的骨架;失败静默回空
* (空树=侧栏退化为末级平铺,不会整块空掉)。 */
const categoryTree = ref<JdCategoryNode[]>([])
const detailItem = ref<JdProductItem | null>(null)
const detailVisible = ref(false)
/** 归类对话框(2026-17 替代下线的店铺分类弹窗,工具栏「归入分类」打开)。 */
@@ -125,9 +130,16 @@ const canManageCategories = computed(() => currentGroupOption.value?.editable ==
* 弹窗右栏的勾选面 ⇒ 勾选面对「本组可写」放开,否则管理人员没有归类入口。 */
const hasSelection = computed(() => canWriteProducts.value || canManageCategories.value)
/** 侧栏选中回显:类目(京东平台末级类目名;path 恒空——平铺列表没有层级)与分类 id。 */
/** 侧栏选中回显:类目(节点名+一级到本行的名称链,侧栏据此展开祖先)与分类 id。
* names(实际下发的末级名集合)也带上——侧栏只把它原样透传,不再自己算。 */
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 id = Number.parseInt(filter.groupId, 10)
return Number.isFinite(id) && id > 0 ? id : null
@@ -166,8 +178,12 @@ const activeFilterChips = computed(() => {
* 左栏「商品目录」=后端 `/categories` 的 DISTINCT `category_path`(京麦末级类目名+计数),
* 点一行=按该末级类目名**等值**过滤(后端 `p.category_path IN (...)`,单元素集合);
* 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 || ''
// 名称链只喂回显展开;过滤值看 names(父级点选=整棵子树的末级名集合)。清选时两者一起清,
// 否则会留下一条「名字已清、集合还在」的幽灵谓词。
filter.categoryPath = value?.path ?? []
filter.categoryNames = value?.names ?? []
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 走,
* 误跨组批量归类由归类对话框里的组名标注防住。 */
@@ -466,6 +493,8 @@ async function load(): Promise<void> {
pageSize: pageSize.value,
keyword: filter.keyword,
category: filter.category,
categoryPath: filter.categoryPath ?? [],
categoryNames: filter.categoryNames ?? [],
shopName: filter.shopName,
groupId: filter.groupId,
classified: filter.classified,
@@ -642,6 +671,8 @@ onMounted(async () => {
// 不要先发一条不带 owner_group_id 的列表请求再补,两次请求会落在不同默认组上)。
await loadCategoryScope()
void loadCategoryOptions()
// 授权树与计数行并行(互不依赖):侧栏拿到两份都齐才画得出层级,任何一路慢都不挡首屏行集。
void loadCategoryTree()
await load()
})
</script>
@@ -835,6 +866,7 @@ onMounted(async () => {
取数在页面,侧栏纯展示。 -->
<JdCategorySidebar
:category-options="categoryOptions"
:category-tree="categoryTree"
:categories="groupOptions"
:editable="canManageCategories"
: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 ?? '',
category: params.category ?? '',
categoryPath: params.categoryPath ?? [],
categoryNames: params.categoryNames ?? [],
shopName: params.shopName ?? '',
groupId: params.groupId ?? '',
classified: (params.classified ?? '') as '' | 'classified' | 'ungrouped',
@@ -46,11 +46,17 @@ export interface JdProductFilterState {
/** 合并搜索词(v1.7 对齐原型:一个框同时搜商品编码与标题,OR 语义在后端 SQL)。
* 旧 productCode/titleKeyword 两框随 v1.7 前端下线(后端参数保留兼容在飞请求)。 */
keyword: string
/** 类目(京麦末级类目名=后端 `category_path` DISTINCT 值;选项来自侧栏商品目录平铺),
* 空串=全部类目。2026-11-26 客户口径「京东分类是百分百有的,京东内分类就不需要」:
* 只按末级类目名等值过滤,不再有「父级点选→子树展开集合」这一层(旧 categoryPath/
* categoryNames 两个字段随内置花屿巷快照树一并退役)。 */
/** 类目(回显用的节点名:末级名=`category_path` 词表,或一级/二级的父级名;空串=全部)。
* 真正的过滤值在 `categoryNames`,这里只喂芯片与选中态显示。 */
category: string
/** 选中节点的名称路径(从一级到本节点、含自身;空=「全部商品」)。
* 只用于「挂载即展开祖先链露出选中行」,不参与过滤。 */
categoryPath?: string[]
/** 选中节点展开好的末级类目名集合(后端 `p.category_path IN (...)`):末级行=单元素、
* 父级行=整棵子树的末级名(2026-11-18 客户口径「一级/二级类目也要能选来搜索」)。
* 2026-11-26 随商品目录层级树恢复:展开在**选中那一刻**按当前生效授权树算好放这里,
* 纯函数层不持有树——树换版也不会让一个旧选中悄悄变成另一批类目。 */
categoryNames?: string[]
/** 店铺名(v1.7 店铺名单维度:侧栏点店铺行下发,精确 eq;空串不限)。 */
shopName: string
/** 分类 id 文本(侧栏店铺分类 Tab 里那一行),空串=全部分类。 */
@@ -79,6 +85,8 @@ export function createJdProductFilterState(): JdProductFilterState {
return {
keyword: '',
category: '',
categoryPath: [],
categoryNames: [],
shopName: '',
groupId: '',
classified: JD_PRODUCT_DEFAULT_CLASSIFIED,
@@ -135,6 +143,9 @@ export interface JdProductListParams {
pageSize: number
keyword?: string
category?: string
/** 选中节点路径与展开好的末级名集合(见 JdProductFilterState;父级点选走 categoryNames)。 */
categoryPath?: string[]
categoryNames?: string[]
shopName?: string
groupId?: string
/** 分类状态快筛(''/缺省=全部,'classified'/'ungrouped' 见 JdProductFilterState)。 */
@@ -156,10 +167,15 @@ function toJdProductFilterQuery(state: JdProductFilterState): Omit<JdProductQuer
const keyword = (state.keyword || '').trim()
if (keyword) query.keyword = keyword
const category = (state.category || '').trim()
if (category) {
// 末级类目名等值:单元素集合下发,后端 `p.category_path IN (...)` 单值等价 eq。
// 2026-11-26 起左栏商品目录=京东平台类目平铺(category_path DISTINCT),
// 不再有「父级点选→子树展开集合」这条链。
const categoryNames = (state.categoryNames ?? [])
.map((name) => (name ?? '').trim())
.filter((name) => !!name)
if (categoryNames.length) {
// 父级点选:按选中那一刻展开好的子树末级名集合下发(后端 `p.category_path IN (...)`
// 多值)。单元素时与末级点选逐字同形,两条路不各写一套参数。
query.category = [...new Set(categoryNames)]
} else if (category) {
// 兜底:只有节点名(树未就绪/树外行/buildJdCatalogTree 之前的旧调用点)=单名等值。
query.category = [category]
}
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 }
}