Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 472a7e001b | |||
| 4de78adfc7 | |||
| 96afb685c2 | |||
| 83e9bbe71a |
@@ -5,26 +5,31 @@
|
||||
*
|
||||
* 交互(京麦真机同款,2026-11-16 面板逐级点开取证):面板按点亮路径动态出栏——第一栏
|
||||
* 一级(3 个)、后续栏=点亮节点的 children(最深 4 栏);**非末级行点击=下钻**(推进
|
||||
* 路径)、**末级行(children 空)点击=选中**(radio 蓝,emit change→按 category_path
|
||||
* 等值过滤,后端契约零改动)。搜索框搜**树内全部末级**(名称或路径命中,行 title 带
|
||||
* 全路径);树外命中(已落库但京麦类目体系变更后的历史名)从 options 兜底段选,语义
|
||||
* 同旧版第三栏。「全部类目」行=清选;触发框已选时出 × 清除;面板外点透明遮罩关闭。
|
||||
* 路径)、**末级行(children 空)点击=选中**;2026-11-18 客户口径「一级/二级类目也要能
|
||||
* 选来搜索」:**非末级行的圆点点击=选中该节点**(emit change 带名称路径,页面按子树
|
||||
* 展开类目名集合下发,后端 IN 过滤;行体/箭头仍下钻)。搜索框搜**树内全部层级**
|
||||
* (一级/二级/末级都可选,名称或路径命中,行 title 带全路径);树外命中(已落库但京麦
|
||||
* 类目体系变更后的历史名)从 options 兜底段选,语义同旧版第三栏。「全部类目」行=清选;
|
||||
* 触发框已选时出 × 清除;面板外点透明遮罩关闭。
|
||||
* 零依赖自绘(radio 圆点/箭头都是 CSS),无 element 依赖。 */
|
||||
import { computed, nextTick, ref, watch } from 'vue'
|
||||
import {
|
||||
jdCategoryChildren,
|
||||
jdCategoryRoots,
|
||||
jdCategorySearchLeaves,
|
||||
jdCategorySearchNodes,
|
||||
type JdCategoryNode,
|
||||
} from './jd-category-tree.ts'
|
||||
import { clampPanelLeftX } from './jd-category-cascader-position.ts'
|
||||
|
||||
const props = defineProps<{
|
||||
/** 已落库末级类目全集(/categories 现算,页面传入)——只作**树外兜底**(搜索无树内
|
||||
/** 已落库类目全集(/categories 现算,页面传入)——只作**树外兜底**(搜索无树内
|
||||
* 命中时列出「已落库类目(树外历史)」段),不再默认铺第三栏。 */
|
||||
options?: { name: string; productCount: number }[]
|
||||
/** 当前选中末级类目名;'' = 全部类目。 */
|
||||
/** 当前选中类目名(末级或父级);'' = 全部类目。 */
|
||||
modelValue: string
|
||||
/** 当前选中节点的名称路径(从一级起);空/缺省=末级按名等值或树外行。
|
||||
* 2026-11-18 一级/二级可选中:同名跨支(吊带/背心等)靠路径区分选中态回显。 */
|
||||
selectedPath?: string[]
|
||||
groups?: { id: number; name: string; productCount: number }[]
|
||||
groupId?: string
|
||||
createVersion?: number
|
||||
@@ -33,7 +38,8 @@ const props = defineProps<{
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
(event: 'change', value: string): void
|
||||
/** (类目名, 节点名称路径):末级/父级选中都带路径;树外兜底行与清选带 []。 */
|
||||
(event: 'change', value: string, path: string[]): void
|
||||
(event: 'group', value: string): void
|
||||
(event: 'create-group', value: string): void
|
||||
(event: 'delete-group', id: number): void
|
||||
@@ -74,9 +80,10 @@ function reposition(): void {
|
||||
}
|
||||
|
||||
const roots = jdCategoryRoots()
|
||||
/** 树内全部末级名集合(判定 options 哪些是「树外历史」)。 */
|
||||
const treeLeafNames = new Set(
|
||||
jdCategorySearchLeaves('').map((leaf) => leaf.name),
|
||||
/** 树内全部节点名集合(含非末级;判定 options 哪些是「树外历史」——11-18 起父级名
|
||||
* 也可选中过滤,历史行名只要树内有任何同名节点就走树内行,不再重复铺兜底段)。 */
|
||||
const treeNodeNames = new Set(
|
||||
jdCategorySearchNodes('').map((node) => node.name),
|
||||
)
|
||||
|
||||
/** 面板各栏内容:第 0 栏一级,第 i+1 栏=点亮路径前 i+1 个的 children(路径推进到
|
||||
@@ -91,12 +98,12 @@ const columns = computed<JdCategoryNode[][]>(() => {
|
||||
return cols
|
||||
})
|
||||
|
||||
/** 搜索激活=搜索词非空:面板切换成扁平末级结果列表。 */
|
||||
/** 搜索激活=搜索词非空:面板切换成扁平结果列表(2026-11-18 起含一级/二级)。 */
|
||||
const searching = computed(() => searchText.value.trim().length > 0)
|
||||
|
||||
/** 树内命中末级(名称或路径段命中)。 */
|
||||
const searchLeaves = computed(() =>
|
||||
searching.value ? jdCategorySearchLeaves(searchText.value) : [],
|
||||
/** 树内命中节点(全层级;名称或路径段命中)。 */
|
||||
const searchNodes = computed(() =>
|
||||
searching.value ? jdCategorySearchNodes(searchText.value) : [],
|
||||
)
|
||||
|
||||
/** 树外兜底:options 里不在树名集的行按搜索词过滤(历史行仍可选中过滤)。 */
|
||||
@@ -104,7 +111,7 @@ const fallbackOptions = computed(() => {
|
||||
if (!searching.value) return []
|
||||
const keyword = searchText.value.trim().toLowerCase()
|
||||
return (props.options ?? [])
|
||||
.filter((option) => !treeLeafNames.has(option.name))
|
||||
.filter((option) => !treeNodeNames.has(option.name))
|
||||
.filter((option) => option.name.toLowerCase().includes(keyword))
|
||||
})
|
||||
|
||||
@@ -132,29 +139,46 @@ function close(): void {
|
||||
activePath.value = []
|
||||
}
|
||||
|
||||
/** 非末级行点击=下钻;末级行点击=选中并收面板。 */
|
||||
/** 栏内节点的完整名称路径(下钻态:已点亮前缀+本节点名)。 */
|
||||
function nodePath(node: JdCategoryNode, depth: number): string[] {
|
||||
return [...activePath.value.slice(0, depth), node.name]
|
||||
}
|
||||
|
||||
/** 选中态回显按**路径**比对(同名跨支不串);树外兜底行没有路径,按名比对。 */
|
||||
function isSelected(path: string[]): boolean {
|
||||
const current = props.selectedPath ?? []
|
||||
return current.length === path.length && current.every((segment, i) => segment === path[i])
|
||||
}
|
||||
|
||||
/** 非末级行体/箭头点击=下钻;末级行点击=选中(带路径)。 */
|
||||
function pick(node: JdCategoryNode, depth: number): void {
|
||||
if (node.children && node.children.length) {
|
||||
activePath.value = [...activePath.value.slice(0, depth), node.name]
|
||||
activePath.value = nodePath(node, depth)
|
||||
return
|
||||
}
|
||||
emit('change', node.name)
|
||||
selectNode(node, depth)
|
||||
}
|
||||
|
||||
/** 圆点点击(任意层级)=选中该节点并收面板——2026-11-18 一级/二级类目可选中,
|
||||
* 页面按 jdCategoryNamesUnder(path) 展开子树类目名集合下发。 */
|
||||
function selectNode(node: JdCategoryNode, depth: number): void {
|
||||
emit('change', node.name, nodePath(node, depth))
|
||||
close()
|
||||
}
|
||||
|
||||
function pickAll(): void {
|
||||
emit('change', '')
|
||||
emit('change', '', [])
|
||||
close()
|
||||
}
|
||||
|
||||
/** 搜索结果行点击(树内末级或树外兜底行)=按名选中。 */
|
||||
function pickName(name: string): void {
|
||||
emit('change', name)
|
||||
/** 搜索结果行点击:树内行(含一级/二级)按路径选中;树外兜底行按名选中(path 空)。 */
|
||||
function pickName(name: string, path: string[]): void {
|
||||
emit('change', name, path)
|
||||
close()
|
||||
}
|
||||
|
||||
function clear(): void {
|
||||
emit('change', '')
|
||||
emit('change', '', [])
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -191,33 +215,34 @@ function clear(): void {
|
||||
<button type="button" :aria-label="`删除分类 ${group.name}`" @click.stop="emit('delete-group', group.id)">删除</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 搜索态:树内末级命中+树外兜底段(扁平列表,行 title 带全路径)。 -->
|
||||
<!-- 搜索态:树内全层级命中(一级/二级/末级都可点选)+树外兜底段(扁平列表,行 title 带全路径)。 -->
|
||||
<template v-if="searching">
|
||||
<div class="cat-col cat-col-search">
|
||||
<div class="cat-search-row"><input v-model="searchText" type="text" class="cat-search" placeholder="搜索类目" /></div>
|
||||
<template v-if="searchLeaves.length || fallbackOptions.length">
|
||||
<template v-if="searchNodes.length || fallbackOptions.length">
|
||||
<div
|
||||
v-for="leaf in searchLeaves"
|
||||
:key="`tree-${leaf.path.join('/')}`"
|
||||
v-for="node in searchNodes"
|
||||
:key="`tree-${node.path.join('/')}`"
|
||||
class="cat-row"
|
||||
:class="{ active: modelValue === leaf.name }"
|
||||
:title="leaf.path.join(' > ')"
|
||||
@click="pickName(leaf.name)"
|
||||
:class="{ active: isSelected(node.path) }"
|
||||
:title="node.leaf ? node.path.join(' > ') : `${node.path.join(' > ')}(含下级,选中按整棵子树筛选)`"
|
||||
@click="pickName(node.name, node.path)"
|
||||
>
|
||||
<span class="cat-dot" :class="{ on: modelValue === leaf.name }" aria-hidden="true"></span>
|
||||
<span class="cat-name">{{ leaf.name }}</span>
|
||||
<span class="cat-path">{{ leaf.path.slice(0, -1).join(' › ') }}</span>
|
||||
<span class="cat-dot" :class="{ on: isSelected(node.path) }" aria-hidden="true"></span>
|
||||
<span class="cat-name">{{ node.name }}</span>
|
||||
<span v-if="!node.leaf" class="cat-arrow" aria-hidden="true">›</span>
|
||||
<span class="cat-path">{{ node.path.slice(0, -1).join(' › ') }}</span>
|
||||
</div>
|
||||
<div v-if="fallbackOptions.length" class="cat-seg">已落库类目(树外历史)</div>
|
||||
<div
|
||||
v-for="option in fallbackOptions"
|
||||
:key="`db-${option.name}`"
|
||||
class="cat-row"
|
||||
:class="{ active: modelValue === option.name }"
|
||||
:class="{ active: modelValue === option.name && !(selectedPath && selectedPath.length) }"
|
||||
:title="option.name"
|
||||
@click="pickName(option.name)"
|
||||
@click="pickName(option.name, [])"
|
||||
>
|
||||
<span class="cat-dot" :class="{ on: modelValue === option.name }" aria-hidden="true"></span>
|
||||
<span class="cat-dot" :class="{ on: modelValue === option.name && !(selectedPath && selectedPath.length) }" aria-hidden="true"></span>
|
||||
<span class="cat-name">{{ option.name }}</span>
|
||||
<span class="cat-count">{{ option.productCount }}</span>
|
||||
</div>
|
||||
@@ -250,11 +275,17 @@ function clear(): void {
|
||||
v-for="node in col"
|
||||
:key="`${depth}-${node.name}`"
|
||||
class="cat-row"
|
||||
:class="{ active: activePath[depth] === node.name || (depth === 0 && modelValue === node.name) }"
|
||||
:title="node.name"
|
||||
:class="{ active: activePath[depth] === node.name || isSelected(nodePath(node, depth)) }"
|
||||
:title="node.children && node.children.length ? `${node.name}(点行下钻,点圆点选中整棵子树)` : node.name"
|
||||
@click="pick(node, depth)"
|
||||
>
|
||||
<span class="cat-dot" aria-hidden="true"></span>
|
||||
<span
|
||||
class="cat-dot"
|
||||
:class="{ on: isSelected(nodePath(node, depth)) }"
|
||||
role="button"
|
||||
:aria-label="`选中 ${node.name}`"
|
||||
@click.stop="selectNode(node, depth)"
|
||||
></span>
|
||||
<span class="cat-name">{{ node.name }}</span>
|
||||
<span v-if="node.children && node.children.length" class="cat-arrow" aria-hidden="true">›</span>
|
||||
</div>
|
||||
@@ -273,14 +304,16 @@ function clear(): void {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
}
|
||||
/* 触发框像素对齐页面 .form-group select(42 高/9 圆角/#cbd9e6 边框/#f8fbfd 底)。 */
|
||||
/* 触发框像素对齐筛选行实际渲染高度(2026-11-18 客户「输入框高了一些」):
|
||||
main.css 全局密度收口把 .form-group input/el-select/.btn 压到 34 高,自绘 button
|
||||
不在收口选择器清单里,这里同值对齐(34 高/5x10 padding/9 圆角/#cbd9e6 边框/#f8fbfd 底)。 */
|
||||
.cat-trigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
width: 100%;
|
||||
min-height: 42px;
|
||||
padding: 8px 12px;
|
||||
min-height: 34px;
|
||||
padding: 5px 10px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
|
||||
@@ -210,6 +210,7 @@ async function load(): Promise<void> {
|
||||
productCode: filter.productCode,
|
||||
titleKeyword: filter.titleKeyword,
|
||||
category: filter.category,
|
||||
categoryPath: filter.categoryPath,
|
||||
groupId: filter.groupId,
|
||||
classified: filter.classified,
|
||||
ownerGroupId: ownerGroupId.value,
|
||||
@@ -235,10 +236,12 @@ function apply(): void {
|
||||
void load()
|
||||
}
|
||||
|
||||
/** 类目级联面板点末级即查:选完立刻按该类目过滤刷新(回第一页),同分组下拉口径;
|
||||
* 点「全部类目」/触发框 × = 清选重查。 */
|
||||
function onCategoryPicked(name: string): void {
|
||||
/** 类目级联面板选中即查:选完立刻按该类目过滤刷新(回第一页),同分组下拉口径;
|
||||
* 点「全部类目」/触发框 × = 清选重查。2026-11-18 一级/二级类目可选中:path 非空时
|
||||
* 序列化按子树展开类目名集合下发(后端 IN),末级/树外行 path 空=单名等值旧形状。 */
|
||||
function onCategoryPicked(name: string, path: string[]): void {
|
||||
filter.category = name
|
||||
filter.categoryPath = path
|
||||
apply()
|
||||
}
|
||||
|
||||
@@ -368,11 +371,13 @@ onMounted(async () => {
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>类目</label>
|
||||
<!-- 类目(京麦末级类目)京麦同款级联面板(2026-11-16 客户口径):一/二级为静态导航
|
||||
(采集链无层级数据),第三栏已落库末级+搜索,点行选中即查(回第一页)。 -->
|
||||
<!-- 类目(京麦授权类目树)京麦同款级联面板(2026-11-16 真树取证):点行下钻、
|
||||
末级点行选中;2026-11-18 客户口径「一级/二级也要能选来搜索」——任意层级点
|
||||
圆点选中,序列化按子树展开类目名集合下发(后端 IN),选中即查(回第一页)。 -->
|
||||
<JdCategoryCascader
|
||||
:options="categoryOptions"
|
||||
:model-value="filter.category"
|
||||
:selected-path="filter.categoryPath"
|
||||
tree-only
|
||||
@change="onCategoryPicked"
|
||||
/>
|
||||
|
||||
@@ -85,3 +85,71 @@ export function jdCategorySearchLeaves(keyword: string): JdCategoryLeafRef[] {
|
||||
leaf.path.some((segment) => segment.toLowerCase().includes(needle)),
|
||||
)
|
||||
}
|
||||
|
||||
/** 全树节点引用(含非末级)——2026-11-18 客户口径「一级/二级类目也要能选来搜索」:
|
||||
* 搜索面板从"只铺末级"扩成"铺全部层级",非末级行可选中=按子树展开集合过滤。 */
|
||||
export interface JdCategoryNodeRef {
|
||||
name: string
|
||||
value: string
|
||||
/** 从一级到本节点的名称路径(选中态回显与子树展开都按它定位)。 */
|
||||
path: string[]
|
||||
/** children 缺省/空=末级(落库 category_path 直接等值命中)。 */
|
||||
leaf: boolean
|
||||
}
|
||||
|
||||
export function jdCategoryAllNodes(): JdCategoryNodeRef[] {
|
||||
const out: JdCategoryNodeRef[] = []
|
||||
const walk = (nodes: JdCategoryNode[], prefix: string[]): void => {
|
||||
for (const node of nodes) {
|
||||
const path = [...prefix, node.name]
|
||||
const hasChildren = !!node.children && node.children.length > 0
|
||||
out.push({ name: node.name, value: node.value, path, leaf: !hasChildren })
|
||||
if (hasChildren) walk(node.children as JdCategoryNode[], path)
|
||||
}
|
||||
}
|
||||
walk(JD_CATEGORY_TREE, [])
|
||||
return out
|
||||
}
|
||||
|
||||
/** 全树节点按关键词过滤:名称或路径任一段命中(大小写不敏感 includes)。 */
|
||||
export function jdCategorySearchNodes(keyword: string): JdCategoryNodeRef[] {
|
||||
const needle = keyword.trim().toLowerCase()
|
||||
if (!needle) return jdCategoryAllNodes()
|
||||
return jdCategoryAllNodes().filter(
|
||||
(node) =>
|
||||
node.name.toLowerCase().includes(needle) ||
|
||||
node.path.some((segment) => segment.toLowerCase().includes(needle)),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 选中节点 → 下发后端的类目名集合(2026-11-18 前端展开+后端 IN 路线):
|
||||
* 返回该节点**自身+全部后代**的类目名(去重、层级序)。含自身是因为落库
|
||||
* `category_path` =京麦实际末级名,快照层级可能比实际深/浅——父级名本身也可能就是
|
||||
* 某批行的末级名(真机样本「艺考形体服」即三级节点名)。路径无效返回 null(调用方
|
||||
* 按单名等值兜底,语义同树外历史行)。
|
||||
*/
|
||||
export function jdCategoryNamesUnder(path: string[]): string[] | null {
|
||||
let level = JD_CATEGORY_TREE
|
||||
let target: JdCategoryNode | null = null
|
||||
for (const name of path) {
|
||||
const hit = level.find((node) => node.name === name)
|
||||
if (!hit) return null
|
||||
target = hit
|
||||
level = hit.children ?? []
|
||||
}
|
||||
if (!target) return null
|
||||
const out: string[] = []
|
||||
const seen = new Set<string>()
|
||||
const walk = (nodes: JdCategoryNode[]): void => {
|
||||
for (const node of nodes) {
|
||||
if (!seen.has(node.name)) {
|
||||
seen.add(node.name)
|
||||
out.push(node.name)
|
||||
}
|
||||
if (node.children && node.children.length) walk(node.children)
|
||||
}
|
||||
}
|
||||
walk([target])
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ export async function fetchJdProductList(
|
||||
productCode: params.productCode ?? '',
|
||||
titleKeyword: params.titleKeyword ?? '',
|
||||
category: params.category ?? '',
|
||||
categoryPath: params.categoryPath ?? [],
|
||||
groupId: params.groupId ?? '',
|
||||
classified: (params.classified ?? '') as '' | 'classified' | 'ungrouped',
|
||||
syncedFrom: params.syncedFrom ?? '',
|
||||
@@ -37,7 +38,13 @@ export async function fetchJdProductList(
|
||||
params.pageSize,
|
||||
params.ownerGroupId ?? null,
|
||||
)
|
||||
const { data } = await http.get<unknown>(JD_PRODUCT_ENDPOINT, { params: query })
|
||||
// category 多值(父级展开集合)必须序列化成重复 `category=a&category=b`:axios 默认
|
||||
// 给数组加 `[]` 后缀,后端 @RequestParam("category") List<String> 认不到。
|
||||
// indexes:false = 无括号无下标的重复键(axios 1.x 官方口径)。
|
||||
const { data } = await http.get<unknown>(JD_PRODUCT_ENDPOINT, {
|
||||
params: query,
|
||||
paramsSerializer: { indexes: false },
|
||||
})
|
||||
return parseJdProductPage(data)
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
* 日期默认空字符串:同步台账是累计数据,默认当天会让首屏只剩今天同步的行
|
||||
* (date-filter-default-today 护栏 EXEMPT 口径,外观专利页同款)。 */
|
||||
import { validIsoDateOrUndefined } from '../asin/asin-filter.ts'
|
||||
import { jdCategoryNamesUnder } from './jd-category-tree.ts'
|
||||
|
||||
/** 每页条数默认 20(v1.4 §3.4),上限 100。 */
|
||||
export const JD_PRODUCT_PAGE_SIZE = 20
|
||||
@@ -28,8 +29,12 @@ export interface JdProductFilterState {
|
||||
productCode: string
|
||||
/** 标题关键字,空串不限。 */
|
||||
titleKeyword: string
|
||||
/** 类目(京麦末级类目名,等值过滤;选项来自 GET /categories),空串=全部类目。 */
|
||||
/** 类目(京麦类目名,末级或父级;选项来自级联面板),空串=全部类目。 */
|
||||
category: string
|
||||
/** 选中节点的名称路径(2026-11-18 一级/二级类目可选中):非空时序列化按
|
||||
* jdCategoryNamesUnder 展开为子树类目名集合下发(后端 IN);空=末级/树外行,
|
||||
* 按单名等值下发(旧形状)。 */
|
||||
categoryPath?: string[]
|
||||
/** 分组 id 文本(分组管理里那一行),空串=全部分组。 */
|
||||
groupId: string
|
||||
/** 分类状态快筛(2026-11-17 用户口径「加个已分类和未分类的筛选」,同日定默认卡未分类;
|
||||
@@ -49,7 +54,7 @@ export interface JdProductFilterState {
|
||||
export function createJdProductFilterState(): JdProductFilterState {
|
||||
// 分类状态出厂卡「未分类」(2026-11-17 用户口径「默认卡在未分类上就行」,2026-11-18
|
||||
// 加「全部」档后默认不动):首屏与「重置」都带 classified=false 查,全量走「全部」档。
|
||||
return { productCode: '', titleKeyword: '', category: '', groupId: '', classified: JD_PRODUCT_DEFAULT_CLASSIFIED, syncedFrom: '', syncedTo: '' }
|
||||
return { productCode: '', titleKeyword: '', category: '', categoryPath: [], groupId: '', classified: JD_PRODUCT_DEFAULT_CLASSIFIED, syncedFrom: '', syncedTo: '' }
|
||||
}
|
||||
|
||||
/** 是否有任一激活筛选条件。 */
|
||||
@@ -71,8 +76,9 @@ export interface JdProductQuery {
|
||||
page_size: number
|
||||
product_code?: string
|
||||
title_keyword?: string
|
||||
/** 京麦末级类目等值过滤(后端 JdProductQueryService.Filter.category)。 */
|
||||
category?: string
|
||||
/** 京麦类目名集合 IN 过滤(后端 JdProductQueryService.Filter.categories,
|
||||
* 2026-11-18 一级/二级类目可选中:父级展开为子树类目名集合;末级/树外=单元素)。 */
|
||||
category?: string[]
|
||||
/** 自定义分类 id(当前分组下的一个分类;V203 起按归属表 EXISTS 过滤)。 */
|
||||
group_id?: number
|
||||
/** 分类状态快筛(2026-11-17):true=已分类、false=未分类,缺省不下发=全部。
|
||||
@@ -91,6 +97,8 @@ export interface JdProductListParams {
|
||||
productCode?: string
|
||||
titleKeyword?: string
|
||||
category?: string
|
||||
/** 选中类目节点路径(见 JdProductFilterState.categoryPath;空=单名等值)。 */
|
||||
categoryPath?: string[]
|
||||
groupId?: string
|
||||
/** 分类状态快筛(''/缺省=全部,'classified'/'ungrouped' 见 JdProductFilterState)。 */
|
||||
classified?: string
|
||||
@@ -108,7 +116,14 @@ function toJdProductFilterQuery(state: JdProductFilterState): Omit<JdProductQuer
|
||||
const titleKeyword = (state.titleKeyword || '').trim()
|
||||
if (titleKeyword) query.title_keyword = titleKeyword
|
||||
const category = (state.category || '').trim()
|
||||
if (category) query.category = category
|
||||
if (category) {
|
||||
// 2026-11-18 一级/二级类目可选中:带路径=按子树展开类目名集合(后端 IN);
|
||||
// 路径失效(树外历史名)回落单名等值集合——与旧 eq 语义逐字同形。
|
||||
const expanded = state.categoryPath && state.categoryPath.length
|
||||
? jdCategoryNamesUnder(state.categoryPath)
|
||||
: null
|
||||
query.category = expanded && expanded.length ? expanded : [category]
|
||||
}
|
||||
const groupId = Number.parseInt((state.groupId || '').trim(), 10)
|
||||
if (Number.isFinite(groupId) && groupId > 0) query.group_id = groupId
|
||||
// 分类状态快筛:只认两个显式档位,其余值(含脏值)按「全部」不下发——后端 classified
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。",
|
||||
"totals": {
|
||||
"files": 262,
|
||||
"cases": 1837,
|
||||
"files": 263,
|
||||
"cases": 1847,
|
||||
"pins": 460,
|
||||
"reads": 658
|
||||
},
|
||||
@@ -308,7 +308,7 @@
|
||||
"reads": 0
|
||||
},
|
||||
"jd-category-tree.test.ts": {
|
||||
"cases": 6,
|
||||
"cases": 8,
|
||||
"pins": 0,
|
||||
"reads": 0
|
||||
},
|
||||
@@ -1302,6 +1302,11 @@
|
||||
"pins": 2,
|
||||
"reads": 2
|
||||
},
|
||||
"user-menu-tree-platform-filter.test.ts": {
|
||||
"cases": 8,
|
||||
"pins": 0,
|
||||
"reads": 0
|
||||
},
|
||||
"user-notice-chinese-only.test.ts": {
|
||||
"cases": 4,
|
||||
"pins": 0,
|
||||
|
||||
@@ -2,10 +2,13 @@ import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {
|
||||
JD_CATEGORY_TREE,
|
||||
jdCategoryAllNodes,
|
||||
jdCategoryChildren,
|
||||
jdCategoryLeaves,
|
||||
jdCategoryNamesUnder,
|
||||
jdCategoryRoots,
|
||||
jdCategorySearchLeaves,
|
||||
jdCategorySearchNodes,
|
||||
} from '../src/pages/jd/jd-category-tree.ts'
|
||||
|
||||
/** 京麦授权类目真树(2026-11-16 真机取证 getVenderLicenseCategory 快照;与用户端
|
||||
@@ -95,3 +98,37 @@ test('树数据快照不可空、value 全非空(取证 id 留档完整)', (
|
||||
assert.ok(leaf.value, `叶子 ${leaf.name} 必须带京麦类目 id`)
|
||||
}
|
||||
})
|
||||
|
||||
/** 2026-11-18 客户口径「一级/二级类目也要能选来搜索」:全层级节点+子树展开集合。 */
|
||||
test('全节点搜索:一级/二级/末级都在结果里,leaf 标记如实', () => {
|
||||
assert.equal(jdCategorySearchNodes('').length, jdCategoryAllNodes().length, '空词=全量节点')
|
||||
assert.ok(jdCategoryAllNodes().length > 250, '全节点数必须大于末级 250(含非末级)')
|
||||
const byName = jdCategorySearchNodes('女装')
|
||||
const women = byName.find((node) => node.name === '女装')
|
||||
assert.ok(women, '「女装」这个二级节点必须可搜到(旧版只铺末级,选不了它)')
|
||||
assert.equal(women!.leaf, false, '女装有子级=非末级')
|
||||
assert.deepEqual(women!.path, ['服饰内衣', '女装'], '路径从一级起(同名跨支靠它区分)')
|
||||
assert.ok(byName.some((node) => node.leaf), '末级命中照旧在')
|
||||
})
|
||||
|
||||
test('子树展开集合:含自身+全部后代名、去重、不越支;路径失效回 null', () => {
|
||||
const dress = jdCategoryNamesUnder(['服饰内衣', '女装', '连衣裙'])
|
||||
assert.ok(dress, '连衣裙路径有效')
|
||||
assert.ok(dress!.includes('连衣裙'), '含节点自身名(实际末级可能就在这一级)')
|
||||
assert.ok(dress!.includes('短袖连衣裙') && dress!.includes('长袖连衣裙') && dress!.includes('无袖连衣裙'))
|
||||
assert.ok(!dress!.includes('女装'), '只展开本节点子树,不带上父级')
|
||||
|
||||
const top = jdCategoryNamesUnder(['运动户外'])
|
||||
assert.ok(top!.includes('艺考形体服') && top!.includes('啦啦队服'), '一级展开覆盖全支')
|
||||
assert.ok(!top!.includes('女装'), '不越支')
|
||||
|
||||
const hanfu = jdCategoryNamesUnder(['服饰内衣', '女装', '汉服'])
|
||||
assert.ok(hanfu!.includes('汉服') && hanfu!.includes('汉服套装'), '非叶「汉服」展开含四级')
|
||||
|
||||
assert.equal(jdCategoryNamesUnder(['不存在', '的路径']), null, '路径失效回 null(调用方按单名兜底)')
|
||||
assert.equal(jdCategoryNamesUnder([]), null, '空路径回 null')
|
||||
|
||||
// 去重:同名跨支在**同一子树内**出现两次时集合不重复(唐装/短裤等在女装支内只有一个)。
|
||||
const women = jdCategoryNamesUnder(['服饰内衣', '女装'])!
|
||||
assert.equal(new Set(women).size, women.length, '展开集合内部去重')
|
||||
})
|
||||
|
||||
@@ -97,17 +97,30 @@ test('列表行价格:BigDecimal 的 JSON number 形状与字符串形状都
|
||||
assert.equal(jdPriceRange(missing), '', '两侧都空回空串(列表显示 -)')
|
||||
})
|
||||
|
||||
/** 类目筛选(2026-11-15):京麦末级类目等值过滤,空串不下发、非空透传 category。 */
|
||||
test('类目筛选参数序列化:空串不下发、非空下发 category(等值过滤)', async () => {
|
||||
/** 类目筛选(2026-11-15 末级等值;2026-11-18 一级/二级可选中=子树展开集合 IN):
|
||||
* 空串不下发;无路径=单元素集合(等值旧形状);带路径=jdCategoryNamesUnder 展开。 */
|
||||
test('类目筛选参数序列化:空串不下发、末级单值、父级展开子树集合', async () => {
|
||||
const { createJdProductFilterState, toJdProductListParams, jdProductFilterActive } =
|
||||
await import('../src/pages/jd/jd-product-filter.ts')
|
||||
const empty = createJdProductFilterState()
|
||||
assert.equal('category' in toJdProductListParams(empty, 1, 20), false, '全部类目不下发 category')
|
||||
assert.equal(jdProductFilterActive(empty), false)
|
||||
|
||||
const filtered = { ...empty, category: ' 服饰内衣 ' }
|
||||
assert.equal(toJdProductListParams(filtered, 1, 20).category, '服饰内衣', '去空白透传(等值过滤)')
|
||||
assert.equal(jdProductFilterActive(filtered), true, '选中类目算激活筛选')
|
||||
const leaf = { ...empty, category: ' 艺考形体服 ' }
|
||||
assert.deepEqual(toJdProductListParams(leaf, 1, 20).category, ['艺考形体服'],
|
||||
'无路径=去空白单元素集合(等值旧形状,后端 IN 单值等价)')
|
||||
assert.equal(jdProductFilterActive(leaf), true, '选中类目算激活筛选')
|
||||
|
||||
const parent = { ...empty, category: '女装', categoryPath: ['服饰内衣', '女装'] }
|
||||
const expanded = toJdProductListParams(parent, 1, 20).category as string[]
|
||||
assert.ok(Array.isArray(expanded) && expanded.length > 20, '一级/二级选中=子树展开集合')
|
||||
assert.ok(expanded.includes('女装'), '集合含节点自身名(实际末级可能就在这一级)')
|
||||
assert.ok(expanded.includes('连衣裙') && expanded.includes('短袖连衣裙'), '含后代各级名')
|
||||
assert.ok(!expanded.includes('艺考形体服'), '不越出子树(艺考形体服在运动户外支)')
|
||||
|
||||
const stale = { ...empty, category: '已下架历史类目', categoryPath: ['不存在', '的路径'] }
|
||||
assert.deepEqual(toJdProductListParams(stale, 1, 20).category, ['已下架历史类目'],
|
||||
'路径失效(树外历史名)回落单名等值,不静默丢筛选')
|
||||
})
|
||||
|
||||
test('自定义分类使用 group_id,不发送分类状态参数', async () => {
|
||||
|
||||
@@ -608,6 +608,49 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
|
||||
expect(wrapper.find('.cat-trigger').text()).toContain('腰带/腰链')
|
||||
})
|
||||
|
||||
it('一级/二级类目点圆点可选中即查(2026-11-18 客户口径「没办法选择一级跟二级类目」):入参带节点路径、行体仍下钻', async () => {
|
||||
jdApi.fetchJdProductCategories.mockResolvedValue([])
|
||||
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
|
||||
await wrapper.find('.cat-trigger').trigger('click')
|
||||
|
||||
// 一级行体点击=仍下钻(旧语义不动);一级圆点点击=选中整棵一级子树。
|
||||
const firstCol = wrapper.findAll('.cat-col')[0]
|
||||
const apparelRow = firstCol.findAll('.cat-row').find((row) => row.text().includes('服饰内衣'))!
|
||||
await apparelRow.find('.cat-dot').trigger('click')
|
||||
await flushPromises()
|
||||
expect(wrapper.find('.cat-panel').exists()).toBe(false, '点圆点选中后面板收起')
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({
|
||||
category: '服饰内衣',
|
||||
categoryPath: ['服饰内衣'],
|
||||
page: 1,
|
||||
}, '一级选中=带路径下发(序列化侧展开子树类目名集合)')
|
||||
expect(wrapper.find('.cat-trigger').text()).toContain('服饰内衣')
|
||||
|
||||
// 下钻两级后点二级圆点:路径带全前缀,同名跨支靠路径区分。
|
||||
await wrapper.find('.cat-trigger').trigger('click')
|
||||
const col1 = wrapper.findAll('.cat-col')[0]
|
||||
await col1.findAll('.cat-row').find((row) => row.text().includes('服饰内衣'))!.trigger('click')
|
||||
const col2 = wrapper.findAll('.cat-col')[1]
|
||||
await col2.findAll('.cat-row').find((row) => row.text().includes('女装'))!.find('.cat-dot').trigger('click')
|
||||
await flushPromises()
|
||||
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({
|
||||
category: '女装',
|
||||
categoryPath: ['服饰内衣', '女装'],
|
||||
page: 1,
|
||||
})
|
||||
|
||||
// 选中态回显:重新打开面板并下钻,被选节点(女装)的圆点是蓝芯(.cat-dot.on),
|
||||
// 其余行空心——11-16 旧形状里非末级行圆点永远空心、无法表达选中。
|
||||
await wrapper.find('.cat-trigger').trigger('click')
|
||||
const reopened1 = wrapper.findAll('.cat-col')[0]
|
||||
await reopened1.findAll('.cat-row').find((row) => row.text().includes('服饰内衣'))!.trigger('click')
|
||||
const reopened2 = wrapper.findAll('.cat-col')[1]
|
||||
const womenRow = reopened2.findAll('.cat-row').find((row) => row.text().includes('女装'))!
|
||||
expect(womenRow.find('.cat-dot').classes()).toContain('on', '二级选中态圆点回显')
|
||||
const menRow = reopened2.findAll('.cat-row').find((row) => row.text().includes('男装'))!
|
||||
expect(menRow.find('.cat-dot').classes()).not.toContain('on', '未选中行保持空心圆')
|
||||
})
|
||||
|
||||
it('类目级联搜索与清选(2026-11-16 真树重做):树内末级命中+树外兜底段;「全部类目」行/触发框 × 都能清选重查', async () => {
|
||||
jdApi.fetchJdProductCategories.mockResolvedValue([
|
||||
{ name: '艺考形体服', productCount: 120 },
|
||||
|
||||
@@ -31,6 +31,15 @@ public class CollectRoutingProperties {
|
||||
/** 京东商品上架模块名(v1.5;京麦登录态在用户桌面机 19899 Chrome profile,默认通道必须 LOCAL,铁律 19 同形)。 */
|
||||
public static final String MODULE_JD_PUBLISH = "JD_PUBLISH";
|
||||
|
||||
/**
|
||||
* 品牌检测模块名(2026-11-18)。
|
||||
*
|
||||
* <p>它不在 {@code biz_file_task} 上(独立表 {@code brand_crawl_tasks}),走的是页面
|
||||
* 「本机客户端执行 / 服务端 15126 执行」二选一;默认 LOCAL —— 服务端进程内跨账号并发
|
||||
* 默认只 2 个名额,大单会把后面所有账号的任务排到 120 分钟上限(任务 3374 实测排队 62 分钟)。
|
||||
*/
|
||||
public static final String MODULE_BRAND = "BRAND";
|
||||
|
||||
/** LOCAL 通道的任务在 PENDING 超过多少分钟后允许 Linux 兜底认领。 */
|
||||
private long linuxFallbackMinutes = 30L;
|
||||
|
||||
|
||||
+17
-2
@@ -112,9 +112,15 @@ public class AdminUserService {
|
||||
query.eq(AdminUserEntity::getCompanyId, companyIdFilter);
|
||||
}
|
||||
} else if (isCompanySuperAdmin) {
|
||||
// 公司超管看本公司全部账号(站点超管账号除外——那是平台自己的身份)
|
||||
// 2026-11-18 客户口径「admin 看所有,其余公司超管各自看各自名下的」:
|
||||
// 公司超管只看本人那行+自己直接创建(created_by_id=本人)的账号,
|
||||
// 本公司内由站点超管或其他组长建的行不再可见——与下面组长档同一形状。
|
||||
// 站点超管行本来就不可能落进这个谓词(ne 只是对脏数据的保险,保留)。
|
||||
Long selfId = currentUser.getId();
|
||||
query.eq(AdminUserEntity::getCompanyId, currentUser.getCompanyId())
|
||||
.ne(AdminUserEntity::getRole, "super_admin");
|
||||
.ne(AdminUserEntity::getRole, "super_admin")
|
||||
.and(w -> w.eq(AdminUserEntity::getId, selfId)
|
||||
.or(inner -> inner.eq(AdminUserEntity::getCreatedById, selfId)));
|
||||
if (!kw.isEmpty()) {
|
||||
query.like(AdminUserEntity::getUsername, kw);
|
||||
}
|
||||
@@ -441,6 +447,11 @@ public class AdminUserService {
|
||||
if (!currentUser.getCompanyId().equals(target.getCompanyId())) {
|
||||
throw new BusinessException(403, "只能编辑本公司名下的账号");
|
||||
}
|
||||
// 2026-11-18 与读侧「各自看各自名下」同口径:目标必须是自己直接创建的,
|
||||
// 否则就是「列表看不见、API 照样改」的洞(停用/改密/额度全走这条闸)。
|
||||
if (!currentUser.getId().equals(target.getCreatedById())) {
|
||||
throw new BusinessException(403, "只能编辑自己名下创建的账号");
|
||||
}
|
||||
}
|
||||
if ("super_admin".equals(wantRole)) {
|
||||
throw new BusinessException("不能将用户设为超级管理员");
|
||||
@@ -610,6 +621,10 @@ public class AdminUserService {
|
||||
if (!currentUser.getCompanyId().equals(target.getCompanyId())) {
|
||||
throw new BusinessException(403, "只能删除本公司名下的账号");
|
||||
}
|
||||
// 2026-11-18 与读侧/updateUser 同口径:只清退自己直接创建的账号
|
||||
if (!currentUser.getId().equals(target.getCreatedById())) {
|
||||
throw new BusinessException(403, "只能删除自己名下创建的账号");
|
||||
}
|
||||
}
|
||||
int affected = adminUserMapper.deleteById(uid);
|
||||
if (affected == 0) {
|
||||
|
||||
+11
@@ -24,4 +24,15 @@ public class BrandTaskCreateRequest {
|
||||
|
||||
@Schema(description = "文件夹上传场景下可选的归档名称。当前版本仅保留字段,不参与主流程。")
|
||||
private String archiveName;
|
||||
|
||||
/**
|
||||
* 本单由谁执行(V212):LOCAL=桌面客户端本机跑(用用户自己的代理,不占服务端名额);
|
||||
* ONLINE=服务端 15126 跑(进程内跨账号并发默认 2,大单会把后面所有任务排到 120 分钟上限)。
|
||||
* 空/不可识别=不登记,按模块默认(BRAND 默认 LOCAL)。
|
||||
*/
|
||||
@Schema(description = "采集执行通道:LOCAL=桌面客户端本机采;ONLINE=服务端 15126 采;空=按模块默认(本机)",
|
||||
example = "LOCAL")
|
||||
@com.fasterxml.jackson.annotation.JsonProperty("collect_channel")
|
||||
@com.fasterxml.jackson.annotation.JsonAlias({"collectChannel"})
|
||||
private String collectChannel;
|
||||
}
|
||||
|
||||
+2
@@ -18,6 +18,8 @@ public class BrandCrawlTaskEntity {
|
||||
private Long userId;
|
||||
/** 创建任务的客户端设备(JWT 签名 deviceId claim,V138);历史任务为空。 */
|
||||
private String deviceId;
|
||||
/** 采集执行通道 LOCAL/ONLINE(V212);空=按模块默认(BRAND 默认 LOCAL),见 CollectChannel。 */
|
||||
private String collectChannel;
|
||||
private String filePaths;
|
||||
private String status;
|
||||
private Integer taskType;
|
||||
|
||||
+3
@@ -8,4 +8,7 @@ import lombok.Data;
|
||||
public class BrandTaskCreateVo {
|
||||
|
||||
private Long taskId;
|
||||
|
||||
/** 本单实际生效的执行通道(V212):LOCAL=桌面客户端本机跑;ONLINE=服务端 15126 跑。 */
|
||||
private String collectChannel;
|
||||
}
|
||||
|
||||
+1
-1
@@ -22,6 +22,6 @@ public class LegacyBrandLineProgressInfoVo {
|
||||
@Schema(description = "当前文件总行数")
|
||||
private Integer total_lines;
|
||||
|
||||
@Schema(description = "当前阶段:crawling/assembling/uploading/failed")
|
||||
@Schema(description = "当前阶段:queued/crawling/assembling/uploading/failed")
|
||||
private String phase;
|
||||
}
|
||||
|
||||
+8
-2
@@ -17,6 +17,12 @@ import java.util.Map;
|
||||
@Slf4j
|
||||
public class BrandTaskProgressCacheService {
|
||||
|
||||
/**
|
||||
* 排队阶段:客户端已建任务但还没拿到账号锁/全局并发槽位(跨账号并发上限默认 2,
|
||||
* 被大单占满时后到的任务要等几十分钟)。此前排队期一律报 crawling,界面把
|
||||
* 「排队 62 分钟」显示成「品牌查询中 0/N」,用户只能以为任务卡死。
|
||||
*/
|
||||
public static final String PHASE_QUEUED = "queued";
|
||||
public static final String PHASE_CRAWLING = "crawling";
|
||||
public static final String PHASE_ASSEMBLING = "assembling";
|
||||
public static final String PHASE_UPLOADING = "uploading";
|
||||
@@ -104,7 +110,7 @@ public class BrandTaskProgressCacheService {
|
||||
if phase ~= '' then
|
||||
local stored = redis.call('hget', key, 'phase')
|
||||
local protect = (stored == 'assembling' or stored == 'uploading' or stored == 'failed')
|
||||
if not (protect and phase == 'crawling') then
|
||||
if not (protect and (phase == 'crawling' or phase == 'queued')) then
|
||||
redis.call('hset', key, 'phase', phase)
|
||||
end
|
||||
end
|
||||
@@ -219,7 +225,7 @@ public class BrandTaskProgressCacheService {
|
||||
}
|
||||
String value = phase.trim().toLowerCase();
|
||||
return switch (value) {
|
||||
case PHASE_ASSEMBLING, PHASE_UPLOADING, PHASE_FAILED -> value;
|
||||
case PHASE_QUEUED, PHASE_ASSEMBLING, PHASE_UPLOADING, PHASE_FAILED -> value;
|
||||
default -> PHASE_CRAWLING;
|
||||
};
|
||||
}
|
||||
|
||||
+9
@@ -168,6 +168,10 @@ public class BrandTaskService {
|
||||
BrandCrawlTaskEntity entity = new BrandCrawlTaskEntity();
|
||||
entity.setUserId(userId);
|
||||
entity.setDeviceId(AdminAuthSupport.normalizeDeviceId(deviceId));
|
||||
// 执行方在这一单选(界面 LOCAL/ONLINE 单选框,V212);未登记/脏值=不登记,按模块默认
|
||||
// (BRAND 默认 LOCAL)兜,与 V183 的外观专利/相似ASIN 同一口径。
|
||||
entity.setCollectChannel(com.nanri.aiimage.modules.task.model.CollectChannel
|
||||
.persistedValue(request.getCollectChannel()));
|
||||
entity.setFilePaths(JSONUtil.toJsonStr(files));
|
||||
entity.setStatus(STATUS_PENDING);
|
||||
entity.setTaskType(taskType);
|
||||
@@ -181,6 +185,11 @@ public class BrandTaskService {
|
||||
|
||||
BrandTaskCreateVo vo = new BrandTaskCreateVo();
|
||||
vo.setTaskId(entity.getId());
|
||||
// 回读给调用方的是「库里真正生效的通道」:入库为 NULL 时也告诉前端按哪一侧兜,
|
||||
// 免得界面显示本机、实际默认线上(或反过来)这种两侧各读各的分裂。
|
||||
vo.setCollectChannel(com.nanri.aiimage.modules.task.model.CollectChannel
|
||||
.resolve(entity.getCollectChannel(),
|
||||
com.nanri.aiimage.config.CollectRoutingProperties.MODULE_BRAND).name());
|
||||
return vo;
|
||||
}
|
||||
|
||||
|
||||
+4
-2
@@ -114,7 +114,9 @@ public class AdminJdProductController {
|
||||
@Parameter(description = "每页数量") @RequestParam(name = "page_size", defaultValue = PageDefaults.JD_PRODUCTS_PAGE_SIZE) Long pageSize,
|
||||
@Parameter(description = "商品编码(包含匹配)") @RequestParam(name = "product_code", required = false) String productCode,
|
||||
@Parameter(description = "标题关键词(包含匹配)") @RequestParam(name = "title_keyword", required = false) String titleKeyword,
|
||||
@Parameter(description = "类目(京麦末级类目名,eq)") @RequestParam(name = "category", required = false) String category,
|
||||
@Parameter(description = "类目(京麦类目名,多值 IN;2026-11-18 支持选一级/二级类目——"
|
||||
+ "前端把选中节点展开为其子树全部类目名,用重复 category 参数下发,单值形状照常工作)")
|
||||
@RequestParam(name = "category", required = false) List<String> categories,
|
||||
@Parameter(description = "自定义分类 id(类目面板「自定义分类」选中驱动)") @RequestParam(name = "group_id", required = false) Long groupId,
|
||||
@Parameter(description = "当前数据权限分组 id(分类列/分类筛选按它取;缺省=作用域默认分组)")
|
||||
@RequestParam(name = "owner_group_id", required = false) Long ownerGroupId,
|
||||
@@ -136,7 +138,7 @@ public class AdminJdProductController {
|
||||
requireVisibleCategory(scope, groupId);
|
||||
}
|
||||
return ApiResponse.success(jdProductQueryService.page(page, pageSize,
|
||||
productCode, titleKeyword, category, groupId, syncedFrom, syncedTo, classified,
|
||||
productCode, titleKeyword, categories, groupId, syncedFrom, syncedTo, classified,
|
||||
scopedOwnerGroupId));
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,8 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
|
||||
/**
|
||||
* 后管只读页总数(Phase 5,v1.4):与 {@link #selectProductPage} 同一过滤面
|
||||
* (商品编码/标题关键词/类目/自定义分类/同步起止,全部 SQL 侧下推,铁律 20)。
|
||||
* {@code categories}(2026-11-18 一级/二级类目可选):类目名集合 IN,空/ null=不过滤;
|
||||
* 选父级时由前端展开为子树类目名集合下发,单值=原 eq 形状。
|
||||
* 公司维过滤已随 2026-11-16「删除掉公司 tab,参考品牌数据库」撤掉
|
||||
* (数据全平台公共);{@code groupId} 为空或 ≤0=不过滤该面;
|
||||
* {@code ungrouped}/{@code grouped} 两档(未分类/已分类)已随同日口径
|
||||
@@ -55,7 +57,7 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
|
||||
*/
|
||||
long countProducts(@Param("productCode") String productCode,
|
||||
@Param("titleKeyword") String titleKeyword,
|
||||
@Param("category") String category,
|
||||
@Param("categories") List<String> categories,
|
||||
@Param("groupId") Long groupId,
|
||||
@Param("syncedFrom") LocalDateTime syncedFrom,
|
||||
@Param("syncedTo") LocalDateTime syncedTo,
|
||||
@@ -96,7 +98,7 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
|
||||
*/
|
||||
List<JdProductEntity> selectProductPage(@Param("productCode") String productCode,
|
||||
@Param("titleKeyword") String titleKeyword,
|
||||
@Param("category") String category,
|
||||
@Param("categories") List<String> categories,
|
||||
@Param("groupId") Long groupId,
|
||||
@Param("syncedFrom") LocalDateTime syncedFrom,
|
||||
@Param("syncedTo") LocalDateTime syncedTo,
|
||||
|
||||
+18
-9
@@ -78,7 +78,9 @@ public class JdProductQueryService {
|
||||
/**
|
||||
* 分页查询商品行({@code synced_at} 倒序)。
|
||||
*
|
||||
* <p>过滤面:商品编码 contains、标题关键词 contains、类目 eq、分组 eq(2026-11-16 起
|
||||
* <p>过滤面:商品编码 contains、标题关键词 contains、类目 IN(2026-11-18 起多值:
|
||||
* 选一级/二级类目由前端展开为子树类目名集合下发,单值=原 eq 形状;空集合=不过滤该面)、
|
||||
* 分组 eq(2026-11-16 起
|
||||
* 由类目面板「自定义分类」选中驱动)、同步起止(datetime 闭区间)、分类状态档
|
||||
* {@code classified}(2026-11-17 用户口径「加个已分类和未分类的筛选」:true=当前分组下
|
||||
* 有分类、false=没有、null=全部;按 V203 归属表 EXISTS/NOT EXISTS 在 SQL 侧下推,
|
||||
@@ -89,7 +91,7 @@ public class JdProductQueryService {
|
||||
* 公司维过滤已随 2026-11-16 摘公司 tab 整批撤掉(全平台公共)。</p>
|
||||
*/
|
||||
public JdProductPageVo page(Long page, Long pageSize,
|
||||
String productCode, String titleKeyword, String category, Long groupId,
|
||||
String productCode, String titleKeyword, List<String> categories, Long groupId,
|
||||
LocalDateTime syncedFrom, LocalDateTime syncedTo, Boolean classified, Long ownerGroupId) {
|
||||
if (syncedFrom != null && syncedTo != null && syncedFrom.isAfter(syncedTo)) {
|
||||
throw new BusinessException("开始时间不能晚于结束时间");
|
||||
@@ -97,14 +99,14 @@ public class JdProductQueryService {
|
||||
long safePage = page == null || page < 1 ? 1 : Math.min(page, MAX_PAGE);
|
||||
long safeSize = pageSize == null ? PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT
|
||||
: Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE);
|
||||
Filter filter = filter(productCode, titleKeyword, category,
|
||||
Filter filter = filter(productCode, titleKeyword, categories,
|
||||
groupId, syncedFrom, syncedTo, classified);
|
||||
long total = jdProductMapper.countProducts(filter.productCode(),
|
||||
filter.titleKeyword(), filter.category(), filter.groupId(),
|
||||
filter.titleKeyword(), filter.categories(), filter.groupId(),
|
||||
filter.syncedFrom(), filter.syncedTo(), filter.classified(), ownerGroupId);
|
||||
List<JdProductEntity> rows = total <= 0 ? List.of()
|
||||
: jdProductMapper.selectProductPage(filter.productCode(),
|
||||
filter.titleKeyword(), filter.category(), filter.groupId(),
|
||||
filter.titleKeyword(), filter.categories(), filter.groupId(),
|
||||
filter.syncedFrom(), filter.syncedTo(), filter.classified(), ownerGroupId,
|
||||
(safePage - 1) * safeSize, (int) safeSize);
|
||||
List<JdProductListItemVo> items = rows.stream().map(this::toListItem).toList();
|
||||
@@ -228,18 +230,25 @@ public class JdProductQueryService {
|
||||
// ---------------------------------------------------------------- 过滤面
|
||||
|
||||
/** 服务侧过滤面归一:groupId ≤0 按没选处理,文本 trim 后空串归 null(无公司维,2026-11-16 摘);
|
||||
* classified 原样直传(null=不过滤该面,2026-11-17 分类状态快筛)。 */
|
||||
* classified 原样直传(null=不过滤该面,2026-11-17 分类状态快筛);
|
||||
* categories 逐项 trim、去空白、去重,空集合归 null=不过滤该面(2026-11-18 一级/二级类目展开)。 */
|
||||
private record Filter(String productCode, String titleKeyword,
|
||||
String category, Long groupId,
|
||||
List<String> categories, Long groupId,
|
||||
LocalDateTime syncedFrom, LocalDateTime syncedTo, Boolean classified) {
|
||||
}
|
||||
|
||||
private static Filter filter(String productCode, String titleKeyword,
|
||||
String category, Long groupId,
|
||||
List<String> categories, Long groupId,
|
||||
LocalDateTime syncedFrom, LocalDateTime syncedTo, Boolean classified) {
|
||||
Long safeGroupId = groupId != null && groupId > 0 ? groupId : null;
|
||||
List<String> safeCategories = categories == null ? null : categories.stream()
|
||||
.map(JdProductQueryService::trimToNull)
|
||||
.filter(java.util.Objects::nonNull)
|
||||
.distinct()
|
||||
.toList();
|
||||
return new Filter(trimToNull(productCode), trimToNull(titleKeyword),
|
||||
trimToNull(category), safeGroupId, syncedFrom, syncedTo, classified);
|
||||
safeCategories == null || safeCategories.isEmpty() ? null : safeCategories,
|
||||
safeGroupId, syncedFrom, syncedTo, classified);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 列表/详情搬运
|
||||
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.nanri.aiimage.modules.jd.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity;
|
||||
import com.nanri.aiimage.modules.task.spi.TaskItemsResetSpi;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 京东商品上架的失败重试明细行复位(AC-7 服务端半边,v1.5 Phase 5 消欠账)。
|
||||
*
|
||||
* <p>任务头被 {@code TaskInPlaceRetryService} 原地复位成 PENDING 后,明细分批下发
|
||||
* {@code JdPublishItemMapper.selectPublishableItems} 只出 PENDING 行——上一代留下的
|
||||
* FAILED/PUBLISHING 行不复位,重试就是空页空跑(蓝图 Phase 2 变更记录登记的欠账)。
|
||||
* 本实现把 FAILED/PUBLISHING 行复位回 PENDING 并清旧错误文案,让剩余商品重新进入
|
||||
* 下发候选;SUCCESS 行不动:已发布商品不重发(AC-4),客户端断点 done 集合同口径。
|
||||
*
|
||||
* <p>{@code jd_ware_id} 不清:只有 SUCCESS 行才有值,本条不碰 SUCCESS 行;
|
||||
* 旧 {@code publish_error} 必须清——留着会让用户端面板把「上一代的失败原因」
|
||||
* 显示在「待发布」行上(进度真源是行级状态聚合,JdPublishBoardService 同源)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class JdPublishTaskItemsResetSpiImpl implements TaskItemsResetSpi {
|
||||
|
||||
private final JdPublishItemMapper jdPublishItemMapper;
|
||||
|
||||
@Override
|
||||
public String moduleType() {
|
||||
return JdPublishTaskService.MODULE_TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void resetForRetry(Long taskId) {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
int updated = jdPublishItemMapper.update(null, new LambdaUpdateWrapper<JdPublishItemEntity>()
|
||||
.eq(JdPublishItemEntity::getTaskId, taskId)
|
||||
.in(JdPublishItemEntity::getPublishStatus,
|
||||
JdPublishTaskService.ITEM_FAILED, JdPublishTaskService.ITEM_PUBLISHING)
|
||||
.set(JdPublishItemEntity::getPublishStatus, JdPublishTaskService.ITEM_PENDING)
|
||||
.set(JdPublishItemEntity::getPublishError, null)
|
||||
.set(JdPublishItemEntity::getUpdatedAt, now));
|
||||
log.info("[jd-publish][retry] 明细行已复位可续跑 taskId={} reset={}", taskId, updated);
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -29,10 +29,11 @@ public class CollectRoutingController {
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "查询新建任务的默认采集通道",
|
||||
description = "返回外观专利与相似ASIN在「这一单没登记通道」时按哪一侧执行。只读,无副作用。")
|
||||
description = "返回外观专利、相似ASIN 与品牌检测在「这一单没登记通道」时按哪一侧执行。只读,无副作用。")
|
||||
public ApiResponse<CollectRoutingVo> routing() {
|
||||
return ApiResponse.success(new CollectRoutingVo(
|
||||
CollectChannel.defaultFor(CollectRoutingProperties.MODULE_APPEARANCE_PATENT).isLocal(),
|
||||
CollectChannel.defaultFor(CollectRoutingProperties.MODULE_SIMILAR_ASIN).isLocal()));
|
||||
CollectChannel.defaultFor(CollectRoutingProperties.MODULE_SIMILAR_ASIN).isLocal(),
|
||||
CollectChannel.defaultFor(CollectRoutingProperties.MODULE_BRAND).isLocal()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,7 +30,8 @@ public enum CollectChannel {
|
||||
CollectRoutingProperties.MODULE_APPEARANCE_PATENT,
|
||||
CollectRoutingProperties.MODULE_SIMILAR_ASIN,
|
||||
CollectRoutingProperties.MODULE_JD_SHOP_COLLECT,
|
||||
CollectRoutingProperties.MODULE_JD_PUBLISH);
|
||||
CollectRoutingProperties.MODULE_JD_PUBLISH,
|
||||
CollectRoutingProperties.MODULE_BRAND);
|
||||
|
||||
/**
|
||||
* 未登记通道时读作 {@link #LOCAL} 的模块清单。
|
||||
@@ -38,6 +39,11 @@ public enum CollectChannel {
|
||||
* <p>{@link #defaultFor(String)} 与 mapper 里那条通道谓词({@code FileTaskMapper.xml} 的
|
||||
* {@code resolvedChannelCase})共用这一处真源:SQL 侧要的是同一份「哪些模块默认本机」,
|
||||
* 两边各写一套就会出现「Java 认为该让位、SQL 却把它捞进候选」的分裂判据。
|
||||
*
|
||||
* <p>BRAND 在这份清单里只服务于 {@link #defaultFor(String)}:品牌任务落在独立表
|
||||
* {@code brand_crawl_tasks}(V212),从不进 {@code biz_file_task},所以 SQL 那条 CASE
|
||||
* 见不到 {@code module_type='BRAND'} 的行,也不会被 {@code client-task-pull.module-types}
|
||||
* 白名单选中(那里没有 BRAND)。
|
||||
*/
|
||||
public static List<String> localDefaultModuleTypes() {
|
||||
return LOCAL_DEFAULT_MODULES;
|
||||
|
||||
+3
@@ -16,4 +16,7 @@ public class CollectRoutingVo {
|
||||
|
||||
@Schema(description = "相似ASIN是否本地采集:true=页面推本地客户端(超时后 Linux 兜底);false=只由 Linux 后台执行")
|
||||
private boolean similarAsinLocal;
|
||||
|
||||
@Schema(description = "品牌检测是否本地采集:true=桌面客户端本机执行;false=服务端 15126 执行(进程内跨账号并发默认 2)")
|
||||
private boolean brandLocal;
|
||||
}
|
||||
|
||||
+23
@@ -11,11 +11,13 @@ import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskChunkEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
||||
import com.nanri.aiimage.modules.task.spi.TaskItemsResetSpi;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||
|
||||
/**
|
||||
@@ -64,6 +66,7 @@ public class TaskInPlaceRetryService {
|
||||
private final TaskFileJobService taskFileJobService;
|
||||
private final TaskFileJobMapper taskFileJobMapper;
|
||||
private final ResultFileJobHandlerRegistry resultFileJobHandlers;
|
||||
private final List<TaskItemsResetSpi> itemsResetSpis;
|
||||
|
||||
/**
|
||||
* 把一条失败/已中断任务复位成待执行。幂等:只有当前状态确实是 FAILED/CANCELLED 才动作。
|
||||
@@ -105,6 +108,9 @@ public class TaskInPlaceRetryService {
|
||||
log.info("[task-retry] 状态已不是 FAILED/CANCELLED,跳过复位 taskId={}", task.getId());
|
||||
return false;
|
||||
}
|
||||
// 模块侧明细行复位(AC-7 服务端半边):不复位则重试后的明细分批下发是空页、任务空跑。
|
||||
// 无匹配实现=该模块没有模块侧明细行,什么也不做。
|
||||
resetModuleItems(task.getId(), task.getModuleType());
|
||||
// 形状 (a) 与中断代共用这一段:<b>失败代也要清直链</b>(B96-08 第 1 条修法)。
|
||||
// 旧写法只给中断代清、失败代留直链(本意「上一份可能已经可用」),叠上交付闸
|
||||
// 「直链非空即跳过」就成了恒定空转:作业复位后 2 秒又被标回 SUCCESS,新一代永远组装不了。
|
||||
@@ -216,6 +222,23 @@ public class TaskInPlaceRetryService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 模块侧明细行复位(AC-7 服务端半边):京东上架的行级真源在 biz_jd_publish_item,
|
||||
* 上一代的 FAILED/PUBLISHING 行不复位,重试后的明细分批下发(只出 PENDING 行)就是
|
||||
* 空页、任务空跑。无匹配实现=该模块没有模块侧明细行可复位,直接跳过。
|
||||
*
|
||||
* <p>刻意不吞异常(静默 catch 台账只许减):复位失败会留下「任务已 PENDING、明细没跟上」
|
||||
* 的半截状态,与 {@link #clearDeliveredResultUrl} 同一纪律——响亮失败让用户当场看到,
|
||||
* 不做半截继续。
|
||||
*/
|
||||
private void resetModuleItems(Long taskId, String moduleType) {
|
||||
for (TaskItemsResetSpi spi : itemsResetSpis) {
|
||||
if (moduleType.equals(spi.moduleType())) {
|
||||
spi.resetForRetry(taskId);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
/** 结果行只清错误文案:直链由 {@link #clearDeliveredResultUrl} 在复位前单独清(B96-08)。 */
|
||||
private void clearResultError(Long taskId, String moduleType) {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.nanri.aiimage.modules.task.spi;
|
||||
|
||||
/**
|
||||
* 失败/中断任务「在原任务上重试」的模块侧明细行复位扩展点(AC-7 服务端半边)。
|
||||
*
|
||||
* <p>背景:京东上架(JD_PUBLISH)的行级真源在 {@code biz_jd_publish_item}(V210),
|
||||
* 任务头被 {@code TaskInPlaceRetryService} 原地复位成 PENDING 后,明细分批下发
|
||||
* {@code selectPublishableItems} 只出 PENDING 行——上一代留下的 FAILED/PUBLISHING 行
|
||||
* 不复位,重试后的下发就是空页、任务空跑到判死(v1.5 蓝图 Phase 2 变更记录登记的欠账)。
|
||||
*
|
||||
* <p>各模块按需实现本接口,Spring 装配后由 {@code TaskInPlaceRetryService} 在任务头 CAS
|
||||
* 复位成功后按 {@code moduleType} 建索引调用。task 侧不 import 业务模块(task→业务依赖
|
||||
* 钉死为 0,{@code ArchitectureBoundaryTest} 同口径),与 {@link ClientTaskRetrySpi} 同族
|
||||
* 但语义相反:那个是「克隆新任务」的旧路(外观专利等解析载荷可整体复制的模块),
|
||||
* 这个是「原地续跑」——失败任务重试不克隆(2026-11-01 铁律 26)。
|
||||
*/
|
||||
public interface TaskItemsResetSpi {
|
||||
|
||||
/** 本实现负责的 moduleType(与 biz_file_task.module_type 一致)。 */
|
||||
String moduleType();
|
||||
|
||||
/**
|
||||
* 把该任务在模块侧的明细行复位成可续跑态。
|
||||
*
|
||||
* <p>仅在任务头 CAS 复位成功后被调用;失败不得吞异常——吞掉会留下
|
||||
* 「任务已 PENDING、明细还是旧状态」的半截状态,用户重按也修不回来
|
||||
* (状态闸会拒「只有失败或已中断的任务可以继续」),宁可当场响亮失败。
|
||||
*/
|
||||
void resetForRetry(Long taskId);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
-- V212: 品牌检测任务的采集执行通道(本机采集 / 线上采集)
|
||||
--
|
||||
-- 号段说明:本窗(2026-11-18)V211 已被 `V211__jd_publish_item_permit.sql`(另一路会话
|
||||
-- 的京东上架件)占用,本迁移让到 V212;同一版本号出现两支 Flyway 会直接报重复版本。
|
||||
--
|
||||
-- 背景(2026-11-18 用户拍板):
|
||||
-- 品牌检测原先只有**线上**一档——页面把 /api/brand/run 打到线上 15126,由那台机器
|
||||
-- 用共享代理池串行执行,进程内跨账号并发上限 BRAND_MAX_CONCURRENT_TASKS 默认 2。
|
||||
-- 两个大单(几百上千个品牌)就能把名额占满几小时,后面所有账号的任务全部排队,
|
||||
-- 排队上限 120 分钟;2026-11-17 任务 3374 实测排队 62 分钟、真正执行只 3 分半。
|
||||
-- 现在照外观专利/相似ASIN 的口径(V183)改成建单时界面单选,默认本机:
|
||||
-- 本机执行用用户自己的代理(客户端启动时已把共享代理门面注入 brand_spider),
|
||||
-- 不占服务端名额。
|
||||
--
|
||||
-- 设计口径(与 V183 逐条同形):
|
||||
-- * 可空:NULL=「这一单没登记通道」,由 `CollectChannel.defaultFor(moduleType)` 兜,
|
||||
-- BRAND 读作 LOCAL;历史行不回填,老客户端不带该字段时仍按默认走;
|
||||
-- * 不加索引:品牌任务按 (status, updated_at) 扫描(V120 的
|
||||
-- idx_brand_crawl_task_status_updated),通道只影响"谁来执行",不参与取页;
|
||||
-- * 与 V183 的差异:品牌任务表是 brand_crawl_tasks(不是 biz_file_task),
|
||||
-- 状态词表是小写(pending/running/success/failed/cancelled),本列只记录执行方。
|
||||
--
|
||||
-- 回滚(手工):
|
||||
-- ALTER TABLE `brand_crawl_tasks` DROP COLUMN `collect_channel`;
|
||||
|
||||
ALTER TABLE `brand_crawl_tasks`
|
||||
ADD COLUMN `collect_channel` VARCHAR(16) NULL
|
||||
COMMENT '采集执行通道:LOCAL=桌面客户端本机采/ONLINE=服务端 15126 采;空=按模块默认' AFTER `device_id`;
|
||||
@@ -115,7 +115,13 @@
|
||||
<sql id="productConds">
|
||||
<if test="productCode != null and productCode != ''">AND p.product_code LIKE CONCAT('%', #{productCode}, '%')</if>
|
||||
<if test="titleKeyword != null and titleKeyword != ''">AND p.title LIKE CONCAT('%', #{titleKeyword}, '%')</if>
|
||||
<if test="category != null and category != ''">AND p.category_path = #{category}</if>
|
||||
<!-- 类目过滤(2026-11-18 一级/二级类目可选):单值=原 eq 形状;父级选中由前端展开为
|
||||
子树类目名集合,这里 IN 下推(铁律 20:谓词必须在 SQL 侧,不得 Java 侧对已取页 filter)。
|
||||
服务侧已逐项 trim/去空白/去重,空集合归 null 不进本分支。 -->
|
||||
<if test="categories != null and categories.size() > 0">
|
||||
AND p.category_path IN
|
||||
<foreach collection="categories" item="cat" open="(" separator="," close=")">#{cat}</foreach>
|
||||
</if>
|
||||
<if test="groupId != null and groupId > 0">
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM biz_jd_product_group_assign a
|
||||
|
||||
@@ -97,9 +97,11 @@ class MigrationInventoryTest {
|
||||
* 2026-11-17 已改号 {@code V207__users_jd_publish_quota.sql} 入库(V206 被同窗
|
||||
* admin_account_platform 三表平台列占用,account-platform 提交);202 号自此彻底空置。</p>
|
||||
*
|
||||
* <p><b>211</b>:生产已应用 V212,且 Flyway 未开启 out-of-order;211 永久留空,不得回填。</p>
|
||||
*
|
||||
* <p>共同后果:新迁移只能取当前最大值之上的号(详见 docs/migration-inventory.md)。</p>
|
||||
*/
|
||||
private static final Set<Integer> RETIRED_HOLES = Set.of(132, 133, 148, 168, 169, 202);
|
||||
private static final Set<Integer> RETIRED_HOLES = Set.of(132, 133, 148, 168, 169, 202, 211);
|
||||
|
||||
/**
|
||||
* 文件名版本与头注释版本不一致的历史件。V170 的头注释误写成 V168;它已应用到生产,
|
||||
|
||||
+70
-3
@@ -172,7 +172,9 @@ class AdminUserServiceCompanySuperAdminTest {
|
||||
// ---------- 列表 ----------
|
||||
|
||||
@Test
|
||||
void companySuperAdminListsOwnCompanyWithoutSiteSuperAdmin() {
|
||||
void companySuperAdminOnlyListsOwnSubordinates() {
|
||||
// 2026-11-18 客户口径:公司超管只看「本人那行+自己直接创建的」,不再看本公司全部。
|
||||
// 判据形状:谓词必须同时出现 company_id、created_by_id 与 id=本人(读侧与组长档同形)。
|
||||
AdminUserEntity operator = user(9L, "company_super_admin", 2L, null);
|
||||
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
|
||||
when(userMapper.selectCount(any())).thenReturn(0L);
|
||||
@@ -184,8 +186,27 @@ class AdminUserServiceCompanySuperAdminTest {
|
||||
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(userMapper).selectCount(captor.capture());
|
||||
// 先碰一次 SqlSegment 才会铺出参数(MP 惯例)
|
||||
captor.getValue().getSqlSegment();
|
||||
assertThat(captor.getValue().getParamNameValuePairs().values()).contains(2L);
|
||||
String sql = captor.getValue().getSqlSegment();
|
||||
assertThat(sql).contains("company_id").contains("created_by_id");
|
||||
assertThat(captor.getValue().getParamNameValuePairs().values())
|
||||
.contains(2L) // 本公司
|
||||
.contains(9L); // 本人(id=本人 OR created_by_id=本人,两处同一值)
|
||||
}
|
||||
|
||||
@Test
|
||||
void siteSuperAdminListStillUnscopedBySubordinates() {
|
||||
// 反向保险:收窄只落在公司超管档——平台超管「看所有」,谓词里不得出现 created_by_id 强制项
|
||||
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
when(userMapper.selectCount(any())).thenReturn(0L);
|
||||
when(userMapper.selectList(any())).thenReturn(List.of());
|
||||
|
||||
service.listUsers(operator, 1, 15, null, null, null, null);
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper<AdminUserEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(userMapper).selectCount(captor.capture());
|
||||
assertThat(captor.getValue().getSqlSegment()).doesNotContain("created_by_id");
|
||||
}
|
||||
|
||||
// ---------- 编辑 ----------
|
||||
@@ -244,6 +265,52 @@ class AdminUserServiceCompanySuperAdminTest {
|
||||
.hasMessageContaining("只有超级管理员可以修改公司超级管理员");
|
||||
}
|
||||
|
||||
@Test
|
||||
void companySuperAdminCannotEditAccountCreatedByOthers() {
|
||||
// 2026-11-18 写侧与读侧同口径:本公司但由别人(组长8/站点超管)创建的账号,
|
||||
// 列表已不可见,API 也必须 403——不留「看不见但改得动」的洞。
|
||||
AdminUserEntity operator = user(9L, "company_super_admin", 1L, 2L);
|
||||
AdminUserEntity target = user(12L, "admin", 1L, 8L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
|
||||
when(userMapper.selectById(12L)).thenReturn(target);
|
||||
|
||||
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
|
||||
request.setPassword("secret1");
|
||||
|
||||
assertThatThrownBy(() -> service.updateUser(operator, 12L, request))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("只能编辑自己名下创建的账号");
|
||||
verify(userMapper, never()).update(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void companySuperAdminCanEditOwnCreatedAdmin() {
|
||||
AdminUserEntity operator = user(9L, "company_super_admin", 1L, 2L);
|
||||
AdminUserEntity target = user(12L, "admin", 1L, 9L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
|
||||
when(userMapper.selectById(12L)).thenReturn(target);
|
||||
|
||||
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
|
||||
request.setPassword("secret1");
|
||||
|
||||
service.updateUser(operator, 12L, request);
|
||||
|
||||
verify(userMapper).update(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void companySuperAdminCannotDeleteAccountCreatedByOthers() {
|
||||
AdminUserEntity operator = user(9L, "company_super_admin", 1L, 2L);
|
||||
AdminUserEntity target = user(12L, "normal", 1L, 8L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
|
||||
when(userMapper.selectById(12L)).thenReturn(target);
|
||||
|
||||
assertThatThrownBy(() -> service.deleteUser(operator, 12L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("只能删除自己名下创建的账号");
|
||||
verify(userMapper, never()).deleteById(12L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void companySuperAdminCannotDeleteCompanySuperAdminTarget() {
|
||||
AdminUserEntity operator = user(9L, "company_super_admin", 1L, 2L);
|
||||
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
package com.nanri.aiimage.modules.brand.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
import com.nanri.aiimage.config.BrandProgressProperties;
|
||||
import com.nanri.aiimage.config.StorageProperties;
|
||||
import com.nanri.aiimage.modules.brand.mapper.BrandCrawlTaskMapper;
|
||||
import com.nanri.aiimage.modules.brand.model.dto.BrandSourceFileDto;
|
||||
import com.nanri.aiimage.modules.brand.model.dto.BrandTaskCreateRequest;
|
||||
import com.nanri.aiimage.modules.brand.model.entity.BrandCrawlTaskEntity;
|
||||
import com.nanri.aiimage.modules.brand.model.vo.BrandTaskCreateVo;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskDistributedLockService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFileJobService;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
* 品牌检测建单口的执行通道落库契约(V212)。
|
||||
*
|
||||
* <p>背景:品牌原先只有线上一条路——页面把请求打到 15126,由那台机器用共享代理池执行,
|
||||
* 进程内跨账号并发上限默认 2。两个大单就能把名额占满几小时,2026-11-17 任务 3374
|
||||
* 排队 62 分钟、真正执行只 3 分半。现在照外观专利/相似ASIN(V183)改成建单时界面单选,
|
||||
* 默认本机:本机跑用用户自己的代理,不占服务端名额。
|
||||
*
|
||||
* <p>这里钉三条:① 界面选的 ONLINE/LOCAL 必须原样落库,不许"界面选了线上、库里没登记"
|
||||
* 让执行方按默认换边;② 不传/脏值一律不登记(留 NULL 交给模块默认),不得把脏值写进库;
|
||||
* ③ 回执里的通道是「库里真正生效的那一侧」,NULL 也告诉前端按哪边兜。
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class BrandTaskCreateChannelTest {
|
||||
|
||||
@Mock private BrandCrawlTaskMapper brandCrawlTaskMapper;
|
||||
@Mock private OssStorageService ossStorageService;
|
||||
@Mock private StorageProperties storageProperties;
|
||||
@Mock private BrandProgressProperties brandProgressProperties;
|
||||
@Mock private BrandTaskProgressCacheService brandTaskProgressCacheService;
|
||||
@Mock private BrandTaskStorageService brandTaskStorageService;
|
||||
@Mock private DistributedJobLockService distributedJobLockService;
|
||||
@Mock private TaskDistributedLockService taskDistributedLockService;
|
||||
@Mock private TaskFileJobService taskFileJobService;
|
||||
@Mock private TaskProgressSnapshotService taskProgressSnapshotService;
|
||||
|
||||
@BeforeAll
|
||||
static void initializeTableInfo() {
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
BrandCrawlTaskEntity.class);
|
||||
}
|
||||
|
||||
private BrandTaskService service() {
|
||||
return new BrandTaskService(brandCrawlTaskMapper, ossStorageService, storageProperties,
|
||||
brandProgressProperties, brandTaskProgressCacheService,
|
||||
mock(com.nanri.aiimage.modules.task.service.TaskHeartbeatPositionService.class),
|
||||
brandTaskStorageService,
|
||||
distributedJobLockService, taskDistributedLockService, new ObjectMapper(),
|
||||
taskFileJobService, taskProgressSnapshotService,
|
||||
mock(com.nanri.aiimage.modules.notification.service.NotificationDispatchService.class));
|
||||
}
|
||||
|
||||
private BrandTaskCreateRequest request(String collectChannel) {
|
||||
BrandSourceFileDto file = new BrandSourceFileDto();
|
||||
file.setFileUrl("https://oss.aishufu.top/nanri-ai-images/source/brand.xlsx");
|
||||
file.setOriginalFilename("品牌样例.xlsx");
|
||||
BrandTaskCreateRequest request = new BrandTaskCreateRequest();
|
||||
request.setFiles(List.of(file));
|
||||
request.setStrategy("Simple");
|
||||
request.setTaskType(1);
|
||||
request.setCollectChannel(collectChannel);
|
||||
return request;
|
||||
}
|
||||
|
||||
@Test
|
||||
void 界面选的线上通道原样落库并回显() {
|
||||
BrandTaskCreateVo vo = service().createTask(1338L, request("ONLINE"), "device-1");
|
||||
|
||||
ArgumentCaptor<BrandCrawlTaskEntity> captor = ArgumentCaptor.forClass(BrandCrawlTaskEntity.class);
|
||||
verify(brandCrawlTaskMapper).insert(captor.capture());
|
||||
assertEquals("ONLINE", captor.getValue().getCollectChannel(),
|
||||
"界面选了线上,库列必须是 ONLINE;落空就会按模块默认换成本机");
|
||||
assertEquals("ONLINE", vo.getCollectChannel(), "回执要与库列同侧");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 界面选的本机通道原样落库并回显() {
|
||||
BrandTaskCreateVo vo = service().createTask(1338L, request(" local "), "device-1");
|
||||
|
||||
ArgumentCaptor<BrandCrawlTaskEntity> captor = ArgumentCaptor.forClass(BrandCrawlTaskEntity.class);
|
||||
verify(brandCrawlTaskMapper).insert(captor.capture());
|
||||
assertEquals("LOCAL", captor.getValue().getCollectChannel(), "大小写与空白按规范值归一");
|
||||
assertEquals("LOCAL", vo.getCollectChannel());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 未传通道时留空并由模块默认兜成本机() {
|
||||
BrandTaskCreateVo vo = service().createTask(1338L, request(null), "device-1");
|
||||
|
||||
ArgumentCaptor<BrandCrawlTaskEntity> captor = ArgumentCaptor.forClass(BrandCrawlTaskEntity.class);
|
||||
verify(brandCrawlTaskMapper).insert(captor.capture());
|
||||
assertNull(captor.getValue().getCollectChannel(), "不登记=留空,不许替用户猜一个值写死进库");
|
||||
assertEquals("LOCAL", vo.getCollectChannel(),
|
||||
"回执要报库里真正生效的一侧:BRAND 的模块默认是本机");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 不可识别的通道值不落库只回落默认() {
|
||||
BrandTaskCreateVo vo = service().createTask(1338L, request("本地"), "device-1");
|
||||
|
||||
ArgumentCaptor<BrandCrawlTaskEntity> captor = ArgumentCaptor.forClass(BrandCrawlTaskEntity.class);
|
||||
verify(brandCrawlTaskMapper).insert(captor.capture());
|
||||
assertNull(captor.getValue().getCollectChannel(), "脏值不能进库,否则读侧只能当默认");
|
||||
assertEquals("LOCAL", vo.getCollectChannel());
|
||||
}
|
||||
|
||||
/** 前端按 snake_case 传(`collect_channel`),老调用方按 camelCase 传,两种都得绑上。 */
|
||||
@Test
|
||||
void 请求体两种字段名都能绑定() throws Exception {
|
||||
String body = "{\"files\":[{\"fileUrl\":\"https://oss.aishufu.top/a.xlsx\"}],"
|
||||
+ "\"strategy\":\"Simple\",\"collect_channel\":\"ONLINE\"}";
|
||||
assertEquals("ONLINE", new ObjectMapper()
|
||||
.readValue(body, BrandTaskCreateRequest.class).getCollectChannel());
|
||||
|
||||
String camel = "{\"files\":[{\"fileUrl\":\"https://oss.aishufu.top/a.xlsx\"}],"
|
||||
+ "\"strategy\":\"Simple\",\"collectChannel\":\"local\"}";
|
||||
assertEquals("local", new ObjectMapper()
|
||||
.readValue(camel, BrandTaskCreateRequest.class).getCollectChannel());
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.nanri.aiimage.modules.brand.service;
|
||||
|
||||
import com.nanri.aiimage.config.BrandProgressProperties;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyList;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 品牌心跳 phase 白名单(2026-11-18)。
|
||||
*
|
||||
* <p>排队期(客户端等账号锁/全局并发槽位,跨账号默认 2 个名额)此前一律报
|
||||
* {@code crawling},界面把「排队 62 分钟」显示成「品牌查询中 0/N」,用户只能
|
||||
* 以为任务卡死。现在客户端排队期报 {@code queued},后端必须原样保留——
|
||||
* 归一成 crawling 就等于把这条显示修回原形。
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class BrandTaskProgressCacheQueuedPhaseTest {
|
||||
|
||||
@Mock
|
||||
private StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
@Mock
|
||||
private BrandProgressProperties brandProgressProperties;
|
||||
|
||||
private BrandTaskProgressCacheService newService() {
|
||||
when(brandProgressProperties.getTtlHours()).thenReturn(24L);
|
||||
return new BrandTaskProgressCacheService(
|
||||
stringRedisTemplate, brandProgressProperties, new com.fasterxml.jackson.databind.ObjectMapper());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("排队期 phase=queued 原样下传(不得归一成 crawling)")
|
||||
void queuedPhaseIsKept() {
|
||||
newService().touchHeartbeat(3374L, "queued", 0, 49);
|
||||
verify(stringRedisTemplate).execute(
|
||||
any(DefaultRedisScript.class), anyList(),
|
||||
eq(BrandTaskProgressCacheService.PHASE_QUEUED), eq("0"), eq("49"), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("白名单外的 phase 仍归一成 crawling(防止脏值写进缓存)")
|
||||
void unknownPhaseFallsBackToCrawling() {
|
||||
newService().touchHeartbeat(3374L, "whatever", 0, 49);
|
||||
verify(stringRedisTemplate).execute(
|
||||
any(DefaultRedisScript.class), anyList(),
|
||||
eq(BrandTaskProgressCacheService.PHASE_CRAWLING), eq("0"), eq("49"), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("执行期 crawling 与收尾阶段 assembling 保持原语义")
|
||||
void crawlingAndAssemblingUnchanged() {
|
||||
newService().touchHeartbeat(1L, "crawling", 5, 49);
|
||||
verify(stringRedisTemplate).execute(
|
||||
any(DefaultRedisScript.class), anyList(),
|
||||
eq(BrandTaskProgressCacheService.PHASE_CRAWLING), eq("5"), eq("49"), anyString());
|
||||
|
||||
newService().touchHeartbeat(2L, "assembling", 49, 49);
|
||||
verify(stringRedisTemplate).execute(
|
||||
any(DefaultRedisScript.class), anyList(),
|
||||
eq(BrandTaskProgressCacheService.PHASE_ASSEMBLING), eq("49"), eq("49"), anyString());
|
||||
}
|
||||
}
|
||||
+36
-3
@@ -726,15 +726,48 @@ class AdminJdProductControllerTest {
|
||||
JdProductMapper mapper = mock(JdProductMapper.class);
|
||||
JdProductQueryService service = queryService(mapper);
|
||||
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(1L);
|
||||
service.page(1L, 20L, " SKU-1 ", " 连衣裙 ", " 艺考形体服 ", 7L, null, null, null, null);
|
||||
verify(mapper).countProducts("SKU-1", "连衣裙", "艺考形体服", 7L, null, null, null, null);
|
||||
verify(mapper).selectProductPage("SKU-1", "连衣裙", "艺考形体服", 7L, null, null, null, null, 0L, 20);
|
||||
service.page(1L, 20L, " SKU-1 ", " 连衣裙 ", List.of(" 艺考形体服 "), 7L, null, null, null, null);
|
||||
verify(mapper).countProducts("SKU-1", "连衣裙", List.of("艺考形体服"), 7L, null, null, null, null);
|
||||
verify(mapper).selectProductPage("SKU-1", "连衣裙", List.of("艺考形体服"), 7L, null, null, null, null, 0L, 20);
|
||||
|
||||
service.page(1L, 20L, " ", null, null, 0L, null, null, null, null);
|
||||
verify(mapper).countProducts(null, null, null, null, null, null, null, null);
|
||||
verify(mapper).selectProductPage(null, null, null, null, null, null, null, null, 0L, 20);
|
||||
}
|
||||
|
||||
/**
|
||||
* 2026-11-18 一级/二级类目可选(前端展开子树类目名集合下发):
|
||||
* ① 服务侧逐项 trim、去空白、去重后进 mapper;全空白集合归 null=不过滤该面;
|
||||
* ② XML 绊线:类目谓词必须是 IN+foreach 下推(改回单值 eq 即红,铁律 20 同形)。
|
||||
*/
|
||||
@Test
|
||||
void 类目多值必须逐项归一并IN下推() throws IOException {
|
||||
JdProductMapper mapper = mock(JdProductMapper.class);
|
||||
JdProductQueryService service = queryService(mapper);
|
||||
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(1L);
|
||||
|
||||
service.page(1L, 20L, null, null,
|
||||
java.util.Arrays.asList(" 女装 ", "女装", "", null, " 汉服/旗袍 "),
|
||||
null, null, null, null, null);
|
||||
verify(mapper).countProducts(null, null, List.of("女装", "汉服/旗袍"),
|
||||
null, null, null, null, null);
|
||||
verify(mapper).selectProductPage(null, null, List.of("女装", "汉服/旗袍"),
|
||||
null, null, null, null, null, 0L, 20);
|
||||
|
||||
// 全空白/空集合=不过滤该面(与「全部类目」清选同口径,不得下发空 IN)
|
||||
service.page(1L, 20L, null, null, java.util.Arrays.asList(" ", ""), null, null, null, null, null);
|
||||
verify(mapper).countProducts(null, null, null, null, null, null, null, null);
|
||||
|
||||
Path xml = findJdProductMapperXml();
|
||||
String xmlText = stripComments(Files.readString(xml)).replaceAll("(?s)<!--.*?-->", "");
|
||||
assertTrue(xmlText.contains("p.category_path IN"),
|
||||
"类目谓词必须是 IN 下推(2026-11-18 父级类目展开集合)");
|
||||
assertTrue(xmlText.contains("<foreach collection=\"categories\""),
|
||||
"IN 集合必须由 foreach 展开(拼串即红)");
|
||||
assertFalse(xmlText.contains("p.category_path = #{category}"),
|
||||
"改回单值 eq 即红——一级/二级类目展开会整体失效");
|
||||
}
|
||||
|
||||
/**
|
||||
* 分类状态快筛(2026-11-17 用户口径「加个已分类和未分类的筛选」):
|
||||
* ① classified+ownerGroupId 必须原样下传给 mapper(谓词在 XML 的 EXISTS/NOT EXISTS 段,
|
||||
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.nanri.aiimage.modules.jd.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity;
|
||||
import com.nanri.aiimage.testutil.UpdateWrapperProbe;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* AC-7 服务端半边(v1.5 Phase 5 消欠账):京东上架失败任务「重试」时,
|
||||
* {@code biz_jd_publish_item} 的 FAILED/PUBLISHING 行必须复位回 PENDING 并清旧错误文案。
|
||||
*
|
||||
* <p>不复位的后果(蓝图 Phase 2 变更记录登记):任务头复位成 PENDING 后,
|
||||
* 明细分批下发 {@code selectPublishableItems} 只出 PENDING 行——重试就是空页空跑,
|
||||
* 任务等满 stale 窗口再被判死一次。SUCCESS 行不动(已发布商品不重发,AC-4)。
|
||||
*/
|
||||
class JdPublishTaskItemsResetSpiImplTest {
|
||||
|
||||
@BeforeAll
|
||||
static void initMybatisPlusTableInfo() {
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
JdPublishItemEntity.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void moduleType与建单模块一致() {
|
||||
assertEquals("JD_PUBLISH",
|
||||
new JdPublishTaskItemsResetSpiImpl(mock(JdPublishItemMapper.class)).moduleType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 复位只圈FAILED与PUBLISHING行_清旧错误文案_不碰SUCCESS() {
|
||||
JdPublishItemMapper mapper = mock(JdPublishItemMapper.class);
|
||||
when(mapper.update(isNull(), any())).thenReturn(3);
|
||||
|
||||
new JdPublishTaskItemsResetSpiImpl(mapper).resetForRetry(34567L);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<LambdaUpdateWrapper<JdPublishItemEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
|
||||
verify(mapper).update(isNull(), captor.capture());
|
||||
LambdaUpdateWrapper<JdPublishItemEntity> wrapper = captor.getValue();
|
||||
|
||||
Map<String, Object> sets = UpdateWrapperProbe.setValues(wrapper);
|
||||
assertEquals("PENDING", sets.get("publish_status"), "复位目标态必须是 PENDING(下发只出 PENDING 行)");
|
||||
assertTrue(sets.containsKey("publish_error"), "旧失败文案必须清");
|
||||
assertNull(sets.get("publish_error"), "旧失败文案清成 NULL,不留给待发布行");
|
||||
assertTrue(sets.containsKey("updated_at"), "行级 updated_at 随复位推进");
|
||||
|
||||
// WHERE:按任务圈行;行状态谓词只认 FAILED/PUBLISHING——SUCCESS 行是已发布商品,不重发(AC-4)
|
||||
assertEquals(34567L, UpdateWrapperProbe.whereEq(wrapper).get("task_id"));
|
||||
Map<String, Object> params = UpdateWrapperProbe.paramNameValuePairs(wrapper);
|
||||
assertTrue(params.containsValue("FAILED"), "行状态谓词必须含 FAILED");
|
||||
assertTrue(params.containsValue("PUBLISHING"), "行状态谓词必须含 PUBLISHING(中断遗留行)");
|
||||
assertTrue(params.containsValue("PENDING"), "复位目标值在参数册");
|
||||
}
|
||||
}
|
||||
+5
-2
@@ -28,7 +28,8 @@ class CollectRoutingControllerTest {
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.success").value(true))
|
||||
.andExpect(jsonPath("$.data.appearancePatentLocal").value(true))
|
||||
.andExpect(jsonPath("$.data.similarAsinLocal").value(true));
|
||||
.andExpect(jsonPath("$.data.similarAsinLocal").value(true))
|
||||
.andExpect(jsonPath("$.data.brandLocal").value(true));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -42,6 +43,8 @@ class CollectRoutingControllerTest {
|
||||
mockMvc.perform(get("/api/collect-routing"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.data.appearancePatentLocal").value(true))
|
||||
.andExpect(jsonPath("$.data.similarAsinLocal").value(true));
|
||||
.andExpect(jsonPath("$.data.similarAsinLocal").value(true))
|
||||
// 品牌检测(V212)同样默认本机:服务端只有 2 个跨账号并发名额。
|
||||
.andExpect(jsonPath("$.data.brandLocal").value(true));
|
||||
}
|
||||
}
|
||||
|
||||
+20
-2
@@ -39,11 +39,13 @@ class CollectChannelTest {
|
||||
*/
|
||||
@Test
|
||||
void 本机默认模块清单与defaultFor同源() {
|
||||
// v1.5 起含 JD_PUBLISH(京麦登录态只在用户桌面机 19899 Chrome,铁律 19 同形)。
|
||||
// v1.5 起含 JD_PUBLISH(京麦登录态只在用户桌面机 19899 Chrome,铁律 19 同形);
|
||||
// 2026-11-18 起含 BRAND(服务端 15126 只有 2 个跨账号并发名额,品牌默认本机执行)。
|
||||
assertEquals(List.of(CollectRoutingProperties.MODULE_APPEARANCE_PATENT,
|
||||
CollectRoutingProperties.MODULE_SIMILAR_ASIN,
|
||||
CollectRoutingProperties.MODULE_JD_SHOP_COLLECT,
|
||||
CollectRoutingProperties.MODULE_JD_PUBLISH), CollectChannel.localDefaultModuleTypes());
|
||||
CollectRoutingProperties.MODULE_JD_PUBLISH,
|
||||
CollectRoutingProperties.MODULE_BRAND), CollectChannel.localDefaultModuleTypes());
|
||||
for (String module : CollectChannel.localDefaultModuleTypes()) {
|
||||
assertTrue(CollectChannel.defaultFor(module).isLocal(), module + " 在清单里却不被判本机");
|
||||
}
|
||||
@@ -58,6 +60,22 @@ class CollectChannelTest {
|
||||
assertEquals(CollectChannel.LOCAL, CollectChannel.defaultFor(" SIMILAR_ASIN "));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 品牌检测未登记通道时默认本机() {
|
||||
// 服务端 15126 进程内跨账号并发默认 2 个名额,大单会把后面所有账号的任务排到
|
||||
// 120 分钟上限(2026-11-17 任务 3374 排队 62 分钟、实际执行 3 分半)。
|
||||
// 品牌默认翻转成 ONLINE,等于把这条排队重新钉回所有用户。
|
||||
assertEquals(CollectChannel.LOCAL,
|
||||
CollectChannel.defaultFor(CollectRoutingProperties.MODULE_BRAND));
|
||||
assertEquals(CollectChannel.LOCAL, CollectChannel.defaultFor(" brand "));
|
||||
assertEquals(CollectChannel.ONLINE,
|
||||
CollectChannel.resolve("ONLINE", CollectRoutingProperties.MODULE_BRAND),
|
||||
"这一单显式选了线上就必须读成线上");
|
||||
assertEquals(CollectChannel.LOCAL,
|
||||
CollectChannel.resolve(null, CollectRoutingProperties.MODULE_BRAND),
|
||||
"库列为空的存量行按模块默认读成本机");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 库里登记过就按登记的读() {
|
||||
assertEquals(CollectChannel.ONLINE,
|
||||
|
||||
+82
-1
@@ -12,6 +12,7 @@ import com.nanri.aiimage.modules.task.model.entity.FileResultEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskChunkEntity;
|
||||
import com.nanri.aiimage.modules.task.model.entity.TaskFileJobEntity;
|
||||
import com.nanri.aiimage.modules.task.spi.TaskItemsResetSpi;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -83,7 +84,16 @@ class TaskInPlaceRetryServiceTest {
|
||||
TaskChunkMapper chunks, TaskFileJobService jobs,
|
||||
TaskFileJobMapper jobMapper,
|
||||
ResultFileJobHandlerRegistry registry) {
|
||||
return new TaskInPlaceRetryService(mapper, results, chunks, jobs, jobMapper, registry);
|
||||
return service(mapper, results, chunks, jobs, jobMapper, registry, java.util.List.of());
|
||||
}
|
||||
|
||||
/** AC-7 服务端半边:模块侧明细行复位 SPI(京东上架 JD_PUBLISH)。 */
|
||||
private static TaskInPlaceRetryService service(FileTaskMapper mapper, FileResultMapper results,
|
||||
TaskChunkMapper chunks, TaskFileJobService jobs,
|
||||
TaskFileJobMapper jobMapper,
|
||||
ResultFileJobHandlerRegistry registry,
|
||||
java.util.List<TaskItemsResetSpi> itemsResetSpis) {
|
||||
return new TaskInPlaceRetryService(mapper, results, chunks, jobs, jobMapper, registry, itemsResetSpis);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -118,6 +128,77 @@ class TaskInPlaceRetryServiceTest {
|
||||
assertFalse(ok);
|
||||
verify(jobs, never()).resetTerminalFailedForRecovery(anyLong(), any(), anyLong());
|
||||
}
|
||||
// ---- AC-7 服务端半边(v1.5 Phase 5):模块侧明细行随任务头一并复位 ----
|
||||
|
||||
@Test
|
||||
void 京东上架重试必须复位模块侧明细行() {
|
||||
FileTaskMapper mapper = mock(FileTaskMapper.class);
|
||||
FileResultMapper results = mock(FileResultMapper.class);
|
||||
TaskFileJobService jobs = mock(TaskFileJobService.class);
|
||||
when(mapper.update(isNull(), any())).thenReturn(1);
|
||||
TaskItemsResetSpi jdSpi = mock(TaskItemsResetSpi.class);
|
||||
when(jdSpi.moduleType()).thenReturn("JD_PUBLISH");
|
||||
FileTaskEntity task = failedTask();
|
||||
task.setModuleType("JD_PUBLISH");
|
||||
|
||||
service(mapper, results, mock(TaskChunkMapper.class), jobs,
|
||||
mock(TaskFileJobMapper.class), mock(ResultFileJobHandlerRegistry.class),
|
||||
java.util.List.of(jdSpi)).retryInPlace(task);
|
||||
|
||||
// 明细行随任务头一起回到 PENDING,否则重试后的明细分批下发(只出 PENDING 行)是空页空跑
|
||||
verify(jdSpi).resetForRetry(eq(32967L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 任务头复位失败时不碰模块明细行() {
|
||||
FileTaskMapper mapper = mock(FileTaskMapper.class);
|
||||
FileResultMapper results = mock(FileResultMapper.class);
|
||||
TaskFileJobService jobs = mock(TaskFileJobService.class);
|
||||
when(mapper.update(isNull(), any())).thenReturn(0);
|
||||
TaskItemsResetSpi jdSpi = mock(TaskItemsResetSpi.class);
|
||||
when(jdSpi.moduleType()).thenReturn("JD_PUBLISH");
|
||||
|
||||
service(mapper, results, mock(TaskChunkMapper.class), jobs,
|
||||
mock(TaskFileJobMapper.class), mock(ResultFileJobHandlerRegistry.class),
|
||||
java.util.List.of(jdSpi)).retryInPlace(failedTask());
|
||||
|
||||
verify(jdSpi, never()).resetForRetry(anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 无匹配模块的明细复位直接跳过() {
|
||||
FileTaskMapper mapper = mock(FileTaskMapper.class);
|
||||
FileResultMapper results = mock(FileResultMapper.class);
|
||||
TaskFileJobService jobs = mock(TaskFileJobService.class);
|
||||
when(mapper.update(isNull(), any())).thenReturn(1);
|
||||
TaskItemsResetSpi jdSpi = mock(TaskItemsResetSpi.class);
|
||||
when(jdSpi.moduleType()).thenReturn("JD_PUBLISH");
|
||||
|
||||
service(mapper, results, mock(TaskChunkMapper.class), jobs,
|
||||
mock(TaskFileJobMapper.class), mock(ResultFileJobHandlerRegistry.class),
|
||||
java.util.List.of(jdSpi)).retryInPlace(failedTask());
|
||||
|
||||
verify(jdSpi, never()).resetForRetry(anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 明细复位失败必须响亮失败不留半截状态() {
|
||||
FileTaskMapper mapper = mock(FileTaskMapper.class);
|
||||
FileResultMapper results = mock(FileResultMapper.class);
|
||||
TaskFileJobService jobs = mock(TaskFileJobService.class);
|
||||
when(mapper.update(isNull(), any())).thenReturn(1);
|
||||
TaskItemsResetSpi jdSpi = mock(TaskItemsResetSpi.class);
|
||||
when(jdSpi.moduleType()).thenReturn("JD_PUBLISH");
|
||||
org.mockito.Mockito.doThrow(new IllegalStateException("reset failed"))
|
||||
.when(jdSpi).resetForRetry(anyLong());
|
||||
FileTaskEntity task = failedTask();
|
||||
task.setModuleType("JD_PUBLISH");
|
||||
|
||||
// 吞掉会留下「任务已 PENDING、明细没跟上」的半截状态,用户重按也修不回来
|
||||
assertThrows(IllegalStateException.class, () -> service(mapper, results,
|
||||
mock(TaskChunkMapper.class), jobs, mock(TaskFileJobMapper.class),
|
||||
mock(ResultFileJobHandlerRegistry.class), java.util.List.of(jdSpi)).retryInPlace(task));
|
||||
}
|
||||
|
||||
// ---- 「继续」(2026-11-03):已中断任务在原任务上复位 ----
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<aside class="left-panel">
|
||||
<div class="section-title">待检品牌文件</div>
|
||||
<FileUploadZone
|
||||
hint="Excel 每行含「品牌」列即会加入检测。可多选文件或选择整个文件夹(.xlsx)。检测由本机客户端执行,请在桌面客户端中打开本页面。"
|
||||
hint="Excel 每行含「品牌」列即会加入检测。可多选文件或选择整个文件夹(.xlsx)。请在桌面客户端中打开本页面提交。"
|
||||
:names="selectedPaths"
|
||||
:max-display="8"
|
||||
:disabled="!hasBridge"
|
||||
@@ -30,6 +30,35 @@
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="section-title">本单采集方式</div>
|
||||
<div class="radio-cards">
|
||||
<label class="radio-card" :class="{ selected: collectChannel === 'LOCAL' }">
|
||||
<input
|
||||
type="radio"
|
||||
name="brand-channel"
|
||||
value="LOCAL"
|
||||
v-model="collectChannel"
|
||||
:disabled="channelLocked || !canRunLocal"
|
||||
/>
|
||||
<span class="radio-card-name">本机采集(推荐)</span>
|
||||
<span class="radio-card-desc">由本机客户端执行:用你自己的代理,不受服务端并发名额排队影响</span>
|
||||
</label>
|
||||
<label class="radio-card" :class="{ selected: collectChannel === 'ONLINE' }">
|
||||
<input
|
||||
type="radio"
|
||||
name="brand-channel"
|
||||
value="ONLINE"
|
||||
v-model="collectChannel"
|
||||
:disabled="channelLocked"
|
||||
/>
|
||||
<span class="radio-card-name">线上采集</span>
|
||||
<span class="radio-card-desc">由服务端执行:并发名额有限,前面有大单时会排队较久</span>
|
||||
</label>
|
||||
</div>
|
||||
<p v-if="!canRunLocal" class="env-tip">
|
||||
当前客户端版本不支持「本机采集」,请升级客户端;本次将走线上采集。
|
||||
</p>
|
||||
|
||||
<div class="section-title">运行方式</div>
|
||||
<p class="loading-msg">提交后立即开始检测,可在右侧任务列表查看进度或取消。</p>
|
||||
|
||||
@@ -110,15 +139,18 @@ import {
|
||||
getBrandTask,
|
||||
getBrandTaskDownloadUrl,
|
||||
getBrandTasks,
|
||||
runBrandLocal,
|
||||
runBrandNow,
|
||||
type BrandTaskItem,
|
||||
} from '@/shared/api/brand'
|
||||
import { getCollectRouting } from '@/shared/api/types/modules/collect-routing.ts'
|
||||
import { useExcelFileUpload } from '@/shared/composables/useExcelFileUpload'
|
||||
import { getTaskPollIntervalMs } from '@/shared/task-progress-config'
|
||||
import { createCategorizedTimers } from '@/shared/utils/categorized-timers'
|
||||
import type { UploadedFileRef } from '@/shared/api/types/upload.ts'
|
||||
import { formatDateTime } from '@/shared/utils/datetime'
|
||||
import { taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
|
||||
import { brandPhaseText } from '@/shared/utils/brand-phase'
|
||||
import { isHttpUrl, safeHttpUrl } from '@/shared/utils/safe-url'
|
||||
import { runBatchDelete } from '@/shared/utils/batch-delete'
|
||||
|
||||
@@ -157,6 +189,13 @@ const tasks = ref<BrandTaskItem[]>([])
|
||||
// 品牌检测已服务端化(/api/brand/* 走域名):浏览器降级桥提供文件选择,Web 端可用;
|
||||
// 文件夹选择/模板桥等降级桥未实现的方法在点击时提示"仅桌面端"
|
||||
const hasBridge = computed(() => Boolean(getPywebviewApi()))
|
||||
/**
|
||||
* 本机采集能力(V212):老客户端的 pywebview 桥没有 `run_brand_task`,此时本地选项置灰
|
||||
* 并要求升级——静默改走线上会让用户以为在本地跑,实则又进了服务端那 2 个名额的队列。
|
||||
*/
|
||||
const canRunLocal = computed(() => Boolean(getPywebviewApi()?.run_brand_task))
|
||||
const collectChannel = ref<'LOCAL' | 'ONLINE'>('ONLINE')
|
||||
const channelLocked = computed(() => submitting.value)
|
||||
const hasUid = computed(() => {
|
||||
const raw = typeof window === 'undefined' ? '' : window.localStorage.getItem('uid') || ''
|
||||
const numeric = Number(raw.trim())
|
||||
@@ -168,13 +207,6 @@ let pollTimer: number | null = null
|
||||
/** taskId -> 行级进度快照(按“已处理品牌行 / 总品牌行”推进,成功或查询失败都计入完成数) */
|
||||
const lineProgressMap = ref<Record<string, { current: number; total: number; phase?: string }>>({})
|
||||
|
||||
const BRAND_PHASE_TEXT: Record<string, string> = {
|
||||
crawling: '品牌查询中',
|
||||
assembling: '结果生成中',
|
||||
uploading: '结果上传中',
|
||||
failed: '处理失败',
|
||||
}
|
||||
|
||||
function hasBusyBrandTask() {
|
||||
return tasks.value.some(isBusyBrandTask)
|
||||
}
|
||||
@@ -346,7 +378,7 @@ function toBrandTaskView(item: BrandTaskItem): TaskItemView {
|
||||
if (lp && lineTotal > 0) {
|
||||
progress = {
|
||||
percent: Math.max(0, Math.min(100, Math.round((lineCurrent / lineTotal) * 100))),
|
||||
stage: (lp.phase && BRAND_PHASE_TEXT[lp.phase]) || '品牌检测中',
|
||||
stage: brandPhaseText(lp.phase),
|
||||
countLabel: `${lineCurrent}/${lineTotal}`,
|
||||
}
|
||||
} else {
|
||||
@@ -371,6 +403,15 @@ function toBrandTaskView(item: BrandTaskItem): TaskItemView {
|
||||
}
|
||||
}
|
||||
|
||||
/** 本机采集:把桥返回的驼峰形状收敛成与线上分支一致的 {success, task_id, error}。 */
|
||||
async function runBrandLocalTask(files: UploadedFileRef[]) {
|
||||
const res = await runBrandLocal(files, strategy.value, getPywebviewApi() ?? undefined)
|
||||
if (!res.available) {
|
||||
throw new Error('当前客户端版本不支持本机采集,请升级客户端后重试(也可先改用线上采集)')
|
||||
}
|
||||
return { success: res.success, task_id: res.taskId, error: res.error }
|
||||
}
|
||||
|
||||
async function submitRun() {
|
||||
if (!hasBridge.value) {
|
||||
ElMessage.warning('请在桌面客户端中打开本页面执行品牌检测')
|
||||
@@ -394,9 +435,11 @@ async function submitRun() {
|
||||
relativePath: f.relativePath,
|
||||
fileUrl: f.url || f.localPath,
|
||||
}))
|
||||
const res = await runBrandNow(files, strategy.value)
|
||||
const res = collectChannel.value === 'LOCAL'
|
||||
? await runBrandLocalTask(files)
|
||||
: await runBrandNow(files, strategy.value, 'ONLINE')
|
||||
if (res.success && res.task_id) {
|
||||
ElMessage.success(`已创建任务 ${res.task_id},开始检测`)
|
||||
ElMessage.success(`已创建任务 ${res.task_id}(${collectChannel.value === 'LOCAL' ? '本机采集' : '线上采集'}),开始检测`)
|
||||
} else {
|
||||
throw new Error((res as { error?: string }).error || '运行失败')
|
||||
}
|
||||
@@ -516,6 +559,15 @@ async function downloadTemplate(kind: 'xlsx' | 'zip') {
|
||||
|
||||
onMounted(() => {
|
||||
void syncTasksAndResumePolling()
|
||||
// 默认通道由服务端给(V212 起 BRAND 默认 LOCAL),前端不自己写死:
|
||||
// 老客户端没有 run_brand_task 桥时强制落到线上,并把本地选项置灰。
|
||||
void getCollectRouting()
|
||||
.then((routing) => {
|
||||
collectChannel.value = routing?.brandLocal && canRunLocal.value ? 'LOCAL' : 'ONLINE'
|
||||
})
|
||||
.catch(() => {
|
||||
collectChannel.value = 'ONLINE'
|
||||
})
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
|
||||
@@ -102,13 +102,50 @@ export function expandBrandFolderRecursive(folder: string) {
|
||||
return requestPostJson<BrandExpandFolderResponse>(`${API_PREFIX}/api/brand/expand-folder-recursive`, { folder })
|
||||
}
|
||||
|
||||
export function runBrandNow(files: UploadedFileRef[], strategy: string) {
|
||||
export function runBrandNow(files: UploadedFileRef[], strategy: string, collectChannel?: 'LOCAL' | 'ONLINE') {
|
||||
return requestPostJson<BrandTaskMutationResponse>(
|
||||
`${API_PREFIX}/api/brand/run?userId=${encodeURIComponent(String(getCurrentUserId()))}`,
|
||||
{ files, strategy, taskType: 1 },
|
||||
{ files, strategy, taskType: 1, ...(collectChannel ? { collect_channel: collectChannel } : {}) },
|
||||
)
|
||||
}
|
||||
|
||||
/** 本机采集要用到的桥能力;由页面把 `getPywebviewApi()` 传进来(本模块不引桥,见下) */
|
||||
export interface BrandLocalBridge {
|
||||
run_brand_task?: (payload: { files: UploadedFileRef[]; strategy: string; uid: number }) => Promise<{
|
||||
success?: boolean
|
||||
task_id?: number
|
||||
error?: string
|
||||
}>
|
||||
}
|
||||
|
||||
/**
|
||||
* 本机采集(V212):把这一单交给桌面客户端本机 Flask 执行。
|
||||
*
|
||||
* 页面载入的是线上 Web,`/api/brand/*` 的相对地址一律打到线上 15126(服务端执行);
|
||||
* 本地这一档只能经 pywebview 桥显式送回 127.0.0.1:5123,所以这里不走 fetch 而走桥。
|
||||
* 老客户端没有 `run_brand_task` 方法 ⇒ 返回 available=false,由页面把选项置灰并提示升级。
|
||||
*
|
||||
* 桥由调用方传入而不在此 import:本模块被 `node --test` 直接加载(tests/modules-image-video
|
||||
* 等),而 bridges/pywebview.ts 用的是 vite 别名与省略扩展名的导入,Node ESM 解析不了。
|
||||
*/
|
||||
export function runBrandLocal(files: UploadedFileRef[], strategy: string, bridge?: BrandLocalBridge) {
|
||||
if (!bridge?.run_brand_task) {
|
||||
return Promise.resolve({ available: false as const })
|
||||
}
|
||||
return Promise.resolve(
|
||||
bridge.run_brand_task({
|
||||
files,
|
||||
strategy,
|
||||
uid: getCurrentUserId(),
|
||||
}),
|
||||
).then((res) => ({
|
||||
available: true as const,
|
||||
success: Boolean(res?.success),
|
||||
taskId: Number(res?.task_id) || 0,
|
||||
error: res?.error ? String(res.error) : '',
|
||||
}))
|
||||
}
|
||||
|
||||
export function createBrandTask(files: UploadedFileRef[], strategy: string) {
|
||||
return requestPostJson<BrandTaskMutationResponse>(
|
||||
`${API_PREFIX}/api/brand/tasks?userId=${encodeURIComponent(String(getCurrentUserId()))}`,
|
||||
|
||||
@@ -19,6 +19,8 @@ export type CollectChannel = 'LOCAL' | 'ONLINE';
|
||||
export interface CollectRoutingVo {
|
||||
appearancePatentLocal: boolean;
|
||||
similarAsinLocal: boolean;
|
||||
/** 品牌检测默认通道(2026-11-18,V212):true=桌面客户端本机执行;false=服务端 15126 执行。 */
|
||||
brandLocal: boolean;
|
||||
}
|
||||
|
||||
export function getCollectRouting() {
|
||||
|
||||
@@ -141,6 +141,13 @@ export interface PywebviewApi {
|
||||
expand_brand_folder?: (
|
||||
folder: string,
|
||||
) => Promise<{ success: boolean; items?: Array<{ absolutePath: string; relativePath: string }>; error?: string }>;
|
||||
/**
|
||||
* 品牌检测本机采集(V212):把这一单交给本机 Flask 执行并返回 task_id。
|
||||
* 老客户端没有这个方法 ⇒ 页面据此把「本机采集」置灰并要求升级。
|
||||
*/
|
||||
run_brand_task?: (
|
||||
payload: { files: unknown[]; strategy: string; uid: number },
|
||||
) => Promise<{ success: boolean; task_id?: number; collect_channel?: string; error?: string }>;
|
||||
upload_file_to_java?: (
|
||||
filePath: string,
|
||||
relativePath?: string,
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* 品牌检测的阶段文案(唯一出处)。
|
||||
*
|
||||
* 背景(2026-11-18):品牌任务的服务端执行方(15126)跨账号最多并发 2 个
|
||||
* (`BRAND_MAX_CONCURRENT_TASKS` 默认 2),同账号串行;名额被大单占满时后到的
|
||||
* 任务要排队几十分钟。排队期心跳此前一律报 `crawling`,界面就把「排队 62 分钟」
|
||||
* 显示成「品牌查询中 0/N」——用户只能以为任务卡死。现在排队期单独报 `queued`。
|
||||
*
|
||||
* 这里的 key 必须与后端 `BrandTaskProgressCacheService` 的 phase 白名单同形:
|
||||
* 后端会把白名单外的 phase 归一成 `crawling`,漏加即界面重新退回「品牌查询中」。
|
||||
*/
|
||||
export const BRAND_PHASE_TEXT: Record<string, string> = {
|
||||
queued: '排队中',
|
||||
crawling: '品牌查询中',
|
||||
assembling: '结果生成中',
|
||||
uploading: '结果上传中',
|
||||
failed: '处理失败',
|
||||
}
|
||||
|
||||
/** 未知/缺省 phase 的统一兜底文案(保持改动前的显示口径)。 */
|
||||
export const BRAND_PHASE_FALLBACK = '品牌检测中'
|
||||
|
||||
export function brandPhaseText(phase?: string | null): string {
|
||||
const key = (phase ?? '').trim()
|
||||
if (!key) return BRAND_PHASE_FALLBACK
|
||||
return BRAND_PHASE_TEXT[key] || BRAND_PHASE_FALLBACK
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { http } from '../src/shared/api/http.ts'
|
||||
import { runBrandLocal, runBrandNow, type BrandLocalBridge } from '../src/shared/api/types/modules/brand.ts'
|
||||
|
||||
function setupWindow() {
|
||||
;(globalThis as Record<string, unknown>).window = {
|
||||
localStorage: { getItem: () => '42' },
|
||||
location: { origin: 'http://localhost' },
|
||||
}
|
||||
}
|
||||
|
||||
function mockRequest(
|
||||
t: Parameters<typeof test>[1] extends (t: infer T) => unknown ? T : never,
|
||||
impl: (config: { url?: string; method?: string; data?: unknown }) => Promise<unknown>,
|
||||
) {
|
||||
t.mock.method(http, 'request', impl as never)
|
||||
}
|
||||
|
||||
const files = [{ fileKey: 'k1', originalFilename: '品牌样例.xlsx' }] as never
|
||||
|
||||
/**
|
||||
* 品牌检测的采集执行通道(V212):界面单选本机/线上,默认本机。
|
||||
*
|
||||
* <p>这里钉三件:① 线上这一档必须把 collect_channel 打进请求体(否则服务端按模块默认
|
||||
* 存成 LOCAL,界面选线上却在本机跑);② 不传通道时不编造字段(服务端按默认兜);
|
||||
* ③ 老客户端的桥没有 run_brand_task 时必须明确回答 available=false——页面据此把
|
||||
* 「本机采集」置灰并提示升级,而不是静默回落到线上(否则又排回那 2 个名额)。
|
||||
*/
|
||||
test('test_brand_local_without_bridge_reports_unavailable', async () => {
|
||||
setupWindow()
|
||||
assert.deepEqual(await runBrandLocal(files, 'Simple'), { available: false })
|
||||
assert.deepEqual(await runBrandLocal(files, 'Simple', {} as BrandLocalBridge), { available: false },
|
||||
'桥在但没有 run_brand_task(老客户端)同样置灰')
|
||||
})
|
||||
|
||||
test('test_brand_local_forwards_to_bridge', async () => {
|
||||
setupWindow()
|
||||
const calls: unknown[] = []
|
||||
const bridge: BrandLocalBridge = {
|
||||
run_brand_task: (payload) => {
|
||||
calls.push(payload)
|
||||
return Promise.resolve({ success: true, task_id: 5123 })
|
||||
},
|
||||
}
|
||||
|
||||
const result = await runBrandLocal(files, 'Terms', bridge)
|
||||
|
||||
assert.equal(result.available, true)
|
||||
assert.equal(result.success, true)
|
||||
assert.equal(result.taskId, 5123)
|
||||
assert.deepEqual(calls, [{ files, strategy: 'Terms', uid: 42 }],
|
||||
'桥调用要把 uid 一起带过去:本机 Flask 建单要按用户归属')
|
||||
})
|
||||
|
||||
test('test_brand_local_bridge_failure_is_reported', async () => {
|
||||
setupWindow()
|
||||
const bridge: BrandLocalBridge = {
|
||||
run_brand_task: () => Promise.resolve({ success: false, error: '本机建单失败' }),
|
||||
}
|
||||
|
||||
const result = await runBrandLocal(files, 'Simple', bridge)
|
||||
|
||||
assert.equal(result.available, true)
|
||||
assert.equal(result.success, false)
|
||||
assert.equal(result.error, '本机建单失败')
|
||||
})
|
||||
|
||||
test('test_brand_run_online_channel_in_payload', async (t) => {
|
||||
setupWindow()
|
||||
let captured: { url?: string; method?: string; data?: unknown } = {}
|
||||
mockRequest(t, (config) => {
|
||||
captured = config
|
||||
return Promise.resolve({ data: { success: true, data: { success: true, task_id: '77' } } })
|
||||
})
|
||||
|
||||
await runBrandNow(files, 'Simple', 'ONLINE')
|
||||
|
||||
assert.equal(captured.url, '/api/brand/run?userId=42')
|
||||
assert.equal(captured.method, 'POST')
|
||||
assert.deepEqual(captured.data, { files, strategy: 'Simple', taskType: 1, collect_channel: 'ONLINE' })
|
||||
})
|
||||
|
||||
test('test_brand_run_without_channel_does_not_invent_one', async (t) => {
|
||||
setupWindow()
|
||||
let captured: { data?: unknown } = {}
|
||||
mockRequest(t, (config) => {
|
||||
captured = config
|
||||
return Promise.resolve({ data: { success: true, data: { success: true } } })
|
||||
})
|
||||
|
||||
await runBrandNow(files, 'Simple')
|
||||
|
||||
assert.deepEqual(captured.data, { files, strategy: 'Simple', taskType: 1 },
|
||||
'不选通道时不带字段,由服务端按模块默认兜(BRAND 默认 LOCAL)')
|
||||
})
|
||||
@@ -18,7 +18,7 @@ function mockRequest(
|
||||
}
|
||||
|
||||
/**
|
||||
* 采集路由开关读取口:前端两个工具页据这两个布尔决定「启动」走本地客户端还是后台。
|
||||
* 采集路由开关读取口:前端工具页据这几个布尔决定「启动」走本地客户端还是后台。
|
||||
* 只钉 URL 与返回值原样透传——开关真值来自服务端,前端不自己造默认。
|
||||
*/
|
||||
test('test_collect_routing_url_and_payload', async (t) => {
|
||||
@@ -27,7 +27,11 @@ test('test_collect_routing_url_and_payload', async (t) => {
|
||||
mockRequest(t, (config) => {
|
||||
captured = config
|
||||
return Promise.resolve({
|
||||
data: { success: true, message: 'ok', data: { appearancePatentLocal: true, similarAsinLocal: false } },
|
||||
data: {
|
||||
success: true,
|
||||
message: 'ok',
|
||||
data: { appearancePatentLocal: true, similarAsinLocal: false, brandLocal: true },
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
@@ -37,4 +41,5 @@ test('test_collect_routing_url_and_payload', async (t) => {
|
||||
assert.equal(captured.method, 'GET')
|
||||
assert.equal(routing.appearancePatentLocal, true)
|
||||
assert.equal(routing.similarAsinLocal, false)
|
||||
assert.equal(routing.brandLocal, true)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user