feat: 新增拼读都类目管理

This commit is contained in:
2026-09-06 01:29:39 +08:00
parent dc864ea57c
commit 2b5bc02dc8
27 changed files with 1738 additions and 92 deletions
@@ -0,0 +1,26 @@
/**
* 拼多多平台类目(本地落库)API
*/
import { requestClient } from '#/api/request';
import type { PddCatDTO, PddCatVO } from './types';
/** 触发全量同步 */
export async function syncPddCatsApi() {
return requestClient.post<void>('/channel/pdd/cat/sync');
}
/** 同步状态 */
export async function getPddCatSyncStatusApi() {
return requestClient.get<PddCatVO.SyncStatus>('/channel/pdd/cat/sync/status');
}
/** 子类目列表(懒加载树) */
export async function listPddCatChildrenApi(data: PddCatDTO.ChildrenQuery) {
return requestClient.post<PddCatVO.Cat[]>('/channel/pdd/cat/children', data);
}
/** 按名称/路径搜索(跨层级) */
export async function searchPddCatsApi(data: PddCatDTO.SearchQuery) {
return requestClient.post<PddCatVO.Cat[]>('/channel/pdd/cat/search', data);
}
@@ -0,0 +1,2 @@
export * from './apis';
export type * from './types';
@@ -0,0 +1,40 @@
/** 拼多多类目 DTO / VO */
export namespace PddCatDTO {
export interface ChildrenQuery {
/** 父类目;0 或省略为顶级 */
parentCatId?: number;
}
export interface SearchQuery {
keyword: string;
/** 默认 true:仅叶子(可发布) */
leafOnly?: boolean;
/** 默认 50,最大 100 */
limit?: number;
}
}
export namespace PddCatVO {
export interface Cat {
catId: number;
parentCatId?: number;
catName?: string;
level?: number;
leaf?: boolean;
/** 如 1/23/456 */
pathIds?: string;
/** 如 洗护/纸品/抽纸 */
pathNames?: string;
lastSyncTime?: string;
}
export interface SyncStatus {
status?: 'IDLE' | 'RUNNING' | 'SUCCESS' | 'FAILED' | string;
startedAt?: string | null;
finishedAt?: string | null;
lastError?: string | null;
syncedCount?: number | null;
message?: string | null;
}
}
@@ -0,0 +1,418 @@
<script lang="ts" setup>
import type { TreeProps } from 'ant-design-vue';
import type { PddCatVO } from '#/api/channel/pdd/cat';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import {
Alert,
Button,
Input,
Modal,
Space,
Table,
Tag,
Tree,
message,
notification,
} from 'ant-design-vue';
import {
getPddCatSyncStatusApi,
listPddCatChildrenApi,
searchPddCatsApi,
syncPddCatsApi,
} from '#/api/channel/pdd/cat';
import { PermissionGate } from '#/components/permission';
defineOptions({ name: 'PddCatManagement' });
const RefreshIcon = createIconifyIcon('lucide:refresh-cw');
const SearchIcon = createIconifyIcon('lucide:search');
type TreeNode = {
key: number;
title: string;
isLeaf?: boolean;
children?: TreeNode[];
pathNames?: string;
level?: number;
};
const syncStatus = ref<null | PddCatVO.SyncStatus>(null);
const syncing = ref(false);
const treeLoading = ref(false);
const treeData = ref<TreeNode[]>([]);
const rootRows = ref<PddCatVO.Cat[]>([]);
const expandedKeys = ref<number[]>([]);
const searchKeyword = ref('');
const searchLoading = ref(false);
const searchRows = ref<PddCatVO.Cat[]>([]);
let pollTimer: null | ReturnType<typeof setInterval> = null;
const isRunning = computed(() => syncStatus.value?.status === 'RUNNING');
function mapTreeNode(c: PddCatVO.Cat): TreeNode {
// 同步未收尾时 is_leaf 可能尚未标记;先按非叶子懒加载,空子节点再标叶子
return {
key: c.catId,
title: `${c.catName || `类目${c.catId}`}(${c.catId})`,
isLeaf: !!c.leaf,
pathNames: c.pathNames,
level: c.level,
};
}
async function refreshSyncStatus() {
try {
const prev = syncStatus.value?.status;
syncStatus.value = await getPddCatSyncStatusApi();
if (syncStatus.value?.status === 'RUNNING') {
startPoll();
} else {
stopPoll();
if (prev === 'RUNNING' && syncStatus.value?.status === 'SUCCESS') {
await loadRoot();
const n = syncStatus.value.syncedCount ?? 0;
notification.success({
message: '拼多多类目同步完成',
description: `共入库 ${n} 条。发布商品现可使用本地跨层类目搜索;同步进行中或未成功时会自动降级为拼多多接口逐级选择。`,
duration: 10,
});
message.success(`类目同步完成,共 ${n} 条`);
}
}
} catch {
/* 忽略 */
}
}
function startPoll() {
if (pollTimer) return;
pollTimer = setInterval(() => {
void refreshSyncStatus();
}, 2000);
}
function stopPoll() {
if (pollTimer) {
clearInterval(pollTimer);
pollTimer = null;
}
}
async function handleSync() {
await refreshSyncStatus();
if (isRunning.value) {
message.warning('类目同步正在进行中');
return;
}
const hadSuccess = syncStatus.value?.status === 'SUCCESS';
const hasLocalData =
(syncStatus.value?.syncedCount ?? 0) > 0 || rootRows.value.length > 0;
// 已成功过或库内已有数据:全量重同步很慢,先确认
if (hadSuccess || hasLocalData) {
const countHint =
syncStatus.value?.syncedCount != null
? `当前约 ${syncStatus.value.syncedCount} 条`
: rootRows.value.length
? `当前一级类目 ${rootRows.value.length} 个`
: '本地已有类目数据';
Modal.confirm({
title: '确认重新全量同步类目?',
content: `${countHint}。全量同步通常需要较长时间(受拼多多限流影响可能更久)。同步进行中时,发布商品无法使用本地跨层类目搜索,将自动降级为拼多多接口逐级选择。是否仍要重新同步?`,
okText: '重新同步',
okType: 'primary',
cancelText: '取消',
centered: true,
onOk: () => doTriggerSync(),
});
return;
}
await doTriggerSync();
}
async function doTriggerSync() {
syncing.value = true;
try {
await syncPddCatsApi();
message.success(
'已开始同步拼多多类目;同步期间发布商品的类目搜索功能受限',
);
notification.info({
message: '类目同步进行中',
description:
'全量同步耗时较长。期间发布商品暂不可用本地跨层类目搜索,将自动降级为拼多多授权类目逐级加载。',
duration: 8,
});
await refreshSyncStatus();
startPoll();
} catch (e: any) {
message.error(e?.message || '触发同步失败');
} finally {
syncing.value = false;
}
}
async function loadRoot() {
treeLoading.value = true;
try {
const list = await listPddCatChildrenApi({ parentCatId: 0 });
rootRows.value = list;
treeData.value = list.map(mapTreeNode);
expandedKeys.value = [];
} catch (e: any) {
message.error(e?.message || '加载类目失败,请先同步');
rootRows.value = [];
treeData.value = [];
} finally {
treeLoading.value = false;
}
}
const onLoadData: TreeProps['loadData'] = (treeNode) => {
return new Promise<void>((resolve) => {
void (async () => {
const key = Number(treeNode.key);
if (treeNode.dataRef?.children) {
resolve();
return;
}
try {
const children = await listPddCatChildrenApi({ parentCatId: key });
const nodes = children.map(mapTreeNode);
if (treeNode.dataRef) {
// 无子节点则标为叶子,避免展开空白面板
treeNode.dataRef.isLeaf = nodes.length === 0;
treeNode.dataRef.children = nodes;
}
treeData.value = [...treeData.value];
} catch (e: any) {
message.error(e?.message || '加载子类目失败');
} finally {
resolve();
}
})();
});
};
async function handleSearch() {
const kw = searchKeyword.value.trim();
if (!kw) {
searchRows.value = [];
return;
}
searchLoading.value = true;
try {
searchRows.value = await searchPddCatsApi({
keyword: kw,
leafOnly: false,
limit: 80,
});
} catch (e: any) {
message.error(e?.message || '搜索失败');
searchRows.value = [];
} finally {
searchLoading.value = false;
}
}
const rootColumns = [
{ title: '类目ID', dataIndex: 'catId', width: 120 },
{ title: '名称', dataIndex: 'catName', width: 220 },
{ title: '层级', dataIndex: 'level', width: 72 },
{ title: '路径', dataIndex: 'pathNames', ellipsis: true },
];
const searchColumns = [
{ title: '类目ID', dataIndex: 'catId', width: 120 },
{ title: '名称', dataIndex: 'catName', width: 160 },
{ title: '层级', dataIndex: 'level', width: 72 },
{
title: '叶子',
dataIndex: 'leaf',
width: 72,
customRender: ({ text }: { text: boolean }) => (text ? '是' : '否'),
},
{ title: '完整路径', dataIndex: 'pathNames', ellipsis: true },
];
onMounted(async () => {
await refreshSyncStatus();
await loadRoot();
});
onUnmounted(() => stopPoll());
</script>
<template>
<Page
title="拼多多类目"
description="平台标准类目本地缓存;发布商品时可按名称跨层级搜索,无需每次请求拼多多"
>
<div class="space-y-4">
<Alert
type="info"
show-icon
message="类目为拼多多平台级全量树(pdd.goods.cats.get),与店铺授权可发范围无关。发布时仍以平台校验为准。"
/>
<Alert
v-if="isRunning"
type="warning"
show-icon
message="全量同步进行中:触达拼多多限流时会自动等待,进度可能间歇停顿,属正常现象。已入库数据可在本页浏览/搜索;发布商品暂不可用本地跨层搜索,将自动降级为拼多多授权类目接口。"
/>
<div
class="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-200/80 bg-white p-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<div class="min-w-0 text-sm text-slate-600 dark:text-slate-300">
<div class="flex flex-wrap items-center gap-2">
<span class="font-medium text-slate-800 dark:text-slate-100">
同步状态
</span>
<Tag v-if="isRunning" color="processing">同步中</Tag>
<Tag
v-else-if="syncStatus?.status === 'SUCCESS'"
color="success"
>
成功
</Tag>
<Tag
v-else-if="syncStatus?.status === 'FAILED'"
color="error"
>
失败
</Tag>
<Tag v-else color="default">未同步 / 空闲</Tag>
</div>
<p class="mb-0 mt-1 text-xs text-slate-500">
<template v-if="syncStatus?.syncedCount != null">
已入库 {{ syncStatus.syncedCount }} 条
</template>
<template v-if="rootRows.length">
· 一级类目 {{ rootRows.length }} 个
</template>
<template v-if="syncStatus?.startedAt && isRunning">
· 开始于 {{ syncStatus.startedAt }}
</template>
<template v-if="syncStatus?.finishedAt && !isRunning">
· 完成于 {{ syncStatus.finishedAt }}
</template>
<template v-if="syncStatus?.lastError">
· {{ syncStatus.lastError }}
</template>
<template v-if="syncStatus?.message">
· {{ syncStatus.message }}
</template>
</p>
</div>
<Space wrap>
<Button
@click="
() => {
void refreshSyncStatus();
void loadRoot();
}
"
>
<template #icon>
<component :is="RefreshIcon" class="size-4" />
</template>
刷新
</Button>
<PermissionGate code="channel:pdd:cat:sync">
<Button
type="primary"
:loading="syncing || isRunning"
:disabled="isRunning"
@click="handleSync"
>
同步类目
</Button>
</PermissionGate>
</Space>
</div>
<div
class="rounded-xl border border-slate-200/80 bg-white p-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<h3 class="mb-3 text-sm font-semibold text-slate-800 dark:text-slate-100">
一级类目({{ rootRows.length }})
</h3>
<Table
size="small"
row-key="catId"
:loading="treeLoading"
:columns="rootColumns"
:data-source="rootRows"
:pagination="{ pageSize: 20, hideOnSinglePage: true }"
:locale="{ emptyText: isRunning ? '同步中,稍候刷新…' : '暂无数据,请先同步' }"
/>
</div>
<div
class="rounded-xl border border-slate-200/80 bg-white p-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<h3 class="mb-3 text-sm font-semibold text-slate-800 dark:text-slate-100">
类目树浏览
</h3>
<div
v-if="treeData.length"
class="max-h-[420px] min-h-0 overflow-y-auto rounded-lg border border-slate-100 p-2 dark:border-slate-700"
>
<Tree
v-model:expanded-keys="expandedKeys"
:tree-data="treeData"
:load-data="onLoadData"
:show-line="{ showLeafIcon: false }"
/>
</div>
<p
v-else
class="mb-0 text-sm text-slate-500"
>
{{ treeLoading ? '加载中…' : isRunning ? '同步中,稍候刷新…' : '暂无类目数据' }}
</p>
</div>
<div
class="rounded-xl border border-slate-200/80 bg-white p-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<h3 class="mb-3 text-sm font-semibold text-slate-800 dark:text-slate-100">
跨层级搜索
</h3>
<Space wrap class="mb-3">
<Input
v-model:value="searchKeyword"
class="!w-72"
allow-clear
placeholder="类目名称或路径关键词"
@press-enter="handleSearch"
/>
<Button type="primary" :loading="searchLoading" @click="handleSearch">
<template #icon>
<component :is="SearchIcon" class="size-4" />
</template>
搜索
</Button>
</Space>
<Table
size="small"
row-key="catId"
:loading="searchLoading"
:columns="searchColumns"
:data-source="searchRows"
:pagination="{ pageSize: 20, hideOnSinglePage: true }"
:locale="{ emptyText: '输入关键词后搜索' }"
/>
</div>
</div>
</Page>
</template>
@@ -13,6 +13,7 @@ import { useVbenModal } from '@vben/common-ui';
import { PlusOutlined, DeleteOutlined, MinusOutlined } from '@ant-design/icons-vue';
import {
Alert,
Button,
Card,
Cascader,
@@ -42,6 +43,11 @@ import {
listPddPublishParentSpecsApi,
publishPddGoodsApi,
} from '#/api/channel/pdd/goods';
import {
getPddCatSyncStatusApi,
listPddCatChildrenApi,
searchPddCatsApi,
} from '#/api/channel/pdd/cat';
import { getPddShopPageApi } from '#/api/channel/pdd/shop';
import { getProductPageApi } from '#/api/ec/product';
import { getProductSkuPageApi } from '#/api/ec/product/sku';
@@ -204,13 +210,82 @@ const saleProps = computed(() =>
(catTemplate.value?.properties ?? []).filter((p) => p.sale),
);
const rootCatOptions = ref<
{ label?: string; value: number; isLeaf?: boolean; loading?: boolean; children?: any[] }[]
>([]);
type CatCascaderNode = {
label?: string;
value: number;
isLeaf?: boolean;
loading?: boolean;
children?: CatCascaderNode[];
/** 搜索命中时带回完整 path,便于回填 */
pathIds?: string;
};
type DefaultOptionType = { label?: any; value?: any; children?: any[] };
const rootCatOptions = ref<CatCascaderNode[]>([]);
const catsLoading = ref(false);
/** 已按 parent 拉过的类目,避免重复请求 */
const loadedCatParents = ref<Set<number>>(new Set());
/** 本地库同步状态:仅 SUCCESS 走本地树 + 跨层搜索,其余降级拼多多授权类目接口 */
const catSyncStatus = ref<null | string>(null);
const localCatReady = computed(() => catSyncStatus.value === 'SUCCESS');
const catSourceDegraded = computed(() => !localCatReady.value);
/** Cascader 搜索框文案;本地就绪时用于跨层检索 */
const catCascaderSearch = ref('');
/** 本地跨层搜索命中(扁平叶子),非空时临时替换树选项 */
const catSearchHitOptions = ref<CatCascaderNode[]>([]);
const catSearchLoading = ref(false);
let catSearchTimer: undefined | ReturnType<typeof setTimeout>;
/** 选中后展示的完整路径文案 */
const selectedCatPathLabel = ref('');
/**
* 搜索选中的叶子:清空搜索结果后仍挂到 options 上,避免 Cascader 只显示裸 catId。
*/
const pinnedSelectedCat = ref<CatCascaderNode | null>(null);
const displayCatOptions = computed(() => {
if (localCatReady.value && catCascaderSearch.value.trim()) {
return catSearchHitOptions.value;
}
const roots = rootCatOptions.value;
const pinned = pinnedSelectedCat.value;
if (
pinned &&
form.catPath.length === 1 &&
form.catPath[0] === pinned.value &&
!roots.some((r) => r.value === pinned.value)
) {
return [pinned, ...roots];
}
return roots;
});
/** Cascader 输入框展示:优先完整路径文案,避免只剩数字 ID */
function catDisplayRender(info: {
labels: string[];
selectedOptions?: DefaultOptionType[];
}) {
if (selectedCatPathLabel.value) {
return selectedCatPathLabel.value;
}
const labels = (info.labels ?? []).filter(
(l) => l != null && String(l).trim() !== '',
);
if (labels.length) {
return labels.join(' / ');
}
return '';
}
const catDegradeHint = computed(() => {
if (catSyncStatus.value === 'RUNNING') {
return '平台类目同步进行中:暂不可用本地跨层搜索,已降级为拼多多授权类目逐级加载;搜索仅匹配已展开节点';
}
return '本地类目未就绪:已降级为拼多多授权类目逐级加载;搜索仅匹配已展开节点。同步成功后可跨层搜索';
});
const skuSelectOptions = computed(() =>
skuOptions.value.map((s) => ({
label: `${s.productName} / ${s.name}${s.skuCode ? ` (${s.skuCode})` : ''}`,
@@ -218,40 +293,71 @@ const skuSelectOptions = computed(() =>
})),
);
/** 仅在已加载的本地节点中按类目名过滤 */
const catShowSearch: CascaderProps['showSearch'] = {
filter: (inputValue, path) => {
const kw = String(inputValue ?? '')
.trim()
.toLowerCase();
if (!kw) return true;
return path.some((option) =>
String(option.label ?? '')
.toLowerCase()
.includes(kw),
);
},
};
async function refreshCatSyncStatus() {
try {
const s = await getPddCatSyncStatusApi();
catSyncStatus.value = s?.status ?? null;
} catch {
// 无权限或失败时降级拼多多接口
catSyncStatus.value = null;
}
}
/** 展开时按需加载子类目(每个 parent 只请求一次) */
function mapLocalCatNode(c: {
catId: number;
catName?: string;
leaf?: boolean;
}): CatCascaderNode {
return {
label: c.catName,
value: c.catId,
isLeaf: !!c.leaf,
};
}
function mapPopCatNode(c: PddGoodsPublishVO.Cat): CatCascaderNode {
return {
label: c.catName,
value: c.catId,
isLeaf: !!c.leaf,
};
}
async function fetchCatChildren(parentCatId: number): Promise<CatCascaderNode[]> {
if (localCatReady.value) {
const list = await listPddCatChildrenApi({ parentCatId });
return list.map(mapLocalCatNode);
}
if (!form.pddShopId) {
return [];
}
const list = await listPddPublishCatsApi({
pddShopId: form.pddShopId,
parentCatId,
});
return list.map(mapPopCatNode);
}
/** 展开时按需加载子类目(本地库或拼多多接口) */
const catLoadData: CascaderProps['loadData'] = async (selectedOptions) => {
// 跨层搜索结果为扁平叶子,不走懒加载
if (localCatReady.value && catCascaderSearch.value.trim()) {
return;
}
const target = selectedOptions[selectedOptions.length - 1];
if (!target || !form.pddShopId) return;
if (!target) return;
const parentId = Number(target.value);
if (loadedCatParents.value.has(parentId) || target.isLeaf) {
return;
}
target.loading = true;
try {
const children = await listPddPublishCatsApi({
pddShopId: form.pddShopId,
parentCatId: parentId,
});
target.children = children.map((c) => ({
label: c.catName,
value: c.catId,
isLeaf: !!c.leaf,
}));
const children = await fetchCatChildren(parentId);
target.children = children;
// 降级场景:接口未标 leaf 且无子时标叶子,避免空白展开
if (children.length === 0) {
target.isLeaf = true;
}
loadedCatParents.value.add(parentId);
} catch (e: any) {
message.error(e?.message || '加载类目失败');
@@ -260,6 +366,52 @@ const catLoadData: CascaderProps['loadData'] = async (selectedOptions) => {
}
};
/** Cascader 内置搜索:本地跨层时选项已是命中集;降级时仅过滤已加载节点 */
function catCascaderFilter(inputValue: string, path: DefaultOptionType[]) {
if (localCatReady.value && inputValue.trim()) {
return true;
}
const kw = inputValue.trim().toLowerCase();
if (!kw) return true;
return path.some((o) => String(o.label ?? '').toLowerCase().includes(kw));
}
function onCatCascaderSearch(keyword: string) {
catCascaderSearch.value = keyword ?? '';
if (catSearchTimer) clearTimeout(catSearchTimer);
if (!localCatReady.value) {
catSearchHitOptions.value = [];
return;
}
const kw = String(keyword ?? '').trim();
if (!kw) {
catSearchHitOptions.value = [];
catSearchLoading.value = false;
return;
}
catSearchTimer = setTimeout(async () => {
catSearchLoading.value = true;
try {
const list = await searchPddCatsApi({
keyword: kw,
leafOnly: true,
limit: 50,
});
catSearchHitOptions.value = list.map((c) => ({
label: c.pathNames || c.catName || `类目${c.catId}`,
value: c.catId,
isLeaf: true,
pathIds: c.pathIds,
}));
} catch (e: any) {
message.error(e?.message || '搜索类目失败');
catSearchHitOptions.value = [];
} finally {
catSearchLoading.value = false;
}
}, 280);
}
async function loadShops(keyword = '') {
try {
const data = await getPddShopPageApi({
@@ -279,30 +431,65 @@ async function loadShops(keyword = '') {
}
async function loadRootCats() {
if (!form.pddShopId) return;
// 同店已加载过根节点则不再请求
if (loadedCatParents.value.has(0) && rootCatOptions.value.length > 0) {
if (!form.pddShopId) {
rootCatOptions.value = [];
return;
}
catsLoading.value = true;
loadedCatParents.value = new Set();
rootCatOptions.value = [];
catSearchHitOptions.value = [];
catCascaderSearch.value = '';
pinnedSelectedCat.value = null;
try {
const list = await listPddPublishCatsApi({
pddShopId: form.pddShopId,
parentCatId: 0,
});
rootCatOptions.value = list.map((c) => ({
label: c.catName,
value: c.catId,
isLeaf: !!c.leaf,
}));
await refreshCatSyncStatus();
const list = await fetchCatChildren(0);
rootCatOptions.value = list;
loadedCatParents.value.add(0);
} catch (e: any) {
message.error(e?.message || '加载类目失败');
message.error(
e?.message ||
(localCatReady.value
? '加载本地类目失败'
: '加载拼多多授权类目失败'),
);
} finally {
catsLoading.value = false;
}
}
async function applyCatSelection(catId: number, pathIds?: string, pathLabel?: string) {
const path = pathIds
? pathIds
.split('/')
.map((x) => Number(x))
.filter((n) => Number.isFinite(n) && n > 0)
: [catId];
form.catPath = path;
form.catId = catId;
selectedCatPathLabel.value = pathLabel || '';
catTemplate.value = null;
parentSpecs.value = [];
form.goodsPropValues = {};
if (!form.pddShopId || !form.catId) return;
try {
const [tpl, specs] = await Promise.all([
getPddPublishCatTemplateApi({
pddShopId: form.pddShopId,
catId: form.catId,
}),
listPddPublishParentSpecsApi({
pddShopId: form.pddShopId,
catId: form.catId,
}),
]);
catTemplate.value = tpl;
parentSpecs.value = specs ?? [];
} catch (e: any) {
message.error(e?.message || '加载类目模板失败');
}
}
async function loadLogistics() {
if (!form.pddShopId) return;
try {
@@ -383,14 +570,18 @@ watch(
(id) => {
form.catPath = [];
form.catId = undefined;
selectedCatPathLabel.value = '';
form.costTemplateId = undefined;
costTemplateDetail.value = null;
catTemplate.value = null;
parentSpecs.value = [];
rootCatOptions.value = [];
logisticsOptions.value = [];
form.goodsPropValues = {};
catSearchHitOptions.value = [];
catCascaderSearch.value = '';
rootCatOptions.value = [];
loadedCatParents.value = new Set();
pinnedSelectedCat.value = null;
if (!id) return;
void loadRootCats();
void loadLogistics();
@@ -464,44 +655,85 @@ function removeSkuRow(key: number) {
}
async function onCatChange(path: number[]) {
form.catPath = path ?? [];
form.catId = path?.length ? path[path.length - 1] : undefined;
catTemplate.value = null;
parentSpecs.value = [];
form.goodsPropValues = {};
if (!form.pddShopId || !form.catId) return;
const leafOpt = findCascaderNode(rootCatOptions.value, path);
if (leafOpt && leafOpt.isLeaf === false) {
if (!path?.length) {
form.catPath = [];
form.catId = undefined;
selectedCatPathLabel.value = '';
pinnedSelectedCat.value = null;
catTemplate.value = null;
parentSpecs.value = [];
form.goodsPropValues = {};
return;
}
try {
const [tpl, specs] = await Promise.all([
getPddPublishCatTemplateApi({
pddShopId: form.pddShopId,
catId: form.catId,
}),
listPddPublishParentSpecsApi({
pddShopId: form.pddShopId,
catId: form.catId,
}),
]);
catTemplate.value = tpl;
parentSpecs.value = specs ?? [];
} catch (e: any) {
message.error(e?.message || '加载类目模板失败');
const searching =
localCatReady.value && !!catCascaderSearch.value.trim();
const options = searching
? catSearchHitOptions.value
: rootCatOptions.value;
const leafOpt = findCascaderNode(options, path);
if (leafOpt && leafOpt.isLeaf === false) {
form.catPath = path;
form.catId = undefined;
selectedCatPathLabel.value = '';
pinnedSelectedCat.value = null;
catTemplate.value = null;
parentSpecs.value = [];
return;
}
const catId = path[path.length - 1]!;
const hit =
catSearchHitOptions.value.find((o) => o.value === catId) ||
(pinnedSelectedCat.value?.value === catId
? pinnedSelectedCat.value
: undefined);
const pathLabel =
hit?.label != null
? String(hit.label)
: buildCascaderPathLabel(options, path) ||
(leafOpt?.label != null ? String(leafOpt.label) : undefined);
await applyCatSelection(
catId,
hit?.pathIds || path.join('/'),
pathLabel,
);
// 搜索命中为扁平选项:钉住展示节点,Cascader 值用单级 id
if (hit?.pathIds || searching) {
const label = pathLabel || `类目${catId}`;
pinnedSelectedCat.value = {
label,
value: catId,
isLeaf: true,
pathIds: hit?.pathIds,
};
form.catPath = [catId];
} else {
pinnedSelectedCat.value = null;
}
catCascaderSearch.value = '';
catSearchHitOptions.value = [];
}
function buildCascaderPathLabel(
options: CatCascaderNode[],
path: number[],
): string {
const parts: string[] = [];
let nodes = options;
for (const id of path) {
const found = nodes.find((n) => n.value === id);
if (!found) break;
if (found.label) parts.push(String(found.label));
nodes = found.children ?? [];
}
return parts.join(' / ');
}
function findCascaderNode(
options: { value: number; isLeaf?: boolean; children?: any[] }[],
options: CatCascaderNode[],
path: number[],
): { value: number; isLeaf?: boolean } | null {
): CatCascaderNode | null {
let nodes = options;
let found: { value: number; isLeaf?: boolean; children?: any[] } | null =
null;
let found: CatCascaderNode | null = null;
for (const id of path) {
found = nodes.find((n) => n.value === id) ?? null;
if (!found) return null;
@@ -873,6 +1105,7 @@ function resetAll() {
form.goodsDesc = '';
form.catPath = [];
form.catId = undefined;
selectedCatPathLabel.value = '';
form.costTemplateId = undefined;
costTemplateDetail.value = null;
form.marketPriceYuan = undefined;
@@ -887,14 +1120,19 @@ function resetAll() {
catTemplate.value = null;
parentSpecs.value = [];
rootCatOptions.value = [];
catSearchHitOptions.value = [];
catCascaderSearch.value = '';
logisticsOptions.value = [];
loadedCatParents.value = new Set();
pinnedSelectedCat.value = null;
catSyncStatus.value = null;
specIdCache.clear();
}
onBeforeUnmount(() => {
document.removeEventListener('pointerdown', onOverlayPointerDown, true);
clearLocalImages();
if (catSearchTimer) clearTimeout(catSearchTimer);
});
</script>
@@ -951,23 +1189,47 @@ onBeforeUnmount(() => {
/>
</Form.Item>
<Alert
v-if="form.pddShopId && catSourceDegraded"
class="mb-3"
type="warning"
show-icon
:message="catDegradeHint"
/>
<div class="grid grid-cols-2 gap-3">
<Form.Item label="叶子类目" required>
<Cascader
v-model:value="form.catPath"
v-model:search-value="catCascaderSearch"
class="w-full"
:options="rootCatOptions"
:options="displayCatOptions"
:load-data="catLoadData"
:show-search="catShowSearch"
:show-search="{
filter: catCascaderFilter,
limit: 50,
}"
:display-render="catDisplayRender"
change-on-select
:placeholder="
catsLoading
? '类目加载中…'
: '搜索已加载类目,或逐级展开选择'
!form.pddShopId
? '请先选择渠道店铺'
: catsLoading || catSearchLoading
? '类目加载中…'
: localCatReady
? '搜索类目名称或逐级展开选择'
: '逐级展开选择(搜索仅匹配已展开)'
"
:disabled="!form.pddShopId || catsLoading"
@search="onCatCascaderSearch"
@change="(v: any) => onCatChange(v || [])"
/>
<p
v-if="selectedCatPathLabel"
class="mb-0 mt-1 text-xs text-slate-500"
>
已选:{{ selectedCatPathLabel }}
</p>
</Form.Item>
<Form.Item label="运费模板" required>
<Select