feat(菜单权限): 每家公司一套菜单树(V149)+ 公司 tab 只在注册表页渲染

本批两件事,加上随本批一起入仓的并行会话在制品:

一、菜单权限按公司隔离(批次 6)
- V149 给 columns 加 company_id:先可空加列(末位、ALGORITHM=INSTANT)→ 回填公司 1 →
  MODIFY 收紧 NOT NULL;三段式缺一即撞 1048。同时建 (company_id, column_key) 复合键、
  把公司 2 的 16 笔授权按 column_key 改指向它自己的副本,三类 menu_type 全复制,
  admin_companies 作为角色内生闸门行不复制(D3)。
- 第三道归属门 PermissionMenuService.resolveScopeCompanyId:站点超管可带 company_id
  读写任意公司,非超管锁本公司、越界 403。它注册进 CompanyIdParamGoesThroughReadScopeTest
  的 SCOPE_DOORS,四条判据与 readScope / readCompanyIdOrOwn 共用——护栏在代码出口,不靠清单。
- 旁路种子 PermissionMenuSchemaInitializer 只种公司 1:31 段种子逐条钉公司,
  按 column_key 点查的 14 段全部带 company_id,否则摘了 DEFAULT 就是跨公司串写。
- CompanyService.create 同一次写入里给新公司复制模板树(D4)。

二、公司 tab 收口(批次 b)
tab 条挂在壳层,对 22 页全画;改为按正列表 companyTabAppliesTo(menuKey) 判定,
只有注册表页渲染。护栏钉在用户看见的那个出口。

三、并行会话在制品(控制方「全部提交」,未单独拆分——见下)
- V150 店铺密钥 biz_shop_key 按公司(readCompanyIdOrOwn + writeCompanyId 两道门)
- V151 品牌库/商品类目推翻为全平台共享:只退唯一键、company_id DEFAULT 保留为
  NOT NULL 承重约束(摘了每条 1364);删掉 ProductCategoryControllerCompanyScopeTest
  那支"按公司隔离"的旧护栏,readCompanyId 方法一并移除
- invalidasin 字段与外观专利合批的连带改动

为什么不拆笔:后端 3891 例 / 0 红、前端 1731 例 / 0 红这两个读数是"合起来的树"的读数,
拆成多笔会让每一笔落到从未一起验过的组合上,而这一版要直接上两台。

回滚脚本在 backend-java/docs/rollback-V149/V150/V151-*.sql,不放进 Flyway 扫描路径。
设计记录:docs/ops/menu-company-tree-design-2026-10-06.md
This commit is contained in:
2026-10-06 17:17:14 +08:00
parent e635fa8dcd
commit b7acfc0eef
84 changed files with 5118 additions and 1421 deletions
@@ -12,7 +12,7 @@ const PAGES: Array<{ title: string; path: string; heading: string }> = [
{ title: '用户管理', path: '/admin-vue/account/users', heading: '用户列表' }, { title: '用户管理', path: '/admin-vue/account/users', heading: '用户列表' },
{ title: '菜单管理', path: '/admin-vue/account/menus', heading: '菜单' }, { title: '菜单管理', path: '/admin-vue/account/menus', heading: '菜单' },
{ title: '密钥管理', path: '/admin-vue/account/user-secrets', heading: '用户密钥列表' }, { title: '密钥管理', path: '/admin-vue/account/user-secrets', heading: '用户密钥列表' },
{ title: '不符合ASIN数据', path: '/admin-vue/asin-center/invalid', heading: '品牌数据列表' }, { title: '品牌数据库', path: '/admin-vue/asin-center/invalid', heading: '品牌数据列表' },
{ title: '数据去重总数据', path: '/admin-vue/asin-center/registry', heading: '数据去重总数据' }, { title: '数据去重总数据', path: '/admin-vue/asin-center/registry', heading: '数据去重总数据' },
{ title: '查询ASIN', path: '/admin-vue/asin-center/query', heading: '查询' }, { title: '查询ASIN', path: '/admin-vue/asin-center/query', heading: '查询' },
{ title: '最低价ASIN', path: '/admin-vue/asin-center/skip-price', heading: '最低价' }, { title: '最低价ASIN', path: '/admin-vue/asin-center/skip-price', heading: '最低价' },
+15 -3
View File
@@ -29,11 +29,12 @@ export const COMPANY_SCOPED_PAGES: readonly CompanyScopedPage[] = [
// 这一批把前端接线补齐。apiFiles 只列**真的把 company_id 拼进请求**的模块: // 这一批把前端接线补齐。apiFiles 只列**真的把 company_id 拼进请求**的模块:
// 各页的 *-filter.ts 与 asin-filter.ts 只带 camel 的 companyId 字段(类型 + 白名单构造都不点名它), // 各页的 *-filter.ts 与 asin-filter.ts 只带 camel 的 companyId 字段(类型 + 白名单构造都不点名它),
// 列进来会让正向判据去盯一个本来就不该出现 snake_case 的文件。 // 列进来会让正向判据去盯一个本来就不该出现 snake_case 的文件。
// 【这两页已于 2026-10-06 退出注册表】admin_invalid_asin_data(品牌数据库)与 admin_product_categories
// (商品类目)按控制方定案退回**全平台共享**,摘的不只是 tab:后端读写两侧的 company_id 谓词一起删
// (V151 退唯一键)。反向钉在 tests/company-tab-wiring.test.ts——把它们再加回来必须先推翻那条定案。
{ menuKey: 'admin_dedupe_total_data', apiFiles: ['src/pages/asin/dedupe-total-api.ts', 'src/pages/asin/dedupe-total-export.ts'], pageFiles: ['src/pages/asin/DedupeRegistryPage.vue'] }, { menuKey: 'admin_dedupe_total_data', apiFiles: ['src/pages/asin/dedupe-total-api.ts', 'src/pages/asin/dedupe-total-export.ts'], pageFiles: ['src/pages/asin/DedupeRegistryPage.vue'] },
{ menuKey: 'admin_invalid_asin_data', apiFiles: ['src/pages/invalidasin/invalid-asin-api.ts'], pageFiles: ['src/pages/asin/AsinInvalidPage.vue'] },
{ menuKey: 'admin_query_asin', apiFiles: ['src/pages/asin/query-asin-api.ts', 'src/pages/asin/query-asin-export.ts'], pageFiles: ['src/pages/asin/QueryAsinPage.vue'] }, { menuKey: 'admin_query_asin', apiFiles: ['src/pages/asin/query-asin-api.ts', 'src/pages/asin/query-asin-export.ts'], pageFiles: ['src/pages/asin/QueryAsinPage.vue'] },
{ menuKey: 'admin_skip_price_asin', apiFiles: ['src/pages/asin/skip-price-api.ts', 'src/pages/asin/skip-price-export.ts'], pageFiles: ['src/pages/asin/SkipPricePage.vue'] }, { menuKey: 'admin_skip_price_asin', apiFiles: ['src/pages/asin/skip-price-api.ts', 'src/pages/asin/skip-price-export.ts'], pageFiles: ['src/pages/asin/SkipPricePage.vue'] },
{ menuKey: 'admin_product_categories', apiFiles: ['src/pages/asin/product-category-api.ts', 'src/pages/asin/product-category-export.ts'], pageFiles: ['src/pages/asin/ProductCategoryPage.vue'] },
// 批次 3(控制方 2026-10-05 点名「店铺撞款监控 店铺数据也要做隔离」)。这两页的可见集不是按 company_id 列筛的, // 批次 3(控制方 2026-10-05 点名「店铺撞款监控 店铺数据也要做隔离」)。这两页的可见集不是按 company_id 列筛的,
// 而是「本公司账号名下的店铺」:后端由 DataReadScope 把公司 → 成员账号 → biz_shop_manage.created_by_id 逐级推导, // 而是「本公司账号名下的店铺」:后端由 DataReadScope 把公司 → 成员账号 → biz_shop_manage.created_by_id 逐级推导,
// 前端只负责把 activeId 当 company_id 送下去。 // 前端只负责把 activeId 当 company_id 送下去。
@@ -42,5 +43,16 @@ export const COMPANY_SCOPED_PAGES: readonly CompanyScopedPage[] = [
// 批次 4(控制方 2026-10-05 点名「菜单权限和用户管理也要区分公司 tab 的数据」)。 // 批次 4(控制方 2026-10-05 点名「菜单权限和用户管理也要区分公司 tab 的数据」)。
// 这一页的后端早就认 company_id(AdminUserService 只在**站点超管**身上用它筛,公司超管恒锁本公司), // 这一页的后端早就认 company_id(AdminUserService 只在**站点超管**身上用它筛,公司超管恒锁本公司),
// 断的是前端:users-dto 的 UserListQuery 里连这个字段都没有 ⇒ 三家 tab 看到的是同一份全量列表。 // 断的是前端:users-dto 的 UserListQuery 里连这个字段都没有 ⇒ 三家 tab 看到的是同一份全量列表。
{ menuKey: 'admin_users', apiFiles: ['src/api/users.ts'], pageFiles: ['src/pages/account/UsersPage.vue'] }, { menuKey: 'admin_users', apiFiles: ['src/api/users.ts', 'src/pages/account/user-menu-auth-api.ts'], pageFiles: ['src/pages/account/UsersPage.vue'] },
// 批次 5(控制方 2026-10-06 点名「店铺密钥管理的数据按照公司区分」)。biz_shop_key 原先零归属列,
// 拿到这一页菜单的任意管理员读的是同一池全平台紫鸟令牌,而列表 VO 把令牌原文整列下发(悬停即得全文)。
// V150 加 company_id;后端读门是 readCompanyIdOrOwn ⇒ 非超管连 company_id 都不带也一律锁本公司,
// 这一页的 tab 只对超管改变行数(与其余页同形,见 COMPANY_TAB_GUIDE_NOTE 开头那句「超级管理员」)。
{ menuKey: 'admin_shop_keys', apiFiles: ['src/pages/shop/shop-key-api.ts'], pageFiles: ['src/pages/shop/ShopKeysPage.vue'] },
// 批次 6(控制方 2026-10-06 点名「菜单权限也加字段来区分」,并选了「每家公司一套菜单树」那一档)。
// V149 给 columns 加 company_id 并把 52 行复制成每家一套 ⇒ 同一 column_key 在别家有另一份 id:
// 不带 company_id 时超管拿到的是两家混在一起的目录(两排同名菜单),勾出来的 id 又会撞
// 「无效的菜单权限项」。写侧(编辑/删除/重排)不带参数——归属由那一行的 id 与操作者公司共同判定,
// 跨公司写后端 403(见 docs/ops/menu-company-tree-design-2026-10-06.md §5)。
{ menuKey: 'admin_columns', apiFiles: ['src/pages/account/menu-manage-api.ts'], pageFiles: ['src/pages/account/MenusPage.vue'] },
] ]
@@ -1,16 +1,19 @@
<script setup lang="ts"> <script setup lang="ts">
/** 页面上方的公司 tab(spec §4、§9.3):只有超管看得到,选中哪家由哪一枚 tab 带 is-active 表达—— /** 页面上方的公司 tab(spec §4、§9.3):只有超管看得到,而且只画在**注册表里真的按公司取数的那些页**上——
* 这里不再挂第二处"这家是谁"的文案(§12 第 5 条把页头提示条算未批的界面暴露), * 选中哪家由哪一枚 tab 带 is-active 表达,这里不再挂第二处"这家是谁"的文案(§12 第 5 条把页头提示条算未批的界面暴露),
* 观感说明走 operation-guides 的引导文案。 */ * 观感说明走 operation-guides 的引导文案。 */
import { computed, watch } from 'vue' import { computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import { COMPANY_STATUS_ACTIVE } from '@/api/companies-dto' import { COMPANY_STATUS_ACTIVE } from '@/api/companies-dto'
import { useCompanyTabStore } from '@/stores/company-tab' import { useCompanyTabStore } from '@/stores/company-tab'
import { useAdminSessionStore } from '@/stores/admin-session' import { useAdminSessionStore } from '@/stores/admin-session'
import { companyTabAppliesTo } from '@/layout/company-tab-model'
const route = useRoute()
const tab = useCompanyTabStore() const tab = useCompanyTabStore()
const session = useAdminSessionStore() const session = useAdminSessionStore()
const tabs = computed(() => tab.companies.filter((c) => c.status === COMPANY_STATUS_ACTIVE)) const tabs = computed(() => tab.companies.filter((c) => c.status === COMPANY_STATUS_ACTIVE))
const show = computed(() => tab.visibleForOperator) const show = computed(() => tab.visibleForOperator && companyTabAppliesTo(route.meta.menuKey))
watch(() => session.isSuperAdmin, (v) => { watch(() => session.isSuperAdmin, (v) => {
if (!v) return if (!v) return
@@ -1,8 +1,22 @@
/** 公司 tab 的两支纯函数(store 与护栏用例共用,不依赖 pinia / 组件)。 /** 公司 tab 的三支纯函数(store 与护栏用例共用,不依赖 pinia / 组件)。
* import 用相对路径 + 显式 `.ts`:本文件被 tests 以 `node --test` 直接 import,而测试侧没有 * import 用相对路径 + 显式 `.ts`:本文件被 tests 以 `node --test` 直接 import,而测试侧没有
* vite 的 `@` 别名解析器,写成 `@/api/...` 会 ERR_MODULE_NOT_FOUND(护栏因此读源码而非常规 import, * vite 的 `@` 别名解析器,写成 `@/api/...` 会 ERR_MODULE_NOT_FOUND(护栏因此读源码而非常规 import,
* 见 tests/company-tab-wiring.test.ts 用 readSource 的原因)。 */ * 见 tests/company-tab-wiring.test.ts 用 readSource 的原因)。 */
import { COMPANY_STATUS_ACTIVE, type CompanyItem } from '../api/companies-dto.ts' import { COMPANY_STATUS_ACTIVE, type CompanyItem } from '../api/companies-dto.ts'
import { COMPANY_SCOPED_PAGES } from '../config/company-scope.ts'
/** 参与公司隔离的页(注册表那份 menuKey 的集合形态)。判据**只有这一份来源**:
* 另立一张"哪些页不画 tab"的黑名单,下一个新页会默认长出一条点了没反应的 tab(2026-10-06 的成因)。 */
const SCOPED_MENU_KEYS: ReadonlySet<string> = new Set(COMPANY_SCOPED_PAGES.map((page) => page.menuKey))
/**
* 这一页切了公司**有没有用**。与 store 的 `visibleForOperator` 是两个正交问题,不是同一问的两把尺子:
* 那一条答「目录取到了吗、这名下有几家可切」,这一条答「当前这页吃不吃公司维度」。
* 壳层把 tab 挂在所有页上时,公司管理页头顶就压着一排点了不重取数的 tab(控制方 2026-10-06 点名)。
*/
export function companyTabAppliesTo(menuKey: unknown): boolean {
return typeof menuKey === 'string' && SCOPED_MENU_KEYS.has(menuKey)
}
/** 超管的读范围公司。非超管恒 null——它的公司是固定的,下传一个常数只会让人以为这页在按公司筛。 */ /** 超管的读范围公司。非超管恒 null——它的公司是固定的,下传一个常数只会让人以为这页在按公司筛。 */
export function companyIdForRequest(isSuperAdmin: boolean, activeId: number | null): number | null { export function companyIdForRequest(isSuperAdmin: boolean, activeId: number | null): number | null {
@@ -21,7 +21,7 @@ export const OPERATION_GUIDE_STORAGE_KEY = 'shufuAdminGuideCollapsed'
* (§12 第 5 条把那种提示条算未批的界面暴露;当前哪一家由 is-active 的 tab 表达,一处事实不留两处)。 * (§12 第 5 条把那种提示条算未批的界面暴露;当前哪一家由 is-active 的 tab 表达,一处事实不留两处)。
* 这句必须以「超级管理员」开头、不能写成祈使式的「由上方 tab 决定」:引导文案按 menuKey 取、 * 这句必须以「超级管理员」开头、不能写成祈使式的「由上方 tab 决定」:引导文案按 menuKey 取、
* 不分支角色,而非超管根本看不到 tab 条(company-tab store 的 visibleForOperator 里有 isSuperAdmin)。 * 不分支角色,而非超管根本看不到 tab 条(company-tab store 的 visibleForOperator 里有 isSuperAdmin)。
* 这一句由参与 tab 的 13 页共用、不各抄一遍——文案差一个字,护栏就只盯得住其中一页。 * 这一句由参与 tab 的 14 页共用、不各抄一遍——文案差一个字,护栏就只盯得住其中一页。
* 由 tests/align-operation-guide.test.ts 的 guide_copy_carries_company_tab_note_for_every_scoped_page * 由 tests/align-operation-guide.test.ts 的 guide_copy_carries_company_tab_note_for_every_scoped_page
* 按 COMPANY_SCOPED_PAGES 逐页盯着(分母取注册表,加一页忘了补文案会当场红)。 */ * 按 COMPANY_SCOPED_PAGES 逐页盯着(分母取注册表,加一页忘了补文案会当场红)。 */
const COMPANY_TAB_GUIDE_NOTE = ' 超级管理员可用页面上方的公司 tab 切换公司,切换后行数会变化——行数变少不是数据丢了。' const COMPANY_TAB_GUIDE_NOTE = ' 超级管理员可用页面上方的公司 tab 切换公司,切换后行数会变化——行数变少不是数据丢了。'
@@ -42,7 +42,10 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
steps: ['筛选账号', '编辑权限', '确认保存'], steps: ['筛选账号', '编辑权限', '确认保存'],
}, },
admin_columns: { admin_columns: {
text: '菜单会影响后台和软件端的可见范围。先填写名称并选择对应页面,再设置上级菜单;顺序直接拖动列表左侧手柄调整。', // 2026-10-06 批次 6:V149 起每家公司一套菜单树 ⇒ 这页参与公司 tab,必须带上 §9.3 那句
// (align-operation-guide 按注册表数分母,缺了它当场红)。
text: '菜单会影响后台和软件端的可见范围。先填写名称并选择对应页面,再设置上级菜单;顺序直接拖动列表左侧手柄调整。'
+ COMPANY_TAB_GUIDE_NOTE,
steps: ['新增或调整菜单', '设置层级', '拖动排序'], steps: ['新增或调整菜单', '设置层级', '拖动排序'],
}, },
admin_group_manage: { admin_group_manage: {
@@ -69,7 +72,7 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
}, },
admin_invalid_asin_data: { admin_invalid_asin_data: {
text: '维护不符合规则的 ASIN 或品牌。添加后可使用上方筛选快速回查。' text: '维护不符合规则的 ASIN 或品牌。添加后可使用上方筛选快速回查。'
+ COMPANY_TAB_GUIDE_NOTE, + COMPANY_SCOPE_NOT_APPLIED_NOTE,
steps: ['填写 ASIN/品牌', '选择分组', '保存并回查'], steps: ['填写 ASIN/品牌', '选择分组', '保存并回查'],
}, },
admin_query_asin: { admin_query_asin: {
@@ -79,7 +82,7 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
}, },
admin_product_categories: { admin_product_categories: {
text: '类目树支持展开查看层级。搜索、编辑和删除都在同一列表中完成。' text: '类目树支持展开查看层级。搜索、编辑和删除都在同一列表中完成。'
+ COMPANY_TAB_GUIDE_NOTE, + COMPANY_SCOPE_NOT_APPLIED_NOTE,
steps: ['搜索类目', '展开层级', '新增或编辑'], steps: ['搜索类目', '展开层级', '新增或编辑'],
}, },
admin_skip_price_asin: { admin_skip_price_asin: {
@@ -88,8 +91,10 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
steps: ['筛选店铺', '打开配置抽屉', '保存或批量导入'], steps: ['筛选店铺', '打开配置抽屉', '保存或批量导入'],
}, },
admin_shop_keys: { admin_shop_keys: {
// 2026-10-06 批次 5:这页由「全平台共享」改按公司区分(V150 给 biz_shop_key 加 company_id),
// 所以摘掉 COMPANY_SCOPE_NOT_APPLIED_NOTE、换上共用那一句 §9.3。
text: '紫鸟令牌属于敏感配置。白名单状态可悬停查看检测详情,编辑前请先核对账号名称。' text: '紫鸟令牌属于敏感配置。白名单状态可悬停查看检测详情,编辑前请先核对账号名称。'
+ COMPANY_SCOPE_NOT_APPLIED_NOTE, + COMPANY_TAB_GUIDE_NOTE,
steps: ['新增或筛选密钥', '查看白名单状态', '编辑或删除'], steps: ['新增或筛选密钥', '查看白名单状态', '编辑或删除'],
}, },
admin_shop_manage: { admin_shop_manage: {
@@ -117,11 +122,13 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
steps: ['设置时间范围', '筛选记录', '查看结果预览'], steps: ['设置时间范围', '筛选记录', '查看结果预览'],
}, },
admin_version: { admin_version: {
text: '上传版本后请核对版本号和下载链接,再通知用户更新。', text: '上传版本后请核对版本号和下载链接,再通知用户更新。'
+ COMPANY_SCOPE_NOT_APPLIED_NOTE,
steps: ['上传压缩包', '检查版本记录', '维护历史版本'], steps: ['上传压缩包', '检查版本记录', '维护历史版本'],
}, },
admin_tutorial: { admin_tutorial: {
text: '上传新的教程压缩包后即刻生效:工具台首页「立即下载教程」以下载最新上传的包为准。确认旧包不再需要后再删除。', text: '上传新的教程压缩包后即刻生效:工具台首页「立即下载教程」以下载最新上传的包为准。确认旧包不再需要后再删除。'
+ COMPANY_SCOPE_NOT_APPLIED_NOTE,
steps: ['上传教程压缩包', '到工具台核对下载', '清理历史包'], steps: ['上传教程压缩包', '到工具台核对下载', '清理历史包'],
}, },
digital_human_version: { digital_human_version: {
@@ -155,7 +155,7 @@ async function create(): Promise<void> {
</el-form-item> </el-form-item>
<el-form-item label="菜单权限(勾选上级菜单会继承全部子菜单)"> <el-form-item label="菜单权限(勾选上级菜单会继承全部子菜单)">
<div class="auth-tree-box"> <div class="auth-tree-box">
<UserMenuAuthTree v-model:checked="form.columnIds" /> <UserMenuAuthTree v-model:checked="form.columnIds" :company-id="form.companyId" />
</div> </div>
</el-form-item> </el-form-item>
</el-form> </el-form>
@@ -9,7 +9,9 @@ import { showAdminFeedback } from '@/components/admin-feedback-ui'
import { actionableErrorText } from '@/components/admin-feedback' import { actionableErrorText } from '@/components/admin-feedback'
import UserMenuAuthTree from './UserMenuAuthTree.vue' import UserMenuAuthTree from './UserMenuAuthTree.vue'
const props = defineProps<{ modelValue: boolean; user: AdminUser | null; operatorSuper?: boolean }>() /** companyId 由 UsersPage 把 companyTab.requestCompanyId 透传进来(本页的用户列表本来就由它筛 ⇒ 目标账号的公司
* 就是 tab 选中的那家);弹窗自己不读 store,公司 tab 的取值口只留在页面组件那一处。 */
const props = defineProps<{ modelValue: boolean; user: AdminUser | null; operatorSuper?: boolean; companyId?: number | null }>()
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'updated'): void }>() const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'updated'): void }>()
const form = reactive<EditUserForm>({ uid: 0, username: '', password: '', role: 'normal', columnIds: [], originalRole: '', expiresAt: '' }) const form = reactive<EditUserForm>({ uid: 0, username: '', password: '', role: 'normal', columnIds: [], originalRole: '', expiresAt: '' })
@@ -48,7 +50,7 @@ async function refreshAuth(): Promise<void> {
if (!props.user) return if (!props.user) return
loadingAuth.value = true loadingAuth.value = true
try { try {
const { checkedIds } = await loadUserMenuAuth(props.user.id) const { checkedIds } = await loadUserMenuAuth(props.user.id, props.companyId)
form.columnIds = checkedIds form.columnIds = checkedIds
authReady.value = true authReady.value = true
} catch (error) { } catch (error) {
@@ -133,7 +135,7 @@ async function save(): Promise<void> {
</el-form-item> </el-form-item>
<el-form-item label="菜单权限(勾选上级菜单会继承全部子菜单)"> <el-form-item label="菜单权限(勾选上级菜单会继承全部子菜单)">
<div class="auth-tree-box"> <div class="auth-tree-box">
<UserMenuAuthTree v-model:checked="form.columnIds" /> <UserMenuAuthTree v-model:checked="form.columnIds" :company-id="props.companyId" />
<div v-if="loadingAuth" class="auth-loading">菜单权限加载中…</div> <div v-if="loadingAuth" class="auth-loading">菜单权限加载中…</div>
<div v-else-if="!authReady" class="auth-loading auth-loading-error"> <div v-else-if="!authReady" class="auth-loading auth-loading-error">
菜单权限加载失败,保存已禁用;请关闭后重试 菜单权限加载失败,保存已禁用;请关闭后重试
@@ -2,9 +2,10 @@
import { formatDateTime } from '@/utils/datetime' import { formatDateTime } from '@/utils/datetime'
/** 菜单权限配置页 · 像素复刻旧版 admin.html panel-columns(自绘:面板头+新增菜单、拖拽手柄 ⠿、树形缩进+└、旧式表格、全量无分页同旧版)。 /** 菜单权限配置页 · 像素复刻旧版 admin.html panel-columns(自绘:面板头+新增菜单、拖拽手柄 ⠿、树形缩进+└、旧式表格、全量无分页同旧版)。
* script 逻辑沿用现有 Vue 实现(拖拽分组/落点/重排保存、弹窗表单)。 */ * script 逻辑沿用现有 Vue 实现(拖拽分组/落点/重排保存、弹窗表单)。 */
import { computed, onMounted, reactive, ref } from 'vue' import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import OldPagination from '@/components/OldPagination.vue' import OldPagination from '@/components/OldPagination.vue'
import { useCompanyTabStore } from '@/stores/company-tab'
import { createMenu, deleteMenu, loadMenuManageTree, reorderMenus, updateMenu } from './menu-manage-api' import { createMenu, deleteMenu, loadMenuManageTree, reorderMenus, updateMenu } from './menu-manage-api'
import { import {
MENU_TYPE_OPTIONS, MENU_TYPE_OPTIONS,
@@ -28,6 +29,7 @@ interface MenuRow extends MenuManageNode {
depth: number depth: number
} }
const companyTab = useCompanyTabStore()
const loading = ref(false) const loading = ref(false)
const rows = ref<MenuManageNode[]>([]) const rows = ref<MenuManageNode[]>([])
/** 筛选:菜单名称/类型(用户要求账户域子菜单补筛选条件)。 */ /** 筛选:菜单名称/类型(用户要求账户域子菜单补筛选条件)。 */
@@ -84,7 +86,7 @@ function parentNameOf(node: MenuManageNode): string {
async function loadMenus() { async function loadMenus() {
loading.value = true loading.value = true
try { try {
rows.value = await loadMenuManageTree() rows.value = await loadMenuManageTree(companyTab.requestCompanyId)
} catch (error) { } catch (error) {
ElMessage.error(error instanceof Error ? error.message : '菜单列表加载失败') ElMessage.error(error instanceof Error ? error.message : '菜单列表加载失败')
} finally { } finally {
@@ -175,7 +177,7 @@ async function saveMenu() {
await updateMenu(editingNode.value.id, menuForm) await updateMenu(editingNode.value.id, menuForm)
ElMessage.success('保存成功') ElMessage.success('保存成功')
} else { } else {
await createMenu(menuForm) await createMenu(menuForm, companyTab.requestCompanyId)
ElMessage.success('创建成功') ElMessage.success('创建成功')
} }
createVisible.value = false createVisible.value = false
@@ -204,6 +206,11 @@ async function removeMenu(node: MenuManageNode) {
} }
} }
/** 切公司:菜单名称/类型是客户端筛选(在 filteredMenuRows 上筛,不进请求),留着上一家填的值
* 就是拿别家的字符串去筛新一家那一套树 ⇒ 首屏「暂无匹配菜单」而输入框里还显示着它;页码回 1
* 是因为新一家的行数不同。末尾的 void loadMenus() 才是本页唯一的数据出口。 */
watch(() => companyTab.activeId, () => { filterName.value = ''; filterType.value = ''; page.value = 1; void loadMenus() })
onMounted(loadMenus) onMounted(loadMenus)
</script> </script>
@@ -4,7 +4,7 @@ import type { MenuOptionNode } from './user-menu-auth'
import { compactDirectGrantIds } from './user-menu-auth' import { compactDirectGrantIds } from './user-menu-auth'
import { fetchGrantableMenus } from './user-menu-auth-api' import { fetchGrantableMenus } from './user-menu-auth-api'
const props = defineProps<{ checked?: number[] }>() const props = defineProps<{ checked?: number[]; companyId?: number | null }>()
const emit = defineEmits<{ const emit = defineEmits<{
(e: 'update:checked', ids: number[]): void (e: 'update:checked', ids: number[]): void
(e: 'load', ok: boolean): void (e: 'load', ok: boolean): void
@@ -42,7 +42,7 @@ function onCheck(): void {
async function load(): Promise<void> { async function load(): Promise<void> {
try { try {
data.value = await fetchGrantableMenus() data.value = await fetchGrantableMenus(props.companyId)
loaded.value = true loaded.value = true
emit('load', true) emit('load', true)
// el-tree 的 store 通过异步 watch 同步 props.data,setCheckedKeys 必须等树 // el-tree 的 store 通过异步 watch 同步 props.data,setCheckedKeys 必须等树
@@ -62,6 +62,12 @@ watch(
if (loaded.value) applyChecked() if (loaded.value) applyChecked()
}, },
) )
/** 公司换了要整棵重取:勾选集里存的是 column id,别家同名菜单是另一份 id(V149 每公司一套树),
* 拿别家的树勾出来的 id 提交会被后端判「无效的菜单权限项」,而已授权项也因为 id 不在这棵树上勾不上。 */
watch(
() => props.companyId,
() => { void load() },
)
</script> </script>
<template> <template>
@@ -260,7 +260,7 @@ onMounted(() => {
:company-options="companyOptions" :company-options="companyOptions"
@created="loadUsers" @created="loadUsers"
/> />
<EditUserDialog v-model="editVisible" :user="editUser" :operator-super="isSuperAdmin" @updated="loadUsers" /> <EditUserDialog v-model="editVisible" :user="editUser" :operator-super="isSuperAdmin" :company-id="companyTab.requestCompanyId" @updated="loadUsers" />
</div> </div>
</template> </template>
@@ -14,20 +14,27 @@ import {
export const MENUS_ENDPOINT = '/api/admin/permission-menus' export const MENUS_ENDPOINT = '/api/admin/permission-menus'
export const REORDER_ENDPOINT = '/api/admin/column/reorder' export const REORDER_ENDPOINT = '/api/admin/column/reorder'
/** 拉取扁平可编辑菜单节点(全量类型,对齐 admin.js loadColumns 的 /api/admin/columns 语义)。 */ /** 拉取扁平可编辑菜单节点(全量类型,对齐 admin.js loadColumns 的 /api/admin/columns 语义)。
export async function fetchMenuManageNodes(): Promise<MenuManageNode[]> { * 公司 tab 的值由调用方(MenusPage)传 companyTab.requestCompanyId:菜单字典 2026-10-06 起每家公司一套树,
const { data } = await http.get<unknown>(MENUS_ENDPOINT) * 不带 company_id 时非超管恒锁本公司、超管拿到的是全部公司的行(两排同名菜单)。 */
export async function fetchMenuManageNodes(companyId?: number | null): Promise<MenuManageNode[]> {
const query: Record<string, string | number> = {}
if (companyId != null) query.company_id = companyId
const { data } = await http.get<unknown>(MENUS_ENDPOINT, { params: query })
return parseMenuManageList(data) return parseMenuManageList(data)
} }
/** 拉取并按 parentId 组装成展示树。 */ /** 拉取并按 parentId 组装成展示树。 */
export async function loadMenuManageTree(): Promise<MenuManageNode[]> { export async function loadMenuManageTree(companyId?: number | null): Promise<MenuManageNode[]> {
return buildMenuManageTree(await fetchMenuManageNodes()) return buildMenuManageTree(await fetchMenuManageNodes(companyId))
} }
/** 新建菜单:POST /api/admin/permission-menus,返回后端落库节点。 */ /** 新建菜单:POST /api/admin/permission-menus,返回后端落库节点。
export async function createMenu(form: MenuManageForm): Promise<MenuManageNode> { * 归属由端点的 company_id 决定(缺省=操作者本公司),前端不靠从树里猜。 */
const { data } = await http.post<unknown>(MENUS_ENDPOINT, toMenuCreateRequest(form)) export async function createMenu(form: MenuManageForm, companyId?: number | null): Promise<MenuManageNode> {
const query: Record<string, string | number> = {}
if (companyId != null) query.company_id = companyId
const { data } = await http.post<unknown>(MENUS_ENDPOINT, toMenuCreateRequest(form), { params: query })
const created = parseMenuManageItem(unwrap<unknown>(data)) const created = parseMenuManageItem(unwrap<unknown>(data))
if (!created) throw new Error('创建菜单响应异常:缺少菜单数据') if (!created) throw new Error('创建菜单响应异常:缺少菜单数据')
return created return created
@@ -18,11 +18,18 @@ export const USER_PERMISSION_COLUMNS_ENDPOINT = '/api/admin/permission-users'
/** /**
* 拉取可授权菜单树(后台 admin + 前端客户端 app 两类合并,按 sort 排序)。 * 拉取可授权菜单树(后台 admin + 前端客户端 app 两类合并,按 sort 排序)。
* grantableOnly:非超管只拿到自己已持有的菜单,范围外的项后端不再下发。 * grantableOnly:非超管只拿到自己已持有的菜单,范围外的项后端不再下发。
* <p>companyId 传 companyTab.requestCompanyId:2026-10-06 起每家公司一套菜单树,同一 column_key 在
* 别家有一份**不同 id** 的副本。这一页的授权载荷提交的是 column id,树取错公司就等于
* 把别家的 id 授给本公司账号(后端按「id 必须在被授权账号自己的树里」拒 ⇒ 保存必然失败,
* 而已授权项因为 id 对不上树根本勾不上,看上去像"这个人一条权限都没有")。
* null(非超管、或建号时没指定公司)由后端锁到操作者本公司。
*/ */
export async function fetchGrantableMenus(): Promise<MenuOptionNode[]> { export async function fetchGrantableMenus(companyId?: number | null): Promise<MenuOptionNode[]> {
const query: Record<string, string | number> = {}
if (companyId != null) query.company_id = companyId
const [adminRes, appRes] = await Promise.all([ const [adminRes, appRes] = await Promise.all([
http.get<unknown>(GRANT_MENUS_ENDPOINT, { params: { menuType: ADMIN_MENU_TYPE, grantableOnly: true } }), http.get<unknown>(GRANT_MENUS_ENDPOINT, { params: { ...query, menuType: ADMIN_MENU_TYPE, grantableOnly: true } }),
http.get<unknown>(GRANT_MENUS_ENDPOINT, { params: { menuType: APP_MENU_TYPE, grantableOnly: true } }), http.get<unknown>(GRANT_MENUS_ENDPOINT, { params: { ...query, menuType: APP_MENU_TYPE, grantableOnly: true } }),
]) ])
const nodes = [ const nodes = [
...parseMenuOptionList(adminRes.data, ADMIN_MENU_TYPE), ...parseMenuOptionList(adminRes.data, ADMIN_MENU_TYPE),
@@ -53,8 +60,8 @@ export interface UserMenuAuthData {
checkedIds: number[] checkedIds: number[]
} }
export async function loadUserMenuAuth(userId: number): Promise<UserMenuAuthData> { export async function loadUserMenuAuth(userId: number, companyId?: number | null): Promise<UserMenuAuthData> {
const [tree, checkedIds] = await Promise.all([fetchGrantableMenus(), fetchUserGrantedColumnIds(userId)]) const [tree, checkedIds] = await Promise.all([fetchGrantableMenus(companyId), fetchUserGrantedColumnIds(userId)])
return { tree, checkedIds } return { tree, checkedIds }
} }
@@ -5,7 +5,6 @@ import { formatDateTime } from '@/utils/datetime'
import { computed, onMounted, reactive, ref, watch } from 'vue' import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus' import { ElMessage } from 'element-plus'
import { useAdminSessionStore } from '@/stores/admin-session' import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
import { createInvalidAsin, deleteInvalidAsin, fetchInvalidAsinPage, updateInvalidAsin } from '../invalidasin/invalid-asin-api.ts' import { createInvalidAsin, deleteInvalidAsin, fetchInvalidAsinPage, updateInvalidAsin } from '../invalidasin/invalid-asin-api.ts'
import type { InvalidAsinItem } from '../invalidasin/invalid-asin-model.ts' import type { InvalidAsinItem } from '../invalidasin/invalid-asin-model.ts'
import { invalidAsinDeleteText, invalidAsinLockedGroupId, recordSourceLabel } from '../invalidasin/invalid-asin-model.ts' import { invalidAsinDeleteText, invalidAsinLockedGroupId, recordSourceLabel } from '../invalidasin/invalid-asin-model.ts'
@@ -15,7 +14,6 @@ import type { ShopGroupOption } from '../shop/shop-dto.ts'
import OldPagination from '@/components/OldPagination.vue' import OldPagination from '@/components/OldPagination.vue'
const session = useAdminSessionStore() const session = useAdminSessionStore()
const companyTab = useCompanyTabStore()
const loading = ref(false) const loading = ref(false)
const rows = ref<InvalidAsinItem[]>([]) const rows = ref<InvalidAsinItem[]>([])
const total = ref(0) const total = ref(0)
@@ -46,7 +44,7 @@ const groupOptions = computed<ShopGroupOption[]>(() => {
async function loadGroups() { async function loadGroups() {
try { try {
groups.value = await fetchShopManageGroups(companyTab.requestCompanyId) groups.value = await fetchShopManageGroups()
} catch { } catch {
groups.value = [] groups.value = []
} }
@@ -65,7 +63,6 @@ async function load() {
dataValue: filter.dataValue.trim() || undefined, dataValue: filter.dataValue.trim() || undefined,
brand: filter.brand.trim() || undefined, brand: filter.brand.trim() || undefined,
groupId: filter.groupId, groupId: filter.groupId,
companyId: companyTab.requestCompanyId,
}) })
rows.value = result.items rows.value = result.items
total.value = result.total total.value = result.total
@@ -163,10 +160,6 @@ watch(isSuperAdmin, () => {
if (isSuperAdmin.value) filter.groupId = null if (isSuperAdmin.value) filter.groupId = null
}) })
// 切公司 = 重新取数:列表与分组下拉共用这一个 watch(少一个 = 那半边的 tab 是装饰品)。
// groupId 必须一起清掉:上一家选中的分组在新一家根本不存在,留着会把切 tab 后的首屏筛成空列表。
watch(() => companyTab.activeId, () => { filter.groupId = null; void loadGroups(); void load() })
onMounted(() => { onMounted(() => {
loadGroups() loadGroups()
load() load()
@@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
/** 商品类目 · 像素复刻旧版 admin.html panel-product-categories(自绘:面板头搜索框组+新增类目 同行、原生树表格[+/−]折叠+懒加载「加载更多 已加载 x/y」、搜索态旧式分页)。 /** 商品类目 · 像素复刻旧版 admin.html panel-product-categories(自绘:面板头搜索框组+新增类目 同行、原生树表格[+/−]折叠+懒加载「加载更多 已加载 x/y」、搜索态旧式分页)。
* script 逻辑沿用现有 Vue 实现(懒加载树/编辑删除/导出/弹窗)。 */ * script 逻辑沿用现有 Vue 实现(懒加载树/编辑删除/导出/弹窗)。 */
import { computed, onMounted, reactive, ref, watch } from 'vue' import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import { fetchProductCategoryChildren, searchProductCategories } from './product-category-api.ts' import { fetchProductCategoryChildren, searchProductCategories } from './product-category-api.ts'
import { createProductCategory, deleteProductCategory, updateProductCategory } from './product-category-editor-api.ts' import { createProductCategory, deleteProductCategory, updateProductCategory } from './product-category-editor-api.ts'
@@ -17,9 +17,7 @@ import { categoryDraftError, createProductCategoryDraft, toCategorySaveRequest,
import { buildProductCategoryExportUrl } from './product-category-export.ts' import { buildProductCategoryExportUrl } from './product-category-export.ts'
import { formatDateTime } from '@/utils/datetime' import { formatDateTime } from '@/utils/datetime'
import OldPagination from '@/components/OldPagination.vue' import OldPagination from '@/components/OldPagination.vue'
import { useCompanyTabStore } from '@/stores/company-tab'
const companyTab = useCompanyTabStore()
const loading = ref(false) const loading = ref(false)
const tree = ref<ProductCategoryNode[]>([]) const tree = ref<ProductCategoryNode[]>([])
const keyword = ref('') const keyword = ref('')
@@ -70,7 +68,7 @@ const rootTotal = ref(0)
async function loadTree(): Promise<void> { async function loadTree(): Promise<void> {
loading.value = true loading.value = true
try { try {
const result = await fetchProductCategoryChildren(null, rootPage.value, rootPageSize.value, companyTab.requestCompanyId) const result = await fetchProductCategoryChildren(null, rootPage.value, rootPageSize.value)
const state = { page: result.page, total: result.total, hasMore: result.hasMore, loading: false } const state = { page: result.page, total: result.total, hasMore: result.hasMore, loading: false }
childrenState.set(ROOT_KEY, state) childrenState.set(ROOT_KEY, state)
// 顶层当前页直接作为树根(不含合成「加载更多」节点,翻页由 OldPagination 承担)。 // 顶层当前页直接作为树根(不含合成「加载更多」节点,翻页由 OldPagination 承担)。
@@ -146,7 +144,7 @@ async function loadChildrenPage(parent: ProductCategoryNode | null, page: number
if (state?.loading) return if (state?.loading) return
childrenState.set(key, { page: state?.page ?? 0, total: state?.total ?? 0, hasMore: state?.hasMore ?? false, loading: true }) childrenState.set(key, { page: state?.page ?? 0, total: state?.total ?? 0, hasMore: state?.hasMore ?? false, loading: true })
try { try {
const result = await fetchProductCategoryChildren(parent?.id ?? null, page, PRODUCT_CATEGORY_DEFAULT_PAGE_SIZE, companyTab.requestCompanyId) const result = await fetchProductCategoryChildren(parent?.id ?? null, page, PRODUCT_CATEGORY_DEFAULT_PAGE_SIZE)
const loaded = append ? (state?.page ?? 0) + result.items.length : result.items.length const loaded = append ? (state?.page ?? 0) + result.items.length : result.items.length
const nextState = { page: result.page, total: result.total, hasMore: result.hasMore, loading: false } const nextState = { page: result.page, total: result.total, hasMore: result.hasMore, loading: false }
childrenState.set(key, nextState) childrenState.set(key, nextState)
@@ -197,7 +195,7 @@ function changeSearchSize(size: number) {
async function runSearch(page: number): Promise<void> { async function runSearch(page: number): Promise<void> {
searchLoading.value = true searchLoading.value = true
try { try {
const result = await searchProductCategories(keyword.value, page, searchPageSize.value, companyTab.requestCompanyId) const result = await searchProductCategories(keyword.value, page, searchPageSize.value)
searchRows.value = result.items searchRows.value = result.items
searchTotal.value = result.total searchTotal.value = result.total
searchPage.value = result.page searchPage.value = result.page
@@ -299,17 +297,13 @@ async function submit(): Promise<void> {
function exportCategories(): void { function exportCategories(): void {
const anchor = document.createElement('a') const anchor = document.createElement('a')
anchor.href = buildProductCategoryExportUrl(keyword.value, companyTab.requestCompanyId) anchor.href = buildProductCategoryExportUrl(keyword.value)
document.body.appendChild(anchor) document.body.appendChild(anchor)
anchor.click() anchor.click()
anchor.remove() anchor.remove()
ElMessage.success('类目导出已开始下载') ElMessage.success('类目导出已开始下载')
} }
// 切公司 = 重新取数。childrenState/expandedIds 必须一起清:这两份是**上一家**的懒加载分页缓存与展开集,
// 留着会把别家的子级行画进新一家的树里(同一个父级 id 在两家的子集不同),而请求本身是对的。
watch(() => companyTab.activeId, () => { childrenState.clear(); expandedIds.value = new Set(); selected.value = null; rootPage.value = 1; void (searching.value ? runSearch(1) : loadTree()) })
onMounted(loadTree) onMounted(loadTree)
</script> </script>
@@ -332,14 +326,14 @@ onMounted(loadTree)
<table> <table>
<thead> <thead>
<tr> <tr>
<th style="width: 34%">类目</th> <th style="width: 220px">类目</th>
<th>层级路径</th> <th style="width: 230px">层级路径</th>
<th style="width: 90px">排序</th> <th style="width: 66px">排序</th>
<th style="width: 120px">来源</th> <th style="width: 82px">来源</th>
<th>备注</th> <th style="width: 170px">备注</th>
<th style="width: 170px">创建时间</th> <th style="width: 154px">创建时间</th>
<th style="width: 170px">更新时间</th> <th style="width: 154px">更新时间</th>
<th style="width: 150px">操作</th> <th style="width: 148px">操作</th>
</tr> </tr>
</thead> </thead>
<tbody v-if="!searching"> <tbody v-if="!searching">
@@ -598,7 +592,10 @@ h3 {
table-layout: fixed; table-layout: fixed;
} }
.category-table-scroll > table { .category-table-scroll > table {
min-width: 860px; /* table-layout:fixed 下,没写宽度的列在容器变窄时第一个被压到 0(10-06 截图:层级路径只剩一个字、
备注只剩破折号)。承重的是 thead 里 8 列全部显式 px 定宽;这个下限与它们成对维护,
数值由 tests/align-product-category.test.ts 从 markup 现算比对,改列宽要同时改这里。 */
min-width: 1224px;
} }
.table-scroll th, .table-scroll th,
.table-scroll td { .table-scroll td {
@@ -1,4 +1,5 @@
/** 商品类目树/搜索适配(任务 78):GET /api/admin/product-categories(+keyword) 与 /product-categories/search。 */ /** 商品类目树/搜索适配(任务 78):GET /api/admin/product-categories(+keyword) 与 /product-categories/search。
* 2026-10-06 起这一页全平台共享:三个取数口都不带 company_id。 */
import { http } from '@/api/http' import { http } from '@/api/http'
import { import {
parseProductCategoryList, parseProductCategoryList,
@@ -11,10 +12,9 @@ import {
export const PRODUCT_CATEGORY_ENDPOINT = '/api/admin/product-categories' export const PRODUCT_CATEGORY_ENDPOINT = '/api/admin/product-categories'
/** 拉取类目树(keyword 非空时由服务端过滤并保留父路径)。 */ /** 拉取类目树(keyword 非空时由服务端过滤并保留父路径)。 */
export async function fetchProductCategoryTree(keyword = '', companyId?: number | null): Promise<ProductCategoryListResult> { export async function fetchProductCategoryTree(keyword = ''): Promise<ProductCategoryListResult> {
const trimmed = keyword.trim() const trimmed = keyword.trim()
const params: Record<string, string | number> = trimmed ? { keyword: trimmed } : {} const params: Record<string, string | number> = trimmed ? { keyword: trimmed } : {}
if (companyId != null) params.company_id = companyId
const { data } = await http.get<unknown>(PRODUCT_CATEGORY_ENDPOINT, { params }) const { data } = await http.get<unknown>(PRODUCT_CATEGORY_ENDPOINT, { params })
return parseProductCategoryList(data) return parseProductCategoryList(data)
} }
@@ -24,12 +24,10 @@ export async function searchProductCategories(
keyword: string, keyword: string,
page: number, page: number,
pageSize: number, pageSize: number,
companyId?: number | null,
): Promise<ProductCategorySearchPage> { ): Promise<ProductCategorySearchPage> {
const params: Record<string, string | number> = { page, page_size: pageSize } const params: Record<string, string | number> = { page, page_size: pageSize }
const trimmed = keyword.trim() const trimmed = keyword.trim()
if (trimmed) params.keyword = trimmed if (trimmed) params.keyword = trimmed
if (companyId != null) params.company_id = companyId
const { data } = await http.get<unknown>(`${PRODUCT_CATEGORY_ENDPOINT}/search`, { params }) const { data } = await http.get<unknown>(`${PRODUCT_CATEGORY_ENDPOINT}/search`, { params })
return parseProductCategorySearchPage(data) return parseProductCategorySearchPage(data)
} }
@@ -47,11 +45,9 @@ export async function fetchProductCategoryChildren(
parentId: number | null, parentId: number | null,
page: number, page: number,
pageSize: number, pageSize: number,
companyId?: number | null,
): Promise<ProductCategoryChildrenPage> { ): Promise<ProductCategoryChildrenPage> {
const params: Record<string, string | number> = { page, page_size: pageSize } const params: Record<string, string | number> = { page, page_size: pageSize }
if (parentId != null) params.parent_id = parentId if (parentId != null) params.parent_id = parentId
if (companyId != null) params.company_id = companyId
const { data } = await http.get<unknown>(`${PRODUCT_CATEGORY_ENDPOINT}/children`, { params }) const { data } = await http.get<unknown>(`${PRODUCT_CATEGORY_ENDPOINT}/children`, { params })
const parsed = parseProductCategorySearchPage(data) const parsed = parseProductCategorySearchPage(data)
return { items: parsed.items, total: parsed.total, page: parsed.page, hasMore: parsed.hasMore } return { items: parsed.items, total: parsed.total, page: parsed.page, hasMore: parsed.hasMore }
@@ -3,11 +3,10 @@
export const PRODUCT_CATEGORY_EXPORT_ENDPOINT = '/api/admin/product-categories/export' export const PRODUCT_CATEGORY_EXPORT_ENDPOINT = '/api/admin/product-categories/export'
/** 导出下载地址:浏览器直接访问该 URL 触发流式下载。 /** 导出下载地址:浏览器直接访问该 URL 触发流式下载。
* company_id 与列表同源:导出走的是同一个服务口径,不带它就是把别家类目写进同一份 XLSX。 */ * 与列表同源:导出走的是同一个服务口径。这一页 2026-10-06 起全平台共享,不带 company_id。 */
export function buildProductCategoryExportUrl(keyword: string, companyId?: number | null): string { export function buildProductCategoryExportUrl(keyword: string): string {
const params: string[] = [] const params: string[] = []
const trimmed = (keyword || '').trim() const trimmed = (keyword || '').trim()
if (trimmed) params.push(`keyword=${encodeURIComponent(trimmed)}`) if (trimmed) params.push(`keyword=${encodeURIComponent(trimmed)}`)
if (companyId != null) params.push(`company_id=${companyId}`)
return params.length ? `${PRODUCT_CATEGORY_EXPORT_ENDPOINT}?${params.join('&')}` : PRODUCT_CATEGORY_EXPORT_ENDPOINT return params.length ? `${PRODUCT_CATEGORY_EXPORT_ENDPOINT}?${params.join('&')}` : PRODUCT_CATEGORY_EXPORT_ENDPOINT
} }
@@ -12,8 +12,6 @@ export interface InvalidAsinQuery {
dataValue?: string dataValue?: string
brand?: string brand?: string
groupId?: number | null groupId?: number | null
/** 公司 tab 的值;toQuery 是白名单构造、不点名它,所以由发送口从原始 query 读。 */
companyId?: number | null
} }
function trimOrUndefined(value: unknown): string | undefined { function trimOrUndefined(value: unknown): string | undefined {
@@ -31,11 +29,8 @@ function toQuery(query: InvalidAsinQuery): Record<string, string | number> {
} }
export async function fetchInvalidAsinPage(query: InvalidAsinQuery): Promise<InvalidAsinPageResult> { export async function fetchInvalidAsinPage(query: InvalidAsinQuery): Promise<InvalidAsinPageResult> {
// 公司值落在 toQuery 之后、发请求之前的唯一一处:toQuery 是白名单构造(只点名 page/data_value/brand/group_id), // 这一页 2026-10-06 起全平台共享:请求里不许出现 company_id(后端唯一键退回全局见 V151)。
// 所以这里必须从原始 query 读 companyId——从 toQuery 的结果里读是 undefined,请求照发、参数没有。 const { data } = await http.get<unknown>(INVALID_ASIN_ENDPOINT, { params: toQuery(query) })
const params = toQuery(query)
if (query.companyId != null) params.company_id = query.companyId
const { data } = await http.get<unknown>(INVALID_ASIN_ENDPOINT, { params })
return parseInvalidAsinPage(data) return parseInvalidAsinPage(data)
} }
@@ -2,14 +2,16 @@
import { formatDateTime } from '@/utils/datetime' import { formatDateTime } from '@/utils/datetime'
/** 店铺密钥管理页 · 像素复刻旧版 admin.html panel-shop-keys(自绘:面板头+新增店铺密钥、序号列、令牌掩码、白名单状态药丸+悬停详情、旧式分页)。 /** 店铺密钥管理页 · 像素复刻旧版 admin.html panel-shop-keys(自绘:面板头+新增店铺密钥、序号列、令牌掩码、白名单状态药丸+悬停详情、旧式分页)。
* script 逻辑沿用现有 Vue 实现(编辑留空令牌=沿用);弹窗保留现有组件。 */ * script 逻辑沿用现有 Vue 实现(编辑留空令牌=沿用);弹窗保留现有组件。 */
import { computed, onMounted, reactive, ref } from 'vue' import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus' import { ElMessage } from 'element-plus'
import { useCompanyTabStore } from '@/stores/company-tab'
import { fetchShopKeyList, submitCreateShopKey, updateShopKey, deleteShopKey, checkShopKeyWhitelist } from './shop-key-api.ts' import { fetchShopKeyList, submitCreateShopKey, updateShopKey, deleteShopKey, checkShopKeyWhitelist } from './shop-key-api.ts'
import { emptyShopKeyForm, normalizeZiniaoToken, validateProxyUrl } from './shop-key-form-model.ts' import { emptyShopKeyForm, normalizeZiniaoToken, validateProxyUrl } from './shop-key-form-model.ts'
import type { ShopKeyItem } from './shop-dto.ts' import type { ShopKeyItem } from './shop-dto.ts'
import { whitelistStatusMeta } from './shop-key-model.ts' import { whitelistStatusMeta } from './shop-key-model.ts'
import OldPagination from '@/components/OldPagination.vue' import OldPagination from '@/components/OldPagination.vue'
const companyTab = useCompanyTabStore()
const loading = ref(false) const loading = ref(false)
const rows = ref<ShopKeyItem[]>([]) const rows = ref<ShopKeyItem[]>([])
const total = ref(0) const total = ref(0)
@@ -56,7 +58,11 @@ function whitelistTooltip(row: ShopKeyItem): string {
async function load() { async function load() {
loading.value = true loading.value = true
try { try {
const result = await fetchShopKeyList({ page: page.value, pageSize: pageSize.value }) const result = await fetchShopKeyList({
page: page.value,
pageSize: pageSize.value,
companyId: companyTab.requestCompanyId,
})
rows.value = result.items rows.value = result.items
total.value = result.total total.value = result.total
page.value = result.page page.value = result.page
@@ -172,6 +178,8 @@ function goJump() {
changePage(Math.min(Math.max(n, 1), totalPages.value)) changePage(Math.min(Math.max(n, 1), totalPages.value))
} }
watch(() => companyTab.activeId, () => { filterKeyword.value = ''; page.value = 1; void load() })
onMounted(load) onMounted(load)
</script> </script>
@@ -81,10 +81,12 @@ export interface ShopGroupOption {
leaderUsername?: string leaderUsername?: string
} }
/** 店铺密钥列表分页参数(该接口只支持分页)。 */ /** 店铺密钥列表分页参数(分页 + 公司 tab;归一是白名单构造,不点名 companyId)。 */
export interface ShopKeyListParams { export interface ShopKeyListParams {
page: number page: number
pageSize: number pageSize: number
/** 公司 tab 的值;normalizeKeyListParams 不点名它,只有 api 层能从原始 params 读到。 */
companyId?: number | null
} }
/** 店铺列表分页/筛选参数。 */ /** 店铺列表分页/筛选参数。 */
@@ -100,6 +102,8 @@ export interface ShopManageListParams {
export interface ShopKeyPageQuery { export interface ShopKeyPageQuery {
page: number page: number
pageSize: number pageSize: number
/** 下划线形:与后端 @RequestParam(name = "company_id") 逐字对齐。 */
company_id?: number
} }
export interface ShopManagePageQuery { export interface ShopManagePageQuery {
@@ -19,7 +19,11 @@ export const SHOP_KEYS_ENDPOINT = '/api/admin/shop-keys'
export async function fetchShopKeyList(params: Partial<ShopKeyListParams> = {}): Promise<ShopKeyPageResult> { export async function fetchShopKeyList(params: Partial<ShopKeyListParams> = {}): Promise<ShopKeyPageResult> {
const normalized = normalizeKeyListParams(params) const normalized = normalizeKeyListParams(params)
const { data } = await http.get<unknown>(SHOP_KEYS_ENDPOINT, { params: toKeyPageQuery(normalized) }) // normalizeKeyListParams 与 toKeyPageQuery 都是白名单构造(不点名 companyId),
// 所以公司值只能从原始 params 读:写成 normalized.companyId 是 TS 绿、运行时恒 undefined。
const query = toKeyPageQuery(normalized)
if (params.companyId != null) query.company_id = params.companyId
const { data } = await http.get<unknown>(SHOP_KEYS_ENDPOINT, { params: query })
return parseShopKeyPage(data) return parseShopKeyPage(data)
} }
+6 -6
View File
@@ -19,26 +19,26 @@ export interface AdminPageDef extends AdminPageMeta {
/** 业务域路由注册表(任务 8):首批 account 域;后续按业务域在此登记页面。 */ /** 业务域路由注册表(任务 8):首批 account 域;后续按业务域在此登记页面。 */
export const adminPages: AdminPageDef[] = [ export const adminPages: AdminPageDef[] = [
{ path: 'account/users', menuKey: 'admin_users', title: '用户管理', companyScoped: true, load: () => import('@/pages/account/UsersPage.vue') }, { path: 'account/users', menuKey: 'admin_users', title: '用户管理', companyScoped: true, load: () => import('@/pages/account/UsersPage.vue') },
{ path: 'account/menus', menuKey: 'admin_columns', title: '菜单管理', load: () => import('@/pages/account/MenusPage.vue') }, { path: 'account/menus', menuKey: 'admin_columns', title: '菜单管理', companyScoped: true, load: () => import('@/pages/account/MenusPage.vue') },
{ path: 'account/groups', menuKey: 'admin_group_manage', title: '数据权限分组', companyScoped: true, load: () => import('@/pages/account/GroupsPage.vue') }, { path: 'account/groups', menuKey: 'admin_group_manage', title: '数据权限分组', companyScoped: true, load: () => import('@/pages/account/GroupsPage.vue') },
{ path: 'account/user-secrets', menuKey: 'admin_user_secrets', title: '密钥管理', companyScoped: true, load: () => import('@/pages/account/UserSecretsPage.vue') }, { path: 'account/user-secrets', menuKey: 'admin_user_secrets', title: '密钥管理', companyScoped: true, load: () => import('@/pages/account/UserSecretsPage.vue') },
{ path: 'account/user-secret-usage', menuKey: 'admin_user_secret_usage', title: '密钥用量统计', companyScoped: true, load: () => import('@/pages/account/UserSecretUsagePage.vue') }, { path: 'account/user-secret-usage', menuKey: 'admin_user_secret_usage', title: '密钥用量统计', companyScoped: true, load: () => import('@/pages/account/UserSecretUsagePage.vue') },
{ path: 'account/companies', menuKey: 'admin_companies', title: '公司管理', superAdminOnly: true, load: () => import('@/pages/account/CompaniesPage.vue') }, { path: 'account/companies', menuKey: 'admin_companies', title: '公司管理', superAdminOnly: true, load: () => import('@/pages/account/CompaniesPage.vue') },
{ path: 'shop-center/duplicate-check', menuKey: 'admin_shop_data_duplicate_check', title: '店铺撞款监控', companyScoped: true, load: () => import('@/pages/tasks/DuplicateCheckPage.vue') }, { path: 'shop-center/duplicate-check', menuKey: 'admin_shop_data_duplicate_check', title: '店铺撞款监控', companyScoped: true, load: () => import('@/pages/tasks/DuplicateCheckPage.vue') },
{ path: 'shop-center/keys', menuKey: 'admin_shop_keys', title: '店铺密钥管理', companyScoped: false, load: () => import('@/pages/shop/ShopKeysPage.vue') }, { path: 'shop-center/keys', menuKey: 'admin_shop_keys', title: '店铺密钥管理', companyScoped: true, load: () => import('@/pages/shop/ShopKeysPage.vue') },
{ path: 'shop-center/shops', menuKey: 'admin_shop_manage', title: '店铺管理', companyScoped: true, load: () => import('@/pages/shop/ShopManagePage.vue') }, { path: 'shop-center/shops', menuKey: 'admin_shop_manage', title: '店铺管理', companyScoped: true, load: () => import('@/pages/shop/ShopManagePage.vue') },
{ path: 'records/history', menuKey: 'admin_history', title: '生成记录', companyScoped: true, load: () => import('@/pages/records/RecordsHistoryPage.vue') }, { path: 'records/history', menuKey: 'admin_history', title: '生成记录', companyScoped: true, load: () => import('@/pages/records/RecordsHistoryPage.vue') },
{ path: 'records/software-version', menuKey: 'admin_version', title: '软件版本管理', load: () => import('@/pages/records/RecordsSoftwareVersionPage.vue') }, { path: 'records/software-version', menuKey: 'admin_version', title: '软件版本管理', companyScoped: false, load: () => import('@/pages/records/RecordsSoftwareVersionPage.vue') },
{ path: 'records/tutorial', menuKey: 'admin_tutorial', title: '教程管理', load: () => import('@/pages/records/RecordsTutorialPage.vue') }, { path: 'records/tutorial', menuKey: 'admin_tutorial', title: '教程管理', companyScoped: false, load: () => import('@/pages/records/RecordsTutorialPage.vue') },
{ path: 'records/device-logs', menuKey: 'admin_device_logs', title: '日志管理', companyScoped: true, load: () => import('@/pages/records/DeviceLogsPage.vue') }, { path: 'records/device-logs', menuKey: 'admin_device_logs', title: '日志管理', companyScoped: true, load: () => import('@/pages/records/DeviceLogsPage.vue') },
{ path: 'task-center/board', menuKey: 'admin_task_center', title: '客户端任务管理', companyScoped: true, load: () => import('@/pages/task-center/TaskCenterBoardPage.vue') }, { path: 'task-center/board', menuKey: 'admin_task_center', title: '客户端任务管理', companyScoped: true, load: () => import('@/pages/task-center/TaskCenterBoardPage.vue') },
{ path: 'records/digital-human-version', menuKey: 'digital_human_version', title: '数字人版本管理', load: () => import('@/pages/records/RecordsDigitalHumanVersionPage.vue') }, { path: 'records/digital-human-version', menuKey: 'digital_human_version', title: '数字人版本管理', load: () => import('@/pages/records/RecordsDigitalHumanVersionPage.vue') },
{ path: 'records/image-video-tasks', menuKey: 'admin_image_video_tasks', title: '视频任务记录', companyScoped: true, load: () => import('@/pages/tasks/ImageVideoTasksPage.vue') }, { path: 'records/image-video-tasks', menuKey: 'admin_image_video_tasks', title: '视频任务记录', companyScoped: true, load: () => import('@/pages/tasks/ImageVideoTasksPage.vue') },
{ path: 'shop-center/data-tasks', menuKey: 'admin_shop_data_crawl_tasks', title: '店铺数据记录', companyScoped: true, load: () => import('@/pages/tasks/ShopDataTasksPage.vue') }, { path: 'shop-center/data-tasks', menuKey: 'admin_shop_data_crawl_tasks', title: '店铺数据记录', companyScoped: true, load: () => import('@/pages/tasks/ShopDataTasksPage.vue') },
{ path: 'asin-center/registry', menuKey: 'admin_dedupe_total_data', title: '数据去重总数据', companyScoped: true, load: () => import('@/pages/asin/DedupeRegistryPage.vue') }, { path: 'asin-center/registry', menuKey: 'admin_dedupe_total_data', title: '数据去重总数据', companyScoped: true, load: () => import('@/pages/asin/DedupeRegistryPage.vue') },
{ path: 'asin-center/invalid', menuKey: 'admin_invalid_asin_data', title: '不符合ASIN数据', companyScoped: true, load: () => import('@/pages/asin/AsinInvalidPage.vue') }, { path: 'asin-center/invalid', menuKey: 'admin_invalid_asin_data', title: '品牌数据库', companyScoped: false, load: () => import('@/pages/asin/AsinInvalidPage.vue') },
{ path: 'asin-center/query', menuKey: 'admin_query_asin', title: '查询ASIN', companyScoped: true, load: () => import('@/pages/asin/QueryAsinPage.vue') }, { path: 'asin-center/query', menuKey: 'admin_query_asin', title: '查询ASIN', companyScoped: true, load: () => import('@/pages/asin/QueryAsinPage.vue') },
{ path: 'asin-center/categories', menuKey: 'admin_product_categories', title: '商品类目', companyScoped: true, 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') },
] ]
@@ -91,7 +91,7 @@ test('guide_copy_carries_company_tab_note_for_every_scoped_page', () => {
// 新页缺文案仍会红(operationGuideFor 对没登记的 key 返回 null ⇒ assert.ok(g) 当场红,没有兜底可糊)。 // 新页缺文案仍会红(operationGuideFor 对没登记的 key 返回 null ⇒ assert.ok(g) 当场红,没有兜底可糊)。
const scopedKeys = COMPANY_SCOPED_PAGES.map((p) => p.menuKey) const scopedKeys = COMPANY_SCOPED_PAGES.map((p) => p.menuKey)
const need = scopedKeys.filter((k) => k !== EXCEPTED_KEY) const need = scopedKeys.filter((k) => k !== EXCEPTED_KEY)
assert.ok(need.length >= 15, `取样集非空自检:注册表今天有 ${scopedKeys.length} 页进了 tab 范围(批次 1 的 8 页 + 批次 2 的 5 页 + 批次 3 的 2 页 + 批次 4 的 1 页),减去唯一豁免页后只剩 ${need.length} 页`) assert.ok(need.length >= 15, `取样集非空自检:注册表今天有 ${scopedKeys.length} 页进了 tab 范围(批次 1 的 8 页 + 批次 2 剩下的 3 页 + 批次 3 的 2 页 + 批次 4 的 1 页 + 批次 5 的 1 页 + 批次 6 的 1 页),减去唯一豁免页后只剩 ${need.length} 页`)
assert.ok(scopedKeys.includes(EXCEPTED_KEY), assert.ok(scopedKeys.includes(EXCEPTED_KEY),
'取样集前提自检:撞款监控已不在 COMPANY_SCOPED_PAGES 里,上面那道豁免就成了空豁免——把它连同 EXCEPTED_KEY 一起删掉') '取样集前提自检:撞款监控已不在 COMPANY_SCOPED_PAGES 里,上面那道豁免就成了空豁免——把它连同 EXCEPTED_KEY 一起删掉')
for (const key of need) { for (const key of need) {
@@ -101,11 +101,15 @@ test('guide_copy_carries_company_tab_note_for_every_scoped_page', () => {
} }
// C 类页(spec §5):它们要的是**另一句**——"这页不参与",不是"会随 tab 变"。 // C 类页(spec §5):它们要的是**另一句**——"这页不参与",不是"会随 tab 变"。
// 分母**取注册表里显式写 companyScoped:false 的页**,不抄名单:漏写一条 ⇒ 这支在自检那句红。 // 分母**取注册表里显式写 companyScoped:false 的页**,不抄名单:漏写一条 ⇒ 这支在自检那句红。
// 批次 2 之前这里是 2 页(店铺密钥 + 商品类目),商品类目已接上公司口径 ⇒ 今天只剩 admin_shop_keys // 批次 2 之前这里是 2 页(店铺密钥 + 商品类目),商品类目一度接上了公司口径;
// 一条,所以自检降到 1;再往下掉就是有人把注册表里那条 false 改成不写(不写 = 不参与但没人说)。 // 2026-10-06 控制方定案「品牌数据库 / 商品类目 / 教程管理 / 软件版本管理都做成共享的,不区分」,
// 于是这一族一度变成 5 页(店铺密钥 + 品牌库 + 商品类目 + 软件版本 + 教程);
// 同日批次 5 又把店铺密钥改回按公司区分(V150 给 biz_shop_key 加 company_id),今天剩 4 页。
// 后四页是**新登记**的:教程管理与软件版本管理的后端本来就没有公司引用,此前既不在清单也没写 false
// =「不参与但没人说」,现在显式写出来,这句文案与下面那条 deepEqual 才盖得到它们。
const scoped = new Set(COMPANY_SCOPED_PAGES.map((p) => p.menuKey)) const scoped = new Set(COMPANY_SCOPED_PAGES.map((p) => p.menuKey))
const cClass = adminPages.filter((p) => p.companyScoped === false).map((p) => p.menuKey) const cClass = adminPages.filter((p) => p.companyScoped === false).map((p) => p.menuKey)
assert.ok(cClass.length >= 1, '取样集非空自检:注册表里显式 companyScoped:false 的一条都不剩了——那这句判据就是空跑') assert.ok(cClass.length >= 4, `取样集非空自检:注册表里显式 companyScoped:false 只剩 ${cClass.length} 页——那这句判据就是空跑`)
for (const key of cClass) { for (const key of cClass) {
assert.equal(scoped.has(key), false, `${key} 既声明 false 又在清单里,两处口径打架`) assert.equal(scoped.has(key), false, `${key} 既声明 false 又在清单里,两处口径打架`)
const g = operationGuideFor(key) const g = operationGuideFor(key)
@@ -85,3 +85,63 @@ test('align_category_page_tree_and_search_wiring', () => {
assert.match(page, /来源/, '搜索表格补来源列') assert.match(page, /来源/, '搜索表格补来源列')
assert.match(page, /childCount/, '删除按钮按有子禁用') assert.match(page, /childCount/, '删除按钮按有子禁用')
}) })
/**
* 列宽算术闸门(2026-10-06 控制方圈出:层级路径整列只剩一个字、备注只剩一个破折号)。
* `.table-scroll table` 是 table-layout:fixed —— 首行 th 定宽后,列宽之和一旦超过表格实宽,
* 浏览器把各列等比压缩,而没写宽度的 auto 列第一个被压到 0px。旧写法(类目 34% + 两个 auto 列 +
* 700px 固定列)在表格宽度 < 1061px 时就是这么塌的;min-width 当时是 860px,比列宽之和还小,
* 等于下限自己把塌缩区放进了合法区间。
*
* 闸门只认三条,其中真正承重的是前两条(浏览器实测,同一份 CSS 与真实 thead 生成的复现页):
* 旧写法在表格宽度 1224px 时把 层级路径 与 备注 量成 0px,而 8 列全显式定宽后在 1920/1440/1100/900
* 四档没有一列低于 90px —— 也就是"把 min-width 抬到 1224"单独并不能救旧写法,auto 列才是塌的那一根。
* 第三条(min-width >= 列宽之和)管的是成对维护:加一列却忘了抬下限会直接红。
* 求和从 markup 现算,不是抄常量——把某列从 220px 改成 400px 而忘了同步会直接红。
* (注:单元格左右各 12px padding 是加在列宽之外的,所以渲染出的表格自然宽度是"列宽之和 + 24×8 = 1416px",
* 与这里比对的 1224 不是同一个数,别混。)
*/
function categoryHeaderColumns(page: string): Array<{ label: string; px: number | null }> {
const theadBlocks = page.match(/<thead>[\s\S]*?<\/thead>/g) ?? []
assert.equal(theadBlocks.length, 1, '类目页应只有一个 thead(本闸门按单个表头求列宽之和)')
const columns: Array<{ label: string; px: number | null }> = []
for (const cell of theadBlocks[0].matchAll(/<th\b[^>]*>([^<]*)<\/th>/g)) {
const style = cell[0].match(/style="([^"]*)"/)?.[1] ?? ''
const px = /width:\s*(\d+)px/.exec(style)?.[1]
columns.push({ label: cell[1].trim(), px: px === undefined ? null : Number(px) })
}
return columns
}
function categoryTableMinWidth(page: string): number | null {
const block = page.match(/\.category-table-scroll\s*>\s*table\s*\{([^}]*)\}/)?.[1] ?? ''
const px = /min-width:\s*(\d+)px/.exec(block)?.[1]
return px === undefined ? null : Number(px)
}
test('align_category_fixed_layout_never_leaves_a_column_to_be_squeezed', () => {
const page = readSource('src/pages/asin/ProductCategoryPage.vue')
// 前提也要钉:这条闸门只在 fixed 布局下成立,改成 auto 布局时它该喊,而不是安静地继续绿。
// 窗口用 [^}] 而不是定长字符数:本页 CSS 注释里就写着 "table-layout:fixed 下……" 这句话,
// 定长窗口能跨过 } 把注释喂成"前提成立"(变异自证时实测过一次 SURVIVED)。
assert.match(page, /\.table-scroll\s+table\s*\{[^}]*table-layout:\s*fixed/, '本闸门的前提:表格是 table-layout:fixed')
const columns = categoryHeaderColumns(page)
assert.equal(columns.length, 8, `表头应有 8 列(与 <td colspan="8"> 对齐),实际 ${columns.length}:${JSON.stringify(columns)}`)
const unwidthed = columns.filter((c) => c.px === null).map((c) => c.label)
assert.deepEqual(unwidthed, [], 'fixed 布局下没写宽度的列会在容器变窄时被第一个压到 0px:' + unwidthed.join('/'))
assert.equal(/width:\s*\d+%/.test(page.match(/<thead>[\s\S]*?<\/thead>/)?.[0] ?? ''), false,
'表头不许用百分比:百分比与 px 混排时列宽之和随表格宽度变,下限就无从比对')
const sum = columns.reduce((acc, c) => acc + (c.px ?? 0), 0)
const minWidth = categoryTableMinWidth(page)
assert.notEqual(minWidth, null, '.category-table-scroll > table 必须有 px 下限,否则塌缩区又合法了')
assert.ok((minWidth ?? 0) >= sum,
`min-width(${minWidth}px) 必须 >= 8 列宽度之和(${sum}px):否则表格落在 [min-width, 列宽和] 这一段时列被等比压缩`)
// 控制方圈出的那两列是这次的直接症状:它们是文字列,宽度下限给死,别被"重新调配比"顺手砍回去。
for (const label of ['层级路径', '备注']) {
const col = columns.find((c) => c.label === label)
assert.ok(col && (col.px ?? 0) >= 120, `${label} 列宽不得低于 120px,实际 ${col?.px ?? '未定义'}px`)
}
})
@@ -102,8 +102,18 @@ test('align_user_menu_grantable_wired_end_to_end', () => {
) )
assert.match( assert.match(
controller, controller,
/permissionMenuService\.list\(requireAdmin\(request\), menuType, grantableOnly\)/, /permissionMenuService\.resolveScopeCompanyId\(operator, companyId\)/,
'列表接口传入操作者与授权树开关', '列表接口先把请求里的 company_id 过一遍归属判据(非超管带别家当场 403),传下去的是判定结果而不是 tab 原文',
)
assert.match(
controller,
/permissionMenuService\.list\(\s*operator, menuType, grantableOnly, scopeCompanyId\s*\)/,
'列表接口传入操作者、授权树开关与**已判定**的那一家(2026-10-06 每家公司一套树:授权树取错公司=已授权勾不上)',
)
assert.doesNotMatch(
controller,
/menuType, grantableOnly, companyId\s*\)/,
'反向钉:不许把 tab 原文直接透传给 list(),否则"前端传什么都不算"这条口径在这一口断掉',
) )
const service = readSource( const service = readSource(
@@ -88,8 +88,10 @@ test('吃公司 tab 的页面集合恰好等于 COMPANY_SCOPED_PAGES 的 pageFil
.filter((rel) => readSource(rel).includes(STORE_USE_TOKEN)) .filter((rel) => readSource(rel).includes(STORE_USE_TOKEN))
.sort() .sort()
const declared = COMPANY_SCOPED_PAGES.flatMap((entry) => entry.pageFiles).sort() const declared = COMPANY_SCOPED_PAGES.flatMap((entry) => entry.pageFiles).sort()
assert.ok(declared.length >= 16, `清单的 pageFiles 只剩 ${declared.length} 条 ⇒ 分母被删空,深比较会退化成空集自比`) // 分母 15 = 今天注册表的 pageFiles 条数(批次 1 的 8 + 批次 2 剩下的 3 + 批次 3 的 2 + 批次 4 的 1 + 批次 5 的 1;
assert.ok(consumers.length >= 16, `真实消费者只有 ${consumers.length} 页 ⇒ 扫描谓词(${STORE_USE_TOKEN})或页面文件本身出了问题`) // 品牌库与商品类目 2026-10-06 退回全平台共享后不在其中,见 company-tab-wiring 末尾那条反向钉)。
assert.ok(declared.length >= 15, `清单的 pageFiles 只剩 ${declared.length} 条 ⇒ 分母被删空,深比较会退化成空集自比`)
assert.ok(consumers.length >= 15, `真实消费者只有 ${consumers.length} 页 ⇒ 扫描谓词(${STORE_USE_TOKEN})或页面文件本身出了问题`)
assert.deepEqual(consumers, declared, assert.deepEqual(consumers, declared,
'公司 tab 的消费者与清单对不上:多出来的一页=悄悄给一页不参与隔离的页上了 tab(公司管理就属于这类),' '公司 tab 的消费者与清单对不上:多出来的一页=悄悄给一页不参与隔离的页上了 tab(公司管理就属于这类),'
+ '少掉的一页=清单声明它隔离但页面根本没取值') + '少掉的一页=清单声明它隔离但页面根本没取值')
@@ -48,9 +48,10 @@ test('剪枝是纯函数且幂等(store 里会反复调用)', () => {
test('不参与 tab 的页必须显式声明 companyScoped: false(spec §5:声明,不是遗漏)', () => { test('不参与 tab 的页必须显式声明 companyScoped: false(spec §5:声明,不是遗漏)', () => {
// 留空和 false 运行时等价,但只有 false 是"读过普查、决定不参与"的证据。 // 留空和 false 运行时等价,但只有 false 是"读过普查、决定不参与"的证据。
// 名单批次 1 是两页(店铺密钥 + 商品类目);商品类目在批次 2(2026-10-05)接上了公司口径, // 名单批次 1 是两页(店铺密钥 + 商品类目);商品类目在批次 2(2026-10-05)接上了公司口径,
// 今天只剩紫鸟令牌这一页真的是"全平台共享、与公司无关"。 // 2026-10-06 控制方定案品牌库/教程管理/软件版本管理一律全平台共享,同日批次 5 又把店铺密钥
// 改回按公司区分(V150)⇒ 今天这一族是 4 页,一句「与公司无关」都没写给它们的页不许进这张表。
// 想再往这页上加 false 的对向(把某页改回 false)不用改这里:上面那条双向对账会红。 // 想再往这页上加 false 的对向(把某页改回 false)不用改这里:上面那条双向对账会红。
for (const key of ['admin_shop_keys']) { for (const key of ['admin_invalid_asin_data', 'admin_product_categories', 'admin_version', 'admin_tutorial']) {
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, `${key} 必须显式写 companyScoped: false,不能留空`) assert.equal(page.companyScoped, false, `${key} 必须显式写 companyScoped: false,不能留空`)
@@ -4,6 +4,7 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs'
import { occurrences, readSource } from './helpers.ts' import { occurrences, readSource } from './helpers.ts'
import { adminPages } from '../src/router/routes.ts' import { adminPages } from '../src/router/routes.ts'
import { COMPANY_SCOPED_PAGES, SUPER_ADMIN_ONLY_MENU_KEYS } from '../src/config/company-scope.ts' import { COMPANY_SCOPED_PAGES, SUPER_ADMIN_ONLY_MENU_KEYS } from '../src/config/company-scope.ts'
import { companyTabAppliesTo } from '../src/layout/company-tab-model.ts'
const read = (p: string) => { const read = (p: string) => {
assert.ok(existsSync(p), `护栏读不到 ${p}:api 文件改名了,清单必须同步(别把用例改成"不存在就跳过")`) assert.ok(existsSync(p), `护栏读不到 ${p}:api 文件改名了,清单必须同步(别把用例改成"不存在就跳过")`)
@@ -69,9 +70,12 @@ function escapeRegExp(text: string): string {
} }
/** /**
* 全部 22 个字面发送口:批次 1 的任务看板 5 处 + 批次 2(控制方 2026-10-05 点名「切 tab 数据还一样」那五页)12 处 * 全部 21 个字面发送口:批次 1 的任务看板 5 处 + 批次 2(控制方 2026-10-05 点名「切 tab 数据还一样」那五页)7 处
* + 批次 3(控制方 2026-10-05 点名「店铺撞款监控 店铺数据也要做隔离」那两页)4 处 * + 批次 3(控制方 2026-10-05 点名「店铺撞款监控 店铺数据也要做隔离」那两页)4 处
* + 批次 4(控制方 2026-10-05 点名「菜单权限和用户管理也要区分公司 tab 的数据」里的用户管理)1 处。 * + 批次 4(控制方 2026-10-05 点名「菜单权限和用户管理也要区分公司 tab 的数据」里的用户管理)1 处
* + 批次 5(控制方 2026-10-06 点名「店铺密钥管理的数据按照公司区分」)1 处
* + 批次 6(控制方 2026-10-06 点名「菜单权限也加字段来区分」)3 处:菜单目录 / 新建菜单 / 用户管理里的授权树。
* 批次 2 原 12 处里的品牌库 1 处 + 商品类目 4 处,随 2026-10-06「这两页退回全平台共享」一并摘掉。
* *
* <p>`window` 的取法:本轮实扫的 own(到自己那行的距离)+ ≥150 余量,且当同文件还有下一个同名发送口时必须 * <p>`window` 的取法:本轮实扫的 own(到自己那行的距离)+ ≥150 余量,且当同文件还有下一个同名发送口时必须
* `window < next`。own/next 不写死在这里——下面「窗口与真文件对平」那条用例逐处从真文件重算, * `window < next`。own/next 不写死在这里——下面「窗口与真文件对平」那条用例逐处从真文件重算,
@@ -94,15 +98,10 @@ const SEND_POINTS: ReadonlyArray<SendPoint> = [
{ menuKey: 'admin_dedupe_total_data', file: 'src/pages/asin/dedupe-total-api.ts', fn: 'fetchDedupeTotalList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 400, title: 'GET /dedupe-total-data 列表' }, { menuKey: 'admin_dedupe_total_data', file: 'src/pages/asin/dedupe-total-api.ts', fn: 'fetchDedupeTotalList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 400, title: 'GET /dedupe-total-data 列表' },
{ menuKey: 'admin_dedupe_total_data', file: 'src/pages/asin/dedupe-total-api.ts', fn: 'fetchDedupeTotalGroups', line: 'http.get<unknown>(DEDUPE_GROUPS_ENDPOINT, { params: companyId != null ? { company_id: companyId } : {} })', window: 400, title: 'GET /shop-manages/groups 分组候选(与店铺管理同源,两页口径要对得上)' }, { menuKey: 'admin_dedupe_total_data', file: 'src/pages/asin/dedupe-total-api.ts', fn: 'fetchDedupeTotalGroups', line: 'http.get<unknown>(DEDUPE_GROUPS_ENDPOINT, { params: companyId != null ? { company_id: companyId } : {} })', window: 400, title: 'GET /shop-manages/groups 分组候选(与店铺管理同源,两页口径要对得上)' },
{ menuKey: 'admin_dedupe_total_data', file: 'src/pages/asin/dedupe-total-export.ts', fn: 'buildDedupeExportParams', line: 'if (companyId != null) params.company_id = String(companyId)', window: 800, title: 'GET /dedupe-total-data/export 导出' }, { menuKey: 'admin_dedupe_total_data', file: 'src/pages/asin/dedupe-total-export.ts', fn: 'buildDedupeExportParams', line: 'if (companyId != null) params.company_id = String(companyId)', window: 800, title: 'GET /dedupe-total-data/export 导出' },
{ menuKey: 'admin_invalid_asin_data', file: 'src/pages/invalidasin/invalid-asin-api.ts', fn: 'fetchInvalidAsinPage', line: 'if (query.companyId != null) params.company_id = query.companyId', window: 400, title: 'GET /invalid-asin-data 列表(品牌数据库)' },
{ menuKey: 'admin_query_asin', file: 'src/pages/asin/query-asin-api.ts', fn: 'fetchQueryAsinList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 400, title: 'GET /query-asins 列表' }, { menuKey: 'admin_query_asin', file: 'src/pages/asin/query-asin-api.ts', fn: 'fetchQueryAsinList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 400, title: 'GET /query-asins 列表' },
{ menuKey: 'admin_query_asin', file: 'src/pages/asin/query-asin-export.ts', fn: 'buildQueryAsinExportParams', line: 'if (companyId != null) params.company_id = String(companyId)', window: 700, title: 'GET /query-asins/export 导出' }, { menuKey: 'admin_query_asin', file: 'src/pages/asin/query-asin-export.ts', fn: 'buildQueryAsinExportParams', line: 'if (companyId != null) params.company_id = String(companyId)', window: 700, title: 'GET /query-asins/export 导出' },
{ menuKey: 'admin_skip_price_asin', file: 'src/pages/asin/skip-price-api.ts', fn: 'fetchSkipPriceList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 400, title: 'GET /skip-price-asins 列表(最低价 ASIN)' }, { menuKey: 'admin_skip_price_asin', file: 'src/pages/asin/skip-price-api.ts', fn: 'fetchSkipPriceList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 400, title: 'GET /skip-price-asins 列表(最低价 ASIN)' },
{ menuKey: 'admin_skip_price_asin', file: 'src/pages/asin/skip-price-export.ts', fn: 'buildSkipPriceExportParams', line: 'if (companyId != null) params.company_id = String(companyId)', window: 1000, title: 'GET /skip-price-asins/export 导出(本批新建:原先 href 不带任何参数=恒导全平台)' }, { menuKey: 'admin_skip_price_asin', file: 'src/pages/asin/skip-price-export.ts', fn: 'buildSkipPriceExportParams', line: 'if (companyId != null) params.company_id = String(companyId)', window: 1000, title: 'GET /skip-price-asins/export 导出(本批新建:原先 href 不带任何参数=恒导全平台)' },
{ menuKey: 'admin_product_categories', file: 'src/pages/asin/product-category-api.ts', fn: 'fetchProductCategoryTree', line: 'if (companyId != null) params.company_id = companyId', window: 450, title: 'GET /product-categories 类目树' },
{ menuKey: 'admin_product_categories', file: 'src/pages/asin/product-category-api.ts', fn: 'searchProductCategories', line: 'if (companyId != null) params.company_id = companyId', window: 450, title: 'GET /product-categories/search 搜索' },
{ menuKey: 'admin_product_categories', file: 'src/pages/asin/product-category-api.ts', fn: 'fetchProductCategoryChildren', line: 'if (companyId != null) params.company_id = companyId', window: 450, title: 'GET /product-categories/children 懒加载子级' },
{ menuKey: 'admin_product_categories', file: 'src/pages/asin/product-category-export.ts', fn: 'buildProductCategoryExportUrl', line: 'if (companyId != null) params.push(`company_id=${companyId}`)', window: 400, title: 'GET /product-categories/export 导出(字符串拼接而非对象,锚整条 push)' },
// ↓ 批次 3 的两页(控制方 2026-10-05 点名「店铺撞款监控 店铺数据也要做隔离」)。 // ↓ 批次 3 的两页(控制方 2026-10-05 点名「店铺撞款监控 店铺数据也要做隔离」)。
// 撞款三处各锚一个左值名(query/params/itemsQuery),店铺数据记录一处。 // 撞款三处各锚一个左值名(query/params/itemsQuery),店铺数据记录一处。
{ menuKey: 'admin_shop_data_duplicate_check', file: 'src/pages/tasks/duplicate-console-api.ts', fn: 'fetchDuplicateConsole', line: 'if (companyId != null) query.company_id = companyId', window: 400, title: 'GET /duplicate-check-console 指标/店铺/撞款全集/分组统计' }, { menuKey: 'admin_shop_data_duplicate_check', file: 'src/pages/tasks/duplicate-console-api.ts', fn: 'fetchDuplicateConsole', line: 'if (companyId != null) query.company_id = companyId', window: 400, title: 'GET /duplicate-check-console 指标/店铺/撞款全集/分组统计' },
@@ -111,6 +110,16 @@ const SEND_POINTS: ReadonlyArray<SendPoint> = [
{ menuKey: 'admin_shop_data_crawl_tasks', file: 'src/pages/tasks/shop-data-api.ts', fn: 'fetchShopDataTaskList', line: 'if (companyId != null) query.company_id = companyId', window: 400, title: 'GET /shop-data-crawl-tasks 店铺数据记录列表' }, { menuKey: 'admin_shop_data_crawl_tasks', file: 'src/pages/tasks/shop-data-api.ts', fn: 'fetchShopDataTaskList', line: 'if (companyId != null) query.company_id = companyId', window: 400, title: 'GET /shop-data-crawl-tasks 店铺数据记录列表' },
// ↓ 批次 4(控制方 2026-10-05 点名「菜单权限和用户管理也要区分公司 tab 的数据」)。 // ↓ 批次 4(控制方 2026-10-05 点名「菜单权限和用户管理也要区分公司 tab 的数据」)。
{ menuKey: 'admin_users', file: 'src/api/users.ts', fn: 'fetchUserList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 400, title: 'GET /users 用户列表(后端早就认这个参数,断的是前端没发)' }, { menuKey: 'admin_users', file: 'src/api/users.ts', fn: 'fetchUserList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 400, title: 'GET /users 用户列表(后端早就认这个参数,断的是前端没发)' },
// ↓ 批次 5(控制方 2026-10-06 点名「店铺密钥管理的数据按照公司区分」)。
{ menuKey: 'admin_shop_keys', file: 'src/pages/shop/shop-key-api.ts', fn: 'fetchShopKeyList', line: 'if (params.companyId != null) query.company_id = params.companyId', window: 400, title: 'GET /shop-keys 紫鸟令牌列表(不带 company_id 时非超管仍由后端会话裁剪,超管点了 tab 才会变)' },
// ↓ 批次 6(控制方 2026-10-06 点名「菜单权限也加字段来区分,现在的默认归到 admin 下」,定案「每家公司一套树」)。
// 三处都锚同一串 TASK_CENTER_SEND_LINE,但分属两个文件 ⇒ (文件, 整行) 分组各成一组,钉数与条数仍逐处对平。
// 窗口取 300:两处 menu-manage 的 own 是 110/130,而 fetchMenuManageNodes 到 createMenu 那行的 next 是 611
// ⇒ 300 够得着自己、够不到隔壁(这三个数由下面「窗口与真文件对平」那条用例逐处从真文件重测,注释过期即红)。
// user-menu-auth-api 那处一条发送口喂两个 GET(admin/app 两类各一支,共用同一个 query 展开)⇒ 一函数一钉。
{ menuKey: 'admin_columns', file: 'src/pages/account/menu-manage-api.ts', fn: 'fetchMenuManageNodes', line: TASK_CENTER_SEND_LINE, window: 300, title: 'GET /permission-menus 目录(超管不带就把两家的同名行混成一排下发)' },
{ menuKey: 'admin_columns', file: 'src/pages/account/menu-manage-api.ts', fn: 'createMenu', line: TASK_CENTER_SEND_LINE, window: 300, title: 'POST /permission-menus 新建:归属由端点参数决定,前端不从树里猜' },
{ menuKey: 'admin_users', file: 'src/pages/account/user-menu-auth-api.ts', fn: 'fetchGrantableMenus', line: TASK_CENTER_SEND_LINE, window: 300, title: 'GET /permission-menus?grantableOnly 授权树:一家一套树后取错公司=已授权勾不上、提交必判无效' },
] ]
/** 任务看板那 5 处(1b ④ 那条用例按文件筛它们,沿用旧名字不漂;表只有一份,不会漂出两个口径)。 */ /** 任务看板那 5 处(1b ④ 那条用例按文件筛它们,沿用旧名字不漂;表只有一份,不会漂出两个口径)。 */
@@ -206,17 +215,24 @@ const COMPANY_ID_SOURCE_PINS: Readonly<Record<string, readonly CompanyIdPin[]>>
note: '列表窄了而下拉不窄 = 两页口径对不上,且下拉能选到别家的组', note: '列表窄了而下拉不窄 = 两页口径对不上,且下拉能选到别家的组',
}, },
], ],
// 批次 2 的五页:取值口钉全部由 SEND_POINTS 现算(一页几处发送口就几条钉), // 批次 2 剩下的三页:取值口钉全部由 SEND_POINTS 现算(一页几处发送口就几条钉),
// 手写一份就会和表漂开——那正是复评 I-1 拆条要避免的形状。 // 手写一份就会和表漂开——那正是复评 I-1 拆条要避免的形状。
// admin_invalid_asin_data / admin_product_categories 两页 2026-10-06 退回全平台共享,
// 已不在注册表里 ⇒ 这里的条目一并摘掉(留着是死表项,"不得回流"由文件末尾那条反向钉看守)。
admin_dedupe_total_data: pinsFor('admin_dedupe_total_data'), admin_dedupe_total_data: pinsFor('admin_dedupe_total_data'),
admin_invalid_asin_data: pinsFor('admin_invalid_asin_data'),
admin_query_asin: pinsFor('admin_query_asin'), admin_query_asin: pinsFor('admin_query_asin'),
admin_skip_price_asin: pinsFor('admin_skip_price_asin'), admin_skip_price_asin: pinsFor('admin_skip_price_asin'),
admin_product_categories: pinsFor('admin_product_categories'),
// 批次 3 的两页同样由 SEND_POINTS 现算(撞款控制台三处发送口 = 三条钉)。 // 批次 3 的两页同样由 SEND_POINTS 现算(撞款控制台三处发送口 = 三条钉)。
admin_shop_data_duplicate_check: pinsFor('admin_shop_data_duplicate_check'), admin_shop_data_duplicate_check: pinsFor('admin_shop_data_duplicate_check'),
admin_shop_data_crawl_tasks: pinsFor('admin_shop_data_crawl_tasks'), admin_shop_data_crawl_tasks: pinsFor('admin_shop_data_crawl_tasks'),
admin_users: pinsFor('admin_users'), admin_users: pinsFor('admin_users'),
// 批次 5(店铺密钥)同样由 SEND_POINTS 现算:这一页只有一个发送口(列表),
// 新增/编辑/删除/白名单检测四支都不带公司参数——归属由后端从操作者会话推导(writeCompanyId 闸门)。
admin_shop_keys: pinsFor('admin_shop_keys'),
// 批次 6(菜单权限):菜单目录 + 新建两处,都由 SEND_POINTS 现算。
// 编辑/删除/重排三支**故意不带**参数——归属由那一行的 id 与操作者公司共同判定,跨公司写后端 403
// (见 docs/ops/menu-company-tree-design-2026-10-06.md §5),给它们发 company_id 反而是第三处口径。
admin_columns: pinsFor('admin_columns'),
} }
/** 严格判据的分母由本轮实扫得出(修完不许恒绿也不许恒红):求值了几条 shape、其中几条通过。 */ /** 严格判据的分母由本轮实扫得出(修完不许恒绿也不许恒红):求值了几条 shape、其中几条通过。 */
@@ -303,11 +319,13 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
// 不许让另一支用例替我证明"这串本来就会被匹配到")。 // 不许让另一支用例替我证明"这串本来就会被匹配到")。
// ⚠ 身份要说清:下面这几条是对**字面量字符串**求值的探针,只证明判据形状没写坏 // ⚠ 身份要说清:下面这几条是对**字面量字符串**求值的探针,只证明判据形状没写坏
// (正样本匹配得出 ⇒ 不恒红;窗口外的负样本不匹配 ⇒ 窗口真有界,删一处不会靠隔壁过关), // (正样本匹配得出 ⇒ 不恒红;窗口外的负样本不匹配 ⇒ 窗口真有界,删一处不会靠隔壁过关),
// 任何代码注入都不会让它们红。真覆盖 = 上面 loop 里那 17 条 shape 对真实文件的求值 + 变异自证。 // 任何代码注入都不会让它们红。真覆盖 = 上面 loop 里那批 shape(条数由 strictPinsEvaluated 当场自证)
// ⚠ 分母是本轮实扫的表条数(批次 1 的 5 + 批次 2 的 12 + 批次 3 的 4 + 批次 4 的 1)。这条只防"整表被摘空/被改窄", // 对真实文件的求值 + 变异自证。
// 逐处脱管由下面两条(对平闸门 + 窗口对平)负责。 // ⚠ 分母是本轮实扫的表条数(批次 1 的 5 + 批次 2 的 7 + 批次 3 的 4 + 批次 4 的 1 + 批次 5 的 1 + 批次 6 的 3;
assert.ok(SEND_POINTS.length >= 22, // 批次 2 原 12 条里的品牌库 1 条 + 商品类目 4 条随 2026-10-06「这两页退回全平台共享」摘掉)。
`发送口表只剩 ${SEND_POINTS.length} 条(批次 1+2+3+4 实扫 22 条)⇒ 有人把钉从表里摘了,取值口看守成空`) // 这条只防"整表被摘空/被改窄",逐处脱管由下面两条(对平闸门 + 窗口对平)负责。
assert.ok(SEND_POINTS.length >= 21,
`发送口表只剩 ${SEND_POINTS.length} 条(批次 1+2+3+4+5+6 实扫 21 条)⇒ 有人把钉从表里摘了,取值口看守成空`)
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)
@@ -330,7 +348,7 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
// 这一条杀的是「把 TASK_CENTER_SEND_POINTS 删剩 4 行」——少一条钉就等于少一处看守,而 5 条 shape 谁都不会红。 // 这一条杀的是「把 TASK_CENTER_SEND_POINTS 删剩 4 行」——少一条钉就等于少一处看守,而 5 条 shape 谁都不会红。
// 路线 ②(occurrences 计数)在这里只当"钉数与发送口条数对平"的闸门,不当"是哪一处"的判据: // 路线 ②(occurrences 计数)在这里只当"钉数与发送口条数对平"的闸门,不当"是哪一处"的判据:
// 计数回答不了"哪三处"(把一处重复写三遍、另一处删掉,计数照样对平),所以主判据仍是路线 ① 的函数名锚 + 有界窗口。 // 计数回答不了"哪三处"(把一处重复写三遍、另一处删掉,计数照样对平),所以主判据仍是路线 ① 的函数名锚 + 有界窗口。
// 分母按 (文件, 整行) 而不是按文件:批次 2 的 product-category-api.ts 一个文件三处发送口、三处是逐字同一行, // 分母按 (文件, 整行) 而不是按文件:任务看板的 task-center.ts 一个文件三处发送口、三处是逐字同一行,
// 按文件计只钉得出"3 条"这个数,按行计才和 occurrences 同一粒度;三个 *-export.ts 的行各只出现 1 次,同理。 // 按文件计只钉得出"3 条"这个数,按行计才和 occurrences 同一粒度;三个 *-export.ts 的行各只出现 1 次,同理。
const grouped = new Map<string, { readonly file: string; readonly line: string; pinned: number }>() const grouped = new Map<string, { readonly file: string; readonly line: string; pinned: number }>()
for (const p of SEND_POINTS) { for (const p of SEND_POINTS) {
@@ -340,7 +358,7 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
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, 17, assert.equal(grouped.size, 17,
`发送口表按 (文件, 整行) 应聚成 17 组(22 处发送口),现在却有 ${grouped.size} 组 —— 表被改形状了,对平判据失去分母`) `发送口表按 (文件, 整行) 应聚成 17 组(21 处发送口),现在却有 ${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,
@@ -357,7 +375,8 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
// own = 从 `function <fn>(` 的括号后到自己那一行的距离 ⇒ 必须 < window(函数体写长 = 假红,fail-closed 可接受); // own = 从 `function <fn>(` 的括号后到自己那一行的距离 ⇒ 必须 < window(函数体写长 = 假红,fail-closed 可接受);
// next = 到同文件**下一条同名发送行**开头的距离 ⇒ 存在时必须 > window(否则删一处还有隔壁顶着,这条钉就是摆设)。 // next = 到同文件**下一条同名发送行**开头的距离 ⇒ 存在时必须 > window(否则删一处还有隔壁顶着,这条钉就是摆设)。
// 隔壁的"名字"用的是自己的整行,所以 next 只在同文件有逐字同行的另一处时才有意义: // 隔壁的"名字"用的是自己的整行,所以 next 只在同文件有逐字同行的另一处时才有意义:
// product-category-api.ts 三处同行(next 实测 705/929/无)是这一族唯一的真冲突面,其余 14 处 own 唯一。 // product-category-api.ts 那组(三处同行)2026-10-06 随「商品类目退回全平台共享」摘掉了;
// 这一族剩下的真冲突面只有任务看板:task-center.ts 三处逐字同行、task-center-model.ts 两处,其余各文件唯一。
for (const p of SEND_POINTS) { for (const p of SEND_POINTS) {
const src = stripComments(read(p.file)) const src = stripComments(read(p.file))
const anchor = 'function ' + p.fn + '(' const anchor = 'function ' + p.fn + '('
@@ -477,6 +496,48 @@ test('发送口的第二实参:task-center 五处 http.get 必须把 query 交
} }
}) })
/**
* 1b ④ 的那一半缺口(批次 5 补,2026-10-06 变异自证 M9 实测存活):上面那支按**端点 URL 字面量**锚,
* 取样文件只有 `src/api/task-center.ts`。店铺密钥这一页的 GET 写的是 `http.get<unknown>(SHOP_KEYS_ENDPOINT, { params: query })`
* ——端点是模块常量、调用还带泛型,那条正则两头都锚不到。把 `{ params: query }` 整段删掉后,
* `if (params.companyId != null) query.company_id = params.companyId` 那一行逐字还在 ⇒ 取值口五判据全绿、
* 编译器一声不响、URL 里没有 company_id:正是 1b ④ 当初要杀的那一形,只是换了一个文件。
*
* <p>判据换成「整行字面量 + 同文件 GET 总条数对平」:锚整行是因为常量名就是这一处的稳定身份,
* 对平是因为只钉一行的话,第二处新 GET 忘了带 params 也照样没人红(与上面「同一 URL 只许一处调用」同理)。</p>
*/
const CONSTANT_ENDPOINT_GET_PINS: ReadonlyArray<{ readonly file: string; readonly fn: string; readonly call: string }> = [
{ file: 'src/pages/shop/shop-key-api.ts', fn: 'fetchShopKeyList', call: 'http.get<unknown>(SHOP_KEYS_ENDPOINT, { params: query })' },
]
test('非字面量端点的发送口:query 必须交给带 params 的第二实参,且同文件 GET 条数与登记表对平(1b ④ 的另一半)', () => {
assert.ok(CONSTANT_ENDPOINT_GET_PINS.length >= 1, '常量端点登记表为空 ⇒ 这一族的第二实参没人看守')
const byFile = new Map<string, number>()
for (const p of CONSTANT_ENDPOINT_GET_PINS) byFile.set(p.file, (byFile.get(p.file) ?? 0) + 1)
for (const p of CONSTANT_ENDPOINT_GET_PINS) {
const src = stripComments(read(p.file))
// ① 判据自证(正样本):登记的那一行本身必须含 params,否则下面的对平是在钉一个坏形状。
assert.ok(p.call.includes(', { params'), `登记表里「${p.call}」不含 params 第二实参 ⇒ 这条判据恒红`)
// ② 判据自证(负样本):删掉第二实参后必须匹配不出自己,否则"带没带 params"都算过。
assert.equal(p.call.replace(', { params: query }', '').includes(p.call), false,
`删掉 { params: query } 之后「${p.call}」仍然自匹配 ⇒ 判据只看得到端点,杀不了这一记变异`)
// ③ 函数身份:这一处 GET 必须由它自己的函数发出。
assert.equal(occurrences(src, `function ${p.fn}(`), 1,
`${p.file} 里「function ${p.fn}(」出现 ${occurrences(src, `function ${p.fn}(`)} 次(要求 1):函数改名或被复制,这一行锚对不上是谁发的`)
// ④ 真文件求值:这一行必须逐字在场一次。
const hits = occurrences(src, p.call)
assert.equal(hits, 1,
`${p.file} 里带 params 实参的「${p.call}」匹配到 ${hits} 处(要求 1):`
+ '0 处 = 发送口把 query 丢了(后端收不到 company_id、接口照旧 200、切 tab 一动不动),多于 1 处 = 有第二处同形调用没人钉')
}
// ⑤ 同文件 GET 总条数对平:新增一处 http.get 而没登记 ⇒ 当场红,不留"新那处还没人管"的默认分支。
for (const [file, pinned] of byFile) {
const src = stripComments(read(file))
const actual = occurrences(src, 'http.get')
assert.equal(actual, pinned,
`${file} 实扫到 ${actual} 处 http.get,登记表只有 ${pinned} 条 —— 有一处 GET 的第二实参没人看守`)
}
})
test('反向:把 company_id 当查询参数用的取数模块必须被清单认领(防止"筛了但没人知道这页参与")', () => { test('反向:把 company_id 当查询参数用的取数模块必须被清单认领(防止"筛了但没人知道这页参与")', () => {
const claimed = new Set(COMPANY_SCOPED_PAGES.flatMap((p) => p.apiFiles)) const claimed = new Set(COMPANY_SCOPED_PAGES.flatMap((p) => p.apiFiles))
const scanned = requestModules() const scanned = requestModules()
@@ -506,7 +567,7 @@ test('反向:把 company_id 当查询参数用的取数模块必须被清单
* 症状回到裁决 1 想避免的那一型。</p> * 症状回到裁决 1 想避免的那一型。</p>
* *
* <p>判据形状:从 `watch(() => companyTab.activeId, …)` 那**一条语句**取文本(正则在第一个 * <p>判据形状:从 `watch(() => companyTab.activeId, …)` 那**一条语句**取文本(正则在第一个
* `}` + `)` 处收口 ⇒ 单层,体内再嵌对象字面量会截早;表里这九页今天都没有那种写法,由下面的取样自检兜着)。 * `}` + `)` 处收口 ⇒ 单层,体内再嵌对象字面量会截早;表里这十页今天都没有那种写法,由下面的取样自检兜着)。
* 反向钉与正样本同支(全局约束 15,三条前提不成立就是探针失效、当场红,不许静默空跑),**每一对**都各跑一遍: * 反向钉与正样本同支(全局约束 15,三条前提不成立就是探针失效、当场红,不许静默空跑),**每一对**都各跑一遍:
* ① 合规样本必须匹配得出且含两把 token ⇒ 判据不恒红; * ① 合规样本必须匹配得出且含两把 token ⇒ 判据不恒红;
* ② 删掉那一句的样本必须不含 ⇒ 判据能红(变异自证走的就是这一条); * ② 删掉那一句的样本必须不含 ⇒ 判据能红(变异自证走的就是这一条);
@@ -521,7 +582,7 @@ test('反向:把 company_id 当查询参数用的取数模块必须被清单
const WATCH_ACTIVE_ID = /watch\(\(\)\s*=>\s*companyTab\.activeId\s*,\s*\(\)\s*=>\s*\{([\s\S]*?)\}\s*\)/ const WATCH_ACTIVE_ID = /watch\(\(\)\s*=>\s*companyTab\.activeId\s*,\s*\(\)\s*=>\s*\{([\s\S]*?)\}\s*\)/
/** /**
* (文件, 必须出现在 watch 体内的赋值) 九对,同一条 test 里逐对钉(批次 1 两对 + 批次 2 五对 + 批次 3 两对)。 * (文件, 必须出现在 watch 体内的赋值) 十对,同一条 test 里逐对钉(批次 1 两对 + 批次 2 三对 + 批次 3 两对 + 批次 4 一对 + 批次 5 一对 + 批次 6 一对)。
* `premise` 是这一对的反向钉前提:这一页的发送口今天还在发 `company_id`,清筛选项才有意义; * `premise` 是这一对的反向钉前提:这一页的发送口今天还在发 `company_id`,清筛选项才有意义;
* 哪天发送口退回不带参,watch 看守就变成"清了一个没人用的筛选项",必须一起红。 * 哪天发送口退回不带参,watch 看守就变成"清了一个没人用的筛选项",必须一起红。
*/ */
@@ -551,7 +612,8 @@ const WATCH_BODY_PINS: ReadonlyArray<{
{ file: 'src/pages/task-center/task-center-model.ts', shapes: [/company_id\s*=\s*companyId\b/] }, { file: 'src/pages/task-center/task-center-model.ts', shapes: [/company_id\s*=\s*companyId\b/] },
], ],
}, },
// ↓ 批次 2 的五页(控制方 2026-10-05 点名「切 tab 数据还一样」那一批)。 // ↓ 批次 2 剩下的三页(控制方 2026-10-05 点名「切 tab 数据还一样」那一批;
// 品牌库、商品类目两页 2026-10-06 退回全平台共享,条目一并摘掉)。
// token 在两页上同形(`filter.groupId = null` 出现三次),这**不是**漏洞:判据按 (file, token) 成对求值, // token 在两页上同形(`filter.groupId = null` 出现三次),这**不是**漏洞:判据按 (file, token) 成对求值,
// 每一对都各自去读它自己那一页的源码,别家页缺了这行不会红在这一页,反之这一页删掉了也不会被隔壁顶住 // 每一对都各自去读它自己那一页的源码,别家页缺了这行不会红在这一页,反之这一页删掉了也不会被隔壁顶住
// (负样本 ③「挪到 watch 之外」钉的就是位置)。 // (负样本 ③「挪到 watch 之外」钉的就是位置)。
@@ -563,14 +625,6 @@ const WATCH_BODY_PINS: ReadonlyArray<{
{ file: 'src/pages/asin/dedupe-total-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] }, { file: 'src/pages/asin/dedupe-total-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] },
], ],
}, },
{
file: 'src/pages/asin/AsinInvalidPage.vue',
token: 'filter.groupId = null',
why: '品牌库的分组下拉按公司收窄,留着上一家的 groupId 就是拿一个新一家看不见的组去筛列表',
premise: [
{ file: 'src/pages/invalidasin/invalid-asin-api.ts', shapes: [/company_id\s*=\s*query\.companyId\b/] },
],
},
{ {
file: 'src/pages/asin/QueryAsinPage.vue', file: 'src/pages/asin/QueryAsinPage.vue',
token: "filter.groupId = null; filter.shopName = ''", token: "filter.groupId = null; filter.shopName = ''",
@@ -588,15 +642,6 @@ const WATCH_BODY_PINS: ReadonlyArray<{
{ file: 'src/pages/asin/skip-price-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] }, { file: 'src/pages/asin/skip-price-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] },
], ],
}, },
{
file: 'src/pages/asin/ProductCategoryPage.vue',
token: 'childrenState.clear()',
why: '类目树是**懒加载缓存**:childrenState 里存着上一家每个父级的子页与页码,切公司不清它,展开同一父级就'
+ '直接把别家的子类目画出来(这一处根本不发请求,比"筛成空页"更静默)',
premise: [
{ file: 'src/pages/asin/product-category-api.ts', shapes: [/company_id\s*=\s*companyId\b/] },
],
},
// ↓ 批次 3 的两页(控制方 2026-10-05 点名「店铺撞款监控 店铺数据也要做隔离」)。 // ↓ 批次 3 的两页(控制方 2026-10-05 点名「店铺撞款监控 店铺数据也要做隔离」)。
// 这两页的 token 一直写到 reload 那两句为止(批次 1/2 的老条目仍只钉清筛选项,不动它们): // 这两页的 token 一直写到 reload 那两句为止(批次 1/2 的老条目仍只钉清筛选项,不动它们):
// 变异自证发现「删掉 void loadConsole()」当时全绿——清筛选项那半守住了,重新取数那半没人守。 // 变异自证发现「删掉 void loadConsole()」当时全绿——清筛选项那半守住了,重新取数那半没人守。
@@ -633,6 +678,28 @@ const WATCH_BODY_PINS: ReadonlyArray<{
{ file: 'src/api/users.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] }, { file: 'src/api/users.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] },
], ],
}, },
// ↓ 批次 5(控制方 2026-10-06 点名「店铺密钥管理的数据按照公司区分」)。
{
file: 'src/pages/shop/ShopKeysPage.vue',
token: "filterKeyword.value = ''; page.value = 1; void load()",
why: '这一页的「备注名 / 紫鸟账号」是客户端过滤(filteredRows 在本页 rows 上筛,不进请求):'
+ '留着上一家填的关键字,切到新一家就是拿别家的字符串去筛本公司那几行 ⇒ 首屏「暂无符合条件的密钥」而筛选框里还显示着它;'
+ '页码回 1 是因为新一家的令牌更少,末尾的 void load() 才让切 tab 真的换数据',
premise: [
{ file: 'src/pages/shop/shop-key-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] },
],
},
// ↓ 批次 6(控制方 2026-10-06 点名「菜单权限也加字段来区分」,定案「每家公司一套树」)。
{
file: 'src/pages/account/MenusPage.vue',
token: "filterName.value = ''; filterType.value = ''; page.value = 1; void loadMenus()",
why: '菜单名称/类型是客户端筛选(filteredMenuRows 在本页已取的 rows 上筛,不进请求):留着上一家填的值'
+ '就是拿别家的字符串去筛新一家那一套树 ⇒ 首屏「暂无匹配菜单」,而输入框里还显示着那个值。页码回 1 是因为'
+ '新一家的行数不同,末尾的 void loadMenus() 才是本页唯一的数据出口',
premise: [
{ file: 'src/pages/account/menu-manage-api.ts', shapes: [/company_id\s*=\s*companyId\b/] },
],
},
] ]
/** 取「`watch(() => companyTab.activeId, () => { … })`」这一条语句的原文;匹配不出返回 null(由调用方判探针失效)。 */ /** 取「`watch(() => companyTab.activeId, () => { … })`」这一条语句的原文;匹配不出返回 null(由调用方判探针失效)。 */
@@ -641,9 +708,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 一页)', () => { test('切公司的 watch 体:每对 (file, token) 都要在该页 watch 体内出现(批次 1 两页 + 批次 2 三页 + 批次 3 两页 + 批次 4 一页 + 批次 5 一页 + 批次 6 一页)', () => {
assert.ok(WATCH_BODY_PINS.length >= 10, assert.ok(WATCH_BODY_PINS.length >= 10,
`watch 体看守只剩 ${WATCH_BODY_PINS.length} 对(批次 1 的店铺管理/任务看板 + 批次 2 的去重库/品牌库/查询ASIN/最低价ASIN/商品类目 + 批次 3 的撞款监控/店铺数据记录 + 批次 4 的用户管理共 10 对)` `watch 体看守只剩 ${WATCH_BODY_PINS.length} 对(批次 1 的店铺管理/任务看板 + 批次 2 的去重库/查询ASIN/最低价ASIN + 批次 3 的撞款监控/店铺数据记录 + 批次 4 的用户管理 + 批次 5 的店铺密钥 + 批次 6 的菜单管理共 10 对)`
+ '⇒ 这一族又退回"只钉少数几页",被摘掉那一页的"切公司不清筛选项"再次没人看守') + '⇒ 这一族又退回"只钉少数几页",被摘掉那一页的"切公司不清筛选项"再次没人看守')
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) {
@@ -810,3 +877,108 @@ test('挂载与单一尺子:tab 条挂在壳层、公司名读 companyName、
assert.match(tabs, /initialize\(\)\.catch\(/, assert.match(tabs, /initialize\(\)\.catch\(/,
'组件侧必须 .catch 接住 store 的 rethrow,否则又变回 unhandled rejection') '组件侧必须 .catch 接住 store 的 rethrow,否则又变回 unhandled rejection')
}) })
test('渲染范围:tab 条只画在按公司取数的页上,公司管理那排点了没反应的 tab 摘掉', () => {
// 2026-10-06 控制方:「公司管理不要有 tab」。10-05 那一轮只钉住了「CompaniesPage 不消费 store」
// (company-config-entry-super-only 最后那条),而 tab 条本身挂在壳层 AdminLayout、对全部页都画
// ⇒ 界面一个字都没变,同一天被第二次点名。这条补的是**渲染侧**那一半。
// 判据取 COMPANY_SCOPED_PAGES 这一张注册表:写黑名单的话,下一个新页默认长出一条装饰 tab。
const pageKeys = adminPages.map((p) => p.menuKey)
assert.ok(pageKeys.length >= 22, `路由注册表只取到 ${pageKeys.length} 页 ⇒ 分母被删空,下面的差集会假绿`)
const scoped = new Set(COMPANY_SCOPED_PAGES.map((p) => p.menuKey))
const unscoped = pageKeys.filter((k) => !scoped.has(k))
assert.ok(scoped.size >= 15, `注册表只剩 ${scoped.size} 页 ⇒ 正向那半的循环没东西可验`)
assert.ok(unscoped.includes('admin_companies'),
'admin_companies 竟在公司 tab 注册表里:与「公司管理仅超管、不做 tab」直接冲突')
const model = stripComments(readSource('src/layout/company-tab-model.ts'))
assert.match(model, /new Set\(COMPANY_SCOPED_PAGES\.map/,
'companyTabAppliesTo 必须从 COMPANY_SCOPED_PAGES 派生,不是另立一张名单')
assert.equal(model.includes("'admin_companies'"), false,
'渲染判据里不许写死菜单名:那是第二张清单,与注册表迟早漂移')
// 真值双向:注册表内 ⇒ 画(漏了就是取值口与渲染口分家),注册表外每一页 ⇒ 不画(点了不重取数)
for (const key of scoped) assert.equal(companyTabAppliesTo(key), true, `${key} 在注册表里却不画 tab`)
for (const key of unscoped) assert.equal(companyTabAppliesTo(key), false, `${key} 没接公司隔离却画着 tab`)
assert.equal(companyTabAppliesTo(undefined), false, '没有 menuKey 的开放页(登录页等)默认不画')
// 组件真把这一条串进了 show:只导出函数不接线=这条护栏恒绿
const tabs = stripComments(readSource('src/layout/CompanyTabs.vue'))
const showLine = tabs.split('\n').find((line) => line.includes('const show ='))
assert.ok(showLine, 'CompanyTabs.vue 找不到 `const show =` 这一行:渲染开关换写法了,先确认它还在不在')
assert.ok(showLine.includes('tab.visibleForOperator'), 'show 少了「目录可用」那条')
assert.ok(showLine.includes('companyTabAppliesTo(route.meta.menuKey)'),
'show 少了「这一页吃公司」那条 ⇒ 退回全页画 tab,公司管理页头顶又会长出那一排')
})
/**
* 2026-10-06 控制方定案:品牌数据库、商品类目「做成所有公司共享的,不区分」。
*
* <p>上面那几条正向判据全是从 {@code COMPANY_SCOPED_PAGES} 派生的,页一退出注册表就自动不再求值 ⇒
* 「退出」这件事本身没有看守:谁把 {@code company_id} 重新塞回这三个取数口,全仓用例一支都不会红,
* 而后端唯一键已经退回全局(V151),带公司参数的读会把共享库筛窄成「只看这一家」,
* 写侧则把一张全平台共享的表按家拆开——两边都是静默改口径,不是报错。所以这一支必须存在。</p>
*
* <p>判据只认「剥完注释的代码」:这三份文件现在各自留有一句说明共享口径的注释,
* 注释里的 {@code company_id} 三个字面字符不是接线(全局约束 6)。正样本用摘掉之前那三行原文,
* 所以下面的 false 是测出来的,不是「正则本来就抓不到」。</p>
*/
const SHARED_PAGE_KEYS = ['admin_invalid_asin_data', 'admin_product_categories'] as const
const SHARED_API_FILES = [
'src/pages/invalidasin/invalid-asin-api.ts',
'src/pages/asin/product-category-api.ts',
'src/pages/asin/product-category-export.ts',
] as const
const SHARED_PAGE_FILES = [
'src/pages/asin/AsinInvalidPage.vue',
'src/pages/asin/ProductCategoryPage.vue',
] as const
/** 公司参数的两种写法:下传用的 snake、形参/字段用的 camel。 */
const COMPANY_PARAM_TOKEN = /(?:company_id|companyId)/
/** 本次摘掉的三行原发送口(逐字取自改动前的源码),做反向钉的同支正样本。 */
const FORMER_SEND_LINES = [
'if (query.companyId != null) params.company_id = query.companyId',
'if (companyId != null) params.company_id = companyId',
'if (companyId != null) params.push(`company_id=${companyId}`)',
]
test('公司维度不得回流:品牌库与商品类目已定案全平台共享,取数口与页面都不许再带公司参数', () => {
// 判据自证(全局约束 15:反向钉不许独自成立)——改动前那三行必须抓得到,否则下面的 false 是空判据。
for (const line of FORMER_SEND_LINES) {
assert.ok(COMPANY_PARAM_TOKEN.test(line), `反向钉判据连原来的发送口「${line}」都匹配不出 ⇒ 这一族恒绿`)
}
// watch 探针同理:它今天还在 WATCH_BODY_PINS 那十对上起作用,这里再就地复验一次形状,
// 免得「页面里没有 watch」是因为正则换了写法而失明。
assert.ok(WATCH_ACTIVE_ID.test('watch(() => companyTab.activeId, () => { void load() })'),
'WATCH_ACTIVE_ID 连合规样本都匹配不出 ⇒ 下面「不许再长出 watch」那条恒绿')
// 注册表本身非空自证:表被删空时 some() 会对所有 key 返回 false,看着像「都退出了」。
assert.ok(COMPANY_SCOPED_PAGES.length >= 15,
`注册表只剩 ${COMPANY_SCOPED_PAGES.length} 页 ⇒ 分母被删空,下面的 some() 会假绿`)
for (const key of SHARED_PAGE_KEYS) {
assert.equal(COMPANY_SCOPED_PAGES.some((p) => p.menuKey === key), false,
`${key} 又回到 COMPANY_SCOPED_PAGES:2026-10-06 已定案这两页全平台共享,不区分公司`)
const page = adminPages.find((p) => p.menuKey === key)
assert.ok(page, `${key} 在路由注册表里找不到:菜单名改了,反向钉对不上页`)
assert.equal(page.companyScoped, false,
`${key} 的 meta.companyScoped 不再是 false:tab 条会画出来,而这一页的取数口没有公司参数 ⇒ 点了没反应)`)
}
for (const file of [...SHARED_API_FILES, ...SHARED_PAGE_FILES]) {
const src = stripComments(read(file))
assert.equal(COMPANY_PARAM_TOKEN.test(src), false,
`${file} 又出现了公司参数:这两页读的是全平台共享的库,带上 company_id 等于把共享口径偷偷改回按家筛`)
assert.ok(COMPANY_PARAM_TOKEN.test(`${src}\n${FORMER_SEND_LINES[0]}`),
`(同支正样本)${file} 的源码喂进判据后连拼上原发送口都匹配不出 ⇒ 上面那条 false 无从判定`)
}
for (const file of SHARED_PAGE_FILES) {
const src = stripComments(read(file))
assert.equal(WATCH_ACTIVE_ID.test(src), false,
`${file} 又 watch 了 companyTab.activeId:这一页不按公司取数,切 tab 重取数只会把用户正在看的页刷掉`)
assert.equal(/useCompanyTabStore|companyTab\.requestCompanyId/.test(src), false,
`${file} 重新引回了公司 tab store,而它对应的 tab 条已经摘掉`)
}
})
+21 -8
View File
@@ -1,16 +1,17 @@
# Flyway 迁移盘点(task-193) # Flyway 迁移盘点(task-193)
> 生成方式:`src/test/java/com/nanri/aiimage/config/MigrationInventoryTest.java`(只读审计,可重复)。 > 生成方式:`src/test/java/com/nanri/aiimage/config/MigrationInventoryTest.java`(只读审计,可重复)。
> 快照日期:2026-10-01;2026-10-03 随 V142 追加时同步过概览数字与取号起点;2026-10-04 随 V143 同步;2026-10-04 随 V144 同步;2026-10-04 15:1x 随 V145 同步;2026-10-05 随 V146 同步;2026-10-05 23:0x 随 V147 同步。 > 快照日期:2026-10-01;2026-10-03 随 V142 追加时同步过概览数字与取号起点;2026-10-04 随 V143 同步;2026-10-04 随 V144 同步;2026-10-04 15:1x 随 V145 同步;2026-10-05 随 V146 同步;2026-10-05 23:0x 随 V147 同步;2026-10-06 随 V148 同步(并把 V145/V146/V147 从"待发版"挪进"已应用");2026-10-06 随 V149 同步(菜单树按公司一套;V148 仍未上线,故 V149 与它同批);2026-10-06 随 V150/V151 同步,并删掉未上线的 V148(该号就此退役,见下)。
## 概览 ## 概览
- 版本化迁移文件数:**146**(`src/main/resources/db/V*.sql`,其中整数版本 145 个 + 小版本 V25_1) - 版本化迁移文件数:**149**(`src/main/resources/db/V*.sql`,其中整数版本 148 个 + 小版本 V25_1)
- 整数版本范围:**V1..V147**,其中 V132/V133 为已退役空号(见下),其余连续 - 整数版本范围:**V1..V151**,其中 V132/V133/V148 为已退役空号(见下),其余连续
- 历史遗留小版本:**V25_1__shop_manage_group_bind_user.sql**(Flyway 语义 25.1,紧跟在 V25 之后、V26 之前执行,属历史命名,保留) - 历史遗留小版本:**V25_1__shop_manage_group_bind_user.sql**(Flyway 语义 25.1,紧跟在 V25 之后、V26 之前执行,属历史命名,保留)
- 最新版本:**V147__product_category_company_scope.sql**(上一版 **V146__users_expires_at_admin_expiry.sql**,再上一版 **V145__brand_dedupe_company_scope.sql**) - 最新版本:**V151__rule_tables_shared_across_companies.sql**(上一版 **V150__shop_key_company_scope.sql**,再上一版 **V149__permission_menu_company_tree.sql**)
- 待下一次 jar 发版执行的三条:`V145__brand_dedupe_company_scope.sql`、`V146__users_expires_at_admin_expiry.sql`、`V147__product_category_company_scope.sql` - 待下一次 jar 发版执行的三条(按序):`V149__permission_menu_company_tree.sql`、`V150__shop_key_company_scope.sql`、`V151__rule_tables_shared_across_companies.sql`
- 已应用:V142(10-03 18:23)、V143(10-04 10:48)、**V144(10-04 13:22)** - 已应用:V142(10-03 18:23)、V143(10-04 10:48)、**V144(10-04 13:22)**、`V145__brand_dedupe_company_scope.sql`(10-05 13:01)、`V146__users_expires_at_admin_expiry.sql`(10-05 13:01)、**`V147__product_category_company_scope.sql`(10-06 11:03)**
- 末段 `flyway_schema_history` 为 2026-10-06 主机A 只读实查(`success` 全 1,最大整数版本 147),不是从 jar 版本推的
- 重复版本:无 - 重复版本:无
- 迁移命名:全部符合 `V<整数>(_<子版本>)?__<描述>.sql`,无空格 - 迁移命名:全部符合 `V<整数>(_<子版本>)?__<描述>.sql`,无空格
@@ -18,11 +19,23 @@
生产 `flyway_schema_history` 末段:V125..V131 之后直接是 **V134__publish_item_free_text_columns**、**V135__dedupe_total_data_wide_columns**(两条 `installed_on` 均为 2026-09-25 20:46:16),库内没有 132/133 记录。 生产 `flyway_schema_history` 末段:V125..V131 之后直接是 **V134__publish_item_free_text_columns**、**V135__dedupe_total_data_wide_columns**(两条 `installed_on` 均为 2026-09-25 20:46:16),库内没有 132/133 记录。
## V132/V133 空号的来历 ## 空号的来历(V132/V133/V148)
本地曾存在 `V132__web_config_add_is_latest.sql`、`V133__hide_redundant_indexes_invisible.sql`,与另一分支已在生产落库的 V134/V135 冲突。因 Flyway 未开启 `out-of-order`,把任何迁移编到 132/133 会在启动期报 "resolved migration not applied";因此这两条改为 **V136/V137**,132/133 永久退役,不可回填。 本地曾存在 `V132__web_config_add_is_latest.sql`、`V133__hide_redundant_indexes_invisible.sql`,与另一分支已在生产落库的 V134/V135 冲突。因 Flyway 未开启 `out-of-order`,把任何迁移编到 132/133 会在启动期报 "resolved migration not applied";因此这两条改为 **V136/V137**,132/133 永久退役,不可回填。
后续新增迁移从 **V148** 起取号(只认"当前最大值 + 1",不要为还没写出来的迁移预留号段——预留会在 1..max 里留洞,`integerVersionsSequentialFromOne` 会红)。V148 的第一件已知待办就是摘掉 `biz_product_category.company_id` 的 DEFAULT(一条 `ALTER … ALTER COLUMN company_id DROP DEFAULT`,禁 MODIFY),前提是同批 jar 已双节点上线且写侧都显式落公司。 `V148__product_category_builtin_owned_by_company.sql`(把 18 行内置类目的归属从共享哨兵 0 改成厦门米椿花 1)从未上线,2026-10-06 控制方点名「商品类目做成共享的,不区分」⇒ 它的口径被 V151 整体推翻,文件连同 `ProductCategoryMigrationV148Test`、`docs/rollback-V148-product-category-builtin-shared.sql` 一起删除。它与 132/133 的区别要写清:**把新迁移编号写回 148 在 Flyway 语义上是可行的**(生产最大值仍是 147,不存在 out-of-order),这里禁它是共树并发的护栏——148 与 149/150 是同一工作区里另一路会话此刻正在引用的号,被删的 `V148` 文件可能被再次写出,而同号两个文件会让 Flyway 启动期报 "Found more than one migration with version 148" ⇒ 两台 java 同时起不来。宁可让 `integerVersionsSequentialFromOne` 的红字出现在测试里,也不把撞号留到运行期发现。因此这三个号都在 `MigrationInventoryTest.RETIRED_HOLES` 里登记。
后续新增迁移从 **V152** 起取号(只认"当前最大值 + 1",不要为还没写出来的迁移预留号段——预留会在 1..max 里留洞,`integerVersionsSequentialFromOne` 会红;也不要回填上面那三个洞)。原先挂在 V149 名下的"摘 DEFAULT"待办,现在只剩一条元数据操作:
- `ALTER TABLE columns ALTER COLUMN company_id DROP DEFAULT;` —— 前提:V149 那版 jar 两台同版(`PermissionMenuService` 的所有建/改菜单出口都显式写 companyId),旧 jar 已不可能再靠 DEFAULT 兜住插行。
**`biz_product_category.company_id` 的 DEFAULT 由"待摘"改成"必须保留"**(这一条与 V151 同批生效):V151 之后新 jar 的 INSERT 列清单不含 `company_id`,而该列是 `NOT NULL`,全靠 `DEFAULT 1` 满足——此时执行 `DROP DEFAULT` 会让每一次新建类目报 1364。`biz_invalid_asin_data.company_id` 同理(品牌库那条写入失败还会被 `CollectDataInvalidAsinBatchWriter` 吞成 `log.warn` ⇒ 接口返回成功而黑名单静默少一批)。所以这两张表已从 `CompanyDefaultGuard.WATCHED_TABLES` 与探针 SQL 的 IN 列表里同时摘掉(清单与 SQL 由 `CompanyDefaultGuardTest` 双向钉同源),否则哨兵会在每次启动时对着一列"没人读、摘了会炸"的默认值喊 `COMPANY_DEFAULT_STILL_PRESENT`,而巡检把那条签名计进 ALERTS。
它们真正消失的时点是下一版(两台同版之后):
- `ALTER TABLE biz_invalid_asin_data DROP COLUMN company_id;`
- `ALTER TABLE biz_product_category DROP COLUMN company_id;`
摘除 DEFAULT 的动作在这两条里"顺带完成"(列没了,默认值随之消失),**仍然禁写成 `MODIFY COLUMN ... NOT NULL`**(重建表会按当时的列默认值物化历史行)。`biz_dedupe_total_data` 与 `biz_shop_key` 不在此列:它们仍然按公司写,DEFAULT 该摘还是要摘,哨兵继续盯。
原先挂在待办里的"V137 冗余索引 DROP"迁移计划取 V139,该号已被 `V139__asin_result_cache.sql` 占用,顺延到 V140;V140 已被品牌补测队列表 `V140__collectdata_brand_recheck.sql` 落用。 原先挂在待办里的"V137 冗余索引 DROP"迁移计划取 V139,该号已被 `V139__asin_result_cache.sql` 占用,顺延到 V140;V140 已被品牌补测队列表 `V140__collectdata_brand_recheck.sql` 落用。
@@ -0,0 +1,149 @@
-- =============================================================
-- 回滚补丁 V149__permission_menu_company_tree(人工执行,故意放在 Flyway 扫描路径之外)
-- 对应迁移:src/main/resources/db/V149__permission_menu_company_tree.sql
-- 设计:crawler-plugin/docs/ops/menu-company-tree-design-2026-10-06.md §9
--
-- 【为什么不是 V150】src/main/resources/db/ 是 Flyway 扫描路径,任何 V*.sql 都会在应用下次启动时
-- 自动执行。把回滚编成版本化迁移,等于让"决定回滚"这件事在没有人工执行的情况下自己发生。
--
-- 【执行顺序,一步不能换】
-- 1) 停两台 java(/api 经主机 B 的 clb 打到两台,留一台跑旧 jar 会让回滚中途被写入)
-- 2) 先跑第 0 段的两个 COUNT,把数记下来 —— 第 3 段判据要用它
-- 3) 跑本脚本(第 1..7 段)
-- 4) 删 flyway_schema_history 的 version=149 行(第 8 段;漏掉这步,将来重装时 Flyway
-- 见"已应用"会跳过 V149,回滚就白做了一半)
-- 5) 回滚 jar 到与本批不兼容的上一版(即只认 V147 及更早、columns 还没有 company_id 的那版构建;
-- V148 是已退役空号,不存在对应 jar —— 号位以 docs/migration-inventory.md 为准)
-- 6) 起应用
--
-- 【顺序上的唯一陷阱:必须先重指授权、后删副本】
-- user_column_permission 的 FK 是 ON DELETE CASCADE:直接 DELETE 副本行会把它名下所有授权
-- 一起删光 —— 而 V149 之后账号名下"本来就该"挂的是副本行。所以第 2 段先按 column_key 把指针
-- 挪回公司 1 的源行,第 3 段才敢删副本。这两段写反 = 把 133 只账号的菜单全清掉。
-- =============================================================
-- ---------- 0. 回滚前取证(只读,先把这两个数抄下来) ----------
-- 0a 副本行数(V149 后应 = 公司数-1 家 × 51)
SELECT 'V149_ROLLBACK_PRE copy_rows' AS marker, COUNT(*) AS rows_to_delete
FROM `columns` WHERE company_id <> 1;
-- 0b 挂在副本上的授权数(这些是回滚后必须回到源行的那批)
SELECT 'V149_ROLLBACK_PRE grants_on_copies' AS marker, COUNT(*) AS grants_to_repoint
FROM `user_column_permission` g
JOIN `users` u ON u.id = g.user_id
JOIN `columns` c ON c.id = g.column_id
WHERE c.company_id <> 1;
-- ---------- 1. 备份(两张都整表抄,回滚失败时按 <表名>_bak_v149_rollback 反插) ----------
-- 必须显式建、不要依赖 mysqldump:这两张表小(52+ 行 / 784 行),同库内备份是秒级,
-- 而"删完才发现判据错"的唯一出路就是这里有原样一份。
CREATE TABLE IF NOT EXISTS `columns_bak_v149_rollback` AS SELECT * FROM `columns`;
CREATE TABLE IF NOT EXISTS `user_column_permission_bak_v149_rollback` AS SELECT * FROM `user_column_permission`;
-- ---------- 2. 授权指针挪回公司 1 的源行 ----------
-- 2a 先去重:同一账号若同时挂着源行与副本(正常不会有,属 repair 中途态),删副本那一侧,
-- 留源行那一侧给 2b 判定,避免 2b 撞 PK (user_id, column_id) 报 1062。
DELETE dup FROM `user_column_permission` dup
JOIN `users` u ON u.id = dup.user_id
JOIN `columns` copy ON copy.id = dup.column_id AND copy.company_id = u.company_id
JOIN `columns` src ON src.id <> copy.id AND src.column_key = copy.column_key AND src.company_id = 1
JOIN `user_column_permission` old ON old.user_id = dup.user_id AND old.column_id = src.id;
-- 2b 重指回源行。
UPDATE `user_column_permission` g
JOIN `columns` copy ON copy.id = g.column_id AND copy.company_id <> 1
JOIN `columns` src ON src.company_id = 1 AND src.column_key = copy.column_key
SET g.column_id = src.id;
-- 2c 闸门:此时绝不允许再有"授权指向非 1 公司的行"。不为 0 就是 2b 漏了行,
-- 下一步的 CASCADE 会把它们静默删掉 —— 宁可这里报错停下,也不要少一批菜单而没人知道。
CREATE TEMPORARY TABLE `_v149_rb_gate` (`must_be_zero` INT NOT NULL);
INSERT INTO `_v149_rb_gate`
SELECT IF(COUNT(*) = 0, 0, NULL)
FROM (
SELECT g.user_id FROM `user_column_permission` g
JOIN `columns` c ON c.id = g.column_id
WHERE c.company_id <> 1
) bad;
DROP TEMPORARY TABLE `_v149_rb_gate`;
-- ---------- 3. 删副本 ----------
DELETE FROM `columns` WHERE company_id <> 1;
-- ---------- 4. 换回两条全平台唯一键(副本已删,源行本来就唯一 ⇒ 不会因重复失败) ----------
SET @db_name = DATABASE();
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'columns' AND INDEX_NAME = 'uk_column_key');
SET @sql := IF(@idx_exists = 0,
'ALTER TABLE `columns` ADD UNIQUE KEY `uk_column_key` (`column_key`)',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'columns' AND INDEX_NAME = 'uk_menu_type_route_path');
SET @sql := IF(@idx_exists = 0,
'ALTER TABLE `columns` ADD UNIQUE KEY `uk_menu_type_route_path` (`menu_type`, `route_path`)',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 5. 摘掉两条按公司的新键 ----------
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'columns' AND INDEX_NAME = 'uk_company_column_key');
SET @sql := IF(@idx_exists = 1, 'ALTER TABLE `columns` DROP INDEX `uk_company_column_key`', 'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'columns'
AND INDEX_NAME = 'uk_company_menu_type_route_path');
SET @sql := IF(@idx_exists = 1, 'ALTER TABLE `columns` DROP INDEX `uk_company_menu_type_route_path`', 'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 6. 删列 ----------
SET @col_exists := (SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'columns' AND COLUMN_NAME = 'company_id');
SET @sql := IF(@col_exists = 1, 'ALTER TABLE `columns` DROP COLUMN `company_id`', 'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 7. 复验(三条读数抄进回滚记录) ----------
-- 列已删(应 0 行)
SELECT 'V149_ROLLBACK_POST company_col' AS marker, COUNT(*) AS col_still_there
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'columns' AND COLUMN_NAME = 'company_id';
-- 两条旧键在、两条新键没了(应恰好 4 行且 NON_UNIQUE 全 0)
SELECT 'V149_ROLLBACK_POST indexes' AS marker, INDEX_NAME,
GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX) AS cols, NON_UNIQUE
FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'columns' AND NON_UNIQUE = 0
GROUP BY INDEX_NAME, NON_UNIQUE;
SELECT 'V149_ROLLBACK_POST rows' AS marker, COUNT(*) AS rows_now FROM `columns`;
SELECT 'V149_ROLLBACK_POST grants' AS marker, COUNT(*) AS grants_now FROM `user_column_permission`;
-- ---------- 8. 删 Flyway 历史行(漏掉 = 重装时 V149 被跳过) ----------
DELETE FROM `flyway_schema_history` WHERE `version` = '149';
-- ---------- 9. 回滚后的语义,写明别当 bug ----------
-- 公司 2 的 2 只账号回到 V149 之前的状态:授权挂在公司 1 的行上,两家共用一棵树。
-- 跨公司串扰因此重新发生(这本来就是回滚的代价),而 columns 表回到全平台唯一键。
-- 备份表 columns_bak_v149_rollback / user_column_permission_bak_v149_rollback 确认无误后手工 DROP。
@@ -0,0 +1,38 @@
-- 回滚 V150(人工补丁,不放进 src/main/resources/db/——那里是 Flyway 扫描路径,
-- 任何 V*.sql 都会在应用下次启动时自动执行;把回滚编成版本化迁移等于让"决定回滚"这件事
-- 在没有人工执行的情况下自己发生。)
--
-- 顺序:停两台应用 → 执行本脚本 → DELETE FROM flyway_schema_history WHERE version='150'
-- → 回滚 jar → 起应用。
-- 漏掉"删历史行"那步,将来重装带 V150 的 jar 时 Flyway 判定"已应用"直接跳过重建,
-- 而 Java 侧实体照常读写 company_id ⇒ 运行期 Unknown column。
--
-- 【本版本没有唯一键要退】V150 刻意不动 uk_ziniao_token_hash(理由见迁移文件头注释第 4 段:
-- 同一个紫鸟令牌在两家公司各存一行会被 ZiniaoApiKeyProvider 按令牌并成一条,白名单状态与代理互相顶掉),
-- 所以这里没有 V147 那种"先加旧键后删新键"的第 1 段,也没有 1062 预检。
--
-- ---------- 0. 预检:这一列上到底有几家公司的行 ----------
-- SELECT company_id, COUNT(*) AS rows_per_company
-- FROM `biz_shop_key`
-- GROUP BY company_id
-- ORDER BY company_id;
-- -> 只有一行(company_id=1):说明批次上线后没有第 2 家建过密钥,第 1 段 DROP 掉的只是"全 1"这一列,
-- 损失可忽略。
-- -> 出现 company_id<>1:第 2 家已经在这一列上登记过自己的令牌归属。此时【不要】DROP COLUMN——
-- 这张表没有任何账号列,归属删掉就再也分不回去(V150 §2 写明了这个不可逆点)。
-- 改走第 2 段"只回滚 jar、保留新列"。
--
-- ---------- 1. 把列也删掉才解开下面这行(不可逆,先备份) ----------
-- ALTER TABLE `biz_shop_key` DROP COLUMN `company_id`;
--
-- ---------- 2. 默认档:保留新列,只回滚 jar ----------
-- 旧 jar 的 ShopKeyEntity 没有 companyId 字段,MyBatis-Plus 的 insert 列清单不含它 ⇒
-- 这一列对旧 jar 是惰性的:不读写就不影响,而 DEFAULT 1 正好把旧 jar 插入的行接住。
-- 所以真要止损时,这一档比删列安全得多,也是第 0 段查出多家公司时的唯一走法。
-- (代价:混合窗口里旧 jar 建的密钥会静默归进第 1 家——这与 V150 上线之前没有任何区别,
-- 不是回滚引入的新问题。)
--
-- ALTER TABLE `biz_shop_key` ALTER COLUMN company_id DROP DEFAULT;
-- ↑ 这一句【不属于回滚】。它是"摘 DEFAULT"那笔前向修复的内容(V150 §6)。
-- 任何时候都不要写 MODIFY COLUMN ... NOT NULL:重建表会按"当时的列默认值"物化历史行,
-- 而 V150 没有写回历史行,历史归属的全部依据就是那个默认值。
@@ -0,0 +1,69 @@
-- 回滚 V151(人工补丁,不放进 src/main/resources/db/——那里是 Flyway 扫描路径,
-- 任何 V*.sql 都会在应用下次启动时自动执行;把回滚编成版本化迁移等于让"决定回滚"这件事
-- 在没有人工执行的情况下自己发生。)
--
-- 顺序:停两台应用 → 执行本脚本 → DELETE FROM flyway_schema_history WHERE version='151'
-- → 回滚 jar(回到仍按公司筛的那版)→ 起应用。
-- 漏掉"删历史行"那步,将来重装带 V151 的 jar 时 Flyway 判定"已应用"直接跳过,两把公司键不再重建,
-- 而回滚后的 jar 的读侧谓词是 company_id = X ⇒ 表现为"读得到但写同名值被 IGNORE 掉",不报错。
--
-- 回滚方向 = 把两把公司键加回来。加回来之前必须先回滚 jar:
-- "键按公司、代码不分公司"时,第 2 家能建出与第 1 家同 (company_id 档, 值) 的行——
-- 而 V151 之后的 jar 根本不写 company_id,两张表的这一列全由 DEFAULT 1 兜 ⇒ 加回公司键
-- 在数据上是安全的(见第 0 段预检),但只有配回滚后的 jar 才有意义。
--
-- ⚠ 本脚本【不】恢复 company_id 列本身:V151 没有删列(列在 V151 之后仍然带着 DEFAULT 1),
-- 所以回滚也不涉及建列。DROP COLUMN 是下一版的事,那一版的回滚要把列与默认值一起加回来,
-- 并且必须先确认两张表的历史归属还能不能分清——品牌库能(uploader_user_id 还在),
-- 类目表不能(这张表没有任何账号列,V147 §2 已写明事后无法反推)。
-- ---------- 0. 预检(必须先跑,返回 0 行才允许第 1、2 段) ----------
-- SELECT data_value, LEFT(brand, 191) b, COUNT(*) c
-- FROM `biz_invalid_asin_data`
-- GROUP BY data_value, b
-- HAVING COUNT(*) > 1;
-- -> 期望 0 行。V151 之后全局键在守,所以这一条应当恒为 0;非 0 说明有人在 V151 与本次回滚
-- 之间手工绕过迁移改过索引,先查 flyway_schema_history 再决定。
-- SELECT company_id, COUNT(*) c FROM `biz_invalid_asin_data` GROUP BY company_id;
-- -> 期望只有一档且值为 1(新 jar 的 INSERT 不带这一列,由 DEFAULT 1 兜)。
-- 出现第二档说明有写入显式带过公司值,加回公司键后这些行会从别家的视图里隐身。
-- SELECT category_key, COUNT(*) c FROM `biz_product_category` GROUP BY category_key HAVING c > 1;
-- -> 期望 0 行(同上,V151 之后由全局键保证)。
-- SELECT SUM(is_builtin = 1 AND company_id <> 0) AS bad_builtin FROM `biz_product_category`;
-- -> 期望 0。V148 从未上线,内置节点仍挂哨兵 0;非 0 说明有人跑过 V148 的人工版本,
-- 回滚后这些内置节点在旧 jar 的 company_id IN (0, X) 谓词下会同时出现在每一家的树上。
-- ---------- 1. 品牌数据库:先加公司键、后删全局键(中间任一步至少有一个唯一键在守并发) ----------
ALTER TABLE `biz_invalid_asin_data`
ADD UNIQUE KEY `uk_company_value_brand` (`company_id`, `data_value`, `brand`(191)),
ALGORITHM = INPLACE, LOCK = NONE;
ALTER TABLE `biz_invalid_asin_data`
DROP INDEX `uk_data_value_brand`,
ALGORITHM = INPLACE, LOCK = NONE;
-- ---------- 2. 商品类目:同一形状 ----------
ALTER TABLE `biz_product_category`
ADD UNIQUE KEY `uk_company_category_key` (`company_id`, `category_key`),
ALGORITHM = INPLACE, LOCK = NONE;
ALTER TABLE `biz_product_category`
DROP INDEX `uk_product_category_key`,
ALGORITHM = INPLACE, LOCK = NONE;
-- ---------- 3. biz_dedupe_total_data 不在本脚本范围内 ----------
-- V151 没有动去重库(它的 uk_company_data_value 一直都在),回滚自然也不动它。
-- ---------- 4. 验证 ----------
-- SELECT TABLE_NAME, INDEX_NAME,
-- GROUP_CONCAT(CONCAT(COLUMN_NAME,'@',SEQ_IN_INDEX) ORDER BY SEQ_IN_INDEX) AS cols
-- FROM information_schema.STATISTICS
-- WHERE TABLE_SCHEMA = DATABASE()
-- AND TABLE_NAME IN ('biz_invalid_asin_data','biz_product_category','biz_dedupe_total_data')
-- AND NON_UNIQUE = 0
-- GROUP BY TABLE_NAME, INDEX_NAME;
-- -> 期望回到 V145+V147 之后的形状:
-- uk_company_value_brand(company_id@1,data_value@2,brand@3)
-- uk_company_category_key(company_id@1,category_key@2)
-- uk_company_data_value(company_id@1,data_value@2)
-- 加三行 PRIMARY(id);uk_data_value_brand / uk_product_category_key 必须【不】在结果里。
@@ -41,37 +41,21 @@ public class DataReadScope {
} }
/** /**
* 归属已经**物化成 company_id 列**的表(品牌库 biz_invalid_asin_data)用的谓词出口: * 归属物化成 {@code company_id} 列、<b>且可见集不靠账号/分组</b>的表用的谓词出口。
* 返回要筛的公司 id,null = 不筛。
* *
* <p>这些表不能走 {@link #readScope} 的账号集合:2026-10-05 生产只读取证,品牌库 14,801 行里 * <p>今天的消费者是「店铺密钥」{@code biz_shop_key}(V150 起每公司一套)。
* {@code uploader_user_id} 非空的有 <b>0</b> 行(实体没这字段、批量 INSERT 的列清单也没带, * <b>品牌库与商品类目不走这里</b>:控制方 2026-10-06 点名这两页"做成所有公司共享的,不区分",
* V145 补的列一直是空的),按账号筛等于把全部历史从每一个公司 tab 里静默删掉。 * 它们的 {@code company_id} 列只剩 V145/V147 留下的历史值,读写两侧都不引用
* 而 {@code company_id} 那一列虽然是被 DEFAULT 1 盖上去的,对历史却是诚实的: * (唯一键退回全局见 {@code V151__rule_tables_shared_across_companies.sql})。
* 第 2 家公司 10-04 14:55 才开通,它名下账号历史任务 0 条、去重库上传 0 行, * 谁要给它们再接一个公司开关,得先推翻那一条定案。</p>
* 所以「建号之前存在的行都归第 1 家」是可证的事实,不是猜。</p>
* *
* <p>非超管返回 null(不筛):他们的可见集本来就锁在自己的分组上,叠一层公司会把 * <p>"不靠账号/分组"是这一道门存在的理由:可见集若无账号/分组谓词兜住,返回 null 等于
* 「靠分组可见」的行整批删掉(同 {@code ShopManageController} 的口径)。 * 把整张表交给每一家(2026-10-06 逐节点复验实测:公司 2 的 admin 读该页得 412 行,
* 超管的 company_id 是视图开关不是安全边界(spec §4),所以这里不需要再校验它属于谁。</p> * 其中 394 行是公司 1 的资产)。若某页的可见集本来就锁在自己的分组/账号上,走
*/ * {@link #readScope} 即可,非超管在这里再叠一层公司会把那些行整批删掉。</p>
public Long readCompanyId(AdminUserEntity operator, Long requestedCompanyId) {
if (!SUPER_ADMIN.equals(adminAuthSupport.currentRole(operator))) {
return null;
}
return requestedCompanyId != null && requestedCompanyId > 0 ? requestedCompanyId : null;
}
/**
* 第三道门:归属物化成 {@code company_id} 列、<b>且可见集不靠账号/分组</b>的表(商品类目)。
* *
* <p>与 {@link #readCompanyId} 只差非超管那一支。差别不是省事,是那张表没有可以保护的东西: * <p>非超管<b>钉在本公司</b>而不是"带别家就返回空":返回空是一个<b>可用视图</b>而不是错误,
* 品牌库的"非超管不筛"靠的是账号/分组谓词兜住可见集,而 {@code biz_product_category} * 而 {@code create} 的 {@code parentId = null} / 空清单让那一家能从零自建。
* 连账号列都没有(V147 才加的 {@code company_id})。返回 null 在这里等于把整棵树交给每一家——
* 2026-10-06 逐节点复验实测:公司 2 的 admin 读该页得 412 行,其中 394 行是公司 1 的自建类目。</p>
*
* <p>非超管<b>钉在本公司</b>而不是"带别家就返回空":类目树里没有"空树"这个可用视图——
* 内置节点(哨兵 0)在任何公司视图里都必须在,否则那一家装不上任何自建子级。
* 请求里带什么都不算,与 {@code readScope} 非超管分支同一口径(tab 不是安全边界)。</p> * 请求里带什么都不算,与 {@code readScope} 非超管分支同一口径(tab 不是安全边界)。</p>
*/ */
public Long readCompanyIdOrOwn(AdminUserEntity operator, Long requestedCompanyId) { public Long readCompanyIdOrOwn(AdminUserEntity operator, Long requestedCompanyId) {
@@ -85,8 +69,11 @@ public class DataReadScope {
* 写侧的行级归属闸门要的值:{@code null} = 平台超管不限,其余账号一律是自己那一家。 * 写侧的行级归属闸门要的值:{@code null} = 平台超管不限,其余账号一律是自己那一家。
* *
* <p>读侧收窄而写侧不收窄,等于"藏起来的行仍然能删"——那是静默删除,不是隔离。 * <p>读侧收窄而写侧不收窄,等于"藏起来的行仍然能删"——那是静默删除,不是隔离。
* 返回值直接交给 service 与<b>行自己的</b> {@code company_id} 比(不是与 tab 比: * 返回值直接交给 service 与<b>行自己的</b> {@code company_id} 比(不是与 tab 比)。
* 内置行归哨兵 0,任何公司账号都不该改得动它)。</p> * 今天的消费者与 {@link #readCompanyIdOrOwn} 同一批(店铺密钥)。
* <b>商品类目已经不走这里</b>:那页的 {@code assertRowWritable}(含按 {@code is_builtin}
* 拦内置节点的那一刀)随 2026-10-06「类目全平台共享、谁都能改整棵树」的定案一起删掉了,
* 内置节点现在对任何管理员可改可删——这是控制方点名的口径,不是漏改。</p>
*/ */
public Long writeCompanyId(AdminUserEntity operator) { public Long writeCompanyId(AdminUserEntity operator) {
return SUPER_ADMIN.equals(adminAuthSupport.currentRole(operator)) return SUPER_ADMIN.equals(adminAuthSupport.currentRole(operator))
@@ -7,6 +7,7 @@ import com.nanri.aiimage.config.AppearancePatentProperties;
import com.nanri.aiimage.config.HttpClientPool; import com.nanri.aiimage.config.HttpClientPool;
import com.nanri.aiimage.metrics.ExternalCallMetricsRecorder; import com.nanri.aiimage.metrics.ExternalCallMetricsRecorder;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResultRowDto; import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentResultRowDto;
import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePatentSheetBuilder;
import com.nanri.aiimage.modules.brand.client.BrandCheckClient; import com.nanri.aiimage.modules.brand.client.BrandCheckClient;
import com.nanri.aiimage.modules.usersecret.service.UserSecretUsageService; import com.nanri.aiimage.modules.usersecret.service.UserSecretUsageService;
import com.nanri.aiimage.modules.usersecret.support.SecretUsageContext; import com.nanri.aiimage.modules.usersecret.support.SecretUsageContext;
@@ -1064,7 +1065,11 @@ public class AppearancePatentLlmClient {
return NO_INFRINGEMENT; return NO_INFRINGEMENT;
} }
if (isBrandQueryFailed(titleRisk)) { if (isBrandQueryFailed(titleRisk)) {
return BRAND_QUERY_FAILED; // 外观已经判出「无侵权」时别把它整格盖掉:这一行缺的只是商标那一维,
// 结论要说「外观无侵权·商标待复核」,用户才不会把已判出的外观结论读成"整单没检测"。
return isNoInfringement(appearanceRisk)
? "外观" + normalize(appearanceRisk) + AppearancePatentSheetBuilder.PENDING_REVIEW_SUFFIX
: BRAND_QUERY_FAILED;
} }
return firstNonBlank(fallbackConclusion, ""); return firstNonBlank(fallbackConclusion, "");
} }
@@ -51,6 +51,13 @@ public final class AppearancePatentSheetBuilder {
*/ */
public static final String NO_RESULT_TEXT = "未取得检测结果"; public static final String NO_RESULT_TEXT = "未取得检测结果";
/**
* 结论列上「外观已判定、商标那一维没核上」的标记。
* <p>放在这里而不是客户端里:结论是这里写的、状态列也是这里判的,
* 两处共用一个字面量才不会各写各的(历史上「结论写着查询失败、状态写着成功」就是这么来的)。
*/
public static final String PENDING_REVIEW_SUFFIX = "·商标待复核";
private static final String NO_RESULT_REASON = NO_RESULT_TEXT + ":该行没有返回判定,重新运行任务可补检"; private static final String NO_RESULT_REASON = NO_RESULT_TEXT + ":该行没有返回判定,重新运行任务可补检";
public static void buildResultSheet(Workbook workbook, List<AppearancePatentParsedRowVo> rows, public static void buildResultSheet(Workbook workbook, List<AppearancePatentParsedRowVo> rows,
@@ -261,12 +268,17 @@ public final class AppearancePatentSheetBuilder {
* 两者都含「侵权」二字;而「商标查询失败」(品牌检测上游查询失败)、「外观识别异常」、 * 两者都含「侵权」二字;而「商标查询失败」(品牌检测上游查询失败)、「外观识别异常」、
* LLM 技术性失败、空白都表示这一行没得出完整结论,一律判「失败」。 * LLM 技术性失败、空白都表示这一行没得出完整结论,一律判「失败」。
* 历史缺陷:曾按「结论非空即成功」,于是结论列写着"商标查询失败"、状态列却写"成功"。 * 历史缺陷:曾按「结论非空即成功」,于是结论列写着"商标查询失败"、状态列却写"成功"。
* 带 {@link #PENDING_REVIEW_SUFFIX} 的结论含「侵权」二字,必须排在字面判定之前判掉,
* 否则「外观无侵权·商标待复核」会被读成成功。
*/ */
public static String resolveResultStatus(String conclusion) { public static String resolveResultStatus(String conclusion) {
String normalized = conclusion == null ? "" : conclusion.trim(); String normalized = conclusion == null ? "" : conclusion.trim();
if (normalized.isBlank() || isTechnicalLlmFailure(normalized)) { if (normalized.isBlank() || isTechnicalLlmFailure(normalized)) {
return "失败"; return "失败";
} }
if (normalized.contains(PENDING_REVIEW_SUFFIX)) {
return "失败";
}
return normalized.contains("侵权") ? "成功" : "失败"; return normalized.contains("侵权") ? "成功" : "失败";
} }
@@ -1,6 +1,5 @@
package com.nanri.aiimage.modules.collectdata.util; package com.nanri.aiimage.modules.collectdata.util;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.modules.collectdata.model.vo.CollectDataResultRowVo; import com.nanri.aiimage.modules.collectdata.model.vo.CollectDataResultRowVo;
import com.nanri.aiimage.modules.invalidasin.mapper.InvalidAsinDataMapper; import com.nanri.aiimage.modules.invalidasin.mapper.InvalidAsinDataMapper;
import com.nanri.aiimage.modules.invalidasin.model.entity.InvalidAsinDataEntity; import com.nanri.aiimage.modules.invalidasin.model.entity.InvalidAsinDataEntity;
@@ -16,52 +15,39 @@ import java.util.regex.Pattern;
/** /**
* invalid ASIN 批量写入器:把不合规 ASIN 行按批次批量 INSERT IGNORE 写入 * invalid ASIN 批量写入器:把不合规 ASIN 行按批次批量 INSERT IGNORE 写入
* biz_invalid_asin_data,替代逐行 insert + 捕获唯一键异常的旧路径。 * biz_invalid_asin_data,替代逐行 insert + 捕获唯一键异常的旧路径。
* 幂等由唯一键 (company_id, data_value, brand) + INSERT IGNORE 语义保证;批量失败时 * 幂等由唯一键 (data_value, brand) + INSERT IGNORE 语义保证;批量失败时
* 跳过该批(记录计数,不中断提交流程),恢复后继续后续批次。 * 跳过该批(记录计数,不中断提交流程),恢复后继续后续批次。
* 空输入、无合法 data_value/brand 的行、null 行均安全跳过,不发起调用。 * 空输入、无合法 data_value/brand 的行、null 行均安全跳过,不发起调用。
* *
* <p>归属(company_id + uploader_user_id)由调用方给任务发起账号,本类负责推公司: * <p>这一张黑名单是<b>全平台共享的,不按公司区分</b>(控制方 2026-10-06 定案)。
* 此前实体与 INSERT 列清单都不带这两列,V145 补的 company_id 全靠 DEFAULT 1 盖, * {@code uploader_user_id} 只记"哪个账号采出来的",推不出账号也照写:
* 于是第 2 家公司跑货源产生的行会被记成第 1 家,且事后分不开。</p> * 少一条黑名单 = 下次同样的品牌再买一次代理,而归属记不上不影响任何人看数据。</p>
*/ */
@Slf4j @Slf4j
@Component @Component
public class CollectDataInvalidAsinBatchWriter { public class CollectDataInvalidAsinBatchWriter {
/** 巡检可 grep 的标记:账号已不存在、推不出公司,这批 rejected 品牌整批不写。 */
static final String OWNER_UNRESOLVED_MARKER = "INVALID_ASIN_OWNER_UNRESOLVED";
private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+"); private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+");
private final InvalidAsinDataMapper invalidAsinDataMapper; private final InvalidAsinDataMapper invalidAsinDataMapper;
private final CompanyScopeSupport companyScopeSupport;
private final int batchSize; private final int batchSize;
public CollectDataInvalidAsinBatchWriter(InvalidAsinDataMapper invalidAsinDataMapper, public CollectDataInvalidAsinBatchWriter(InvalidAsinDataMapper invalidAsinDataMapper,
CompanyScopeSupport companyScopeSupport,
@Value("${aiimage.collect-data.invalid-asin-batch-size:100}") int batchSize) { @Value("${aiimage.collect-data.invalid-asin-batch-size:100}") int batchSize) {
this.invalidAsinDataMapper = invalidAsinDataMapper; this.invalidAsinDataMapper = invalidAsinDataMapper;
this.companyScopeSupport = companyScopeSupport;
this.batchSize = Math.max(1, batchSize); this.batchSize = Math.max(1, batchSize);
} }
/** /**
* 批量写入并返回实际尝试写入的行数(INSERT IGNORE 忽略重复,幂等)。 * 批量写入并返回实际尝试写入的行数(INSERT IGNORE 忽略重复,幂等)。
* *
* @param uploaderUserId 任务发起账号(biz_file_task.user_id);推不出公司时整批不写并打 * @param uploaderUserId 任务发起账号(biz_file_task.user_id);可为 null(账号已删),
* {@link #OWNER_UNRESOLVED_MARKER}——宁可少记一条黑名单, * 只影响这一列记不记得上,不影响写不写得进
* 也不把行盖成别家公司(那会让另一家的正常品牌被静默过滤)
*/ */
public int writeBatch(List<CollectDataResultRowVo> rows, Long uploaderUserId) { public int writeBatch(List<CollectDataResultRowVo> rows, Long uploaderUserId) {
if (rows == null || rows.isEmpty()) { if (rows == null || rows.isEmpty()) {
return 0; return 0;
} }
Long companyId = companyScopeSupport.companyIdOrNull(uploaderUserId);
if (companyId == null) {
log.warn("{} 无法按账号推出处置公司,本批不写入无效品牌表 rows={} userId={}",
OWNER_UNRESOLVED_MARKER, rows.size(), uploaderUserId);
return 0;
}
int written = 0; int written = 0;
for (int start = 0; start < rows.size(); start += batchSize) { for (int start = 0; start < rows.size(); start += batchSize) {
int end = Math.min(start + batchSize, rows.size()); int end = Math.min(start + batchSize, rows.size());
@@ -70,7 +56,6 @@ public class CollectDataInvalidAsinBatchWriter {
for (CollectDataResultRowVo row : batch) { for (CollectDataResultRowVo row : batch) {
InvalidAsinDataEntity entity = toEntity(row); InvalidAsinDataEntity entity = toEntity(row);
if (entity != null) { if (entity != null) {
entity.setCompanyId(companyId);
entity.setUploaderUserId(uploaderUserId); entity.setUploaderUserId(uploaderUserId);
entities.add(entity); entities.add(entity);
} }
@@ -24,6 +24,10 @@ import java.util.Map;
* 所以这里探的是【清单】而不是单个列名。清单与探针 SQL 的 IN 列表由 {@code CompanyDefaultGuardTest} * 所以这里探的是【清单】而不是单个列名。清单与探针 SQL 的 IN 列表由 {@code CompanyDefaultGuardTest}
* 双向钉同源:只钉"清单里的都在 SQL 里"会漏掉"SQL 里有、清单漏了"那一半,而那一半才是静默的形状。</p> * 双向钉同源:只钉"清单里的都在 SQL 里"会漏掉"SQL 里有、清单漏了"那一半,而那一半才是静默的形状。</p>
* *
* <p>清单也会随口径<b>缩短</b>:{@code biz_invalid_asin_data} 与 {@code biz_product_category}
* 已按 2026-10-06「这两页全平台共享」的定案一起摘掉,理由见 {@link #WATCHED_TABLES}——
* 对一张不再分公司写行的表喊"去摘 DEFAULT",会把一个无人报错的遗留列变成一次真故障(1364)。</p>
*
* <p>标记串({@link #ALARM} / {@link #PROBE_FAILED})是纯 ASCII:巡检脚本要在 docker logs 里 * <p>标记串({@link #ALARM} / {@link #PROBE_FAILED})是纯 ASCII:巡检脚本要在 docker logs 里
* grep 它,中文一旦在容器里变了编码就整条签名失效。</p> * grep 它,中文一旦在容器里变了编码就整条签名失效。</p>
*/ */
@@ -41,17 +45,31 @@ public class CompanyDefaultGuard {
/** /**
* 该带 company_id 且历史上可能被塞过 DEFAULT 的表。新增一列就要在这里登记一条—— * 该带 company_id 且历史上可能被塞过 DEFAULT 的表。新增一列就要在这里登记一条——
* 漏登记的后果不是报错,是哨兵对着一个不存在的列一声不响({@link #check} 会把它当探不到处理)。 * 漏登记的后果不是报错,是哨兵对着一个不存在的列一声不响({@link #check} 会把它当探不到处理)。
* V147 的 {@code biz_product_category} 是第四条:它的 DEFAULT 1 同样只为同批旧 jar 存在, *
* 摘除动作与上面三张同形(一条元数据操作,禁 MODIFY)。 * <p><b>登记表里只能放"仍然按公司写"的表</b>,这一条比上一句更容易踩。
* {@code biz_invalid_asin_data}(V145)与 {@code biz_product_category}(V147)已经在
* 2026-10-06「品牌数据库/商品类目做成所有公司共享」的定案里一并摘掉:它们的 {@code company_id}
* 现在没有任何读写路径引用,靠 {@code DEFAULT 1} 满足 {@code NOT NULL}。此时喊
* {@code COMPANY_DEFAULT_STILL_PRESENT} 并让人去执行本类给出的 {@code DROP DEFAULT},
* 后果不是"修好了"而是每一次写入报 1364——品牌库那条还会被
* {@code CollectDataInvalidAsinBatchWriter} 吞成 warn ⇒ 接口成功而黑名单静默少一批。
* 这两列的 DEFAULT 由下一版的 {@code DROP COLUMN} 一并带走(见 docs/migration-inventory.md)。</p>
*
* <p>V147 的 {@code biz_product_category} 曾是第三条、V150 的 {@code biz_shop_key} 是第五条:
* 加它们时用的是同一条理由,摘它们时也必须是同一条理由——"这张表还分公司吗"是唯一判据。</p>
*
* <p>V149 的 {@code columns} 方向相反,是【加进来】的一条:菜单树如今真的按公司写(每家公司一套),
* 它的 {@code DEFAULT 1} 只为同批的旧 jar 存在(旧实体没有 companyId,insert 整列跳过会报 1364)。
* 新 jar 的每个建/改菜单出口都显式落公司,此后留着默认值的后果是"忘了传公司的行静默归第 1 家",
* 与上面那两条"没人读的列"不同 —— 判据仍是同一句:这张表还分公司吗。</p>
*/ */
static final List<String> WATCHED_TABLES = List.of( static final List<String> WATCHED_TABLES = List.of(
"users", "biz_invalid_asin_data", "biz_dedupe_total_data", "biz_product_category"); "users", "biz_dedupe_total_data", "biz_shop_key", "columns");
private static final String COLUMN_DEFAULT_SQL = """ private static final String COLUMN_DEFAULT_SQL = """
SELECT TABLE_NAME, COLUMN_DEFAULT FROM information_schema.COLUMNS SELECT TABLE_NAME, COLUMN_DEFAULT FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE() AND COLUMN_NAME = 'company_id' WHERE TABLE_SCHEMA = DATABASE() AND COLUMN_NAME = 'company_id'
AND TABLE_NAME IN ('users', 'biz_invalid_asin_data', 'biz_dedupe_total_data', AND TABLE_NAME IN ('users', 'biz_dedupe_total_data', 'biz_shop_key', 'columns')
'biz_product_category')
"""; """;
private final CompanyMapper companyMapper; private final CompanyMapper companyMapper;
@@ -7,8 +7,10 @@ import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.company.mapper.CompanyMapper; import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
import com.nanri.aiimage.modules.company.model.dto.CompanySaveRequest; import com.nanri.aiimage.modules.company.model.dto.CompanySaveRequest;
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity; import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@@ -31,6 +33,7 @@ public class CompanyService {
private final CompanyMapper companyMapper; private final CompanyMapper companyMapper;
private final AdminAuthSupport adminAuthSupport; private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService;
/** 建号指定的公司必须真实存在且启用:否则账号挂在查不到的公司上,按公司筛选时整体失明。 */ /** 建号指定的公司必须真实存在且启用:否则账号挂在查不到的公司上,按公司筛选时整体失明。 */
public CompanyEntity requireActive(Long companyId) { public CompanyEntity requireActive(Long companyId) {
@@ -104,7 +107,14 @@ public class CompanyService {
return company.getCompanyName(); return company.getCompanyName();
} }
/** 新增公司:只有超管能建,一期也只有超管需要建(开通第二家公司是人工动作)。 */ /**
* 新增公司:只有超管能建,一期也只有超管需要建(开通第二家公司是人工动作)。
*
* <p>事务包住两件事:插公司行 + 给它复制一套菜单树。每家公司一棵树之后,零菜单行的租户
* 表现是"那家账号侧边栏全空"且不报错,所以建树不能留成上线后的人工动作;
* 复制失败必须连公司行一起回滚,不留半成品。</p>
*/
@Transactional
public CompanyEntity create(AdminUserEntity operator, CompanySaveRequest request) { public CompanyEntity create(AdminUserEntity operator, CompanySaveRequest request) {
ensureSuperAdmin(operator); ensureSuperAdmin(operator);
String companyName = requireValidName(request.getCompanyName()); String companyName = requireValidName(request.getCompanyName());
@@ -117,6 +127,7 @@ public class CompanyService {
entity.setStatus(status); entity.setStatus(status);
entity.setRemark(remark); entity.setRemark(remark);
companyMapper.insert(entity); companyMapper.insert(entity);
permissionMenuService.copyTreeFromTemplate(entity.getId(), operator.getCompanyId());
return entity; return entity;
} }
@@ -3,7 +3,6 @@ package com.nanri.aiimage.modules.invalidasin.controller;
import com.nanri.aiimage.common.api.ApiResponse; import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.exception.BusinessException; import com.nanri.aiimage.common.exception.BusinessException;
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.invalidasin.model.dto.InvalidAsinDataCreateRequest; import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataCreateRequest;
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataUpdateRequest; import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataUpdateRequest;
import com.nanri.aiimage.modules.invalidasin.model.vo.InvalidAsinDataItemVo; import com.nanri.aiimage.modules.invalidasin.model.vo.InvalidAsinDataItemVo;
@@ -39,7 +38,7 @@ import java.security.MessageDigest;
@RestController @RestController
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/api/admin/invalid-asin-data") @RequestMapping("/api/admin/invalid-asin-data")
@Tag(name = "不符合ASIN数据", description = "维护不符合ASIN数据列表,支持增删改查。") @Tag(name = "品牌数据库", description = "维护品牌数据库(不符合规则的 ASIN / 品牌)列表,支持增删改查。全平台共享,不按公司区分。")
public class InvalidAsinDataController { public class InvalidAsinDataController {
private static final String INVALID_ASIN_DATA_COLUMN_KEY = "admin_invalid_asin_data"; private static final String INVALID_ASIN_DATA_COLUMN_KEY = "admin_invalid_asin_data";
@@ -50,10 +49,9 @@ public class InvalidAsinDataController {
private final InvalidAsinDataService invalidAsinDataService; private final InvalidAsinDataService invalidAsinDataService;
private final AdminAuthSupport adminAuthSupport; private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService; private final PermissionMenuService permissionMenuService;
private final DataReadScope dataReadScope;
@GetMapping @GetMapping
@Operation(summary = "分页查询不符合ASIN数据", description = "分页查询不符合ASIN数据,支持按 ASIN/品牌 模糊搜索。") @Operation(summary = "分页查询品牌数据库", description = "分页查询品牌数据库(全平台共享,不按公司区分),支持按 ASIN/品牌 模糊搜索。")
@ApiResponses({ @ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = InvalidAsinDataPageVo.class))) @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = InvalidAsinDataPageVo.class)))
}) })
@@ -64,18 +62,14 @@ public class InvalidAsinDataController {
@Parameter(description = "ASIN 模糊搜索") @RequestParam(name = "data_value", required = false) String dataValue, @Parameter(description = "ASIN 模糊搜索") @RequestParam(name = "data_value", required = false) String dataValue,
@Parameter(description = "品牌模糊搜索") @RequestParam(name = "brand", required = false) String brand, @Parameter(description = "品牌模糊搜索") @RequestParam(name = "brand", required = false) String brand,
@Parameter(description = "分组 ID") @RequestParam(name = "group_id", required = false) Long groupId, @Parameter(description = "分组 ID") @RequestParam(name = "group_id", required = false) Long groupId,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
HttpServletRequest request) { HttpServletRequest request) {
RequestOperator operator = requireInvalidAsinDataAccess(request); RequestOperator operator = requireInvalidAsinDataAccess(request);
AdminUserEntity user = operator.user();
Long scopedCompanyId = dataReadScope.readCompanyId(user, companyId);
return ApiResponse.success(invalidAsinDataService.page( return ApiResponse.success(invalidAsinDataService.page(
page, pageSize, keyword, dataValue, brand, groupId, operator.id(), operator.superAdmin(), page, pageSize, keyword, dataValue, brand, groupId, operator.id(), operator.superAdmin()));
scopedCompanyId));
} }
@PostMapping @PostMapping
@Operation(summary = "新增不符合ASIN数据", description = "新增一条不符合ASIN数据。") @Operation(summary = "新增品牌数据库记录", description = "新增一条品牌数据库记录(全平台共享)。")
@ApiResponses({ @ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功", content = @Content(schema = @Schema(implementation = InvalidAsinDataItemVo.class))), @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功", content = @Content(schema = @Schema(implementation = InvalidAsinDataItemVo.class))),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不合法或数据重复") @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不合法或数据重复")
@@ -89,7 +83,7 @@ public class InvalidAsinDataController {
} }
@PutMapping("/{id}") @PutMapping("/{id}")
@Operation(summary = "更新不符合ASIN数据", description = "按 ID 更新一条不符合ASIN数据。") @Operation(summary = "更新品牌数据库记录", description = "按 ID 更新一条品牌数据库记录。")
@ApiResponses({ @ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = InvalidAsinDataItemVo.class))), @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = InvalidAsinDataItemVo.class))),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不合法或数据重复"), @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不合法或数据重复"),
@@ -105,7 +99,7 @@ public class InvalidAsinDataController {
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
@Operation(summary = "删除不符合ASIN数据", description = "按 ID 删除一条不符合ASIN数据。") @Operation(summary = "删除品牌数据库记录", description = "按 ID 删除一条品牌数据库记录。")
@ApiResponses({ @ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "删除成功"), @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "删除成功"),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "数据不存在") @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "数据不存在")
@@ -127,7 +121,7 @@ public class InvalidAsinDataController {
if (!superAdmin && !hasInvalidAsinDataPermission(operator)) { if (!superAdmin && !hasInvalidAsinDataPermission(operator)) {
throw new BusinessException(403, "无权访问品牌数据库"); throw new BusinessException(403, "无权访问品牌数据库");
} }
return new RequestOperator(operator.getId(), superAdmin, operator); return new RequestOperator(operator.getId(), superAdmin);
} }
private AdminUserEntity resolveOperator(HttpServletRequest request) { private AdminUserEntity resolveOperator(HttpServletRequest request) {
@@ -170,7 +164,7 @@ public class InvalidAsinDataController {
private record RequestOperator(Long id, boolean superAdmin, AdminUserEntity user) { private record RequestOperator(Long id, boolean superAdmin) {
} }
private boolean isTrustedInternalRequest(String suppliedToken) { private boolean isTrustedInternalRequest(String suppliedToken) {
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken); return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
@@ -12,22 +12,26 @@ import java.util.List;
public interface InvalidAsinDataMapper extends BaseMapper<InvalidAsinDataEntity> { public interface InvalidAsinDataMapper extends BaseMapper<InvalidAsinDataEntity> {
/** /**
* 批量 INSERT IGNORE:命中唯一键 (company_id, data_value, brand) 的重复行静默跳过,幂等。 * 批量 INSERT IGNORE:命中唯一键 (data_value, brand) 的重复行静默跳过,幂等。
* created_at/updated_at 不显式写入:依赖列的 DEFAULT CURRENT_TIMESTAMP。 * created_at/updated_at 不显式写入:依赖列的 DEFAULT CURRENT_TIMESTAMP。
* 显式传 null 会绕过默认值,在宽松 SQL 模式下落为 '0000-00-00 00:00:00', * 显式传 null 会绕过默认值,在宽松 SQL 模式下落为 '0000-00-00 00:00:00',
* 随后在 NO_ZERO_DATE 模式(生产已启用)下读取即报 Zero date value prohibited。 * 随后在 NO_ZERO_DATE 模式(生产已启用)下读取即报 Zero date value prohibited。
* *
* <p>company_id 与 uploader_user_id 由调用方填好:company_id 是 NOT NULL, * <p>列清单里<b>没有</b> company_id:品牌数据库全平台共享,归属不参与幂等(控制方 2026-10-06 定案)。
* 这一列显式传 null 不会走 DEFAULT 1,而是直接报错(上面 created_at 那段说的正是这类列的 * 库里那一列带 {@code DEFAULT 1} 且仍 NOT NULL,所以省略它安全;反过来<b>显式传 null 会直接报错</b>
* "宽松模式才静默"),所以归属推不出来时调用方必须整批不写,而不是塞 null 进来。</p> * (上面 created_at 那段说的正是这类列的"宽松模式才静默")。</p>
*
* <p>uploader_user_id 可空,jdbcType 必须写:任务账号已被删时这一列就是 null,
* 不告诉 MyBatis 类型它会抛 "Error setting null parameter",而调用方把异常吞成 log.warn,
* 于是整批黑名单静默丢掉。</p>
*/ */
@Insert(""" @Insert("""
<script> <script>
INSERT IGNORE INTO biz_invalid_asin_data INSERT IGNORE INTO biz_invalid_asin_data
(data_value, brand, record_source, company_id, uploader_user_id) (data_value, brand, record_source, uploader_user_id)
VALUES VALUES
<foreach collection="rows" item="row" separator=","> <foreach collection="rows" item="row" separator=",">
(#{row.dataValue}, #{row.brand}, #{row.recordSource}, #{row.companyId}, #{row.uploaderUserId}) (#{row.dataValue}, #{row.brand}, #{row.recordSource}, #{row.uploaderUserId,jdbcType=BIGINT})
</foreach> </foreach>
</script> </script>
""") """)
@@ -7,7 +7,7 @@ import jakarta.validation.constraints.Size;
import lombok.Data; import lombok.Data;
@Data @Data
@Schema(description = "不符合ASIN数据新增请求") @Schema(description = "品牌数据库新增请求")
public class InvalidAsinDataCreateRequest { public class InvalidAsinDataCreateRequest {
@NotBlank(message = "ASIN 不能为空") @NotBlank(message = "ASIN 不能为空")
@@ -6,7 +6,7 @@ import jakarta.validation.constraints.Size;
import lombok.Data; import lombok.Data;
@Data @Data
@Schema(description = "不符合ASIN数据更新请求") @Schema(description = "品牌数据库更新请求")
public class InvalidAsinDataUpdateRequest { public class InvalidAsinDataUpdateRequest {
@NotBlank(message = "ASIN 不能为空") @NotBlank(message = "ASIN 不能为空")
@@ -9,6 +9,16 @@ import lombok.Data;
import java.time.LocalDateTime; import java.time.LocalDateTime;
/**
* 品牌数据库(不符合 ASIN / 品牌黑名单)——<b>全平台共享,不按公司区分</b>(控制方 2026-10-06 定案)。
*
* <p>所以这里<b>不声明</b> {@code company_id} 字段。库里那一列(V145 加的,带 {@code DEFAULT 1})
* 暂时还在,但没有任何读写路径引用它:不声明字段 ⇒ SELECT 列清单与 INSERT 都不含它 ⇒ 新 jar 配旧库
* (列还在)不会报错。摘列必须等两台都跑上这一版,否则旧 jar 带着这一列来 INSERT/SELECT 会撞
* {@code Unknown column},而批量写入器把异常吞成 log.warn——那是静默丢黑名单行。
* 唯一键退回全局见 {@code V151__rule_tables_shared_across_companies.sql};<b>摘列本身不在 V151 里</b>
* (V151 只退键),它是下一版的待办,取号与理由见 {@code docs/migration-inventory.md}。</p>
*/
@Data @Data
@TableName("biz_invalid_asin_data") @TableName("biz_invalid_asin_data")
public class InvalidAsinDataEntity { public class InvalidAsinDataEntity {
@@ -19,11 +29,9 @@ public class InvalidAsinDataEntity {
private String brand; private String brand;
private Long groupId; private Long groupId;
/** /**
* 归属公司(company.id)。列由 V145 物化,但**实体与批量 INSERT 的列清单此前都没带它**, * 归属账号:AUTO 行取 task.user_id、MANUAL 行取操作人;V145 之前的历史行为 NULL(无从追溯)。
* 所以 2026-10-05 生产只读取证 14,801 行全是被 DEFAULT 1 盖出来的。写入侧从本版本起显式盖章。 * 这一列只记"谁加的",不参与任何筛选——品牌数据库全平台共享,见类注释。
*/ */
private Long companyId;
/** 归属账号:AUTO 行取 task.user_id、MANUAL 行取操作人;V145 之前的历史行为 NULL(无从追溯)。 */
private Long uploaderUserId; private Long uploaderUserId;
private String recordSource; private String recordSource;
private LocalDateTime createdAt; private LocalDateTime createdAt;
@@ -6,7 +6,7 @@ import lombok.Data;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@Data @Data
@Schema(description = "不符合ASIN数据项") @Schema(description = "品牌数据库数据项")
public class InvalidAsinDataItemVo { public class InvalidAsinDataItemVo {
@Schema(description = "主键ID") @Schema(description = "主键ID")
@@ -6,7 +6,7 @@ import lombok.Data;
import java.util.List; import java.util.List;
@Data @Data
@Schema(description = "不符合ASIN数据分页结果") @Schema(description = "品牌数据库分页结果")
public class InvalidAsinDataPageVo { public class InvalidAsinDataPageVo {
@Schema(description = "列表") @Schema(description = "列表")
@@ -2,7 +2,6 @@ package com.nanri.aiimage.modules.invalidasin.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException; import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.modules.invalidasin.mapper.InvalidAsinDataMapper; import com.nanri.aiimage.modules.invalidasin.mapper.InvalidAsinDataMapper;
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataCreateRequest; import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataCreateRequest;
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataUpdateRequest; import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataUpdateRequest;
@@ -31,10 +30,9 @@ public class InvalidAsinDataService {
private final InvalidAsinDataMapper invalidAsinDataMapper; private final InvalidAsinDataMapper invalidAsinDataMapper;
private final ShopManageGroupService shopManageGroupService; private final ShopManageGroupService shopManageGroupService;
private final CompanyScopeSupport companyScopeSupport;
public InvalidAsinDataPageVo page(long page, long pageSize, String keyword, String dataValue, String brand, public InvalidAsinDataPageVo page(long page, long pageSize, String keyword, String dataValue, String brand,
Long groupId, Long operatorId, boolean superAdmin, Long companyFilterId) { Long groupId, Long operatorId, boolean superAdmin) {
long safePage = Math.max(page, 1); long safePage = Math.max(page, 1);
long safePageSize = Math.min(Math.max(pageSize, 1), 100); long safePageSize = Math.min(Math.max(pageSize, 1), 100);
String safeKeyword = keyword == null ? "" : keyword.trim(); String safeKeyword = keyword == null ? "" : keyword.trim();
@@ -48,9 +46,6 @@ public class InvalidAsinDataService {
.like(!safeDataValue.isEmpty(), InvalidAsinDataEntity::getDataValue, safeDataValue) .like(!safeDataValue.isEmpty(), InvalidAsinDataEntity::getDataValue, safeDataValue)
.like(!safeBrand.isEmpty(), InvalidAsinDataEntity::getBrand, safeBrand) .like(!safeBrand.isEmpty(), InvalidAsinDataEntity::getBrand, safeBrand)
.orderByDesc(InvalidAsinDataEntity::getId); .orderByDesc(InvalidAsinDataEntity::getId);
if (companyFilterId != null) {
query.eq(InvalidAsinDataEntity::getCompanyId, companyFilterId);
}
if (!superAdmin) { if (!superAdmin) {
Long fixedGroupId = resolveFixedAccessibleGroupId(operatorId); Long fixedGroupId = resolveFixedAccessibleGroupId(operatorId);
if (fixedGroupId == null) { if (fixedGroupId == null) {
@@ -85,16 +80,13 @@ public class InvalidAsinDataService {
@Transactional @Transactional
public InvalidAsinDataItemVo create(InvalidAsinDataCreateRequest request, Long operatorId, boolean superAdmin) { public InvalidAsinDataItemVo create(InvalidAsinDataCreateRequest request, Long operatorId, boolean superAdmin) {
ShopManageGroupEntity group = resolveManualWriteGroup(request.getGroupId(), operatorId, superAdmin); ShopManageGroupEntity group = resolveManualWriteGroup(request.getGroupId(), operatorId, superAdmin);
// 归属从操作者会话推导,不读请求里的公司:超管在哪个 tab 下建都归他自己那家公司(一期定案口径)。
Long companyId = companyScopeSupport.requireCompanyId(operatorId);
String dataValue = normalizeRequired(request.getDataValue(), "ASIN 不能为空"); String dataValue = normalizeRequired(request.getDataValue(), "ASIN 不能为空");
String brand = normalizeRequired(request.getBrand(), "品牌不能为空").toLowerCase(Locale.ROOT); String brand = normalizeRequired(request.getBrand(), "品牌不能为空").toLowerCase(Locale.ROOT);
ensureUnique(dataValue, null, companyId); ensureUnique(dataValue, null);
InvalidAsinDataEntity entity = new InvalidAsinDataEntity(); InvalidAsinDataEntity entity = new InvalidAsinDataEntity();
entity.setDataValue(dataValue); entity.setDataValue(dataValue);
entity.setBrand(brand); entity.setBrand(brand);
entity.setGroupId(group.getId()); entity.setGroupId(group.getId());
entity.setCompanyId(companyId);
entity.setUploaderUserId(operatorId); entity.setUploaderUserId(operatorId);
entity.setRecordSource(RECORD_SOURCE_MANUAL); entity.setRecordSource(RECORD_SOURCE_MANUAL);
invalidAsinDataMapper.insert(entity); invalidAsinDataMapper.insert(entity);
@@ -114,7 +106,7 @@ public class InvalidAsinDataService {
} }
String dataValue = normalizeRequired(request.getDataValue(), "ASIN 不能为空"); String dataValue = normalizeRequired(request.getDataValue(), "ASIN 不能为空");
String brand = normalizeRequired(request.getBrand(), "品牌不能为空").toLowerCase(Locale.ROOT); String brand = normalizeRequired(request.getBrand(), "品牌不能为空").toLowerCase(Locale.ROOT);
ensureUnique(dataValue, id, entity.getCompanyId()); ensureUnique(dataValue, id);
entity.setDataValue(dataValue); entity.setDataValue(dataValue);
entity.setBrand(brand); entity.setBrand(brand);
String groupName = ""; String groupName = "";
@@ -153,12 +145,15 @@ public class InvalidAsinDataService {
} }
/** /**
* 应用层的重复预检必须与 V145 放宽后的唯一键同宽——(company_id, data_value, brand)。 * 全平台一份黑名单:同一条 ASIN 只要已经被任何一家录过,第二家再录就报「ASIN 已存在」。
* 少了公司这一维,第 2 家永远无法新增第 1 家已有的品牌(跨公司误报「ASIN 已存在」)。 *
* <p>预检比 {@code data_value} 一个字段,而库里唯一键是 {@code (data_value, brand)} ——预检更严,
* 这是改造前就有的口径(同一 ASIN 换品牌重录在页面上看不出区别)。V145 一度给这里叠过公司维度,
* 2026-10-06 控制方定案"品牌数据库不区分公司"后摘回全局。<b>不许再把公司加回来</b>:
* 那会让同一条 ASIN 在共享列表里长出两行,而这一页没有任何地方告诉操作员它们分属两家。</p>
*/ */
private void ensureUnique(String dataValue, Long excludeId, Long companyId) { private void ensureUnique(String dataValue, Long excludeId) {
LambdaQueryWrapper<InvalidAsinDataEntity> query = new LambdaQueryWrapper<InvalidAsinDataEntity>() LambdaQueryWrapper<InvalidAsinDataEntity> query = new LambdaQueryWrapper<InvalidAsinDataEntity>()
.eq(companyId != null, InvalidAsinDataEntity::getCompanyId, companyId)
.eq(InvalidAsinDataEntity::getDataValue, dataValue) .eq(InvalidAsinDataEntity::getDataValue, dataValue)
.last("LIMIT 1"); .last("LIMIT 1");
InvalidAsinDataEntity exists = invalidAsinDataMapper.selectOne(query); InvalidAsinDataEntity exists = invalidAsinDataMapper.selectOne(query);
@@ -53,17 +53,29 @@ public class PermissionMenuController {
public ApiResponse<List<PermissionMenuItemVo>> listMenus(HttpServletRequest request, public ApiResponse<List<PermissionMenuItemVo>> listMenus(HttpServletRequest request,
@Parameter(description = "菜单类型: app/admin") @RequestParam(required = false) String menuType, @Parameter(description = "菜单类型: app/admin") @RequestParam(required = false) String menuType,
@Parameter(description = "授权树语义: true 时非超管只返回自己可授予的菜单") @Parameter(description = "授权树语义: true 时非超管只返回自己可授予的菜单")
@RequestParam(required = false, defaultValue = "false") boolean grantableOnly) { @RequestParam(required = false, defaultValue = "false") boolean grantableOnly,
@Parameter(description = "公司 ID:仅站点超管可指定,缺省取操作者本公司")
@RequestParam(name = "company_id", required = false) Long companyId) {
// 传入操作者:授权树据此只下发(并把范围外节点标成不可勾选)操作者有权授予的菜单 // 传入操作者:授权树据此只下发(并把范围外节点标成不可勾选)操作者有权授予的菜单
return ApiResponse.success(permissionMenuService.list(requireAdmin(request), menuType, grantableOnly)); AdminUserEntity operator = requireAdmin(request);
// 归属判据只有一条(读写共用):先在这里过一遍,别家公司的 company_id 在取任何数之前就被 403 拒掉,
// 传下去的是定下来那一家,而不是 tab 原文。service 内部还会再判一次(幂等),控制器不重算口径。
Long scopeCompanyId = permissionMenuService.resolveScopeCompanyId(operator, companyId);
return ApiResponse.success(permissionMenuService.list(
operator, menuType, grantableOnly, scopeCompanyId));
} }
@PostMapping("/permission-menus") @PostMapping("/permission-menus")
@Operation(summary = "新增菜单权限项") @Operation(summary = "新增菜单权限项")
public ApiResponse<PermissionMenuItemVo> createMenu(HttpServletRequest httpRequest, public ApiResponse<PermissionMenuItemVo> createMenu(HttpServletRequest httpRequest,
@Valid @RequestBody PermissionMenuCreateRequest request) { @Valid @RequestBody PermissionMenuCreateRequest request,
@Parameter(description = "建到哪家公司的树:仅站点超管可指定")
@RequestParam(name = "company_id", required = false)
Long companyId) {
AdminUserEntity operator = requireAdmin(httpRequest);
Long scopeCompanyId = permissionMenuService.resolveScopeCompanyId(operator, companyId);
return ApiResponse.success("创建成功", permissionMenuService.create( return ApiResponse.success("创建成功", permissionMenuService.create(
requireAdmin(httpRequest), request)); operator, scopeCompanyId, request));
} }
@PutMapping("/permission-menus/{id}") @PutMapping("/permission-menus/{id}")
@@ -86,7 +98,7 @@ public class PermissionMenuController {
@Operation(summary = "同级菜单拖拽排序") @Operation(summary = "同级菜单拖拽排序")
public ApiResponse<Void> reorderColumns(HttpServletRequest httpRequest, public ApiResponse<Void> reorderColumns(HttpServletRequest httpRequest,
@RequestBody(required = false) Map<String, Object> body) { @RequestBody(required = false) Map<String, Object> body) {
requireAdmin(httpRequest); AdminUserEntity operator = requireAdmin(httpRequest);
Object raw = body == null ? null Object raw = body == null ? null
: (body.get("ordered_ids") != null ? body.get("ordered_ids") : body.get("orderedIds")); : (body.get("ordered_ids") != null ? body.get("ordered_ids") : body.get("orderedIds"));
if (!(raw instanceof List<?> list)) { if (!(raw instanceof List<?> list)) {
@@ -104,7 +116,8 @@ public class PermissionMenuController {
} }
} }
} }
permissionMenuService.reorder(ids); // 带上操作者:重排会写兄弟集的 sort_order,每家公司一棵树之后必须先确认锚点行属于他
permissionMenuService.reorder(operator, ids);
return ApiResponse.success("排序已保存", null); return ApiResponse.success("排序已保存", null);
} }
@@ -142,34 +155,48 @@ public class PermissionMenuController {
@GetMapping("/image-video-task-permissions") @GetMapping("/image-video-task-permissions")
@Operation(summary = "查询视频任务数据权限用户") @Operation(summary = "查询视频任务数据权限用户")
public ApiResponse<List<ImageVideoDataPermissionUserVo>> listImageVideoDataPermissionUsers( public ApiResponse<List<ImageVideoDataPermissionUserVo>> listImageVideoDataPermissionUsers(
HttpServletRequest request) { HttpServletRequest request,
return ApiResponse.success(permissionMenuService.listImageVideoDataPermissionUsers(requireAdmin(request))); @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = requireAdmin(request);
Long scopeCompanyId = permissionMenuService.resolveScopeCompanyId(operator, companyId);
return ApiResponse.success(permissionMenuService.listImageVideoDataPermissionUsers(
operator, scopeCompanyId));
} }
@PutMapping("/image-video-task-permissions") @PutMapping("/image-video-task-permissions")
@Operation(summary = "更新视频任务数据权限用户") @Operation(summary = "更新视频任务数据权限用户")
public ApiResponse<Integer> updateImageVideoDataPermissionUsers( public ApiResponse<Integer> updateImageVideoDataPermissionUsers(
HttpServletRequest request, HttpServletRequest request,
@RequestParam(name = "company_id", required = false) Long companyId,
@RequestBody(required = false) ImageVideoDataPermissionUpdateRequest body) { @RequestBody(required = false) ImageVideoDataPermissionUpdateRequest body) {
AdminUserEntity operator = requireAdmin(request);
Long scopeCompanyId = permissionMenuService.resolveScopeCompanyId(operator, companyId);
int grantedCount = permissionMenuService.updateImageVideoDataPermissionUsers( int grantedCount = permissionMenuService.updateImageVideoDataPermissionUsers(
requireAdmin(request), body == null ? List.of() : body.getUserIds()); operator, scopeCompanyId, body == null ? List.of() : body.getUserIds());
return ApiResponse.success("视频任务权限已更新", grantedCount); return ApiResponse.success("视频任务权限已更新", grantedCount);
} }
@GetMapping("/shop-data-crawl-task-permissions") @GetMapping("/shop-data-crawl-task-permissions")
@Operation(summary = "查询店铺数据任务数据权限用户") @Operation(summary = "查询店铺数据任务数据权限用户")
public ApiResponse<List<ImageVideoDataPermissionUserVo>> listShopDataCrawlDataPermissionUsers( public ApiResponse<List<ImageVideoDataPermissionUserVo>> listShopDataCrawlDataPermissionUsers(
HttpServletRequest request) { HttpServletRequest request,
return ApiResponse.success(permissionMenuService.listShopDataCrawlDataPermissionUsers(requireAdmin(request))); @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = requireAdmin(request);
Long scopeCompanyId = permissionMenuService.resolveScopeCompanyId(operator, companyId);
return ApiResponse.success(permissionMenuService.listShopDataCrawlDataPermissionUsers(
operator, scopeCompanyId));
} }
@PutMapping("/shop-data-crawl-task-permissions") @PutMapping("/shop-data-crawl-task-permissions")
@Operation(summary = "更新店铺数据任务数据权限用户") @Operation(summary = "更新店铺数据任务数据权限用户")
public ApiResponse<Integer> updateShopDataCrawlDataPermissionUsers( public ApiResponse<Integer> updateShopDataCrawlDataPermissionUsers(
HttpServletRequest request, HttpServletRequest request,
@RequestParam(name = "company_id", required = false) Long companyId,
@RequestBody(required = false) ImageVideoDataPermissionUpdateRequest body) { @RequestBody(required = false) ImageVideoDataPermissionUpdateRequest body) {
AdminUserEntity operator = requireAdmin(request);
Long scopeCompanyId = permissionMenuService.resolveScopeCompanyId(operator, companyId);
int grantedCount = permissionMenuService.updateShopDataCrawlDataPermissionUsers( int grantedCount = permissionMenuService.updateShopDataCrawlDataPermissionUsers(
requireAdmin(request), body == null ? List.of() : body.getUserIds()); operator, scopeCompanyId, body == null ? List.of() : body.getUserIds());
return ApiResponse.success("店铺数据任务权限已更新", grantedCount); return ApiResponse.success("店铺数据任务权限已更新", grantedCount);
} }
@@ -22,6 +22,15 @@ public class PermissionMenuEntity {
private String menuType; private String menuType;
private String routePath; private String routePath;
private Integer sortOrder; private Integer sortOrder;
/**
* 归属公司(V149):菜单字典从"全平台一棵树"改成"每家公司一套树",
* {@code column_key} 与 {@code (menu_type, route_path)} 都只在本公司内唯一。
*
* <p>写侧一律显式赋值({@code PermissionMenuService} 的 create/update 从操作者或目标行推导),
* 不许依赖列上那条临时的 {@code DEFAULT 1}:V149 留 DEFAULT 只为让同批的旧 jar 不报 1364,
* 下一版就摘掉;一旦有出口忘了赋值,DEFAULT 会把别家的菜单静默塞进厦门米椿花。</p>
*/
private Long companyId;
private LocalDateTime createdAt; private LocalDateTime createdAt;
/** /**
* 更新时间(V131 新增):由数据库维护(DEFAULT CURRENT_TIMESTAMP + ON UPDATE CURRENT_TIMESTAMP)。 * 更新时间(V131 新增):由数据库维护(DEFAULT CURRENT_TIMESTAMP + ON UPDATE CURRENT_TIMESTAMP)。
@@ -11,6 +11,19 @@ import org.springframework.stereotype.Component;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
/**
* 菜单字典的建表/种子旁路(生产默认关,见 application.yml 的 aiimage.permission-schema-init.enabled)。
*
* <p>V149 之后它只维护<b>公司 1 那棵平台默认树</b>:每一条种子语句的 INSERT 列清单都显式写
* {@code company_id = 1},判存守卫、认父 JOIN、按 key 的 UPDATE 也一律带 {@code company_id = 1}——
* 因为 column_key 如今只在单家公司内唯一,一条裸 {@code WHERE column_key = ...} 在这张表上
* 就是"把每一家的同名行都改一遍"(把别家副本的 parent 拍平、或把授权发给别家的行 id)。
* 显式写公司还有一层作用:这条通道不再依赖列上那条 {@code DEFAULT 1},
* 于是 V152 起摘掉它({@code ALTER TABLE columns ALTER COLUMN company_id DROP DEFAULT})
* 不会让这里的建号变成 1364 被 {@code executeQuietly} 吞成"一声不响少一套菜单"。
* 别家公司的树不由这里插行——存量公司归 V149 的复制段,新建公司归
* {@code PermissionMenuService.copyTreeFromTemplate}({@code CompanyService.create} 同事务调用)。</p>
*/
@Component @Component
@RequiredArgsConstructor @RequiredArgsConstructor
@Slf4j @Slf4j
@@ -92,17 +105,26 @@ public class PermissionMenuSchemaInitializer {
name VARCHAR(128) NOT NULL COMMENT '菜单标题', name VARCHAR(128) NOT NULL COMMENT '菜单标题',
column_key VARCHAR(64) NOT NULL COMMENT '菜单唯一标识', column_key VARCHAR(64) NOT NULL COMMENT '菜单唯一标识',
parent_id INT NULL COMMENT '直接父菜单 ID', parent_id INT NULL COMMENT '直接父菜单 ID',
company_id BIGINT NOT NULL DEFAULT 1 COMMENT '归属公司:每家公司一套菜单树',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP, created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uk_column_key (column_key) UNIQUE KEY uk_company_column_key (company_id, column_key)
) )
"""); """);
executeQuietly("ALTER TABLE columns ADD COLUMN menu_type VARCHAR(20) NOT NULL DEFAULT 'app' COMMENT '菜单类型: app/admin' AFTER column_key"); executeQuietly("ALTER TABLE columns ADD COLUMN menu_type VARCHAR(20) NOT NULL DEFAULT 'app' COMMENT '菜单类型: app/admin' AFTER column_key");
executeQuietly("ALTER TABLE columns ADD COLUMN parent_id INT NULL COMMENT '直接父菜单 ID' AFTER id"); executeQuietly("ALTER TABLE columns ADD COLUMN parent_id INT NULL COMMENT '直接父菜单 ID' AFTER id");
executeQuietly("ALTER TABLE columns ADD COLUMN route_path VARCHAR(255) NOT NULL DEFAULT '' COMMENT '菜单路由或页面标识' AFTER menu_type"); executeQuietly("ALTER TABLE columns ADD COLUMN route_path VARCHAR(255) NOT NULL DEFAULT '' COMMENT '菜单路由或页面标识' AFTER menu_type");
executeQuietly("ALTER TABLE columns ADD COLUMN sort_order INT NOT NULL DEFAULT 0 COMMENT '菜单排序' AFTER route_path"); executeQuietly("ALTER TABLE columns ADD COLUMN sort_order INT NOT NULL DEFAULT 0 COMMENT '菜单排序' AFTER route_path");
executeQuietly("ALTER TABLE columns ADD COLUMN company_id BIGINT NULL COMMENT '归属公司:每家公司一套菜单树'");
executeQuietly("UPDATE columns SET company_id = 1 WHERE company_id IS NULL");
executeQuietly("ALTER TABLE columns MODIFY COLUMN company_id BIGINT NOT NULL DEFAULT 1 COMMENT '归属公司:每家公司一套菜单树'");
executeQuietly("UPDATE columns SET menu_type = 'app' WHERE menu_type IS NULL OR menu_type = ''"); executeQuietly("UPDATE columns SET menu_type = 'app' WHERE menu_type IS NULL OR menu_type = ''");
executeQuietly("UPDATE columns SET sort_order = id WHERE sort_order IS NULL OR sort_order = 0"); executeQuietly("UPDATE columns SET sort_order = id WHERE sort_order IS NULL OR sort_order = 0");
executeQuietly("ALTER TABLE columns ADD UNIQUE KEY uk_menu_type_route_path (menu_type, route_path)"); // 两条全局唯一键在"每家公司一套树"之后会把别家同名菜单挡成"标识已存在"。
// 先加复合键、再摘旧键(与 V149 第 4/5 段同一顺序:任一步失败都至少还剩一条键守并发)。
executeQuietly("ALTER TABLE columns ADD UNIQUE KEY uk_company_column_key (company_id, column_key)");
executeQuietly("ALTER TABLE columns ADD UNIQUE KEY uk_company_menu_type_route_path (company_id, menu_type, route_path)");
executeQuietly("ALTER TABLE columns DROP INDEX uk_column_key");
executeQuietly("ALTER TABLE columns DROP INDEX uk_menu_type_route_path");
ensureDefaultAdminGroups(); ensureDefaultAdminGroups();
ensureDefaultAdminMenus(); ensureDefaultAdminMenus();
boolean shopDataCrawlDataPermissionCreated = ensureShopDataCrawlAdminDefaults(); boolean shopDataCrawlDataPermissionCreated = ensureShopDataCrawlAdminDefaults();
@@ -126,10 +148,10 @@ public class PermissionMenuSchemaInitializer {
private void ensureDefaultAdminGroups() { private void ensureDefaultAdminGroups() {
for (DefaultAdminGroup group : DEFAULT_ADMIN_GROUPS) { for (DefaultAdminGroup group : DEFAULT_ADMIN_GROUPS) {
executeQuietly(""" executeQuietly("""
INSERT INTO columns (name, column_key, menu_type, route_path, parent_id, sort_order) INSERT INTO columns (company_id, name, column_key, menu_type, route_path, parent_id, sort_order)
SELECT '%s', '%s', 'admin', '%s', NULL, %d SELECT 1, '%s', '%s', 'admin', '%s', NULL, %d
WHERE NOT EXISTS ( WHERE NOT EXISTS (
SELECT 1 FROM columns WHERE column_key = '%s' SELECT 1 FROM columns WHERE company_id = 1 AND column_key = '%s'
) )
""".formatted(group.name(), group.columnKey(), group.routePath(), group.sortOrder(), group.columnKey())); """.formatted(group.name(), group.columnKey(), group.routePath(), group.sortOrder(), group.columnKey()));
} }
@@ -138,21 +160,21 @@ public class PermissionMenuSchemaInitializer {
private void ensureDefaultAdminMenus() { private void ensureDefaultAdminMenus() {
for (DefaultAdminMenu menu : DEFAULT_ADMIN_MENUS) { for (DefaultAdminMenu menu : DEFAULT_ADMIN_MENUS) {
executeQuietly(""" executeQuietly("""
INSERT INTO columns (name, column_key, menu_type, route_path, sort_order, parent_id) INSERT INTO columns (company_id, name, column_key, menu_type, route_path, sort_order, parent_id)
SELECT '%s', '%s', 'admin', '%s', %d, parent.id SELECT 1, '%s', '%s', 'admin', '%s', %d, parent.id
FROM columns parent FROM columns parent
WHERE parent.column_key = '%s' WHERE parent.company_id = 1 AND parent.column_key = '%s'
AND NOT EXISTS ( AND NOT EXISTS (
SELECT 1 FROM columns WHERE column_key = '%s' SELECT 1 FROM columns WHERE company_id = 1 AND column_key = '%s'
) )
""".formatted(menu.name(), menu.columnKey(), menu.routePath(), menu.sortOrder(), """.formatted(menu.name(), menu.columnKey(), menu.routePath(), menu.sortOrder(),
menu.parentKey(), menu.columnKey())); menu.parentKey(), menu.columnKey()));
executeQuietly(""" executeQuietly("""
UPDATE columns child UPDATE columns child
JOIN columns parent ON parent.column_key = '%s' JOIN columns parent ON parent.company_id = 1 AND parent.column_key = '%s'
SET child.name = '%s', child.sort_order = %d, SET child.name = '%s', child.sort_order = %d,
child.parent_id = COALESCE(child.parent_id, parent.id) child.parent_id = COALESCE(child.parent_id, parent.id)
WHERE child.column_key = '%s' WHERE child.company_id = 1 AND child.column_key = '%s'
""".formatted(menu.parentKey(), menu.name(), menu.sortOrder(), menu.columnKey())); """.formatted(menu.parentKey(), menu.name(), menu.sortOrder(), menu.columnKey()));
} }
} }
@@ -160,16 +182,16 @@ public class PermissionMenuSchemaInitializer {
private void ensureDefaultAppMenus() { private void ensureDefaultAppMenus() {
for (DefaultAppMenu menu : DEFAULT_APP_MENUS) { for (DefaultAppMenu menu : DEFAULT_APP_MENUS) {
executeQuietly(""" executeQuietly("""
INSERT INTO columns (name, column_key, menu_type, route_path, sort_order) INSERT INTO columns (company_id, name, column_key, menu_type, route_path, sort_order)
SELECT '%s', '%s', 'app', '%s', %d SELECT 1, '%s', '%s', 'app', '%s', %d
WHERE NOT EXISTS ( WHERE NOT EXISTS (
SELECT 1 FROM columns WHERE column_key = '%s' SELECT 1 FROM columns WHERE company_id = 1 AND column_key = '%s'
) )
""".formatted(menu.name(), menu.columnKey(), menu.routePath(), menu.sortOrder(), menu.columnKey())); """.formatted(menu.name(), menu.columnKey(), menu.routePath(), menu.sortOrder(), menu.columnKey()));
executeQuietly(""" executeQuietly("""
UPDATE columns UPDATE columns
SET sort_order = %d, route_path = '%s', menu_type = 'app', parent_id = NULL SET sort_order = %d, route_path = '%s', menu_type = 'app', parent_id = NULL
WHERE column_key = '%s' WHERE company_id = 1 AND column_key = '%s'
""".formatted(menu.sortOrder(), menu.routePath(), menu.columnKey())); """.formatted(menu.sortOrder(), menu.routePath(), menu.columnKey()));
} }
} }
@@ -177,55 +199,55 @@ public class PermissionMenuSchemaInitializer {
private void ensureDefaultAppChildMenus() { private void ensureDefaultAppChildMenus() {
// Older migrations used underscore keys for a few app pages. Normalize // Older migrations used underscore keys for a few app pages. Normalize
// them once so the frontend item key and permission key stay aligned. // them once so the frontend item key and permission key stay aligned.
executeQuietly("UPDATE columns SET column_key = 'collect-data' WHERE column_key = 'collect_data'"); executeQuietly("UPDATE columns SET column_key = 'collect-data' WHERE company_id = 1 AND column_key = 'collect_data'");
executeQuietly("UPDATE columns SET column_key = 'appearance-patent' WHERE column_key = 'appearance_patent'"); executeQuietly("UPDATE columns SET column_key = 'appearance-patent' WHERE company_id = 1 AND column_key = 'appearance_patent'");
executeQuietly("UPDATE columns SET column_key = 'similar-asin' WHERE column_key = 'similar_asin'"); executeQuietly("UPDATE columns SET column_key = 'similar-asin' WHERE company_id = 1 AND column_key = 'similar_asin'");
for (DefaultAppChildMenu menu : DEFAULT_APP_CHILD_MENUS) { for (DefaultAppChildMenu menu : DEFAULT_APP_CHILD_MENUS) {
executeQuietly(""" executeQuietly("""
INSERT INTO columns (name, column_key, menu_type, route_path, sort_order, parent_id) INSERT INTO columns (company_id, name, column_key, menu_type, route_path, sort_order, parent_id)
SELECT '%s', '%s', 'app', '%s', %d, parent.id SELECT 1, '%s', '%s', 'app', '%s', %d, parent.id
FROM columns parent FROM columns parent
WHERE parent.column_key = '%s' WHERE parent.company_id = 1 AND parent.column_key = '%s'
AND NOT EXISTS ( AND NOT EXISTS (
SELECT 1 FROM columns existing WHERE existing.column_key = '%s' SELECT 1 FROM columns existing WHERE existing.company_id = 1 AND existing.column_key = '%s'
) )
""".formatted(menu.name(), menu.columnKey(), menu.routePath(), menu.sortOrder(), """.formatted(menu.name(), menu.columnKey(), menu.routePath(), menu.sortOrder(),
menu.parentKey(), menu.columnKey())); menu.parentKey(), menu.columnKey()));
executeQuietly(""" executeQuietly("""
UPDATE columns child UPDATE columns child
JOIN columns parent ON parent.column_key = '%s' JOIN columns parent ON parent.company_id = 1 AND parent.column_key = '%s'
SET child.name = '%s', child.menu_type = 'app', child.route_path = '%s', SET child.name = '%s', child.menu_type = 'app', child.route_path = '%s',
child.sort_order = %d, child.parent_id = parent.id child.sort_order = %d, child.parent_id = parent.id
WHERE child.column_key = '%s' WHERE child.company_id = 1 AND child.column_key = '%s'
""".formatted(menu.parentKey(), menu.name(), menu.routePath(), menu.sortOrder(), menu.columnKey())); """.formatted(menu.parentKey(), menu.name(), menu.routePath(), menu.sortOrder(), menu.columnKey()));
} }
} }
private void ensureInternalDataPermissions() { private void ensureInternalDataPermissions() {
executeQuietly(""" executeQuietly("""
INSERT INTO columns (name, column_key, menu_type, route_path, sort_order) INSERT INTO columns (company_id, name, column_key, menu_type, route_path, sort_order)
SELECT '视频任务数据查看', 'admin_image_video_task_data', 'internal', 'image-video-task-data', 0 SELECT 1, '视频任务数据查看', 'admin_image_video_task_data', 'internal', 'image-video-task-data', 0
WHERE NOT EXISTS ( WHERE NOT EXISTS (
SELECT 1 FROM columns WHERE column_key = 'admin_image_video_task_data' SELECT 1 FROM columns WHERE company_id = 1 AND column_key = 'admin_image_video_task_data'
) )
"""); """);
} }
private boolean ensureShopDataCrawlAdminDefaults() { private boolean ensureShopDataCrawlAdminDefaults() {
executeQuietly(""" executeQuietly("""
INSERT INTO columns (name, column_key, menu_type, route_path, sort_order, parent_id) INSERT INTO columns (company_id, name, column_key, menu_type, route_path, sort_order, parent_id)
SELECT '店铺数据记录', 'admin_shop_data_crawl_tasks', 'admin', 'shop-data-crawl-tasks', 82, SELECT 1, '店铺数据记录', 'admin_shop_data_crawl_tasks', 'admin', 'shop-data-crawl-tasks', 82,
(SELECT id FROM columns WHERE column_key = 'admin_group_shop' LIMIT 1) (SELECT id FROM columns WHERE company_id = 1 AND column_key = 'admin_group_shop' LIMIT 1)
WHERE NOT EXISTS ( WHERE NOT EXISTS (
SELECT 1 FROM columns WHERE column_key = 'admin_shop_data_crawl_tasks' SELECT 1 FROM columns WHERE company_id = 1 AND column_key = 'admin_shop_data_crawl_tasks'
) )
"""); """);
return executeUpdateQuietly(""" return executeUpdateQuietly("""
INSERT INTO columns (name, column_key, menu_type, route_path, sort_order) INSERT INTO columns (company_id, name, column_key, menu_type, route_path, sort_order)
SELECT '店铺数据任务数据查看', 'admin_shop_data_crawl_task_data', 'internal', 'shop-data-crawl-task-data', 0 SELECT 1, '店铺数据任务数据查看', 'admin_shop_data_crawl_task_data', 'internal', 'shop-data-crawl-task-data', 0
WHERE NOT EXISTS ( WHERE NOT EXISTS (
SELECT 1 FROM columns WHERE column_key = 'admin_shop_data_crawl_task_data' SELECT 1 FROM columns WHERE company_id = 1 AND column_key = 'admin_shop_data_crawl_task_data'
) )
""") > 0; """) > 0;
} }
@@ -236,7 +258,8 @@ public class PermissionMenuSchemaInitializer {
SELECT old_perm.user_id, data_col.id SELECT old_perm.user_id, data_col.id
FROM user_column_permission old_perm FROM user_column_permission old_perm
INNER JOIN columns old_col ON old_col.id = old_perm.column_id INNER JOIN columns old_col ON old_col.id = old_perm.column_id
INNER JOIN columns data_col ON data_col.column_key = 'admin_shop_data_crawl_task_data' INNER JOIN columns data_col ON data_col.company_id = old_col.company_id
AND data_col.column_key = 'admin_shop_data_crawl_task_data'
LEFT JOIN user_column_permission existing LEFT JOIN user_column_permission existing
ON existing.user_id = old_perm.user_id ON existing.user_id = old_perm.user_id
AND existing.column_id = data_col.id AND existing.column_id = data_col.id
@@ -79,9 +79,24 @@ public class PermissionMenuService {
* 一旦可勾,「勾父覆盖全部后代」就会把树上未展示的范围外菜单一起授出去。 * 一旦可勾,「勾父覆盖全部后代」就会把树上未展示的范围外菜单一起授出去。
* 保存侧必须配套按操作者范围替换,见 * 保存侧必须配套按操作者范围替换,见
* {@link #updateUserColumnPermissions(AdminUserEntity, Long, UserColumnPermissionUpdateRequest, String, boolean)}。 * {@link #updateUserColumnPermissions(AdminUserEntity, Long, UserColumnPermissionUpdateRequest, String, boolean)}。
* @param requestedCompanyId V149 目录页的公司 tab:站点超管可指定任意公司的树;非超管传别家 403,
* 不传就锁本公司。缺省值不是"全公司"——每家公司一套树之后,跨公司的目录混在一起
* 等于让 {@code column_key} 在同一个响应里出现两次,前端按 key 建树会直接长错。
*/ */
public List<PermissionMenuItemVo> list(AdminUserEntity operator, String menuType,
boolean grantableOnly, Long requestedCompanyId) {
Long companyId = resolveScopeCompanyId(operator, requestedCompanyId);
return listAt(companyId, operator, menuType, grantableOnly);
}
public List<PermissionMenuItemVo> list(AdminUserEntity operator, String menuType, boolean grantableOnly) { public List<PermissionMenuItemVo> list(AdminUserEntity operator, String menuType, boolean grantableOnly) {
List<PermissionMenuEntity> menus = loadMenus(menuType); return list(operator, menuType, grantableOnly, null);
}
/** 目录/授权树的唯一出口:{@code companyId} 为非空时只取那一棵树的行,null 仅留给无操作者的内部调用。 */
private List<PermissionMenuItemVo> listAt(Long companyId, AdminUserEntity operator,
String menuType, boolean grantableOnly) {
List<PermissionMenuEntity> menus = loadMenus(companyId, menuType);
Set<Long> grantableIds = resolveGrantableMenuIds(operator); Set<Long> grantableIds = resolveGrantableMenuIds(operator);
List<PermissionMenuEntity> visibleMenus = menus; List<PermissionMenuEntity> visibleMenus = menus;
if (grantableOnly && grantableIds != null) { if (grantableOnly && grantableIds != null) {
@@ -109,13 +124,68 @@ public class PermissionMenuService {
/** /**
* 操作者可授予的菜单 id 全集(自身直接授权 + 其后代)。 * 操作者可授予的菜单 id 全集(自身直接授权 + 其后代)。
* *
* <p>V149 之后按<b>操作者本公司</b>那棵树展开:授权只会指向本公司的行(迁移第 9 段与
* 闸门 3 保证),拿全平台目录去展开等于把别家同名菜单的 id 也算进"可授予",
* 那是"范围收窄只做在界面上"的同一类事故。</p>
*
* @return null 表示不限制(超管或无操作者) * @return null 表示不限制(超管或无操作者)
*/ */
private Set<Long> resolveGrantableMenuIds(AdminUserEntity operator) { private Set<Long> resolveGrantableMenuIds(AdminUserEntity operator) {
if (operator == null || operator.getId() == null || isSuperAdmin(operator)) { if (operator == null || operator.getId() == null || isSuperAdmin(operator)) {
return null; return null;
} }
return expandDescendantIds(new LinkedHashSet<>(loadDirectColumnIds(operator.getId())), loadMenus(null)); return expandDescendantIds(new LinkedHashSet<>(loadDirectColumnIds(operator.getId())),
loadMenus(operator.getCompanyId(), null));
}
/**
* 归属公司的统一判据(设计文档 §2 D2):不传就锁操作者本公司;站点超管可以显式指定
* 任意一家(他今天就在替两家公司共 133 只账号配权限),非超管传别家一律 403。
*
* <p>读侧与写侧共用这一个方法:分成两个迟早漂移成「读能看别家、写挡不住」或反过来,
* 而那正是 09-13「权限自己没掉」那一族事故的形状。</p>
*
* <p>{@code null} 只可能来自「没有操作者」的历史内部调用与单测夹具,此时不下公司条件、
* 退回换列之前的全量目录语义;生产上 {@code users.company_id} 是 NOT NULL,
* 真出现无归属账号由列上的约束喊,不在这里编一个默认公司。</p>
*
* <p>公开是为了让控制器在收 {@code company_id} 参数的当场就走这道门(把返回值往下传),
* 而不是把裸参数扔进来再靠本类内部兜——{@code CompanyIdParamGoesThroughReadScopeTest}
* 认的就是这条出口,控制器少接一次就等于"tab 传了但没人用"。</p>
*/
public Long resolveScopeCompanyId(AdminUserEntity operator, Long requestedCompanyId) {
if (requestedCompanyId != null && requestedCompanyId <= 0) {
throw new BusinessException("company_id 无效");
}
if (operator == null || operator.getId() == null) {
return requestedCompanyId;
}
Long operatorCompanyId = operator.getCompanyId();
if (requestedCompanyId == null) {
return operatorCompanyId;
}
if (requestedCompanyId.equals(operatorCompanyId) || isSuperAdmin(operator)) {
return requestedCompanyId;
}
throw new BusinessException(403, "无权读写其他公司的菜单");
}
/**
* 写侧闸门(§5):非超管只能动<b>本公司那棵树</b>里的行。
*
* <p>补这道闸门之前 {@link #ensureAdminOperatorIfPresent} 只判 isAdmin,等于任何管理员
* 都能改整张字典;每家公司一棵树之后,跨公司改一行会把别家的菜单搬进自己树里
* ({@code column_key} 在两家之间不再全局唯一,只有 id 认得出它属于谁)。
* 菜单字典是租户配置,改坏它比跨公司读数据更糟——那家所有账号的权限页一起坏。</p>
*/
private void ensureMenuWritable(AdminUserEntity operator, PermissionMenuEntity menu) {
if (operator == null || isSuperAdmin(operator)) {
return;
}
Long menuCompanyId = menu == null ? null : menu.getCompanyId();
if (!Objects.equals(menuCompanyId, operator.getCompanyId())) {
throw new BusinessException(403, "无权修改其他公司的菜单");
}
} }
/** /**
@@ -139,13 +209,25 @@ public class PermissionMenuService {
@Transactional @Transactional
public PermissionMenuItemVo create(PermissionMenuCreateRequest request) { public PermissionMenuItemVo create(PermissionMenuCreateRequest request) {
return create(null, request); return create(null, null, request);
} }
/** Controller-facing variant; the caller may pass the authenticated admin. */ /** Controller-facing variant; the caller may pass the authenticated admin. */
@Transactional @Transactional
public PermissionMenuItemVo create(AdminUserEntity operator, PermissionMenuCreateRequest request) { public PermissionMenuItemVo create(AdminUserEntity operator, PermissionMenuCreateRequest request) {
return create(operator, null, request);
}
/**
* 新增菜单。归属公司由 {@code requestedCompanyId} 决定,缺省取操作者本公司(设计文档 §5):
* 站点超管可以替别家建菜单(今天就是他一人在给 133 只账号配权限),非超管只能在自已公司建,
* 传别家 403。<b>绝不靠列上的 DEFAULT 1 兜归属</b>——那等于把别家的菜单静默塞进厦门米椿花。
*/
@Transactional
public PermissionMenuItemVo create(AdminUserEntity operator, Long requestedCompanyId,
PermissionMenuCreateRequest request) {
ensureAdminOperatorIfPresent(operator); ensureAdminOperatorIfPresent(operator);
Long companyId = resolveScopeCompanyId(operator, requestedCompanyId);
if (request == null) { if (request == null) {
throw new BusinessException("菜单参数不能为空"); throw new BusinessException("菜单参数不能为空");
} }
@@ -161,9 +243,9 @@ public class PermissionMenuService {
routePath = generateRoutePath(columnKey); routePath = generateRoutePath(columnKey);
} }
Long parentId = normalizeParentId(request.getParentId()); Long parentId = normalizeParentId(request.getParentId());
ensureParentValid(parentId, null, menuType); ensureParentValid(companyId, parentId, null, menuType);
ensureUniqueColumnKey(columnKey, null); ensureUniqueColumnKey(companyId, columnKey, null);
ensureUniqueRoutePath(menuType, routePath, null); ensureUniqueRoutePath(companyId, menuType, routePath, null);
PermissionMenuEntity entity = new PermissionMenuEntity(); PermissionMenuEntity entity = new PermissionMenuEntity();
entity.setName(name); entity.setName(name);
@@ -171,7 +253,8 @@ public class PermissionMenuService {
entity.setParentId(parentId); entity.setParentId(parentId);
entity.setMenuType(menuType); entity.setMenuType(menuType);
entity.setRoutePath(routePath); entity.setRoutePath(routePath);
entity.setSortOrder(resolveSortOrder(menuType, request.getSortOrder(), null)); entity.setCompanyId(companyId);
entity.setSortOrder(resolveSortOrder(companyId, menuType, request.getSortOrder(), null));
permissionMenuMapper.insert(entity); permissionMenuMapper.insert(entity);
return toItemVo(getMenuById(entity.getId())); return toItemVo(getMenuById(entity.getId()));
} }
@@ -186,6 +269,10 @@ public class PermissionMenuService {
public PermissionMenuItemVo update(AdminUserEntity operator, Long id, PermissionMenuUpdateRequest request) { public PermissionMenuItemVo update(AdminUserEntity operator, Long id, PermissionMenuUpdateRequest request) {
ensureAdminOperatorIfPresent(operator); ensureAdminOperatorIfPresent(operator);
PermissionMenuEntity entity = getMenuById(id); PermissionMenuEntity entity = getMenuById(id);
// 归属不接收请求参数:改哪棵树由<b>这一行自己属于谁</b>决定,编辑动作只能把行留在原公司。
// 让载荷带 company_id 等于开一条"把别家的菜单搬进自己树"的旁路。
ensureMenuWritable(operator, entity);
Long companyId = entity.getCompanyId();
if (request == null) { if (request == null) {
throw new BusinessException("菜单参数不能为空"); throw new BusinessException("菜单参数不能为空");
} }
@@ -201,17 +288,17 @@ public class PermissionMenuService {
routePath = entity.getRoutePath(); routePath = entity.getRoutePath();
} }
Long parentId = normalizeParentId(request.getParentId()); Long parentId = normalizeParentId(request.getParentId());
ensureParentValid(parentId, id, menuType); ensureParentValid(companyId, parentId, id, menuType);
ensureMenuTypeChangeAllowed(entity, menuType); ensureMenuTypeChangeAllowed(entity, menuType);
ensureUniqueColumnKey(columnKey, id); ensureUniqueColumnKey(companyId, columnKey, id);
ensureUniqueRoutePath(menuType, routePath, id); ensureUniqueRoutePath(companyId, menuType, routePath, id);
entity.setName(name); entity.setName(name);
entity.setColumnKey(columnKey); entity.setColumnKey(columnKey);
entity.setParentId(parentId); entity.setParentId(parentId);
entity.setMenuType(menuType); entity.setMenuType(menuType);
entity.setRoutePath(routePath); entity.setRoutePath(routePath);
entity.setSortOrder(resolveSortOrder(menuType, request.getSortOrder(), id)); entity.setSortOrder(resolveSortOrder(companyId, menuType, request.getSortOrder(), id));
permissionMenuMapper.updateById(entity); permissionMenuMapper.updateById(entity);
return toItemVo(getMenuById(id)); return toItemVo(getMenuById(id));
} }
@@ -229,6 +316,7 @@ public class PermissionMenuService {
public void delete(AdminUserEntity operator, Long id) { public void delete(AdminUserEntity operator, Long id) {
ensureAdminOperatorIfPresent(operator); ensureAdminOperatorIfPresent(operator);
PermissionMenuEntity entity = getMenuById(id); PermissionMenuEntity entity = getMenuById(id);
ensureMenuWritable(operator, entity);
Long childCount = permissionMenuMapper.selectCount(new LambdaQueryWrapper<PermissionMenuEntity>() Long childCount = permissionMenuMapper.selectCount(new LambdaQueryWrapper<PermissionMenuEntity>()
.eq(PermissionMenuEntity::getParentId, entity.getId())); .eq(PermissionMenuEntity::getParentId, entity.getId()));
if (childCount != null && childCount > 0) { if (childCount != null && childCount > 0) {
@@ -243,9 +331,12 @@ public class PermissionMenuService {
/** /**
* 同级菜单拖拽重排:orderedIds 为同一父级下按新顺序排列的菜单 ID 列表。 * 同级菜单拖拽重排:orderedIds 为同一父级下按新顺序排列的菜单 ID 列表。
* 不在列表中的兄弟节点保持原相对顺序追加在末尾,重排块锚定在原最小 sort_order,避免跨级穿插。 * 不在列表中的兄弟节点保持原相对顺序追加在末尾,重排块锚定在原最小 sort_order,避免跨级穿插。
*
* <p>兄弟集必须按<b>锚点行的公司</b>筛:每家公司一棵树之后,"同级"这个概念本身就带公司口径,
* 混进别家的同名分组会让重排把两棵树的 sort_order 交织在一起(表现为两排同名菜单穿插)。</p>
*/ */
@Transactional @Transactional
public void reorder(List<Long> orderedIds) { public void reorder(AdminUserEntity operator, List<Long> orderedIds) {
if (orderedIds == null || orderedIds.isEmpty()) { if (orderedIds == null || orderedIds.isEmpty()) {
return; return;
} }
@@ -257,9 +348,13 @@ public class PermissionMenuService {
if (anchor == null) { if (anchor == null) {
throw new BusinessException("菜单不存在"); throw new BusinessException("菜单不存在");
} }
ensureAdminOperatorIfPresent(operator);
ensureMenuWritable(operator, anchor);
Long companyId = anchor.getCompanyId();
Long parentId = anchor.getParentId(); Long parentId = anchor.getParentId();
String menuType = anchor.getMenuType(); String menuType = anchor.getMenuType();
List<PermissionMenuEntity> siblings = permissionMenuMapper.selectList(new LambdaQueryWrapper<PermissionMenuEntity>() List<PermissionMenuEntity> siblings = permissionMenuMapper.selectList(new LambdaQueryWrapper<PermissionMenuEntity>()
.eq(PermissionMenuEntity::getCompanyId, companyId)
.eq(PermissionMenuEntity::getMenuType, menuType) .eq(PermissionMenuEntity::getMenuType, menuType)
.eq(PermissionMenuEntity::getParentId, parentId) .eq(PermissionMenuEntity::getParentId, parentId)
.orderByAsc(PermissionMenuEntity::getSortOrder) .orderByAsc(PermissionMenuEntity::getSortOrder)
@@ -288,6 +383,88 @@ public class PermissionMenuService {
} }
} }
/**
* 给新公司复制一套模板菜单树(父子指向按 {@code column_key} 重映射),与 V149 第 6/7 段同一语义:
* 那一版补的是<b>当时已经存在</b>的公司,这一版补的是之后新建的公司。
*
* <p>没有它,「公司管理 -> 新增公司」就造出一个零菜单行的租户:那家的账号登录后台侧边栏全空、
* 授权树一个勾都没有,而且全程不报错。这正是本次要消灭的那类静默失效,
* 所以建树必须是建号公司的同一次写入,不能留成"上线后再手工跑一遍 V149 的复制段"。</p>
*
* <p>两趟写:第一趟只管插(父先留空,避开插入顺序),第二趟按 key 把父指向落到本公司新行上
* ——与 V149 第 7 段同形,两级三层都成立。幂等:目标公司已有的 key 原样保留,重跑只补差集。</p>
*
* @param companyId 目标(新)公司
* @param templateCompanyId 模板树所属公司,由调用方给操作者本公司,这里不编默认值
* @return 本次新插入的行数
*/
@Transactional
public int copyTreeFromTemplate(Long companyId, Long templateCompanyId) {
if (companyId == null || companyId <= 0) {
throw new BusinessException("目标公司 id 不能为空");
}
if (templateCompanyId == null || templateCompanyId <= 0) {
throw new BusinessException("当前账号没有所属公司,无法为新公司复制菜单树");
}
if (companyId.equals(templateCompanyId)) {
return 0;
}
// 角色内在闸门那几行不进副本(D3):它在任何别家的树里都不该存在,
// 连行都没有就没人能勾它,比"有一行但看不见"更干净。
List<PermissionMenuEntity> template = loadRawMenus(templateCompanyId, null).stream()
.filter(menu -> menu.getId() != null && menu.getColumnKey() != null)
.filter(menu -> !SUPER_ADMIN_ONLY_KEYS.contains(menu.getColumnKey()))
.toList();
if (template.isEmpty()) {
throw new BusinessException("模板公司没有可复制的菜单树");
}
Map<String, PermissionMenuEntity> targetByKey = new HashMap<>();
for (PermissionMenuEntity menu : loadRawMenus(companyId, null)) {
if (menu.getColumnKey() != null) {
targetByKey.put(menu.getColumnKey(), menu);
}
}
Map<Long, PermissionMenuEntity> templateById = new HashMap<>();
template.forEach(menu -> templateById.put(menu.getId(), menu));
int inserted = 0;
for (PermissionMenuEntity source : template) {
if (targetByKey.containsKey(source.getColumnKey())) {
continue;
}
PermissionMenuEntity copy = new PermissionMenuEntity();
copy.setCompanyId(companyId);
copy.setName(source.getName());
copy.setColumnKey(source.getColumnKey());
copy.setMenuType(source.getMenuType());
copy.setRoutePath(source.getRoutePath());
copy.setSortOrder(source.getSortOrder());
copy.setParentId(null);
permissionMenuMapper.insert(copy);
targetByKey.put(copy.getColumnKey(), copy);
inserted++;
}
for (PermissionMenuEntity source : template) {
PermissionMenuEntity child = targetByKey.get(source.getColumnKey());
PermissionMenuEntity templateParent = templateById.get(source.getParentId());
if (child == null || child.getId() == null || templateParent == null) {
continue;
}
PermissionMenuEntity parent = targetByKey.get(templateParent.getColumnKey());
if (parent == null || parent.getId() == null || parent.getId().equals(child.getId())) {
continue;
}
if (!Objects.equals(child.getParentId(), parent.getId())) {
permissionMenuMapper.update(null, new LambdaUpdateWrapper<PermissionMenuEntity>()
.eq(PermissionMenuEntity::getId, child.getId())
.set(PermissionMenuEntity::getParentId, parent.getId()));
child.setParentId(parent.getId());
}
}
log.info("[menu-tree-copy] 新公司菜单树已建 companyId={} template={} rows={}",
companyId, templateCompanyId, inserted);
return inserted;
}
/** Returns only persisted direct grant IDs (never recursively expanded). */ /** Returns only persisted direct grant IDs (never recursively expanded). */
public UserColumnIdsVo getUserColumnIds(Long userId, String menuType) { public UserColumnIdsVo getUserColumnIds(Long userId, String menuType) {
return getUserColumnIds(null, userId, menuType); return getUserColumnIds(null, userId, menuType);
@@ -314,7 +491,9 @@ public class PermissionMenuService {
AdminUserEntity user = getUserById(userId); AdminUserEntity user = getUserById(userId);
ensureTargetAccessible(operator, user); ensureTargetAccessible(operator, user);
List<PermissionMenuEntity> menus = loadMenus(menuType); // 回填集按<b>目标账号所属公司</b>的那棵树取:授权弹窗里勾的是"这个账号家"的菜单行 id,
// 操作者是谁都不该改变这一点(超管替德阳配权限时勾出公司 1 的行 id,就是跨公司授权)。
List<PermissionMenuEntity> menus = loadMenus(user.getCompanyId(), menuType);
Map<Long, PermissionMenuEntity> menuMap = menus.stream() Map<Long, PermissionMenuEntity> menuMap = menus.stream()
.filter(menu -> menu.getId() != null) .filter(menu -> menu.getId() != null)
.collect(Collectors.toMap(PermissionMenuEntity::getId, Function.identity(), (left, right) -> left)); .collect(Collectors.toMap(PermissionMenuEntity::getId, Function.identity(), (left, right) -> left));
@@ -351,7 +530,7 @@ public class PermissionMenuService {
boolean includeAncestorGroups) { boolean includeAncestorGroups) {
AdminUserEntity user = getUserById(userId); AdminUserEntity user = getUserById(userId);
ensureTargetAccessible(operator, user); ensureTargetAccessible(operator, user);
List<PermissionMenuEntity> menus = loadMenus(menuType); List<PermissionMenuEntity> menus = loadMenus(user.getCompanyId(), menuType);
if (isSuperAdmin(user)) { if (isSuperAdmin(user)) {
return toItemVos(menus, menus); return toItemVos(menus, menus);
} }
@@ -387,7 +566,12 @@ public class PermissionMenuService {
if (isSuperAdmin(user)) { if (isSuperAdmin(user)) {
return true; return true;
} }
List<PermissionMenuEntity> menus = loadMenus(target.getMenuType()); // 跨公司的 column_id 一律判「无权限」:本账号的直接授权里出现别家的行,只可能是载荷被
// 拼错(或前端缓存了换键之前的旧 id)。方向是拒绝,不是放行——放宽等于让别家的行 id 生效。
if (!Objects.equals(target.getCompanyId(), user.getCompanyId())) {
return false;
}
List<PermissionMenuEntity> menus = loadMenus(target.getCompanyId(), target.getMenuType());
return expandDescendantIds(new LinkedHashSet<>(loadDirectColumnIds(userId)), menus) return expandDescendantIds(new LinkedHashSet<>(loadDirectColumnIds(userId)), menus)
.contains(columnId); .contains(columnId);
} }
@@ -397,26 +581,40 @@ public class PermissionMenuService {
* *
* <p>权限页此前一律 `selectList(new LambdaQueryWrapper<>())` 整表拉回,而 admin_user * <p>权限页此前一律 `selectList(new LambdaQueryWrapper<>())` 整表拉回,而 admin_user
* 含密码哈希等敏感列,每次打开权限页都把全表(含哈希)读进内存(2026-09-15 优化)。 * 含密码哈希等敏感列,每次打开权限页都把全表(含哈希)读进内存(2026-09-15 优化)。
* 判定用 role/is_admin/created_by_id,展示用 id/username。 * 判定用 role/is_admin/created_by_id,展示用 id/username,按公司筛用 company_id
* (V149:数据权限行分属各棵树,用户列表必须同一家,否则「勾了人、写到别家的行」
* 会静默落空——页面照旧显示已授权,账号却永远拿不到那份数据)。
*/ */
private LambdaQueryWrapper<AdminUserEntity> grantableUserQuery() { private LambdaQueryWrapper<AdminUserEntity> grantableUserQuery(Long companyId) {
return new LambdaQueryWrapper<AdminUserEntity>() return new LambdaQueryWrapper<AdminUserEntity>()
.select(AdminUserEntity::getId, .select(AdminUserEntity::getId,
AdminUserEntity::getUsername, AdminUserEntity::getUsername,
AdminUserEntity::getRole, AdminUserEntity::getRole,
AdminUserEntity::getIsAdmin, AdminUserEntity::getIsAdmin,
AdminUserEntity::getCreatedById); AdminUserEntity::getCreatedById,
AdminUserEntity::getCompanyId)
.eq(companyId != null, AdminUserEntity::getCompanyId, companyId);
} }
public List<ImageVideoDataPermissionUserVo> listImageVideoDataPermissionUsers(AdminUserEntity operator) { public List<ImageVideoDataPermissionUserVo> listImageVideoDataPermissionUsers(AdminUserEntity operator) {
return listImageVideoDataPermissionUsers(operator, null);
}
/**
* 「视频任务数据查看」这一项内部数据权限的分公司读口:超管切到哪家公司就解析那棵树的行,
* 用户列表同步按那一家筛({@link #grantableUserQuery(Long)})。
*/
public List<ImageVideoDataPermissionUserVo> listImageVideoDataPermissionUsers(AdminUserEntity operator,
Long requestedCompanyId) {
ensureSuperAdminOperator(operator); ensureSuperAdminOperator(operator);
PermissionMenuEntity dataPermission = requireImageVideoDataPermission(); Long companyId = resolveScopeCompanyId(operator, requestedCompanyId);
PermissionMenuEntity dataPermission = requireImageVideoDataPermission(companyId);
Set<Long> grantedUserIds = userColumnPermissionMapper.selectByColumnId(dataPermission.getId()) Set<Long> grantedUserIds = userColumnPermissionMapper.selectByColumnId(dataPermission.getId())
.stream() .stream()
.map(UserColumnPermissionEntity::getUserId) .map(UserColumnPermissionEntity::getUserId)
.filter(id -> id != null && id > 0) .filter(id -> id != null && id > 0)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
return adminUserMapper.selectList(grantableUserQuery() return adminUserMapper.selectList(grantableUserQuery(companyId)
.orderByAsc(AdminUserEntity::getUsername) .orderByAsc(AdminUserEntity::getUsername)
.orderByAsc(AdminUserEntity::getId)) .orderByAsc(AdminUserEntity::getId))
.stream() .stream()
@@ -427,10 +625,22 @@ public class PermissionMenuService {
@Transactional @Transactional
public int updateImageVideoDataPermissionUsers(AdminUserEntity operator, List<Long> userIds) { public int updateImageVideoDataPermissionUsers(AdminUserEntity operator, List<Long> userIds) {
return updateImageVideoDataPermissionUsers(operator, null, userIds);
}
/**
* 整分区替换本公司的那一条内部数据权限授权。别家的账号 id 会落进
* 「contains unknown or non-grantable user」——用户列表已经按公司筛过,
* 这不是新报错,是既有的那条从严判定现在有了公司口径。
*/
@Transactional
public int updateImageVideoDataPermissionUsers(AdminUserEntity operator, Long requestedCompanyId,
List<Long> userIds) {
ensureSuperAdminOperator(operator); ensureSuperAdminOperator(operator);
PermissionMenuEntity dataPermission = requireImageVideoDataPermission(); Long companyId = resolveScopeCompanyId(operator, requestedCompanyId);
PermissionMenuEntity dataPermission = requireImageVideoDataPermission(companyId);
List<Long> requestedIds = normalizeColumnIds(userIds); List<Long> requestedIds = normalizeColumnIds(userIds);
List<AdminUserEntity> users = adminUserMapper.selectList(grantableUserQuery()); List<AdminUserEntity> users = adminUserMapper.selectList(grantableUserQuery(companyId));
Map<Long, AdminUserEntity> grantableUsers = users.stream() Map<Long, AdminUserEntity> grantableUsers = users.stream()
.filter(user -> user.getId() != null && !isSuperAdmin(user)) .filter(user -> user.getId() != null && !isSuperAdmin(user))
.collect(Collectors.toMap(AdminUserEntity::getId, Function.identity(), (left, right) -> left)); .collect(Collectors.toMap(AdminUserEntity::getId, Function.identity(), (left, right) -> left));
@@ -448,15 +658,22 @@ public class PermissionMenuService {
} }
public List<ImageVideoDataPermissionUserVo> listShopDataCrawlDataPermissionUsers(AdminUserEntity operator) { public List<ImageVideoDataPermissionUserVo> listShopDataCrawlDataPermissionUsers(AdminUserEntity operator) {
return listShopDataCrawlDataPermissionUsers(operator, null);
}
/** 与视频任务那一路同口径:内部数据权限行与用户列表必须解析到同一家公司。 */
public List<ImageVideoDataPermissionUserVo> listShopDataCrawlDataPermissionUsers(AdminUserEntity operator,
Long requestedCompanyId) {
ensureSuperAdminOperator(operator, "店铺数据任务"); ensureSuperAdminOperator(operator, "店铺数据任务");
Long companyId = resolveScopeCompanyId(operator, requestedCompanyId);
PermissionMenuEntity dataPermission = requireDataPermission( PermissionMenuEntity dataPermission = requireDataPermission(
SHOP_DATA_CRAWL_DATA_PERMISSION_KEY, "店铺数据任务数据"); companyId, SHOP_DATA_CRAWL_DATA_PERMISSION_KEY, "店铺数据任务数据");
Set<Long> grantedUserIds = userColumnPermissionMapper.selectByColumnId(dataPermission.getId()) Set<Long> grantedUserIds = userColumnPermissionMapper.selectByColumnId(dataPermission.getId())
.stream() .stream()
.map(UserColumnPermissionEntity::getUserId) .map(UserColumnPermissionEntity::getUserId)
.filter(id -> id != null && id > 0) .filter(id -> id != null && id > 0)
.collect(Collectors.toSet()); .collect(Collectors.toSet());
return adminUserMapper.selectList(grantableUserQuery() return adminUserMapper.selectList(grantableUserQuery(companyId)
.orderByAsc(AdminUserEntity::getUsername) .orderByAsc(AdminUserEntity::getUsername)
.orderByAsc(AdminUserEntity::getId)) .orderByAsc(AdminUserEntity::getId))
.stream() .stream()
@@ -467,11 +684,18 @@ public class PermissionMenuService {
@Transactional @Transactional
public int updateShopDataCrawlDataPermissionUsers(AdminUserEntity operator, List<Long> userIds) { public int updateShopDataCrawlDataPermissionUsers(AdminUserEntity operator, List<Long> userIds) {
return updateShopDataCrawlDataPermissionUsers(operator, null, userIds);
}
@Transactional
public int updateShopDataCrawlDataPermissionUsers(AdminUserEntity operator, Long requestedCompanyId,
List<Long> userIds) {
ensureSuperAdminOperator(operator, "店铺数据任务"); ensureSuperAdminOperator(operator, "店铺数据任务");
Long companyId = resolveScopeCompanyId(operator, requestedCompanyId);
PermissionMenuEntity dataPermission = requireDataPermission( PermissionMenuEntity dataPermission = requireDataPermission(
SHOP_DATA_CRAWL_DATA_PERMISSION_KEY, "店铺数据任务数据"); companyId, SHOP_DATA_CRAWL_DATA_PERMISSION_KEY, "店铺数据任务数据");
List<Long> requestedIds = normalizeColumnIds(userIds); List<Long> requestedIds = normalizeColumnIds(userIds);
List<AdminUserEntity> users = adminUserMapper.selectList(grantableUserQuery()); List<AdminUserEntity> users = adminUserMapper.selectList(grantableUserQuery(companyId));
Map<Long, AdminUserEntity> grantableUsers = users.stream() Map<Long, AdminUserEntity> grantableUsers = users.stream()
.filter(user -> user.getId() != null && !isSuperAdmin(user)) .filter(user -> user.getId() != null && !isSuperAdmin(user))
.collect(Collectors.toMap(AdminUserEntity::getId, Function.identity(), (left, right) -> left)); .collect(Collectors.toMap(AdminUserEntity::getId, Function.identity(), (left, right) -> left));
@@ -505,12 +729,15 @@ public class PermissionMenuService {
if (isSuperAdmin(operator)) { if (isSuperAdmin(operator)) {
return; return;
} }
// 三行都按操作者本公司解析:换键之后同一个 key 每家公司各一行,
// 少带条件就是 LIMIT 1 跨公司借位(§4 里最危险的那处静默失效)。
Long companyId = operator.getCompanyId();
PermissionMenuEntity taskMenu = requireDataPermission( PermissionMenuEntity taskMenu = requireDataPermission(
"admin_shop_data_crawl_tasks", "店铺数据任务管理菜单"); companyId, "admin_shop_data_crawl_tasks", "店铺数据任务管理菜单");
PermissionMenuEntity duplicateCheckMenu = requireDataPermission( PermissionMenuEntity duplicateCheckMenu = requireDataPermission(
"admin_shop_data_duplicate_check", "店铺数据重复检查菜单"); companyId, "admin_shop_data_duplicate_check", "店铺数据重复检查菜单");
PermissionMenuEntity dataPermission = requireDataPermission( PermissionMenuEntity dataPermission = requireDataPermission(
SHOP_DATA_CRAWL_DATA_PERMISSION_KEY, "店铺数据任务数据"); companyId, SHOP_DATA_CRAWL_DATA_PERMISSION_KEY, "店铺数据任务数据");
boolean hasShopDataMenu = hasEffectiveColumnPermission(operator.getId(), taskMenu.getId()) boolean hasShopDataMenu = hasEffectiveColumnPermission(operator.getId(), taskMenu.getId())
|| hasEffectiveColumnPermission(operator.getId(), duplicateCheckMenu.getId()); || hasEffectiveColumnPermission(operator.getId(), duplicateCheckMenu.getId());
if (!hasShopDataMenu || !hasEffectiveColumnPermission(operator.getId(), dataPermission.getId())) { if (!hasShopDataMenu || !hasEffectiveColumnPermission(operator.getId(), dataPermission.getId())) {
@@ -532,7 +759,8 @@ public class PermissionMenuService {
if (isSuperAdmin(operator)) { if (isSuperAdmin(operator)) {
return; return;
} }
PermissionMenuEntity menu = requireDataPermission("admin_task_center", "客户端任务管理菜单"); PermissionMenuEntity menu = requireDataPermission(
operator.getCompanyId(), "admin_task_center", "客户端任务管理菜单");
if (!hasEffectiveColumnPermission(operator.getId(), menu.getId())) { if (!hasEffectiveColumnPermission(operator.getId(), menu.getId())) {
throw new BusinessException(403, "无权查看客户端任务管理"); throw new BusinessException(403, "无权查看客户端任务管理");
} }
@@ -549,7 +777,7 @@ public class PermissionMenuService {
if (isSuperAdmin(operator)) { if (isSuperAdmin(operator)) {
return true; return true;
} }
List<PermissionMenuEntity> menus = loadMenus(MENU_TYPE_ADMIN); List<PermissionMenuEntity> menus = loadMenus(operator.getCompanyId(), MENU_TYPE_ADMIN);
List<Long> wantedIds = menus.stream() List<Long> wantedIds = menus.stream()
.filter(menu -> menu.getColumnKey() != null && columnKeys.contains(menu.getColumnKey())) .filter(menu -> menu.getColumnKey() != null && columnKeys.contains(menu.getColumnKey()))
.map(PermissionMenuEntity::getId) .map(PermissionMenuEntity::getId)
@@ -606,8 +834,11 @@ public class PermissionMenuService {
AdminUserEntity target = getUserById(userId); AdminUserEntity target = getUserById(userId);
ensureTargetAccessible(operator, target); ensureTargetAccessible(operator, target);
List<Long> requestedIds = request == null ? List.of() : normalizeColumnIds(request.getColumnIds()); List<Long> requestedIds = request == null ? List.of() : normalizeColumnIds(request.getColumnIds());
// 整条链的归属口径 = 目标账号<b>自己那棵树</b>(不是操作者的):超管替德阳配权限时,
// 勾选与落库都必须指向德阳的菜单行 id,否则写进去的授权在本公司的树上认不出来。
Long targetCompanyId = target.getCompanyId();
// 出口 3(提交授权):超管专属项在这里被剥掉,越权校验与落库都看不到它(剥而不拒)。 // 出口 3(提交授权):超管专属项在这里被剥掉,越权校验与落库都看不到它(剥而不拒)。
requestedIds = stripSuperAdminOnlyGrantIds(requestedIds, operator); requestedIds = stripSuperAdminOnlyGrantIds(requestedIds, operator, targetCompanyId);
String normalizedType = menuType == null || menuType.isBlank() String normalizedType = menuType == null || menuType.isBlank()
? null ? null
: normalizeMenuTypeRequired(menuType); : normalizeMenuTypeRequired(menuType);
@@ -616,13 +847,14 @@ public class PermissionMenuService {
if (normalizedType == null) { if (normalizedType == null) {
if (!requestedIds.isEmpty()) { if (!requestedIds.isEmpty()) {
Long validCount = permissionMenuMapper.selectCount(new LambdaQueryWrapper<PermissionMenuEntity>() Long validCount = permissionMenuMapper.selectCount(new LambdaQueryWrapper<PermissionMenuEntity>()
.eq(PermissionMenuEntity::getCompanyId, targetCompanyId)
.in(PermissionMenuEntity::getId, requestedIds)); .in(PermissionMenuEntity::getId, requestedIds));
if (validCount == null || validCount != requestedIds.size()) { if (validCount == null || validCount != requestedIds.size()) {
throw new BusinessException("存在无效的菜单权限项"); throw new BusinessException("存在无效的菜单权限项");
} }
} }
} else { } else {
scopedMenuIds.addAll(loadMenus(normalizedType).stream() scopedMenuIds.addAll(loadMenus(targetCompanyId, normalizedType).stream()
.map(PermissionMenuEntity::getId) .map(PermissionMenuEntity::getId)
.filter(Objects::nonNull) .filter(Objects::nonNull)
.toList()); .toList());
@@ -633,9 +865,9 @@ public class PermissionMenuService {
Set<Long> protectedIds = new LinkedHashSet<>(); Set<Long> protectedIds = new LinkedHashSet<>();
if (normalizedType == null) { if (normalizedType == null) {
PermissionMenuEntity imageVideoDataPermission = findImageVideoDataPermission(); PermissionMenuEntity imageVideoDataPermission = findImageVideoDataPermission(targetCompanyId);
PermissionMenuEntity shopDataCrawlDataPermission = PermissionMenuEntity shopDataCrawlDataPermission =
findDataPermission(SHOP_DATA_CRAWL_DATA_PERMISSION_KEY); findDataPermission(targetCompanyId, SHOP_DATA_CRAWL_DATA_PERMISSION_KEY);
if (imageVideoDataPermission != null && imageVideoDataPermission.getId() != null) { if (imageVideoDataPermission != null && imageVideoDataPermission.getId() != null) {
protectedIds.add(imageVideoDataPermission.getId()); protectedIds.add(imageVideoDataPermission.getId());
} }
@@ -686,7 +918,8 @@ public class PermissionMenuService {
userColumnPermissionMapper.insert(entity); userColumnPermissionMapper.insert(entity);
} }
if (MENU_TYPE_ADMIN.equals(normalizedType)) { if (MENU_TYPE_ADMIN.equals(normalizedType)) {
autoGrantShopDataDataPermission(userId, finalGrantIds, loadMenus(MENU_TYPE_ADMIN)); autoGrantShopDataDataPermission(userId, finalGrantIds,
loadMenus(targetCompanyId, MENU_TYPE_ADMIN), targetCompanyId);
} }
// 目标管理员的权限被回收后,其直接创建的员工若仍持有超出范围的 // 目标管理员的权限被回收后,其直接创建的员工若仍持有超出范围的
@@ -712,13 +945,13 @@ public class PermissionMenuService {
* 只增不删:数据授权的回收仍走超管专用的「数据范围授权」UI。 * 只增不删:数据授权的回收仍走超管专用的「数据范围授权」UI。
*/ */
private void autoGrantShopDataDataPermission(Long userId, Set<Long> directGrantIds, private void autoGrantShopDataDataPermission(Long userId, Set<Long> directGrantIds,
List<PermissionMenuEntity> adminMenus) { List<PermissionMenuEntity> adminMenus, Long companyId) {
if (directGrantIds.isEmpty() || adminMenus.isEmpty()) { if (directGrantIds.isEmpty() || adminMenus.isEmpty()) {
return; return;
} }
PermissionMenuEntity taskMenu = findDataPermission("admin_shop_data_crawl_tasks"); PermissionMenuEntity taskMenu = findDataPermission(companyId, "admin_shop_data_crawl_tasks");
PermissionMenuEntity duplicateCheckMenu = findDataPermission("admin_shop_data_duplicate_check"); PermissionMenuEntity duplicateCheckMenu = findDataPermission(companyId, "admin_shop_data_duplicate_check");
PermissionMenuEntity dataPermission = findDataPermission(SHOP_DATA_CRAWL_DATA_PERMISSION_KEY); PermissionMenuEntity dataPermission = findDataPermission(companyId, SHOP_DATA_CRAWL_DATA_PERMISSION_KEY);
if (dataPermission == null || dataPermission.getId() == null) { if (dataPermission == null || dataPermission.getId() == null) {
return; return;
} }
@@ -755,12 +988,16 @@ public class PermissionMenuService {
if (target == null || target.getId() == null || isSuperAdmin(target)) { if (target == null || target.getId() == null || isSuperAdmin(target)) {
return; return;
} }
Long companyId = target.getCompanyId();
Set<Long> targetEffectiveIds = expandDescendantIds( Set<Long> targetEffectiveIds = expandDescendantIds(
new LinkedHashSet<>(loadDirectColumnIds(target.getId())), loadMenus(null)); new LinkedHashSet<>(loadDirectColumnIds(target.getId())), loadMenus(companyId, null));
// 只用到 id:不要为一次级联清理把整表(含密码哈希)拉回 // 只用到 id:不要为一次级联清理把整表(含密码哈希)拉回。
// 下属集要同时按公司筛:这段是批量删除,一旦 created_by 出现跨公司的脏数据,
// "越权"判定就会拿 A 家的有效集去删 B 家员工的授权——删多隔离比删少更贵。
List<AdminUserEntity> subordinates = adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>() List<AdminUserEntity> subordinates = adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>()
.select(AdminUserEntity::getId) .select(AdminUserEntity::getId)
.eq(AdminUserEntity::getCreatedById, target.getId())); .eq(AdminUserEntity::getCreatedById, target.getId())
.eq(companyId != null, AdminUserEntity::getCompanyId, companyId));
for (AdminUserEntity subordinate : subordinates) { for (AdminUserEntity subordinate : subordinates) {
Long subordinateId = subordinate.getId(); Long subordinateId = subordinate.getId();
if (subordinateId == null || subordinateId.equals(target.getId())) { if (subordinateId == null || subordinateId.equals(target.getId())) {
@@ -782,8 +1019,14 @@ public class PermissionMenuService {
} }
} }
private List<PermissionMenuEntity> loadMenus(String menuType) { /**
List<PermissionMenuEntity> rows = loadRawMenus(menuType); * 目录取数的唯一出口(§4):{@code companyId} 非空时只返回那一棵树的行。
* 授权树、有效菜单、可授予全集、越权判定都从这里取数,所以公司收窄改这一处就够一片。
*
* @param companyId null 只来自「无操作者 / 无归属」的历史与测试路径,此时退回全量目录
*/
private List<PermissionMenuEntity> loadMenus(Long companyId, String menuType) {
List<PermissionMenuEntity> rows = loadRawMenus(companyId, menuType);
if (rows == null || rows.isEmpty()) { if (rows == null || rows.isEmpty()) {
return List.of(); return List.of();
} }
@@ -794,13 +1037,14 @@ public class PermissionMenuService {
} }
/** /**
* Fetches every menu (optionally scoped to one type) in insertion order. * Fetches every menu (optionally scoped to one company and one type) in insertion order.
* Sorting happens in {@link #loadMenus(String)} and only for hierarchies * Sorting happens in {@link #loadMenus(Long, String)} and only for hierarchies
* that actually need one, keeping raw SQL and comparator semantics in sync. * that actually need one, keeping raw SQL and comparator semantics in sync.
*/ */
private List<PermissionMenuEntity> loadRawMenus(String menuType) { private List<PermissionMenuEntity> loadRawMenus(Long companyId, String menuType) {
String normalizedType = normalizeMenuType(menuType); String normalizedType = normalizeMenuType(menuType);
LambdaQueryWrapper<PermissionMenuEntity> query = new LambdaQueryWrapper<PermissionMenuEntity>() LambdaQueryWrapper<PermissionMenuEntity> query = new LambdaQueryWrapper<PermissionMenuEntity>()
.eq(companyId != null, PermissionMenuEntity::getCompanyId, companyId)
.eq(normalizedType != null, PermissionMenuEntity::getMenuType, normalizedType) .eq(normalizedType != null, PermissionMenuEntity::getMenuType, normalizedType)
.orderByAsc(PermissionMenuEntity::getSortOrder) .orderByAsc(PermissionMenuEntity::getSortOrder)
.orderByAsc(PermissionMenuEntity::getId); .orderByAsc(PermissionMenuEntity::getId);
@@ -1006,11 +1250,12 @@ public class PermissionMenuService {
* 唯一例外是超管且 menuType 为空的「整树替换」分支:{@code deleteByUserId} 先清空目标整个 * 唯一例外是超管且 menuType 为空的「整树替换」分支:{@code deleteByUserId} 先清空目标整个
* 分区再按提交重插,被剥的这条按既有语义就不会回来——那是该分支本来就有的行为,不是剥离引入的。 * 分区再按提交重插,被剥的这条按既有语义就不会回来——那是该分支本来就有的行为,不是剥离引入的。
*/ */
private List<Long> stripSuperAdminOnlyGrantIds(List<Long> requestedIds, AdminUserEntity operator) { private List<Long> stripSuperAdminOnlyGrantIds(List<Long> requestedIds, AdminUserEntity operator,
Long companyId) {
if (requestedIds.isEmpty()) { if (requestedIds.isEmpty()) {
return requestedIds; return requestedIds;
} }
Set<Long> restricted = superAdminOnlyMenuIds(); Set<Long> restricted = superAdminOnlyMenuIds(companyId);
if (restricted.isEmpty()) { if (restricted.isEmpty()) {
return requestedIds; return requestedIds;
} }
@@ -1029,8 +1274,12 @@ public class PermissionMenuService {
* <p>一次全量目录查询折出来,绝不按 id 逐条点查:保存权限这个入口上 N 次点查会被日志放大, * <p>一次全量目录查询折出来,绝不按 id 逐条点查:保存权限这个入口上 N 次点查会被日志放大,
* 而 {@code findDataPermission} 每次都是一个 {@code selectOne}。</p> * 而 {@code findDataPermission} 每次都是一个 {@code selectOne}。</p>
*/ */
private Set<Long> superAdminOnlyMenuIds() { /**
return loadMenus(null).stream() * <p>V149 之后这行闸门菜单只存在于公司 1 的树里(§2 D3:副本不复制它),所以别家公司
* 拿到的是空集——那里的提交里本来就不可能有它,剥离逻辑照常走完,不多一条分支。</p>
*/
private Set<Long> superAdminOnlyMenuIds(Long companyId) {
return loadMenus(companyId, null).stream()
.filter(menu -> SUPER_ADMIN_ONLY_KEYS.contains(menu.getColumnKey())) .filter(menu -> SUPER_ADMIN_ONLY_KEYS.contains(menu.getColumnKey()))
.map(PermissionMenuEntity::getId) .map(PermissionMenuEntity::getId)
.collect(Collectors.toCollection(LinkedHashSet::new)); .collect(Collectors.toCollection(LinkedHashSet::new));
@@ -1073,12 +1322,12 @@ public class PermissionMenuService {
return !Integer.valueOf(1).equals(user.getIsAdmin()); return !Integer.valueOf(1).equals(user.getIsAdmin());
} }
private PermissionMenuEntity findImageVideoDataPermission() { private PermissionMenuEntity findImageVideoDataPermission(Long companyId) {
return findDataPermission(IMAGE_VIDEO_DATA_PERMISSION_KEY); return findDataPermission(companyId, IMAGE_VIDEO_DATA_PERMISSION_KEY);
} }
private PermissionMenuEntity requireImageVideoDataPermission() { private PermissionMenuEntity requireImageVideoDataPermission(Long companyId) {
PermissionMenuEntity permission = findImageVideoDataPermission(); PermissionMenuEntity permission = findImageVideoDataPermission(companyId);
if (permission == null || permission.getId() == null) { if (permission == null || permission.getId() == null) {
throw new BusinessException("视频任务数据权限尚未初始化"); throw new BusinessException("视频任务数据权限尚未初始化");
} }
@@ -1099,14 +1348,20 @@ public class PermissionMenuService {
} }
} }
private PermissionMenuEntity findDataPermission(String columnKey) { /**
* 按 key 点查一行菜单。<b>必须带公司</b>:V149 之后同一个 key 在每家公司各有一行,
* 少了这个条件就是 {@code LIMIT 1} 跨公司借位——拿到别家的行 id 再往本账号身上写一条
* 本公司树里认不出的授权,页面显示"已授权"、权限却永远不生效,且不报任何错。
*/
private PermissionMenuEntity findDataPermission(Long companyId, String columnKey) {
return permissionMenuMapper.selectOne(new LambdaQueryWrapper<PermissionMenuEntity>() return permissionMenuMapper.selectOne(new LambdaQueryWrapper<PermissionMenuEntity>()
.eq(companyId != null, PermissionMenuEntity::getCompanyId, companyId)
.eq(PermissionMenuEntity::getColumnKey, columnKey) .eq(PermissionMenuEntity::getColumnKey, columnKey)
.last("LIMIT 1")); .last("LIMIT 1"));
} }
private PermissionMenuEntity requireDataPermission(String columnKey, String displayName) { private PermissionMenuEntity requireDataPermission(Long companyId, String columnKey, String displayName) {
PermissionMenuEntity permission = findDataPermission(columnKey); PermissionMenuEntity permission = findDataPermission(companyId, columnKey);
if (permission == null || permission.getId() == null) { if (permission == null || permission.getId() == null) {
throw new BusinessException(displayName + "权限尚未初始化"); throw new BusinessException(displayName + "权限尚未初始化");
} }
@@ -1126,7 +1381,7 @@ public class PermissionMenuService {
return vo; return vo;
} }
private void ensureParentValid(Long parentId, Long currentId, String menuType) { private void ensureParentValid(Long companyId, Long parentId, Long currentId, String menuType) {
if (parentId == null) { if (parentId == null) {
return; return;
} }
@@ -1151,6 +1406,11 @@ public class PermissionMenuService {
if (currentId != null && currentId.equals(cursor.getId())) { if (currentId != null && currentId.equals(cursor.getId())) {
throw new BusinessException("父级菜单不能选择自己的子级"); throw new BusinessException("父级菜单不能选择自己的子级");
} }
// fk_columns_parent_id 只保证父行存在,挡不住跨公司挂父(§3.6),同公司判定只能做在这里。
// 整条祖先链都判:一个同公司的父、上面挂着别家的分组,落库后这行在两棵树里都渲染不出。
if (companyId != null && !companyId.equals(cursor.getCompanyId())) {
throw new BusinessException("父级菜单必须与当前菜单属于同一公司");
}
Long ancestorId = cursor.getParentId(); Long ancestorId = cursor.getParentId();
if (ancestorId == null) { if (ancestorId == null) {
break; break;
@@ -1173,8 +1433,10 @@ public class PermissionMenuService {
} }
} }
private void ensureUniqueColumnKey(String columnKey, Long excludeId) { /** 查重范围 = 本公司(与 {@code uk_company_column_key} 同一条键)。不加条件会拿别家的副本误报"已存在"。 */
private void ensureUniqueColumnKey(Long companyId, String columnKey, Long excludeId) {
PermissionMenuEntity exists = permissionMenuMapper.selectOne(new LambdaQueryWrapper<PermissionMenuEntity>() PermissionMenuEntity exists = permissionMenuMapper.selectOne(new LambdaQueryWrapper<PermissionMenuEntity>()
.eq(companyId != null, PermissionMenuEntity::getCompanyId, companyId)
.eq(PermissionMenuEntity::getColumnKey, columnKey) .eq(PermissionMenuEntity::getColumnKey, columnKey)
.last("LIMIT 1")); .last("LIMIT 1"));
if (exists != null && (excludeId == null || !excludeId.equals(exists.getId()))) { if (exists != null && (excludeId == null || !excludeId.equals(exists.getId()))) {
@@ -1182,8 +1444,10 @@ public class PermissionMenuService {
} }
} }
private void ensureUniqueRoutePath(String menuType, String routePath, Long excludeId) { /** 同上,对应 {@code uk_company_menu_type_route_path}。 */
private void ensureUniqueRoutePath(Long companyId, String menuType, String routePath, Long excludeId) {
PermissionMenuEntity exists = permissionMenuMapper.selectOne(new LambdaQueryWrapper<PermissionMenuEntity>() PermissionMenuEntity exists = permissionMenuMapper.selectOne(new LambdaQueryWrapper<PermissionMenuEntity>()
.eq(companyId != null, PermissionMenuEntity::getCompanyId, companyId)
.eq(PermissionMenuEntity::getMenuType, menuType) .eq(PermissionMenuEntity::getMenuType, menuType)
.eq(PermissionMenuEntity::getRoutePath, routePath) .eq(PermissionMenuEntity::getRoutePath, routePath)
.last("LIMIT 1")); .last("LIMIT 1"));
@@ -1297,7 +1561,7 @@ public class PermissionMenuService {
} }
private PermissionMenuItemVo toItemVo(PermissionMenuEntity entity) { private PermissionMenuItemVo toItemVo(PermissionMenuEntity entity) {
return toItemVos(List.of(entity), loadMenus(entity.getMenuType())).getFirst(); return toItemVos(List.of(entity), loadMenus(entity.getCompanyId(), entity.getMenuType())).getFirst();
} }
private PermissionMenuItemVo toItemVo(PermissionMenuEntity entity, private PermissionMenuItemVo toItemVo(PermissionMenuEntity entity,
@@ -1333,14 +1597,16 @@ public class PermissionMenuService {
/** /**
* Resolves the default sort order when none is supplied, scoped to the * Resolves the default sort order when none is supplied, scoped to the
* menu's own type (parent takes precedence, then hierarchy ancestors). * menu's own type (parent takes precedence, then hierarchy ancestors).
* The DB query mirrors {@link #loadMenus(String)} ordering so the last row * The DB query mirrors {@link #loadMenus(Long, String)} ordering so the last row
* is the true tail of the type's ordering. * is the true tail of the type's ordering, and the same company the new row lands in
* (两棵树的 sort_order 各排各的,跨公司取 MAX 会让两排同名菜单交织)。
*/ */
private Integer resolveSortOrder(String menuType, Integer sortOrder, Long excludeId) { private Integer resolveSortOrder(Long companyId, String menuType, Integer sortOrder, Long excludeId) {
if (sortOrder != null) { if (sortOrder != null) {
return sortOrder; return sortOrder;
} }
PermissionMenuEntity tail = permissionMenuMapper.selectOne(new LambdaQueryWrapper<PermissionMenuEntity>() PermissionMenuEntity tail = permissionMenuMapper.selectOne(new LambdaQueryWrapper<PermissionMenuEntity>()
.eq(companyId != null, PermissionMenuEntity::getCompanyId, companyId)
.eq(PermissionMenuEntity::getMenuType, normalizeMenuType(menuType)) .eq(PermissionMenuEntity::getMenuType, normalizeMenuType(menuType))
.ne(excludeId != null, PermissionMenuEntity::getId, excludeId) .ne(excludeId != null, PermissionMenuEntity::getId, excludeId)
.orderByDesc(PermissionMenuEntity::getSortOrder) .orderByDesc(PermissionMenuEntity::getSortOrder)
@@ -1,8 +1,6 @@
package com.nanri.aiimage.modules.productcategory.controller; package com.nanri.aiimage.modules.productcategory.controller;
import com.nanri.aiimage.common.api.ApiResponse; import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.common.util.DownloadHeaderUtil; import com.nanri.aiimage.common.util.DownloadHeaderUtil;
import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.productcategory.model.dto.ProductCategorySaveRequest; import com.nanri.aiimage.modules.productcategory.model.dto.ProductCategorySaveRequest;
@@ -10,7 +8,6 @@ import com.nanri.aiimage.modules.productcategory.model.vo.ProductCategoryItemVo;
import com.nanri.aiimage.modules.productcategory.model.vo.ProductCategoryListVo; import com.nanri.aiimage.modules.productcategory.model.vo.ProductCategoryListVo;
import com.nanri.aiimage.modules.productcategory.service.ProductCategoryService; import com.nanri.aiimage.modules.productcategory.service.ProductCategoryService;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid; import jakarta.validation.Valid;
@@ -34,24 +31,21 @@ import java.time.format.DateTimeFormatter;
@RestController @RestController
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/api/admin") @RequestMapping("/api/admin")
@Tag(name = "商品类目管理", description = "维护商品类目树") @Tag(name = "商品类目管理", description = "维护商品类目树(全平台共享,不按公司区分)")
public class ProductCategoryController { public class ProductCategoryController {
private static final DateTimeFormatter EXPORT_FILENAME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"); private static final DateTimeFormatter EXPORT_FILENAME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
private final ProductCategoryService productCategoryService; private final ProductCategoryService productCategoryService;
private final AdminAuthSupport adminAuthSupport; private final AdminAuthSupport adminAuthSupport;
private final DataReadScope dataReadScope;
@GetMapping("/product-categories") @GetMapping("/product-categories")
@Operation(summary = "查询商品类目树") @Operation(summary = "查询商品类目树")
public ApiResponse<ProductCategoryListVo> list( public ApiResponse<ProductCategoryListVo> list(
HttpServletRequest request, HttpServletRequest request,
@RequestParam(value = "keyword", required = false) String keyword, @RequestParam(value = "keyword", required = false) String keyword) {
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) { adminAuthSupport.requireAdminOrInternal(request);
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request); return ApiResponse.success(productCategoryService.list(keyword));
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId);
return ApiResponse.success(productCategoryService.list(keyword, scopedCompanyId));
} }
@GetMapping("/product-categories/children") @GetMapping("/product-categories/children")
@@ -60,11 +54,9 @@ public class ProductCategoryController {
HttpServletRequest request, HttpServletRequest request,
@RequestParam(value = "parent_id", required = false) Long parentId, @RequestParam(value = "parent_id", required = false) Long parentId,
@RequestParam(value = "page", defaultValue = "1") Long page, @RequestParam(value = "page", defaultValue = "1") Long page,
@RequestParam(value = "page_size", defaultValue = "20") Long pageSize, @RequestParam(value = "page_size", defaultValue = "20") Long pageSize) {
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) { adminAuthSupport.requireAdminOrInternal(request);
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request); return ApiResponse.success(productCategoryService.children(parentId, page, pageSize));
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId);
return ApiResponse.success(productCategoryService.children(parentId, page, pageSize, scopedCompanyId));
} }
@GetMapping("/product-categories/search") @GetMapping("/product-categories/search")
@@ -73,22 +65,18 @@ public class ProductCategoryController {
HttpServletRequest request, HttpServletRequest request,
@RequestParam(value = "keyword", required = false) String keyword, @RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "page", defaultValue = "1") Long page, @RequestParam(value = "page", defaultValue = "1") Long page,
@RequestParam(value = "page_size", defaultValue = "20") Long pageSize, @RequestParam(value = "page_size", defaultValue = "20") Long pageSize) {
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) { adminAuthSupport.requireAdminOrInternal(request);
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request); return ApiResponse.success(productCategoryService.search(keyword, page, pageSize));
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId);
return ApiResponse.success(productCategoryService.search(keyword, page, pageSize, scopedCompanyId));
} }
@GetMapping("/product-categories/export") @GetMapping("/product-categories/export")
@Operation(summary = "导出商品类目") @Operation(summary = "导出商品类目")
public ResponseEntity<byte[]> export( public ResponseEntity<byte[]> export(
HttpServletRequest request, HttpServletRequest request,
@RequestParam(value = "keyword", required = false) String keyword, @RequestParam(value = "keyword", required = false) String keyword) {
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) { adminAuthSupport.requireAdminOrInternal(request);
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request); byte[] bytes = productCategoryService.export(keyword);
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId);
byte[] bytes = productCategoryService.export(keyword, scopedCompanyId);
String filename = "product-categories-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER) + ".xlsx"; String filename = "product-categories-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER) + ".xlsx";
return ResponseEntity.ok() return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, DownloadHeaderUtil.contentDisposition(filename)) .header(HttpHeaders.CONTENT_DISPOSITION, DownloadHeaderUtil.contentDisposition(filename))
@@ -102,10 +90,8 @@ public class ProductCategoryController {
public ApiResponse<ProductCategoryItemVo> create( public ApiResponse<ProductCategoryItemVo> create(
HttpServletRequest request, HttpServletRequest request,
@Valid @RequestBody ProductCategorySaveRequest body) { @Valid @RequestBody ProductCategorySaveRequest body) {
// 归属只从会话推(请求体一律不带 company_id):service 里 requireCompanyId 取不到就抛, adminAuthSupport.requireAdminOrInternal(request);
// 不让 V147 的 DEFAULT 1 静默兜住。 return ApiResponse.success("创建成功", productCategoryService.create(body));
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
return ApiResponse.success("创建成功", productCategoryService.create(body, operator.getId()));
} }
@PutMapping("/product-category/{id}") @PutMapping("/product-category/{id}")
@@ -114,10 +100,8 @@ public class ProductCategoryController {
HttpServletRequest request, HttpServletRequest request,
@PathVariable Long id, @PathVariable Long id,
@Valid @RequestBody ProductCategorySaveRequest body) { @Valid @RequestBody ProductCategorySaveRequest body) {
// 写侧闸门与读侧同源:读已经收窄到本公司,写不收窄就是"藏起来的行照样能删"。 adminAuthSupport.requireAdminOrInternal(request);
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request); return ApiResponse.success("保存成功", productCategoryService.update(id, body));
return ApiResponse.success("保存成功",
productCategoryService.update(id, body, dataReadScope.writeCompanyId(operator)));
} }
@DeleteMapping("/product-category/{id}") @DeleteMapping("/product-category/{id}")
@@ -125,8 +109,8 @@ public class ProductCategoryController {
public ApiResponse<Void> delete( public ApiResponse<Void> delete(
HttpServletRequest request, HttpServletRequest request,
@PathVariable Long id) { @PathVariable Long id) {
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request); adminAuthSupport.requireAdminOrInternal(request);
productCategoryService.delete(id, dataReadScope.writeCompanyId(operator)); productCategoryService.delete(id);
return ApiResponse.success("删除成功", null); return ApiResponse.success("删除成功", null);
} }
} }
@@ -7,20 +7,19 @@ import lombok.Data;
import java.time.LocalDateTime; import java.time.LocalDateTime;
/**
* 商品类目——<b>全平台共享的一棵树,不按公司区分</b>(控制方 2026-10-06 定案)。
*
* <p>所以这里<b>不声明</b> {@code company_id} 字段。库里那一列(V147 加的,带临时 {@code DEFAULT 1})
* 暂时还在,但没有任何读写路径引用它:不声明字段 ⇒ MyBatis-Plus 的 SELECT 列清单与 INSERT 都不含它
* ⇒ 新 jar 配旧库(列还在)不会报错,摘列则必须等两台都跑上这一版(见 migration-inventory 的下一版待办)。</p>
*/
@Data @Data
@TableName("biz_product_category") @TableName("biz_product_category")
public class ProductCategoryEntity { public class ProductCategoryEntity {
@TableId(type = IdType.AUTO) @TableId(type = IdType.AUTO)
private Long id; private Long id;
/**
* 归属公司(V147)。{@code 0} = 平台内置共享节点(不是 company 表里的行),其余是那一家的自建节点。
*
* <p>写侧必须显式盖章:这一列在 V147 里带着<b>临时</b>的 {@code DEFAULT 1}(旧 jar 的实体没这字段),
* 漏传不会报错、会被静默塞进厦门米椿花。{@code ProductCategoryService.create} 因此走
* {@code CompanyScopeSupport.requireCompanyId}(取不到就抛),不依赖这一默认值。</p>
*/
private Long companyId;
private Long parentId; private Long parentId;
private String name; private String name;
private String categoryKey; private String categoryKey;
@@ -4,7 +4,6 @@ import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException; import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.modules.productcategory.mapper.ProductCategoryMapper; import com.nanri.aiimage.modules.productcategory.mapper.ProductCategoryMapper;
import com.nanri.aiimage.modules.productcategory.model.dto.ProductCategorySaveRequest; import com.nanri.aiimage.modules.productcategory.model.dto.ProductCategorySaveRequest;
import com.nanri.aiimage.modules.productcategory.model.entity.ProductCategoryEntity; import com.nanri.aiimage.modules.productcategory.model.entity.ProductCategoryEntity;
@@ -28,6 +27,7 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.function.Function;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -35,109 +35,71 @@ public class ProductCategoryService {
private static final DateTimeFormatter EXPORT_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); private static final DateTimeFormatter EXPORT_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/**
* 内置节点的哨兵归属(V147 回填):它不是公司表里的行,而是"所有公司都看得见、谁都不拥有"的那半棵树。
*
* <p>取 0 是因为 {@code company.id} 从 1 起自增,而 {@code CompanyScopeSupport.requireCompanyId}
* 对 {@code <= 0} 直接抛 ⇒ 没有任何账号会被登记成 0 号公司,这个值和真实公司永不撞。</p>
*/
static final long SHARED_BUILTIN_COMPANY_ID = 0L;
private final ProductCategoryMapper productCategoryMapper; private final ProductCategoryMapper productCategoryMapper;
private final CompanyScopeSupport companyScopeSupport;
/** /**
* 全平台类目树——<b>不按公司筛,且不许改成按公司筛</b>。 * 全平台一棵树——<b>不按公司筛,且不许改成按公司筛</b>(控制方 2026-10-06 定案:商品类目共享、不区分)。
* *
* <p>唯一的消费者是货源/外观的类目归类({@code SimilarAsinLlmService:215 CategoryTree.load(list())})。 * <p>两个消费者共用它:后台这一页,以及货源/外观的类目归类
* 那一侧按公司切会同时改两件事:候选节点变少(分类结果按公司分叉)与 prompt 里的类目表变化(影响 LLM 成本)。 * ({@code SimilarAsinLlmService:215 CategoryTree.load(list())})。后者若按公司切会同时改两件事:
* 后台的公司 tab 走 {@link #list(String, Long)},两件事别混。</p> * 候选节点变少(分类结果按公司分叉)与 prompt 里的类目表变化(影响 LLM 成本)。</p>
*/ */
public ProductCategoryListVo list() { public ProductCategoryListVo list() {
return list(null); return list(null);
} }
/** 不筛公司(超管没选 tab 时的口径,与改造前一致)。 */
public ProductCategoryListVo list(String keyword) { public ProductCategoryListVo list(String keyword) {
return list(keyword, null); List<ProductCategoryEntity> rows = productCategoryMapper.selectList(
}
/**
* @param companyId 要收窄到的公司;null = 不筛。内置节点({@value #SHARED_BUILTIN_COMPANY_ID})
* 在任何公司的视图里都可见,否则第 2 家的类目树会是空的、连一个自建根都挂不上。
*/
public ProductCategoryListVo list(String keyword, Long companyId) {
List<ProductCategoryEntity> rows = productCategoryMapper.selectList(applyCompanyScope(
new LambdaQueryWrapper<ProductCategoryEntity>() new LambdaQueryWrapper<ProductCategoryEntity>()
.orderByAsc(ProductCategoryEntity::getParentId) .orderByAsc(ProductCategoryEntity::getParentId)
.orderByAsc(ProductCategoryEntity::getSortOrder) .orderByAsc(ProductCategoryEntity::getSortOrder)
.orderByAsc(ProductCategoryEntity::getId), .orderByAsc(ProductCategoryEntity::getId));
companyId));
rows = filterRowsByKeyword(rows, keyword); rows = filterRowsByKeyword(rows, keyword);
return buildListVo(rows); return buildListVo(rows);
} }
public ProductCategoryListVo children(Long parentId, long page, long pageSize) { public ProductCategoryListVo children(Long parentId, long page, long pageSize) {
return children(parentId, page, pageSize, null);
}
public ProductCategoryListVo children(Long parentId, long page, long pageSize, Long companyId) {
long safePage = Math.max(page, 1); long safePage = Math.max(page, 1);
long safePageSize = normalizePageSize(pageSize); long safePageSize = normalizePageSize(pageSize);
Long normalizedParentId = normalizeParentId(parentId); Long normalizedParentId = normalizeParentId(parentId);
LambdaQueryWrapper<ProductCategoryEntity> countQuery = applyCompanyScope(new LambdaQueryWrapper<>(), companyId); LambdaQueryWrapper<ProductCategoryEntity> countQuery = new LambdaQueryWrapper<>();
applyParentFilter(countQuery, normalizedParentId); applyParentFilter(countQuery, normalizedParentId);
Long total = productCategoryMapper.selectCount(countQuery); Long total = productCategoryMapper.selectCount(countQuery);
LambdaQueryWrapper<ProductCategoryEntity> pageQuery = applyCompanyScope( LambdaQueryWrapper<ProductCategoryEntity> pageQuery = new LambdaQueryWrapper<ProductCategoryEntity>()
new LambdaQueryWrapper<ProductCategoryEntity>() .orderByAsc(ProductCategoryEntity::getSortOrder)
.orderByAsc(ProductCategoryEntity::getSortOrder) .orderByAsc(ProductCategoryEntity::getId)
.orderByAsc(ProductCategoryEntity::getId),
companyId)
.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize); .last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize);
applyParentFilter(pageQuery, normalizedParentId); applyParentFilter(pageQuery, normalizedParentId);
List<ProductCategoryEntity> rows = productCategoryMapper.selectList(pageQuery); List<ProductCategoryEntity> rows = productCategoryMapper.selectList(pageQuery);
return buildPageVo(rows, total, safePage, safePageSize, companyId); return buildPageVo(rows, total, safePage, safePageSize);
} }
public ProductCategoryListVo search(String keyword, long page, long pageSize) { public ProductCategoryListVo search(String keyword, long page, long pageSize) {
return search(keyword, page, pageSize, null);
}
public ProductCategoryListVo search(String keyword, long page, long pageSize, Long companyId) {
String normalized = normalizeSearchKeyword(keyword); String normalized = normalizeSearchKeyword(keyword);
if (normalized.isBlank()) { if (normalized.isBlank()) {
return emptyPageVo(Math.max(page, 1), normalizePageSize(pageSize)); return emptyPageVo(Math.max(page, 1), normalizePageSize(pageSize));
} }
long safePage = Math.max(page, 1); long safePage = Math.max(page, 1);
long safePageSize = normalizePageSize(pageSize); long safePageSize = normalizePageSize(pageSize);
Long total = productCategoryMapper.selectCount(buildSearchQuery(normalized, companyId)); Long total = productCategoryMapper.selectCount(buildSearchQuery(normalized));
List<ProductCategoryEntity> rows = productCategoryMapper.selectList(buildSearchQuery(normalized, companyId) List<ProductCategoryEntity> rows = productCategoryMapper.selectList(buildSearchQuery(normalized)
.orderByAsc(ProductCategoryEntity::getParentId) .orderByAsc(ProductCategoryEntity::getParentId)
.orderByAsc(ProductCategoryEntity::getSortOrder) .orderByAsc(ProductCategoryEntity::getSortOrder)
.orderByAsc(ProductCategoryEntity::getId) .orderByAsc(ProductCategoryEntity::getId)
.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize)); .last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize));
return buildSearchPageVo(rows, total, safePage, safePageSize, companyId); return buildSearchPageVo(rows, total, safePage, safePageSize);
} }
/** /** 新建的类目落进全平台共享的那一棵树:谁建的都不记归属,只保证同级不重名。 */
* 归属由<b>操作者会话</b>推导(请求体/查询参数一律不带 company_id):漏了这一句,新类目就会被
* V147 的 {@code DEFAULT 1} 静默塞进厦门米椿花——那是"归属失真且不报错",而 {@code requireCompanyId}
* 取不到公司时是抛,不会返回 null。所以这里<b>不保留</b>不带操作者的重载:留着它等于留着一个
* "调用方忘了传也照样绿"的出口。
*
* @param operatorId 操作者账号 id
*/
@Transactional @Transactional
public ProductCategoryItemVo create(ProductCategorySaveRequest request, Long operatorId) { public ProductCategoryItemVo create(ProductCategorySaveRequest request) {
String name = normalizeRequired(request.getName(), "类目名称不能为空"); String name = normalizeRequired(request.getName(), "类目名称不能为空");
Long parentId = normalizeParentId(request.getParentId()); Long parentId = normalizeParentId(request.getParentId());
Long companyId = companyScopeSupport.requireCompanyId(operatorId); ensureParentVisible(parentId, null);
ensureParentVisible(parentId, null, companyId); ensureSiblingNameUnique(parentId, name, null);
ensureSiblingNameUnique(parentId, name, null, companyId);
ProductCategoryEntity entity = new ProductCategoryEntity(); ProductCategoryEntity entity = new ProductCategoryEntity();
entity.setCompanyId(companyId);
entity.setParentId(parentId); entity.setParentId(parentId);
entity.setName(name); entity.setName(name);
entity.setCategoryKey(generateCategoryKey(parentId, name)); entity.setCategoryKey(generateCategoryKey(parentId, name));
@@ -148,22 +110,13 @@ public class ProductCategoryService {
return findItem(entity.getId()); return findItem(entity.getId());
} }
/**
* @param writableCompanyId 行归属闸门({@code DataReadScope.writeCompanyId} 给):
* {@code null} = 平台超管不限,否则只能动这一家自己的行。
* 读侧收窄而写侧不收窄="藏起来的行仍然能删",那是静默删除不是隔离。
*/
@Transactional @Transactional
public ProductCategoryItemVo update(Long id, ProductCategorySaveRequest request, Long writableCompanyId) { public ProductCategoryItemVo update(Long id, ProductCategorySaveRequest request) {
ProductCategoryEntity entity = getById(id); ProductCategoryEntity entity = getById(id);
assertRowWritable(entity, writableCompanyId);
String name = normalizeRequired(request.getName(), "类目名称不能为空"); String name = normalizeRequired(request.getName(), "类目名称不能为空");
Long parentId = normalizeParentId(request.getParentId()); Long parentId = normalizeParentId(request.getParentId());
// 改行时"生效公司"取行自己的归属,不取 tab:内置行归 0、自建行归那一家, ensureParentVisible(parentId, id);
// 换父级时不能把行挪到可见集外的节点下面(那会让它从原本看得见它的 tab 里消失)。 ensureSiblingNameUnique(parentId, name, id);
Long companyId = entity.getCompanyId();
ensureParentVisible(parentId, id, companyId);
ensureSiblingNameUnique(parentId, name, id, companyId);
entity.setParentId(parentId); entity.setParentId(parentId);
entity.setName(name); entity.setName(name);
@@ -174,9 +127,8 @@ public class ProductCategoryService {
} }
@Transactional @Transactional
public void delete(Long id, Long writableCompanyId) { public void delete(Long id) {
ProductCategoryEntity entity = getById(id); ProductCategoryEntity entity = getById(id);
assertRowWritable(entity, writableCompanyId);
Long childCount = productCategoryMapper.selectCount(new LambdaQueryWrapper<ProductCategoryEntity>() Long childCount = productCategoryMapper.selectCount(new LambdaQueryWrapper<ProductCategoryEntity>()
.eq(ProductCategoryEntity::getParentId, entity.getId())); .eq(ProductCategoryEntity::getParentId, entity.getId()));
if (childCount != null && childCount > 0) { if (childCount != null && childCount > 0) {
@@ -185,29 +137,13 @@ public class ProductCategoryService {
productCategoryMapper.deleteById(entity.getId()); productCategoryMapper.deleteById(entity.getId());
} }
/**
* 行归属闸门。走 {@code assertSameCompany} 而不是在这里比一次:它对本仓所有"按公司写"的闸门
* 是唯一一份判定,两处各写就会有一处先漂。
*
* <p>内置节点(哨兵 0)在这一支里必然被拒——{@code 0 != 任何真实公司 id},
* 而"公司账号能改/删平台内置类目"正是这一页最容易出事的一刀:改了它,
* 所有公司的类目树与货源归类的候选表同一天跟着变。</p>
*/
private void assertRowWritable(ProductCategoryEntity row, Long writableCompanyId) {
if (writableCompanyId == null) {
return;
}
companyScopeSupport.assertSameCompany(writableCompanyId, row.getCompanyId(),
"无权修改该类目:内置类目或别家公司的类目不在本公司的写范围内");
}
private ProductCategoryItemVo findItem(Long id) { private ProductCategoryItemVo findItem(Long id) {
ProductCategoryEntity entity = getById(id); ProductCategoryEntity entity = getById(id);
Long childCount = productCategoryMapper.selectCount(new LambdaQueryWrapper<ProductCategoryEntity>() Long childCount = productCategoryMapper.selectCount(new LambdaQueryWrapper<ProductCategoryEntity>()
.eq(ProductCategoryEntity::getParentId, entity.getId())); .eq(ProductCategoryEntity::getParentId, entity.getId()));
ProductCategoryItemVo item = toItemVo(entity, childCount == null ? 0 : childCount.intValue()); ProductCategoryItemVo item = toItemVo(entity, childCount == null ? 0 : childCount.intValue());
item.setLevel(resolveLevel(entity)); item.setLevel(resolveLevel(entity, productCategoryMapper::selectById));
item.setPath(resolvePath(entity)); item.setPath(resolvePath(entity, productCategoryMapper::selectById));
return item; return item;
} }
@@ -236,10 +172,16 @@ public class ProductCategoryService {
return vo; return vo;
} }
private ProductCategoryListVo buildPageVo(List<ProductCategoryEntity> rows, Long total, long page, long pageSize, Long companyId) { private ProductCategoryListVo buildPageVo(List<ProductCategoryEntity> rows, Long total, long page, long pageSize) {
Map<Long, Integer> childCountById = buildChildCountById(rows, companyId); Map<Long, Integer> childCountById = buildChildCountById(rows);
Map<Long, ProductCategoryEntity> ancestors = loadAncestorIndex(rows);
List<ProductCategoryItemVo> items = rows.stream() List<ProductCategoryItemVo> items = rows.stream()
.map(row -> toItemVo(row, childCountById.getOrDefault(row.getId(), 0))) .map(row -> {
ProductCategoryItemVo item = toItemVo(row, childCountById.getOrDefault(row.getId(), 0));
item.setLevel(resolveLevel(row, ancestors::get));
item.setPath(resolvePath(row, ancestors::get));
return item;
})
.toList(); .toList();
ProductCategoryListVo vo = new ProductCategoryListVo(); ProductCategoryListVo vo = new ProductCategoryListVo();
vo.setItems(items); vo.setItems(items);
@@ -251,13 +193,9 @@ public class ProductCategoryService {
return vo; return vo;
} }
/** 导出的行集合必须与页面列表同源:都走 {@link #list(String, Long)},否则"tab 里看不见但导出里有"就是第二个真相源。 */ /** 导出的行集合必须与页面列表同源:都走 {@link #list(String)},否则"页面里没有但导出里有"就是第二个真相源。 */
public byte[] export(String keyword) { public byte[] export(String keyword) {
return export(keyword, null); ProductCategoryListVo list = list(keyword);
}
public byte[] export(String keyword, Long companyId) {
ProductCategoryListVo list = list(keyword, companyId);
List<ProductCategoryItemVo> rows = list.getItems() == null ? List.of() : list.getItems(); List<ProductCategoryItemVo> rows = list.getItems() == null ? List.of() : list.getItems();
Map<Long, String> nameById = buildExportNameById(rows); Map<Long, String> nameById = buildExportNameById(rows);
try (SXSSFWorkbook workbook = new SXSSFWorkbook(100); try (SXSSFWorkbook workbook = new SXSSFWorkbook(100);
@@ -276,13 +214,13 @@ public class ProductCategoryService {
} }
} }
private ProductCategoryListVo buildSearchPageVo(List<ProductCategoryEntity> rows, Long total, long page, long pageSize, Long companyId) { private ProductCategoryListVo buildSearchPageVo(List<ProductCategoryEntity> rows, Long total, long page, long pageSize) {
Map<Long, Integer> childCountById = buildChildCountById(rows, companyId); Map<Long, Integer> childCountById = buildChildCountById(rows);
List<ProductCategoryItemVo> items = rows.stream() List<ProductCategoryItemVo> items = rows.stream()
.map(row -> { .map(row -> {
ProductCategoryItemVo item = toItemVo(row, childCountById.getOrDefault(row.getId(), 0)); ProductCategoryItemVo item = toItemVo(row, childCountById.getOrDefault(row.getId(), 0));
item.setLevel(resolveLevel(row)); item.setLevel(resolveLevel(row, productCategoryMapper::selectById));
item.setPath(resolvePath(row)); item.setPath(resolvePath(row, productCategoryMapper::selectById));
return item; return item;
}) })
.toList(); .toList();
@@ -383,12 +321,8 @@ public class ProductCategoryService {
return time == null ? "" : time.format(EXPORT_TIME_FORMATTER); return time == null ? "" : time.format(EXPORT_TIME_FORMATTER);
} }
/** /** 列表页的「子类目数」徽章走全表聚合(不是内存里那批行)——整棵树共享,聚合也就没有"别家的数"这一说。 */
* 列表页的「子类目数」徽章走的是<b>全表聚合</b>(不是内存里那批行),所以它必须和公司视图同源: private Map<Long, Integer> buildChildCountById(List<ProductCategoryEntity> rows) {
* 不加这一段,第 1 家的父节点上会显示"3 个子类目"而 tab 里只列得出一两个——
* 数字来自别人的公司,点开却是自己的树。
*/
private Map<Long, Integer> buildChildCountById(List<ProductCategoryEntity> rows, Long companyId) {
Map<Long, Integer> childCountById = new HashMap<>(); Map<Long, Integer> childCountById = new HashMap<>();
if (rows.isEmpty()) { if (rows.isEmpty()) {
return childCountById; return childCountById;
@@ -396,9 +330,6 @@ public class ProductCategoryService {
QueryWrapper<ProductCategoryEntity> countQuery = new QueryWrapper<ProductCategoryEntity>() QueryWrapper<ProductCategoryEntity> countQuery = new QueryWrapper<ProductCategoryEntity>()
.select("parent_id", "count(*) AS child_count") .select("parent_id", "count(*) AS child_count")
.isNotNull("parent_id"); .isNotNull("parent_id");
if (companyId != null) {
countQuery.in("company_id", visibleCompanyIds(companyId));
}
List<Map<String, Object>> countRows = productCategoryMapper.selectMaps(countQuery.groupBy("parent_id")); List<Map<String, Object>> countRows = productCategoryMapper.selectMaps(countQuery.groupBy("parent_id"));
for (Map<String, Object> countRow : countRows) { for (Map<String, Object> countRow : countRows) {
Object parentId = countRow.get("parent_id"); Object parentId = countRow.get("parent_id");
@@ -420,39 +351,19 @@ public class ProductCategoryService {
} }
/** /**
* 关键字命中三条列任一即算命中,但<b>整条 OR 必须包起来再 AND 公司</b>:MyBatis-Plus 的 * 关键字命中三条列任一即算命中,整条 OR 必须包起来:MyBatis-Plus 的 {@code or()} 只改
* {@code or()} 只改"下一个连接符",直接在这串后面 {@code .in(company_id, ...)} 会拼成 * "下一个连接符",直接在这串后面再 AND 别的条件会拼成
* {@code name LIKE ? OR key LIKE ? OR (desc LIKE ? AND company_id IN ...)} —— SQL 里 AND 结合更紧, * {@code name LIKE ? OR key LIKE ? OR (desc LIKE ? AND ...)} —— SQL 里 AND 结合更紧,
* 结果前两条列命中的行<b>不受公司约束</b>,这一页的筛选就成了假的(且不报错)。 * 前两条列命中的行不受那个条件约束(且不报错)。
*/ */
private LambdaQueryWrapper<ProductCategoryEntity> buildSearchQuery(String keyword, Long companyId) { private LambdaQueryWrapper<ProductCategoryEntity> buildSearchQuery(String keyword) {
LambdaQueryWrapper<ProductCategoryEntity> query = new LambdaQueryWrapper<ProductCategoryEntity>() return new LambdaQueryWrapper<ProductCategoryEntity>()
.and(group -> group .and(group -> group
.like(ProductCategoryEntity::getName, keyword) .like(ProductCategoryEntity::getName, keyword)
.or() .or()
.like(ProductCategoryEntity::getCategoryKey, keyword) .like(ProductCategoryEntity::getCategoryKey, keyword)
.or() .or()
.like(ProductCategoryEntity::getDescription, keyword)); .like(ProductCategoryEntity::getDescription, keyword));
return applyCompanyScope(query, companyId);
}
/**
* 公司视图的唯一落点:null = 不筛(超管没选 tab、非超管、以及 {@link #list()} 那棵给 LLM 的全局树);
* 否则 {@code company_id IN (0, X)} —— 哨兵 0 那批内置节点在任何公司视图里都必须在,
* 不然第 2 家的类目页是一棵空树,它自建不出任何子级(父级只能挂在这批上面)。
*/
private LambdaQueryWrapper<ProductCategoryEntity> applyCompanyScope(
LambdaQueryWrapper<ProductCategoryEntity> query, Long companyId) {
if (companyId != null) {
query.in(ProductCategoryEntity::getCompanyId, visibleCompanyIds(companyId));
}
return query;
}
private List<Long> visibleCompanyIds(Long companyId) {
return companyId == SHARED_BUILTIN_COMPANY_ID
? List.of(SHARED_BUILTIN_COMPANY_ID)
: List.of(SHARED_BUILTIN_COMPANY_ID, companyId);
} }
private List<ProductCategoryEntity> filterRowsByKeyword(List<ProductCategoryEntity> rows, String keyword) { private List<ProductCategoryEntity> filterRowsByKeyword(List<ProductCategoryEntity> rows, String keyword) {
@@ -570,12 +481,43 @@ public class ProductCategoryService {
return vo; return vo;
} }
private int resolveLevel(ProductCategoryEntity entity) { /**
* 一次分页里所有行的父链索引:按层批量取,最多 depth 次 {@code selectBatchIds}。
*
* <p>「层级路径」这一列在懒加载通路上曾经是恒空的——{@code /children} 走
* {@link #buildPageVo},它过去只填 {@link #toItemVo}、不设 {@code level}/{@code path},
* 于是前端 {@code path || name} 回退成类目名,那一列画的是「类目」列的副本。补上它就要走父链,
* 而一页最多 100 行、每行按层点查一次,形状是 N+1;这张表只有 412 行所以今天量不出来,
* 但按行按层点查这个形状不该留在这里。</p>
*/
private Map<Long, ProductCategoryEntity> loadAncestorIndex(List<ProductCategoryEntity> rows) {
Map<Long, ProductCategoryEntity> index = new HashMap<>();
Set<Long> pending = new HashSet<>();
for (ProductCategoryEntity row : rows) {
if (row.getParentId() != null) {
pending.add(row.getParentId());
}
}
while (!pending.isEmpty()) {
List<Long> ids = List.copyOf(pending);
pending.clear();
for (ProductCategoryEntity parent : productCategoryMapper.selectBatchIds(ids)) {
if (index.put(parent.getId(), parent) == null
&& parent.getParentId() != null
&& !index.containsKey(parent.getParentId())) {
pending.add(parent.getParentId());
}
}
}
return index;
}
private int resolveLevel(ProductCategoryEntity entity, Function<Long, ProductCategoryEntity> lookup) {
int level = 0; int level = 0;
ProductCategoryEntity cursor = entity; ProductCategoryEntity cursor = entity;
Set<Long> visited = new HashSet<>(); Set<Long> visited = new HashSet<>();
while (cursor != null && cursor.getParentId() != null && visited.add(cursor.getId())) { while (cursor != null && cursor.getParentId() != null && visited.add(cursor.getId())) {
ProductCategoryEntity parent = productCategoryMapper.selectById(cursor.getParentId()); ProductCategoryEntity parent = lookup.apply(cursor.getParentId());
if (parent == null) { if (parent == null) {
break; break;
} }
@@ -585,13 +527,13 @@ public class ProductCategoryService {
return level; return level;
} }
private String resolvePath(ProductCategoryEntity entity) { private String resolvePath(ProductCategoryEntity entity, Function<Long, ProductCategoryEntity> lookup) {
List<String> names = new ArrayList<>(); List<String> names = new ArrayList<>();
ProductCategoryEntity cursor = entity; ProductCategoryEntity cursor = entity;
Set<Long> visited = new HashSet<>(); Set<Long> visited = new HashSet<>();
while (cursor != null && cursor.getId() != null && visited.add(cursor.getId())) { while (cursor != null && cursor.getId() != null && visited.add(cursor.getId())) {
names.add(cursor.getName()); names.add(cursor.getName());
cursor = cursor.getParentId() == null ? null : productCategoryMapper.selectById(cursor.getParentId()); cursor = cursor.getParentId() == null ? null : lookup.apply(cursor.getParentId());
} }
List<String> ordered = new ArrayList<>(); List<String> ordered = new ArrayList<>();
for (int i = names.size() - 1; i >= 0; i--) { for (int i = names.size() - 1; i >= 0; i--) {
@@ -608,14 +550,8 @@ public class ProductCategoryService {
return entity; return entity;
} }
/** /** 父级必须存在,且不能把自己挂到自己的子级下面({@code parent_id} 没有外键,库里一声不响)。 */
* 父级必须"存在且在这一公司的可见集里"。 private void ensureParentVisible(Long parentId, Long currentId) {
*
* <p>只查存在性是不够的:把行的 parent_id 指到别家公司的节点上,这一行就从原本看得见它的
* tab 里消失(读侧按父级子树裁),而 {@code parent_id} 没有外键、库里一声不响。
* companyId 为 null 时不校验——那是改造前/内部调用的口径,不是"允许跨公司挂"。</p>
*/
private void ensureParentVisible(Long parentId, Long currentId, Long companyId) {
if (parentId == null) { if (parentId == null) {
return; return;
} }
@@ -626,9 +562,6 @@ public class ProductCategoryService {
if (parent == null) { if (parent == null) {
throw new BusinessException("父级类目不存在"); throw new BusinessException("父级类目不存在");
} }
if (companyId != null && !visibleCompanyIds(companyId).contains(parent.getCompanyId())) {
throw new BusinessException(403, "父级类目不属于当前公司");
}
Set<Long> visited = new HashSet<>(); Set<Long> visited = new HashSet<>();
Long cursor = parent.getParentId(); Long cursor = parent.getParentId();
while (cursor != null) { while (cursor != null) {
@@ -644,16 +577,12 @@ public class ProductCategoryService {
} }
/** /**
* 同级重名检查的范围 = 这一家的<b>可见集</b>(自建 + 内置),不是只查自建。 * 同级重名检查的范围 = <b>全平台那一棵树</b>:同层同名必须拦,否则页面上一排两个"面霜",
* * 货源归类按名字回填时不知道落到哪一个。
* <p>只查自建会让第 2 家在内置父级"护肤品"下建出一个也叫"面霜"的节点,和内置的那个
* 同层同名——页面上一排两个"面霜",而货源归类按名字回填时不知道落到哪一个。
* 反过来,跨家的同名要放行:那正是 {@code uk_company_category_key} 换掉全平台唯一键要解决的问题。</p>
*/ */
private void ensureSiblingNameUnique(Long parentId, String name, Long excludeId, Long companyId) { private void ensureSiblingNameUnique(Long parentId, String name, Long excludeId) {
LambdaQueryWrapper<ProductCategoryEntity> query = new LambdaQueryWrapper<ProductCategoryEntity>() LambdaQueryWrapper<ProductCategoryEntity> query = new LambdaQueryWrapper<ProductCategoryEntity>()
.eq(ProductCategoryEntity::getName, name); .eq(ProductCategoryEntity::getName, name);
applyCompanyScope(query, companyId);
if (parentId == null) { if (parentId == null) {
query.isNull(ProductCategoryEntity::getParentId); query.isNull(ProductCategoryEntity::getParentId);
} else { } else {
@@ -1,7 +1,9 @@
package com.nanri.aiimage.modules.shopkey.controller; package com.nanri.aiimage.modules.shopkey.controller;
import com.nanri.aiimage.common.api.ApiResponse; 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.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyCreateRequest; import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyCreateRequest;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyUpdateRequest; import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyUpdateRequest;
import com.nanri.aiimage.modules.shopkey.model.vo.ShopKeyItemVo; import com.nanri.aiimage.modules.shopkey.model.vo.ShopKeyItemVo;
@@ -34,22 +36,27 @@ public class ShopKeyController {
private final ShopKeyService shopKeyService; private final ShopKeyService shopKeyService;
private final AdminAuthSupport adminAuthSupport; private final AdminAuthSupport adminAuthSupport;
private final DataReadScope dataReadScope;
@GetMapping @GetMapping
@Operation(summary = "分页查询店铺密钥", description = "分页查询店铺密钥列表。") @Operation(summary = "分页查询店铺密钥", description = "分页查询店铺密钥列表。company_id 只收窄可见集、不放大:"
+ "超管按 tab 指定的公司读,非超管一律锁本公司(越界公司为空页)。")
@ApiResponses({ @ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = ShopKeyPageVo.class))) @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = ShopKeyPageVo.class)))
}) })
public ApiResponse<ShopKeyPageVo> page( public ApiResponse<ShopKeyPageVo> page(
HttpServletRequest request, HttpServletRequest request,
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page, @Parameter(description = "页码") @RequestParam(defaultValue = "1") Long page,
@Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize) { @Parameter(description = "每页数量") @RequestParam(defaultValue = "15") Long pageSize,
adminAuthSupport.requireAdminOrInternal(request); @Parameter(description = "按公司筛选(仅超管生效;非超管一律按会话公司裁剪)")
return ApiResponse.success(shopKeyService.page(page, pageSize)); @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(operator, companyId);
return ApiResponse.success(shopKeyService.page(page, pageSize, scopedCompanyId));
} }
@PostMapping @PostMapping
@Operation(summary = "新增店铺密钥", description = "新增一条店铺密钥记录。") @Operation(summary = "新增店铺密钥", description = "新增一条店铺密钥记录。归属由操作者会话推导,请求体不带 company_id。")
@ApiResponses({ @ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功", content = @Content(schema = @Schema(implementation = ShopKeyItemVo.class))), @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "创建成功", content = @Content(schema = @Schema(implementation = ShopKeyItemVo.class))),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不合法") @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不合法")
@@ -57,51 +64,55 @@ public class ShopKeyController {
public ApiResponse<ShopKeyItemVo> create( public ApiResponse<ShopKeyItemVo> create(
HttpServletRequest request, HttpServletRequest request,
@Valid @RequestBody ShopKeyCreateRequest body) { @Valid @RequestBody ShopKeyCreateRequest body) {
adminAuthSupport.requireAdminOrInternal(request); AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
return ApiResponse.success("创建成功", shopKeyService.create(body)); return ApiResponse.success("创建成功", shopKeyService.create(body, operator.getId()));
} }
@PutMapping("/{id}") @PutMapping("/{id}")
@Operation(summary = "更新店铺密钥", description = "按 ID 更新一条店铺密钥记录。") @Operation(summary = "更新店铺密钥", description = "按 ID 更新一条店铺密钥记录。别家公司的密钥不在本公司的写范围内。")
@ApiResponses({ @ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = ShopKeyItemVo.class))), @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "更新成功", content = @Content(schema = @Schema(implementation = ShopKeyItemVo.class))),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不合法"), @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数不合法"),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "跨公司写操作被拒"),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "记录不存在") @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "记录不存在")
}) })
public ApiResponse<ShopKeyItemVo> update( public ApiResponse<ShopKeyItemVo> update(
HttpServletRequest request, HttpServletRequest request,
@Parameter(description = "主键ID", required = true) @PathVariable Long id, @Parameter(description = "主键ID", required = true) @PathVariable Long id,
@Valid @RequestBody ShopKeyUpdateRequest body) { @Valid @RequestBody ShopKeyUpdateRequest body) {
adminAuthSupport.requireAdminOrInternal(request); AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
return ApiResponse.success("更新成功", shopKeyService.update(id, body)); return ApiResponse.success("更新成功", shopKeyService.update(id, body, dataReadScope.writeCompanyId(operator)));
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
@Operation(summary = "删除店铺密钥", description = "按 ID 删除一条店铺密钥记录。") @Operation(summary = "删除店铺密钥", description = "按 ID 删除一条店铺密钥记录。别家公司的密钥不在本公司的写范围内。")
@ApiResponses({ @ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "删除成功"), @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "删除成功"),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "跨公司写操作被拒"),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "记录不存在") @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "记录不存在")
}) })
public ApiResponse<Void> delete( public ApiResponse<Void> delete(
HttpServletRequest request, HttpServletRequest request,
@Parameter(description = "主键ID", required = true) @PathVariable Long id) { @Parameter(description = "主键ID", required = true) @PathVariable Long id) {
adminAuthSupport.requireAdminOrInternal(request); AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
shopKeyService.delete(id); shopKeyService.delete(id, dataReadScope.writeCompanyId(operator));
return ApiResponse.success("删除成功", null); return ApiResponse.success("删除成功", null);
} }
@PostMapping("/{id}/check-whitelist") @PostMapping("/{id}/check-whitelist")
@Operation(summary = "手动检测 IP 白名单", @Operation(summary = "手动检测 IP 白名单",
description = "绕过缓存真实请求一次紫鸟接口,重置自动重试次数。" description = "绕过缓存真实请求一次紫鸟接口,重置自动重试次数。"
+ "白名单放行需紫鸟公司侧授权,自动重试达上限后会停止重试,授权后可用此接口重新验证。") + "白名单放行需紫鸟公司侧授权,自动重试达上限后会停止重试,授权后可用此接口重新验证。"
+ "别家公司的密钥同样不能替它发起出网检测。")
@ApiResponses({ @ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "检测完成", content = @Content(schema = @Schema(implementation = ShopKeyItemVo.class))), @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "检测完成", content = @Content(schema = @Schema(implementation = ShopKeyItemVo.class))),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "跨公司写操作被拒"),
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "记录不存在") @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "记录不存在")
}) })
public ApiResponse<ShopKeyItemVo> checkWhitelist( public ApiResponse<ShopKeyItemVo> checkWhitelist(
HttpServletRequest request, HttpServletRequest request,
@Parameter(description = "主键ID", required = true) @PathVariable Long id) { @Parameter(description = "主键ID", required = true) @PathVariable Long id) {
adminAuthSupport.requireAdminOrInternal(request); AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
return ApiResponse.success("检测完成", shopKeyService.checkWhitelist(id)); return ApiResponse.success("检测完成", shopKeyService.checkWhitelist(id, dataReadScope.writeCompanyId(operator)));
} }
} }
@@ -15,6 +15,8 @@ public class ShopKeyEntity {
@TableId(type = IdType.AUTO) @TableId(type = IdType.AUTO)
private Long id; private Long id;
/** 归属公司(company.id)。V150 加的列,历史行的值来自当时的列默认值 1,本表无账号列故事后不可反推。 */
private Long companyId;
private String remarkName; private String remarkName;
private String ziniaoAccountName; private String ziniaoAccountName;
private String ziniaoToken; private String ziniaoToken;
@@ -15,6 +15,14 @@ import java.util.List;
/** /**
* shop_key 表对紫鸟侧的只读/回写适配器:把紫鸟需要的字段暴露给 ziniao 模块, * shop_key 表对紫鸟侧的只读/回写适配器:把紫鸟需要的字段暴露给 ziniao 模块,
* 使 ziniao 不再直接引用 shopkey 的 Mapper 与 Entity(打破模块循环依赖)。 * 使 ziniao 不再直接引用 shopkey 的 Mapper 与 Entity(打破模块循环依赖)。
*
* <p><b>这里的 listAll/count 恒为全平台,刻意不跟着 V150 的 company_id 收窄。</b>
* 它的消费者是店铺索引刷新({@code ZiniaoShopIndexService},游标 scopeKey 就是 "global")
* 和令牌轮询({@code ZiniaoAuthService#getScanApiKeys})——那是<b>运行时令牌池</b>,
* 一个后台定时任务没有"当前公司"这个上下文,也没有可以筛的目标:按公司筛它,
* 等于让第二家公司的紫鸟店铺永远进不了索引,而这一页的隔离要收窄的是
* <b>谁能看见/改动这把握在紫鸟那边的令牌</b>(管理面),不是"这把令牌替谁出网"(用量面)。
* 想要用量面也隔离,得先给索引刷新建每公司一份的游标与索引行,那是另一期工程。</p>
*/ */
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.shopkey.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.common.exception.BusinessException; import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.modules.shopkey.mapper.ShopKeyMapper; import com.nanri.aiimage.modules.shopkey.mapper.ShopKeyMapper;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyCreateRequest; import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyCreateRequest;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyUpdateRequest; import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyUpdateRequest;
@@ -36,12 +37,17 @@ public class ShopKeyService {
private final ZiniaoShopIndexService ziniaoShopIndexService; private final ZiniaoShopIndexService ziniaoShopIndexService;
private final ZiniaoApiKeyProvider ziniaoApiKeyProvider; private final ZiniaoApiKeyProvider ziniaoApiKeyProvider;
private final ZiniaoAuthService ziniaoAuthService; private final ZiniaoAuthService ziniaoAuthService;
private final CompanyScopeSupport companyScopeSupport;
public ShopKeyPageVo page(long page, long pageSize) { /**
* @param companyId 读范围公司:由 {@code DataReadScope.readCompanyIdOrOwn} 判定后传下来,
* {@code null} 只可能来自平台超管「不筛」的判定,调用方不许在这里补默认值。
*/
public ShopKeyPageVo page(long page, long pageSize, Long companyId) {
long safePage = Math.max(page, 1); long safePage = Math.max(page, 1);
long safePageSize = Math.min(Math.max(pageSize, 1), 100); long safePageSize = Math.min(Math.max(pageSize, 1), 100);
LambdaQueryWrapper<ShopKeyEntity> query = new LambdaQueryWrapper<ShopKeyEntity>() LambdaQueryWrapper<ShopKeyEntity> query = applyCompanyScope(
.orderByDesc(ShopKeyEntity::getId); new LambdaQueryWrapper<ShopKeyEntity>().orderByDesc(ShopKeyEntity::getId), companyId);
Long total = shopKeyMapper.selectCount(query); Long total = shopKeyMapper.selectCount(query);
List<ShopKeyItemVo> items = shopKeyMapper.selectList(query.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize)) List<ShopKeyItemVo> items = shopKeyMapper.selectList(query.last("LIMIT " + ((safePage - 1) * safePageSize) + ", " + safePageSize))
.stream() .stream()
@@ -55,13 +61,19 @@ public class ShopKeyService {
return vo; return vo;
} }
/**
* 归属由<b>操作者会话</b>推导(请求体一律不带 company_id):漏了这一句,新密钥就会被 V150 的
* {@code DEFAULT 1} 静默塞进第 1 家——那是"归属失真且不报错",而 {@code requireCompanyId}
* 取不到公司时是抛,不会返回 null。所以这里<b>不保留</b>不带操作者的重载。
*/
@Transactional @Transactional
public ShopKeyItemVo create(ShopKeyCreateRequest request) { public ShopKeyItemVo create(ShopKeyCreateRequest request, Long operatorId) {
String ziniaoAccountName = normalizeRequired(request.getZiniaoAccountName(), "紫鸟账号名称不能为空"); String ziniaoAccountName = normalizeRequired(request.getZiniaoAccountName(), "紫鸟账号名称不能为空");
String ziniaoToken = normalizeToken(request.getZiniaoToken()); String ziniaoToken = normalizeToken(request.getZiniaoToken());
String ziniaoTokenHash = hashToken(ziniaoToken); String ziniaoTokenHash = hashToken(ziniaoToken);
ensureTokenAvailable(ziniaoTokenHash, null); ensureTokenAvailable(ziniaoTokenHash, null);
ShopKeyEntity entity = new ShopKeyEntity(); ShopKeyEntity entity = new ShopKeyEntity();
entity.setCompanyId(companyScopeSupport.requireCompanyId(operatorId));
entity.setRemarkName(normalizeOptional(request.getRemarkName())); entity.setRemarkName(normalizeOptional(request.getRemarkName()));
entity.setZiniaoAccountName(ziniaoAccountName); entity.setZiniaoAccountName(ziniaoAccountName);
entity.setZiniaoToken(ziniaoToken); entity.setZiniaoToken(ziniaoToken);
@@ -72,12 +84,12 @@ public class ShopKeyService {
insertOrThrowDuplicateToken(entity); insertOrThrowDuplicateToken(entity);
ziniaoApiKeyProvider.invalidateProxyUrlCache(); ziniaoApiKeyProvider.invalidateProxyUrlCache();
triggerShopIndexRefresh(); triggerShopIndexRefresh();
return toItemVo(getById(entity.getId())); return toItemVo(loadRow(entity.getId()));
} }
@Transactional @Transactional
public ShopKeyItemVo update(Long id, ShopKeyUpdateRequest request) { public ShopKeyItemVo update(Long id, ShopKeyUpdateRequest request, Long writableCompanyId) {
ShopKeyEntity entity = getById(id); ShopKeyEntity entity = getById(id, writableCompanyId);
String ziniaoAccountName = normalizeRequired(request.getZiniaoAccountName(), "紫鸟账号名称不能为空"); String ziniaoAccountName = normalizeRequired(request.getZiniaoAccountName(), "紫鸟账号名称不能为空");
String ziniaoToken = normalizeToken(request.getZiniaoToken()); String ziniaoToken = normalizeToken(request.getZiniaoToken());
String ziniaoTokenHash = hashToken(ziniaoToken); String ziniaoTokenHash = hashToken(ziniaoToken);
@@ -105,12 +117,12 @@ public class ShopKeyService {
updateOrThrowDuplicateToken(entity); updateOrThrowDuplicateToken(entity);
ziniaoApiKeyProvider.invalidateProxyUrlCache(); ziniaoApiKeyProvider.invalidateProxyUrlCache();
triggerShopIndexRefresh(); triggerShopIndexRefresh();
return toItemVo(getById(id)); return toItemVo(getById(id, writableCompanyId));
} }
@Transactional @Transactional
public void delete(Long id) { public void delete(Long id, Long writableCompanyId) {
ShopKeyEntity entity = getById(id); ShopKeyEntity entity = getById(id, writableCompanyId);
shopKeyMapper.deleteById(entity.getId()); shopKeyMapper.deleteById(entity.getId());
ziniaoApiKeyProvider.invalidateProxyUrlCache(); ziniaoApiKeyProvider.invalidateProxyUrlCache();
triggerShopIndexRefresh(); triggerShopIndexRefresh();
@@ -125,8 +137,8 @@ public class ShopKeyService {
* 挂在事务上等于把连接池的连接按上游 RTT 扣住,多次点击即可耗尽池——这正是本仓 * 挂在事务上等于把连接池的连接按上游 RTT 扣住,多次点击即可耗尽池——这正是本仓
* 「事务内含外部 IO」要避免的形态。 * 「事务内含外部 IO」要避免的形态。
*/ */
public ShopKeyItemVo checkWhitelist(Long id) { public ShopKeyItemVo checkWhitelist(Long id, Long writableCompanyId) {
ShopKeyEntity entity = getById(id); ShopKeyEntity entity = getById(id, writableCompanyId);
ziniaoApiKeyProvider.invalidateProxyUrlCache(); ziniaoApiKeyProvider.invalidateProxyUrlCache();
try { try {
ziniaoAuthService.probeApiKeyUpstream(entity.getZiniaoToken()); ziniaoAuthService.probeApiKeyUpstream(entity.getZiniaoToken());
@@ -145,7 +157,7 @@ public class ShopKeyService {
id, entity.getZiniaoAccountName(), ex.getMessage()); id, entity.getZiniaoAccountName(), ex.getMessage());
} }
} }
return toItemVo(getById(id)); return toItemVo(getById(id, writableCompanyId));
} }
private void updateWhitelistState(Long id, String status, String message, int failCount) { private void updateWhitelistState(Long id, String status, String message, int failCount) {
@@ -157,7 +169,18 @@ public class ShopKeyService {
.set(ShopKeyEntity::getIpWhitelistFailCount, failCount)); .set(ShopKeyEntity::getIpWhitelistFailCount, failCount));
} }
private ShopKeyEntity getById(Long id) { private ShopKeyEntity getById(Long id, Long writableCompanyId) {
ShopKeyEntity entity = loadRow(id);
assertRowWritable(entity, writableCompanyId);
return entity;
}
/**
* 不带归属闸门的裸读取:只给两条已经由别的方式确定范围的路径用——
* {@code create} 刚写完自己那一行(归属是它自己落的),以及 {@link #getById} 的内部复用。
* 其余入口一律走 {@link #getById(Long, Long)},别在这里加"顺手读一行"的口子。
*/
private ShopKeyEntity loadRow(Long id) {
ShopKeyEntity entity = shopKeyMapper.selectById(id); ShopKeyEntity entity = shopKeyMapper.selectById(id);
if (entity == null) { if (entity == null) {
throw new BusinessException("店铺密钥不存在"); throw new BusinessException("店铺密钥不存在");
@@ -165,6 +188,30 @@ public class ShopKeyService {
return entity; return entity;
} }
/**
* 行级归属闸门:{@code null} = 平台超管不限。读侧已经收窄而写侧不收窄,等于"藏起来的密钥照样能改能删"。
* 比较的是<b>行自己的</b> {@code company_id},不是 tab 的值。
*/
private void assertRowWritable(ShopKeyEntity row, Long writableCompanyId) {
if (writableCompanyId == null) {
return;
}
companyScopeSupport.assertSameCompany(writableCompanyId, row.getCompanyId(),
"无权操作该密钥:别家公司的紫鸟令牌不在本公司的写范围内");
}
/**
* 公司读范围:{@code null} 侧(平台超管「不筛」)原样不加条件。
* <b>不许在它上面补一个默认公司</b>——那会让超管切到第 2 家时看到的还是第 1 家的令牌。
*/
private LambdaQueryWrapper<ShopKeyEntity> applyCompanyScope(
LambdaQueryWrapper<ShopKeyEntity> query, Long companyId) {
if (companyId != null) {
query.eq(ShopKeyEntity::getCompanyId, companyId);
}
return query;
}
private String normalizeRequired(String value, String message) { private String normalizeRequired(String value, String message) {
String normalized = value == null ? "" : value.trim(); String normalized = value == null ? "" : value.trim();
if (normalized.isEmpty()) { if (normalized.isEmpty()) {
@@ -248,6 +295,12 @@ public class ShopKeyService {
} }
} }
/**
* 令牌查重<b>跨公司全局</b>做,不按 {@code companyId} 收窄——这与 V150 刻意不动
* {@code uk_ziniao_token_hash} 是同一条决定的两面:同一个紫鸟令牌在两家公司各存一行,
* 物理上是同一把握在紫鸟那边的账号被登记两次,而 {@code ZiniaoApiKeyProvider} 按令牌聚合,
* 两行会并成一条、代理地址与白名单失败次数互相顶掉。数据库那把唯一键也根本不允许它发生。
*/
private void ensureTokenAvailable(String tokenHash, Long currentId) { private void ensureTokenAvailable(String tokenHash, Long currentId) {
ShopKeyEntity existing = shopKeyMapper.selectOne(new LambdaQueryWrapper<ShopKeyEntity>() ShopKeyEntity existing = shopKeyMapper.selectOne(new LambdaQueryWrapper<ShopKeyEntity>()
.eq(ShopKeyEntity::getZiniaoTokenHash, tokenHash) .eq(ShopKeyEntity::getZiniaoTokenHash, tokenHash)
@@ -0,0 +1,240 @@
-- =============================================================
-- 迁移 V149__permission_menu_company_tree
-- 模板:docs/flyway-migration-template.md
-- 设计:crawler-plugin/docs/ops/menu-company-tree-design-2026-10-06.md
-- 需求:2026-10-06「菜单权限也加字段来区分,现在的默认归到 admin 下」,控制方选「每家公司一套菜单树」
--
-- 1. 变更目的:把 columns 从"全平台一棵菜单字典"改成"每家公司一套树",并把存量全部归厦门米椿花(id=1)。
-- 今天这张表一个归属列都没有,两条唯一键都是全平台口径:
-- - uk_column_key(column_key) ⇒ 第 2 家公司连"和别家同名"的菜单都建不出来(不是看不到,是建不出);
-- - uk_menu_type_route_path(menu_type, route_path) ⇒ 同上,路径也不允许复用;
-- 而读侧 findDataPermission 这类"按 column_key 点查 + LIMIT 1"(PermissionMenuService:1102)在换键后
-- 会在同名的多行里借位拿到别家的行——所以这一版必须"加列 + 换键 + 复制 + 重指授权"同批做完,
-- 只做加列等于把静默串扰装进生产。
--
-- 2. 口径:
-- - 存量 52 行一律归公司 1(厦门米椿花)= 控制方说的"默认归到 admin 下"。
-- - 三种 menu_type 全复制(admin 26 / app 24 / internal 2):客户端账号同样分属两家公司,
-- 只复制 admin 会留半棵共享树,app 侧的权限键集合还是全平台一份。
-- - 【唯一例外】admin_companies(id 109)不复制:它是角色内在闸门
-- (Java 的 SUPER_ADMIN_ONLY_KEYS / 前端 SUPER_ADMIN_ONLY_MENU_KEYS 同一值),本来就"非超管看不见、
-- 谁也授不出去",别家的树里没有这行比"有一行但被三道出口剪掉"更干净。
-- - 公司 2 那 16 笔授权按 column_key 重指向本公司副本。不留成人工动作:否则德阳的 2 只账号
-- 一上线就掉光菜单,"隐藏"就变成了静默删除。
-- - 复制对 company 表里【所有】id<>1 的公司做(含 status=0 的停用公司):一行菜单不构成任何成本,
-- 而"启用一家公司还要先补树"会让启用动作多一个能被忘掉的步骤。
--
-- 3. 影响表与数据量(2026-10-06 主机A 业务库只读实查,不是估的):
-- columns = 52 行(admin 26:id 4..109|app 24:id 1..96|internal 2:id 69、95)
-- company = 2 家(1 厦门米椿花、2 德阳)⇒ 复制段新增 51 行/家,本批共 +51 行
-- user_column_permission = 784 笔 / 133 账号(公司1 131人768笔|公司2 2人16笔)⇒ 重指段最多改 16 行
-- 同 column_key 重复行 = 0 ⇒ 新唯一键是旧键的严格放宽,换键不会因重复失败
-- users / company / 其余业务表 0 改动
--
-- 4. 锁表风险:低。52 行的字典表,任何形态的 DDL 都在毫秒级;两条加唯一键仍按规矩钉
-- ALGORITHM = INPLACE, LOCK = NONE。唯一的 COPY 是第 3 段那条 MODIFY ... NOT NULL(52 行,V143 同形)。
-- 加列一律走【末位追加】(不写 AFTER):非末位加列能不能 INSTANT 取决于生产 MySQL 的小版本,
-- 把这一条押在版本语义上,代价是发版窗口里第 1 段直接报 1846;而这一列的位置没有任何语义(读写都按列名)。
-- 不碰 biz_task_file_job 等锁热点表。索引字节预算(utf8mb4 + DYNAMIC,上限 3072):
-- uk_company_column_key = 8 + 64*4 = 264
-- uk_company_menu_type_route_path = 8 + 20*4 + 255*4 = 1108
-- 【不加 idx_columns_company】两条新唯一键的最左前缀就是 company_id,52 行的表再单开列索引
-- 就是 V139 那轮清理掉的冗余索引形状。
--
-- 5. 换键顺序:先 ADD 新键,再 DROP 旧键,最后才插副本。倒过来写下的话第 6 段会撞 1062
-- (旧键 uk_column_key 还在全局口径上守着一家一份)。中间任一步失败都至少还有一个唯一键在守并发。
--
-- 6. 回滚步骤:人工补丁 backend-java/docs/rollback-V149-permission-menu-company.sql(在 Flyway 扫描路径之外,
-- 不写成 V150——版本化回滚等于让"决定回滚"这件事在没有人工执行的情况下自己发生)。
-- 顺序:停两台应用 → 跑脚本 → 删 flyway_schema_history 的 version=149 行 → 回滚 jar → 起应用。
--
-- 7. 上线窗口:随 jar 双节点同窗口发布(迁移在首台启动期执行,第二台见"已应用"即跳过),
-- 金丝雀过了立刻补第二台,把混合版本窗口压到分钟级。窗口内旧 jar 的后果清单见设计文档 §7,
-- 三条都是"难看/保守拒绝",不是跨公司放行。
-- DEFAULT 1 是【临时】的,唯一存在理由是同批的旧 jar:它的 PermissionMenuEntity 没有 companyId 字段,
-- MyBatis-Plus 的 insert 会整列跳过,严格模式下报 1364,打到旧节点的"新增菜单"会全失败。
-- 摘除动作与前四张表同一版做(下一版一条元数据操作 ALTER TABLE `columns` ALTER COLUMN company_id DROP DEFAULT,
-- 与 biz_product_category 那条一起;禁写成 MODIFY,重建会按当时的列默认值物化历史行),
-- 在摘掉之前由启动期 CompanyDefaultGuard 盯住(WATCHED_TABLES 已加 columns),
-- 巡检按 COMPANY_DEFAULT_STILL_PRESENT 这条 ASCII 签名 grep——"漏摘"由代码喊,不靠人记得。
--
-- 【可重跑性】MySQL 的 DDL 不进事务。本迁移若在换键或复制段失败,前面的加列与回填已落库;
-- 按「补数据 → flyway repair → 重启」恢复时 Flyway 从第一条语句重跑整个文件,所以每条 DDL
-- 都先查 information_schema 再 PREPARE,回填 UPDATE 带 company_id IS NULL 限定,复制段带 NOT EXISTS 守卫,
-- 重映射段带 parent_id IS NULL 限定,重指段带"行还挂在别家"限定 ⇒ 重跑逐条是 no-op。
-- 末了四道自检闸门(临时表 must_be_zero NOT NULL,V143 那个"让约束替我喊"的家族):残留不为 0 就抛 1048
-- 让迁移失败,而不是留一棵静默分叉的树——尤其闸门 1,它专防"NOT EXISTS 守卫把该插的行挡掉"这种
-- 一声不响少一整家树的形状(PermissionMenuSchemaInitializer 那批裸 column_key 守卫就是同一形态)。
-- =============================================================
SET @db_name = DATABASE();
-- ---------- 1. 加列(末位 + INSTANT,先可空:第 2 段的回填才有行可写) ----------
SET @col_exists := (SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'columns' AND COLUMN_NAME = 'company_id');
SET @sql := IF(@col_exists = 0,
'ALTER TABLE `columns` ADD COLUMN `company_id` bigint NULL COMMENT ''归属公司(company.id):每家公司一套菜单树;V149'', ALGORITHM = INSTANT',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 2. 存量 52 行全部归厦门米椿花 ----------
-- WHERE 限定 NULL ⇒ 重跑是 no-op,也不会覆盖任何人工指定过公司的行。
UPDATE `columns` SET `company_id` = 1 WHERE `company_id` IS NULL;
-- ---------- 3. 收成 NOT NULL(这一句同时是回填自检闸门) ----------
-- 第 2 段若漏掉任何一行,这里抛 1048 让迁移失败:NULL 意味着这一行在任何公司的树上都不出现,
-- 而按 key 点查会把它当"没有这个菜单"。DEFAULT 1 的临时性与摘除时机见头部第 7 段。
-- 这里的 MODIFY 是【建列时】定形状(52 行,毫秒级 COPY);摘 DEFAULT 那一版禁写 MODIFY,两者不是一回事。
ALTER TABLE `columns`
MODIFY COLUMN `company_id` bigint NOT NULL DEFAULT 1 COMMENT '归属公司(company.id):每家公司一套菜单树;V149(DEFAULT 1 待下一版摘除)';
-- ---------- 4. 两条唯一键按公司放宽:先 ADD 新键 ----------
-- 新键是旧键的严格放宽(旧键全平台唯一 ⇒ 新键必唯一),所以这两步不可能因重复而失败。
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'columns' AND INDEX_NAME = 'uk_company_column_key');
SET @sql := IF(@idx_exists = 0,
'ALTER TABLE `columns` ADD UNIQUE KEY `uk_company_column_key` (`company_id`, `column_key`), ALGORITHM = INPLACE, LOCK = NONE',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'columns'
AND INDEX_NAME = 'uk_company_menu_type_route_path');
SET @sql := IF(@idx_exists = 0,
'ALTER TABLE `columns` ADD UNIQUE KEY `uk_company_menu_type_route_path` (`company_id`, `menu_type`, `route_path`), ALGORITHM = INPLACE, LOCK = NONE',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 5. 再 DROP 旧键(顺序不能反,见头部第 5 段) ----------
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'columns' AND INDEX_NAME = 'uk_column_key');
SET @sql := IF(@idx_exists = 1,
'ALTER TABLE `columns` DROP INDEX `uk_column_key`, ALGORITHM = INPLACE, LOCK = NONE',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'columns' AND INDEX_NAME = 'uk_menu_type_route_path');
SET @sql := IF(@idx_exists = 1,
'ALTER TABLE `columns` DROP INDEX `uk_menu_type_route_path`, ALGORITHM = INPLACE, LOCK = NONE',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 6. 给 id<>1 的公司复制整棵树(parent_id 先留 NULL,第 7 段按 key 重映射) ----------
-- 驱动集是「company 全表 × 公司 1 的字典行」,不是硬编码公司 2:第三家公司开通时不用再改迁移。
-- 父指向不能照抄源行的 parent_id——那是全局 id,会跨公司挂到厦门米椿花的分组上;而外键
-- fk_columns_parent_id 只保证父行【存在】,挡不住挂到别家,所以这里宁可先留 NULL 再按 key 认父。
INSERT INTO `columns` (`company_id`, `name`, `column_key`, `menu_type`, `route_path`, `sort_order`, `parent_id`, `created_at`)
SELECT co.id, src.name, src.column_key, src.menu_type, src.route_path, src.sort_order, NULL, src.created_at
FROM `company` co
JOIN `columns` src ON src.company_id = 1
WHERE co.id <> 1
AND src.column_key <> 'admin_companies'
AND NOT EXISTS (
SELECT 1 FROM `columns` cp
WHERE cp.company_id = co.id AND cp.column_key = src.column_key
);
-- ---------- 7. 副本认父:沿 (company_id, column_key) 把父指向换成同公司副本 ----------
-- 与插入顺序无关(源行父指向先落 NULL,join 命中才写),重跑时已认过父的行 parent_id 非 NULL ⇒ no-op;
-- 源行本身是根的行 join 不到 sp ⇒ 一行不动,永久保持 NULL。
UPDATE `columns` copy
JOIN `columns` src ON src.company_id = 1 AND src.column_key = copy.column_key
JOIN `columns` sp ON sp.id = src.parent_id
JOIN `columns` pcopy ON pcopy.company_id = copy.company_id AND pcopy.column_key = sp.column_key
SET copy.parent_id = pcopy.id
WHERE copy.company_id <> 1
AND copy.parent_id IS NULL;
-- ---------- 8. 先把"源行 + 副本"并存的重复授权摘掉(今天 0 行,为 repair 重跑准备) ----------
-- 第 9 段是把指针从源行改到副本,若某账号同时挂着这两笔,改完会撞 PK (user_id, column_id) 报 1062。
-- 删副本那一侧、留源行那一侧给第 9 段去重指 ⇒ 结果只有一笔且指向本公司行。
DELETE dup FROM `user_column_permission` dup
JOIN `users` u ON u.id = dup.user_id
JOIN `columns` copy ON copy.id = dup.column_id AND copy.company_id = u.company_id
JOIN `columns` src ON src.id <> copy.id AND src.column_key = copy.column_key AND src.company_id = 1
JOIN `user_column_permission` old ON old.user_id = dup.user_id AND old.column_id = src.id
WHERE u.company_id <> 1;
-- ---------- 9. 存量授权重指向本公司副本(控制方 D1 定案:不留人工动作) ----------
-- 驱动条件"行还挂在公司 1 而账号不属于公司 1"⇒ 重跑时第 9 段一行都选不出来,是 no-op。
-- 按 column_key 认行而不是按 id 猜:这正是"每家公司一套树"之后唯一还站得住的对应关系。
UPDATE `user_column_permission` g
JOIN `users` u ON u.id = g.user_id
JOIN `columns` src ON src.id = g.column_id AND src.company_id = 1
JOIN `columns` copy ON copy.company_id = u.company_id AND copy.column_key = src.column_key
SET g.column_id = copy.id
WHERE u.company_id <> 1;
-- ---------- 10. 四道自检闸门:不为 0 就抛 1048(列 must_be_zero NOT NULL) ----------
CREATE TEMPORARY TABLE IF NOT EXISTS `_v149_gate` (`must_be_zero` INT NOT NULL);
-- 闸门 1:每一家公司的树都必须和公司 1 一样齐(除角色内在闸门那一行)。
-- 这一道专防复制段被 NOT EXISTS 守卫"一声不响少一整家树"——少树的后果不是报错,
-- 是那家公司的账号有效菜单为空、侧边栏空白,而按 key 点查会判成"这个菜单不存在"。
INSERT INTO `_v149_gate`
SELECT IF(COUNT(*) = 0, 0, NULL)
FROM `company` co
JOIN `columns` src ON src.company_id = 1 AND src.column_key <> 'admin_companies'
LEFT JOIN `columns` cp ON cp.company_id = co.id AND cp.column_key = src.column_key
WHERE co.id <> 1 AND cp.id IS NULL;
-- 闸门 2:父指向绝不跨公司(第 7 段没认上父、或源行本来就挂着别家父时会不为 0)。
INSERT INTO `_v149_gate`
SELECT IF(COUNT(*) = 0, 0, NULL)
FROM (
SELECT c.id
FROM `columns` c
JOIN `columns` p ON p.id = c.parent_id
WHERE c.company_id <> p.company_id
) bad;
-- 闸门 3:授权绝不指向别家的行(第 9 段漏一行,那家公司就 permanently 少一个菜单)。
INSERT INTO `_v149_gate`
SELECT IF(COUNT(*) = 0, 0, NULL)
FROM (
SELECT g.user_id
FROM `user_column_permission` g
JOIN `users` u ON u.id = g.user_id
JOIN `columns` c ON c.id = g.column_id
WHERE c.company_id <> u.company_id
) bad;
-- 闸门 4:company_id 不为 NULL。第 3 段的 MODIFY 已经挡过一次,这一道是给
-- "有人在 V149 之后手工插过不带公司的行"留的复验位——重跑整个文件时它才会响。
INSERT INTO `_v149_gate`
SELECT IF(COUNT(*) = 0, 0, NULL)
FROM (SELECT id FROM `columns` WHERE `company_id` IS NULL OR `company_id` <= 0) bad;
DROP TEMPORARY TABLE `_v149_gate`;
-- ---------- 验证(上线后人工只读复跑,不进迁移) ----------
-- ① 各家行数应相等且 = 公司 1 的 52 - 1 = 51:
-- SELECT company_id, menu_type, COUNT(*) FROM columns GROUP BY company_id, menu_type;
-- ② 跨公司授权残留 0:
-- SELECT COUNT(*) FROM user_column_permission g JOIN users u ON u.id=g.user_id
-- JOIN columns c ON c.id=g.column_id WHERE c.company_id <> u.company_id;
-- ③ 两条旧键已摘、两条新键在:
-- SELECT INDEX_NAME, GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX), NON_UNIQUE
-- FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='columns'
-- GROUP BY INDEX_NAME, NON_UNIQUE;
@@ -0,0 +1,122 @@
-- =============================================================
-- 迁移 V150__shop_key_company_scope
-- 模板:docs/flyway-migration-template.md
-- 需求:2026-10-06「店铺密钥管理的数据按照公司区分」
-- 口径参照:V147__product_category_company_scope.sql(同为"表里一个归属列都没有"的那一类)
--
-- 1. 变更目的:把「店铺密钥管理」biz_shop_key 从"全平台共享的一池紫鸟令牌"改成"每公司一池"。
-- 现状是这张表零归属列(列全集见 V5 + V76 + V82 + V89 + V114,共 12 列,没有 company_id,
-- 也没有任何账号/分组列),而 ShopKeyService.page() 的 LambdaQueryWrapper 除 orderByDesc(id)
-- 之外没有任何 where ⇒ 拿到 admin_shop_keys 这个菜单的任意管理员,读的是同一份全表,
-- 且 ShopKeyItemVo 把 ziniaoToken 原文整列返回、页面把它挂在 title 属性上(悬停即得全文)。
-- 所以这一页今天漏的不是"多看几行",是**别家公司的紫鸟令牌原文**。
--
-- 2. 影响表与数据量:只动 biz_shop_key 一张表,只加一列。
-- 【行数今天没有实查,这一条不许当成已知】本仓的口径是"上线前有人实跑一遍验证 SQL",
-- 取证命令(主机A 业务库只读):
-- SELECT COUNT(*) AS total,
-- SUM(created_at >= '2026-10-04 14:55:00') AS after_company_2_opened
-- FROM biz_shop_key;
-- 为什么必须是 14:55 这个时刻:第二家公司(company.id=2)是 10-04 14:55 开通的(V145 头注释 2 段),
-- 而这一页的写侧闸门是随本批 jar 才装上的 ⇒ **从 14:55 到本次发布之间,第 2 家管理员建的密钥
-- 会落在 DEFAULT 1 上,归进厦门米椿花,事后无从反推**(这张表没有账号列,V145 给品牌库补
-- uploader_user_id 的那个锚点在这里补不出来:历史行的"由谁产生"根本没记过)。
-- 这一段的处置与 V145 一致:不猜、不编,把窗口压短(本批尽快上线),并让
-- after_company_2_opened 在迁移前跑一次——它是非 0 时必须在发布说明里点名"这些行的归属不可追回"。
--
-- 3. 锁表风险:低。
-- ADD COLUMN 走 ALGORITHM = INSTANT 且【不加 AFTER】:非末位列加列在 InnoDB 里要重建聚簇记录,
-- 钉死 INSTANT 之后,万一某个前提不成立,MySQL 直接报 1846 而不是悄悄退化成 COPY——
-- 宁可迁移失败走 repair 重跑,也不要一次没人预期的整表重建(首例 V145 第 3 段)。
-- 全文【没有一条 UPDATE】:历史行的 1 由加列时记录的默认值给出,不需要回填,
-- 所以也就没有 V145 那条"派生值哨兵"要防的写回缺口——但摘 DEFAULT 时仍要重跑验证 SQL 第 2 条,
-- 理由见第 6 段。
-- 不碰 users / company / biz_shop_manage / biz_task_file_job。
--
-- 4. 唯一键【刻意不动】:uk_ziniao_token_hash(V89:20)保持全平台唯一。
-- 【为什么不学 V145/V147 把它按公司放宽】那两个键管的是"同一张表里两家公司都要有名字叫 X 的行"
-- (同名类、同名 ASIN 规则),把它们按公司放宽是隔离的前提;而这里的键管的是**一把握在紫鸟那边的
-- 令牌字符串**本身:同一个令牌在两家公司各存一行,物理上是同一个紫鸟账号被登记了两次,
-- 白名单状态、代理地址、连续失败次数会各自漂移,而 ZiniaoApiKeyProvider.listApiKeyAccounts()
-- 是按令牌聚合的(LinkedHashMap 以 token 为键),两行会并成一条 ApiKeyAccount、
-- resolveProxyUrl 取"第一个非空代理"、resolveIpWhitelistFailCount 取 max ⇒ 一家改了代理,
-- 另一家的出口跟着变。这不是"看不到",是"两行互相顶掉成一行",保持全局唯一才是对的。
-- 【代价,写清】第 2 家管理员提交一把第 1 家已经登记过的令牌,会拿到"紫鸟令牌已存在,不能重复维护"。
-- 这句报错确实说出了"别家有这一条",但能撞出这句话的前提是他已经握着这把握在紫鸟那边的令牌原文,
-- 保密性在那一刻已经没有了 ⇒ 不构成跨租户泄露。
--
-- 5. 回滚步骤:人工补丁 backend-java/docs/rollback-V150-shop-key-company.sql(在 Flyway 扫描路径之外,
-- 不写成 V151——版本化回滚等于让"决定回滚"这件事在没有人工执行的情况下自己发生)。
-- 顺序:停两台应用 → 跑脚本 → 删 flyway_schema_history 的 version=150 行 → 回滚 jar → 起应用。
--
-- 6. 上线窗口:随 jar 双节点同窗口发布,金丝雀过了立刻补第二台,把混合版本窗口压到分钟级。
-- DEFAULT 1 是【临时】的,唯一存在理由是同批的旧 jar:它的 ShopKeyEntity 没有 companyId 字段,
-- MyBatis-Plus 的 insert 会整列跳过,严格模式下报 1364(旧 jar 的 create 会当场 500,
-- 不像 V145 那样被 catch 成 log.warn 静默丢——但"新增密钥这一页在混合窗口里坏掉"同样不可接受)。
-- 摘除动作与前三张同形,是一条纯元数据操作:
-- ALTER TABLE biz_shop_key ALTER COLUMN company_id DROP DEFAULT;
-- 【禁写成 MODIFY COLUMN ... NOT NULL】——那会重建表,而重建时"历史上没有这一列的行"会按
-- 【当时】的列默认值物化:默认刚被摘掉,历史归属就没了依据。本迁移没有写回历史行(第 3 段),
-- 所以摘 DEFAULT 之前必须先重跑下面第 2 条验证 SQL 确认 company_id 全 = 1。
-- 在摘掉之前,启动期 CompanyDefaultGuard 的 WATCHED_TABLES 与探针 SQL 的 IN 列表已把本表一并登记
-- (公司数 > 1 且这一列还带 DEFAULT 就打 COMPANY_DEFAULT_STILL_PRESENT,巡检按这条 ASCII 签名 grep
-- ⇒ "漏摘"由代码喊,不靠人记得)。
-- 【下一笔的取号】本表这条与 docs/migration-inventory.md 里那条同形待办(`columns` 的 DROP DEFAULT,
-- 原先挂在 V149 名下,现登记在「后续新增迁移从 V152 起取号」那一段)应合并成一版发出:
-- 两条都是纯元数据、前提各自独立,任一前提没成立就单独顺延,不要把待办拆散成两个理由。
-- 【不要再往里加 biz_product_category / biz_invalid_asin_data】那两张表的 DEFAULT 由"待摘"改成
-- "必须保留"(10-06 复验后改成共享口径,V151 的 INSERT 列清单不含 company_id,靠 DEFAULT 满足 NOT NULL;
-- 此时执行 DROP DEFAULT 会让每一次新建报 1364)。它们真正消失的时点是下一版直接 DROP COLUMN。
--
-- 【可重跑性】MySQL 的 DDL 不进事务。按「补数据 → flyway repair → 重启」恢复时 Flyway 从第一条
-- 语句重跑整个文件,所以加列先查 information_schema 再 PREPARE。写法首例见 V143 全文件、V145 的加列段。
-- =============================================================
SET @db_name = DATABASE();
-- ---------- 1. 加列(末位 + INSTANT) ----------
SET @col_exists := (SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_shop_key' AND COLUMN_NAME = 'company_id');
SET @sql := IF(@col_exists = 0,
'ALTER TABLE `biz_shop_key` ADD COLUMN `company_id` bigint NOT NULL DEFAULT 1 COMMENT ''归属公司(company.id):本表无账号列,历史行由本默认值给出,不可反推;V150'', ALGORITHM = INSTANT',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 2. 本迁移刻意不做的事 ----------
-- · 不加二级索引:biz_shop_key 是"一个紫鸟账号一行"量级的小表,读路径 WHERE company_id = ? 的
-- 选择性再高也扫不出可感知的差别,而 uk_ziniao_token_hash 之外再挂一个单列索引就是 V139 那轮
-- 清理掉的冗余索引形状。真有慢日志再单独立项(本库的瓶颈是锁不是索引)。
-- · 不加 created_by_id:V145 给品牌库补 uploader_user_id 的理由是"归属只能靠账号反推",
-- 而本表的归属从本版本起由 ShopKeyService.create 显式落 company_id,反推这条路用不上;
-- 留一列没有消费者的审计位,只是给下一次"要不要用它"的争论留个口子。
-- · 不动 uk_ziniao_token_hash(理由见头注释第 4 段)。
-- =============================================================
-- 验证 SQL(迁移后在库上执行,不许只看启动日志的 Successfully applied)
-- SHOW COLUMNS FROM `biz_shop_key` LIKE 'company_id';
-- -> 期望 Null = NO,Default = 1(混合窗口要求带 DEFAULT;摘 DEFAULT 的那一版之后 Default 必须变 NULL)
--
-- SELECT COUNT(*) AS total, SUM(company_id IS NULL) AS null_company,
-- SUM(company_id NOT IN (1)) AS not_company_1
-- FROM `biz_shop_key`;
-- -> 期望 null_company = 0;not_company_1 = 0 表示历史行确实全在第 1 家
-- -> 【派生值哨兵】本迁移没有写回历史行,这里的 1 全部来自加列时记录的默认值。
-- 摘 DEFAULT 的那笔迁移必须【重跑这一条】:一旦某次表重建按"摘掉之后的默认值"物化历史行,
-- not_company_1 会立刻跳出来。
-- -> 与迁移前那次取证对齐:total 必须等于迁移前的 total(INSTANT 加列不该改变行数)。
--
-- SELECT TABLE_NAME, INDEX_NAME, GROUP_CONCAT(CONCAT(COLUMN_NAME,'@',SEQ_IN_INDEX) ORDER BY SEQ_IN_INDEX) AS cols
-- FROM information_schema.STATISTICS
-- WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'biz_shop_key' AND NON_UNIQUE = 0
-- GROUP BY TABLE_NAME, INDEX_NAME;
-- -> 期望恰好两行:PRIMARY(id) 与 uk_ziniao_token_hash(ziniao_token_hash);
-- 这一条是"第 4 段确实没动唯一键"的证据,不是"应该没动"的信念
--
-- SELECT COUNT(*) FROM information_schema.COLUMNS
-- WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'biz_shop_key'
-- AND COLUMN_NAME = 'company_id' AND COLUMN_DEFAULT IS NOT NULL;
-- -> 本版本发布后期望 1(DEFAULT 1 还在,由 CompanyDefaultGuard 喊);摘 DEFAULT 的那一版之后必须变 0
-- =============================================================
@@ -0,0 +1,181 @@
-- =============================================================
-- 迁移 V151__rule_tables_shared_across_companies
-- 模板:docs/flyway-migration-template.md
-- 需求:2026-10-06 控制方点名「品牌数据库做成所有公司共享的,不区分了」「商品类目也都是做成共享的,不区分」
-- 前版:V145(品牌库+去重库按公司一套)、V147(商品类目按公司一棵树)——本文件只退这两张表的唯一键
--
-- 1. 变更目的:把「品牌数据库」biz_invalid_asin_data 与「商品类目」biz_product_category 的
-- 唯一键从"公司+值"退回【全平台】键,与同一批 jar 里已经摘掉公司谓词的读写侧对齐。
-- 不退这一刀的后果不是"看不到",是"写不进去":新代码的 INSERT 列清单已不含 company_id,
-- 严格模式下这一列由 DEFAULT 1 兜住,所以旧键 (company_id, ...) 在功能上"暂时还能用"——
-- 但它把第 2 家公司将来手工建的同名类目/手工加的同名品牌挡在同一行里,
-- 而这一版之后系统里根本不存在"哪一家"这个概念,键里留着公司维度就是一把没有对照物的锁。
--
-- 2. 口径:两张表都退回 V145/V147 之前的形状,键名也复用当时的名字,让"回滚到 V94/V50 时代"
-- 这件事在 SHOW INDEX 里一眼可辨:
-- biz_invalid_asin_data uk_company_value_brand(company_id,data_value,brand(191))
-- -> uk_data_value_brand(data_value,brand(191))
-- biz_product_category uk_company_category_key(company_id,category_key)
-- -> uk_product_category_key(category_key)
-- 【biz_dedupe_total_data 不动】:「去重数据汇总」仍是每公司一套(控制方点名"本次只改品牌数据库"),
-- 它的 uk_company_data_value 与哨兵登记都保持原样。
--
-- 3. 影响表与数据量(2026-10-06 主机A 业务库只读实查,不是估的):
-- biz_invalid_asin_data = 15,056 行,SUM(company_id <> 1) = 0
-- biz_product_category = 412 行(内置 18 = company_id 0、自定义 394 = company_id 1)
-- 按 category_key 分组的重复组 = 0 组
-- V147 上线(10-06 11:03)后的新写入 = 0 行
-- 【两张表能退键的理由不一样,别混着抄】
-- 品牌库:现行唯一键的第一列在库里恒为 1 ⇒ 目标键 (data_value, brand 前 191 字符)
-- 与现行键判的是同一件事,所以只要这个前提还在,ADD UNIQUE 就不可能撞 1062。
-- 文末「验证」段要证的前提只有一条:SUM(company_id <> 1) 仍然是 0(10-06 实查是 0)。
-- 类目表:归属有两档(0 与 1),同一个 category_key 理论上可以一档一行,现行键拦不住,
-- 所以"重复组 = 0"必须实测,「验证」段那条 GROUP BY 是承重的、不是走过场。
-- ⇒ 这两条预检在发版前都要【重跑】:10-06 的数字是快照,不是恒真。
-- company / users / columns 与其余业务表一律不动。
--
-- 4. 锁表风险:低,但两表的形态不同,分开说。
-- biz_invalid_asin_data 15,056 行 / 约 4.5 MB:建 uk_data_value_brand 要扫描并排序全表,
-- 钉 ALGORITHM = INPLACE, LOCK = NONE ⇒ 建索引期间并发 DML 可以进(同 V145 第 3 段的做法)。
-- biz_product_category 412 行:任何形态都在毫秒级,仍然钉同一对子句,不给"顺手退化成交换锁"留机会。
-- DROP INDEX 只吃一下元数据锁。
-- 两条 ADD UNIQUE 都排在对应的 DROP 之前:中间任一步失败时【至少还有一个唯一键在守并发】,
-- 而失败的表象是 Flyway 迁移报错、应用起不来,不是"键没了、重复行静默进库"。
-- 索引字节预算(utf8mb4 + DYNAMIC,上限 3072):
-- uk_data_value_brand = 128*4 + 191*4 = 1276
-- uk_product_category_key = 128*4 = 512
-- 【不用前缀索引迁就长度】(V135:6-9 的结论照搬):data_value 走全列、只有 brand 因为是 TEXT
-- 才必须带 (191),这与 V94 原键完全同形,退回去不改变任何一列的判重宽度。
-- 不碰 biz_task_file_job 等锁热点表。
--
-- 5. 回滚步骤:人工补丁 backend-java/docs/rollback-V151-rule-tables-shared.sql
-- (在 Flyway 扫描路径之外,不写成 V152——版本化回滚等于让"决定回滚"这件事在没有人工执行
-- 的情况下自己发生)。回滚方向是把两把公司键加回来:今天两张表的 company_id 只有一个值
-- (品牌库全是 1、类目是 0/1 两档),所以回滚不会撞 1062;但 jar 必须先回到带公司谓词的那版,
-- 否则"键按公司、代码不分公司"会让第 2 家建出与第 1 家同键的行。
-- 顺序:停两台应用 → 跑脚本 → 删 flyway_schema_history 的 version=151 行 → 回滚 jar → 起应用。
--
-- 6. 上线窗口:随 jar 双节点同窗口发布,金丝雀过了立刻补第二台,把混合版本窗口压到分钟级。
-- 【为什么本文件不 DROP COLUMN,尽管控制方要的是"删掉 company_id 列"】
-- 线上那版 jar 的读写两侧都带着 company_id:InvalidAsinDataMapper 的 INSERT 列清单点名这一列,
-- ProductCategoryEntity 带 companyId 字段(MyBatis-Plus 的 SELECT 列清单也含它)。
-- 这两句合起来的后果是"删列与换键同批"必然在混合窗口里打断旧 jar——而且打断得很难看:
-- 旧 jar 的 INSERT ... (company_id, ...) -> 1054 Unknown column,而
-- CollectDataInvalidAsinBatchWriter 把批量写失败 catch 成 log.warn 后跳过整批,接口照样返回成功
-- ⇒ 品牌黑名单静默少一批(这正是 V145 头注释为 DEFAULT 写下的那条禁令的反方向:
-- 一次迁移只解决一个可回滚的理由,别把"能静默丢数"的那一刀和换键捆在一起)。
-- 所以拆两步:本文件退键(旧 jar 配新库仍然全绿——键只是变严,数据本来就不冲突),
-- 下一版(两台同版确认后)再出
-- ALTER TABLE biz_invalid_asin_data DROP COLUMN company_id;
-- ALTER TABLE biz_product_category DROP COLUMN company_id;
-- 并同步把 CompanyDefaultGuard 的清单再清一遍。uploader_user_id 保留:它是"由谁产生"的审计锚点,
-- 与归属公司无关,摘了就把 10-05 起 AUTO 行的来源信息一起删掉。
-- 【DEFAULT 1 在本版之后从"待摘"变成"必须保留",这点必须写清,否则会有人照哨兵的提示去摘它】
-- 新 jar 的 INSERT 不带 company_id,靠 DEFAULT 1 满足 NOT NULL;此时执行
-- ALTER TABLE ... ALTER COLUMN company_id DROP DEFAULT 会让每一次写入报 1364(品牌库那条
-- 同样被 writer 吞成 warn ⇒ 静默丢数)。因此本版把这两张表从 WATCHED_TABLES 与探针 SQL 的
-- IN 列表里同时摘掉(清单与 SQL 由 CompanyDefaultGuardTest 双向钉同源),"摘 DEFAULT"这条
-- 待办由"改天要执行"改成"等 DROP COLUMN 那一版一起消失"。
-- biz_dedupe_total_data 与 biz_shop_key 不在此列:它们仍然按公司写,DEFAULT 仍是要摘的。
--
-- 【可重跑性】MySQL 的 DDL 不进事务。本迁移若在 DROP 段失败,前面的 ADD 已落库;
-- 按「补数据 → flyway repair → 重启」恢复时 Flyway 从第一条语句重跑整个文件,所以四条 DDL
-- 都先查 information_schema 再 PREPARE。写法首例见 V145 的加列/换键段、V147 全文件。
-- =============================================================
SET @db_name = DATABASE();
-- ---------- 1. 品牌数据库:先加全局键 ----------
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_invalid_asin_data' AND INDEX_NAME = 'uk_data_value_brand');
SET @sql := IF(@idx_exists = 0,
'ALTER TABLE `biz_invalid_asin_data` ADD UNIQUE KEY `uk_data_value_brand` (`data_value`, `brand`(191)), ALGORITHM = INPLACE, LOCK = NONE',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 2. 品牌数据库:再摘公司键 ----------
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_invalid_asin_data' AND INDEX_NAME = 'uk_company_value_brand');
SET @sql := IF(@idx_exists > 0,
'ALTER TABLE `biz_invalid_asin_data` DROP INDEX `uk_company_value_brand`, ALGORITHM = INPLACE, LOCK = NONE',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 3. 商品类目:先加全局键 ----------
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_product_category' AND INDEX_NAME = 'uk_product_category_key');
SET @sql := IF(@idx_exists = 0,
'ALTER TABLE `biz_product_category` ADD UNIQUE KEY `uk_product_category_key` (`category_key`), ALGORITHM = INPLACE, LOCK = NONE',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 4. 商品类目:再摘公司键 ----------
SET @idx_exists := (SELECT COUNT(DISTINCT INDEX_NAME) FROM information_schema.STATISTICS
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_product_category' AND INDEX_NAME = 'uk_company_category_key');
SET @sql := IF(@idx_exists > 0,
'ALTER TABLE `biz_product_category` DROP INDEX `uk_company_category_key`, ALGORITHM = INPLACE, LOCK = NONE',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 5. 本迁移刻意不做的事 ----------
-- · 不 DROP COLUMN、不 DROP DEFAULT:理由见第 6 段(旧 jar 会撞 1054/1364,且失败被 writer 吞成 warn)。
-- · 不动 biz_dedupe_total_data:去重库仍每公司一套。
-- · 不加二级索引:两张表读侧已不按公司筛,company_id 的选择性在本版之后没有消费者,索引只是维护成本。
-- · 不回填 group_id:14,000+ 行 AUTO 的 group_id 为 NULL 是既成事实,非超管的可见集仍由
-- record_source = 'MANUAL' AND group_id = 固定组 这条谓词决定(与 V145/V151 无关,本文件不碰读侧)。
-- =============================================================
-- 验证 SQL(迁移后在库上执行,必须有人实跑,不许只看启动日志的 Successfully applied)
--
-- SELECT TABLE_NAME, INDEX_NAME, GROUP_CONCAT(CONCAT(COLUMN_NAME,'@',SEQ_IN_INDEX) ORDER BY SEQ_IN_INDEX) AS cols
-- FROM information_schema.STATISTICS
-- WHERE TABLE_SCHEMA = DATABASE()
-- AND TABLE_NAME IN ('biz_invalid_asin_data','biz_product_category','biz_dedupe_total_data')
-- AND NON_UNIQUE = 0
-- GROUP BY TABLE_NAME, INDEX_NAME;
-- -> 期望恰好六行:PRIMARY(id) x3,加
-- biz_invalid_asin_data.uk_data_value_brand(data_value@1,brand@2)
-- biz_product_category.uk_product_category_key(category_key@1)
-- biz_dedupe_total_data.uk_company_data_value(company_id@1,data_value@2) <- 这条【必须还在】
-- -> uk_company_value_brand / uk_company_category_key 必须【不】在结果里;
-- uk_company_data_value 若在结果里【消失】了,说明本文件误伤了去重库。
--
-- SELECT COUNT(*) AS dup_brand_rows FROM (
-- SELECT data_value FROM biz_invalid_asin_data
-- GROUP BY data_value, LEFT(brand, 191) HAVING COUNT(*) > 1 LIMIT 1
-- ) t;
-- SELECT COUNT(*) AS dup_category_keys FROM (
-- SELECT category_key FROM biz_product_category GROUP BY category_key HAVING COUNT(*) > 1 LIMIT 1
-- ) t;
-- -> 两条都期望 0(本文件能建起严格键的前提)。发版前【重跑】这两条:10-06 的 0 组是快照。
--
-- SELECT COUNT(*) AS total FROM biz_invalid_asin_data;
-- SELECT COUNT(*) AS total, SUM(is_builtin = 1) AS builtin FROM biz_product_category;
-- -> 期望与迁移前一致(15,056 上下、412 / 18):本文件只换键,不增删行。
--
-- INSERT IGNORE 在退回全局键后(事务内跑完回滚,只插 ZZTEST 前缀):
-- START TRANSACTION;
-- INSERT INTO `biz_invalid_asin_data` (data_value, brand, record_source) VALUES ('ZZTESTKEY000001', 'zztestbrand', 'MANUAL');
-- INSERT INTO `biz_invalid_asin_data` (data_value, brand, record_source) VALUES ('ZZTESTKEY000001', 'zztestbrand', 'MANUAL');
-- SELECT COUNT(*) AS one_row FROM `biz_invalid_asin_data` WHERE data_value = 'ZZTESTKEY000001';
-- ROLLBACK;
-- -> 期望 one_row = 1:同名值第二次被 IGNORE 掉 = 键真的回到全平台一档。
-- 第二次也进去(=2)说明新键没建成,第 1 段被跳过了。
--
-- SHOW COLUMNS FROM `biz_invalid_asin_data` LIKE 'company_id';
-- SHOW COLUMNS FROM `biz_product_category` LIKE 'company_id';
-- -> 期望两条都仍是 Null = NO、Default = 1。本版【故意留着】:新 jar 的 INSERT 靠它满足 NOT NULL。
-- 它们变成"列不存在"的那一版才是 DROP DEFAULT 该一起消失的时候。
-- =============================================================
@@ -112,15 +112,20 @@ import org.junit.jupiter.api.Test;
* D 的代价与射程一并交代:非 {@code Long} 型公司参数取不到绑定名,判红并报形状;而"handler 之外的私有 * D 的代价与射程一并交代:非 {@code Long} 型公司参数取不到绑定名,判红并报形状;而"handler 之外的私有
* 收口方法里把公司参数硬写成 {@code null}"这一族 D 看不见——块边界止于该 handler 自己的闭括号 * 收口方法里把公司参数硬写成 {@code null}"这一族 D 看不见——块边界止于该 handler 自己的闭括号
* (第 7 条),{@code AdminImageVideoTaskController.scopeOf} 正是它,那一处是<b>故意</b>传 null 的。</li> * (第 7 条),{@code AdminImageVideoTaskController.scopeOf} 正是它,那一处是<b>故意</b>传 null 的。</li>
* <li><b>几条正门,一套判据</b>(批次 2/3 新增;10-06 复验后加第三道)。{@code DataReadScope} 现在有三个出口: * <li><b>几条正门,一套判据</b>(批次 2/3 新增;10-06 复验后加第二道,批次 6 加第三道)。出口现在有三个:
* {@code readScope(} 按账号集合给范围(去重库、查询 ASIN、最低价 ASIN、历史、视频), * {@code readScope(} 按账号集合给范围(去重库、查询 ASIN、最低价 ASIN、历史、视频),
* {@code readCompanyId(} 给"归属已物化成 {@code company_id} 列"的表(品牌库、商品类目—— * {@code readCompanyIdOrOwn(} 给"归属物化成 {@code company_id} 列、可见集又不靠账号/分组"的表
* 那两张表的 {@code uploader_user_id} 在生产是 0 行非空,按账号筛等于把全部历史从每个公司 tab 里 * (今天只有店铺密钥,V150 起每公司一套),{@code resolveScopeCompanyId(} 给菜单字典那一棵树一套
* 静默删掉,理由写在 {@code DataReadScope#readCompanyId} 的注释里)。两条门共用 A/B/C/D 四条判据: * (V149 起,读写共用同一判据,见 {@link #RESOLVE_MENU_SCOPE_CALL} 的理由)。
* 三道门共用 A/B/C/D 四条判据:
* {@link #SCOPE_DOORS} 供 A 与 C 逐条跑,{@link #SCOPE_CALLEE_NAMES} 供 D 认被调名, * {@link #SCOPE_DOORS} 供 A 与 C 逐条跑,{@link #SCOPE_CALLEE_NAMES} 供 D 认被调名,
* <b>名单只写一次</b>(红因消息与自检断言咬的是拼出来的同一个标签,两处各写一遍会随哈希顺序漂红)。 * <b>名单只写一次</b>(红因消息与自检断言咬的是拼出来的同一个标签,两处各写一遍会随哈希顺序漂红)。
* 每条门各自带能红/能绿两向探针(全局约束 15 那把尺子):只在 {@code readScope} 上验过, * 每条门各自带能红/能绿两向探针(全局约束 15 那把尺子):只在 {@code readScope} 上验过,
* 等于第二道门上的返回值与入参没人看守。</li> * 等于第二道门上的返回值与入参没人看守;第三道门(菜单字典)的三枚 {@code MENU_SCOPE_*} 探针同理。
* <p>批次 2 时这里还有<b>中间</b>那道 {@code readCompanyId(},服务品牌库 {@code biz_invalid_asin_data}
* 与商品类目 {@code biz_product_category} 两张物化列表。10-06 控制方把这两页定成全平台共享,
* 方法随之删除 ⇒ 门也从名单一起摘掉:名单里留一门没有实现者的门,等于给"把公司开关再接回那两张表"
* 预先铺好合规形状。这一族现在由 {@link #SHARED_TABLES_MUST_STAY_UNSCOPED} 反向钉住。</p></li>
* <li><b>取实参表按配对括号,不按单层括号正则</b>(10-05 批次 2/3 实跑)。原先 C 的第 ② 步与 D 都用 * <li><b>取实参表按配对括号,不按单层括号正则</b>(10-05 批次 2/3 实跑)。原先 C 的第 ② 步与 D 都用
* {@code ([\w$]*)\s*\(([^()]*)\)},实参表里只要还有一次方法调用就整条看不见。而第 7 条把块边界钉死在 * {@code ([\w$]*)\s*\(([^()]*)\)},实参表里只要还有一次方法调用就整条看不见。而第 7 条把块边界钉死在
* handler 自己的闭括号上、断言 A 因此要求正门调用必须内联,两支约束合起来把合规接线逼成了 * handler 自己的闭括号上、断言 A 因此要求正门调用必须内联,两支约束合起来把合规接线逼成了
@@ -171,29 +176,35 @@ class CompanyIdParamGoesThroughReadScopeTest {
* 不钉这一条的话,"取样集非空"自检可以由任何一支别的 handler 满足,而这两页哪天改了 * 不钉这一条的话,"取样集非空"自检可以由任何一支别的 handler 满足,而这两页哪天改了
* mapping 注解 / 换了参数形状就会静默脱离射程——分母由本轮自己造,等于没有分母。 * mapping 注解 / 换了参数形状就会静默脱离射程——分母由本轮自己造,等于没有分母。
* *
* <p>10-05 批次 2/3(去重库、品牌库、查询ASIN、最低价ASIN、商品类目)把样本面扩到了 * <p>10-05 批次 2/3 把样本面扩到当时那条按物化列给范围的正门({@code readCompanyId})上,
* {@link #READ_COMPANY_ID_CALL} 那条正门上,所以这里补两条同样口径的射程下限: * 并补了两条同样口径的射程下限(品牌库、商品类目)。10-06 那两页定案全平台共享、门随之删除,
* 那五页哪天改了参数形状,静默脱离的是这一页的 tab,不是这条用例。</p> * 这两条下限一起摘掉——剩下的六页哪天改了参数形状,静默脱离的是它自己的 tab,不是这条用例。</p>
*/ */
private static final String SCOPE_CAUGHT_HISTORY_KEY = private static final String SCOPE_CAUGHT_HISTORY_KEY =
"com/nanri/aiimage/modules/imagehistory/controller/ImageHistoryController.java#@GetMapping(\"/history\")"; "com/nanri/aiimage/modules/imagehistory/controller/ImageHistoryController.java#@GetMapping(\"/history\")";
private static final String SCOPE_CAUGHT_VIDEO_KEY = private static final String SCOPE_CAUGHT_VIDEO_KEY =
"com/nanri/aiimage/modules/imagevideo/controller/AdminImageVideoTaskController.java#@GetMapping"; "com/nanri/aiimage/modules/imagevideo/controller/AdminImageVideoTaskController.java#@GetMapping";
private static final String SCOPE_CAUGHT_INVALID_ASIN_KEY =
"com/nanri/aiimage/modules/invalidasin/controller/InvalidAsinDataController.java#@GetMapping";
private static final String SCOPE_CAUGHT_PRODUCT_CATEGORY_KEY =
"com/nanri/aiimage/modules/productcategory/controller/ProductCategoryController.java#@GetMapping(\"/product-categories\")";
private static final String SCOPE_CAUGHT_DEDUPE_KEY = private static final String SCOPE_CAUGHT_DEDUPE_KEY =
"com/nanri/aiimage/modules/dedupe/controller/DedupeTotalDataController.java#@GetMapping"; "com/nanri/aiimage/modules/dedupe/controller/DedupeTotalDataController.java#@GetMapping";
private static final String SCOPE_CAUGHT_QUERY_ASIN_KEY = private static final String SCOPE_CAUGHT_QUERY_ASIN_KEY =
"com/nanri/aiimage/modules/shopkey/controller/QueryAsinController.java#@GetMapping"; "com/nanri/aiimage/modules/shopkey/controller/QueryAsinController.java#@GetMapping";
private static final String SCOPE_CAUGHT_SKIP_PRICE_ASIN_KEY = private static final String SCOPE_CAUGHT_SKIP_PRICE_ASIN_KEY =
"com/nanri/aiimage/modules/shopkey/controller/SkipPriceAsinController.java#@GetMapping"; "com/nanri/aiimage/modules/shopkey/controller/SkipPriceAsinController.java#@GetMapping";
/**
* V150(10-06「店铺密钥管理的数据按照公司区分」)接的第八支:这一页的正门是
* {@code readCompanyIdOrOwn}(表里没有账号列,只有 V150 新加的 {@code company_id})。
*/
private static final String SCOPE_CAUGHT_SHOP_KEY_KEY =
"com/nanri/aiimage/modules/shopkey/controller/ShopKeyController.java#@GetMapping";
/** /**
* 射程下限的<b>唯一一份</b>名单:C 与 D 两条射程断言共用它,不许各写一份(两处各写就会有一处先漂)。 * 射程下限的<b>唯一一份</b>名单:C 与 D 两条射程断言共用它,不许各写一份(两处各写就会有一处先漂)。
* 这七支是"切 tab 数据还是一样"这次报障正对着的页面 —— 用户报的五页(去重库、品牌库、最低价ASIN、 * 这六支是"切 tab 数据还是一样"这次报障正对着的页面里<b>今天仍按公司取数</b>的那些:
* 商品类目、查询ASIN)加批次 1 已接线的两页(图片历史、图片视频任务)。 * 批次 1 的两页(图片历史、图片视频任务)+ 批次 2 剩下三页(去重库、查询ASIN、最低价ASIN)
* + V150 的店铺密钥。
* <p>品牌库、商品类目 2026-10-06 定案退回全平台共享({@link #SHARED_TABLES_MUST_STAY_UNSCOPED}),
* 它们的公司参数已从 controller 上摘掉,留在这里只会让 {@code contains(...)} 恒红——
* "不得回流"改由那一条反向钉看守,不靠射程名单。</p>
*/ */
private static final List<String> WIRED_PAGE_KEYS = List.of( private static final List<String> WIRED_PAGE_KEYS = List.of(
SCOPE_CAUGHT_HISTORY_KEY, SCOPE_CAUGHT_HISTORY_KEY,
@@ -201,38 +212,36 @@ class CompanyIdParamGoesThroughReadScopeTest {
SCOPE_CAUGHT_DEDUPE_KEY, SCOPE_CAUGHT_DEDUPE_KEY,
SCOPE_CAUGHT_QUERY_ASIN_KEY, SCOPE_CAUGHT_QUERY_ASIN_KEY,
SCOPE_CAUGHT_SKIP_PRICE_ASIN_KEY, SCOPE_CAUGHT_SKIP_PRICE_ASIN_KEY,
SCOPE_CAUGHT_INVALID_ASIN_KEY, SCOPE_CAUGHT_SHOP_KEY_KEY);
SCOPE_CAUGHT_PRODUCT_CATEGORY_KEY);
private static final String READ_SCOPE_CALL = "readScope("; private static final String READ_SCOPE_CALL = "readScope(";
/** /**
* 第二个被认可的正门(10-05 批次 2/3):{@code DataReadScope.readCompanyId(operator, companyId)}。 * 第二道正门(10-06 复验后补):{@code readCompanyIdOrOwn}。
* *
* <p>它存在的理由不是省事:品牌库 {@code biz_invalid_asin_data} 实测 14,801 行里 * <p>它补的是"归属物化成 {@code company_id} 列、且可见集不靠账号/分组"那一族表:今天的消费者是
* {@code uploader_user_id} 非空 <b>0</b> 行(实体没这字段、批量 INSERT 的列清单也没带,V145 补的列 * 店铺密钥 {@code biz_shop_key}(V150 起每公司一套),表里没有账号列,返回 null 等于把整张表交给每一家。</p>
* 一直是空的),走 {@code readScope} 那批账号集合等于把全部历史从每一个公司 tab 里静默删掉;
* 商品类目 {@code biz_product_category} 更是连账号列都没有(V147 才加的 company_id)。
* 这两页的归属是<b>物化列</b>,正门必须按列给。</p>
*
* <p>几条正门是并列的<b>白名单</b>而不是新的自由口径:判据 A/C/D 与 {@code readScope} 逐字共用,
* 只是把"出现过 readScope("换成"出现过任一正门"," companyId 进了 readScope 的实参表"换成
* "进了任一正门的实参表"。页里自己写 {@code if (companyId != null) ...} 那一族
* 依然红——名单只加在 {@code DataReadScope} 上,加不在页上。</p>
*/
private static final String READ_COMPANY_ID_CALL = "readCompanyId(";
/**
* 第三道正门(10-06 复验后补):{@code readCompanyIdOrOwn}。
*
* <p>它补的是 {@code readCompanyId} 在非超管那一支的洞:品牌库的"非超管不筛"靠账号/分组谓词兜底,
* 商品类目既没有账号列也没有分组可见集,返回 null 就是"每一家都读到整棵树"——
* 2026-10-06 逐节点复验实测公司 2 的 admin 在该页读到 412 行(含公司 1 的 394 个自建类目)。</p>
* *
* <p>入名单的前提是它仍然只是 {@code DataReadScope} 上的一个方法,不是页里自己写的 if: * <p>入名单的前提是它仍然只是 {@code DataReadScope} 上的一个方法,不是页里自己写的 if:
* 第三条门若开在 controller 里,这一页的判据就没人看守了。</p> * 第二条门若开在 controller 里,这一页的判据就没人看守了。</p>
*
* <p>原先这里还有中间那道 {@code readCompanyId(}:品牌库、商品类目两张物化列表用它在超管身上做
* "tab 选哪家"的开关。2026-10-06 控制方定案那两页全平台共享、不区分公司,方法已从
* {@code DataReadScope} 删除、全树零消费者,所以这道门连同它的三枚探针一起摘掉——
* 判据名单里留一门没有实现者的门,等于给"把公司开关再接回那两张表"预先铺好合规形状。</p>
*/ */
private static final String READ_OWN_COMPANY_ID_CALL = "readCompanyIdOrOwn("; private static final String READ_OWN_COMPANY_ID_CALL = "readCompanyIdOrOwn(";
/**
* 第三道正门(10-06 批次 6 补):{@code resolveScopeCompanyId}——菜单字典({@code columns} 每家公司一套树)
* 的归属判据。它开在 {@code PermissionMenuService} 上而不是 {@code DataReadScope} 上,理由与 {@code readCompanyIdOrOwn}
* 那条"必须是共享方法、不许页里自己写 if"是同一条:读写两侧、{@code loadRawMenus} 的每一个取数、
* 建/改/删/排四道写侧闸门全都只从这一个方法拿公司 id,判据分两处迟早漂移成"读能看别家、写挡不住"。
*
* <p>与 {@code readCompanyIdOrOwn} 的差别是定案 D2 要求的,不是笔误:超管<b>不传</b>时这道门返回他自己的
* 公司(菜单字典没有"混着两家的树一起列"这种视图),非超管<b>传别家</b>时抛 403 而不是静默改成本公司。</p>
*/
private static final String RESOLVE_MENU_SCOPE_CALL = "resolveScopeCompanyId(";
private static final List<String> SCOPE_DOORS = private static final List<String> SCOPE_DOORS =
List.of(READ_SCOPE_CALL, READ_COMPANY_ID_CALL, READ_OWN_COMPANY_ID_CALL); List.of(READ_SCOPE_CALL, READ_OWN_COMPANY_ID_CALL, RESOLVE_MENU_SCOPE_CALL);
private static final String EXPLICIT_PARAM_NAME = "name = \"company_id\""; private static final String EXPLICIT_PARAM_NAME = "name = \"company_id\"";
private static final String SNAKE_PARAM = "company_id"; private static final String SNAKE_PARAM = "company_id";
private static final String CAMEL_PARAM = "companyId"; private static final String CAMEL_PARAM = "companyId";
@@ -275,10 +284,11 @@ class CompanyIdParamGoesThroughReadScopeTest {
"if", "for", "while", "switch", "do", "catch", "synchronized", "return", "throw", "else", "try"); "if", "for", "while", "switch", "do", "catch", "synchronized", "return", "throw", "else", "try");
/** /**
* 断言 D 认的三个被调名:{@code readScope} 是按账号集合给范围的唯一出口, * 断言 D 认的四个被调名:{@code readScope} 是按账号集合给范围的唯一出口,
* {@code resolveScope} 是 Task 11 模板鼓励的"controller 里的私有收口方法"那一形(它内部再去 * {@code resolveScope} 是 Task 11 模板鼓励的"controller 里的私有收口方法"那一形(它内部再去
* readScope),{@code readCompanyId} 是归属已物化成 {@code company_id} 列那两张表 * readScope),{@code readCompanyIdOrOwn} 是"归属物化成 {@code company_id} 列、可见集不靠账号/分组"
* (品牌库、商品类目)的正门(见 {@link #READ_COMPANY_ID_CALL} 的理由)。 * 那一族表(今天只有店铺密钥)的正门(见 {@link #READ_OWN_COMPANY_ID_CALL} 的理由),
* {@code resolveScopeCompanyId} 是菜单字典那一棵树一套的归属判据(见 {@link #RESOLVE_MENU_SCOPE_CALL} 的理由)。
* 除此之外的调用都不算"把公司参数交给了出口"——尤其 {@code readScope(operator, null)} 里那个 {@code null}。 * 除此之外的调用都不算"把公司参数交给了出口"——尤其 {@code readScope(operator, null)} 里那个 {@code null}。
*/ */
private static final String RESOLVE_SCOPE_CALL = "resolveScope("; private static final String RESOLVE_SCOPE_CALL = "resolveScope(";
@@ -288,7 +298,7 @@ class CompanyIdParamGoesThroughReadScopeTest {
* 那就等于一条会自己漂红的用例。 * 那就等于一条会自己漂红的用例。
*/ */
private static final List<String> SCOPE_CALLEE_NAMES = private static final List<String> SCOPE_CALLEE_NAMES =
List.of("readScope", "resolveScope", "readCompanyId", "readCompanyIdOrOwn"); List.of("readScope", "resolveScope", "readCompanyIdOrOwn", "resolveScopeCompanyId");
private static final Set<String> SCOPE_CALLEES = Set.copyOf(SCOPE_CALLEE_NAMES); private static final Set<String> SCOPE_CALLEES = Set.copyOf(SCOPE_CALLEE_NAMES);
private static final String SCOPE_CALLEE_LABEL = String.join("/", SCOPE_CALLEE_NAMES); private static final String SCOPE_CALLEE_LABEL = String.join("/", SCOPE_CALLEE_NAMES);
@@ -448,64 +458,20 @@ class CompanyIdParamGoesThroughReadScopeTest {
"""; """;
/** /**
* 第二条正门({@code readCompanyId})的<b>正探针</b>:形状逐字抄现网那一支 * 第二道正门({@code readCompanyIdOrOwn})的<b>正探针</b>:形状抄现网
* ({@code InvalidAsinDataController.page} —— 先 {@code operator.user()} 把实体取出来, * {@code ShopKeyController.list} —— 门给什么是什么,controller 不自己补。
* 再 {@code Long scopedCompanyId = dataReadScope.readCompanyId(user, companyId);}, * C 的两步与 D 都必须在这一形上判绿,否则密钥页红在护栏上而不是红在缺陷上。
* 最后把 {@code scopedCompanyId} 交给 service)。
* <p>它证明的是"判据不是只认 {@code readScope} 那一族":C 的第 ①/② 步和 D 都必须在这一形上判绿,
* 否则五页里靠物化列给范围的那两页会红在护栏上,而不是红在真缺陷上。</p>
*/
private static final String READ_COMPANY_ID_CAUGHT_PROBE = """
@GetMapping("/probe")
public String typedDoor(@RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity user = operator.user();
Long scopedCompanyId = dataReadScope.readCompanyId(user, companyId);
return String.valueOf(invalidAsinDataService.page(1, 15, scopedCompanyId));
}
""";
/**
* 第二条正门的<b>裸语句探针</b>(C 第 ① 步在该门上的"能红"证据):
* {@code scopeCatchFailure} 是对两条门<b>逐条</b>跑那两步的,只在 {@code readScope} 上验过不算验过——
* 少了这一枚,"第二道门根本没人看守它的返回值"就能悄悄进仓。
*/
private static final String READ_COMPANY_ID_DISCARD_PROBE = """
@GetMapping("/probe")
public String typedDoorDiscard(@RequestParam(name = "company_id", required = false) Long companyId) {
dataReadScope.readCompanyId(user, companyId);
return "ok";
}
""";
/**
* 第二条正门的<b>负探针</b>(D 在该门上的存在理由):出口调了、结果接住了、也喂给 service 了,
* 唯独进出口的是 {@code null} —— 与 {@link #SCOPE_PASSED_NULL_PROBE} 同一记刀,只是换了道门。
* A/B/C 三条前提在自检里逐条钉住为绿,才说明这一刀今天确实只有 D 会喊。
*/
private static final String READ_COMPANY_ID_PASSED_NULL_PROBE = """
@GetMapping("/probe")
public String typedDoorNull(@RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity user = operator.user();
Long scopedCompanyId = dataReadScope.readCompanyId(user, null);
return String.valueOf(invalidAsinDataService.page(1, 15, scopedCompanyId));
}
""";
/**
* 第三道正门({@code readCompanyIdOrOwn})的<b>正探针</b>:形状抄现网
* {@code ProductCategoryController.list} —— 门给什么是什么,controller 不自己补。
* C 的两步与 D 都必须在这一形上判绿,否则类目页红在护栏上而不是红在缺陷上。
*/ */
private static final String READ_OWN_COMPANY_ID_CAUGHT_PROBE = """ private static final String READ_OWN_COMPANY_ID_CAUGHT_PROBE = """
@GetMapping("/probe") @GetMapping("/probe")
public String thirdDoor(@RequestParam(name = "company_id", required = false) Long companyId) { public String thirdDoor(@RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity user = operator.user(); AdminUserEntity user = operator.user();
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId); Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, companyId);
return String.valueOf(productCategoryService.list(null, scopedCompanyId)); return String.valueOf(shopKeyService.list(null, scopedCompanyId));
} }
"""; """;
/** 第三道正门的<b>裸语句探针</b>(C 第 ① 步在该门上的"能红"证据):算完直接丢,等于没筛。 */ /** 第二道正门的<b>裸语句探针</b>(C 第 ① 步在该门上的"能红"证据):算完直接丢,等于没筛。 */
private static final String READ_OWN_COMPANY_ID_DISCARD_PROBE = """ private static final String READ_OWN_COMPANY_ID_DISCARD_PROBE = """
@GetMapping("/probe") @GetMapping("/probe")
public String thirdDoorDiscard(@RequestParam(name = "company_id", required = false) Long companyId) { public String thirdDoorDiscard(@RequestParam(name = "company_id", required = false) Long companyId) {
@@ -514,13 +480,59 @@ class CompanyIdParamGoesThroughReadScopeTest {
} }
"""; """;
/** 第三道正门的<b>负探针</b>(D 在该门上的存在理由):进出口的是 {@code null},tab 恒不动。 */ /** 第二道正门的<b>负探针</b>(D 在该门上的存在理由):进出口的是 {@code null},tab 恒不动。 */
private static final String READ_OWN_COMPANY_ID_PASSED_NULL_PROBE = """ private static final String READ_OWN_COMPANY_ID_PASSED_NULL_PROBE = """
@GetMapping("/probe") @GetMapping("/probe")
public String thirdDoorNull(@RequestParam(name = "company_id", required = false) Long companyId) { public String thirdDoorNull(@RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity user = operator.user(); AdminUserEntity user = operator.user();
Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, null); Long scopedCompanyId = dataReadScope.readCompanyIdOrOwn(user, null);
return String.valueOf(productCategoryService.list(null, scopedCompanyId)); return String.valueOf(shopKeyService.list(null, scopedCompanyId));
}
""";
/**
* 第三道正门(菜单字典归属判据 {@code resolveScopeCompanyId})的<b>正探针</b>:
* 结果接进变量并喂给 {@code list(…)},公司参数本身进了门 —— C 与 D 都必须判它绿,
* 否则 {@code PermissionMenuController} 那六支 handler 全是假红。
*/
private static final String MENU_SCOPE_CAUGHT_PROBE = """
@GetMapping("/probe")
public String menuScopeDoor(@RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity user = operator.user();
Long scopeCompanyId = permissionMenuService.resolveScopeCompanyId(user, companyId);
return String.valueOf(permissionMenuService.list(user, "admin", false, scopeCompanyId));
}
""";
/** 第三道正门的<b>裸语句探针</b>(C 第 ① 步在该门上的"能红"证据):门调了、403 也发了,结果却没人接。 */
private static final String MENU_SCOPE_DISCARD_PROBE = """
@GetMapping("/probe")
public String menuScopeDoorDiscard(@RequestParam(name = "company_id", required = false) Long companyId) {
permissionMenuService.resolveScopeCompanyId(user, companyId);
return "ok";
}
""";
/** 第三道正门的<b>负探针</b>(D 在该门上的存在理由):门里进出的是 {@code null},切了 tab 取的还是操作者本公司。 */
private static final String MENU_SCOPE_PASSED_NULL_PROBE = """
@GetMapping("/probe")
public String menuScopeDoorNull(@RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity user = operator.user();
Long scopeCompanyId = permissionMenuService.resolveScopeCompanyId(user, null);
return String.valueOf(permissionMenuService.list(user, "admin", false, scopeCompanyId));
}
""";
/**
* 已摘掉那道门的<b>正样本探针</b>(形状抄退回前的 {@code InvalidAsinDataController.page}:
* 收 {@code company_id} 参数、体内调 {@code readCompanyId})。它现在应当被 A/C/D 三条同时判红——
* 红因必须落在"三条正门都没走"上,而不是"这段源码没被切成 handler"。
*/
private static final String RETIRED_DOOR_WIRED_PROBE = """
@GetMapping("/probe")
public String retiredDoorWired(@RequestParam(name = "company_id", required = false) Long companyId) {
Long scoped = dataReadScope.readCompanyId(user, companyId);
return String.valueOf(invalidAsinDataService.page(scoped));
} }
"""; """;
@@ -622,16 +634,6 @@ class CompanyIdParamGoesThroughReadScopeTest {
assertThat(scopeProbeReason(SCOPE_TYPE_FORM_PROBE, "SCOPE_TYPE_FORM_PROBE")) assertThat(scopeProbeReason(SCOPE_TYPE_FORM_PROBE, "SCOPE_TYPE_FORM_PROBE"))
.as("断言 C 自检(第二形):ReadScope s = dataReadScope.readScope(…) 且 s 进了 service.page(…) 的实参 ⇒ 同样要认") .as("断言 C 自检(第二形):ReadScope s = dataReadScope.readScope(…) 且 s 进了 service.page(…) 的实参 ⇒ 同样要认")
.isNull(); .isNull();
// 第二条正门必须<b>各自</b>有能红/能绿两向证据:C 的判据是对 SCOPE_DOORS 逐条跑的,
// 只在 readScope 上验过,就等于没验过 readCompanyId —— 那一道门上的返回值会没人看守。
assertThat(scopeProbeReason(READ_COMPANY_ID_CAUGHT_PROBE, "READ_COMPANY_ID_CAUGHT_PROBE"))
.as("断言 C 自检(第二道门·正样本):Long scopedCompanyId = dataReadScope.readCompanyId(user, companyId) "
+ "且它进了 service.page(…) 的实参 ⇒ 该判这一形绿,判红就是护栏假红(现网品牌库/商品类目都是这形)")
.isNull();
assertThat(scopeProbeReason(READ_COMPANY_ID_DISCARD_PROBE, "READ_COMPANY_ID_DISCARD_PROBE"))
.as("断言 C 自检(第二道门·负样本):readCompanyId( 写成裸语句、结果当场丢掉 ⇒ 必须判红")
.isNotNull()
.contains("范围算了但没接住");
// 断言 D 的判据自检(两个方向都要,全局约束 15)。负探针要先证明"A/B/C 三条对它都判通过"—— // 断言 D 的判据自检(两个方向都要,全局约束 15)。负探针要先证明"A/B/C 三条对它都判通过"——
// 这三条前提不成立就说明这段源码本来已经有人看守,D 没有区分度、只是重复劳动。 // 这三条前提不成立就说明这段源码本来已经有人看守,D 没有区分度、只是重复劳动。
@@ -662,45 +664,80 @@ class CompanyIdParamGoesThroughReadScopeTest {
.as("断言 D 自检(改名那一族):参数声明叫 orgId、交出去的也是 orgId ⇒ 不许红" .as("断言 D 自检(改名那一族):参数声明叫 orgId、交出去的也是 orgId ⇒ 不许红"
+ "(这条同时钉住\"D 不许硬编码 companyId\":写死了它就会在这一支假红)") + "(这条同时钉住\"D 不许硬编码 companyId\":写死了它就会在这一支假红)")
.isNull(); .isNull();
// 第二道门上的 D:先钉 A/B/C 三条前提对它同样全绿(换了道门不等于换了缺陷形状),再钉 D 必须红。
String typedNullProbeText = String.join("\n", textsOf(sourceLines(READ_COMPANY_ID_PASSED_NULL_PROBE)));
assertThat(typedNullProbeText)
.as("断言 D(第二道门)负样本的前提(断言 A/B):readCompanyId( 在 handler 体内、name = \"company_id\" 也在")
.contains(READ_COMPANY_ID_CALL)
.contains(EXPLICIT_PARAM_NAME);
assertThat(scopeProbeReason(READ_COMPANY_ID_PASSED_NULL_PROBE, "READ_COMPANY_ID_PASSED_NULL_PROBE"))
.as("断言 D(第二道门)负样本的前提(断言 C):结果接进 scopedCompanyId 又喂给了 service ⇒ C 判它绿")
.isNull();
assertThat(companyIdArgProbeReason(
READ_COMPANY_ID_PASSED_NULL_PROBE, "READ_COMPANY_ID_PASSED_NULL_PROBE", CAMEL_PARAM))
.as("断言 D 自检(第二道门·负样本):readCompanyId(user, null) —— 出口调了、门也认了,"
+ "tab 传下来的值仍没进出口 ⇒ 同样必须判红(D 不能只咬 readScope 那一族)")
.isNotNull()
.contains("没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表");
// 第三道门同样要各自带能红/能绿两向证据:C 与 D 都是对 SCOPE_DOORS 逐条跑的, // 第二道门同样要各自带能红/能绿两向证据:C 与 D 都是对 SCOPE_DOORS 逐条跑的,
// 少一枚探针就等于那道门上的返回值与入参没人看守(类目页正是走这道门的页)。 // 少一枚探针就等于那道门上的返回值与入参没人看守(店铺密钥页正是走这道门的页)。
assertThat(scopeProbeReason(READ_OWN_COMPANY_ID_CAUGHT_PROBE, "READ_OWN_COMPANY_ID_CAUGHT_PROBE")) assertThat(scopeProbeReason(READ_OWN_COMPANY_ID_CAUGHT_PROBE, "READ_OWN_COMPANY_ID_CAUGHT_PROBE"))
.as("断言 C 自检(第三道门·正样本):Long scopedCompanyId = readCompanyIdOrOwn(user, companyId) " .as("断言 C 自检(第二道门·正样本):Long scopedCompanyId = readCompanyIdOrOwn(user, companyId) "
+ "且它进了 service.list(…) 的实参 ⇒ 判红就是护栏假红") + "且它进了 service.list(…) 的实参 ⇒ 判红就是护栏假红")
.isNull(); .isNull();
assertThat(companyIdArgProbeReason( assertThat(companyIdArgProbeReason(
READ_OWN_COMPANY_ID_CAUGHT_PROBE, "READ_OWN_COMPANY_ID_CAUGHT_PROBE", CAMEL_PARAM)) READ_OWN_COMPANY_ID_CAUGHT_PROBE, "READ_OWN_COMPANY_ID_CAUGHT_PROBE", CAMEL_PARAM))
.as("断言 D 自检(第三道门·正样本):companyId 真进了 readCompanyIdOrOwn 的实参表 ⇒ 不许红") .as("断言 D 自检(第二道门·正样本):companyId 真进了 readCompanyIdOrOwn 的实参表 ⇒ 不许红")
.isNull(); .isNull();
assertThat(scopeProbeReason(READ_OWN_COMPANY_ID_DISCARD_PROBE, "READ_OWN_COMPANY_ID_DISCARD_PROBE")) assertThat(scopeProbeReason(READ_OWN_COMPANY_ID_DISCARD_PROBE, "READ_OWN_COMPANY_ID_DISCARD_PROBE"))
.as("断言 C 自检(第三道门·负样本):readCompanyIdOrOwn( 写成裸语句、结果当场丢掉 ⇒ 必须判红") .as("断言 C 自检(第二道门·负样本):readCompanyIdOrOwn( 写成裸语句、结果当场丢掉 ⇒ 必须判红")
.isNotNull() .isNotNull()
.contains("范围算了但没接住"); .contains("范围算了但没接住");
assertThat(scopeProbeReason(READ_OWN_COMPANY_ID_PASSED_NULL_PROBE, "READ_OWN_COMPANY_ID_PASSED_NULL_PROBE")) assertThat(scopeProbeReason(READ_OWN_COMPANY_ID_PASSED_NULL_PROBE, "READ_OWN_COMPANY_ID_PASSED_NULL_PROBE"))
.as("断言 D(第三道门)负样本的前提(断言 C):结果接进 scopedCompanyId 又喂给了 service ⇒ C 判它绿") .as("断言 D(第二道门)负样本的前提(断言 C):结果接进 scopedCompanyId 又喂给了 service ⇒ C 判它绿")
.isNull(); .isNull();
assertThat(companyIdArgProbeReason( assertThat(companyIdArgProbeReason(
READ_OWN_COMPANY_ID_PASSED_NULL_PROBE, "READ_OWN_COMPANY_ID_PASSED_NULL_PROBE", CAMEL_PARAM)) READ_OWN_COMPANY_ID_PASSED_NULL_PROBE, "READ_OWN_COMPANY_ID_PASSED_NULL_PROBE", CAMEL_PARAM))
.as("断言 D 自检(第三道门·负样本):readCompanyIdOrOwn(user, null) ⇒ 必须判红") .as("断言 D 自检(第二道门·负样本):readCompanyIdOrOwn(user, null) ⇒ 必须判红")
.isNotNull() .isNotNull()
.contains("没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表"); .contains("没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表");
// 第三道门(菜单字典)同样各自带能红/能绿两向证据:它今天有六个真实消费者
// (PermissionMenuController 的目录/新建/两页数据范围授权的读与写),只钉"名单里有这个名字"
// 而不验返回值与入参,等于那六支 handler 的 tab 可以随便坏。
assertThat(scopeProbeReason(MENU_SCOPE_CAUGHT_PROBE, "MENU_SCOPE_CAUGHT_PROBE"))
.as("断言 C 自检(第三道门·正样本):Long scopeCompanyId = resolveScopeCompanyId(user, companyId) "
+ "且它进了 permissionMenuService.list(…) ⇒ 判红就是护栏假红")
.isNull();
assertThat(companyIdArgProbeReason(MENU_SCOPE_CAUGHT_PROBE, "MENU_SCOPE_CAUGHT_PROBE", CAMEL_PARAM))
.as("断言 D 自检(第三道门·正样本):companyId 真进了 resolveScopeCompanyId 的实参表 ⇒ 不许红")
.isNull();
assertThat(scopeProbeReason(MENU_SCOPE_DISCARD_PROBE, "MENU_SCOPE_DISCARD_PROBE"))
.as("断言 C 自检(第三道门·负样本):resolveScopeCompanyId( 写成裸语句、结果当场丢掉 ⇒ 必须判红")
.isNotNull()
.contains("范围算了但没接住");
assertThat(scopeProbeReason(MENU_SCOPE_PASSED_NULL_PROBE, "MENU_SCOPE_PASSED_NULL_PROBE"))
.as("断言 D(第三道门)负样本的前提(断言 C):结果接进 scopeCompanyId 又喂给了 list ⇒ C 判它绿")
.isNull();
assertThat(companyIdArgProbeReason(
MENU_SCOPE_PASSED_NULL_PROBE, "MENU_SCOPE_PASSED_NULL_PROBE", CAMEL_PARAM))
.as("断言 D 自检(第三道门·负样本):resolveScopeCompanyId(user, null) ⇒ 必须判红")
.isNotNull()
.contains("没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表");
// 已摘掉的那道门不许再接回(全局约束 15 的"能红"方向)。这一族 handler(品牌库、商品类目)现在定案
// 全平台共享、不再收公司参数 ⇒ 它们已不进 A/C/D 的样本,"哪天有人把 ?company_id= 接回这两张表"
// 只剩这条探针还在求值,而今天真正拦它的是断言 A:C 与 D 在主循环里都以"体内有正门调用"为前提
// ({@link Block#hasScopeCall()}),只调已摘那道门时它们根本不求值 —— 把这层写成注释而不是三条全红,
// 是因为下一条要钉的就是"D 的名单里不许提前把 readCompanyId 加回来"。
// 前提同样要自证:探针真被切成 1 支收公司 id 参数的 handler、体内一条现存正门都没有、
// 但确实调了 readCompanyId( —— 否则"判红"只是"源码没读到"的另一种形状。
List<Block> retiredDoorBlocks = splitBlocks(sourceLines(RETIRED_DOOR_WIRED_PROBE)).handlers();
assertThat(retiredDoorBlocks)
.as("已摘门探针切不出 handler ⇒ 下面几条判红断言是空跑")
.hasSize(1);
Block retiredDoor = retiredDoorBlocks.get(0);
assertThat(retiredDoor.takesCompanyParam())
.as("已摘门探针没被认成收公司 id 参数(参数形状变了)⇒ A 不会对它求值,这条反向钉没有内容")
.isTrue();
assertThat(retiredDoor.text())
.as("已摘门探针的反面证据:它确实调了 readCompanyId(,这正是定案不许再接回的那一形")
.contains("readCompanyId(");
assertThat(anyScopeDoor(retiredDoor.text()))
.as("断言 A(已摘门):这条 handler 体内一条现存正门都没走过 ⇒ A 必然落进判红分支。"
+ "这里若为 true,说明探针混进了别的正门调用,A 不再是这一形的守门人,本用例失去内容")
.isFalse();
assertThat(retiredDoor.companyIdArgFailure())
.as("断言 D 对被调名单的看守:readCompanyId 一旦被人加回 SCOPE_CALLEE_NAMES(门还没接回、"
+ "名单先到),这一形就会被 D 判绿 ⇒ 这条必须保持判红")
.isNotNull();
// 配对括号取实参表(放宽)的成对证据:两枚正样本必须绿(否则 6 支已接线 handler 假红), // 配对括号取实参表(放宽)的成对证据:两枚正样本必须绿(否则 6 支已接线 handler 假红),
// 一枚"嵌套了但没带公司参数"的样本必须照旧红(否则放宽 = 把 D 关掉)。 // 一枚"嵌套了但没带公司参数"的样本必须照旧红(否则放宽 = 把 D 关掉)。
assertThat(scopeProbeReason(SCOPE_NESTED_ARG_PROBE, "SCOPE_NESTED_ARG_PROBE")) assertThat(scopeProbeReason(SCOPE_NESTED_ARG_PROBE, "SCOPE_NESTED_ARG_PROBE"))
@@ -865,6 +902,138 @@ class CompanyIdParamGoesThroughReadScopeTest {
.isEmpty(); .isEmpty();
} }
/**
* 10-06 定案"全平台共享、不区分公司"的两张表:{@code biz_invalid_asin_data}(品牌数据库)、
* {@code biz_product_category}(商品类目)。名单按 <b>module 目录</b>给而不是按 controller——
* 这两页的公司维度原先落在 entity 列、mapper 幂等键和 service 谓词上,只盯 controller 会漏掉那三段。
*
* <p>为什么不能只靠"退出 {@link #WIRED_PAGE_KEYS}":射程名单管的是"收了公司参数的 handler 必须走正门",
* 一页一旦不再收参数就不进样本,A/C/D 三条一起对它停止求值——"哪天有人把 {@code ?company_id=} 接回去"
* 恰好只剩这一条反向钉看得见。</p>
*/
private static final List<String> SHARED_TABLES_MUST_STAY_UNSCOPED = List.of(
"com/nanri/aiimage/modules/invalidasin",
"com/nanri/aiimage/modules/productcategory");
/** 这两张表的类型名锚:module 目录之外的引用者(自动导入那条写侧路)按它取样。 */
private static final List<String> SHARED_TABLE_TYPE_ANCHORS = List.of("InvalidAsinData", "ProductCategory");
/**
* 正样本目录:店铺密钥到今天仍是按公司取数的那一族({@code biz_shop_key},V150)。
* 同一把尺子必须在这里量出命中,否则"共享目录零命中"可能只是尺子坏了(全局约束 15)。
*/
private static final String STILL_SCOPED_MODULE_DIR = "com/nanri/aiimage/modules/shopkey";
private static final String DATA_READ_SCOPE_FILE = "com/nanri/aiimage/common/service/DataReadScope.java";
/** 公司 token 的尺子:整词大小写不敏感,比 {@code company_id}/{@code companyId} 两种写法都宽(含 {@code CompanyScopeSupport})。 */
private static final Pattern ANY_COMPANY_TOKEN = Pattern.compile("(?i)company");
@Test
@DisplayName("品牌库 / 商品类目已定案全平台共享:公司维度不许回流到这两张表的任何一处,出口上也不许再有那条门")
void companyDimensionMustNotFlowBackIntoTheTwoSharedTables() throws IOException {
// ① 尺子自证:同一把尺子必须在仍按公司取数的目录上量出命中,否则下面"共享目录零命中"全是空断言。
List<String> scopedHits = companyTokenLines(STILL_SCOPED_MODULE_DIR);
assertThat(scopedHits)
.as("公司 token 尺子在仍按公司取数的 %s 上零命中 ⇒ 尺子或取样坏了,后面的反向钉全是空断言",
STILL_SCOPED_MODULE_DIR)
.isNotEmpty();
// ② 两张共享表:目录里必须扫得到 .java(目录被改名/挪走也算红,那等于没人看守),且可执行行零公司 token。
for (String dir : SHARED_TABLES_MUST_STAY_UNSCOPED) {
assertThat(javaFilesUnder(dir))
.as("%s 扫不到 .java:目录被改名或挪走了,这条反向钉对它已经不再求值", dir)
.isNotEmpty();
assertThat(companyTokenLines(dir))
.as("品牌数据库 / 商品类目 2026-10-06 定案全平台共享(唯一键退回全局、页面不画公司 tab):"
+ "这两张表的 entity 列、mapper 幂等键、service 谓词、controller 参数都不许再出现公司维度"
+ "(只打可执行行,注释里『故意没有这一列』的说明不算)")
.isEmpty();
}
// ③ 目录外那几处引用这两张表的消费者同样不许带公司维度;锚本身要自证真取到了人。
List<String> consumers = sharedTableConsumerFiles();
assertThat(consumers)
.as("按类型名锚 %s 在两个 module 目录之外连自动导入那条写侧路都没取到 ⇒ 锚失效,这一族没人看守",
SHARED_TABLE_TYPE_ANCHORS)
.contains("com/nanri/aiimage/modules/collectdata/util/CollectDataInvalidAsinBatchWriter.java");
List<String> consumerHits = new ArrayList<>();
for (String rel : consumers) {
consumerHits.addAll(companyTokenLinesInFile(MAIN_ROOT.resolve(rel)));
}
assertThat(consumerHits)
.as("引用这两张表的外部消费者里出现了公司维度——自动导入「推不出公司就整批不写」那道闸门已定案放开,"
+ "把它接回去等于让整批 AUTO 行静默丢失")
.isEmpty();
// ④ 出口这一侧:readCompanyId 是专为这两页的「超管按 tab 选哪家」加的,两页退掉后全树零消费者,已删。
// 先钉同一族的 readCompanyIdOrOwn 还读得到,否则 noneMatch 只是"文件读空"的另一种绿。
List<String> scopeLines = executableLines(read(MAIN_ROOT.resolve(DATA_READ_SCOPE_FILE)));
assertThat(scopeLines)
.as("%s 里一行可执行行都没读到 ⇒ 门检查是空断言", DATA_READ_SCOPE_FILE)
.isNotEmpty();
assertThat(scopeLines.stream().anyMatch(line -> line.contains(READ_OWN_COMPANY_ID_CALL)))
.as("DataReadScope 上那条 OrOwn 门读不到了(改名或删除都要一起改这里):先确认这份文件真被扫到,"
+ "再谈『readCompanyId 不该存在』")
.isTrue();
assertThat(scopeLines.stream().noneMatch(line -> line.contains("readCompanyId(")))
.as("readCompanyId 又回到了 DataReadScope 上:品牌库/商品类目已定案共享,"
+ "一门没有实现者的正门留在出口名单里,等于给公司开关预先铺好合规形状")
.isTrue();
}
/** 某 module 目录(相对 {@code src/main/java},正斜杠)下的全部 {@code .java},按路径排序;目录不存在给空表,由调用方判红。 */
private static List<Path> javaFilesUnder(String moduleDir) throws IOException {
Path root = MAIN_ROOT.resolve(moduleDir);
if (!Files.isDirectory(root)) return List.of();
try (Stream<Path> walk = Files.walk(root)) {
return walk.filter(Files::isRegularFile)
.filter(p -> p.getFileName().toString().endsWith(".java"))
.sorted()
.collect(Collectors.toList());
}
}
/** 一个目录下所有可执行行上的公司 token,报 {@code 相对路径: 行文本}(不带行号:行号会随无关提交漂,文件名+原文足够定位)。 */
private static List<String> companyTokenLines(String moduleDir) throws IOException {
List<String> hits = new ArrayList<>();
for (Path file : javaFilesUnder(moduleDir)) {
hits.addAll(companyTokenLinesInFile(file));
}
return hits;
}
private static List<String> companyTokenLinesInFile(Path file) {
String rel = relativeKey(file);
return executableLines(read(file)).stream()
.filter(line -> ANY_COMPANY_TOKEN.matcher(line).find())
.map(line -> rel + ": " + line)
.collect(Collectors.toList());
}
/**
* 两个 module 目录之外、可执行行里点到这两张表类型名的 main 文件(相对 {@code src/main/java}、正斜杠、排序)。
* 口径同第 1 条:只打可执行行,注释里提一句类名不算引用。
*/
private static List<String> sharedTableConsumerFiles() throws IOException {
List<String> consumers = new ArrayList<>();
try (Stream<Path> walk = Files.walk(MAIN_ROOT)) {
List<Path> files = walk.filter(Files::isRegularFile)
.filter(p -> p.getFileName().toString().endsWith(".java"))
.sorted()
.collect(Collectors.toList());
for (Path file : files) {
String rel = relativeKey(file);
if (SHARED_TABLES_MUST_STAY_UNSCOPED.stream().anyMatch(rel::startsWith)) continue;
if (executableLines(read(file)).stream()
.anyMatch(line -> SHARED_TABLE_TYPE_ANCHORS.stream().anyMatch(line::contains))) {
consumers.add(rel);
}
}
}
return consumers;
}
/** /**
* 断言 C 的探针驱动器:先确认这段样本真被切成"1 支收公司 id 参数、体内写了 readScope(" 的 handler, * 断言 C 的探针驱动器:先确认这段样本真被切成"1 支收公司 id 参数、体内写了 readScope(" 的 handler,
* 再跑 {@link Block#scopeCatchFailure()}。切不出 handler / 不认公司参数 / 没有 readScope( 这三种 * 再跑 {@link Block#scopeCatchFailure()}。切不出 handler / 不认公司参数 / 没有 readScope( 这三种
@@ -880,7 +1049,8 @@ class CompanyIdParamGoesThroughReadScopeTest {
.as(probeName + " 的 handler 没被认成收公司 id 参数,断言 C 根本不会触发 ⇒ 探针失效") .as(probeName + " 的 handler 没被认成收公司 id 参数,断言 C 根本不会触发 ⇒ 探针失效")
.isTrue(); .isTrue();
assertThat(anyScopeDoor(handler.text())) assertThat(anyScopeDoor(handler.text()))
.as(probeName + " 的 handler 体内两条正门都没走(readScope( / readCompanyId(),断言 C 扫不到它 ⇒ 探针失效") .as(probeName + " 的 handler 体内一条正门都没走(" + String.join(" / ", SCOPE_DOORS)
+ "),断言 C 扫不到它 ⇒ 探针失效")
.isTrue(); .isTrue();
return handler.scopeCatchFailure(); return handler.scopeCatchFailure();
} }
@@ -966,7 +1136,7 @@ class CompanyIdParamGoesThroughReadScopeTest {
return line.contains(SNAKE_PARAM) || line.contains(CAMEL_PARAM); return line.contains(SNAKE_PARAM) || line.contains(CAMEL_PARAM);
} }
/** 两条正门之一有没有在这段文本里出现过(A/C 的判据都走它,不各写一份)。 */ /** 任一条正门有没有在这段文本里出现过(A/C 的判据都走它,不各写一份)。 */
private static boolean anyScopeDoor(String text) { private static boolean anyScopeDoor(String text) {
return SCOPE_DOORS.stream().anyMatch(text::contains); return SCOPE_DOORS.stream().anyMatch(text::contains);
} }
@@ -1294,7 +1464,7 @@ class CompanyIdParamGoesThroughReadScopeTest {
return null; return null;
} }
/** 逐条正门跑"接住 → 交出去"两步:两条门都得走这两步,第二道门不能成为绕过第一道门判据的后门。 */ /** 逐条正门跑"接住 → 交出去"两步:三道门都得走这两步,后一道不能成为绕过前一道判据的后门。 */
private static String scopeCatchFailureFor(String src, String door) { private static String scopeCatchFailureFor(String src, String door) {
for (int at = src.indexOf(door); at >= 0; for (int at = src.indexOf(door); at >= 0;
at = src.indexOf(door, at + door.length())) { at = src.indexOf(door, at + door.length())) {
@@ -1397,7 +1567,7 @@ class CompanyIdParamGoesThroughReadScopeTest {
* 与 A/B/C 同一个 handler 窗口)。 * 与 A/B/C 同一个 handler 窗口)。
* <ul> * <ul>
* <li>{@code dataReadScope.readScope(operator, companyId)} ⇒ 绿;</li> * <li>{@code dataReadScope.readScope(operator, companyId)} ⇒ 绿;</li>
* <li>{@code dataReadScope.readCompanyId(user, companyId)}(第二条正门)⇒ 绿;</li> * <li>{@code dataReadScope.readCompanyIdOrOwn(user, companyId)}(第二条正门)⇒ 绿;</li>
* <li>{@code resolveScope(request, companyId)}(私有收口方法内部再去 readScope)⇒ 绿;</li> * <li>{@code resolveScope(request, companyId)}(私有收口方法内部再去 readScope)⇒ 绿;</li>
* <li>{@code readScope(operator, normalizeCompany(companyId))} ⇒ <b>绿</b>:嵌套写法自 10-05 * <li>{@code readScope(operator, normalizeCompany(companyId))} ⇒ <b>绿</b>:嵌套写法自 10-05
* 批次 2/3 起算消费(第 13 条:旧单层正则在这一形上判红,而那正是断言 A 逼出来的形状), * 批次 2/3 起算消费(第 13 条:旧单层正则在这一形上判红,而那正是断言 A 逼出来的形状),
@@ -119,42 +119,22 @@ class DataReadScopeTest {
.isInstanceOf(com.nanri.aiimage.common.exception.BusinessException.class); .isInstanceOf(com.nanri.aiimage.common.exception.BusinessException.class);
} }
// ---- 第二条正门:归属已物化成 company_id 列的表(品牌库、商品类目)---- // ---- 第二道正门 readCompanyIdOrOwn:归属已物化成 company_id 列、且可见集不靠账号/分组的表 ----
// 这一道门的语义与 readScope 相反方向:返回的是"要筛哪个公司",null = 不筛。 // 语义与 readScope 相反方向:返回的是"要筛哪个公司",null = 不筛。今天的消费者是店铺密钥
// 非超管一律 null(他们的可见集本来就锁在自己的分组上,再叠一层公司会把"靠分组可见"的行整批删掉, // biz_shop_key(V150 起每公司一套,表里没有账号列)。
// 见 DataReadScope#readCompanyId 的注释)。这三条若不写,把 `return null` 改成 //
// `return companyScope.requireCompanyId(operator)` 不会让任何现有用例变红——而那一改的后果是 // 这里原先还有一道 readCompanyId:为品牌库/商品类目那两个"物化列 + 非超管靠分组可见"的表而写,
// 品牌库里靠分组可见的历史行从每个非超管账号下消失。 // 非超管一律返回 null(叠一层公司会把靠分组可见的行整批删掉)。2026-10-06 控制方定案那两页
// 全平台共享、不区分公司,方法已从 DataReadScope 删除、全树零消费者,这三条用例一起摘掉。
// "不许再接回"由 CompanyIdParamGoesThroughReadScopeTest#companyDimensionMustNotFlowBackIntoTheTwoSharedTables
// 反向钉(它同时钉住出口上没有这道门),不靠这里留一份无人调用的行为规格。
// 这一道门与 readScope 只差非超管那一支,而那一支正是 10-06 逐节点复验抓到的洞:表里连账号列都没有,
// 非超管返回 null=把整张表交给每一家(实测公司 2 的 admin 读到 412 行、其中 394 行是公司 1 的数据)。
// 这三条若不写,把 `requireCompanyId` 改回 `return null` 不会让任何现有用例变红。
@Test @Test
@DisplayName("第二道门:超管选公司 = 原样给回那一列的筛值") @DisplayName("第二道门:超管仍按 tab 走(tab 是视图开关,不是安全边界)")
void readCompanyIdForSuperAdminReturnsTheTab() {
assertThat(dataReadScope.readCompanyId(user(1L, "super_admin", 1L), 2L)).isEqualTo(2L);
}
@Test
@DisplayName("第二道门:超管不选 / 选 0 / 选负数都归一化成「不筛」,不是去查 0 号公司")
void readCompanyIdForSuperAdminNormalisesMissingAndNonPositive() {
assertThat(dataReadScope.readCompanyId(user(1L, "super_admin", 1L), null)).isNull();
assertThat(dataReadScope.readCompanyId(user(1L, "super_admin", 1L), 0L)).isNull();
assertThat(dataReadScope.readCompanyId(user(1L, "super_admin", 1L), -3L)).isNull();
}
@Test
@DisplayName("第二道门:非超管一律 null,别家的 tab 也不炸、也不筛")
void readCompanyIdForNonSuperAdminAlwaysMeansNoFilter() {
assertThat(dataReadScope.readCompanyId(user(5L, "admin", 2L), 2L)).isNull();
assertThat(dataReadScope.readCompanyId(user(5L, "admin", 2L), 7L)).isNull();
assertThat(dataReadScope.readCompanyId(user(5L, "admin", 2L), null)).isNull();
}
// ---- 第三道门 readCompanyIdOrOwn:归属物化列、且可见集不靠账号/分组的表(商品类目)----
// 与第二道门只差非超管那一支,而那一支正是 10-06 逐节点复验抓到的洞:biz_product_category 连账号列
// 都没有,非超管返回 null=把整棵树交给每一家(实测公司 2 的 admin 读到 412 行、其中 394 行是公司 1
// 的自建类目)。这三条若不写,把 `requireCompanyId` 改回 `return null` 不会让任何现有用例变红。
@Test
@DisplayName("第三道门:超管仍按 tab 走(tab 是视图开关,不是安全边界)")
void readOwnDoorForSuperAdminFollowsTheTab() { void readOwnDoorForSuperAdminFollowsTheTab() {
assertThat(dataReadScope.readCompanyIdOrOwn(user(1L, "super_admin", 1L), 2L)).isEqualTo(2L); assertThat(dataReadScope.readCompanyIdOrOwn(user(1L, "super_admin", 1L), 2L)).isEqualTo(2L);
assertThat(dataReadScope.readCompanyIdOrOwn(user(1L, "super_admin", 1L), null)).isNull(); assertThat(dataReadScope.readCompanyIdOrOwn(user(1L, "super_admin", 1L), null)).isNull();
@@ -163,18 +143,18 @@ class DataReadScopeTest {
} }
@Test @Test
@DisplayName("第三道门:非超管钉本公司,带别家的 tab 也不越权、也不返回空") @DisplayName("第二道门:非超管钉本公司,带别家的 tab 也不越权、也不返回空")
void readOwnDoorPinsNonSuperAdminToItsOwnCompany() { void readOwnDoorPinsNonSuperAdminToItsOwnCompany() {
when(companyScope.requireCompanyId(any(AdminUserEntity.class))).thenReturn(2L); when(companyScope.requireCompanyId(any(AdminUserEntity.class))).thenReturn(2L);
assertThat(dataReadScope.readCompanyIdOrOwn(user(5L, "admin", 2L), 2L)).isEqualTo(2L); assertThat(dataReadScope.readCompanyIdOrOwn(user(5L, "admin", 2L), 2L)).isEqualTo(2L);
// 传 7(别家)必须还是 2:类目树没有"空树"这个可用视图,返回空集等于把那一家自己的自建项也删掉。 // 传 7(别家)必须还是 2:这类表没有"空视图"这个可用状态,返回空集等于把那一家自己的数据也删掉。
assertThat(dataReadScope.readCompanyIdOrOwn(user(5L, "admin", 2L), 7L)).isEqualTo(2L); assertThat(dataReadScope.readCompanyIdOrOwn(user(5L, "admin", 2L), 7L)).isEqualTo(2L);
assertThat(dataReadScope.readCompanyIdOrOwn(user(5L, "admin", 2L), null)).isEqualTo(2L); assertThat(dataReadScope.readCompanyIdOrOwn(user(5L, "admin", 2L), null)).isEqualTo(2L);
} }
/** 「公司超级管理员」在这三道门里都按非超管处理——它不是 super_admin,这一支若漂了就是整家公司越权。 */ /** 「公司超级管理员」在这两道门里都按非超管处理——它不是 super_admin,这一支若漂了就是整家公司越权。 */
@Test @Test
@DisplayName("第三道门:company_super_admin 按非超管钉本公司,不当站点超管") @DisplayName("第二道门:company_super_admin 按非超管钉本公司,不当站点超管")
void readOwnDoorTreatsCompanySuperAdminAsNonSuperAdmin() { void readOwnDoorTreatsCompanySuperAdminAsNonSuperAdmin() {
when(companyScope.requireCompanyId(any(AdminUserEntity.class))).thenReturn(2L); when(companyScope.requireCompanyId(any(AdminUserEntity.class))).thenReturn(2L);
assertThat(dataReadScope.readCompanyIdOrOwn(user(9L, "company_super_admin", 2L), null)).isEqualTo(2L); assertThat(dataReadScope.readCompanyIdOrOwn(user(9L, "company_super_admin", 2L), null)).isEqualTo(2L);
@@ -326,18 +326,56 @@ class CompanyScopeMigrationV145Test {
} }
/** /**
* 破坏点:头注释喊了哨兵,哨兵却没探这两列 ⇒ "有人盯着摘 DEFAULT"这件事是假的。 * 破坏点:头注释喊了哨兵,哨兵却没探这一列 ⇒ "有人盯着摘 DEFAULT"这件事是假的。
* 这条把文档承诺与代码实现对齐(§10 护栏 1 的可执行部分)。 * 这条把文档承诺与代码实现对齐(§10 护栏 1 的可执行部分)。
*
* <p>2026-10-06 口径变更后,本用例的"对齐对象"从 V145 的头注释移到了 V151 的头注释——
* 那一笔才是现在的说法。两张表在这里分道:{@code biz_dedupe_total_data} 仍每公司一套,
* DEFAULT 的倒计时还在;{@code biz_invalid_asin_data} 随「全平台共享」定案<b>退出</b>哨兵清单,
* 它的 DEFAULT 从"待摘"翻转成 {@code NOT NULL} 的承重约束(新 jar 的 INSERT 不带这一列,
* 靠默认值填)。所以这一支既要钉它真的不在了,也要钉"不在"这件事在版本化的迁移注释里有据可查——
* 否则下一个人会照本文件头注释的旧承诺去执行 {@code DROP DEFAULT},把每次写入变成 1364。</p>
*/ */
@Test @Test
void startupSentinelActuallyWatchesTheTwoNewColumns() throws IOException { void startupSentinelStillWatchesDedupeAndV151RecordsWhyTheSharedOneLeft() throws IOException {
Path guard = ROOT.resolve("src/main/java/com/nanri/aiimage/modules/company/service/CompanyDefaultGuard.java"); Path guardFile = ROOT.resolve("src/main/java/com/nanri/aiimage/modules/company/service/CompanyDefaultGuard.java");
assertTrue(Files.isRegularFile(guard), "启动期 DEFAULT 哨兵应存在:" + guard); assertTrue(Files.isRegularFile(guardFile), "启动期 DEFAULT 哨兵应存在:" + guardFile);
String text = raw(guard); String text = raw(guardFile);
assertTrue(text.contains("COMPANY_DEFAULT_STILL_PRESENT"), "哨兵标记串必须保持 ASCII 原样(巡检按它 grep docker logs)"); assertTrue(text.contains("COMPANY_DEFAULT_STILL_PRESENT"), "哨兵标记串必须保持 ASCII 原样(巡检按它 grep docker logs)");
assertTrue(text.contains("'" + INVALID + "'"), "哨兵要探品牌库的 company_id,否则 V145 的 DEFAULT 没人盯");
assertTrue(text.contains("'" + DEDUPE + "'"), "哨兵要探去重库的 company_id");
assertTrue(text.contains("COLUMN_DEFAULT"), "哨兵应真的读列元数据,而不是靠猜"); assertTrue(text.contains("COLUMN_DEFAULT"), "哨兵应真的读列元数据,而不是靠猜");
List<String> watched = probeTables(text);
assertTrue(watched.contains(DEDUPE), "去重库仍按公司:它的 DEFAULT 必须还有人盯");
assertFalse(watched.contains(INVALID),
"品牌库已按「全平台共享」退出哨兵清单,哨兵不该再对它喊 DROP DEFAULT");
String sharedKeyMigration = raw(sharedKeyMigrationFile());
assertTrue(sharedKeyMigration.contains(INVALID),
"V151 的头注释要点名品牌库(它就是为这两张表退键而存在的)");
assertTrue(sharedKeyMigration.contains("1364") && sharedKeyMigration.contains("DROP DEFAULT"),
"退出哨兵的理由必须写在换键那一笔里:不写清 1364,"
+ "本文件头注释那条旧承诺就会让人去摘一个现在摘不得的默认值");
}
/** 取哨兵探针 SQL 的 {@code TABLE_NAME IN ('a', 'b')} 段;只认这一段,别把 {@code 'company_id'} 也算进来。 */
private static List<String> probeTables(String guardSource) {
Matcher inList = Pattern.compile("TABLE_NAME\\s+IN\\s*\\(([^)]*)\\)").matcher(guardSource);
assertTrue(inList.find(), "哨兵源码里没有 TABLE_NAME IN (…) 这一段,取不到清单");
List<String> tables = new ArrayList<>();
Matcher quoted = Pattern.compile("'([^']+)'").matcher(inList.group(1));
while (quoted.find()) {
tables.add(quoted.group(1));
}
assertFalse(tables.isEmpty(), "IN 列表解析出 0 张表 ⇒ contains/assertFalse 两条都会恒真或恒假");
return tables;
}
private static Path sharedKeyMigrationFile() throws IOException {
List<Path> hits = versionFiles().stream()
.filter(p -> p.getFileName().toString().startsWith("V151__"))
.toList();
assertEquals(1, hits.size(), "V151(两张共享表退回全局唯一键)应存在且只有一个:" + hits);
return hits.get(0);
} }
/** 破坏点:盘点文档没跟着改,下一个人按"取号起点"取号就撞号。 */ /** 破坏点:盘点文档没跟着改,下一个人按"取号起点"取号就撞号。 */
@@ -0,0 +1,553 @@
package com.nanri.aiimage.config;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* V149({@code columns} 从"全平台一棵菜单字典"改成"每家公司一套树")的文件审计。
* 设计:crawler-plugin/docs/ops/menu-company-tree-design-2026-10-06.md;
* 定案三条:D1 同笔迁移重指存量授权、D2 站点超管可带 company_id、D3 不复制 admin_companies。
*
* <p>本仓 pom 无 H2、无 testcontainers,迁移跑不起来,所以文件审计是唯一能守住的层——
* 与 {@link CompanyScopeMigrationV145Test} / {@link ProductCategoryMigrationV147Test} 同口径:
* 断言打在剥掉注释后的可执行 SQL 上,注释里的内容另用 {@link #rawMigration()} 单独钉。</p>
*
* <p>这一版和 V145/V147 最大的不同:它不是"加一列",而是<b>加列 + 换键 + 复制 + 重指授权</b>四件事
* 同批。只做前三件,第 2 家的账号一上线就掉光菜单(隐藏=静默删除);只做加列,
* {@code findDataPermission} 这类"按 column_key 点查 + LIMIT 1"会在同名多行里借位拿到别家的行。
* 所以下面每条破坏点都在问"这四件是不是真的都做完了、而且顺序对"。</p>
*/
class MenuTreeCompanyMigrationV149Test {
private static final Path ROOT = Path.of(System.getProperty("user.dir"));
private static final Path DB_DIR = ROOT.resolve("src/main/resources/db");
private static final String COLUMNS = "columns";
private static final String GRANTS = "user_column_permission";
/** 角色内在闸门那一行:设计定案 D3——唯一不复制的菜单。 */
private static final String GATE_KEY = "admin_companies";
// ---------------------------------------------------------------- 取文件
private static List<Path> versionFiles() throws IOException {
try (Stream<Path> s = Files.list(DB_DIR)) {
return s.filter(p -> p.getFileName().toString().matches("^V\\d+(?:_\\d+)?__.*\\.sql$"))
.sorted()
.toList();
}
}
private static int versionOf(Path p) {
Matcher m = Pattern.compile("^V(\\d+)(?:_\\d+)?__").matcher(p.getFileName().toString());
return m.find() ? Integer.parseInt(m.group(1)) : -1;
}
private static Path migration() throws IOException {
List<Path> hits = versionFiles().stream()
.filter(p -> p.getFileName().toString().startsWith("V149__"))
.toList();
assertFalse(hits.isEmpty(), "缺少 V149__*.sql:菜单树还没按公司分棵");
assertEquals(1, hits.size(), "V149 只允许一个迁移文件(撞号会让两台 java 同时起不来)");
return hits.get(0);
}
private static String raw(Path file) throws IOException {
return Files.readString(file, StandardCharsets.UTF_8);
}
private static String rawMigration() throws IOException {
return raw(migration());
}
private static String statements() throws IOException {
return normalize(stripComments(rawMigration()));
}
// ------------------------------------------------------------ SQL 预处理
// 与 CompanyScopeMigrationV145Test 逐字同实现:注释里的 -- 与字符串里的 -- 是两件事,
// 另写一版简化实现会让断言打在残缺 SQL 上。
private static String stripComments(String sql) {
StringBuilder out = new StringBuilder(sql.length());
int i = 0;
while (i < sql.length()) {
char c = sql.charAt(i);
if (c == '\'') {
int end = i + 1;
while (end < sql.length()) {
if (sql.charAt(end) == '\'') {
if (end + 1 < sql.length() && sql.charAt(end + 1) == '\'') {
end += 2;
continue;
}
break;
}
end++;
}
out.append(sql, i, Math.min(end + 1, sql.length()));
i = end + 1;
continue;
}
if (c == '-' && i + 1 < sql.length() && sql.charAt(i + 1) == '-') {
while (i < sql.length() && sql.charAt(i) != '\n') {
i++;
}
continue;
}
if (c == '/' && i + 1 < sql.length() && sql.charAt(i + 1) == '*') {
int end = sql.indexOf("*/", i + 2);
i = end < 0 ? sql.length() : end + 2;
continue;
}
out.append(c);
i++;
}
return out.toString();
}
private static String normalize(String sql) {
return sql.replaceAll("\\s+", " ").trim();
}
private static long count(String haystack, String needle) {
long n = 0;
int i = haystack.indexOf(needle);
while (i >= 0) {
n++;
i = haystack.indexOf(needle, i + needle.length());
}
return n;
}
/** 抽出所有形如 {@code ALTER TABLE `x`} 的表名,用于"只动这几张表"的判据。 */
private static List<String> alteredTables(String sql) {
List<String> hits = new ArrayList<>();
Matcher m = Pattern.compile("ALTER TABLE `([a-z_]+)`").matcher(sql);
while (m.find()) {
hits.add(m.group(1));
}
return hits;
}
/**
* 把旁路种子类的源切成"一条种子语句 = 一段":每个 {@code executeQuietly(} /
* {@code executeUpdateQuietly(} 的起点到下一个标记的起点。
* 只在<b>注释已剥、空白已归一</b>的源上切,所以类注释里那句"裸 {@code WHERE column_key = ...}"
* 不会被当成一条种子喂给判据。
*/
private static List<String> seedStatements(String normalizedSource) {
Matcher m = Pattern.compile("execute(?:Update)?Quietly\\(").matcher(normalizedSource);
List<Integer> starts = new ArrayList<>();
List<Integer> bodies = new ArrayList<>();
while (m.find()) {
starts.add(m.start());
bodies.add(m.end());
}
List<String> regions = new ArrayList<>();
for (int i = 0; i < bodies.size(); i++) {
int to = i + 1 < starts.size() ? starts.get(i + 1) : normalizedSource.length();
regions.add(normalizedSource.substring(bodies.get(i), to));
}
return regions;
}
/**
* 一把尺子:一段种子语句里凡按 {@code column_key} 认菜单的(写比较的,不是列清单里那个列名),
* 就必须在同一段里钉住 {@code company_id}。返回"按 key 认菜单却没钉公司"的那些段。
*/
private static List<String> keyLookupsWithoutCompany(List<String> regions) {
List<String> offenders = new ArrayList<>();
for (String region : regions) {
if (region.contains("column_key =") && !region.contains("company_id")) {
offenders.add(region);
}
}
return offenders;
}
// ------------------------------------------------------------------ 用例
/** 破坏点:取到已应用的号(原地改=两台都起不来),或者根本没落盘。 */
@Test
void migrationIsVersionedOneFourNine() throws IOException {
Path file = migration();
assertEquals(149, versionOf(file), "本迁移必须是 V149");
assertTrue(file.getFileName().toString().matches("^V149__[A-Za-z0-9_.-]+\\.sql$"),
"命名应 V149__<snake 描述>.sql:" + file.getFileName());
}
/**
* 破坏点:三段式少任何一段。少回填 ⇒ 第 3 段的 MODIFY 把存量行撞成 1048;
* 少 MODIFY ⇒ 列可空,"没有归属的行"在任何公司的树上都不出现,而按 key 点查会判成"这个菜单不存在"。
* 加列必须走<b>末位</b>(不许出现 {@code AFTER}):非末位加列能不能 INSTANT 取决于生产 MySQL 小版本,
* 押错了是发版窗口第 1 段直接 1846,而这一列的位置没有任何语义。
*/
@Test
void companyColumnIsAppendedBackfilledThenTightened() throws IOException {
String sql = statements();
assertTrue(sql.contains("ALTER TABLE `columns` ADD COLUMN `company_id` bigint NULL COMMENT"),
"第 1 段应先加成可空:" + sql);
assertEquals(1, count(sql, "ALGORITHM = INSTANT"), "只有加列这一条走 INSTANT");
assertEquals(0, count(sql, " AFTER "), "末位加列才配得上 ALGORITHM = INSTANT,不许写 AFTER");
assertTrue(sql.contains("UPDATE `columns` SET `company_id` = 1 WHERE `company_id` IS NULL;"),
"存量归第 1 家必须带 IS NULL 限定(重跑才是 no-op,也不覆盖人工指定过的行)");
assertTrue(sql.contains("ALTER TABLE `columns` MODIFY COLUMN `company_id` bigint NOT NULL DEFAULT 1"),
"第 3 段收成 NOT NULL DEFAULT 1,它同时是回填没跑全的自检闸门(1048)");
assertEquals(1, count(sql, "MODIFY COLUMN `company_id`"), "MODIFY 只许出现在建列定形状这一处");
}
/**
* 破坏点:新键没把 company_id 放第一位,或旧键还在。
* 旧键 {@code uk_column_key} 不摘,第 2 家公司连"和别家同名"的菜单都建不出来——
* 那不是看不到,是建不出,整套改造白做;而先 DROP 后 ADD 的写法会让中间态裸奔,
* 且复制段直接撞旧键的全局唯一(1062)。
*/
@Test
void uniqueKeysAreReplacedNotLayeredAndInThatOrder() throws IOException {
String sql = statements();
assertTrue(sql.contains("ADD UNIQUE KEY `uk_company_column_key` (`company_id`, `column_key`)"), sql);
assertTrue(sql.contains("ADD UNIQUE KEY `uk_company_menu_type_route_path` (`company_id`, `menu_type`, `route_path`)"), sql);
assertTrue(sql.contains("DROP INDEX `uk_column_key`"), "旧的全局键必须摘,否则第二棵树建不出来");
assertTrue(sql.contains("DROP INDEX `uk_menu_type_route_path`"), "路径的全局键同理");
assertTrue(sql.indexOf("ADD UNIQUE KEY `uk_company_column_key`") < sql.indexOf("DROP INDEX `uk_column_key`"),
"顺序必须是先 ADD 后 DROP:中间任一步失败都还剩一个唯一键在守并发");
assertTrue(sql.indexOf("ADD UNIQUE KEY `uk_company_menu_type_route_path`") < sql.indexOf("DROP INDEX `uk_menu_type_route_path`"));
// 复制段(第 6 段)排在两条旧键摘掉之后,否则它撞的就是旧键。
assertTrue(sql.indexOf("DROP INDEX `uk_column_key`") < sql.indexOf("INSERT INTO `columns`"),
"换键必须早于复制段");
assertEquals(4, count(sql, "ALGORITHM = INPLACE, LOCK = NONE"),
"四条索引操作都要钉 INPLACE+LOCK=NONE,否则 MySQL 可以选 COPY 锁写");
}
/**
* 破坏点:驱动集硬编码"公司 2"。第三家开通时就得再发一版迁移。
* 破坏点 2:把 {@code admin_companies} 也复制了——它是角色内在闸门(Java 的 SUPER_ADMIN_ONLY_KEYS
* 与前端 SUPER_ADMIN_ONLY_MENU_KEYS 同值),别家树里有这一行只会多一个"谁也授不出去"的摆设。
*/
@Test
void copyIsDrivenByTheCompanyTableAndSkipsTheRoleIntrinsicGate() throws IOException {
String sql = statements();
assertTrue(sql.contains("FROM `company` co"), "复制段的驱动集应是 company 全表,不是写死一个公司 id");
assertTrue(sql.contains("JOIN `columns` src ON src.company_id = 1"), "源树固定取公司 1");
assertTrue(sql.contains("WHERE co.id <> 1"), "对【所有】非 1 的公司做(含 status=0,少一家树就少一次启用检查)");
assertTrue(sql.contains("AND src.column_key <> 'admin_companies'"),
"定案 D3:admin_companies 不复制");
assertTrue(sql.contains("AND NOT EXISTS ("), "复制段必须幂等(repair 重跑不插第二份)");
assertEquals(1, count(sql, "INSERT INTO `columns`"), "本迁移只有一条插菜单行的语句");
}
/**
* 破坏点:副本照抄源行的 parent_id。那是全局 id,会把别家的子页面挂到厦门米椿花的分组下——
* 而 {@code fk_columns_parent_id} 只保证父行【存在】,挡不住跨公司挂父,库侧不会喊。
* 所以插入时父必须留 NULL,再按 (company_id, column_key) 认父。
*/
@Test
void copiesReparentByColumnKeyNeverById() throws IOException {
String sql = statements();
assertTrue(sql.contains("SELECT co.id, src.name, src.column_key, src.menu_type, src.route_path, src.sort_order, NULL, src.created_at"),
"插入段的 parent 位置必须是字面 NULL:" + sql);
assertTrue(sql.contains("JOIN `columns` pcopy ON pcopy.company_id = copy.company_id AND pcopy.column_key = sp.column_key"),
"认父要沿 (company_id, column_key) 走");
assertTrue(sql.contains("SET copy.parent_id = pcopy.id"));
assertTrue(sql.contains("AND copy.parent_id IS NULL"), "重跑时已认过父的行不再改动");
assertEquals(1, count(sql, "SET copy.parent_id"), "认父只有一条语句");
}
/**
* 破坏点:第 8 段(去重)没跑就先重指。同一账号若同时挂着源行与副本,重指会撞
* {@code (user_id, column_id)} 主键报 1062 —— 而这条只在 repair 重跑那种中途态才可能出现,
* 所以它必须写在重指之前,而不是"反正今天 0 行"。
*/
@Test
void duplicateGrantsArePrunedBeforeTheRepoint() throws IOException {
String sql = statements();
assertTrue(sql.contains("DELETE dup FROM `user_column_permission` dup"), "缺第 8 段的重指在重跑时会撞 1062");
assertTrue(sql.indexOf("DELETE dup FROM") < sql.indexOf("UPDATE `user_column_permission` g"),
"去重必须排在重指之前");
assertEquals(1, count(sql, "DELETE dup FROM"), "去重只删副本那一侧,且只此一处");
}
/**
* 破坏点(定案 D1 的核心):只复制树不重指授权。存量 784 笔里公司 2 那 16 笔仍挂在
* 公司 1 的行上,而读侧改成"只认本公司"之后,德阳的 2 只账号一上线掉光菜单——
* 这是"隐藏=静默删除"的同一类事故,所以它必须是同笔迁移的动作而不是发布后的人工待办。
*/
@Test
void existingGrantsAreRepointedToTheOwnCompanyCopy() throws IOException {
String sql = statements();
assertTrue(sql.contains("UPDATE `user_column_permission` g"), "第 9 段:存量授权重指向本公司副本");
assertTrue(sql.contains("JOIN `columns` copy ON copy.company_id = u.company_id AND copy.column_key = src.column_key"),
"认行按 column_key,不按 id 猜");
assertTrue(sql.contains("SET g.column_id = copy.id"));
assertTrue(sql.contains("WHERE u.company_id <> 1"),
"驱动条件限定在\"不属于公司 1\",重跑时这一行都选不出来=no-op");
assertEquals(1, count(sql, "SET g.column_id"), "改授权指针只有一条语句");
}
/**
* 破坏点:残留没让它响。四道闸门(临时表 must_be_zero NOT NULL,V143 那个"让约束替我喊"的家族)
* 缺任何一道,对应的失效形状都是"树少一棵 / 父挂错家 / 授权挂别家 / 冒出无归属行"——
* 四条全都不报错,只是某家公司侧边栏空白或按 key 点查判成"菜单不存在"。
*/
@Test
void fourGatesFailTheMigrationOnAnyResidual() throws IOException {
String sql = statements();
assertTrue(sql.contains("CREATE TEMPORARY TABLE IF NOT EXISTS `_v149_gate` (`must_be_zero` INT NOT NULL)"),
"闸门表必须是 NOT NULL 的一列——插 NULL 才抛 1048");
assertEquals(4, count(sql, "INSERT INTO `_v149_gate`"), "四道闸门:齐套性/跨公司父/跨公司授权/无归属行");
assertEquals(4, count(sql, "SELECT IF(COUNT(*) = 0, 0, NULL)"),
"每道都必须是\"计数为 0 才插得进去\"的形状,写成了 SELECT 就永远不为 0");
assertEquals(1, count(sql, "DROP TEMPORARY TABLE `_v149_gate`"), "闸门表用完要删");
// 逐道点名,防"四道其实都探同一件事"
assertTrue(sql.contains("LEFT JOIN `columns` cp ON cp.company_id = co.id AND cp.column_key = src.column_key"),
"闸门 1 要按公司逐行核对齐套");
assertTrue(sql.contains("WHERE c.company_id <> p.company_id"), "闸门 2 探跨公司父");
assertTrue(sql.contains("WHERE c.company_id <> u.company_id"), "闸门 3 探跨公司授权");
assertTrue(sql.contains("WHERE `company_id` IS NULL OR `company_id` <= 0"), "闸门 4 探无归属行");
}
/**
* 破坏点:写成裸 ALTER(不可重跑)。MySQL 的 DDL 不进事务,repair + 重启会从第一条语句重跑整个文件,
* 裸 ALTER 在恢复路径上必撞 1060/1050。
* 计数由本轮扫描得出、不自挑:五条条件 DDL(1 加列 + 2 加键 + 2 摘键)各配一份元数据判断与 PREPARE;
* 唯一不守卫的那条是 MODIFY——它在已 NOT NULL 的列上重跑不报错,属于天生幂等。
*/
@Test
void everyConditionalDdlIsGuardedByInformationSchema() throws IOException {
String sql = statements();
long alters = count(sql, "ALTER TABLE");
assertEquals(6, alters, "本迁移应有 6 条 ALTER(5 条件 + 1 条 MODIFY),实际 " + alters);
assertEquals(alters - 1, count(sql, "PREPARE stmt FROM @sql"), "五条条件 DDL 都要走 PREPARE");
assertEquals(alters - 1, count(sql, "DEALLOCATE PREPARE stmt"), "PREPARE 名复用前必须 DEALLOCATE");
assertEquals(alters - 1, count(sql, "information_schema"), "每条条件 DDL 各自要一次元数据存在性判断");
assertEquals(1, count(sql, "MODIFY COLUMN"), "不守卫的那一条只能是 MODIFY");
}
/** 破坏点:顺手改了 users / company,或建了持久表(菜单树的归属改造只该动这两张表)。 */
@Test
void touchesOnlyTheMenuCatalogAndItsGrants() throws IOException {
String sql = statements();
assertTrue(alteredTables(sql).stream().allMatch(COLUMNS::equals),
"所有 ALTER 都只能打在 columns 上,实际动到了 " + alteredTables(sql));
assertFalse(sql.contains("ALTER TABLE `users`"), "users.company_id 归 V143/V144 管,本迁移只读它");
assertFalse(sql.contains("ALTER TABLE `company`"), "company 表结构不动");
assertFalse(sql.replace("CREATE TEMPORARY TABLE", "").contains("CREATE TABLE"),
"除闸门临时表外不建持久表");
assertTrue(sql.contains("UPDATE `user_column_permission`"), "授权重指是本迁移的第二张写表");
assertEquals(0, count(sql, "DELETE FROM `users`"), "绝不删账号");
}
/** 破坏点:影响面是估的、DEFAULT 的倒计时没人接。锁表结论与摘 DEFAULT 的时点都只有配上实查数才站得住。 */
@Test
void headerCarriesMeasuredVolumesAndTheDefaultCountdown() throws IOException {
String raw = rawMigration();
assertTrue(raw.contains("52 行"), "columns 行数必须是生产实查值");
assertTrue(raw.contains("784") && raw.contains("133"), "授权笔数/账号数必须是生产实查值(重指段的分母)");
assertTrue(raw.contains("admin_companies"), "头注释要写明那一行不复制的理由,否则后人以为漏了");
assertTrue(raw.contains("1048"), "MODIFY 兼作回填自检闸门这件事要写进注释");
assertTrue(raw.contains("1364"), "DEFAULT 1 是为同批旧 jar 存在(旧实体没这列,insert 整列跳过会报它)");
assertTrue(raw.contains("COMPANY_DEFAULT_STILL_PRESENT"),
"摘 DEFAULT 的倒计时由启动期哨兵喊,头注释要点名那条 ASCII 签名");
assertTrue(raw.contains("ALTER COLUMN company_id DROP DEFAULT"),
"要给出摘除的安全写法(纯元数据),否则后人会照 V143 用 MODIFY 重建表");
assertTrue(raw.contains("禁写成 MODIFY"), "下一版摘 DEFAULT 禁 MODIFY 这条要写在文件里");
assertTrue(raw.contains("从第一条语句重跑整个文件"), "可重跑性是恢复路径的前提,注释要写明");
}
/** 破坏点:验证段没核对"各家齐不齐"和"授权还挂不挂在别家"。这两条是上线当晚唯一能证伪的读数。 */
@Test
void shipsPostDeployVerificationSql() throws IOException {
String raw = rawMigration();
assertTrue(raw.contains("SELECT company_id, menu_type, COUNT(*) FROM columns GROUP BY company_id, menu_type"),
"验证 SQL 要按公司×类型数行数");
assertTrue(raw.contains("WHERE c.company_id <> u.company_id"), "验证 SQL 要复验跨公司授权残留");
assertTrue(raw.contains("information_schema.STATISTICS"), "验证 SQL 要复验两条旧键已摘、两条新键在");
}
/**
* 破坏点:回滚被编成版本化迁移(Flyway 扫描路径里的 V*.sql 会在下次启动自动执行),
* 或者回滚把"删副本"排在"重指授权"之前。
*
* <p>后者是这一版独有的陷阱:{@code user_column_permission} 的外键是 ON DELETE CASCADE,
* 先删副本会把它名下授权一起删光——而 V149 之后账号名下"本来就该"挂的是副本行。
* 写反的读数不是报错,是 133 只账号的菜单被清空。</p>
*/
@Test
void rollbackRepointsGrantsBeforeDeletingTheCopiesAndStaysUnversioned() throws IOException {
Pattern writesHistoryTable = Pattern.compile(
"\\b(DELETE|UPDATE|INSERT|TRUNCATE|ALTER|DROP)\\b[^;]*\\bflyway_schema_history\\b",
Pattern.CASE_INSENSITIVE);
for (Path file : versionFiles()) {
String executable = normalize(stripComments(raw(file)));
assertFalse(writesHistoryTable.matcher(executable).find(),
"回滚不许编成版本化迁移:" + file.getFileName() + " 的执行段写了 flyway_schema_history");
}
Path rollback = ROOT.resolve("docs/rollback-V149-permission-menu-company.sql");
assertTrue(Files.isRegularFile(rollback), "回滚人工补丁必须存在:" + rollback);
String whole = raw(rollback);
assertTrue(whole.contains("flyway_schema_history"), "回滚必须删本版本历史行(漏掉=重装时 Flyway 跳过 V149)");
String executable = normalize(stripComments(whole));
assertTrue(executable.contains("SET g.column_id = src.id"), "回滚要先把授权指针挪回公司 1 的源行");
assertTrue(executable.contains("DELETE FROM `columns` WHERE company_id <> 1"), "再删副本");
assertTrue(executable.indexOf("SET g.column_id = src.id") < executable.indexOf("DELETE FROM `columns`"),
"顺序不能反:FK 是 ON DELETE CASCADE,先删副本等于清空 133 只账号的菜单");
assertTrue(whole.contains("ON DELETE CASCADE"), "注释要写明为什么这个顺序是陷阱");
assertTrue(executable.contains("ADD UNIQUE KEY `uk_column_key` (`column_key`)"), "回滚要把两条全平台旧键加回来");
assertTrue(executable.contains("ADD UNIQUE KEY `uk_menu_type_route_path` (`menu_type`, `route_path`)"));
assertTrue(executable.contains("DROP INDEX `uk_company_column_key`"), "并摘掉两条按公司的新键");
assertTrue(executable.contains("DROP INDEX `uk_company_menu_type_route_path`"));
assertTrue(executable.indexOf("ADD UNIQUE KEY `uk_column_key`") < executable.indexOf("DROP INDEX `uk_company_column_key`"),
"回滚同样是先 ADD 后 DROP:中间态必须还剩一个唯一键");
assertTrue(executable.contains("CREATE TEMPORARY TABLE `_v149_rb_gate`"),
"重指与删除之间要有闸门:漏一行就会被 CASCADE 静默吞掉");
assertTrue(executable.contains("CREATE TABLE IF NOT EXISTS `columns_bak_v149_rollback`"),
"删副本前必须整表留底");
}
/**
* 破坏点:头注释喊了哨兵,哨兵却没探这一列 ⇒ "有人盯着摘 DEFAULT"这件事是假的。
* 这条把文档承诺与代码实现对齐(V145 同类用例的同口径)。
*/
@Test
void startupSentinelActuallyWatchesTheMenuColumn() throws IOException {
Path guard = ROOT.resolve("src/main/java/com/nanri/aiimage/modules/company/service/CompanyDefaultGuard.java");
assertTrue(Files.isRegularFile(guard), "启动期 DEFAULT 哨兵应存在:" + guard);
String text = raw(guard);
assertTrue(text.contains("COMPANY_DEFAULT_STILL_PRESENT"), "哨兵标记串必须保持 ASCII 原样(巡检按它 grep docker logs)");
assertTrue(text.contains("\"columns\""), "哨兵要探 columns.company_id,否则 V149 的 DEFAULT 没人盯");
assertTrue(text.contains("'columns'"), "探针 SQL 的 IN 列表也要含它,只进清单是假盯");
assertTrue(text.contains("COLUMN_DEFAULT"), "哨兵应真的读列元数据,而不是靠猜");
}
/**
* 破坏点:旁路种子(启动期自建表/键的那个初始化器)还按换列之前的全局口径建键。
* 它一旦被执行,新库就会带着 {@code uk_column_key} 起来 ⇒ 第二家公司的树建不出来,
* 而 V149 的 DROP 只在存量库跑过——这条是"不得回流"的反向钉。
*/
@Test
void schemaInitializerKeepsTheCompanyScopedKeys() throws IOException {
Path initializer = ROOT.resolve(
"src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java");
String text = raw(initializer);
assertTrue(text.contains("UNIQUE KEY uk_company_column_key (company_id, column_key)"),
"建表要直接带复合键");
assertFalse(text.contains("ADD UNIQUE KEY uk_column_key"), "不得再建全局 column_key 键");
assertFalse(text.contains("ADD UNIQUE KEY uk_menu_type_route_path"), "不得再建全局 (menu_type, route_path) 键");
assertFalse(text.contains("company_id BIGINT NULL COMMENT '归属公司:每家公司一套菜单树' AFTER"),
"加列同样是末位追加,INSTANT 不押版本");
assertTrue(text.contains("UPDATE columns SET company_id = 1 WHERE company_id IS NULL"),
"种子路径也要把存量收成 NOT NULL 三段式的第 2 段");
}
/**
* 破坏点:旁路种子(生产默认关,但新库/本地/那条 `permission-schema-init.enabled=true` 的通道会跑)
* 建出来的行没钉公司。V149 之后 {@code column_key} <b>只在单家公司内唯一</b>,这条通道里一句裸
* {@code WHERE column_key = ...} 就是"把每一家的同名行都改一遍"——别家副本的 parent 被拍平、
* 初始授权发给别家的行 id;而 {@code executeQuietly} 把 1048/1062 吞成一行 debug 日志,
* 表现是"某一家一声不响少一套菜单"。
*
* <p>另一层:这里显式写 {@code company_id} 之后,这条通道就不再依赖列上那条 {@code DEFAULT 1},
* 于是待办里那句 {@code ALTER TABLE columns ALTER COLUMN company_id DROP DEFAULT} 落地时
* 不会把这里的建号变成 1364。所以本用例同时钉"列清单带公司"与"投影是真常量 1"。</p>
*
* <p>形状与 {@code PermissionCompanyMenuHiddenTest} 同一套:先证明取样集非空、
* 再证明这把尺子认得出已知的一条违规(否则上面的 0 命中是恒绿)。</p>
*/
@Test
void schemaInitializerSeedsEveryRowIntoTheTemplateCompany() throws IOException {
String src = normalize(stripComments(raw(ROOT.resolve(
"src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuSchemaInitializer.java"))));
List<String> regions = seedStatements(src);
List<String> keyLookups = regions.stream().filter(r -> r.contains("column_key =")).toList();
assertTrue(regions.size() >= 25, "种子语句取样集太小,扫描器多半没切开:" + regions.size());
assertTrue(keyLookups.size() >= 12,
"按 column_key 认菜单的种子语句取样集太小(换键后这类语句只会更多,不会更少):" + keyLookups.size());
assertEquals(count(src, "INSERT INTO columns ("), count(src, "INSERT INTO columns (company_id,"),
"每条 INSERT 的列清单都要显式带 company_id,不许再让列 DEFAULT 兜");
assertTrue(count(src, "INSERT INTO columns (company_id,") >= 6,
"取样集自检:这条通道本就要种 4 个分组 + 18 条菜单 + 2 条 internal,INSERT 语句不该只剩几条");
assertEquals(count(src, "INSERT INTO columns (company_id,"), count(src, "SELECT 1, "),
"每条种子 INSERT 的投影都必须是常量 1(模板公司):换成别的数字就是在往别家插平台默认行");
assertEquals(1, count(src, "data_col.company_id = old_col.company_id"),
"初始授权必须把 data_col 收在 old_col 同一家,否则老账号拿到别家的数据权限行 id");
assertTrue(keyLookupsWithoutCompany(regions).isEmpty(),
"这些种子语句按 column_key 认菜单却没钉公司,等于对每一家各改一遍:" + keyLookupsWithoutCompany(regions));
String scoped = " ( SELECT 1, 'x', 'admin_users' FROM columns WHERE company_id = 1 AND column_key = 'admin_users' ) ";
String bare = " ( SELECT 1, 'x', 'admin_users' FROM columns WHERE column_key = 'admin_users' ) ";
assertEquals(List.of(bare), keyLookupsWithoutCompany(List.of(scoped, bare)),
"尺子自检:一条没钉公司的已知违规必须被抓到,同时已钉公司的那条不许误报");
}
/**
* 破坏点:读侧或写侧编一个"没带公司就回落公司 1"的临时分支。
* 定案是路线甲(V149 与 jar 同批双台),混合窗口里旧 jar 靠列上的 DEFAULT 兜,不需要 Java 侧兜——
* 而 Java 侧一旦有兜底,"忘了传公司"就从 1048/403 变成静默归到第 1 家。
*
* <p>断言形状:先确认扫描器抓得到锚点(0 命中=尺子坏了),再要求三种兜底写法各 0 命中。</p>
*/
@Test
void serviceHasNoFallbackBranchToTheDefaultCompany() throws IOException {
String src = raw(ROOT.resolve(
"src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuService.java"));
assertTrue(src.contains("resolveScopeCompanyId"), "扫描器要能命中归属判据本身,否则下面的 0 命中不作数");
assertEquals(0, count(src, "? 1L"), "不许出现 `x == null ? 1L` 这种回落默认公司");
assertEquals(0, Pattern.compile("\\?\\s*1L\\b").matcher(src).results().count(), "同上,容空格拉写");
assertFalse(src.contains("COMPANY_DEFAULT"), "不许在本类里另立默认公司常量");
}
/**
* 破坏点:目录取数留下"不带公司"的重载。生产上 operator 恒有 companyId,走不到无参那条,
* 于是"跨公司混树"这条路永远只对新代码开放——按方法名精确匹配,不接受 {@code loadMenus(} 这种含二参的宽匹配。
*
* <p>判据用"括号里既无逗号也无嵌套括号"来认单参调用;抓不住的形状是 {@code loadMenus(resolve(a, b))}
* 这种把唯一实参写成调用式的写法。下面那条阳性对照(喂一条已知违规)证明这把尺子不是恒绿的。</p>
*/
@Test
void menuLoadingAlwaysCarriesACompany() throws IOException {
String src = raw(ROOT.resolve(
"src/main/java/com/nanri/aiimage/modules/permission/service/PermissionMenuService.java"));
for (String method : List.of("loadMenus", "loadRawMenus")) {
Pattern singleArg = Pattern.compile(method + "\\([^(),]*\\)");
assertEquals(1, Pattern.compile("List<PermissionMenuEntity> " + method + "\\(").matcher(src).results().count(),
method + " 只允许一个声明");
assertEquals(0, singleArg.matcher(src).results().count(),
method + " 不许有单参调用/重载:每个取数点都要显式带公司");
assertEquals(1, singleArg.matcher("List<PermissionMenuEntity> rows = " + method + "(companyId);")
.results().count(), "尺子自检:已知的一条单参调用必须被抓到,否则上面的 0 命中不作数");
}
}
/** 破坏点:盘点文档没跟着改,下一个人按"取号起点"取号就撞号。 */
@Test
void inventoryDocTracksV149() throws IOException {
String text = raw(ROOT.resolve("docs/migration-inventory.md"));
assertTrue(text.contains(migration().getFileName().toString()), "盘点文档应记录 V149 文件名");
assertTrue(text.contains("V152"), "盘点文档应记下新的取号起点(V150/V151 已被同批占用)");
// 取号起点是否真等于"当前最大值 + 1"由 MigrationInventoryTest 派生判定,这里不重复钉死字面号。
}
/** 自检:本用例集扫的是真文件,且 normalize 后仍能命中关键串(0 命中的断言是恒绿的)。 */
@Test
void scannedSignaturesAreActuallyPresent() throws IOException {
String sql = statements();
assertTrue(sql.length() > 1000, "剥注释后的 SQL 太短,说明预处理把内容吃掉了:" + sql.length());
assertTrue(count(sql, "ALTER TABLE") > 0 && count(sql, "information_schema") > 0
&& count(sql, "INSERT INTO `columns`") > 0,
"关键签名 0 命中=预处理或文件路径坏了,本类的断言全部不可信");
}
}
@@ -68,13 +68,24 @@ class MigrationInventoryTest {
} }
/** /**
* 已在生产 flyway_schema_history 中占位、但本地文件被改名让位的版本号。 * 不许再被占用的整数版本洞。两条来历不同,得分开记:
* 生产 131 之后直接装了 134/135(2026-09-25 20:46:16),132/133 从未落库; *
* 而 Flyway 未开 out-of-order,把新迁移编号改回 132/133 会导致启动期 * <p><b>132/133</b>:已在生产 {@code flyway_schema_history} 中占位、但本地文件被改名让位的版本号。
* "resolved migration not applied" 失败,所以这个洞只能永久保留、不能回填。 * 生产 131 之后直接装了 134/135(2026-09-25 20:46:16),132/133 从未落库;而 Flyway 未开
* 后果:新迁移只能取当前最大值之上的号(详见 docs/migration-inventory.md)。 * out-of-order,把新迁移编号改回 132/133 会导致启动期 "resolved migration not applied" 失败,
* 所以这个洞只能永久保留、不能回填。</p>
*
* <p><b>148</b>:{@code V148__product_category_builtin_owned_by_company.sql}(内置类目归还厦门米椿花)
* 从未上线,2026-10-06 控制方点名「商品类目做成共享的,不区分」⇒ 这一版的口径被整体推翻,
* 文件连同 {@code ProductCategoryMigrationV148Test} 与 rollback 补丁一起删掉。
* 与 132/133 不同,把新迁移编号写回 148 在 Flyway 语义上【是】可行的(生产最大值仍是 147)——
* 这里禁它是共树并发的护栏:那一版是另一路会话此刻正在引用的号,删掉的文件可能被再次写出,
* 而同号两个文件会让 Flyway 启动期报 "Found more than one migration with version 148",
* 后果是两台 java 同时起不来。宁可让本用例红,也不把撞号留到运行期发现。</p>
*
* <p>共同后果:新迁移只能取当前最大值之上的号(详见 docs/migration-inventory.md)。</p>
*/ */
private static final Set<Integer> RETIRED_HOLES = Set.of(132, 133); private static final Set<Integer> RETIRED_HOLES = Set.of(132, 133, 148);
@Test @Test
void integerVersionsSequentialFromOne() throws IOException { void integerVersionsSequentialFromOne() throws IOException {
@@ -6,6 +6,7 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@@ -231,19 +232,69 @@ class ProductCategoryMigrationV147Test {
} }
/** /**
* 破坏点:V147 的 DEFAULT 1 没进启动期哨兵清单 ⇒ "下一次记得摘"这件事没人喊, * 破坏点(2026-10-06 起方向相反):类目表随「商品类目做成所有公司共享」的定案<b>退出</b>了启动期
* 而巡检按 {@code COMPANY_DEFAULT_STILL_PRESENT} 这条 ASCII 签名 grep docker logs。 * 哨兵清单,而它现在仍带 {@code DEFAULT 1}——这一列从"待摘的风险"翻转成了 {@code NOT NULL} 的
* 承重约束:新 jar 的 INSERT/UPDATE 列清单都不带 company_id,靠默认值填。
*
* <p>所以这一支钉的是"哨兵必须不再对它喊"。清单与探针 SQL 的 IN 列表<b>两侧都要钉</b>:
* 只摘一侧会重演本类要避免的那两种静默形状——清单里还在、IN 里没有 ⇒ 每次启动报"探不到"的 WARN;
* IN 里还在、清单里没有 ⇒ 查到了却没人判定,而 {@code CompanyDefaultGuardTest} 的双向同源钉
* 会红在那一张"仍按公司"的表上,不会红在这里。</p>
*
* <p>另一半:退出这件事必须在版本化的迁移注释里有据可查。只改代码不改说法,下一个人会照
* 本文件头注释(V147 那一版写的是"记得摘 DEFAULT")或 {@code CompanyDefaultGuard} 给出的
* {@code DROP DEFAULT} 语句去执行,代价是每次写入 1364,而且这张表的失败会直接顶到管理员面前。</p>
*/ */
@Test @Test
void startupSentinelWatchesTheProductCategoryColumn() throws IOException { void startupSentinelHasStoppedWatchingTheProductCategoryColumn() throws IOException {
Path guard = ROOT.resolve("src/main/java/com/nanri/aiimage/modules/company/service/CompanyDefaultGuard.java"); Path guard = ROOT.resolve("src/main/java/com/nanri/aiimage/modules/company/service/CompanyDefaultGuard.java");
assertTrue(Files.isRegularFile(guard), "启动期 DEFAULT 哨兵应存在:" + guard); assertTrue(Files.isRegularFile(guard), "启动期 DEFAULT 哨兵应存在:" + guard);
String text = raw(guard); String text = raw(guard);
assertTrue(text.contains("COMPANY_DEFAULT_STILL_PRESENT"), "哨兵标记串必须保持 ASCII 原样(巡检按它 grep)"); assertTrue(text.contains("COMPANY_DEFAULT_STILL_PRESENT"), "哨兵标记串必须保持 ASCII 原样(巡检按它 grep)");
assertTrue(text.contains("'" + TABLE + "'"),
"探针 SQL 的 IN 列表要含 " + TABLE + "(不在 IN 里就查不到这一列,哨兵等于没探)"); assertFalse(probeInList(text).contains(TABLE),
assertTrue(text.contains("\"" + TABLE + "\""), "探针 SQL 的 IN 列表不许再有 " + TABLE + ":查到了就等于还要人摘 DEFAULT");
"WATCHED_TABLES 清单要含 " + TABLE + "(查到了却不在清单里,就没人去喊那条签名)"); assertFalse(watchedTables(text).contains(TABLE),
"WATCHED_TABLES 清单不许再有 " + TABLE + ":清单才是判定走不走的那一侧");
Path v151 = sharedKeyMigrationFile();
String note = raw(v151);
assertTrue(note.contains(TABLE), "退键那一笔要点名类目表:" + v151.getFileName());
assertTrue(note.contains("DROP DEFAULT") && note.contains("1364"),
"必须写明\"这一版的 DEFAULT 摘不得\"及其后果,否则 V147 头注释那条旧承诺仍然会被执行");
}
/** 取探针 SQL 的 {@code TABLE_NAME IN ('a', 'b')} 段(单引号)。 */
private static List<String> probeInList(String guardSource) {
Matcher inList = Pattern.compile("TABLE_NAME\\s+IN\\s*\\(([^)]*)\\)").matcher(guardSource);
assertTrue(inList.find(), "哨兵源码里没有 TABLE_NAME IN (…) 这一段,取不到清单");
return quotedValues(inList.group(1), "'([^']+)'");
}
/** 取 {@code WATCHED_TABLES = List.of("a", "b")} 那批双引号表名。 */
private static List<String> watchedTables(String guardSource) {
Matcher list = Pattern.compile("WATCHED_TABLES\\s*=\\s*List\\.of\\(([^)]*)\\)").matcher(guardSource);
assertTrue(list.find(), "取不到 WATCHED_TABLES 清单:哨兵源码的形状变了,本用例的尺子要跟着改");
return quotedValues(list.group(1), "\"([^\"]+)\"");
}
/** 解析不出任何一条就当场判红:0 命中会让上面那两条 {@code assertFalse} 恒真。 */
private static List<String> quotedValues(String segment, String quotePattern) {
List<String> values = new ArrayList<>();
Matcher quoted = Pattern.compile(quotePattern).matcher(segment);
while (quoted.find()) {
values.add(quoted.group(1));
}
assertFalse(values.isEmpty(), "从源码段里解析出 0 个表名 ⇒ 这段断言是恒绿的:" + segment);
return values;
}
private static Path sharedKeyMigrationFile() throws IOException {
List<Path> hits = versionFiles().stream()
.filter(p -> p.getFileName().toString().startsWith("V151__"))
.toList();
assertEquals(1, hits.size(), "V151(两张共享表退回全局唯一键)应存在且只有一个:" + hits);
return hits.get(0);
} }
/** /**
@@ -0,0 +1,296 @@
package com.nanri.aiimage.config;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* V150({@code biz_shop_key} 加 company_id)的文件审计。
* 需求:2026-10-06 控制方点名「店铺密钥管理的数据按照公司区分」;设计见迁移文件头 §1–§6。
*
* <p>为什么必须单独有一支:本仓 pom 无 H2、无 testcontainers,迁移跑不起来,文件审计是唯一能守住的那层
* (与 {@link ProductCategoryMigrationV147Test}、{@link CompanyScopeMigrationV145Test} 同口径)。
* V150 的三条关键决定全都"错了不报错":</p>
* <ol>
* <li>历史归属靠加列时记录的 {@code DEFAULT 1},而不是回填——写成可空列或补一条 UPDATE 都改成另一种语义;</li>
* <li>唯一键 {@code uk_ziniao_token_hash} <b>刻意保持全局</b>(不像 V145/V147 那样按公司放宽),
* 谁"顺手把它按公司放宽"就会让同一个令牌在两家公司各存一行、被 {@code ZiniaoApiKeyProvider}
* 按令牌并成一条,白名单状态与代理地址互相顶掉;</li>
* <li>回滚的默认档是<b>保留新列、只回 jar</b>,删列那一步留在注释里由人工解开(这张表没有账号列,
* 列一删归属就再也分不回去)。</li>
* </ol>
*
* <p>{@code stripComments}/{@code normalize} 逐字沿用 {@link CompanyScopeMigrationV145Test} 那一份实现:
* 注释里的 {@code --} 与字符串字面量里的 {@code --} 是两件事,另写一版简化实现会让断言打在残缺 SQL 上。</p>
*/
class ShopKeyMigrationV150Test {
private static final Path ROOT = Path.of(System.getProperty("user.dir"));
private static final Path DB_DIR = ROOT.resolve("src/main/resources/db");
private static final String TABLE = "biz_shop_key";
private static final String GLOBAL_UNIQUE_KEY = "uk_ziniao_token_hash";
// ---------------------------------------------------------------- 取文件
private static List<Path> versionFiles() throws IOException {
try (Stream<Path> s = Files.list(DB_DIR)) {
return s.filter(p -> p.getFileName().toString().matches("^V\\d+(?:_\\d+)?__.*\\.sql$"))
.sorted()
.toList();
}
}
private static Path migration() throws IOException {
List<Path> hits = versionFiles().stream()
.filter(p -> p.getFileName().toString().startsWith("V150__"))
.toList();
assertEquals(1, hits.size(),
"V150 必须恰好一个迁移文件,实际 " + hits.size() + " 个(0 个=密钥表还没归属列;2 个=撞号,Flyway 启动即失败)");
return hits.get(0);
}
private static String raw(Path file) throws IOException {
return Files.readString(file, StandardCharsets.UTF_8);
}
private static String statements() throws IOException {
return normalize(stripComments(raw(migration())));
}
// ------------------------------------------------------------ SQL 预处理
// 与 CompanyScopeMigrationV145Test / ProductCategoryMigrationV147Test 逐字同实现,理由见类注释。
private static String stripComments(String sql) {
StringBuilder out = new StringBuilder(sql.length());
int i = 0;
while (i < sql.length()) {
char c = sql.charAt(i);
if (c == '\'') {
int end = i + 1;
while (end < sql.length()) {
if (sql.charAt(end) == '\'') {
if (end + 1 < sql.length() && sql.charAt(end + 1) == '\'') {
end += 2;
continue;
}
break;
}
end++;
}
out.append(sql, i, Math.min(end + 1, sql.length()));
i = end + 1;
continue;
}
if (c == '-' && i + 1 < sql.length() && sql.charAt(i + 1) == '-') {
while (i < sql.length() && sql.charAt(i) != '\n') {
i++;
}
continue;
}
if (c == '/' && i + 1 < sql.length() && sql.charAt(i + 1) == '*') {
int end = sql.indexOf("*/", i + 2);
i = end < 0 ? sql.length() : end + 2;
continue;
}
out.append(c);
i++;
}
return out.toString();
}
private static String normalize(String sql) {
return sql.replaceAll("\\s+", " ").trim();
}
// ------------------------------------------------------------------ 用例
/** 破坏点:取到已应用的号(原地改=两台都起不来),或把这一版编成 V152(V150 就被跳开,归属列永远不加)。 */
@Test
void migrationIsVersionedOneFiveZero() throws IOException {
Path file = migration();
Matcher m = Pattern.compile("^V(\\d+)(?:_\\d+)?__").matcher(file.getFileName().toString());
assertTrue(m.find(), "文件名应能抽出整数版本:" + file.getFileName());
assertEquals(150, Integer.parseInt(m.group(1)), "本迁移必须是 V150(V149 之后的下一号)");
assertTrue(file.getFileName().toString().matches("^V150__[A-Za-z0-9_.-]+\\.sql$"),
"命名应 V150__<snake 描述>.sql:" + file.getFileName());
}
/**
* 破坏点 ①:加成可空 ⇒ 混合窗口里旧 jar 写进来的密钥行 {@code company_id} 为 NULL,
* 而 {@code applyCompanyScope} 的 null 分支是「不裁剪」,这些行会同时出现在每一家的 tab 上。
* 破坏点 ②:写 {@code MODIFY COLUMN} ⇒ 重建表并按"当时的列默认值"物化历史行,而本迁移没写回历史行,
* 历史归属的全部依据就是加列那一刻记录的默认值(§6)。
* 破坏点 ③:加 {@code AFTER} ⇒ 非末位列在 InnoDB 里要重建聚簇记录,INSTANT 的前提没了。
* {@code DEFAULT 1} 必须<b>在场</b>:它是同批旧 jar 唯一能插进这张表的通道,摘它的是下一版。
*/
@Test
void addsANotNullCompanyColumnWithInstantAndNeverModify() throws IOException {
String sql = statements();
assertTrue(sql.contains("ALTER TABLE `" + TABLE + "` ADD COLUMN `company_id` bigint NOT NULL DEFAULT 1"),
TABLE + " 应一次到位加成 NOT NULL DEFAULT 1(DEFAULT 只为同批旧 jar 存在,摘除是下一版)");
assertTrue(sql.contains("ALGORITHM = INSTANT"),
"加列必须钉 INSTANT:前提不成立时 MySQL 直接报 1846,而不是悄悄退化成 COPY(§3)");
assertFalse(sql.toUpperCase().contains(" AFTER "), "不许写 AFTER:非末位列加列会触发整表重建(§3)");
assertFalse(sql.contains("MODIFY COLUMN"), "禁 MODIFY COLUMN——它会重建表并按当时的默认值物化历史行(§6)");
assertFalse(sql.contains("ALTER TABLE `" + TABLE + "` DROP COLUMN"), "本版本不删列:归属一旦删掉就再也分不出是第几家公司(§2)");
}
/**
* 列注释里那句「历史行由本默认值给出,不可反推」是这一列存在理由的一半:
* 它跟着 schema 走,将来接手的人不必翻迁移文件就知道第 1 家的行里混着窗口期的别家数据。
*/
@Test
void columnCommentCarriesTheProvenanceLimitation() throws IOException {
String sql = statements();
assertTrue(sql.contains("本表无账号列"), "列注释要写明「本表无账号列」,否则后来人会试图按创建人反推归属");
assertTrue(sql.contains("不可反推"), "列注释要写明历史归属「不可反推」,这是 §2 那个不可追回窗口的落点");
}
/**
* 破坏点:有人"顺手"补一条回填 UPDATE(这张表没有账号列,任何"按人回填"都是编数据);
* 或者加了 created_by_id / 二级索引,把"刻意不做的事"做成了既成事实。
* 计数取 0 而不是「不超过 1」:§2 的口径是历史行的 1 来自默认值,一条 DML 都不该有。
*/
@Test
void writesNoDmlAtAllAndAddsNoIndex() throws IOException {
String sql = statements();
Matcher d = Pattern.compile("\\b(UPDATE|INSERT|DELETE|REPLACE)\\b", Pattern.CASE_INSENSITIVE).matcher(sql);
int hits = 0;
while (d.find()) {
hits++;
}
assertEquals(0, hits, TABLE + " 的可执行段一条 DML 都不该有,实际命中 " + hits + " 条 DML 关键字");
assertFalse(sql.contains("created_by_id"), "本版本不加 created_by_id:归属从本版本起由 service 显式落,反推那条路用不上(§2)");
assertEquals(0, count(sql, "ADD INDEX") + count(sql, "ADD KEY"),
"本版本不加二级索引:这张表是「一个紫鸟账号一行」量级,多挂一个单列索引就是 V139 那轮清掉的冗余形状");
}
/**
* 唯一键必须一动不动(§4)。这是本迁移与 V145/V147 最大的口径差别,所以钉成"可执行段里
* 没有任何索引动作",而不是"索引动作少"——放宽那一步一旦发生,运行期的表现是两行并成一行、
* 代理与白名单状态跨公司互相顶掉,不会有任何报错。
*/
@Test
void uniqueKeyStaysGlobalAndTheReasonTravelsWithTheFile() throws IOException {
String sql = statements();
assertEquals(0, count(sql, "DROP INDEX") + count(sql, "ADD UNIQUE KEY"),
"本版本不许动任何索引:uk_ziniao_token_hash 刻意保持全平台唯一(§4)");
assertFalse(sql.contains(GLOBAL_UNIQUE_KEY),
"可执行段里不该出现 " + GLOBAL_UNIQUE_KEY + "(它只应出现在解释为什么不动的注释里)");
String whole = raw(migration());
assertTrue(whole.contains(GLOBAL_UNIQUE_KEY), "「为什么不动唯一键」的理由必须写在迁移文件里,而不是只写在评审意见里");
assertTrue(whole.contains("ZiniaoApiKeyProvider"), "理由的关键环是令牌聚合那一步:注释要点名 ZiniaoApiKeyProvider");
}
/**
* 破坏点:删掉存在性守卫 ⇒ DDL 不进事务,中途失败后按「repair → 重启」重跑会撞 1060(重复列)而彻底起不来。
* 计数取 1 而不是「大于 0」:本文件的可执行段恰好查一次 information_schema(只查列),
* 多一次说明有人加了没登记的索引/键动作,少一次就是守卫没了。
*/
@Test
void addColumnIsGuardedByExistenceCheckAndReRunnable() throws IOException {
String sql = statements();
assertEquals(1, count(sql, "information_schema"),
"可执行段应查 1 次 information_schema(列存在性),实际次数见消息");
assertTrue(sql.contains("TABLE_NAME = '" + TABLE + "'"), "加列的守卫要按本表查");
assertTrue(sql.contains("COLUMN_NAME = 'company_id'"), "加列的守卫要按列名查");
assertTrue(count(sql, "PREPARE stmt FROM @sql") == 1 && count(sql, "EXECUTE stmt") == 1
&& count(sql, "DEALLOCATE PREPARE stmt") == 1,
"条件 DDL 必须走 PREPARE/EXECUTE 并收口(MySQL 不能在 IF 里直接写 DDL)");
}
/**
* 行数今天没实查(§2 写明),取证命令与不可追回窗口必须留在文件里。
* 这一支钉的是"取证责任没被写成既成事实":文件里出现"行数已确认"这类话就是把它编完了。
*/
@Test
void unprobedRowCountStaysAnExplicitDebtWithTheProbeQuery() throws IOException {
String whole = raw(migration());
assertTrue(whole.contains("SELECT COUNT(*) AS total"),
"§2 要带上可实跑的取证 SQL,而不是只留一句「上线前查一下」");
assertTrue(whole.contains("2026-10-04 14:55"), "不可追回窗口的锚点是第二家公司开通时刻,必须在文件里");
assertTrue(whole.contains("没有实查") || whole.contains("未实查"), "行数没查过这件事必须写在文件里,不许读成已知");
}
/**
* 回滚是人工补丁,且在 Flyway 扫描路径之外。
*
* <p>本迁移的回滚默认档<b>一条 SQL 都不执行</b>:这张表没有账号列,删列就删掉了唯一的归属依据,
* 所以 {@code DROP COLUMN} 留在注释里由人工解开,止损走"保留新列、只回 jar"那一档
* (新列对旧 jar 是惰性的,{@code DEFAULT 1} 正好把旧 jar 插入的行接住)。
* {@link CompanyScopeMigrationV145Test#rollbackStaysOutOfFlywayScanAndCoversTheHistoryRow} 按全目录
* 钉"回滚不得版本化",本类只钉本迁移这一支的内容。</p>
*/
@Test
void rollbackIsAHumanPatchThatDefaultsToKeepingTheColumn() throws IOException {
Path doc = ROOT.resolve("docs/rollback-V150-shop-key-company.sql");
assertTrue(Files.isRegularFile(doc), "V150 的人工回滚补丁必须存在:" + doc);
String whole = raw(doc);
assertTrue(whole.contains("flyway_schema_history"), "回滚必须写明删 version='150' 的历史行");
assertTrue(whole.contains("'150'"), "回滚补丁要点名本版本号,后来人才知道删的是哪一行");
String executable = normalize(stripComments(whole));
assertTrue(executable.isEmpty(),
"默认档不执行任何 SQL(删列是不可逆动作,必须留在注释里由人工解开),实际可执行段:" + executable);
assertTrue(whole.contains("DROP COLUMN"), "删列那一步要在文件里,只是不许默认可执行");
}
/**
* 破坏点:V150 的 DEFAULT 1 没进启动期哨兵清单 ⇒ "下一次记得摘"这件事没人喊,
* 而巡检按 {@code COMPANY_DEFAULT_STILL_PRESENT} 这条 ASCII 签名 grep docker logs。
*/
@Test
void startupSentinelWatchesTheShopKeyColumn() throws IOException {
Path guard = ROOT.resolve("src/main/java/com/nanri/aiimage/modules/company/service/CompanyDefaultGuard.java");
assertTrue(Files.isRegularFile(guard), "启动期 DEFAULT 哨兵应存在:" + guard);
String text = raw(guard);
assertTrue(text.contains("COMPANY_DEFAULT_STILL_PRESENT"), "哨兵标记串必须保持 ASCII 原样(巡检按它 grep)");
assertTrue(text.contains("'" + TABLE + "'"),
"探针 SQL 的 IN 列表要含 " + TABLE + "(不在 IN 里就查不到这一列,哨兵等于没探)");
assertTrue(text.contains("\"" + TABLE + "\""),
"WATCHED_TABLES 清单要含 " + TABLE + "(查到了却不在清单里,就没人去喊那条签名)");
}
/** 破坏点:盘点文档没跟着改 ⇒ 下一个人按"取号起点"取号就撞号,或按"最新版本"漏掉本文件。 */
@Test
void inventoryDocTracksTheShopKeyFile() throws IOException {
Path doc = ROOT.resolve("docs/migration-inventory.md");
String text = raw(doc);
assertTrue(text.contains(migration().getFileName().toString()),
"盘点文档应逐字保留本迁移文件名:" + migration().getFileName());
assertTrue(text.contains("V147__product_category_company_scope.sql"),
"盘点文档应同时保留更早的文件名:只钉最新一条会重演「推进概览时把旧条目挤掉」那一次回归");
}
/** 自检:本用例集扫的是真文件,且 normalize 后仍能命中关键串(0 命中的断言是恒绿的)。 */
@Test
void scannedSignaturesAreActuallyPresent() throws IOException {
String sql = statements();
assertTrue(sql.length() > 120, "剥注释后的 SQL 太短,说明预处理把内容吃掉了:" + sql.length());
assertTrue(count(sql, "ALTER TABLE") >= 1 && count(sql, "information_schema") > 0,
"关键签名 0 命中=预处理或文件路径坏了,本类的断言全部不可信");
String rollbackExecutable = normalize(stripComments(raw(ROOT.resolve("docs/rollback-V150-shop-key-company.sql"))));
assertTrue(raw(ROOT.resolve("docs/rollback-V150-shop-key-company.sql")).contains("--"),
"回滚补丁若一条注释都没有,上面那条「可执行段为空」就成了恒真断言");
assertTrue(rollbackExecutable.isEmpty(), "回滚补丁的可执行段应当确实为空");
}
private static int count(String haystack, String needle) {
int n = 0, i = haystack.indexOf(needle);
while (i >= 0) {
n++;
i = haystack.indexOf(needle, i + needle.length());
}
return n;
}
}
@@ -62,6 +62,23 @@ class AppearancePatentLlmClientTest {
assertThat(client.buildConclusion("无侵权", "无侵权", "")).isEqualTo("无侵权"); assertThat(client.buildConclusion("无侵权", "无侵权", "")).isEqualTo("无侵权");
} }
/**
* 商标维度查询失败、外观已判定:结论必须带着外观结论并标出「商标待复核」,
* 不能整格写「商标查询失败」把已判出的外观结论盖掉 —— 用户据此以为整单没检测,
* 而实际上只有商标那一维没核上。
*/
@Test
void conclusionKeepsAppearanceVerdictWhenBrandQueryFailed() {
assertThat(client.buildConclusion("商标查询失败", "无侵权", ""))
.isEqualTo("外观无侵权·商标待复核");
// 外观也没判出来时不编造结论:维持原文案
assertThat(client.buildConclusion("商标查询失败", "外观识别异常", ""))
.isEqualTo("商标查询失败");
assertThat(client.buildConclusion("商标查询失败", "", "")).isEqualTo("商标查询失败");
// 外观已判侵权:保守结论优先,且不引入新词形(分组传播按「侵权」精确命中)
assertThat(client.buildConclusion("商标查询失败", "侵权", "")).isEqualTo("侵权");
}
@Test @Test
void skipBrandCheckWhenLlmTitleIsNone() throws Exception { void skipBrandCheckWhenLlmTitleIsNone() throws Exception {
BrandCheckClient brandCheckClient = mock(BrandCheckClient.class); BrandCheckClient brandCheckClient = mock(BrandCheckClient.class);
@@ -285,8 +285,9 @@ class AppearancePatentSheetBuilderTest {
} }
/** /**
* 结论列写「商标查询失败」时状态列必须判失败: * 结论列没给出完整判定时状态列必须判失败:
* 历史缺陷是按「结论非空即成功」推状态,于是结论写着"商标查询失败"、状态却写"成功",自相矛盾。 * 历史缺陷是按「结论非空即成功」推状态,于是结论写着"商标查询失败"、状态却写"成功",自相矛盾。
* 两种没判完整的形状都要覆盖:外观也没判定(整格查询失败)、外观已判定但商标待复核。
*/ */
@Test @Test
void test_sheet_builder_brand_query_failed_row_status_failed() throws Exception { void test_sheet_builder_brand_query_failed_row_status_failed() throws Exception {
@@ -295,14 +296,26 @@ class AppearancePatentSheetBuilderTest {
AppearancePatentResultRowDto r = resultRow("2_1", "B01A", "US"); AppearancePatentResultRowDto r = resultRow("2_1", "B01A", "US");
r.setTitleRisk("商标查询失败"); r.setTitleRisk("商标查询失败");
r.setAppearanceRisk("无侵权"); r.setAppearanceRisk("无侵权");
r.setConclusion("商标查询失败"); r.setConclusion("外观无侵权·商标待复核");
AppearancePatentSheetBuilder.buildResultSheet(wb, List.of(p), Map.of( AppearancePatentParsedRowVo p2 = parsedRow("2_2", "B01B", "US", "t", "", "");
AppearancePatentSheetBuilder.rowKey(r), r)); AppearancePatentResultRowDto r2 = resultRow("2_2", "B01B", "US");
r2.setTitleRisk("商标查询失败");
r2.setAppearanceRisk("外观识别异常");
r2.setConclusion("商标查询失败");
AppearancePatentSheetBuilder.buildResultSheet(wb, List.of(p, p2), Map.of(
AppearancePatentSheetBuilder.rowKey(r), r,
AppearancePatentSheetBuilder.rowKey(r2), r2));
Row data = wb.getSheet("外观专利检测结果").getRow(1); Row data = wb.getSheet("外观专利检测结果").getRow(1);
assertEquals("商标查询失败", data.getCell(9).getStringCellValue(), "标题维度保留查询失败文案"); assertEquals("商标查询失败", data.getCell(9).getStringCellValue(), "标题维度保留查询失败文案");
assertEquals("商标查询失败", data.getCell(11).getStringCellValue(), "结论列保留查询失败文案"); assertEquals("无侵权", data.getCell(10).getStringCellValue(), "外观维度保留已判定结论");
assertEquals("外观无侵权·商标待复核", data.getCell(11).getStringCellValue(),
"结论列带上外观判定与待复核标记");
assertEquals("失败", data.getCell(12).getStringCellValue(), "商标没成功 → 状态失败"); assertEquals("失败", data.getCell(12).getStringCellValue(), "商标没成功 → 状态失败");
Row both = wb.getSheet("外观专利检测结果").getRow(2);
assertEquals("商标查询失败", both.getCell(11).getStringCellValue(), "外观也没判定 → 结论仍是查询失败");
assertEquals("失败", both.getCell(12).getStringCellValue(), "两维都没判完整 → 状态失败");
} }
} }
@@ -318,6 +331,8 @@ class AppearancePatentSheetBuilderTest {
assertEquals("失败", AppearancePatentSheetBuilder.resolveResultStatus("LLM http 503: overloaded")); assertEquals("失败", AppearancePatentSheetBuilder.resolveResultStatus("LLM http 503: overloaded"));
assertEquals("失败", AppearancePatentSheetBuilder.resolveResultStatus(" ")); assertEquals("失败", AppearancePatentSheetBuilder.resolveResultStatus(" "));
assertEquals("失败", AppearancePatentSheetBuilder.resolveResultStatus(null)); assertEquals("失败", AppearancePatentSheetBuilder.resolveResultStatus(null));
// 「含侵权二字即成功」这条判据不能把带待复核标记的结论读成成功
assertEquals("失败", AppearancePatentSheetBuilder.resolveResultStatus("外观无侵权·商标待复核"));
} }
@Test @Test
@@ -1,6 +1,5 @@
package com.nanri.aiimage.modules.collectdata.util; package com.nanri.aiimage.modules.collectdata.util;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.modules.collectdata.model.vo.CollectDataResultRowVo; import com.nanri.aiimage.modules.collectdata.model.vo.CollectDataResultRowVo;
import com.nanri.aiimage.modules.invalidasin.mapper.InvalidAsinDataMapper; import com.nanri.aiimage.modules.invalidasin.mapper.InvalidAsinDataMapper;
import com.nanri.aiimage.modules.invalidasin.model.entity.InvalidAsinDataEntity; import com.nanri.aiimage.modules.invalidasin.model.entity.InvalidAsinDataEntity;
@@ -12,6 +11,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.doThrow;
@@ -28,28 +28,24 @@ import static org.mockito.Mockito.when;
* data_value 的批次不发起任何 insertBatchIgnore 调用;远程失败降级记录 * data_value 的批次不发起任何 insertBatchIgnore 调用;远程失败降级记录
* 计数(跳过写入),可恢复后继续,不抛出中断整个提交流程的异常。 * 计数(跳过写入),可恢复后继续,不抛出中断整个提交流程的异常。
* *
* <p>归属那一笔(10-05 批次 3):实体与 INSERT 列清单此前都不带 company_id/uploader_user_id, * <p>归属那一笔的现网口径(控制方 2026-10-06 定案):这张黑名单<b>全平台共享、不按公司区分</b>,
* V145 补的列全靠 DEFAULT 1 盖 ⇒ 第 2 家公司跑货源产生的行被记成第 1 家。写入器现在按 * 写入器不再推公司、实体上也没有 company_id 可写({@code InvalidAsinDataServiceTest} 与
* 调用方给的任务发起账号推公司,<b>推不出公司就整批不写</b>(宁可少一条黑名单,也不把行盖成 * {@code CompanyIdParamGoesThroughReadScopeTest} 分别钉住"预检不带公司列"和"这一族不许回流")。
* 别家公司 —— 那会让另一家的正常品牌被静默过滤)。</p> * 10-05 那版"推不出公司就整批不写"的闸门一并放开:{@code uploader_user_id} 只记"哪个账号采出来的",
* 推不出账号照写 —— 少一条黑名单 = 下次同样的品牌再买一次代理费。</p>
*/ */
class CollectDataInvalidAsinBatchWriterTest { class CollectDataInvalidAsinBatchWriterTest {
/** 任务发起账号(biz_file_task.user_id)。 */ /** 任务发起账号(biz_file_task.user_id):只落 uploader_user_id 这一列,不参与可见性。 */
private static final Long UPLOADER = 7L; private static final Long UPLOADER = 7L;
/** 该账号归属的公司 —— 必须与 UPLOADER 不同值,否则断言分不清写进去的是哪个。 */
private static final Long UPLOADER_COMPANY = 2L;
private InvalidAsinDataMapper invalidAsinDataMapper; private InvalidAsinDataMapper invalidAsinDataMapper;
private CompanyScopeSupport companyScopeSupport;
private CollectDataInvalidAsinBatchWriter writer; private CollectDataInvalidAsinBatchWriter writer;
@BeforeEach @BeforeEach
void setUp() { void setUp() {
invalidAsinDataMapper = mock(InvalidAsinDataMapper.class); invalidAsinDataMapper = mock(InvalidAsinDataMapper.class);
companyScopeSupport = mock(CompanyScopeSupport.class); writer = new CollectDataInvalidAsinBatchWriter(invalidAsinDataMapper, 10);
when(companyScopeSupport.companyIdOrNull(UPLOADER)).thenReturn(UPLOADER_COMPANY);
writer = new CollectDataInvalidAsinBatchWriter(invalidAsinDataMapper, companyScopeSupport, 10);
} }
@Test @Test
@@ -151,7 +147,7 @@ class CollectDataInvalidAsinBatchWriterTest {
when(invalidAsinDataMapper.insertBatchIgnore(anyList())).thenAnswer( when(invalidAsinDataMapper.insertBatchIgnore(anyList())).thenAnswer(
invocation -> ((List<?>) invocation.getArgument(0)).size()); invocation -> ((List<?>) invocation.getArgument(0)).size());
CollectDataInvalidAsinBatchWriter smallWriter = CollectDataInvalidAsinBatchWriter smallWriter =
new CollectDataInvalidAsinBatchWriter(invalidAsinDataMapper, companyScopeSupport, 3); new CollectDataInvalidAsinBatchWriter(invalidAsinDataMapper, 3);
List<CollectDataResultRowVo> rows = new ArrayList<>(); List<CollectDataResultRowVo> rows = new ArrayList<>();
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
rows.add(row("B" + String.format("%09d", i + 1), "brand")); rows.add(row("B" + String.format("%09d", i + 1), "brand"));
@@ -211,12 +207,10 @@ class CollectDataInvalidAsinBatchWriterTest {
} }
@Test @Test
void test_batch_3_asin_normal_ownership_is_stamped_on_every_row() { void test_batch_3_asin_normal_uploader_is_stamped_on_every_row() {
// 归属由任务发起账号推:每一行都带 company_id + uploader_user_id, // uploader_user_id 每行都从调用方给的任务发起账号落,不留空(空了事后追不到是哪次采集采出来的)。
// 而不是留空让 DEFAULT 1 去盖(那会把第 2 家的行记成第 1 家,事后分不开)。
when(invalidAsinDataMapper.insertBatchIgnore(anyList())).thenAnswer( when(invalidAsinDataMapper.insertBatchIgnore(anyList())).thenAnswer(
invocation -> ((List<?>) invocation.getArgument(0)).size()); invocation -> ((List<?>) invocation.getArgument(0)).size());
when(companyScopeSupport.companyIdOrNull(UPLOADER)).thenReturn(UPLOADER_COMPANY);
writer.writeBatch(List.of(row("B000000001", "nike"), row("B000000002", "zara")), UPLOADER); writer.writeBatch(List.of(row("B000000001", "nike"), row("B000000002", "zara")), UPLOADER);
@@ -225,21 +219,27 @@ class CollectDataInvalidAsinBatchWriterTest {
List<InvalidAsinDataEntity> entities = captor.getValue(); List<InvalidAsinDataEntity> entities = captor.getValue();
assertEquals(2, entities.size()); assertEquals(2, entities.size());
for (InvalidAsinDataEntity entity : entities) { for (InvalidAsinDataEntity entity : entities) {
assertEquals(UPLOADER_COMPANY, entity.getCompanyId(), "company_id 来自发起账号,不是 DEFAULT");
assertEquals(UPLOADER, entity.getUploaderUserId(), "uploader_user_id 一并落,处置可回溯到人"); assertEquals(UPLOADER, entity.getUploaderUserId(), "uploader_user_id 一并落,处置可回溯到人");
} }
} }
@Test @Test
void test_batch_3_asin_invalid_owner_unresolved_skips_whole_batch() { void test_shared_asin_normal_unresolved_uploader_still_writes() {
// 推不出公司(账号已删/没有公司):整批不写、返回 0、一次 insertBatchIgnore 都不发。 // 10-06 定案「放开:照样写入」的钉子。账号已删/推不出归属时整批照写,只是那一列留空——
// 这一族的替代方案是"照常写、让 DEFAULT 盖一家",那是静默串数据,必须判红。 // 黑名单是全平台共享的,可见性不看这两列。原口径「推不出就整批不写」的后果是少一条黑名单 =
when(companyScopeSupport.companyIdOrNull(UPLOADER)).thenReturn(null); // 下次同样的品牌再买一次代理,那是为了一个不参与读过滤的列丢真实的降本数据。
when(invalidAsinDataMapper.insertBatchIgnore(anyList())).thenAnswer(
invocation -> ((List<?>) invocation.getArgument(0)).size());
int written = writer.writeBatch(List.of(row("B000000001", "nike"), row("B000000002", "zara")), UPLOADER); int written = writer.writeBatch(List.of(row("B000000001", "nike"), row("B000000002", "zara")), null);
assertEquals(0, written, "归属推不出 ⇒ 一行都不写"); assertEquals(2, written, "推不出发起账号也整批写入");
verify(invalidAsinDataMapper, never()).insertBatchIgnore(anyList()); ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class);
verify(invalidAsinDataMapper).insertBatchIgnore(captor.capture());
assertEquals(2, captor.getValue().size());
for (InvalidAsinDataEntity entity : captor.getValue()) {
assertNull(entity.getUploaderUserId(), "那一列留空即可,不许因此少写一行");
}
} }
private static CollectDataResultRowVo row(String asin, String brand) { private static CollectDataResultRowVo row(String asin, String brand) {
@@ -36,10 +36,15 @@ import static org.mockito.Mockito.when;
* 还没摘,此后每个没显式传公司的写入都会被静默塞进默认那家——不报错、不丢数据,只在后台列表里 * 还没摘,此后每个没显式传公司的写入都会被静默塞进默认那家——不报错、不丢数据,只在后台列表里
* 表现成"这条数据怎么在别家公司"。所以必须用代码在启动期喊出来,而不是写在注释里等人记得。</p> * 表现成"这条数据怎么在别家公司"。所以必须用代码在启动期喊出来,而不是写在注释里等人记得。</p>
* *
* <p>V145 之后盯的是【一张清单】(users + 两张规则库 + V147 的 biz_product_category),不是一列: * <p>V145 之后盯的是【一张清单】,不是一列:漏登记的那张表等于没人盯,所以"探不到列"也要出声(见
* 漏登记的那张表等于没人盯,所以"探不到列"也要出声(见
* {@link #unwatchedTableIsAnnouncedInsteadOfLookingClean})。清单与探针 SQL 的 IN 列表双向同源由 * {@link #unwatchedTableIsAnnouncedInsteadOfLookingClean})。清单与探针 SQL 的 IN 列表双向同源由
* {@link #watchedTablesMatchTheProbeSql} 钉住。</p> * {@link #watchedTablesMatchTheProbeSql} 钉住。</p>
*
* <p>清单也会随口径<b>缩短</b>:{@code biz_invalid_asin_data}(V145)与 {@code biz_product_category}
* (V147)已按 2026-10-06「品牌数据库/商品类目做成所有公司共享」的定案一并摘掉登记。这两列的
* {@code DEFAULT 1} 于是从"待摘的风险"翻转成"<b>承重</b>约束"——列还在库里,写入路径不再传公司,
* {@code NOT NULL} 就靠它填。此时哨兵再喊"去摘 DEFAULT",后果不是修好了而是每次写入 1364,
* 由 {@link #sharedTablesStayOutOfTheWatchList} 反向钉住不许回流。</p>
*/ */
class CompanyDefaultGuardTest { class CompanyDefaultGuardTest {
@@ -125,7 +130,7 @@ class CompanyDefaultGuardTest {
@DisplayName("第二家公司已开通、users 的 DEFAULT 还在:打 ERROR 并带上哨兵标记") @DisplayName("第二家公司已开通、users 的 DEFAULT 还在:打 ERROR 并带上哨兵标记")
void secondCompanyWithDefaultStillOnShoutsError() { void secondCompanyWithDefaultStillOnShoutsError() {
companies(2); companies(2);
probeReturns("users=1", "biz_invalid_asin_data=null", "biz_dedupe_total_data=null"); probeReturns("users=1", "biz_dedupe_total_data=null");
guard.check(); guard.check();
@@ -136,18 +141,15 @@ class CompanyDefaultGuardTest {
} }
@Test @Test
@DisplayName("V145 的两张规则库带 DEFAULT:两张都要点出来,不许只报第一条") @DisplayName("biz_dedupe_total_data 仍按公司:DEFAULT 还在必须点出来,不许因为它是清单第二条就漏掉")
void ruleTablesAreWatchedToo() { void dedupeTableIsStillWatched() {
companies(2); companies(2);
probeReturns("users=null", probeReturns("users=null", "biz_dedupe_total_data=1");
"biz_invalid_asin_data=1",
"biz_dedupe_total_data=1");
guard.check(); guard.check();
assertThat(messageAt(Level.ERROR)) assertThat(messageAt(Level.ERROR))
.contains(CompanyDefaultGuard.ALARM) .contains(CompanyDefaultGuard.ALARM)
.contains("biz_invalid_asin_data.company_id DEFAULT=1")
.contains("biz_dedupe_total_data.company_id DEFAULT=1"); .contains("biz_dedupe_total_data.company_id DEFAULT=1");
} }
@@ -155,7 +157,7 @@ class CompanyDefaultGuardTest {
@DisplayName("给出的修复语句必须是 ALTER COLUMN ... DROP DEFAULT:MODIFY 会重建表、把派生归属洗掉") @DisplayName("给出的修复语句必须是 ALTER COLUMN ... DROP DEFAULT:MODIFY 会重建表、把派生归属洗掉")
void fixHintIsTheMetadataOnlyForm() { void fixHintIsTheMetadataOnlyForm() {
companies(2); companies(2);
probeReturns("users=null", "biz_invalid_asin_data=null", "biz_dedupe_total_data=1"); probeReturns("users=null", "biz_dedupe_total_data=1");
guard.check(); guard.check();
@@ -176,10 +178,10 @@ class CompanyDefaultGuardTest {
} }
@Test @Test
@DisplayName("三张表的 DEFAULT 都已摘掉:一声不响") @DisplayName("清单里每一条的 DEFAULT 都已摘掉:一声不响")
void droppedDefaultKeepsQuiet() { void droppedDefaultKeepsQuiet() {
companies(3); companies(3);
probeReturns("users=null", "biz_invalid_asin_data=null", "biz_dedupe_total_data=null"); probeReturns("users=null", "biz_dedupe_total_data=null");
guard.check(); guard.check();
@@ -191,7 +193,7 @@ class CompanyDefaultGuardTest {
@DisplayName("DEFAULT 是空串也按「已摘除」处理,别把空值读成还在") @DisplayName("DEFAULT 是空串也按「已摘除」处理,别把空值读成还在")
void blankDefaultCountsAsDropped() { void blankDefaultCountsAsDropped() {
companies(2); companies(2);
probeReturns("users= ", "biz_invalid_asin_data=null", "biz_dedupe_total_data=null"); probeReturns("users= ", "biz_dedupe_total_data=null");
guard.check(); guard.check();
@@ -243,26 +245,46 @@ class CompanyDefaultGuardTest {
} }
} }
/**
* 反向钉,形状与 {@link #shopKeyTableIsWatchedToo} 相反。{@code biz_invalid_asin_data}(V145)
* 与 {@code biz_product_category}(V147)按 2026-10-06「这两页做成所有公司共享」的定案一起摘了登记,
* 但<b>列和 {@code DEFAULT 1} 都还在库里</b>——它们如今是 {@code NOT NULL} 的承重约束
* (写入路径不再传公司,全靠默认值填这一列)。
*
* <p>所以这一支演的是"探针<b>真的</b>把 {@code DEFAULT=1} 端上桌,哨兵必须一声不响"。
* 谁把这两张表加回 {@code WATCHED_TABLES}(那等于指挥运维去执行本类给出的 {@code DROP DEFAULT},
* 代价是每次写入 1364;品牌库那条还会被 {@code CollectDataInvalidAsinBatchWriter} 吞成 warn ⇒
* 接口报成功而黑名单静默少一批),就会在这里红。</p>
*
* <p>用 {@code probeReturnsOnly} 而不是 {@code probeReturns}:后者只按清单建行,未登记的表根本
* 进不了结果集——那样"哨兵没喊"是空转转出来的,不是判出来的。四张仍登记的表逐个给 {@code null},
* 既是这一支的正样本(少给一条就会撞 WARN 而红,说明"没喊"不是因为什么都没探到)。</p>
*/
@Test @Test
@DisplayName("V147 的 biz_product_category 也在盯的清单里:摘 DEFAULT 那一步不许把它落下") @DisplayName("两张共享表故意不在清单里:探针端出 DEFAULT=1 也不许喊")
void productCategoryTableIsWatchedToo() { void sharedTablesStayOutOfTheWatchList() {
companies(2); companies(2);
probeReturns("biz_product_category=1"); probeReturnsOnly("users=null",
"biz_dedupe_total_data=null",
"biz_shop_key=null",
"columns=null",
"biz_invalid_asin_data=1",
"biz_product_category=1");
guard.check(); guard.check();
assertThat(messageAt(Level.ERROR)) assertThat(CompanyDefaultGuard.WATCHED_TABLES)
.contains(CompanyDefaultGuard.ALARM) .as("摘登记是定案的一部分:加回清单就等于让哨兵去喊一次真故障")
.contains("biz_product_category.company_id DEFAULT=1") .doesNotContain("biz_invalid_asin_data", "biz_product_category");
.contains("ALTER TABLE biz_product_category ALTER COLUMN company_id DROP DEFAULT") assertThat(messageAt(Level.ERROR)).isEmpty();
.doesNotContain("MODIFY"); assertThat(messageAt(Level.WARN)).isEmpty();
} }
@Test @Test
@DisplayName("探的是清单里这几张表的 company_id 列,表名列名写错就等于没探") @DisplayName("探的是清单里这几张表的 company_id 列,表名列名写错就等于没探")
void probeReadsTheRightColumns() { void probeReadsTheRightColumns() {
companies(2); companies(2);
probeReturns("users=null", "biz_invalid_asin_data=null", "biz_dedupe_total_data=null"); probeReturns("users=null", "biz_dedupe_total_data=null");
guard.check(); guard.check();
@@ -277,6 +299,26 @@ class CompanyDefaultGuardTest {
} }
} }
/**
* V150 的 {@code biz_shop_key}:这一列的 DEFAULT 1 与前三张同形(只为同批旧 jar 存在),
* 而这张表<b>没有账号列</b>,历史归属的全部依据就是加列那一刻记录的默认值——
* 所以"摘 DEFAULT"这一步必须由哨兵盯着,漏摘的代价是第 2 家管理员新建的密钥静默归进第 1 家。
*/
@Test
@DisplayName("V150 的 biz_shop_key 也在盯的清单里:摘 DEFAULT 那一步不许把它落下")
void shopKeyTableIsWatchedToo() {
companies(2);
probeReturns("biz_shop_key=1");
guard.check();
assertThat(messageAt(Level.ERROR))
.contains(CompanyDefaultGuard.ALARM)
.contains("biz_shop_key.company_id DEFAULT=1")
.contains("ALTER TABLE biz_shop_key ALTER COLUMN company_id DROP DEFAULT")
.doesNotContain("MODIFY");
}
/** /**
* 双向钉同源。只钉"清单里的都在 SQL 里"会漏掉另一侧:有人往 SQL 的 IN 列表加了一张表、 * 双向钉同源。只钉"清单里的都在 SQL 里"会漏掉另一侧:有人往 SQL 的 IN 列表加了一张表、
* 却没加进 {@code WATCHED_TABLES},那么 {@link #check} 的逐表循环根本不会走到它—— * 却没加进 {@code WATCHED_TABLES},那么 {@link #check} 的逐表循环根本不会走到它——
@@ -307,7 +349,7 @@ class CompanyDefaultGuardTest {
private String probeSqlText() { private String probeSqlText() {
companies(2); companies(2);
probeReturns("users=null", "biz_invalid_asin_data=null", "biz_dedupe_total_data=null"); probeReturns("users=null", "biz_dedupe_total_data=null");
guard.check(); guard.check();
ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
verify(jdbcTemplate).queryForList(sql.capture()); verify(jdbcTemplate).queryForList(sql.capture());
@@ -9,17 +9,21 @@ import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.company.mapper.CompanyMapper; import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
import com.nanri.aiimage.modules.company.model.dto.CompanySaveRequest; import com.nanri.aiimage.modules.company.model.dto.CompanySaveRequest;
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity; import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import org.apache.ibatis.builder.MapperBuilderAssistant; import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor; import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.util.List; import java.util.List;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@@ -37,6 +41,7 @@ class CompanyServiceDirectoryTest {
private CompanyMapper companyMapper; private CompanyMapper companyMapper;
private AdminAuthSupport adminAuthSupport; private AdminAuthSupport adminAuthSupport;
private PermissionMenuService permissionMenuService;
private CompanyService companyService; private CompanyService companyService;
@BeforeEach @BeforeEach
@@ -46,7 +51,8 @@ class CompanyServiceDirectoryTest {
new MapperBuilderAssistant(new MybatisConfiguration(), ""), CompanyEntity.class); new MapperBuilderAssistant(new MybatisConfiguration(), ""), CompanyEntity.class);
companyMapper = mock(CompanyMapper.class); companyMapper = mock(CompanyMapper.class);
adminAuthSupport = mock(AdminAuthSupport.class); adminAuthSupport = mock(AdminAuthSupport.class);
companyService = new CompanyService(companyMapper, adminAuthSupport); permissionMenuService = mock(PermissionMenuService.class);
companyService = new CompanyService(companyMapper, adminAuthSupport, permissionMenuService);
} }
private AdminUserEntity operator(String role, Long companyId) { private AdminUserEntity operator(String role, Long companyId) {
@@ -184,6 +190,44 @@ class CompanyServiceDirectoryTest {
assertThat(capturedSelectCount().getParamNameValuePairs()).containsValue("福州数富"); assertThat(capturedSelectCount().getParamNameValuePairs()).containsValue("福州数富");
} }
/**
* 设计文档 §2 D4 的那一行调用:每家公司一棵树之后,「新增公司」必须同批把菜单树建出来。
*
* <p>零菜单行的租户<b>全程不报错</b>——那家账号登录侧边栏全空、授权树一个勾都没有,
* 症状长得像"这个公司还没开通"。所以这一钉守的是 {@code create()} 里那次调用本身
* ({@code copyTreeFromTemplate} 的内部形状由 PermissionMenuServiceCompanyScopeTest 那三条盖),
* 而不是复制逻辑写得多对。</p>
*/
@Test
@DisplayName("超管新建公司:插行之后同一次写入里给它复制一套菜单树,模板取操作者本公司")
void createSeedsTheNewCompanyMenuTreeAfterInsert() {
when(companyMapper.selectCount(any())).thenReturn(0L);
// 真库里 insert 会回填自增 id;不模拟这一步就只能断出 copyTreeFromTemplate(null, …)。
when(companyMapper.insert(any(CompanyEntity.class))).thenAnswer(invocation -> {
invocation.getArgument(0, CompanyEntity.class).setId(77L);
return 1;
});
companyService.create(operator("super_admin", 5L), request("福州数富", null, null));
InOrder order = inOrder(companyMapper, permissionMenuService);
order.verify(companyMapper).insert(any(CompanyEntity.class));
// 模板公司取操作者的 5L 而不是硬编码 1L:厦门米椿花不再是"唯一有树的那家"以后,
// 抄公司 1 在眼下照样能跑,第三家开通时就把三家拴成一棵——那正是 §7 路线乙被否决的形状。
order.verify(permissionMenuService).copyTreeFromTemplate(77L, 5L);
}
@Test
@DisplayName("建公司被拒时不建树:重名那笔先抛,不许留下一套挂在不存在公司上的菜单")
void rejectedCreateDoesNotSeedMenuTree() {
when(companyMapper.selectCount(any())).thenReturn(1L);
assertThatThrownBy(() -> companyService.create(operator("super_admin", 1L), request("厦门米椿花", null, null)))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("已存在");
verify(permissionMenuService, never()).copyTreeFromTemplate(any(), any());
}
@Test @Test
@DisplayName("公司名超过列宽 128 时先拒,别把 1406 抛成 500") @DisplayName("公司名超过列宽 128 时先拒,别把 1406 抛成 500")
void createRejectsNameLongerThanColumn() { void createRejectsNameLongerThanColumn() {
@@ -6,6 +6,7 @@ import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.company.mapper.CompanyMapper; import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity; import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import org.apache.ibatis.builder.MapperBuilderAssistant; import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.DisplayName;
@@ -41,7 +42,8 @@ class CompanyServiceNameLookupTest {
TableInfoHelper.initTableInfo( TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""), CompanyEntity.class); new MapperBuilderAssistant(new MybatisConfiguration(), ""), CompanyEntity.class);
companyMapper = mock(CompanyMapper.class); companyMapper = mock(CompanyMapper.class);
companyService = new CompanyService(companyMapper, mock(AdminAuthSupport.class)); companyService = new CompanyService(companyMapper, mock(AdminAuthSupport.class),
mock(PermissionMenuService.class));
} }
private CompanyEntity company(Long id, String name, int status) { private CompanyEntity company(Long id, String name, int status) {
@@ -4,6 +4,7 @@ import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.company.mapper.CompanyMapper; import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity; import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@@ -49,7 +50,7 @@ class CompanyServiceRequireActiveTest {
} }
private CompanyService service(CompanyMapper mapper) { private CompanyService service(CompanyMapper mapper) {
return new CompanyService(mapper, mock(AdminAuthSupport.class)); return new CompanyService(mapper, mock(AdminAuthSupport.class), mock(PermissionMenuService.class));
} }
private CompanyEntity company(Long id, Integer status) { private CompanyEntity company(Long id, Integer status) {
@@ -1,10 +1,10 @@
package com.nanri.aiimage.modules.invalidasin.controller; package com.nanri.aiimage.modules.invalidasin.controller;
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.security.AdminAuthSupport; import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.invalidasin.model.vo.InvalidAsinDataPageVo; import com.nanri.aiimage.modules.invalidasin.model.vo.InvalidAsinDataPageVo;
import com.nanri.aiimage.modules.invalidasin.service.InvalidAsinDataService; import com.nanri.aiimage.modules.invalidasin.service.InvalidAsinDataService;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo; import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService; import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
@@ -20,13 +20,21 @@ import java.util.List;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/**
* 鉴权那一半(内网代理换真人、直连不许伪造 super_admin)+ 「全平台共享」的现网口径。
*
* <p>10-06 定案品牌数据库不区分公司:这里原先另有两条钉「tab 传什么都不算」的
* (超管不选 tab ⇒ 交给 service 的筛值是 null、非超管传别家 ⇒ 收窄成 null),它们吃的都是
* controller 上那个 {@code company_id} 形参,形参已随定案摘掉,两条一起删除。
* "公司维度不许回流"由 {@code CompanyIdParamGoesThroughReadScopeTest} 按 module 目录反向钉,
* 不靠本文件(这里连可断言的参数都没有了)。</p>
*/
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class InvalidAsinDataControllerTest { class InvalidAsinDataControllerTest {
@@ -36,8 +44,6 @@ class InvalidAsinDataControllerTest {
private AdminAuthSupport adminAuthSupport; private AdminAuthSupport adminAuthSupport;
@Mock @Mock
private PermissionMenuService permissionMenuService; private PermissionMenuService permissionMenuService;
@Mock
private com.nanri.aiimage.common.service.DataReadScope dataReadScope;
@InjectMocks @InjectMocks
private InvalidAsinDataController controller; private InvalidAsinDataController controller;
@@ -60,13 +66,12 @@ class InvalidAsinDataControllerTest {
when(adminAuthSupport.currentRole(operator)).thenReturn(null); when(adminAuthSupport.currentRole(operator)).thenReturn(null);
when(permissionMenuService.getUserColumnPermissions(7L, "admin")) when(permissionMenuService.getUserColumnPermissions(7L, "admin"))
.thenReturn(List.of(invalidAsinDataPermission())); .thenReturn(List.of(invalidAsinDataPermission()));
when(invalidAsinDataService.page(1L, 15L, "", "", "", 3L, 7L, false, null)) when(invalidAsinDataService.page(1L, 15L, "", "", "", 3L, 7L, false))
.thenReturn(new InvalidAsinDataPageVo()); .thenReturn(new InvalidAsinDataPageVo());
when(dataReadScope.readCompanyId(operator, null)).thenReturn(null);
controller.page(1L, 15L, "", "", "", 3L, null, request); controller.page(1L, 15L, "", "", "", 3L, request);
verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 7L, false, null); verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 7L, false);
} }
@Test @Test
@@ -76,7 +81,7 @@ class InvalidAsinDataControllerTest {
request.addParameter("superAdmin", "true"); request.addParameter("superAdmin", "true");
when(adminAuthSupport.requireUser(request)).thenThrow(new BusinessException(401, "未登录")); when(adminAuthSupport.requireUser(request)).thenThrow(new BusinessException(401, "未登录"));
assertThrows(BusinessException.class, () -> controller.page(1L, 15L, "", "", "", 3L, null, request)); assertThrows(BusinessException.class, () -> controller.page(1L, 15L, "", "", "", 3L, request));
verifyNoInteractions(invalidAsinDataService); verifyNoInteractions(invalidAsinDataService);
verify(permissionMenuService, never()).requireUserOperator(any()); verify(permissionMenuService, never()).requireUserOperator(any());
@@ -89,52 +94,15 @@ class InvalidAsinDataControllerTest {
AdminUserEntity operator = user(1L, "super_admin"); AdminUserEntity operator = user(1L, "super_admin");
when(adminAuthSupport.requireUser(request)).thenReturn(operator); when(adminAuthSupport.requireUser(request)).thenReturn(operator);
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin"); when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
when(invalidAsinDataService.page(1L, 15L, "", "", "", 3L, 1L, true, 2L)) when(invalidAsinDataService.page(1L, 15L, "", "", "", 3L, 1L, true))
.thenReturn(new InvalidAsinDataPageVo()); .thenReturn(new InvalidAsinDataPageVo());
when(dataReadScope.readCompanyId(operator, 2L)).thenReturn(2L);
controller.page(1L, 15L, "", "", "", 3L, 2L, request); controller.page(1L, 15L, "", "", "", 3L, request);
verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 1L, true, 2L); verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 1L, true);
verify(permissionMenuService, never()).getUserColumnPermissions(eq(1L), eq("admin")); verify(permissionMenuService, never()).getUserColumnPermissions(eq(1L), eq("admin"));
} }
@Test
void superAdminWithoutCompanyTabStaysUnfiltered() {
// 反向钉:tab 没传公司(companyId=null)⇒ 交给 service 的筛值必须是 null(= 不筛)。
// 哪天有人把它硬写成某个默认公司,全量视图会静默变成一家的视图。
MockHttpServletRequest request = new MockHttpServletRequest();
AdminUserEntity operator = user(1L, "super_admin");
when(adminAuthSupport.requireUser(request)).thenReturn(operator);
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
when(dataReadScope.readCompanyId(operator, null)).thenReturn(null);
when(invalidAsinDataService.page(1L, 15L, "", "", "", 3L, 1L, true, null))
.thenReturn(new InvalidAsinDataPageVo());
controller.page(1L, 15L, "", "", "", 3L, null, request);
verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 1L, true, null);
}
@Test
void forgedCompanyTabForNonSuperAdminIsNarrowedToItsOwnCompany() {
// 非超管传别人的公司 id:出口给的是 null(不筛)而不是那家 —— 这页的隔离靠分组权限,
// 叠公司会把「靠分组可见」的行整批删掉。钉住"传什么都不算"的现网口径。
MockHttpServletRequest request = new MockHttpServletRequest();
AdminUserEntity operator = user(9L, "admin");
when(adminAuthSupport.requireUser(request)).thenReturn(operator);
when(adminAuthSupport.currentRole(operator)).thenReturn("admin");
when(permissionMenuService.getUserColumnPermissions(9L, "admin"))
.thenReturn(List.of(invalidAsinDataPermission()));
when(dataReadScope.readCompanyId(operator, 5L)).thenReturn(null);
when(invalidAsinDataService.page(1L, 15L, "", "", "", 3L, 9L, false, null))
.thenReturn(new InvalidAsinDataPageVo());
controller.page(1L, 15L, "", "", "", 3L, 5L, request);
verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 9L, false, null);
}
private AdminUserEntity user(Long id, String role) { private AdminUserEntity user(Long id, String role) {
AdminUserEntity user = new AdminUserEntity(); AdminUserEntity user = new AdminUserEntity();
user.setId(id); user.setId(id);
@@ -4,7 +4,6 @@ import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper; import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException; import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.modules.invalidasin.mapper.InvalidAsinDataMapper; import com.nanri.aiimage.modules.invalidasin.mapper.InvalidAsinDataMapper;
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataCreateRequest; import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataCreateRequest;
import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataUpdateRequest; import com.nanri.aiimage.modules.invalidasin.model.dto.InvalidAsinDataUpdateRequest;
@@ -40,16 +39,10 @@ import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class InvalidAsinDataServiceTest { class InvalidAsinDataServiceTest {
/** 操作者 7L 所属公司。故意取 2 不取 1:DEFAULT 1 那家也能通过"非空"这一断言,取 2 才钉得住"真从会话来"。 */
private static final Long OPERATOR_COMPANY_ID = 2L;
@Mock @Mock
private InvalidAsinDataMapper invalidAsinDataMapper; private InvalidAsinDataMapper invalidAsinDataMapper;
@Mock @Mock
private ShopManageGroupService shopManageGroupService; private ShopManageGroupService shopManageGroupService;
/** 归属从操作者会话推导(create 里那唯一一处 requireCompanyId):不 mock 就是构造注入不到、整个 service 空指针。 */
@Mock
private CompanyScopeSupport companyScopeSupport;
@InjectMocks @InjectMocks
private InvalidAsinDataService service; private InvalidAsinDataService service;
@@ -63,7 +56,6 @@ class InvalidAsinDataServiceTest {
ShopManageGroupEntity group = group(9L, "group-a"); ShopManageGroupEntity group = group(9L, "group-a");
InvalidAsinDataEntity saved = data(91L, "MANUAL", 9L); InvalidAsinDataEntity saved = data(91L, "MANUAL", 9L);
when(companyScopeSupport.requireCompanyId(7L)).thenReturn(OPERATOR_COMPANY_ID);
when(shopManageGroupService.listAccessibleGroupIds(7L, false)).thenReturn(Set.of(12L, 9L)); when(shopManageGroupService.listAccessibleGroupIds(7L, false)).thenReturn(Set.of(12L, 9L));
when(shopManageGroupService.getAccessibleById(9L, 7L, false)).thenReturn(group); when(shopManageGroupService.getAccessibleById(9L, 7L, false)).thenReturn(group);
when(invalidAsinDataMapper.selectOne(any())).thenReturn(null); when(invalidAsinDataMapper.selectOne(any())).thenReturn(null);
@@ -83,21 +75,23 @@ class InvalidAsinDataServiceTest {
assertEquals("MANUAL", captor.getValue().getRecordSource()); assertEquals("MANUAL", captor.getValue().getRecordSource());
assertEquals("group-a", item.getGroupName()); assertEquals("group-a", item.getGroupName());
assertEquals("MANUAL", item.getRecordSource()); assertEquals("MANUAL", item.getRecordSource());
// 写侧归属:MANUAL 行的 company_id 必须真从操作者会话推导。V146 已摘掉该列的 DEFAULT 1,
// 没人推导就是 NULL —— 而 NULL 行在 readCompanyId 谓词下对所有公司 tab 都不可见(静默删除),
// 比"归属错一家"更难发现。
assertEquals(OPERATOR_COMPANY_ID, captor.getValue().getCompanyId());
assertEquals(7L, captor.getValue().getUploaderUserId()); assertEquals(7L, captor.getValue().getUploaderUserId());
// 重复预检必须与 V145 放宽后的唯一键 (company_id, data_value, brand) 同宽:少公司这一维, // 重复预检与 V151 退回后的全局唯一键 (data_value, brand) 同宽。
// 第 2 家永远无法新增第 1 家已有的品牌(跨公司误报「ASIN 已存在」)。 // 这是反向钉(2026-10-06 定案「品牌数据库全平台共享,不区分」):预检再带上 company_id 的话,
// 键是全局的而预检是按家的 ⇒ 同一 ASIN 在第 2 家能插进去,撞库时报 1062 而不是「ASIN 已存在」,
// 用户看到的是一句 500。所以这里钉的是"谓词里没有公司维度",不是"没有正样本"。
ArgumentCaptor<LambdaQueryWrapper<InvalidAsinDataEntity>> unique = ArgumentCaptor<LambdaQueryWrapper<InvalidAsinDataEntity>> unique =
ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class); ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
verify(invalidAsinDataMapper).selectOne(unique.capture()); verify(invalidAsinDataMapper).selectOne(unique.capture());
TableInfoHelper.initTableInfo( TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""), new MapperBuilderAssistant(new MybatisConfiguration(), ""),
InvalidAsinDataEntity.class); InvalidAsinDataEntity.class);
assertTrue(unique.getValue().getSqlSegment().contains("company_id")); String uniqueSql = unique.getValue().getSqlSegment();
assertTrue(unique.getValue().getParamNameValuePairs().containsValue(OPERATOR_COMPANY_ID)); assertTrue(uniqueSql.contains("data_value"), "预检判据整段没了:换了写法,下面的排他就是空断言");
assertFalse(uniqueSql.contains("company_id"),
"ensureUnique 又带上了 company_id:唯一键已退回全局(V151),按家预检会让重复行撞 1062 而不是报「ASIN 已存在」");
assertFalse(uniqueSql.contains("group_id"),
"ensureUnique 又按分组预检了:全局键里没有分组这一维,同形状会漏判");
} }
@Test @Test
@@ -109,7 +103,7 @@ class InvalidAsinDataServiceTest {
when(invalidAsinDataMapper.selectList(any())).thenReturn(List.of(manual)); when(invalidAsinDataMapper.selectList(any())).thenReturn(List.of(manual));
when(shopManageGroupService.buildGroupNameMap(any())).thenReturn(Map.of(9L, "group-a")); when(shopManageGroupService.buildGroupNameMap(any())).thenReturn(Map.of(9L, "group-a"));
InvalidAsinDataPageVo page = service.page(1, 15, "", "", "", 10L, 7L, false, null); InvalidAsinDataPageVo page = service.page(1, 15, "", "", "", 10L, 7L, false);
ArgumentCaptor<LambdaQueryWrapper<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class); ArgumentCaptor<LambdaQueryWrapper<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
verify(invalidAsinDataMapper).selectCount(captor.capture()); verify(invalidAsinDataMapper).selectCount(captor.capture());
@@ -133,7 +127,7 @@ class InvalidAsinDataServiceTest {
when(invalidAsinDataMapper.selectList(any())).thenReturn(List.of(automatic, orphan)); when(invalidAsinDataMapper.selectList(any())).thenReturn(List.of(automatic, orphan));
when(shopManageGroupService.buildGroupNameMap(any())).thenReturn(Map.of()); when(shopManageGroupService.buildGroupNameMap(any())).thenReturn(Map.of());
InvalidAsinDataPageVo page = service.page(1, 15, "", "", "", null, 1L, true, null); InvalidAsinDataPageVo page = service.page(1, 15, "", "", "", null, 1L, true);
assertEquals(2, page.getItems().size()); assertEquals(2, page.getItems().size());
assertEquals("AUTO", page.getItems().getFirst().getRecordSource()); assertEquals("AUTO", page.getItems().getFirst().getRecordSource());
@@ -147,7 +141,7 @@ class InvalidAsinDataServiceTest {
when(invalidAsinDataMapper.selectCount(any())).thenReturn(0L); when(invalidAsinDataMapper.selectCount(any())).thenReturn(0L);
when(invalidAsinDataMapper.selectList(any())).thenReturn(List.of()); when(invalidAsinDataMapper.selectList(any())).thenReturn(List.of());
service.page(1, 15, "", "", "", 9L, 1L, true, null); service.page(1, 15, "", "", "", 9L, 1L, true);
ArgumentCaptor<LambdaQueryWrapper<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class); ArgumentCaptor<LambdaQueryWrapper<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
verify(invalidAsinDataMapper).selectCount(captor.capture()); verify(invalidAsinDataMapper).selectCount(captor.capture());
@@ -164,7 +158,7 @@ class InvalidAsinDataServiceTest {
when(invalidAsinDataMapper.selectCount(any())).thenReturn(0L); when(invalidAsinDataMapper.selectCount(any())).thenReturn(0L);
when(invalidAsinDataMapper.selectList(any())).thenReturn(List.of()); when(invalidAsinDataMapper.selectList(any())).thenReturn(List.of());
service.page(1, 15, "", "B01", "acme", null, 1L, true, null); service.page(1, 15, "", "B01", "acme", null, 1L, true);
ArgumentCaptor<LambdaQueryWrapper<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class); ArgumentCaptor<LambdaQueryWrapper<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
verify(invalidAsinDataMapper).selectCount(captor.capture()); verify(invalidAsinDataMapper).selectCount(captor.capture());
@@ -141,8 +141,18 @@ class PermissionCompanyMenuHiddenTest {
return code.substring(from, end); return code.substring(from, end);
} }
/**
* 每一处引用受控集的出口都要点名数到(原名 {@code threeExitsAllReferenceTheSuperAdminOnlySet})。
*
* <p>V149(每家公司一套菜单树,定案 D3)冒出第四处出口:{@code copyTreeFromTemplate} 给新公司复制
* 模板树时<b>不许</b>把 {@code admin_companies} 那一行复制过去——它是角色内在闸门,公司 2 的树里
* 根本没有这行才干净。按 {@code docs/plans/19-company-tab.md} 那条交代("要加第四处出口 = 未批准的
* 行为变化,须自带一记变异"),这一记已经跑了:变异点 {@code copyTree clones the role-intrinsic gate row}
* 被 {@code PermissionMenuServiceCompanyScopeTest} 的「建树:三种 menu_type 全复制、闸门行不复制」打死,
* 详见 {@code docs/ops/menu-company-tree-design-2026-10-06.md} §8。</p>
*/
@Test @Test
void threeExitsAllReferenceTheSuperAdminOnlySet() throws IOException { void everyExitReferencesTheSuperAdminOnlySet() throws IOException {
String text = source(); String text = source();
assertThat(text).contains("SUPER_ADMIN_ONLY_KEYS"); assertThat(text).contains("SUPER_ADMIN_ONLY_KEYS");
List<String> code = executableCodeLines(text); List<String> code = executableCodeLines(text);
@@ -151,30 +161,31 @@ class PermissionCompanyMenuHiddenTest {
// 注释必须真被滤掉了:javadoc 里那四处 SUPER_ADMIN_ONLY_KEYS 链接一旦混进取样集,上面的计数就又回到"数得出但没数代码"。 // 注释必须真被滤掉了:javadoc 里那四处 SUPER_ADMIN_ONLY_KEYS 链接一旦混进取样集,上面的计数就又回到"数得出但没数代码"。
assertThat(code).as("扫描取样集自检: 注释行必须已被剔除") assertThat(code).as("扫描取样集自检: 注释行必须已被剔除")
.noneMatch(line -> line.contains("{@link") || line.trim().startsWith("*")); .noneMatch(line -> line.contains("{@link") || line.trim().startsWith("*"));
assertThat(code).as("扫描取样集自检: 三处出口都落在 toItemVos/落库这条链上,扫描必须扫得到它") assertThat(code).as("扫描取样集自检: 出口 1/2 落在 toItemVos/落库这条链上,扫描必须扫得到它")
.filteredOn(line -> line.contains("toItemVos(")).isNotEmpty(); .filteredOn(line -> line.contains("toItemVos(")).isNotEmpty();
// 三个出口各自都要引用它,而且只数代码:漏一个就留一条旁路(授权树能看见 / 当前用户菜单能带出 / 提交能写回)。 // 四个出口各自都要引用它,而且只数代码:漏一个就留一条旁路(授权树能看见 / 当前用户菜单能带出 /
// 提交能写回 / 新公司能拿到一行本该只在公司 1 树里存在的闸门菜单)。
// 旧写法是"SUPER_ADMIN_ONLY_KEYS 在整份文本里出现 ≥4 次",可 1 处定义 + 4 处 javadoc 就凑得满(三处过滤器全删仍剩 5 次), // 旧写法是"SUPER_ADMIN_ONLY_KEYS 在整份文本里出现 ≥4 次",可 1 处定义 + 4 处 javadoc 就凑得满(三处过滤器全删仍剩 5 次),
// 三处过滤器全删(或移进注释 / if (false) / 死分支)它照样绿 —— 变异 R10 就是这一记。 // 三处过滤器全删(或移进注释 / if (false) / 死分支)它照样绿 —— 变异 R10 就是这一记。
// 现在逐口钉:负向("不是受控项才留下")= 出口 1 的 list(operator, menuType, grantableOnly) // 现在逐口钉:负向("不是受控项才留下")= 出口 1 的 list(operator, menuType, grantableOnly)、
// 与出口 2 的 getUserColumnPermissions(...) 各一条;正向("是受控项才进剥离集") // 出口 2 的 getUserColumnPermissions(...)、出口 4 的 copyTreeFromTemplate(...) 各一条;
// = 出口 3 用来反解受控 id 的 superAdminOnlyMenuIds() 一条。行号会漂,所以只点方法名。 // 正向("是受控项才进剥离集")= 出口 3 用来反解受控 id 的 superAdminOnlyMenuIds() 一条。行号会漂,所以只点方法名。
// 将来真要加第四处出口时,连同这三条期望一起改(当前口径:恰三处出口,不许多也不许少)。 // 将来真要加第五处出口时,连同这三条期望一起改(当前口径:恰四处出口,不许多也不许少)。
List<String> negative = code.stream().filter(line -> line.contains(NEGATIVE_FILTER)).toList(); List<String> negative = code.stream().filter(line -> line.contains(NEGATIVE_FILTER)).toList();
List<String> positive = code.stream() List<String> positive = code.stream()
.filter(line -> line.contains(POSITIVE_FILTER)) .filter(line -> line.contains(POSITIVE_FILTER))
.filter(line -> !line.contains(NEGATIVE_FILTER)) .filter(line -> !line.contains(NEGATIVE_FILTER))
.toList(); .toList();
assertThat(negative) assertThat(negative)
.as("出口 1(授权树)+ 出口 2(当前用户菜单)各一条负向过滤,少一条就是一条旁路") .as("出口 1(授权树)+ 出口 2(当前用户菜单)+ 出口 4(给新公司复制树)各一条负向过滤,少一条就是一条旁路")
.hasSize(2); .hasSize(3);
assertThat(positive) assertThat(positive)
.as("出口 3(提交剥离)的正向反解恰好一条") .as("出口 3(提交剥离)的正向反解恰好一条")
.hasSize(1); .hasSize(1);
assertThat(code.stream().filter(line -> line.contains(GUARD_SET)).toList()) assertThat(code.stream().filter(line -> line.contains(GUARD_SET)).toList())
.as("1 处定义 + 3 处出口,全都得落在可执行行上") .as("1 处定义 + 4 处出口,全都得落在可执行行上")
.hasSizeGreaterThanOrEqualTo(4); .hasSizeGreaterThanOrEqualTo(5);
} }
@Test @Test
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.permission.controller;
import com.nanri.aiimage.common.exception.BusinessException; import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.permission.model.dto.ImageVideoDataPermissionUpdateRequest; import com.nanri.aiimage.modules.permission.model.dto.ImageVideoDataPermissionUpdateRequest;
import com.nanri.aiimage.modules.permission.model.dto.PermissionMenuCreateRequest;
import com.nanri.aiimage.modules.permission.model.dto.UserColumnPermissionUpdateRequest; import com.nanri.aiimage.modules.permission.model.dto.UserColumnPermissionUpdateRequest;
import com.nanri.aiimage.common.model.entity.AdminUserEntity; import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.permission.model.vo.ImageVideoDataPermissionUserVo; import com.nanri.aiimage.modules.permission.model.vo.ImageVideoDataPermissionUserVo;
@@ -15,10 +16,10 @@ import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.List; import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
@@ -30,6 +31,12 @@ import static org.mockito.Mockito.when;
class PermissionMenuControllerTest { class PermissionMenuControllerTest {
/**
* 归属判据的返回值替身:与测试里传进去的 {@code 7L} 不同,这样"下游收到的是判据的结果"
* 这一条才有内容——若控制器仍传原文,verify 会拿 7L 与 99L 对不上而红。
*/
private static final Long RESOLVED_COMPANY = 99L;
@Test @Test
void effectivePermissionEndpointAllowsAuthenticatedNormalUserToReadSelf() { void effectivePermissionEndpointAllowsAuthenticatedNormalUserToReadSelf() {
AdminAuthSupport authSupport = mock(AdminAuthSupport.class); AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
@@ -125,12 +132,16 @@ class PermissionMenuControllerTest {
when(request.getHeader("X-Internal-Token")).thenReturn("shared-token"); when(request.getHeader("X-Internal-Token")).thenReturn("shared-token");
when(request.getParameter("operatorId")).thenReturn("12"); when(request.getParameter("operatorId")).thenReturn("12");
when(service.requireAdminOperator(12L)).thenReturn(operator); when(service.requireAdminOperator(12L)).thenReturn(operator);
when(service.list(operator, "app", false)).thenReturn(List.of()); // 归属判据给什么,下游就查什么:这里故意返回与入参 7L 不同的 99L,
// 于是"控制器把 tab 原文往下传"和"控制器把判据的结果往下传"两种写法给不出同一个绿。
when(service.resolveScopeCompanyId(operator, 7L)).thenReturn(RESOLVED_COMPANY);
when(service.list(operator, "app", false, RESOLVED_COMPANY)).thenReturn(List.of());
controller.listMenus(request, "app", false); controller.listMenus(request, "app", false, 7L);
verify(service).requireAdminOperator(12L); verify(service).requireAdminOperator(12L);
verify(service).list(operator, "app", false); verify(service).resolveScopeCompanyId(operator, 7L);
verify(service).list(operator, "app", false, RESOLVED_COMPANY);
verify(request, never()).getParameter("superAdmin"); verify(request, never()).getParameter("superAdmin");
} }
@@ -146,10 +157,11 @@ class PermissionMenuControllerTest {
when(authSupport.requireAdmin(request)).thenThrow(authFailure); when(authSupport.requireAdmin(request)).thenThrow(authFailure);
when(request.getHeader("X-Internal-Token")).thenReturn("wrong-token"); when(request.getHeader("X-Internal-Token")).thenReturn("wrong-token");
assertThatThrownBy(() -> controller.listMenus(request, "app", false)) assertThatThrownBy(() -> controller.listMenus(request, "app", false, 7L))
.isSameAs(authFailure); .isSameAs(authFailure);
verify(service, never()).requireAdminOperator(anyLong()); verify(service, never()).requireAdminOperator(anyLong());
verify(service, never()).list(any(AdminUserEntity.class), eq("app"), eq(false)); // 只 verify 某一组形参的 never() 会随控制器换签名一起失效,这里要的是「一次服务调用都没发生」。
verifyNoInteractions(service);
} }
@Test @Test
@@ -167,17 +179,20 @@ class PermissionMenuControllerTest {
body.setUserIds(List.of(20L)); body.setUserIds(List.of(20L));
when(authSupport.requireAdmin(request)).thenReturn(operator); when(authSupport.requireAdmin(request)).thenReturn(operator);
when(service.listImageVideoDataPermissionUsers(operator)).thenReturn(List.of(permissionUser)); when(service.resolveScopeCompanyId(operator, 7L)).thenReturn(RESOLVED_COMPANY);
when(service.updateImageVideoDataPermissionUsers(operator, List.of(20L))).thenReturn(1); when(service.listImageVideoDataPermissionUsers(operator, RESOLVED_COMPANY)).thenReturn(List.of(permissionUser));
when(service.updateImageVideoDataPermissionUsers(operator, RESOLVED_COMPANY, List.of(20L))).thenReturn(1);
var listResponse = controller.listImageVideoDataPermissionUsers(request); var listResponse = controller.listImageVideoDataPermissionUsers(request, 7L);
var updateResponse = controller.updateImageVideoDataPermissionUsers(request, body); var updateResponse = controller.updateImageVideoDataPermissionUsers(request, 7L, body);
assertThat(listResponse.getData()).containsExactly(permissionUser); assertThat(listResponse.getData()).containsExactly(permissionUser);
assertThat(updateResponse.getData()).isEqualTo(1); assertThat(updateResponse.getData()).isEqualTo(1);
verify(authSupport, times(2)).requireAdmin(request); verify(authSupport, times(2)).requireAdmin(request);
verify(service).listImageVideoDataPermissionUsers(operator); // 两页数据范围授权本批只做到后端:读与写都先过判据、再按判据那一家取数(界面还没接 tab)。
verify(service).updateImageVideoDataPermissionUsers(operator, List.of(20L)); verify(service, times(2)).resolveScopeCompanyId(operator, 7L);
verify(service).listImageVideoDataPermissionUsers(operator, RESOLVED_COMPANY);
verify(service).updateImageVideoDataPermissionUsers(operator, RESOLVED_COMPANY, List.of(20L));
} }
@Test @Test
@@ -195,16 +210,73 @@ class PermissionMenuControllerTest {
body.setUserIds(List.of(20L)); body.setUserIds(List.of(20L));
when(authSupport.requireAdmin(request)).thenReturn(operator); when(authSupport.requireAdmin(request)).thenReturn(operator);
when(service.listShopDataCrawlDataPermissionUsers(operator)).thenReturn(List.of(permissionUser)); when(service.resolveScopeCompanyId(operator, 7L)).thenReturn(RESOLVED_COMPANY);
when(service.updateShopDataCrawlDataPermissionUsers(operator, List.of(20L))).thenReturn(1); when(service.listShopDataCrawlDataPermissionUsers(operator, RESOLVED_COMPANY)).thenReturn(List.of(permissionUser));
when(service.updateShopDataCrawlDataPermissionUsers(operator, RESOLVED_COMPANY, List.of(20L))).thenReturn(1);
var listResponse = controller.listShopDataCrawlDataPermissionUsers(request); var listResponse = controller.listShopDataCrawlDataPermissionUsers(request, 7L);
var updateResponse = controller.updateShopDataCrawlDataPermissionUsers(request, body); var updateResponse = controller.updateShopDataCrawlDataPermissionUsers(request, 7L, body);
assertThat(listResponse.getData()).containsExactly(permissionUser); assertThat(listResponse.getData()).containsExactly(permissionUser);
assertThat(updateResponse.getData()).isEqualTo(1); assertThat(updateResponse.getData()).isEqualTo(1);
verify(authSupport, times(2)).requireAdmin(request); verify(authSupport, times(2)).requireAdmin(request);
verify(service).listShopDataCrawlDataPermissionUsers(operator); verify(service, times(2)).resolveScopeCompanyId(operator, 7L);
verify(service).updateShopDataCrawlDataPermissionUsers(operator, List.of(20L)); verify(service).listShopDataCrawlDataPermissionUsers(operator, RESOLVED_COMPANY);
verify(service).updateShopDataCrawlDataPermissionUsers(operator, RESOLVED_COMPANY, List.of(20L));
}
/**
* {@code company_id} 必须先交给归属判据、再由判据的结果决定建到哪家:控制器自己兜一个默认公司,
* 等于把「站超管指定别家」这条需求做成假的,而且缺省值会在前端没带参数时静默变成「只看公司 1」。
*/
@Test
void createMenuForwardsCompanyIdAndReorderForwardsOperator() {
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService service = mock(PermissionMenuService.class);
HttpServletRequest request = mock(HttpServletRequest.class);
PermissionMenuController controller = new PermissionMenuController(authSupport, service);
AdminUserEntity operator = new AdminUserEntity();
operator.setId(1L);
operator.setRole("super_admin");
operator.setCompanyId(7L);
PermissionMenuCreateRequest createRequest = new PermissionMenuCreateRequest();
when(authSupport.requireAdmin(request)).thenReturn(operator);
when(service.resolveScopeCompanyId(operator, 7L)).thenReturn(RESOLVED_COMPANY);
controller.createMenu(request, createRequest, 7L);
controller.reorderColumns(request, Map.of("ordered_ids", List.of(2L, 1L)));
verify(service).resolveScopeCompanyId(operator, 7L);
verify(service).create(operator, RESOLVED_COMPANY, createRequest);
// 排序原先只有 ids 没有操作者,公司闸门就无处可查;换签名后必须确认操作者真到了 service。
verify(service).reorder(operator, List.of(2L, 1L));
}
/**
* 前端没带 {@code company_id} 时,控制器把 {@code null} 原样交给判据,自己一个字都不编:
* "那一家到底是哪家"由 {@code resolveScopeCompanyId} 定(非超管=本公司,超管=本公司那棵树),
* 下游拿到的是它的返回值而不是 {@code null},这样"缺省到底查了哪家"在两条断言里都留得下痕迹。
*/
@Test
void absentCompanyIdGoesToTheScopeDoorInsteadOfAnInventedDefault() {
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService service = mock(PermissionMenuService.class);
HttpServletRequest request = mock(HttpServletRequest.class);
PermissionMenuController controller = new PermissionMenuController(authSupport, service);
AdminUserEntity operator = new AdminUserEntity();
operator.setId(1L);
operator.setRole("admin");
operator.setCompanyId(7L);
when(authSupport.requireAdmin(request)).thenReturn(operator);
when(service.resolveScopeCompanyId(operator, null)).thenReturn(7L);
controller.listMenus(request, "admin", false, null);
controller.listImageVideoDataPermissionUsers(request, null);
controller.listShopDataCrawlDataPermissionUsers(request, null);
verify(service, times(3)).resolveScopeCompanyId(operator, null);
verify(service).list(operator, "admin", false, 7L);
verify(service).listImageVideoDataPermissionUsers(operator, 7L);
verify(service).listShopDataCrawlDataPermissionUsers(operator, 7L);
} }
} }
@@ -0,0 +1,536 @@
package com.nanri.aiimage.modules.permission.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.permission.mapper.PermissionMenuMapper;
import com.nanri.aiimage.modules.permission.mapper.UserColumnPermissionMapper;
import com.nanri.aiimage.modules.permission.model.dto.PermissionMenuCreateRequest;
import com.nanri.aiimage.modules.permission.model.dto.PermissionMenuUpdateRequest;
import com.nanri.aiimage.modules.permission.model.dto.UserColumnPermissionUpdateRequest;
import com.nanri.aiimage.modules.permission.model.entity.PermissionMenuEntity;
import com.nanri.aiimage.modules.permission.model.entity.UserColumnPermissionEntity;
import com.nanri.aiimage.modules.permission.model.vo.ImageVideoDataPermissionUserVo;
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.stubbing.Answer;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* V149「每家公司一套菜单树」之后的归属判定(设计文档 §5、定案 D1/D2/D3)。
*
* <p>这些用例的共同写法是<b>让 mock 装作一间真库</b>:带了 {@code company_id} 条件就只回本公司的行,
* 没带就把别家那行也交出来。于是"少写一个公司条件"不会表现为一行代码没被覆盖,而表现为
* 返回值里冒出别家的 id —— 断言打在结果上,而不是打在"源码里有没有那一句"上。</p>
*
* <p>为什么值得这么绕:这一族的失效全是静默的。按 key 点查少一个条件就是 {@code LIMIT 1}
* 跨公司借位(页面显示已授权、账号永远拿不到那份权限);读侧不收窄就是两家的同名菜单混进同一个
* 响应(前端按 key 建树直接长错形)。两者都不抛异常、都不进巡检。</p>
*/
class PermissionMenuServiceCompanyScopeTest {
private static final long COMPANY_A = 1L;
private static final long COMPANY_B = 2L;
private static final Set<Object> KNOWN_COMPANIES = Set.of(COMPANY_A, COMPANY_B);
private static final String IMAGE_VIDEO_KEY = "admin_image_video_task_data";
private PermissionMenuMapper menuMapper;
private UserColumnPermissionMapper permissionMapper;
private AdminUserMapper userMapper;
private PermissionMenuService service;
/** lambda 条件要渲染成 SQL 才往 paramNameValuePairs 落值,而渲染依赖 TableInfo 缓存。 */
@BeforeAll
static void initMybatisPlusTableInfo() {
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
TableInfoHelper.initTableInfo(assistant, PermissionMenuEntity.class);
TableInfoHelper.initTableInfo(assistant, AdminUserEntity.class);
}
@BeforeEach
void setUp() {
menuMapper = mock(PermissionMenuMapper.class);
permissionMapper = mock(UserColumnPermissionMapper.class);
userMapper = mock(AdminUserMapper.class);
service = new PermissionMenuService(menuMapper, permissionMapper, userMapper);
}
// --------------------------------------------------------------- 夹具
private static PermissionMenuEntity menu(long id, long companyId, String columnKey,
String menuType, Long parentId, int sortOrder) {
PermissionMenuEntity entity = new PermissionMenuEntity();
entity.setId(id);
entity.setCompanyId(companyId);
entity.setName(columnKey);
entity.setColumnKey(columnKey);
entity.setMenuType(menuType);
entity.setRoutePath("/" + columnKey);
entity.setParentId(parentId);
entity.setSortOrder(sortOrder);
return entity;
}
private static AdminUserEntity user(long id, String role, Long companyId) {
AdminUserEntity entity = new AdminUserEntity();
entity.setId(id);
entity.setUsername("u" + id);
entity.setRole(role);
entity.setCompanyId(companyId);
return entity;
}
private static UserColumnPermissionEntity grant(long userId, long columnId) {
UserColumnPermissionEntity entity = new UserColumnPermissionEntity();
entity.setUserId(userId);
entity.setColumnId(columnId);
return entity;
}
/** 先摸一次 getSqlSegment():MP 只在条件渲染时把值写进 paramNameValuePairs。 */
private static List<Object> params(LambdaQueryWrapper<?> query) {
assertThat(query.getSqlSegment()).isNotNull();
return new ArrayList<>(query.getParamNameValuePairs().values());
}
private static List<Object> params(LambdaUpdateWrapper<?> update) {
assertThat(update.getSqlSegment()).isNotNull();
return new ArrayList<>(update.getParamNameValuePairs().values());
}
/** 这条查询有没有按公司筛过——用"参数里出现了任一已知公司 id"来读,不认列名字符串。 */
private static boolean filteredByAnyCompany(LambdaQueryWrapper<?> query) {
return params(query).stream().anyMatch(KNOWN_COMPANIES::contains);
}
/**
* 一间真库:带公司条件只回那一家,不带就把两家都回出来(=借位)。
* 用例因此同时咬得住"条件漏了"(结果多出别家)与"条件写死了别家"(结果少了本该有的)。
*/
private static List<PermissionMenuEntity> fakeDbRows(List<PermissionMenuEntity> all,
LambdaQueryWrapper<PermissionMenuEntity> query) {
if (!filteredByAnyCompany(query)) {
return new ArrayList<>(all);
}
List<Object> values = params(query);
List<PermissionMenuEntity> hits = new ArrayList<>();
for (PermissionMenuEntity row : all) {
if (values.contains(row.getCompanyId())) {
hits.add(row);
}
}
return hits;
}
private static Answer<List<PermissionMenuEntity>> menusFromFakeDb(List<PermissionMenuEntity> all) {
return invocation -> fakeDbRows(all, invocation.getArgument(0));
}
/** 账号侧同一间真库:{@code grantableUserQuery} 少了公司条件就会把别家的人一起列进来。 */
private static List<AdminUserEntity> fakeDbUsers(List<AdminUserEntity> all,
LambdaQueryWrapper<AdminUserEntity> query) {
if (!filteredByAnyCompany(query)) {
return new ArrayList<>(all);
}
List<Object> values = params(query);
List<AdminUserEntity> hits = new ArrayList<>();
for (AdminUserEntity row : all) {
if (values.contains(row.getCompanyId())) {
hits.add(row);
}
}
return hits;
}
/**
* 两家公司各有一套同名 key 的树(A 家 id 个位/十位、B 家 id 1xx),
* 外加一条只在 A 家存在的角色内在闸门行 {@code admin_companies}。
*/
private List<PermissionMenuEntity> twoTrees() {
return new ArrayList<>(List.of(
menu(9, COMPANY_A, "admin_group_data", "admin", null, 5),
menu(10, COMPANY_A, "collect-data", "admin", 9L, 10),
menu(109, COMPANY_A, "admin_companies", "admin", null, 200),
menu(111, COMPANY_B, "admin_group_data", "admin", null, 5),
menu(110, COMPANY_B, "collect-data", "admin", 111L, 10)));
}
// ------------------------------------------------------------------ 用例
@Test
@DisplayName("非超管取菜单目录时,每一次取数都带他自己那一家")
void everyMenuQueryCarriesTheOperatorsCompany() {
when(userMapper.selectById(20L)).thenReturn(user(20L, "admin", COMPANY_B));
when(permissionMapper.selectByUserId(20L)).thenReturn(List.of());
when(menuMapper.selectList(any())).thenReturn(List.of());
service.list(user(20L, "admin", COMPANY_B), "admin", false);
ArgumentCaptor<LambdaQueryWrapper<PermissionMenuEntity>> captor =
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
// 目录取数 + 可授予集合展开,两次都必须带公司;少任一次=别家的行混进同一个响应。
verify(menuMapper, atLeast(2)).selectList(captor.capture());
for (LambdaQueryWrapper<PermissionMenuEntity> query : captor.getAllValues()) {
assertThat(params(query)).contains(COMPANY_B);
}
}
@Test
@DisplayName("定案 D2:站点超管可以指定任意一家,非超管指定别家一律 403 且不落到任何查询")
void onlyTheSiteSuperAdminMayCrossCompanies() {
when(menuMapper.selectList(any())).thenReturn(List.of());
service.list(user(1L, "super_admin", COMPANY_A), "admin", false, COMPANY_B);
ArgumentCaptor<LambdaQueryWrapper<PermissionMenuEntity>> captor =
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(menuMapper).selectList(captor.capture());
assertThat(params(captor.getValue())).contains(COMPANY_B);
clearInvocations(menuMapper);
assertThatThrownBy(() -> service.list(user(20L, "admin", COMPANY_B), "admin", false, COMPANY_A))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("其他公司");
verify(menuMapper, never()).selectList(any());
}
@Test
@DisplayName("company_id 传 0 或负数是在查询之前就拒掉,不是拿去点查一轮")
void nonPositiveCompanyIdIsRejectedBeforeAnyQuery() {
assertThatThrownBy(() -> service.list(user(1L, "super_admin", COMPANY_A), "admin", false, 0L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("company_id 无效");
assertThatThrownBy(() -> service.list(user(1L, "super_admin", COMPANY_A), "admin", false, -3L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("company_id 无效");
verify(menuMapper, never()).selectList(any());
}
@Test
@DisplayName("内部数据权限行与可授权用户列表必须解析到同一家:少一个条件就把别家的人列进来")
void dataPermissionLookupAndUserListResolveToTheSameCompany() {
List<PermissionMenuEntity> all = List.of(
menu(75, COMPANY_A, IMAGE_VIDEO_KEY, "admin", null, 10),
menu(975, COMPANY_B, IMAGE_VIDEO_KEY, "admin", null, 10));
// selectOne 同真库:带公司条件命中本公司行;漏条件就 LIMIT 1 借位到 A 家那行。
when(menuMapper.selectOne(any())).thenAnswer(invocation ->
fakeDbRows(all, (LambdaQueryWrapper<PermissionMenuEntity>) invocation.getArgument(0)).get(0));
when(permissionMapper.selectByColumnId(75L)).thenReturn(List.of(grant(300L, 75L)));
when(permissionMapper.selectByColumnId(975L)).thenReturn(List.of(grant(400L, 975L)));
when(userMapper.selectList(any())).thenAnswer(invocation -> fakeDbUsers(
List.of(user(300L, "admin", COMPANY_A), user(400L, "admin", COMPANY_B)),
invocation.getArgument(0)));
List<ImageVideoDataPermissionUserVo> visible =
service.listImageVideoDataPermissionUsers(user(1L, "super_admin", COMPANY_B));
assertThat(visible).extracting(ImageVideoDataPermissionUserVo::getId).containsExactly(400L);
assertThat(visible).extracting(ImageVideoDataPermissionUserVo::isGranted).containsExactly(true);
}
@Test
@DisplayName("跨公司挂父被拒:外键只保证父行存在,挡不住挂到别家的分组上")
void crossCompanyParentIsRejected() {
PermissionMenuCreateRequest request = new PermissionMenuCreateRequest();
request.setName("新页面");
request.setColumnKey("brand-new");
request.setMenuType("admin");
request.setRoutePath("/brand-new");
request.setParentId(9L);
when(menuMapper.selectById(9L)).thenReturn(menu(9, COMPANY_A, "admin_group_data", "admin", null, 5));
assertThatThrownBy(() -> service.create(user(20L, "admin", COMPANY_B), null, request))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("同一公司");
verify(menuMapper, never()).insert(any(PermissionMenuEntity.class));
}
@Test
@DisplayName("整条祖先链都要同一家:父是同公司、上面挂着别家的分组也一样拒")
void crossCompanyAncestorIsRejected() {
PermissionMenuCreateRequest request = new PermissionMenuCreateRequest();
request.setName("新页面");
request.setColumnKey("brand-new");
request.setMenuType("admin");
request.setRoutePath("/brand-new");
request.setParentId(50L);
when(menuMapper.selectById(50L)).thenReturn(menu(50, COMPANY_B, "b-group", "admin", 9L, 5));
when(menuMapper.selectById(9L)).thenReturn(menu(9, COMPANY_A, "admin_group_data", "admin", null, 5));
assertThatThrownBy(() -> service.create(user(20L, "admin", COMPANY_B), null, request))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("同一公司");
verify(menuMapper, never()).insert(any(PermissionMenuEntity.class));
}
@Test
@DisplayName("同名 key 在别家已存在不算重复:查重范围=本公司(与 uk_company_column_key 同一条键)")
void sameColumnKeyInAnotherCompanyDoesNotBlockMyCreate() {
when(menuMapper.selectOne(any())).thenAnswer(invocation -> {
LambdaQueryWrapper<PermissionMenuEntity> query = invocation.getArgument(0);
// 带公司条件:B 家没有 collect-data ⇒ null;漏了条件:A 家那行就成"重复"。
return params(query).contains(COMPANY_B)
? null
: menu(10, COMPANY_A, "collect-data", "admin", 9L, 10);
});
when(menuMapper.insert(any(PermissionMenuEntity.class))).thenAnswer(invocation -> {
invocation.getArgument(0, PermissionMenuEntity.class).setId(777L);
return 1;
});
when(menuMapper.selectById(777L)).thenReturn(menu(777, COMPANY_B, "collect-data", "admin", null, 11));
PermissionMenuCreateRequest request = new PermissionMenuCreateRequest();
request.setName("德阳的采集页");
request.setColumnKey("collect-data");
request.setMenuType("admin");
request.setRoutePath("/collect-data");
request.setSortOrder(11);
assertThat(service.create(user(20L, "admin", COMPANY_B), null, request).getId()).isEqualTo(777L);
ArgumentCaptor<PermissionMenuEntity> captor = ArgumentCaptor.forClass(PermissionMenuEntity.class);
verify(menuMapper).insert(captor.capture());
assertThat(captor.getValue().getCompanyId()).isEqualTo(COMPANY_B);
assertThat(captor.getValue().getColumnKey()).isEqualTo("collect-data");
}
@Test
@DisplayName("改/删/排别家的菜单一律 403,而且改之前就被拒,不会先读后写地留痕")
void writesToAnotherCompanysMenuAreForbidden() {
when(menuMapper.selectById(10L)).thenReturn(menu(10, COMPANY_A, "collect-data", "admin", 9L, 10));
PermissionMenuUpdateRequest update = new PermissionMenuUpdateRequest();
update.setName("改名");
update.setColumnKey("collect-data");
update.setMenuType("admin");
update.setRoutePath("/collect-data");
assertThatThrownBy(() -> service.update(user(20L, "admin", COMPANY_B), 10L, update))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("其他公司");
assertThatThrownBy(() -> service.delete(user(20L, "admin", COMPANY_B), 10L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("其他公司");
assertThatThrownBy(() -> service.reorder(user(20L, "admin", COMPANY_B), List.of(10L, 11L)))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("其他公司");
verify(menuMapper, never()).updateById(any(PermissionMenuEntity.class));
verify(menuMapper, never()).deleteById(anyLong());
verify(permissionMapper, never()).deleteByColumnId(any());
}
@Test
@DisplayName("同级重排的兄弟集按锚点行的公司筛:少了它会把两棵树的 sort_order 织在一起")
void reorderSiblingsAreCompanyScoped() {
// 锚点 111 属 B 家;A 家有一排同名兄弟(id 210/211、分组 212)——漏了公司条件就会一起进 siblings。
when(menuMapper.selectById(111L)).thenReturn(menu(111, COMPANY_B, "brand-check", "admin", 112L, 40));
when(menuMapper.selectList(any())).thenAnswer(menusFromFakeDb(List.of(
menu(110, COMPANY_B, "collect-data", "admin", 112L, 30),
menu(111, COMPANY_B, "brand-check", "admin", 112L, 40),
menu(210, COMPANY_A, "collect-data", "admin", 212L, 10),
menu(211, COMPANY_A, "brand-check", "admin", 212L, 20))));
service.reorder(user(20L, "admin", COMPANY_B), List.of(111L, 110L));
ArgumentCaptor<LambdaQueryWrapper<PermissionMenuEntity>> siblings =
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(menuMapper).selectList(siblings.capture());
assertThat(params(siblings.getValue())).contains(COMPANY_B);
// 交换 B 家这两行的顺序必然产生两次写入;关键是写入的 id 只能是 B 家那两个。
ArgumentCaptor<LambdaUpdateWrapper<PermissionMenuEntity>> updates =
ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(menuMapper, times(2)).update(nullable(PermissionMenuEntity.class), updates.capture());
for (LambdaUpdateWrapper<PermissionMenuEntity> update : updates.getAllValues()) {
assertThat(params(update)).containsAnyOf(110L, 111L);
assertThat(params(update)).doesNotContain(210L, 211L);
}
}
@Test
@DisplayName("给用户提交的授权 id 必须在【该用户自己】的树里:别家的行 id 报无效,不落库")
void grantIsBoundToTheTargetUsersOwnTree() {
when(userMapper.selectById(400L)).thenReturn(user(400L, "normal", COMPANY_B));
// A 家的 id 10 与 B 家的 id 110:本公司只认后者 ⇒ 带公司条件 count=1,漏条件 count=2。
when(menuMapper.selectCount(any())).thenAnswer(invocation ->
params((LambdaQueryWrapper<PermissionMenuEntity>) invocation.getArgument(0))
.contains(COMPANY_B) ? 1L : 2L);
when(menuMapper.selectList(any())).thenReturn(List.of());
UserColumnPermissionUpdateRequest request = new UserColumnPermissionUpdateRequest();
request.setColumnIds(List.of(10L, 110L));
assertThatThrownBy(() -> service.updateUserColumnPermissions(
user(1L, "super_admin", COMPANY_A), 400L, request, null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("无效的菜单权限项");
verify(permissionMapper, never()).insert(any(UserColumnPermissionEntity.class));
verify(permissionMapper, never()).deleteByUserId(anyLong());
}
@Test
@DisplayName("回填集与有效菜单都只认目标账号那棵树:挂在别家行上的旧授权不复活")
void effectiveMenusOnlyComeFromTheUsersOwnTree() {
when(userMapper.selectById(400L)).thenReturn(user(400L, "normal", COMPANY_B));
when(permissionMapper.selectByUserId(400L)).thenReturn(List.of(grant(400L, 10L)));
when(menuMapper.selectList(any())).thenAnswer(menusFromFakeDb(twoTrees()));
assertThat(service.getUserColumnPermissions(user(1L, "super_admin", COMPANY_A), 400L, "admin"))
.isEmpty();
assertThat(service.getUserColumnIds(user(1L, "super_admin", COMPANY_A), 400L, "admin").getColumnIds())
.isEmpty();
// 同一个人换成 A 家的账号,同一笔授权就该生效——证明上面那两条空是因为公司,不是因为查不到行。
when(userMapper.selectById(400L)).thenReturn(user(400L, "normal", COMPANY_A));
assertThat(service.getUserColumnPermissions(user(1L, "super_admin", COMPANY_A), 400L, "admin"))
.extracting(PermissionMenuItemVo::getId).containsExactly(10L);
}
@Test
@DisplayName("权限判定遇到别家的 column_id 判「无权限」,方向是拒不是放")
void hasEffectiveColumnPermissionDeniesForeignColumnId() {
when(userMapper.selectById(400L)).thenReturn(user(400L, "normal", COMPANY_B));
when(menuMapper.selectById(10L)).thenReturn(menu(10, COMPANY_A, "collect-data", "admin", 9L, 10));
when(permissionMapper.selectByUserId(400L)).thenReturn(List.of(grant(400L, 10L)));
assertThat(service.hasEffectiveColumnPermission(400L, 10L)).isFalse();
// 拒在展开之前:一条目录查询都不该发生。
verify(menuMapper, never()).selectList(any());
}
@Test
@DisplayName("建树:三种 menu_type 全复制、闸门行不复制、父子指向按 key 落到本公司新行")
void copyTreeClonesEveryTypeAndRemapsParentsByKey() {
List<PermissionMenuEntity> template = new ArrayList<>(List.of(
menu(1, COMPANY_A, "app-collect", "app", null, 10),
menu(2, COMPANY_A, "app-child", "app", 1L, 20),
menu(3, COMPANY_A, "admin-group", "admin", null, 30),
menu(4, COMPANY_A, "admin-page", "admin", 3L, 40),
menu(5, COMPANY_A, "internal-thing", "internal", null, 50),
menu(109, COMPANY_A, "admin_companies", "admin", null, 60)));
List<PermissionMenuEntity> created = new ArrayList<>();
when(menuMapper.selectList(any())).thenAnswer(invocation -> {
LambdaQueryWrapper<PermissionMenuEntity> query = invocation.getArgument(0);
return params(query).contains(COMPANY_B)
? new ArrayList<>(created) : new ArrayList<>(template);
});
when(menuMapper.insert(any(PermissionMenuEntity.class))).thenAnswer(invocation -> {
PermissionMenuEntity row = invocation.getArgument(0);
row.setId(500L + created.size());
created.add(row);
return 1;
});
int inserted = service.copyTreeFromTemplate(COMPANY_B, COMPANY_A);
assertThat(inserted).isEqualTo(5);
assertThat(created).extracting(PermissionMenuEntity::getColumnKey)
.doesNotContain("admin_companies")
.containsExactlyInAnyOrder("app-collect", "app-child", "admin-group", "admin-page", "internal-thing");
assertThat(created).allSatisfy(row -> {
assertThat(row.getCompanyId()).isEqualTo(COMPANY_B);
assertThat(row.getMenuType()).isIn("app", "admin", "internal");
});
// 第二趟认父:父指向必须落在本公司新行上,绝不能是模板那排的全局 id。
Set<Long> copyIds = new LinkedHashSet<>();
created.forEach(row -> copyIds.add(row.getId()));
PermissionMenuEntity child = created.stream()
.filter(row -> "app-child".equals(row.getColumnKey())).findFirst().orElseThrow();
PermissionMenuEntity group = created.stream()
.filter(row -> "app-collect".equals(row.getColumnKey())).findFirst().orElseThrow();
assertThat(child.getParentId()).isEqualTo(group.getId());
assertThat(copyIds).contains(child.getParentId());
assertThat(child.getParentId()).isNotEqualTo(1L);
}
@Test
@DisplayName("建树可重跑:目标公司已有的 key 原样保留,第二次一行都不插")
void copyTreeIsIdempotentOnRerun() {
List<PermissionMenuEntity> template = new ArrayList<>(List.of(
menu(1, COMPANY_A, "app-collect", "app", null, 10),
menu(3, COMPANY_A, "admin-group", "admin", null, 30)));
List<PermissionMenuEntity> existing = new ArrayList<>(List.of(
menu(900, COMPANY_B, "app-collect", "app", null, 10),
menu(901, COMPANY_B, "admin-group", "admin", null, 30)));
when(menuMapper.selectList(any())).thenAnswer(invocation -> {
LambdaQueryWrapper<PermissionMenuEntity> query = invocation.getArgument(0);
return params(query).contains(COMPANY_B)
? new ArrayList<>(existing) : new ArrayList<>(template);
});
assertThat(service.copyTreeFromTemplate(COMPANY_B, COMPANY_A)).isZero();
verify(menuMapper, never()).insert(any(PermissionMenuEntity.class));
verify(menuMapper, never()).update(any(), any());
}
@Test
@DisplayName("建树不许靠默认值兜:模板公司缺失或操作者没归属都直接拒")
void copyTreeRefusesInsteadOfInventingADefaultCompany() {
when(menuMapper.selectList(any())).thenReturn(List.of());
assertThatThrownBy(() -> service.copyTreeFromTemplate(COMPANY_B, COMPANY_A))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("没有可复制的菜单树");
assertThatThrownBy(() -> service.copyTreeFromTemplate(COMPANY_B, null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("没有所属公司");
assertThatThrownBy(() -> service.copyTreeFromTemplate(null, COMPANY_A))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("目标公司");
verify(menuMapper, never()).insert(any(PermissionMenuEntity.class));
// 给"自己"复制是条无意义的写入:早返回 0,一条查询都不发。
clearInvocations(menuMapper);
assertThat(service.copyTreeFromTemplate(COMPANY_A, COMPANY_A)).isZero();
verify(menuMapper, never()).selectList(any());
}
@Test
@DisplayName("判据要能咬住实现:不带公司条件时,夹具必须把别家的行也交出来")
void fakeDatabaseStubActuallyBites() {
// 自证尺子不是恒绿的:这些用例全部依赖「少一个 .eq(companyId) ⇒ 结果多出别家行」这个性质。
// 若夹具改成无脑只回本公司,上面那批断言就一条都咬不动了。
List<PermissionMenuEntity> all = twoTrees();
LambdaQueryWrapper<PermissionMenuEntity> withoutCompany =
new LambdaQueryWrapper<PermissionMenuEntity>().orderByAsc(PermissionMenuEntity::getSortOrder);
assertThat(filteredByAnyCompany(withoutCompany)).isFalse();
assertThat(fakeDbRows(all, withoutCompany)).extracting(PermissionMenuEntity::getId)
.contains(10L, 110L);
LambdaQueryWrapper<PermissionMenuEntity> withCompany =
new LambdaQueryWrapper<PermissionMenuEntity>().eq(PermissionMenuEntity::getCompanyId, COMPANY_B);
assertThat(filteredByAnyCompany(withCompany)).isTrue();
assertThat(fakeDbRows(all, withCompany)).extracting(PermissionMenuEntity::getId)
.containsExactlyInAnyOrder(110L, 111L)
.doesNotContain(10L, 109L);
}
}
@@ -1,158 +0,0 @@
package com.nanri.aiimage.modules.productcategory.controller;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.productcategory.model.dto.ProductCategorySaveRequest;
import com.nanri.aiimage.modules.productcategory.service.ProductCategoryService;
import jakarta.servlet.http.HttpServletRequest;
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 org.springframework.mock.web.MockHttpServletRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* 「商品类目」controller 的正门接线(护栏 G2 断言 A 要求这些调用内联在 handler 块里,
* 本文件钉的是内联之后的<b>语义</b>:tab 的值确实进了出口、出口的结果确实交给了 service)。
*
* <p>G2 只看形状(有没有调、结果有没有被当实参用),看不见"把 service 那侧的实参改成 null"
* 这一记 —— 那一记由本文件的 {@code verify(service).list("面霜", 2L)} 负责。</p>
*/
@ExtendWith(MockitoExtension.class)
class ProductCategoryControllerCompanyScopeTest {
private static final Long OPERATOR_ID = 1L;
private static final Long COMPANY_ID = 2L;
@Mock
private ProductCategoryService productCategoryService;
@Mock
private AdminAuthSupport adminAuthSupport;
@Mock
private DataReadScope dataReadScope;
private ProductCategoryController controller() {
return new ProductCategoryController(productCategoryService, adminAuthSupport, dataReadScope);
}
@Test
@DisplayName("列表:tab 的公司 id 交给 readCompanyIdOrOwn,出口给什么 service 就用什么")
void listPassesTheTabValueThroughTheDoor() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(COMPANY_ID);
controller().list(request, "面霜", COMPANY_ID);
verify(dataReadScope).readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID));
verify(productCategoryService).list("面霜", COMPANY_ID);
}
@Test
@DisplayName("列表:非超管由出口判成\"不筛\",controller 不许自己补一个公司 id 进去")
void listUsesTheDoorsVerdictForNonSuperAdmin() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(null);
controller().list(request, "面霜", COMPANY_ID);
verify(productCategoryService).list("面霜", null);
}
@Test
@DisplayName("children / search / export 三支同样走出口,漏一支就是那一处的 tab 仍是装饰")
void everyReadEndpointGoesThroughTheDoor() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(COMPANY_ID);
// export 的返回要真喂给 ResponseEntity.contentLength(bytes.length):mock 给 null 会 NPE 在断言之前的装配里。
when(productCategoryService.export("面霜", COMPANY_ID)).thenReturn(new byte[0]);
ProductCategoryController controller = controller();
controller.children(request, 10L, 1L, 20L, COMPANY_ID);
controller.search(request, "面霜", 1L, 20L, COMPANY_ID);
controller.export(request, "面霜", COMPANY_ID);
verify(productCategoryService).children(10L, 1L, 20L, COMPANY_ID);
verify(productCategoryService).search("面霜", 1L, 20L, COMPANY_ID);
verify(productCategoryService).export("面霜", COMPANY_ID);
verify(dataReadScope, times(3))
.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID));
}
/** 写侧口径(一期定案):归属由后端从操作者会话推导,请求体不带 company_id,controller 也不读 tab。 */
@Test
@DisplayName("新增:只把操作者 id 交给 service,公司由 service 从会话推导")
void createPassesOnlyTheOperator() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
ProductCategorySaveRequest body = new ProductCategorySaveRequest();
body.setName("面霜套装");
body.setParentId(10L);
controller().create(request, body);
ArgumentCaptor<Long> operatorId = ArgumentCaptor.forClass(Long.class);
verify(productCategoryService).create(eq(body), operatorId.capture());
assertEquals(OPERATOR_ID, operatorId.getValue());
verifyNoInteractions(dataReadScope);
}
/** 写侧闸门(10-06 逐节点复验后补):读侧已经收窄,写侧不收窄="藏起来的行照样能删"。 */
@Test
@DisplayName("更新/删除:把 writeCompanyId 的判定原样交给 service,controller 不自己补公司 id")
void writeEndpointsPassTheRowOwnershipGate() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
when(dataReadScope.writeCompanyId(any(AdminUserEntity.class))).thenReturn(COMPANY_ID);
ProductCategorySaveRequest body = new ProductCategorySaveRequest();
body.setName("面霜改名");
ProductCategoryController controller = controller();
controller.update(request, 300L, body);
controller.delete(request, 300L);
verify(productCategoryService).update(300L, body, COMPANY_ID);
verify(productCategoryService).delete(300L, COMPANY_ID);
}
/** 反向钉:闸门给 null(平台超管)时必须原样传 null——顺手补一个公司 id 会把超管锁死在本公司。 */
@Test
@DisplayName("更新:闸门判超管(null)时把 null 传下去,不补任何公司 id")
void writeGateKeepsTheSuperAdminVerdict() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
when(dataReadScope.writeCompanyId(any(AdminUserEntity.class))).thenReturn(null);
ProductCategorySaveRequest body = new ProductCategorySaveRequest();
body.setName("内置类目改名");
controller().update(request, 10L, body);
verify(productCategoryService).update(10L, body, null);
}
private MockHttpServletRequest login() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader("X-Internal-Token", "irrelevant-here");
return request;
}
private AdminUserEntity user() {
AdminUserEntity user = new AdminUserEntity();
user.setId(OPERATOR_ID);
user.setRole("super_admin");
return user;
}
}
@@ -4,8 +4,6 @@ import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper; import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.modules.productcategory.mapper.ProductCategoryMapper; import com.nanri.aiimage.modules.productcategory.mapper.ProductCategoryMapper;
import com.nanri.aiimage.modules.productcategory.model.dto.ProductCategorySaveRequest; import com.nanri.aiimage.modules.productcategory.model.dto.ProductCategorySaveRequest;
import com.nanri.aiimage.modules.productcategory.model.entity.ProductCategoryEntity; import com.nanri.aiimage.modules.productcategory.model.entity.ProductCategoryEntity;
@@ -20,16 +18,15 @@ import org.mockito.ArgumentCaptor;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.never; import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
@@ -37,32 +34,34 @@ import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** /**
* 「商品类目」按公司视图的那几条不变量(V147 / 需求 2026-10-05「切 tab 数据还一样」)。 * 「商品类目」这棵树的公司口径(控制方 2026-10-06 定案:全平台共享、不区分公司,
* 写侧同样是「谁都能改整棵树」)。
* *
* <p>这一页的归属是<b>物化列</b>而不是账号集合,所以判据形状与 readScope 那一族不同: * <p>类名里的 CompanyScope 是有意保留的:这一页确实按公司切过(V147 加列、V148 取消共享哨兵 0、
* 可见集 = {@code company_id IN (0, X)},其中 0 是内置节点的哨兵。两支最容易静默坏掉的形状 * 内置行归还第 1 家)。本文件现在钉的是<b>反向</b>不变量——四条读通路真正渲染出来的 SQL 里一个
* 都由本文件钉住:① 哨兵那半不许丢(丢了第 2 家是一棵空树,连自建根都挂不上); * {@code company_id} 都不许出现。原先那族「{@code company_id = 这一家}、不许带哨兵 0」的单值谓词钉子,
* ② 给 LLM 用的那棵全局树不许被顺手加上公司谓词(加了货源归类的候选就按公司分叉)。</p> * 以及跨公司 403、"公司账号改不动内置节点"那两道写侧闸门,随定案一起作废:现在没有归属值可比,
* 也没有"别人的行"这一说。</p>
*
* <p>为什么留 SQL 层的钉子,而不只靠源码文本扫描({@code CompanyIdParamGoesThroughReadScopeTest}
* 已按 module 目录反向钉过一遍):那把尺子读的是 Java 源码里的公司 token,谓词若来自这两个文件之外
* (mapper XML、公共分页/租户拦截器)它看不见;这里读的是 MyBatis-Plus 真正拼出来的那一段。</p>
*/ */
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
class ProductCategoryCompanyScopeTest { class ProductCategoryCompanyScopeTest {
private static final long BUILTIN = 0L; /** 原来的"内置根"在定案后只是同一棵树上的一个普通节点,不再带归属含义。 */
private static final Long OPERATOR_ID = 7L; private static final Long PARENT_ID = 10L;
/** 故意取 2:DEFAULT 1 那一家通不过"值等于会话公司"这种断言,取 2 才钉得住"真从会话推导"。 */
private static final Long COMPANY_ID = 2L;
private static final Long BUILTIN_PARENT_ID = 10L;
@Mock @Mock
private ProductCategoryMapper productCategoryMapper; private ProductCategoryMapper productCategoryMapper;
@Mock
private CompanyScopeSupport companyScopeSupport;
private ProductCategoryService service; private ProductCategoryService service;
@BeforeAll @BeforeAll
static void initTableInfo() { static void initTableInfo() {
// Lambda 条件要解析列名,没有 TableInfo 时 getSqlSegment() 里根本不会出现 company_id。 // Lambda 条件要解析列名。没有 TableInfo 时 getSqlSegment() 里一个列名都不会出现,
// "不含 company_id"就变成恒真的空断言。
TableInfoHelper.initTableInfo( TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""), new MapperBuilderAssistant(new MybatisConfiguration(), ""),
ProductCategoryEntity.class); ProductCategoryEntity.class);
@@ -70,281 +69,112 @@ class ProductCategoryCompanyScopeTest {
@BeforeEach @BeforeEach
void setUp() { void setUp() {
service = new ProductCategoryService(productCategoryMapper, companyScopeSupport); service = new ProductCategoryService(productCategoryMapper);
}
@Test
@DisplayName("公司视图带哨兵 0:可见集是 (0, 该公司),只查自建会让第 2 家连自建根都挂不上")
void companyViewIncludesTheBuiltinSentinel() {
when(productCategoryMapper.selectList(any())).thenReturn(List.of(row(1L, null, "护肤品", BUILTIN)));
service.list(null, COMPANY_ID);
LambdaQueryWrapper<ProductCategoryEntity> query = capturedListWrapper();
assertTrue(query.getSqlSegment().contains("company_id IN"), query.getSqlSegment());
Map<String, Object> params = paramsOf(query);
assertTrue(params.containsValue(BUILTIN), "哨兵 0 必须留在可见集里:" + params);
assertTrue(params.containsValue(COMPANY_ID), "公司谓词丢了 tab 就是装饰:" + params);
} }
/** /**
* 反向钉(新维度不许顺手回流到别的通路):{@link ProductCategoryService#list()} 唯一的消费者是 * 四条读通路(全局树、带关键字的树、分页 children、搜索)逐条渲染后汇总比对。
* 货源/外观的类目归类({@code SimilarAsinLlmService} 读的是全局树)。给它加公司谓词会让同一个 * 三条锚(ORDER BY / parent_id / LIKE)先自证"确实扫到了真 SQL",否则末尾那条否证是空断言。
* "面霜"有 N 个 category_key、LLM 分类结果按公司分叉,那是成本不只是口径。
*/ */
@Test @Test
@DisplayName("给 LLM 用的全局树不带公司谓词:按公司切会让归类结果按公司分叉") @DisplayName("四条读通路渲染出的 SQL 里都没有 company_id:全局树、分页 children、搜索")
void globalTreeForTheLlmConsumerStaysUnscoped() { @SuppressWarnings("unchecked")
when(productCategoryMapper.selectList(any())).thenReturn(List.of(row(1L, null, "护肤品", BUILTIN))); void noReadPathRendersACompanyPredicate() {
when(productCategoryMapper.selectList(any())).thenReturn(List.of(row(20L, PARENT_ID, "面霜")));
when(productCategoryMapper.selectCount(any())).thenReturn(1L);
when(productCategoryMapper.selectMaps(any())).thenReturn(List.of());
when(productCategoryMapper.selectBatchIds(any())).thenReturn(List.of(row(PARENT_ID, null, "护肤品")));
service.list(); service.list();
service.list("面霜");
service.children(PARENT_ID, 1, 20);
service.search("面霜", 1, 20);
LambdaQueryWrapper<ProductCategoryEntity> query = capturedListWrapper(); ArgumentCaptor<Wrapper<ProductCategoryEntity>> pageQueries = ArgumentCaptor.forClass(Wrapper.class);
String sql = query.getSqlSegment(); verify(productCategoryMapper, atLeastOnce()).selectList(pageQueries.capture());
// 两条一起才算非恒真:只看"不含 company_id"时,一条空 segment(列名解析不到、wrapper 根本没拼) ArgumentCaptor<Wrapper<ProductCategoryEntity>> countQueries = ArgumentCaptor.forClass(Wrapper.class);
// 也会通过,那条断言就变成恒绿。先证明 wrapper 真渲染了东西,再证明它一个实参都没带。 verify(productCategoryMapper, atLeastOnce()).selectCount(countQueries.capture());
assertTrue(sql.contains("ORDER BY"), "wrapper 根本没渲染,下面的否证是空话:" + sql); // 「子类目数」徽章走全表聚合:它要是被加上公司谓词,数字就会和点开的那棵树不一致。
assertFalse(sql.contains("company_id"), ArgumentCaptor<Wrapper<ProductCategoryEntity>> badgeQueries = ArgumentCaptor.forClass(Wrapper.class);
"无参 list() 被接上了公司谓词 —— 货源归类的候选树随之按公司分叉:" + sql); verify(productCategoryMapper, atLeastOnce()).selectMaps(badgeQueries.capture());
assertTrue(query.getParamNameValuePairs().isEmpty(),
"全局树带出了实参(说明有谓词被塞进来):" + query.getParamNameValuePairs());
}
@Test List<Wrapper<ProductCategoryEntity>> queries = new ArrayList<>();
@DisplayName("搜索的公司谓词必须在整条 OR 之外:AND 结合更紧会让前两列命中不受公司约束") queries.addAll(pageQueries.getAllValues());
void searchKeepsTheOrGroupWrappedBeforeTheCompanyPredicate() { queries.addAll(countQueries.getAllValues());
when(productCategoryMapper.selectCount(any())).thenReturn(0L); queries.addAll(badgeQueries.getAllValues());
when(productCategoryMapper.selectList(any())).thenReturn(List.of()); List<String> rendered = new ArrayList<>();
for (Wrapper<ProductCategoryEntity> query : queries) {
service.search("面霜", 1, 20, COMPANY_ID); rendered.add(query.getSqlSegment());
List<LambdaQueryWrapper<ProductCategoryEntity>> queries = capturedSearchWrappers();
for (LambdaQueryWrapper<ProductCategoryEntity> query : queries) {
String sql = query.getSqlSegment();
assertTrue(sql.contains(") AND company_id IN"),
"OR 组没有被包起来再 AND 公司(前两个 like 命中的行会跨公司):" + sql);
Map<String, Object> params = paramsOf(query);
assertTrue(params.containsValue("%面霜%"), sql);
assertTrue(params.containsValue(COMPANY_ID), sql);
} }
assertEquals(2, queries.size(), "count 与 list 两条查询都要带公司谓词"); assertFalse(rendered.isEmpty(), "一条查询都没捕到:读通路的形状变了,后面的断言全是空话");
assertTrue(rendered.stream().anyMatch(sql -> sql.contains("ORDER BY")),
"捕到的全是没渲染的空调用(列名解析失败时 getSqlSegment() 给空串):" + rendered);
assertTrue(rendered.stream().anyMatch(sql -> sql.contains("parent_id")),
"分页 children 与徽章那几条查询没进样本(parent_id 谓词形状变了):" + rendered);
assertTrue(rendered.stream().anyMatch(sql -> sql.contains("LIKE")),
"搜索那条没进样本,「搜索那一支的过滤形状」没人看守:" + rendered);
assertFalse(rendered.stream().anyMatch(sql -> sql.contains("company_id")),
"有读通路又按公司筛了(2026-10-06 定案:全平台共享一棵树):" + rendered);
} }
@Test @Test
@DisplayName("分页 children 的 count 与 list 两条查询同源,且子类目数徽章也按可见集聚合") @DisplayName("分页 children 补 level/path:父级按层批量取,那一列不再是类目名的副本")
void childrenScopeCountListAndChildBadgeTogether() { void childrenPageCarriesPathAndLevel() {
when(productCategoryMapper.selectCount(any())).thenReturn(1L); when(productCategoryMapper.selectCount(any())).thenReturn(1L);
when(productCategoryMapper.selectList(any())).thenReturn(List.of(row(20L, BUILTIN_PARENT_ID, "面霜", COMPANY_ID))); when(productCategoryMapper.selectList(any())).thenReturn(List.of(row(20L, PARENT_ID, "面霜")));
when(productCategoryMapper.selectMaps(any())).thenReturn(List.of()); when(productCategoryMapper.selectMaps(any())).thenReturn(List.of());
when(productCategoryMapper.selectBatchIds(any())).thenReturn(List.of(row(PARENT_ID, null, "护肤品")));
service.children(BUILTIN_PARENT_ID, 1, 20, COMPANY_ID); ProductCategoryListVo vo = service.children(null, 1, 20);
ArgumentCaptor<Wrapper<ProductCategoryEntity>> countCaptor = ArgumentCaptor.forClass(Wrapper.class); assertEquals("护肤品 / 面霜", vo.getItems().get(0).getPath());
verify(productCategoryMapper).selectCount(countCaptor.capture()); assertEquals(1, vo.getItems().get(0).getLevel());
assertTrue(countCaptor.getValue().getSqlSegment().contains("company_id IN")); // 父级取的是批量那一条,不是每行一次 selectById。
ArgumentCaptor<List<Long>> ids = ArgumentCaptor.forClass(List.class);
LambdaQueryWrapper<ProductCategoryEntity> pageQuery = capturedListWrapper(); verify(productCategoryMapper).selectBatchIds(ids.capture());
assertTrue(pageQuery.getSqlSegment().contains("company_id IN")); assertEquals(List.of(PARENT_ID), ids.getValue());
assertTrue(pageQuery.getSqlSegment().contains("parent_id")); verify(productCategoryMapper, never()).selectById(anyLong());
// 「子类目数」徽章走全表聚合:不加公司谓词就会把别家子节点数算进来,数字与点开看到的树不一致。
ArgumentCaptor<Wrapper<ProductCategoryEntity>> badgeCaptor = ArgumentCaptor.forClass(Wrapper.class);
verify(productCategoryMapper).selectMaps(badgeCaptor.capture());
assertTrue(badgeCaptor.getValue().getSqlSegment().contains("company_id IN"),
badgeCaptor.getValue().getSqlSegment());
}
@Test
@DisplayName("新增:归属从操作者会话推导,不靠 V147 那个临时 DEFAULT 1")
void createStampsTheOperatorsCompany() {
when(companyScopeSupport.requireCompanyId(OPERATOR_ID)).thenReturn(COMPANY_ID);
when(productCategoryMapper.selectById(BUILTIN_PARENT_ID))
.thenReturn(row(BUILTIN_PARENT_ID, null, "护肤品", BUILTIN));
when(productCategoryMapper.selectCount(any())).thenReturn(0L);
when(productCategoryMapper.insert(any(ProductCategoryEntity.class))).thenAnswer(call -> {
call.getArgument(0, ProductCategoryEntity.class).setId(500L);
return 1;
});
when(productCategoryMapper.selectById(500L)).thenReturn(row(500L, BUILTIN_PARENT_ID, "面霜套装", COMPANY_ID));
service.create(saveRequest("面霜套装", BUILTIN_PARENT_ID), OPERATOR_ID);
ArgumentCaptor<ProductCategoryEntity> inserted = ArgumentCaptor.forClass(ProductCategoryEntity.class);
verify(productCategoryMapper).insert(inserted.capture());
assertEquals(COMPANY_ID, inserted.getValue().getCompanyId());
assertFalse(Boolean.TRUE.equals(inserted.getValue().getIsBuiltin()));
assertTrue(inserted.getValue().getCategoryKey().startsWith("custom_"));
// 同级重名预检的范围 = 可见集(自建 + 内置):漏了它,第 2 家能在内置"护肤品"下再建一个同名"面霜",
// 页面一排两个而货源归类不知落到哪个;反过来跨家同名必须放行(那正是 uk_company_category_key 要解的)。
// 第 0 条=同级重名预检;findItem 里那条「子类目数」聚合不在本断言射程内(它按 parent_id 数,
// 不带公司谓词——那是详情返回值的计数,与列表可见集两回事)。
LambdaQueryWrapper<ProductCategoryEntity> sibling = countWrappers().get(0);
assertTrue(sibling.getSqlSegment().contains("company_id IN"), sibling.getSqlSegment());
Map<String, Object> params = paramsOf(sibling);
assertTrue(params.containsValue(BUILTIN), "重名检查漏了内置那一半:" + params);
assertTrue(params.containsValue(COMPANY_ID), "重名检查漏了这一家自己:" + params);
}
@Test
@DisplayName("新增:父级挂在别家公司名下要 403,不能静默把行挪出可见集")
void createRejectsParentOwnedByAnotherCompany() {
Long foreignParentId = 77L;
when(companyScopeSupport.requireCompanyId(OPERATOR_ID)).thenReturn(COMPANY_ID);
when(productCategoryMapper.selectById(foreignParentId))
.thenReturn(row(foreignParentId, null, "别家的根", 3L));
BusinessException exception = assertThrows(BusinessException.class,
() -> service.create(saveRequest("面霜套装", foreignParentId), OPERATOR_ID));
assertEquals(403, exception.getCode());
verify(productCategoryMapper, never()).insert(any(ProductCategoryEntity.class));
}
@Test
@DisplayName("新增:内置节点(哨兵 0)当父级放行,否则第 2 家永远建不出子级")
void createAcceptsTheSharedBuiltinParent() {
when(companyScopeSupport.requireCompanyId(OPERATOR_ID)).thenReturn(COMPANY_ID);
when(productCategoryMapper.selectById(BUILTIN_PARENT_ID))
.thenReturn(row(BUILTIN_PARENT_ID, null, "护肤品", BUILTIN));
when(productCategoryMapper.selectCount(any())).thenReturn(0L);
when(productCategoryMapper.insert(any(ProductCategoryEntity.class))).thenAnswer(call -> {
call.getArgument(0, ProductCategoryEntity.class).setId(501L);
return 1;
});
when(productCategoryMapper.selectById(501L)).thenReturn(row(501L, BUILTIN_PARENT_ID, "自建子级", COMPANY_ID));
service.create(saveRequest("自建子级", BUILTIN_PARENT_ID), OPERATOR_ID);
ArgumentCaptor<ProductCategoryEntity> inserted = ArgumentCaptor.forClass(ProductCategoryEntity.class);
verify(productCategoryMapper).insert(inserted.capture());
assertEquals(COMPANY_ID, inserted.getValue().getCompanyId());
assertEquals(BUILTIN_PARENT_ID, inserted.getValue().getParentId());
}
@Test
@DisplayName("更新时按行自己的归属判可见集:内置行归 0、自建行归那一家,都不取 tab")
void updateUsesTheRowsOwnCompanyNotTheTab() {
ProductCategoryEntity custom = row(300L, BUILTIN_PARENT_ID, "面霜", COMPANY_ID);
when(productCategoryMapper.selectById(300L)).thenReturn(custom);
when(productCategoryMapper.selectById(BUILTIN_PARENT_ID))
.thenReturn(row(BUILTIN_PARENT_ID, null, "护肤品", BUILTIN));
when(productCategoryMapper.selectCount(any())).thenReturn(0L);
when(productCategoryMapper.updateById(any(ProductCategoryEntity.class))).thenReturn(1);
service.update(300L, saveRequest("面霜改名", BUILTIN_PARENT_ID), COMPANY_ID);
LambdaQueryWrapper<ProductCategoryEntity> sibling = countWrappers().get(0);
assertTrue(sibling.getSqlSegment().contains("company_id IN"), sibling.getSqlSegment());
Map<String, Object> params = paramsOf(sibling);
assertTrue(params.containsValue(COMPANY_ID), params.toString());
assertFalse(params.containsValue(3L),
"把行挪到可见集外的节点下面会让它从原本看得见它的 tab 里消失:" + params);
}
// ---- 写侧行归属闸门(10-06 逐节点复验后补)----
// 读侧已经把这一页收窄到本公司,写侧不收窄="藏起来的行照样能改名/删除",那是静默删除不是隔离。
// assertSameCompany 自己的判定由 CompanyScopeSupportTest 钉(本仓唯一一份),这里只钉"service 有没有
// 把这一刀落在正确的两个值上、被拒之后还写不写库"——所以桩按真方法的语义给:只有配对不对才抛。
@Test
@DisplayName("更新别家公司的行:闸门 403 且 updateById 一次都不跑")
void updateRejectsARowOwnedByAnotherCompany() {
Long foreignCompanyId = 3L;
when(productCategoryMapper.selectById(300L)).thenReturn(row(300L, null, "别家的根", foreignCompanyId));
stubSameCompanyJudgment();
BusinessException exception = assertThrows(BusinessException.class,
() -> service.update(300L, saveRequest("改名", null), COMPANY_ID));
assertEquals(403, exception.getCode());
verify(productCategoryMapper, never()).updateById(any(ProductCategoryEntity.class));
// 断言闸门拿到的是<b>行自己的</b>归属而不是 tab 之外的什么值:喂错第二个实参,这一刀形同没落。
verify(companyScopeSupport).assertSameCompany(eq(COMPANY_ID), eq(foreignCompanyId), any());
}
@Test
@DisplayName("更新内置节点(哨兵 0):公司账号一律拒,改了它所有公司的树与货源归类同一天跟着变")
void updateRejectsTheSharedBuiltinRow() {
when(productCategoryMapper.selectById(BUILTIN_PARENT_ID))
.thenReturn(row(BUILTIN_PARENT_ID, null, "护肤品", BUILTIN));
stubSameCompanyJudgment();
BusinessException exception = assertThrows(BusinessException.class,
() -> service.update(BUILTIN_PARENT_ID, saveRequest("护肤品改名", null), COMPANY_ID));
assertEquals(403, exception.getCode());
verify(productCategoryMapper, never()).updateById(any(ProductCategoryEntity.class));
}
@Test
@DisplayName("更新:本公司自己的行放行(闸门不该把这一页的正常编辑也拦死)")
void updateAcceptsTheRowsOwnCompany() {
when(productCategoryMapper.selectById(300L)).thenReturn(row(300L, null, "面霜", COMPANY_ID));
when(productCategoryMapper.selectCount(any())).thenReturn(0L);
when(productCategoryMapper.updateById(any(ProductCategoryEntity.class))).thenReturn(1);
stubSameCompanyJudgment();
service.update(300L, saveRequest("面霜改名", null), COMPANY_ID);
verify(productCategoryMapper).updateById(any(ProductCategoryEntity.class));
}
/** 反向钉(多隔离那一向):闸门判 null = 平台超管不限,顺手补一个公司 id 会把超管锁死在本公司。 */
@Test
@DisplayName("更新:超管口径(null)不调用行归属闸门,内置节点照样能改")
void superAdminUpdateSkipsTheRowGate() {
when(productCategoryMapper.selectById(BUILTIN_PARENT_ID))
.thenReturn(row(BUILTIN_PARENT_ID, null, "护肤品", BUILTIN));
when(productCategoryMapper.selectCount(any())).thenReturn(0L);
when(productCategoryMapper.updateById(any(ProductCategoryEntity.class))).thenReturn(1);
service.update(BUILTIN_PARENT_ID, saveRequest("护肤品改名", null), null);
verify(productCategoryMapper).updateById(any(ProductCategoryEntity.class));
verifyNoInteractions(companyScopeSupport);
}
@Test
@DisplayName("删除:闸门在数子级之前,别家的行连「有几个子节点」都不去查")
void deleteRejectsARowOwnedByAnotherCompany() {
Long foreignCompanyId = 3L;
when(productCategoryMapper.selectById(400L)).thenReturn(row(400L, null, "别家的叶子", foreignCompanyId));
stubSameCompanyJudgment();
BusinessException exception = assertThrows(BusinessException.class,
() -> service.delete(400L, COMPANY_ID));
assertEquals(403, exception.getCode());
verify(productCategoryMapper, never()).deleteById(anyLong());
verify(productCategoryMapper, never()).selectCount(any());
}
@Test
@DisplayName("删除:本公司自己的行放行并真删")
void deleteAcceptsTheRowsOwnCompany() {
when(productCategoryMapper.selectById(401L)).thenReturn(row(401L, null, "自建叶子", COMPANY_ID));
when(productCategoryMapper.selectCount(any())).thenReturn(0L);
stubSameCompanyJudgment();
service.delete(401L, COMPANY_ID);
verify(productCategoryMapper).deleteById(401L);
} }
/** /**
* 把 {@code assertSameCompany} 按<b>真方法的语义</b>桩上(第一参 ≠ 第二参才抛 403)。 * 同级重名预检的判据只剩 {@code (name, parent_id)}。这一条是这一族里唯一还可能被"顺手加回去"的形状——
* 不这么写的话 Mockito 对 void 方法默认"什么都不做",三条拒绝用例会因为错误的理由恒绿。 * 归属列整个删了,但只要有人把列加回来,{@code .eq(ProductCategoryEntity::getCompanyId, …)} 就能写,
* 而那一记不报错:第 2 家能建出与第 1 家同名的同级节点,两棵树各长一份。
*/ */
private void stubSameCompanyJudgment() { @Test
org.mockito.Mockito.doAnswer(call -> { @DisplayName("同级重名预检只看 name 与 parent_id:全平台共享后没有归属这一维可比")
Long operatorCompanyId = call.getArgument(0); @SuppressWarnings("unchecked")
Long rowCompanyId = call.getArgument(1); void createSiblingUniquenessChecksNameAndParentOnly() {
if (rowCompanyId == null || !rowCompanyId.equals(operatorCompanyId)) { when(productCategoryMapper.selectCount(any())).thenReturn(0L);
throw new BusinessException(403, call.getArgument(2, String.class)); when(productCategoryMapper.insert(any(ProductCategoryEntity.class))).thenAnswer(call -> {
} call.getArgument(0, ProductCategoryEntity.class).setId(300L);
return null; return 1;
}).when(companyScopeSupport).assertSameCompany(any(), any(), any()); });
when(productCategoryMapper.selectById(300L)).thenReturn(row(300L, null, "面霜套装"));
service.create(saveRequest("面霜套装", null));
ArgumentCaptor<Wrapper<ProductCategoryEntity>> counts = ArgumentCaptor.forClass(Wrapper.class);
verify(productCategoryMapper, atLeastOnce()).selectCount(counts.capture());
LambdaQueryWrapper<ProductCategoryEntity> uniqueness =
(LambdaQueryWrapper<ProductCategoryEntity>) counts.getAllValues().get(0);
String sql = uniqueness.getSqlSegment();
// 实参表是惰性填充的:不先求值 segment,getParamNameValuePairs() 是空 map(正反两断言会双双恒真)。
Map<String, Object> params = uniqueness.getParamNameValuePairs();
assertTrue(sql.contains("name ="), "重名预检整段没了,下面的排他就是空断言:" + sql);
assertTrue(sql.contains("parent_id IS NULL"), "同级这一维没了,重名预检退成了全表比对:" + sql);
assertFalse(sql.contains("company_id"), "重名预检又按公司切了:" + sql);
assertTrue(params.containsValue("面霜套装"), params.toString());
}
@Test
@DisplayName("空关键字的直接搜索返回空页,不探库")
void blankKeywordSearchShortCircuits() {
ProductCategoryListVo vo = service.search(" ", 1, 20);
assertEquals(0L, vo.getTotal());
assertTrue(vo.getItems().isEmpty());
verifyNoInteractions(productCategoryMapper);
} }
private ProductCategorySaveRequest saveRequest(String name, Long parentId) { private ProductCategorySaveRequest saveRequest(String name, Long parentId) {
@@ -354,64 +184,14 @@ class ProductCategoryCompanyScopeTest {
return request; return request;
} }
private static ProductCategoryEntity row(Long id, Long parentId, String name, Long companyId) { private static ProductCategoryEntity row(Long id, Long parentId, String name) {
ProductCategoryEntity entity = new ProductCategoryEntity(); ProductCategoryEntity entity = new ProductCategoryEntity();
entity.setId(id); entity.setId(id);
entity.setParentId(parentId); entity.setParentId(parentId);
entity.setName(name); entity.setName(name);
entity.setCategoryKey("cat_" + id); entity.setCategoryKey("cat_" + id);
entity.setSortOrder(100); entity.setSortOrder(100);
entity.setCompanyId(companyId); entity.setIsBuiltin(false);
entity.setIsBuiltin(companyId == BUILTIN);
return entity; return entity;
} }
@SuppressWarnings("unchecked")
private LambdaQueryWrapper<ProductCategoryEntity> capturedListWrapper() {
ArgumentCaptor<Wrapper<ProductCategoryEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(productCategoryMapper).selectList(captor.capture());
return (LambdaQueryWrapper<ProductCategoryEntity>) captor.getValue();
}
/** create/update 之后 selectCount 至少两条(重名预检 + 详情里的子类目数),按调用顺序取。 */
@SuppressWarnings("unchecked")
private List<LambdaQueryWrapper<ProductCategoryEntity>> countWrappers() {
ArgumentCaptor<Wrapper<ProductCategoryEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(productCategoryMapper, atLeastOnce()).selectCount(captor.capture());
return captor.getAllValues().stream()
.map(wrapper -> (LambdaQueryWrapper<ProductCategoryEntity>) wrapper)
.toList();
}
/**
* MyBatis-Plus 的实参表是<b>惰性</b>填充的:不先求值 {@code getSqlSegment()},
* {@code getParamNameValuePairs()} 是个空 map——那会让"含 0"与"不含 3"两个方向的断言同时恒真。
* 读参数一律走这里,别在测试里各自记得。
*/
private static Map<String, Object> paramsOf(LambdaQueryWrapper<ProductCategoryEntity> query) {
query.getSqlSegment();
return query.getParamNameValuePairs();
}
@SuppressWarnings("unchecked")
private List<LambdaQueryWrapper<ProductCategoryEntity>> capturedSearchWrappers() {
ArgumentCaptor<Wrapper<ProductCategoryEntity>> count = ArgumentCaptor.forClass(Wrapper.class);
verify(productCategoryMapper).selectCount(count.capture());
ArgumentCaptor<Wrapper<ProductCategoryEntity>> list = ArgumentCaptor.forClass(Wrapper.class);
verify(productCategoryMapper).selectList(list.capture());
return List.of((LambdaQueryWrapper<ProductCategoryEntity>) count.getValue(),
(LambdaQueryWrapper<ProductCategoryEntity>) list.getValue());
}
@Test
@DisplayName("空关键字的直接搜索返回空页,不探库")
void blankKeywordSearchShortCircuits() {
ProductCategoryListVo vo = service.search(" ", 1, 20, COMPANY_ID);
assertEquals(0L, vo.getTotal());
verify(productCategoryMapper, never()).selectCount(any());
verify(productCategoryMapper, never()).selectMaps(any());
// CompanyScopeSupport 有 (Long) 与 (AdminUserEntity) 两形:any() 会撞上重载歧义(javac 直接拒绝)。
verify(companyScopeSupport, never()).requireCompanyId(anyLong());
}
} }
@@ -0,0 +1,167 @@
package com.nanri.aiimage.modules.shopkey.controller;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyCreateRequest;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyUpdateRequest;
import com.nanri.aiimage.modules.shopkey.service.ShopKeyService;
import jakarta.servlet.http.HttpServletRequest;
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 org.springframework.mock.web.MockHttpServletRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* 「店铺密钥管理」controller 的正门接线(护栏 G2 断言 A 要求正门调用内联在 handler 块里,
* 本文件钉的是内联之后的<b>语义</b>:tab 的值确实进了出口、出口的结果确实交给了 service)。
*
* <p>G2 只看形状(有没有调、结果有没有被当实参用),看不见"把 service 那侧的实参改成 null"
* 这一记 —— 那一记由本文件的 {@code verify(service).page(1L, 15L, 2L)} 负责。</p>
*
* <p>口径参照 {@code ProductCategoryControllerCompanyScopeTest}:同一套"出口给什么就用什么"的两向钉,
* 少任何一向都会放开一类静默失效(正向量不到「出口被绕过」,反向量不到「controller 自己补公司 id」)。</p>
*/
@ExtendWith(MockitoExtension.class)
class ShopKeyControllerCompanyScopeTest {
private static final Long OPERATOR_ID = 11L;
private static final Long COMPANY_ID = 2L;
@Mock
private ShopKeyService shopKeyService;
@Mock
private AdminAuthSupport adminAuthSupport;
@Mock
private DataReadScope dataReadScope;
private ShopKeyController controller() {
return new ShopKeyController(shopKeyService, adminAuthSupport, dataReadScope);
}
@Test
@DisplayName("列表:tab 的公司 id 交给 readCompanyIdOrOwn,出口给什么 service 就用什么")
void pagePassesTheTabValueThroughTheDoor() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(COMPANY_ID);
controller().page(request, 1L, 15L, COMPANY_ID);
verify(dataReadScope).readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID));
verify(shopKeyService).page(1L, 15L, COMPANY_ID);
}
/**
* 反向钉:超管走"不筛"时出口返回 null,controller 必须原样把 null 传下去。
* 这里"顺手补一个公司 id"的后果是超管切到第 2 家以外时列表永远是第 2 家——
* 与本文件第一支同为正门语义的两半,缺任何一半都放行一次静默改口径。
*/
@Test
@DisplayName("列表:出口判超管(null)时把 null 传下去,不补任何公司 id")
void pageKeepsTheDoorsUnfilteredVerdict() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(null);
controller().page(request, 1L, 15L, COMPANY_ID);
verify(shopKeyService).page(1L, 15L, null);
}
/**
* 非超管带别家的 company_id 时,出口返回的是<b>会话那一家</b>(readCompanyIdOrOwn 的语义),
* controller 不许拿请求里的值再自己判一次——那正是"tab 不是安全边界"被写反的形状。
*/
@Test
@DisplayName("列表:出口按会话收窄后,交给 service 的是收窄值而不是请求里的值")
void pageUsesTheNarrowedValueNotTheRequestedOne() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyIdOrOwn(any(AdminUserEntity.class), eq(99L))).thenReturn(COMPANY_ID);
controller().page(request, 1L, 15L, 99L);
verify(shopKeyService).page(1L, 15L, COMPANY_ID);
}
@Test
@DisplayName("更新/删除/白名单检测:把 writeCompanyId 的判定原样交给 service,controller 不自己补公司 id")
void writeEndpointsPassTheRowOwnershipGate() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
when(dataReadScope.writeCompanyId(any(AdminUserEntity.class))).thenReturn(COMPANY_ID);
ShopKeyUpdateRequest body = new ShopKeyUpdateRequest();
body.setZiniaoAccountName("ziniao-a");
body.setZiniaoToken("token-a");
ShopKeyController controller = controller();
controller.update(request, 300L, body);
controller.delete(request, 300L);
controller.checkWhitelist(request, 300L);
verify(shopKeyService).update(300L, body, COMPANY_ID);
verify(shopKeyService).delete(300L, COMPANY_ID);
verify(shopKeyService).checkWhitelist(300L, COMPANY_ID);
verify(dataReadScope, times(3)).writeCompanyId(any(AdminUserEntity.class));
}
@Test
@DisplayName("写侧:闸门判超管(null)时把 null 传下去,否则超管被锁死在本公司")
void writeGateKeepsTheSuperAdminVerdict() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
when(dataReadScope.writeCompanyId(any(AdminUserEntity.class))).thenReturn(null);
ShopKeyUpdateRequest body = new ShopKeyUpdateRequest();
body.setZiniaoAccountName("ziniao-a");
body.setZiniaoToken("token-a");
controller().update(request, 300L, body);
verify(shopKeyService).update(300L, body, null);
}
/**
* 写侧口径(一期定案):归属由后端从操作者会话推导,请求体不带 company_id,
* 所以 create 这一支<b>不许</b>碰任何读门——碰了就是"建号归谁由前端说了算"。
*/
@Test
@DisplayName("新增:只把操作者 id 交给 service,公司由 service 从会话推导")
void createPassesOnlyTheOperator() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
ShopKeyCreateRequest body = new ShopKeyCreateRequest();
body.setZiniaoAccountName("ziniao-a");
body.setZiniaoToken("token-a");
body.setRemarkName("备注");
controller().create(request, body);
ArgumentCaptor<Long> operatorId = ArgumentCaptor.forClass(Long.class);
verify(shopKeyService).create(eq(body), operatorId.capture());
assertEquals(OPERATOR_ID, operatorId.getValue());
verifyNoInteractions(dataReadScope);
}
private MockHttpServletRequest login() {
return new MockHttpServletRequest();
}
private AdminUserEntity user() {
AdminUserEntity user = new AdminUserEntity();
user.setId(OPERATOR_ID);
user.setRole("super_admin");
return user;
}
}
@@ -0,0 +1,345 @@
package com.nanri.aiimage.modules.shopkey.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.CompanyScopeSupport;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.modules.shopkey.mapper.ShopKeyMapper;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyCreateRequest;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopKeyUpdateRequest;
import com.nanri.aiimage.modules.shopkey.model.entity.ShopKeyEntity;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoApiKeyProvider;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoAuthService;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopIndexService;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeEach;
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.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* V150「店铺密钥管理按公司区分」的 service 侧闸门。
*
* <p>钉的是三件事,每一件都对应一种"接口 200、页面看不出来"的静默形状:</p>
* <ol>
* <li>读范围:{@code companyId} 非空时查询条件里必须真的出现 {@code company_id =},为空时一个条件都不许加。
* 只钉正向等于放行"永远筛第 1 家",只钉反向等于放行"超管被锁死在本公司"。</li>
* <li>写归属:{@code create} 的 {@code company_id} 由<b>操作者会话</b>推导,取不到公司时必须抛而不是落 null
* 让 {@code DEFAULT 1} 静默兜住——那正是本仓一期点名要消灭的"归属失真且不报错"。</li>
* <li>写闸门:跨公司的行必须被 {@code assertSameCompany} 拦下,且拦下之后<b>后面的动作一个都不许发生</b>
* ({@code updateById}/{@code deleteById}/出网探测)。读侧已经收窄而写侧不收窄="藏起来的密钥照样能删"。</li>
* </ol>
*
* <p>{@code CompanyScopeSupport} 用<b>真实现</b>(只 mock 它的 {@code AdminUserMapper}):
* {@code requireCompanyId} 的抛与 {@code assertSameCompany} 的比较都是本文件要验的语义,
* mock 掉等于把闸门本身换成"永远通过"的桩。</p>
*/
@ExtendWith(MockitoExtension.class)
class ShopKeyServiceCompanyScopeTest {
private static final Long OPERATOR_ID = 11L;
private static final Long OWN_COMPANY = 2L;
private static final Long OTHER_COMPANY = 1L;
private static final long ROW_ID = 300L;
@Mock
private ShopKeyMapper shopKeyMapper;
@Mock
private ZiniaoShopIndexService ziniaoShopIndexService;
@Mock
private ZiniaoApiKeyProvider ziniaoApiKeyProvider;
@Mock
private ZiniaoAuthService ziniaoAuthService;
@Mock
private AdminUserMapper adminUserMapper;
private ShopKeyService service;
@BeforeEach
@SuppressWarnings({"unchecked", "rawtypes"})
void setUp() {
// LambdaQueryWrapper 要把 ShopKeyEntity::getCompanyId 解析成列名,靠的是 MP 解析过的 TableInfo;
// 不先 initTableInfo 时断言打在"根本没渲染出来"的空串上,那是一枝恒绿的假断言。
TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""), ShopKeyEntity.class);
service = new ShopKeyService(shopKeyMapper, ziniaoShopIndexService, ziniaoApiKeyProvider,
ziniaoAuthService, new CompanyScopeSupport(adminUserMapper));
}
// -------------------------------------------------------------- 读范围
@Test
@DisplayName("V150 加的列就是代码读写的那一列:companyId → company_id")
void entityMapsCompanyIdToTheColumnTheMigrationAdds() {
TableInfo tableInfo = TableInfoHelper.getTableInfo(ShopKeyEntity.class);
assertThat(tableInfo.getTableName()).isEqualTo("biz_shop_key");
assertThat(tableInfo.getFieldList().stream()
.filter(field -> "companyId".equals(field.getProperty()))
.map(TableFieldInfo::getColumn)
.collect(Collectors.toList()))
.as("实体必须有 companyId 字段且解析到 company_id:列名对不上时 WHERE 与 INSERT 一起打到不存在的列")
.containsExactly("company_id");
}
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void readScopeAddsTheCompanyCondition() {
stubPageQueries();
service.page(1L, 15L, OWN_COMPANY);
LambdaQueryWrapper<ShopKeyEntity> query = capturedCountQuery();
// 钉成等值而不是 contains("company"):把条件写成 company_id IS NOT NULL 也含 "company",
// 而那种写法在第 2 家的 tab 上会把第 1 家的行一起放出来。
assertThat(query.getSqlSegment()).contains("company_id =");
assertThat(query.getParamNameValuePairs()).containsValue(OWN_COMPANY);
}
@Test
void readScopeNullMeansUnfilteredAndNothingIsSubstituted() {
stubPageQueries();
service.page(1L, 15L, null);
// 与上一条对照才有意义:null 是超管「不筛」的判定,这里补一个默认公司就把超管锁死在本公司,
// 而"切 tab 数字不动"的报障会重新出现。
LambdaQueryWrapper<ShopKeyEntity> query = capturedCountQuery();
assertThat(query.getSqlSegment()).doesNotContain("company_id");
assertThat(query.getParamNameValuePairs()).isEmpty();
}
// -------------------------------------------------------------- 写归属
@Test
void createAttributesTheRowToTheOperatorCompanyNotToTheRequestBody() {
stubInsertAndReload(ROW_ID, OWN_COMPANY);
when(adminUserMapper.selectById(OPERATOR_ID)).thenReturn(operatorInCompany(OWN_COMPANY));
service.create(createRequest(), OPERATOR_ID);
ArgumentCaptor<ShopKeyEntity> inserted = ArgumentCaptor.forClass(ShopKeyEntity.class);
verify(shopKeyMapper).insert(inserted.capture());
assertThat(inserted.getValue().getCompanyId()).isEqualTo(OWN_COMPANY);
}
/**
* 请求体里根本没有 company_id 这个字段(一期定案:归属由后端从会话推导)。
* 这一支钉的是"别给 DTO 加一个 company_id 就完事"——加了之后前端传什么算什么,
* 而 {@code ShopKeyController.create} 不读任何门,归属就成了可写字段。
*/
@Test
@DisplayName("请求体不许带归属字段:create/update 两个 DTO 都不该有 companyId")
void requestDtoCarriesNoCompanyField() {
for (Class<?> dto : List.of(ShopKeyCreateRequest.class, ShopKeyUpdateRequest.class)) {
List<String> fields = Arrays.stream(dto.getDeclaredFields())
.map(field -> field.getName())
.collect(Collectors.toList());
assertThat(fields)
.as(dto.getSimpleName() + " 一旦出现 companyId,归属就从「后端按会话推导」变成「前端说了算」")
.doesNotContain("companyId")
.doesNotContain("company_id");
}
}
@Test
@DisplayName("操作者没有所属公司:抛,且一行都不许落库(不许让 DEFAULT 1 静默兜住)")
void createRefusesWhenTheOperatorHasNoCompany() {
when(adminUserMapper.selectById(OPERATOR_ID)).thenReturn(operatorInCompany(null));
assertThatThrownBy(() -> service.create(createRequest(), OPERATOR_ID))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("没有所属公司");
verify(shopKeyMapper, never()).insert(any(ShopKeyEntity.class));
}
// -------------------------------------------------------------- 写闸门
@Test
@DisplayName("更新别家公司的密钥:403 且 updateById 一次都不许发生")
void updateRefusesAnotherCompanysRow() {
stubSelectById(row(ROW_ID, OTHER_COMPANY));
assertThatThrownBy(() -> service.update(ROW_ID, updateRequest(), OWN_COMPANY))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("别家公司的紫鸟令牌");
verify(shopKeyMapper, never()).updateById(any(ShopKeyEntity.class));
}
@Test
@DisplayName("删除别家公司的密钥:403 且 deleteById 一次都不许发生")
void deleteRefusesAnotherCompanysRow() {
stubSelectById(row(ROW_ID, OTHER_COMPANY));
assertThatThrownBy(() -> service.delete(ROW_ID, OWN_COMPANY))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("别家公司的紫鸟令牌");
verify(shopKeyMapper, never()).deleteById(anyLong());
}
/**
* 手动白名单检测会<b>真的出网</b>(打一次紫鸟接口):跨公司拦不住的话,代价不只是"看到别家的行",
* 而是用别家的令牌消耗别家的上游配额、并把别家那行的失败计数改着玩。
*/
@Test
@DisplayName("检测别家公司密钥的白名单:403 且一次出网探测都不发")
void whitelistProbeRefusesAnotherCompanysRow() {
stubSelectById(row(ROW_ID, OTHER_COMPANY));
assertThatThrownBy(() -> service.checkWhitelist(ROW_ID, OWN_COMPANY))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("别家公司的紫鸟令牌");
verify(ziniaoAuthService, never()).probeApiKeyUpstream(anyString());
}
@Test
@DisplayName("同公司的行照常放行:闸门不是把这一页整个锁死")
void sameCompanyRowIsStillWritable() {
ShopKeyEntity existing = row(ROW_ID, OWN_COMPANY);
stubSelectById(existing);
service.delete(ROW_ID, OWN_COMPANY);
verify(shopKeyMapper).deleteById(ROW_ID);
}
@Test
@DisplayName("超管闸门给 null:别家的行也照删(写侧口径与读侧同源,不另立规矩)")
void superAdminGatePassesEveryRow() {
stubSelectById(row(ROW_ID, OTHER_COMPANY));
service.delete(ROW_ID, null);
verify(shopKeyMapper).deleteById(ROW_ID);
}
@Test
@DisplayName("行上没有归属(历史脏行):按跨公司处理拦下,不当成「谁的都不是」放过去")
void rowWithoutCompanyIsTreatedAsForeign() {
stubSelectById(row(ROW_ID, null));
assertThatThrownBy(() -> service.delete(ROW_ID, OWN_COMPANY))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("别家公司的紫鸟令牌");
verify(shopKeyMapper, never()).deleteById(anyLong());
}
// ------------------------------------------------------ 令牌查重的范围
/**
* 令牌查重<b>刻意保持跨公司全局</b>(迁移文件头 §4:同一个令牌在两家公司各存一行会被
* {@code ZiniaoApiKeyProvider} 按令牌并成一条,白名单状态与代理地址互相顶掉)。
*
* <p>这一支是对那条决定的<b>反向钉</b>:将来有人"顺手"把 {@code ensureTokenAvailable} 按
* {@code companyId} 收窄,数据库那把全局唯一键照样会撞 1062,而 service 侧的友好报错先没了 ——
* 症状变成"新增密钥偶发 500"。所以这里钉的是查重的谓词里<b>不许出现 company_id</b>。</p>
*/
@Test
@SuppressWarnings({"unchecked", "rawtypes"})
void tokenDedupePredicateStaysGlobal() {
when(adminUserMapper.selectById(OPERATOR_ID)).thenReturn(operatorInCompany(OWN_COMPANY));
when(shopKeyMapper.selectOne(any(LambdaQueryWrapper.class))).thenReturn(null);
stubInsertAndReload(ROW_ID, OWN_COMPANY);
service.create(createRequest(), OPERATOR_ID);
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(shopKeyMapper).selectOne(captor.capture());
LambdaQueryWrapper<ShopKeyEntity> query = captor.getValue();
assertThat(query.getSqlSegment()).contains("ziniao_token_hash =");
assertThat(query.getSqlSegment()).doesNotContain("company_id");
}
// ---------------------------------------------------------------- 桩
@SuppressWarnings({"unchecked", "rawtypes"})
private void stubPageQueries() {
when(shopKeyMapper.selectCount(any(LambdaQueryWrapper.class))).thenReturn(0L);
when(shopKeyMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of());
}
@SuppressWarnings({"unchecked", "rawtypes"})
private LambdaQueryWrapper<ShopKeyEntity> capturedCountQuery() {
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(shopKeyMapper).selectCount(captor.capture());
return captor.getValue();
}
private void stubSelectById(ShopKeyEntity row) {
when(shopKeyMapper.selectById(ROW_ID)).thenReturn(row);
}
/**
* MP 的真 insert 会把自增主键回填进实体;mock 不会,所以这里用 thenAnswer 补那一步——
* 少了它,{@code create} 结尾的 {@code loadRow(entity.getId())} 会拿着 null 去查,
* 于是"归属落对了"这条断言红在"店铺密钥不存在"上,报的是错原因。
*/
private ShopKeyEntity stubInsertAndReload(Long id, Long companyId) {
ShopKeyEntity stored = row(id, companyId);
when(shopKeyMapper.insert(any(ShopKeyEntity.class))).thenAnswer(invocation -> {
ShopKeyEntity entity = invocation.getArgument(0);
entity.setId(id);
return 1;
});
when(shopKeyMapper.selectById(id)).thenReturn(stored);
return stored;
}
private static ShopKeyEntity row(Long id, Long companyId) {
ShopKeyEntity entity = new ShopKeyEntity();
entity.setId(id);
entity.setCompanyId(companyId);
entity.setZiniaoAccountName("ziniao-account");
entity.setZiniaoToken("old-token");
entity.setZiniaoTokenHash("old-hash");
entity.setIpWhitelistStatus("UNKNOWN");
entity.setIpWhitelistFailCount(0);
return entity;
}
private static AdminUserEntity operatorInCompany(Long companyId) {
AdminUserEntity user = new AdminUserEntity();
user.setId(OPERATOR_ID);
user.setCompanyId(companyId);
return user;
}
private static ShopKeyCreateRequest createRequest() {
ShopKeyCreateRequest request = new ShopKeyCreateRequest();
request.setZiniaoAccountName("ziniao-account");
request.setZiniaoToken("new-token");
return request;
}
private static ShopKeyUpdateRequest updateRequest() {
ShopKeyUpdateRequest request = new ShopKeyUpdateRequest();
request.setZiniaoAccountName("ziniao-account");
request.setZiniaoToken("new-token");
return request;
}
}
@@ -75,8 +75,7 @@ public class SimilarAsinLlmLocalVerify {
// 生产真实类目数据(导出自 biz_product_category),spy 类目服务按 parentId 过滤。 // 生产真实类目数据(导出自 biz_product_category),spy 类目服务按 parentId 过滤。
List<com.nanri.aiimage.modules.productcategory.model.entity.ProductCategoryEntity> categories = loadCategories(objectMapper); List<com.nanri.aiimage.modules.productcategory.model.entity.ProductCategoryEntity> categories = loadCategories(objectMapper);
ProductCategoryService categoryService = Mockito.spy(new ProductCategoryService( ProductCategoryService categoryService = Mockito.spy(new ProductCategoryService(
Mockito.mock(com.nanri.aiimage.modules.productcategory.mapper.ProductCategoryMapper.class), Mockito.mock(com.nanri.aiimage.modules.productcategory.mapper.ProductCategoryMapper.class)));
Mockito.mock(com.nanri.aiimage.common.service.CompanyScopeSupport.class)));
Mockito.doAnswer(invocation -> { Mockito.doAnswer(invocation -> {
Long parentId = invocation.getArgument(0); Long parentId = invocation.getArgument(0);
List<com.nanri.aiimage.modules.productcategory.model.vo.ProductCategoryItemVo> items = categories.stream() List<com.nanri.aiimage.modules.productcategory.model.vo.ProductCategoryItemVo> items = categories.stream()
@@ -0,0 +1,311 @@
# 菜单权限按公司一套树 · 设计(2026-10-06)
控制方要求:「菜单权限也加字段来区分,现在的默认归到 admin 下」,并在两个档位里选了重的那一档——
**每家公司一套菜单树**(不是"只给字典行打个归属标记")。
关联:`company-multi-tenant-design-2026-10-04.md`(账号归属,已上线)、
`brand-dedupe-company-isolation-design-2026-10-04.md`(规则库每公司一套,同一形状)。
## 1. 线上家底(2026-10-06 主机A 业务库只读实查,不是估的)
| 事实 | 读数 |
| --- | --- |
| `columns` 行数 | 52 = admin 26(id 4…109)+ app 24(id 1…96)+ internal 2(id 69、95) |
| `columns` 列 | id/parent_id/name/column_key/menu_type/route_path/sort_order/created_at/updated_at,**无 company_id** |
| 唯一键 | **两条**:`uk_column_key(column_key)`、`uk_menu_type_route_path(menu_type, route_path)` |
| 其他索引/约束 | `PRIMARY(id)`、`idx_columns_parent_sort_id`、`idx_menu_type_sort_id`、`fk_columns_parent_id`→`columns(id)` |
| `user_column_permission` | 784 笔 / 133 只账号 / 34 个被授权 column_id |
| 授权按公司分布 | 公司 1(厦门米椿花)131 人 768 笔;公司 2(德阳)2 人 **16 笔** |
| 同 key 重复行 | 0 行 ⇒ 原地换复合键不会因重复失败 |
| `admin_companies`(id 109)授权 | 0 笔(10-04 事故后的既定状态) |
`PermissionMenuSchemaInitializer` 生产是关的(`application.yml:259` 默认 `false`),但它是 JdbcTemplate
旁路,十几条种子 SQL 的幂等守卫全是裸 `NOT EXISTS(column_key)`——换键后它不改就会一声不响地不再插行。
本批已把这条通道的 31 段种子语句逐条钉上 `company_id = 1`(落法与理由见 §5 末条,护栏见 §8)。
## 2. 三档定案(控制方「直接开干」,按推荐档落)
- **D1 存量授权**:V149 同笔把公司 2 那 16 笔授权按 `column_key` 重指向本公司副本。
不留成人工动作,否则德阳那 2 只账号一上线就掉光菜单(隐藏=静默删除)。
- **D2 谁能编辑别家的树**:站点超管可带 `company_id` 读写任意公司的树;非超管恒锁本公司,
传了别人的 `company_id` 一律 403。今天就是超管在给 133 只账号配权限,锁死本公司等于把这件活关掉。
- **D3 复制范围**:admin + app + internal 三种 `menu_type` 全复制(客户端账号同样分属两家公司,
只复制 admin 会留半棵共享树);**`admin_companies` 那一行不复制**——它是角色内在闸门
(`SUPER_ADMIN_ONLY_KEYS`),公司 2 的树里根本没有这行,比"有一行但看不见"更干净。
- **D4 之后新建的公司**:V149 只补当时已存在的公司,「公司管理 → 新增公司」必须同批建树,
否则新租户是一个零菜单行的公司(账号登录侧边栏全空、授权树一个勾都没有,全程不报错)。
落法见 §5 的 `copyTreeFromTemplate`,与建号同一次写入、不留"上线后手工再跑一遍复制段"。
## 3. 数据模型(V149)
1. `ADD COLUMN company_id bigint NULL`(末位)→ `UPDATE ... SET company_id = 1 WHERE company_id IS NULL`
→ `MODIFY COLUMN company_id bigint NOT NULL DEFAULT 1`。第三句同时是回填自检闸门:漏一行就抛 1048
(V143 同形)。`DEFAULT 1` 只为混合版本窗口的旧 jar 存在(旧 jar 的实体没这字段,严格模式建菜单会 1364),
摘除动作是下一版的一条纯元数据操作 `ALTER TABLE columns ALTER COLUMN company_id DROP DEFAULT`(**禁 MODIFY**,
重建会按当时的列默认值物化历史行),取号见 `backend-java/docs/migration-inventory.md`(当前 V152 起)。
哨兵 `CompanyDefaultGuard.WATCHED_TABLES` 已把 `columns` 探进清单——摘之前巡检每天多喊一条
`COMPANY_DEFAULT_STILL_PRESENT`,那是哨兵在干活,不是新故障。
2. 两条唯一键**先 ADD 后 DROP**(中间任一步失败都至少还有一个键在守并发):
`uk_company_column_key(company_id, column_key)`、
`uk_company_menu_type_route_path(company_id, menu_type, route_path)`。
新键是旧键的严格放宽 ⇒ 不会因重复失败。索引字节预算(utf8mb4):8+256=264、8+80+1020=1108,都远低于 3072。
3. 不加 `company_id` 的单列索引:新唯一键的最左前缀就是它,52 行的表再开索引就是 V139 那轮清理掉的冗余形状。
4. 复制:按「`company` 全表 × 公司 1 的字典行」插副本(不是硬编码公司 2,第三家开通时不用再改迁移),
`parent_id` **先留 NULL**,再由下一条 UPDATE 沿 `(company_id, column_key)` 把父指向重映射到同公司副本——
与插入顺序无关,两级三层都成立。带源值插入是错的:那是全局 id,副本会跨公司挂到厦门米椿花的分组上,
而 FK 只保证父行存在、挡不住挂在别家。
5. 授权重指向:`user_column_permission` 按「账号公司 = 行公司」重算 `column_id`。
重跑是 no-op(驱动条件要求行还挂在公司 1 上且账号不属于公司 1);重指前先摘掉"源行 + 副本"并存的重复授权,
否则重指会撞 PK `(user_id, column_id)` 报 1062。
6. 四道自检闸门(临时表 `must_be_zero INT NOT NULL`,V143 那个"约束替我喊"的家族):
① 每家公司的树与公司 1 一样齐(专防复制段被 `NOT EXISTS` 守卫一声不响挡掉一整家);
② 跨公司父指向残留 = 0;③ 跨公司授权残留 = 0;④ `company_id` 不为 NULL/不为 0。
不为 0 就让迁移失败,而不是留下一个静默分叉的树。
外键 `fk_columns_parent_id` 只保证父行存在,**挡不住跨公司挂父**,所以同公司判定必须在应用层(§4)。
## 4. 后端读侧:出口一起收窄
判据只有一个来源:`loadRawMenus(companyId, menuType)`。它是 `hasAnyAdminMenu`、`expandDescendantIds`、
`superAdminOnlyMenuIds`、授权树、有效菜单、`resolveGrantableMenuIds` 的共同上游,剪这一处等于剪一片。
| 出口 | 现在的形状 | 改成 |
| --- | --- | --- |
| `list()` 目录(菜单管理页) | 全量 52 行 | 按**操作者**公司;超管可用 `?company_id=` 指定 |
| `list(operator, type, true)` 授权树 | 操作者范围 | 范围集按操作者公司算,跨公司项永不下发 |
| `getUserColumnPermissions()` 有效菜单(登录/侧边栏) | `loadMenus(type)` 全表 | 按**被授权账号**公司 |
| `getUserColumnIds()` 回填集 | 同上 | 按目标账号公司 |
| `findDataPermission()`(`selectOne + LIMIT 1`) | 全局按 key 点查 | **必须带公司**:换键后同 key 有 N 行,`LIMIT 1` 会跨公司借位拿到别家的数据权限行——本次最危险的一处静默失效 |
| `hasEffectiveColumnPermission()` | 查得到就展开判定 | 行公司与账号公司不同 ⇒ 直接 false |
| `ensureUniqueColumnKey()` / `ensureUniqueRoutePath()` | 全局查重 | 本公司内查重;不改的话德阳在公司 1 建过的 key 上**根本建不出来** |
| `resolveSortOrder()` / `reorder()` | 同类型全局 MAX+1 / 兄弟集 | 同公司内 |
| `resolveMenuTypes()`(建号/编辑拆分 admin+app) | 按 id 归类 | **归类本身不带公司**(它按 id 批量取行,跨公司照样归得出类型);真正挡下别家 id 的是它下游的出口 3——`updateUserColumnPermissions` 的有效计数与 `loadMenus` 都按**目标账号公司**取,别家 id 在那里被抛 400「存在无效或不属于当前类型的菜单权限项」。这条要写准,否则下一个人会到 `resolveMenuTypes` 里找一道并不存在的公司闸门 |
| 两个数据范围授权端点 | 只挡超管,用户列表全量 | 数据权限行按公司解析,用户列表按公司筛 |
`hasEffectiveColumnPermission` 那处保守方向要说清:跨公司拿不到行时判"无权限",是拒绝而不是放行。
**"请求里的 `company_id` 到底在哪一步被收窄"要说准**:不在 controller 里写 `if`,也不在各页 service 里各写一遍,
而是收参数的当场交给 `PermissionMenuService.resolveScopeCompanyId(operator, companyId)`(公开方法,
把返回值**往下传**而不是丢掉),六个带这参数的 handler 全部同形——目录 GET/POST、两个数据范围授权的 GET 与 PUT:
```java
AdminUserEntity operator = requireAdmin(request);
Long scopeCompanyId = permissionMenuService.resolveScopeCompanyId(operator, companyId);
return ApiResponse.success(permissionMenuService.list(operator, menuType, grantableOnly, scopeCompanyId));
```
这条出口注册进了 `CompanyIdParamGoesThroughReadScopeTest` 的 `SCOPE_DOORS`(现在是**三道门**:
`readScope(`、`readCompanyIdOrOwn(`、`resolveScopeCompanyId(`),A/B/C/D 四条判据共用:
handler 收了 `company_id` 就必须走门、取到的绑定名必须真的出现在下游实参里。
所以"控制器多写一个带 `company_id` 的口却没过归属判定"是编译后跑一条用例就红,不靠人记着。
`PUT /permission-users/{userId}/columns` 与 `update`/`delete`/`reorder` 故意不带这个参数:
它们按行 id 或按被授权账号定位,归属在 service 里判(§5),前端再猜一个公司参数只会多出一个可伪造的入口。
## 5. 后端写侧
- `ensureAdminOperatorIfPresent` 只判 `isAdmin`,这是写侧唯一的洞——非超管今天能改整张目录。
补两条:目标行公司 = 操作者公司(超管除外,`ensureMenuWritable`);`ensureParentValid` 对**整条祖先链**
判同公司(一个同公司的父、上面挂着别家的分组,落库后这行在两棵树里都渲染不出)。
- `delete` 与 `reorder` 都先过 `ensureMenuWritable`;`reorder` 原来不带操作者(控制器那一层),已补。
- 新增菜单的归属:由**端点的 `company_id` 参数(缺省=操作者公司)**决定,前端不靠猜;超管传别家=给别家建。
读侧与写侧共用同一个判据 `resolveScopeCompanyId`——分成两个迟早漂移成「读能看别家、写挡不住」。
- `copyTreeFromTemplate(companyId, templateCompanyId)`(D4):`CompanyService.create` 在建号那笔事务里
调它,模板公司是**操作者本公司**(参数由调用方给,方法内部不编默认值;缺归属直接拒)。
两趟写与 V149 第 6/7 段同形:第一趟只管插、父先留空,第二趟按 `column_key` 认父;
`SUPER_ADMIN_ONLY_KEYS` 那行不进副本;目标公司已有的 key 原样保留 ⇒ 重跑只补差集。
- **旁路种子(`PermissionMenuSchemaInitializer`)只种公司 1**:七条 `INSERT INTO columns` 的列清单显式写
`company_id`、投影写真常量 `1`;判存守卫、认父 JOIN、按 key 的 UPDATE、三条下划线→连字符改名,
全部带 `company_id = 1`。理由是换键之后 `column_key` 只在单家公司内唯一——一条裸
`WHERE column_key = ...` 在这张表上的语义是"把每一家的同名行都改一遍"(别家副本的 parent 被拍平、
初始授权发给别家的行 id),而 `executeQuietly` 把 1048/1062 吞成一行 debug 日志,表现是"某一家
一声不响少一套菜单"。`grantInitialShopDataCrawlDataPermissions` 那条 JOIN 另加
`data_col.company_id = old_col.company_id`。显式写公司还有一层作用:这条通道不再依赖列上那条
`DEFAULT 1`,于是 §3 待办里那句 `DROP DEFAULT` 落地时不会让建号变成 1364。
别家公司的树不由这里插行——存量归 V149 的复制段,新建归 `copyTreeFromTemplate`。
## 6. 前端
每个响应只含一家公司的行 ⇒ `column_key` 在单响应内仍唯一,侧边栏、路由守卫、`hasMenuKey`、
`menu-route-map`、`parseMenuTree` 全不用改。这条不变量的看守是"查询条件必须带公司"本身
(§8 的 `everyMenuQueryCarriesTheOperatorsCompany` + `onlyTheSiteSuperAdminMayCrossCompanies`:
不传 `company_id` 时锁操作者本公司,超管显式指定才换家),不是"响应里数一遍 key 有没有重复"——
后者在假数据上永远为真,杀不掉任何变异。
- 「菜单管理」(`admin_columns`) 把 10-06 摘掉的公司 tab 装回来:`COMPANY_SCOPED_PAGES` 加一行
(正向清单 `companyTabAppliesTo` 自动放行,不需要新代码),`MenusPage.vue` watch `tab.activeId`
清掉本页那两个客户端筛选项(菜单名称/类型不进请求)并重取数。
- **「菜单管理」这一页带 `company_id` 的只有两个口**:`fetchMenuManageNodes`(GET 目录)与 `createMenu`(POST 新建)。
`updateMenu`/`deleteMenu`/`reorderMenus` 故意不带——它们按行 id 定位,归属判定在后端
(`ensureMenuWritable` 比较行公司与操作者公司,跨公司 403);前端再从树里猜一个公司参数只会多出一个可被伪造的入口。
- **用户管理里的授权弹窗必须带 `company_id`**(本条推翻初稿写的"不加参数:树按被授权账号的公司出,
载荷里的 id 天然同公司"——那句在 V149 之后是错的):一棵树一套 id,
授权树若按**操作者**公司下发,而目标账号在另一家(超管切了 tab 或在给自己以外公司的账号配权限),
则该账号已有的 `column_id` 全都不在这棵树里 ⇒ 已授权一项勾不上,点保存又被
`ensureGrantable` 判「无效的菜单权限项」,整页授权直接不可用。所以读侧(`fetchGrantableMenus`)
与写侧(按范围整树替换)必须同时收窄,只窄一侧等于把授权藏掉。
取值来源分两处、各对应后端真正会用的那一家:编辑弹窗用 `companyTab.requestCompanyId`
(列表本来就由它筛 ⇒ 行公司 = tab 公司),新建弹窗用 `form.companyId`(建号弹窗里选的那家,
与 `user-create-model` 下发给后端的 `payload.companyId` 同一个值;未选则为 null,后端落操作者本公司)。
- **两处没做界面暴露(本批只到后端)**:图片视频任务、店铺数据任务那两个「数据范围授权」弹窗
(`fetchImageVideoPermissionUsers` / `fetchShopDataTaskPermissionUsers` 及其 PUT 孪生)仍然一个公司参数都不发。
后端那两个端点本批已经收下 `company_id`(缺省=操作者本公司 ⇒ 与改动前同义,不是回归),
但站点超管在那两页切 tab 时弹窗候选不会跟着换家。这属于"新维度的界面暴露",按口径要单独批准,不在本批顺手做。
## 7. 发布顺序与混合版本窗口
路线甲(选定):V149 与 jar 同批发,双台同窗口(A 金丝雀过了立刻补 B),迁移在首台启动期执行。
V149 不是单独一支 jar:按 `backend-java/docs/migration-inventory.md`,下一版要连着跑 `V150__shop_key_company_scope`
与 `V151__rule_tables_shared_across_companies`(同批待发的另外两路),三条按序、一次启动跑完;
取号只认"当前最大值 + 1",V148 已随它被推翻的口径退役,不许回填。
窗口内旧 jar 的后果逐条列清:
- 目录/授权树会短时出现两排同名菜单(难看,不伤人);
- `findDataPermission` 的 `LIMIT 1` 借到公司 1 的行时,判的是"本公司授权集合里没有这个 id" ⇒ **拒绝而不是放行**;
- 建菜单会误报"菜单标识已存在"(旧 jar 的全局查重撞副本)。
都是分钟级、方向保守。路线乙(新 jar 带"本公司无行就回落公司 1"的临时分支)否决:那条回落正是
`ProductCategoryService` 这一轮刚拆掉的"哨兵 0 可见集"形状,而且公司 2 在两批之间看不到自己的树。
## 8. 自证(落码后按实物补,不写"补一些用例"这种没法核对的话)
| 面 | 看守 | 数量 |
| --- | --- | --- |
| 迁移形状 | `MenuTreeCompanyMigrationV149Test`:列存在且 NOT NULL、两条新复合键在、两条旧键已摘、`company_id` 无 NULL/无 0、复制段与重指段的驱动条件逐条在场、四道 `_v149_gate` 自检各就各位、回滚脚本不在 Flyway 扫描路径、**旁路种子逐条钉公司**(`schemaInitializerSeedsEveryRowIntoTheTemplateCompany`:31 段种子/14 段按 key 认菜单,取样集有下限,且喂一条已知违规必须被抓到) | 20 例 |
| 读侧收窄 | `PermissionMenuServiceCompanyScopeTest`:`loadRawMenus`/`findDataPermission`(`LIMIT 1` 借位那一形)/`hasEffectiveColumnPermission`/祖先链/重名查重/授权有效性计数/`resolveScopeCompanyId` 各按公司取;反向钉"不许出现回落公司 1 的临时分支" | 16 例 |
| 控制器 | `PermissionMenuControllerTest`:`company_id` **先过 `resolveScopeCompanyId` 再往下传**(六个 handler 各验一次,桩返回 `99L` 与原始 `7L` 不同值 ⇒ "传了原值"和"传了判定值"不可能双双通过),缺省 `null` 那两例同样进门而不是编一个默认公司 | 10 例 |
| 归属正门 | `CompanyIdParamGoesThroughReadScopeTest`:`SCOPE_DOORS` 从两道门加到三道(`readScope(` / `readCompanyIdOrOwn(` / `resolveScopeCompanyId(`),A/B/C/D 四条判据共用;新增三条 `menuScopeDoor*` 探针,其中"取到范围却丢掉"和"门参数列表里没有那个绑定名"两条必须红 | 3 例(含全部页面的取样) |
| 哨兵 | `CompanyDefaultGuardTest`:`columns` 同时进 `WATCHED_TABLES` 与探测 SQL 的 IN 清单(双向钉同源) | 14 例 |
| 闸门行不旁路 | `PermissionCompanyMenuHiddenTest`:本批给建树加了**第四处**出口,`SUPER_ADMIN_ONLY_KEYS` 的引用从"两处负向 + 一处反解"改成三处负向(`list` / `getUserColumnPermissions` / `copyTreeFromTemplate`)+ 一处正向反解,且只数剥掉注释后的可执行行——旧写法"整份文本里出现 ≥4 次"被 1 处定义 + 4 处 javadoc 就凑得满,三处过滤器全删照样绿 | 7 例 |
| 前端接线 | `company-tab-wiring.test.ts`:`admin_columns` 进 `COMPANY_SCOPED_PAGES` + `SEND_POINTS` 登记三处新发送口(全表 21 处 / 按 (文件,整行) 聚成 17 组,与真文件条数逐处对平)、`WATCH_BODY_PINS` 加 `MenusPage.vue` 一对(共 10 对) | `node --test` 1731 例全绿 |
| 前端文案 | `align-operation-guide.test.ts`:`admin_columns` 的引导文案补上公司 tab 那句(句子本体与分母规则见 `company-tab-design-2026-10-04.md`,不在本文件里):带 tab 那句的页面集合 = 注册表 16 页减去唯一豁免 = 15 页,多一页少一页都红 | 同一批 1731 例内 |
| 建司种子 | `CompanyServiceDirectoryTest`:`create` 在插公司行之后同一次写入里调 `copyTreeFromTemplate(新公司, 操作者本公司)`(`InOrder` 钉顺序);重名被拒那一笔反向钉"不许留下一套挂在不存在公司上的菜单" | 19 例(本批新增 2 例) |
| 类型 | `vue-tsc --noEmit` | 0 错误 |
| 全量(主树 2026-10-06 16:59 / 17:0x 实跑) | 后端 `mvn -o test`(无 skipTests)`Tests run: 3891, Failures: 0, Errors: 0, Skipped: 7` / BUILD SUCCESS,460 支测试类(逐类相加同为 3891);前端 `node --test tests/*.test.ts` 1731 例 / 0 红 | 本轮跑出的三条红见下节末「补记」 |
变异自证(已实跑,2026-10-06,在 `tmp/v149-wt` 独立 worktree 里,主树 `PermissionMenuService.java`
全程 md5 `2f29aa0bb39447dcab6f68878bd546b3` 未动):对 `PermissionMenuService` 逐点注入
"把 `.eq(…companyId…)` 改成 `.eq(false, …companyId…)`"(这一形就是"列名还在、值被丢"的静默失效原型)
以及三条建树/归属语义的反向改写,12 个点各开一次 mvn,分母恒为 `PermissionMenuServiceCompanyScopeTest` 的 16 例:
```
PRISTINE bytes=86315 lines=1615
BASELINE tests=16 failures=0 errors=0 rc=0 (401s)
KILLED loadRawMenus drops company red=4/16 (286s)
KILLED reorder siblings drop company red=1/16 (354s)
KILLED grant validity count drops target company red=1/16 (317s)
KILLED findDataPermission drops company (LIMIT 1 borrow) red=1/16 (211s)
KILLED ensureUniqueColumnKey drops company red=1/16 (193s)
KILLED grantableUserQuery drops company red=1/16 (216s)
KILLED resolveScopeCompanyId lets anyone cross companies red=1/16 (182s)
KILLED ensureMenuWritable stops guarding red=1/16 (135s)
KILLED hasEffectiveColumnPermission stops denying foreign id red=1/16 (163s)
KILLED ensureParentValid stops checking ancestor chain red=2/16 (208s)
KILLED copyTree clones the role-intrinsic gate row red=1/16 (193s)
KILLED copyTree no longer short-circuits self-copy red=1/16 (137s)
RESTORE-CHECK ok
SUMMARY injected=12 killed=12 survived=0 void=0
```
`red=4/16` 那一处(`loadRawMenus`)是唯一的公共读口,四条用例同时红;其余各点各红 1 条,
`ensureParentValid` 红 2 条。两条 `copyTree` 变异分别被「建树:三种 menu_type 全复制、闸门行不复制」
和「建树不许靠默认值兜」这两条打死——D3(不复制 `admin_companies`)与"不自拷"都由这套用例独立看守,
不是靠读侧顺带压住的;本轮选中的类只有 `PermissionMenuServiceCompanyScopeTest`(分母恒 16),
所以这 12 条红全部出在它内部。`CompanyService.create` 那一笔种树调用另由
`CompanyServiceDirectoryTest` 的「插行之后同一次写入里复制菜单树」与「建公司被拒时不建树」两条钉住
(验的是调用点与顺序,不在变异分母里)。
**补记(那 12 轮之后全量跑出的三条红,加一处顺带收口)**:上面那份日志的 md5 只覆盖到扫描时点,
之后的改动不在那 12 个点里,各自另加了尺子——
1. **后端红**:控制器六个 handler 收了 `company_id` 却没走任何归属出口
(`CompanyIdParamGoesThroughReadScopeTest` 断言 A 红)。修法不是往 `READ_SCOPE_ALLOWLIST` 里添六条豁免,
而是把 `resolveScopeCompanyId` 注册成**第三道正门**,并给它配三条自己的探针(能过 / 取了丢掉 / 传 null),
让"下一个新页面忘了收口"这件事仍然是编译后跑一条用例就红。
2. **后端红**:`copyTreeFromTemplate` 是 `SUPER_ADMIN_ONLY_KEYS` 的第四处引用点
(`PermissionCompanyMenuHiddenTest` 红)。这条 SDD 台账里预先写过(要求加变异 + 把期望从
"恰 2 负 + 恰 1 正 + ≥4"往前挪),本批按它挪成 **恰 3 负 + 恰 1 正 + 定义与出口共 ≥5 行**;
对应变异就是那份日志里的第 11 轮 `copyTree clones the role-intrinsic gate row`(已被打死,`red=1/16`)。
3. **前端红**:`align-user-menu-grantable.test.ts:105` 原本把控制器的调用形状钉成
`list(requireAdmin(request), menuType, grantableOnly, companyId)`(原值透传),本批改过门之后它红。
这条不是"测试写错了",而是**前端侧唯一读 Java 控制器源的那把尺子**——挪成新形状时补了一条
`doesNotMatch(/menuType, grantableOnly, companyId\s*\)/)` 反向钉:不许有人图省事把 tab 原文再透传回去。
4. **顺带收口**:旁路种子(`PermissionMenuSchemaInitializer`)的 31 段种子逐条钉上 `company_id`,
并加 `schemaInitializerSeedsEveryRowIntoTheTemplateCompany` 反向钉住——这条通道的失效形状是
`executeQuietly` 把 SQL 错误吞成 debug 日志,"某一家少一套菜单"不会喊。
这些都不在变异分母 16 例里(护栏形状与文件形状,不是运行时行为),靠的是各自用例里的取样下限 +
已知违规探针;验收读数是本轮主树实跑:后端 `mvn -o test` **3891 例 / 0 红 / 7 skip**(460 支类,逐类相加同为 3891),
前端 `node --test tests/*.test.ts` **1731 例 / 0 红**。
线上复验探针(发版后只读跑):`scripts/_probe_menu_company_shape.py` 在原有 8 条之后加了 5 条——
各家 × `menu_type` 的行数(每家必须与公司 1 一样齐)、跨公司挂父 = 0、跨公司授权残留 = 0、
`admin_companies` 那一行不在公司 1 之外、`columns.company_id` 的 `COLUMN_DEFAULT`(摘 DEFAULT 那条待办的复验口)。
发版前跑这五条会各回一条 `Unknown column 'company_id'`——那是列还没有,不是探针坏,五条各有 `@@` 标记互不牵连。
生产写操作一律先取证 → 备份 → `--apply`,由控制方执行或明确授权后代跑。
## 9. 回滚
`backend-java/docs/rollback-V149-permission-menu-company.sql`(Flyway 扫描路径之外):
授权重指回公司 1 的行 → 删副本 → 换回两条旧唯一键 → `DROP COLUMN company_id` →
删 `flyway_schema_history` 的 version=149 行 → 回滚 jar → 起应用。
副本 `column_id` 一旦有新增授权,回滚脚本先报数再停手,不做静默删除。
## 10. 发版命令包(本批 0 手工 SQL:迁移在 jar 启动期由 Flyway 跑)
前提:两支待发的后端批次(V149 本批 + V150/V151 店铺密钥与规则库)都要先进同一个提交,
出包树才能同时带上三条迁移;前端要带本批的 `admin_columns` 接线与 10-06 那三个公司 tab 文件。
提交与推送由控制方决定,代跑生产写操作需要明确授权。
**下面每一行都在同一个目录下跑:工作区根 `D:\todesk\副业\数富AI`**(`scripts/` 在这一层,
`crawler-plugin/` 也在这一层)。前面那条 `cd` 会把后面几行带到别的目录里去,所以每条需要换目录的
都用子 shell 括号包住,不留状态。
**发版前取证(只读,我可以自己跑)**
```
python scripts/_probe_jar_md5.py # 两台现网 jar 的 md5 与体积(回滚点)
python scripts/_probe_menu_company_shape.py # 基线:前 8 条有数,后 5 条回 Unknown column 'company_id' 才是对的
```
**出包(本地,从干净 worktree;入口与输入件路径 10-06 逐条 `-e` 验过存在)**
```
git -C crawler-plugin worktree add crawler-plugin/tmp/v149-build <含本批的提交>
# 三处文档输入未入库,读者是 ExplainIndexAuditDocTest / ArchitecturePlanSection6DocTest / IndexMigrationV101Test:
cp -r crawler-plugin/backend-java/docs/specs crawler-plugin/tmp/v149-build/backend-java/docs/
cp crawler-plugin/backend-java/docs/explain-index-audit.md \
crawler-plugin/backend-java/docs/java-architecture-optimization-plan.md \
crawler-plugin/tmp/v149-build/backend-java/docs/
(cd crawler-plugin/tmp/v149-build/backend-java && mvn -o clean package) # 上线不许 skipTests;clean 只在出包树,主树禁
ls -l crawler-plugin/tmp/v149-build/backend-java/target/*.jar
```
**发布(写生产,两台同窗,逐台健康门禁按主机给端口:A 18080 / B 19080)**
```
python scripts/_deploy_verified_jar.py <jar路径> <期望md5> --check # 只读:记录线上 md5 + 两台健康
python scripts/_deploy_verified_jar.py <jar路径> <期望md5> # 上传 → 校验 → 重启 → 健康 → 复核
(cd crawler-plugin/admin-frontend-vue && npm run build)
python scripts/_deploy_admin_vue.py # dist 只在主机B /var/www,软链原子切
```
**发版后复验(只读)**
```
python scripts/_probe_menu_company_shape.py # cols_by_company 各家行数须等于公司 1;三条残留须为 0;
# admin_companies_outside_company1 须为 0(D3)
python scripts/_prod_watch.py --window 30m # ALERTS 只认 † 那几条;本批预期多一条 COMPANY_DEFAULT_STILL_PRESENT
# (columns 进了哨兵清单,摘 DEFAULT 之前它每天都在喊,那是哨兵在干活)
```
前端两件事各自单独核:**线上树 == 本地构建**用整树聚合摘要(本地在 `dist` 上跑、远端在
`/var/www/admin-vue-<ts>` 上跑同一条管道,两个值必须相等):
```
(cd crawler-plugin/admin-frontend-vue/dist && find . -type f | sort | xargs md5sum | cut -d' ' -f1 | sort | md5sum)
```
**这版到底带没带本批的接线**用扛得住 minify 的字面量数:`dist/assets/MenusPage-*.js` 里 `company_id` 应为 2
(目录 + 新建),带 `grantableOnly` 的那个 UsersPage chunk 里应为 1(授权树)。
本地 10-06 17:05 那版构建(`vue-tsc --noEmit` 0 错误、`npm run build` RC=0)实测就是这两个数:
`MenusPage-Cui-Lsn1.js` `company_id`=2、`UsersPage-DeJ6Wy_U.js` `company_id`=1(同文件 `grantableOnly`=2)。