Compare commits

..

3 Commits

Author SHA1 Message Date
huangzd1997 a5e390750b refactor(slim-r3): 删除零引用死模块——keywordshare/debug/PublicWorkbenchClientVersion 三线 40 件
Project-Slimming 第三轮收尾执行(用户拍板「零引用的也都要删除」):
定谳依据=6.4 天生产访问日志零流量(970 万行单遍对撞,26 UNIQUE 前缀防撞车)
+四树代码零引用(后端类名/包名/字符串、admin、用户端、app_client 全扫)
+V163 建菜单→V165 撤菜单的历史链(功能入口 10 月底已下线,Controller 成孤儿)。

删除(40 件):
- modules/keywordshare 整模块 31 类+4 mapper XML+KeywordShareServiceTest
  (后管 V165 已撤菜单、app_client 同步链 kw_share_api 亦无调用方;
  biz_keyword_share 等表按「已应用迁移不可回改」保留在库)
- modules/debug 2 支控制器(/debug/request-info、/debug/task-recovery/*)
- workbenchclient/controller/PublicWorkbenchClientVersionController
  (/api/workbench-client/version/latest:app_client 实际走 /api/version/latest,
  admin 侧仅文案引用,无任何真实调用方)
- config/KeywordShareSyncProperties(唯一消费方 KeywordShareService 同批删)

同步编辑:
- AdminApiGuardFilter:摘 DEBUG_PREFIX 前缀(常量/javadoc/审计日志块/requiresCredential/
  guardedPrefixes 五处);ApiGuardCoverageAuditor:METHOD_GUARDED_PATHS 摘 /api/keyword-share
- PropertiesConfig 摘 KeywordShareSyncProperties.class;application.yml 与
  application-local.example.yml 摘 keyword-share-sync 段与两个 env
- 台账两处扣减:XML_SELECT_TOTAL 114→103(11 select)、XML_STATEMENT_TOTAL 164→147
  (11 select+4 insert+1 delete);MigratedSqlEquivalenceTest.NOT_MIGRATED 摘 12 条点名
  (tsv 基准账本零 KeywordShare 行,LEDGER_ROWS/LEDGER_SELECTS 不动)
- PendingPhase5ReadPathTest 摘 P1-B2(RAND 断言随 XML 删);ApiGuardCoverageAuditorTest
  前缀总数 25→24;AdminApiGuardFilterTest 摘 4 支 /debug 用例与 2 条边界 URI
- admin:workbench-client-api 死常量、页面头注释与 page-hint、operation-guides 指南文案
  摘被删端点字样;align-workbench-client.test 摘 3 条对应断言

零行为影响:全部删除件在 6.4 天窗口内零流量;守卫过滤器行为对现存前缀不变
(/api/admin、用户态、自助清单原样)。
2026-11-16 12:18:05 +08:00
huangzd1997 c9ecae6e6d feat(jd): 京东数据库与建单页类目面板换京麦授权类目真树(2026-11-16 客户拍板「京麦类目是这些 我们后台的现在的不对」+「你直接爬」)
真机取证京麦首屏接口 getVenderLicenseCategory(62KB:一级就 3 个=该店铺授权经营类目 服饰内衣1315/母婴1319/运动户外1318,250 个末级,最深 4 级;落库末级名样本「艺考形体服/啦啦队服/拉丁舞服」都在树内 level 3=category_path 等值过滤契约成立;4 组末级同名跨支如实登记,取证件 D:/tmp/jd_cat_probe/)。两份 jd-category-tree.ts 正本同轮重写;JdCategoryCascader 重做京麦同款逐级下钻+末级选中(admin 单选过滤/建单页多选 categoryPaths),搜索搜树内末级(行 title 带路径)+树外兜底段(京麦树已无的历史名仍可选);建单页 hint 文案随真树口径更新。判据:vue-tsc×2 rc=0;node --test 树测试 6/6×2+jd-collect-tab 9/9;vitest admin mount 28/28、用户端 mount 78/78(「勾选类目」用例改真树下钻 运动户外>舞蹈体操鞋服/装备>艺考形体服);fast 闸门 overall=pass 四面绿
2026-11-16 12:16:18 +08:00
huangzd1997 7b853a605e fix(jd): 京东数据库摘除公司 tab(2026-11-16 用户定案「删除掉公司 tab 参考品牌数据库」=品牌库 2026-10-06 先例同形:摘的不只是 tab)——前端 admin_jd_database 退出 COMPANY_SCOPED_PAGES 注册表(定案注释+「公司维度不得回流」SHARED 清单钉住)+routes companyScoped:false+页面卸 companyTab watch 与两处 companyId 发送口(列表 params/类目下拉 fetchJdProductCategories 无参化,JdProductAssignPane 取数同形);后端读侧同窗摘:XML productConds 与 selectProductCategories 的公司维谓词删除(行 company_id 列保留=同步来源标记,JdSchemaContractTest 契约不动)、JdProductMapper.countProducts/selectProductPage 8 参、selectProductCategories() 无参、JdProductQueryService.page 10 参+Filter 去 companyId、AdminJdProductController.page 10 参数+categories(request) 去 superAdminScopedCompanyId 与 DataReadScope 注入、JdCollectController.categories() 调用方同步。判据:vue-tsc rc=0;node --test 9 文件 56/56(wiring SEND_POINTS 27→25、分组 21→19、watch 分母 12→11;menu-route 钉 companyScoped=false;jd-page 钉退出注册表);vitest mount 28/28(删「切公司 Tab 重取」用例,companyId 发送口全改 not.toHaveProperty);mvn -o test-compile rc=0;mvn -o test jd 模块全绿(AdminJdProductControllerTest 20/20:结构判据改「读侧零公司维度_公司tab口径整批摘除」反向钉 company_id/superAdminScopedCompanyId/DataReadScope 不得回潜,行为样本改 requireJdAccess 正门装 200 信封) 2026-11-16 12:05:18 +08:00
79 changed files with 948 additions and 3685 deletions
@@ -63,9 +63,9 @@ export const COMPANY_SCOPED_PAGES: readonly CompanyScopedPage[] = [
// 外观专利无侵权数据(2026-11-10 v1.3):出表成功自动同步的只读明细,归属物化在行 company_id 列 // 外观专利无侵权数据(2026-11-10 v1.3):出表成功自动同步的只读明细,归属物化在行 company_id 列
// (V189,同店铺密钥形状)⇒ 后端正门 readCompanyIdOrOwn(超管显式传才收窄,非超管强制本公司)。 // (V189,同店铺密钥形状)⇒ 后端正门 readCompanyIdOrOwn(超管显式传才收窄,非超管强制本公司)。
{ menuKey: 'admin_appearance_patent_clean_items', apiFiles: ['src/pages/patent/appearance-patent-clean-api.ts'], pageFiles: ['src/pages/patent/AppearancePatentCleanItemsPage.vue'] }, { menuKey: 'admin_appearance_patent_clean_items', apiFiles: ['src/pages/patent/appearance-patent-clean-api.ts'], pageFiles: ['src/pages/patent/AppearancePatentCleanItemsPage.vue'] },
// 京东数据库(2026-11-14 v1.4;2026-11-15 公共化改口径):京麦店铺商品采集落库的只读镜像, // 京东数据库(2026-11-14 v1.4)已于 2026-11-16 退出注册表(用户定案「删除掉公司 tab,参考品牌
// 行 company_id 只剩"哪家公司客户端同步的"来源标记。数据公共(用户定案「不区分公司、属于 // 数据库」=品牌库 2026-10-06 先例同形):数据全平台公共(行 company_id 只剩"哪家公司客户端
// 公共的」):详情/编辑/删除/分组管理不带公司维度;留在注册表里的理由是超管的公司 tab 筛选 // 同步的"来源标记),摘的不只是 tab——页面/api 的 company_id 发送口与后端读侧 company_id 谓词
// (=筛选管理员)仍作用于只读列表与类目下拉两个发送口,非超管没有这个筛选、看同一份全量。 // (superAdminScopedCompanyId)同窗一起摘。反向钉在 tests/company-tab-wiring.test.ts 的
{ menuKey: 'admin_jd_database', apiFiles: ['src/pages/jd/jd-product-api.ts'], pageFiles: ['src/pages/jd/JdDatabasePage.vue'] }, // 「公司维度不得回流」清单里,再加回来必须先推翻这条定案。
] ]
@@ -98,7 +98,7 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
steps: ['上传教程压缩包', '到工具台核对下载', '清理历史包'], steps: ['上传教程压缩包', '到工具台核对下载', '清理历史包'],
}, },
admin_workbench_client_package: { admin_workbench_client_package: {
text: '上传新的工作台客户端 ZIP 包后即刻生效:客户端从 /api/workbench-client/version/latest 自动检测版本并升级;服务端会复算 sha256 供客户端校验。确认旧包不再需要后再删除。', text: '上传新的工作台客户端 ZIP 包后即刻生效;服务端会复算 sha256 供客户端校验。确认旧包不再需要后再删除。',
steps: ['填写版本号并上传 ZIP', '核对版本与 sha256', '清理历史包'], steps: ['填写版本号并上传 ZIP', '核对版本与 sha256', '清理历史包'],
}, },
digital_human_version: { digital_human_version: {
@@ -1,22 +1,27 @@
<script setup lang="ts"> <script setup lang="ts">
/** 京东数据库「类目」筛选的京麦同款级联面板(2026-11-16 客户口径「京东类目要做成京麦 /** 京东数据库「类目」筛选的京麦同款级联面板(2026-11-16 客户口径「京麦类目是这些 我们
* 同款样式」)。三栏形状照京麦:第一栏静态一级导航(jd-category-tree,京东公开类目 * 后台的现在的不对」+「你直接爬」→ 树数据换成京麦授权类目真树,见 ./jd-category-tree.ts
* 体系;服饰内衣子树二级按京麦面板真机样本逐字)、第二栏该一级的静态二级(hover/点击 * 头注释的取证来源与边界)。
* 展开;radio 不选中——纯导航)、第三栏「已落库末级类目全集+搜索」(选中发生地)。
* *
* 数据边界如实声明:采集链只有末级类目名(categoryDetailVO.lastCategoryName),没有 * 交互(京麦真机同款,2026-11-16 面板逐级点开取证):面板按点亮路径动态出栏——第一栏
* 一/二级归属,所以第二栏与第三栏**不联动**(点了二级第三栏照旧全集+搜索)——过滤语义 * 一级(3 个)、后续栏=点亮节点的 children(最深 4 栏);**非末级行点击=下钻**(推进
* 零风险(仍按 category_path 等值,后端零改动);采集链补齐层级后,把静态树换掉、第三栏 * 路径)、**末级行(children 空)点击=选中**(radio 蓝,emit change→按 category_path
* 按选中二级过滤即可升级真联动。零依赖自绘(radio 圆点/箭头都是 CSS),无 element 依赖。 * 等值过滤,后端契约零改动)。搜索框搜**树内全部末级**(名称或路径命中,行 title 带
* * 全路径);树外命中(已落库但京麦类目体系变更后的历史名)从 options 兜底段选,语义
* 交互:点开面板 → 点/hover 一级展第二栏 → 第三栏搜索或点行选中(radio 蓝)→ 收面板; * 同旧版第三栏。「全部类目」行=清选;触发框已选时出 × 清除;面板外点透明遮罩关闭。
* 「全部类目」行=清选;触发框已选时出 × 清除;面板外点透明遮罩关闭。 */ * 零依赖自绘(radio 圆点/箭头都是 CSS),无 element 依赖。 */
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import { jdCategoryNavChildren, jdCategoryNavRoots } from './jd-category-tree.ts' import {
jdCategoryChildren,
jdCategoryRoots,
jdCategorySearchLeaves,
type JdCategoryNode,
} from './jd-category-tree.ts'
const props = defineProps<{ const props = defineProps<{
/** 已落库末级类目选项(/categories 现算,页面传入:{name, productCount})。 */ /** 已落库末级类目全集(/categories 现算,页面传入)——只作**树外兜底**(搜索无树内
options: { name: string; productCount: number }[] * 命中时列出「已落库类目(树外历史)」段),不再默认铺第三栏。 */
options?: { name: string; productCount: number }[]
/** 当前选中末级类目名;'' = 全部类目。 */ /** 当前选中末级类目名;'' = 全部类目。 */
modelValue: string modelValue: string
}>() }>()
@@ -24,18 +29,43 @@ const props = defineProps<{
const emit = defineEmits<{ (event: 'change', value: string): void }>() const emit = defineEmits<{ (event: 'change', value: string): void }>()
const open = ref(false) const open = ref(false)
const activeRoot = ref('') /** 已下钻的节点名路径(非末级行点击推进)。 */
const activePath = ref<string[]>([])
const searchText = ref('') const searchText = ref('')
const roots = jdCategoryNavRoots() const roots = jdCategoryRoots()
/** 第二栏=点亮一级的静态二级;无静态子级的一级不出第二栏。 */ /** 树内全部末级名集合(判定 options 哪些是「树外历史」)。 */
const activeChildren = computed(() => jdCategoryNavChildren(activeRoot.value)) const treeLeafNames = new Set(
jdCategorySearchLeaves('').map((leaf) => leaf.name),
)
/** 第三栏=已落库末级全集按搜索词过滤(大小写不敏感的 includes)。 */ /** 面板各栏内容:第 0 栏一级,第 i+1 栏=点亮路径前 i+1 个的 children(路径推进到
const filteredLeaves = computed(() => { * 末级时末栏是叶子所在栏,children 空不出栏——栏数随路径动态 1~4)。 */
const columns = computed<JdCategoryNode[][]>(() => {
const cols: JdCategoryNode[][] = [roots]
for (let i = 0; i < activePath.value.length; i++) {
const children = jdCategoryChildren(activePath.value.slice(0, i + 1))
if (!children.length) break
cols.push(children)
}
return cols
})
/** 搜索激活=搜索词非空:面板切换成扁平末级结果列表。 */
const searching = computed(() => searchText.value.trim().length > 0)
/** 树内命中末级(名称或路径段命中)。 */
const searchLeaves = computed(() =>
searching.value ? jdCategorySearchLeaves(searchText.value) : [],
)
/** 树外兜底:options 里不在树名集的行按搜索词过滤(历史行仍可选中过滤)。 */
const fallbackOptions = computed(() => {
if (!searching.value) return []
const keyword = searchText.value.trim().toLowerCase() const keyword = searchText.value.trim().toLowerCase()
if (!keyword) return props.options return (props.options ?? [])
return props.options.filter((option) => option.name.toLowerCase().includes(keyword)) .filter((option) => !treeLeafNames.has(option.name))
.filter((option) => option.name.toLowerCase().includes(keyword))
}) })
function toggle(): void { function toggle(): void {
@@ -43,18 +73,24 @@ function toggle(): void {
close() close()
return return
} }
activeRoot.value = '' activePath.value = []
searchText.value = '' searchText.value = ''
open.value = true open.value = true
} }
function close(): void { function close(): void {
open.value = false open.value = false
activeRoot.value = '' activePath.value = []
} }
function pickRoot(name: string): void { /** 非末级行点击=下钻;末级行点击=选中并收面板。 */
activeRoot.value = name function pick(node: JdCategoryNode, depth: number): void {
if (node.children && node.children.length) {
activePath.value = [...activePath.value.slice(0, depth), node.name]
return
}
emit('change', node.name)
close()
} }
function pickAll(): void { function pickAll(): void {
@@ -62,7 +98,8 @@ function pickAll(): void {
close() close()
} }
function pickLeaf(name: string): void { /** 搜索结果行点击(树内末级或树外兜底行)=按名选中。 */
function pickName(name: string): void {
emit('change', name) emit('change', name)
close() close()
} }
@@ -94,61 +131,74 @@ function clear(): void {
<!-- 面板外点透明遮罩关闭(零 document 监听器,无泄漏面)。 --> <!-- 面板外点透明遮罩关闭(零 document 监听器,无泄漏面)。 -->
<div v-if="open" class="cat-mask" @click="close"></div> <div v-if="open" class="cat-mask" @click="close"></div>
<div v-if="open" class="cat-panel"> <div v-if="open" class="cat-panel">
<!-- 第一栏:静态一级导航(radio 形状照京麦,点选只展开不落值)。 --> <!-- 搜索态:树内末级命中+树外兜底段(扁平列表,行 title 带全路径)。 -->
<div class="cat-col"> <template v-if="searching">
<div <div class="cat-col cat-col-search">
v-for="root in roots" <template v-if="searchLeaves.length || fallbackOptions.length">
:key="root" <div
class="cat-row" v-for="leaf in searchLeaves"
:class="{ active: activeRoot === root }" :key="`tree-${leaf.path.join('/')}`"
@click="pickRoot(root)" class="cat-row"
@mouseenter="pickRoot(root)" :class="{ active: modelValue === leaf.name }"
> :title="leaf.path.join(' > ')"
<span class="cat-dot" aria-hidden="true"></span> @click="pickName(leaf.name)"
<span class="cat-name" :title="root">{{ root }}</span> >
<span v-if="jdCategoryNavChildren(root).length" class="cat-arrow" aria-hidden="true">›</span> <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>
</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 }"
:title="option.name"
@click="pickName(option.name)"
>
<span class="cat-dot" :class="{ on: modelValue === option.name }" aria-hidden="true"></span>
<span class="cat-name">{{ option.name }}</span>
<span class="cat-count">{{ option.productCount }}</span>
</div>
</template>
<div v-else class="cat-empty">未找到类目</div>
</div> </div>
</div> </template>
<!-- 第二栏:点亮一级的静态二级(纯导航;归属数据缺,不联动第三栏——组件头注释)。 --> <!-- 下钻态:逐级动态栏;首栏顶部「全部类目」行=清选。 -->
<div v-if="activeChildren.length" class="cat-col"> <template v-else>
<div <div
v-for="child in activeChildren" v-for="(col, depth) in columns"
:key="child" :key="depth"
class="cat-row" class="cat-col"
> >
<span class="cat-dot" aria-hidden="true"></span> <div v-if="depth === 0" class="cat-search-row">
<span class="cat-name" :title="child">{{ child }}</span> <input
<span class="cat-arrow" aria-hidden="true">›</span> v-model="searchText"
type="text"
class="cat-search"
placeholder="搜索类目"
@click.stop
/>
</div>
<div v-if="depth === 0" class="cat-row cat-row-all" :class="{ active: !modelValue }" @click="pickAll">
<span class="cat-dot" :class="{ on: !modelValue }" aria-hidden="true"></span>
<span class="cat-name">全部类目</span>
</div>
<div
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"
@click="pick(node, depth)"
>
<span class="cat-dot" aria-hidden="true"></span>
<span class="cat-name">{{ node.name }}</span>
<span v-if="node.children && node.children.length" class="cat-arrow" aria-hidden="true">›</span>
</div>
</div> </div>
</div> </template>
<!-- 第三栏:已落库末级全集+搜索(选中发生地;点行=按 category_path 等值过滤)。 -->
<div class="cat-col cat-col-leaf">
<div class="cat-row cat-row-all" :class="{ active: !modelValue }" @click="pickAll">
<span class="cat-dot" aria-hidden="true"></span>
<span class="cat-name">全部类目</span>
</div>
<input
v-model="searchText"
type="text"
class="cat-search"
placeholder="搜索类目"
@click.stop
/>
<div v-if="!filteredLeaves.length" class="cat-empty">未找到类目</div>
<div
v-for="leaf in filteredLeaves"
:key="leaf.name"
class="cat-row"
:class="{ active: modelValue === leaf.name }"
@click="pickLeaf(leaf.name)"
>
<span class="cat-dot" :class="{ on: modelValue === leaf.name }" aria-hidden="true"></span>
<span class="cat-name" :title="leaf.name">{{ leaf.name }}</span>
<span class="cat-count">{{ leaf.productCount }}</span>
</div>
</div>
</div> </div>
</div> </div>
</template> </template>
@@ -237,7 +287,7 @@ function clear(): void {
z-index: 2560; z-index: 2560;
display: flex; display: flex;
align-items: stretch; align-items: stretch;
max-width: min(720px, 90vw); max-width: min(820px, 90vw);
border: 1px solid #d8e3ee; border: 1px solid #d8e3ee;
border-radius: 10px; border-radius: 10px;
background: #ffffff; background: #ffffff;
@@ -245,7 +295,7 @@ function clear(): void {
overflow: hidden; overflow: hidden;
} }
.cat-col { .cat-col {
width: 210px; width: 200px;
max-height: 340px; max-height: 340px;
overflow-y: auto; overflow-y: auto;
padding: 6px 0; padding: 6px 0;
@@ -254,8 +304,8 @@ function clear(): void {
.cat-col:last-child { .cat-col:last-child {
border-right: 0; border-right: 0;
} }
.cat-col-leaf { .cat-col-search {
width: 240px; width: 300px;
} }
/* 行=京麦同款:圆点 radio + 名称 + 右箭头;hover 浅蓝底。 */ /* 行=京麦同款:圆点 radio + 名称 + 右箭头;hover 浅蓝底。 */
.cat-row { .cat-row {
@@ -283,7 +333,7 @@ function clear(): void {
border-radius: 50%; border-radius: 50%;
background: #ffffff; background: #ffffff;
} }
/* radio 选中=京麦同款蓝芯;一级/二级的圆点是导航形状,不落选中态。 */ /* radio 选中=京麦同款蓝芯。 */
.cat-dot.on { .cat-dot.on {
border-color: #3b82c4; border-color: #3b82c4;
background: radial-gradient(circle, #3b82c4 0 4px, #ffffff 4.6px); background: radial-gradient(circle, #3b82c4 0 4px, #ffffff 4.6px);
@@ -295,6 +345,16 @@ function clear(): void {
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
} }
/* 搜索态行尾的路径灰字(同名跨支时定位用)。 */
.cat-path {
flex: none;
max-width: 110px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: #9fb0c0;
font-size: 12px;
}
.cat-arrow { .cat-arrow {
flex: none; flex: none;
color: #9fb0c0; color: #9fb0c0;
@@ -306,10 +366,19 @@ function clear(): void {
color: #8293a5; color: #8293a5;
font-size: 12px; font-size: 12px;
} }
.cat-seg {
padding: 8px 12px 4px;
color: #8293a5;
font-size: 11.5px;
border-top: 1px solid #e7eef5;
}
.cat-search-row {
padding: 4px 8px 6px;
border-bottom: 1px solid #e7eef5;
}
.cat-search { .cat-search {
display: block; display: block;
width: calc(100% - 20px); width: 100%;
margin: 4px 10px 8px;
min-height: 30px; min-height: 30px;
padding: 4px 10px; padding: 4px 10px;
border: 1px solid #cbd9e6; border: 1px solid #cbd9e6;
@@ -3,7 +3,10 @@
* 公共的」,分类同亚马逊口径全平台一份),筛选行(商品编码/标题关键字/分类/分类状态/ * 公共的」,分类同亚马逊口径全平台一份),筛选行(商品编码/标题关键字/分类/分类状态/
* 类目/同步起止 date 对)+查询/重置/店铺分类 + 自绘明细表(勾选列+点行开详情抽屉) * 类目/同步起止 date 对)+查询/重置/店铺分类 + 自绘明细表(勾选列+点行开详情抽屉)
* + 删除(单行/批量,先删桶对象、全成功才删库行,确认弹窗点名数量)+ OldPagination。 * + 删除(单行/批量,先删桶对象、全成功才删库行,确认弹窗点名数量)+ OldPagination。
* 公司维度只剩超管的公司 tab(=筛选管理员,非超管没有这个筛选、看到同一份公共全量); * 公司维度 2026-11-16 整页摘除(用户定案「删除掉公司 tab,参考品牌数据库」=品牌库
* 2026-10-06 先例同形):页面不再消费公司 tab store、列表/类目下拉不再下传 company_id
* (后端读侧 company_id 谓词同窗摘,行 company_id 列仍作同步来源标记留在详情里);
* 每个管理员看到同一份公共全量。反向钉在 company-tab-wiring「公司维度不得回流」清单。
* 列表按京麦商品列表样式(2026-11-15 用户口径):分类前置为第 1 列;商品信息列=京麦同款 * 列表按京麦商品列表样式(2026-11-15 用户口径):分类前置为第 1 列;商品信息列=京麦同款
* 合并布局(主图+图下信息分+标题两行+商品编码/货号+SKU 数标签,编码带一键复制);类目/上架 * 合并布局(主图+图下信息分+标题两行+商品编码/货号+SKU 数标签,编码带一键复制);类目/上架
* 时间/京东创建/修改时间仍收详情抽屉基本信息(B104「详情显示全部属性」口径不变)。 * 时间/京东创建/修改时间仍收详情抽屉基本信息(B104「详情显示全部属性」口径不变)。
@@ -18,11 +21,11 @@
* 下线(jd_created_at/jd_updated_at 仍收详情抽屉),列表时间列只剩同步时间收尾; * 下线(jd_created_at/jd_updated_at 仍收详情抽屉),列表时间列只剩同步时间收尾;
* ⑤ 工具栏加「移除分类」批量按钮(batch-assign-group 的 groupId=null 口径,勾选里只算已分类行)。 * ⑤ 工具栏加「移除分类」批量按钮(batch-assign-group 的 groupId=null 口径,勾选里只算已分类行)。
* 骨架像素复刻「外观专利数据库」页(panel-box + LoadFailureBar + 自绘 table + 旧式分页); * 骨架像素复刻「外观专利数据库」页(panel-box + LoadFailureBar + 自绘 table + 旧式分页);
* 超管切公司 tab = 清筛选重取(watch 体照外观专利页逐字形状);日期对护栏:起侧 max=止侧、 * 日期对护栏:起侧 max=止侧、止侧 min=起侧、两侧 @change 用 orderedPair 把倒挂交换回来
* 止侧 min=起侧、两侧 @change 用 orderedPair 把倒挂交换回来(clampJdSyncedRange 照 clampDatePair)。 * (clampJdSyncedRange 照 clampDatePair)。
* 日期初值故意留空:同步数据是累计集,默认当天会让首屏只剩今天同步的行 * 日期初值故意留空:同步数据是累计集,默认当天会让首屏只剩今天同步的行
* (date-filter-default-today 护栏 EXEMPT 口径,外观专利页同款)。 */ * (date-filter-default-today 护栏 EXEMPT 口径,外观专利页同款)。 */
import { computed, onMounted, reactive, ref, watch } from 'vue' import { computed, onMounted, reactive, ref } from 'vue'
import { import {
batchAssignJdProductGroup, batchAssignJdProductGroup,
deleteJdProducts, deleteJdProducts,
@@ -41,15 +44,12 @@ import JdProductEditDrawer from './JdProductEditDrawer.vue'
import JdProductGroupDialog from './JdProductGroupDialog.vue' import JdProductGroupDialog from './JdProductGroupDialog.vue'
import JdCategoryCascader from './JdCategoryCascader.vue' import JdCategoryCascader from './JdCategoryCascader.vue'
import OldPagination from '@/components/OldPagination.vue' import OldPagination from '@/components/OldPagination.vue'
import { useCompanyTabStore } from '@/stores/company-tab'
import { showAdminFeedback } from '@/components/admin-feedback-ui' import { showAdminFeedback } from '@/components/admin-feedback-ui'
import { openAdminConfirm } from '@/components/admin-confirm' import { openAdminConfirm } from '@/components/admin-confirm'
import { loadFailureMessage } from '@/components/load-failure-model' import { loadFailureMessage } from '@/components/load-failure-model'
import LoadFailureBar from '@/components/LoadFailureBar.vue' import LoadFailureBar from '@/components/LoadFailureBar.vue'
import { formatDateTime, orderedPair } from '@/utils/datetime' import { formatDateTime, orderedPair } from '@/utils/datetime'
const companyTab = useCompanyTabStore()
const loading = ref(false) const loading = ref(false)
const loadFailure = ref('') const loadFailure = ref('')
const rows = ref<JdProductItem[]>([]) const rows = ref<JdProductItem[]>([])
@@ -60,8 +60,7 @@ const filter = reactive(createJdProductFilterState())
/** 分组下拉选项:分组全平台一份(公共),进页取一次即可;选项失败不拦列表,只回空下拉 /** 分组下拉选项:分组全平台一份(公共),进页取一次即可;选项失败不拦列表,只回空下拉
* (可见「全部分组」)。 */ * (可见「全部分组」)。 */
const groupOptions = ref<JdProductGroup[]>([]) const groupOptions = ref<JdProductGroup[]>([])
/** 类目下拉选项(京麦末级类目):与当前行集同源(超管切公司 tab 时按 tab 收窄重取、 /** 类目下拉选项(京麦末级类目):与当前行集同源(公共库全量);失败静默回空。 */
* 普通行集全量);失败静默回空。 */
const categoryOptions = ref<JdProductCategoryOption[]>([]) const categoryOptions = ref<JdProductCategoryOption[]>([])
/** 分组管理弹窗与详情抽屉。 */ /** 分组管理弹窗与详情抽屉。 */
const groupDialogVisible = ref(false) const groupDialogVisible = ref(false)
@@ -108,7 +107,7 @@ async function loadGroupOptions(): Promise<void> {
/** 类目选项同分组口径:失败静默回空下拉(可见「全部类目」),不拦首屏行集。 */ /** 类目选项同分组口径:失败静默回空下拉(可见「全部类目」),不拦首屏行集。 */
async function loadCategoryOptions(): Promise<void> { async function loadCategoryOptions(): Promise<void> {
try { try {
categoryOptions.value = await fetchJdProductCategories(companyTab.requestCompanyId) categoryOptions.value = await fetchJdProductCategories()
} catch { } catch {
categoryOptions.value = [] categoryOptions.value = []
} }
@@ -135,7 +134,6 @@ async function load(): Promise<void> {
groupScope: filter.groupScope, groupScope: filter.groupScope,
syncedFrom: filter.syncedFrom, syncedFrom: filter.syncedFrom,
syncedTo: filter.syncedTo, syncedTo: filter.syncedTo,
companyId: companyTab.requestCompanyId,
}) })
rows.value = result.items rows.value = result.items
total.value = result.total total.value = result.total
@@ -204,7 +202,7 @@ async function copyText(text: string): Promise<void> {
// ---------------- 删除(先删桶、全成功才删库行,语义在后端 JdProductDeleteService) ---------------- // ---------------- 删除(先删桶、全成功才删库行,语义在后端 JdProductDeleteService) ----------------
/** 本页勾选集(按行 id)。切页/切公司/重取后勾选清空——上一页勾的行不自动带到下一页。 */ /** 本页勾选集(按行 id)。切页/重取后勾选清空——上一页勾的行不自动带到下一页。 */
const selectedIds = ref<Set<number>>(new Set()) const selectedIds = ref<Set<number>>(new Set())
const deleting = ref(false) const deleting = ref(false)
@@ -278,11 +276,6 @@ async function removeSelectedGroup(): Promise<void> {
} }
} }
// 超管切公司 tab = 重新取数:编码/关键字/类目/日期是按行集筛的自由值,在另一家的
// 行集里筛不出东西,必须一起清(分组与分类状态全平台一份,groupId/groupScope 与公司维度
// 正交、不清);类目选项与行集同源,按新 tab 重取;分组选项是全局的、进页取一次即可。
watch(() => companyTab.activeId, () => { filter.productCode = ''; filter.titleKeyword = ''; filter.category = ''; filter.syncedFrom = ''; filter.syncedTo = ''; page.value = 1; void loadCategoryOptions(); void load() })
onMounted(() => { onMounted(() => {
void loadGroupOptions() void loadGroupOptions()
void loadCategoryOptions() void loadCategoryOptions()
@@ -4,8 +4,8 @@
* +勾选行 →「归入所选分类」/「移出分类」。归类走批量端点 * +勾选行 →「归入所选分类」/「移出分类」。归类走批量端点
* POST /api/admin/jd-products/batch-assign-group:后端与单行编辑同口径置 manual_locked=1 * POST /api/admin/jd-products/batch-assign-group:后端与单行编辑同口径置 manual_locked=1
* (归类即人工干预,采集 upsert/覆盖清理不再碰该行,分类永不丢;代价是该行价格/库存随锁 * (归类即人工干预,采集 upsert/覆盖清理不再碰该行,分类永不丢;代价是该行价格/库存随锁
* 停更——弹窗提示语点名这个后果)。取数复用 fetchJdProductList(不带公司维度, * 停更——弹窗提示语点名这个后果)。取数复用 fetchJdProductList(不带公司维度,全平台一份);
* company-tab-wiring 只认两个公司维度发送口);「未分类」走 ungrouped 参数。 * 「未分类」走 ungrouped 参数。
* 归类目标(selectedGroup)由左栏(父件)点亮下发;弹窗壳 v-if 整树重建 ⇒ 每次打开即本件 * 归类目标(selectedGroup)由左栏(父件)点亮下发;弹窗壳 v-if 整树重建 ⇒ 每次打开即本件
* 重挂载、onMounted 自取首屏行集。成功后 emit('changed') 让父件刷新分类商品数并上抛页面; * 重挂载、onMounted 自取首屏行集。成功后 emit('changed') 让父件刷新分类商品数并上抛页面;
* 业务失败把后端中文文案展示在本面板红条内。 */ * 业务失败把后端中文文案展示在本面板红条内。 */
@@ -54,7 +54,6 @@ async function loadProducts(): Promise<void> {
titleKeyword: keyword.value.trim(), titleKeyword: keyword.value.trim(),
groupId: scope.value === 'current' && props.selectedGroup ? String(props.selectedGroup.id) : '', groupId: scope.value === 'current' && props.selectedGroup ? String(props.selectedGroup.id) : '',
ungrouped: scope.value === 'ungrouped', ungrouped: scope.value === 'ungrouped',
companyId: null,
}) })
products.value = result.items products.value = result.items
productTotal.value = result.total productTotal.value = result.total
File diff suppressed because one or more lines are too long
@@ -1,10 +1,10 @@
/** 京东数据库查询适配(v1.4 Phase 5):GET /api/admin/jd-products + 删除(DELETE /{id} + /** 京东数据库查询适配(v1.4 Phase 5):GET /api/admin/jd-products + 删除(DELETE /{id} +
* POST /batch-delete)+ 分组端点 /api/admin/jd-product-groups。 * POST /batch-delete)+ 分组端点 /api/admin/jd-product-groups。
* 公司口径(2026-11-15 用户定案「京东数据库不区分公司、属于公共的」):公共库只有两个 * 公司口径(2026-11-16 用户定案「删除掉公司 tab,参考品牌数据库」):全页零公司维度——
* 公司维度出口——只读列表与类目下拉把公司 tab 的值下传(仅超管生效=筛选管理员); * 只读列表与类目下拉的 company_id 发送口已随公司 tab 摘除(后端读侧谓词同窗撤,重上时
* 详情/编辑/删除/分组管理全平台一份,不收 company_id(后端写侧也没有公司维度)。 * 从 git 历史找回),详情/编辑/删除/分组管理本就不带;行 company_id 列仍是同步来源标记、
* 取值口形状由 company-tab-wiring 护栏钉住。导出发送口已随 2026-11-15 客户口径 * 随详情下发。反向钉在 company-tab-wiring「公司维度不得回流」清单。
* 「导出也不用」从前端下线(后端 /export 端点保留)。 */ * 导出发送口已随 2026-11-15 客户口径「导出也不用」从前端下线(后端 /export 端点保留)。 */
import { http } from '@/api/http' import { http } from '@/api/http'
import { errorTextOf, unwrap } from '../../api/envelope.ts' import { errorTextOf, unwrap } from '../../api/envelope.ts'
import { import {
@@ -36,8 +36,7 @@ export async function fetchJdProductList(
params.page, params.page,
params.pageSize, params.pageSize,
) )
if (params.companyId != null) query.company_id = params.companyId // 未分类范围(店铺分类弹窗「未分类」页签):由发送口直传,构造器不认识它。
// 未分类范围(店铺分类弹窗「未分类」页签):与 company_id 一样由发送口直传,构造器不认识它。
if (params.ungrouped) query.ungrouped = true if (params.ungrouped) query.ungrouped = true
const { data } = await http.get<unknown>(JD_PRODUCT_ENDPOINT, { params: query }) const { data } = await http.get<unknown>(JD_PRODUCT_ENDPOINT, { params: query })
return parseJdProductPage(data) return parseJdProductPage(data)
@@ -189,12 +188,8 @@ export interface JdProductCategoryOption {
productCount: number productCount: number
} }
export async function fetchJdProductCategories( export async function fetchJdProductCategories(): Promise<JdProductCategoryOption[]> {
companyId: number | null, const { data } = await http.get<unknown>(`${JD_PRODUCT_ENDPOINT}/categories`)
): Promise<JdProductCategoryOption[]> {
const query: Record<string, number> = {}
if (companyId != null) query.company_id = companyId
const { data } = await http.get<unknown>(`${JD_PRODUCT_ENDPOINT}/categories`, { params: query })
const core = unwrap<unknown>(data) const core = unwrap<unknown>(data)
if (!Array.isArray(core)) return [] if (!Array.isArray(core)) return []
const out: JdProductCategoryOption[] = [] const out: JdProductCategoryOption[] = []
@@ -9,8 +9,8 @@
* 后端 `sale_status` 参数与 `/export` 端点保留(无 UI 入口),重上时从 git 历史找回取值口。 * 后端 `sale_status` 参数与 `/export` 端点保留(无 UI 入口),重上时从 git 历史找回取值口。
* 分页钳制(铁律 15):page < 1 归 1、上限 10_000(后端 CR-18 同值),(page-1)*page_size * 分页钳制(铁律 15):page < 1 归 1、上限 10_000(后端 CR-18 同值),(page-1)*page_size
* 最大 999_900,Number.MAX_SAFE_INTEGER 也不会把乘积顶出安全整数。纯逻辑,node --test 直测。 * 最大 999_900,Number.MAX_SAFE_INTEGER 也不会把乘积顶出安全整数。纯逻辑,node --test 直测。
* 公司维不在这里:归一化构造器不认识 company_id(同外观专利 filter 惯例),由 api 发送口从 * 公司维已整页摘除(2026-11-16 用户定案「删除掉公司 tab,参考品牌数据库」):归一化构造器
* 原始入参自己下传——取值口由 company-tab-wiring 护栏的发送行钉看守。 * 与入参类型都不认识 company_id——读侧发送口已随公司 tab 撤下(品牌库 2026-10-06 先例同形)。
* 日期默认空字符串:同步台账是累计数据,默认当天会让首屏只剩今天同步的行 * 日期默认空字符串:同步台账是累计数据,默认当天会让首屏只剩今天同步的行
* (date-filter-default-today 护栏 EXEMPT 口径,外观专利页同款)。 */ * (date-filter-default-today 护栏 EXEMPT 口径,外观专利页同款)。 */
import { validIsoDateOrUndefined } from '../asin/asin-filter.ts' import { validIsoDateOrUndefined } from '../asin/asin-filter.ts'
@@ -70,11 +70,9 @@ export interface JdProductQuery {
grouped?: boolean grouped?: boolean
synced_from?: string synced_from?: string
synced_to?: string synced_to?: string
/** 公司 tab:白名单构造不点名它,字段只为 api 发送口的 `query.company_id = params.companyId` 存在。 */
company_id?: number
} }
/** api 模块的入参:筛选态 + 分页 + 公司值(camel)。 */ /** api 模块的入参:筛选态 + 分页(公共库无公司维度)。 */
export interface JdProductListParams { export interface JdProductListParams {
page: number page: number
pageSize: number pageSize: number
@@ -88,7 +86,6 @@ export interface JdProductListParams {
ungrouped?: boolean ungrouped?: boolean
syncedFrom?: string syncedFrom?: string
syncedTo?: string syncedTo?: string
companyId?: number | null
} }
/** 过滤态 → 过滤面参数(snake_case,仅下发非空字段)。 */ /** 过滤态 → 过滤面参数(snake_case,仅下发非空字段)。 */
@@ -1,7 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { formatDateTime } from '@/utils/datetime' import { formatDateTime } from '@/utils/datetime'
/** 数富AI工作台客户端包管理页:上传 ZIP → 直传 MinIO → 服务端复算 sha256 落库; /** 数富AI工作台客户端包管理页:上传 ZIP → 直传 MinIO → 服务端复算 sha256 落库。
* 客户端从 /api/workbench-client/version/latest 自动检测并按最新上传升级。
* 列表默认按上传时间倒序,第一条即当前生效版本;删除最新包后自动回落到上一版。 */ * 列表默认按上传时间倒序,第一条即当前生效版本;删除最新包后自动回落到上一版。 */
import { computed, onMounted, ref, watch } from 'vue' import { computed, onMounted, ref, watch } from 'vue'
import OldPagination from '@/components/OldPagination.vue' import OldPagination from '@/components/OldPagination.vue'
@@ -177,7 +176,7 @@ onMounted(load)
<button class="btn" type="button" @click="openUpload">上传客户端包</button> <button class="btn" type="button" @click="openUpload">上传客户端包</button>
</div> </div>
</div> </div>
<p class="page-hint">客户端更新检查接口:<code>/api/workbench-client/version/latest</code>;最新上传的一条即当前生效版本。</p> <p class="page-hint">最新上传的一条即当前生效版本。</p>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" /> <LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
<div class="table-scroll workbench-table-scroll"> <div class="table-scroll workbench-table-scroll">
@@ -20,9 +20,6 @@ export const WORKBENCH_CLIENT_CHUNK_ENDPOINT = `${WORKBENCH_CLIENT_PACKAGE_ENDPO
export const WORKBENCH_CLIENT_UNCONFIRMED_OBJECT_ENDPOINT = `${WORKBENCH_CLIENT_PACKAGE_ENDPOINT}/object` export const WORKBENCH_CLIENT_UNCONFIRMED_OBJECT_ENDPOINT = `${WORKBENCH_CLIENT_PACKAGE_ENDPOINT}/object`
export const FILES_CHUNK_ENDPOINT = '/api/files/chunk' export const FILES_CHUNK_ENDPOINT = '/api/files/chunk'
/** 客户端自动更新契约(后管页面不直接调用):GET 返回 {version,file_url,sha256,...}。 */
export const WORKBENCH_CLIENT_PUBLIC_LATEST_ENDPOINT = '/api/workbench-client/version/latest'
/** MinIO 直传专用实例:不带 cookie、不挂 401 跳登录拦截器;大 zip 给足超时。 */ /** MinIO 直传专用实例:不带 cookie、不挂 401 跳登录拦截器;大 zip 给足超时。 */
const directPut = axios.create({ timeout: 600_000, withCredentials: false }) const directPut = axios.create({ timeout: 600_000, withCredentials: false })
+2 -1
View File
@@ -45,7 +45,8 @@ export const adminPages: AdminPageDef[] = [
{ path: 'asin-center/categories', menuKey: 'admin_product_categories', title: '商品类目', companyScoped: false, load: () => import('@/pages/asin/ProductCategoryPage.vue') }, { path: 'asin-center/categories', menuKey: 'admin_product_categories', title: '商品类目', companyScoped: false, load: () => import('@/pages/asin/ProductCategoryPage.vue') },
{ path: 'asin-center/skip-price', menuKey: 'admin_skip_price_asin', title: '最低价ASIN', companyScoped: true, load: () => import('@/pages/asin/SkipPricePage.vue') }, { path: 'asin-center/skip-price', menuKey: 'admin_skip_price_asin', title: '最低价ASIN', companyScoped: true, load: () => import('@/pages/asin/SkipPricePage.vue') },
{ path: 'patent-center/clean-items', menuKey: 'admin_appearance_patent_clean_items', title: '外观专利数据库', companyScoped: true, load: () => import('@/pages/patent/AppearancePatentCleanItemsPage.vue') }, { path: 'patent-center/clean-items', menuKey: 'admin_appearance_patent_clean_items', title: '外观专利数据库', companyScoped: true, load: () => import('@/pages/patent/AppearancePatentCleanItemsPage.vue') },
{ path: 'jd-center/database', menuKey: 'admin_jd_database', title: '京东数据库', companyScoped: true, load: () => import('@/pages/jd/JdDatabasePage.vue') }, // 京东数据库 2026-11-16 退出公司 tab(参考品牌数据库先例):数据全平台公共,不按公司取数。
{ path: 'jd-center/database', menuKey: 'admin_jd_database', title: '京东数据库', companyScoped: false, load: () => import('@/pages/jd/JdDatabasePage.vue') },
] ]
export function routeOf(page: AdminPageDef): RouteRecordRaw { export function routeOf(page: AdminPageDef): RouteRecordRaw {
@@ -4,7 +4,7 @@ import { readSource } from './helpers.ts'
import { adminPages } from '../src/router/routes.ts' import { adminPages } from '../src/router/routes.ts'
import { OPERATION_GUIDES } from '../src/layout/operation-guides.ts' import { OPERATION_GUIDES } from '../src/layout/operation-guides.ts'
/** 工作台客户端包管理页:独立渠道、上传直传、服务端 sha256、客户端自动更新契约。 */ /** 工作台客户端包管理页:独立渠道、上传直传、服务端 sha256。 */
test('align_workbench_client_page_registered', () => { test('align_workbench_client_page_registered', () => {
const page = adminPages.find((p) => p.path === 'records/workbench-client-package') const page = adminPages.find((p) => p.path === 'records/workbench-client-package')
@@ -28,7 +28,6 @@ test('align_workbench_client_page_wiring', () => {
assert.match(page, /当前生效/, '最新上传的包标记当前生效') assert.match(page, /当前生效/, '最新上传的包标记当前生效')
assert.match(page, /sha256/, '展示服务端复算的摘要') assert.match(page, /sha256/, '展示服务端复算的摘要')
assert.match(page, /formatFileSize/, '展示包体大小') assert.match(page, /formatFileSize/, '展示包体大小')
assert.match(page, /\/api\/workbench-client\/version\/latest/, '页面标明客户端更新检查接口')
assert.match(page, /确认删除选中的/, '批量删除二次确认') assert.match(page, /确认删除选中的/, '批量删除二次确认')
assert.match(page, /暂无客户端包记录/, '空态文案') assert.match(page, /暂无客户端包记录/, '空态文案')
}) })
@@ -43,7 +42,6 @@ test('align_workbench_client_api_contract', () => {
assert.match(api, /params: \{ file_name: fileName, version \}/, '预签名回传文件名与版本号') assert.match(api, /params: \{ file_name: fileName, version \}/, '预签名回传文件名与版本号')
assert.match(api, /params: \{ object_key: objectKey, file_name: fileName, version \}/, '确认回传对象 key、文件名与版本号') assert.match(api, /params: \{ object_key: objectKey, file_name: fileName, version \}/, '确认回传对象 key、文件名与版本号')
assert.match(api, /withCredentials: false/, '直传实例不挂会话拦截器') assert.match(api, /withCredentials: false/, '直传实例不挂会话拦截器')
assert.match(api, /\/api\/workbench-client\/version\/latest/, '公开更新契约路径固定')
}) })
test('align_workbench_client_model_parsers', () => { test('align_workbench_client_model_parsers', () => {
@@ -61,5 +59,4 @@ test('align_workbench_client_guide_registered', () => {
const guide = OPERATION_GUIDES.admin_workbench_client_package const guide = OPERATION_GUIDES.admin_workbench_client_package
assert.ok(guide, '每个菜单页都必须有操作提示') assert.ok(guide, '每个菜单页都必须有操作提示')
assert.match(guide.text, /sha256/, '提示说明服务端会复算摘要') assert.match(guide.text, /sha256/, '提示说明服务端会复算摘要')
assert.match(guide.text, /\/api\/workbench-client\/version\/latest/, '提示说明客户端更新检查接口')
}) })
@@ -111,7 +111,10 @@ test('V196 新增的京东数据库菜单 key 必须在路由注册表登记', (
assert.ok(page, 'routes.ts 必须有 admin_jd_database 页面,否则菜单点进去 404') assert.ok(page, 'routes.ts 必须有 admin_jd_database 页面,否则菜单点进去 404')
assert.equal(page.path, menu.routePath, '库里的 route_path 应与注册表路径一致') assert.equal(page.path, menu.routePath, '库里的 route_path 应与注册表路径一致')
assert.equal(page.title, menu.name, '页面标题应与菜单名一致') assert.equal(page.title, menu.name, '页面标题应与菜单名一致')
assert.equal(page.companyScoped, true, '京东数据库按公司 tab 取数') // 2026-11-16 用户定案「删除掉公司 tab,参考品牌数据库」:数据全平台公共(行 company_id
// 只剩同步来源标记),页面退出公司 tab 注册表、取数口不带 company_id ⇒ meta 必须 false
// (true 会画出 tab 而取数不带参=点了没反应;同品牌数据库 admin_invalid_asin_data 的形状)。
assert.equal(page.companyScoped, false, '京东数据库全平台公共,不画公司 tab(V196 当时的按公司隔离口径已被推翻)')
// 每公司一套树(公司 1 模板行 + 其余公司复制),挂数据管理组、排序 68(V190 外观专利占 67)。 // 每公司一套树(公司 1 模板行 + 其余公司复制),挂数据管理组、排序 68(V190 外观专利占 67)。
assert.ok(sql.includes("grp.`column_key` = 'admin_group_data'"), 'V196 必须把京东数据库挂到数据管理组') assert.ok(sql.includes("grp.`column_key` = 'admin_group_data'"), 'V196 必须把京东数据库挂到数据管理组')
@@ -77,6 +77,7 @@ function escapeRegExp(text: string): string {
* + 批次 6(控制方 2026-10-06 点名「菜单权限也加字段来区分」)3 处:菜单目录 / 新建菜单 / 用户管理里的授权树 * + 批次 6(控制方 2026-10-06 点名「菜单权限也加字段来区分」)3 处:菜单目录 / 新建菜单 / 用户管理里的授权树
* + 批次 7(2026-11-10 v1.3 外观专利无侵权数据)2 处:只读列表 + 导出(2026-11-11 客户需求「数据得导出来」)。 * + 批次 7(2026-11-10 v1.3 外观专利无侵权数据)2 处:只读列表 + 导出(2026-11-11 客户需求「数据得导出来」)。
* 批次 2 原 12 处里的品牌库 1 处 + 商品类目 4 处,随 2026-10-06「这两页退回全平台共享」一并摘掉。 * 批次 2 原 12 处里的品牌库 1 处 + 商品类目 4 处,随 2026-10-06「这两页退回全平台共享」一并摘掉。
* 批次 8 原 2 处(京东数据库列表/类目)随 2026-11-16「删除掉公司 tab,参考品牌数据库」一并摘掉。
* *
* <p>`window` 的取法:本轮实扫的 own(到自己那行的距离)+ ≥150 余量,且当同文件还有下一个同名发送口时必须 * <p>`window` 的取法:本轮实扫的 own(到自己那行的距离)+ ≥150 余量,且当同文件还有下一个同名发送口时必须
* `window < next`。own/next 不写死在这里——下面「窗口与真文件对平」那条用例逐处从真文件重算, * `window < next`。own/next 不写死在这里——下面「窗口与真文件对平」那条用例逐处从真文件重算,
@@ -132,15 +133,9 @@ const SEND_POINTS: ReadonlyArray<SendPoint> = [
// 500 够得着自己、够不到隔壁(对平用例逐处从真文件重算,注释过期即红)。 // 500 够得着自己、够不到隔壁(对平用例逐处从真文件重算,注释过期即红)。
{ menuKey: 'admin_appearance_patent_clean_items', file: 'src/pages/patent/appearance-patent-clean-api.ts', fn: 'fetchAppearancePatentCleanList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 500, title: 'GET /appearance-patent-clean-items 无侵权只读列表' }, { menuKey: 'admin_appearance_patent_clean_items', file: 'src/pages/patent/appearance-patent-clean-api.ts', fn: 'fetchAppearancePatentCleanList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 500, title: 'GET /appearance-patent-clean-items 无侵权只读列表' },
{ menuKey: 'admin_appearance_patent_clean_items', file: 'src/pages/patent/appearance-patent-clean-api.ts', fn: 'exportAppearancePatentCleanList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 500, title: 'GET /appearance-patent-clean-items/export 导出(2026-11-11 客户需求「数据得导出来」,与列表共用同一过滤面)' }, { menuKey: 'admin_appearance_patent_clean_items', file: 'src/pages/patent/appearance-patent-clean-api.ts', fn: 'exportAppearancePatentCleanList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 500, title: 'GET /appearance-patent-clean-items/export 导出(2026-11-11 客户需求「数据得导出来」,与列表共用同一过滤面)' },
// ↓ 批次 8(2026-11-14 v1.4 京东数据库;2026-11-15 公共化改口径):京麦店铺商品采集落库的 // 批次 8(2026-11-14 v1.4 京东数据库)的两条发送口(列表/类目下拉)已于 2026-11-16 随
// 只读镜像,行 company_id 只剩"哪家公司客户端同步的"来源标记。2026-11-15 用户定案 // 「删除掉公司 tab,参考品牌数据库」整批摘下(后端读侧谓词同窗撤,重上时从 git 历史找回);
// 「京东数据库不区分公司、属于公共的」「分组和亚马逊功能一样」⇒ 详情/编辑/删除/分组管理 // 「不得回流」由文件末尾「公司维度不得回流」清单看守(admin_jd_database 已入列)。
// 的 6 个 company_id 发送口整批撤下(后端写侧同窗摘掉公司谓词,重上时从 git 历史找回);
// 留下的两个公司维度出口=只读列表与类目下拉(仅超管生效=筛选管理员,普通管理员没有
// 这个筛选)。导出发送口已随 2026-11-15 客户口径「导出也不用」从前端下线(后端 /export
// 端点保留,前端发送口撤,重上时从 git 历史找回发送行再登记——同批次 7 主管两口的先例)。
{ menuKey: 'admin_jd_database', file: 'src/pages/jd/jd-product-api.ts', fn: 'fetchJdProductList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 500, title: 'GET /jd-products 京东数据库只读列表(超管公司 tab 筛选=筛选管理员)' },
{ menuKey: 'admin_jd_database', file: 'src/pages/jd/jd-product-api.ts', fn: 'fetchJdProductCategories', line: 'if (companyId != null) query.company_id = companyId', window: 500, title: 'GET /jd-products/categories 类目下拉(选项集与超管当前 tab 行集同源)' },
] ]
/** 任务看板那 5 处(1b ④ 那条用例按文件筛它们,沿用旧名字不漂;表只有一份,不会漂出两个口径)。 */ /** 任务看板那 5 处(1b ④ 那条用例按文件筛它们,沿用旧名字不漂;表只有一份,不会漂出两个口径)。 */
@@ -264,8 +259,8 @@ const COMPANY_ID_SOURCE_PINS: Readonly<Record<string, readonly CompanyIdPin[]>>
admin_columns: pinsFor('admin_columns'), admin_columns: pinsFor('admin_columns'),
// 批次 7(v1.3 无侵权只读页):同样由 SEND_POINTS 现算——只有一个发送口(列表)。 // 批次 7(v1.3 无侵权只读页):同样由 SEND_POINTS 现算——只有一个发送口(列表)。
admin_appearance_patent_clean_items: pinsFor('admin_appearance_patent_clean_items'), admin_appearance_patent_clean_items: pinsFor('admin_appearance_patent_clean_items'),
// 批次 8(v1.4 京东数据库):列表一口(导出发送口 2026-11-15 随客户口径下线),由 SEND_POINTS 现算。 // 批次 8(v1.4 京东数据库)2026-11-16 随「删除掉公司 tab」整页摘除:登记表条目一并撤下,
admin_jd_database: pinsFor('admin_jd_database'), // 「不得回流」改由文件末尾「公司维度不得回流」清单看守(同品牌库/商品类目的先例形状)。
} }
/** 严格判据的分母由本轮实扫得出(修完不许恒绿也不许恒红):求值了几条 shape、其中几条通过。 */ /** 严格判据的分母由本轮实扫得出(修完不许恒绿也不许恒红):求值了几条 shape、其中几条通过。 */
@@ -366,9 +361,11 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
// 这条只防"整表被摘空/被改窄",逐处脱管由下面两条(对平闸门 + 窗口对平)负责。 // 这条只防"整表被摘空/被改窄",逐处脱管由下面两条(对平闸门 + 窗口对平)负责。
// 2026-11-15 京东数据库公共化(用户定案「不区分公司、属于公共的」):批次 8 的详情/删除/ // 2026-11-15 京东数据库公共化(用户定案「不区分公司、属于公共的」):批次 8 的详情/删除/
// 分组列表/删分组/编辑 5 条 company_id 发送口随公司谓词整批撤下(后端写侧同窗摘),批次 8 // 分组列表/删分组/编辑 5 条 company_id 发送口随公司谓词整批撤下(后端写侧同窗摘),批次 8
// 只剩列表/类目两条(超管筛选管理员)⇒ 32 → 27。 // 只剩列表/类目两条 ⇒ 32 → 27。
assert.ok(SEND_POINTS.length >= 27, // 2026-11-16 京东数据库摘公司 tab(用户定案「删除掉公司 tab,参考品牌数据库」):最后两条
`发送口表只剩 ${SEND_POINTS.length} 条(批次 1+2+3+4+5+6 实扫 21 条 + 批次 7 v1.3 无侵权列表/导出 2 条 + 主管聚合 1 条 + 按主管删除 1 条 + 批次 8 v1.4 京东数据库列表/类目 2 条(详情/删除/分组/删分组/编辑 5 口随 2026-11-15 公共化撤、导出口随客户口径下线)= 27 条)⇒ 有人把钉从表里摘了,取值口看守成空`) // 发送口(列表/类目下拉)与后端读侧谓词同窗摘掉,页面退出注册表 ⇒ 27 → 25。
assert.ok(SEND_POINTS.length >= 25,
`发送口表只剩 ${SEND_POINTS.length} 条(批次 1+2+3+4+5+6 实扫 21 条 + 批次 7 v1.3 无侵权列表/导出 2 条 + 主管聚合 1 条 + 按主管删除 1 条 = 25 条;京东数据库两条 2026-11-16 随「删除掉公司 tab」摘、导出口 2026-11-15 随客户口径摘)⇒ 有人把钉从表里摘了,取值口看守成空`)
for (const p of SEND_POINTS) { for (const p of SEND_POINTS) {
const shape = pointShape(p) const shape = pointShape(p)
const compliant = pointCompliant(p) const compliant = pointCompliant(p)
@@ -400,8 +397,8 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
if (hit) hit.pinned += 1 if (hit) hit.pinned += 1
else grouped.set(key, { file: p.file, line: p.line, pinned: 1 }) else grouped.set(key, { file: p.file, line: p.line, pinned: 1 })
} }
assert.equal(grouped.size, 21, assert.equal(grouped.size, 19,
`发送口表按 (文件, 整行) 应聚成 21 组(32 处发送口,批次 7 的列表/导出/主管聚合/按主管删除、批次 8 的京东详情/删除/分组/类目/删分组/编辑逐字同行各走同一组;京东导出口 2026-11-15 随客户口径下线),现在却有 ${grouped.size} 组 —— 表被改形状了,对平判据失去分母`) `发送口表按 (文件, 整行) 应聚成 19 组(25 处发送口,批次 7 的列表/导出/主管聚合/按主管删除逐字同行各走同一组;京东数据库两组 2026-11-16 随「删除掉公司 tab」摘),现在却有 ${grouped.size} 组 —— 表被改形状了,对平判据失去分母`)
for (const g of grouped.values()) { for (const g of grouped.values()) {
const actual = occurrences(stripComments(read(g.file)), g.line) const actual = occurrences(stripComments(read(g.file)), g.line)
assert.equal(g.pinned, actual, assert.equal(g.pinned, actual,
@@ -757,21 +754,9 @@ const WATCH_BODY_PINS: ReadonlyArray<{
{ file: 'src/pages/patent/appearance-patent-clean-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] }, { file: 'src/pages/patent/appearance-patent-clean-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] },
], ],
}, },
// ↓ 批次 8(2026-11-14 v1.4 京东数据库;2026-11-15 公共化改口径):商品编码/标题是 // 批次 8(2026-11-14 v1.4 京东数据库页)那条 watch 看守已于 2026-11-16 随「删除掉公司 tab,
// 按行集筛的自由文本,类目选项集与超管当前 tab 的行集同源 ⇒ 上一家的筛选值与 category // 参考品牌数据库」一并摘下——页面不再 watch companyTab.activeId、不再消费公司 tab store,
// 在新一家的行集/选项集里不存在,切 tab 必清且类目选项重取;页码回 1 同外观专利页。 // 「不得回流」改由文件末尾「公司维度不得回流」清单看守。
// 分组 2026-11-15 起全平台一份(公共),groupId 与公司维度正交——不清、选项也不随 tab 重取。
// 店铺筛选 2026-11-15 客户口径「店铺不需要」下线(watch 体不再清 shopName,参数面无它)。
{
file: 'src/pages/jd/JdDatabasePage.vue',
token: "filter.productCode = ''; filter.titleKeyword = ''; filter.category = ''; filter.syncedFrom = ''; filter.syncedTo = ''; page.value = 1; void loadCategoryOptions(); void load()",
why: '商品编码/标题是按行集筛的自由文本,上一家的值在新一家的行里不存在 ⇒ 切 tab 后首屏被筛成「暂无商品」,'
+ '而输入框还显示着上一家填的值;类目选项集与超管当前 tab 的行集同源,上一家选的 category 在新一家的选项里不存在,'
+ '同罪必清且选项重取;页码回 1 是因为新一家的行数更少,末尾的 void load() 才让切 tab 真的换数据',
premise: [
{ file: 'src/pages/jd/jd-product-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] },
],
},
] ]
/** 取「`watch(() => companyTab.activeId, () => { … })`」这一条语句的原文;匹配不出返回 null(由调用方判探针失效)。 */ /** 取「`watch(() => companyTab.activeId, () => { … })`」这一条语句的原文;匹配不出返回 null(由调用方判探针失效)。 */
@@ -780,9 +765,9 @@ function watchStatement(source: string): string | null {
return m ? m[0] : null return m ? m[0] : null
} }
test('切公司的 watch 体:每对 (file, token) 都要在该页 watch 体内出现(批次 1 两页 + 批次 2 三页 + 批次 3 两页 + 批次 4 一页 + 批次 5 一页 + 批次 6 一页 + 批次 7 一页 + 批次 8 一页)', () => { test('切公司的 watch 体:每对 (file, token) 都要在该页 watch 体内出现(批次 1 两页 + 批次 2 三页 + 批次 3 两页 + 批次 4 一页 + 批次 5 一页 + 批次 6 一页 + 批次 7 一页)', () => {
assert.ok(WATCH_BODY_PINS.length >= 11, assert.ok(WATCH_BODY_PINS.length >= 11,
`watch 体看守只剩 ${WATCH_BODY_PINS.length} 对(批次 1 的店铺管理/任务看板 + 批次 2 的去重库/查询ASIN/最低价ASIN + 批次 3 的撞款监控/店铺数据记录 + 批次 4 的用户管理 + 批次 5 的店铺密钥 + 批次 6 的菜单管理 + 批次 7 v1.3 无侵权只读页 + 批次 8 v1.4 京东数据库页共 12 对)` `watch 体看守只剩 ${WATCH_BODY_PINS.length} 对(批次 1 的店铺管理/任务看板 + 批次 2 的去重库/查询ASIN/最低价ASIN + 批次 3 的撞款监控/店铺数据记录 + 批次 4 的用户管理 + 批次 5 的店铺密钥 + 批次 6 的菜单管理 + 批次 7 v1.3 无侵权只读页共 11 对;批次 8 京东数据库页那条 2026-11-16 随「删除掉公司 tab」摘下)`
+ '⇒ 这一族又退回"只钉少数几页",被摘掉那一页的"切公司不清筛选项"再次没人看守') + '⇒ 这一族又退回"只钉少数几页",被摘掉那一页的"切公司不清筛选项"再次没人看守')
const pinnedFiles = new Set(WATCH_BODY_PINS.map((pin) => pin.file)) const pinnedFiles = new Set(WATCH_BODY_PINS.map((pin) => pin.file))
for (const pin of WATCH_BODY_PINS) { for (const pin of WATCH_BODY_PINS) {
@@ -984,26 +969,30 @@ test('渲染范围:tab 条只画在按公司取数的页上,公司管理那
}) })
/** /**
* 2026-10-06 控制方定案:品牌数据库、商品类目「做成所有公司共享的,不区分」。 * 控制方/用户定案的「全平台共享、不区分公司」页清单:
* - 品牌数据库、商品类目(2026-10-06 控制方定案「做成所有公司共享的,不区分」);
* - 京东数据库(2026-11-16 用户定案「删除掉公司 tab,参考品牌数据库」)。
* *
* <p>上面那几条正向判据全是从 {@code COMPANY_SCOPED_PAGES} 派生的,页一退出注册表就自动不再求值 ⇒ * <p>上面那几条正向判据全是从 {@code COMPANY_SCOPED_PAGES} 派生的,页一退出注册表就自动不再求值 ⇒
* 「退出」这件事本身没有看守:谁把 {@code company_id} 重新塞回这三个取数口,全仓用例一支都不会红, * 「退出」这件事本身没有看守:谁把 {@code company_id} 重新塞回这些取数口,全仓用例一支都不会红,
* 而后端唯一键已经退回全局(V151),带公司参数的读会把共享库筛窄成「只看这一家」, * 而后端唯一键已经退回全局(V151)/读侧谓词已摘(京东),带公司参数的读会把共享库筛窄成「只看这一家」,
* 写侧则把一张全平台共享的表按家拆开——两边都是静默改口径,不是报错。所以这一支必须存在。</p> * 写侧则把一张全平台共享的表按家拆开——两边都是静默改口径,不是报错。所以这一支必须存在。</p>
* *
* <p>判据只认「剥完注释的代码」:这三份文件现在各自留有一句说明共享口径的注释, * <p>判据只认「剥完注释的代码」:这些文件各自留有一句说明共享口径的注释,
* 注释里的 {@code company_id} 三个字面字符不是接线(全局约束 6)。正样本用摘掉之前那三行原文, * 注释里的 {@code company_id} 三个字面字符不是接线(全局约束 6)。正样本用摘掉之前那些行原文,
* 所以下面的 false 是测出来的,不是「正则本来就抓不到」。</p> * 所以下面的 false 是测出来的,不是「正则本来就抓不到」。</p>
*/ */
const SHARED_PAGE_KEYS = ['admin_invalid_asin_data', 'admin_product_categories'] as const const SHARED_PAGE_KEYS = ['admin_invalid_asin_data', 'admin_product_categories', 'admin_jd_database'] as const
const SHARED_API_FILES = [ const SHARED_API_FILES = [
'src/pages/invalidasin/invalid-asin-api.ts', 'src/pages/invalidasin/invalid-asin-api.ts',
'src/pages/asin/product-category-api.ts', 'src/pages/asin/product-category-api.ts',
'src/pages/asin/product-category-export.ts', 'src/pages/asin/product-category-export.ts',
'src/pages/jd/jd-product-api.ts',
] as const ] as const
const SHARED_PAGE_FILES = [ const SHARED_PAGE_FILES = [
'src/pages/asin/AsinInvalidPage.vue', 'src/pages/asin/AsinInvalidPage.vue',
'src/pages/asin/ProductCategoryPage.vue', 'src/pages/asin/ProductCategoryPage.vue',
'src/pages/jd/JdDatabasePage.vue',
] as const ] as const
/** 公司参数的两种写法:下传用的 snake、形参/字段用的 camel。 */ /** 公司参数的两种写法:下传用的 snake、形参/字段用的 camel。 */
@@ -1016,7 +1005,7 @@ const FORMER_SEND_LINES = [
'if (companyId != null) params.push(`company_id=${companyId}`)', 'if (companyId != null) params.push(`company_id=${companyId}`)',
] ]
test('公司维度不得回流:品牌库与商品类目已定案全平台共享,取数口与页面都不许再带公司参数', () => { test('公司维度不得回流:品牌库/商品类目/京东数据库已定案全平台共享,取数口与页面都不许再带公司参数', () => {
// 判据自证(全局约束 15:反向钉不许独自成立)——改动前那三行必须抓得到,否则下面的 false 是空判据。 // 判据自证(全局约束 15:反向钉不许独自成立)——改动前那三行必须抓得到,否则下面的 false 是空判据。
for (const line of FORMER_SEND_LINES) { for (const line of FORMER_SEND_LINES) {
assert.ok(COMPANY_PARAM_TOKEN.test(line), `反向钉判据连原来的发送口「${line}」都匹配不出 ⇒ 这一族恒绿`) assert.ok(COMPANY_PARAM_TOKEN.test(line), `反向钉判据连原来的发送口「${line}」都匹配不出 ⇒ 这一族恒绿`)
@@ -1031,7 +1020,7 @@ test('公司维度不得回流:品牌库与商品类目已定案全平台共
for (const key of SHARED_PAGE_KEYS) { for (const key of SHARED_PAGE_KEYS) {
assert.equal(COMPANY_SCOPED_PAGES.some((p) => p.menuKey === key), false, assert.equal(COMPANY_SCOPED_PAGES.some((p) => p.menuKey === key), false,
`${key} 又回到 COMPANY_SCOPED_PAGES:2026-10-06 已定案这两页全平台共享,不区分公司`) `${key} 又回到 COMPANY_SCOPED_PAGES:已定案全平台共享、不区分公司(品牌库/商品类目 2026-10-06、京东数据库 2026-11-16)`)
const page = adminPages.find((p) => p.menuKey === key) const page = adminPages.find((p) => p.menuKey === key)
assert.ok(page, `${key} 在路由注册表里找不到:菜单名改了,反向钉对不上页`) assert.ok(page, `${key} 在路由注册表里找不到:菜单名改了,反向钉对不上页`)
assert.equal(page.companyScoped, false, assert.equal(page.companyScoped, false,
@@ -0,0 +1,97 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
JD_CATEGORY_TREE,
jdCategoryChildren,
jdCategoryLeaves,
jdCategoryRoots,
jdCategorySearchLeaves,
} from '../src/pages/jd/jd-category-tree.ts'
/** 京麦授权类目真树(2026-11-16 真机取证 getVenderLicenseCategory 快照;与用户端
* frontend-vue 侧同数据两份正本,改树两边同轮同步)。判据钉的是取证读数:
* 3 个一级 / 250 个末级 / 最深 4 级 / 4 组同名跨支——改树先对取证数据(京麦面板
* 或 getVenderLicenseCategory 重抓),不得手改数字凑测试。 */
test('树形状=京麦授权类目真机读数:3 个一级、250 个末级、最深 4 级', () => {
const roots = jdCategoryRoots()
assert.deepEqual(
roots.map((node) => node.name),
['服饰内衣', '母婴', '运动户外'],
'一级就 3 个(京麦面板 2026-11-16 真机:该店铺授权经营类目,不得加回京东公开全量)',
)
assert.deepEqual(
roots.map((node) => node.value),
['1315', '1319', '1318'],
'一级类目 id 与取证响应逐字同',
)
const leaves = jdCategoryLeaves()
assert.equal(leaves.length, 250, '末级节点 250 个(取证读数)')
const maxDepth = Math.max(...leaves.map((leaf) => leaf.path.length))
assert.equal(maxDepth, 4, '树最深 4 级')
})
test('服饰内衣二级与京麦面板逐字同源;逐级下钻到真机样本叶', () => {
assert.deepEqual(
jdCategoryChildren(['服饰内衣']).map((node) => node.name),
['服饰配件', '内衣', '女装', '男装', '定制服装/工装'],
'服饰内衣二级 5 个(京麦面板逐字)',
)
assert.deepEqual(
jdCategoryChildren(['服饰内衣', '服饰配件']).map((node) => node.name),
['腰带/腰链', '耳罩/耳包', '领带/领结/领带夹', '男士丝巾/围巾', '女士丝巾/围巾/披肩', '鸭舌帽',
'礼帽', '手套', '围巾/手套/帽子套装', '毛线帽', '遮阳帽', '棒球帽', '渔夫帽'],
'服饰配件三级 13 个(京麦面板 2026-11-16 截图逐字前 6 +取证快照全量)',
)
assert.deepEqual(
jdCategoryChildren(['服饰内衣', '服饰配件', '腰带/腰链']),
[],
'三级叶子 children 空(末级,可选中)',
)
assert.deepEqual(
jdCategoryChildren(['不存在的一级']),
[],
'未知路径回落空子级(面板该栏缺省)',
)
})
test('落库末级名真机样本都在树内(category_path 等值过滤成立的前提)', () => {
const names = new Set(jdCategoryLeaves().map((leaf) => leaf.name))
for (const sample of ['艺考形体服', '啦啦队服', '拉丁舞服']) {
assert.ok(names.has(sample), `真机样本「${sample}」必须是树内末级(契约 E3 口径)`)
}
const yikao = jdCategoryLeaves().find((leaf) => leaf.name === '艺考形体服')
assert.ok(yikao, '艺考形体服在树内')
assert.equal(yikao!.path.length, 3, '艺考形体服是 level 3 节点(取证读数)')
})
test('同名跨支叶子如实登记:4 组重名(同名行等值过滤一起命中,B112-05 口径)', () => {
const counts = new Map<string, number>()
for (const leaf of jdCategoryLeaves()) {
counts.set(leaf.name, (counts.get(leaf.name) ?? 0) + 1)
}
const dups = [...counts.entries()].filter(([, count]) => count > 1)
assert.deepEqual(
dups.map(([name]) => name).sort(),
['唐装', '吊带/背心', '短裤', '赠品'].sort(),
'重名集与取证读数逐字同(改树后这里红=重名集变了,须复核登记)。注:「汉服」两处节点中'
+ '一处带四级子级是非叶(点它会下钻),不构成末级重名。',
)
})
test('搜索:按名称或路径段命中末级;空词返回全量', () => {
assert.equal(jdCategorySearchLeaves('').length, 250, '空词=全量末级')
const byName = jdCategorySearchLeaves('艺考')
assert.equal(byName.length, 1)
assert.equal(byName[0]!.name, '艺考形体服')
const byPath = jdCategorySearchLeaves('服饰配件')
assert.ok(byPath.length >= 13, '按路径段命中服饰配件全部末级')
assert.ok(byPath.every((leaf) => leaf.path.includes('服饰配件')))
assert.deepEqual(jdCategorySearchLeaves('不存在词xyz'), [])
})
test('树数据快照不可空、value 全非空(取证 id 留档完整)', () => {
assert.ok(JD_CATEGORY_TREE.length > 0)
for (const leaf of jdCategoryLeaves()) {
assert.ok(leaf.value, `叶子 ${leaf.name} 必须带京麦类目 id`)
}
})
@@ -22,12 +22,14 @@ import {
const MENU_KEY = 'admin_jd_database' const MENU_KEY = 'admin_jd_database'
const ROUTE = 'jd-center/database' const ROUTE = 'jd-center/database'
test('routes 注册表出现京东数据库页面且公司隔离', () => { test('routes 注册表出现京东数据库页面且退出公司 tab(2026-11-16 参考品牌数据库定案)', () => {
const page = adminPages.find((item) => item.menuKey === MENU_KEY) const page = adminPages.find((item) => item.menuKey === MENU_KEY)
assert.ok(page, `routes.ts 缺 menuKey=${MENU_KEY} 的注册行`) assert.ok(page, `routes.ts 缺 menuKey=${MENU_KEY} 的注册行`)
assert.equal(page.path, ROUTE, 'route_path 必须与 V196 菜单一侧一致') assert.equal(page.path, ROUTE, 'route_path 必须与 V196 菜单一侧一致')
assert.equal(page.title, '京东数据库', '菜单标题以「京东数据库」为准') assert.equal(page.title, '京东数据库', '菜单标题以「京东数据库」为准')
assert.equal(page.companyScoped, true, '京东数据库按公司隔离(AC-6)') // 数据全平台公共(2026-11-15「不区分公司」→ 2026-11-16「删除掉公司 tab,参考品牌数据库」):
// meta.companyScoped 必须 false——true 会画出公司 tab,而取数口已不带 company_id(点了没反应)。
assert.equal(page.companyScoped, false, '京东数据库全平台公共,不画公司 tab(AC-6 已被 11-15/11-16 口径推翻)')
}) })
/** 详情面的 SKU 矩阵解析(V198):后端下发 camelCase,snake 容错;坏行不炸整块。 */ /** 详情面的 SKU 矩阵解析(V198):后端下发 camelCase,snake 容错;坏行不炸整块。 */
@@ -3,7 +3,8 @@
* *
* 形态:panel-box + 筛选行(商品编码/标题关键字/分类/分类状态/类目/同步起止 date 对)+ * 形态:panel-box + 筛选行(商品编码/标题关键字/分类/分类状态/类目/同步起止 date 对)+
* 查询/重置/店铺分类 + 自绘明细表(点行开详情抽屉)+ OldPagination; * 查询/重置/店铺分类 + 自绘明细表(点行开详情抽屉)+ OldPagination;
* 公司 tab 切换=清筛选重取(company-tab-wiring 同口径)。 * 公司维度 2026-11-16 整页摘除(「删除掉公司 tab,参考品牌数据库」):页面不消费公司 tab
* store、列表/类目下拉不带 company_id(反向钉在 company-tab-wiring「公司维度不得回流」)。
* 商品状态筛选/列与导出按钮已随 2026-11-15 客户口径从前端下线(后端端点保留); * 商品状态筛选/列与导出按钮已随 2026-11-15 客户口径从前端下线(后端端点保留);
* 店铺筛选与店铺列同日客户口径「店铺不需要」下线(后端 shop_name 参数同窗撤,店铺仍收详情抽屉)。 * 店铺筛选与店铺列同日客户口径「店铺不需要」下线(后端 shop_name 参数同窗撤,店铺仍收详情抽屉)。
* 不用 readFileSync(source-pin-ratchet 对台账外新文件带读点即红),全部走真实挂载断言。 * 不用 readFileSync(source-pin-ratchet 对台账外新文件带读点即红),全部走真实挂载断言。
@@ -17,7 +18,6 @@ import { createPinia, setActivePinia, type Pinia } from 'pinia'
import JdDatabasePage from '@/pages/jd/JdDatabasePage.vue' import JdDatabasePage from '@/pages/jd/JdDatabasePage.vue'
import JdProductGroupDialog from '@/pages/jd/JdProductGroupDialog.vue' import JdProductGroupDialog from '@/pages/jd/JdProductGroupDialog.vue'
import { useAdminSessionStore } from '@/stores/admin-session' import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
const jdApi = vi.hoisted(() => ({ const jdApi = vi.hoisted(() => ({
JD_PRODUCT_ENDPOINT: '/api/admin/jd-products', JD_PRODUCT_ENDPOINT: '/api/admin/jd-products',
@@ -79,7 +79,6 @@ beforeEach(() => {
pinia = createPinia() pinia = createPinia()
setActivePinia(pinia) setActivePinia(pinia)
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' } useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
useCompanyTabStore().setActiveId(1)
jdApi.fetchJdProductGroups.mockResolvedValue([]) jdApi.fetchJdProductGroups.mockResolvedValue([])
jdApi.fetchJdProductCategories.mockResolvedValue([]) jdApi.fetchJdProductCategories.mockResolvedValue([])
confirmMock.mockResolvedValue(true) confirmMock.mockResolvedValue(true)
@@ -94,13 +93,14 @@ async function mountWith(payload: unknown): Promise<VueWrapper<Element>> {
} }
describe('京东数据库页(v1.4 Phase 5)', () => { describe('京东数据库页(v1.4 Phase 5)', () => {
it('挂载后按首屏分页参数取列表(pageSize 默认 20、带公司 tab),行数=本页条数', async () => { it('挂载后按首屏分页参数取列表(pageSize 默认 20、不带公司维度),行数=本页条数', async () => {
const wrapper = await mountWith({ items: [item(1), item(2), item(3)], total: 42, page: 1, pageSize: 20 }) const wrapper = await mountWith({ items: [item(1), item(2), item(3)], total: 42, page: 1, pageSize: 20 })
expect(jdApi.fetchJdProductList).toHaveBeenCalledTimes(1) expect(jdApi.fetchJdProductList).toHaveBeenCalledTimes(1)
const firstCall = jdApi.fetchJdProductList.mock.calls[0][0] const firstCall = jdApi.fetchJdProductList.mock.calls[0][0]
expect(firstCall.page).toBe(1) expect(firstCall.page).toBe(1)
expect(firstCall.pageSize).toBe(20) expect(firstCall.pageSize).toBe(20)
expect(firstCall.companyId).toBe(1) // 公司维度 2026-11-16 整页摘除:入参层不再有 companyId 键(单参 toHaveProperty 才是「键不存在」的真判据)。
expect(firstCall).not.toHaveProperty('companyId')
expect(wrapper.findAll('tbody tr')).toHaveLength(3) expect(wrapper.findAll('tbody tr')).toHaveLength(3)
expect(wrapper.find('.jd-summary').text()).toContain('共 42 条京东商品') expect(wrapper.find('.jd-summary').text()).toContain('共 42 条京东商品')
}) })
@@ -242,12 +242,12 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
syncedFrom: '2026-11-01', syncedFrom: '2026-11-01',
syncedTo: '2026-11-09', syncedTo: '2026-11-09',
page: 1, page: 1,
companyId: 1,
}) })
// 单参 toHaveProperty 才是「键不存在」的真判据(第二参会稀释成值断言): // 单参 toHaveProperty 才是「键不存在」的真判据(第二参会稀释成值断言):
// 页面 load() 入参已不带这两个键(店铺/商品状态筛选下线)。 // 页面 load() 入参已不带这三个键(店铺/商品状态筛选下线、公司维度 2026-11-16 摘除)。
expect(last).not.toHaveProperty('shopName') expect(last).not.toHaveProperty('shopName')
expect(last).not.toHaveProperty('saleStatus') expect(last).not.toHaveProperty('saleStatus')
expect(last).not.toHaveProperty('companyId')
}) })
it('分组下拉选中即查', async () => { jdApi.fetchJdProductGroups.mockResolvedValue([ it('分组下拉选中即查', async () => { jdApi.fetchJdProductGroups.mockResolvedValue([
@@ -269,13 +269,13 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ groupId: '7', page: 1 }) expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ groupId: '7', page: 1 })
}) })
it('类目京麦同款级联面板:一/二级静态导航展开,第三栏=已落库末级全集+行数,点末级即查回第一页', async () => { it('类目京麦同款级联面板(2026-11-16 真树重做):授权一级 3 个逐级下钻,点末级即查回第一页', async () => {
jdApi.fetchJdProductCategories.mockResolvedValue([ jdApi.fetchJdProductCategories.mockResolvedValue([
{ name: '艺考形体服', productCount: 120 }, { name: '艺考形体服', productCount: 120 },
{ name: '啦啦队服', productCount: 8 }, { name: '啦啦队服', productCount: 8 },
]) ])
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 }) const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
expect(jdApi.fetchJdProductCategories).toHaveBeenCalledWith(1) expect(jdApi.fetchJdProductCategories).toHaveBeenCalledWith()
const trigger = wrapper.find('.cat-trigger') const trigger = wrapper.find('.cat-trigger')
expect(trigger.text()).toContain('全部类目', '未选时触发框显示占位「全部类目」') expect(trigger.text()).toContain('全部类目', '未选时触发框显示占位「全部类目」')
@@ -283,58 +283,74 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
await trigger.trigger('click') await trigger.trigger('click')
expect(wrapper.find('.cat-panel').exists()).toBe(true) expect(wrapper.find('.cat-panel').exists()).toBe(true)
// 第一栏=静态一级导航(京麦同款顺序,服饰内衣在首)。 // 第一栏=京麦授权一级真树(2026-11-16 真机取证就 3 个:服饰内衣/母婴/运动户外)。
const firstCol = wrapper.findAll('.cat-col')[0] const firstCol = wrapper.findAll('.cat-col')[0]
expect(firstCol.text()).toContain('服饰内衣') expect(firstCol.text()).toContain('服饰内衣')
expect(firstCol.text()).toContain('母婴') expect(firstCol.text()).toContain('母婴')
expect(firstCol.text()).toContain('运动户外') expect(firstCol.text()).toContain('运动户外')
// hover 一级展开第二栏(服饰内衣的静态二级=京麦面板样本同款)。 // 点一级展开第二栏(非末级行点击=下钻)。
await firstCol.findAll('.cat-row')[0].trigger('mouseenter') await firstCol.findAll('.cat-row').find((row) => row.text().includes('服饰内衣'))!.trigger('click')
const cols = wrapper.findAll('.cat-col') let cols = wrapper.findAll('.cat-col')
expect(cols).toHaveLength(3, '点亮有静态子级的一级后第二栏出现(第三栏常驻)') expect(cols).toHaveLength(2, '点亮一级后第二栏出现(树内逐级下钻)')
expect(cols[1].text()).toContain('服饰配件') expect(cols[1].text()).toContain('服饰配件')
expect(cols[1].text()).toContain('女装') expect(cols[1].text()).toContain('女装')
// 第三栏=已落库末级全集+行数(与二级不联动——采集链无层级归属,组件头注释如实声明)。 // 点二级展开第三栏(京麦同款三级末级,取证快照:服饰配件 13 个)。
expect(cols[2].text()).toContain('艺考形体服') await cols[1].findAll('.cat-row').find((row) => row.text().includes('服饰配件'))!.trigger('click')
expect(cols[2].text()).toContain('120') cols = wrapper.findAll('.cat-col')
expect(cols[2].text()).toContain('啦啦队服') expect(cols).toHaveLength(3, '三级栏出现(末级行不再下钻)')
expect(cols[2].text()).toContain('腰带/腰链')
// 点末级=选中即查(等值过滤口径不变)、面板收起、触发框显示已选名。 // 点末级=选中即查(按 category_path 等值过滤口径不变)、面板收起、触发框显示已选名。
const leafRows = cols[2].findAll('.cat-row') await cols[2].findAll('.cat-row').find((row) => row.text().includes('腰带/腰链'))!.trigger('click')
await leafRows.find((row) => row.text().includes('啦啦队服'))!.trigger('click')
await flushPromises() await flushPromises()
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ category: '啦啦队服', page: 1 }) expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ category: '腰带/腰链', page: 1 })
expect(wrapper.find('.cat-panel').exists()).toBe(false, '选中后面板收起') expect(wrapper.find('.cat-panel').exists()).toBe(false, '选中后面板收起')
expect(wrapper.find('.cat-trigger').text()).toContain('啦啦队服') expect(wrapper.find('.cat-trigger').text()).toContain('腰带/腰链')
}) })
it('类目级联搜索与清选:搜索词过滤第三栏;「全部类目」行/触发框 × 都能清选重查', async () => { it('类目级联搜索与清选(2026-11-16 真树重做):树内末级命中+树外兜底段;「全部类目」行/触发框 × 都能清选重查', async () => {
jdApi.fetchJdProductCategories.mockResolvedValue([ jdApi.fetchJdProductCategories.mockResolvedValue([
{ name: '艺考形体服', productCount: 120 }, { name: '艺考形体服', productCount: 120 },
{ name: '啦啦队服', productCount: 8 }, { name: '已下架历史类目', productCount: 3 },
]) ])
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 }) const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
await wrapper.find('.cat-trigger').trigger('click') await wrapper.find('.cat-trigger').trigger('click')
const leafCol = wrapper.findAll('.cat-col').at(-1)! // 搜索态:树内末级按名称/路径命中(艺考形体服在树内=女装支末级)。
await leafCol.find('.cat-search').setValue('艺考') await wrapper.findAll('.cat-col')[0].find('.cat-search').setValue('艺考')
const visibleRows = leafCol.findAll('.cat-row').filter((row) => row.text().includes('艺考')) const searchCol = wrapper.find('.cat-col-search')
expect(visibleRows).toHaveLength(1, '搜索词过滤后只剩匹配项') const visibleRows = searchCol.findAll('.cat-row')
expect(leafCol.text()).not.toContain('啦啦队服', '不匹配的末级被搜索词滤掉') expect(visibleRows).toHaveLength(1, '搜索「艺考」只命中树内末级「艺考形体服」')
expect(searchCol.text()).toContain('艺考形体服')
expect(searchCol.text()).not.toContain('已下架历史类目', '不匹配项不出现')
await visibleRows[0].trigger('click')
await flushPromises()
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ category: '艺考形体服', page: 1 })
// 清空搜索后点「全部类目」= 清选重查(category 入参回空串、query 层不下发,回第一页)。 // 树外兜底:已落库但京麦树里已没有的名字(历史行)从兜底段搜出可选。
await leafCol.find('.cat-search').setValue('') await wrapper.find('.cat-trigger').trigger('click')
await wrapper.findAll('.cat-col')[0].find('.cat-search').setValue('已下架历史')
const fallbackCol = wrapper.find('.cat-col-search')
expect(fallbackCol.text()).toContain('已落库类目(树外历史)')
expect(fallbackCol.text()).toContain('已下架历史类目')
await fallbackCol.findAll('.cat-row').find((row) => row.text().includes('已下架历史类目'))!.trigger('click')
await flushPromises()
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ category: '已下架历史类目' })
// 点「全部类目」行=清选重查(category 入参回空串、query 层不下发,回第一页)。
await wrapper.find('.cat-trigger').trigger('click')
const callsBefore = jdApi.fetchJdProductList.mock.calls.length const callsBefore = jdApi.fetchJdProductList.mock.calls.length
await leafCol.find('.cat-row-all').trigger('click') await wrapper.find('.cat-row-all').trigger('click')
await flushPromises() await flushPromises()
expect(jdApi.fetchJdProductList.mock.calls.length).toBe(callsBefore + 1, '清选也要重查') expect(jdApi.fetchJdProductList.mock.calls.length).toBe(callsBefore + 1, '清选也要重查')
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0].category).toBe('') expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0].category).toBe('')
// 触发框已选时出 × 清除按钮:点了同样清选。 // 触发框已选时出 × 清除按钮:点了同样清选。
await wrapper.find('.cat-trigger').trigger('click') await wrapper.find('.cat-trigger').trigger('click')
await wrapper.findAll('.cat-col').at(-1)!.findAll('.cat-row').find((row) => row.text().includes('啦啦队服'))!.trigger('click') await wrapper.findAll('.cat-col')[0].find('.cat-search').setValue('艺考')
await wrapper.find('.cat-col-search').findAll('.cat-row')[0].trigger('click')
await flushPromises() await flushPromises()
expect(wrapper.find('.cat-trigger').text()).toContain('啦啦队服') expect(wrapper.find('.cat-trigger').text()).toContain('艺考形体服')
const callsBeforeClear = jdApi.fetchJdProductList.mock.calls.length const callsBeforeClear = jdApi.fetchJdProductList.mock.calls.length
await wrapper.find('.cat-clear').trigger('click') await wrapper.find('.cat-clear').trigger('click')
await flushPromises() await flushPromises()
@@ -627,7 +643,7 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith() expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith()
// 右栏取数复用 fetchJdProductList:不带公司维度(公共库),默认「全部」范围不带 ungrouped=true。 // 右栏取数复用 fetchJdProductList:不带公司维度(公共库),默认「全部」范围不带 ungrouped=true。
const dialogCall = jdApi.fetchJdProductList.mock.calls.at(-1)![0] const dialogCall = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
expect(dialogCall.companyId).toBeNull() expect(dialogCall).not.toHaveProperty('companyId')
expect(dialogCall.ungrouped).toBe(false) expect(dialogCall.ungrouped).toBe(false)
// 模拟分类管理里删了一个分类:emit changed → 页面刷新分类下拉与列表(回第一页) // 模拟分类管理里删了一个分类:emit changed → 页面刷新分类下拉与列表(回第一页)
@@ -635,7 +651,7 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
await flushPromises() await flushPromises()
await flushPromises() await flushPromises()
expect(jdApi.fetchJdProductList.mock.calls.length).toBeGreaterThan(callsBefore) expect(jdApi.fetchJdProductList.mock.calls.length).toBeGreaterThan(callsBefore)
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ page: 1, companyId: 1 }) expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ page: 1 })
}) })
it('店铺分类弹窗:左侧点亮分类→勾选商品→「归入所选分类」按(ids, 目标分类 id)调批量归类', async () => { it('店铺分类弹窗:左侧点亮分类→勾选商品→「归入所选分类」按(ids, 目标分类 id)调批量归类', async () => {
@@ -688,7 +704,7 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
await wrapper.findAll('.scope-tabs button').find((b) => b.text() === '未分类')!.trigger('click') await wrapper.findAll('.scope-tabs button').find((b) => b.text() === '未分类')!.trigger('click')
await flushPromises() await flushPromises()
expect(jdApi.fetchJdProductList.mock.calls.length).toBe(listCallsBefore + 1, '切「未分类」必须立刻重取') expect(jdApi.fetchJdProductList.mock.calls.length).toBe(listCallsBefore + 1, '切「未分类」必须立刻重取')
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ ungrouped: true, companyId: null }) expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ ungrouped: true })
await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true) await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true)
jdApi.batchAssignJdProductGroup.mockResolvedValue(1) jdApi.batchAssignJdProductGroup.mockResolvedValue(1)
@@ -698,34 +714,6 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledWith([1], null) expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledWith([1], null)
}) })
it('切公司 Tab 重取并清掉上一家的筛选(company-tab-wiring 同口径;分组公共不清)', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 3 }])
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
const textInputs = wrapper.findAll('.form-group input[type="text"]')
await textInputs[0].setValue('JD-1001')
await textInputs[1].setValue('保温杯')
await wrapper.find('select').setValue('7')
const callsBefore = jdApi.fetchJdProductList.mock.calls.length
useCompanyTabStore().setActiveId(2)
await flushPromises()
await flushPromises()
expect(jdApi.fetchJdProductList.mock.calls.length).toBeGreaterThan(callsBefore)
const last = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
expect(last.companyId).toBe(2)
expect(last.productCode).toBe('', '切公司必须清掉上一家的商品编码')
expect(last.titleKeyword).toBe('', '切公司必须清掉上一家的标题关键字')
expect(last.groupId).toBe('7', '分组全平台一份(公共),groupId 与公司维度正交——切 tab 不清')
expect(last.category).toBe('', '切公司必须清掉上一家选的类目(入参回空串、query 层不下发)')
expect(last).not.toHaveProperty('shopName', '店铺筛选已下线:页面入参层不再传该键')
expect(last.page).toBe(1)
// 分组选项是全局的:切 tab 不重取(首屏那一次之后就不再增长),且任何一次拉取都不带公司维度。
for (const call of jdApi.fetchJdProductGroups.mock.calls) {
expect(call).toEqual([], '分组选项是全局的,任何一次拉取都不带公司维度')
}
})
it('空态与加载失败条(失败给重试,不把整页打死)', async () => { it('空态与加载失败条(失败给重试,不把整页打死)', async () => {
const empty = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 }) const empty = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
const tip = empty.find('.empty-tip') const tip = empty.find('.empty-tip')
@@ -24,19 +24,13 @@ import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** /**
* /api/admin/**、/debug/** 兜底鉴权过滤器。 * /api/admin/** 兜底鉴权过滤器。
* *
* <p>SecurityConfig 全局 permitAll 且无路径级拦截,历史上有多个 /api/admin 控制器遗漏方法级 * <p>SecurityConfig 全局 permitAll 且无路径级拦截,历史上有多个 /api/admin 控制器遗漏方法级
* require*(公网 18080 直连可达即匿名裸奔)。本过滤器作为第二道网:凡进入受保护前缀的请求 * require*(公网 18080 直连可达即匿名裸奔)。本过滤器作为第二道网:凡进入受保护前缀的请求
* 必须具备"有效身份"(Java JWT,或可信内部令牌 X-Internal-Token + operatorId,复用 * 必须具备"有效身份"(Java JWT,或可信内部令牌 X-Internal-Token + operatorId,复用
* AdminAuthSupport),否则直接返回与全局异常一致的 401 响应体(HTTP 200 + {success:false,code})。 * AdminAuthSupport),否则直接返回与全局异常一致的 401 响应体(HTTP 200 + {success:false,code})。
* *
* <p>/debug/** 于 2026-09-11 一并纳入:两个 debug 控制器都没有方法级鉴权,而主机A 18080 公网
* 直连、主机B nginx 的 location / 全量反代 Java,实测三处均可匿名调通——
* GET /debug/request-info(泄漏实例与转发头)与
* POST /debug/task-recovery/run-stale-finalize(**写操作**,强制收尾指定 task)。
* 应急调用方改用 X-Internal-Token 或管理员 JWT 即可通过,不再裸奔。
*
* <p>只保证"已认证",管理员/菜单级校验仍由各控制器 require* 负责,避免拦截普通登录用户本可 * <p>只保证"已认证",管理员/菜单级校验仍由各控制器 require* 负责,避免拦截普通登录用户本可
* 访问的 /api/admin 接口(如权限菜单列表仅 requireUser)。 * 访问的 /api/admin 接口(如权限菜单列表仅 requireUser)。
* *
@@ -70,9 +64,6 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
private static final String ADMIN_API_PREFIX = "/api/admin"; private static final String ADMIN_API_PREFIX = "/api/admin";
/** 调试端点前缀:无方法级鉴权的诊断/运维入口,同样纳入兜底(2026-09-11)。 */
private static final String DEBUG_PREFIX = "/debug";
/** /**
* 用户态工具接口前缀:controller 无方法级鉴权(归属由请求参数 user_id 判定), * 用户态工具接口前缀:controller 无方法级鉴权(归属由请求参数 user_id 判定),
* 匿名可达即越权读写他人数据。**默认不纳入兜底**,由 * 匿名可达即越权读写他人数据。**默认不纳入兜底**,由
@@ -290,11 +281,6 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
return; return;
} }
} }
// /debug/** 是应急/诊断入口,调用频次极低但敏感,单独留一条审计日志便于事后追溯
if (matchesPrefix(uri, DEBUG_PREFIX)) {
log.warn("[debug-guard] {} {} 通过鉴权放行,remoteAddr={}",
request.getMethod(), uri, request.getRemoteAddr());
}
chain.doFilter(request, response); chain.doFilter(request, response);
} }
@@ -332,9 +318,9 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
|| Integer.valueOf(DeviceSessionPolicy.CODE_KICKED).equals(code); || Integer.valueOf(DeviceSessionPolicy.CODE_KICKED).equals(code);
} }
/** 必须解析出身份才放行的前缀:/api/admin、/debug、自助接口,以及已纳入收紧清单的用户态前缀。 */ /** 必须解析出身份才放行的前缀:/api/admin、自助接口,以及已纳入收紧清单的用户态前缀。 */
private boolean requiresCredential(String uri) { private boolean requiresCredential(String uri) {
if (matchesPrefix(uri, ADMIN_API_PREFIX) || matchesPrefix(uri, DEBUG_PREFIX)) { if (matchesPrefix(uri, ADMIN_API_PREFIX)) {
return true; return true;
} }
if (isCredentialRequiredWriteEndpoint(uri)) { if (isCredentialRequiredWriteEndpoint(uri)) {
@@ -448,7 +434,6 @@ public class AdminApiGuardFilter extends OncePerRequestFilter {
public static java.util.List<String> guardedPrefixes() { public static java.util.List<String> guardedPrefixes() {
java.util.List<String> all = new java.util.ArrayList<>(); java.util.List<String> all = new java.util.ArrayList<>();
all.add(ADMIN_API_PREFIX); all.add(ADMIN_API_PREFIX);
all.add(DEBUG_PREFIX);
all.addAll(java.util.List.of(USER_TOOL_PREFIXES)); all.addAll(java.util.List.of(USER_TOOL_PREFIXES));
all.addAll(java.util.List.of(SELF_SERVICE_PREFIXES)); all.addAll(java.util.List.of(SELF_SERVICE_PREFIXES));
return all; return all;
@@ -77,7 +77,6 @@ public class ApiGuardCoverageAuditor implements SmartInitializingSingleton {
"/logout", "/logout",
"/api/version", // 客户端启动时拉最新版本号,必须先于登录 "/api/version", // 客户端启动时拉最新版本号,必须先于登录
"/api/tutorial", // 后台可维护的使用教程,公开内容 "/api/tutorial", // 后台可维护的使用教程,公开内容
"/api/workbench-client", // 数富AI工作台客户端更新检查:必须先于登录,公开只读版本元数据
"/api/kd-flow/verify", // 开店流程访问密码校验:它自己就是那道门 "/api/kd-flow/verify", // 开店流程访问密码校验:它自己就是那道门
// 下面四条都是 AdminConsoleController 的 302 兜底(response.sendRedirect 完事, // 下面四条都是 AdminConsoleController 的 302 兜底(response.sendRedirect 完事,
// 不读库、不回数据),旧书签打进这些地址只会被送到 /admin-vue/。 // 不读库、不回数据),旧书签打进这些地址只会被送到 /admin-vue/。
@@ -102,12 +101,7 @@ public class ApiGuardCoverageAuditor implements SmartInitializingSingleton {
* 往里塞一条没设防的路径会红。 * 往里塞一条没设防的路径会红。
*/ */
static final Set<String> METHOD_GUARDED_PATHS = Set.of( static final Set<String> METHOD_GUARDED_PATHS = Set.of(
"/api/client/credentials", "/api/client/credentials");
// 五国关键词共享(2026-10-23 keywordshare 模块):9 个端点全部在 handler 体内经
// requireKeywordShareAccess → adminAuthSupport.requireUser + PermissionMenuService
// .requireConsolePageAccess(operator, …, "keyword-share") 逐请求把门,且 company_id
// 一律服务端取、不收请求参数——第二道门已到位,只欠进 USER_TOOL_PREFIXES 第一道门。
"/api/keyword-share");
/** /**
* 待收欠账:数据按 user_id 归属、却既不进守卫名单也没有 require* 的前缀。 * 待收欠账:数据按 user_id 归属、却既不进守卫名单也没有 require* 的前缀。
@@ -1,36 +0,0 @@
package com.nanri.aiimage.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList;
import java.util.List;
/**
* 五国关键词客户端同步({@code /api/keyword-share/sync/import})的服务端参数。
*
* <p>存在的主要理由:工作台按对接文档口径使用**共享专用 API 账号**,而 {@code keyword_usage.user_name}
* 是「谁用了哪个词」的唯一出处。若一律取 token 账号名,多人使用会被记成同一个人,后台按使用者筛选
* 就失去意义;若无条件信任客户端自报姓名,又会把「阿武(扶金凡)/阿武(吴棋龙)」这类同音异写
* 直接灌进留痕表。名单校验是这两者之间的收口:命中名单才按自报姓名落库。</p>
*/
@Data
@ConfigurationProperties(prefix = "aiimage.keyword-share-sync")
public class KeywordShareSyncProperties {
/**
* 可信操作人姓名名单(真人显示名,与 {@code keyword_usage.user_name} 同形)。
* 比对时两侧都做 trim + 全角括号归一,所以名单里写「阿武(吴棋龙)」也能匹配半角写法。
*/
private List<String> usedUsers = new ArrayList<>();
/**
* 名单外姓名的处置。
* <ul>
* <li>{@code false}(默认):放行自报姓名,只在响应里计数回报——首次上线时名单还没填,
* 直接回退会把全部记录静默改写成账号名,比现状更糟;</li>
* <li>{@code true}:名单外一律回退为本次调用的账号名,并计入 {@code usedUserFallback}。</li>
* </ul>
*/
private boolean strict = false;
}
@@ -4,6 +4,6 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@Configuration @Configuration
@EnableConfigurationProperties({OssProperties.class, TransientStorageProperties.class, StorageProperties.class, BrandProgressProperties.class, DeleteBrandProgressProperties.class, BrandCheckProperties.class, ZiniaoProperties.class, ModuleCleanupProperties.class, TaskPressureProperties.class, TaskImageCacheCleanupProperties.class, AppearancePatentProperties.class, SimilarAsinProperties.class, ImageVideoProperties.class, InstanceRoutingProperties.class, CapacityPlanProperties.class, UserSecretProperties.class, NotificationProperties.class, DeviceLogOssProperties.class, CollectDataBrandRecheckProperties.class, ClientCredentialProperties.class, CostGuardProperties.class, KeywordShareSyncProperties.class, CollectRoutingProperties.class, EvidenceProperties.class}) @EnableConfigurationProperties({OssProperties.class, TransientStorageProperties.class, StorageProperties.class, BrandProgressProperties.class, DeleteBrandProgressProperties.class, BrandCheckProperties.class, ZiniaoProperties.class, ModuleCleanupProperties.class, TaskPressureProperties.class, TaskImageCacheCleanupProperties.class, AppearancePatentProperties.class, SimilarAsinProperties.class, ImageVideoProperties.class, InstanceRoutingProperties.class, CapacityPlanProperties.class, UserSecretProperties.class, NotificationProperties.class, DeviceLogOssProperties.class, CollectDataBrandRecheckProperties.class, ClientCredentialProperties.class, CostGuardProperties.class, CollectRoutingProperties.class, EvidenceProperties.class})
public class PropertiesConfig { public class PropertiesConfig {
} }
@@ -1,55 +0,0 @@
package com.nanri.aiimage.modules.debug.controller;
import com.nanri.aiimage.config.InstanceMetadata;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.LinkedHashMap;
import java.util.Map;
@RestController
@RequestMapping("/debug")
public class DebugRequestInfoController {
private final InstanceMetadata instanceMetadata;
public DebugRequestInfoController(InstanceMetadata instanceMetadata) {
this.instanceMetadata = instanceMetadata;
}
@GetMapping("/request-info")
public Map<String, Object> requestInfo(
HttpServletRequest request,
@RequestHeader(value = "X-Forwarded-For", required = false) String forwardedFor,
@RequestHeader(value = "X-Real-IP", required = false) String realIp,
@RequestHeader(value = "X-Forwarded-Proto", required = false) String forwardedProto,
@RequestHeader(value = "X-Forwarded-Host", required = false) String forwardedHost,
@RequestHeader(value = "X-Forwarded-Port", required = false) String forwardedPort,
@RequestHeader(value = "X-Request-Id", required = false) String requestId,
@RequestHeader(value = "X-Amzn-Trace-Id", required = false) String amazonTraceId,
@RequestHeader(value = "Traceparent", required = false) String traceparent
) {
Map<String, Object> result = new LinkedHashMap<>();
result.put("instanceId", instanceMetadata.getInstanceId());
result.put("instanceSource", instanceMetadata.getSource());
result.put("instanceStable", instanceMetadata.isStable());
result.put("hostname", instanceMetadata.getHostname());
result.put("serverName", request.getServerName());
result.put("serverPort", request.getServerPort());
result.put("method", request.getMethod());
result.put("uri", request.getRequestURI());
result.put("remoteAddr", request.getRemoteAddr());
result.put("xForwardedFor", forwardedFor);
result.put("xRealIp", realIp);
result.put("xForwardedProto", forwardedProto);
result.put("xForwardedHost", forwardedHost);
result.put("xForwardedPort", forwardedPort);
result.put("xRequestId", requestId);
result.put("xAmznTraceId", amazonTraceId);
result.put("traceparent", traceparent);
return result;
}
}
@@ -1,44 +0,0 @@
package com.nanri.aiimage.modules.debug.controller;
import com.nanri.aiimage.modules.appearancepatent.service.AppearancePatentTaskService;
import com.nanri.aiimage.modules.similarasin.service.SimilarAsinTaskService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
@RestController
@RequestMapping("/debug/task-recovery")
public class DebugTaskRecoveryController {
private final AppearancePatentTaskService appearancePatentTaskService;
private final SimilarAsinTaskService similarAsinTaskService;
public DebugTaskRecoveryController(AppearancePatentTaskService appearancePatentTaskService,
SimilarAsinTaskService similarAsinTaskService) {
this.appearancePatentTaskService = appearancePatentTaskService;
this.similarAsinTaskService = similarAsinTaskService;
}
@PostMapping("/run-stale-finalize")
public Map<String, Object> runStaleFinalize(@RequestParam("module") String module,
@RequestParam("taskId") Long taskId) {
String normalizedModule = module == null ? "" : module.trim().toUpperCase(Locale.ROOT);
if ("APPEARANCE_PATENT".equals(normalizedModule)) {
appearancePatentTaskService.debugFinalizeStaleTask(taskId);
} else if ("SIMILAR_ASIN".equals(normalizedModule)) {
similarAsinTaskService.debugFinalizeStaleTask(taskId);
} else {
throw new IllegalArgumentException("Unsupported module: " + module);
}
Map<String, Object> result = new LinkedHashMap<>();
result.put("module", normalizedModule);
result.put("taskId", taskId);
result.put("accepted", true);
return result;
}
}
@@ -6,7 +6,6 @@ import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.model.entity.AdminUserEntity; import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.security.DeviceSessionPolicy; import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest; import com.nanri.aiimage.modules.jd.model.dto.JdProductBatchAssignGroupRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdProductBatchDeleteRequest; import com.nanri.aiimage.modules.jd.model.dto.JdProductBatchDeleteRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdProductUpdateRequest; import com.nanri.aiimage.modules.jd.model.dto.JdProductUpdateRequest;
@@ -60,13 +59,13 @@ import java.util.List;
* 非超管菜单权限(column_key/route_path 双匹配)。菜单行由 V196 只插 columns 不预授权 * 非超管菜单权限(column_key/route_path 双匹配)。菜单行由 V196 只插 columns 不预授权
* ⇒ 默认仅 super_admin 可见可访问,其余角色由超管在权限页手工勾授后才放行。</p> * ⇒ 默认仅 super_admin 可见可访问,其余角色由超管在权限页手工勾授后才放行。</p>
* *
* <p><b>公司口径(2026-11-15 用户定案「京东数据库不区分公司、属于公共的」)</b>:行上的 * <p><b>公司口径(2026-11-16 用户定案「删除掉公司 tab,参考品牌数据库」)</b>:读侧零公司
* company_id 只剩「哪家公司客户端同步的」来源标记,不再构成可见性边界——读侧全公共; * 维度——company_id 请求参数与 {@code superAdminScopedCompanyId} 谓词已随公共化收尾整批
* 唯一保留的公司维度是<b>站点超管</b>的公司 tab 筛选({@code superAdminScopedCompanyId}: * 摘除(2026-11-15 定案「京东数据库不区分公司、属于公共的」的最后一截),行上的 company_id
* 超管显式传 company_id 才收窄,非超管传什么都不收),也就是「管理员没有这个筛选、 * 只剩「哪家公司客户端同步的」来源标记,不构成可见性边界;每个拿到本页菜单权限的管理员
* 超管可以筛选管理员」。详情与写侧(编辑/删除)没有公司维度:任何拿到本页菜单权限的 * (含站点超管)看到同一份全量公共库。详情与写侧(编辑/删除)同样没有公司维度:
* 管理员对全部公共行可编辑可删除(同商品类目「谁都能改」的 2026-10-06 定案形状), * 对全部公共行可编辑可删除(同商品类目「谁都能改」的 2026-10-06 定案形状),写侧端点的
* 请求里的 company_id 传参已随公共化从写侧端点摘除。</p> * company_id 传参已随 2026-11-15 公共化摘除。</p>
* *
* <p>导出端点已随 2026-11-15 客户口径「导出也不用」整段下线(控制器/服务/mapper 参数一起删); * <p>导出端点已随 2026-11-15 客户口径「导出也不用」整段下线(控制器/服务/mapper 参数一起删);
* {@code sale_status} 查询参数同窗撤掉(商品状态筛选框已从前端下线)。店铺筛选参数 * {@code sale_status} 查询参数同窗撤掉(商品状态筛选框已从前端下线)。店铺筛选参数
@@ -77,7 +76,7 @@ import java.util.List;
@RequiredArgsConstructor @RequiredArgsConstructor
@Slf4j @Slf4j
@RequestMapping("/api/admin/jd-products") @RequestMapping("/api/admin/jd-products")
@Tag(name = "京东数据库", description = "后管京东店铺商品库:分页查询、详情、编辑与删除。数据全平台公共,仅超管可按公司(同步来源)筛选。") @Tag(name = "京东数据库", description = "后管京东店铺商品库:分页查询、详情、编辑与删除。数据全平台公共,无公司维度。")
public class AdminJdProductController { public class AdminJdProductController {
private static final String COLUMN_KEY = "admin_jd_database"; private static final String COLUMN_KEY = "admin_jd_database";
@@ -88,11 +87,10 @@ public class AdminJdProductController {
private final JdProductUpdateService jdProductUpdateService; private final JdProductUpdateService jdProductUpdateService;
private final AdminAuthSupport adminAuthSupport; private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService; private final PermissionMenuService permissionMenuService;
private final DataReadScope dataReadScope;
@GetMapping @GetMapping
@Operation(summary = "分页查询京东数据库商品", description = "公共库分页查询同步落表的京东商品;" @Operation(summary = "分页查询京东数据库商品", description = "公共库分页查询同步落表的京东商品;"
+ "company_id 只对站点超管生效(显式传才收窄=按同步来源公司筛),非超管传什么都不收(全量)。") + "全平台公共、无公司维度(2026-11-16 摘公司 tab:公司维参数与超管筛选谓词已整批摘除)。")
@ApiResponses({ @ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = JdProductPageVo.class))) @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = JdProductPageVo.class)))
}) })
@@ -111,29 +109,19 @@ public class AdminJdProductController {
@RequestParam(name = "synced_from", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedFrom, @RequestParam(name = "synced_from", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedFrom,
@Parameter(description = "同步结束时间(包含,ISO datetime)") @Parameter(description = "同步结束时间(包含,ISO datetime)")
@RequestParam(name = "synced_to", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedTo, @RequestParam(name = "synced_to", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
HttpServletRequest request) { HttpServletRequest request) {
RequestOperator operator = requireJdAccess(request); requireJdAccess(request);
AdminUserEntity user = operator.user(); return ApiResponse.success(jdProductQueryService.page(page, pageSize,
// 公司维度只剩超管的公司 tab 筛选(superAdminScopedCompanyId):超管显式传才收窄,
// 非超管传什么都不收——公共库对每一家管理员都是同一份全量。
Long scopedCompanyId = dataReadScope.superAdminScopedCompanyId(user, companyId);
return ApiResponse.success(jdProductQueryService.page(page, pageSize, scopedCompanyId,
productCode, titleKeyword, category, groupId, ungrouped, grouped, syncedFrom, syncedTo)); productCode, titleKeyword, category, groupId, ungrouped, grouped, syncedFrom, syncedTo));
} }
@GetMapping("/categories") @GetMapping("/categories")
@Operation(summary = "类目筛选下拉数据源", description = "已落库行 DISTINCT 的 category_path" @Operation(summary = "类目筛选下拉数据源", description = "已落库行 DISTINCT 的 category_path"
+ "(京麦末级类目名)+ 行数,按类目名排序;company_id 只对站点超管生效(显式传才收窄=" + "(京麦末级类目名)+ 行数,按类目名排序;全平台公共去重、无公司维度"
+ "选项集与超管当前公司 tab 的行集同源),非超管传什么都不收(全量)。") + "(与用户端采集建单侧同一出口同一口径)。")
public ApiResponse<List<JdProductCategoryVo>> categories( public ApiResponse<List<JdProductCategoryVo>> categories(HttpServletRequest request) {
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId, requireJdAccess(request);
HttpServletRequest request) { return ApiResponse.success(jdProductQueryService.categories());
RequestOperator operator = requireJdAccess(request);
AdminUserEntity user = operator.user();
// 类目下拉与列表同走超管筛选口径:选项集永远和当前请求能看到的行集同源。
Long scopedCompanyId = dataReadScope.superAdminScopedCompanyId(user, companyId);
return ApiResponse.success(jdProductQueryService.categories(scopedCompanyId));
} }
@GetMapping("/{id}") @GetMapping("/{id}")
@@ -71,12 +71,12 @@ public class JdCollectController {
@GetMapping("/categories") @GetMapping("/categories")
@Operation(summary = "采集类目下拉数据源", description = "建单页类目多选面板的选项集:公共库已落库行" @Operation(summary = "采集类目下拉数据源", description = "建单页类目多选面板的选项集:公共库已落库行"
+ " DISTINCT 的 category_path(京麦末级类目名)+ 行数,按类目名排序。与后管京东数据库" + " DISTINCT 的 category_path(京麦末级类目名)+ 行数,按类目名排序。与后管京东数据库"
+ "同一条 SQL(JdProductQueryService.categories),公共库无公司维度——传 null 全量口径。" + "同一条 SQL(JdProductQueryService.categories),公共库无公司维度、全平台去重。"
+ "边界:从未采集过的店铺/新类目不在集内(先全店采一次即有),页面选项空态不阻塞建单。") + "边界:从未采集过的店铺/新类目不在集内(先全店采一次即有),页面选项空态不阻塞建单。")
public ApiResponse<List<JdProductCategoryVo>> categories(HttpServletRequest httpRequest) { public ApiResponse<List<JdProductCategoryVo>> categories(HttpServletRequest httpRequest) {
// 登录用户即可读(公共库口径):解析不出会话身份就 401(fail-closed,与建单同口径)。 // 登录用户即可读(公共库口径):解析不出会话身份就 401(fail-closed,与建单同口径)。
adminAuthSupport.requireOwnershipUserId(httpRequest, null); adminAuthSupport.requireOwnershipUserId(httpRequest, null);
return ApiResponse.success(jdProductQueryService.categories(null)); return ApiResponse.success(jdProductQueryService.categories());
} }
@GetMapping("/groups") @GetMapping("/groups")
@@ -42,14 +42,14 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
/** /**
* 后管只读页总数(Phase 5,v1.4):与 {@link #selectProductPage} 同一过滤面 * 后管只读页总数(Phase 5,v1.4):与 {@link #selectProductPage} 同一过滤面
* (公司/商品编码/标题关键词/类目/分组/未分类/已分类/同步起止,全部 SQL 侧下推, * (商品编码/标题关键词/类目/分组/未分类/已分类/同步起止,全部 SQL 侧下推,
* 铁律 20)。{@code companyId}/{@code groupId} 为空或 ≤0=不过滤该面; * 铁律 20)。公司维过滤已随 2026-11-16「删除掉公司 tab,参考品牌数据库」撤掉
* (数据全平台公共);{@code groupId} 为空或 ≤0=不过滤该面;
* {@code ungrouped=true}=只看未分类行(group_id IS NULL,店铺分类弹窗「未分类」范围); * {@code ungrouped=true}=只看未分类行(group_id IS NULL,店铺分类弹窗「未分类」范围);
* {@code grouped=true}=只看已分类行(group_id IS NOT NULL,页面筛选行「分类状态」档)。 * {@code grouped=true}=只看已分类行(group_id IS NOT NULL,页面筛选行「分类状态」档)。
* 店铺名过滤参数已随 2026-11-15 客户口径「店铺不需要」同窗撤掉(DB 列与详情/回传链不动)。 * 店铺名过滤参数已随 2026-11-15 客户口径「店铺不需要」同窗撤掉(DB 列与详情/回传链不动)。
*/ */
long countProducts(@Param("companyId") Long companyId, long countProducts(@Param("productCode") String productCode,
@Param("productCode") String productCode,
@Param("titleKeyword") String titleKeyword, @Param("titleKeyword") String titleKeyword,
@Param("category") String category, @Param("category") String category,
@Param("groupId") Long groupId, @Param("groupId") Long groupId,
@@ -90,8 +90,7 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
* <p>{@code offset}/{@code limit} 必须是服务侧钳制后的值——page 钳制防 * <p>{@code offset}/{@code limit} 必须是服务侧钳制后的值——page 钳制防
* {@code (page-1)*page_size} 溢出(铁律 15),mapper 不做第二次换算,避免两处各算各的。</p> * {@code (page-1)*page_size} 溢出(铁律 15),mapper 不做第二次换算,避免两处各算各的。</p>
*/ */
List<JdProductEntity> selectProductPage(@Param("companyId") Long companyId, List<JdProductEntity> selectProductPage(@Param("productCode") String productCode,
@Param("productCode") String productCode,
@Param("titleKeyword") String titleKeyword, @Param("titleKeyword") String titleKeyword,
@Param("category") String category, @Param("category") String category,
@Param("groupId") Long groupId, @Param("groupId") Long groupId,
@@ -104,8 +103,8 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
/** /**
* 类目筛选下拉数据源(2026-11-15 用户口径「京麦的类目也要同步过来后台」): * 类目筛选下拉数据源(2026-11-15 用户口径「京麦的类目也要同步过来后台」):
* 本公司已落库行的 DISTINCT {@code category_path}(=京麦末级类目名)+ 行数。 * 已落库行的 DISTINCT {@code category_path}(=京麦末级类目名)+ 行数,全平台公共去重
* {@code companyId} 为空(超管不选公司)=跨公司全量去重。 * (2026-11-16 起与用户端采集建单侧同口径,无公司维过滤)。
*/ */
List<JdProductCategoryVo> selectProductCategories(@Param("companyId") Long companyId); List<JdProductCategoryVo> selectProductCategories();
} }
@@ -35,10 +35,10 @@ import java.util.Map;
* 先例:{@code page} 上限 {@link #MAX_PAGE}、{@code page_size} 上限 {@link #MAX_PAGE_SIZE}, * 先例:{@code page} 上限 {@link #MAX_PAGE}、{@code page_size} 上限 {@link #MAX_PAGE_SIZE},
* {@code page=Long.MAX_VALUE} 不会把乘积顶成负数生成 {@code LIMIT -N} 的 500 错。</p> * {@code page=Long.MAX_VALUE} 不会把乘积顶成负数生成 {@code LIMIT -N} 的 500 错。</p>
* *
* <p><b>公司口径(2026-11-15 公共化)</b>:{@code scopedCompanyId} 由控制器经 * <p><b>公司口径(2026-11-16「删除掉公司 tab,参考品牌数据库」)</b>:读侧零公司维度——
* {@code DataReadScope#superAdminScopedCompanyId} 算好传入——只有站点超管显式传 company_id * 公司 tab 与 {@code superAdminScopedCompanyId} 谓词已随公共化收尾整批摘除,每个管理员
* (公司 tab 筛选)才是正数,其余请求(含全部非超管)恒为 {@code null} = 全量;详情没有 * (含站点超管)看到同一份全量公共库;行上的 {@code company_id} 列仍是"哪家公司客户端
* 公司维度,按 id 直取。</p> * 同步的"来源标记,随详情下发但不构成可见性边界。详情本就按 id 直取。</p>
* *
* <p><b>详情 attr_json 解析(AC-7 未识别属性不丢弃)</b>:客户端实拍契约 * <p><b>详情 attr_json 解析(AC-7 未识别属性不丢弃)</b>:客户端实拍契约
* {@code {"tabs":[{"tab":"...","attrs":[{key,label,value}]}],"images":[...],"productCode":"..."}}—— * {@code {"tabs":[{"tab":"...","attrs":[{key,label,value}]}],"images":[...],"productCode":"..."}}——
@@ -75,12 +75,13 @@ public class JdProductQueryService {
/** /**
* 分页查询商品行({@code synced_at} 倒序)。 * 分页查询商品行({@code synced_at} 倒序)。
* *
* <p>过滤面:公司(物化列 eq)、商品编码 contains、标题关键词 contains、 * <p>过滤面:商品编码 contains、标题关键词 contains、类目 eq、分组 eq、
* 类目 eq、分组 eq、未分类(group_id IS NULL,店铺分类弹窗「未分类」范围)、 * 未分类(group_id IS NULL,店铺分类弹窗「未分类」范围)、
* 已分类(group_id IS NOT NULL,页面筛选行「分类状态」档,2026-11-15 客户口径 * 已分类(group_id IS NOT NULL,页面筛选行「分类状态」档,2026-11-15 客户口径
* 「查询已分类的跟未分类,分类好的可以不显示」)、同步起止(datetime 闭区间)。</p> * 「查询已分类的跟未分类,分类好的可以不显示」)、同步起止(datetime 闭区间)。
* 公司维过滤已随 2026-11-16 摘公司 tab 整批撤掉(全平台公共)。</p>
*/ */
public JdProductPageVo page(Long page, Long pageSize, Long scopedCompanyId, public JdProductPageVo page(Long page, Long pageSize,
String productCode, String titleKeyword, String category, Long groupId, Boolean ungrouped, String productCode, String titleKeyword, String category, Long groupId, Boolean ungrouped,
Boolean grouped, LocalDateTime syncedFrom, LocalDateTime syncedTo) { Boolean grouped, LocalDateTime syncedFrom, LocalDateTime syncedTo) {
if (syncedFrom != null && syncedTo != null && syncedFrom.isAfter(syncedTo)) { if (syncedFrom != null && syncedTo != null && syncedFrom.isAfter(syncedTo)) {
@@ -89,13 +90,13 @@ public class JdProductQueryService {
long safePage = page == null || page < 1 ? 1 : Math.min(page, MAX_PAGE); long safePage = page == null || page < 1 ? 1 : Math.min(page, MAX_PAGE);
long safeSize = pageSize == null ? PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT long safeSize = pageSize == null ? PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT
: Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE); : Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE);
Filter filter = filter(scopedCompanyId, productCode, titleKeyword, category, Filter filter = filter(productCode, titleKeyword, category,
groupId, ungrouped, grouped, syncedFrom, syncedTo); groupId, ungrouped, grouped, syncedFrom, syncedTo);
long total = jdProductMapper.countProducts(filter.companyId(), filter.productCode(), long total = jdProductMapper.countProducts(filter.productCode(),
filter.titleKeyword(), filter.category(), filter.groupId(), filter.ungrouped(), filter.titleKeyword(), filter.category(), filter.groupId(), filter.ungrouped(),
filter.grouped(), filter.syncedFrom(), filter.syncedTo()); filter.grouped(), filter.syncedFrom(), filter.syncedTo());
List<JdProductEntity> rows = total <= 0 ? List.of() List<JdProductEntity> rows = total <= 0 ? List.of()
: jdProductMapper.selectProductPage(filter.companyId(), filter.productCode(), : jdProductMapper.selectProductPage(filter.productCode(),
filter.titleKeyword(), filter.category(), filter.groupId(), filter.ungrouped(), filter.titleKeyword(), filter.category(), filter.groupId(), filter.ungrouped(),
filter.grouped(), filter.syncedFrom(), filter.syncedTo(), filter.grouped(), filter.syncedFrom(), filter.syncedTo(),
(safePage - 1) * safeSize, (int) safeSize); (safePage - 1) * safeSize, (int) safeSize);
@@ -112,12 +113,11 @@ public class JdProductQueryService {
/** /**
* 类目筛选下拉数据源(2026-11-15 用户口径「京麦的类目也要同步过来后台」): * 类目筛选下拉数据源(2026-11-15 用户口径「京麦的类目也要同步过来后台」):
* 已落库行 distinct 的 {@code category_path}(=京麦末级类目名,契约 §2.3 E3) * 已落库行 distinct 的 {@code category_path}(=京麦末级类目名,契约 §2.3 E3)
* + 各自行数,按类目名排序。公司口径与分页同门(控制器经 {@code superAdminScopedCompanyId} 传入, * + 各自行数,按类目名排序。全平台公共去重(2026-11-16 起与用户端采集建单侧
* {@code null} = 全量公共选项集)。 * 同一出口同一口径,无公司维过滤)。
*/ */
public List<JdProductCategoryVo> categories(Long scopedCompanyId) { public List<JdProductCategoryVo> categories() {
Long companyId = scopedCompanyId != null && scopedCompanyId > 0 ? scopedCompanyId : null; return jdProductMapper.selectProductCategories();
return jdProductMapper.selectProductCategories(companyId);
} }
/** /**
@@ -173,23 +173,22 @@ public class JdProductQueryService {
// ---------------------------------------------------------------- 过滤面 // ---------------------------------------------------------------- 过滤面
/** 服务侧过滤面归一:companyId/groupId ≤0 按没选处理,文本 trim 后空串归 null。 */ /** 服务侧过滤面归一:groupId ≤0 按没选处理,文本 trim 后空串归 null(无公司维,2026-11-16 摘)。 */
private record Filter(Long companyId, String productCode, String titleKeyword, private record Filter(String productCode, String titleKeyword,
String category, Long groupId, Boolean ungrouped, Boolean grouped, String category, Long groupId, Boolean ungrouped, Boolean grouped,
LocalDateTime syncedFrom, LocalDateTime syncedTo) { LocalDateTime syncedFrom, LocalDateTime syncedTo) {
} }
private static Filter filter(Long scopedCompanyId, String productCode, String titleKeyword, private static Filter filter(String productCode, String titleKeyword,
String category, Long groupId, Boolean ungrouped, Boolean grouped, String category, Long groupId, Boolean ungrouped, Boolean grouped,
LocalDateTime syncedFrom, LocalDateTime syncedTo) { LocalDateTime syncedFrom, LocalDateTime syncedTo) {
Long companyId = scopedCompanyId != null && scopedCompanyId > 0 ? scopedCompanyId : null;
Long safeGroupId = groupId != null && groupId > 0 ? groupId : null; Long safeGroupId = groupId != null && groupId > 0 ? groupId : null;
// 未分类与其它过滤面同口径:没显式要(true)=null=不进 IS NULL 分支。 // 未分类与其它过滤面同口径:没显式要(true)=null=不进 IS NULL 分支。
Boolean safeUngrouped = Boolean.TRUE.equals(ungrouped) ? Boolean.TRUE : null; Boolean safeUngrouped = Boolean.TRUE.equals(ungrouped) ? Boolean.TRUE : null;
// 已分类同口径:true=只看 group_id IS NOT NULL 的行;与未分类同选时 SQL 侧两谓词相与=空集 // 已分类同口径:true=只看 group_id IS NOT NULL 的行;与未分类同选时 SQL 侧两谓词相与=空集
// (前端下拉是单选,正常到不了这个组合)。 // (前端下拉是单选,正常到不了这个组合)。
Boolean safeGrouped = Boolean.TRUE.equals(grouped) ? Boolean.TRUE : null; Boolean safeGrouped = Boolean.TRUE.equals(grouped) ? Boolean.TRUE : null;
return new Filter(companyId, trimToNull(productCode), trimToNull(titleKeyword), return new Filter(trimToNull(productCode), trimToNull(titleKeyword),
trimToNull(category), safeGroupId, safeUngrouped, safeGrouped, syncedFrom, syncedTo); trimToNull(category), safeGroupId, safeUngrouped, safeGrouped, syncedFrom, syncedTo);
} }
@@ -1,188 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareAddRequest;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareDeleteRequest;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareSyncImportRequest;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordUsageBatchRequest;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareAddResultVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareDeleteResultVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareFiltersVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareLogPageVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareMarkResultVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordSharePageVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareRowVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareStatsGroupedVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareSyncResultVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareUnmarkResultVo;
import com.nanri.aiimage.modules.keywordshare.service.KeywordShareService;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 五国关键词共享(桌面 Tkinter 工具的 web 化)。
*
* <p>company_id 一律服务端从当前登录人取,前端不传、也不接受传参;
* 页面权限键 {@code keyword-share}(后台菜单 column_key,经 requireConsolePageAccess 把门)。</p>
*/
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/keyword-share")
@Tag(name = "五国关键词共享", description = "五国关键词共享词库的查询、增删、使用标记与团队共享记录。数据按公司隔离。")
public class KeywordShareController {
/** 后台菜单权限键(column_key)。 */
private static final String PERMISSION_KEY = "keyword-share";
private static final String DENIAL_MESSAGE = "无权访问五国关键词共享";
private final KeywordShareService keywordShareService;
private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService;
@GetMapping("/keywords")
@Operation(summary = "分页查询关键词", description = "按国家/类目/搜索/使用状态筛选,未使用在前、已使用按使用时间升序。")
public ApiResponse<KeywordSharePageVo> page(
HttpServletRequest request,
@Parameter(description = "国家") @RequestParam(name = "country", required = false) String country,
@Parameter(description = "一级类目") @RequestParam(name = "category", required = false) String category,
@Parameter(description = "二级类目") @RequestParam(name = "subCategory", required = false) String subCategory,
@Parameter(description = "三级类目") @RequestParam(name = "categoryL3", required = false) String categoryL3,
@Parameter(description = "四级类目") @RequestParam(name = "categoryL4", required = false) String categoryL4,
@Parameter(description = "关键词/中文模糊搜索") @RequestParam(name = "search", required = false) String search,
@Parameter(description = "使用状态:all|used|unused") @RequestParam(name = "status", required = false) String status,
@Parameter(description = "已使用时间范围(天):1=今天,7/30/90/180/360;0或不传=全部")
@RequestParam(name = "usedDays", required = false) Integer usedDays,
@Parameter(description = "仅看我使用") @RequestParam(name = "onlyMine", required = false) Boolean onlyMine,
@Parameter(description = "页码(1 起)") @RequestParam(name = "page", required = false) Long page,
@Parameter(description = "每页数量(默认 200,上限 500)") @RequestParam(name = "size", required = false) Long size) {
Operator operator = requireKeywordShareAccess(request);
return ApiResponse.success(keywordShareService.page(operator.companyId(), operator.userName(),
country, category, subCategory, categoryL3, categoryL4, search,
status, usedDays, Boolean.TRUE.equals(onlyMine), page, size));
}
@GetMapping("/filters")
@Operation(summary = "查询筛选名册", description = "国家列表与一级→二级→三级→四级类目树,按当前公司 DISTINCT。")
public ApiResponse<KeywordShareFiltersVo> filters(HttpServletRequest request) {
Operator operator = requireKeywordShareAccess(request);
return ApiResponse.success(keywordShareService.filters(operator.companyId()));
}
@GetMapping("/stats-grouped")
@Operation(summary = "词库统计", description = "国家与一级/二级/三级类目的分布计数(统计弹窗)。")
public ApiResponse<KeywordShareStatsGroupedVo> statsGrouped(HttpServletRequest request) {
Operator operator = requireKeywordShareAccess(request);
return ApiResponse.success(keywordShareService.statsGrouped(operator.companyId()));
}
@PostMapping("/keywords")
@Operation(summary = "批量添加关键词", description = "trim 规范化;已存在/为空跳过;成功行写词本体、添加留痕并自动标记已使用。")
public ApiResponse<KeywordShareAddResultVo> add(
HttpServletRequest request,
@Valid @RequestBody KeywordShareAddRequest body) {
Operator operator = requireKeywordShareAccess(request);
return ApiResponse.success("添加成功", keywordShareService.add(body, operator.companyId(), operator.userName()));
}
@DeleteMapping("/keywords")
@Operation(summary = "批量删除关键词", description = "删除本公司词行并写删除留痕。")
public ApiResponse<KeywordShareDeleteResultVo> delete(
HttpServletRequest request,
@Valid @RequestBody KeywordShareDeleteRequest body) {
Operator operator = requireKeywordShareAccess(request);
return ApiResponse.success("删除成功", keywordShareService.delete(body, operator.companyId(), operator.userName()));
}
@PostMapping("/usage/mark")
@Operation(summary = "批量标记已使用", description = "写 keyword_usage,唯一键冲突按 UPSERT 刷新,幂等。")
public ApiResponse<KeywordShareMarkResultVo> mark(
HttpServletRequest request,
@Valid @RequestBody KeywordUsageBatchRequest body) {
Operator operator = requireKeywordShareAccess(request);
return ApiResponse.success(keywordShareService.mark(body, operator.companyId(), operator.userName()));
}
@PostMapping("/usage/unmark")
@Operation(summary = "批量取消使用", description = "删除 keyword_usage 行。")
public ApiResponse<KeywordShareUnmarkResultVo> unmark(
HttpServletRequest request,
@Valid @RequestBody KeywordUsageBatchRequest body) {
Operator operator = requireKeywordShareAccess(request);
return ApiResponse.success(keywordShareService.unmark(body, operator.companyId()));
}
@GetMapping("/logs")
@Operation(summary = "团队共享记录", description = "使用/添加/删除三类留痕的分页只读展示。")
public ApiResponse<KeywordShareLogPageVo> logs(
HttpServletRequest request,
@Parameter(description = "记录类型:usage|add|delete", required = true)
@RequestParam(name = "type") String type,
@Parameter(description = "国家") @RequestParam(name = "country", required = false) String country,
@Parameter(description = "页码(1 起)") @RequestParam(name = "page", required = false) Long page,
@Parameter(description = "每页数量") @RequestParam(name = "size", required = false) Long size) {
Operator operator = requireKeywordShareAccess(request);
return ApiResponse.success(keywordShareService.logs(operator.companyId(), type, country, page, size));
}
@GetMapping("/random")
@Operation(summary = "随机抽词", description = "从当前筛选的未使用池随机抽取(默认 10 条)。")
public ApiResponse<List<KeywordShareRowVo>> random(
HttpServletRequest request,
@Parameter(description = "抽取条数(默认 10)") @RequestParam(name = "count", required = false) Long count,
@Parameter(description = "国家") @RequestParam(name = "country", required = false) String country,
@Parameter(description = "一级类目") @RequestParam(name = "category", required = false) String category,
@Parameter(description = "二级类目") @RequestParam(name = "subCategory", required = false) String subCategory,
@Parameter(description = "三级类目") @RequestParam(name = "categoryL3", required = false) String categoryL3,
@Parameter(description = "四级类目") @RequestParam(name = "categoryL4", required = false) String categoryL4,
@Parameter(description = "关键词/中文模糊搜索") @RequestParam(name = "search", required = false) String search) {
Operator operator = requireKeywordShareAccess(request);
return ApiResponse.success(keywordShareService.random(operator.companyId(), operator.userName(),
country, category, subCategory, categoryL3, categoryL4, search, count));
}
/**
* 客户端全量同步导入。与 {@code POST /keywords} + {@code /usage/mark} 的分工:那两条是网页侧
* 交互式单条操作(使用人/时间取服务端此刻),这条专供工作台将本地历史批量搬入,
* 必须保住客户端传来的四级类目与真实使用人/使用时间。
*/
@PostMapping("/sync/import")
@Operation(summary = "客户端批量同步导入",
description = "按 (company_id, country, keyword) UPSERT 词本体并同步使用状态,"
+ "保留客户端传入的 usedTime/usedUser;used=false 删除对应使用记录。"
+ "幂等,单请求不超过 2000 行,失败只需重传该批。")
public ApiResponse<KeywordShareSyncResultVo> syncImport(
HttpServletRequest request,
@Valid @RequestBody KeywordShareSyncImportRequest body) {
Operator operator = requireKeywordShareAccess(request);
return ApiResponse.success("同步完成",
keywordShareService.syncImport(body, operator.companyId(), operator.userName()));
}
/**
* 逐端点把门:登录态 + 后台菜单权限;公司 id 与用户名都从登录人实体取,前端传参不参与归属判定。
*/
private Operator requireKeywordShareAccess(HttpServletRequest request) {
AdminUserEntity operator = adminAuthSupport.requireUser(request);
permissionMenuService.requireConsolePageAccess(operator, DENIAL_MESSAGE, PERMISSION_KEY);
return new Operator(operator.getCompanyId(), operator.getUsername());
}
private record Operator(Long companyId, String userName) {
}
}
@@ -1,18 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordAddLogEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 五国关键词共享——添加留痕(keyword_add_log)数据访问。
*/
@Mapper
public interface KeywordAddLogMapper extends BaseMapper<KeywordAddLogEntity> {
/** 批量写添加留痕(对齐桌面版 ShareSync.log_add_batch 的单次往返)。 */
int insertBatch(@Param("rows") List<KeywordAddLogEntity> rows);
}
@@ -1,18 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordDeleteLogEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 五国关键词共享——删除留痕(keyword_delete_log)数据访问。
*/
@Mapper
public interface KeywordDeleteLogMapper extends BaseMapper<KeywordDeleteLogEntity> {
/** 批量写删除留痕。 */
int insertBatch(@Param("rows") List<KeywordDeleteLogEntity> rows);
}
@@ -1,68 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryCountRow;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryL3CountRow;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryTreeRow;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordNameCountRow;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareFilterQuery;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareKey;
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordShareEntity;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareRowVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 五国关键词共享——词本体(keyword_share)数据访问。
*
* <p>列表/统计/随机这类带 JOIN 与动态筛选的 SQL 全部收口在本 Mapper 的 XML 里
* ({@code mapper/keywordshare/KeywordShareMapper.xml}),筛选值一律 {@code #{}} 占位符。</p>
*/
@Mapper
public interface KeywordShareMapper extends BaseMapper<KeywordShareEntity> {
/** 筛选命中总数(含状态/时间/仅看我条件)。 */
long countHit(@Param("f") KeywordShareFilterQuery filter);
/** 当前页行:未使用在前,已使用按 used_time 升序(对齐桌面版 _filtered_rows_conn 的口径)。 */
List<KeywordShareRowVo> selectRows(@Param("f") KeywordShareFilterQuery filter);
/** 未使用池随机抽词。 */
List<KeywordShareRowVo> selectRandomUnused(@Param("f") KeywordShareFilterQuery filter);
/** 本公司跨国重复词数:同词出现在 2 个及以上国家。 */
long countDupKeywords(@Param("companyId") Long companyId);
/** 类目筛选名册:国家平铺。 */
List<String> selectFilterCountries(@Param("companyId") Long companyId);
/** 类目筛选名册:类目树的去重行(category/sub_category/category_l3/category_l4)。 */
List<KeywordCategoryTreeRow> selectFilterTreeRows(@Param("companyId") Long companyId);
/** 词库统计:按国家分布。 */
List<KeywordNameCountRow> selectCountryCounts(@Param("companyId") Long companyId);
/** 词库统计:按一级类目分布。 */
List<KeywordNameCountRow> selectCategoryCounts(@Param("companyId") Long companyId);
/** 词库统计:按二级类目分布(挂一级类目下)。 */
List<KeywordCategoryCountRow> selectSubCategoryCounts(@Param("companyId") Long companyId);
/** 词库统计:按三级类目分布(挂一级+二级下)。 */
List<KeywordCategoryL3CountRow> selectCategoryL3Counts(@Param("companyId") Long companyId);
/** 批量查 (country, keyword) 已存在的键(添加防重预检)。 */
List<KeywordShareKey> selectExistingKeywords(@Param("companyId") Long companyId,
@Param("keys") List<KeywordShareKey> keys);
/** 批量 INSERT IGNORE:命中唯一键 uk_comp_cw 的重复行静默跳过,兜底与预检双保险。 */
int insertBatchIgnore(@Param("rows") List<KeywordShareEntity> rows);
/**
* 客户端全量同步专用 UPSERT:新词整行插入,已存在的词只把非空的四级类目/chinese/ktype/source
* 覆盖进去,添加人与添加时间不动。与 {@link #insertBatchIgnore} 的区别正是这条会更新已有行。
*/
int upsertBatchFromSync(@Param("rows") List<KeywordShareEntity> rows);
}
@@ -1,24 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareKey;
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordUsageEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 五国关键词共享——使用状态(keyword_usage)数据访问。
* 批量标记走 UPSERT(对齐桌面版 ShareSync.mark 的 ON DUPLICATE KEY UPDATE 语义,天然幂等),
* SQL 收口在 {@code mapper/keywordshare/KeywordUsageMapper.xml}。
*/
@Mapper
public interface KeywordUsageMapper extends BaseMapper<KeywordUsageEntity> {
/** 批量 UPSERT:唯一键冲突时刷新 user_name/used_time,幂等。 */
int upsertBatch(@Param("rows") List<KeywordUsageEntity> rows);
/** 批量取消使用:按 (company_id, country, keyword) 删行,返回实际删除条数。 */
int deleteBatch(@Param("companyId") Long companyId, @Param("keys") List<KeywordShareKey> keys);
}
@@ -1,14 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.dto;
import lombok.Data;
/**
* 词库统计的「一级类目 + 二级类目 + 计数」行。
*/
@Data
public class KeywordCategoryCountRow {
private String category;
private String name;
private Long count;
}
@@ -1,15 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.dto;
import lombok.Data;
/**
* 词库统计的「一级 + 二级 + 三级类目 + 计数」行。
*/
@Data
public class KeywordCategoryL3CountRow {
private String category;
private String subCategory;
private String name;
private Long count;
}
@@ -1,15 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.dto;
import lombok.Data;
/**
* 类目筛选名册的树行(DISTINCT category/sub_category/category_l3/category_l4),Service 内组装成树。
*/
@Data
public class KeywordCategoryTreeRow {
private String category;
private String subCategory;
private String categoryL3;
private String categoryL4;
}
@@ -1,13 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.dto;
import lombok.Data;
/**
* 词库统计的「名称 + 计数」行(按国家 / 按一级类目)。
*/
@Data
public class KeywordNameCountRow {
private String name;
private Long count;
}
@@ -1,36 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.List;
/**
* 批量添加关键词请求。词的一级~四级类目由词库既有口径维护,web 端添加不携带类目字段
* (落库取列默认值 ''),与桌面版从纯文本行解析出 country/keyword/chinese 的输入面一致。
*/
@Data
@Schema(description = "五国关键词批量添加请求")
public class KeywordShareAddRequest {
@Valid
@NotEmpty(message = "items 不能为空")
@Schema(description = "待添加的词列表", requiredMode = Schema.RequiredMode.REQUIRED)
private List<Item> items;
@Data
@Schema(description = "单个待添加词")
public static class Item {
@Schema(description = "国家", requiredMode = Schema.RequiredMode.REQUIRED)
private String country;
@Schema(description = "关键词", requiredMode = Schema.RequiredMode.REQUIRED)
private String keyword;
@Schema(description = "中文翻译")
private String chinese;
}
}
@@ -1,19 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.List;
/**
* 批量删除关键词请求(按列表行的主键 id)。
*/
@Data
@Schema(description = "五国关键词批量删除请求")
public class KeywordShareDeleteRequest {
@NotEmpty(message = "ids 不能为空")
@Schema(description = "待删除的行主键列表", requiredMode = Schema.RequiredMode.REQUIRED)
private List<Long> ids;
}
@@ -1,53 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.dto;
import lombok.Data;
import java.time.LocalDateTime;
/**
* keyword_share 列表/随机抽词的筛选条件与分页参数——Mapper XML 的唯一入参载体({@code @Param("f")})。
*
* <p>筛选值全部走 {@code #{}} 占位符,SQL 侧不做任何字符串拼接。</p>
*/
@Data
public class KeywordShareFilterQuery {
/** 归属公司,服务端从当前登录人取,永远不为空。 */
private Long companyId;
private String country;
private String category;
private String subCategory;
private String categoryL3;
private String categoryL4;
/** keyword/chinese 双列 LIKE 的搜索词,服务端已 trim;空串表示不筛。 */
private String search;
/** all | used | unused;空/未知按 all 处理。 */
private String status;
/** 已使用时间下限;null 表示不筛时间。 */
private LocalDateTime usedSince;
/** true = 仅看当前用户名标记的使用记录。 */
private Boolean onlyMine;
/** 仅看我的判定基准用户名。 */
private String userName;
private long offset;
private long limit;
/** 复制一份基础筛选,只换状态口径(命中总数与「命中内已使用数」要按不同 status 各数一遍)。 */
public KeywordShareFilterQuery copyWithStatus(String newStatus) {
KeywordShareFilterQuery copy = new KeywordShareFilterQuery();
copy.setCompanyId(companyId);
copy.setCountry(country);
copy.setCategory(category);
copy.setSubCategory(subCategory);
copy.setCategoryL3(categoryL3);
copy.setCategoryL4(categoryL4);
copy.setSearch(search);
copy.setStatus(newStatus);
copy.setUsedSince(usedSince);
copy.setOnlyMine(onlyMine);
copy.setUserName(userName);
copy.setOffset(offset);
copy.setLimit(limit);
return copy;
}
}
@@ -1,20 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.dto;
import lombok.Data;
/**
* (country, keyword) 业务键——查重、标记/取消使用的批量键载体。
*/
@Data
public class KeywordShareKey {
private String country;
private String keyword;
public static KeywordShareKey of(String country, String keyword) {
KeywordShareKey key = new KeywordShareKey();
key.setCountry(country);
key.setKeyword(keyword);
return key;
}
}
@@ -1,80 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.util.List;
/**
* 客户端全量同步导入请求。与 {@link KeywordShareAddRequest} 的分工:那条只补新词、由服务端
* 定添加人与时间;这条要把客户端本地那份四级类目与真实使用历史原样搬进主库。
*/
@Data
@Schema(description = "五国关键词客户端批量同步导入请求")
public class KeywordShareSyncImportRequest {
@Schema(description = "只统计不写库,用于导入前对账", example = "false")
private Boolean dryRun;
@Schema(description = "是否为新词写 keyword_add_log 留痕;几十万级全量导入默认不写,避免刷屏",
example = "false")
private Boolean writeAddLogs;
@Valid
@NotEmpty(message = "items 不能为空")
@Size(max = KeywordShareSyncImportRequest.MAX_ITEMS, message = "items 单次不超过 2000 条")
@Schema(description = "待同步的词行列表", requiredMode = Schema.RequiredMode.REQUIRED)
private List<Item> items;
/** 单请求上限:2000 行 × 12 列约 0.6–1MB,留出网关与请求体日志的余量。 */
public static final int MAX_ITEMS = 2000;
@Data
@Schema(description = "单个待同步词行")
public static class Item {
@Schema(description = "国家", requiredMode = Schema.RequiredMode.REQUIRED)
private String country;
@Schema(description = "关键词", requiredMode = Schema.RequiredMode.REQUIRED)
private String keyword;
@Schema(description = "中文释义;传空不会清空主库已有值")
private String chinese;
@Schema(description = "关键词类型;传空不会清空主库已有值")
private String ktype;
@Schema(description = "来源;传空不会清空主库已有值")
private String source;
@Schema(description = "一级类目;传空不会清空主库已有值")
private String category;
@Schema(description = "二级类目;传空不会清空主库已有值")
private String subCategory;
@Schema(description = "三级类目;传空不会清空主库已有值")
private String categoryL3;
@Schema(description = "四级类目;传空不会清空主库已有值")
private String categoryL4;
@Schema(description = "使用状态三态:true 写/刷 keyword_usage,false 删该行,"
+ "**不传(null)=完全不改动该词的使用状态**。只同步词库时必须整批省略此字段,"
+ "否则会把后台已有使用记录删掉",
requiredMode = Schema.RequiredMode.NOT_REQUIRED)
private Boolean used;
@Schema(description = "真实使用人;命中服务端名单才落库,否则回退为本次调用的账号名",
example = "阿武(吴棋龙)")
private String usedUser;
@Schema(description = "真实使用时间,ISO-8601 本地日期时间;服务端按此保留历史时刻而非同步时刻",
example = "2026-10-25T22:59:26")
private String usedTime;
}
}
@@ -1,32 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.List;
/**
* 批量标记/取消使用请求。接口语义由路径区分(/usage/mark 与 /usage/unmark),body 同形。
*/
@Data
@Schema(description = "五国关键词批量标记/取消使用请求")
public class KeywordUsageBatchRequest {
@Valid
@NotEmpty(message = "items 不能为空")
@Schema(description = "待操作的词键列表", requiredMode = Schema.RequiredMode.REQUIRED)
private List<Item> items;
@Data
@Schema(description = "单个词键")
public static class Item {
@Schema(description = "国家", requiredMode = Schema.RequiredMode.REQUIRED)
private String country;
@Schema(description = "关键词", requiredMode = Schema.RequiredMode.REQUIRED)
private String keyword;
}
}
@@ -1,28 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 五国关键词共享——添加留痕(谁添加了哪个词,可追溯源头)。
*
* <p>列结构按桌面版 {@code ShareSync.log_add} 的 {@code CREATE TABLE IF NOT EXISTS keyword_add_log}
* 逐列核对(keyword_share_app.py L2058-2066):id 自增主键、country NOT NULL、keyword NOT NULL、
* user_name DEFAULT ''、add_time 可空、company_id NOT NULL DEFAULT 1。</p>
*/
@Data
@TableName("keyword_add_log")
public class KeywordAddLogEntity {
@TableId(type = IdType.AUTO)
private Long id;
private String country;
private String keyword;
private String userName;
private LocalDateTime addTime;
private Long companyId;
}
@@ -1,28 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 五国关键词共享——删除留痕(谁删了哪个词,可追溯源头)。
*
* <p>列结构按桌面版 {@code ShareSync.log_delete} 的 {@code CREATE TABLE IF NOT EXISTS keyword_delete_log}
* 逐列核对(keyword_share_app.py L2019-2026):id 自增主键、country NOT NULL、keyword NOT NULL、
* user_name DEFAULT ''、delete_time 可空、company_id NOT NULL DEFAULT 1。</p>
*/
@Data
@TableName("keyword_delete_log")
public class KeywordDeleteLogEntity {
@TableId(type = IdType.AUTO)
private Long id;
private String country;
private String keyword;
private String userName;
private LocalDateTime deleteTime;
private Long companyId;
}
@@ -1,35 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 五国关键词共享——词本体(含四级类目)。
*
* <p>表在主库(aiimage)早已存在且已是全量词库,桌面 Tkinter 工具与 web 版共用同一份,
* 每公司一份、按 {@code company_id} 隔离;唯一键 {@code uk_comp_cw(company_id, country, keyword)}。
* <b>不建表、不走 Flyway</b>:本模块只做实体/Mapper 映射既有表。</p>
*/
@Data
@TableName("keyword_share")
public class KeywordShareEntity {
@TableId(type = IdType.AUTO)
private Long id;
private String country;
private String keyword;
private String chinese;
private String ktype;
private String source;
private String category;
private String subCategory;
private String categoryL3;
private String categoryL4;
private String userName;
private LocalDateTime addTime;
private Long companyId;
}
@@ -1,27 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 五国关键词共享——使用状态(谁在什么时候标记了哪个词)。
*
* <p>每公司一份,唯一键 {@code uk_comp_cw(company_id, country, keyword)};
* 「仅看我使用」按 {@code user_name = 当前用户名} 过滤。词的删除不走这里(删词写 keyword_delete_log)。</p>
*/
@Data
@TableName("keyword_usage")
public class KeywordUsageEntity {
@TableId(type = IdType.AUTO)
private Long id;
private String country;
private String keyword;
private String userName;
private LocalDateTime usedTime;
private Long companyId;
}
@@ -1,18 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 批量添加结果:成功条数 + 跳过条数(已存在/为空/批内重复)。
*/
@Data
@Schema(description = "五国关键词批量添加结果")
public class KeywordShareAddResultVo {
@Schema(description = "成功添加条数")
private int added;
@Schema(description = "跳过条数(已存在、关键词为空或批内重复)")
private int skipped;
}
@@ -1,15 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 批量删除结果。
*/
@Data
@Schema(description = "五国关键词批量删除结果")
public class KeywordShareDeleteResultVo {
@Schema(description = "实际删除条数(仅计本公司存在的行)")
private int deleted;
}
@@ -1,53 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 类目筛选名册:国家平铺 + 一级→二级→三级→四级类目树(按当前公司 DISTINCT)。
*/
@Data
@Schema(description = "五国关键词筛选名册")
public class KeywordShareFiltersVo {
@Schema(description = "国家列表")
private List<String> countries;
@Schema(description = "类目树")
private List<CategoryNode> categories;
@Data
@Schema(description = "一级类目节点")
public static class CategoryNode {
@Schema(description = "一级类目名")
private String name;
@Schema(description = "二级类目列表")
private List<SubCategoryNode> subs;
}
@Data
@Schema(description = "二级类目节点")
public static class SubCategoryNode {
@Schema(description = "二级类目名")
private String name;
@Schema(description = "三级类目列表")
private List<L3Node> l3;
}
@Data
@Schema(description = "三级类目节点")
public static class L3Node {
@Schema(description = "三级类目名")
private String name;
@Schema(description = "四级类目列表")
private List<String> l4;
}
}
@@ -1,20 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 团队共享记录分页。
*/
@Data
@Schema(description = "五国关键词共享记录分页")
public class KeywordShareLogPageVo {
@Schema(description = "总条数")
private long total;
@Schema(description = "当前页行")
private List<KeywordShareLogVo> rows;
}
@@ -1,26 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 团队共享记录单行(使用 / 添加 / 删除三类留痕同形展示,只读)。
*/
@Data
@Schema(description = "五国关键词共享记录行")
public class KeywordShareLogVo {
@Schema(description = "操作人")
private String userName;
@Schema(description = "国家")
private String country;
@Schema(description = "关键词")
private String keyword;
@Schema(description = "操作时间(使用时间/添加时间/删除时间)")
private LocalDateTime time;
}
@@ -1,15 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 批量标记使用结果。
*/
@Data
@Schema(description = "五国关键词批量标记使用结果")
public class KeywordShareMarkResultVo {
@Schema(description = "成功标记条数(唯一键冲突按幂等处理,仍计入)")
private int marked;
}
@@ -1,23 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 关键词分页列表:总命中数 + 当前行 + 统计条。
*/
@Data
@Schema(description = "五国关键词分页列表")
public class KeywordSharePageVo {
@Schema(description = "筛选命中总数")
private long total;
@Schema(description = "当前页行")
private List<KeywordShareRowVo> rows;
@Schema(description = "统计条")
private KeywordShareStatsVo stats;
}
@@ -1,47 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 关键词列表/随机抽词的单行。
*/
@Data
@Schema(description = "五国关键词行")
public class KeywordShareRowVo {
@Schema(description = "行主键")
private Long id;
@Schema(description = "国家")
private String country;
@Schema(description = "关键词")
private String keyword;
@Schema(description = "中文翻译")
private String chinese;
@Schema(description = "一级类目")
private String category;
@Schema(description = "二级类目")
private String subCategory;
@Schema(description = "三级类目")
private String categoryL3;
@Schema(description = "四级类目")
private String categoryL4;
@Schema(description = "是否已使用")
private boolean used;
@Schema(description = "使用时间(未使用为 null)")
private LocalDateTime usedTime;
@Schema(description = "使用者(未使用为空串)")
private String usedUser;
}
@@ -1,29 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.vo;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryCountRow;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryL3CountRow;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordNameCountRow;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 词库统计弹窗:国家、一级/二级/三级类目的分布计数(对齐桌面版统计窗的四段展示)。
*/
@Data
@Schema(description = "五国关键词词库统计")
public class KeywordShareStatsGroupedVo {
@Schema(description = "按国家分布")
private List<KeywordNameCountRow> byCountry;
@Schema(description = "按一级类目分布")
private List<KeywordNameCountRow> byCategory;
@Schema(description = "按二级类目分布(挂一级类目下)")
private List<KeywordCategoryCountRow> bySubCategory;
@Schema(description = "按三级类目分布(挂一级+二级下)")
private List<KeywordCategoryL3CountRow> byCategoryL3;
}
@@ -1,24 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 列表页统计条:命中数、命中内已/未使用数、本公司跨国重复词数。
*/
@Data
@Schema(description = "五国关键词列表统计")
public class KeywordShareStatsVo {
@Schema(description = "筛选命中总数")
private long hit;
@Schema(description = "命中内已使用数")
private long used;
@Schema(description = "命中内未使用数")
private long unused;
@Schema(description = "本公司跨国重复词数")
private long dup;
}
@@ -1,51 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 客户端批量同步导入结果。计数是观测值而非事务保证:预检与写入之间有并发窗口,
* 同一批被两个客户端同时推时 added/updated 会漂,但落库内容幂等。
*/
@Data
@Schema(description = "五国关键词客户端批量同步导入结果")
public class KeywordShareSyncResultVo {
@Schema(description = "新插入的词行数")
private int added;
@Schema(description = "命中唯一键、被刷了类目/释义的既有词行数")
private int updated;
@Schema(description = "整行丢弃数(国家或关键词为空、批内重复、字段超长)")
private int skipped;
@Schema(description = "本批请求写入或刷新 keyword_usage 的行数(dryRun 下为预计数)")
private int usageUpserted;
@Schema(description = "本批请求按 used=false 取消使用的行数(dryRun 下为预计数;"
+ "实际删除条数不会多于它,主库可能本就没有该 usage 行)")
private int usageDeleted;
@Schema(description = "词已入库但使用状态被丢弃的行数(usedTime 解析失败或早于下限)")
private int usageSkipped;
@Schema(description = "usedUser 未命中服务端名单、回退为调用账号名的行数(仅 strict=true 时会产生)")
private int usedUserFallback;
@Schema(description = "usedUser 自报姓名不在名单内的行数;非 strict 下照原样落库但仍计数,"
+ "供运维据此判断名单是否该补齐、能否切 strict")
private int usedUserUnknown;
@Schema(description = "usedTime 缺失、回退为服务端当前时间的行数")
private int usedTimeFallback;
@Schema(description = "usedTime 落在未来、被钳到当前时间的行数")
private int usedTimeClamped;
@Schema(description = "写入 keyword_add_log 留痕的行数(writeAddLogs=true 时才可能非 0)")
private int addLogged;
@Schema(description = "本次是否为 dryRun")
private boolean dryRun;
}
@@ -1,15 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 批量取消使用结果。
*/
@Data
@Schema(description = "五国关键词批量取消使用结果")
public class KeywordShareUnmarkResultVo {
@Schema(description = "实际删除的使用记录条数")
private int unmarked;
}
@@ -1,771 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.support.LooseLocalDateTimeParser;
import com.nanri.aiimage.config.KeywordShareSyncProperties;
import com.nanri.aiimage.modules.keywordshare.mapper.KeywordAddLogMapper;
import com.nanri.aiimage.modules.keywordshare.mapper.KeywordDeleteLogMapper;
import com.nanri.aiimage.modules.keywordshare.mapper.KeywordShareMapper;
import com.nanri.aiimage.modules.keywordshare.mapper.KeywordUsageMapper;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryCountRow;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryL3CountRow;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryTreeRow;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordNameCountRow;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareAddRequest;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareDeleteRequest;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareFilterQuery;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareKey;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareSyncImportRequest;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordUsageBatchRequest;
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordAddLogEntity;
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordDeleteLogEntity;
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordShareEntity;
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordUsageEntity;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareAddResultVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareDeleteResultVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareFiltersVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareLogPageVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareLogVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareMarkResultVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordSharePageVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareRowVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareStatsGroupedVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareStatsVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareSyncResultVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareUnmarkResultVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
/**
* 五国关键词共享(桌面 Tkinter 工具的 web 化)。
*
* <p>词本体 = 主库 keyword_share(每公司一份、company_id 隔离),web 版没有 SQLite;
* 所有查询/写入都以服务端取到的 companyId 收口,杜绝跨公司读写。
* 行为口径对齐桌面版 keyword_share_app.py:列表「未使用在前、已使用按 used_time 升序」,
* 添加即自动标记已使用(使用者=当前用户、时间=添加时刻),删词写 keyword_delete_log 留痕,
* 标记走 UPSERT 天然幂等。</p>
*/
@Service
@RequiredArgsConstructor
public class KeywordShareService {
/** 列表默认页容量(API 契约定值;不走 PageDefaults 以免挤进它的逐点台账)。 */
public static final long DEFAULT_PAGE_SIZE = 200;
/** 列表页容量上限。 */
public static final long MAX_PAGE_SIZE = 500;
/** 随机抽词默认条数。 */
public static final long DEFAULT_RANDOM_COUNT = 10;
/** 随机抽词单次上限。 */
public static final long MAX_RANDOM_COUNT = 100;
/** 共享记录单页上限(留痕查询非无限拉取)。 */
public static final long MAX_LOG_PAGE_SIZE = 500;
public static final String FILTER_ALL = "all";
public static final String FILTER_USED = "used";
public static final String FILTER_UNUSED = "unused";
/** 添加词的固定口径,与桌面版 insert_keyword 一致。 */
private static final String KTYPE_MANUAL = "主关键词";
private static final String SOURCE_MANUAL = "手动添加";
/**
* 同步写入的分片行数:与仓内批量写惯例一致,控制单条 SQL 的占位符总量
* (12 列 × 500 行 = 6000 个占位符)。
*/
private static final int SYNC_SHARD_SIZE = 500;
/**
* 客户端自报使用时间的可信下限。早于此的一律当作脏值丢掉使用状态(1970/0000 这类
* SQLite 零值日期),但词本体照收——不该为一个坏时间戳丢掉一个词。
*/
private static final LocalDateTime MIN_SYNC_USED_TIME = LocalDateTime.of(2000, 1, 1, 0, 0);
/**
* 各列字符上限,对齐 V177 建表口径(线上真表若更窄,由部署前的 SHOW CREATE TABLE 预检兜住)。
* 超限一律整行拒绝而不是截断入库:静默截断会让客户端以为同步成功,而词已经被改坏了。
*/
private static final int WIDTH_COUNTRY = 32;
private static final int WIDTH_KEYWORD = 255;
private static final int WIDTH_CHINESE = 255;
private static final int WIDTH_KTYPE = 64;
private static final int WIDTH_SOURCE = 64;
private static final int WIDTH_CATEGORY = 128;
private static final int WIDTH_USER_NAME = 128;
private final KeywordShareMapper keywordShareMapper;
private final KeywordUsageMapper keywordUsageMapper;
private final KeywordAddLogMapper keywordAddLogMapper;
private final KeywordDeleteLogMapper keywordDeleteLogMapper;
private final KeywordShareSyncProperties syncProperties;
// ---------------------------------------------------------------- 列表与统计
public KeywordSharePageVo page(Long companyId, String viewerUserName,
String country, String category, String subCategory,
String categoryL3, String categoryL4, String search,
String status, Integer usedDays, boolean onlyMine,
Long page, Long size) {
KeywordShareFilterQuery filter = buildFilter(companyId, viewerUserName, country, category, subCategory,
categoryL3, categoryL4, search, status, usedDays, onlyMine);
filter.setOffset((safePage(page) - 1) * safePageSize(size));
filter.setLimit(safePageSize(size));
long hit = keywordShareMapper.countHit(filter);
// 命中内已使用数:状态过滤生效时命中即答案;否则按同条件单独数一遍 used
long used = switch (filter.getStatus()) {
case FILTER_USED -> hit;
case FILTER_UNUSED -> 0;
default -> keywordShareMapper.countHit(filter.copyWithStatus(FILTER_USED));
};
List<KeywordShareRowVo> rows = keywordShareMapper.selectRows(filter).stream()
.map(this::normalizeRow)
.toList();
long dup = keywordShareMapper.countDupKeywords(companyId);
KeywordShareStatsVo stats = new KeywordShareStatsVo();
stats.setHit(hit);
stats.setUsed(used);
stats.setUnused(hit - used);
stats.setDup(dup);
KeywordSharePageVo vo = new KeywordSharePageVo();
vo.setTotal(hit);
vo.setRows(rows);
vo.setStats(stats);
return vo;
}
public KeywordShareFiltersVo filters(Long companyId) {
KeywordShareFiltersVo vo = new KeywordShareFiltersVo();
vo.setCountries(keywordShareMapper.selectFilterCountries(companyId));
Map<String, Map<String, Map<String, Set<String>>>> tree = new LinkedHashMap<>();
for (KeywordCategoryTreeRow row : keywordShareMapper.selectFilterTreeRows(companyId)) {
tree.computeIfAbsent(orEmpty(row.getCategory()), c -> new LinkedHashMap<>())
.computeIfAbsent(orEmpty(row.getSubCategory()), s -> new LinkedHashMap<>())
.computeIfAbsent(orEmpty(row.getCategoryL3()), l -> new LinkedHashSet<>())
.add(orEmpty(row.getCategoryL4()));
}
List<KeywordShareFiltersVo.CategoryNode> categories = new ArrayList<>();
tree.forEach((category, subs) -> {
KeywordShareFiltersVo.CategoryNode categoryNode = new KeywordShareFiltersVo.CategoryNode();
categoryNode.setName(category);
List<KeywordShareFiltersVo.SubCategoryNode> subNodes = new ArrayList<>();
subs.forEach((sub, l3s) -> {
KeywordShareFiltersVo.SubCategoryNode subNode = new KeywordShareFiltersVo.SubCategoryNode();
subNode.setName(sub);
List<KeywordShareFiltersVo.L3Node> l3Nodes = new ArrayList<>();
l3s.forEach((l3, l4s) -> {
// 三级/四级类目与桌面版同口径:空值不进名册
if (l3.isBlank()) {
return;
}
KeywordShareFiltersVo.L3Node l3Node = new KeywordShareFiltersVo.L3Node();
l3Node.setName(l3);
l3Node.setL4(l4s.stream().filter(l4 -> !l4.isBlank()).toList());
l3Nodes.add(l3Node);
});
subNode.setL3(l3Nodes);
subNodes.add(subNode);
});
categoryNode.setSubs(subNodes);
categories.add(categoryNode);
});
vo.setCategories(categories);
return vo;
}
public KeywordShareStatsGroupedVo statsGrouped(Long companyId) {
KeywordShareStatsGroupedVo vo = new KeywordShareStatsGroupedVo();
vo.setByCountry(keywordShareMapper.selectCountryCounts(companyId));
vo.setByCategory(keywordShareMapper.selectCategoryCounts(companyId));
vo.setBySubCategory(keywordShareMapper.selectSubCategoryCounts(companyId));
vo.setByCategoryL3(keywordShareMapper.selectCategoryL3Counts(companyId));
return vo;
}
/** 未使用池随机抽词;国家/类目筛选可选,数量默认 10、上限 100。 */
public List<KeywordShareRowVo> random(Long companyId, String viewerUserName,
String country, String category, String subCategory,
String categoryL3, String categoryL4, String search,
Long count) {
KeywordShareFilterQuery filter = buildFilter(companyId, viewerUserName, country, category, subCategory,
categoryL3, categoryL4, search, FILTER_UNUSED, null, false);
long safeCount = count == null ? DEFAULT_RANDOM_COUNT : Math.min(Math.max(count, 1), MAX_RANDOM_COUNT);
filter.setLimit(safeCount);
// AC-19(审计 P1-B2):窗口起点先数命中集再掷,MySQL 就不必给全表打 RAND 后 filesort。
// 掷的是起点而非每一行,所以同一批词的相邻关系仍在(一次抽到的是连续 id 的一段),
// 服务层洗牌补回"散着"的观感;命中集不足一批时起点恒 0,与旧口径同为"全给你"。
filter.setOffset(randomWindowOffset(keywordShareMapper.countHit(filter), safeCount));
List<KeywordShareRowVo> window = new ArrayList<>(keywordShareMapper.selectRandomUnused(filter).stream()
.map(this::normalizeRow)
.toList());
Collections.shuffle(window);
return window;
}
/** 随机窗口起点:落在 {@code [0, total - count]},装得下整批才有得掷。 */
static long randomWindowOffset(long total, long count) {
long span = total - count;
return span > 0 ? ThreadLocalRandom.current().nextLong(span + 1) : 0L;
}
// ---------------------------------------------------------------- 写操作
/** 批量添加:trim 规范化、防重跳过;成功行写词本体 + 添加留痕 + 自动标记已使用。 */
@Transactional
public KeywordShareAddResultVo add(KeywordShareAddRequest request, Long companyId, String operatorName) {
int skipped = 0;
List<KeywordShareAddRequest.Item> candidates = new ArrayList<>();
Set<String> seen = new LinkedHashSet<>();
for (KeywordShareAddRequest.Item item : request.getItems()) {
String country = normalize(item == null ? null : item.getCountry());
String keyword = normalize(item == null ? null : item.getKeyword());
if (country.isEmpty() || keyword.isEmpty()) {
skipped++;
continue;
}
if (!seen.add(country + "\n" + keyword)) {
skipped++;
continue;
}
KeywordShareAddRequest.Item normalized = new KeywordShareAddRequest.Item();
normalized.setCountry(country);
normalized.setKeyword(keyword);
normalized.setChinese(normalize(item.getChinese()));
candidates.add(normalized);
}
List<KeywordShareEntity> toInsert = new ArrayList<>();
if (!candidates.isEmpty()) {
Set<String> existing = new LinkedHashSet<>();
List<KeywordShareKey> keys = candidates.stream()
.map(item -> KeywordShareKey.of(item.getCountry(), item.getKeyword()))
.toList();
for (KeywordShareKey key : keywordShareMapper.selectExistingKeywords(companyId, keys)) {
existing.add(key.getCountry() + "\n" + key.getKeyword());
}
for (KeywordShareAddRequest.Item item : candidates) {
if (existing.contains(item.getCountry() + "\n" + item.getKeyword())) {
skipped++;
continue;
}
KeywordShareEntity entity = new KeywordShareEntity();
entity.setCountry(item.getCountry());
entity.setKeyword(item.getKeyword());
entity.setChinese(item.getChinese());
entity.setKtype(KTYPE_MANUAL);
entity.setSource(SOURCE_MANUAL);
entity.setUserName(operatorName);
entity.setAddTime(LocalDateTime.now());
entity.setCompanyId(companyId);
toInsert.add(entity);
}
}
if (!toInsert.isEmpty()) {
keywordShareMapper.insertBatchIgnore(toInsert);
keywordAddLogMapper.insertBatch(toInsert.stream().map(row -> {
KeywordAddLogEntity log = new KeywordAddLogEntity();
log.setCompanyId(companyId);
log.setCountry(row.getCountry());
log.setKeyword(row.getKeyword());
log.setUserName(operatorName);
log.setAddTime(row.getAddTime());
return log;
}).toList());
markInternal(companyId, operatorName, toInsert.stream()
.map(row -> KeywordShareKey.of(row.getCountry(), row.getKeyword()))
.toList());
}
KeywordShareAddResultVo vo = new KeywordShareAddResultVo();
vo.setAdded(toInsert.size());
vo.setSkipped(skipped);
return vo;
}
/** 批量删除:只删本公司行并写删除留痕(谁删了哪个词可追溯)。 */
@Transactional
public KeywordShareDeleteResultVo delete(KeywordShareDeleteRequest request, Long companyId, String operatorName) {
List<Long> ids = request.getIds().stream().filter(java.util.Objects::nonNull).distinct().toList();
// 公司隔离在应用侧过滤:selectBatchIds 拉回后只认本公司行,别家的 id 传进来也不动
List<KeywordShareEntity> rows = ids.isEmpty() ? List.of()
: keywordShareMapper.selectBatchIds(ids).stream()
.filter(row -> companyId != null && companyId.equals(row.getCompanyId()))
.toList();
if (!rows.isEmpty()) {
keywordShareMapper.deleteBatchIds(rows.stream().map(KeywordShareEntity::getId).toList());
keywordDeleteLogMapper.insertBatch(rows.stream().map(row -> {
KeywordDeleteLogEntity log = new KeywordDeleteLogEntity();
log.setCompanyId(companyId);
log.setCountry(row.getCountry());
log.setKeyword(row.getKeyword());
log.setUserName(operatorName);
log.setDeleteTime(LocalDateTime.now());
return log;
}).toList());
}
KeywordShareDeleteResultVo vo = new KeywordShareDeleteResultVo();
vo.setDeleted(rows.size());
return vo;
}
/** 批量标记已使用;唯一键冲突按 UPSERT 刷新,幂等。used_time 取服务器当前时间。 */
@Transactional
public KeywordShareMarkResultVo mark(KeywordUsageBatchRequest request, Long companyId, String operatorName) {
int marked = markInternal(companyId, operatorName, normalizeKeys(request));
KeywordShareMarkResultVo vo = new KeywordShareMarkResultVo();
vo.setMarked(marked);
return vo;
}
/** 批量取消使用:删 usage 行,返回实际删除条数。 */
@Transactional
public KeywordShareUnmarkResultVo unmark(KeywordUsageBatchRequest request, Long companyId) {
List<KeywordShareKey> keys = normalizeKeys(request);
int unmarked = keys.isEmpty() ? 0 : keywordUsageMapper.deleteBatch(companyId, keys);
KeywordShareUnmarkResultVo vo = new KeywordShareUnmarkResultVo();
vo.setUnmarked(unmarked);
return vo;
}
// ---------------------------------------------------------------- 客户端全量同步
/**
* 客户端全量同步导入:把工作台本地那份词库+使用状态搬进主库,并且**保住客户端传来的
* 真实使用人与真实使用时间**——这正是 {@link #add} 与 {@link #mark} 给不了的两件事:
* add() 从不写四级类目且会自动标记已使用,mark() 把 user_name/used_time 硬写成 token 账号与此刻。
*
* <p>幂等:词按 {@code uk_comp_cw} UPSERT、使用状态按同键 UPSERT/删除,同一批重复推送结果一致。
* 一个请求=一个事务=一批(items ≤ 2000),整批要么全落要么全不回;客户端只需重传失败的那一批,
* 不做逐行重放——事务内一次 SQLException 已把整笔标记为 rollback-only,重放不出第二结果。</p>
*
* @param companyId 一律由服务端从 token 取,与其余写侧同口径
* @param tokenUser 本次调用的账号名,用作自报姓名不可信时的落点
*/
@Transactional
public KeywordShareSyncResultVo syncImport(KeywordShareSyncImportRequest request,
Long companyId, String tokenUser) {
KeywordShareSyncResultVo vo = new KeywordShareSyncResultVo();
boolean dryRun = Boolean.TRUE.equals(request.getDryRun());
boolean writeAddLogs = Boolean.TRUE.equals(request.getWriteAddLogs());
vo.setDryRun(dryRun);
Map<String, String> roster = canonicalRoster(syncProperties.getUsedUsers());
boolean strict = syncProperties.isStrict();
LocalDateTime now = LocalDateTime.now();
List<KeywordShareEntity> words = new ArrayList<>();
List<KeywordUsageEntity> usageUpserts = new ArrayList<>();
List<KeywordShareKey> usageDeletes = new ArrayList<>();
Set<String> seen = new LinkedHashSet<>();
int usedUserFallback = 0;
int usedUserUnknown = 0;
int usedTimeFallback = 0;
int usedTimeClamped = 0;
int usageSkipped = 0;
for (KeywordShareSyncImportRequest.Item item : request.getItems()) {
String country = normalize(item == null ? null : item.getCountry());
String keyword = normalize(item == null ? null : item.getKeyword());
if (country.isEmpty() || keyword.isEmpty()
|| !seen.add(country + "\n" + keyword)
|| !withinSyncColumnWidths(country, keyword, item)) {
vo.setSkipped(vo.getSkipped() + 1);
continue;
}
words.add(syncWordRow(companyId, tokenUser, now, country, keyword, item));
// used 三态:null=客户端没表达使用状态,一律不改动 keyword_usage。
// 不能把缺省当 false——那等于「只同步词库」的一次调用会把后台已有使用记录整批删掉。
Boolean used = item.getUsed();
if (used == null) {
continue;
}
if (!used) {
usageDeletes.add(KeywordShareKey.of(country, keyword));
continue;
}
UsedUserResult usedUser = resolveUsedUser(item.getUsedUser(), tokenUser, roster, strict);
if (usedUser.fellBack()) {
usedUserFallback++;
}
if (usedUser.unknown()) {
usedUserUnknown++;
}
UsedTimeResult usedTime = resolveUsedTime(item.getUsedTime(), now);
switch (usedTime.outcome()) {
case MISSING, UNPARSEABLE -> usedTimeFallback++;
case FUTURE -> usedTimeClamped++;
case TOO_OLD -> usageSkipped++;
case EXACT -> { }
}
if (usedTime.value() == null) {
continue;
}
KeywordUsageEntity usage = new KeywordUsageEntity();
usage.setCompanyId(companyId);
usage.setCountry(country);
usage.setKeyword(keyword);
usage.setUserName(usedUser.value());
usage.setUsedTime(usedTime.value());
usageUpserts.add(usage);
}
vo.setUsedUserFallback(usedUserFallback);
vo.setUsedUserUnknown(usedUserUnknown);
vo.setUsedTimeFallback(usedTimeFallback);
vo.setUsedTimeClamped(usedTimeClamped);
vo.setUsageSkipped(usageSkipped);
// added/updated 走预检分组:UPSERT 的 affected-rows 是 1/2/0(插入/值变/值未变),
// 求和后不可逆,拿它计数会把「重复推同一批」报成 0 新增或 2 倍新增。
Set<String> existing = existingWordKeys(companyId, words);
List<KeywordShareEntity> freshWords = words.stream()
.filter(row -> !existing.contains(row.getCountry() + "\n" + row.getKeyword()))
.toList();
vo.setAdded(freshWords.size());
vo.setUpdated(words.size() - freshWords.size());
vo.setUsageUpserted(usageUpserts.size());
vo.setUsageDeleted(usageDeletes.size());
if (dryRun) {
return vo;
}
for (List<KeywordShareEntity> shard : shard(words, SYNC_SHARD_SIZE)) {
keywordShareMapper.upsertBatchFromSync(shard);
}
if (writeAddLogs && !freshWords.isEmpty()) {
List<KeywordAddLogEntity> logs = freshWords.stream().map(row -> {
KeywordAddLogEntity log = new KeywordAddLogEntity();
log.setCompanyId(companyId);
log.setCountry(row.getCountry());
log.setKeyword(row.getKeyword());
log.setUserName(tokenUser);
log.setAddTime(row.getAddTime());
return log;
}).toList();
for (List<KeywordAddLogEntity> shard : shard(logs, SYNC_SHARD_SIZE)) {
keywordAddLogMapper.insertBatch(shard);
}
vo.setAddLogged(logs.size());
}
for (List<KeywordUsageEntity> shard : shard(usageUpserts, SYNC_SHARD_SIZE)) {
keywordUsageMapper.upsertBatch(shard);
}
for (List<KeywordShareKey> shard : shard(usageDeletes, SYNC_SHARD_SIZE)) {
keywordUsageMapper.deleteBatch(companyId, shard);
}
return vo;
}
// ---------------------------------------------------------------- 共享记录(只读)
public KeywordShareLogPageVo logs(Long companyId, String type, String country, Long page, Long size) {
long safePage = safePage(page);
long safeSize = size == null ? DEFAULT_PAGE_SIZE : Math.min(Math.max(size, 1), MAX_LOG_PAGE_SIZE);
return switch (type == null ? "" : type) {
case "usage" -> usageLogs(companyId, country, safePage, safeSize);
case "add" -> addLogs(companyId, country, safePage, safeSize);
case "delete" -> deleteLogs(companyId, country, safePage, safeSize);
default -> throw new BusinessException("type 只支持 usage / add / delete");
};
}
private KeywordShareLogPageVo usageLogs(Long companyId, String country, long page, long size) {
LambdaQueryWrapper<KeywordUsageEntity> query = new LambdaQueryWrapper<KeywordUsageEntity>()
.eq(KeywordUsageEntity::getCompanyId, companyId)
.eq(country != null && !country.isBlank(), KeywordUsageEntity::getCountry, normalize(country))
.orderByDesc(KeywordUsageEntity::getUsedTime)
.orderByDesc(KeywordUsageEntity::getId);
long total = keywordUsageMapper.selectCount(query);
List<KeywordUsageEntity> rows = keywordUsageMapper.selectList(
query.last("LIMIT " + ((page - 1) * size) + ", " + size));
return toLogPage(total, rows.stream().map(row -> {
KeywordShareLogVo vo = new KeywordShareLogVo();
vo.setUserName(orEmpty(row.getUserName()));
vo.setCountry(orEmpty(row.getCountry()));
vo.setKeyword(orEmpty(row.getKeyword()));
vo.setTime(row.getUsedTime());
return vo;
}).toList());
}
private KeywordShareLogPageVo addLogs(Long companyId, String country, long page, long size) {
LambdaQueryWrapper<KeywordAddLogEntity> query = new LambdaQueryWrapper<KeywordAddLogEntity>()
.eq(KeywordAddLogEntity::getCompanyId, companyId)
.eq(country != null && !country.isBlank(), KeywordAddLogEntity::getCountry, normalize(country))
.orderByDesc(KeywordAddLogEntity::getAddTime)
.orderByDesc(KeywordAddLogEntity::getId);
long total = keywordAddLogMapper.selectCount(query);
List<KeywordAddLogEntity> rows = keywordAddLogMapper.selectList(
query.last("LIMIT " + ((page - 1) * size) + ", " + size));
return toLogPage(total, rows.stream().map(row -> {
KeywordShareLogVo vo = new KeywordShareLogVo();
vo.setUserName(orEmpty(row.getUserName()));
vo.setCountry(orEmpty(row.getCountry()));
vo.setKeyword(orEmpty(row.getKeyword()));
vo.setTime(row.getAddTime());
return vo;
}).toList());
}
private KeywordShareLogPageVo deleteLogs(Long companyId, String country, long page, long size) {
LambdaQueryWrapper<KeywordDeleteLogEntity> query = new LambdaQueryWrapper<KeywordDeleteLogEntity>()
.eq(KeywordDeleteLogEntity::getCompanyId, companyId)
.eq(country != null && !country.isBlank(), KeywordDeleteLogEntity::getCountry, normalize(country))
.orderByDesc(KeywordDeleteLogEntity::getDeleteTime)
.orderByDesc(KeywordDeleteLogEntity::getId);
long total = keywordDeleteLogMapper.selectCount(query);
List<KeywordDeleteLogEntity> rows = keywordDeleteLogMapper.selectList(
query.last("LIMIT " + ((page - 1) * size) + ", " + size));
return toLogPage(total, rows.stream().map(row -> {
KeywordShareLogVo vo = new KeywordShareLogVo();
vo.setUserName(orEmpty(row.getUserName()));
vo.setCountry(orEmpty(row.getCountry()));
vo.setKeyword(orEmpty(row.getKeyword()));
vo.setTime(row.getDeleteTime());
return vo;
}).toList());
}
private KeywordShareLogPageVo toLogPage(long total, List<KeywordShareLogVo> rows) {
KeywordShareLogPageVo vo = new KeywordShareLogPageVo();
vo.setTotal(total);
vo.setRows(rows);
return vo;
}
// ---------------------------------------------------------------- 内部工具
private int markInternal(Long companyId, String operatorName, List<KeywordShareKey> keys) {
if (keys.isEmpty()) {
return 0;
}
LocalDateTime now = LocalDateTime.now();
List<KeywordUsageEntity> rows = keys.stream().map(key -> {
KeywordUsageEntity entity = new KeywordUsageEntity();
entity.setCompanyId(companyId);
entity.setCountry(key.getCountry());
entity.setKeyword(key.getKeyword());
entity.setUserName(operatorName);
entity.setUsedTime(now);
return entity;
}).toList();
keywordUsageMapper.upsertBatch(rows);
return rows.size();
}
private List<KeywordShareKey> normalizeKeys(KeywordUsageBatchRequest request) {
Set<String> seen = new LinkedHashSet<>();
List<KeywordShareKey> keys = new ArrayList<>();
for (KeywordUsageBatchRequest.Item item : request.getItems()) {
String country = normalize(item == null ? null : item.getCountry());
String keyword = normalize(item == null ? null : item.getKeyword());
if (country.isEmpty() || keyword.isEmpty() || !seen.add(country + "\n" + keyword)) {
continue;
}
keys.add(KeywordShareKey.of(country, keyword));
}
return keys;
}
private KeywordShareFilterQuery buildFilter(Long companyId, String viewerUserName,
String country, String category, String subCategory,
String categoryL3, String categoryL4, String search,
String status, Integer usedDays, boolean onlyMine) {
KeywordShareFilterQuery filter = new KeywordShareFilterQuery();
filter.setCompanyId(companyId);
filter.setCountry(normalizeOrNull(country));
filter.setCategory(normalizeOrNull(category));
filter.setSubCategory(normalizeOrNull(subCategory));
filter.setCategoryL3(normalizeOrNull(categoryL3));
filter.setCategoryL4(normalizeOrNull(categoryL4));
filter.setSearch(normalizeOrNull(search));
filter.setStatus(normalizeStatus(status));
filter.setUsedSince(resolveUsedSince(usedDays));
filter.setOnlyMine(onlyMine);
filter.setUserName(viewerUserName);
return filter;
}
/** usedDays:1=今天(当日零点起),7/30/90/180/360=往前推 N 天;0/null=不限。 */
private LocalDateTime resolveUsedSince(Integer usedDays) {
if (usedDays == null || usedDays <= 0) {
return null;
}
if (usedDays == 1) {
return LocalDate.now().atStartOfDay();
}
return LocalDateTime.now().minusDays(usedDays);
}
private String normalizeStatus(String status) {
String normalized = normalize(status);
return switch (normalized) {
case FILTER_USED -> FILTER_USED;
case FILTER_UNUSED -> FILTER_UNUSED;
default -> FILTER_ALL;
};
}
private KeywordShareRowVo normalizeRow(KeywordShareRowVo row) {
if (!row.isUsed()) {
row.setUsedUser("");
}
return row;
}
private long safePage(Long page) {
return page == null ? 1 : Math.max(page, 1);
}
private long safePageSize(Long size) {
return size == null ? DEFAULT_PAGE_SIZE : Math.min(Math.max(size, 1), MAX_PAGE_SIZE);
}
private KeywordShareEntity syncWordRow(Long companyId, String tokenUser, LocalDateTime now,
String country, String keyword,
KeywordShareSyncImportRequest.Item item) {
KeywordShareEntity row = new KeywordShareEntity();
row.setCompanyId(companyId);
row.setCountry(country);
row.setKeyword(keyword);
row.setChinese(normalize(item.getChinese()));
row.setKtype(normalize(item.getKtype()));
row.setSource(normalize(item.getSource()));
row.setCategory(normalize(item.getCategory()));
row.setSubCategory(normalize(item.getSubCategory()));
row.setCategoryL3(normalize(item.getCategoryL3()));
row.setCategoryL4(normalize(item.getCategoryL4()));
// 词本体的 user_name 是「添加人」,与 usedUser(使用人)不是一回事:客户端没有自报添加人的通道,
// 新词的添加人就是本次同步账号。UPSERT 的更新分支不碰这两列,既有归属不会被同步改写。
row.setUserName(tokenUser);
row.setAddTime(now);
return row;
}
/**
* 逐列比宽。用 {@code String.length()} 数的是 UTF-16 码元,MySQL 数的是字符,
* 差异只在增补平面字符(emoji)上出现且这里偏大 ⇒ 只会多拒不会漏拒。
*/
private boolean withinSyncColumnWidths(String country, String keyword,
KeywordShareSyncImportRequest.Item item) {
return country.length() <= WIDTH_COUNTRY
&& keyword.length() <= WIDTH_KEYWORD
&& normalize(item.getChinese()).length() <= WIDTH_CHINESE
&& normalize(item.getKtype()).length() <= WIDTH_KTYPE
&& normalize(item.getSource()).length() <= WIDTH_SOURCE
&& normalize(item.getCategory()).length() <= WIDTH_CATEGORY
&& normalize(item.getSubCategory()).length() <= WIDTH_CATEGORY
&& normalize(item.getCategoryL3()).length() <= WIDTH_CATEGORY
&& normalize(item.getCategoryL4()).length() <= WIDTH_CATEGORY;
}
/** 预检哪些 (country, keyword) 已在主库:分片查,避免 IN 列表一次塞进整批。 */
private Set<String> existingWordKeys(Long companyId, List<KeywordShareEntity> words) {
List<KeywordShareKey> keys = words.stream()
.map(row -> KeywordShareKey.of(row.getCountry(), row.getKeyword()))
.toList();
Set<String> existing = new LinkedHashSet<>();
for (List<KeywordShareKey> shard : shard(keys, SYNC_SHARD_SIZE)) {
keywordShareMapper.selectExistingKeywords(companyId, shard)
.forEach(key -> existing.add(key.getCountry() + "\n" + key.getKeyword()));
}
return existing;
}
private static <T> List<List<T>> shard(List<T> rows, int size) {
List<List<T>> shards = new ArrayList<>();
for (int from = 0; from < rows.size(); from += size) {
shards.add(rows.subList(from, Math.min(from + size, rows.size())));
}
return shards;
}
/**
* 自报使用人的收口:命中名单才按姓名落库,且**落的是名单里那份写法**。
* 名单两侧都做全角/半角括号归一,所以「阿武(吴棋龙)」也能命中「阿武(吴棋龙)」;
* 若原样存客户端写法,同一个人会因括号全半角不同被后管的使用者筛选器拆成两个人。
*/
private UsedUserResult resolveUsedUser(String declared, String tokenUser,
Map<String, String> roster, boolean strict) {
String name = normalize(declared);
if (name.length() > WIDTH_USER_NAME || name.isEmpty()) {
return new UsedUserResult(tokenUser, !name.isEmpty(), true);
}
String listed = roster.get(canonicalName(name));
if (listed != null) {
return new UsedUserResult(listed, false, false);
}
return strict
? new UsedUserResult(tokenUser, true, true)
: new UsedUserResult(name, true, false);
}
/** 客户端 usedTime 的判定:缺失/不可解析回退此刻,未来值钳到此刻,早于下限则丢使用状态。 */
private UsedTimeResult resolveUsedTime(String raw, LocalDateTime now) {
LocalDateTime parsed = LooseLocalDateTimeParser.parseOrNull(raw);
if (parsed == null) {
return new UsedTimeResult(now, normalize(raw).isEmpty()
? UsedTimeOutcome.MISSING : UsedTimeOutcome.UNPARSEABLE);
}
if (parsed.isAfter(now)) {
return new UsedTimeResult(now, UsedTimeOutcome.FUTURE);
}
if (parsed.isBefore(MIN_SYNC_USED_TIME)) {
return new UsedTimeResult(null, UsedTimeOutcome.TOO_OLD);
}
return new UsedTimeResult(parsed, UsedTimeOutcome.EXACT);
}
private Map<String, String> canonicalRoster(List<String> configured) {
Map<String, String> roster = new LinkedHashMap<>();
if (configured == null) {
return roster;
}
for (String name : configured) {
String canonical = canonicalName(name);
if (!canonical.isEmpty()) {
roster.putIfAbsent(canonical, normalize(name));
}
}
return roster;
}
private String canonicalName(String value) {
return normalize(value).replace('(', '(').replace(')', ')');
}
private String normalize(String value) {
return value == null ? "" : value.trim();
}
private String normalizeOrNull(String value) {
String normalized = normalize(value);
return normalized.isEmpty() ? null : normalized;
}
private String orEmpty(String value) {
return value == null ? "" : value;
}
/** usedTime 判定结果分类,直接对应响应里的降级计数。 */
private enum UsedTimeOutcome { EXACT, MISSING, UNPARSEABLE, FUTURE, TOO_OLD }
/** 解析后的使用时间;{@code value} 为 null 表示这条使用状态不该落库。 */
private record UsedTimeResult(LocalDateTime value, UsedTimeOutcome outcome) { }
/** 自报使用人的收口结果:最终落库名、是否不在名单内、是否被回退成账号名。 */
private record UsedUserResult(String value, boolean unknown, boolean fellBack) { }
}
@@ -1,40 +0,0 @@
package com.nanri.aiimage.modules.workbenchclient.controller;
import com.nanri.aiimage.modules.workbenchclient.service.WorkbenchClientPackageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* 工作台客户端公开版本接口。
*
* <p>返回裸 JSON(不套 ApiResponse),字段名固定为 {@code version/file_url/sha256}:
* 客户端更新器直接按这三个字段比较版本、下载、校验摘要。新增字段只能追加,不能改名。
*/
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/workbench-client/version")
@Tag(name = "工作台客户端公开版本接口", description = "工作台客户端自动更新检查")
public class PublicWorkbenchClientVersionController {
private final WorkbenchClientPackageService packageService;
@GetMapping("/latest")
@Operation(summary = "最新客户端包", description = "返回最新上传的版本号、公开下载直链与 sha256;空表时字段为 null")
public Map<String, Object> latestVersion() {
return packageService.latestPackage();
}
@GetMapping("/list")
@Operation(summary = "客户端包版本列表", description = "按上传时间倒序返回最近 50 条,供客户端「指定版本更新」使用")
public Map<String, Object> listVersions() {
return packageService.listPublicPackages();
}
}
@@ -186,8 +186,3 @@ AIIMAGE_ZINIAO_SESSION_TTL_HOURS=2
AIIMAGE_ZINIAO_SHOPS_CACHE_MINUTES=30 AIIMAGE_ZINIAO_SHOPS_CACHE_MINUTES=30
AIIMAGE_ZINIAO_CONNECT_TIMEOUT_SECONDS=5 AIIMAGE_ZINIAO_CONNECT_TIMEOUT_SECONDS=5
AIIMAGE_ZINIAO_READ_TIMEOUT_SECONDS=15 AIIMAGE_ZINIAO_READ_TIMEOUT_SECONDS=15
# 工作台客户端关键词全量同步(POST /api/keyword-share/sync/import)。
# 客户端每行自报真实使用人,服务端只接受名单内姓名并按名单写法落库;名单为空时必须保持 strict=false。
AIIMAGE_KEYWORD_SHARE_SYNC_STRICT=false
AIIMAGE_KEYWORD_SHARE_SYNC_USED_USERS=
@@ -315,12 +315,6 @@ aiimage:
cron: ${AIIMAGE_MODULE_CLEANUP_CRON:0 0 0 * * *} cron: ${AIIMAGE_MODULE_CLEANUP_CRON:0 0 0 * * *}
retention-days: ${AIIMAGE_MODULE_CLEANUP_RETENTION_DAYS:7} retention-days: ${AIIMAGE_MODULE_CLEANUP_RETENTION_DAYS:7}
module-types: ${AIIMAGE_MODULE_CLEANUP_MODULE_TYPES:DEDUPE,SPLIT,CONVERT,DELETE_BRAND,PRODUCT_RISK_RESOLVE,PRICE_TRACK,SHOP_MATCH,PATROL_DELETE,QUERY_ASIN,WITHDRAW,APPEARANCE_PATENT,SIMILAR_ASIN,COLLECT_DATA,JD_SHOP_COLLECT} module-types: ${AIIMAGE_MODULE_CLEANUP_MODULE_TYPES:DEDUPE,SPLIT,CONVERT,DELETE_BRAND,PRODUCT_RISK_RESOLVE,PRICE_TRACK,SHOP_MATCH,PATROL_DELETE,QUERY_ASIN,WITHDRAW,APPEARANCE_PATENT,SIMILAR_ASIN,COLLECT_DATA,JD_SHOP_COLLECT}
# 工作台客户端全量同步(POST /api/keyword-share/sync/import)。客户端每行自报真实使用人,
# 服务端只接受名单内姓名、并统一按名单里那份写法落库(避免全/半角括号把同一个人拆成两个使用者)。
# 名单为空时必须保持 strict=false:否则首次上线会把全部记录静默改写成同步账号名,比现状更糟。
keyword-share-sync:
strict: ${AIIMAGE_KEYWORD_SHARE_SYNC_STRICT:false}
used-users: ${AIIMAGE_KEYWORD_SHARE_SYNC_USED_USERS:}
# 以下为各业务表的保留期清理(2026-09-16 统一补齐):这些表此前只增不删, # 以下为各业务表的保留期清理(2026-09-16 统一补齐):这些表此前只增不删,
# 或只有"读的时候顺手删一行"这类碰运气的清理。全部按天分批删除、带分布式锁单实例执行。 # 或只有"读的时候顺手删一行"这类碰运气的清理。全部按天分批删除、带分布式锁单实例执行。
device-log: device-log:
@@ -100,16 +100,16 @@
) )
</select> </select>
<!-- 后管只读页(Phase 5,v1.4)过滤面:公司(物化列 eq)、商品编码/标题关键词 <!-- 后管只读页(Phase 5,v1.4)过滤面:商品编码/标题关键词(contains LIKE)、类目 eq、
(contains LIKE)、类目 eq、分组 eq、未分类(group_id IS NULL,店铺分类弹窗 分组 eq、未分类(group_id IS NULL,店铺分类弹窗「未分类」范围)、已分类
「未分类」范围)、已分类(group_id IS NOT NULL,页面筛选行「分类状态」档, (group_id IS NOT NULL,页面筛选行「分类状态」档,2026-11-15 客户口径
2026-11-15 客户口径「查询已分类的跟未分类,分类好的可以不显示」)、 「查询已分类的跟未分类,分类好的可以不显示」)、同步起止(datetime 闭区间)。
同步起止(datetime 闭区间)。 公司维过滤随 2026-11-16「删除掉公司 tab,参考品牌数据库」撤掉(数据全平台公共;
行 company_id 列仍是同步来源标记,不构成可见性边界)。
sale_status 筛选随 2026-11-15 客户口径撤掉;店铺名过滤同日客户口径「店铺不需要」 sale_status 筛选随 2026-11-15 客户口径撤掉;店铺名过滤同日客户口径「店铺不需要」
同窗撤掉(前端筛选框与列下线;DB 列本身与详情/回传链不动)。 同窗撤掉(前端筛选框与列下线;DB 列本身与详情/回传链不动)。
全部走 #{} 占位符;offset/limit 必须是服务侧钳制后的值(铁律 15),mapper 不做第二次换算。 --> 全部走 #{} 占位符;offset/limit 必须是服务侧钳制后的值(铁律 15),mapper 不做第二次换算。 -->
<sql id="productConds"> <sql id="productConds">
<if test="companyId != null and companyId &gt; 0">AND p.company_id = #{companyId}</if>
<if test="productCode != null and productCode != ''">AND p.product_code LIKE CONCAT('%', #{productCode}, '%')</if> <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="titleKeyword != null and titleKeyword != ''">AND p.title LIKE CONCAT('%', #{titleKeyword}, '%')</if>
<if test="category != null and category != ''">AND p.category_path = #{category}</if> <if test="category != null and category != ''">AND p.category_path = #{category}</if>
@@ -142,14 +142,13 @@
LIMIT #{offset}, #{limit} LIMIT #{offset}, #{limit}
</select> </select>
<!-- 类目筛选下拉数据源(2026-11-15 用户口径「京麦的类目也要同步过来后台」):本公司已落库行 <!-- 类目筛选下拉数据源(2026-11-15 用户口径「京麦的类目也要同步过来后台」):已落库行
的 DISTINCT category_path(=京麦末级类目名,契约 §2.3 E3)+ 行数。 的 DISTINCT category_path(=京麦末级类目名,契约 §2.3 E3)+ 行数,全平台公共去重
空类目行不进下拉;companyId 为空(超管不选公司=全量)时跨公司去重。 --> (2026-11-16 起公司与后管两侧同口径,无公司维过滤)。空类目行不进下拉。 -->
<select id="selectProductCategories" resultType="com.nanri.aiimage.modules.jd.model.vo.JdProductCategoryVo"> <select id="selectProductCategories" resultType="com.nanri.aiimage.modules.jd.model.vo.JdProductCategoryVo">
SELECT p.category_path AS name, COUNT(*) AS productCount SELECT p.category_path AS name, COUNT(*) AS productCount
FROM biz_jd_product p FROM biz_jd_product p
WHERE p.category_path IS NOT NULL AND p.category_path != '' WHERE p.category_path IS NOT NULL AND p.category_path != ''
<if test="companyId != null">AND p.company_id = #{companyId}</if>
GROUP BY p.category_path GROUP BY p.category_path
ORDER BY p.category_path ORDER BY p.category_path
</select> </select>
@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.nanri.aiimage.modules.keywordshare.mapper.KeywordAddLogMapper">
<insert id="insertBatch">
INSERT INTO keyword_add_log (company_id, country, keyword, user_name, add_time)
VALUES
<foreach collection="rows" item="row" separator=",">
(#{row.companyId}, #{row.country}, #{row.keyword}, #{row.userName}, #{row.addTime})
</foreach>
</insert>
</mapper>
@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.nanri.aiimage.modules.keywordshare.mapper.KeywordDeleteLogMapper">
<insert id="insertBatch">
INSERT INTO keyword_delete_log (company_id, country, keyword, user_name, delete_time)
VALUES
<foreach collection="rows" item="row" separator=",">
(#{row.companyId}, #{row.country}, #{row.keyword}, #{row.userName}, #{row.deleteTime})
</foreach>
</insert>
</mapper>
@@ -1,167 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.nanri.aiimage.modules.keywordshare.mapper.KeywordShareMapper">
<!-- 五国关键词共享(词本体 keyword_share)。动态筛选全部走 #{} 占位符,不做任何字符串拼接;
排序口径对齐桌面版 keyword_share_app.py _filtered_rows_conn(未使用在前、已使用按 used_time 升序)。 -->
<!-- 词表 × 使用状态:usage 行按 (company_id, country, keyword) 三键对上,与桌面版同一口径 -->
<sql id="usageJoin">
keyword_share k
LEFT JOIN keyword_usage u
ON u.company_id = k.company_id
AND u.country = k.country
AND u.keyword = k.keyword
</sql>
<sql id="filterConds">
k.company_id = #{f.companyId}
<if test="f.country != null and f.country != ''">AND k.country = #{f.country}</if>
<if test="f.category != null and f.category != ''">AND k.category = #{f.category}</if>
<if test="f.subCategory != null and f.subCategory != ''">AND k.sub_category = #{f.subCategory}</if>
<if test="f.categoryL3 != null and f.categoryL3 != ''">AND k.category_l3 = #{f.categoryL3}</if>
<if test="f.categoryL4 != null and f.categoryL4 != ''">AND k.category_l4 = #{f.categoryL4}</if>
<if test="f.search != null and f.search != ''">
AND (k.keyword LIKE CONCAT('%', #{f.search}, '%') OR k.chinese LIKE CONCAT('%', #{f.search}, '%'))
</if>
<if test="f.status == 'used'">AND u.country IS NOT NULL</if>
<if test="f.status == 'unused'">AND u.country IS NULL</if>
<if test="f.usedSince != null">AND u.country IS NOT NULL AND u.used_time &gt;= #{f.usedSince}</if>
<if test="f.onlyMine != null and f.onlyMine">AND u.user_name = #{f.userName}</if>
</sql>
<select id="countHit" resultType="long">
SELECT COUNT(*)
FROM <include refid="usageJoin"/>
WHERE <include refid="filterConds"/>
</select>
<select id="selectRows" resultType="com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareRowVo">
<!-- used_user 别名不可省:VO 属性叫 usedUser,驼峰映射只会把 user_name 认成不存在的 userName。 -->
SELECT k.id, k.country, k.keyword, k.chinese, k.category, k.sub_category, k.category_l3, k.category_l4,
(u.country IS NOT NULL) AS used, u.used_time, u.user_name AS used_user
FROM <include refid="usageJoin"/>
WHERE <include refid="filterConds"/>
ORDER BY (u.country IS NULL) ASC, u.used_time ASC
LIMIT #{f.offset}, #{f.limit}
</select>
<!-- AC-19(审计 P1-B2):随机抽词不再 ORDER BY RAND()——那一句给命中集每一行打一个随机数再
filesort 全表,词库越大越慢。改成「按主键升序取一段窗口」:窗口起点由服务层先 count 命中集、
再掷在 [0, total-limit] 上,LIMIT 之前不必排序。服务层拿到窗口后就地洗牌,
页面看到的仍是散着的词。 -->
<select id="selectRandomUnused" resultType="com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareRowVo">
SELECT k.id, k.country, k.keyword, k.chinese, k.category, k.sub_category, k.category_l3, k.category_l4,
(u.country IS NOT NULL) AS used, u.used_time, u.user_name AS used_user
FROM <include refid="usageJoin"/>
WHERE <include refid="filterConds"/>
ORDER BY k.id
LIMIT #{f.limit} OFFSET #{f.offset}
</select>
<select id="countDupKeywords" resultType="long">
SELECT COUNT(*)
FROM (
SELECT keyword FROM keyword_share
WHERE company_id = #{companyId}
GROUP BY keyword
HAVING COUNT(DISTINCT country) &gt; 1
) t
</select>
<select id="selectFilterCountries" resultType="string">
SELECT DISTINCT country
FROM keyword_share
WHERE company_id = #{companyId}
AND country IS NOT NULL AND country != ''
ORDER BY country
</select>
<select id="selectFilterTreeRows" resultType="com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryTreeRow">
SELECT DISTINCT category, sub_category, category_l3, category_l4
FROM keyword_share
WHERE company_id = #{companyId}
AND category IS NOT NULL AND category != ''
ORDER BY category, sub_category, category_l3, category_l4
</select>
<select id="selectCountryCounts" resultType="com.nanri.aiimage.modules.keywordshare.model.dto.KeywordNameCountRow">
SELECT country AS name, COUNT(*) AS count
FROM keyword_share
WHERE company_id = #{companyId}
AND country IS NOT NULL AND country != ''
GROUP BY country
ORDER BY count DESC
</select>
<select id="selectCategoryCounts" resultType="com.nanri.aiimage.modules.keywordshare.model.dto.KeywordNameCountRow">
SELECT category AS name, COUNT(*) AS count
FROM keyword_share
WHERE company_id = #{companyId}
AND category IS NOT NULL AND category != ''
GROUP BY category
ORDER BY count DESC
</select>
<select id="selectSubCategoryCounts" resultType="com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryCountRow">
SELECT category, sub_category AS name, COUNT(*) AS count
FROM keyword_share
WHERE company_id = #{companyId}
AND category IS NOT NULL AND category != ''
GROUP BY category, sub_category
ORDER BY category, count DESC
</select>
<select id="selectCategoryL3Counts" resultType="com.nanri.aiimage.modules.keywordshare.model.dto.KeywordCategoryL3CountRow">
SELECT category, sub_category, category_l3 AS name, COUNT(*) AS count
FROM keyword_share
WHERE company_id = #{companyId}
AND category IS NOT NULL AND category != ''
GROUP BY category, sub_category, category_l3
ORDER BY category, count DESC
</select>
<select id="selectExistingKeywords" resultType="com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareKey">
SELECT country, keyword
FROM keyword_share
WHERE company_id = #{companyId}
AND (country, keyword) IN
<foreach collection="keys" item="key" open="(" separator="," close=")">
(#{key.country}, #{key.keyword})
</foreach>
</select>
<insert id="insertBatchIgnore">
INSERT IGNORE INTO keyword_share
(country, keyword, chinese, ktype, source, category, sub_category, category_l3, category_l4,
user_name, add_time, company_id)
VALUES
<foreach collection="rows" item="row" separator=",">
(#{row.country}, #{row.keyword}, #{row.chinese}, #{row.ktype}, #{row.source}, #{row.category},
#{row.subCategory}, #{row.categoryL3}, #{row.categoryL4}, #{row.userName}, #{row.addTime}, #{row.companyId})
</foreach>
</insert>
<!-- 客户端全量同步专用 UPSERT。与 insertBatchIgnore 的分工:那条只补新词、重复行静默跳过;
这条要把客户端本地那份「四级类目」写进已存在的行——add() 从不设类目,主库存量行的类目是空的。
命中 uk_comp_cw 时只覆盖非空值(COALESCE(NULLIF(...))):客户端是四级类目的唯一权威源,
但一次不带类目的同步不该把已导入的类目永久打回空串,所以「主动清空」不走这条路。
user_name/add_time(添加人与添加时间)在更新分支一律不动:那是历史归属,不由同步改写。 -->
<insert id="upsertBatchFromSync">
INSERT INTO keyword_share
(country, keyword, chinese, ktype, source, category, sub_category, category_l3, category_l4,
user_name, add_time, company_id)
VALUES
<foreach collection="rows" item="row" separator=",">
(#{row.country}, #{row.keyword}, #{row.chinese}, #{row.ktype}, #{row.source}, #{row.category},
#{row.subCategory}, #{row.categoryL3}, #{row.categoryL4}, #{row.userName}, #{row.addTime}, #{row.companyId})
</foreach>
ON DUPLICATE KEY UPDATE
chinese = COALESCE(NULLIF(VALUES(chinese), ''), chinese),
ktype = COALESCE(NULLIF(VALUES(ktype), ''), ktype),
source = COALESCE(NULLIF(VALUES(source), ''), source),
category = COALESCE(NULLIF(VALUES(category), ''), category),
sub_category = COALESCE(NULLIF(VALUES(sub_category), ''), sub_category),
category_l3 = COALESCE(NULLIF(VALUES(category_l3), ''), category_l3),
category_l4 = COALESCE(NULLIF(VALUES(category_l4), ''), category_l4)
</insert>
</mapper>
@@ -1,23 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.nanri.aiimage.modules.keywordshare.mapper.KeywordUsageMapper">
<!-- 使用状态批量写:UPSERT 语义对齐桌面版 ShareSync.mark(ON DUPLICATE KEY UPDATE),
唯一键 uk_comp_cw(company_id, country, keyword) 冲突即刷新使用者与时间,天然幂等。 -->
<insert id="upsertBatch">
INSERT INTO keyword_usage (company_id, country, keyword, user_name, used_time)
VALUES
<foreach collection="rows" item="row" separator=",">
(#{row.companyId}, #{row.country}, #{row.keyword}, #{row.userName}, #{row.usedTime})
</foreach>
ON DUPLICATE KEY UPDATE user_name = VALUES(user_name), used_time = VALUES(used_time)
</insert>
<delete id="deleteBatch">
DELETE FROM keyword_usage
WHERE company_id = #{companyId}
AND (country, keyword) IN
<foreach collection="keys" item="key" open="(" separator="," close=")">
(#{key.country}, #{key.keyword})
</foreach>
</delete>
</mapper>
@@ -94,7 +94,9 @@ class MigratedSqlEquivalenceTest {
// 113 → 114:2026-11-15 商品上架配额计数(b9b66bcb)在 JdProductMapper 新写 1 条只读 select // 113 → 114:2026-11-15 商品上架配额计数(b9b66bcb)在 JdProductMapper 新写 1 条只读 select
//(countByUserIds,按 owner uid 集计 biz_jd_product 行数),逐条点名进 NOT_MIGRATED。 //(countByUserIds,按 owner uid 集计 biz_jd_product 行数),逐条点名进 NOT_MIGRATED。
// 该笔当时只点编译没跑整量、两处账本都漏记,2026-11-15 发版前整量抓到补记。 // 该笔当时只点编译没跑整量、两处账本都漏记,2026-11-15 发版前整量抓到补记。
private static final int XML_SELECT_TOTAL = 114; // 114 → 103:keywordshare 模块整体下线(Project-Slimming 第三轮:6.4 天访问日志零流量、
// 四树零引用、V165 已撤菜单),随删 11 条 select 与下方 NOT_MIGRATED 的 12 条点名。
private static final int XML_SELECT_TOTAL = 103;
/** /**
* 不是「从注解搬过来」的语句:注解时代没有原文可对撞,等价性这支只能跳过它们。 * 不是「从注解搬过来」的语句:注解时代没有原文可对撞,等价性这支只能跳过它们。
@@ -112,21 +114,6 @@ class MigratedSqlEquivalenceTest {
"UserSecretUsageMapper#addTokens", "UserSecretUsageMapper#addTokens",
// 失败任务重试:INSERT ... SELECT 复制采集明细行,非注解迁移件。 // 失败任务重试:INSERT ... SELECT 复制采集明细行,非注解迁移件。
"CollectDataItemMapper#copyItemsForRetry", "CollectDataItemMapper#copyItemsForRetry",
// keywordshare 模块(五国关键词共享网页化,2026-10-23)新写 11 条 select。
"KeywordShareMapper#countHit",
"KeywordShareMapper#selectRows",
"KeywordShareMapper#selectRandomUnused",
"KeywordShareMapper#countDupKeywords",
"KeywordShareMapper#selectFilterCountries",
"KeywordShareMapper#selectFilterTreeRows",
"KeywordShareMapper#selectCountryCounts",
"KeywordShareMapper#selectCategoryCounts",
"KeywordShareMapper#selectSubCategoryCounts",
"KeywordShareMapper#selectCategoryL3Counts",
"KeywordShareMapper#selectExistingKeywords",
// 工作台客户端全量同步新写的词本体 UPSERT:注解时代没有原文可对撞,按新写语句点名留痕。
// 它是 insert 不是 select,故 XML_SELECT_TOTAL 不随之变。
"KeywordShareMapper#upsertBatchFromSync",
// brandgating 模块(品牌Gating库并入管理后台,2026-10-23)新写 8 条 select。 // brandgating 模块(品牌Gating库并入管理后台,2026-10-23)新写 8 条 select。
"BrandGatingMapper#countByFilter", "BrandGatingMapper#countByFilter",
"BrandGatingMapper#selectRows", "BrandGatingMapper#selectRows",
@@ -128,7 +128,10 @@ class SqlLayeringConventionTest {
//(countByUserIds,按 owner uid 集计 biz_jd_product 行数,JdPublishQuotaService 配额原语), //(countByUserIds,按 owner uid 集计 biz_jd_product 行数,JdPublishQuotaService 配额原语),
// 全部新写,非迁移语句。该笔当时只点编译没跑整量、两处账本都漏记,2026-11-15 发版前 // 全部新写,非迁移语句。该笔当时只点编译没跑整量、两处账本都漏记,2026-11-15 发版前
// 整量抓到补记(同轮 MigratedSqlEquivalenceTest.XML_SELECT_TOTAL 113 → 114)。 // 整量抓到补记(同轮 MigratedSqlEquivalenceTest.XML_SELECT_TOTAL 113 → 114)。
private static final int XML_STATEMENT_TOTAL = 164; // 164 → 147:keywordshare 模块整体下线(Project-Slimming 第三轮:6.4 天访问日志零流量、
// 四树零引用、V165 已撤菜单),4 份 XML 17 条语句(11 select + 4 insert + 1 delete)随删;
// 同轮 MigratedSqlEquivalenceTest.XML_SELECT_TOTAL 114 → 103、NOT_MIGRATED 摘掉 12 条点名。
private static final int XML_STATEMENT_TOTAL = 147;
/** /**
* wrapper 里夹带函数级 SQL 的现状("这不是简单单表"的证据),文件名 → 条数: * wrapper 里夹带函数级 SQL 的现状("这不是简单单表"的证据),文件名 → 条数:
@@ -22,7 +22,7 @@ import static org.mockito.Mockito.when;
* 兜底鉴权过滤器单测:非受保护路径放行、OPTIONS/豁免前缀放行、 * 兜底鉴权过滤器单测:非受保护路径放行、OPTIONS/豁免前缀放行、
* 匿名拒绝返回与全局一致的 401 体、紧急开关可整体关闭。 * 匿名拒绝返回与全局一致的 401 体、紧急开关可整体关闭。
* *
* <p>/debug/** 于 2026-09-11 纳入保护范围,对应用例见本类后半部分。 * <p>/debug/** 用例随 debug 控制器整体下线一并移除(Project-Slimming 第三轮,2026-11-16)。
*/ */
class AdminApiGuardFilterTest { class AdminApiGuardFilterTest {
@@ -178,84 +178,13 @@ class AdminApiGuardFilterTest {
assertThat(chain.getRequest()).isNotNull(); assertThat(chain.getRequest()).isNotNull();
} }
// ---- /debug/** 纳入保护(2026-09-11)----
// 背景:两个 debug 控制器都没有方法级鉴权,而主机A 18080 公网直连、主机B nginx location /
// 全量反代 Java,导致匿名即可调通(其中 run-stale-finalize 是强制收尾指定 task 的写操作)。
@Test
void anonymousDebugWriteEndpointRejected() throws Exception {
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
when(authSupport.requireUserOrInternal(any()))
.thenThrow(new BusinessException(401, "未登录"));
AdminApiGuardFilter filter = newFilter(authSupport, true, "");
MockHttpServletRequest request =
new MockHttpServletRequest("POST", "/debug/task-recovery/run-stale-finalize");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
JsonNode body = objectMapper.readTree(response.getContentAsString());
assertThat(body.path("success").asBoolean()).isFalse();
assertThat(body.path("code").asInt()).isEqualTo(401);
assertThat(chain.getRequest()).isNull();
}
@Test
void anonymousDebugRequestInfoRejected() throws Exception {
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
when(authSupport.requireUserOrInternal(any()))
.thenThrow(new BusinessException(401, "未登录"));
AdminApiGuardFilter filter = newFilter(authSupport, true, "");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/debug/request-info");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertThat(chain.getRequest()).isNull();
assertThat(response.getContentAsString()).contains("401");
}
@Test
void debugEndpointStillReachableWithInternalToken() throws Exception {
// 应急调用方(run-stale-finalize 是文档指定的线上排障工具)带 X-Internal-Token 仍可直达
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
when(authSupport.isTrustedInternalToken(any())).thenReturn(true);
AdminApiGuardFilter filter = newFilter(authSupport, true, "");
MockHttpServletRequest request =
new MockHttpServletRequest("POST", "/debug/task-recovery/run-stale-finalize");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
verify(authSupport, never()).requireUserOrInternal(any());
assertThat(chain.getRequest()).isNotNull();
assertThat(response.getContentAsString()).isEmpty();
}
@Test
void debugBarePrefixItselfIsGuarded() throws Exception {
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
when(authSupport.requireUserOrInternal(any()))
.thenThrow(new BusinessException(401, "未登录"));
AdminApiGuardFilter filter = newFilter(authSupport, true, "");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/debug");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertThat(chain.getRequest()).isNull();
}
@Test @Test
void similarLookingPathsAreNotSweptIn() throws Exception { void similarLookingPathsAreNotSweptIn() throws Exception {
// 前缀边界:只按整段匹配,/debugging、/debug-tools、/api/adminx 都不应被误纳入 // 前缀边界:只按整段匹配,/api/adminx 不应被误纳入(/debugging、/debug-tools 两条
// 随 /debug 前缀下线一并移除——它们守护的前缀已不存在)
AdminAuthSupport authSupport = mock(AdminAuthSupport.class); AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminApiGuardFilter filter = newFilter(authSupport, true, ""); AdminApiGuardFilter filter = newFilter(authSupport, true, "");
for (String uri : new String[] {"/debugging", "/debug-tools/list", "/api/adminx"}) { for (String uri : new String[] {"/api/adminx"}) {
MockHttpServletRequest request = new MockHttpServletRequest("GET", uri); MockHttpServletRequest request = new MockHttpServletRequest("GET", uri);
MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain(); MockFilterChain chain = new MockFilterChain();
@@ -64,14 +64,14 @@ class ApiGuardCoverageAuditorTest {
void guardedPrefixesCarriesEveryGuardedList() { void guardedPrefixesCarriesEveryGuardedList() {
List<String> guarded = AdminApiGuardFilter.guardedPrefixes(); List<String> guarded = AdminApiGuardFilter.guardedPrefixes();
assertTrue(guarded.contains("/api/admin"), "admin 前缀没进自检可见名单"); assertTrue(guarded.contains("/api/admin"), "admin 前缀没进自检可见名单");
assertTrue(guarded.contains("/debug"), "debug 前缀没进自检可见名单");
// 这两组条数是实测基线(2026-10-08:用户态 15 条、自助 6 条)。 // 这两组条数是实测基线(2026-10-08:用户态 15 条、自助 6 条)。
// 只钉"contains 某条"的话,从数组里删掉一整段都可能不红,所以钉总数。 // 只钉"contains 某条"的话,从数组里删掉一整段都可能不红,所以钉总数。
// 2026-10-24 自助 6 → 7:cost-guard 的 status/resume 两个端点 uid 只从 JWT 取, // 2026-10-24 自助 6 → 7:cost-guard 的 status/resume 两个端点 uid 只从 JWT 取,
// 匿名既读不到状态也不该能解除暂停闸,所以进无条件名单而不是登记成「方法内自校验」。 // 匿名既读不到状态也不该能解除暂停闸,所以进无条件名单而不是登记成「方法内自校验」。
// 2026-10-29 用户态 15 → 16:采集路由读取口 /api/collect-routing 新建即入名单。 // 2026-10-29 用户态 15 → 16:采集路由读取口 /api/collect-routing 新建即入名单。
assertEquals(24, count(guarded, "/api/"), () -> "以 /api/ 开头的守卫前缀数变了(基线 24 = admin 1 + 用户态 16 + 自助 7):" + guarded); assertEquals(24, count(guarded, "/api/"), () -> "以 /api/ 开头的守卫前缀数变了(基线 24 = admin 1 + 用户态 16 + 自助 7):" + guarded);
assertEquals(25, guarded.size(), "守卫前缀总数变了(24 条 /api/ + /debug):" + guarded); // 2026-11-16 /debug 前缀随 debug 控制器整体下线(Project-Slimming 第三轮)后,总名单 = 24 条 /api/。
assertEquals(24, guarded.size(), "守卫前缀总数变了(24 条 /api/):" + guarded);
assertTrue(guarded.contains("/api/publish"), "2026-10-07 补的上架前缀不能退回名单外"); assertTrue(guarded.contains("/api/publish"), "2026-10-07 补的上架前缀不能退回名单外");
assertTrue(guarded.contains("/api/tasks"), "心跳/打断前缀不能退回名单外"); assertTrue(guarded.contains("/api/tasks"), "心跳/打断前缀不能退回名单外");
assertTrue(guarded.contains("/api/internal"), "内部端点前缀不能退回名单外"); assertTrue(guarded.contains("/api/internal"), "内部端点前缀不能退回名单外");
@@ -5,7 +5,6 @@ import com.nanri.aiimage.common.api.PageDefaults;
import com.nanri.aiimage.common.exception.BusinessException; import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.model.entity.AdminUserEntity; import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper; import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper; import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
import com.nanri.aiimage.modules.jd.model.dto.JdProductBatchDeleteRequest; import com.nanri.aiimage.modules.jd.model.dto.JdProductBatchDeleteRequest;
@@ -48,16 +47,16 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** /**
* v1.4 Phase 5:后管「京东数据库」只读接口(列表/详情)与分组管理入口。 * v1.4 Phase 5:后管「京东数据库」只读接口(列表/详情)与分组管理入口。
* *
* <p>结构判据(照 {@code AdminAppearancePatentCleanItemsControllerTest} 双形态): * <p>结构判据(照 {@code AdminAppearancePatentCleanItemsControllerTest} 双形态):
* 端点只读、鉴权 seam、公司口径(读侧只剩超管筛选 superAdminScopedCompanyId,公共库不走 * 端点只读、鉴权 seam、公司口径(2026-11-16 用户定案「删除掉公司 tab,参考品牌数据库」=
* readCompanyIdOrOwn)、snake 参数带默认值、SQL 只落 XML; * 品牌库 2026-10-06 先例同形:company_id 请求参数与 superAdminScopedCompanyId 谓词整批摘除,
* 行为样本:mock HttpServletRequest 把 company 参数交给 superAdminScopedCompanyId 并装进 200 信封、 * 读侧零公司维度、反向钉住防回潜)、snake 参数带默认值、SQL 只落 XML;
* 行为样本:mock HttpServletRequest 走 requireJdAccess 鉴权正门并把结果装进 200 信封、
* 分页钳制 offset/limit(page=Long.MAX_VALUE 不得负,铁律 15)、详情 attr_json * 分页钳制 offset/limit(page=Long.MAX_VALUE 不得负,铁律 15)、详情 attr_json
* tabs→attrGroups 解析与非法形状兜底(AC-7)。 * tabs→attrGroups 解析与非法形状兜底(AC-7)。
* 导出端点与 sale_status 筛选参数已随 2026-11-15 客户口径整段下线(反向钉住防回潜)。</p> * 导出端点与 sale_status 筛选参数已随 2026-11-15 客户口径整段下线(反向钉住防回潜)。</p>
@@ -114,23 +113,30 @@ class AdminJdProductControllerTest {
} }
@Test @Test
void 公司口径只剩超管筛选_公共库不走readCompanyIdOrOwn() throws IOException { void 读侧零公司维度_公司tab口径整批摘除() throws IOException {
String source = stripComments(Files.readString(CONTROLLER)); String source = stripComments(Files.readString(CONTROLLER));
assertTrue(source.contains("DataReadScope"), "公司维度唯一出口是 DataReadScope"); // 2026-11-16 用户定案「删除掉公司 tab,参考品牌数据库」=品牌库 2026-10-06 先例同形:
assertTrue(source.contains("superAdminScopedCompanyId"), // 摘的不只是 tab——company_id 参数与 superAdminScopedCompanyId 谓词一起撤,
"读侧(列表/类目)必须走 superAdminScopedCompanyId:只有站点超管显式传 company_id 才收窄" // 数据全平台公共(行 company_id 列仍是同步来源标记,不构成可见性边界)。
+ "(公司 tab 筛选管理员),其余请求全量(2026-11-15 用户定案「京东数据库不区分公司、属于公共的」)"); assertFalse(source.contains("company_id"),
"company_id 请求参数必须已删除,不得回潜(2026-11-16 随公司 tab 整批摘除)");
assertFalse(source.contains("superAdminScopedCompanyId"),
"superAdminScopedCompanyId 谓词必须已删除:第五道门(超管显式收窄)对京东只读面不再生效");
assertFalse(source.contains("readCompanyIdOrOwn"), assertFalse(source.contains("readCompanyIdOrOwn"),
"不得走 readCompanyIdOrOwn:它对非超管强制本公司,公共库对每一家管理员都是同一份全量"); "不得走 readCompanyIdOrOwn:全平台公共数据对每一家管理员都是同一份全量,无公司可见性边界");
assertFalse(source.contains("DataReadScope"),
"DataReadScope 不得再注入京东只读控制器(公司收口已随 2026-11-16 摘除)");
} }
@Test @Test
void 分页参数snake且带默认值() throws IOException { void 分页参数snake且带默认值() throws IOException {
String source = stripComments(Files.readString(CONTROLLER)); String source = stripComments(Files.readString(CONTROLLER));
for (String param : List.of("page_size", "product_code", "title_keyword", for (String param : List.of("page_size", "product_code", "title_keyword",
"group_id", "ungrouped", "grouped", "synced_from", "synced_to", "company_id")) { "group_id", "ungrouped", "grouped", "synced_from", "synced_to")) {
assertTrue(source.contains(param), "查询参数必须 snake_case:" + param); assertTrue(source.contains(param), "查询参数必须 snake_case:" + param);
} }
// company_id 参数已随 2026-11-16「删除掉公司 tab」整批摘除(读侧零公司维度支另有反向钉)。
assertFalse(source.contains("company_id"), "company_id 请求参数必须已删除,不得回潜");
// 商品状态筛选框已随 2026-11-15 客户口径从前端下线 ⇒ 服务端同名参数一起撤(反向钉住防回潜)。 // 商品状态筛选框已随 2026-11-15 客户口径从前端下线 ⇒ 服务端同名参数一起撤(反向钉住防回潜)。
assertFalse(source.contains("\"sale_status\""), "sale_status 筛选参数必须已删除,不得回潜"); assertFalse(source.contains("\"sale_status\""), "sale_status 筛选参数必须已删除,不得回潜");
// 店铺筛选同日客户口径「店铺不需要」下线 ⇒ shop_name 参数同窗撤(反向钉住防回潜)。 // 店铺筛选同日客户口径「店铺不需要」下线 ⇒ shop_name 参数同窗撤(反向钉住防回潜)。
@@ -177,64 +183,58 @@ class AdminJdProductControllerTest {
// ===================== 行为样本 ===================== // ===================== 行为样本 =====================
@Test @Test
void 控制器把公司参数交给superAdminScopedCompanyId并把结果装进200信封() { void 控制器列表走requireJdAccess正门并把查询结果装进200信封() {
JdProductQueryService queryService = mock(JdProductQueryService.class); JdProductQueryService queryService = mock(JdProductQueryService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class); AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class); PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
AdminJdProductController controller = new AdminJdProductController( AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport, queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport,
permissionMenuService, dataReadScope); permissionMenuService);
AdminUserEntity operator = new AdminUserEntity(); AdminUserEntity operator = new AdminUserEntity();
operator.setId(7L); operator.setId(7L);
HttpServletRequest request = mock(HttpServletRequest.class); HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator); when(authSupport.requireUser(request)).thenReturn(operator);
when(authSupport.currentRole(operator)).thenReturn("super_admin"); when(authSupport.currentRole(operator)).thenReturn("super_admin");
// 超管显式传 company_id=5 ⇒ 超管筛选把 5 交出来(不传时给 null=全量,同一行为样本家族)。
when(dataReadScope.superAdminScopedCompanyId(operator, 5L)).thenReturn(5L);
JdProductPageVo pageVo = new JdProductPageVo(); JdProductPageVo pageVo = new JdProductPageVo();
pageVo.setItems(List.of()); pageVo.setItems(List.of());
pageVo.setTotal(0L); pageVo.setTotal(0L);
pageVo.setPage(1L); pageVo.setPage(1L);
pageVo.setPageSize((long) PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT); pageVo.setPageSize((long) PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT);
when(queryService.page(1L, 20L, 5L, null, null, null, null, null, null, null, null)).thenReturn(pageVo); when(queryService.page(1L, 20L, null, null, null, null, null, null, null, null)).thenReturn(pageVo);
// 2026-11-16 起请求面没有 company_id:任何授权身份看到的都是同一份全量。
ApiResponse<JdProductPageVo> response = controller.page(1L, 20L, null, null, null, null, null, ApiResponse<JdProductPageVo> response = controller.page(1L, 20L, null, null, null, null, null,
null, null, null, 5L, request); null, null, null, request);
verify(dataReadScope).superAdminScopedCompanyId(operator, 5L); verify(queryService).page(1L, 20L, null, null, null, null, null, null, null, null);
verify(queryService).page(1L, 20L, 5L, null, null, null, null, null, null, null, null);
assertEquals(Boolean.TRUE, response.isSuccess(), "拒绝走 403 业务码,放行必须是 success 信封(B80-03)"); assertEquals(Boolean.TRUE, response.isSuccess(), "拒绝走 403 业务码,放行必须是 success 信封(B80-03)");
assertEquals(pageVo, response.getData()); assertEquals(pageVo, response.getData());
} }
@Test @Test
void 类目下拉端点走同一超管筛选口径并回选项集() { void 类目下拉端点走同一鉴权正门并回全平台选项集() {
JdProductQueryService queryService = mock(JdProductQueryService.class); JdProductQueryService queryService = mock(JdProductQueryService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class); AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
AdminJdProductController controller = new AdminJdProductController( AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport, queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport,
mock(PermissionMenuService.class), dataReadScope); mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity(); AdminUserEntity operator = new AdminUserEntity();
operator.setId(7L); operator.setId(7L);
HttpServletRequest request = mock(HttpServletRequest.class); HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator); when(authSupport.requireUser(request)).thenReturn(operator);
when(authSupport.currentRole(operator)).thenReturn("super_admin"); when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(dataReadScope.superAdminScopedCompanyId(operator, 5L)).thenReturn(5L);
JdProductCategoryVo row = new JdProductCategoryVo(); JdProductCategoryVo row = new JdProductCategoryVo();
row.setName("艺考形体服"); row.setName("艺考形体服");
row.setProductCount(85L); row.setProductCount(85L);
when(queryService.categories(5L)).thenReturn(List.of(row)); when(queryService.categories()).thenReturn(List.of(row));
ApiResponse<List<JdProductCategoryVo>> response = controller.categories(5L, request); ApiResponse<List<JdProductCategoryVo>> response = controller.categories(request);
verify(dataReadScope).superAdminScopedCompanyId(operator, 5L); verify(queryService).categories();
verify(queryService).categories(5L);
assertEquals(Boolean.TRUE, response.isSuccess(), "类目下拉与列表同一鉴权正门(200 信封)"); assertEquals(Boolean.TRUE, response.isSuccess(), "类目下拉与列表同一鉴权正门(200 信封)");
assertEquals("艺考形体服", response.getData().get(0).getName(), "选项=已落库行的末级类目名"); assertEquals("艺考形体服", response.getData().get(0).getName(), "选项=已落库行的末级类目名(全平台去重)");
assertEquals(85L, response.getData().get(0).getProductCount()); assertEquals(85L, response.getData().get(0).getProductCount());
} }
@@ -242,10 +242,9 @@ class AdminJdProductControllerTest {
void 控制器详情走同一鉴权正门并回详情且不问公司() { void 控制器详情走同一鉴权正门并回详情且不问公司() {
JdProductQueryService queryService = mock(JdProductQueryService.class); JdProductQueryService queryService = mock(JdProductQueryService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class); AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
AdminJdProductController controller = new AdminJdProductController( AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport, queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class), authSupport,
mock(PermissionMenuService.class), dataReadScope); mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity(); AdminUserEntity operator = new AdminUserEntity();
operator.setId(7L); operator.setId(7L);
@@ -258,8 +257,7 @@ class AdminJdProductControllerTest {
ApiResponse<JdProductDetailVo> response = controller.detail(11L, request); ApiResponse<JdProductDetailVo> response = controller.detail(11L, request);
// 公共库详情没有公司维度:DataReadScope 不参与(防有人把公司收口接回来)。 // 公共库详情没有公司维度(DataReadScope 反向钉在结构判据支,2026-11-16 已整批摘除)。
verifyNoInteractions(dataReadScope);
verify(queryService).detail(11L); verify(queryService).detail(11L);
assertEquals(Boolean.TRUE, response.isSuccess()); assertEquals(Boolean.TRUE, response.isSuccess());
assertEquals(detailVo, response.getData()); assertEquals(detailVo, response.getData());
@@ -270,10 +268,9 @@ class AdminJdProductControllerTest {
JdProductQueryService queryService = mock(JdProductQueryService.class); JdProductQueryService queryService = mock(JdProductQueryService.class);
JdProductDeleteService deleteService = mock(JdProductDeleteService.class); JdProductDeleteService deleteService = mock(JdProductDeleteService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class); AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
AdminJdProductController controller = new AdminJdProductController( AdminJdProductController controller = new AdminJdProductController(
queryService, deleteService, mock(JdProductUpdateService.class), authSupport, queryService, deleteService, mock(JdProductUpdateService.class), authSupport,
mock(PermissionMenuService.class), dataReadScope); mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity(); AdminUserEntity operator = new AdminUserEntity();
operator.setId(7L); operator.setId(7L);
@@ -288,8 +285,7 @@ class AdminJdProductControllerTest {
ApiResponse<JdProductDeleteVo> response = controller.delete(11L, request); ApiResponse<JdProductDeleteVo> response = controller.delete(11L, request);
// 公共库写侧没有公司维度:不收 company_id、DataReadScope 不参与。 // 公共库写侧没有公司维度(结构判据支反向钉 company_id/DataReadScope 不得回流)。
verifyNoInteractions(dataReadScope);
verify(deleteService).delete(List.of(11L)); verify(deleteService).delete(List.of(11L));
assertEquals(Boolean.TRUE, response.isSuccess()); assertEquals(Boolean.TRUE, response.isSuccess());
assertEquals(9, response.getData().getObjectsDeleted()); assertEquals(9, response.getData().getObjectsDeleted());
@@ -300,10 +296,9 @@ class AdminJdProductControllerTest {
JdProductQueryService queryService = mock(JdProductQueryService.class); JdProductQueryService queryService = mock(JdProductQueryService.class);
JdProductDeleteService deleteService = mock(JdProductDeleteService.class); JdProductDeleteService deleteService = mock(JdProductDeleteService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class); AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
AdminJdProductController controller = new AdminJdProductController( AdminJdProductController controller = new AdminJdProductController(
queryService, deleteService, mock(JdProductUpdateService.class), authSupport, queryService, deleteService, mock(JdProductUpdateService.class), authSupport,
mock(PermissionMenuService.class), dataReadScope); mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity(); AdminUserEntity operator = new AdminUserEntity();
operator.setId(7L); operator.setId(7L);
@@ -326,23 +321,23 @@ class AdminJdProductControllerTest {
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class), JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class), mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class)); mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(1L); when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(1L);
// page=0 / size=null ⇒ 归一为第 1 页、默认 20 条;offset = 0。 // page=0 / size=null ⇒ 归一为第 1 页、默认 20 条;offset = 0。
service.page(0L, null, null, null, null, null, null, null, null, null, null); service.page(0L, null, null, null, null, null, null, null, null, null);
ArgumentCaptor<Long> offset = ArgumentCaptor.forClass(Long.class); ArgumentCaptor<Long> offset = ArgumentCaptor.forClass(Long.class);
ArgumentCaptor<Integer> limit = ArgumentCaptor.forClass(Integer.class); ArgumentCaptor<Integer> limit = ArgumentCaptor.forClass(Integer.class);
verify(mapper).selectProductPage(isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), verify(mapper).selectProductPage(isNull(), isNull(), isNull(), isNull(), isNull(), isNull(),
isNull(), isNull(), isNull(), offset.capture(), limit.capture()); isNull(), isNull(), offset.capture(), limit.capture());
assertEquals(0L, offset.getValue()); assertEquals(0L, offset.getValue());
assertEquals(PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT, limit.getValue()); assertEquals(PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT, limit.getValue());
// page=Long.MAX_VALUE / size=500 ⇒ 钳到 10_000 页、100 条;乘积 999_900 不得变负(铁律 15)。 // page=Long.MAX_VALUE / size=500 ⇒ 钳到 10_000 页、100 条;乘积 999_900 不得变负(铁律 15)。
service.page(Long.MAX_VALUE, 500L, null, null, null, null, null, null, null, null, null); service.page(Long.MAX_VALUE, 500L, null, null, null, null, null, null, null, null);
ArgumentCaptor<Long> offsetMax = ArgumentCaptor.forClass(Long.class); ArgumentCaptor<Long> offsetMax = ArgumentCaptor.forClass(Long.class);
ArgumentCaptor<Integer> limitMax = ArgumentCaptor.forClass(Integer.class); ArgumentCaptor<Integer> limitMax = ArgumentCaptor.forClass(Integer.class);
verify(mapper, times(2)).selectProductPage(any(), any(), any(), any(), any(), any(), verify(mapper, times(2)).selectProductPage(any(), any(), any(), any(), any(), any(),
any(), any(), any(), offsetMax.capture(), limitMax.capture()); any(), any(), offsetMax.capture(), limitMax.capture());
assertEquals(999_900L, offsetMax.getValue(), "(page-1)*page_size 最大 999_900,钳制后不得溢出变负"); assertEquals(999_900L, offsetMax.getValue(), "(page-1)*page_size 最大 999_900,钳制后不得溢出变负");
assertEquals(100, limitMax.getValue()); assertEquals(100, limitMax.getValue());
} }
@@ -356,9 +351,9 @@ class AdminJdProductControllerTest {
LocalDateTime from = LocalDateTime.of(2026, 11, 14, 12, 0); LocalDateTime from = LocalDateTime.of(2026, 11, 14, 12, 0);
LocalDateTime to = LocalDateTime.of(2026, 11, 14, 8, 0); LocalDateTime to = LocalDateTime.of(2026, 11, 14, 8, 0);
BusinessException ex = assertThrows(BusinessException.class, BusinessException ex = assertThrows(BusinessException.class,
() -> service.page(1L, 20L, null, null, null, null, null, null, null, from, to)); () -> service.page(1L, 20L, null, null, null, null, null, null, from, to));
assertTrue(ex.getMessage().contains("开始时间不能晚于结束时间"), "倒挂时间按业务异常拒绝"); assertTrue(ex.getMessage().contains("开始时间不能晚于结束时间"), "倒挂时间按业务异常拒绝");
verify(mapper, never()).countProducts(any(), any(), any(), any(), any(), any(), any(), any(), any()); verify(mapper, never()).countProducts(any(), any(), any(), any(), any(), any(), any(), any());
} }
@Test @Test
@@ -367,37 +362,37 @@ class AdminJdProductControllerTest {
JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class), JdProductQueryService service = new JdProductQueryService(mapper, mock(JdProductImageMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class), mock(com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper.class),
mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class)); mock(com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper.class));
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(0L); when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(0L);
// 超管显式传 5 ⇒ 按公司 5 筛(收窄);groupId ≤0 按没选分组处理;文本两侧空白剥掉。 // groupId ≤0 按没选分组处理;文本两侧空白剥掉。
// 类目(京麦末级类目名)走同一过滤面:传值原样直传、空白归 null。 // 类目(京麦末级类目名)走同一过滤面:传值原样直传、空白归 null。
service.page(1L, 20L, 5L, " SKU-1 ", " 连衣裙 ", " 艺考形体服 ", 0L, null, null, null, null); service.page(1L, 20L, " SKU-1 ", " 连衣裙 ", " 艺考形体服 ", 0L, null, null, null, null);
verify(mapper).countProducts(eq(5L), eq("SKU-1"), eq("连衣裙"), verify(mapper).countProducts(eq("SKU-1"), eq("连衣裙"),
eq("艺考形体服"), isNull(), isNull(), isNull(), isNull(), isNull()); eq("艺考形体服"), isNull(), isNull(), isNull(), isNull(), isNull());
// 全量(scopedCompanyId=null)⇒ companyId 不过滤。 // 全量口径(2026-11-16 起读侧无公司维)⇒ 过滤面全 null。
service.page(1L, 20L, null, null, null, null, null, null, null, null, null); service.page(1L, 20L, null, null, null, null, null, null, null, null);
verify(mapper).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(), verify(mapper).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(),
isNull(), isNull(), isNull(), isNull()); isNull(), isNull(), isNull());
// 未分类范围(店铺分类弹窗「未分类」页签):ungrouped=true 原样下推到 SQL 侧。 // 未分类范围(店铺分类弹窗「未分类」页签):ungrouped=true 原样下推到 SQL 侧。
service.page(1L, 20L, null, null, null, null, null, Boolean.TRUE, null, null, null); service.page(1L, 20L, null, null, null, null, Boolean.TRUE, null, null, null);
verify(mapper).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(), verify(mapper).countProducts(isNull(), isNull(), isNull(), isNull(), eq(Boolean.TRUE),
eq(Boolean.TRUE), isNull(), isNull(), isNull()); isNull(), isNull(), isNull());
// ungrouped=false / 缺省按不过滤处理(Filter 归一成 null,不进 IS NULL 分支); // ungrouped=false / 缺省按不过滤处理(Filter 归一成 null,不进 IS NULL 分支);
// 与②「全量」那发同形状,累计 2 次。 // 与②「全量」那发同形状,累计 2 次。
service.page(1L, 20L, null, null, null, null, null, Boolean.FALSE, null, null, null); service.page(1L, 20L, null, null, null, null, Boolean.FALSE, null, null, null);
verify(mapper, times(2)).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(), verify(mapper, times(2)).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(),
isNull(), isNull(), isNull(), isNull()); isNull(), isNull(), isNull());
// 已分类档(页面筛选行「分类状态」=已分类,2026-11-15 客户口径「分类好的可以不显示」反选): // 已分类档(页面筛选行「分类状态」=已分类,2026-11-15 客户口径「分类好的可以不显示」反选):
// grouped=true 原样下推到 SQL 侧(group_id IS NOT NULL),ungrouped 不动。 // grouped=true 原样下推到 SQL 侧(group_id IS NOT NULL),ungrouped 不动。
service.page(1L, 20L, null, null, null, null, null, null, Boolean.TRUE, null, null); service.page(1L, 20L, null, null, null, null, null, Boolean.TRUE, null, null);
verify(mapper).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(), verify(mapper).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(),
isNull(), eq(Boolean.TRUE), isNull(), isNull()); eq(Boolean.TRUE), isNull(), isNull());
// grouped=false / 缺省同口径归一成 null(不进 IS NOT NULL 分支);与②「全量」累计 3 次。 // grouped=false / 缺省同口径归一成 null(不进 IS NOT NULL 分支);与②「全量」累计 3 次。
service.page(1L, 20L, null, null, null, null, null, null, Boolean.FALSE, null, null); service.page(1L, 20L, null, null, null, null, null, Boolean.FALSE, null, null);
verify(mapper, times(3)).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(), verify(mapper, times(3)).countProducts(isNull(), isNull(), isNull(), isNull(), isNull(),
isNull(), isNull(), isNull(), isNull()); isNull(), isNull(), isNull());
} }
@Test @Test
@@ -405,10 +400,9 @@ class AdminJdProductControllerTest {
JdProductQueryService queryService = mock(JdProductQueryService.class); JdProductQueryService queryService = mock(JdProductQueryService.class);
JdProductUpdateService updateService = mock(JdProductUpdateService.class); JdProductUpdateService updateService = mock(JdProductUpdateService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class); AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
AdminJdProductController controller = new AdminJdProductController( AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), updateService, authSupport, queryService, mock(JdProductDeleteService.class), updateService, authSupport,
mock(PermissionMenuService.class), dataReadScope); mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity(); AdminUserEntity operator = new AdminUserEntity();
operator.setId(7L); operator.setId(7L);
@@ -423,8 +417,7 @@ class AdminJdProductControllerTest {
body.setGroupId(3L); body.setGroupId(3L);
ApiResponse<Integer> response = controller.batchAssignGroup(body, request); ApiResponse<Integer> response = controller.batchAssignGroup(body, request);
// 公共库写侧没有公司维度:不收 company_id、DataReadScope 不参与。 // 公共库写侧没有公司维度(结构判据支反向钉 company_id/DataReadScope 不得回流)。
verifyNoInteractions(dataReadScope);
verify(updateService).assignGroup(List.of(11L, 12L), 3L); verify(updateService).assignGroup(List.of(11L, 12L), 3L);
assertEquals(Boolean.TRUE, response.isSuccess(), "放行必须是 success 信封(B80-03)"); assertEquals(Boolean.TRUE, response.isSuccess(), "放行必须是 success 信封(B80-03)");
assertEquals(2, response.getData(), "回执=实际更新的行数"); assertEquals(2, response.getData(), "回执=实际更新的行数");
@@ -598,8 +591,8 @@ class AdminJdProductControllerTest {
grouped.setGroupId(3L); grouped.setGroupId(3L);
JdProductEntity missing = productEntity(2L); JdProductEntity missing = productEntity(2L);
missing.setGroupId(99L); missing.setGroupId(99L);
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(2L); when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(2L);
when(mapper.selectProductPage(any(), any(), any(), any(), any(), any(), any(), any(), any(), when(mapper.selectProductPage(any(), any(), any(), any(), any(), any(), any(), any(),
anyLong(), anyInt())).thenReturn(List.of(grouped, missing)); anyLong(), anyInt())).thenReturn(List.of(grouped, missing));
com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity group = com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity group =
new com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity(); new com.nanri.aiimage.modules.jd.model.entity.JdProductGroupEntity();
@@ -607,7 +600,7 @@ class AdminJdProductControllerTest {
group.setName("秋冬款"); group.setName("秋冬款");
when(groupMapper.selectBatchIds(any())).thenReturn(List.of(group)); when(groupMapper.selectBatchIds(any())).thenReturn(List.of(group));
JdProductPageVo vo = service.page(1L, 20L, 5L, null, null, null, null, null, null, null, null); JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null, null, null);
assertEquals("秋冬款", vo.getItems().get(0).getGroupName(), "行集 group_id 一次取齐分组名(无逐行查询)"); assertEquals("秋冬款", vo.getItems().get(0).getGroupName(), "行集 group_id 一次取齐分组名(无逐行查询)");
assertNull(vo.getItems().get(1).getGroupName(), "分组已删=不猜名字(铁律 30),前端展示 -"); assertNull(vo.getItems().get(1).getGroupName(), "分组已删=不猜名字(铁律 30),前端展示 -");
@@ -1,690 +0,0 @@
package com.nanri.aiimage.modules.keywordshare.service;
import com.nanri.aiimage.config.KeywordShareSyncProperties;
import com.nanri.aiimage.modules.keywordshare.mapper.KeywordAddLogMapper;
import com.nanri.aiimage.modules.keywordshare.mapper.KeywordDeleteLogMapper;
import com.nanri.aiimage.modules.keywordshare.mapper.KeywordShareMapper;
import com.nanri.aiimage.modules.keywordshare.mapper.KeywordUsageMapper;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareFilterQuery;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareKey;
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordAddLogEntity;
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordDeleteLogEntity;
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordShareEntity;
import com.nanri.aiimage.modules.keywordshare.model.entity.KeywordUsageEntity;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareAddRequest;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareDeleteRequest;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordShareSyncImportRequest;
import com.nanri.aiimage.modules.keywordshare.model.dto.KeywordUsageBatchRequest;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordSharePageVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareRowVo;
import com.nanri.aiimage.modules.keywordshare.model.vo.KeywordShareSyncResultVo;
import org.junit.jupiter.api.DisplayName;
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.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 五国关键词共享 Service 单测:列表筛选/状态过滤/排序契约、分页与 usedDays 归一化、
* mark 幂等、add 查重跳过 + 留痕 + 自动标记、delete 留痕、random、dup 计数。
*/
@ExtendWith(MockitoExtension.class)
class KeywordShareServiceTest {
private static final Long COMPANY_ID = 7L;
private static final String VIEWER = "阿华";
@Mock
private KeywordShareMapper keywordShareMapper;
@Mock
private KeywordUsageMapper keywordUsageMapper;
@Mock
private KeywordAddLogMapper keywordAddLogMapper;
@Mock
private KeywordDeleteLogMapper keywordDeleteLogMapper;
private KeywordShareService newService() {
return newService(new KeywordShareSyncProperties());
}
private KeywordShareService newService(KeywordShareSyncProperties syncProperties) {
return new KeywordShareService(keywordShareMapper, keywordUsageMapper,
keywordAddLogMapper, keywordDeleteLogMapper, syncProperties);
}
private static KeywordShareSyncProperties rosterOf(boolean strict, String... names) {
KeywordShareSyncProperties properties = new KeywordShareSyncProperties();
properties.setStrict(strict);
properties.setUsedUsers(List.of(names));
return properties;
}
private static KeywordShareRowVo row(long id, String keyword, boolean used, String usedUser) {
KeywordShareRowVo vo = new KeywordShareRowVo();
vo.setId(id);
vo.setCountry("英国");
vo.setKeyword(keyword);
vo.setChinese("翻译" + id);
vo.setUsed(used);
if (used) {
vo.setUsedTime(LocalDateTime.now().minusHours(id));
vo.setUsedUser(usedUser);
}
return vo;
}
// ---------------------------------------------------------------- 列表
@Test
@DisplayName("列表:命中数按用户筛选口径、命中内已使用数单独数一遍、dup 计数进统计条")
void pageComputesHitUsedUnusedAndDup() {
KeywordShareFilterQuery all = new KeywordShareFilterQuery();
all.setCompanyId(COMPANY_ID);
all.setStatus("all");
when(keywordShareMapper.countHit(any(KeywordShareFilterQuery.class))).thenReturn(10L, 4L);
when(keywordShareMapper.selectRows(any(KeywordShareFilterQuery.class))).thenReturn(List.of());
when(keywordShareMapper.countDupKeywords(COMPANY_ID)).thenReturn(3L);
KeywordSharePageVo vo = newService().page(COMPANY_ID, VIEWER, null, null, null, null, null,
null, "all", 0, false, 1L, 200L);
assertThat(vo.getTotal()).isEqualTo(10L);
assertThat(vo.getStats().getHit()).isEqualTo(10L);
assertThat(vo.getStats().getUsed()).isEqualTo(4L);
assertThat(vo.getStats().getUnused()).isEqualTo(6L);
assertThat(vo.getStats().getDup()).isEqualTo(3L);
// 第二次 countHit 是「命中内已使用数」,必须把 status 换成 used、其余条件原样
ArgumentCaptor<KeywordShareFilterQuery> captor = ArgumentCaptor.forClass(KeywordShareFilterQuery.class);
verify(keywordShareMapper, org.mockito.Mockito.times(2)).countHit(captor.capture());
assertThat(captor.getAllValues().get(0).getStatus()).isEqualTo("all");
assertThat(captor.getAllValues().get(1).getStatus()).isEqualTo("used");
assertThat(captor.getAllValues().get(1).getCompanyId()).isEqualTo(COMPANY_ID);
}
@Test
@DisplayName("列表:状态过滤 used/unused 时命中内已/未使用数直接由命中推导,不再多查一遍")
void pageWithActiveStatusFilterDerivesStats() {
when(keywordShareMapper.countHit(any(KeywordShareFilterQuery.class))).thenReturn(6L);
when(keywordShareMapper.selectRows(any(KeywordShareFilterQuery.class))).thenReturn(List.of());
when(keywordShareMapper.countDupKeywords(COMPANY_ID)).thenReturn(0L);
KeywordSharePageVo used = newService().page(COMPANY_ID, VIEWER, null, null, null, null, null,
null, "used", 0, false, 1L, 200L);
assertThat(used.getStats().getHit()).isEqualTo(6L);
assertThat(used.getStats().getUsed()).isEqualTo(6L);
assertThat(used.getStats().getUnused()).isZero();
KeywordSharePageVo unused = newService().page(COMPANY_ID, VIEWER, null, null, null, null, null,
null, "unused", 0, false, 1L, 200L);
assertThat(unused.getStats().getUsed()).isZero();
assertThat(unused.getStats().getUnused()).isEqualTo(6L);
// 状态过滤生效时不再为「命中内已使用数」多查一遍:两次 page 各查 1 次
verify(keywordShareMapper, org.mockito.Mockito.times(2)).countHit(any(KeywordShareFilterQuery.class));
}
@Test
@DisplayName("列表:筛选条件(类目/搜索/仅看我/usedDays)与分页进 Mapper 载体,size 上限 500")
void pageCarriesFilterAndNormalizedPaging() {
when(keywordShareMapper.countHit(any(KeywordShareFilterQuery.class))).thenReturn(0L);
when(keywordShareMapper.selectRows(any(KeywordShareFilterQuery.class))).thenReturn(List.of());
when(keywordShareMapper.countDupKeywords(COMPANY_ID)).thenReturn(0L);
newService().page(COMPANY_ID, VIEWER, " 英国 ", "厨房用品", "锅具", "煎锅", "平底锅",
" storage ", "all", 30, true, 0L, 1000L);
ArgumentCaptor<KeywordShareFilterQuery> captor = ArgumentCaptor.forClass(KeywordShareFilterQuery.class);
verify(keywordShareMapper).selectRows(captor.capture());
KeywordShareFilterQuery filter = captor.getValue();
assertThat(filter.getCountry()).isEqualTo("英国");
assertThat(filter.getCategory()).isEqualTo("厨房用品");
assertThat(filter.getSubCategory()).isEqualTo("锅具");
assertThat(filter.getCategoryL3()).isEqualTo("煎锅");
assertThat(filter.getCategoryL4()).isEqualTo("平底锅");
assertThat(filter.getSearch()).isEqualTo("storage");
assertThat(filter.getStatus()).isEqualTo("all");
assertThat(filter.getOnlyMine()).isTrue();
assertThat(filter.getUserName()).isEqualTo(VIEWER);
// usedDays=30:往前推 30 天
assertThat(filter.getUsedSince()).isNotNull();
assertThat(filter.getUsedSince()).isBefore(LocalDateTime.now());
assertThat(filter.getUsedSince()).isAfter(LocalDateTime.now().minusDays(31));
// 分页归一化:page=0→1、size=1000→500
assertThat(filter.getOffset()).isZero();
assertThat(filter.getLimit()).isEqualTo(500L);
}
@Test
@DisplayName("usedDays=1 表示「今天」:时间下限取当日零点;不传/0 表示不限")
void usedDaysOneMeansStartOfToday() {
when(keywordShareMapper.countHit(any(KeywordShareFilterQuery.class))).thenReturn(0L);
when(keywordShareMapper.selectRows(any(KeywordShareFilterQuery.class))).thenReturn(List.of());
when(keywordShareMapper.countDupKeywords(COMPANY_ID)).thenReturn(0L);
newService().page(COMPANY_ID, VIEWER, null, null, null, null, null, null, "all", 1, false, 1L, 200L);
ArgumentCaptor<KeywordShareFilterQuery> captor = ArgumentCaptor.forClass(KeywordShareFilterQuery.class);
verify(keywordShareMapper).selectRows(captor.capture());
assertThat(captor.getValue().getUsedSince()).isEqualTo(LocalDate.now().atStartOfDay());
newService().page(COMPANY_ID, VIEWER, null, null, null, null, null, null, "all", null, false, 1L, 200L);
verify(keywordShareMapper, org.mockito.Mockito.times(2)).selectRows(captor.capture());
assertThat(captor.getValue().getUsedSince()).isNull();
}
@Test
@DisplayName("列表:行按 Mapper 返回顺序透传(SQL 侧已按未使用在前、已使用按 used_time 升序排好),未使用行不带使用者")
void pageRowsKeepMapperOrderAndNormalizeUnusedRows() {
when(keywordShareMapper.countHit(any(KeywordShareFilterQuery.class))).thenReturn(3L);
when(keywordShareMapper.selectRows(any(KeywordShareFilterQuery.class))).thenReturn(List.of(
row(2, "kw-old-used", true, "张三"),
row(3, "kw-new-used", true, VIEWER),
row(1, "kw-unused", false, "不该有名字")));
when(keywordShareMapper.countDupKeywords(COMPANY_ID)).thenReturn(0L);
KeywordSharePageVo vo = newService().page(COMPANY_ID, VIEWER, null, null, null, null, null,
null, "all", 0, false, 1L, 200L);
assertThat(vo.getRows()).extracting(KeywordShareRowVo::getId).containsExactly(2L, 3L, 1L);
assertThat(vo.getRows().get(0).isUsed()).isTrue();
assertThat(vo.getRows().get(0).getUsedUser()).isEqualTo("张三");
assertThat(vo.getRows().get(2).isUsed()).isFalse();
assertThat(vo.getRows().get(2).getUsedTime()).isNull();
assertThat(vo.getRows().get(2).getUsedUser()).isEmpty();
}
@Test
@DisplayName("排序契约:Mapper XML 的 ORDER BY 必须是「已使用在前(对齐桌面版)、按 used_time 升序」,且禁止 ${} 拼接")
void mapperXmlKeepsSortContractAndPlaceholderOnly() throws Exception {
String xml = Files.readString(Path.of(
"src/main/resources/mapper/keywordshare/KeywordShareMapper.xml"), StandardCharsets.UTF_8);
assertThat(xml).contains("ORDER BY (u.country IS NULL) ASC, u.used_time ASC");
assertThat(xml).doesNotContain("${");
String usageXml = Files.readString(Path.of(
"src/main/resources/mapper/keywordshare/KeywordUsageMapper.xml"), StandardCharsets.UTF_8);
assertThat(usageXml).contains("ON DUPLICATE KEY UPDATE").doesNotContain("${");
}
// ---------------------------------------------------------------- 标记/取消使用
@Test
@DisplayName("mark:UPSERT 幂等——重复标记同一词两次结果一致,使用者与时间都取服务端当前值")
void markIsIdempotentWithServerTime() {
KeywordUsageBatchRequest request = new KeywordUsageBatchRequest();
KeywordUsageBatchRequest.Item item1 = new KeywordUsageBatchRequest.Item();
item1.setCountry("英国");
item1.setKeyword(" storage box ");
KeywordUsageBatchRequest.Item item2 = new KeywordUsageBatchRequest.Item();
item2.setCountry("德国");
item2.setKeyword("aufbewahrungsbox");
request.setItems(List.of(item1, item2));
KeywordShareService service = newService();
LocalDateTime before = LocalDateTime.now();
var first = service.mark(request, COMPANY_ID, VIEWER);
var second = service.mark(request, COMPANY_ID, VIEWER);
LocalDateTime after = LocalDateTime.now();
assertThat(first.getMarked()).isEqualTo(2);
assertThat(second.getMarked()).isEqualTo(2);
ArgumentCaptor<List<KeywordUsageEntity>> captor = ArgumentCaptor.forClass(List.class);
verify(keywordUsageMapper, org.mockito.Mockito.times(2)).upsertBatch(captor.capture());
List<KeywordUsageEntity> rows = captor.getAllValues().get(0);
assertThat(rows).hasSize(2);
assertThat(rows).allSatisfy(row -> {
assertThat(row.getCompanyId()).isEqualTo(COMPANY_ID);
assertThat(row.getUserName()).isEqualTo(VIEWER);
assertThat(row.getUsedTime()).isAfterOrEqualTo(before).isBeforeOrEqualTo(after);
});
assertThat(rows.get(0).getKeyword()).isEqualTo("storage box");
assertThat(rows.get(1).getCountry()).isEqualTo("德国");
}
@Test
@DisplayName("mark:批内重复键去重、空键跳过;全空时不动库")
void markSkipsBlankAndDuplicateKeys() {
KeywordUsageBatchRequest request = new KeywordUsageBatchRequest();
KeywordUsageBatchRequest.Item blank = new KeywordUsageBatchRequest.Item();
blank.setCountry("英国");
blank.setKeyword(" ");
KeywordUsageBatchRequest.Item dup = new KeywordUsageBatchRequest.Item();
dup.setCountry("英国");
dup.setKeyword("box");
KeywordUsageBatchRequest.Item dupAgain = new KeywordUsageBatchRequest.Item();
dupAgain.setCountry(" 英国 ");
dupAgain.setKeyword("box");
request.setItems(List.of(blank, dup, dupAgain));
var result = newService().mark(request, COMPANY_ID, VIEWER);
assertThat(result.getMarked()).isEqualTo(1);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<KeywordUsageEntity>> captor = ArgumentCaptor.forClass(List.class);
verify(keywordUsageMapper).upsertBatch(captor.capture());
assertThat(captor.getValue()).hasSize(1);
assertThat(captor.getValue().get(0).getKeyword()).isEqualTo("box");
KeywordUsageBatchRequest allBlank = new KeywordUsageBatchRequest();
KeywordUsageBatchRequest.Item item = new KeywordUsageBatchRequest.Item();
item.setKeyword(" ");
allBlank.setItems(List.of(item));
assertThat(newService().mark(allBlank, COMPANY_ID, VIEWER).getMarked()).isZero();
}
@Test
@DisplayName("unmark:按 (company, country, keyword) 删行,返回实际删除条数")
void unmarkDeletesRowsAndCountsAffected() {
KeywordUsageBatchRequest request = new KeywordUsageBatchRequest();
KeywordUsageBatchRequest.Item item = new KeywordUsageBatchRequest.Item();
item.setCountry("英国");
item.setKeyword("box");
request.setItems(List.of(item));
when(keywordUsageMapper.deleteBatch(eq(COMPANY_ID), anyList())).thenReturn(1);
var result = newService().unmark(request, COMPANY_ID);
assertThat(result.getUnmarked()).isEqualTo(1);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<KeywordShareKey>> captor = ArgumentCaptor.forClass(List.class);
verify(keywordUsageMapper).deleteBatch(eq(COMPANY_ID), captor.capture());
assertThat(captor.getValue().get(0).getKeyword()).isEqualTo("box");
}
// ---------------------------------------------------------------- 添加
@Test
@DisplayName("add:查重跳过已存在词,空词/批内重复跳过;成功行写词本体 + 添加留痕 + 自动标记已使用")
void addSkipsExistingAndBlankAndWritesLogsAndAutoMarks() {
KeywordShareAddRequest request = new KeywordShareAddRequest();
KeywordShareAddRequest.Item good = new KeywordShareAddRequest.Item();
good.setCountry("英国");
good.setKeyword(" storage box ");
good.setChinese("收纳盒");
KeywordShareAddRequest.Item existing = new KeywordShareAddRequest.Item();
existing.setCountry("德国");
existing.setKeyword("aufbewahrungsbox");
existing.setChinese("收纳箱");
KeywordShareAddRequest.Item blank = new KeywordShareAddRequest.Item();
blank.setCountry("法国");
blank.setKeyword(" ");
KeywordShareAddRequest.Item dup = new KeywordShareAddRequest.Item();
dup.setCountry("英国");
dup.setKeyword("storage box");
request.setItems(List.of(good, existing, blank, dup));
KeywordShareKey existingKey = KeywordShareKey.of("德国", "aufbewahrungsbox");
when(keywordShareMapper.selectExistingKeywords(eq(COMPANY_ID), anyList())).thenReturn(List.of(existingKey));
LocalDateTime before = LocalDateTime.now();
var result = newService().add(request, COMPANY_ID, VIEWER);
assertThat(result.getAdded()).isEqualTo(1);
assertThat(result.getSkipped()).isEqualTo(3);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<KeywordShareEntity>> insertCaptor = ArgumentCaptor.forClass(List.class);
verify(keywordShareMapper).insertBatchIgnore(insertCaptor.capture());
KeywordShareEntity inserted = insertCaptor.getValue().get(0);
assertThat(inserted.getCountry()).isEqualTo("英国");
assertThat(inserted.getKeyword()).isEqualTo("storage box");
assertThat(inserted.getChinese()).isEqualTo("收纳盒");
assertThat(inserted.getKtype()).isEqualTo("主关键词");
assertThat(inserted.getSource()).isEqualTo("手动添加");
assertThat(inserted.getCompanyId()).isEqualTo(COMPANY_ID);
assertThat(inserted.getUserName()).isEqualTo(VIEWER);
assertThat(inserted.getAddTime()).isAfterOrEqualTo(before);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<KeywordAddLogEntity>> logCaptor = ArgumentCaptor.forClass(List.class);
verify(keywordAddLogMapper).insertBatch(logCaptor.capture());
assertThat(logCaptor.getValue()).hasSize(1);
assertThat(logCaptor.getValue().get(0).getKeyword()).isEqualTo("storage box");
assertThat(logCaptor.getValue().get(0).getUserName()).isEqualTo(VIEWER);
@SuppressWarnings("unchecked")
ArgumentCaptor<List<KeywordUsageEntity>> usageCaptor = ArgumentCaptor.forClass(List.class);
verify(keywordUsageMapper).upsertBatch(usageCaptor.capture());
assertThat(usageCaptor.getValue()).hasSize(1);
assertThat(usageCaptor.getValue().get(0).getKeyword()).isEqualTo("storage box");
assertThat(usageCaptor.getValue().get(0).getUserName()).isEqualTo(VIEWER);
}
@Test
@DisplayName("add:全部跳过时不动任何表(词本体/留痕/使用状态都不写)")
void addWithNothingToAddTouchesNothing() {
KeywordShareAddRequest request = new KeywordShareAddRequest();
KeywordShareAddRequest.Item blank = new KeywordShareAddRequest.Item();
blank.setCountry("英国");
blank.setKeyword("");
request.setItems(List.of(blank));
var result = newService().add(request, COMPANY_ID, VIEWER);
assertThat(result.getAdded()).isZero();
assertThat(result.getSkipped()).isEqualTo(1);
verify(keywordShareMapper, never()).insertBatchIgnore(anyList());
verify(keywordAddLogMapper, never()).insertBatch(anyList());
verify(keywordUsageMapper, never()).upsertBatch(anyList());
verify(keywordShareMapper, never()).selectExistingKeywords(any(), anyList());
}
// ---------------------------------------------------------------- 删除
@Test
@DisplayName("delete:只删本公司存在的行并逐行写删除留痕(谁删了哪个词可追溯)")
void deleteWritesDeleteLogForCompanyRows() {
KeywordShareDeleteRequest request = new KeywordShareDeleteRequest();
request.setIds(List.of(1L, 2L, 999L));
KeywordShareEntity row1 = new KeywordShareEntity();
row1.setId(1L);
row1.setCountry("英国");
row1.setKeyword("box");
row1.setCompanyId(COMPANY_ID);
KeywordShareEntity row2 = new KeywordShareEntity();
row2.setId(2L);
row2.setCountry("德国");
row2.setKeyword("kiste");
row2.setCompanyId(COMPANY_ID);
KeywordShareEntity foreign = new KeywordShareEntity();
foreign.setId(999L);
foreign.setCountry("法国");
foreign.setKeyword("mot-etranger");
foreign.setCompanyId(8L);
when(keywordShareMapper.selectBatchIds(List.of(1L, 2L, 999L))).thenReturn(List.of(row1, row2, foreign));
LocalDateTime before = LocalDateTime.now();
var result = newService().delete(request, COMPANY_ID, VIEWER);
// 公司隔离:999 号行是别家公司的,即使 id 在请求里也绝不能删
assertThat(result.getDeleted()).isEqualTo(2);
verify(keywordShareMapper).deleteBatchIds(List.of(1L, 2L));
@SuppressWarnings("unchecked")
ArgumentCaptor<List<KeywordDeleteLogEntity>> logCaptor = ArgumentCaptor.forClass(List.class);
verify(keywordDeleteLogMapper).insertBatch(logCaptor.capture());
List<KeywordDeleteLogEntity> logs = logCaptor.getValue();
assertThat(logs).hasSize(2);
assertThat(logs).extracting(KeywordDeleteLogEntity::getKeyword).containsExactly("box", "kiste");
assertThat(logs).allSatisfy(log -> {
assertThat(log.getCompanyId()).isEqualTo(COMPANY_ID);
assertThat(log.getUserName()).isEqualTo(VIEWER);
assertThat(log.getDeleteTime()).isAfterOrEqualTo(before);
});
}
@Test
@DisplayName("delete:请求里的行都不属于本公司(或不存在)时,不动库也不留痕")
void deleteWithNoCompanyRowsTouchesNothing() {
KeywordShareDeleteRequest request = new KeywordShareDeleteRequest();
request.setIds(List.of(1L));
when(keywordShareMapper.selectBatchIds(anyList())).thenReturn(List.of());
var result = newService().delete(request, COMPANY_ID, VIEWER);
assertThat(result.getDeleted()).isZero();
verify(keywordShareMapper, never()).deleteBatchIds(anyList());
verify(keywordDeleteLogMapper, never()).insertBatch(anyList());
}
// ---------------------------------------------------------------- 随机抽词
@Test
@DisplayName("random:只从「未使用」池抽,条数默认 10、上限 100、下限 1")
void randomUsesUnusedPoolWithClampedCount() {
when(keywordShareMapper.selectRandomUnused(any(KeywordShareFilterQuery.class))).thenReturn(List.of(
row(5, "kw-random", false, "")));
var result = newService().random(COMPANY_ID, VIEWER, "英国", null, null, null, null, null, 5L);
assertThat(result).hasSize(1);
assertThat(result.get(0).getKeyword()).isEqualTo("kw-random");
ArgumentCaptor<KeywordShareFilterQuery> captor = ArgumentCaptor.forClass(KeywordShareFilterQuery.class);
verify(keywordShareMapper).selectRandomUnused(captor.capture());
assertThat(captor.getValue().getStatus()).isEqualTo("unused");
assertThat(captor.getValue().getLimit()).isEqualTo(5L);
assertThat(captor.getValue().getCountry()).isEqualTo("英国");
newService().random(COMPANY_ID, VIEWER, null, null, null, null, null, null, null);
verify(keywordShareMapper, org.mockito.Mockito.times(2)).selectRandomUnused(captor.capture());
assertThat(captor.getValue().getLimit()).isEqualTo(KeywordShareService.DEFAULT_RANDOM_COUNT);
newService().random(COMPANY_ID, VIEWER, null, null, null, null, null, null, 1000L);
verify(keywordShareMapper, org.mockito.Mockito.times(3)).selectRandomUnused(captor.capture());
assertThat(captor.getValue().getLimit()).isEqualTo(KeywordShareService.MAX_RANDOM_COUNT);
}
// ---------------------------------------------------------------- 防回流的供应商隔离自检
@Test
@DisplayName("公司隔离:全部 Mapper 写路径的第一个参数都是服务端给的 companyId(抽查写 SQL 收口)")
void writeSqlStaysInMapperLayerWithCompanyScope() throws Exception {
String shareXml = Files.readString(Path.of(
"src/main/resources/mapper/keywordshare/KeywordShareMapper.xml"), StandardCharsets.UTF_8);
// 词本体的读路径一律带 company_id 条件(含 dup 子查询与类目名册)
long scopedSelects = shareXml.lines().filter(line -> line.contains("company_id = #{")).count();
assertThat(scopedSelects).isGreaterThanOrEqualTo(5);
String usageXml = Files.readString(Path.of(
"src/main/resources/mapper/keywordshare/KeywordUsageMapper.xml"), StandardCharsets.UTF_8);
assertThat(usageXml).contains("company_id = #{companyId}");
String addXml = Files.readString(Path.of(
"src/main/resources/mapper/keywordshare/KeywordAddLogMapper.xml"), StandardCharsets.UTF_8);
String deleteXml = Files.readString(Path.of(
"src/main/resources/mapper/keywordshare/KeywordDeleteLogMapper.xml"), StandardCharsets.UTF_8);
assertThat(addXml + deleteXml)
.contains("company_id", "user_name")
.doesNotContain("${");
}
// ---------------------------------------------------------------- 客户端全量同步
private static KeywordShareSyncImportRequest.Item syncItem(String country, String keyword, Boolean used,
String usedUser, String usedTime) {
KeywordShareSyncImportRequest.Item item = new KeywordShareSyncImportRequest.Item();
item.setCountry(country);
item.setKeyword(keyword);
item.setUsed(used);
item.setUsedUser(usedUser);
item.setUsedTime(usedTime);
return item;
}
private static KeywordShareSyncImportRequest syncRequest(List<KeywordShareSyncImportRequest.Item> items) {
KeywordShareSyncImportRequest request = new KeywordShareSyncImportRequest();
request.setItems(items);
return request;
}
@Test
@DisplayName("sync/import:客户端传来的 usedTime/usedUser 与四级类目原样落库,不被服务端此刻与账号覆盖")
void syncImportKeepsClientUsedTimeUserAndCategories() {
KeywordShareSyncImportRequest.Item item = syncItem("英国", "wraps", true, "阿武(吴棋龙)", "2026-10-25T22:59:26");
item.setChinese("包裹");
item.setCategory("衣物鞋类");
item.setSubCategory("包包");
item.setCategoryL3("其他包包");
item.setCategoryL4("其他包包");
item.setKtype("主关键词");
item.setSource("本地导入");
KeywordShareService service = newService(rosterOf(true, "阿武(吴棋龙)"));
LocalDateTime before = LocalDateTime.now();
KeywordShareSyncResultVo vo = service.syncImport(syncRequest(List.of(item)), COMPANY_ID, "kw_share_api");
// 这条用例存在的理由:mark() 走的是 used_time=now()、user_name=token 账号,
// 同步历史时会被改写成「谁在同步那一刻用的」,真实使用人与使用时刻双双丢失。
ArgumentCaptor<List<KeywordUsageEntity>> usageCaptor = ArgumentCaptor.forClass(List.class);
verify(keywordUsageMapper).upsertBatch(usageCaptor.capture());
KeywordUsageEntity usage = usageCaptor.getValue().get(0);
assertThat(usage.getUserName()).isEqualTo("阿武(吴棋龙)");
assertThat(usage.getUsedTime()).isEqualTo(LocalDateTime.of(2026, 10, 25, 22, 59, 26))
.isBefore(before);
assertThat(usage.getCompanyId()).isEqualTo(COMPANY_ID);
ArgumentCaptor<List<KeywordShareEntity>> wordCaptor = ArgumentCaptor.forClass(List.class);
verify(keywordShareMapper).upsertBatchFromSync(wordCaptor.capture());
KeywordShareEntity word = wordCaptor.getValue().get(0);
assertThat(word.getCategory()).isEqualTo("衣物鞋类");
assertThat(word.getSubCategory()).isEqualTo("包包");
assertThat(word.getCategoryL3()).isEqualTo("其他包包");
// 词本体的 user_name 是「添加人」,新词就是本次同步账号——它和使用人是两回事
assertThat(word.getUserName()).isEqualTo("kw_share_api");
assertThat(vo.getAdded()).isEqualTo(1);
assertThat(vo.getUpdated()).isZero();
assertThat(vo.getUsedUserFallback()).isZero();
assertThat(vo.getUsedUserUnknown()).isZero();
assertThat(vo.getUsedTimeFallback()).isZero();
}
@Test
@DisplayName("sync/import:名单外姓名 strict=true 回退账号名并计数,strict=false 放行但仍计 unknown")
void syncImportResolvesOperatorAgainstRoster() {
// 半角括号写法要能命中全角名单,否则同一个人会被后管拆成两个使用者
KeywordShareSyncImportRequest.Item hit = syncItem("英国", "basket", true, "阿武(吴棋龙)", "2026-10-01 08:00:00");
KeywordShareSyncImportRequest.Item miss = syncItem("英国", "hanger", true, "陌生人", "2026-10-01 08:00:00");
ArgumentCaptor<List<KeywordUsageEntity>> captor = ArgumentCaptor.forClass(List.class);
KeywordShareSyncResultVo strict = newService(rosterOf(true, "阿武(吴棋龙)"))
.syncImport(syncRequest(List.of(hit, miss)), COMPANY_ID, "kw_share_api");
verify(keywordUsageMapper).upsertBatch(captor.capture());
// 命中名单后落的是名单里那份写法:客户端传半角也不能让它把同一个人拆成两个使用者
assertThat(captor.getValue()).extracting(KeywordUsageEntity::getUserName)
.containsExactly("阿武(吴棋龙)", "kw_share_api");
assertThat(strict.getUsedUserFallback()).isEqualTo(1);
assertThat(strict.getUsedUserUnknown()).isEqualTo(1);
KeywordShareSyncResultVo lenient = newService(rosterOf(false, "阿武(吴棋龙)"))
.syncImport(syncRequest(List.of(hit, miss)), COMPANY_ID, "kw_share_api");
assertThat(lenient.getUsedUserFallback()).isZero();
assertThat(lenient.getUsedUserUnknown()).isEqualTo(1);
}
@Test
@DisplayName("sync/import:脏时间按行降级——1970 丢使用状态但词照收、未来值钳到此刻、缺失回退此刻")
void syncImportDegradesDirtyUsedTimePerRow() {
KeywordShareSyncImportRequest.Item ancient = syncItem("英国", "ancient", true, "阿武(吴棋龙)", "1970-01-01T00:00:00");
KeywordShareSyncImportRequest.Item future = syncItem("英国", "future", true, "阿武(吴棋龙)", "2099-01-01T00:00:00");
KeywordShareSyncImportRequest.Item missing = syncItem("英国", "missing", true, "阿武(吴棋龙)", " ");
KeywordShareSyncImportRequest.Item unparsable = syncItem("英国", "garbage", true, "阿武(吴棋龙)", "昨天下午");
LocalDateTime before = LocalDateTime.now();
KeywordShareSyncResultVo vo = newService(rosterOf(true, "阿武(吴棋龙)"))
.syncImport(syncRequest(List.of(ancient, future, missing, unparsable)), COMPANY_ID, "kw_share_api");
assertThat(vo.getUsageSkipped()).isEqualTo(1);
assertThat(vo.getUsedTimeClamped()).isEqualTo(1);
assertThat(vo.getUsedTimeFallback()).isEqualTo(2);
// 一颗脏时间戳不该打掉整批:四个词全部入库,只有 ancient 的使用状态被丢
assertThat(vo.getAdded()).isEqualTo(4);
ArgumentCaptor<List<KeywordShareEntity>> wordCaptor = ArgumentCaptor.forClass(List.class);
verify(keywordShareMapper).upsertBatchFromSync(wordCaptor.capture());
assertThat(wordCaptor.getValue()).extracting(KeywordShareEntity::getKeyword)
.containsExactly("ancient", "future", "missing", "garbage");
ArgumentCaptor<List<KeywordUsageEntity>> usageCaptor = ArgumentCaptor.forClass(List.class);
verify(keywordUsageMapper).upsertBatch(usageCaptor.capture());
assertThat(usageCaptor.getValue()).hasSize(3)
.allSatisfy(row -> assertThat(row.getUsedTime()).isAfterOrEqualTo(before));
}
@Test
@DisplayName("sync/import:used=false 删使用记录;dryRun 只统计不写;空键与批内重复计入 skipped")
void syncImportDeletesUsageAndHonoursDryRun() {
List<KeywordShareSyncImportRequest.Item> items = List.of(
syncItem("英国", "keep", false, null, null),
syncItem("英国", "drop", true, "阿武(吴棋龙)", "2026-10-01T08:00:00"),
syncItem("英国", "drop", true, "阿武(吴棋龙)", "2026-10-01T08:00:00"),
syncItem("", "no-country", true, "阿武(吴棋龙)", "2026-10-01T08:00:00"));
KeywordShareSyncImportRequest request = syncRequest(items);
KeywordShareService service = newService(rosterOf(true, "阿武(吴棋龙)"));
KeywordShareSyncImportRequest dryRunRequest = syncRequest(items);
dryRunRequest.setDryRun(true);
KeywordShareSyncResultVo dryRun = service.syncImport(dryRunRequest, COMPANY_ID, "kw_share_api");
assertThat(dryRun.isDryRun()).isTrue();
assertThat(dryRun.getSkipped()).isEqualTo(2);
assertThat(dryRun.getAdded()).isEqualTo(2);
verify(keywordShareMapper, never()).upsertBatchFromSync(anyList());
verify(keywordUsageMapper, never()).upsertBatch(anyList());
verify(keywordUsageMapper, never()).deleteBatch(any(), anyList());
KeywordShareSyncResultVo real = service.syncImport(request, COMPANY_ID, "kw_share_api");
assertThat(real.isDryRun()).isFalse();
ArgumentCaptor<List<KeywordShareKey>> deleteCaptor = ArgumentCaptor.forClass(List.class);
verify(keywordUsageMapper).deleteBatch(eq(COMPANY_ID), deleteCaptor.capture());
assertThat(deleteCaptor.getValue()).extracting(KeywordShareKey::getKeyword).containsExactly("keep");
assertThat(real.getUsageDeleted()).isEqualTo(1);
}
@Test
@DisplayName("sync/import:used 不传=不碰使用状态(只同步词库不能把后台已有使用记录删掉)")
void syncImportLeavesUsageUntouchedWhenUsedFlagOmitted() {
KeywordShareSyncImportRequest.Item wordOnly = syncItem("英国", "wraps", null, null, null);
wordOnly.setCategory("衣物鞋类");
KeywordShareSyncResultVo vo = newService(rosterOf(true, "阿武(吴棋龙)"))
.syncImport(syncRequest(List.of(wordOnly)), COMPANY_ID, "kw_share_api");
assertThat(vo.getAdded()).isEqualTo(1);
assertThat(vo.getUsageUpserted()).isZero();
assertThat(vo.getUsageDeleted()).isZero();
verify(keywordUsageMapper, never()).upsertBatch(anyList());
verify(keywordUsageMapper, never()).deleteBatch(any(), anyList());
ArgumentCaptor<List<KeywordShareEntity>> captor = ArgumentCaptor.forClass(List.class);
verify(keywordShareMapper).upsertBatchFromSync(captor.capture());
assertThat(captor.getValue().get(0).getCategory()).isEqualTo("衣物鞋类");
}
@Test
@DisplayName("sync/import:写侧按 500 行分片,不把整批塞进一条 SQL 的占位符里")
void syncImportShardsWrites() {
List<KeywordShareSyncImportRequest.Item> items = new java.util.ArrayList<>();
for (int i = 0; i < 1200; i++) {
items.add(syncItem("英国", "kw-" + i, true, "阿武(吴棋龙)", "2026-10-01T08:00:00"));
}
KeywordShareSyncResultVo vo = newService(rosterOf(true, "阿武(吴棋龙)"))
.syncImport(syncRequest(items), COMPANY_ID, "kw_share_api");
assertThat(vo.getAdded()).isEqualTo(1200);
ArgumentCaptor<List<KeywordShareEntity>> wordCaptor = ArgumentCaptor.forClass(List.class);
verify(keywordShareMapper, org.mockito.Mockito.times(3)).upsertBatchFromSync(wordCaptor.capture());
assertThat(wordCaptor.getAllValues()).extracting(List::size).containsExactly(500, 500, 200);
ArgumentCaptor<List<KeywordUsageEntity>> usageCaptor = ArgumentCaptor.forClass(List.class);
verify(keywordUsageMapper, org.mockito.Mockito.times(3)).upsertBatch(usageCaptor.capture());
assertThat(usageCaptor.getAllValues()).extracting(List::size).containsExactly(500, 500, 200);
}
@Test
@DisplayName("sync/import 的 UPSERT SQL:类目非空才覆盖,且更新分支不得改写添加人与添加时间")
void syncUpsertKeepsCategoriesAndProvenance() throws Exception {
String xml = Files.readString(Path.of(
"src/main/resources/mapper/keywordshare/KeywordShareMapper.xml"), StandardCharsets.UTF_8);
String upsert = xml.substring(xml.indexOf("<insert id=\"upsertBatchFromSync\">"));
assertThat(upsert).contains("ON DUPLICATE KEY UPDATE")
.contains("category = COALESCE(NULLIF(VALUES(category), ''), category)")
.contains("sub_category = COALESCE(NULLIF(VALUES(sub_category), ''), sub_category)")
.doesNotContain("${");
// 更新分支只碰类目/释义/类型/来源:user_name、add_time 是历史归属,同步无权改写
String updateBranch = upsert.substring(upsert.indexOf("ON DUPLICATE KEY UPDATE"));
assertThat(updateBranch).doesNotContain("user_name =")
.doesNotContain("add_time =");
}
}
@@ -25,7 +25,7 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** /**
* AC-19(R8/审计 P1-B1、P1-B2、P1-B3、P1-B4):任务中心时间窗+keyset、关键词去 RAND、 * AC-19(R8/审计 P1-B1、P1-B3、P1-B4):任务中心时间窗+keyset、
* 心跳瘦字段、权限菜单短 TTL 缓存。 * 心跳瘦字段、权限菜单短 TTL 缓存。
* *
* <p>逐条证据: * <p>逐条证据:
@@ -35,8 +35,6 @@ import static org.mockito.Mockito.when;
* {@code ORDER BY m.createdAt DESC, m.id DESC LIMIT #{limit} OFFSET #{offset}}, * {@code ORDER BY m.createdAt DESC, m.id DESC LIMIT #{limit} OFFSET #{offset}},
* 而 {@code TaskCenterQueryService.tasks()}(:110-139)把 {@code startTime/endTime} * 而 {@code TaskCenterQueryService.tasks()}(:110-139)把 {@code startTime/endTime}
* 原样透传、服务层不填默认窗口 ⇒ 不带时间参数就是全历史 UNION + 深 OFFSET。</li> * 原样透传、服务层不填默认窗口 ⇒ 不带时间参数就是全历史 UNION + 深 OFFSET。</li>
* <li><b>P1-B2</b> {@code mapper/keywordshare/KeywordShareMapper.xml:53} 的
* {@code selectRandomUnused} 是 {@code ORDER BY RAND()}(全表 filesort)。</li>
* <li><b>P1-B3</b> {@code TaskHeartbeatService.java:111-116} 的 {@code selectFileTask} * <li><b>P1-B3</b> {@code TaskHeartbeatService.java:111-116} 的 {@code selectFileTask}
* 没有 {@code .select(...)},捞整行 {@code FileTaskEntity}(含 * 没有 {@code .select(...)},捞整行 {@code FileTaskEntity}(含
* {@code requestJson}/{@code resultJson}),而心跳只用 * {@code requestJson}/{@code resultJson}),而心跳只用
@@ -82,16 +80,6 @@ class PendingPhase5ReadPathTest {
.containsAnyOf("DEFAULT_WINDOW", "minusDays", "startOfDefaultWindow"); .containsAnyOf("DEFAULT_WINDOW", "minusDays", "startOfDefaultWindow");
} }
@Test
void 关键词抽词不许再_ORDER_BY_RAND() throws Exception {
String body = MapperXmlSupport.statementBody(
com.nanri.aiimage.modules.keywordshare.mapper.KeywordShareMapper.class, "selectRandomUnused");
assertThat(body)
.as("P1-B2:ORDER BY RAND() 对全表 filesort;要么先 count 取随机 offset,要么物化 used 标记")
.doesNotContain("RAND()");
}
@Test @Test
void 心跳取任务必须只读瘦字段() { void 心跳取任务必须只读瘦字段() {
String service = SourceScan.withoutComments(SourceScan.sourceText("TaskHeartbeatService.java")); String service = SourceScan.withoutComments(SourceScan.sourceText("TaskHeartbeatService.java"));
+172 -100
View File
@@ -1,24 +1,28 @@
<script setup lang="ts"> <script setup lang="ts">
/** 建单页「采集类目」多选级联面板(2026-11-16 客户口径「客户端前端也要同步加上京东类目」)。 /** 建单页「采集类目」多选级联面板(2026-11-16 客户口径「京麦类目是这些 我们后台的现在
* 的不对」+「你直接爬」→ 树数据换成京麦授权类目真树,见 ./jd-category-tree.ts 头注释
* 的取证来源与边界;面板形状与后管筛选面板同款,两处差异:① **多选**——末级行点击=
* toggle(方点 checkbox),「全部类目」行=清空,触发框显示「已选 N 个类目」;
* ② 触发框配色按本页暗色主题适配(面板本体仍是白底弹层)。
* *
* 形状照后管京东数据库的筛选面板(admin-frontend-vue/src/pages/jd/JdCategoryCascader.vue, * 交互(京麦真机同款,2026-11-16 面板逐级点开取证):面板按点亮路径动态出栏——第一栏
* 京麦同款三栏:一级静态导航 / 二级纯导航 / 第三栏已落库末级全集+搜索),两处差异: * 一级(3 个)、后续栏=点亮节点的 children(最深 4 栏);**非末级行点击=下钻**、
* ① **多选**——第三栏行点击=toggle(方点 checkbox),「全部类目」行=清空,触发框显示 * **末级行(children 空)点击=toggle 勾选**(随建单走 categoryPaths → 客户端按
* 「已选 N 个类目」;② 触发框配色按本页暗色主题适配(面板本体仍是白底弹层)。 * categoryPath 等值过滤)。搜索框搜树内全部末级(行 title 带全路径);树外命中(已
* * 落库但京麦类目体系变更后的历史名)从 options 兜底段选。面板是 fixed 浮层(窄触发框
* 数据边界与后管同源(见 ./jd-category-tree.ts 头注释):采集链只有末级类目名,一/二级 * 不撑文档横向滚动),打开瞬间按触发框实际位置定位。零依赖自绘,无 element 依赖。 */
* 不参与过滤;第三栏选项=/api/jd-collect/categories 现算的公共库已落库全集,从未采集过
* 的店铺类目不在集内(先全店采一次即有)。选中值随建单走 categoryPaths → 客户端按
* categoryPath 等值过滤。零依赖自绘(方点/箭头都是 CSS),无 element 依赖。
*
* 交互:点开面板 → 点/hover 一级展第二栏 → 第三栏搜索或点行勾选/取消 → 收面板;
* 「全部类目」行=清空;触发框已选时出 × 清除;面板外点透明遮罩关闭。 */
import { computed, ref } from 'vue' import { computed, ref } from 'vue'
import { jdCategoryNavChildren, jdCategoryNavRoots } from './jd-category-tree.ts' import {
jdCategoryChildren,
jdCategoryRoots,
jdCategorySearchLeaves,
type JdCategoryNode,
} from './jd-category-tree.ts'
const props = defineProps<{ const props = defineProps<{
/** 已落库末级类目选项(/api/jd-collect/categories 现算,页面传入:{name, productCount})。 */ /** 已落库末级类目全集(/api/jd-collect/categories 现算)——只作**树外兜底**(搜索无
options: { name: string; productCount: number }[] * 树内命中时列出「已落库类目(树外历史)」段),不再默认铺第三栏。 */
options?: { name: string; productCount: number }[]
/** 当前选中的末级类目名列表;空数组 = 全部类目(全店采集)。 */ /** 当前选中的末级类目名列表;空数组 = 全部类目(全店采集)。 */
modelValue: string[] modelValue: string[]
}>() }>()
@@ -26,22 +30,46 @@ const props = defineProps<{
const emit = defineEmits<{ (event: 'change', value: string[]): void }>() const emit = defineEmits<{ (event: 'change', value: string[]): void }>()
const open = ref(false) const open = ref(false)
const activeRoot = ref('') /** 已下钻的节点名路径(非末级行点击推进)。 */
const activePath = ref<string[]>([])
const searchText = ref('') const searchText = ref('')
/** 触发框元素:打开面板瞬间按它的实际位置给浮层定位(fixed 不撑文档横向滚动)。 */ /** 触发框元素:打开面板瞬间按它的实际位置给浮层定位(fixed 不撑文档横向滚动)。 */
const triggerRef = ref<HTMLElement | null>(null) const triggerRef = ref<HTMLElement | null>(null)
/** 面板浮层定位(fixed 的 top/left,px 字符串)。 */ /** 面板浮层定位(fixed 的 top/left,px 字符串)。 */
const panelPos = ref({ top: '0px', left: '0px' }) const panelPos = ref({ top: '0px', left: '0px' })
const roots = jdCategoryNavRoots() const roots = jdCategoryRoots()
/** 第二栏=点亮一级的静态二级;无静态子级的一级不出第二栏。 */ /** 树内全部末级名集合(判定 options 哪些是「树外历史」)。 */
const activeChildren = computed(() => jdCategoryNavChildren(activeRoot.value)) const treeLeafNames = new Set(
jdCategorySearchLeaves('').map((leaf) => leaf.name),
)
/** 第三栏=已落库末级全集按搜索词过滤(大小写不敏感的 includes)。 */ /** 面板各栏内容:第 0 栏一级,第 i+1 栏=点亮路径前 i+1 个的 children(栏数随路径动态 1~4)。 */
const filteredLeaves = computed(() => { const columns = computed<JdCategoryNode[][]>(() => {
const cols: JdCategoryNode[][] = [roots]
for (let i = 0; i < activePath.value.length; i++) {
const children = jdCategoryChildren(activePath.value.slice(0, i + 1))
if (!children.length) break
cols.push(children)
}
return cols
})
/** 搜索激活=搜索词非空:面板切换成扁平末级结果列表。 */
const searching = computed(() => searchText.value.trim().length > 0)
/** 树内命中末级(名称或路径段命中)。 */
const searchLeaves = computed(() =>
searching.value ? jdCategorySearchLeaves(searchText.value) : [],
)
/** 树外兜底:options 里不在树名集的行按搜索词过滤(历史行仍可勾选过滤)。 */
const fallbackOptions = computed(() => {
if (!searching.value) return []
const keyword = searchText.value.trim().toLowerCase() const keyword = searchText.value.trim().toLowerCase()
if (!keyword) return props.options return (props.options ?? [])
return props.options.filter((option) => option.name.toLowerCase().includes(keyword)) .filter((option) => !treeLeafNames.has(option.name))
.filter((option) => option.name.toLowerCase().includes(keyword))
}) })
/** 触发框文案:空=全店采集;一个=类目名;多个=已选 N 个类目(title 列全名)。 */ /** 触发框文案:空=全店采集;一个=类目名;多个=已选 N 个类目(title 列全名)。 */
@@ -57,10 +85,10 @@ function toggle(): void {
close() close()
return return
} }
activeRoot.value = '' activePath.value = []
searchText.value = '' searchText.value = ''
// 面板是 fixed 浮层(京麦本尊形态:窄触发框 + 视口级宽面板,不撑文档横向滚动条), // 面板是 fixed 浮层:打开瞬间按触发框实际位置定位;测试环境无真实布局时 rect 全 0,
// 打开瞬间按触发框实际位置定位;测试环境无真实布局时 rect 全 0,top/left 落在视口原点即可。 // top/left 落在视口原点即可。
const rect = triggerRef.value?.getBoundingClientRect() const rect = triggerRef.value?.getBoundingClientRect()
if (rect) { if (rect) {
const width = Math.min(652, Math.max(320, window.innerWidth - 24)) const width = Math.min(652, Math.max(320, window.innerWidth - 24))
@@ -74,11 +102,16 @@ function toggle(): void {
function close(): void { function close(): void {
open.value = false open.value = false
activeRoot.value = '' activePath.value = []
} }
function pickRoot(name: string): void { /** 非末级行点击=下钻;末级行点击=toggle 勾选(多选,不收面板,连续勾多个)。 */
activeRoot.value = name function pick(node: JdCategoryNode, depth: number): void {
if (node.children && node.children.length) {
activePath.value = [...activePath.value.slice(0, depth), node.name]
return
}
toggleLeaf(node.name)
} }
function clearAll(): void { function clearAll(): void {
@@ -86,7 +119,7 @@ function clearAll(): void {
close() close()
} }
/** 第三栏行点击=toggle(多选);勾选状态由页面传入的 modelValue 决定。 */ /** 叶子勾选/取消(同名跨支叶子是同一个过滤值,选中态共享)。 */
function toggleLeaf(name: string): void { function toggleLeaf(name: string): void {
const picked = props.modelValue.includes(name) const picked = props.modelValue.includes(name)
? props.modelValue.filter((item) => item !== name) ? props.modelValue.filter((item) => item !== name)
@@ -94,6 +127,11 @@ function toggleLeaf(name: string): void {
emit('change', picked) emit('change', picked)
} }
/** 搜索结果行点击=toggle 勾选(不收面板,连续勾多个)。 */
function pickName(name: string): void {
toggleLeaf(name)
}
function clear(): void { function clear(): void {
emit('change', []) emit('change', [])
} }
@@ -123,67 +161,88 @@ function clear(): void {
<!-- 面板外点透明遮罩关闭(零 document 监听器,无泄漏面)。 --> <!-- 面板外点透明遮罩关闭(零 document 监听器,无泄漏面)。 -->
<div v-if="open" class="cat-mask" @click="close"></div> <div v-if="open" class="cat-mask" @click="close"></div>
<div v-if="open" class="cat-panel" :style="panelPos"> <div v-if="open" class="cat-panel" :style="panelPos">
<!-- 第一栏:静态一级导航(radio 形状照京麦,点选只展开不落值)。 --> <!-- 搜索态:树内末级命中+树外兜底段(扁平列表,行 title 带全路径)。 -->
<div class="cat-col"> <template v-if="searching">
<div <div class="cat-col cat-col-search">
v-for="root in roots" <template v-if="searchLeaves.length || fallbackOptions.length">
:key="root" <div
class="cat-row" v-for="leaf in searchLeaves"
:class="{ active: activeRoot === root }" :key="`tree-${leaf.path.join('/')}`"
@click="pickRoot(root)" class="cat-row"
@mouseenter="pickRoot(root)" :class="{ active: modelValue.includes(leaf.name) }"
> :title="leaf.path.join(' > ')"
<span class="cat-dot" aria-hidden="true"></span> @click="pickName(leaf.name)"
<span class="cat-name" :title="root">{{ root }}</span> >
<span v-if="jdCategoryNavChildren(root).length" class="cat-arrow" aria-hidden="true">›</span> <span
class="cat-dot cat-dot-check"
:class="{ on: modelValue.includes(leaf.name) }"
aria-hidden="true"
></span>
<span class="cat-name">{{ leaf.name }}</span>
<span class="cat-path">{{ leaf.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.includes(option.name) }"
:title="option.name"
@click="pickName(option.name)"
>
<span
class="cat-dot cat-dot-check"
:class="{ on: modelValue.includes(option.name) }"
aria-hidden="true"
></span>
<span class="cat-name">{{ option.name }}</span>
<span class="cat-count">{{ option.productCount }}</span>
</div>
</template>
<div v-else class="cat-empty">未找到类目</div>
</div> </div>
</div> </template>
<!-- 第二栏:点亮一级的静态二级(纯导航;归属数据缺,不联动第三栏——组件头注释)。 --> <!-- 下钻态:逐级动态栏;首栏顶部搜索框+「全部类目」行=清空。 -->
<div v-if="activeChildren.length" class="cat-col"> <template v-else>
<div <div
v-for="child in activeChildren" v-for="(col, depth) in columns"
:key="child" :key="depth"
class="cat-row" class="cat-col"
> >
<span class="cat-dot" aria-hidden="true"></span> <div v-if="depth === 0" class="cat-search-row">
<span class="cat-name" :title="child">{{ child }}</span> <input
<span class="cat-arrow" aria-hidden="true">›</span> v-model="searchText"
type="text"
class="cat-search"
placeholder="搜索类目"
@click.stop
/>
</div>
<div v-if="depth === 0" class="cat-row cat-row-all" :class="{ active: !modelValue.length }" @click="clearAll">
<span class="cat-dot" :class="{ on: !modelValue.length }" aria-hidden="true"></span>
<span class="cat-name">全部类目(全店采集)</span>
</div>
<div
v-for="node in col"
:key="`${depth}-${node.name}`"
class="cat-row"
:class="{ active: activePath[depth] === node.name || (depth === 0 && modelValue.includes(node.name)) }"
:title="node.name"
@click="pick(node, depth)"
>
<span
v-if="!node.children || !node.children.length"
class="cat-dot cat-dot-check"
:class="{ on: modelValue.includes(node.name) }"
aria-hidden="true"
></span>
<span v-else class="cat-dot" aria-hidden="true"></span>
<span class="cat-name">{{ node.name }}</span>
<span v-if="node.children && node.children.length" class="cat-arrow" aria-hidden="true">›</span>
</div>
</div> </div>
</div> </template>
<!-- 第三栏:已落库末级全集+搜索(选中发生地;点行=勾选/取消,随建单走 categoryPaths)。 -->
<div class="cat-col cat-col-leaf">
<div class="cat-row cat-row-all" :class="{ active: !modelValue.length }" @click="clearAll">
<span class="cat-dot" :class="{ on: !modelValue.length }" aria-hidden="true"></span>
<span class="cat-name">全部类目(全店采集)</span>
</div>
<input
v-model="searchText"
type="text"
class="cat-search"
placeholder="搜索类目"
@click.stop
/>
<div v-if="!filteredLeaves.length" class="cat-empty">
{{ options.length ? '未找到类目' : '暂无可选类目:先全店采集一次,落库后这里出选项' }}
</div>
<div
v-for="leaf in filteredLeaves"
:key="leaf.name"
class="cat-row"
:class="{ active: modelValue.includes(leaf.name) }"
@click="toggleLeaf(leaf.name)"
>
<span
class="cat-dot cat-dot-check"
:class="{ on: modelValue.includes(leaf.name) }"
aria-hidden="true"
></span>
<span class="cat-name" :title="leaf.name">{{ leaf.name }}</span>
<span class="cat-count">{{ leaf.productCount }}</span>
</div>
</div>
</div> </div>
</div> </div>
</template> </template>
@@ -265,10 +324,9 @@ function clear(): void {
} }
.cat-panel { .cat-panel {
/* fixed 浮层:位置由 toggle() 按触发框实际位置写 :style(top/left)。 /* fixed 浮层:位置由 toggle() 按触发框实际位置写 :style(top/left)。
* 建单页侧栏只有 ~370px,贴容器宽会把三栏压到每栏 ~120px(一级名截成「服饰…」); * 宽度随栏数自适应(200/栏 + 搜索态 300),cap 652 不撑文档横向滚动条。 */
* 三栏内容 200+200+250=650,宽度固定 652 向右展开,fixed 不撑文档横向滚动条。 */
position: fixed; position: fixed;
width: min(652px, calc(100vw - 16px)); max-width: min(860px, calc(100vw - 16px));
z-index: 2560; z-index: 2560;
display: flex; display: flex;
align-items: stretch; align-items: stretch;
@@ -288,8 +346,8 @@ function clear(): void {
.cat-col:last-child { .cat-col:last-child {
border-right: 0; border-right: 0;
} }
.cat-col-leaf { .cat-col-search {
width: 250px; width: 300px;
} }
/* 行=京麦同款:圆点 + 名称 + 右箭头;hover 浅蓝底。 */ /* 行=京麦同款:圆点 + 名称 + 右箭头;hover 浅蓝底。 */
.cat-row { .cat-row {
@@ -317,12 +375,7 @@ function clear(): void {
border-radius: 50%; border-radius: 50%;
background: #ffffff; background: #ffffff;
} }
/* radio 选中=京麦同款蓝芯;一级/二级的圆点是导航形状,不落选中态。 */ /* 导航圆点(非末级)=纯形状;末级=方点 checkbox。 */
.cat-dot.on {
border-color: #3b82c4;
background: radial-gradient(circle, #3b82c4 0 4px, #ffffff 4.6px);
}
/* 第三栏多选=方点 checkbox(与第一/二栏的导航圆点区分形状)。 */
.cat-dot-check { .cat-dot-check {
border-radius: 3px; border-radius: 3px;
} }
@@ -348,6 +401,16 @@ function clear(): void {
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
} }
/* 搜索态行尾的路径灰字(同名跨支时定位用)。 */
.cat-path {
flex: none;
max-width: 110px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: #9fb0c0;
font-size: 12px;
}
.cat-arrow { .cat-arrow {
flex: none; flex: none;
color: #9fb0c0; color: #9fb0c0;
@@ -359,10 +422,19 @@ function clear(): void {
color: #8293a5; color: #8293a5;
font-size: 12px; font-size: 12px;
} }
.cat-seg {
padding: 8px 12px 4px;
color: #8293a5;
font-size: 11.5px;
border-top: 1px solid #e7eef5;
}
.cat-search-row {
padding: 4px 8px 6px;
border-bottom: 1px solid #e7eef5;
}
.cat-search { .cat-search {
display: block; display: block;
width: calc(100% - 20px); width: 100%;
margin: 4px 10px 8px;
min-height: 30px; min-height: 30px;
padding: 4px 10px; padding: 4px 10px;
border: 1px solid #cbd9e6; border: 1px solid #cbd9e6;
+1 -1
View File
@@ -437,7 +437,7 @@ onUnmounted(() => {
<p class="category-hint"> <p class="category-hint">
{{ selectedCategories.length {{ selectedCategories.length
? `只采选中 ${selectedCategories.length} 个类目的商品;清空恢复全店采集。` ? `只采选中 ${selectedCategories.length} 个类目的商品;清空恢复全店采集。`
: '不选=全店采集。选项来自「京东数据库」已落库类目,新店铺先全店采一次即出。' }} : '不选=全店采集。类目树与京麦后台一致(按店铺授权类目逐级下钻到末级)。' }}
</p> </p>
</div> </div>
File diff suppressed because one or more lines are too long
+91 -13
View File
@@ -1,19 +1,97 @@
import { test } from 'node:test' import { test } from 'node:test'
import assert from 'node:assert/strict' import assert from 'node:assert/strict'
import { jdCategoryNavChildren, jdCategoryNavRoots } from '../src/pages/jd/jd-category-tree.ts' import {
JD_CATEGORY_TREE,
jdCategoryChildren,
jdCategoryLeaves,
jdCategoryRoots,
jdCategorySearchLeaves,
} from '../src/pages/jd/jd-category-tree.ts'
/** 建单页类目级联的静态导航树(与后管 admin-frontend-vue/tests/jd-product-group.test.ts /** 京麦授权类目真树(2026-11-16 真机取证 getVenderLicenseCategory 快照;与后管
* 同判据同数据——两份正本必须同形,改树两边同轮同步)。 */ * admin-frontend-vue 侧同数据两份正本,改树两边同轮同步)。判据钉的是取证读数:
test('类目级联静态导航树——服饰内衣二级与京麦面板样本逐字同源', () => { * 3 个一级 / 250 个末级 / 最深 4 级 / 5 个同名跨支——改树先对取证数据(京麦面板
assert.deepEqual(jdCategoryNavChildren('服饰内衣'), * 或 getVenderLicenseCategory 重抓),不得手改数字凑测试。 */
['服饰配件', '内衣', '女装', '男装', '定制服装/工装']) test('树形状=京麦授权类目真机读数:3 个一级、250 个末级、最深 4 级', () => {
assert.deepEqual(jdCategoryNavChildren('不存在的一级'), [], const roots = jdCategoryRoots()
'未知一级回落空子级(面板该栏缺省)') assert.deepEqual(
roots.map((node) => node.name),
['服饰内衣', '母婴', '运动户外'],
'一级就 3 个(京麦面板 2026-11-16 真机:该店铺授权经营类目,不得加回京东公开全量)',
)
assert.deepEqual(
roots.map((node) => node.value),
['1315', '1319', '1318'],
'一级类目 id 与取证响应逐字同',
)
const leaves = jdCategoryLeaves()
assert.equal(leaves.length, 250, '末级节点 250 个(取证读数)')
const maxDepth = Math.max(...leaves.map((leaf) => leaf.path.length))
assert.equal(maxDepth, 4, '树最深 4 级')
}) })
test('一级导航顺序——服饰内衣置首、不得重复、常用集在册', () => { test('服饰内衣二级与京麦面板逐字同源;逐级下钻到真机样本叶', () => {
const roots = jdCategoryNavRoots() assert.deepEqual(
assert.ok(roots.length >= 20, '一级类目常用集至少 20 个') jdCategoryChildren(['服饰内衣']).map((node) => node.name),
assert.equal(new Set(roots).size, roots.length, '一级类目不得重复') ['服饰配件', '内衣', '女装', '男装', '定制服装/工装'],
assert.equal(roots[0], '服饰内衣', '服饰内衣置首(客户主采类目)') '服饰内衣二级 5 个(京麦面板逐字)',
)
assert.deepEqual(
jdCategoryChildren(['服饰内衣', '服饰配件']).map((node) => node.name),
['腰带/腰链', '耳罩/耳包', '领带/领结/领带夹', '男士丝巾/围巾', '女士丝巾/围巾/披肩', '鸭舌帽',
'礼帽', '手套', '围巾/手套/帽子套装', '毛线帽', '遮阳帽', '棒球帽', '渔夫帽'],
'服饰配件三级 13 个(京麦面板 2026-11-16 截图逐字前 6 +取证快照全量)',
)
assert.deepEqual(
jdCategoryChildren(['服饰内衣', '服饰配件', '腰带/腰链']),
[],
'三级叶子 children 空(末级,可选中)',
)
assert.deepEqual(
jdCategoryChildren(['不存在的一级']),
[],
'未知路径回落空子级(面板该栏缺省)',
)
})
test('落库末级名真机样本都在树内(category_path 等值过滤成立的前提)', () => {
const names = new Set(jdCategoryLeaves().map((leaf) => leaf.name))
for (const sample of ['艺考形体服', '啦啦队服', '拉丁舞服']) {
assert.ok(names.has(sample), `真机样本「${sample}」必须是树内末级(契约 E3 口径)`)
}
const yikao = jdCategoryLeaves().find((leaf) => leaf.name === '艺考形体服')
assert.ok(yikao, '艺考形体服在树内')
assert.equal(yikao!.path.length, 3, '艺考形体服是 level 3 节点(取证读数)')
})
test('同名跨支叶子如实登记:4 组重名(同名行等值过滤一起命中,B112-05 口径)', () => {
const counts = new Map<string, number>()
for (const leaf of jdCategoryLeaves()) {
counts.set(leaf.name, (counts.get(leaf.name) ?? 0) + 1)
}
const dups = [...counts.entries()].filter(([, count]) => count > 1)
assert.deepEqual(
dups.map(([name]) => name).sort(),
['唐装', '吊带/背心', '短裤', '赠品'].sort(),
'重名集与取证读数逐字同(改树后这里红=重名集变了,须复核登记)。注:「汉服」两处节点中'
+ '一处带四级子级是非叶(点它会下钻),不构成末级重名。',
)
})
test('搜索:按名称或路径段命中末级;空词返回全量', () => {
assert.equal(jdCategorySearchLeaves('').length, 250, '空词=全量末级')
const byName = jdCategorySearchLeaves('艺考')
assert.equal(byName.length, 1)
assert.equal(byName[0]!.name, '艺考形体服')
const byPath = jdCategorySearchLeaves('服饰配件')
assert.ok(byPath.length >= 12, '按路径段命中服饰配件全部末级')
assert.ok(byPath.every((leaf) => leaf.path.includes('服饰配件')))
assert.deepEqual(jdCategorySearchLeaves('不存在词xyz'), [])
})
test('树数据快照不可空、value 全非空(取证 id 留档完整)', () => {
assert.ok(JD_CATEGORY_TREE.length > 0)
for (const leaf of jdCategoryLeaves()) {
assert.ok(leaf.value, `叶子 ${leaf.name} 必须带京麦类目 id`)
}
}) })
@@ -284,32 +284,41 @@ describe('获取店铺数据:一键采集 + 任务面板', () => {
}) })
it('勾选类目后建单:categoryPaths 随建单请求体与推送载荷同链下发', async () => { it('勾选类目后建单:categoryPaths 随建单请求体与推送载荷同链下发', async () => {
// 2026-11-16 用户口径「客户端前端也要同步加上京东类目」:多选面板勾「女装」后 // 2026-11-16 用户口径「客户端前端也要同步加上京东类目」+「你直接爬」:面板换京麦
// 建单请求体与推送载荷都要带 ['女装']——客户端按行 categoryPath 等值过滤的源头。 // 授权类目真树(逐级下钻、末级勾选)——下钻 运动户外 → 舞蹈体操鞋服/装备(客户
// 舞蹈服类目在京麦归运动户外支)→ 勾末级「艺考形体服」后建单请求体与推送载荷都要
// 带 ['艺考形体服'](客户端按行 categoryPath 等值过滤的源头;mock 类目用树内真实
// 末级名,贴合落库形状)。
api.fetchJdCollectCategories.mockResolvedValue([ api.fetchJdCollectCategories.mockResolvedValue([
{ name: '女装', productCount: 5 }, { name: '艺考形体服', productCount: 5 },
{ name: '男装', productCount: 3 }, { name: '啦啦队服', productCount: 3 },
]) ])
const w = await mountPage() const w = await mountPage()
await w.find('.cat-trigger').trigger('click') await w.find('.cat-trigger').trigger('click')
const leafRow = w.findAll('.cat-row').find((row) => row.text().includes('女装')) await w.findAll('.cat-col')[0].findAll('.cat-row').find((row) => row.text().includes('运动户外'))!.trigger('click')
expect(leafRow, '面板第三栏必须渲染出已落库类目选项').toBeTruthy() let cols = w.findAll('.cat-col')
expect(cols).toHaveLength(2, '点亮一级后第二栏出现(真树下钻)')
await cols[1].findAll('.cat-row').find((row) => row.text().includes('舞蹈体操鞋服/装备'))!.trigger('click')
cols = w.findAll('.cat-col')
expect(cols).toHaveLength(3, '二级非末级:第三栏出末级子级')
const leafRow = cols[2].findAll('.cat-row').find((row) => row.text().includes('艺考形体服'))
expect(leafRow, '第三栏必须渲染出该支的末级(艺考形体服)').toBeTruthy()
await leafRow!.trigger('click') await leafRow!.trigger('click')
await flushPromises() await flushPromises()
expect(w.find('.cat-trigger-text').text()).toBe('女装', '单选勾选后触发框显示类目名') expect(w.find('.cat-trigger-text').text()).toBe('艺考形体服', '单选勾选后触发框显示类目名')
await w.find('.cat-mask').trigger('click') await w.find('.cat-mask').trigger('click')
await startCollect(w) await startCollect(w)
expect(api.createJdCollectTask).toHaveBeenCalledWith('京麦后台', ['ONSALE', 'OFFSALE'], 0, ['女装']) expect(api.createJdCollectTask).toHaveBeenCalledWith('京麦后台', ['ONSALE', 'OFFSALE'], 0, ['艺考形体服'])
const payload = api.enqueue.mock.calls[0][0] const payload = api.enqueue.mock.calls[0][0]
expect(payload.data).toEqual({ expect(payload.data).toEqual({
taskId: 88, taskId: 88,
shopName: '京麦后台', shopName: '京麦后台',
listTabs: ['ONSALE', 'OFFSALE'], listTabs: ['ONSALE', 'OFFSALE'],
maxProducts: 0, maxProducts: 0,
categoryPaths: ['女装'], categoryPaths: ['艺考形体服'],
}) })
}) })