feat(公司tab): 批次 2/3/4 再接 8 页,注册表收到 16 页——用户页回流 company_id 按新边界改写反向钉

「切 tab 数据还一样」的根因一直是分母小于现实:批次 1 只登记 8 页,本轮按控制方
三次点名扩到 16 页(company-scope.ts 是唯一清单,routes.ts 的 companyScoped 逐页对平)。

批次 2(五页 ASIN 中心):去重总数据 / 不符合ASIN / 查询ASIN / 最低价ASIN / 商品类目。
批次 3(两页店铺中心):撞款监控、店铺数据记录。这两页没有归属列可筛,归属口径是
「本公司账号名下的店铺」——后端由 DataReadScope 推公司 → 成员账号 → biz_shop_manage.
created_by_id,前端只把 activeId 当 company_id 送下去。空成员集必须交空集合,绝不能
退化成 null(null 在这里=全量,那样第二家会看到全部数据)。
批次 4(用户管理):后端早就认 company_id(只对站点超管生效,公司超管恒锁本公司),
断的是前端——UserListQuery 里连这个字段都没有,三家 tab 看的是同一份全量列表。

三处口径改动,逐条说明:
1)company-user-list.test.ts 的反向钉被改写。2026-10-04 定案把公司维度从用户页整体摘掉,
   那条钉的原文是「列表查询/筛选/行渲染不允许出现公司维度」。控制方 2026-10-05 明确要
   用户管理区分公司 tab,所以钉的边界收窄成两半:渲染层(行级公司列、「所属公司」标签、
   筛选状态、顶栏公司名)仍不得回流;请求层的 company_id 是这次加回来的,尺子换成
   「取值口唯一」——页面每处 companyId 都必须等于 companyTab.requestCompanyId,且
   normalizeUserPageParams/toUserListQuery 两只白名单构造器体内不许出现公司值。
   新增一支行为钉:往归一化里传 companyId 必须被丢掉,这是 users.ts 读原始入参的全部理由
   (写成 normalized.companyId 时 TS 照样绿、运行时恒 undefined)。
2)align-dup-console 那条 watch 看守的 token 扩到含 reload。变异自证里「删掉 void
   loadConsole()」当场全绿:体里的清筛选项守住了,重新取数那半没人守。批次 3/4 三对
   token 一起写到 reload 为止(批次 1/2 的老条目不动)。
3)公司管理页补正/反向两把尺子:company-config-entry-super-only 新增「吃公司 tab 的页面
   集合恰好等于 COMPANY_SCOPED_PAGES 的 pageFiles」——按代码真值比,不按清单比,所以
   清单不改一字而往 CompaniesPage.vue 里塞 store 也会红。谓词带括号,否则 import 行也算消费者。

菜单权限(admin_columns)本轮不动:MenusPage 只消费 /api/admin/permission-menus 这一份全局
菜单字典,切 tab 一样是数据本身全局,不是筛选坏了。真问题在写侧——PermissionMenuService
create/update/delete 只有 ensureAdminOperatorIfPresent(isAdmin 即放行),公司管理员改的是
全平台的菜单行。收窄为仅站点超管 vs 给 permission_menu 加归属列,两种改法代价差一个量级,
留给控制方定档。

护栏:G1 发送口 22 个 / 页面分组 17、watch 体看守 10 对、operation-guide 的 tab 文案 15 页
(撞款监控是显式豁免,另有一条自检盯「豁免落空」)。
变异自证 12/12 全杀(前端 10 + 公司管理反向钉 2),分母钉死在 27 例。
门禁:后端全量 3823 例 / 0 失败 / 0 错误 / 7 skipped,BUILD SUCCESS;admin-frontend-vue
1741 例 / 0 红;vue-tsc rc=0。首轮后端 4 红是另一路 task_partial 改动与本轮编译抢跑,
单跑 13 例已绿,本笔不含他们的任何文件。

未上线:jar 与 admin-vue 都没出包,V147 未在生产执行。
This commit is contained in:
2026-10-06 02:32:59 +08:00
parent bff7068421
commit 2cae0d742c
87 changed files with 3519 additions and 459 deletions
+4
View File
@@ -15,6 +15,9 @@ export interface UserListParams {
adminId?: number | null adminId?: number | null
/** 角色过滤(''=全部)。 */ /** 角色过滤(''=全部)。 */
role?: string role?: string
/** 公司 tab 的当前公司;由页面从 store 传入,**不住在 UserFilterState 里**
* (normalizeUserPageParams 白名单构造会把它丢掉,取值口只认 fetchUserList 的原始入参)。 */
companyId?: number | null
} }
/** 序列化到 GET /api/admin/users 的查询参数(Java snake_case)。 */ /** 序列化到 GET /api/admin/users 的查询参数(Java snake_case)。 */
@@ -26,6 +29,7 @@ export interface UserListQuery {
created_by_id?: number created_by_id?: number
admin_id?: number admin_id?: number
role?: string role?: string
company_id?: number
} }
/** 用户列表项即 AdminUser(与 Java AdminUserItemVo 字段对齐)。 */ /** 用户列表项即 AdminUser(与 Java AdminUserItemVo 字段对齐)。 */
+5 -1
View File
@@ -11,7 +11,11 @@ import {
/** 分页查询用户列表:归一化参数 → GET /api/admin/users → 解析 Java 分页负载。 */ /** 分页查询用户列表:归一化参数 → GET /api/admin/users → 解析 Java 分页负载。 */
export async function fetchUserList(params: Partial<UserListParams> = {}): Promise<UserPageResult> { export async function fetchUserList(params: Partial<UserListParams> = {}): Promise<UserPageResult> {
const normalized = normalizeUserPageParams(params) const normalized = normalizeUserPageParams(params)
const { data } = await http.get('/api/admin/users', { params: toUserListQuery(normalized) }) const query = toUserListQuery(normalized)
// normalizeUserPageParams 是白名单构造(只点名 page/pageSize/keyword/createdById/adminId/role),
// 公司值必须从原始 params 读:写成 normalized.companyId 会 TS 绿、运行时恒 undefined。
if (params.companyId != null) query.company_id = params.companyId
const { data } = await http.get('/api/admin/users', { params: query })
return parseUserPage(data) return parseUserPage(data)
} }
@@ -25,4 +25,22 @@ export const COMPANY_SCOPED_PAGES: readonly CompanyScopedPage[] = [
{ menuKey: 'admin_device_logs', apiFiles: ['src/api/device-logs.ts'], pageFiles: ['src/pages/records/DeviceLogsPage.vue'] }, { menuKey: 'admin_device_logs', apiFiles: ['src/api/device-logs.ts'], pageFiles: ['src/pages/records/DeviceLogsPage.vue'] },
{ menuKey: 'admin_group_manage', apiFiles: ['src/pages/account/shop-group-api.ts'], pageFiles: ['src/pages/account/GroupsPage.vue'] }, { menuKey: 'admin_group_manage', apiFiles: ['src/pages/account/shop-group-api.ts'], pageFiles: ['src/pages/account/GroupsPage.vue'] },
{ menuKey: 'admin_shop_manage', apiFiles: ['src/pages/shop/shop-manage-api.ts'], pageFiles: ['src/pages/shop/ShopManagePage.vue'] }, { menuKey: 'admin_shop_manage', apiFiles: ['src/pages/shop/shop-manage-api.ts'], pageFiles: ['src/pages/shop/ShopManagePage.vue'] },
// 批次 2(控制方 2026-10-05 点名「切 tab 数据还一样」那五页):读门已在后端接上(V145 补归属 / V147 加列),
// 这一批把前端接线补齐。apiFiles 只列**真的把 company_id 拼进请求**的模块:
// 各页的 *-filter.ts 与 asin-filter.ts 只带 camel 的 companyId 字段(类型 + 白名单构造都不点名它),
// 列进来会让正向判据去盯一个本来就不该出现 snake_case 的文件。
{ 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_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 列筛的,
// 而是「本公司账号名下的店铺」:后端由 DataReadScope 把公司 → 成员账号 → biz_shop_manage.created_by_id 逐级推导,
// 前端只负责把 activeId 当 company_id 送下去。
{ menuKey: 'admin_shop_data_duplicate_check', apiFiles: ['src/pages/tasks/duplicate-console-api.ts'], pageFiles: ['src/pages/tasks/DuplicateCheckPage.vue'] },
{ menuKey: 'admin_shop_data_crawl_tasks', apiFiles: ['src/pages/tasks/shop-data-api.ts'], pageFiles: ['src/pages/tasks/ShopDataTasksPage.vue'] },
// 批次 4(控制方 2026-10-05 点名「菜单权限和用户管理也要区分公司 tab 的数据」)。
// 这一页的后端早就认 company_id(AdminUserService 只在**站点超管**身上用它筛,公司超管恒锁本公司),
// 断的是前端:users-dto 的 UserListQuery 里连这个字段都没有 ⇒ 三家 tab 看到的是同一份全量列表。
{ menuKey: 'admin_users', apiFiles: ['src/api/users.ts'], pageFiles: ['src/pages/account/UsersPage.vue'] },
] ]
@@ -21,9 +21,9 @@ 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 的 8 页共用、不各抄一遍——文案差一个字,护栏就只盯得住其中一页。 * 这一句由参与 tab 的 13 页共用、不各抄一遍——文案差一个字,护栏就只盯得住其中一页。
* 由 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 逐页盯着(分母取注册表,加第 9 页忘了补文案会当场红)。 */ * 按 COMPANY_SCOPED_PAGES 逐页盯着(分母取注册表,加一页忘了补文案会当场红)。 */
const COMPANY_TAB_GUIDE_NOTE = ' 超级管理员可用页面上方的公司 tab 切换公司,切换后行数会变化——行数变少不是数据丢了。' const COMPANY_TAB_GUIDE_NOTE = ' 超级管理员可用页面上方的公司 tab 切换公司,切换后行数会变化——行数变少不是数据丢了。'
/** §5 的承载:注册表里显式 companyScoped:false 的 C 类页要的是**另一句**——"这页不参与", /** §5 的承载:注册表里显式 companyScoped:false 的 C 类页要的是**另一句**——"这页不参与",
@@ -35,7 +35,10 @@ const SHOP_OWNER_COMPANY_NOTE = ' 店铺归哪家公司由「负责人」决定
export const OPERATION_GUIDES: Record<string, OperationGuideData> = { export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
admin_users: { admin_users: {
text: '先用筛选定位账号,再编辑角色和菜单权限;删除账号会要求二次确认。', // 2026-10-05 批次 4:与 group-manage 同型偏离——参与公司 tab 的页必须在原文之后带上那句 §9.3,
// 所以这一条不再与旧版 guides 逐字相等(护栏改为 match 原句子串,见 align_guide_users_matches_reference_text)。
text: '先用筛选定位账号,再编辑角色和菜单权限;删除账号会要求二次确认。'
+ COMPANY_TAB_GUIDE_NOTE,
steps: ['筛选账号', '编辑权限', '确认保存'], steps: ['筛选账号', '编辑权限', '确认保存'],
}, },
admin_columns: { admin_columns: {
@@ -60,24 +63,28 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
steps: ['查看公司列表', '新建公司', '改名或启停'], steps: ['查看公司列表', '新建公司', '改名或启停'],
}, },
admin_dedupe_total_data: { admin_dedupe_total_data: {
text: '支持按关键词、用户、分组和国家筛选;导入前先确认所选分组,导出会按日期范围生成文件。', text: '支持按关键词、用户、分组和国家筛选;导入前先确认所选分组,导出会按日期范围生成文件。'
+ COMPANY_TAB_GUIDE_NOTE,
steps: ['选择分组', '筛选或导入', '核对并导出'], steps: ['选择分组', '筛选或导入', '核对并导出'],
}, },
admin_invalid_asin_data: { admin_invalid_asin_data: {
text: '维护不符合规则的 ASIN 或品牌。添加后可使用上方筛选快速回查。', text: '维护不符合规则的 ASIN 或品牌。添加后可使用上方筛选快速回查。'
+ COMPANY_TAB_GUIDE_NOTE,
steps: ['填写 ASIN/品牌', '选择分组', '保存并回查'], steps: ['填写 ASIN/品牌', '选择分组', '保存并回查'],
}, },
admin_query_asin: { admin_query_asin: {
text: '查询 ASIN 以店铺为单位维护。列表里点击 ASIN 即可复制,点右侧「配置」可一次维护该店铺所有站点的 ASIN。', text: '查询 ASIN 以店铺为单位维护。列表里点击 ASIN 即可复制,点右侧「配置」可一次维护该店铺所有站点的 ASIN。'
+ COMPANY_TAB_GUIDE_NOTE,
steps: ['筛选店铺', '打开配置抽屉', '保存或导出'], steps: ['筛选店铺', '打开配置抽屉', '保存或导出'],
}, },
admin_product_categories: { admin_product_categories: {
text: '类目树支持展开查看层级。搜索、编辑和删除都在同一列表中完成。' text: '类目树支持展开查看层级。搜索、编辑和删除都在同一列表中完成。'
+ COMPANY_SCOPE_NOT_APPLIED_NOTE, + COMPANY_TAB_GUIDE_NOTE,
steps: ['搜索类目', '展开层级', '新增或编辑'], steps: ['搜索类目', '展开层级', '新增或编辑'],
}, },
admin_skip_price_asin: { admin_skip_price_asin: {
text: '最低价 ASIN 以店铺为单位维护。列表里点击 ASIN 即可复制,点右侧「配置」可一次维护该店铺所有站点的 ASIN 与最低价。', text: '最低价 ASIN 以店铺为单位维护。列表里点击 ASIN 即可复制,点右侧「配置」可一次维护该店铺所有站点的 ASIN 与最低价。'
+ COMPANY_TAB_GUIDE_NOTE,
steps: ['筛选店铺', '打开配置抽屉', '保存或批量导入'], steps: ['筛选店铺', '打开配置抽屉', '保存或批量导入'],
}, },
admin_shop_keys: { admin_shop_keys: {
@@ -92,10 +99,13 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
steps: ['选择分组', '维护店铺信息', '筛选核对结果'], steps: ['选择分组', '维护店铺信息', '筛选核对结果'],
}, },
admin_shop_data_crawl_tasks: { admin_shop_data_crawl_tasks: {
text: '店铺数据任务按状态和时间筛选。批量操作前请核对已选任务。', text: '店铺数据任务按状态和时间筛选。批量操作前请核对已选任务。'
+ COMPANY_TAB_GUIDE_NOTE,
steps: ['筛选任务', '检查状态', '执行批量操作'], steps: ['筛选任务', '检查状态', '执行批量操作'],
}, },
// admin_shop_data_duplicate_check(店铺撞款监控)为例外页:不展示全局提示条,不参与对齐。 // admin_shop_data_duplicate_check(店铺撞款监控)为例外页:不展示全局提示条,不参与对齐。
// 它进了公司 tab 范围(COMPANY_SCOPED_PAGES)却没有文案可挂,所以那句 §9.3 的看守在这一页由
// tests/align-operation-guide.test.ts 显式豁免;这一页的「切 tab 行数会变」写在页面自身的说明里。
admin_image_video_tasks: { admin_image_video_tasks: {
text: '可先使用筛选缩小任务范围,再查看任务状态、结果和权限范围。' text: '可先使用筛选缩小任务范围,再查看任务状态、结果和权限范围。'
+ COMPANY_TAB_GUIDE_NOTE, + COMPANY_TAB_GUIDE_NOTE,
@@ -2,11 +2,12 @@
import { formatDateTime } from '@/utils/datetime' import { formatDateTime } from '@/utils/datetime'
/** 用户管理页 · 像素复刻旧版 admin.html panel-users(自绘:panel-box + 页头按钮 + 筛选 form-row + 旧式表格/分页 + 原生 confirm 删除)。 /** 用户管理页 · 像素复刻旧版 admin.html panel-users(自绘:panel-box + 页头按钮 + 筛选 form-row + 旧式表格/分页 + 原生 confirm 删除)。
* 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 type { AdminUser } from '@/types/admin' import type { AdminUser } from '@/types/admin'
import { roleLabel } from '@/types/admin' import { roleLabel } from '@/types/admin'
import { useAdminSessionStore } from '@/stores/admin-session' import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
import { deleteUser, fetchUserList } from '@/api/users' import { deleteUser, fetchUserList } from '@/api/users'
import { fetchCompanies } from '@/api/companies' import { fetchCompanies } from '@/api/companies'
import { createUserFilterState, toUserListParams, type UserFilterState } from './users-filter' import { createUserFilterState, toUserListParams, type UserFilterState } from './users-filter'
@@ -20,6 +21,7 @@ import EditUserDialog from './EditUserDialog.vue'
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 loadError = ref('') const loadError = ref('')
const rows = ref<AdminUser[]>([]) const rows = ref<AdminUser[]>([])
@@ -54,11 +56,17 @@ function editableOf(row: AdminUser): boolean {
return editableBy(row.role, operatorRole.value) return editableBy(row.role, operatorRole.value)
} }
/** 列表请求参数 = 用户填的筛选态 + 当前公司。公司值每次现取、不写进 filters:
* 它由上方 tab 决定而不是用户填的筛选项,住进 filters 就等于多出第二个取值口径(Store 之外再长一个)。 */
function listParams() {
return { ...toUserListParams(filters), companyId: companyTab.requestCompanyId }
}
async function loadUsers() { async function loadUsers() {
loading.value = true loading.value = true
loadError.value = '' loadError.value = ''
try { try {
const page = await fetchUserList(toUserListParams(filters)) const page = await fetchUserList(listParams())
rows.value = page.items rows.value = page.items
total.value = page.total total.value = page.total
if (Array.isArray(page.admins)) admins.value = page.admins if (Array.isArray(page.admins)) admins.value = page.admins
@@ -66,7 +74,7 @@ async function loadUsers() {
const last = totalPageCount(page.total, filters.pageSize) const last = totalPageCount(page.total, filters.pageSize)
if (last > 0 && filters.page > last) { if (last > 0 && filters.page > last) {
filters.page = last filters.page = last
const retried = await fetchUserList(toUserListParams(filters)) const retried = await fetchUserList(listParams())
rows.value = retried.items rows.value = retried.items
total.value = retried.total total.value = retried.total
} }
@@ -126,6 +134,11 @@ function goJump() {
changePage(Math.min(Math.max(n, 1), totalPages.value)) changePage(Math.min(Math.max(n, 1), totalPages.value))
} }
// 切公司 = 重新取数,并清掉两处上一家遗留:
// ①「所属管理员」下拉的候选(admins)随本公司的列表响应给出,上一家选中的 adminId 在新一家的下拉里不存在;
// ② 用户名全平台唯一(V143 的唯一索引),留着上一家填的关键字去筛新一家 ⇒ 必然空页,而输入框还显示着那个值。
watch(() => companyTab.activeId, () => { filters.createdByAdminId = null; filters.keyword = ''; filters.page = 1; void loadUsers() })
onMounted(() => { onMounted(() => {
void loadUsers() void loadUsers()
// 公司目录仅站点超管拉取(建「公司超级管理员」时选公司用);非超管不发这个请求,后端 403 兜底 // 公司目录仅站点超管拉取(建「公司超级管理员」时选公司用);非超管不发这个请求,后端 403 兜底
@@ -5,6 +5,7 @@ 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'
@@ -14,6 +15,7 @@ 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)
@@ -44,7 +46,7 @@ const groupOptions = computed<ShopGroupOption[]>(() => {
async function loadGroups() { async function loadGroups() {
try { try {
groups.value = await fetchShopManageGroups() groups.value = await fetchShopManageGroups(companyTab.requestCompanyId)
} catch { } catch {
groups.value = [] groups.value = []
} }
@@ -63,6 +65,7 @@ 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
@@ -160,6 +163,10 @@ 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()
@@ -2,7 +2,7 @@
import { formatDateTime } from '@/utils/datetime' import { formatDateTime } from '@/utils/datetime'
/** 数据去重总数据(registry) · 像素复刻旧版 admin.html panel-dedupe-total-data(自绘:分组摘要 + 双行筛选 + 旧式表格/分页 + 编辑/导入弹窗 + 导出等待遮罩)。 /** 数据去重总数据(registry) · 像素复刻旧版 admin.html panel-dedupe-total-data(自绘:分组摘要 + 双行筛选 + 旧式表格/分页 + 编辑/导入弹窗 + 导出等待遮罩)。
* 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 { import {
fetchDedupeTotalList, fetchDedupeTotalList,
@@ -25,8 +25,10 @@ import type { DedupeImportProgress } from './dedupe-import-model.ts'
import { toExportUrl } from './dedupe-total-export.ts' import { toExportUrl } from './dedupe-total-export.ts'
import OldPagination from '@/components/OldPagination.vue' import OldPagination from '@/components/OldPagination.vue'
import { useAdminSessionStore } from '@/stores/admin-session' import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
const session = useAdminSessionStore() const session = useAdminSessionStore()
const companyTab = useCompanyTabStore()
/** 仅超管需要分组维度:非超管数据由后端裁剪到本人分组,分组筛选/列一律不展示。 */ /** 仅超管需要分组维度:非超管数据由后端裁剪到本人分组,分组筛选/列一律不展示。 */
const isSuperAdmin = computed(() => session.isSuperAdmin) const isSuperAdmin = computed(() => session.isSuperAdmin)
@@ -91,7 +93,7 @@ async function load(): Promise<void> {
loading.value = true loading.value = true
try { try {
const result = await fetchDedupeTotalList( const result = await fetchDedupeTotalList(
toDedupeListParams(filter, page.value, pageSize.value, pendingCursor), toDedupeListParams(filter, page.value, pageSize.value, pendingCursor, companyTab.requestCompanyId),
) )
rows.value = result.items rows.value = result.items
total.value = result.total total.value = result.total
@@ -277,7 +279,7 @@ async function doExport(): Promise<void> {
startExportWait() startExportWait()
try { try {
// 对齐 admin.js:fetch 流式下载,带筛选参数;失败响应(JSON)解析错误提示。 // 对齐 admin.js:fetch 流式下载,带筛选参数;失败响应(JSON)解析错误提示。
const response = await window.fetch(toExportUrl(filter), { credentials: 'include' }) const response = await window.fetch(toExportUrl(filter, companyTab.requestCompanyId), { credentials: 'include' })
const contentType = response.headers.get('content-type') || '' const contentType = response.headers.get('content-type') || ''
if (!response.ok || contentType.includes('application/json')) { if (!response.ok || contentType.includes('application/json')) {
const body = (await response.json().catch(() => ({}))) as { error?: string; message?: string; msg?: string } const body = (await response.json().catch(() => ({}))) as { error?: string; message?: string; msg?: string }
@@ -304,11 +306,22 @@ async function doExport(): Promise<void> {
} }
} }
async function loadGroups(): Promise<void> {
try {
groups.value = await fetchDedupeTotalGroups(companyTab.requestCompanyId)
} catch {
groups.value = []
}
}
// 切公司 = 重新取数:列表与分组下拉共用这一个 watch(少一个 = 那半边的 tab 是装饰品)。
// groupId 与 keyset 游标必须一起清:上一家选中的分组在新一家不存在,而上一家响应回传的 lastId
// 拿到新一家去翻页会把「游标之后」当成条件,首屏直接筛成空列表。
watch(() => companyTab.activeId, () => { filter.groupId = null; pageCursor.value = null; pendingCursor = null; void loadGroups(); void load() })
onMounted(() => { onMounted(() => {
void load() void load()
fetchDedupeTotalGroups().then((items) => { void loadGroups()
groups.value = items
})
}) })
</script> </script>
@@ -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 } from 'vue' import { computed, onMounted, reactive, ref, watch } 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,7 +17,9 @@ 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('')
@@ -68,7 +70,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) const result = await fetchProductCategoryChildren(null, rootPage.value, rootPageSize.value, companyTab.requestCompanyId)
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 承担)。
@@ -144,7 +146,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) const result = await fetchProductCategoryChildren(parent?.id ?? null, page, PRODUCT_CATEGORY_DEFAULT_PAGE_SIZE, companyTab.requestCompanyId)
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)
@@ -195,7 +197,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) const result = await searchProductCategories(keyword.value, page, searchPageSize.value, companyTab.requestCompanyId)
searchRows.value = result.items searchRows.value = result.items
searchTotal.value = result.total searchTotal.value = result.total
searchPage.value = result.page searchPage.value = result.page
@@ -297,13 +299,17 @@ 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) anchor.href = buildProductCategoryExportUrl(keyword.value, companyTab.requestCompanyId)
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>
@@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
/** 查询 ASIN · 像素复刻旧版 admin.html panel-query-asin(自绘:面板头操作组、筛选+导出 XLSX、原生 rowspan 表格+可复制 ASIN、旧式分页)。 /** 查询 ASIN · 像素复刻旧版 admin.html panel-query-asin(自绘:面板头操作组、筛选+导出 XLSX、原生 rowspan 表格+可复制 ASIN、旧式分页)。
* 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 CopyText from '@/components/CopyText.vue' import CopyText from '@/components/CopyText.vue'
import { formatDateTime } from '@/utils/datetime' import { formatDateTime } from '@/utils/datetime'
@@ -18,8 +18,10 @@ import { fetchShopManageGroups } from '../shop/shop-manage-api.ts'
import type { ShopGroupOption } from '../shop/shop-dto.ts' import type { ShopGroupOption } from '../shop/shop-dto.ts'
import OldPagination from '@/components/OldPagination.vue' import OldPagination from '@/components/OldPagination.vue'
import { useAdminSessionStore } from '@/stores/admin-session' import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
const session = useAdminSessionStore() const session = useAdminSessionStore()
const companyTab = useCompanyTabStore()
/** 仅超管需要分组维度:非超管数据由后端裁剪到本人分组,分组筛选/列一律不展示。 */ /** 仅超管需要分组维度:非超管数据由后端裁剪到本人分组,分组筛选/列一律不展示。 */
const isSuperAdmin = computed(() => session.isSuperAdmin) const isSuperAdmin = computed(() => session.isSuperAdmin)
@@ -146,7 +148,7 @@ async function onCreateGroupChange(): Promise<void> {
} }
shopNamesLoading.value = true shopNamesLoading.value = true
try { try {
shopNames.value = await fetchShopNamesByGroup(createGroupId.value) shopNames.value = await fetchShopNamesByGroup(createGroupId.value, companyTab.requestCompanyId)
} catch (error) { } catch (error) {
shopNames.value = [] shopNames.value = []
ElMessage.error(error instanceof Error ? error.message : '店铺列表加载失败') ElMessage.error(error instanceof Error ? error.message : '店铺列表加载失败')
@@ -279,7 +281,7 @@ async function submitImport(): Promise<void> {
function doExport(): void { function doExport(): void {
// 带当前筛选(分组/店铺名/ASIN/国家)导出,范围与列表筛选一致(此前不带参数导致导出恒为全量)。 // 带当前筛选(分组/店铺名/ASIN/国家)导出,范围与列表筛选一致(此前不带参数导致导出恒为全量)。
const anchor = document.createElement('a') const anchor = document.createElement('a')
anchor.href = toQueryAsinExportUrl(filter) anchor.href = toQueryAsinExportUrl(filter, companyTab.requestCompanyId)
document.body.appendChild(anchor) document.body.appendChild(anchor)
anchor.click() anchor.click()
anchor.remove() anchor.remove()
@@ -288,7 +290,7 @@ function doExport(): void {
async function loadGroups() { async function loadGroups() {
try { try {
groups.value = await fetchShopManageGroups() groups.value = await fetchShopManageGroups(companyTab.requestCompanyId)
} catch { } catch {
groups.value = [] groups.value = []
} }
@@ -304,6 +306,7 @@ async function load() {
shopName: filter.shopName.trim() || undefined, shopName: filter.shopName.trim() || undefined,
asin: filter.asin.trim() || undefined, asin: filter.asin.trim() || undefined,
country: filter.country || undefined, country: filter.country || undefined,
companyId: companyTab.requestCompanyId,
}) })
rows.value = result.items rows.value = result.items
total.value = result.total total.value = result.total
@@ -342,6 +345,11 @@ function goJump() {
changePage(Math.min(Math.max(n, 1), totalPages.value)) changePage(Math.min(Math.max(n, 1), totalPages.value))
} }
// 切公司 = 重新取数:列表与分组下拉共用这一个 watch(少一个 = 那半边的 tab 是装饰品)。
// groupId 与 shopName 必须一起清:上一家选中的分组/店铺名在新一家的可见集与候选字典里根本不存在,
// 留着会把切 tab 后的首屏筛成空列表(请求、后端、权限三处都没错,最难查的那一型)。
watch(() => companyTab.activeId, () => { filter.groupId = null; filter.shopName = ''; void loadGroups(); void load() })
onMounted(() => { onMounted(() => {
void loadGroups() void loadGroups()
void load() void load()
@@ -1,11 +1,12 @@
<script setup lang="ts"> <script setup lang="ts">
/** 最低价 ASIN(跳过跟价)· 像素复刻旧版 admin.html panel-skip-price-asin(自绘:面板头操作组、筛选(分组/店铺/国家/ASIN/最低价≥≤)+导出 XLSX、原生 rowspan 表格、旧式分页)。 /** 最低价 ASIN(跳过跟价)· 像素复刻旧版 admin.html panel-skip-price-asin(自绘:面板头操作组、筛选(分组/店铺/国家/ASIN/最低价≥≤)+导出 XLSX、原生 rowspan 表格、旧式分页)。
* 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 CopyText from '@/components/CopyText.vue' import CopyText from '@/components/CopyText.vue'
import { formatDateTime } from '@/utils/datetime' import { formatDateTime } from '@/utils/datetime'
import { createSkipPriceAsin, fetchSkipPriceList } from './skip-price-api.ts' import { createSkipPriceAsin, fetchSkipPriceList } from './skip-price-api.ts'
import { toSkipPriceExportUrl } from './skip-price-export.ts'
import { skipPriceDisplayRows, type SkipPriceItem } from './skip-price-model.ts' import { skipPriceDisplayRows, type SkipPriceItem } from './skip-price-model.ts'
import { asinCountryLabel } from './asin-country.ts' import { asinCountryLabel } from './asin-country.ts'
import { createSkipPriceFilterState, toSkipPriceParams, type SkipPriceFilterState } from './skip-price-filter.ts' import { createSkipPriceFilterState, toSkipPriceParams, type SkipPriceFilterState } from './skip-price-filter.ts'
@@ -17,8 +18,10 @@ import { fetchShopManageGroups } from '../shop/shop-manage-api.ts'
import type { ShopGroupOption } from '../shop/shop-dto.ts' import type { ShopGroupOption } from '../shop/shop-dto.ts'
import OldPagination from '@/components/OldPagination.vue' import OldPagination from '@/components/OldPagination.vue'
import { useAdminSessionStore } from '@/stores/admin-session' import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
const session = useAdminSessionStore() const session = useAdminSessionStore()
const companyTab = useCompanyTabStore()
/** 仅超管需要分组维度:非超管数据由后端裁剪到本人分组,分组筛选/列一律不展示。 */ /** 仅超管需要分组维度:非超管数据由后端裁剪到本人分组,分组筛选/列一律不展示。 */
const isSuperAdmin = computed(() => session.isSuperAdmin) const isSuperAdmin = computed(() => session.isSuperAdmin)
@@ -89,7 +92,7 @@ async function onCreateGroupChange(): Promise<void> {
} }
shopNamesLoading.value = true shopNamesLoading.value = true
try { try {
shopNames.value = await fetchShopNamesByGroup(createGroupId.value) shopNames.value = await fetchShopNamesByGroup(createGroupId.value, companyTab.requestCompanyId)
} catch (error) { } catch (error) {
shopNames.value = [] shopNames.value = []
ElMessage.error(error instanceof Error ? error.message : '店铺列表加载失败') ElMessage.error(error instanceof Error ? error.message : '店铺列表加载失败')
@@ -329,8 +332,9 @@ async function submitImport(): Promise<void> {
} }
function doExport(): void { function doExport(): void {
// 带当前筛选(分组/店铺名/ASIN/国家/最低价区间)+ 公司范围导出:此前不带任何参数,导出恒为全平台全量。
const anchor = document.createElement('a') const anchor = document.createElement('a')
anchor.href = '/api/admin/skip-price-asins/export' anchor.href = toSkipPriceExportUrl(filter, companyTab.requestCompanyId)
document.body.appendChild(anchor) document.body.appendChild(anchor)
anchor.click() anchor.click()
anchor.remove() anchor.remove()
@@ -339,7 +343,7 @@ function doExport(): void {
async function loadGroups() { async function loadGroups() {
try { try {
groups.value = await fetchShopManageGroups() groups.value = await fetchShopManageGroups(companyTab.requestCompanyId)
} catch { } catch {
groups.value = [] groups.value = []
} }
@@ -348,7 +352,7 @@ async function loadGroups() {
async function load() { async function load() {
loading.value = true loading.value = true
try { try {
const result = await fetchSkipPriceList(toSkipPriceParams(filter, page.value, pageSize.value)) const result = await fetchSkipPriceList(toSkipPriceParams(filter, page.value, pageSize.value, 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
@@ -386,6 +390,11 @@ function goJump() {
changePage(Math.min(Math.max(n, 1), totalPages.value)) changePage(Math.min(Math.max(n, 1), totalPages.value))
} }
// 切公司 = 重新取数:列表与分组下拉共用这一个 watch(少一个 = 那半边的 tab 是装饰品)。
// groupId 与 shopName 必须一起清:上一家选中的分组/店铺名在新一家的可见集与候选字典里根本不存在,
// 留着会把切 tab 后的首屏筛成空列表(请求、后端、权限三处都没错,最难查的那一型)。
watch(() => companyTab.activeId, () => { filter.groupId = null; filter.shopName = ''; void loadGroups(); void load() })
onMounted(() => { onMounted(() => {
void loadGroups() void loadGroups()
void load() void load()
@@ -26,6 +26,10 @@ export interface AsinListParams {
country?: string country?: string
/** 顺序翻页游标(上一页返回的 nextLastId):传了就忽略 page 偏移,走 keyset。 */ /** 顺序翻页游标(上一页返回的 nextLastId):传了就忽略 page 偏移,走 keyset。 */
lastId?: number lastId?: number
/** 公司 tab 的值。normalizeAsinPageParams 是白名单构造、**故意不点名它**
*(归一化函数不认识公司这一维,也不许认识:公司值由发送口自己下传),
* 所以取数函数必须从原始入参读这一项,读归一化结果会拿到 undefined。 */
companyId?: number | null
} }
/** 序列化到 Java 分页接口的查询参数(snake_case)。 */ /** 序列化到 Java 分页接口的查询参数(snake_case)。 */
@@ -40,6 +44,8 @@ export interface AsinPageQuery {
country?: string country?: string
/** 顺序翻页游标(keyset):传了就忽略 page 偏移。 */ /** 顺序翻页游标(keyset):传了就忽略 page 偏移。 */
last_id?: number last_id?: number
/** 公司 tab:与 Java 各列表接口的 `@RequestParam(name = "company_id")` 逐字对齐。 */
company_id?: number
} }
function finiteInt(value: unknown): number | null { function finiteInt(value: unknown): number | null {
@@ -10,7 +10,11 @@ export const DEDUPE_GROUPS_ENDPOINT = '/api/admin/shop-manages/groups'
export async function fetchDedupeTotalList(params: Partial<AsinListParams> = {}): Promise<DedupeTotalPageResult> { export async function fetchDedupeTotalList(params: Partial<AsinListParams> = {}): Promise<DedupeTotalPageResult> {
const normalized = normalizeAsinPageParams(params) const normalized = normalizeAsinPageParams(params)
const { data } = await http.get<unknown>(DEDUPE_TOTAL_ENDPOINT, { params: toAsinPageQuery(normalized) }) // normalizeAsinPageParams 是白名单构造(不点名 companyId),所以公司值只能从原始 params 读:
// 写成 normalized.companyId 是 TS 绿、运行时恒 undefined,请求里根本没这个参数。
const query = toAsinPageQuery(normalized)
if (params.companyId != null) query.company_id = params.companyId
const { data } = await http.get<unknown>(DEDUPE_TOTAL_ENDPOINT, { params: query })
return parseDedupeTotalPage(data) return parseDedupeTotalPage(data)
} }
@@ -32,7 +36,8 @@ export async function deleteDedupeTotal(id: number): Promise<void> {
} }
/** 加载数据权限分组选项:GET /shop-manages/groups → {id,name,leaderUserId}[]。 */ /** 加载数据权限分组选项:GET /shop-manages/groups → {id,name,leaderUserId}[]。 */
export async function fetchDedupeTotalGroups(): Promise<DedupeGroupOption[]> { export async function fetchDedupeTotalGroups(companyId?: number | null): Promise<DedupeGroupOption[]> {
const { data } = await http.get<unknown>(DEDUPE_GROUPS_ENDPOINT) // null 由发送口自己丢掉(不依赖 axios 丢 null):非超管/未选 tab 时不发 company_id,后端按会话裁剪。
const { data } = await http.get<unknown>(DEDUPE_GROUPS_ENDPOINT, { params: companyId != null ? { company_id: companyId } : {} })
return parseDedupeGroupOptionList(data) return parseDedupeGroupOptionList(data)
} }
@@ -20,23 +20,33 @@ export function exportStageHint(stage: DedupeExportStage): string | undefined {
} }
} }
/** 按导出可用筛选(用户名/日期区间/分组/国家)构建查询串;空白/非法条件不下发。 */ /** 按导出可用筛选(用户名/日期区间/分组/国家)构建查询参数;空白/非法条件不下发。
export function buildDedupeExportQuery(state: DedupeTotalFilterState): string { * 公司 tab 也在参数里:导出与列表必须同一个范围,否则「tab 筛了表格、导出给全量」就是越权泄露。 */
const params = new URLSearchParams() export function buildDedupeExportParams(
state: DedupeTotalFilterState,
companyId?: number | null,
): Record<string, string> {
const params: Record<string, string> = {}
const username = (state.username || '').trim() const username = (state.username || '').trim()
const country = (state.country || '').trim() const country = (state.country || '').trim()
if (username) params.set('username', username) if (username) params.username = username
if (country) params.set('country', country) if (country) params.country = country
const startDate = validIsoDateOrUndefined(state.startDate) const startDate = validIsoDateOrUndefined(state.startDate)
const endDate = validIsoDateOrUndefined(state.endDate) const endDate = validIsoDateOrUndefined(state.endDate)
if (startDate) params.set('start_date', startDate) if (startDate) params.start_date = startDate
if (endDate) params.set('end_date', endDate) if (endDate) params.end_date = endDate
if (typeof state.groupId === 'number' && state.groupId >= 1) params.set('group_id', String(state.groupId)) if (typeof state.groupId === 'number' && state.groupId >= 1) params.group_id = String(state.groupId)
return params.toString() if (companyId != null) params.company_id = String(companyId)
return params
}
/** 按导出可用筛选构建查询串;条件编码与 URLSearchParams 一致。 */
export function buildDedupeExportQuery(state: DedupeTotalFilterState, companyId?: number | null): string {
return new URLSearchParams(buildDedupeExportParams(state, companyId)).toString()
} }
/** 导出下载地址:浏览器直接访问该 URL 触发流式下载。 */ /** 导出下载地址:浏览器直接访问该 URL 触发流式下载。 */
export function toExportUrl(state: DedupeTotalFilterState): string { export function toExportUrl(state: DedupeTotalFilterState, companyId?: number | null): string {
const query = buildDedupeExportQuery(state) const query = buildDedupeExportQuery(state, companyId)
return query ? `${DEDUPE_TOTAL_EXPORT_ENDPOINT}?${query}` : DEDUPE_TOTAL_EXPORT_ENDPOINT return query ? `${DEDUPE_TOTAL_EXPORT_ENDPOINT}?${query}` : DEDUPE_TOTAL_EXPORT_ENDPOINT
} }
@@ -31,9 +31,11 @@ export function toDedupeListParams(
page: number, page: number,
pageSize: number, pageSize: number,
lastId?: number | null, lastId?: number | null,
companyId?: number | null,
): AsinListParams { ): AsinListParams {
const params: AsinListParams = { page, pageSize } const params: AsinListParams = { page, pageSize }
if (typeof lastId === 'number' && lastId > 0) params.lastId = lastId if (typeof lastId === 'number' && lastId > 0) params.lastId = lastId
if (companyId != null) params.companyId = companyId
const keyword = (state.keyword || '').trim() const keyword = (state.keyword || '').trim()
const username = (state.username || '').trim() const username = (state.username || '').trim()
const country = (state.country || '').trim() const country = (state.country || '').trim()
@@ -11,11 +11,11 @@ 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 = ''): Promise<ProductCategoryListResult> { export async function fetchProductCategoryTree(keyword = '', companyId?: number | null): Promise<ProductCategoryListResult> {
const trimmed = keyword.trim() const trimmed = keyword.trim()
const { data } = await http.get<unknown>(PRODUCT_CATEGORY_ENDPOINT, { const params: Record<string, string | number> = trimmed ? { keyword: trimmed } : {}
params: trimmed ? { keyword: trimmed } : {}, if (companyId != null) params.company_id = companyId
}) const { data } = await http.get<unknown>(PRODUCT_CATEGORY_ENDPOINT, { params })
return parseProductCategoryList(data) return parseProductCategoryList(data)
} }
@@ -24,10 +24,12 @@ 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)
} }
@@ -45,9 +47,11 @@ 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 }
@@ -2,9 +2,12 @@
export const PRODUCT_CATEGORY_EXPORT_ENDPOINT = '/api/admin/product-categories/export' export const PRODUCT_CATEGORY_EXPORT_ENDPOINT = '/api/admin/product-categories/export'
/** 导出下载地址:浏览器直接访问该 URL 触发流式下载。 */ /** 导出下载地址:浏览器直接访问该 URL 触发流式下载。
export function buildProductCategoryExportUrl(keyword: string): string { * company_id 与列表同源:导出走的是同一个服务口径,不带它就是把别家类目写进同一份 XLSX。 */
export function buildProductCategoryExportUrl(keyword: string, companyId?: number | null): string {
const params: string[] = []
const trimmed = (keyword || '').trim() const trimmed = (keyword || '').trim()
if (!trimmed) return PRODUCT_CATEGORY_EXPORT_ENDPOINT if (trimmed) params.push(`keyword=${encodeURIComponent(trimmed)}`)
return `${PRODUCT_CATEGORY_EXPORT_ENDPOINT}?keyword=${encodeURIComponent(trimmed)}` if (companyId != null) params.push(`company_id=${companyId}`)
return params.length ? `${PRODUCT_CATEGORY_EXPORT_ENDPOINT}?${params.join('&')}` : PRODUCT_CATEGORY_EXPORT_ENDPOINT
} }
@@ -13,7 +13,11 @@ export const QUERY_ASIN_ENDPOINT = '/api/admin/query-asins'
export async function fetchQueryAsinList(params: Partial<QueryAsinListParams> = {}): Promise<QueryAsinPageResult> { export async function fetchQueryAsinList(params: Partial<QueryAsinListParams> = {}): Promise<QueryAsinPageResult> {
const normalized = normalizeQueryAsinParams(params) const normalized = normalizeQueryAsinParams(params)
const { data } = await http.get<unknown>(QUERY_ASIN_ENDPOINT, { params: toQueryAsinQuery(normalized) }) // normalizeQueryAsinParams 是白名单构造(不点名 companyId)⇒ 公司值必须从原始 params 读,
// 从 normalized 读是 undefined:请求发了、tab 画了、参数没有。
const query = toQueryAsinQuery(normalized)
if (params.companyId != null) query.company_id = params.companyId
const { data } = await http.get<unknown>(QUERY_ASIN_ENDPOINT, { params: query })
return parseQueryAsinPage(data) return parseQueryAsinPage(data)
} }
@@ -34,12 +38,13 @@ export async function createQueryAsin(payload: QueryAsinCreatePayload): Promise<
return message || '保存成功' return message || '保存成功'
} }
/** 按分组加载店铺名列表(对齐 admin.js loadAsinShopNameOptions:100/页翻页聚合去重,上限 20 页)。 */ /** 按分组加载店铺名列表(对齐 admin.js loadAsinShopNameOptions:100/页翻页聚合去重,上限 20 页)。
export async function fetchShopNamesByGroup(groupId: number): Promise<string[]> { * companyId 透传给 /shop-manages:不传的话候选字典是全平台的,建号弹窗能选到别家的店铺名。 */
export async function fetchShopNamesByGroup(groupId: number, companyId?: number | null): Promise<string[]> {
const names: string[] = [] const names: string[] = []
const seen = new Set<string>() const seen = new Set<string>()
for (let page = 1; page <= 20; page += 1) { for (let page = 1; page <= 20; page += 1) {
const result = await fetchShopManageList({ page, pageSize: 100, groupId }) const result = await fetchShopManageList({ page, pageSize: 100, groupId, companyId })
for (const shop of result.items) { for (const shop of result.items) {
const name = (shop.shopName || '').trim() const name = (shop.shopName || '').trim()
if (name && !seen.has(name)) { if (name && !seen.has(name)) {
@@ -3,22 +3,32 @@ import { normalizeQueryAsinCountry, type QueryAsinFilterState } from './query-as
export const QUERY_ASIN_EXPORT_ENDPOINT = '/api/admin/query-asins/export' export const QUERY_ASIN_EXPORT_ENDPOINT = '/api/admin/query-asins/export'
/** 按导出可用筛选(分组/店铺名/ASIN/国家)构建查询串;空白/非法条件不下发,避免导出范围被误解。 */ /** 按导出可用筛选(分组/店铺名/ASIN/国家)构建查询参数;空白/非法条件不下发,避免导出范围被误解。
export function buildQueryAsinExportQuery(state: QueryAsinFilterState): string { * 公司 tab 也在参数里:导出与列表必须同一个范围,否则「tab 筛了表格、导出给全量」就是越权泄露。 */
const params = new URLSearchParams() export function buildQueryAsinExportParams(
state: QueryAsinFilterState,
companyId?: number | null,
): Record<string, string> {
const params: Record<string, string> = {}
const groupId = state.groupId const groupId = state.groupId
if (typeof groupId === 'number' && groupId >= 1) params.set('group_id', String(Math.floor(groupId))) if (typeof groupId === 'number' && groupId >= 1) params.group_id = String(Math.floor(groupId))
const shopName = (state.shopName || '').trim() const shopName = (state.shopName || '').trim()
if (shopName) params.set('shop_name', shopName) if (shopName) params.shop_name = shopName
const asin = (state.asin || '').trim() const asin = (state.asin || '').trim()
if (asin) params.set('asin', asin) if (asin) params.asin = asin
const country = normalizeQueryAsinCountry(state.country) const country = normalizeQueryAsinCountry(state.country)
if (country) params.set('country', country) if (country) params.country = country
return params.toString() if (companyId != null) params.company_id = String(companyId)
return params
} }
/** 导出下载地址:浏览器直接访问该 URL 触发流式下载;无筛选时为全量导出。 */ /** 按导出可用筛选构建查询串;条件编码与 URLSearchParams 一致。 */
export function toQueryAsinExportUrl(state: QueryAsinFilterState): string { export function buildQueryAsinExportQuery(state: QueryAsinFilterState, companyId?: number | null): string {
const query = buildQueryAsinExportQuery(state) return new URLSearchParams(buildQueryAsinExportParams(state, companyId)).toString()
}
/** 导出下载地址:浏览器直接访问该 URL 触发流式下载;无筛选时为该公司(或全平台)的导出。 */
export function toQueryAsinExportUrl(state: QueryAsinFilterState, companyId?: number | null): string {
const query = buildQueryAsinExportQuery(state, companyId)
return query ? `${QUERY_ASIN_EXPORT_ENDPOINT}?${query}` : QUERY_ASIN_EXPORT_ENDPOINT return query ? `${QUERY_ASIN_EXPORT_ENDPOINT}?${query}` : QUERY_ASIN_EXPORT_ENDPOINT
} }
@@ -21,6 +21,8 @@ export interface QueryAsinListParams {
shopName?: string shopName?: string
asin?: string asin?: string
country?: string country?: string
/** 公司 tab 的值。normalizeQueryAsinParams 是白名单构造、不点名它 ⇒ 发送口必须从原始入参读。 */
companyId?: number | null
} }
export interface QueryAsinQuery { export interface QueryAsinQuery {
@@ -30,6 +32,8 @@ export interface QueryAsinQuery {
shop_name?: string shop_name?: string
asin?: string asin?: string
country?: string country?: string
/** 下划线形:与 Java `@RequestParam(name = "company_id")` 逐字对齐。 */
company_id?: number
} }
export function createQueryAsinFilterState(): QueryAsinFilterState { export function createQueryAsinFilterState(): QueryAsinFilterState {
@@ -12,7 +12,11 @@ export const SKIP_PRICE_ENDPOINT = '/api/admin/skip-price-asins'
export async function fetchSkipPriceList(params: Partial<SkipPriceListParams> = {}): Promise<SkipPricePageResult> { export async function fetchSkipPriceList(params: Partial<SkipPriceListParams> = {}): Promise<SkipPricePageResult> {
const normalized = normalizeSkipPriceParams(params) const normalized = normalizeSkipPriceParams(params)
const { data } = await http.get<unknown>(SKIP_PRICE_ENDPOINT, { params: toSkipPriceQuery(normalized) }) // normalizeSkipPriceParams 是白名单构造(不点名 companyId),所以公司值只能从原始 params 读:
// 写成 normalized.companyId 是 TS 绿、运行时恒 undefined,请求照发而参数没有。
const query = toSkipPriceQuery(normalized)
if (params.companyId != null) query.company_id = params.companyId
const { data } = await http.get<unknown>(SKIP_PRICE_ENDPOINT, { params: query })
return parseSkipPricePage(data) return parseSkipPricePage(data)
} }
@@ -0,0 +1,40 @@
/** 最低价 ASIN 导出 URL 构建:按当前筛选下发 group_id/shop_name/asin/country/最低价区间
* (对齐 Java SkipPriceAsinController export 的 snake_case @RequestParam),纯逻辑。 */
import { normalizeAsinCountry } from './asin-country.ts'
import { normalizePriceInput, type SkipPriceFilterState } from './skip-price-filter.ts'
export const SKIP_PRICE_EXPORT_ENDPOINT = '/api/admin/skip-price-asins/export'
/** 按导出可用筛选构建查询参数;空白/非法条件不下发。
* 公司 tab 也在参数里:导出与列表必须同一个范围,否则「tab 筛了表格、导出给全量」就是越权泄露。 */
export function buildSkipPriceExportParams(
state: SkipPriceFilterState,
companyId?: number | null,
): Record<string, string> {
const params: Record<string, string> = {}
const groupId = state.groupId
if (typeof groupId === 'number' && groupId >= 1) params.group_id = String(Math.floor(groupId))
const shopName = (state.shopName || '').trim()
if (shopName) params.shop_name = shopName
const asin = (state.asin || '').trim()
if (asin) params.asin = asin
const country = normalizeAsinCountry(state.country)
if (country) params.country = country
const minimumPriceFrom = normalizePriceInput(state.minimumPriceFrom)
if (minimumPriceFrom !== null) params.minimum_price_from = String(minimumPriceFrom)
const minimumPriceTo = normalizePriceInput(state.minimumPriceTo)
if (minimumPriceTo !== null) params.minimum_price_to = String(minimumPriceTo)
if (companyId != null) params.company_id = String(companyId)
return params
}
/** 按导出可用筛选构建查询串;条件编码与 URLSearchParams 一致。 */
export function buildSkipPriceExportQuery(state: SkipPriceFilterState, companyId?: number | null): string {
return new URLSearchParams(buildSkipPriceExportParams(state, companyId)).toString()
}
/** 导出下载地址:浏览器直接访问该 URL 触发流式下载;无筛选时导出该范围全量。 */
export function toSkipPriceExportUrl(state: SkipPriceFilterState, companyId?: number | null): string {
const query = buildSkipPriceExportQuery(state, companyId)
return query ? `${SKIP_PRICE_EXPORT_ENDPOINT}?${query}` : SKIP_PRICE_EXPORT_ENDPOINT
}
@@ -25,6 +25,8 @@ export interface SkipPriceListParams {
country?: string country?: string
minimumPriceFrom?: number | null minimumPriceFrom?: number | null
minimumPriceTo?: number | null minimumPriceTo?: number | null
/** 公司 tab 的值。normalizeSkipPriceParams 是白名单构造、不点名它 ⇒ 由 toSkipPriceParams 显式补回。 */
companyId?: number | null
} }
export interface SkipPriceQuery { export interface SkipPriceQuery {
@@ -36,6 +38,8 @@ export interface SkipPriceQuery {
country?: string country?: string
minimum_price_from?: number minimum_price_from?: number
minimum_price_to?: number minimum_price_to?: number
/** 下划线形:与 Java `@RequestParam(name = "company_id")` 逐字对齐。 */
company_id?: number
} }
export function createSkipPriceFilterState(): SkipPriceFilterState { export function createSkipPriceFilterState(): SkipPriceFilterState {
@@ -91,8 +95,9 @@ export function toSkipPriceParams(
state: SkipPriceFilterState, state: SkipPriceFilterState,
page: number, page: number,
pageSize: number, pageSize: number,
companyId?: number | null,
): SkipPriceListParams { ): SkipPriceListParams {
return normalizeSkipPriceParams({ const params = normalizeSkipPriceParams({
page, page,
pageSize, pageSize,
groupId: state.groupId, groupId: state.groupId,
@@ -102,6 +107,8 @@ export function toSkipPriceParams(
minimumPriceFrom: normalizePriceInput(state.minimumPriceFrom), minimumPriceFrom: normalizePriceInput(state.minimumPriceFrom),
minimumPriceTo: normalizePriceInput(state.minimumPriceTo), minimumPriceTo: normalizePriceInput(state.minimumPriceTo),
}) })
if (companyId != null) params.companyId = companyId
return params
} }
/** 前端查询参数 → Java 查询参数;与 SkipPriceAsinController @RequestParam(snake) 对齐,仅下发非空字段。 */ /** 前端查询参数 → Java 查询参数;与 SkipPriceAsinController @RequestParam(snake) 对齐,仅下发非空字段。 */
@@ -12,6 +12,8 @@ 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 {
@@ -29,7 +31,11 @@ function toQuery(query: InvalidAsinQuery): Record<string, string | number> {
} }
export async function fetchInvalidAsinPage(query: InvalidAsinQuery): Promise<InvalidAsinPageResult> { export async function fetchInvalidAsinPage(query: InvalidAsinQuery): Promise<InvalidAsinPageResult> {
const { data } = await http.get<unknown>(INVALID_ASIN_ENDPOINT, { params: toQuery(query) }) // 公司值落在 toQuery 之后、发请求之前的唯一一处:toQuery 是白名单构造(只点名 page/data_value/brand/group_id),
// 所以这里必须从原始 query 读 companyId——从 toQuery 的结果里读是 undefined,请求照发、参数没有。
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)
} }
@@ -6,6 +6,7 @@
*/ */
import { computed, onMounted, reactive, ref, watch } from 'vue' import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useAdminSessionStore } from '@/stores/admin-session' import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
import type { DuplicateItem, DuplicateOccurrence, DuplicateMetrics, DuplicateShop } from './duplicate-model.ts' import type { DuplicateItem, DuplicateOccurrence, DuplicateMetrics, DuplicateShop } from './duplicate-model.ts'
import { fetchDuplicateConsole, fetchDuplicateLedger, requestDuplicateExportBlob, type LedgerSortKey } from './duplicate-console-api.ts' import { fetchDuplicateConsole, fetchDuplicateLedger, requestDuplicateExportBlob, type LedgerSortKey } from './duplicate-console-api.ts'
import { aggregateDrawerRows, drawerSummaryOf, dupWithinGroup, indexShopGroups, type DrawerAggRow, type DrawerSummary, type ShopGroups } from './duplicate-console-logic.ts' import { aggregateDrawerRows, drawerSummaryOf, dupWithinGroup, indexShopGroups, type DrawerAggRow, type DrawerSummary, type ShopGroups } from './duplicate-console-logic.ts'
@@ -24,6 +25,7 @@ const filter = reactive({ asin: '', shop: '', group: '', country: '', dateFrom:
/** 角色范围:超管可看全部分组店铺并可跨分组筛选;管理员数据已由后端裁剪到自己分组,无需分组筛选。 */ /** 角色范围:超管可看全部分组店铺并可跨分组筛选;管理员数据已由后端裁剪到自己分组,无需分组筛选。 */
const session = useAdminSessionStore() const session = useAdminSessionStore()
const companyTab = useCompanyTabStore()
const isSuper = computed(() => session.isSuperAdmin) const isSuper = computed(() => session.isSuperAdmin)
const activeTab = ref<Tab>('dup') const activeTab = ref<Tab>('dup')
@@ -207,7 +209,7 @@ async function loadConsole() {
loading.value = true loading.value = true
loadError.value = '' loadError.value = ''
try { try {
consoleData.value = await fetchDuplicateConsole({ view: '', ...activeFilterParams() }) consoleData.value = await fetchDuplicateConsole({ view: '', ...activeFilterParams() }, companyTab.requestCompanyId)
shopGroups.value = indexShopGroups(orderedShops.value) shopGroups.value = indexShopGroups(orderedShops.value)
if (groupStats.value.length && !groupStats.value.some((group) => group.name === selectedGroup.value)) { if (groupStats.value.length && !groupStats.value.some((group) => group.name === selectedGroup.value)) {
selectedGroup.value = groupChips.value[0] ? groupChips.value[0].name : '' selectedGroup.value = groupChips.value[0] ? groupChips.value[0].name : ''
@@ -227,7 +229,14 @@ async function loadLedger(page: number, resetSort = false) {
sortState.key = 'earliest' sortState.key = 'earliest'
sortState.dir = 'asc' sortState.dir = 'asc'
} }
const result = await fetchDuplicateLedger({ view: '', ...activeFilterParams() }, page, ledgerPageSize.value, sortState.key, sortState.dir) const result = await fetchDuplicateLedger(
{ view: '', ...activeFilterParams() },
page,
ledgerPageSize.value,
sortState.key,
sortState.dir,
companyTab.requestCompanyId,
)
ledgerItems.value = result.items ledgerItems.value = result.items
ledgerTotal.value = result.total ledgerTotal.value = result.total
ledgerPage.value = result.page ledgerPage.value = result.page
@@ -374,7 +383,7 @@ async function exportXlsx() {
params.shopName = selectedGroup.value params.shopName = selectedGroup.value
} }
try { try {
const blob = await requestDuplicateExportBlob({ view, ...params }, view) const blob = await requestDuplicateExportBlob({ view, ...params }, view, companyTab.requestCompanyId)
saveBlob(blob, `店铺数据_${activeTab.value === 'ledger' ? '台账' : '撞款'}_${new Date().toISOString().slice(0, 10)}.xlsx`) saveBlob(blob, `店铺数据_${activeTab.value === 'ledger' ? '台账' : '撞款'}_${new Date().toISOString().slice(0, 10)}.xlsx`)
toast('已导出 Excel') toast('已导出 Excel')
} catch (error) { } catch (error) {
@@ -396,6 +405,11 @@ function siteColor(code: string): string {
return map[code.toUpperCase()] || '#98A1B1' return map[code.toUpperCase()] || '#98A1B1'
} }
// 切公司 = 重新取数。店铺/分组两个筛选项的候选字典本身就按公司收窄(/duplicate-check-console 的 shops/groups),
// 留着上一家选中的值会把新一家首屏筛成空页;分组范围(scope)一并回全店,否则切到没有分组的公司在
// loadConsole 的重挑分支(groupStats 为空时不触发)里留着一个不属于本公司的 selectedGroup。
watch(() => companyTab.activeId, () => { filter.shop = ''; filter.group = ''; selectedGroup.value = ''; scope.value = 'global'; void loadConsole(); void loadLedger(1) })
onMounted(() => { onMounted(() => {
loadConsole() loadConsole()
// 台账 Tab 计数打开即显示:挂载时预取第一页拿 total(对齐 reference 渲染即见台账条数)。 // 台账 Tab 计数打开即显示:挂载时预取第一页拿 total(对齐 reference 渲染即见台账条数)。
@@ -2,7 +2,7 @@
import { formatDateTime } from '@/utils/datetime' import { formatDateTime } from '@/utils/datetime'
/** 店铺数据记录页 · 像素复刻旧版 admin.html panel-shop-data-crawl-tasks(自绘:form-box 筛选[h4 筛选条件] + panel-box toolbar[全选/批量下载/权限配置/汇总] + 每店卡片网格 + 旧式分页(店铺级+卡片级 9/页))。 /** 店铺数据记录页 · 像素复刻旧版 admin.html panel-shop-data-crawl-tasks(自绘:form-box 筛选[h4 筛选条件] + panel-box toolbar[全选/批量下载/权限配置/汇总] + 每店卡片网格 + 旧式分页(店铺级+卡片级 9/页))。
* 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 { asinCountryLabel } from '../asin/asin-country.ts' import { asinCountryLabel } from '../asin/asin-country.ts'
import { createShopDataFilter, type ShopDataFilter } from './shop-data-filter.ts' import { createShopDataFilter, type ShopDataFilter } from './shop-data-filter.ts'
@@ -25,9 +25,11 @@ import {
toggleShopDataSelection, toggleShopDataSelection,
} from './shop-data-selection.ts' } from './shop-data-selection.ts'
import { useAdminSessionStore } from '@/stores/admin-session' import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
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 groups = ref<ShopDataTaskGroup[]>([]) const groups = ref<ShopDataTaskGroup[]>([])
const totalShops = ref(0) const totalShops = ref(0)
@@ -120,7 +122,7 @@ function toFilter(): ShopDataFilter {
async function load() { async function load() {
loading.value = true loading.value = true
try { try {
const result = await fetchShopDataTaskList(toFilter(), page.value, pageSize.value) const result = await fetchShopDataTaskList(toFilter(), page.value, pageSize.value, companyTab.requestCompanyId)
groups.value = result.items groups.value = result.items
totalShops.value = result.total totalShops.value = result.total
page.value = result.page page.value = result.page
@@ -296,6 +298,11 @@ async function savePermission() {
const grantedCount = computed(() => grantedUserIds(permissionItems.value).length) const grantedCount = computed(() => grantedUserIds(permissionItems.value).length)
// 切公司 = 重新取数,并把上一家的两处遗留一起清掉:
// ① 店铺名/分组名是自由文本筛选项,上一家填的值在新一家的可见集里不存在 ⇒ 首屏筛成空页;
// ② 勾选集住的是 resultId,跨公司留着会让「批量下载」把别家店铺的结果文件打进同一个 zip。
watch(() => companyTab.activeId, () => { filter.shopName = ''; filter.groupName = ''; selection.value = createShopDataSelection(); page.value = 1; cardPage.value = 1; void load() })
onMounted(load) onMounted(load)
</script> </script>
@@ -33,10 +33,15 @@ function toConsoleQuery(filter: DuplicateFilter): Record<string, string> {
export type LedgerSortKey = 'asin' | 'brand' | 'store_count' | 'record_count' | 'earliest' | 'latest' export type LedgerSortKey = 'asin' | 'brand' | 'store_count' | 'record_count' | 'earliest' | 'latest'
/** 加载撞款控制台快照:GET /duplicate-check-console。 */ /** 加载撞款控制台快照:GET /duplicate-check-console。 */
export async function fetchDuplicateConsole(filter: DuplicateFilter): Promise<DuplicateConsole> { export async function fetchDuplicateConsole(
const { data } = await http.get<unknown>(`${DUPLICATE_CHECK_ENDPOINT}/duplicate-check-console`, { filter: DuplicateFilter,
params: toConsoleQuery(filter), companyId?: number | null,
}) ): Promise<DuplicateConsole> {
// toConsoleQuery 是白名单构造(只点名 asin/shop_name/group/country/site/date_*),
// 公司值只许落在本函数自己的 companyId 形参上。
const query: Record<string, string | number> = toConsoleQuery(filter)
if (companyId != null) query.company_id = companyId
const { data } = await http.get<unknown>(`${DUPLICATE_CHECK_ENDPOINT}/duplicate-check-console`, { params: query })
return parseDuplicateConsole(data) return parseDuplicateConsole(data)
} }
@@ -47,18 +52,26 @@ export async function fetchDuplicateLedger(
pageSize: number, pageSize: number,
sortKey: LedgerSortKey | '', sortKey: LedgerSortKey | '',
sortDir: 'asc' | 'desc', sortDir: 'asc' | 'desc',
companyId?: number | null,
): Promise<LedgerPage> { ): Promise<LedgerPage> {
const params: Record<string, string | number> = { ...toConsoleQuery(filter), page, page_size: pageSize } const params: Record<string, string | number> = { ...toConsoleQuery(filter), page, page_size: pageSize }
if (sortKey) params.sort_key = sortKey if (sortKey) params.sort_key = sortKey
params.sort_dir = sortDir params.sort_dir = sortDir
if (companyId != null) params.company_id = companyId
const { data } = await http.get<unknown>(`${DUPLICATE_CHECK_ENDPOINT}/duplicate-check-ledger`, { params }) const { data } = await http.get<unknown>(`${DUPLICATE_CHECK_ENDPOINT}/duplicate-check-ledger`, { params })
return parseLedgerPage(data) return parseLedgerPage(data)
} }
/** 导出 Excel(撞款 view=monitor / 台账 view=all):GET /duplicate-check-export → xlsx Blob。 */ /** 导出 Excel(撞款 view=monitor / 台账 view=all):GET /duplicate-check-export → xlsx Blob。 */
export async function requestDuplicateExportBlob(filter: DuplicateFilter, view: string): Promise<Blob> { export async function requestDuplicateExportBlob(
filter: DuplicateFilter,
view: string,
companyId?: number | null,
): Promise<Blob> {
const itemsQuery = toDuplicateItemsQuery({ ...filter, view }, 1, 100)
if (companyId != null) itemsQuery.company_id = companyId
const { data } = await http.get<Blob>(`${DUPLICATE_CHECK_ENDPOINT}/duplicate-check-export`, { const { data } = await http.get<Blob>(`${DUPLICATE_CHECK_ENDPOINT}/duplicate-check-export`, {
params: toDuplicateItemsQuery({ ...filter, view }, 1, 100), params: itemsQuery,
responseType: 'blob', responseType: 'blob',
}) })
return data return data
@@ -27,6 +27,7 @@ export interface DuplicateItemsQuery {
site?: string site?: string
date_from?: string date_from?: string
date_to?: string date_to?: string
company_id?: number
} }
function textOrUndefined(value: unknown): string | undefined { function textOrUndefined(value: unknown): string | undefined {
@@ -14,10 +14,13 @@ export async function fetchShopDataTaskList(
filter: ShopDataFilter, filter: ShopDataFilter,
page: number, page: number,
pageSize: number, pageSize: number,
companyId?: number | null,
): Promise<ShopDataTaskPageResult> { ): Promise<ShopDataTaskPageResult> {
const { data } = await http.get<unknown>(SHOP_DATA_CRAWL_TASKS_ENDPOINT, { // toShopDataQuery 是白名单构造(只点名 shop_name/group_name/country/created_*),
params: toShopDataQuery(filter, page, pageSize), // 公司值只许落在本函数自己的 companyId 形参上。
}) const query = toShopDataQuery(filter, page, pageSize)
if (companyId != null) query.company_id = companyId
const { data } = await http.get<unknown>(SHOP_DATA_CRAWL_TASKS_ENDPOINT, { params: query })
return parseShopDataTaskPage(data) return parseShopDataTaskPage(data)
} }
@@ -23,6 +23,7 @@ export interface ShopDataQuery {
country?: string country?: string
created_from?: string created_from?: string
created_to?: string created_to?: string
company_id?: number
} }
export function createShopDataFilter(): ShopDataFilter { export function createShopDataFilter(): ShopDataFilter {
+8 -8
View File
@@ -18,13 +18,13 @@ export interface AdminPageDef extends AdminPageMeta {
/** 业务域路由注册表(任务 8):首批 account 域;后续按业务域在此登记页面。 */ /** 业务域路由注册表(任务 8):首批 account 域;后续按业务域在此登记页面。 */
export const adminPages: AdminPageDef[] = [ export const adminPages: AdminPageDef[] = [
{ path: 'account/users', menuKey: 'admin_users', title: '用户管理', 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: '菜单管理', 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: '店铺撞款监控', 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: false, 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') },
@@ -34,12 +34,12 @@ export const adminPages: AdminPageDef[] = [
{ 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: '店铺数据记录', 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: '数据去重总数据', 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数据', load: () => import('@/pages/asin/AsinInvalidPage.vue') }, { path: 'asin-center/invalid', menuKey: 'admin_invalid_asin_data', title: '不符合ASIN数据', companyScoped: true, load: () => import('@/pages/asin/AsinInvalidPage.vue') },
{ path: 'asin-center/query', menuKey: 'admin_query_asin', title: '查询ASIN', 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: false, load: () => import('@/pages/asin/ProductCategoryPage.vue') }, { path: 'asin-center/categories', menuKey: 'admin_product_categories', title: '商品类目', companyScoped: true, load: () => import('@/pages/asin/ProductCategoryPage.vue') },
{ path: 'asin-center/skip-price', menuKey: 'admin_skip_price_asin', title: '最低价ASIN', 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') },
] ]
export function routeOf(page: AdminPageDef): RouteRecordRaw { export function routeOf(page: AdminPageDef): RouteRecordRaw {
@@ -88,7 +88,12 @@ test('align_dup_console_role_scope_group_controls_only_super', () => {
assert.match(page, /<div v-if="isSuper" class="scope-bar">/, '分组撞款分段仅超管可见') assert.match(page, /<div v-if="isSuper" class="scope-bar">/, '分组撞款分段仅超管可见')
assert.match(page, /v-if="isSuper" class="btn btn-ghost btn-sm" type="button" @click="groupInfoVisible = true"/, '分组说明按钮仅超管可见') assert.match(page, /v-if="isSuper" class="btn btn-ghost btn-sm" type="button" @click="groupInfoVisible = true"/, '分组说明按钮仅超管可见')
const service = readSource('../backend-java/src/main/java/com/nanri/aiimage/modules/shopduplicatecheck/service/ShopDataDuplicateCheckQueryService.java') const service = readSource('../backend-java/src/main/java/com/nanri/aiimage/modules/shopduplicatecheck/service/ShopDataDuplicateCheckQueryService.java')
assert.match(service, /if \(superAdmin\) \{\s*return null;/, '超管可见范围=全量(null)') // 2026-10-05 批次 3 之后「超管全量」不再是 `if (superAdmin) return null`,而是"超管且没切公司 tab(成员集为 null)"。
// 逐字判据 + 空成员集那支一起钉:后者一旦退化成 null,第二家公司会看到全部店铺(语义由
// ShopDataDuplicateCheckCompanyScopeTest 用真调用验,这里只保证源码形状没被顺手改回去)。
assert.match(service, /if \(companyMemberIds == null\) \{\s*return null;/, '超管未切公司 tab=全量(null)')
assert.match(service, /companyMemberIds\.isEmpty\(\)\s*\?\s*new LinkedHashSet<>\(\)/,
'公司一个账号都没有=空可见集,不许退化成 null')
assert.match(service, /selectManagedShopNames\(operatorId\)/, '管理员可见范围=所管分组店铺') assert.match(service, /selectManagedShopNames\(operatorId\)/, '管理员可见范围=所管分组店铺')
}) })
@@ -17,7 +17,9 @@ const EXCEPTED_KEY = 'admin_shop_data_duplicate_check'
test('align_guide_users_matches_reference_text', () => { test('align_guide_users_matches_reference_text', () => {
const g = operationGuideFor('admin_users') const g = operationGuideFor('admin_users')
assert.ok(g) assert.ok(g)
assert.equal(g.text, '先用筛选定位账号,再编辑角色和菜单权限;删除账号会要求二次确认。') // 批次 4 起这页参与公司 tab ⇒ 原文之后追加那句 §9.3,不再逐字相等(同 group-manage 那处故意偏离)。
assert.match(g.text, /^先用筛选定位账号,再编辑角色和菜单权限;删除账号会要求二次确认。/)
assert.match(g.text, /超级管理员可用页面上方的公司 tab 切换公司/)
assert.deepEqual(g.steps, ['筛选账号', '编辑权限', '确认保存']) assert.deepEqual(g.steps, ['筛选账号', '编辑权限', '确认保存'])
}) })
@@ -85,18 +87,25 @@ test('align_guide_fallback_shape', () => {
test('guide_copy_carries_company_tab_note_for_every_scoped_page', () => { test('guide_copy_carries_company_tab_note_for_every_scoped_page', () => {
// spec §9.3:tab 会改行数观感,承载方式是既有引导文案(不新做控件)。 // spec §9.3:tab 会改行数观感,承载方式是既有引导文案(不新做控件)。
// 分母=COMPANY_SCOPED_PAGES,杜绝"加了一页忘了补文案"。 // 分母=COMPANY_SCOPED_PAGES,杜绝"加了一页忘了补文案"。
const need = COMPANY_SCOPED_PAGES.map((p) => p.menuKey) // 唯一豁免 = EXCEPTED_KEY(撞款监控不展示提示条,那句没有可挂的地方);豁免是**显式列出的**,
assert.ok(need.length >= 8, '取样集非空自检:注册表应当至少有 8 页进了 tab 范围') // 新页缺文案仍会红(operationGuideFor 对没登记的 key 返回 null ⇒ assert.ok(g) 当场红,没有兜底可糊)。
const scopedKeys = COMPANY_SCOPED_PAGES.map((p) => p.menuKey)
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(scopedKeys.includes(EXCEPTED_KEY),
'取样集前提自检:撞款监控已不在 COMPANY_SCOPED_PAGES 里,上面那道豁免就成了空豁免——把它连同 EXCEPTED_KEY 一起删掉')
for (const key of need) { for (const key of need) {
const g = operationGuideFor(key) const g = operationGuideFor(key)
assert.ok(g, `注册表页缺 guide: ${key}`) assert.ok(g, `注册表页缺 guide: ${key}`)
assert.match(g.text, /超级管理员可用页面上方的公司 tab 切换公司/, `${key} 缺 §9.3 那句`) assert.match(g.text, /超级管理员可用页面上方的公司 tab 切换公司/, `${key} 缺 §9.3 那句`)
} }
// C 类两页(spec §5):它们要的是**另一句**——"这页不参与",不是"会随 tab 变"。 // C 类页(spec §5):它们要的是**另一句**——"这页不参与",不是"会随 tab 变"。
// 分母**取注册表里显式写 companyScoped:false 的页**,不抄名单:漏写一条 ⇒ 这支在自检那句红。 // 分母**取注册表里显式写 companyScoped:false 的页**,不抄名单:漏写一条 ⇒ 这支在自检那句红。
// 批次 2 之前这里是 2 页(店铺密钥 + 商品类目),商品类目已接上公司口径 ⇒ 今天只剩 admin_shop_keys
// 一条,所以自检降到 1;再往下掉就是有人把注册表里那条 false 改成不写(不写 = 不参与但没人说)。
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 >= 2, '取样集非空自检:注册表里显式 companyScoped:false 的至少 C 类那两页') assert.ok(cClass.length >= 1, '取样集非空自检:注册表里显式 companyScoped:false 的一条都不剩了——那这句判据就是空跑')
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)
@@ -111,7 +120,7 @@ test('guide_copy_carries_company_tab_note_for_every_scoped_page', () => {
// 反向分母取 OPERATION_GUIDES 的全部 key(不是 adminPages):没带文案的页走 fallback,由下面那支单独钉。 // 反向分母取 OPERATION_GUIDES 的全部 key(不是 adminPages):没带文案的页走 fallback,由下面那支单独钉。
const withTabNote = Object.keys(OPERATION_GUIDES).filter((k) => operationGuideFor(k)!.text.includes('公司 tab 切换公司')) const withTabNote = Object.keys(OPERATION_GUIDES).filter((k) => operationGuideFor(k)!.text.includes('公司 tab 切换公司'))
assert.deepEqual(withTabNote.sort(), [...need].sort(), assert.deepEqual(withTabNote.sort(), [...need].sort(),
'tab 那句只能出现在 COMPANY_SCOPED_PAGES 那 8 页:多一页 = 把公司 tab 端给一页不参与 tab 的页') 'tab 那句只能出现在 COMPANY_SCOPED_PAGES 那 ' + need.length + ' 页:多一页 = 把公司 tab 端给一页不参与 tab 的页')
const withNotAppliedNote = Object.keys(OPERATION_GUIDES).filter((k) => operationGuideFor(k)!.text.includes('全平台共享,不按公司区分')) const withNotAppliedNote = Object.keys(OPERATION_GUIDES).filter((k) => operationGuideFor(k)!.text.includes('全平台共享,不按公司区分'))
assert.deepEqual(withNotAppliedNote.sort(), [...cClass].sort(), assert.deepEqual(withNotAppliedNote.sort(), [...cClass].sort(),
'「本页不参与」那句只能出现在注册表显式 companyScoped:false 的页:多一页 = 给了它没有的口径') '「本页不参与」那句只能出现在注册表显式 companyScoped:false 的页:多一页 = 给了它没有的口径')
@@ -4,7 +4,7 @@ import { readdirSync, statSync } from 'node:fs'
import { join } from 'node:path' import { join } from 'node:path'
import { readSource } from './helpers.ts' import { readSource } from './helpers.ts'
import { adminPages } from '../src/router/routes.ts' import { adminPages } from '../src/router/routes.ts'
import { 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'
/** 递归扫 src 下指定后缀的文件(相对路径统一正斜杠)。 /** 递归扫 src 下指定后缀的文件(相对路径统一正斜杠)。
* 不走 execSync('grep'):node 在 Windows 上把 execSync 交给 cmd.exe,那里没有 grep, * 不走 execSync('grep'):node 在 Windows 上把 execSync 交给 cmd.exe,那里没有 grep,
@@ -70,3 +70,27 @@ test('公司列表的读路径不靠 canManage 把关(把关只有两处:Tas
assert.equal(loader.includes('canManage'), false, assert.equal(loader.includes('canManage'), false,
'loadCompanies 里不许出现 canManage:列表可见性由入口剪枝和后端决定,前端再加一道就变成第三套口径') 'loadCompanies 里不许出现 canManage:列表可见性由入口剪枝和后端决定,前端再加一道就变成第三套口径')
}) })
/** 公司 tab 唯一取值口的调用签名。
* 必须带括号:光匹配标识符会把 `import { useCompanyTabStore } from '@/stores/company-tab'` 也算成消费者 ⇒
* 「import 留着、调用删了」这种变异会存活。 */
const STORE_USE_TOKEN = 'useCompanyTabStore()'
test('吃公司 tab 的页面集合恰好等于 COMPANY_SCOPED_PAGES 的 pageFiles(公司管理页永远不在其中)', () => {
// 控制方 2026-10-05:「公司管理菜单仅 admin 账号可见,不需要做公司 tab」。
// 这条是 SUPER_ADMIN_ONLY_MENU_KEYS ∩ COMPANY_SCOPED_PAGES = ∅(company-tab-wiring:687)的反向尺子:
// 那条比的是两张**清单**,这条比的是**代码真值**——有人往 CompaniesPage.vue 里塞 companyTab 时,
// 清单可以一字不改而界面已经变了。
// 范围只扫 src/pages:src/layout/CompanyTabs.vue 渲染 tab 条本身、src/stores/company-tab.ts 是定义处,
// 两者都不是「一页」,把它们算进分母会让断言变成常量自比。
const consumers = filesWithSuffix(['.vue'])
.filter((rel) => rel.startsWith('src/pages/'))
.filter((rel) => readSource(rel).includes(STORE_USE_TOKEN))
.sort()
const declared = COMPANY_SCOPED_PAGES.flatMap((entry) => entry.pageFiles).sort()
assert.ok(declared.length >= 16, `清单的 pageFiles 只剩 ${declared.length} 条 ⇒ 分母被删空,深比较会退化成空集自比`)
assert.ok(consumers.length >= 16, `真实消费者只有 ${consumers.length} 页 ⇒ 扫描谓词(${STORE_USE_TOKEN})或页面文件本身出了问题`)
assert.deepEqual(consumers, declared,
'公司 tab 的消费者与清单对不上:多出来的一页=悄悄给一页不参与隔离的页上了 tab(公司管理就属于这类),'
+ '少掉的一页=清单声明它隔离但页面根本没取值')
})
@@ -45,9 +45,12 @@ test('剪枝是纯函数且幂等(store 里会反复调用)', () => {
assert.deepEqual(pruneSuperAdminOnly(once, false), once) assert.deepEqual(pruneSuperAdminOnly(once, false), once)
}) })
test('C 类两页必须显式声明 companyScoped: false(spec §5:声明,不是遗漏)', () => { test('不参与 tab 的页必须显式声明 companyScoped: false(spec §5:声明,不是遗漏)', () => {
// 留空和 false 运行时等价,但只有 false 是"读过普查、决定不参与"的证据。 // 留空和 false 运行时等价,但只有 false 是"读过普查、决定不参与"的证据。
for (const key of ['admin_shop_keys', 'admin_product_categories']) { // 名单批次 1 是两页(店铺密钥 + 商品类目);商品类目在批次 2(2026-10-05)接上了公司口径,
// 今天只剩紫鸟令牌这一页真的是"全平台共享、与公司无关"。
// 想再往这页上加 false 的对向(把某页改回 false)不用改这里:上面那条双向对账会红。
for (const key of ['admin_shop_keys']) {
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,不能留空`)
@@ -41,42 +41,100 @@ const TASK_CENTER_SEND_LINE = 'if (companyId != null) query.company_id = company
* - 从 `function` 这个词的头起算(旧举证用的口径,比上组各多 33~36):154/147/196/238/244 与 471/726/(无)/877/(无)。 * - 从 `function` 这个词的头起算(旧举证用的口径,比上组各多 33~36):154/147/196/238/244 与 471/726/(无)/877/(无)。
* ⇒ 320 够得着自己的行(最紧 217),够不到隔壁(最紧 438,余量 **118 字符**):删掉任一处,那条 shape 就匹配不出 * ⇒ 320 够得着自己的行(最紧 217),够不到隔壁(最紧 438,余量 **118 字符**):删掉任一处,那条 shape 就匹配不出
* (不是"文件里还有别人在发"就算过)。 * (不是"文件里还有别人在发"就算过)。
* ⚠ 下面那段「拆条取样自检·负样本」只证明「窗口有界」,它跟着 `TASK_CENTER_WINDOW` 自动缩放 ⇒ **证明不了余量还在**。 * ⚠ 下面那段「拆条取样自检·负样本」只证明「窗口有界」,它跟着窗口预算自动缩放 ⇒ **证明不了余量还在**。
* 把 320 调大之前必须按第一组口径重测这五个数;api 函数体写长会先假红(fail-closed,可接受)。 * 把 320 调大之前必须按第一组口径重测这五个数;api 函数体写长会先假红(fail-closed,可接受)。
* 批次 2 起这一档改成 `SendPoint.window`(每处一个值),举证不再靠这段注释,
* 而由「窗口与真文件对平」那条用例逐处重测 own/next。
*/ */
const TASK_CENTER_WINDOW = 320 const TASK_CENTER_WINDOW = 320
/** 一个登记项 = 一个字面发送口(一函数一处、逐处一条,一条都不许并)。 */
interface SendPoint {
readonly menuKey: string
readonly file: string
/** 这一处所在函数的名字:shape 锚在 `function <fn>(` 的括号后,红点直接报到函数。 */
readonly fn: string
/** 塞键那一整行(缩进不入锚串)。整行入锚而不只锚 `company_id = companyId`:
* 评审把 `params.companyId` 改成 `normalized.companyId` 时形状判据(复评 I-2)要能红,
* 锚右半边的字面量才是举证。 */
readonly line: string
/** 从 `function <fn>(` 括号后到自己那一行的字符预算,见上面 TASK_CENTER_WINDOW 的注释。 */
readonly window: number
readonly title: string
}
/** 正则字面量转义:`line` 里带 `( ) . = { } $ [ ]` 与反引号,不转义就匹配到别处(sendArgsShape 同一把尺子)。 */
function escapeRegExp(text: string): string {
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
/** /**
* 这一页的 5 处 `company_id` 发送口(2026-10-05 修复轮 1,复评 I-1)。 * 全部 22 个字面发送口:批次 1 的任务看板 5 处 + 批次 2(控制方 2026-10-05 点名「切 tab 数据还一样」那五页)12 处
* + 批次 3(控制方 2026-10-05 点名「店铺撞款监控 店铺数据也要做隔离」那两页)4 处
* + 批次 4(控制方 2026-10-05 点名「菜单权限和用户管理也要区分公司 tab 的数据」里的用户管理)1 处。
* *
* <p>为什么从 2 条文件级钉拆成 5 条:`shape` 的求值是整文件 `RegExp.test`(不数次数), * <p>`window` 的取法:本轮实扫的 own(到自己那行的距离)+ ≥150 余量,且当同文件还有下一个同名发送口时必须
* 评审实测「删掉 5 处里的任何一处」在两条文件级钉下**双双仍为 true**——包括 brief * `window < next`。own/next 不写死在这里——下面「窗口与真文件对平」那条用例逐处从真文件重算,
* `task-10-brief.md:14` 点名的那一处(`fetchTaskCenterTaskDetail` 少带参数 ⇒ 超管在别家 tab 下按 * `own >= window`(函数体写长)或 `window >= next`(窗口够到隔壁)都当场红。</p>
* taskNo 读别家详情照样 200,这一页的护栏恰好全落在前端)。`vue-tsc` 也救不了:tsconfig 没开
* `noUnusedParameters`,删了塞键那一行、留一个没人用的形参,编译器不响。</p>
* *
* <p>选「拆条」而不是「计数」(`occurrences()` 数 api=3 / model=2):计数不回答「哪三处」, * <p>三个 `*-export.ts` 的 own 天生比 api 侧大(构造器是多行签名 + 一串前置筛选条件:625/528/827),
* 把一处重复写三遍、另一处删掉,计数照样绿;函数名锚 + 有界窗口才把判据绑到发送口自己的身份上。 * 它们的 `line` 在同文件只出现 1 次(对平闸门数得出),所以"窗口会不会够到隔壁"在这一族是空命题,
* 形状照 `admin_shop_manage` 的先例(同一个文件两条 pin,「两条各管一处取值口,不许合成一条 alternation」)。</p> * 真正的看守是「这一处脱管就没人钉」。</p>
* *
* <p>`shape` 与取样样本同源于这张表(都由 fn/window 现算),不会出现「钉改了、自检还测旧串」的漂移。</p> * <p>批次 3 的撞款控制台三个发送口把塞键行的左值各起一个名字(query / params / itemsQuery):
* 三处若逐字同行,(文件, 整行) 分组会把它们并成一组、要求钉 3 条,而「窗口够不到隔壁」这条判据
* 在同一行重复时才有意义——左值不同名既是真代码的样子,也让每条钉各自点到唯一一个发送口。</p>
*/ */
const TASK_CENTER_SEND_POINTS: ReadonlyArray<{ readonly file: string; readonly fn: string; readonly title: string }> = [ const SEND_POINTS: ReadonlyArray<SendPoint> = [
{ file: 'src/api/task-center.ts', fn: 'fetchTaskCenterOverview', title: 'GET /overview 汇总卡' }, { menuKey: 'admin_task_center', file: 'src/api/task-center.ts', fn: 'fetchTaskCenterOverview', line: TASK_CENTER_SEND_LINE, window: TASK_CENTER_WINDOW, title: 'GET /overview 汇总卡' },
{ file: 'src/api/task-center.ts', fn: 'fetchTaskCenterShopOptions', title: 'GET /shop-options 店铺候选' }, { menuKey: 'admin_task_center', file: 'src/api/task-center.ts', fn: 'fetchTaskCenterShopOptions', line: TASK_CENTER_SEND_LINE, window: TASK_CENTER_WINDOW, title: 'GET /shop-options 店铺候选' },
{ file: 'src/api/task-center.ts', fn: 'fetchTaskCenterTaskDetail', title: 'GET /tasks/detail 详情(brief 点名那一处)' }, { menuKey: 'admin_task_center', file: 'src/api/task-center.ts', fn: 'fetchTaskCenterTaskDetail', line: TASK_CENTER_SEND_LINE, window: TASK_CENTER_WINDOW, title: 'GET /tasks/detail 详情(brief 点名那一处)' },
{ file: 'src/pages/task-center/task-center-model.ts', fn: 'buildTaskQuery', title: '任务列表 query 构造器' }, { menuKey: 'admin_task_center', file: 'src/pages/task-center/task-center-model.ts', fn: 'buildTaskQuery', line: TASK_CENTER_SEND_LINE, window: TASK_CENTER_WINDOW, title: '任务列表 query 构造器' },
{ file: 'src/pages/task-center/task-center-model.ts', fn: 'buildVariantQuery', title: '变体采集 query 构造器' }, { menuKey: 'admin_task_center', file: 'src/pages/task-center/task-center-model.ts', fn: 'buildVariantQuery', line: TASK_CENTER_SEND_LINE, window: TASK_CENTER_WINDOW, title: '变体采集 query 构造器' },
{ 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-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-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-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 点名「店铺撞款监控 店铺数据也要做隔离」)。
// 撞款三处各锚一个左值名(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: 'fetchDuplicateLedger', line: 'if (companyId != null) params.company_id = companyId', window: 400, title: 'GET /duplicate-check-ledger 全部 ASIN 台账分页' },
{ menuKey: 'admin_shop_data_duplicate_check', file: 'src/pages/tasks/duplicate-console-api.ts', fn: 'requestDuplicateExportBlob', line: 'if (companyId != null) itemsQuery.company_id = companyId', window: 400, title: 'GET /duplicate-check-export 导出(不带就导全平台)' },
{ 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 的数据」)。
{ 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 处(1b ④ 那条用例按文件筛它们,沿用旧名字不漂;表只有一份,不会漂出两个口径)。 */
function sendPointShape(fn: string): RegExp { const TASK_CENTER_SEND_POINTS: ReadonlyArray<SendPoint> =
return new RegExp(`function ${fn}\\([\\s\\S]{0,${TASK_CENTER_WINDOW}}company_id\\s*=\\s*companyId\\b`) SEND_POINTS.filter((p) => p.menuKey === 'admin_task_center')
/** 一条钉 = 一个发送口:锚在自己的函数开行上,要求窗口内出现「塞键」那一整行。 */
function pointShape(p: SendPoint): RegExp {
return new RegExp(`function ${p.fn}\\([\\s\\S]{0,${p.window}}${escapeRegExp(p.line)}`)
} }
/** 正样本用的迷你源码:函数开行 + 它自己那行塞键(缩进、形状逐字照抄真实发送口)。 */ /** 正样本用的迷你源码:函数开行 + 它自己那行塞键(缩进、形状逐字照抄真实发送口)。 */
function sendPointCompliant(fn: string): string { function pointCompliant(p: SendPoint): string {
return `function ${fn}(companyId?: number | null) {\n const query: QueryParams = {}\n ${TASK_CENTER_SEND_LINE}\n` return `function ${p.fn}(companyId?: number | null) {\n const query: QueryParams = {}\n ${p.line}\n`
}
/** 同一页的取值口钉由 SEND_POINTS 现算,不许手写:手写会和表漂开(复评 I-1 拆条的初衷)。 */
function pinsFor(menuKey: string): readonly CompanyIdPin[] {
return SEND_POINTS.filter((p) => p.menuKey === menuKey).map((p) => ({
file: p.file,
shape: pointShape(p),
note: `发送口 ${p.fn}(${p.title}):company_id 的右半边必须是本函数自己的入参(表里登记的整行锚),`
+ '值由页面传 companyTab.requestCompanyId;红点归属见「窗口与真文件对平」那条用例',
}))
} }
const COMPANY_ID_SOURCE_PINS: Readonly<Record<string, readonly CompanyIdPin[]>> = { const COMPANY_ID_SOURCE_PINS: Readonly<Record<string, readonly CompanyIdPin[]>> = {
@@ -97,16 +155,10 @@ const COMPANY_ID_SOURCE_PINS: Readonly<Record<string, readonly CompanyIdPin[]>>
note: 'filter 走 toImageVideoQuery 白名单构造,公司值只能落在 companyId 形参上', note: 'filter 走 toImageVideoQuery 白名单构造,公司值只能落在 companyId 形参上',
}, },
], ],
// 五个发送口五条钉(一函数一条),不是一条文件级钉数五处:判据形状见 TASK_CENTER_SEND_POINTS 的举证。 // 五个发送口五条钉(一函数一条),不是一条文件级钉数五处:判据形状见 SEND_POINTS 的举证。
// 这一页也不许套 Task 8 的 `params.companyId` 形——api 侧 `tasks`/`variant-tasks` 是 `params: QueryParams` // 这一页也不许套 Task 8 的 `params.companyId` 形——api 侧 `tasks`/`variant-tasks` 是 `params: QueryParams`
// 直传、没有 params.companyId 这个口,公司键由 model 那两个 builder 补进同一个对象。 // 直传、没有 params.companyId 这个口,公司键由 model 那两个 builder 补进同一个对象。
admin_task_center: TASK_CENTER_SEND_POINTS.map((p, i) => ({ admin_task_center: pinsFor('admin_task_center'),
file: p.file,
shape: sendPointShape(p.fn),
note: `发送口 ${i + 1}/5 ${p.title}(${p.fn}):null 由发送口自己丢(不依赖 axios 丢 null),`
+ '右半边必须是本函数自己的形参 companyId;红点归属见下面「拆条的补集」那段——删掉塞键那一行报在对平闸门,'
+ '这条 shape 独家点名的是计数不掉的形变(函数名改了、或那一行离自己函数开行超过了窗口)',
})),
admin_user_secret_usage: [ admin_user_secret_usage: [
{ {
file: 'src/api/user-secret-usage.ts', file: 'src/api/user-secret-usage.ts',
@@ -154,6 +206,17 @@ const COMPANY_ID_SOURCE_PINS: Readonly<Record<string, readonly CompanyIdPin[]>>
note: '列表窄了而下拉不窄 = 两页口径对不上,且下拉能选到别家的组', note: '列表窄了而下拉不窄 = 两页口径对不上,且下拉能选到别家的组',
}, },
], ],
// 批次 2 的五页:取值口钉全部由 SEND_POINTS 现算(一页几处发送口就几条钉),
// 手写一份就会和表漂开——那正是复评 I-1 拆条要避免的形状。
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_skip_price_asin: pinsFor('admin_skip_price_asin'),
admin_product_categories: pinsFor('admin_product_categories'),
// 批次 3 的两页同样由 SEND_POINTS 现算(撞款控制台三处发送口 = 三条钉)。
admin_shop_data_duplicate_check: pinsFor('admin_shop_data_duplicate_check'),
admin_shop_data_crawl_tasks: pinsFor('admin_shop_data_crawl_tasks'),
admin_users: pinsFor('admin_users'),
} }
/** 严格判据的分母由本轮实扫得出(修完不许恒绿也不许恒红):求值了几条 shape、其中几条通过。 */ /** 严格判据的分母由本轮实扫得出(修完不许恒绿也不许恒红):求值了几条 shape、其中几条通过。 */
@@ -236,29 +299,28 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
&& COMPANY_ID_SOURCE_PINS.admin_image_video_tasks.some((p) => p.shape !== null), && COMPANY_ID_SOURCE_PINS.admin_image_video_tasks.some((p) => p.shape !== null),
'Task 8 已接线的两页在登记表里的 shape 被改回 null 了:严格判据对这两页不再起作用(正样本归零)') 'Task 8 已接线的两页在登记表里的 shape 被改回 null 了:严格判据对这两页不再起作用(正样本归零)')
// —— I-1 拆条那 5 条钉的取样自检(全局约束 15:反向钉必须自带同支正样本, // —— 取值口拆条钉的取样自检(全局约束 15:反向钉必须自带同支正样本,
// 不许让另一支用例替我证明"这串本来就会被匹配到")。 // 不许让另一支用例替我证明"这串本来就会被匹配到")。
// ⚠ 身份要说清:下面这几条是对**字面量字符串**求值的探针,只证明判据形状没写坏 // ⚠ 身份要说清:下面这几条是对**字面量字符串**求值的探针,只证明判据形状没写坏
// (正样本匹配得出 ⇒ 不恒红;窗口外的负样本不匹配 ⇒ 窗口真有界,删一处不会靠隔壁过关), // (正样本匹配得出 ⇒ 不恒红;窗口外的负样本不匹配 ⇒ 窗口真有界,删一处不会靠隔壁过关),
// 任何代码注入都不会让它们红。真覆盖 = 上面 loop 里那 5 条 shape 对真实文件的求值 + 变异自证。 // 任何代码注入都不会让它们红。真覆盖 = 上面 loop 里那 17 条 shape 对真实文件的求值 + 变异自证。
// ⚠ 这条 length 比对**按构造恒真**(2026-10-05 复评 N-2):登记表条目就是 `TASK_CENTER_SEND_POINTS.map(...)`, // ⚠ 分母是本轮实扫的表条数(批次 1 的 5 + 批次 2 的 12 + 批次 3 的 4 + 批次 4 的 1)。这条只防"整表被摘空/被改窄",
// 删表一行两边同时变成 4,它一声不响。它只剩一种防御对象——有人把那个 `.map()` 换成手写 N 条字面 pin; // 逐处脱管由下面两条(对平闸门 + 窗口对平)负责。
// 「删表一行」的真红点在下面「拆条的补集」那条逐文件对平闸门(它的分母取自源码里的字面发送口,与表不同源)。 assert.ok(SEND_POINTS.length >= 22,
assert.equal(COMPANY_ID_SOURCE_PINS.admin_task_center.length, TASK_CENTER_SEND_POINTS.length, `发送口表只剩 ${SEND_POINTS.length} 条(批次 1+2+3+4 实扫 22 条)⇒ 有人把钉从表里摘了,取值口看守成空`)
`登记表条数与 TASK_CENTER_SEND_POINTS 条数不等 ⇒ 上面那条 .map() 被换成了手写 pin 且数量不符` for (const p of SEND_POINTS) {
+ `(表 ${TASK_CENTER_SEND_POINTS.length} 条 / 登记表 ${COMPANY_ID_SOURCE_PINS.admin_task_center.length} 条)`) const shape = pointShape(p)
for (const p of TASK_CENTER_SEND_POINTS) { const compliant = pointCompliant(p)
const shape = sendPointShape(p.fn)
const compliant = sendPointCompliant(p.fn)
assert.ok(shape.test(compliant), assert.ok(shape.test(compliant),
`(拆条取样自检·正样本)${p.fn} 的合规样本都匹配不出 ${shape} ⇒ 这条钉恒红,删没删发送口都会红,等于没看守`) `(拆条取样自检·正样本)${p.fn} 的合规样本都匹配不出 ${shape} ⇒ 这条钉恒红,删没删发送口都会红,等于没看守`)
const deleted = compliant.replace(` ${TASK_CENTER_SEND_LINE}\n`, '') const deleted = compliant.replace(` ${p.line}\n`, '')
+ ' '.repeat(TASK_CENTER_WINDOW + 1) + TASK_CENTER_SEND_LINE + ' '.repeat(p.window + 1) + p.line
assert.equal(shape.test(deleted), false, assert.equal(shape.test(deleted), false,
`(拆条取样自检·负样本)${p.fn} 删掉自己那一行、只剩窗口外的隔壁发送口却仍然匹配 ⇒ 窗口够得到了隔壁,删一处不会红`) `(拆条取样自检·负样本)${p.fn} 删掉自己那一行、只剩窗口外的隔壁发送口却仍然匹配 ⇒ 窗口够得到了隔壁,删一处不会红`)
} }
// 拆条的补集(复评 I-1 的另一半):一条钉管一个发送口 ⇒ 每个文件登记的钉数必须等于该文件里发送口的实际条数。 // 拆条的补集(复评 I-1 的另一半):一条钉管一个发送口 ⇒ 每个 (文件, 塞键整行) 登记的钉数
// 必须等于它在该文件的实际条数。
// 红点归属要说实(2026-10-05 复评 N-1):shape 不匹配只往 gaps 里记,得等本用例末尾的 // 红点归属要说实(2026-10-05 复评 N-1):shape 不匹配只往 gaps 里记,得等本用例末尾的
// `assert.deepEqual(problems, [])` 才喊,而这条闸门在同一 test 体内**先执行** ⇒ // `assert.deepEqual(problems, [])` 才喊,而这条闸门在同一 test 体内**先执行** ⇒
// 「删源码里的塞键那一行」(变异自证 M1–M5 就是这一形)实际报的是这里的「钉数 ≠ 实际条数」消息 // 「删源码里的塞键那一行」(变异自证 M1–M5 就是这一形)实际报的是这里的「钉数 ≠ 实际条数」消息
@@ -268,21 +330,65 @@ test('正向:声明 companyScoped 的页,其 api 文件必须真的带 company
// 这一条杀的是「把 TASK_CENTER_SEND_POINTS 删剩 4 行」——少一条钉就等于少一处看守,而 5 条 shape 谁都不会红。 // 这一条杀的是「把 TASK_CENTER_SEND_POINTS 删剩 4 行」——少一条钉就等于少一处看守,而 5 条 shape 谁都不会红。
// 路线 ②(occurrences 计数)在这里只当"钉数与发送口条数对平"的闸门,不当"是哪一处"的判据: // 路线 ②(occurrences 计数)在这里只当"钉数与发送口条数对平"的闸门,不当"是哪一处"的判据:
// 计数回答不了"哪三处"(把一处重复写三遍、另一处删掉,计数照样对平),所以主判据仍是路线 ① 的函数名锚 + 有界窗口。 // 计数回答不了"哪三处"(把一处重复写三遍、另一处删掉,计数照样对平),所以主判据仍是路线 ① 的函数名锚 + 有界窗口。
const pinnedPerFile = new Map<string, number>() // 分母按 (文件, 整行) 而不是按文件:批次 2 的 product-category-api.ts 一个文件三处发送口、三处是逐字同一行,
for (const p of TASK_CENTER_SEND_POINTS) { // 按文件计只钉得出"3 条"这个数,按行计才和 occurrences 同一粒度;三个 *-export.ts 的行各只出现 1 次,同理。
pinnedPerFile.set(p.file, (pinnedPerFile.get(p.file) ?? 0) + 1) const grouped = new Map<string, { readonly file: string; readonly line: string; pinned: number }>()
for (const p of SEND_POINTS) {
const key = p.file + '|' + p.line
const hit = grouped.get(key)
if (hit) hit.pinned += 1
else grouped.set(key, { file: p.file, line: p.line, pinned: 1 })
} }
assert.equal(pinnedPerFile.size, 2, assert.equal(grouped.size, 17,
`发送口表应当只覆盖 api + model 这 2 个文件,现在却有 ${pinnedPerFile.size} 个 —— 表被改形状了,对平判据失去分母`) `发送口表按 (文件, 整行) 应聚成 17 组(22 处发送口),现在却有 ${grouped.size} 组 —— 表被改形状了,对平判据失去分母`)
for (const [file, pinned] of pinnedPerFile) { for (const g of grouped.values()) {
const actual = occurrences(stripComments(read(file)), TASK_CENTER_SEND_LINE) const actual = occurrences(stripComments(read(g.file)), g.line)
assert.equal(pinned, actual, assert.equal(g.pinned, actual,
`${file} 里实际有 ${actual} 处「${TASK_CENTER_SEND_LINE}」,登记表却只钉了 ${pinned} 条 —— ` `${g.file} 里实际有 ${actual} 处「${g.line}」,登记表却只钉了 ${g.pinned} 条 —— `
+ '有一处发送口脱管(一函数一钉:钉数必须与该文件的发送口条数逐文件对平)') + '有一处发送口脱管(一函数一钉:钉数必须与该文件该行的实际条数对平)')
} }
// 同支正样本(全局约束 15:计数判据不许"0 == 0 也算对平"就当自己成立):字面样本里有两条,occurrences 必须数得出 2。 // 同支正样本(全局约束 15:计数判据不许"0 == 0 也算对平"就当自己成立):字面样本里有两条,occurrences 必须数得出 2。
assert.equal(occurrences(sendPointCompliant('f') + sendPointCompliant('g'), TASK_CENTER_SEND_LINE), 2, const twoSendLines = `function f() {\n ${TASK_CENTER_SEND_LINE}\n}\nfunction g() {\n ${TASK_CENTER_SEND_LINE}\n}\n`
'(计数取样自检·正样本)occurrences 连两条字面发送口都数不出来 ⇒ 上面那条逐文件对平恒真,等于没看守') assert.equal(occurrences(twoSendLines, TASK_CENTER_SEND_LINE), 2,
'(计数取样自检·正样本)occurrences 连两条字面发送口都数不出来 ⇒ 上面那条逐行对平恒真,等于没看守')
// 窗口预算与真文件对平:批次 2 把上面 TASK_CENTER_WINDOW 那段"320 够得着自己、够不到隔壁"的举证从注释挪进代码,
// 逐处从**当前源码**重算两个距离,注释过期也不会骗人:
// own = 从 `function <fn>(` 的括号后到自己那一行的距离 ⇒ 必须 < window(函数体写长 = 假红,fail-closed 可接受);
// next = 到同文件**下一条同名发送行**开头的距离 ⇒ 存在时必须 > window(否则删一处还有隔壁顶着,这条钉就是摆设)。
// 隔壁的"名字"用的是自己的整行,所以 next 只在同文件有逐字同行的另一处时才有意义:
// product-category-api.ts 三处同行(next 实测 705/929/无)是这一族唯一的真冲突面,其余 14 处 own 唯一。
for (const p of SEND_POINTS) {
const src = stripComments(read(p.file))
const anchor = 'function ' + p.fn + '('
const anchorCount = occurrences(src, anchor)
assert.equal(anchorCount, 1,
`${p.file} 里「${anchor}」出现 ${anchorCount} 次(要求 1):函数改名或被复制,这条按函数名钉的看守就对不上是谁发的`)
const open = src.indexOf(anchor) + anchor.length
const own = src.indexOf(p.line, open) - open
assert.ok(own >= 0 && own < p.window,
`${p.fn} 的塞键行离自己函数开行 ${own} 字符,窗口预算却是 ${p.window}:own<0 = 那一行整段没了或换了写法;`
+ 'own>=window = 函数体写长把这一处挤出了窗口(这条判据宁可假红也不放宽,放宽就等于够得着隔壁)')
const second = src.indexOf(p.line, src.indexOf(p.line, open) + p.line.length)
assert.ok(second < 0 || p.window < second - open,
`${p.fn} 的窗口(${p.window})够得着同文件下一条同名发送口(距离 ${second - open}):`
+ '删掉这一处,隔壁那行会替它过关,这条钉就只守得住"两处一起删"')
}
// 覆盖性自检的另一半:清单里每个 api 文件,只要它已经把 company_id 当参数下传,就必须被**点名到文件**的钉盖住。
// 上面 loop 的 shape 只求值"登记了的那条钉指向的文件",而正向的 `/company_id\s*[:=]/` 问的是整个文件——
// 于是"给某页的 apiFiles 新增一个会发 company_id 的模块、却不给它登记取值口钉"这一手能双双过关
// (新模块的宽松判据绿、旧模块的严格判据也绿)。批次 2 的 dedupe/query/skip-price 三页各有 2 个发送文件,正是这一形。
for (const page of COMPANY_SCOPED_PAGES) {
const pinnedFiles = new Set((COMPANY_ID_SOURCE_PINS[page.menuKey] ?? []).map((p) => p.file))
for (const file of page.apiFiles) {
const wired = /company_id\s*[:=]/.test(stripComments(read(file)))
if (wired && !pinnedFiles.has(file)) {
problems.push(`${page.menuKey}:${file} 已经在下传 company_id,登记表里却没有一条钉指向它`
+ '——正向只问"文件里有没有",那是恒绿的宽松档')
}
}
}
assert.deepEqual(problems, [], assert.deepEqual(problems, [],
`公司 tab 接线缺口(逐页列全;批次 1 的 8 页到 Task 10 已全部接线,谁再退回未接线就红在这里):\n` `公司 tab 接线缺口(逐页列全;批次 1 的 8 页到 Task 10 已全部接线,谁再退回未接线就红在这里):\n`
@@ -400,7 +506,7 @@ test('反向:把 company_id 当查询参数用的取数模块必须被清单
* 症状回到裁决 1 想避免的那一型。</p> * 症状回到裁决 1 想避免的那一型。</p>
* *
* <p>判据形状:从 `watch(() => companyTab.activeId, …)` 那**一条语句**取文本(正则在第一个 * <p>判据形状:从 `watch(() => companyTab.activeId, …)` 那**一条语句**取文本(正则在第一个
* `}` + `)` 处收口 ⇒ 单层,体内再嵌对象字面量会截早;两页今天都没有那种写法,由下面的取样自检兜着)。 * `}` + `)` 处收口 ⇒ 单层,体内再嵌对象字面量会截早;表里这九页今天都没有那种写法,由下面的取样自检兜着)。
* 反向钉与正样本同支(全局约束 15,三条前提不成立就是探针失效、当场红,不许静默空跑),**每一对**都各跑一遍: * 反向钉与正样本同支(全局约束 15,三条前提不成立就是探针失效、当场红,不许静默空跑),**每一对**都各跑一遍:
* ① 合规样本必须匹配得出且含两把 token ⇒ 判据不恒红; * ① 合规样本必须匹配得出且含两把 token ⇒ 判据不恒红;
* ② 删掉那一句的样本必须不含 ⇒ 判据能红(变异自证走的就是这一条); * ② 删掉那一句的样本必须不含 ⇒ 判据能红(变异自证走的就是这一条);
@@ -415,7 +521,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 里逐对钉。 * (文件, 必须出现在 watch 体内的赋值) 九对,同一条 test 里逐对钉(批次 1 两对 + 批次 2 五对 + 批次 3 两对)。
* `premise` 是这一对的反向钉前提:这一页的发送口今天还在发 `company_id`,清筛选项才有意义; * `premise` 是这一对的反向钉前提:这一页的发送口今天还在发 `company_id`,清筛选项才有意义;
* 哪天发送口退回不带参,watch 看守就变成"清了一个没人用的筛选项",必须一起红。 * 哪天发送口退回不带参,watch 看守就变成"清了一个没人用的筛选项",必须一起红。
*/ */
@@ -445,6 +551,88 @@ 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 数据还一样」那一批)。
// token 在两页上同形(`filter.groupId = null` 出现三次),这**不是**漏洞:判据按 (file, token) 成对求值,
// 每一对都各自去读它自己那一页的源码,别家页缺了这行不会红在这一页,反之这一页删掉了也不会被隔壁顶住
// (负样本 ③「挪到 watch 之外」钉的就是位置)。
{
file: 'src/pages/asin/DedupeRegistryPage.vue',
token: 'filter.groupId = null',
why: '分组候选 /shop-manages/groups 现在按公司下传,上一家选中的 groupId 在新一家的字典里不存在 ⇒ 去重库被它筛成空页',
premise: [
{ 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',
token: "filter.groupId = null; filter.shopName = ''",
why: '这一页的店铺名候选是按分组现拉的(fetchShopNamesByGroup 也透传了公司):只清 groupId 而留着 shopName,'
+ '新一家会被一个不属于它的店铺名筛空,而筛选项 UI 上还显示着上一家填的值',
premise: [
{ file: 'src/pages/asin/query-asin-api.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] },
],
},
{
file: 'src/pages/asin/SkipPricePage.vue',
token: "filter.groupId = null; filter.shopName = ''",
why: '同查询 ASIN 页:分组与店铺名是一对(店铺名候选跟着分组走),切公司必须一起清',
premise: [
{ 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 点名「店铺撞款监控 店铺数据也要做隔离」)。
// 这两页的 token 一直写到 reload 那两句为止(批次 1/2 的老条目仍只钉清筛选项,不动它们):
// 变异自证发现「删掉 void loadConsole()」当时全绿——清筛选项那半守住了,重新取数那半没人守。
{
file: 'src/pages/tasks/DuplicateCheckPage.vue',
token: "filter.shop = ''; filter.group = ''; selectedGroup.value = ''; scope.value = 'global'; void loadConsole(); void loadLedger(1)",
why: '这一页的店铺下拉与分组下拉的候选字典都由 /duplicate-check-console 按公司下发(shops/groups 都来自裁剪后的可见集),'
+ '留着上一家选中的店铺名/分组名,新一家首屏就被一个不属于它的值筛成空页;selectedGroup 单独清是因为'
+ ' loadConsole 的重挑分支只在 groupStats 非空时触发,切到没有分组的公司时它会原样留着。'
+ '末尾两句是 reload:清完了却不重取,页面还是上一家的快照',
premise: [
{ file: 'src/pages/tasks/duplicate-console-api.ts', shapes: [/company_id\s*=\s*companyId\b/] },
],
},
{
file: 'src/pages/tasks/ShopDataTasksPage.vue',
token: "filter.shopName = ''; filter.groupName = ''; selection.value = createShopDataSelection(); page.value = 1; cardPage.value = 1; void load()",
why: '两处自由文本筛选项留着上一家填的值 = 拿新一家看不见的店铺名去筛列表;勾选集更硬——它存的是 resultId,'
+ '跨公司不清的话点「批量下载」会把别家店铺的结果文件打进同一个 zip(不发筛选请求,直接按 id 取件);'
+ '页码回 1 是因为新一家的条数更少,末尾的 void load() 才让切 tab 真的换数据',
premise: [
{ file: 'src/pages/tasks/shop-data-api.ts', shapes: [/company_id\s*=\s*companyId\b/] },
],
},
// ↓ 批次 4(控制方 2026-10-05 点名「菜单权限和用户管理也要区分公司 tab 的数据」)。
{
file: 'src/pages/account/UsersPage.vue',
token: "filters.createdByAdminId = null; filters.keyword = ''; filters.page = 1; void loadUsers()",
why: '「所属管理员」的候选 admins 随本公司的列表响应给出,上一家的 adminId 在新一家的下拉里不存在;'
+ '用户名又全平台唯一(V143 的唯一索引),留着上一家填的关键字去筛新一家必然空页,'
+ '而输入框还显示着那个值——两处都不是后端筛坏了。末尾的 void loadUsers() 是本页唯一的数据出口,'
+ '少了它前面三条赋值都只是清了一遍没人看的表单',
premise: [
{ file: 'src/api/users.ts', shapes: [/company_id\s*=\s*params\.companyId\b/] },
],
},
] ]
/** 取「`watch(() => companyTab.activeId, () => { … })`」这一条语句的原文;匹配不出返回 null(由调用方判探针失效)。 */ /** 取「`watch(() => companyTab.activeId, () => { … })`」这一条语句的原文;匹配不出返回 null(由调用方判探针失效)。 */
@@ -453,9 +641,10 @@ function watchStatement(source: string): string | null {
return m ? m[0] : null return m ? m[0] : null
} }
test('切公司的 watch 体:每对 (file, token) 都要在该页 watch 体内出现(店铺管理清 groupId、任务看板清 shop)', () => { test('切公司的 watch 体:每对 (file, token) 都要在该页 watch 体内出现(批次 1 两页 + 批次 2 五页 + 批次 3 两页 + 批次 4 一页)', () => {
assert.ok(WATCH_BODY_PINS.length >= 2, assert.ok(WATCH_BODY_PINS.length >= 10,
'watch 体看守被删到只剩一对 ⇒ 这一族又退回"只钉 ShopManagePage",任务看板那行 filter.shop 再次没人看守') `watch 体看守只剩 ${WATCH_BODY_PINS.length} 对(批次 1 的店铺管理/任务看板 + 批次 2 的去重库/品牌库/查询ASIN/最低价ASIN/商品类目 + 批次 3 的撞款监控/店铺数据记录 + 批次 4 的用户管理共 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) {
// ① 正样本(判据不恒红)——逐字就是这一页今天 watch 体里的那一行。 // ① 正样本(判据不恒红)——逐字就是这一页今天 watch 体里的那一行。
@@ -17,6 +17,12 @@ import { topbarUserOf } from '../src/layout/topbar-model.ts'
* `AdminUserService#resolveTargetCompanyId` 落操作者自己的公司;跨公司隔离发生在消费侧与读取侧 * `AdminUserService#resolveTargetCompanyId` 落操作者自己的公司;跨公司隔离发生在消费侧与读取侧
* (二期批次 2/3),不依赖页面把公司名渲染出来。所以这里的断言全部打在"不得回流"上: * (二期批次 2/3),不依赖页面把公司名渲染出来。所以这里的断言全部打在"不得回流"上:
* 任何一处重新渲染公司,本文件就红。</p> * 任何一处重新渲染公司,本文件就红。</p>
*
* <p><b>2026-10-05 批次 4 修订(控制方点名「用户管理也要区分公司 tab 的数据」)</b>:
* 摘掉的是<b>渲染层</b>的公司维度——行级公司列、「所属公司」标签、筛选状态里的公司、顶栏公司名,这些仍不得回流
* (界面暴露要单独批准,而且 tab 已经是公司选择器,页面里再加一个公司筛选就是第二套口径)。
* <b>请求层</b>的 company_id 是这次明确要加回来的,且取值口唯一:`companyTab.requestCompanyId`。
* 下面 `companyId 的取值口唯一` 那条就是这条新边界的尺子。</p>
*/ */
test('公司列不再写进列表项,但其余字段必须照常解析', () => { test('公司列不再写进列表项,但其余字段必须照常解析', () => {
@@ -39,7 +45,7 @@ test('公司列不再写进列表项,但其余字段必须照常解析', () =>
assert.equal(item.creatorUsername, 'admin') assert.equal(item.creatorUsername, 'admin')
}) })
test('筛选状态与查询参数里都没有公司这一维', () => { test('筛选状态与查询参数里都没有公司这一维(公司值只从 fetchUserList 的原始入参走)', () => {
const state = createUserFilterState() const state = createUserFilterState()
assert.equal('companyId' in state, false) assert.equal('companyId' in state, false)
assert.deepEqual(state, { keyword: '', createdByAdminId: null, role: '', page: 1, pageSize: 10 }) assert.deepEqual(state, { keyword: '', createdByAdminId: null, role: '', page: 1, pageSize: 10 })
@@ -49,7 +55,16 @@ test('筛选状态与查询参数里都没有公司这一维', () => {
assert.equal(isFilterActive({ ...state, keyword: ' ' }), false) assert.equal(isFilterActive({ ...state, keyword: ' ' }), false)
const query = toUserListQuery(normalizeUserPageParams({ page: 2, pageSize: 20, keyword: 'x' })) const query = toUserListQuery(normalizeUserPageParams({ page: 2, pageSize: 20, keyword: 'x' }))
assert.equal('company_id' in query, false, '绝不下发 company_id:一旦下发就是"只看这家"的过滤') assert.equal('company_id' in query, false, '两只白名单构造器都不造公司值')
// 批次 4 的落点证据:normalizeUserPageParams 是白名单构造(返回对象只点名 page/pageSize/keyword/…),
// 传进 companyId 也会被丢 ⇒ users.ts 必须读**原始入参** params.companyId。
// 写成 normalized.companyId 时 TS 照样绿(字段在 UserListParams 上声明着),运行时恒 undefined——
// 这正是这条要拦的形状,所以它比的是行为不是字符串。
const dropped = normalizeUserPageParams({ page: 1, pageSize: 10, companyId: 3 })
assert.equal('companyId' in dropped, false,
'归一化结果里出现了 companyId ⇒ 白名单构造改了,users.ts 那句读原始入参的注释与实现得一起对账')
assert.equal(dropped.page, 1, '反向自检:归一化本身没坏(不许靠整只函数报废变绿)')
}) })
test('顶栏不再渲染公司名', () => { test('顶栏不再渲染公司名', () => {
@@ -59,15 +74,15 @@ test('顶栏不再渲染公司名', () => {
assert.equal(topbarUserOf(null).hasUser, false) assert.equal(topbarUserOf(null).hasUser, false)
}) })
// 反向钉:公司维度不得回流到「列表/筛选/顶栏」(2026-10-04 定口径;2026-10-05 修订—— // 反向钉:公司维度不得回流到「行渲染/筛选状态/顶栏」(2026-10-04 定口径;2026-10-05 修订——
// 唯一例外是建号弹窗里的「公司超级管理员」所属公司下拉,由 company-user-create.test.ts 单独钉住) // ①建号弹窗里的「公司超级管理员」所属公司下拉,由 company-user-create.test.ts 单独钉住;
// ②列表请求带 company_id 是批次 4 明确加回来的,尺子换成下面的「取值口唯一」)
test('账号页与顶栏的源码里公司维度已摘干净', () => { test('账号页与顶栏的源码里公司维度已摘干净', () => {
const page = readSource('src/pages/account/UsersPage.vue') const page = readSource('src/pages/account/UsersPage.vue')
assert.equal(/所属公司/.test(page), false, '账号页不该再出现「所属公司」标签') assert.equal(/所属公司/.test(page), false, '账号页不该再出现「所属公司」标签')
// 列表契约层面不许出现公司维度:查询参数 company_id、筛选状态、行级公司列。 // 渲染层与筛选状态不许有公司维度;snake_case 的 company_id 更不许在页面里手拼(那是 api 层的事)。
// (companyOptions/c.companyName 是 2026-10-05 建公司超管选公司的唯一豁免,不在此列。) assert.equal(/filters\.company|row\.company|company_id/.test(page), false,
assert.equal(/company_id|filters\.company|row\.company|companyId/.test(page), false, '行渲染/筛选状态里回流了公司维度,或页面自己拼了 snake_case 查询键')
'列表查询/筛选/行渲染不允许出现公司维度')
assert.match(page, /fetchCompanies/, '公司目录仅供建号弹窗的「公司超管」下拉使用(唯一豁免)') assert.match(page, /fetchCompanies/, '公司目录仅供建号弹窗的「公司超管」下拉使用(唯一豁免)')
assert.match(page, /isSuperAdmin[\s\S]{0,200}fetchCompanies/, assert.match(page, /isSuperAdmin[\s\S]{0,200}fetchCompanies/,
'拉公司目录必须按站点超管门控,非超管不发这个请求(后端 403 兜底)') '拉公司目录必须按站点超管门控,非超管不发这个请求(后端 403 兜底)')
@@ -95,7 +110,40 @@ test('账号页与顶栏的源码里公司维度已摘干净', () => {
const filter = readSource('src/pages/account/users-filter.ts') const filter = readSource('src/pages/account/users-filter.ts')
assert.equal(/companyId/.test(filter), false) assert.equal(/companyId/.test(filter), false)
const dto = readSource('src/api/users-dto.ts') const dto = readSource('src/api/users-dto.ts')
assert.equal(/company_id|companyId/.test(dto), false) // 批次 4 之后 DTO 里**有**公司字段(UserListParams.companyId / UserListQuery.company_id),
// 但只许当类型声明用:两只构造函数一旦开始造这个值,页面的 requestCompanyId 就成了第二套口径的摆设。
for (const fn of ['normalizeUserPageParams', 'toUserListQuery']) {
assert.doesNotMatch(bodyOf(dto, fn), /compan/i,
`users-dto 的 ${fn} 里出现了公司值 ⇒ 取值口从页面挪进了构造器`)
}
const model = readSource('src/api/users-model.ts') const model = readSource('src/api/users-model.ts')
assert.equal(/company_id|company_name/.test(model), false) assert.equal(/company_id|company_name/.test(model), false, '列表项解析不认后端回传的公司列')
})
/** 花括号配对取函数体(整文件比字符串会被类型声明和注释骗)。 */
function bodyOf(source: string, name: string): string {
const at = source.indexOf(`function ${name}(`)
assert.notEqual(at, -1, `${name} 不在了——先确认它不是被改名/删掉了`)
const open = source.indexOf('{', at)
let depth = 0
for (let i = open; i < source.length; i++) {
if (source[i] === '{') depth++
else if (source[i] === '}') { depth--; if (depth === 0) return source.slice(open, i + 1) }
}
assert.fail(`${name} 花括号不配对,解析失败`)
}
test('列表请求的公司值取值口唯一:每处 companyId 都指向 tab 的 requestCompanyId', () => {
const page = readSource('src/pages/account/UsersPage.vue')
// 分母从真源码现算,不是常量和自己比:0 处=批次 4 的接线被摘掉 ⇒ 三家公司又看到同一份全量列表。
const assigned = [...page.matchAll(/companyId:\s*([^,\n}]+)/g)].map((m) => m[1].trim())
assert.ok(assigned.length >= 1, 'UsersPage 已不再把公司值放进列表请求 ⇒ 用户页的公司隔离断了')
for (const value of assigned) {
assert.equal(value, 'companyTab.requestCompanyId',
`companyId 的取值口不唯一(${value}):请求体里的公司值只许来自公司 tab 的唯一取值口`)
}
// 建号请求仍然不带 company_id(归属由后端从操作者推导):弹窗那侧不许出现这个键。
const dialog = readSource('src/pages/account/CreateUserDialog.vue')
assert.equal(/companyId:|company_id:/.test(dialog), false,
'建号请求体不许带 company_id——那是 2026-10-04 定死的口径,跟列表读侧无关')
}) })
+7 -5
View File
@@ -1,14 +1,16 @@
# 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-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 同步。
## 概览 ## 概览
- 版本化迁移文件数:**145**(`src/main/resources/db/V*.sql`,其中整数版本 144 个 + 小版本 V25_1) - 版本化迁移文件数:**146**(`src/main/resources/db/V*.sql`,其中整数版本 145 个 + 小版本 V25_1)
- 整数版本范围:**V1..V146**,其中 V132/V133 为已退役空号(见下),其余连续 - 整数版本范围:**V1..V147**,其中 V132/V133 为已退役空号(见下),其余连续
- 历史遗留小版本:**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 之前执行,属历史命名,保留)
- 最新版本:**V146__users_expires_at_admin_expiry.sql**(上一版 **V145__brand_dedupe_company_scope.sql**;V142 已于 10-03 18:23 应用、V143 已于 10-04 10:48 应用、**V144 已于 10-04 13:22 应用**;V145/V146 待下一次 jar 发版执行) - 最新版本:**V147__product_category_company_scope.sql**(上一版 **V146__users_expires_at_admin_expiry.sql**,再上一版 **V145__brand_dedupe_company_scope.sql**)
- 待下一次 jar 发版执行的三条:`V145__brand_dedupe_company_scope.sql`、`V146__users_expires_at_admin_expiry.sql`、`V147__product_category_company_scope.sql`
- 已应用:V142(10-03 18:23)、V143(10-04 10:48)、**V144(10-04 13:22)**
- 重复版本:无 - 重复版本:无
- 迁移命名:全部符合 `V<整数>(_<子版本>)?__<描述>.sql`,无空格 - 迁移命名:全部符合 `V<整数>(_<子版本>)?__<描述>.sql`,无空格
@@ -20,7 +22,7 @@
本地曾存在 `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 永久退役,不可回填。
后续新增迁移从 **V147** 起取号(只认"当前最大值 + 1",不要为还没写出来的迁移预留号段——预留会在 1..max 里留洞,`integerVersionsSequentialFromOne` 会红)。 后续新增迁移从 **V148** 起取号(只认"当前最大值 + 1",不要为还没写出来的迁移预留号段——预留会在 1..max 里留洞,`integerVersionsSequentialFromOne` 会红)。V148 的第一件已知待办就是摘掉 `biz_product_category.company_id` 的 DEFAULT(一条 `ALTER … ALTER COLUMN company_id DROP DEFAULT`,禁 MODIFY),前提是同批 jar 已双节点上线且写侧都显式落公司。
原先挂在待办里的"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,42 @@
-- 回滚 V147(人工补丁,不放进 src/main/resources/db/——那里是 Flyway 扫描路径,
-- 任何 V*.sql 都会在应用下次启动时自动执行;把回滚编成版本化迁移等于让"决定回滚"这件事
-- 在没有人工执行的情况下自己发生。)
--
-- 顺序:停两台应用 → 执行本脚本 → DELETE FROM flyway_schema_history WHERE version='147'
-- → 回滚 jar → 起应用。
-- 漏掉"删历史行"那步,将来重装带 V147 的 jar 时 Flyway 判定"已应用"直接跳过,列与键都不会重建,
-- 而 Java 侧实体照常读写 company_id ⇒ 运行期 Unknown column。
--
-- ⚠ 本脚本默认只做「保留新列、把唯一键退回全局」这一档。
-- 退回全局唯一键要求"跨公司没有同名 category_key"。V147 之前该键是全平台唯一,所以【回填那一刻】
-- 必然满足;但批次 2/3(每公司自建类目)上线之后这一前提不再由代码保证——两家各自建了同名
-- 自定义类目时,generateCategoryKey(parentId, name) 会算出同一串。所以先跑第 0 段那条预检查询。
-- 报 1062 说明确实已经有跨公司同名行:此时【不要】硬删数据,改走"保留新键、只回滚 jar"
-- (新列对新 jar 是惰性的,不读写就不影响)。
-- ---------- 0. 预检(必须先跑,返回 0 行才允许第 1 段) ----------
-- SELECT company_id, category_key, COUNT(*) c
-- FROM `biz_product_category`
-- GROUP BY company_id, category_key
-- HAVING COUNT(*) > 1;
-- -> 期望 0 行。非 0 就是"跨公司已有同名键",第 1 段会撞 1062。
-- SELECT SUM(is_builtin = 1 AND company_id <> 0) AS bad_builtin
-- FROM `biz_product_category`;
-- -> 期望 0。非 0 说明有内置节点被当成公司自建,回滚后这些节点在旧 jar 里仍会出现在每一家的树上,
-- 与 V147 之前的行为一致,不影响回滚本身,但要记进核对清单。
-- ---------- 1. 唯一键退回全局(先加旧键、后删新键,理由同 V147:中间任一步都至少有一个唯一键在守并发) ----------
ALTER TABLE `biz_product_category`
ADD UNIQUE KEY `uk_product_category_key` (`category_key`),
ALGORITHM = INPLACE, LOCK = NONE;
ALTER TABLE `biz_product_category`
DROP INDEX `uk_company_category_key`,
ALGORITHM = INPLACE, LOCK = NONE;
-- ---------- 2. 真的要把列也删掉才解开下面这行(不可逆,先备份) ----------
-- company_id 上写着"哪个自定义节点是哪一家建的",而这张表没有任何账号列(V147 §2:事后无法反推),
-- 一旦 DROP 就只能靠"全表填 1"重建 ⇒ 第 2 家自建的类目会全部划归第 1 家,且再没有证据能分回去。
-- 另外哨兵那条纪律在这里同样成立:摘 DEFAULT 用 ALTER COLUMN ... DROP DEFAULT,
-- 任何时候都不要写 MODIFY COLUMN(重建表会按"当时的列默认值"物化历史行)。
-- ALTER TABLE `biz_product_category` DROP COLUMN `company_id`;
@@ -49,6 +49,26 @@ public class CompanyScopeSupport {
return companyId; return companyId;
} }
/**
* 后台自动写入路径(货源 chunk 回传、品牌补测调度器)专用的宽容版:账号已经不存在时返回 null,
* 而不是像 {@link #requireCompanyId(Long)} 那样抛。
*
* <p>这两个入口的锚点是 {@code biz_file_task.user_id},而账号是**物理删**的:2026-10-05 生产只读
* 取证,2026-06 以来的 716 条任务里 108 条的 user_id 在 users 里查不到(货源 174 条里 2 条)。
* 在这里抛等于让整单采集提交失败——比归属失真更糟。调用方拿到 null 必须记一条可巡检的日志、
* 并放弃这批写入,不许把 null 传进实体让 DEFAULT 1 静默兜住。</p>
*/
public Long companyIdOrNull(Long userId) {
if (userId == null || userId <= 0) {
return null;
}
AdminUserEntity user = adminUserMapper.selectById(userId);
if (user == null || user.getCompanyId() == null || user.getCompanyId() <= 0) {
return null;
}
return user.getCompanyId();
}
/** 行级归属闸门:跨公司写/删的第一道,消息由调用方给(前端按它显示,别在这里编文案)。 */ /** 行级归属闸门:跨公司写/删的第一道,消息由调用方给(前端按它显示,别在这里编文案)。 */
public void assertSameCompany(Long operatorCompanyId, Long rowCompanyId, String deniedMessage) { public void assertSameCompany(Long operatorCompanyId, Long rowCompanyId, String deniedMessage) {
if (rowCompanyId == null || !rowCompanyId.equals(operatorCompanyId)) { if (rowCompanyId == null || !rowCompanyId.equals(operatorCompanyId)) {
@@ -39,4 +39,26 @@ public class DataReadScope {
List<Long> base = userDataScopeSupport.resolveVisibleUserIds(operator.getId()); List<Long> base = userDataScopeSupport.resolveVisibleUserIds(operator.getId());
return ReadScope.users(ReadScope.users(companyScope.memberUserIds(own)).userIdsOr(base)); return ReadScope.users(ReadScope.users(companyScope.memberUserIds(own)).userIdsOr(base));
} }
/**
* 归属已经**物化成 company_id 列**的表(品牌库 biz_invalid_asin_data)用的谓词出口:
* 返回要筛的公司 id,null = 不筛。
*
* <p>这些表不能走 {@link #readScope} 的账号集合:2026-10-05 生产只读取证,品牌库 14,801 行里
* {@code uploader_user_id} 非空的有 <b>0</b> 行(实体没这字段、批量 INSERT 的列清单也没带,
* V145 补的列一直是空的),按账号筛等于把全部历史从每一个公司 tab 里静默删掉。
* 而 {@code company_id} 那一列虽然是被 DEFAULT 1 盖上去的,对历史却是诚实的:
* 第 2 家公司 10-04 14:55 才开通,它名下账号历史任务 0 条、去重库上传 0 行,
* 所以「建号之前存在的行都归第 1 家」是可证的事实,不是猜。</p>
*
* <p>非超管返回 null(不筛):他们的可见集本来就锁在自己的分组上,叠一层公司会把
* 「靠分组可见」的行整批删掉(同 {@code ShopManageController} 的口径)。
* 超管的 company_id 是视图开关不是安全边界(spec §4),所以这里不需要再校验它属于谁。</p>
*/
public Long readCompanyId(AdminUserEntity operator, Long requestedCompanyId) {
if (!SUPER_ADMIN.equals(adminAuthSupport.currentRole(operator))) {
return null;
}
return requestedCompanyId != null && requestedCompanyId > 0 ? requestedCompanyId : null;
}
} }
@@ -44,12 +44,38 @@ public final class ExcelStreamReader {
} else { } else {
EasyExcel.read(inputStream, listener).sheet(0).headRowNumber(1).doRead(); EasyExcel.read(inputStream, listener).sheet(0).headRowNumber(1).doRead();
} }
} catch (WrappedRuntimeException ex) { } catch (RuntimeException ex) {
if (ex.getCause() instanceof IOException ioException) { // EasyExcel/POI 的解析异常是 RuntimeException,原样冒到接口层会变成 HTTP 500;
// 本工具的契约是 IOException,调用方已按 IOException 给用户回 400。
throw toContractException(listener.handlerFailure(), ex);
}
}
private static IOException toContractException(Exception handlerFailure, RuntimeException readFailure) throws IOException {
if (handlerFailure != null) {
// 调用方自己抛的不算"文件坏了":运行时异常原样透传,保住 BusinessException 的 400 语义。
if (handlerFailure instanceof IOException ioException) {
throw ioException; throw ioException;
} }
throw ex; if (handlerFailure instanceof RuntimeException runtimeException) {
throw runtimeException;
}
throw new IOException("Excel 行处理失败:" + describe(handlerFailure), handlerFailure);
} }
throw new IOException("Excel 解析失败:" + describe(readFailure), readFailure);
}
private static String describe(Throwable ex) {
Throwable deepest = ex;
String message = ex.getMessage();
while (deepest.getCause() != null) {
deepest = deepest.getCause();
String current = deepest.getMessage();
if (current != null && !current.isBlank()) {
message = current;
}
}
return message == null || message.isBlank() ? ex.getClass().getSimpleName() : message;
} }
public interface SheetRowHandler { public interface SheetRowHandler {
@@ -70,11 +96,27 @@ public final class ExcelStreamReader {
private final SheetRowHandler handler; private final SheetRowHandler handler;
private Map<Integer, String> currentHeaderMap = Map.of(); private Map<Integer, String> currentHeaderMap = Map.of();
private Exception handlerFailure;
private StreamingListener(SheetRowHandler handler) { private StreamingListener(SheetRowHandler handler) {
this.handler = handler; this.handler = handler;
} }
private Exception handlerFailure() {
return handlerFailure;
}
/** 记下调用方抛出的异常,好让 runRead 分得清「文件解析坏了」和「行处理被调用方拒了」。 */
private RuntimeException recordHandlerFailure(Exception ex) {
if (handlerFailure == null) {
handlerFailure = ex;
}
if (ex instanceof RuntimeException runtimeException) {
return runtimeException;
}
return new WrappedRuntimeException(ex);
}
@Override @Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) { public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
Map<Integer, String> normalizedHeadMap = new LinkedHashMap<>(); Map<Integer, String> normalizedHeadMap = new LinkedHashMap<>();
@@ -85,10 +127,8 @@ public final class ExcelStreamReader {
try { try {
handler.onHeader(sheetName(context), sheetNo(context), currentHeaderMap); handler.onHeader(sheetName(context), sheetNo(context), currentHeaderMap);
handler.onSheetTotal(sheetName(context), sheetNo(context), approximateTotalRows(context)); handler.onSheetTotal(sheetName(context), sheetNo(context), approximateTotalRows(context));
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) { } catch (Exception ex) {
throw new WrappedRuntimeException(ex); throw recordHandlerFailure(ex);
} }
} }
@@ -106,10 +146,8 @@ public final class ExcelStreamReader {
currentHeaderMap, currentHeaderMap,
normalizedRow normalizedRow
); );
} catch (RuntimeException ex) {
throw ex;
} catch (Exception ex) { } catch (Exception ex) {
throw new WrappedRuntimeException(ex); throw recordHandlerFailure(ex);
} }
} }
@@ -1039,7 +1039,8 @@ public class BrandTaskService {
} catch (BusinessException ex) { } catch (BusinessException ex) {
throw ex; throw ex;
} catch (IOException ex) { } catch (IOException ex) {
throw new BusinessException("读取 Excel 失败"); log.warn("[brand] Excel 解析失败 file={} err={}", inputFile.getName(), ex.getMessage(), ex);
throw new BusinessException("读取 Excel 失败", ex);
} }
return context.finish(); return context.finish();
} }
@@ -111,7 +111,7 @@ public class CollectDataBrandRecheckInjector {
List<CollectDataResultRowVo> chunkRejected = rowsOfBrands(rows, rejectedBrands); List<CollectDataResultRowVo> chunkRejected = rowsOfBrands(rows, rejectedBrands);
if (!chunkRejected.isEmpty()) { if (!chunkRejected.isEmpty()) {
// INSERT IGNORE 幂等:重复补测同品牌不会在无效品牌表翻倍 // INSERT IGNORE 幂等:重复补测同品牌不会在无效品牌表翻倍
rejectedRows += invalidAsinBatchWriter.writeBatch(chunkRejected); rejectedRows += invalidAsinBatchWriter.writeBatch(chunkRejected, task.getUserId());
} }
} }
if (cleanBrands.isEmpty()) { if (cleanBrands.isEmpty()) {
@@ -896,7 +896,7 @@ public class CollectDataService {
// 8 行查询失败被写表后误杀,最终结果 Excel 0 行)。rejected 为空时 // 8 行查询失败被写表后误杀,最终结果 Excel 0 行)。rejected 为空时
// 不触发任何写入,避免空批次无意义调用。 // 不触发任何写入,避免空批次无意义调用。
if (!brandOutcome.rejected().isEmpty()) { if (!brandOutcome.rejected().isEmpty()) {
invalidAsinBatchWriter.writeBatch(brandOutcome.rejected()); invalidAsinBatchWriter.writeBatch(brandOutcome.rejected(), task.getUserId());
} }
List<CollectDataResultRowVo> accepted = brandOutcome.accepted(); List<CollectDataResultRowVo> accepted = brandOutcome.accepted();
// 结果明细改为 chunk 级存储:整个 chunk 的 accepted 行共享一个 // 结果明细改为 chunk 级存储:整个 chunk 的 accepted 行共享一个
@@ -1,5 +1,6 @@
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;
@@ -15,30 +16,52 @@ 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 + 捕获唯一键异常的旧路径。
* 幂等由唯一键 (data_value, brand) + INSERT IGNORE 语义保证;批量失败时 * 幂等由唯一键 (company_id, data_value, brand) + INSERT IGNORE 语义保证;批量失败时
* 跳过该批(记录计数,不中断提交流程),恢复后继续后续批次。 * 跳过该批(记录计数,不中断提交流程),恢复后继续后续批次。
* 空输入、无合法 data_value/brand 的行、null 行均安全跳过,不发起调用。 * 空输入、无合法 data_value/brand 的行、null 行均安全跳过,不发起调用。
*
* <p>归属(company_id + uploader_user_id)由调用方给任务发起账号,本类负责推公司:
* 此前实体与 INSERT 列清单都不带这两列,V145 补的 company_id 全靠 DEFAULT 1 盖,
* 于是第 2 家公司跑货源产生的行会被记成第 1 家,且事后分不开。</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 忽略重复,幂等)。 */ /**
public int writeBatch(List<CollectDataResultRowVo> rows) { * 批量写入并返回实际尝试写入的行数(INSERT IGNORE 忽略重复,幂等)。
*
* @param uploaderUserId 任务发起账号(biz_file_task.user_id);推不出公司时整批不写并打
* {@link #OWNER_UNRESOLVED_MARKER}——宁可少记一条黑名单,
* 也不把行盖成别家公司(那会让另一家的正常品牌被静默过滤)
*/
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());
@@ -47,6 +70,8 @@ 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);
entities.add(entity); entities.add(entity);
} }
} }
@@ -20,7 +20,9 @@ import java.util.Map;
* 唯一理由是发布期的旧 jar,§8.2 / V145 头注释)。正因为它安静,所以由代码来喊,而不是靠人记得。</p> * 唯一理由是发布期的旧 jar,§8.2 / V145 头注释)。正因为它安静,所以由代码来喊,而不是靠人记得。</p>
* *
* <p>盯的列随迁移增长:V143 给 {@code users} 加过一版(DEFAULT 已由 V144 摘),V145 给两张规则库 * <p>盯的列随迁移增长:V143 给 {@code users} 加过一版(DEFAULT 已由 V144 摘),V145 给两张规则库
* 各加一版。一张表一行都插不进来的时候才是"摘干净",所以这里探的是【清单】而不是单个列名。</p> * 各加一版,V147 给 {@code biz_product_category} 加一版。一张表一行都插不进来的时候才是"摘干净",
* 所以这里探的是【清单】而不是单个列名。清单与探针 SQL 的 IN 列表由 {@code CompanyDefaultGuardTest}
* 双向钉同源:只钉"清单里的都在 SQL 里"会漏掉"SQL 里有、清单漏了"那一半,而那一半才是静默的形状。</p>
* *
* <p>标记串({@link #ALARM} / {@link #PROBE_FAILED})是纯 ASCII:巡检脚本要在 docker logs 里 * <p>标记串({@link #ALARM} / {@link #PROBE_FAILED})是纯 ASCII:巡检脚本要在 docker logs 里
* grep 它,中文一旦在容器里变了编码就整条签名失效。</p> * grep 它,中文一旦在容器里变了编码就整条签名失效。</p>
@@ -39,14 +41,17 @@ public class CompanyDefaultGuard {
/** /**
* 该带 company_id 且历史上可能被塞过 DEFAULT 的表。新增一列就要在这里登记一条—— * 该带 company_id 且历史上可能被塞过 DEFAULT 的表。新增一列就要在这里登记一条——
* 漏登记的后果不是报错,是哨兵对着一个不存在的列一声不响({@link #check} 会把它当探不到处理)。 * 漏登记的后果不是报错,是哨兵对着一个不存在的列一声不响({@link #check} 会把它当探不到处理)。
* V147 的 {@code biz_product_category} 是第四条:它的 DEFAULT 1 同样只为同批旧 jar 存在,
* 摘除动作与上面三张同形(一条元数据操作,禁 MODIFY)。
*/ */
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"); "users", "biz_invalid_asin_data", "biz_dedupe_total_data", "biz_product_category");
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_invalid_asin_data', 'biz_dedupe_total_data',
'biz_product_category')
"""; """;
private final CompanyMapper companyMapper; private final CompanyMapper companyMapper;
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.dedupe.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.common.util.DownloadHeaderUtil; import com.nanri.aiimage.common.util.DownloadHeaderUtil;
import com.nanri.aiimage.modules.dedupe.model.dto.DedupeTotalDataCreateRequest; import com.nanri.aiimage.modules.dedupe.model.dto.DedupeTotalDataCreateRequest;
import com.nanri.aiimage.modules.dedupe.model.dto.DedupeTotalDataUpdateRequest; import com.nanri.aiimage.modules.dedupe.model.dto.DedupeTotalDataUpdateRequest;
@@ -48,6 +49,7 @@ 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.security.MessageDigest; import java.security.MessageDigest;
import java.util.List;
@RestController @RestController
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -65,6 +67,7 @@ public class DedupeTotalDataController {
private final DedupeTotalDataService dedupeTotalDataService; private final DedupeTotalDataService dedupeTotalDataService;
private final AdminAuthSupport adminAuthSupport; private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService; private final PermissionMenuService permissionMenuService;
private final DataReadScope dataReadScope;
@@ -86,10 +89,16 @@ public class DedupeTotalDataController {
@Parameter(description = "国家代码(如 DE、UK)") @RequestParam(name = "country", required = false) String country, @Parameter(description = "国家代码(如 DE、UK)") @RequestParam(name = "country", required = false) String country,
@Parameter(description = "顺序翻页游标(上一页返回的 nextLastId;传了就忽略 page 偏移)") @Parameter(description = "顺序翻页游标(上一页返回的 nextLastId;传了就忽略 page 偏移)")
@RequestParam(name = "last_id", required = false) Long lastId, @RequestParam(name = "last_id", required = false) Long lastId,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
HttpServletRequest request) { HttpServletRequest request) {
RequestOperator operator = requireDedupeTotalDataAccess(request); RequestOperator operator = requireDedupeTotalDataAccess(request);
AdminUserEntity user = operator.user();
List<Long> memberIds = operator.superAdmin()
? dataReadScope.readScope(user, companyId).userIdsOr(null)
: null;
return ApiResponse.success(dedupeTotalDataService.page( return ApiResponse.success(dedupeTotalDataService.page(
page, pageSize, keyword, username, startDate, endDate, groupId, country, lastId, operator.id())); page, pageSize, keyword, username, startDate, endDate, groupId, country, lastId,
operator.id(), memberIds));
} }
@GetMapping("/export") @GetMapping("/export")
@@ -102,19 +111,27 @@ public class DedupeTotalDataController {
@RequestParam(name = "end_date", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate, @RequestParam(name = "end_date", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
@Parameter(description = "分组 ID") @RequestParam(name = "group_id", required = false) Long groupId, @Parameter(description = "分组 ID") @RequestParam(name = "group_id", required = false) Long groupId,
@Parameter(description = "国家代码(如 DE、UK)") @RequestParam(name = "country", required = false) String country, @Parameter(description = "国家代码(如 DE、UK)") @RequestParam(name = "country", required = false) String country,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
HttpServletRequest request) { HttpServletRequest request) {
if (startDate != null && endDate != null && startDate.isAfter(endDate)) { if (startDate != null && endDate != null && startDate.isAfter(endDate)) {
throw new BusinessException(400, "invalid export date range"); throw new BusinessException(400, "invalid export date range");
} }
RequestOperator operator = requireDedupeTotalDataAccess(request); RequestOperator operator = requireDedupeTotalDataAccess(request);
AdminUserEntity user = operator.user();
Long operatorId = operator.id();
List<Long> memberIds = operator.superAdmin()
? dataReadScope.readScope(user, companyId).userIdsOr(null)
: null;
boolean monthlyZip = isCrossMonthRange(startDate, endDate); boolean monthlyZip = isCrossMonthRange(startDate, endDate);
String filename = "dedupe-total-data-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER) String filename = "dedupe-total-data-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER)
+ (monthlyZip ? ".zip" : ".xlsx"); + (monthlyZip ? ".zip" : ".xlsx");
// 两个分支的实参表都不许出现嵌套括号(operator.id() 那种写法护栏 G2 的单层括号判据看不穿,
// 会把它当成"范围没交给任何调用"而假红),所以 operatorId 先在局部变量里落好。
StreamingResponseBody body = monthlyZip StreamingResponseBody body = monthlyZip
? outputStream -> dedupeTotalDataService.writeMonthlyZipExport( ? outputStream -> dedupeTotalDataService.writeMonthlyZipExport(
outputStream, username, startDate, endDate, groupId, country, operator.id()) outputStream, username, startDate, endDate, groupId, country, operatorId, memberIds)
: outputStream -> dedupeTotalDataService.writeExport( : outputStream -> dedupeTotalDataService.writeExport(
outputStream, username, startDate, endDate, groupId, country, operator.id()); outputStream, username, startDate, endDate, groupId, country, operatorId, memberIds);
return ResponseEntity.ok() return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, DownloadHeaderUtil.contentDisposition(filename)) .header(HttpHeaders.CONTENT_DISPOSITION, DownloadHeaderUtil.contentDisposition(filename))
.contentType(MediaType.parseMediaType(monthlyZip ? ZIP_CONTENT_TYPE : XLSX_CONTENT_TYPE)) .contentType(MediaType.parseMediaType(monthlyZip ? ZIP_CONTENT_TYPE : XLSX_CONTENT_TYPE))
@@ -224,7 +241,7 @@ public class DedupeTotalDataController {
if (!superAdmin && !hasDedupeTotalDataPermission(operator)) { if (!superAdmin && !hasDedupeTotalDataPermission(operator)) {
throw new BusinessException(403, "无权访问数据去重总数据"); throw new BusinessException(403, "无权访问数据去重总数据");
} }
return new RequestOperator(operator.getId(), superAdmin); return new RequestOperator(operator.getId(), superAdmin, operator);
} }
private AdminUserEntity resolveOperator(HttpServletRequest request) { private AdminUserEntity resolveOperator(HttpServletRequest request) {
@@ -267,7 +284,13 @@ public class DedupeTotalDataController {
private record RequestOperator(Long id, boolean superAdmin) { // 公司 tab 的读范围就地算在 handler 里,不留私有收口方法:G2 的断言 A 只在这支 handler 的
// 块内找 readScope(,私有方法在它自己的闭括号处收口、不算在内(CompanyIdParamGoesThroughReadScopeTest
// 类注释第 5、7 条),挪进去 = 这一页的 tab 没人看守。收窄只给超管:非超管已由 resolveAccessScope
// 按会话裁剪,且他的可见集里含「靠分组可见」的行,叠一层账号 IN 会把那批行静默删掉
// (同 ShopManageController 的口径)。
private record RequestOperator(Long id, boolean superAdmin, AdminUserEntity user) {
} }
private boolean isTrustedInternalRequest(String suppliedToken) { private boolean isTrustedInternalRequest(String suppliedToken) {
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken); return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
@@ -160,16 +160,18 @@ public class DedupeTotalDataService {
public DedupeTotalDataPageVo page(long page, long pageSize, String keyword, String username, public DedupeTotalDataPageVo page(long page, long pageSize, String keyword, String username,
LocalDate startDate, LocalDate endDate, Long groupId, String country, Long operatorId) { LocalDate startDate, LocalDate endDate, Long groupId, String country, Long operatorId) {
return page(page, pageSize, keyword, username, startDate, endDate, groupId, country, null, operatorId); return page(page, pageSize, keyword, username, startDate, endDate, groupId, country, null, operatorId, null);
} }
/** /**
* @param lastId keyset 游标(上一页返回的 nextLastId);非空时忽略 page 偏移, * @param lastId keyset 游标(上一页返回的 nextLastId);非空时忽略 page 偏移,
* 直接按 id 倒序取"比它小"的一页,避免深分页 offset 扫索引的代价 * 直接按 id 倒序取"比它小"的一页,避免深分页 offset 扫索引的代价
* @param companyMemberIds 公司 tab 收窄后的成员账号集({@code DataReadScope} 给出);
* null = 不筛(超管没选公司 / 非超管走会话范围)
*/ */
public DedupeTotalDataPageVo page(long page, long pageSize, String keyword, String username, public DedupeTotalDataPageVo page(long page, long pageSize, String keyword, String username,
LocalDate startDate, LocalDate endDate, Long groupId, String country, LocalDate startDate, LocalDate endDate, Long groupId, String country,
Long lastId, Long operatorId) { Long lastId, Long operatorId, List<Long> companyMemberIds) {
if (startDate != null && endDate != null && startDate.isAfter(endDate)) { if (startDate != null && endDate != null && startDate.isAfter(endDate)) {
throw new BusinessException("开始日期不能晚于结束日期"); throw new BusinessException("开始日期不能晚于结束日期");
} }
@@ -194,6 +196,7 @@ public class DedupeTotalDataService {
endDate == null ? null : endDate.plusDays(1).atStartOfDay()) endDate == null ? null : endDate.plusDays(1).atStartOfDay())
.orderByDesc(DedupeTotalDataEntity::getId); .orderByDesc(DedupeTotalDataEntity::getId);
applyGroupScope(query, scope, groupId); applyGroupScope(query, scope, groupId);
applyCompanyScope(query, companyMemberIds);
Long total = dedupeTotalDataMapper.selectCount(query); Long total = dedupeTotalDataMapper.selectCount(query);
boolean keyset = lastId != null && lastId > 0; boolean keyset = lastId != null && lastId > 0;
if (keyset) { if (keyset) {
@@ -256,6 +259,17 @@ public class DedupeTotalDataService {
Long groupId, Long groupId,
String country, String country,
Long operatorId) { Long operatorId) {
writeExport(outputStream, username, startDate, endDate, groupId, country, operatorId, null);
}
public void writeExport(OutputStream outputStream,
String username,
LocalDate startDate,
LocalDate endDate,
Long groupId,
String country,
Long operatorId,
List<Long> companyMemberIds) {
if (outputStream == null) { if (outputStream == null) {
throw new BusinessException("导出输出流不能为空"); throw new BusinessException("导出输出流不能为空");
} }
@@ -264,7 +278,8 @@ public class DedupeTotalDataService {
} }
String safeUsername = username == null ? "" : username.trim(); String safeUsername = username == null ? "" : username.trim();
AccessScope scope = resolveAccessScope(operatorId); AccessScope scope = resolveAccessScope(operatorId);
buildExportWorkbook(outputStream, safeUsername, startDate, endDate, groupId, country, scope); buildExportWorkbook(outputStream, safeUsername, startDate, endDate, groupId, country, scope, false,
companyMemberIds);
} }
public void writeMonthlyZipExport(OutputStream outputStream, public void writeMonthlyZipExport(OutputStream outputStream,
@@ -283,11 +298,22 @@ public class DedupeTotalDataService {
Long groupId, Long groupId,
String country, String country,
Long operatorId) { Long operatorId) {
writeMonthlyZipExport(outputStream, username, startDate, endDate, groupId, country, operatorId, null);
}
public void writeMonthlyZipExport(OutputStream outputStream,
String username,
LocalDate startDate,
LocalDate endDate,
Long groupId,
String country,
Long operatorId,
List<Long> companyMemberIds) {
if (outputStream == null) { if (outputStream == null) {
throw new BusinessException("export output stream cannot be null"); throw new BusinessException("export output stream cannot be null");
} }
if (startDate == null || endDate == null || YearMonth.from(startDate).equals(YearMonth.from(endDate))) { if (startDate == null || endDate == null || YearMonth.from(startDate).equals(YearMonth.from(endDate))) {
writeExport(outputStream, username, startDate, endDate, groupId, country, operatorId); writeExport(outputStream, username, startDate, endDate, groupId, country, operatorId, companyMemberIds);
return; return;
} }
if (startDate.isAfter(endDate)) { if (startDate.isAfter(endDate)) {
@@ -311,7 +337,7 @@ public class DedupeTotalDataService {
LocalDate entryEndDate = endDate.isBefore(monthEnd) ? endDate : monthEnd; LocalDate entryEndDate = endDate.isBefore(monthEnd) ? endDate : monthEnd;
zipOutputStream.putNextEntry(new ZipEntry(monthlyExportEntryName(currentMonth))); zipOutputStream.putNextEntry(new ZipEntry(monthlyExportEntryName(currentMonth)));
buildExportWorkbook(zipOutputStream, safeUsername, entryStartDate, entryEndDate, buildExportWorkbook(zipOutputStream, safeUsername, entryStartDate, entryEndDate,
groupId, safeCountry, scope, groupPrevalidated); groupId, safeCountry, scope, groupPrevalidated, companyMemberIds);
zipOutputStream.closeEntry(); zipOutputStream.closeEntry();
currentMonth = currentMonth.plusMonths(1); currentMonth = currentMonth.plusMonths(1);
} }
@@ -330,7 +356,7 @@ public class DedupeTotalDataService {
Long groupId, Long groupId,
String country, String country,
AccessScope scope) { AccessScope scope) {
buildExportWorkbook(outputStream, username, startDate, endDate, groupId, country, scope, false); buildExportWorkbook(outputStream, username, startDate, endDate, groupId, country, scope, false, null);
} }
private void buildExportWorkbook(OutputStream outputStream, private void buildExportWorkbook(OutputStream outputStream,
@@ -340,7 +366,8 @@ public class DedupeTotalDataService {
Long groupId, Long groupId,
String country, String country,
AccessScope scope, AccessScope scope,
boolean groupPrevalidated) { boolean groupPrevalidated,
List<Long> companyMemberIds) {
try (SXSSFWorkbook workbook = new SXSSFWorkbook(100)) { try (SXSSFWorkbook workbook = new SXSSFWorkbook(100)) {
Sheet sheet = workbook.createSheet("DedupeTotalData"); Sheet sheet = workbook.createSheet("DedupeTotalData");
Row header = sheet.createRow(0); Row header = sheet.createRow(0);
@@ -354,7 +381,7 @@ public class DedupeTotalDataService {
int rowIndex = 1; int rowIndex = 1;
while (true) { while (true) {
LambdaQueryWrapper<DedupeTotalDataEntity> pageQuery = buildExportQuery( LambdaQueryWrapper<DedupeTotalDataEntity> pageQuery = buildExportQuery(
username, startDate, endDate, groupId, country, scope, groupPrevalidated); username, startDate, endDate, groupId, country, scope, groupPrevalidated, companyMemberIds);
if (lastId != null) { if (lastId != null) {
pageQuery.lt(DedupeTotalDataEntity::getId, lastId); pageQuery.lt(DedupeTotalDataEntity::getId, lastId);
} }
@@ -402,7 +429,7 @@ public class DedupeTotalDataService {
LocalDate endDate, LocalDate endDate,
Long groupId, Long groupId,
AccessScope scope) { AccessScope scope) {
return buildExportQuery(username, startDate, endDate, groupId, null, scope, false); return buildExportQuery(username, startDate, endDate, groupId, null, scope, false, null);
} }
private LambdaQueryWrapper<DedupeTotalDataEntity> buildExportQuery(String username, private LambdaQueryWrapper<DedupeTotalDataEntity> buildExportQuery(String username,
@@ -411,7 +438,8 @@ public class DedupeTotalDataService {
Long groupId, Long groupId,
String country, String country,
AccessScope scope, AccessScope scope,
boolean groupPrevalidated) { boolean groupPrevalidated,
List<Long> companyMemberIds) {
String safeUsername = username == null ? "" : username.trim(); String safeUsername = username == null ? "" : username.trim();
String safeCountry = country == null ? "" : country.trim(); String safeCountry = country == null ? "" : country.trim();
LambdaQueryWrapper<DedupeTotalDataEntity> query = new LambdaQueryWrapper<DedupeTotalDataEntity>() LambdaQueryWrapper<DedupeTotalDataEntity> query = new LambdaQueryWrapper<DedupeTotalDataEntity>()
@@ -425,6 +453,7 @@ public class DedupeTotalDataService {
endDate == null ? null : endDate.plusDays(1).atStartOfDay()) endDate == null ? null : endDate.plusDays(1).atStartOfDay())
.orderByDesc(DedupeTotalDataEntity::getId); .orderByDesc(DedupeTotalDataEntity::getId);
applyGroupScope(query, scope, groupId, groupPrevalidated); applyGroupScope(query, scope, groupId, groupPrevalidated);
applyCompanyScope(query, companyMemberIds);
return query; return query;
} }
@@ -1252,6 +1281,26 @@ public class DedupeTotalDataService {
}); });
} }
/**
* 公司 tab 收窄:本表按「上传账号」认公司——{@code uploader_user_id} 是 NOT NULL(V75 先回灌再收紧),
* 且有 idx_uploader_user_id_id 可走点查。
*
* <p>不读 V145 新加的 company_id:写入侧实体没有该字段、{@code insertBatchIgnore} 的列清单也不带,
* 全靠 MySQL 的 DEFAULT 1 兜底,所以第 2 家账号新导入的行今天仍会被盖成公司 1。那一列不能当读侧依据。</p>
*
* <p>空集给一条不可能命中的条件而不是"不筛":tab 选了这家公司却看得到全平台,比看不到更坏。</p>
*/
private void applyCompanyScope(LambdaQueryWrapper<DedupeTotalDataEntity> query, List<Long> companyMemberIds) {
if (companyMemberIds == null) {
return;
}
if (companyMemberIds.isEmpty()) {
query.eq(DedupeTotalDataEntity::getId, -1L);
return;
}
query.in(DedupeTotalDataEntity::getUploaderUserId, companyMemberIds);
}
private ShopManageGroupEntity resolveWritableGroup(Long groupId, AdminUserEntity operator) { private ShopManageGroupEntity resolveWritableGroup(Long groupId, AdminUserEntity operator) {
if (groupId == null || groupId <= 0) { if (groupId == null || groupId <= 0) {
throw new BusinessException("请选择分组"); throw new BusinessException("请选择分组");
@@ -3,6 +3,7 @@ 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;
@@ -49,6 +50,7 @@ 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 = "分页查询不符合ASIN数据", description = "分页查询不符合ASIN数据,支持按 ASIN/品牌 模糊搜索。")
@@ -62,10 +64,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
@@ -121,7 +127,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); return new RequestOperator(operator.getId(), superAdmin, operator);
} }
private AdminUserEntity resolveOperator(HttpServletRequest request) { private AdminUserEntity resolveOperator(HttpServletRequest request) {
@@ -164,7 +170,7 @@ public class InvalidAsinDataController {
private record RequestOperator(Long id, boolean superAdmin) { private record RequestOperator(Long id, boolean superAdmin, AdminUserEntity user) {
} }
private boolean isTrustedInternalRequest(String suppliedToken) { private boolean isTrustedInternalRequest(String suppliedToken) {
return adminAuthSupport.isTrustedSuppliedToken(suppliedToken); return adminAuthSupport.isTrustedSuppliedToken(suppliedToken);
@@ -12,18 +12,22 @@ import java.util.List;
public interface InvalidAsinDataMapper extends BaseMapper<InvalidAsinDataEntity> { public interface InvalidAsinDataMapper extends BaseMapper<InvalidAsinDataEntity> {
/** /**
* 批量 INSERT IGNORE:命中唯一键 (data_value, brand) 的重复行静默跳过,幂等。 * 批量 INSERT IGNORE:命中唯一键 (company_id, 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,
* 这一列显式传 null 不会走 DEFAULT 1,而是直接报错(上面 created_at 那段说的正是这类列的
* "宽松模式才静默"),所以归属推不出来时调用方必须整批不写,而不是塞 null 进来。</p>
*/ */
@Insert(""" @Insert("""
<script> <script>
INSERT IGNORE INTO biz_invalid_asin_data INSERT IGNORE INTO biz_invalid_asin_data
(data_value, brand, record_source) (data_value, brand, record_source, company_id, uploader_user_id)
VALUES VALUES
<foreach collection="rows" item="row" separator=","> <foreach collection="rows" item="row" separator=",">
(#{row.dataValue}, #{row.brand}, #{row.recordSource}) (#{row.dataValue}, #{row.brand}, #{row.recordSource}, #{row.companyId}, #{row.uploaderUserId})
</foreach> </foreach>
</script> </script>
""") """)
@@ -18,6 +18,13 @@ public class InvalidAsinDataEntity {
private String dataValue; private String dataValue;
private String brand; private String brand;
private Long groupId; private Long groupId;
/**
* 归属公司(company.id)。列由 V145 物化,但**实体与批量 INSERT 的列清单此前都没带它**,
* 所以 2026-10-05 生产只读取证 14,801 行全是被 DEFAULT 1 盖出来的。写入侧从本版本起显式盖章。
*/
private Long companyId;
/** 归属账号:AUTO 行取 task.user_id、MANUAL 行取操作人;V145 之前的历史行为 NULL(无从追溯)。 */
private Long uploaderUserId;
private String recordSource; private String recordSource;
private LocalDateTime createdAt; private LocalDateTime createdAt;
/** /**
@@ -2,6 +2,7 @@ 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;
@@ -30,8 +31,10 @@ 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, Long groupId, Long operatorId, boolean superAdmin) { public InvalidAsinDataPageVo page(long page, long pageSize, String keyword, String dataValue, String brand,
Long groupId, Long operatorId, boolean superAdmin, Long companyFilterId) {
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();
@@ -45,6 +48,9 @@ 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) {
@@ -79,13 +85,17 @@ 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); ensureUnique(dataValue, null, companyId);
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.setRecordSource(RECORD_SOURCE_MANUAL); entity.setRecordSource(RECORD_SOURCE_MANUAL);
invalidAsinDataMapper.insert(entity); invalidAsinDataMapper.insert(entity);
return toItemVo(getById(entity.getId()), group.getGroupName()); return toItemVo(getById(entity.getId()), group.getGroupName());
@@ -104,7 +114,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); ensureUnique(dataValue, id, entity.getCompanyId());
entity.setDataValue(dataValue); entity.setDataValue(dataValue);
entity.setBrand(brand); entity.setBrand(brand);
String groupName = ""; String groupName = "";
@@ -142,8 +152,13 @@ public class InvalidAsinDataService {
return entity; return entity;
} }
private void ensureUnique(String dataValue, Long excludeId) { /**
* 应用层的重复预检必须与 V145 放宽后的唯一键同宽——(company_id, data_value, brand)。
* 少了公司这一维,第 2 家永远无法新增第 1 家已有的品牌(跨公司误报「ASIN 已存在」)。
*/
private void ensureUnique(String dataValue, Long excludeId, Long companyId) {
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);
@@ -1,6 +1,8 @@
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;
@@ -8,6 +10,7 @@ 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;
@@ -38,14 +41,17 @@ public class ProductCategoryController {
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,
adminAuthSupport.requireAdminOrInternal(request); @Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
return ApiResponse.success(productCategoryService.list(keyword)); AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
Long scopedCompanyId = dataReadScope.readCompanyId(operator, companyId);
return ApiResponse.success(productCategoryService.list(keyword, scopedCompanyId));
} }
@GetMapping("/product-categories/children") @GetMapping("/product-categories/children")
@@ -54,9 +60,11 @@ 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,
adminAuthSupport.requireAdminOrInternal(request); @Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
return ApiResponse.success(productCategoryService.children(parentId, page, pageSize)); AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
Long scopedCompanyId = dataReadScope.readCompanyId(operator, companyId);
return ApiResponse.success(productCategoryService.children(parentId, page, pageSize, scopedCompanyId));
} }
@GetMapping("/product-categories/search") @GetMapping("/product-categories/search")
@@ -65,18 +73,22 @@ 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,
adminAuthSupport.requireAdminOrInternal(request); @Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
return ApiResponse.success(productCategoryService.search(keyword, page, pageSize)); AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
Long scopedCompanyId = dataReadScope.readCompanyId(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,
adminAuthSupport.requireAdminOrInternal(request); @Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
byte[] bytes = productCategoryService.export(keyword); AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
Long scopedCompanyId = dataReadScope.readCompanyId(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))
@@ -90,8 +102,10 @@ public class ProductCategoryController {
public ApiResponse<ProductCategoryItemVo> create( public ApiResponse<ProductCategoryItemVo> create(
HttpServletRequest request, HttpServletRequest request,
@Valid @RequestBody ProductCategorySaveRequest body) { @Valid @RequestBody ProductCategorySaveRequest body) {
adminAuthSupport.requireAdminOrInternal(request); // 归属只从会话推(请求体一律不带 company_id):service 里 requireCompanyId 取不到就抛,
return ApiResponse.success("创建成功", productCategoryService.create(body)); // 不让 V147 的 DEFAULT 1 静默兜住。
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
return ApiResponse.success("创建成功", productCategoryService.create(body, operator.getId()));
} }
@PutMapping("/product-category/{id}") @PutMapping("/product-category/{id}")
@@ -13,6 +13,14 @@ 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,6 +4,7 @@ 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;
@@ -34,63 +35,109 @@ 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");
private final ProductCategoryMapper productCategoryMapper; /**
* 内置节点的哨兵归属(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 CompanyScopeSupport companyScopeSupport;
/**
* 全平台类目树——<b>不按公司筛,且不许改成按公司筛</b>。
*
* <p>唯一的消费者是货源/外观的类目归类({@code SimilarAsinLlmService:215 CategoryTree.load(list())})。
* 那一侧按公司切会同时改两件事:候选节点变少(分类结果按公司分叉)与 prompt 里的类目表变化(影响 LLM 成本)。
* 后台的公司 tab 走 {@link #list(String, Long)},两件事别混。</p>
*/
public ProductCategoryListVo list() { public ProductCategoryListVo list() {
return list(null); return list(null);
} }
/** 不筛公司(超管没选 tab 时的口径,与改造前一致)。 */
public ProductCategoryListVo list(String keyword) { public ProductCategoryListVo list(String keyword) {
List<ProductCategoryEntity> rows = productCategoryMapper.selectList(new LambdaQueryWrapper<ProductCategoryEntity>() return list(keyword, null);
.orderByAsc(ProductCategoryEntity::getParentId) }
.orderByAsc(ProductCategoryEntity::getSortOrder)
.orderByAsc(ProductCategoryEntity::getId)); /**
* @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>()
.orderByAsc(ProductCategoryEntity::getParentId)
.orderByAsc(ProductCategoryEntity::getSortOrder)
.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 = new LambdaQueryWrapper<>(); LambdaQueryWrapper<ProductCategoryEntity> countQuery = applyCompanyScope(new LambdaQueryWrapper<>(), companyId);
applyParentFilter(countQuery, normalizedParentId); applyParentFilter(countQuery, normalizedParentId);
Long total = productCategoryMapper.selectCount(countQuery); Long total = productCategoryMapper.selectCount(countQuery);
LambdaQueryWrapper<ProductCategoryEntity> pageQuery = new LambdaQueryWrapper<ProductCategoryEntity>() LambdaQueryWrapper<ProductCategoryEntity> pageQuery = applyCompanyScope(
.orderByAsc(ProductCategoryEntity::getSortOrder) new LambdaQueryWrapper<ProductCategoryEntity>()
.orderByAsc(ProductCategoryEntity::getId) .orderByAsc(ProductCategoryEntity::getSortOrder)
.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); return buildPageVo(rows, total, safePage, safePageSize, companyId);
} }
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);
LambdaQueryWrapper<ProductCategoryEntity> countQuery = buildSearchQuery(normalized); Long total = productCategoryMapper.selectCount(buildSearchQuery(normalized, companyId));
Long total = productCategoryMapper.selectCount(countQuery); 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); return buildSearchPageVo(rows, total, safePage, safePageSize, companyId);
} }
/**
* 归属由<b>操作者会话</b>推导(请求体/查询参数一律不带 company_id):漏了这一句,新类目就会被
* V147 的 {@code DEFAULT 1} 静默塞进厦门米椿花——那是"归属失真且不报错",而 {@code requireCompanyId}
* 取不到公司时是抛,不会返回 null。所以这里<b>不保留</b>不带操作者的重载:留着它等于留着一个
* "调用方忘了传也照样绿"的出口。
*
* @param operatorId 操作者账号 id
*/
@Transactional @Transactional
public ProductCategoryItemVo create(ProductCategorySaveRequest request) { public ProductCategoryItemVo create(ProductCategorySaveRequest request, Long operatorId) {
String name = normalizeRequired(request.getName(), "类目名称不能为空"); String name = normalizeRequired(request.getName(), "类目名称不能为空");
Long parentId = normalizeParentId(request.getParentId()); Long parentId = normalizeParentId(request.getParentId());
ensureParentExists(parentId, null); Long companyId = companyScopeSupport.requireCompanyId(operatorId);
ensureSiblingNameUnique(parentId, name, null); ensureParentVisible(parentId, null, companyId);
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));
@@ -106,8 +153,11 @@ public class ProductCategoryService {
ProductCategoryEntity entity = getById(id); ProductCategoryEntity entity = getById(id);
String name = normalizeRequired(request.getName(), "类目名称不能为空"); String name = normalizeRequired(request.getName(), "类目名称不能为空");
Long parentId = normalizeParentId(request.getParentId()); Long parentId = normalizeParentId(request.getParentId());
ensureParentExists(parentId, id); // 改行时" Acting 公司"取行自己的归属,不取 tab:内置行归 0、自建行归那一家,
ensureSiblingNameUnique(parentId, name, id); // 换父级时不能把行挪到可见集外的节点下面(那会让它从原本看得见它的 tab 里消失)。
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);
@@ -163,8 +213,8 @@ public class ProductCategoryService {
return vo; return vo;
} }
private ProductCategoryListVo buildPageVo(List<ProductCategoryEntity> rows, Long total, long page, long pageSize) { private ProductCategoryListVo buildPageVo(List<ProductCategoryEntity> rows, Long total, long page, long pageSize, Long companyId) {
Map<Long, Integer> childCountById = buildChildCountById(rows); Map<Long, Integer> childCountById = buildChildCountById(rows, companyId);
List<ProductCategoryItemVo> items = rows.stream() List<ProductCategoryItemVo> items = rows.stream()
.map(row -> toItemVo(row, childCountById.getOrDefault(row.getId(), 0))) .map(row -> toItemVo(row, childCountById.getOrDefault(row.getId(), 0)))
.toList(); .toList();
@@ -178,8 +228,13 @@ public class ProductCategoryService {
return vo; return vo;
} }
/** 导出的行集合必须与页面列表同源:都走 {@link #list(String, Long)},否则"tab 里看不见但导出里有"就是第二个真相源。 */
public byte[] export(String keyword) { public byte[] export(String keyword) {
ProductCategoryListVo list = list(keyword); return export(keyword, null);
}
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);
@@ -198,8 +253,8 @@ public class ProductCategoryService {
} }
} }
private ProductCategoryListVo buildSearchPageVo(List<ProductCategoryEntity> rows, Long total, long page, long pageSize) { private ProductCategoryListVo buildSearchPageVo(List<ProductCategoryEntity> rows, Long total, long page, long pageSize, Long companyId) {
Map<Long, Integer> childCountById = buildChildCountById(rows); Map<Long, Integer> childCountById = buildChildCountById(rows, companyId);
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));
@@ -305,15 +360,23 @@ public class ProductCategoryService {
return time == null ? "" : time.format(EXPORT_TIME_FORMATTER); return time == null ? "" : time.format(EXPORT_TIME_FORMATTER);
} }
private Map<Long, Integer> buildChildCountById(List<ProductCategoryEntity> rows) { /**
* 列表页的「子类目数」徽章走的是<b>全表聚合</b>(不是内存里那批行),所以它必须和公司视图同源:
* 不加这一段,第 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;
} }
List<Map<String, Object>> countRows = productCategoryMapper.selectMaps(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");
.groupBy("parent_id")); if (companyId != null) {
countQuery.in("company_id", visibleCompanyIds(companyId));
}
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");
Object childCount = countRow.get("child_count"); Object childCount = countRow.get("child_count");
@@ -333,13 +396,40 @@ public class ProductCategoryService {
} }
} }
private LambdaQueryWrapper<ProductCategoryEntity> buildSearchQuery(String keyword) { /**
return new LambdaQueryWrapper<ProductCategoryEntity>() * 关键字命中三条列任一即算命中,但<b>整条 OR 必须包起来再 AND 公司</b>:MyBatis-Plus 的
.like(ProductCategoryEntity::getName, keyword) * {@code or()} 只改"下一个连接符",直接在这串后面 {@code .in(company_id, ...)} 会拼成
.or() * {@code name LIKE ? OR key LIKE ? OR (desc LIKE ? AND company_id IN ...)} —— SQL 里 AND 结合更紧,
.like(ProductCategoryEntity::getCategoryKey, keyword) * 结果前两条列命中的行<b>不受公司约束</b>,这一页的筛选就成了假的(且不报错)。
.or() */
.like(ProductCategoryEntity::getDescription, keyword); private LambdaQueryWrapper<ProductCategoryEntity> buildSearchQuery(String keyword, Long companyId) {
LambdaQueryWrapper<ProductCategoryEntity> query = new LambdaQueryWrapper<ProductCategoryEntity>()
.and(group -> group
.like(ProductCategoryEntity::getName, keyword)
.or()
.like(ProductCategoryEntity::getCategoryKey, keyword)
.or()
.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) {
@@ -495,7 +585,14 @@ public class ProductCategoryService {
return entity; return entity;
} }
private void ensureParentExists(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;
} }
@@ -506,6 +603,9 @@ 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) {
@@ -520,9 +620,17 @@ public class ProductCategoryService {
} }
} }
private void ensureSiblingNameUnique(Long parentId, String name, Long excludeId) { /**
* 同级重名检查的范围 = 这一家的<b>可见集</b>(自建 + 内置),不是只查自建。
*
* <p>只查自建会让第 2 家在内置父级"护肤品"下建出一个也叫"面霜"的节点,和内置的那个
* 同层同名——页面上一排两个"面霜",而货源归类按名字回填时不知道落到哪一个。
* 反过来,跨家的同名要放行:那正是 {@code uk_company_category_key} 换掉全平台唯一键要解决的问题。</p>
*/
private void ensureSiblingNameUnique(Long parentId, String name, Long excludeId, Long companyId) {
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 {
@@ -6,10 +6,12 @@ import com.nanri.aiimage.common.util.DownloadHeaderUtil;
import com.nanri.aiimage.config.HttpClientPool; import com.nanri.aiimage.config.HttpClientPool;
import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.model.entity.AdminUserEntity; import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService; import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import com.nanri.aiimage.modules.shopdatacrawl.model.dto.ShopDataCrawlDownloadRowDto; import com.nanri.aiimage.modules.shopdatacrawl.model.dto.ShopDataCrawlDownloadRowDto;
import com.nanri.aiimage.modules.shopdatacrawl.service.ShopDataCrawlAdminTasksService; import com.nanri.aiimage.modules.shopdatacrawl.service.ShopDataCrawlAdminTasksService;
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.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
@@ -76,6 +78,7 @@ public class AdminShopDataCrawlTasksController {
private final AdminAuthSupport adminAuthSupport; private final AdminAuthSupport adminAuthSupport;
private final PermissionMenuService permissionMenuService; private final PermissionMenuService permissionMenuService;
private final ShopDataCrawlAdminTasksService adminTasksService; private final ShopDataCrawlAdminTasksService adminTasksService;
private final DataReadScope dataReadScope;
@GetMapping @GetMapping
@Operation(summary = "店铺数据抓取记录:按店铺分组分页列表(每店最新结果文件)") @Operation(summary = "店铺数据抓取记录:按店铺分组分页列表(每店最新结果文件)")
@@ -87,13 +90,19 @@ public class AdminShopDataCrawlTasksController {
@RequestParam(name = "group_name", required = false) String groupName, @RequestParam(name = "group_name", required = false) String groupName,
@RequestParam(name = "country", required = false) String country, @RequestParam(name = "country", required = false) String country,
@RequestParam(name = "created_from", required = false) String createdFrom, @RequestParam(name = "created_from", required = false) String createdFrom,
@RequestParam(name = "created_to", required = false) String createdTo) { @RequestParam(name = "created_to", required = false) String createdTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = requireShopDataCrawlTaskAccess(request); AdminUserEntity operator = requireShopDataCrawlTaskAccess(request);
int safePage = Math.max(1, parseInt(page, 1, "page 参数不合法")); int safePage = Math.max(1, parseInt(page, 1, "page 参数不合法"));
int safePageSize = Math.min(PAGE_SIZE_MAX, int safePageSize = Math.min(PAGE_SIZE_MAX,
Math.max(10, parseInt(pageSize, PAGE_SIZE_DEFAULT, "page_size 参数不合法"))); Math.max(10, parseInt(pageSize, PAGE_SIZE_DEFAULT, "page_size 参数不合法")));
boolean superAdmin = "super_admin".equals(adminAuthSupport.currentRole(operator)); boolean superAdmin = "super_admin".equals(adminAuthSupport.currentRole(operator));
List<String> visibleShopKeys = superAdmin ? null : resolveVisibleShopNameKeys(operator.getId()); // 成员集就地算,且只在超管这一支算(口径同最低价ASIN/查询ASIN);null = 不筛=今天的超管全量。
List<Long> companyMemberIds = superAdmin
? dataReadScope.readScope(operator, companyId).userIdsOr(null)
: null;
List<String> visibleShopKeys = adminTasksService.resolveVisibleShopKeys(
operator.getId(), superAdmin, companyMemberIds);
Map<String, Object> payload = adminTasksService.listShopGroups( Map<String, Object> payload = adminTasksService.listShopGroups(
safePage, safePageSize, shopName, groupName, country, createdFrom, createdTo, visibleShopKeys); safePage, safePageSize, shopName, groupName, country, createdFrom, createdTo, visibleShopKeys);
return ApiResponse.success(payload); return ApiResponse.success(payload);
@@ -282,11 +291,6 @@ public class AdminShopDataCrawlTasksController {
return operator; return operator;
} }
/** 非超管返回其可管店铺名(trim+小写去重,与撞款可见口径一致);超管调用方传 null 表示全量。 */
private List<String> resolveVisibleShopNameKeys(Long operatorId) {
return adminTasksService.resolveVisibleShopNameKeys(operatorId);
}
private AdminUserEntity resolveInternalOperator(HttpServletRequest request) { private AdminUserEntity resolveInternalOperator(HttpServletRequest request) {
String suppliedToken = request.getHeader("X-Internal-Token"); String suppliedToken = request.getHeader("X-Internal-Token");
if (!isTrustedInternalRequest(suppliedToken)) { if (!isTrustedInternalRequest(suppliedToken)) {
@@ -222,9 +222,26 @@ public class ShopDataCrawlAdminTasksService {
return rows; return rows;
} }
/** 非超管可管店铺名(trim+小写去重,与撞款可见口径一致);超管调用方传 null 表示全量。 */ /**
public List<String> resolveVisibleShopNameKeys(Long operatorId) { * 可见店铺名 key 集(trim+小写去重,与撞款页口径一致);返回 {@code null} 表示全量。
List<String> names = managedShopNamesPort.selectManagedShopNames(operatorId); *
* <p>公司条件只在超管这一支生效({@code companyMemberIds} 由 controller 经 {@code DataReadScope} 算好传入),
* 非超管一律按分组关系推——他在这一页看到的范围不随 tab 变化,这条与撞款页逐字一致,
* 也与 {@code ShopManageService.page} 的注释同源:给非超管叠 created_by IN 成员会把
* 「只挂了 user_id 的分组」那批店铺静默删掉。</p>
*/
public List<String> resolveVisibleShopKeys(Long operatorId, boolean superAdmin, List<Long> companyMemberIds) {
if (!superAdmin) {
return shopNameKeys(managedShopNamesPort.selectManagedShopNames(operatorId));
}
if (companyMemberIds == null) {
return null;
}
// 端口对空成员集返回空列表 ⇒ 这里自然得到空列表("这家没有店铺"),不会退化成 null("全量")。
return shopNameKeys(managedShopNamesPort.selectShopNamesOwnedByMembers(companyMemberIds));
}
private static List<String> shopNameKeys(List<String> names) {
if (names == null || names.isEmpty()) { if (names == null || names.isEmpty()) {
return List.of(); return List.of();
} }
@@ -11,4 +11,12 @@ public interface ManagedShopNamesPort {
/** 该操作人可管的店铺名;传 null 表示全量(超管调用方)。 */ /** 该操作人可管的店铺名;传 null 表示全量(超管调用方)。 */
List<String> selectManagedShopNames(Long operatorId); List<String> selectManagedShopNames(Long operatorId);
/**
* 某家公司的店铺名(按店铺行自己的负责人推,口径同「店铺管理」页的公司 tab)。
*
* <p>空成员集必须由调用方挡住:这条是给「切到第 2 家」用的,成员为空=这家公司一家店铺都没有,
* 该返回空集合(页面显示"没有店铺"),而不是把空 IN 丢进 SQL。</p>
*/
List<String> selectShopNamesOwnedByMembers(List<Long> memberIds);
} }
@@ -5,12 +5,14 @@ import com.nanri.aiimage.common.exception.BusinessException;
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.common.model.entity.AdminUserEntity; import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService; import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import com.nanri.aiimage.modules.shopduplicatecheck.service.ShopDataDuplicateCheckImportService; import com.nanri.aiimage.modules.shopduplicatecheck.service.ShopDataDuplicateCheckImportService;
import com.nanri.aiimage.modules.shopduplicatecheck.service.ShopDataDuplicateCheckQueryService; import com.nanri.aiimage.modules.shopduplicatecheck.service.ShopDataDuplicateCheckQueryService;
import com.nanri.aiimage.modules.shopduplicatecheck.service.ShopDataDuplicateCheckScanService; import com.nanri.aiimage.modules.shopduplicatecheck.service.ShopDataDuplicateCheckScanService;
import com.nanri.aiimage.modules.shopduplicatecheck.service.ShopDataDuplicateCheckScanService.DuplicateScanView; import com.nanri.aiimage.modules.shopduplicatecheck.service.ShopDataDuplicateCheckScanService.DuplicateScanView;
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.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
@@ -30,6 +32,7 @@ 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.security.MessageDigest; import java.security.MessageDigest;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@@ -51,12 +54,14 @@ public class AdminShopDataDuplicateCheckController {
private final ShopDataDuplicateCheckScanService scanService; private final ShopDataDuplicateCheckScanService scanService;
private final ShopDataDuplicateCheckQueryService queryService; private final ShopDataDuplicateCheckQueryService queryService;
private final ShopDataDuplicateCheckImportService importService; private final ShopDataDuplicateCheckImportService importService;
private final DataReadScope dataReadScope;
@GetMapping("/duplicate-check-overview") @GetMapping("/duplicate-check-overview")
@Operation(summary = "撞款指标与店铺分布(force=1 触发同步重扫)") @Operation(summary = "撞款指标与店铺分布(force=1 触发同步重扫)")
public ApiResponse<Object> overview( public ApiResponse<Object> overview(
HttpServletRequest request, HttpServletRequest request,
@RequestParam(name = "force", required = false) String force) { @RequestParam(name = "force", required = false) String force,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
RequestOperator operator = requireDuplicateCheckAccess(request); RequestOperator operator = requireDuplicateCheckAccess(request);
boolean forced = force != null && ("1".equals(force.trim().toLowerCase()) boolean forced = force != null && ("1".equals(force.trim().toLowerCase())
|| "true".equals(force.trim().toLowerCase()) || "yes".equals(force.trim().toLowerCase())); || "true".equals(force.trim().toLowerCase()) || "yes".equals(force.trim().toLowerCase()));
@@ -68,7 +73,11 @@ public class AdminShopDataDuplicateCheckController {
if (view == null) { if (view == null) {
return ApiResponse.success(queryService.pendingOverview()); return ApiResponse.success(queryService.pendingOverview());
} }
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(operator.id(), operator.superAdmin()); List<Long> companyMemberIds = operator.superAdmin()
? dataReadScope.readScope(operator.user(), companyId).userIdsOr(null)
: null;
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(
operator.id(), operator.superAdmin(), companyMemberIds);
return ApiResponse.success(queryService.overviewData(view, visibleKeys)); return ApiResponse.success(queryService.overviewData(view, visibleKeys));
} }
@@ -84,7 +93,8 @@ public class AdminShopDataDuplicateCheckController {
@RequestParam(name = "country", required = false) String country, @RequestParam(name = "country", required = false) String country,
@RequestParam(name = "site", required = false) String site, @RequestParam(name = "site", required = false) String site,
@RequestParam(name = "date_from", required = false) String dateFrom, @RequestParam(name = "date_from", required = false) String dateFrom,
@RequestParam(name = "date_to", required = false) String dateTo) { @RequestParam(name = "date_to", required = false) String dateTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
RequestOperator operator = requireDuplicateCheckAccess(request); RequestOperator operator = requireDuplicateCheckAccess(request);
int safePage = parsePage(page); int safePage = parsePage(page);
int safeSize = clamp(parseSize(pageSize, 20), 10, 100); int safeSize = clamp(parseSize(pageSize, 20), 10, 100);
@@ -95,7 +105,11 @@ public class AdminShopDataDuplicateCheckController {
if (scan == null) { if (scan == null) {
return ApiResponse.success(queryService.pendingList(safePage, safeSize)); return ApiResponse.success(queryService.pendingList(safePage, safeSize));
} }
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(operator.id(), operator.superAdmin()); List<Long> companyMemberIds = operator.superAdmin()
? dataReadScope.readScope(operator.user(), companyId).userIdsOr(null)
: null;
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(
operator.id(), operator.superAdmin(), companyMemberIds);
return ApiResponse.success(queryService.itemsData(scan, visibleKeys, safePage, safeSize, viewMode, filters)); return ApiResponse.success(queryService.itemsData(scan, visibleKeys, safePage, safeSize, viewMode, filters));
} }
@@ -110,7 +124,8 @@ public class AdminShopDataDuplicateCheckController {
@RequestParam(name = "country", required = false) String country, @RequestParam(name = "country", required = false) String country,
@RequestParam(name = "site", required = false) String site, @RequestParam(name = "site", required = false) String site,
@RequestParam(name = "date_from", required = false) String dateFrom, @RequestParam(name = "date_from", required = false) String dateFrom,
@RequestParam(name = "date_to", required = false) String dateTo) { @RequestParam(name = "date_to", required = false) String dateTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
RequestOperator operator = requireDuplicateCheckAccess(request); RequestOperator operator = requireDuplicateCheckAccess(request);
int safePage = parsePage(page); int safePage = parsePage(page);
int safeSize = clamp(parseSize(pageSize, 6), 1, 24); int safeSize = clamp(parseSize(pageSize, 6), 1, 24);
@@ -120,7 +135,11 @@ public class AdminShopDataDuplicateCheckController {
if (scan == null) { if (scan == null) {
return ApiResponse.success(queryService.pendingDetail(safePage, safeSize)); return ApiResponse.success(queryService.pendingDetail(safePage, safeSize));
} }
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(operator.id(), operator.superAdmin()); List<Long> companyMemberIds = operator.superAdmin()
? dataReadScope.readScope(operator.user(), companyId).userIdsOr(null)
: null;
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(
operator.id(), operator.superAdmin(), companyMemberIds);
return ApiResponse.success(queryService.detailData(scan, visibleKeys, safePage, safeSize, filters)); return ApiResponse.success(queryService.detailData(scan, visibleKeys, safePage, safeSize, filters));
} }
@@ -134,7 +153,8 @@ public class AdminShopDataDuplicateCheckController {
@RequestParam(name = "country", required = false) String country, @RequestParam(name = "country", required = false) String country,
@RequestParam(name = "site", required = false) String site, @RequestParam(name = "site", required = false) String site,
@RequestParam(name = "date_from", required = false) String dateFrom, @RequestParam(name = "date_from", required = false) String dateFrom,
@RequestParam(name = "date_to", required = false) String dateTo) { @RequestParam(name = "date_to", required = false) String dateTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
RequestOperator operator = requireDuplicateCheckAccess(request); RequestOperator operator = requireDuplicateCheckAccess(request);
ShopDataDuplicateCheckQueryService.Filters filters = ShopDataDuplicateCheckQueryService.Filters filters =
ShopDataDuplicateCheckQueryService.Filters.clean(asin, shopName, country, site, dateFrom, dateTo); ShopDataDuplicateCheckQueryService.Filters.clean(asin, shopName, country, site, dateFrom, dateTo);
@@ -142,7 +162,11 @@ public class AdminShopDataDuplicateCheckController {
if (scan == null) { if (scan == null) {
return ApiResponse.success(queryService.pendingConsole()); return ApiResponse.success(queryService.pendingConsole());
} }
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(operator.id(), operator.superAdmin()); List<Long> companyMemberIds = operator.superAdmin()
? dataReadScope.readScope(operator.user(), companyId).userIdsOr(null)
: null;
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(
operator.id(), operator.superAdmin(), companyMemberIds);
Set<String> effectiveKeys = queryService.withGroupFilter(visibleKeys, scan, group); Set<String> effectiveKeys = queryService.withGroupFilter(visibleKeys, scan, group);
return ApiResponse.success(queryService.consoleData(scan, effectiveKeys, filters)); return ApiResponse.success(queryService.consoleData(scan, effectiveKeys, filters));
} }
@@ -161,7 +185,8 @@ public class AdminShopDataDuplicateCheckController {
@RequestParam(name = "country", required = false) String country, @RequestParam(name = "country", required = false) String country,
@RequestParam(name = "site", required = false) String site, @RequestParam(name = "site", required = false) String site,
@RequestParam(name = "date_from", required = false) String dateFrom, @RequestParam(name = "date_from", required = false) String dateFrom,
@RequestParam(name = "date_to", required = false) String dateTo) { @RequestParam(name = "date_to", required = false) String dateTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
RequestOperator operator = requireDuplicateCheckAccess(request); RequestOperator operator = requireDuplicateCheckAccess(request);
int safePage = parsePage(page); int safePage = parsePage(page);
int safeSize = clamp(parseSize(pageSize, 100), 1, 200); int safeSize = clamp(parseSize(pageSize, 100), 1, 200);
@@ -171,7 +196,11 @@ public class AdminShopDataDuplicateCheckController {
if (scan == null) { if (scan == null) {
return ApiResponse.success(queryService.pendingLedger(safePage, safeSize)); return ApiResponse.success(queryService.pendingLedger(safePage, safeSize));
} }
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(operator.id(), operator.superAdmin()); List<Long> companyMemberIds = operator.superAdmin()
? dataReadScope.readScope(operator.user(), companyId).userIdsOr(null)
: null;
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(
operator.id(), operator.superAdmin(), companyMemberIds);
Set<String> effectiveKeys = queryService.withGroupFilter(visibleKeys, scan, group); Set<String> effectiveKeys = queryService.withGroupFilter(visibleKeys, scan, group);
return ApiResponse.success(queryService.ledgerData(scan, effectiveKeys, safePage, safeSize, sortKey, sortDir, filters)); return ApiResponse.success(queryService.ledgerData(scan, effectiveKeys, safePage, safeSize, sortKey, sortDir, filters));
} }
@@ -187,7 +216,8 @@ public class AdminShopDataDuplicateCheckController {
@RequestParam(name = "country", required = false) String country, @RequestParam(name = "country", required = false) String country,
@RequestParam(name = "site", required = false) String site, @RequestParam(name = "site", required = false) String site,
@RequestParam(name = "date_from", required = false) String dateFrom, @RequestParam(name = "date_from", required = false) String dateFrom,
@RequestParam(name = "date_to", required = false) String dateTo) { @RequestParam(name = "date_to", required = false) String dateTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
RequestOperator operator = requireDuplicateCheckAccess(request); RequestOperator operator = requireDuplicateCheckAccess(request);
DuplicateScanView scan = scanService.loadLatest(); DuplicateScanView scan = scanService.loadLatest();
if (scan == null) { if (scan == null) {
@@ -196,7 +226,11 @@ public class AdminShopDataDuplicateCheckController {
String viewMode = view == null ? "monitor" : view.trim().toLowerCase(); String viewMode = view == null ? "monitor" : view.trim().toLowerCase();
ShopDataDuplicateCheckQueryService.Filters filters = ShopDataDuplicateCheckQueryService.Filters filters =
ShopDataDuplicateCheckQueryService.Filters.clean(asin, shopName, country, site, dateFrom, dateTo); ShopDataDuplicateCheckQueryService.Filters.clean(asin, shopName, country, site, dateFrom, dateTo);
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(operator.id(), operator.superAdmin()); List<Long> companyMemberIds = operator.superAdmin()
? dataReadScope.readScope(operator.user(), companyId).userIdsOr(null)
: null;
Set<String> visibleKeys = queryService.resolveVisibleShopKeys(
operator.id(), operator.superAdmin(), companyMemberIds);
try { try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
DownloadHeaderUtil.setAttachment(response, "shop-data-duplicate-check.xlsx"); DownloadHeaderUtil.setAttachment(response, "shop-data-duplicate-check.xlsx");
@@ -241,7 +275,15 @@ public class AdminShopDataDuplicateCheckController {
} }
} }
private record RequestOperator(Long id, boolean superAdmin) { /**
* 带上操作者实体:{@code DataReadScope.readScope} 只认 {@code AdminUserEntity}(它要读这一行的
* company_id 和角色),而 G2 护栏要求 {@code readScope(} 落在<b>每支 handler 体内</b>(私有收口方法
* 不算证据——那一支可以整批不接出口还跟着别人的绿),所以成员集只能就地算。
*/
private record RequestOperator(AdminUserEntity user, boolean superAdmin) {
Long id() {
return user.getId();
}
} }
private RequestOperator requireDuplicateCheckAccess(HttpServletRequest request) { private RequestOperator requireDuplicateCheckAccess(HttpServletRequest request) {
@@ -256,7 +298,7 @@ public class AdminShopDataDuplicateCheckController {
} }
permissionMenuService.requireShopDataCrawlTaskAccess(operator); permissionMenuService.requireShopDataCrawlTaskAccess(operator);
boolean superAdmin = "super_admin".equals(adminAuthSupport.currentRole(operator)); boolean superAdmin = "super_admin".equals(adminAuthSupport.currentRole(operator));
return new RequestOperator(operator.getId(), superAdmin); return new RequestOperator(operator, superAdmin);
} }
private AdminUserEntity resolveInternalOperator(HttpServletRequest request) { private AdminUserEntity resolveInternalOperator(HttpServletRequest request) {
@@ -96,4 +96,25 @@ public interface ShopDuplicateCheckSourceMapper {
) )
""") """)
List<String> selectManagedShopNames(@Param("operatorId") Long operatorId); List<String> selectManagedShopNames(@Param("operatorId") Long operatorId);
/**
* 公司 tab 的店铺名集:按店铺自己的负责人({@code biz_shop_manage.created_by_id})落在这批成员里推。
*
* <p>口径与「店铺管理」页 {@code ShopManageService.page} 的 companyMemberIds 那一段逐字同一把尺子:
* 同一个 tab 在店铺中心的两页上推出两个不同的店铺集合,比看到空页更糟(后者至少不会骗人)。
* 这里【不】走 {@code listCompanyGroupIds} 那条分组归属路线——分组归属认 created_by_id 与 user_id 两列,
* 而店铺管理页只认店铺行的 created_by_id;跟着已上线那页走,才不会出现「店铺管理看不到、撞款看得到」。</p>
*
* <p>空成员集不在这条 SQL 里兜:IN () 是语法错,调用方必须在 memberIds 为空时直接给空集合。</p>
*/
@Select("""
<script>
SELECT DISTINCT TRIM(sm.shop_name)
FROM biz_shop_manage sm
WHERE TRIM(COALESCE(sm.shop_name, '')) &lt;&gt; ''
AND sm.created_by_id IN
<foreach collection="memberIds" item="mid" open="(" separator="," close=")">#{mid}</foreach>
</script>
""")
List<String> selectShopNamesOwnedBy(@Param("memberIds") List<Long> memberIds);
} }
@@ -20,4 +20,12 @@ public class ManagedShopNamesPortAdapter implements ManagedShopNamesPort {
public List<String> selectManagedShopNames(Long operatorId) { public List<String> selectManagedShopNames(Long operatorId) {
return sourceMapper.selectManagedShopNames(operatorId); return sourceMapper.selectManagedShopNames(operatorId);
} }
@Override
public List<String> selectShopNamesOwnedByMembers(List<Long> memberIds) {
if (memberIds == null || memberIds.isEmpty()) {
return List.of();
}
return sourceMapper.selectShopNamesOwnedBy(memberIds);
}
} }
@@ -74,13 +74,34 @@ public class ShopDataDuplicateCheckQueryService {
return (shopName == null ? "" : shopName.trim()).toLowerCase(Locale.ROOT); return (shopName == null ? "" : shopName.trim()).toLowerCase(Locale.ROOT);
} }
/** 主管可见店铺 key 集;超管用 null 表示全量。 */ /**
public Set<String> resolveVisibleShopKeys(Long operatorId, boolean superAdmin) { * 可见店铺 key 集;{@code null} = 全量(超管没切公司 tab 时的今天)。
if (superAdmin) { *
* <p>{@code companyMemberIds} 只在超管这一支由 controller 算好传入(非超管一律 null:他的范围本来就锁在
* 分组关系上,叠一层 created_by IN 成员会把「只挂了 user_id 的分组」下的店铺整批静默删掉——
* 口径与「店铺管理/查询ASIN/最低价ASIN」三页逐字一致)。tab 是视图开关,不是安全边界。</p>
*
* <p><b>公司 tab 下的可见集是「店铺表里有、且负责人属于这家公司」的店铺</b>:扫描结果里那些
* 没登记进 biz_shop_manage 的店铺名(历史上传文件留下的)在任何公司 tab 下都不出现,
* 只有回到「全部」才看得到。这是按负责人推归属的必然代价,不是筛选坏了。</p>
*/
public Set<String> resolveVisibleShopKeys(Long operatorId, boolean superAdmin, List<Long> companyMemberIds) {
if (!superAdmin) {
return shopKeys(sourceMapper.selectManagedShopNames(operatorId));
}
if (companyMemberIds == null) {
return null; return null;
} }
// 空成员集=这家公司一个账号都没有=一家店铺都没有:必须给空集合(页面显示"没有店铺"),
// 绝不能退化成 null——null 在这里是"全量",会让第 2 家看到全部数据。
return companyMemberIds.isEmpty()
? new LinkedHashSet<>()
: shopKeys(sourceMapper.selectShopNamesOwnedBy(companyMemberIds));
}
private static Set<String> shopKeys(List<String> names) {
Set<String> keys = new LinkedHashSet<>(); Set<String> keys = new LinkedHashSet<>();
for (String name : sourceMapper.selectManagedShopNames(operatorId)) { for (String name : names) {
if (name != null && !name.isBlank()) { if (name != null && !name.isBlank()) {
keys.add(shopKey(name)); keys.add(shopKey(name));
} }
@@ -44,6 +44,7 @@ public class QueryAsinController {
private final QueryAsinService queryAsinService; private final QueryAsinService queryAsinService;
private final AdminAuthSupport adminAuthSupport; private final AdminAuthSupport adminAuthSupport;
private final com.nanri.aiimage.common.service.DataReadScope dataReadScope;
/** 解析当前操作者(JWT 或内部令牌通道),权限与数据范围一律以该身份为准。 */ /** 解析当前操作者(JWT 或内部令牌通道),权限与数据范围一律以该身份为准。 */
private AdminUserEntity requireOperator(HttpServletRequest request) { private AdminUserEntity requireOperator(HttpServletRequest request) {
@@ -51,7 +52,7 @@ public class QueryAsinController {
} }
@GetMapping @GetMapping
@Operation(summary = "分页查询 ASIN") @Operation(summary = "分页查询 ASIN", description = "company_id 只收窄可见集、不放大,跨公司查看仅超管")
public ApiResponse<QueryAsinPageVo> page( public ApiResponse<QueryAsinPageVo> page(
HttpServletRequest request, HttpServletRequest request,
@Parameter(description = "页码") @RequestParam(name = "page", defaultValue = "1") Long page, @Parameter(description = "页码") @RequestParam(name = "page", defaultValue = "1") Long page,
@@ -59,8 +60,14 @@ public class QueryAsinController {
@Parameter(description = "分组ID") @RequestParam(name = "group_id", required = false) Long groupId, @Parameter(description = "分组ID") @RequestParam(name = "group_id", required = false) Long groupId,
@Parameter(description = "店铺名") @RequestParam(name = "shop_name", required = false) String shopName, @Parameter(description = "店铺名") @RequestParam(name = "shop_name", required = false) String shopName,
@Parameter(description = "商品 ASIN") @RequestParam(name = "asin", required = false) String asin, @Parameter(description = "商品 ASIN") @RequestParam(name = "asin", required = false) String asin,
@Parameter(description = "国家代码(DE/UK/FR/IT/ES)") @RequestParam(name = "country", required = false) String country) { @Parameter(description = "国家代码(DE/UK/FR/IT/ES)") @RequestParam(name = "country", required = false) String country,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = requireOperator(request); AdminUserEntity operator = requireOperator(request);
// 成员集就地算,且只在超管这一支算(非超管靠分组关系推,叠 created_by_id IN 成员会把
// 「只挂了 user_id 的分组」那批行从每个 tab 里静默删掉——口径与店铺管理逐字一致)。
java.util.List<Long> memberIds = isSuper(operator)
? dataReadScope.readScope(operator, companyId).userIdsOr(null)
: null;
return ApiResponse.success(queryAsinService.page( return ApiResponse.success(queryAsinService.page(
page, page,
pageSize, pageSize,
@@ -69,20 +76,25 @@ public class QueryAsinController {
asin, asin,
country, country,
operator.getId(), operator.getId(),
isSuper(operator))); isSuper(operator),
memberIds));
} }
@GetMapping("/export") @GetMapping("/export")
@Operation(summary = "导出查询 ASIN") @Operation(summary = "导出查询 ASIN", description = "导出与列表同一个 company_id 范围,否则 tab 筛了表格、导出全量=越权泄露")
public ResponseEntity<byte[]> export( public ResponseEntity<byte[]> export(
HttpServletRequest request, HttpServletRequest request,
@Parameter(description = "分组ID") @RequestParam(name = "group_id", required = false) Long groupId, @Parameter(description = "分组ID") @RequestParam(name = "group_id", required = false) Long groupId,
@Parameter(description = "店铺名") @RequestParam(name = "shop_name", required = false) String shopName, @Parameter(description = "店铺名") @RequestParam(name = "shop_name", required = false) String shopName,
@Parameter(description = "商品 ASIN") @RequestParam(name = "asin", required = false) String asin, @Parameter(description = "商品 ASIN") @RequestParam(name = "asin", required = false) String asin,
@Parameter(description = "国家代码(DE/UK/FR/IT/ES)") @RequestParam(name = "country", required = false) String country) { @Parameter(description = "国家代码(DE/UK/FR/IT/ES)") @RequestParam(name = "country", required = false) String country,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = requireOperator(request); AdminUserEntity operator = requireOperator(request);
java.util.List<Long> memberIds = isSuper(operator)
? dataReadScope.readScope(operator, companyId).userIdsOr(null)
: null;
byte[] bytes = queryAsinService.export(groupId, shopName, asin, country, byte[] bytes = queryAsinService.export(groupId, shopName, asin, country,
operator.getId(), isSuper(operator)); operator.getId(), isSuper(operator), memberIds);
String filename = "query-asin-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER) + ".xlsx"; String filename = "query-asin-" + 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))
@@ -45,6 +45,7 @@ public class SkipPriceAsinController {
private final SkipPriceAsinService skipPriceAsinService; private final SkipPriceAsinService skipPriceAsinService;
private final AdminAuthSupport adminAuthSupport; private final AdminAuthSupport adminAuthSupport;
private final com.nanri.aiimage.common.service.DataReadScope dataReadScope;
/** 解析当前操作者(JWT 或内部令牌通道),权限与数据范围一律以该身份为准。 */ /** 解析当前操作者(JWT 或内部令牌通道),权限与数据范围一律以该身份为准。 */
private AdminUserEntity requireOperator(HttpServletRequest request) { private AdminUserEntity requireOperator(HttpServletRequest request) {
@@ -62,8 +63,14 @@ public class SkipPriceAsinController {
@Parameter(description = "商品 ASIN") @RequestParam(name = "asin", required = false) String asin, @Parameter(description = "商品 ASIN") @RequestParam(name = "asin", required = false) String asin,
@Parameter(description = "国家代码(DE/UK/FR/IT/ES)") @RequestParam(name = "country", required = false) String country, @Parameter(description = "国家代码(DE/UK/FR/IT/ES)") @RequestParam(name = "country", required = false) String country,
@Parameter(description = "最低价下限") @RequestParam(name = "minimum_price_from", required = false) BigDecimal minimumPriceFrom, @Parameter(description = "最低价下限") @RequestParam(name = "minimum_price_from", required = false) BigDecimal minimumPriceFrom,
@Parameter(description = "最低价上限") @RequestParam(name = "minimum_price_to", required = false) BigDecimal minimumPriceTo) { @Parameter(description = "最低价上限") @RequestParam(name = "minimum_price_to", required = false) BigDecimal minimumPriceTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = requireOperator(request); AdminUserEntity operator = requireOperator(request);
// 成员集就地算,且只在超管这一支算(非超管靠分组关系推,叠 created_by_id IN 成员会把
// 「只挂了 user_id 的分组」那批行从每个 tab 里静默删掉——口径与店铺管理逐字一致)。
java.util.List<Long> memberIds = isSuper(operator)
? dataReadScope.readScope(operator, companyId).userIdsOr(null)
: null;
return ApiResponse.success(skipPriceAsinService.page( return ApiResponse.success(skipPriceAsinService.page(
page, page,
pageSize, pageSize,
@@ -74,7 +81,8 @@ public class SkipPriceAsinController {
minimumPriceFrom, minimumPriceFrom,
minimumPriceTo, minimumPriceTo,
operator.getId(), operator.getId(),
isSuper(operator))); isSuper(operator),
memberIds));
} }
@GetMapping("/export") @GetMapping("/export")
@@ -86,10 +94,14 @@ public class SkipPriceAsinController {
@Parameter(description = "商品 ASIN") @RequestParam(name = "asin", required = false) String asin, @Parameter(description = "商品 ASIN") @RequestParam(name = "asin", required = false) String asin,
@Parameter(description = "国家代码(DE/UK/FR/IT/ES)") @RequestParam(name = "country", required = false) String country, @Parameter(description = "国家代码(DE/UK/FR/IT/ES)") @RequestParam(name = "country", required = false) String country,
@Parameter(description = "最低价下限") @RequestParam(name = "minimum_price_from", required = false) BigDecimal minimumPriceFrom, @Parameter(description = "最低价下限") @RequestParam(name = "minimum_price_from", required = false) BigDecimal minimumPriceFrom,
@Parameter(description = "最低价上限") @RequestParam(name = "minimum_price_to", required = false) BigDecimal minimumPriceTo) { @Parameter(description = "最低价上限") @RequestParam(name = "minimum_price_to", required = false) BigDecimal minimumPriceTo,
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
AdminUserEntity operator = requireOperator(request); AdminUserEntity operator = requireOperator(request);
java.util.List<Long> memberIds = isSuper(operator)
? dataReadScope.readScope(operator, companyId).userIdsOr(null)
: null;
byte[] bytes = skipPriceAsinService.export(groupId, shopName, asin, country, minimumPriceFrom, minimumPriceTo, byte[] bytes = skipPriceAsinService.export(groupId, shopName, asin, country, minimumPriceFrom, minimumPriceTo,
operator.getId(), isSuper(operator)); operator.getId(), isSuper(operator), memberIds);
String filename = "skip-price-asin-" + LocalDateTime.now().format(EXPORT_FILENAME_FORMATTER) + ".xlsx"; String filename = "skip-price-asin-" + 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))
@@ -95,10 +95,10 @@ public class QueryAsinService {
private static final java.time.Duration IMPORT_STATE_TTL = java.time.Duration.ofHours(3); private static final java.time.Duration IMPORT_STATE_TTL = java.time.Duration.ofHours(3);
public QueryAsinPageVo page(long page, long pageSize, Long groupId, String shopName, String asin, public QueryAsinPageVo page(long page, long pageSize, Long groupId, String shopName, String asin,
String country, Long operatorId, boolean superAdmin) { String country, Long operatorId, boolean superAdmin, List<Long> companyMemberIds) {
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);
Long total = countFilteredRows(groupId, shopName, asin, country, operatorId, superAdmin); Long total = countFilteredRows(groupId, shopName, asin, country, operatorId, superAdmin, companyMemberIds);
List<QueryAsinEntity> rows = listFilteredRows( List<QueryAsinEntity> rows = listFilteredRows(
groupId, groupId,
shopName, shopName,
@@ -106,6 +106,7 @@ public class QueryAsinService {
country, country,
operatorId, operatorId,
superAdmin, superAdmin,
companyMemberIds,
(safePage - 1) * safePageSize, (safePage - 1) * safePageSize,
safePageSize); safePageSize);
@@ -123,12 +124,14 @@ public class QueryAsinService {
return vo; return vo;
} }
public byte[] export(Long groupId, String shopName, String asin, String country, Long operatorId, boolean superAdmin) { public byte[] export(Long groupId, String shopName, String asin, String country, Long operatorId,
Long total = countFilteredRows(groupId, shopName, asin, country, operatorId, superAdmin); boolean superAdmin, List<Long> companyMemberIds) {
Long total = countFilteredRows(groupId, shopName, asin, country, operatorId, superAdmin, companyMemberIds);
if (total != null && total > MAX_EXPORT_ROWS) { if (total != null && total > MAX_EXPORT_ROWS) {
throw new BusinessException("导出数据超过上限 " + MAX_EXPORT_ROWS + " 行,请缩小筛选范围"); throw new BusinessException("导出数据超过上限 " + MAX_EXPORT_ROWS + " 行,请缩小筛选范围");
} }
List<QueryAsinEntity> rows = listFilteredRows(groupId, shopName, asin, country, operatorId, superAdmin, null, null); List<QueryAsinEntity> rows = listFilteredRows(groupId, shopName, asin, country, operatorId, superAdmin,
companyMemberIds, null, null);
Map<Long, String> groupNameById = shopManageGroupService.buildGroupNameMap(rows.stream() Map<Long, String> groupNameById = shopManageGroupService.buildGroupNameMap(rows.stream()
.map(QueryAsinEntity::getGroupId) .map(QueryAsinEntity::getGroupId)
.filter(id -> id != null && id > 0) .filter(id -> id != null && id > 0)
@@ -150,26 +153,30 @@ public class QueryAsinService {
} }
} }
private Long countFilteredRows(Long groupId, String shopName, String asin, String country, Long operatorId, boolean superAdmin) { private Long countFilteredRows(Long groupId, String shopName, String asin, String country, Long operatorId,
return queryAsinMapper.selectCount(buildFilterQuery(groupId, shopName, asin, country, operatorId, superAdmin)); boolean superAdmin, List<Long> companyMemberIds) {
return queryAsinMapper.selectCount(
buildFilterQuery(groupId, shopName, asin, country, operatorId, superAdmin, companyMemberIds));
} }
private List<QueryAsinEntity> listFilteredRows(Long groupId, String shopName, String asin, String country, private List<QueryAsinEntity> listFilteredRows(Long groupId, String shopName, String asin, String country,
Long operatorId, boolean superAdmin, Long operatorId, boolean superAdmin, List<Long> companyMemberIds,
Long offset, Long limit) { Long offset, Long limit) {
LambdaQueryWrapper<QueryAsinEntity> query = buildFilterQuery(groupId, shopName, asin, country, operatorId, superAdmin); LambdaQueryWrapper<QueryAsinEntity> query = buildFilterQuery(
groupId, shopName, asin, country, operatorId, superAdmin, companyMemberIds);
if (offset != null && limit != null) { if (offset != null && limit != null) {
query.last("LIMIT " + Math.max(0L, offset) + ", " + Math.max(1L, limit)); query.last("LIMIT " + Math.max(0L, offset) + ", " + Math.max(1L, limit));
} }
return queryAsinMapper.selectList(query); return queryAsinMapper.selectList(query);
} }
private LambdaQueryWrapper<QueryAsinEntity> buildFilterQuery(Long groupId, String shopName, String asin, String country, private LambdaQueryWrapper<QueryAsinEntity> buildFilterQuery(Long groupId, String shopName, String asin,
Long operatorId, boolean superAdmin) { String country, Long operatorId, boolean superAdmin,
List<Long> companyMemberIds) {
String safeShopName = normalizeBlank(shopName); String safeShopName = normalizeBlank(shopName);
String safeAsin = normalizeBlank(asin); String safeAsin = normalizeBlank(asin);
String safeCountry = normalizeBlank(country).toUpperCase(Locale.ROOT); String safeCountry = normalizeBlank(country).toUpperCase(Locale.ROOT);
Set<Long> accessibleGroupIds = superAdmin ? Set.of() : shopManageGroupService.listAccessibleGroupIds(operatorId, false); Set<Long> visibleGroupIds = visibleGroupIds(operatorId, superAdmin, companyMemberIds);
LambdaQueryWrapper<QueryAsinEntity> query = new LambdaQueryWrapper<QueryAsinEntity>() LambdaQueryWrapper<QueryAsinEntity> query = new LambdaQueryWrapper<QueryAsinEntity>()
.eq(groupId != null && groupId > 0, QueryAsinEntity::getGroupId, groupId) .eq(groupId != null && groupId > 0, QueryAsinEntity::getGroupId, groupId)
.like(!safeShopName.isEmpty(), QueryAsinEntity::getShopName, safeShopName) .like(!safeShopName.isEmpty(), QueryAsinEntity::getShopName, safeShopName)
@@ -190,16 +197,36 @@ public class QueryAsinService {
SFunction<QueryAsinEntity, ?> countryColumn = queryAsinCountryColumn(safeCountry); SFunction<QueryAsinEntity, ?> countryColumn = queryAsinCountryColumn(safeCountry);
query.isNotNull(countryColumn).ne(countryColumn, ""); query.isNotNull(countryColumn).ne(countryColumn, "");
} }
if (!superAdmin) { // null = 不筛(超管没选公司,与今天逐字一致);空集 = 这一档公司一行都不该出现,用恒不成立的 id 兜住。
if (accessibleGroupIds.isEmpty()) { if (visibleGroupIds != null) {
if (visibleGroupIds.isEmpty()) {
query.eq(QueryAsinEntity::getId, -1L); query.eq(QueryAsinEntity::getId, -1L);
} else { } else {
query.in(QueryAsinEntity::getGroupId, accessibleGroupIds); query.in(QueryAsinEntity::getGroupId, visibleGroupIds);
} }
} }
return query; return query;
} }
/**
* 这一页能看哪些分组:非超管沿用既有可见集,公司 tab 只**收窄**它、不放大
* (放大等于把操作员本来看不到的分组端出来,比少看更坏)。
*
* @return null = 不筛分组
*/
private Set<Long> visibleGroupIds(Long operatorId, boolean superAdmin, List<Long> companyMemberIds) {
if (companyMemberIds == null) {
return superAdmin ? null : shopManageGroupService.listAccessibleGroupIds(operatorId, false);
}
Set<Long> companyGroupIds = shopManageGroupService.listCompanyGroupIds(companyMemberIds);
if (superAdmin) {
return companyGroupIds;
}
Set<Long> narrowed = new java.util.LinkedHashSet<>(shopManageGroupService.listAccessibleGroupIds(operatorId, false));
narrowed.retainAll(companyGroupIds);
return narrowed;
}
private SFunction<QueryAsinEntity, ?> queryAsinCountryColumn(String country) { private SFunction<QueryAsinEntity, ?> queryAsinCountryColumn(String country) {
return switch (country) { return switch (country) {
case "DE" -> QueryAsinEntity::getAsinDe; case "DE" -> QueryAsinEntity::getAsinDe;
@@ -97,6 +97,30 @@ public class ShopManageGroupService {
.collect(Collectors.toCollection(LinkedHashSet::new)); .collect(Collectors.toCollection(LinkedHashSet::new));
} }
/**
* 属于这批账号的分组 id——公司 tab 在「只有 group_id、没有账号列」的表上推归属的唯一口径。
*
* <p><b>必须两列一起认</b>:生产 12 个分组里 10 个只有 {@code created_by_id},另外 2 个
* (周丽娥 id=2 / 郭亚芳 id=3)只有 {@code user_id}。只按 {@code created_by_id} 筛会把这 2 个分组
* 从每一个 tab 里静默删掉(不报错、不 403),而它们下面挂着 查询ASIN 4,525 行中的 4,512 行、
* 最低价ASIN 30,963 行中的 29,229 行——那会让「切到本公司」看起来像数据被删了 99%。</p>
*/
public Set<Long> listCompanyGroupIds(List<Long> companyMemberIds) {
if (companyMemberIds == null || companyMemberIds.isEmpty()) {
return Set.of();
}
return groupMapper.selectList(new LambdaQueryWrapper<ShopManageGroupEntity>()
.select(ShopManageGroupEntity::getId)
// 自成一组:MP 会给 and() 补最外层括号,这里再嵌一层 or 才不会让
// created_by_id 那半边逃出公司条件(AND 优先)。
.and(w -> w.in(ShopManageGroupEntity::getCreatedById, companyMemberIds)
.or(x -> x.in(ShopManageGroupEntity::getUserId, companyMemberIds))))
.stream()
.map(ShopManageGroupEntity::getId)
.filter(id -> id != null && id > 0)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
public Set<Long> listAccessibleCreatorUserIds(Long operatorId, boolean superAdmin) { public Set<Long> listAccessibleCreatorUserIds(Long operatorId, boolean superAdmin) {
if (superAdmin) { if (superAdmin) {
return Set.of(); return Set.of();
@@ -97,10 +97,11 @@ public class SkipPriceAsinService {
public SkipPriceAsinPageVo page(long page, long pageSize, Long groupId, String shopName, String asin, public SkipPriceAsinPageVo page(long page, long pageSize, Long groupId, String shopName, String asin,
String country, BigDecimal minimumPriceFrom, BigDecimal minimumPriceTo, String country, BigDecimal minimumPriceFrom, BigDecimal minimumPriceTo,
Long operatorId, boolean superAdmin) { Long operatorId, boolean superAdmin, List<Long> companyMemberIds) {
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);
Long total = countFilteredRows(groupId, shopName, asin, country, minimumPriceFrom, minimumPriceTo, operatorId, superAdmin); Long total = countFilteredRows(groupId, shopName, asin, country, minimumPriceFrom, minimumPriceTo,
operatorId, superAdmin, companyMemberIds);
List<SkipPriceAsinEntity> rows = listFilteredRows( List<SkipPriceAsinEntity> rows = listFilteredRows(
groupId, groupId,
shopName, shopName,
@@ -110,6 +111,7 @@ public class SkipPriceAsinService {
minimumPriceTo, minimumPriceTo,
operatorId, operatorId,
superAdmin, superAdmin,
companyMemberIds,
(safePage - 1) * safePageSize, (safePage - 1) * safePageSize,
safePageSize); safePageSize);
@@ -129,13 +131,14 @@ public class SkipPriceAsinService {
public byte[] export(Long groupId, String shopName, String asin, String country, public byte[] export(Long groupId, String shopName, String asin, String country,
BigDecimal minimumPriceFrom, BigDecimal minimumPriceTo, BigDecimal minimumPriceFrom, BigDecimal minimumPriceTo,
Long operatorId, boolean superAdmin) { Long operatorId, boolean superAdmin, List<Long> companyMemberIds) {
Long total = countFilteredRows(groupId, shopName, asin, country, minimumPriceFrom, minimumPriceTo, operatorId, superAdmin); Long total = countFilteredRows(groupId, shopName, asin, country, minimumPriceFrom, minimumPriceTo,
operatorId, superAdmin, companyMemberIds);
if (total != null && total > MAX_EXPORT_ROWS) { if (total != null && total > MAX_EXPORT_ROWS) {
throw new BusinessException("导出数据超过上限 " + MAX_EXPORT_ROWS + " 行,请缩小筛选范围"); throw new BusinessException("导出数据超过上限 " + MAX_EXPORT_ROWS + " 行,请缩小筛选范围");
} }
List<SkipPriceAsinEntity> rows = listFilteredRows(groupId, shopName, asin, country, List<SkipPriceAsinEntity> rows = listFilteredRows(groupId, shopName, asin, country,
minimumPriceFrom, minimumPriceTo, operatorId, superAdmin, null, null); minimumPriceFrom, minimumPriceTo, operatorId, superAdmin, companyMemberIds, null, null);
Map<Long, String> groupNameById = shopManageGroupService.buildGroupNameMap(rows.stream() Map<Long, String> groupNameById = shopManageGroupService.buildGroupNameMap(rows.stream()
.map(SkipPriceAsinEntity::getGroupId) .map(SkipPriceAsinEntity::getGroupId)
.filter(id -> id != null && id > 0) .filter(id -> id != null && id > 0)
@@ -159,17 +162,17 @@ public class SkipPriceAsinService {
private Long countFilteredRows(Long groupId, String shopName, String asin, String country, private Long countFilteredRows(Long groupId, String shopName, String asin, String country,
BigDecimal minimumPriceFrom, BigDecimal minimumPriceTo, BigDecimal minimumPriceFrom, BigDecimal minimumPriceTo,
Long operatorId, boolean superAdmin) { Long operatorId, boolean superAdmin, List<Long> companyMemberIds) {
return skipPriceAsinMapper.selectCount(buildFilterQuery(groupId, shopName, asin, country, return skipPriceAsinMapper.selectCount(buildFilterQuery(groupId, shopName, asin, country,
minimumPriceFrom, minimumPriceTo, operatorId, superAdmin)); minimumPriceFrom, minimumPriceTo, operatorId, superAdmin, companyMemberIds));
} }
private List<SkipPriceAsinEntity> listFilteredRows(Long groupId, String shopName, String asin, String country, private List<SkipPriceAsinEntity> listFilteredRows(Long groupId, String shopName, String asin, String country,
BigDecimal minimumPriceFrom, BigDecimal minimumPriceTo, BigDecimal minimumPriceFrom, BigDecimal minimumPriceTo,
Long operatorId, boolean superAdmin, Long operatorId, boolean superAdmin, List<Long> companyMemberIds,
Long offset, Long limit) { Long offset, Long limit) {
LambdaQueryWrapper<SkipPriceAsinEntity> query = buildFilterQuery(groupId, shopName, asin, country, LambdaQueryWrapper<SkipPriceAsinEntity> query = buildFilterQuery(groupId, shopName, asin, country,
minimumPriceFrom, minimumPriceTo, operatorId, superAdmin); minimumPriceFrom, minimumPriceTo, operatorId, superAdmin, companyMemberIds);
if (offset != null && limit != null) { if (offset != null && limit != null) {
query.last("LIMIT " + Math.max(0L, offset) + ", " + Math.max(1L, limit)); query.last("LIMIT " + Math.max(0L, offset) + ", " + Math.max(1L, limit));
} }
@@ -178,11 +181,12 @@ public class SkipPriceAsinService {
private LambdaQueryWrapper<SkipPriceAsinEntity> buildFilterQuery(Long groupId, String shopName, String asin, String country, private LambdaQueryWrapper<SkipPriceAsinEntity> buildFilterQuery(Long groupId, String shopName, String asin, String country,
BigDecimal minimumPriceFrom, BigDecimal minimumPriceTo, BigDecimal minimumPriceFrom, BigDecimal minimumPriceTo,
Long operatorId, boolean superAdmin) { Long operatorId, boolean superAdmin,
List<Long> companyMemberIds) {
String safeShopName = normalizeBlank(shopName); String safeShopName = normalizeBlank(shopName);
String safeAsin = normalizeBlank(asin); String safeAsin = normalizeBlank(asin);
String safeCountry = normalizeBlank(country).toUpperCase(Locale.ROOT); String safeCountry = normalizeBlank(country).toUpperCase(Locale.ROOT);
Set<Long> accessibleGroupIds = superAdmin ? Set.of() : shopManageGroupService.listAccessibleGroupIds(operatorId, false); Set<Long> visibleGroupIds = visibleGroupIds(operatorId, superAdmin, companyMemberIds);
LambdaQueryWrapper<SkipPriceAsinEntity> query = new LambdaQueryWrapper<SkipPriceAsinEntity>() LambdaQueryWrapper<SkipPriceAsinEntity> query = new LambdaQueryWrapper<SkipPriceAsinEntity>()
.eq(groupId != null && groupId > 0, SkipPriceAsinEntity::getGroupId, groupId) .eq(groupId != null && groupId > 0, SkipPriceAsinEntity::getGroupId, groupId)
.like(!safeShopName.isEmpty(), SkipPriceAsinEntity::getShopName, safeShopName) .like(!safeShopName.isEmpty(), SkipPriceAsinEntity::getShopName, safeShopName)
@@ -235,16 +239,38 @@ public class SkipPriceAsinService {
} }
} }
} }
if (!superAdmin) { // null = 不筛(超管没选公司,与今天逐字一致);空集 = 这一档公司一行都不该出现,用恒不成立的 id 兜住。
if (accessibleGroupIds.isEmpty()) { if (visibleGroupIds != null) {
if (visibleGroupIds.isEmpty()) {
query.eq(SkipPriceAsinEntity::getId, -1L); query.eq(SkipPriceAsinEntity::getId, -1L);
} else { } else {
query.in(SkipPriceAsinEntity::getGroupId, accessibleGroupIds); query.in(SkipPriceAsinEntity::getGroupId, visibleGroupIds);
} }
} }
return query; return query;
} }
/**
* 这一页能看哪些分组:非超管沿用既有可见集,公司 tab 只**收窄**它、不放大。
* 分组归公司必须 created_by_id 与 user_id 两列一起认,口径在
* {@link ShopManageGroupService#listCompanyGroupIds(java.util.List)} 那一处。
*
* @return null = 不筛分组
*/
private Set<Long> visibleGroupIds(Long operatorId, boolean superAdmin, List<Long> companyMemberIds) {
if (companyMemberIds == null) {
return superAdmin ? null : shopManageGroupService.listAccessibleGroupIds(operatorId, false);
}
Set<Long> companyGroupIds = shopManageGroupService.listCompanyGroupIds(companyMemberIds);
if (superAdmin) {
return companyGroupIds;
}
Set<Long> narrowed = new java.util.LinkedHashSet<>(
shopManageGroupService.listAccessibleGroupIds(operatorId, false));
narrowed.retainAll(companyGroupIds);
return narrowed;
}
private void writeExportHeader(Sheet sheet) { private void writeExportHeader(Sheet sheet) {
Row header = sheet.createRow(0); Row header = sheet.createRow(0);
String[] headers = { String[] headers = {
@@ -0,0 +1,129 @@
-- =============================================================
-- 迁移 V147__product_category_company_scope
-- 模板:docs/flyway-migration-template.md
-- 设计:crawler-plugin/docs/ops/brand-dedupe-company-isolation-design-2026-10-04.md §2.2(规则库每公司一套)
-- 需求:2026-10-05「商品类目也要区分公司,切换 tab 数据显示还一样」
--
-- 1. 变更目的:把「商品类目」biz_product_category 从"全平台一棵树"改成"内置节点共享 + 每公司自己的自定义节点"。
-- 现状是这张表一个归属列都没有(2026-10-05 22:29 主机A 只读实查,列清单为
-- id/parent_id/name/category_key/sort_order/description/is_builtin/created_at/updated_at,共 9 列),
-- 所以后台的公司 tab 在这一页是纯装饰:切到哪一家都是同一棵 412 行的树。
-- 同时 uk_product_category_key(category_key) 是【全平台】唯一键——第 2 家公司在第 1 家建过的
-- 父级下重名建类时,generateCategoryKey(parentId, name) 会算出同一个 sha1 前缀而撞键,
-- 这不是"看不到",是"根本建不出来"。company_id 打头的新唯一键解掉它。
--
-- 2. 口径:内置节点取哨兵公司 0,自定义节点归建号那一家。
-- 【为什么是 0 而不是把 18 行内置节点按公司复制一份】
-- - company.id 是 AUTO_INCREMENT,最小值 1,0 永远不会撞上真实公司;
-- CompanyScopeSupport.requireCompanyId 对 <= 0 直接抛 ⇒ 没有任何账号能被登记成公司 0。
-- - 货源/外观的类目归类读的是【全局】那一棵树(SimilarAsinLlmService:215 调 list() 无参重载),
-- 复制成每公司一份会让同一个"面霜"有 N 个 category_key,LLM 的分类结果从此按公司分叉、
-- 并且每一次归类候选都变多——这是成本,不只是口径。
-- - 复制还要回填 394 行自定义节点的父子指向,而 parent_id 是全表 id,改不动。
-- 【代价,必须写明】第 2 家公司的 tab 里只看得见 18 个内置节点,自建节点从 0 开始长;
-- 而 394 行自定义节点全部回填成公司 1——这不是猜:这些行是"手工建的类目",
-- 今天能建类目的只有第 1 家的账号(第 2 家 10-04 14:55 才开通、名下 0 个任务),
-- 且这张表【没有】任何账号列,事后无法反推。所以这一页的写侧必须从本版本起显式落公司
-- (见下方 DEFAULT 的临时性),否则新行又要靠默认值兜、下一次就彻底分不开了。
--
-- 3. 影响表与数据量(2026-10-05 22:29 主机A 业务库只读实查,不是估的):
-- biz_product_category = 412 行(内置 18、自定义 394;parent_id IS NULL 26,其中自定义根 22;MAX(id)=600)
-- 同一 (parent_id, name) 的重复组合 = 0 组 ⇒ 加列与换键都不会撞新唯一键。
-- company / columns / users 与其余业务表一律不动。
--
-- 4. 锁表风险:低。412 行的表,任何形态的 DDL 都在毫秒级。
-- 仍然按 V145 的规矩写:ADD COLUMN 走 ALGORITHM = INSTANT(前提不成立时 MySQL 直接报 1846,
-- 而不是悄悄退化成 COPY——宁可迁移失败走 repair 重跑,也不要一次没人预期的重建);
-- 两条索引操作钉 ALGORITHM = INPLACE, LOCK = NONE。
-- 只有一条 UPDATE:驱动条件是 is_builtin = 1(18 行),不依赖别的表,不碰锁热点表。
-- 索引字节预算(utf8mb4 + DYNAMIC,上限 3072):uk_company_category_key = 8 + 128*4 = 520。
-- 【不加 idx_product_category_company】新唯一键的最左前缀就是 company_id,412 行的
-- WHERE company_id IN (0, ?) 走它或走全表扫描都在同一量级;再单开一个列索引就是 V139 那轮
-- 清理掉的冗余索引形状。
--
-- 5. 回滚步骤:人工补丁 backend-java/docs/rollback-V147-product-category-company.sql(在 Flyway 扫描路径之外,
-- 不写成 V148——版本化回滚等于让"决定回滚"这件事在没有人工执行的情况下自己发生)。
-- 顺序:停两台应用 → 跑脚本 → 删 flyway_schema_history 的 version=147 行 → 回滚 jar → 起应用。
--
-- 6. 上线窗口:随 jar 双节点同窗口发布,金丝雀过了立刻补第二台,把混合版本窗口压到分钟级。
-- DEFAULT 1 是【临时】的,唯一存在理由是同批的旧 jar:它的 ProductCategoryEntity 没有
-- companyId 字段,MyBatis-Plus 的 insert 会整列跳过,严格模式下报 1364。
-- 和 V145 那张 50.7 万行的表不同,本表的历史值是由第 2 段【显式 UPDATE】写进去的,
-- 所以摘 DEFAULT 不需要回填:下一版迁移只需一条元数据操作
-- ALTER TABLE biz_product_category ALTER COLUMN company_id DROP DEFAULT;
-- (禁止写成 MODIFY COLUMN ... NOT NULL——那会重建表,而重建按"当时的列默认值"物化历史行。)
-- 在摘掉之前,启动期 CompanyDefaultGuard 会把本表一并盯住(WATCHED_TABLES 已加入
-- biz_product_category),公司数 > 1 且本列还带 DEFAULT 就打 COMPANY_DEFAULT_STILL_PRESENT,
-- 巡检按这条 ASCII 签名 grep——"漏摘"由代码喊,不靠人记得。
--
-- 【可重跑性】MySQL 的 DDL 不进事务。本迁移若在换键段失败,前面的加列与回填已落库;
-- 按「补数据 → flyway repair → 重启」恢复时 Flyway 从第一条语句重跑整个文件,所以两条 DDL
-- 都先查 information_schema 再 PREPARE,那条 UPDATE 自带 company_id = 1 限定(重跑是 no-op)。
-- 写法首例见 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_product_category' AND COLUMN_NAME = 'company_id');
SET @sql := IF(@col_exists = 0,
'ALTER TABLE `biz_product_category` ADD COLUMN `company_id` bigint NOT NULL DEFAULT 1 COMMENT ''归属公司(company.id):0 = 平台内置共享节点,> 0 = 该公司自建;V147'', ALGORITHM = INSTANT',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- ---------- 2. 内置节点改挂哨兵公司 0 ----------
-- 18 行,走 is_builtin 条件而不是 category_key 白名单:V50 的种子后来被删过(种子 24 行、
-- 今天 18 行),按标志位才不会漏也不会多。带 company_id = 1 限定 ⇒ 重跑是 no-op。
UPDATE `biz_product_category`
SET `company_id` = 0
WHERE `is_builtin` = 1
AND `company_id` = 1;
-- ---------- 3. 唯一键按公司放宽(先 ADD 后 DROP:中间任一步失败都至少还有一个唯一键在守并发) ----------
-- 新键是旧键的严格放宽(旧键全平台唯一 ⇒ 新键必唯一),所以这一步不可能因重复而失败。
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` ADD UNIQUE KEY `uk_company_category_key` (`company_id`, `category_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 = 'biz_product_category' AND INDEX_NAME = 'uk_product_category_key');
SET @sql := IF(@idx_exists > 0,
'ALTER TABLE `biz_product_category` DROP INDEX `uk_product_category_key`, ALGORITHM = INPLACE, LOCK = NONE',
'SELECT 1');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- =============================================================
-- 验证 SQL(迁移后在库上执行)
-- SELECT COUNT(*) AS total, SUM(company_id = 0) AS builtin_shared,
-- SUM(company_id = 1) AS company_1, SUM(company_id NOT IN (0, 1)) AS other_company
-- FROM `biz_product_category`;
-- -> 期望 412 / 18 / 394 / 0。builtin_shared 必须等于 SUM(is_builtin = 1):
-- 不等就是回填漏了行,而漏掉的内置节点会从第 2 家的类目树里静默消失。
-- SELECT SUM(is_builtin = 1 AND company_id <> 0) AS bad_builtin,
-- SUM(is_builtin = 0 AND company_id = 0) AS bad_custom
-- FROM `biz_product_category`;
-- -> 期望 0 / 0(哨兵值只给内置行用)
-- SHOW INDEX FROM `biz_product_category`;
-- -> 期望有 uk_company_category_key(company_id, category_key) 且【没有】uk_product_category_key
-- SELECT company_id, category_key, COUNT(*) c FROM `biz_product_category`
-- GROUP BY company_id, category_key HAVING c > 1;
-- -> 期望 0 行(新键能建起来的前提)
-- SELECT COUNT(*) FROM information_schema.COLUMNS
-- WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'biz_product_category'
-- AND COLUMN_NAME = 'company_id' AND COLUMN_DEFAULT IS NOT NULL;
-- -> 本版本发布后期望 1(DEFAULT 1 还在,由 CompanyDefaultGuard 喊);
-- 摘 DEFAULT 的那一版之后必须变 0
-- =============================================================
@@ -93,7 +93,7 @@ import org.junit.jupiter.api.Test;
* ① {@code readScope(} 的结果必须<b>被赋值给一个变量</b>({@code List<Long> scoped = …readScope(…);} 与 * ① {@code readScope(} 的结果必须<b>被赋值给一个变量</b>({@code List<Long> scoped = …readScope(…);} 与
* {@code ReadScope s = …readScope(…);} 两种形状都认);找不到赋值目标 = 裸语句、结果被丢掉 ⇒ 红。 * {@code ReadScope s = …readScope(…);} 两种形状都认);找不到赋值目标 = 裸语句、结果被丢掉 ⇒ 红。
* ② 该变量必须出现在 handler 体内<b>另一条方法调用的实参列表</b>里(扣掉它自己那条赋值语句, * ② 该变量必须出现在 handler 体内<b>另一条方法调用的实参列表</b>里(扣掉它自己那条赋值语句,
* 单层括号够用,今天两页都是这一形)。只要求"在别处被引用一次"不够: * 实参表按 {@link #callsOf} 的配对括号取,见第 13 条)。只要求"在别处被引用一次"不够:
* {@code if (scoped != null) throw …} 是装饰,不算把范围交给谁 ⇒ 控制语句关键字不认。</li> * {@code if (scoped != null) throw …} 是装饰,不算把范围交给谁 ⇒ 控制语句关键字不认。</li>
* <li><b>调了出口不等于把公司参数交给了出口</b>(本轮新增的断言 D)。现网最难查的一刀是 * <li><b>调了出口不等于把公司参数交给了出口</b>(本轮新增的断言 D)。现网最难查的一刀是
* {@code dataReadScope.readScope(operator, null)}:参数照样收下(B 绿)、{@code readScope(} 照样写在 * {@code dataReadScope.readScope(operator, null)}:参数照样收下(B 绿)、{@code readScope(} 照样写在
@@ -102,18 +102,35 @@ import org.junit.jupiter.api.Test;
* D 因此先按 {@link Block#boundCompanyParam()} 从<b>声明窗口</b>里取出被绑定到 * D 因此先按 {@link Block#boundCompanyParam()} 从<b>声明窗口</b>里取出被绑定到
* {@code company_id} 的<b>变量名</b>(不硬编码 {@code companyId}:这一支改叫 {@code orgId} 就用 * {@code company_id} 的<b>变量名</b>(不硬编码 {@code companyId}:这一支改叫 {@code orgId} 就用
* {@code orgId} 判),再要求它作为整词实参出现在 {@code readScope}/{@code resolveScope} 的参数表里 * {@code orgId} 判),再要求它作为整词实参出现在 {@code readScope}/{@code resolveScope} 的参数表里
* (单层括号,复用 {@link #CALL_ARGUMENTS};私有收口方法 {@code resolveScope(request, companyId)} * (实参表按 {@link #callsOf} 的配对括号取,见第 13 条;私有收口方法 {@code resolveScope(request, companyId)}
* 那一形算,Task 11 模板鼓励的正是它)。只写在 {@code if (companyId != null)} 里、或只出现在 * 那一形算,Task 11 模板鼓励的正是它)。只写在 {@code if (companyId != null)} 里、或只出现在
* {@code @Operation} 文案里,都不算消费——沿用 C 的 {@link #NOT_VALUE_CONSUMERS} 那把尺子,不放宽。 * {@code @Operation} 文案里,都不算消费——沿用 C 的 {@link #NOT_VALUE_CONSUMERS} 那把尺子,不放宽。
* 射程与 A/B/C 同源:同一个 {@code takesCompanyParam()} 谓词、同一份 * 射程与 A/B/C 同源:同一个 {@code takesCompanyParam()} 谓词、同一份
* {@link #READ_SCOPE_ALLOWLIST}(一条豁免同时免 A/B/C/D,不许另起第二张表),并且只咬 * {@link #READ_SCOPE_ALLOWLIST}(一条豁免同时免 A/B/C/D,不许另起第二张表),并且只咬
* {@code viaRequestParam()} 那一族(F-C 的同一把尺子:{@code getParameter("company_id")} 给不出 * {@code viaRequestParam()} 那一族(F-C 的同一把尺子:{@code getParameter("company_id")} 给不出
* 绑定变量名,D 对它无从判定)。取不到绑定名 = 形状不认识 ⇒ 判红并报形状,不许静默放过。 * 绑定变量名,D 对它无从判定)。取不到绑定名 = 形状不认识 ⇒ 判红并报形状,不许静默放过。
* D 的代价与射程一并交代(本轮报告有逐条清单):{@link #CALL_ARGUMENTS} 只吃单层括号,于是 * D 的代价与射程一并交代:非 {@code Long} 型公司参数取不到绑定名,判红并报形状;而"handler 之外的私有
* {@code readScope(operator, normalize(companyId))} 这种嵌套写法会判红(误伤合规代码,改写法或补宽
* 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 新增)。{@code DataReadScope} 现在有两个出口:
* {@code readScope(} 按账号集合给范围(去重库、查询 ASIN、最低价 ASIN、历史、视频),
* {@code readCompanyId(} 给"归属已物化成 {@code company_id} 列"的表(品牌库、商品类目——
* 那两张表的 {@code uploader_user_id} 在生产是 0 行非空,按账号筛等于把全部历史从每个公司 tab 里
* 静默删掉,理由写在 {@code DataReadScope#readCompanyId} 的注释里)。两条门共用 A/B/C/D 四条判据:
* {@link #SCOPE_DOORS} 供 A 与 C 逐条跑,{@link #SCOPE_CALLEE_NAMES} 供 D 认被调名,
* <b>名单只写一次</b>(红因消息与自检断言咬的是拼出来的同一个标签,两处各写一遍会随哈希顺序漂红)。
* 每条门各自带能红/能绿两向探针(全局约束 15 那把尺子):只在 {@code readScope} 上验过,
* 等于第二道门上的返回值与入参没人看守。</li>
* <li><b>取实参表按配对括号,不按单层括号正则</b>(10-05 批次 2/3 实跑)。原先 C 的第 ② 步与 D 都用
* {@code ([\w$]*)\s*\(([^()]*)\)},实参表里只要还有一次方法调用就整条看不见。而第 7 条把块边界钉死在
* handler 自己的闭括号上、断言 A 因此要求正门调用必须内联,两支约束合起来把合规接线逼成了
* {@code service.page(page, operator.id(), memberIds)} 这一形——本轮实跑 6 记假红
* (DedupeTotalData/InvalidAsin/QueryAsin×2/SkipPriceAsin×2)。判据把合规写法判红的下一步,
* 就是有人为了让它绿而把接线挪回块外的私有方法里,那是护栏逼人拆护栏。
* 现按 {@link #callsOf} 逐字符配对取(深度计数,字符串与字符字面量内的括号不计数,口径同第 5 条),
* 嵌套调用自己也入表。放宽的两枚正探针与一枚"嵌套了但没带公司参数"的负探针
* ({@code readScope(operator, operator.getCompanyId())} 整词大小写敏感、照旧红)成对写死:
* 少了负探针,"放宽"两个字就等于把 C 与 D 关掉。</li>
* </ol> * </ol>
* *
* <p>取样键:可执行行里出现 {@code company_id} <b>或</b> {@code companyId}(裸 token 即入样本,交给逐 handler * <p>取样键:可执行行里出现 {@code company_id} <b>或</b> {@code companyId}(裸 token 即入样本,交给逐 handler
@@ -153,13 +170,57 @@ class CompanyIdParamGoesThroughReadScopeTest {
* 断言 C 的<b>射程下限</b>(复评 I-1):Task 8 已经接线的两页必须真被 C 扫到。 * 断言 C 的<b>射程下限</b>(复评 I-1):Task 8 已经接线的两页必须真被 C 扫到。
* 不钉这一条的话,"取样集非空"自检可以由任何一支别的 handler 满足,而这两页哪天改了 * 不钉这一条的话,"取样集非空"自检可以由任何一支别的 handler 满足,而这两页哪天改了
* mapping 注解 / 换了参数形状就会静默脱离射程——分母由本轮自己造,等于没有分母。 * mapping 注解 / 换了参数形状就会静默脱离射程——分母由本轮自己造,等于没有分母。
*
* <p>10-05 批次 2/3(去重库、品牌库、查询ASIN、最低价ASIN、商品类目)把样本面扩到了
* {@link #READ_COMPANY_ID_CALL} 那条正门上,所以这里补两条同样口径的射程下限:
* 那五页哪天改了参数形状,静默脱离的是这一页的 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 =
"com/nanri/aiimage/modules/dedupe/controller/DedupeTotalDataController.java#@GetMapping";
private static final String SCOPE_CAUGHT_QUERY_ASIN_KEY =
"com/nanri/aiimage/modules/shopkey/controller/QueryAsinController.java#@GetMapping";
private static final String SCOPE_CAUGHT_SKIP_PRICE_ASIN_KEY =
"com/nanri/aiimage/modules/shopkey/controller/SkipPriceAsinController.java#@GetMapping";
/**
* 射程下限的<b>唯一一份</b>名单:C 与 D 两条射程断言共用它,不许各写一份(两处各写就会有一处先漂)。
* 这七支是"切 tab 数据还是一样"这次报障正对着的页面 —— 用户报的五页(去重库、品牌库、最低价ASIN、
* 商品类目、查询ASIN)加批次 1 已接线的两页(图片历史、图片视频任务)。
*/
private static final List<String> WIRED_PAGE_KEYS = List.of(
SCOPE_CAUGHT_HISTORY_KEY,
SCOPE_CAUGHT_VIDEO_KEY,
SCOPE_CAUGHT_DEDUPE_KEY,
SCOPE_CAUGHT_QUERY_ASIN_KEY,
SCOPE_CAUGHT_SKIP_PRICE_ASIN_KEY,
SCOPE_CAUGHT_INVALID_ASIN_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)}。
*
* <p>它存在的理由不是省事:品牌库 {@code biz_invalid_asin_data} 实测 14,801 行里
* {@code uploader_user_id} 非空 <b>0</b> 行(实体没这字段、批量 INSERT 的列清单也没带,V145 补的列
* 一直是空的),走 {@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) ...})
* 依然红。</p>
*/
private static final String READ_COMPANY_ID_CALL = "readCompanyId(";
private static final List<String> SCOPE_DOORS = List.of(READ_SCOPE_CALL, READ_COMPANY_ID_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";
@@ -178,9 +239,21 @@ class CompanyIdParamGoesThroughReadScopeTest {
*/ */
private static final Pattern SCOPE_ASSIGNMENT = Pattern.compile("([A-Za-z_$][\\w$]*)\\s*=(?!=)"); private static final Pattern SCOPE_ASSIGNMENT = Pattern.compile("([A-Za-z_$][\\w$]*)\\s*=(?!=)");
/** 断言 C 第 ② 步的消费形状:{@code 名字(实参)},单层括号(现有两页都是这一形)。 */ /**
private static final Pattern CALL_ARGUMENTS = * 断言 C 第 ② 步与断言 D 共用的消费形状:{@code 名字(实参表)}。
Pattern.compile("([A-Za-z_$][\\w$]*)\\s*\\(([^()]*)\\)"); *
* <p><b>为什么不再是正则</b>(10-05 批次 2/3 实测):原先用 {@code ([\w$]*)\s*\(([^()]*)\)}
* 只吃单层括号,于是 {@code service.page(page, operator.id(), memberIds)} 这种"实参表里还有一次
* 方法调用"的写法整条看不见——而断言 A 要求正门调用必须写在 handler 块<b>内</b>(私有收口方法在
* 块边界之外不算),恰恰把六支 handler 逼成了这一形(本轮实跑 6 记假红:
* DedupeTotalData/QueryAsin×2/SkipPriceAsin×2/InvalidAsin)。判据把合规写法判红,
* 下一步就是有人为了让它绿而把接线挪回块外——那是护栏逼人拆护栏。
* 现按<b>配对括号</b>逐字符取实参表:深度计数,字符串字面量与字符字面量里的括号不计数
* (口径同第 5 条"方法体开行"的判据,不是新尺子),嵌套调用自己也入表(
* {@code readScope(operator.user(), companyId)} 里的 {@code user()} 也在,但它不是正门、不影响判定)。</p>
*/
private record Call(String callee, String arguments) {
}
/** /**
* 控制语句关键字:读了变量但<b>没把它交给任何人</b>。{@code if (scoped != null) throw …} 这种装饰 * 控制语句关键字:读了变量但<b>没把它交给任何人</b>。{@code if (scoped != null) throw …} 这种装饰
@@ -190,12 +263,21 @@ 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} 是唯一出口本身,{@code resolveScope} 是 Task 11 模板 * 断言 D 认的三个被调名:{@code readScope} 是按账号集合给范围的唯一出口,
* 鼓励的"controller 里的私有收口方法"那一形(它内部再去 readScope)。除此之外的调用都不算 * {@code resolveScope} 是 Task 11 模板鼓励的"controller 里的私有收口方法"那一形(它内部再去
* "把公司参数交给了出口"——尤其 {@code readScope(operator, null)} 里那个 {@code null}。 * readScope),{@code readCompanyId} 是归属已物化成 {@code company_id} 列那两张表
* (品牌库、商品类目)的正门(见 {@link #READ_COMPANY_ID_CALL} 的理由)。
* 除此之外的调用都不算"把公司参数交给了出口"——尤其 {@code readScope(operator, null)} 里那个 {@code null}。
*/ */
private static final String RESOLVE_SCOPE_CALL = "resolveScope("; private static final String RESOLVE_SCOPE_CALL = "resolveScope(";
private static final Set<String> SCOPE_CALLEES = Set.of("readScope", "resolveScope"); /**
* 名单只写一次:Set 给 D 判定用,拼好的标签给 D 的红因消息与自检断言用。
* 直接从 {@code Set} 拼会随哈希顺序变 ⇒ 消息里的名字顺序不稳定,而自检断言咬的是整串字面量,
* 那就等于一条会自己漂红的用例。
*/
private static final List<String> SCOPE_CALLEE_NAMES = List.of("readScope", "resolveScope", "readCompanyId");
private static final Set<String> SCOPE_CALLEES = Set.copyOf(SCOPE_CALLEE_NAMES);
private static final String SCOPE_CALLEE_LABEL = String.join("/", SCOPE_CALLEE_NAMES);
/** /**
* 断言 D 的取绑定名(两把锚一起用):先在声明窗口里找 {@code name = "company_id"} * 断言 D 的取绑定名(两把锚一起用):先在声明窗口里找 {@code name = "company_id"}
@@ -352,6 +434,95 @@ class CompanyIdParamGoesThroughReadScopeTest {
} }
"""; """;
/**
* 第二条正门({@code readCompanyId})的<b>正探针</b>:形状逐字抄现网那一支
* ({@code InvalidAsinDataController.page} —— 先 {@code operator.user()} 把实体取出来,
* 再 {@code Long scopedCompanyId = dataReadScope.readCompanyId(user, companyId);},
* 最后把 {@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));
}
""";
/**
* 断言 C 第 ② 步的<b>嵌套实参探针</b>(形状逐字抄现网:{@code DedupeTotalDataController.page})。
* <p>10-05 批次 2/3 实跑 6 记假红全在这一形上——断言 A 要求正门调用写在 handler 块<b>内</b>,
* 于是"把 operatorId 单独传下去"天然长成 {@code service.page(page, operator.id(), memberIds)}。
* 单层括号的取法看不见 {@code memberIds},判据就把合规接线判红;下一步必然有人为了变绿把
* 整段挪到块外的私有方法里——那是护栏逼人拆护栏。放宽后的判据必须有这枚正样本,
* 否则"放宽"两个字没有可证内容。</p>
*/
private static final String SCOPE_NESTED_ARG_PROBE = """
@GetMapping("/probe")
public String nestedArg(@RequestParam(name = "company_id", required = false) Long companyId) {
List<Long> memberIds = operator.superAdmin()
? dataReadScope.readScope(user, companyId).userIdsOr(null)
: null;
return String.valueOf(dedupeTotalDataService.page(page, memberIds, operator.id()));
}
""";
/**
* 断言 D 的<b>嵌套实参探针</b>(正):公司参数经过一次归一化才进出口。
* 与上一枚同一条放宽,但咬的是 D:{@code readScope} 自己的实参表里嵌套了调用,
* 里面确实带着 {@code companyId} ⇒ 必须绿(旧正则在这一形上判红,那是误伤)。
*/
private static final String SCOPE_NESTED_DOOR_ARG_PROBE = """
@GetMapping("/probe")
public String nestedDoorArg(@RequestParam(name = "company_id", required = false) Long companyId) {
List<Long> scoped = dataReadScope.readScope(operator, normalizeCompany(companyId)).userIdsOr(null);
return String.valueOf(shopService.page(page, scoped));
}
""";
/**
* 断言 D 的<b>嵌套负探针</b>(放宽的边界,与上一枚成对):进出口的是
* {@code operator.getCompanyId()} —— 括号取法宽了,"没带 tab 那个值"这一刀不许跟着宽。
* 整词判据大小写敏感(源码里那个名字是 {@code CompanyId},不是 {@code companyId}),
* 嵌套层里也确实取不到被绑定的那个变量名 ⇒ 照旧红。少了这一枚,上面那条正断言就等于把 D 关掉。
*/
private static final String SCOPE_NESTED_DOOR_ARG_FOREIGN_PROBE = """
@GetMapping("/probe")
public String nestedDoorArgForeign(@RequestParam(name = "company_id", required = false) Long companyId) {
List<Long> scoped = dataReadScope.readScope(operator, operator.getCompanyId()).userIdsOr(null);
return String.valueOf(shopService.page(page, scoped));
}
""";
@Test @Test
@DisplayName("每个收公司 id 参数的 handler 都走唯一出口、显式写了 name = \"company_id\"," @DisplayName("每个收公司 id 参数的 handler 都走唯一出口、显式写了 name = \"company_id\","
+ "而且 tab 传下来的那个值真被交给了出口(A/B/C/D)") + "而且 tab 传下来的那个值真被交给了出口(A/B/C/D)")
@@ -382,8 +553,8 @@ class CompanyIdParamGoesThroughReadScopeTest {
.isTrue(); .isTrue();
assertThat(probe.text()) assertThat(probe.text())
.as("块边界自检:handler 块必须止于与 mapping 注解同缩进的 } 行 —— " .as("块边界自检:handler 块必须止于与 mapping 注解同缩进的 } 行 —— "
+ "否则尾随私有方法里的 readScope( 会替这支没接出口的 handler 过关") + "否则尾随私有方法里的正门调用会替这支没接出口的 handler 过关")
.doesNotContain(READ_SCOPE_CALL); .satisfies(text -> assertThat(anyScopeDoor(text)).isFalse());
assertThat(probe.spanText()) assertThat(probe.spanText())
.as("块边界自检的反面证据:readScope( 确实写在收口之后的尾随方法里") .as("块边界自检的反面证据:readScope( 确实写在收口之后的尾随方法里")
.contains(READ_SCOPE_CALL); .contains(READ_SCOPE_CALL);
@@ -405,6 +576,16 @@ 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 没有区分度、只是重复劳动。
@@ -422,12 +603,12 @@ class CompanyIdParamGoesThroughReadScopeTest {
assertThat(companyIdArgProbeReason(SCOPE_PASSED_NULL_PROBE, "SCOPE_PASSED_NULL_PROBE", CAMEL_PARAM)) assertThat(companyIdArgProbeReason(SCOPE_PASSED_NULL_PROBE, "SCOPE_PASSED_NULL_PROBE", CAMEL_PARAM))
.as("断言 D 自检(负样本):readScope(operator, null) —— 公司参数没进出口 ⇒ 必须判红") .as("断言 D 自检(负样本):readScope(operator, null) —— 公司参数没进出口 ⇒ 必须判红")
.isNotNull() .isNotNull()
.contains("没进任何 readScope/resolveScope 的实参列表"); .contains("没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表");
assertThat(companyIdArgProbeReason(SCOPE_ONLY_IF_DECOR_PROBE, "SCOPE_ONLY_IF_DECOR_PROBE", CAMEL_PARAM)) assertThat(companyIdArgProbeReason(SCOPE_ONLY_IF_DECOR_PROBE, "SCOPE_ONLY_IF_DECOR_PROBE", CAMEL_PARAM))
.as("断言 D 自检(负样本 2):companyId 只被 if 读了一次、进出口的是 null ⇒ 同样要红" .as("断言 D 自检(负样本 2):companyId 只被 if 读了一次、进出口的是 null ⇒ 同样要红"
+ "(控制语句不算消费,与 C 同一把尺子)") + "(控制语句不算消费,与 C 同一把尺子)")
.isNotNull() .isNotNull()
.contains("没进任何 readScope/resolveScope 的实参列表"); .contains("没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表");
assertThat(companyIdArgProbeReason(SCOPE_PASSED_THROUGH_HELPER_PROBE, "SCOPE_PASSED_THROUGH_HELPER_PROBE", CAMEL_PARAM)) assertThat(companyIdArgProbeReason(SCOPE_PASSED_THROUGH_HELPER_PROBE, "SCOPE_PASSED_THROUGH_HELPER_PROBE", CAMEL_PARAM))
.as("断言 D 自检(正样本):companyId 交给同文件私有 resolveScope(request, companyId) ⇒ 判据不许恒红") .as("断言 D 自检(正样本):companyId 交给同文件私有 resolveScope(request, companyId) ⇒ 判据不许恒红")
.isNull(); .isNull();
@@ -435,6 +616,43 @@ 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 + " 的实参列表");
// 配对括号取实参表(放宽)的成对证据:两枚正样本必须绿(否则 6 支已接线 handler 假红),
// 一枚"嵌套了但没带公司参数"的样本必须照旧红(否则放宽 = 把 D 关掉)。
assertThat(scopeProbeReason(SCOPE_NESTED_ARG_PROBE, "SCOPE_NESTED_ARG_PROBE"))
.as("断言 C 自检(嵌套实参表·正样本):service.page(page, memberIds, operator.id()) —— "
+ "消费方实参表里另有一次方法调用时也必须认得下 memberIds,"
+ "判红即护栏假红(批次 2/3 实测 6 支 handler 全撞这一形)")
.isNull();
assertThat(companyIdArgProbeReason(SCOPE_NESTED_DOOR_ARG_PROBE, "SCOPE_NESTED_DOOR_ARG_PROBE", CAMEL_PARAM))
.as("断言 D 自检(嵌套实参表·正样本):readScope(operator, normalizeCompany(companyId)) —— "
+ "被绑定的名字嵌在一层调用里也算交出去了")
.isNull();
assertThat(scopeProbeReason(SCOPE_NESTED_DOOR_ARG_FOREIGN_PROBE, "SCOPE_NESTED_DOOR_ARG_FOREIGN_PROBE"))
.as("断言 D 负样本的前提:readScope(operator, operator.getCompanyId()) 三步全绿 —— "
+ "接住了、也喂给 service 了,所以这一刀今天只有 D 会喊")
.isNull();
assertThat(companyIdArgProbeReason(
SCOPE_NESTED_DOOR_ARG_FOREIGN_PROBE, "SCOPE_NESTED_DOOR_ARG_FOREIGN_PROBE", CAMEL_PARAM))
.as("断言 D 自检(放宽的边界):进出口的是 operator.getCompanyId(),嵌套层里并没有被绑定的"
+ "那个变量名 ⇒ 必须照旧红。这条不红,上面那条『嵌套也算』就等于把 D 关掉了")
.isNotNull()
.contains("没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表");
// 断言 C 的分母由本轮实扫得出(不写死数字):扫进射程的 handler 键、走完两步的正样本支数、红因先攒后判。 // 断言 C 的分母由本轮实扫得出(不写死数字):扫进射程的 handler 键、走完两步的正样本支数、红因先攒后判。
List<String> scopeCaughtSample = new ArrayList<>(); List<String> scopeCaughtSample = new ArrayList<>();
@@ -469,9 +687,10 @@ class CompanyIdParamGoesThroughReadScopeTest {
boolean takesCompanyParam = handler.takesCompanyParam(); boolean takesCompanyParam = handler.takesCompanyParam();
// 断言 A:收了公司 id 参数的 handler 必须在该 handler 体内走唯一出口(handler 级豁免)。 // 断言 A:收了公司 id 参数的 handler 必须在该 handler 体内走唯一出口(handler 级豁免)。
if (takesCompanyParam && !READ_SCOPE_ALLOWLIST.contains(exemptionKey(rel, handler))) { if (takesCompanyParam && !READ_SCOPE_ALLOWLIST.contains(exemptionKey(rel, handler))) {
assertThat(handler.text()) assertThat(anyScopeDoor(handler.text()))
.as(where + " 收了公司 id 参数,但该 handler 体内没有出现 readScope( —— 文件里别处接了不算") .as(where + " 收了公司 id 参数,但该 handler 体内没走过任一正门 —— "
.contains(READ_SCOPE_CALL); + "文件里别处接了不算(私有收口方法在这支 handler 的闭括号之外,不算在内)")
.isTrue();
} }
// 断言 B:显式 name= 只咬 @RequestParam 那一族(F-C:getParameter("company_id") 的下划线 // 断言 B:显式 name= 只咬 @RequestParam 那一族(F-C:getParameter("company_id") 的下划线
// 本来就在串里,那个形状永远给不出 name = "company_id",合规写法不该被逼着改写法才绿)。 // 本来就在串里,那个形状永远给不出 name = "company_id",合规写法不该被逼着改写法才绿)。
@@ -482,7 +701,7 @@ class CompanyIdParamGoesThroughReadScopeTest {
} }
// 断言 C(复评 I-1):体内写了 readScope( 只说明"算过",不说明"用出去了"。 // 断言 C(复评 I-1):体内写了 readScope( 只说明"算过",不说明"用出去了"。
// 白名单只免 A 不免 C——被豁免的那支哪天自己算了个范围又丢掉,一样得红。 // 白名单只免 A 不免 C——被豁免的那支哪天自己算了个范围又丢掉,一样得红。
if (takesCompanyParam && handler.text().contains(READ_SCOPE_CALL)) { if (takesCompanyParam && anyScopeDoor(handler.text())) {
scopeCaughtSample.add(exemptionKey(rel, handler)); scopeCaughtSample.add(exemptionKey(rel, handler));
String dropped = handler.scopeCatchFailure(); String dropped = handler.scopeCatchFailure();
if (dropped == null) { if (dropped == null) {
@@ -530,23 +749,26 @@ class CompanyIdParamGoesThroughReadScopeTest {
+ " 支 handler,走完『接住变量 → 当实参传出去』两步的是 0 支 —— 判据恒红或形状不认,不可信") + " 支 handler,走完『接住变量 → 当实参传出去』两步的是 0 支 —— 判据恒红或形状不认,不可信")
.isPositive(); .isPositive();
assertThat(scopeCaughtSample) assertThat(scopeCaughtSample)
.as("断言 C 的射程必须覆盖 Task 8 已接线的两页(改名/换 mapping 会让它静默脱离射程,分母不能自造)") .as("断言 C 的射程必须覆盖已接线的那 " + WIRED_PAGE_KEYS.size()
.contains(SCOPE_CAUGHT_HISTORY_KEY, SCOPE_CAUGHT_VIDEO_KEY); + " 页(改名/换 mapping/换参数形状会让它静默脱离射程,分母不能自造)")
.contains(WIRED_PAGE_KEYS.toArray(new String[0]));
assertThat(scopeDiscarded) assertThat(scopeDiscarded)
.as("范围算了但没接住(断言 C):readScope( 的结果要么没赋给变量,要么赋了却没交给任何方法调用") .as("范围算了但没接住(断言 C):两条正门(readScope( / readCompanyId()的结果要么没赋给变量,"
+ "要么赋了却没交给任何方法调用")
.isEmpty(); .isEmpty();
// 断言 D 的取样自检与分母(与 C 同一族纪律):空样本 = D 空转,射程不含已接线的页 = 静默脱离。 // 断言 D 的取样自检与分母(与 C 同一族纪律):空样本 = D 空转,射程不含已接线的页 = 静默脱离。
assertThat(companyIdArgSample) assertThat(companyIdArgSample)
.as("断言 D 取样集非空自检:一支『用 @RequestParam 收了公司 id 参数、体内又调了 " .as("断言 D 取样集非空自检:一支『用 @RequestParam 收了公司 id 参数、体内又调了 "
+ "readScope/resolveScope』的 handler 都没扫到 ⇒ D 一行都没评") + SCOPE_CALLEE_LABEL + "』的 handler 都没扫到 ⇒ D 一行都没评")
.isNotEmpty(); .isNotEmpty();
assertThat(companyIdArgSample) assertThat(companyIdArgSample)
.as("断言 D 的射程必须覆盖已接线的那两页(改名/换 mapping 会让它静默脱离射程,分母不能自造)") .as("断言 D 的射程必须覆盖已接线的那 " + WIRED_PAGE_KEYS.size()
.contains(SCOPE_CAUGHT_HISTORY_KEY, SCOPE_CAUGHT_VIDEO_KEY); + " 页(改名/换 mapping/换参数形状会让它静默脱离射程,分母不能自造)")
.contains(WIRED_PAGE_KEYS.toArray(new String[0]));
assertThat(companyIdArgMissing) assertThat(companyIdArgMissing)
.as("公司参数没被交给出口(断言 D):readScope/resolveScope 的实参列表里没有出现被绑定到 " .as("公司参数没被交给出口(断言 D):" + SCOPE_CALLEE_LABEL
+ "company_id 的那个变量名 —— 参数收下、出口也调了,tab 却是死的") + " 的实参列表里没有出现被绑定到 company_id 的那个变量名 —— 参数收下、出口也调了,tab 却是死的")
.isEmpty(); .isEmpty();
} }
@@ -587,9 +809,9 @@ class CompanyIdParamGoesThroughReadScopeTest {
assertThat(handler.takesCompanyParam()) assertThat(handler.takesCompanyParam())
.as(probeName + " 的 handler 没被认成收公司 id 参数,断言 C 根本不会触发 ⇒ 探针失效") .as(probeName + " 的 handler 没被认成收公司 id 参数,断言 C 根本不会触发 ⇒ 探针失效")
.isTrue(); .isTrue();
assertThat(handler.text()) assertThat(anyScopeDoor(handler.text()))
.as(probeName + " 的 handler 体内没有 readScope( ,断言 C 扫不到它 ⇒ 探针失效") .as(probeName + " 的 handler 体内两条正门都没走(readScope( / readCompanyId(),断言 C 扫不到它 ⇒ 探针失效")
.contains(READ_SCOPE_CALL); .isTrue();
return handler.scopeCatchFailure(); return handler.scopeCatchFailure();
} }
@@ -674,6 +896,91 @@ class CompanyIdParamGoesThroughReadScopeTest {
return line.contains(SNAKE_PARAM) || line.contains(CAMEL_PARAM); return line.contains(SNAKE_PARAM) || line.contains(CAMEL_PARAM);
} }
/** 两条正门之一有没有在这段文本里出现过(A/C 的判据都走它,不各写一份)。 */
private static boolean anyScopeDoor(String text) {
return SCOPE_DOORS.stream().anyMatch(text::contains);
}
/**
* 逐字符扫出所有 {@code 名字(实参表)}:实参表按<b>配对括号</b>取(深度计数到 0 为止),
* 字符串/字符字面量内的括号不计数。嵌套调用<b>也入表</b>(扫描指针停在 {@code (} 之后而不是
* 跳过整条调用),否则 {@code readScope(operator.user(), companyId)} 里那一层就取不到。
* 括号不配平(切块把一条语句截断了)时,这条调用记到文末为止——宁可多算一次消费,
* 也不让"取不到实参表"变成静默放过;真正的截断形状由结构守卫负责。
*/
private static List<Call> callsOf(String src) {
List<Call> calls = new ArrayList<>();
int i = 0;
while (i < src.length()) {
char c = src.charAt(i);
if (c == '"' || c == '\'') {
i = skipLiteral(src, i, c);
continue;
}
boolean identifierStart = Character.isJavaIdentifierStart(c);
if (!identifierStart) {
i++;
continue;
}
int from = i;
while (i < src.length() && Character.isJavaIdentifierPart(src.charAt(i))) {
i++;
}
int open = i;
while (open < src.length() && Character.isWhitespace(src.charAt(open))) {
open++;
}
if (open >= src.length() || src.charAt(open) != '(') {
continue;
}
int close = matchingClose(src, open);
calls.add(new Call(src.substring(from, i), src.substring(open + 1, close)));
// 不跳到 close:嵌套调用也要被扫到
i = open + 1;
}
return calls;
}
/** 从 {@code quote} 处跳过一段字面量,返回其后的下标(处理 {@code \\} 转义,未闭合则到文末)。 */
private static int skipLiteral(String src, int quote, char marker) {
int i = quote + 1;
while (i < src.length()) {
char c = src.charAt(i);
if (c == '\\') {
i += 2;
continue;
}
if (c == marker) {
return i + 1;
}
i++;
}
return i;
}
/** {@code open} 处的 {@code (} 对应的 {@code )} 下标;取不到(不配平)返回文末。 */
private static int matchingClose(String src, int open) {
int depth = 0;
int i = open;
while (i < src.length()) {
char c = src.charAt(i);
if (c == '"' || c == '\'') {
i = skipLiteral(src, i, c);
continue;
}
if (c == '(') {
depth++;
} else if (c == ')') {
depth--;
if (depth == 0) {
return i;
}
}
i++;
}
return src.length();
}
private static boolean isMappingLine(String line) { private static boolean isMappingLine(String line) {
return MAPPING_ANNOTATIONS.stream().anyMatch(line::startsWith); return MAPPING_ANNOTATIONS.stream().anyMatch(line::startsWith);
} }
@@ -908,20 +1215,32 @@ class CompanyIdParamGoesThroughReadScopeTest {
*/ */
String scopeCatchFailure() { String scopeCatchFailure() {
String src = text(); String src = text();
for (int at = src.indexOf(READ_SCOPE_CALL); at >= 0; for (String door : SCOPE_DOORS) {
at = src.indexOf(READ_SCOPE_CALL, at + READ_SCOPE_CALL.length())) { String reason = scopeCatchFailureFor(src, door);
if (reason != null) {
return reason;
}
}
return null;
}
/** 逐条正门跑"接住 → 交出去"两步:两条门都得走这两步,第二道门不能成为绕过第一道门判据的后门。 */
private static String scopeCatchFailureFor(String src, String door) {
for (int at = src.indexOf(door); at >= 0;
at = src.indexOf(door, at + door.length())) {
// 语句边界:往前取最近的 ';' 或 '{'(方法体开行),往后取第一个 ';'。 // 语句边界:往前取最近的 ';' 或 '{'(方法体开行),往后取第一个 ';'。
int stmtStart = Math.max(src.lastIndexOf(SEMICOLON, at), src.lastIndexOf(WINDOW_OPEN, at)) + 1; int stmtStart = Math.max(src.lastIndexOf(SEMICOLON, at), src.lastIndexOf(WINDOW_OPEN, at)) + 1;
int stmtEnd = src.indexOf(SEMICOLON, at); int stmtEnd = src.indexOf(SEMICOLON, at);
String statement = stmtEnd < 0 ? src.substring(stmtStart) : src.substring(stmtStart, stmtEnd + 1); String statement = stmtEnd < 0 ? src.substring(stmtStart) : src.substring(stmtStart, stmtEnd + 1);
String target = assignedTo(statement, at - stmtStart); String target = assignedTo(statement, at - stmtStart);
if (target == null) { if (target == null) {
return " 的 readScope( 是条裸语句:算完了没赋给任何变量,范围算了但没接住" return " 的 " + door + " 是条裸语句:算完了没赋给任何变量,范围算了但没接住"
+ "(要写成 List<Long> scoped = dataReadScope.readScope(…)…; 再把 scoped 交出去)"; + "(要写成 List<Long> scoped = dataReadScope." + door.replace("(", "")
+ "(…)…; 再把 scoped 交出去)";
} }
String rest = src.substring(0, stmtStart) + (stmtEnd < 0 ? "" : src.substring(stmtEnd + 1)); String rest = src.substring(0, stmtStart) + (stmtEnd < 0 ? "" : src.substring(stmtEnd + 1));
if (!passedAsArgument(rest, target)) { if (!passedAsArgument(rest, target)) {
return " 的 readScope( 结果赋给了 `" + target + "`,但 handler 体内没有任何方法调用的" return " 的 " + door + " 结果赋给了 `" + target + "`,但 handler 体内没有任何方法调用的"
+ "实参列表用到 `" + target + "`:范围接住了却没交出去(把 service 那层的实参改成 " + "实参列表用到 `" + target + "`:范围接住了却没交出去(把 service 那层的实参改成 "
+ "null 就是这个形状)"; + "null 就是这个形状)";
} }
@@ -940,15 +1259,14 @@ class CompanyIdParamGoesThroughReadScopeTest {
return target; return target;
} }
/** {@code id} 有没有落在某个 {@code 名字(…)} 的实参列表里;控制语句关键字读它不算"交出去"。 */ /** {@code id} 有没有落在某个 {@code 名字(…)} 的实参表里;控制语句关键字读它不算"交出去"。 */
private static boolean passedAsArgument(String src, String id) { private static boolean passedAsArgument(String src, String id) {
Matcher call = CALL_ARGUMENTS.matcher(src);
Pattern use = Pattern.compile("(?<!\\w)" + Pattern.quote(id) + "(?!\\w)"); Pattern use = Pattern.compile("(?<!\\w)" + Pattern.quote(id) + "(?!\\w)");
while (call.find()) { for (Call call : callsOf(src)) {
if (NOT_VALUE_CONSUMERS.contains(call.group(1))) { if (NOT_VALUE_CONSUMERS.contains(call.callee())) {
continue; continue;
} }
if (use.matcher(call.group(2)).find()) { if (use.matcher(call.arguments()).find()) {
return true; return true;
} }
} }
@@ -961,7 +1279,7 @@ class CompanyIdParamGoesThroughReadScopeTest {
*/ */
boolean hasScopeCall() { boolean hasScopeCall() {
String src = text(); String src = text();
return src.contains(READ_SCOPE_CALL) || src.contains(RESOLVE_SCOPE_CALL); return anyScopeDoor(src) || src.contains(RESOLVE_SCOPE_CALL);
} }
/** /**
@@ -1005,16 +1323,19 @@ class CompanyIdParamGoesThroughReadScopeTest {
/** /**
* 断言 D:被绑定到 {@code company_id} 的那个变量名,必须作为<b>整词实参</b>出现在这一支 handler * 断言 D:被绑定到 {@code company_id} 的那个变量名,必须作为<b>整词实参</b>出现在这一支 handler
* 体内某一次 {@code readScope}/{@code resolveScope} 调用的参数表里(单层括号,复用 * 体内某一次 {@link #SCOPE_CALLEE_LABEL} 调用的参数表里(实参表由 {@link #callsOf} 按配对括号取,
* {@link #CALL_ARGUMENTS} 的形状,与 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 resolveScope(request, companyId)}(私有收口方法内部再去 readScope)⇒ 绿;</li> * <li>{@code resolveScope(request, companyId)}(私有收口方法内部再去 readScope)⇒ 绿;</li>
* <li>{@code readScope(operator, normalizeCompany(companyId))} ⇒ <b>绿</b>:嵌套写法自 10-05
* 批次 2/3 起算消费(第 13 条:旧单层正则在这一形上判红,而那正是断言 A 逼出来的形状),
* 探针 {@link #SCOPE_NESTED_DOOR_ARG_PROBE};</li>
* <li>{@code dataReadScope.readScope(operator, null)} ⇒ <b>红</b>;</li> * <li>{@code dataReadScope.readScope(operator, null)} ⇒ <b>红</b>;</li>
* <li>{@code readScope(operator, operator.getCompanyId())} ⇒ <b>红</b>:源里那个名字是 * <li>{@code readScope(operator, operator.getCompanyId())} ⇒ <b>红</b>:源里那个名字是
* {@code CompanyId}(大写 C,整词判据大小写敏感,咬不住它);而 {@link #CALL_ARGUMENTS} * {@code CompanyId}(大写 C,整词判据大小写敏感,咬不住它),嵌套层里也确实没有
* 只吃单层括号,看不穿 {@code readScope(operator, normalize(companyId))} 这种嵌套写法 —— * {@code companyId} ⇒ 探针 {@link #SCOPE_NESTED_DOOR_ARG_FOREIGN_PROBE},"放宽"的边界由它钉住;</li>
* 两种都落在"没进参数表"那一侧(后者是会误伤合规写法的已知形状,见类注释第 11 条与本轮报告);</li>
* <li>只在 {@code if (companyId != null)} 里读一次、或只在 {@code @Operation} 文案里提一句 * <li>只在 {@code if (companyId != null)} 里读一次、或只在 {@code @Operation} 文案里提一句
* ⇒ <b>红</b>:控制语句关键字沿用 {@link #NOT_VALUE_CONSUMERS} 那把尺子(与 C 同源,不放宽), * ⇒ <b>红</b>:控制语句关键字沿用 {@link #NOT_VALUE_CONSUMERS} 那把尺子(与 C 同源,不放宽),
* 而注释与文档行根本进不到 {@link #text()} 里。</li> * 而注释与文档行根本进不到 {@link #text()} 里。</li>
@@ -1028,19 +1349,18 @@ class CompanyIdParamGoesThroughReadScopeTest {
+ "Long 变量名 那一形),这支的公司参数是怎么进出口的无从判定 —— 必须人工核对," + "Long 变量名 那一形),这支的公司参数是怎么进出口的无从判定 —— 必须人工核对,"
+ "不许当作\"这支没收公司参数\"静默放过"; + "不许当作\"这支没收公司参数\"静默放过";
} }
Matcher call = CALL_ARGUMENTS.matcher(text());
Pattern use = Pattern.compile("(?<!\\w)" + Pattern.quote(bound) + "(?!\\w)"); Pattern use = Pattern.compile("(?<!\\w)" + Pattern.quote(bound) + "(?!\\w)");
while (call.find()) { for (Call call : callsOf(text())) {
String callee = call.group(1); String callee = call.callee();
// 与 C 同一条纪律:控制语句读它一次不算"把值交给谁";D 只认出口那两个被调名。 // 与 C 同一条纪律:控制语句读它一次不算"把值交给谁";D 只认出口那几个被调名。
if (NOT_VALUE_CONSUMERS.contains(callee) || !SCOPE_CALLEES.contains(callee)) { if (NOT_VALUE_CONSUMERS.contains(callee) || !SCOPE_CALLEES.contains(callee)) {
continue; continue;
} }
if (use.matcher(call.group(2)).find()) { if (use.matcher(call.arguments()).find()) {
return null; return null;
} }
} }
return " 的公司参数 `" + bound + "` 没进任何 readScope/resolveScope 的实参列表" return " 的公司参数 `" + bound + "` 没进任何 " + SCOPE_CALLEE_LABEL + " 的实参列表"
+ "(`readScope(operator, null)`、`readScope(operator, operator.getCompanyId())` 就是这个形状:" + "(`readScope(operator, null)`、`readScope(operator, operator.getCompanyId())` 就是这个形状:"
+ "参数收下了、出口也调了、算出来的范围也交出去了,唯独 tab 传下来的那个值被换成了别的来源" + "参数收下了、出口也调了、算出来的范围也交出去了,唯独 tab 传下来的那个值被换成了别的来源"
+ " ⇒ 接口 200、页面正常、切 tab 数字永远不动,而 A/B/C 三条全绿没人喊)"; + " ⇒ 接口 200、页面正常、切 tab 数字永远不动,而 A/B/C 三条全绿没人喊)";
@@ -116,4 +116,33 @@ class DataReadScopeTest {
() -> dataReadScope.readScope(user(5L, "admin", null), null)) () -> dataReadScope.readScope(user(5L, "admin", null), null))
.isInstanceOf(com.nanri.aiimage.common.exception.BusinessException.class); .isInstanceOf(com.nanri.aiimage.common.exception.BusinessException.class);
} }
// ---- 第二条正门:归属已物化成 company_id 列的表(品牌库、商品类目)----
// 这一道门的语义与 readScope 相反方向:返回的是"要筛哪个公司",null = 不筛。
// 非超管一律 null(他们的可见集本来就锁在自己的分组上,再叠一层公司会把"靠分组可见"的行整批删掉,
// 见 DataReadScope#readCompanyId 的注释)。这三条若不写,把 `return null` 改成
// `return companyScope.requireCompanyId(operator)` 不会让任何现有用例变红——而那一改的后果是
// 品牌库里靠分组可见的历史行从每个非超管账号下消失。
@Test
@DisplayName("第二道门:超管选公司 = 原样给回那一列的筛值")
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();
}
} }
@@ -0,0 +1,185 @@
package com.nanri.aiimage.common.util;
import com.alibaba.excel.EasyExcel;
import com.nanri.aiimage.common.exception.BusinessException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayOutputStream;
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.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* ExcelStreamReader 的异常出口契约(现网缺陷:带单元格图片的 xlsx 解析失败时
* POI 的 ExcelAnalysisException 原样冒到 GlobalExceptionHandler,用户拿到 HTTP 500 且看不到真因)。
*/
class ExcelStreamReaderParseFailureTest {
@TempDir
Path tempDir;
/** 生产现场形状:xlsx 包里有一个未声明 content type 的 media 部件。 */
@Test
void parseFailureOnMalformedPackageSurfacesAsIoExceptionWithReason() throws Exception {
Path bad = tempDir.resolve("cellimage-no-content-type.xlsx");
Files.write(bad, packageWithUndeclaredMediaPart());
IOException thrown = assertThrows(IOException.class,
() -> ExcelStreamReader.readFirstSheet(bad.toFile(), noopHandler()));
String reason = rawParseFailureMessageOf(bad);
assertTrue(thrown.getMessage().contains(reason),
"消息里要能看到底层真因 [" + reason + "],实际=" + thrown.getMessage());
}
/** 反向钉:读全部 sheet 的入口同样收口(另有 6 个调用点走这条)。 */
@Test
void parseFailureOnReadAllSheetsAlsoSurfacesAsIoException() throws Exception {
Path bad = tempDir.resolve("cellimage-no-content-type-all.xlsx");
Files.write(bad, packageWithUndeclaredMediaPart());
assertThrows(IOException.class, () -> ExcelStreamReader.readAllSheets(bad.toFile(), noopHandler()));
}
/** 反向钉:调用方在 onRow 里抛的业务异常不能被改写成 IOException,否则 400 语义会塌成"文件坏了"。 */
@Test
void handlerBusinessExceptionIsNotRewrittenIntoIoException() throws Exception {
Path good = writeWorkbook();
BusinessException thrown = assertThrows(BusinessException.class, () -> ExcelStreamReader
.readFirstSheet(good.toFile(), rowHandlerThatThrows(
new BusinessException("品牌列缺失,请检查表头"))));
assertEquals("品牌列缺失,请检查表头", thrown.getMessage());
}
/** 调用方抛的运行时异常原样透传,不借"解析失败"这条路被包成 IOException。 */
@Test
void handlerRuntimeExceptionPropagatesUnchanged() throws Exception {
Path good = writeWorkbook();
IllegalStateException failure = new IllegalStateException("行处理失败");
IllegalStateException thrown = assertThrows(IllegalStateException.class,
() -> ExcelStreamReader.readFirstSheet(good.toFile(), rowHandlerThatThrows(failure)));
assertSame(failure, thrown);
}
/** 调用方抛的受检异常走 IOException 契约,且不把内部包装类漏给调用方。 */
@Test
void handlerCheckedExceptionSurfacesAsIoExceptionWithReason() throws Exception {
Path good = writeWorkbook();
IOException thrown = assertThrows(IOException.class, () -> ExcelStreamReader.readFirstSheet(
good.toFile(), rowHandlerThatThrows(new Exception("行数据超出上限 5000"))));
assertTrue(thrown.getMessage().contains("行数据超出上限 5000"),
"消息里要能看到调用方抛出的真因,实际=" + thrown.getMessage());
}
/** 好文件照旧能读完(保证收口没有把正常路径一起改掉)。 */
@Test
void validWorkbookStillReadsRows() throws Exception {
Path good = writeWorkbook();
StringBuilder seen = new StringBuilder();
assertDoesNotThrow(() -> ExcelStreamReader.readFirstSheet(
good.toFile(), (sheetName, sheetNo, rowIndex, headerMap, rowMap) ->
seen.append(rowMap.get(0))));
assertEquals("Nike", seen.toString());
}
private Path writeWorkbook() {
Path file = tempDir.resolve("ok.xlsx");
List<List<String>> head = List.of(List.of("品牌"), List.of("ASIN"));
List<List<String>> data = List.of(List.of("Nike", "B01ABC"));
EasyExcel.write(file.toFile()).head(head).sheet("Sheet1").doWrite(data);
return file;
}
private ExcelStreamReader.SheetRowHandler noopHandler() {
return new ExcelStreamReader.SheetRowHandler() {
@Override
public void onRow(String sheetName, Integer sheetNo, int rowIndex,
Map<Integer, String> headerMap, Map<Integer, String> rowMap) {
}
};
}
private ExcelStreamReader.SheetRowHandler rowHandlerThatThrows(Exception failure) {
return new ExcelStreamReader.SheetRowHandler() {
@Override
public void onRow(String sheetName, Integer sheetNo, int rowIndex,
Map<Integer, String> headerMap, Map<Integer, String> rowMap) throws Exception {
throw failure;
}
};
}
/** 直接喂同一个坏包,取 POI 自己报出来的真因文本,用来断言它没被收口吞掉。 */
private String rawParseFailureMessageOf(Path badFile) throws IOException {
String message = null;
try (var input = Files.newInputStream(badFile)) {
EasyExcel.read(input).sheet(0).headRowNumber(1).doRead();
throw new AssertionError("构造的坏包必须让 EasyExcel 抛异常,否则这条用例证明不了收口");
} catch (RuntimeException ex) {
Throwable deepest = ex;
while (deepest.getCause() != null) {
deepest = deepest.getCause();
}
message = deepest.getMessage();
}
assertTrue(message != null && message.length() > 20,
"底层真因文本应当有信息量,实际=" + message);
return message;
}
private byte[] packageWithUndeclaredMediaPart() throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(bytes, StandardCharsets.UTF_8)) {
put(zip, "[Content_Types].xml", """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
</Types>""");
put(zip, "_rels/.rels", """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
</Relationships>""");
put(zip, "xl/workbook.xml", """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets>
</workbook>""");
put(zip, "xl/_rels/workbook.xml.rels", """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/cellImages" Target="cellimages.xml"/>
</Relationships>""");
put(zip, "xl/cellimages.xml", """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cellImages xmlns="http://www.wps.cn/officeDocument/2020/cellImage"/>""");
zip.putNextEntry(new ZipEntry("xl/media/cellimage1.jpeg"));
zip.write(new byte[]{(byte) 0xFF, (byte) 0xD8, (byte) 0xFF, (byte) 0xD9});
zip.closeEntry();
}
return bytes.toByteArray();
}
private void put(ZipOutputStream zip, String name, String content) throws IOException {
zip.putNextEntry(new ZipEntry(name));
zip.write(content.getBytes(StandardCharsets.UTF_8));
zip.closeEntry();
}
}
@@ -346,7 +346,8 @@ class CompanyScopeMigrationV145Test {
Path doc = ROOT.resolve("docs/migration-inventory.md"); Path doc = ROOT.resolve("docs/migration-inventory.md");
String text = raw(doc); String text = raw(doc);
assertTrue(text.contains(migration().getFileName().toString()), "盘点文档应记录 V145 文件名"); assertTrue(text.contains(migration().getFileName().toString()), "盘点文档应记录 V145 文件名");
assertTrue(text.contains("V146"), "盘点文档应把取号起点推到 V146"); // 取号起点不在这里钉:原先写死 contains("V146"),而 V146 真落地后它只因文档里还留着
// 那个文件名而巧合为真。派生尺子=MigrationInventoryTest#inventoryDocNumberingStartIsMaxPlusOne。
assertTrue(text.contains("1833593804"), "盘点文档应记下 V144 的生产存量校验和"); assertTrue(text.contains("1833593804"), "盘点文档应记下 V144 的生产存量校验和");
assertTrue(text.contains("1539570901"), "盘点文档应保留 V143 的生产存量校验和"); assertTrue(text.contains("1539570901"), "盘点文档应保留 V143 的生产存量校验和");
} }
@@ -142,6 +142,35 @@ class MigrationInventoryTest {
} }
} }
/**
* 盘点文档的「起取号」必须是目录当前最大值 + 1 —— 派生式,不写死数字。
*
* <p>破坏点两条:加了 V148 却没改文档 ⇒ 后来人照文档取号撞上刚落地的 V148(改已应用版本=两台都起不来);
* 文档把号位改超前 ⇒ 1..max 留洞,{@link #integerVersionsSequentialFromOne} 会红。
* 各迁移自己的审计类原先把「起点推到 V14x」写死在 assertTrue 里,那种断言在 V14x 真落地那天就
* 只因文档里还留着同名文件而恒为真(基线自己过期)。尺子挪到这里、只对「本轮目录」求值,
* 才不需要每加一版都有人记得回来改一个数字。</p>
*/
@Test
void inventoryDocNumberingStartIsMaxPlusOne() throws IOException {
String text = Files.readString(Path.of(System.getProperty("user.dir"), "docs/migration-inventory.md"));
String marker = "从 **V";
int hits = 0, cursor = -1;
while ((cursor = text.indexOf(marker, cursor + 1)) >= 0) hits++;
assertEquals(1, hits, "「从 **V<号>** 起取号」应只有一条可解析的取号规则," + hits + " 条=后来人不知道按哪条取号");
int digitsFrom = text.indexOf(marker) + marker.length();
int digitsTo = digitsFrom;
while (digitsTo < text.length() && Character.isDigit(text.charAt(digitsTo))) digitsTo++;
assertTrue(digitsTo > digitsFrom, "取号规则里 V 之后必须是数字(解析不出=本用例恒绿)");
int stated = Integer.parseInt(text.substring(digitsFrom, digitsTo));
int maxMajor = parseAll(versionFiles()).stream().filter(Migration::isInteger)
.mapToInt(Migration::major).max().orElse(0);
assertEquals(maxMajor + 1, stated,
"取号起点应是目录最大值 V" + maxMajor + " 的下一号,实际文档写 V" + stated);
}
@Test @Test
void checksumStableAcrossReads() throws IOException { void checksumStableAcrossReads() throws IOException {
Map<String, String> first = sha256All(versionFiles()); Map<String, String> first = sha256All(versionFiles());
@@ -0,0 +1,285 @@
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;
/**
* V147({@code biz_product_category} 加 company_id + 唯一键按公司放宽)的文件审计。
* 需求:2026-10-05 控制方点名「商品类目切换 tab 数据显示还一样」;设计见迁移文件头 §1–§6。
*
* <p>为什么必须单独有一支:V143/V144/V145/V146 每版都有自己的审计类,而 V147 落盘后
* 只有消费侧的两支 service/controller 用例——迁移文件本身(加列形状、哨兵回填、换键顺序、
* 可重跑守卫、回滚补丁、盘点文档取号起点)在 3788 例里一处都没被钉。也就是说
* 「把 ADD COLUMN 改成可空」「把 DROP INDEX 排到 ADD UNIQUE KEY 前面」「把哨兵改成 -1」
* 都能全绿进 jar,而这三条里前两条是运行期静默错、第三条是让第 2 家看不见 18 个内置类目。</p>
*
* <p>本仓 pom 无 H2、无 testcontainers,迁移跑不起来,所以文件审计是唯一能守住的层,
* 与 {@link CompanyScopeMigrationV145Test} 同口径:断言打在剥掉注释后的可执行 SQL 上,
* {@code stripComments}/{@code normalize} 逐字沿用那一份实现(注释里的 {@code --} 与字符串字面量里的
* {@code --} 是两件事,另写一版简化实现会让断言打在残缺 SQL 上)。</p>
*/
class ProductCategoryMigrationV147Test {
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_product_category";
private static final String NEW_KEY = "uk_company_category_key";
private static final String OLD_KEY = "uk_product_category_key";
// ---------------------------------------------------------------- 取文件
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("V147__"))
.toList();
assertEquals(1, hits.size(),
"V147 必须恰好一个迁移文件,实际 " + 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 / CompanyMigrationV144Test 逐字同实现,理由见类注释。
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();
}
// ------------------------------------------------------------------ 用例
/** 破坏点:取到已应用的 146(原地改=两台都起不来),或把这一版编成 V148(V147 就被跳开,类目列永远不加)。 */
@Test
void migrationIsVersionedOneFourSeven() throws IOException {
Path file = migration();
Matcher m = Pattern.compile("^V(\\d+)(?:_\\d+)?__").matcher(file.getFileName().toString());
assertTrue(m.find(), "文件名应能抽出整数版本:" + file.getFileName());
assertEquals(147, Integer.parseInt(m.group(1)), "本迁移必须是 V147(V146 之后的下一号)");
assertTrue(file.getFileName().toString().matches("^V147__[A-Za-z0-9_.-]+\\.sql$"),
"命名应 V147__<snake 描述>.sql:" + file.getFileName());
}
/**
* 破坏点:把列加成可空 ⇒ 混合版本窗口里旧 jar 写进来的类目行 company_id 为 NULL,
* 而 {@code readCompanyId} 返回 null 的分支是「不裁剪」,这些行会同时出现在每一家的树上;
* 把 {@code MODIFY COLUMN} 写进来 ⇒ 重建表并按"当时的列默认值"物化历史行(§6 明令禁止)。
* DEFAULT 1 必须**在场**:它是同批旧 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(§4)");
assertFalse(sql.contains("MODIFY COLUMN"), "禁 MODIFY COLUMN——它会重建表并按当时的默认值物化历史行(§6)");
assertFalse(sql.contains("ALTER TABLE `" + TABLE + "` DROP COLUMN"),
"本版本不删列:归属信息一旦删掉就无法再分清是第几家公司建的(§2)");
}
/**
* 破坏点 ①:删掉那条 UPDATE ⇒ 18 行内置节点留在公司 1,第 2 家的类目树只剩自己自建的 0 行,
* 「切 tab 这一页空白」就是这么来的。破坏点 ②:哨兵值写成 1 或 -1 ⇒ 要么和真实公司 1 混在一起
* (第 1 家的自建类目被当成平台内置、别家也能改),要么被 {@code requireCompanyId} 的 <=0 判定挡在门外。
* 破坏点 ③:这张表除这一条 UPDATE 外不该有任何别的 DML——没有账号列,任何"按人回填"都是编数据。
*/
@Test
void builtinRowsGoToSentinelZeroAndThatIsTheOnlyDml() throws IOException {
String sql = statements();
Pattern dml = Pattern.compile("\\b(UPDATE|INSERT|DELETE|REPLACE)\\b", Pattern.CASE_INSENSITIVE);
Matcher d = dml.matcher(sql);
int hits = 0;
while (d.find()) {
hits++;
}
assertEquals(1, hits, TABLE + " 的可执行段应当只有那一条回填 UPDATE,实际命中 " + hits + " 条 DML 关键字");
assertTrue(sql.contains("SET `company_id` = 0"), "内置节点应挂哨兵公司 0");
assertTrue(sql.contains("WHERE `is_builtin` = 1"),
"驱动条件必须是 is_builtin 而不是 category_key 白名单:V50 的种子后来被删过(种子 24 行、今天 18 行)");
assertTrue(sql.contains("AND `company_id` = 1"),
"回填必须自带 company_id = 1 限定 ⇒ DDL 段失败后 repair 重跑时这条是 no-op(§可重跑性)");
}
/**
* 破坏点:把 DROP 旧键排到 ADD 新键之前 ⇒ 中间那一刻这张表没有任何唯一键在守并发,
* 两个账号同时建同名类目就会落两行;把新键的第二列换掉或把 company_id 挪到第二位 ⇒
* {@code WHERE company_id IN (0, ?)} 走不到这个键,而 §4 明写「不加单独的列索引」,
* 于是这一页的每次列表查询都退化成扫描。
*/
@Test
void swapsTheUniqueKeyCompanyFirstAndAddsBeforeDropping() throws IOException {
String sql = statements();
int add = sql.indexOf("ADD UNIQUE KEY `" + NEW_KEY + "` (`company_id`, `category_key`)");
int drop = sql.indexOf("DROP INDEX `" + OLD_KEY + "`");
assertTrue(add >= 0, "新唯一键应是 (company_id, category_key) 这个顺序,实际串:" + sql.substring(0, Math.min(sql.length(), 400)));
assertTrue(drop >= 0, "旧的全平台唯一键 " + OLD_KEY + " 必须被删掉,否则第 2 家在同一个父级下重名建类会撞 1062");
assertTrue(add < drop, "换键顺序必须先 ADD 后 DROP:中间任一步失败都至少还有一个唯一键在守并发");
assertEquals(2, count(sql, "ALGORITHM = INPLACE, LOCK = NONE"),
"两条索引操作各钉一次 INPLACE + LOCK = NONE(§4:这张表 412 行,但仍不许默默锁表)");
assertFalse(sql.contains("ADD INDEX") || sql.contains("ADD KEY"),
"不该再单开列索引:新唯一键的最左前缀就是 company_id,再开一个就是 V139 那轮清掉的冗余形状");
}
/**
* 破坏点:把两条 DDL 的存在性守卫删掉 ⇒ DDL 不进事务,中途失败后 repair 重跑会撞
* 1060(重复列)/1061(重复键)而彻底起不来,只能人工进库删。
* 计数取 3 而不是「大于 0」:本文件的可执行段恰好查三次 information_schema
* (一次列、两次索引),少一次就是一处守卫没了。
*/
@Test
void bothDdlStatementsAreGuardedByExistenceChecks() throws IOException {
String sql = statements();
assertEquals(3, count(sql, "information_schema"),
"可执行段应查 3 次 information_schema(列存在 + 新键存在 + 旧键存在),实际次数见消息");
assertTrue(sql.contains("COLUMN_NAME = 'company_id'"), "加列的守卫要按列名查");
assertTrue(sql.contains("INDEX_NAME = '" + NEW_KEY + "'"), "加新键的守卫要按新键名查");
assertTrue(sql.contains("INDEX_NAME = '" + OLD_KEY + "'"), "删旧键的守卫要按旧键名查");
assertTrue(count(sql, "PREPARE stmt FROM @sql") == 3 && count(sql, "EXECUTE stmt") == 3,
"三段条件 DDL 都必须走 PREPARE/EXECUTE(MySQL 不能在 IF 里直接写 DDL)");
}
/**
* 破坏点:回滚脚本没跟着写 ⇒ 出问题只能手工现编 SQL,而"漏删 flyway_schema_history 的 147 行"
* 这一手会让重装带 V147 的 jar 时 Flyway 判定已应用直接跳过——列和键都不重建,
* 而 Java 侧实体照常读写 company_id,运行期报 Unknown column。
*
* <p>与 V145 那份同形:{@code DROP COLUMN} 必须留在注释里由人工解开(这张表没有账号列,
* 删了就再也分不出哪一家),而"回滚不得版本化"由 {@link CompanyScopeMigrationV145Test
* #rollbackStaysOutOfFlywayScanAndCoversTheHistoryRow} 那支按全目录扫,本类不重复实现,
* 只在下面那支按文件名把本迁移钉进盘点文档(号位起点由 {@link MigrationInventoryTest
* #inventoryDocNumberingStartIsMaxPlusOne} 派生式盯着)。</p>
*/
@Test
void rollbackIsAHumanPatchOutsideTheFlywayScanPath() throws IOException {
Path doc = ROOT.resolve("docs/rollback-V147-product-category-company.sql");
assertTrue(Files.isRegularFile(doc), "V147 的人工回滚补丁必须存在:" + doc);
String whole = raw(doc);
assertTrue(whole.contains("flyway_schema_history"), "回滚必须写明删 version='147' 的历史行");
String executable = normalize(stripComments(whole));
assertTrue(executable.contains("ADD UNIQUE KEY `" + OLD_KEY + "` (`category_key`)"),
"回滚要把全平台唯一键加回来(新键是旧键的严格放宽,回填那一刻必然不撞)");
assertTrue(executable.contains("DROP INDEX `" + NEW_KEY + "`"), "回滚要摘掉按公司的新唯一键");
assertTrue(executable.indexOf("ADD UNIQUE KEY") < executable.indexOf("DROP INDEX"),
"回滚也必须先加旧键后删新键,理由与迁移同一半:中间时刻不许没有唯一键");
assertFalse(executable.contains("DROP COLUMN"),
"DROP COLUMN 是丢归属信息的动作,必须留在注释里由人工解开");
assertFalse(executable.contains("MODIFY COLUMN"), "同上:任何时候不要写 MODIFY COLUMN");
}
/**
* 破坏点:V147 的 DEFAULT 1 没进启动期哨兵清单 ⇒ "下一次记得摘"这件事没人喊,
* 而巡检按 {@code COMPANY_DEFAULT_STILL_PRESENT} 这条 ASCII 签名 grep docker logs。
*/
@Test
void startupSentinelWatchesTheProductCategoryColumn() 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 + "(查到了却不在清单里,就没人去喊那条签名)");
}
/**
* 破坏点:盘点文档没跟着改 ⇒ 下一个人按"取号起点"取号就撞号,或者按"最新版本"漏掉本文件。
* 这里把 V145/V146/V147 三个文件名同时钉住:只钉最新一条会重演
* 「推进第 11 行时把 V145 挤掉」那一次回归(本轮真实发生过)。
* 号位起点不写在这里——写死 "V148" 到 V148 落地那天就自己过期,改由
* {@link MigrationInventoryTest#inventoryDocNumberingStartIsMaxPlusOne} 按「本轮目录最大值 + 1」求值。
*/
@Test
void inventoryDocTracksV147AndTheEarlierFilenamesTogether() throws IOException {
Path doc = ROOT.resolve("docs/migration-inventory.md");
String text = raw(doc);
for (String keep : List.of("V145__brand_dedupe_company_scope.sql",
"V146__users_expires_at_admin_expiry.sql",
migration().getFileName().toString())) {
assertTrue(text.contains(keep), "盘点文档应逐字保留文件名:" + keep);
}
assertTrue(text.contains("1833593804"), "盘点文档应记下 V144 的生产存量校验和");
}
/** 自检:本用例集扫的是真文件,且 normalize 后仍能命中关键串(0 命中的断言是恒绿的)。 */
@Test
void scannedSignaturesAreActuallyPresent() throws IOException {
String sql = statements();
assertTrue(sql.length() > 800, "剥注释后的 SQL 太短,说明预处理把内容吃掉了:" + sql.length());
assertTrue(count(sql, "ALTER TABLE") >= 3 && count(sql, "information_schema") > 0,
"关键签名 0 命中=预处理或文件路径坏了,本类的断言全部不可信");
}
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;
}
}
@@ -142,7 +142,7 @@ class CollectDataBrandRecheckInjectorTest {
List.of(chunk(1, "s1", "hash1", "ptr1"))); List.of(chunk(1, "s1", "hash1", "ptr1")));
when(transientPayloadStorageService.resolvePayload(eq("ptr1"), anyString())).thenReturn( when(transientPayloadStorageService.resolvePayload(eq("ptr1"), anyString())).thenReturn(
"[{\"asin\":\"B01\",\"brand\":\"Zara\"},{\"asin\":\"B02\",\"brand\":\"Zara\"}]"); "[{\"asin\":\"B01\",\"brand\":\"Zara\"},{\"asin\":\"B02\",\"brand\":\"Zara\"}]");
when(invalidAsinBatchWriter.writeBatch(anyList())).thenReturn(2); when(invalidAsinBatchWriter.writeBatch(anyList(), eq(961L))).thenReturn(2);
GroupOutcome outcome = injector.apply(task(100L), Map.of("zara", RecheckVerdict.REJECTED)); GroupOutcome outcome = injector.apply(task(100L), Map.of("zara", RecheckVerdict.REJECTED));
@@ -208,7 +208,7 @@ class CollectDataServiceTxBoundaryTest {
service.submitResult(TASK_ID, submitRequest()); service.submitResult(TASK_ID, submitRequest());
verify(invalidAsinBatchWriter).writeBatch(any()); verify(invalidAsinBatchWriter).writeBatch(any(), eq(USER_ID));
} }
@Test @Test
@@ -220,7 +220,7 @@ class CollectDataServiceTxBoundaryTest {
service.submitResult(TASK_ID, submitRequest()); service.submitResult(TASK_ID, submitRequest());
verify(invalidAsinBatchWriter, never()).writeBatch(any()); verify(invalidAsinBatchWriter, never()).writeBatch(any(), any());
} }
@Test @Test
@@ -232,7 +232,7 @@ class CollectDataServiceTxBoundaryTest {
service.submitResult(TASK_ID, submitRequest()); service.submitResult(TASK_ID, submitRequest());
verify(invalidAsinBatchWriter, never()).writeBatch(any()); verify(invalidAsinBatchWriter, never()).writeBatch(any(), any());
} }
@Test @Test
@@ -1,5 +1,6 @@
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;
@@ -26,16 +27,29 @@ import static org.mockito.Mockito.when;
* biz_invalid_asin_data(INSERT IGNORE,按唯一键幂等),空批次/无合法 * biz_invalid_asin_data(INSERT IGNORE,按唯一键幂等),空批次/无合法
* data_value 的批次不发起任何 insertBatchIgnore 调用;远程失败降级记录 * data_value 的批次不发起任何 insertBatchIgnore 调用;远程失败降级记录
* 计数(跳过写入),可恢复后继续,不抛出中断整个提交流程的异常。 * 计数(跳过写入),可恢复后继续,不抛出中断整个提交流程的异常。
*
* <p>归属那一笔(10-05 批次 3):实体与 INSERT 列清单此前都不带 company_id/uploader_user_id,
* V145 补的列全靠 DEFAULT 1 盖 ⇒ 第 2 家公司跑货源产生的行被记成第 1 家。写入器现在按
* 调用方给的任务发起账号推公司,<b>推不出公司就整批不写</b>(宁可少一条黑名单,也不把行盖成
* 别家公司 —— 那会让另一家的正常品牌被静默过滤)。</p>
*/ */
class CollectDataInvalidAsinBatchWriterTest { class CollectDataInvalidAsinBatchWriterTest {
/** 任务发起账号(biz_file_task.user_id)。 */
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);
writer = new CollectDataInvalidAsinBatchWriter(invalidAsinDataMapper, 10); companyScopeSupport = mock(CompanyScopeSupport.class);
when(companyScopeSupport.companyIdOrNull(UPLOADER)).thenReturn(UPLOADER_COMPANY);
writer = new CollectDataInvalidAsinBatchWriter(invalidAsinDataMapper, companyScopeSupport, 10);
} }
@Test @Test
@@ -46,7 +60,7 @@ class CollectDataInvalidAsinBatchWriterTest {
int written = writer.writeBatch(List.of( int written = writer.writeBatch(List.of(
row("B000000001", "Zara"), row("B000000001", "Zara"),
row("B000000002", "nike") row("B000000002", "nike")
)); ), UPLOADER);
assertEquals(2, written, "两行都写入"); assertEquals(2, written, "两行都写入");
ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class); ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class);
@@ -68,7 +82,7 @@ class CollectDataInvalidAsinBatchWriterTest {
rows.add(row("B" + String.format("%09d", i + 1), "brand-" + (i % 7))); rows.add(row("B" + String.format("%09d", i + 1), "brand-" + (i % 7)));
} }
int written = writer.writeBatch(rows); int written = writer.writeBatch(rows, UPLOADER);
assertEquals(100, written, "全部写入"); assertEquals(100, written, "全部写入");
ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class); ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class);
@@ -95,8 +109,8 @@ class CollectDataInvalidAsinBatchWriterTest {
row("B000000003", "") row("B000000003", "")
); );
int first = writer.writeBatch(rows); int first = writer.writeBatch(rows, UPLOADER);
int second = writer.writeBatch(rows); int second = writer.writeBatch(rows, UPLOADER);
assertEquals(2, first, "首轮 2 个合法行写入"); assertEquals(2, first, "首轮 2 个合法行写入");
assertEquals(2, second, "重复执行同样只写合法行(幂等键由 SQL 保证)"); assertEquals(2, second, "重复执行同样只写合法行(幂等键由 SQL 保证)");
@@ -108,11 +122,11 @@ class CollectDataInvalidAsinBatchWriterTest {
@Test @Test
void test_task_048_asin_boundary_empty_input() { void test_task_048_asin_boundary_empty_input() {
// 空输入:空列表与全空行均不发起任何批量写入调用,返回 0。 // 空输入:空列表与全空行均不发起任何批量写入调用,返回 0。
int written = writer.writeBatch(null); int written = writer.writeBatch(null, UPLOADER);
assertEquals(0, written, "null 输入返回 0"); assertEquals(0, written, "null 输入返回 0");
verify(invalidAsinDataMapper, never()).insertBatchIgnore(anyList()); verify(invalidAsinDataMapper, never()).insertBatchIgnore(anyList());
int blankWritten = writer.writeBatch(List.of(row("", "nike"), row("B000000001", ""))); int blankWritten = writer.writeBatch(List.of(row("", "nike"), row("B000000001", "")), UPLOADER);
assertEquals(0, blankWritten, "无合法行返回 0"); assertEquals(0, blankWritten, "无合法行返回 0");
verify(invalidAsinDataMapper, never()).insertBatchIgnore(anyList()); verify(invalidAsinDataMapper, never()).insertBatchIgnore(anyList());
} }
@@ -122,7 +136,7 @@ class CollectDataInvalidAsinBatchWriterTest {
// 单元素:单行单品牌正常批量写入;批次大小 1 的边界也正常。 // 单元素:单行单品牌正常批量写入;批次大小 1 的边界也正常。
when(invalidAsinDataMapper.insertBatchIgnore(anyList())).thenReturn(1); when(invalidAsinDataMapper.insertBatchIgnore(anyList())).thenReturn(1);
int written = writer.writeBatch(List.of(row("B000000001", "solo"))); int written = writer.writeBatch(List.of(row("B000000001", "solo")), UPLOADER);
assertEquals(1, written, "单行写入成功"); assertEquals(1, written, "单行写入成功");
ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class); ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class);
@@ -137,13 +151,13 @@ 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, 3); new CollectDataInvalidAsinBatchWriter(invalidAsinDataMapper, companyScopeSupport, 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"));
} }
int written = smallWriter.writeBatch(rows); int written = smallWriter.writeBatch(rows, UPLOADER);
assertEquals(10, written, "全部写入"); assertEquals(10, written, "全部写入");
ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class); ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class);
@@ -164,7 +178,7 @@ class CollectDataInvalidAsinBatchWriterTest {
rows.add(row("B000000001", null)); rows.add(row("B000000001", null));
rows.add(row(" B000000002 ", " nike ")); rows.add(row(" B000000002 ", " nike "));
int written = writer.writeBatch(rows); int written = writer.writeBatch(rows, UPLOADER);
assertEquals(1, written, "仅完全合法的 1 行写入"); assertEquals(1, written, "仅完全合法的 1 行写入");
ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class); ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class);
@@ -187,7 +201,7 @@ class CollectDataInvalidAsinBatchWriterTest {
rows.add(row("B" + String.format("%09d", i + 1), "brand")); rows.add(row("B" + String.format("%09d", i + 1), "brand"));
} }
int written = writer.writeBatch(rows); int written = writer.writeBatch(rows, UPLOADER);
assertEquals(2, written, "首批失败跳过,第二批 2 行写入"); assertEquals(2, written, "首批失败跳过,第二批 2 行写入");
verify(invalidAsinDataMapper, times(2)).insertBatchIgnore(anyList()); verify(invalidAsinDataMapper, times(2)).insertBatchIgnore(anyList());
@@ -196,6 +210,38 @@ class CollectDataInvalidAsinBatchWriterTest {
assertTrue(captor.getAllValues().get(1).size() > 0, "恢复后批次非空"); assertTrue(captor.getAllValues().get(1).size() > 0, "恢复后批次非空");
} }
@Test
void test_batch_3_asin_normal_ownership_is_stamped_on_every_row() {
// 归属由任务发起账号推:每一行都带 company_id + uploader_user_id,
// 而不是留空让 DEFAULT 1 去盖(那会把第 2 家的行记成第 1 家,事后分不开)。
when(invalidAsinDataMapper.insertBatchIgnore(anyList())).thenAnswer(
invocation -> ((List<?>) invocation.getArgument(0)).size());
when(companyScopeSupport.companyIdOrNull(UPLOADER)).thenReturn(UPLOADER_COMPANY);
writer.writeBatch(List.of(row("B000000001", "nike"), row("B000000002", "zara")), UPLOADER);
ArgumentCaptor<List<InvalidAsinDataEntity>> captor = ArgumentCaptor.forClass(List.class);
verify(invalidAsinDataMapper).insertBatchIgnore(captor.capture());
List<InvalidAsinDataEntity> entities = captor.getValue();
assertEquals(2, entities.size());
for (InvalidAsinDataEntity entity : entities) {
assertEquals(UPLOADER_COMPANY, entity.getCompanyId(), "company_id 来自发起账号,不是 DEFAULT");
assertEquals(UPLOADER, entity.getUploaderUserId(), "uploader_user_id 一并落,处置可回溯到人");
}
}
@Test
void test_batch_3_asin_invalid_owner_unresolved_skips_whole_batch() {
// 推不出公司(账号已删/没有公司):整批不写、返回 0、一次 insertBatchIgnore 都不发。
// 这一族的替代方案是"照常写、让 DEFAULT 盖一家",那是静默串数据,必须判红。
when(companyScopeSupport.companyIdOrNull(UPLOADER)).thenReturn(null);
int written = writer.writeBatch(List.of(row("B000000001", "nike"), row("B000000002", "zara")), UPLOADER);
assertEquals(0, written, "归属推不出 ⇒ 一行都不写");
verify(invalidAsinDataMapper, never()).insertBatchIgnore(anyList());
}
private static CollectDataResultRowVo row(String asin, String brand) { private static CollectDataResultRowVo row(String asin, String brand) {
CollectDataResultRowVo row = new CollectDataResultRowVo(); CollectDataResultRowVo row = new CollectDataResultRowVo();
row.setAsin(asin); row.setAsin(asin);
@@ -19,6 +19,8 @@ import java.util.ArrayList;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
@@ -34,8 +36,10 @@ import static org.mockito.Mockito.when;
* 还没摘,此后每个没显式传公司的写入都会被静默塞进默认那家——不报错、不丢数据,只在后台列表里 * 还没摘,此后每个没显式传公司的写入都会被静默塞进默认那家——不报错、不丢数据,只在后台列表里
* 表现成"这条数据怎么在别家公司"。所以必须用代码在启动期喊出来,而不是写在注释里等人记得。</p> * 表现成"这条数据怎么在别家公司"。所以必须用代码在启动期喊出来,而不是写在注释里等人记得。</p>
* *
* <p>V145 之后盯的是【三张表】(users + 两张规则库),不是一列:漏登记的那张表等于没人盯, * <p>V145 之后盯的是【一张清单】(users + 两张规则库 + V147 的 biz_product_category),不是一列:
* 所以"探不到列"也要出声(见 {@link #unwatchedTableIsAnnouncedInsteadOfLookingClean})。</p> * 漏登记的那张表等于没人盯,所以"探不到列"也要出声(见
* {@link #unwatchedTableIsAnnouncedInsteadOfLookingClean})。清单与探针 SQL 的 IN 列表双向同源由
* {@link #watchedTablesMatchTheProbeSql} 钉住。</p>
*/ */
class CompanyDefaultGuardTest { class CompanyDefaultGuardTest {
@@ -66,20 +70,49 @@ class CompanyDefaultGuardTest {
when(companyMapper.selectCount(null)).thenReturn(count); when(companyMapper.selectCount(null)).thenReturn(count);
} }
/** 一条探针结果都没有=这些表在 information_schema 里查不到 company_id。 */ /**
* 一条探针结果都没有=这些表在 information_schema 里查不到 company_id。
*
* <p>未被点名的表按"已摘掉"自动补齐:清单哪天加第五条,本文件那几支"一声不响"的用例不会
* 因为漏了一张而红在 {@link #unwatchedTableIsAnnouncedInsteadOfLookingClean} 的同一条 WARN 上——
* 那种红会把人引去改哨兵,而哨兵是对的。要演"探不到"那一族,用 {@link #probeReturnsOnly}。</p>
*/
private void probeReturns(String... tableAndDefault) { private void probeReturns(String... tableAndDefault) {
Map<String, String> given = new LinkedHashMap<>();
for (String entry : tableAndDefault) {
int split = entry.indexOf('=');
given.put(entry.substring(0, split), split + 1 >= entry.length() ? null : entry.substring(split + 1));
}
List<Map<String, Object>> rows = new ArrayList<>();
for (String table : CompanyDefaultGuard.WATCHED_TABLES) {
if (!given.containsKey(table)) {
rows.add(row(table, null));
} else {
rows.add(row(table, given.get(table)));
}
}
when(jdbcTemplate.queryForList(anyString())).thenReturn(rows);
}
/** 只给这几条结果,不补清单:用来演"某一列在 information_schema 里查不到"。 */
private void probeReturnsOnly(String... tableAndDefault) {
List<Map<String, Object>> rows = new ArrayList<>(); List<Map<String, Object>> rows = new ArrayList<>();
for (String entry : tableAndDefault) { for (String entry : tableAndDefault) {
int split = entry.indexOf('='); int split = entry.indexOf('=');
Map<String, Object> row = new LinkedHashMap<>(); rows.add(row(entry.substring(0, split),
row.put("TABLE_NAME", entry.substring(0, split)); split + 1 >= entry.length() || "null".equals(entry.substring(split + 1))
row.put("COLUMN_DEFAULT", split + 1 >= entry.length() || "null".equals(entry.substring(split + 1)) ? null : entry.substring(split + 1)));
? null : entry.substring(split + 1));
rows.add(row);
} }
when(jdbcTemplate.queryForList(anyString())).thenReturn(rows); when(jdbcTemplate.queryForList(anyString())).thenReturn(rows);
} }
private static Map<String, Object> row(String table, String columnDefault) {
Map<String, Object> row = new LinkedHashMap<>();
row.put("TABLE_NAME", table);
row.put("COLUMN_DEFAULT", "null".equals(columnDefault) ? null : columnDefault);
return row;
}
private String messageAt(Level level) { private String messageAt(Level level) {
return appender.list.stream() return appender.list.stream()
.filter(e -> e.getLevel() == level) .filter(e -> e.getLevel() == level)
@@ -194,19 +227,39 @@ class CompanyDefaultGuardTest {
@DisplayName("盯不到的那张表要出声,不能装作检查过了") @DisplayName("盯不到的那张表要出声,不能装作检查过了")
void unwatchedTableIsAnnouncedInsteadOfLookingClean() { void unwatchedTableIsAnnouncedInsteadOfLookingClean() {
companies(2); companies(2);
probeReturns("users=null"); probeReturnsOnly("users=null");
guard.check(); guard.check();
assertThat(messageAt(Level.ERROR)).isEmpty(); assertThat(messageAt(Level.ERROR)).isEmpty();
assertThat(messageAt(Level.WARN)) String warn = messageAt(Level.WARN);
.contains(CompanyDefaultGuard.PROBE_FAILED) assertThat(warn).contains(CompanyDefaultGuard.PROBE_FAILED);
.contains("biz_invalid_asin_data") // 逐条点名而不是挑两条写死:清单里每一条都必须出现在"探不到"的名单里,
.contains("biz_dedupe_total_data"); // 新登记表漏进 SQL 之外的任何一侧都会在这一支红。
for (String table : CompanyDefaultGuard.WATCHED_TABLES) {
if (!"users".equals(table)) {
assertThat(warn).contains(table);
}
}
} }
@Test @Test
@DisplayName("探的是这三张表的 company_id 列,表名列名写错就等于没探") @DisplayName("V147 的 biz_product_category 也在盯的清单里:摘 DEFAULT 那一步不许把它落下")
void productCategoryTableIsWatchedToo() {
companies(2);
probeReturns("biz_product_category=1");
guard.check();
assertThat(messageAt(Level.ERROR))
.contains(CompanyDefaultGuard.ALARM)
.contains("biz_product_category.company_id DEFAULT=1")
.contains("ALTER TABLE biz_product_category ALTER COLUMN company_id DROP DEFAULT")
.doesNotContain("MODIFY");
}
@Test
@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_invalid_asin_data=null", "biz_dedupe_total_data=null");
@@ -218,19 +271,38 @@ class CompanyDefaultGuardTest {
assertThat(sql.getValue()) assertThat(sql.getValue())
.contains("information_schema.COLUMNS") .contains("information_schema.COLUMNS")
.contains("DATABASE()") .contains("DATABASE()")
.contains("'company_id'") .contains("'company_id'");
.contains("'users'") for (String table : CompanyDefaultGuard.WATCHED_TABLES) {
.contains("'biz_invalid_asin_data'") assertThat(sql.getValue()).contains("'" + table + "'");
.contains("'biz_dedupe_total_data'"); }
} }
/**
* 双向钉同源。只钉"清单里的都在 SQL 里"会漏掉另一侧:有人往 SQL 的 IN 列表加了一张表、
* 却没加进 {@code WATCHED_TABLES},那么 {@link #check} 的逐表循环根本不会走到它——
* 探针查得到、判定查不到,Outcome 是"这张表没人盯"而一声不响,正是本哨兵要消灭的那个形状。
*/
@Test @Test
@DisplayName("清单与探针 SQL 的 IN 列表必须同源:漏一条就是那张表没人盯") @DisplayName("清单与探针 SQL 的 IN 列表必须同源:两个方向都钉,漏一条就是那张表没人盯")
void watchedTablesMatchTheProbeSql() { void watchedTablesMatchTheProbeSql() {
String probeSql = probeSqlText(); String probeSql = probeSqlText();
for (String table : CompanyDefaultGuard.WATCHED_TABLES) { for (String table : CompanyDefaultGuard.WATCHED_TABLES) {
assertThat(probeSql).contains("'" + table + "'"); assertThat(probeSql).contains("'" + table + "'");
} }
assertThat(inListTables(probeSql)).containsExactlyInAnyOrder(
CompanyDefaultGuard.WATCHED_TABLES.toArray(new String[0]));
}
/** 取 {@code TABLE_NAME IN ('a', 'b')} 里那批单引号表名(只认 IN 那一段,别把 'company_id' 也算进来)。 */
private static List<String> inListTables(String probeSql) {
Matcher inList = Pattern.compile("TABLE_NAME\\s+IN\\s*\\(([^)]*)\\)").matcher(probeSql);
assertThat(inList.find()).as("探针 SQL 里没有 TABLE_NAME IN (…) 这一段,取不到清单").isTrue();
List<String> tables = new ArrayList<>();
Matcher quoted = Pattern.compile("'([^']+)'").matcher(inList.group(1));
while (quoted.find()) {
tables.add(quoted.group(1));
}
return tables;
} }
private String probeSqlText() { private String probeSqlText() {
@@ -2,9 +2,12 @@ package com.nanri.aiimage.modules.dedupe.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.common.service.DataReadScope;
import com.nanri.aiimage.common.service.ReadScope;
import com.nanri.aiimage.modules.dedupe.service.DedupeTotalDataService; import com.nanri.aiimage.modules.dedupe.service.DedupeTotalDataService;
import com.nanri.aiimage.common.model.entity.AdminUserEntity; import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService; import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
@@ -15,6 +18,7 @@ import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBo
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -38,9 +42,11 @@ class DedupeTotalDataControllerTest {
DedupeTotalDataService service = mock(DedupeTotalDataService.class); DedupeTotalDataService service = mock(DedupeTotalDataService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class); AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class); PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
HttpServletRequest request = mock(HttpServletRequest.class); HttpServletRequest request = mock(HttpServletRequest.class);
DedupeTotalDataController controller = new DedupeTotalDataController( DedupeTotalDataController controller = new DedupeTotalDataController(
service, authSupport, permissionMenuService); service, authSupport, permissionMenuService, dataReadScope);
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
AdminUserEntity operator = new AdminUserEntity(); AdminUserEntity operator = new AdminUserEntity();
operator.setId(8L); operator.setId(8L);
operator.setRole("super_admin"); operator.setRole("super_admin");
@@ -57,7 +63,8 @@ class DedupeTotalDataControllerTest {
eq(LocalDate.of(2026, 7, 31)), eq(LocalDate.of(2026, 7, 31)),
eq(3L), eq(3L),
isNull(), isNull(),
eq(8L)); eq(8L),
isNull());
ResponseEntity<StreamingResponseBody> response = controller.export( ResponseEntity<StreamingResponseBody> response = controller.export(
"member", "member",
@@ -65,6 +72,7 @@ class DedupeTotalDataControllerTest {
LocalDate.of(2026, 7, 31), LocalDate.of(2026, 7, 31),
3L, 3L,
null, null,
null,
request); request);
assertNotNull(response.getBody()); assertNotNull(response.getBody());
@@ -87,9 +95,10 @@ class DedupeTotalDataControllerTest {
eq(LocalDate.of(2026, 7, 31)), eq(LocalDate.of(2026, 7, 31)),
eq(3L), eq(3L),
isNull(), isNull(),
eq(8L)); eq(8L),
isNull());
verify(service, never()).writeMonthlyZipExport( verify(service, never()).writeMonthlyZipExport(
any(OutputStream.class), any(), any(), any(), any(), any(), any()); any(OutputStream.class), any(), any(), any(), any(), any(), any(), any());
verifyNoInteractions(permissionMenuService); verifyNoInteractions(permissionMenuService);
} }
@@ -98,9 +107,11 @@ class DedupeTotalDataControllerTest {
DedupeTotalDataService service = mock(DedupeTotalDataService.class); DedupeTotalDataService service = mock(DedupeTotalDataService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class); AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class); PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
HttpServletRequest request = mock(HttpServletRequest.class); HttpServletRequest request = mock(HttpServletRequest.class);
DedupeTotalDataController controller = new DedupeTotalDataController( DedupeTotalDataController controller = new DedupeTotalDataController(
service, authSupport, permissionMenuService); service, authSupport, permissionMenuService, dataReadScope);
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
AdminUserEntity operator = new AdminUserEntity(); AdminUserEntity operator = new AdminUserEntity();
operator.setId(8L); operator.setId(8L);
operator.setRole("super_admin"); operator.setRole("super_admin");
@@ -113,6 +124,7 @@ class DedupeTotalDataControllerTest {
LocalDate.of(2026, 8, 2), LocalDate.of(2026, 8, 2),
3L, 3L,
null, null,
null,
request); request);
assertEquals(MediaType.parseMediaType( assertEquals(MediaType.parseMediaType(
@@ -130,9 +142,10 @@ class DedupeTotalDataControllerTest {
eq(LocalDate.of(2026, 8, 2)), eq(LocalDate.of(2026, 8, 2)),
eq(3L), eq(3L),
isNull(), isNull(),
eq(8L)); eq(8L),
isNull());
verify(service, never()).writeMonthlyZipExport( verify(service, never()).writeMonthlyZipExport(
any(OutputStream.class), any(), any(), any(), any(), any(), any()); any(OutputStream.class), any(), any(), any(), any(), any(), any(), any());
} }
@Test @Test
@@ -140,9 +153,11 @@ class DedupeTotalDataControllerTest {
DedupeTotalDataService service = mock(DedupeTotalDataService.class); DedupeTotalDataService service = mock(DedupeTotalDataService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class); AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class); PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
HttpServletRequest request = mock(HttpServletRequest.class); HttpServletRequest request = mock(HttpServletRequest.class);
DedupeTotalDataController controller = new DedupeTotalDataController( DedupeTotalDataController controller = new DedupeTotalDataController(
service, authSupport, permissionMenuService); service, authSupport, permissionMenuService, dataReadScope);
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
AdminUserEntity operator = new AdminUserEntity(); AdminUserEntity operator = new AdminUserEntity();
operator.setId(8L); operator.setId(8L);
operator.setRole("super_admin"); operator.setRole("super_admin");
@@ -159,7 +174,8 @@ class DedupeTotalDataControllerTest {
eq(LocalDate.of(2026, 8, 2)), eq(LocalDate.of(2026, 8, 2)),
eq(3L), eq(3L),
isNull(), isNull(),
eq(8L)); eq(8L),
isNull());
ResponseEntity<StreamingResponseBody> response = controller.export( ResponseEntity<StreamingResponseBody> response = controller.export(
"member", "member",
@@ -167,6 +183,7 @@ class DedupeTotalDataControllerTest {
LocalDate.of(2026, 8, 2), LocalDate.of(2026, 8, 2),
3L, 3L,
null, null,
null,
request); request);
assertEquals(MediaType.parseMediaType("application/zip"), response.getHeaders().getContentType()); assertEquals(MediaType.parseMediaType("application/zip"), response.getHeaders().getContentType());
@@ -184,8 +201,9 @@ class DedupeTotalDataControllerTest {
eq(LocalDate.of(2026, 8, 2)), eq(LocalDate.of(2026, 8, 2)),
eq(3L), eq(3L),
isNull(), isNull(),
eq(8L)); eq(8L),
verify(service, never()).writeExport(any(OutputStream.class), any(), any(), any(), any(), any(), any()); isNull());
verify(service, never()).writeExport(any(OutputStream.class), any(), any(), any(), any(), any(), any(), any());
} }
@Test @Test
@@ -193,9 +211,11 @@ class DedupeTotalDataControllerTest {
DedupeTotalDataService service = mock(DedupeTotalDataService.class); DedupeTotalDataService service = mock(DedupeTotalDataService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class); AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class); PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
HttpServletRequest request = mock(HttpServletRequest.class); HttpServletRequest request = mock(HttpServletRequest.class);
DedupeTotalDataController controller = new DedupeTotalDataController( DedupeTotalDataController controller = new DedupeTotalDataController(
service, authSupport, permissionMenuService); service, authSupport, permissionMenuService, dataReadScope);
when(dataReadScope.readScope(any(), any())).thenReturn(ReadScope.unfiltered());
BusinessException exception = assertThrows(BusinessException.class, () -> controller.export( BusinessException exception = assertThrows(BusinessException.class, () -> controller.export(
"member", "member",
@@ -203,9 +223,62 @@ class DedupeTotalDataControllerTest {
LocalDate.of(2026, 7, 15), LocalDate.of(2026, 7, 15),
3L, 3L,
null, null,
null,
request)); request));
assertEquals(400, exception.getCode()); assertEquals(400, exception.getCode());
verifyNoInteractions(service, authSupport, permissionMenuService); verifyNoInteractions(service, authSupport, permissionMenuService);
} }
@Test
void companyTabNarrowsSuperAdminToListOfMemberAccounts() {
// 超管点公司 tab ⇒ 成员集必须一路传到 service 的最后一个实参。
// 这一记盯的是"参数收了、readScope 也调了、结果却喂了 null"那种假接线(tab 恒不动的现网形状)。
DedupeTotalDataService service = mock(DedupeTotalDataService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
HttpServletRequest request = mock(HttpServletRequest.class);
DedupeTotalDataController controller = new DedupeTotalDataController(
service, authSupport, permissionMenuService, dataReadScope);
AdminUserEntity operator = new AdminUserEntity();
operator.setId(8L);
operator.setRole("super_admin");
when(authSupport.requireUser(request)).thenReturn(operator);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
when(dataReadScope.readScope(operator, 2L)).thenReturn(ReadScope.users(List.of(11L, 12L)));
controller.page(1L, 15L, null, "member", null, null, null, null, null, 2L, request);
verify(service).page(eq(1L), eq(15L), isNull(), eq("member"),
isNull(), isNull(), isNull(), isNull(), isNull(), eq(8L), eq(List.of(11L, 12L)));
}
@Test
void nonSuperAdminStaysUnfilteredEvenWhenCompanyTabIsSent() {
// 非超管:刻意<b>不</b>按公司收窄。他的可见集里含"靠分组权限可见"的行,
// 叠一层账号 IN 会把那批行静默删掉(口径同 ShopManageController)。
// 这条是反向钉:哪天有人给非超管也加上成员集,这里必须红。
DedupeTotalDataService service = mock(DedupeTotalDataService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
PermissionMenuService permissionMenuService = mock(PermissionMenuService.class);
DataReadScope dataReadScope = mock(DataReadScope.class);
HttpServletRequest request = mock(HttpServletRequest.class);
DedupeTotalDataController controller = new DedupeTotalDataController(
service, authSupport, permissionMenuService, dataReadScope);
AdminUserEntity operator = new AdminUserEntity();
operator.setId(9L);
operator.setRole("admin");
when(authSupport.requireUser(request)).thenReturn(operator);
when(authSupport.currentRole(operator)).thenReturn("admin");
PermissionMenuItemVo granted = new PermissionMenuItemVo();
granted.setColumnKey("admin_dedupe_total_data");
when(permissionMenuService.getUserColumnPermissions(9L, "admin")).thenReturn(List.of(granted));
controller.page(1L, 15L, null, null, null, null, null, null, null, 2L, request);
verify(service).page(eq(1L), eq(15L), isNull(), isNull(),
isNull(), isNull(), isNull(), isNull(), isNull(), eq(9L), isNull());
verify(dataReadScope, never()).readScope(any(), any());
}
} }
@@ -652,7 +652,7 @@ class DedupeTotalDataServiceTest {
rows.add(second); rows.add(second);
when(dedupeTotalDataMapper.selectList(any())).thenReturn(rows); when(dedupeTotalDataMapper.selectList(any())).thenReturn(rows);
DedupeTotalDataPageVo vo = service.page(3, 15, "", "", null, null, null, null, 1000L, 1L); DedupeTotalDataPageVo vo = service.page(3, 15, "", "", null, null, null, null, 1000L, 1L, null);
ArgumentCaptor<LambdaQueryWrapper<DedupeTotalDataEntity>> queryCaptor = ArgumentCaptor<LambdaQueryWrapper<DedupeTotalDataEntity>> queryCaptor =
ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class); ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
@@ -36,6 +36,8 @@ 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;
@@ -58,12 +60,13 @@ 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)) when(invalidAsinDataService.page(1L, 15L, "", "", "", 3L, 7L, false, null))
.thenReturn(new InvalidAsinDataPageVo()); .thenReturn(new InvalidAsinDataPageVo());
when(dataReadScope.readCompanyId(operator, null)).thenReturn(null);
controller.page(1L, 15L, "", "", "", 3L, request); controller.page(1L, 15L, "", "", "", 3L, null, request);
verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 7L, false); verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 7L, false, null);
} }
@Test @Test
@@ -73,7 +76,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, request)); assertThrows(BusinessException.class, () -> controller.page(1L, 15L, "", "", "", 3L, null, request));
verifyNoInteractions(invalidAsinDataService); verifyNoInteractions(invalidAsinDataService);
verify(permissionMenuService, never()).requireUserOperator(any()); verify(permissionMenuService, never()).requireUserOperator(any());
@@ -86,13 +89,50 @@ 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)) when(invalidAsinDataService.page(1L, 15L, "", "", "", 3L, 1L, true, 2L))
.thenReturn(new InvalidAsinDataPageVo());
when(dataReadScope.readCompanyId(operator, 2L)).thenReturn(2L);
controller.page(1L, 15L, "", "", "", 3L, 2L, request);
verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 1L, true, 2L);
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()); .thenReturn(new InvalidAsinDataPageVo());
controller.page(1L, 15L, "", "", "", 3L, request); controller.page(1L, 15L, "", "", "", 3L, null, request);
verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 1L, true); verify(invalidAsinDataService).page(1L, 15L, "", "", "", 3L, 1L, true, null);
verify(permissionMenuService, never()).getUserColumnPermissions(eq(1L), eq("admin")); }
@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) {
@@ -4,6 +4,7 @@ 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;
@@ -39,14 +40,21 @@ 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;
@Test @Test
@SuppressWarnings({"rawtypes", "unchecked"})
void createManualRecordUsesAccessibleGroup() { void createManualRecordUsesAccessibleGroup() {
InvalidAsinDataCreateRequest request = new InvalidAsinDataCreateRequest(); InvalidAsinDataCreateRequest request = new InvalidAsinDataCreateRequest();
request.setDataValue("B012345678"); request.setDataValue("B012345678");
@@ -55,6 +63,7 @@ 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);
@@ -74,6 +83,21 @@ 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());
// 重复预检必须与 V145 放宽后的唯一键 (company_id, data_value, brand) 同宽:少公司这一维,
// 第 2 家永远无法新增第 1 家已有的品牌(跨公司误报「ASIN 已存在」)。
ArgumentCaptor<LambdaQueryWrapper<InvalidAsinDataEntity>> unique =
ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
verify(invalidAsinDataMapper).selectOne(unique.capture());
TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""),
InvalidAsinDataEntity.class);
assertTrue(unique.getValue().getSqlSegment().contains("company_id"));
assertTrue(unique.getValue().getParamNameValuePairs().containsValue(OPERATOR_COMPANY_ID));
} }
@Test @Test
@@ -85,7 +109,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); InvalidAsinDataPageVo page = service.page(1, 15, "", "", "", 10L, 7L, false, null);
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());
@@ -109,7 +133,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); InvalidAsinDataPageVo page = service.page(1, 15, "", "", "", null, 1L, true, null);
assertEquals(2, page.getItems().size()); assertEquals(2, page.getItems().size());
assertEquals("AUTO", page.getItems().getFirst().getRecordSource()); assertEquals("AUTO", page.getItems().getFirst().getRecordSource());
@@ -123,7 +147,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); service.page(1, 15, "", "", "", 9L, 1L, true, null);
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());
@@ -140,7 +164,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); service.page(1, 15, "", "B01", "acme", null, 1L, true, null);
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());
@@ -0,0 +1,125 @@
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 交给 readCompanyId,出口给什么 service 就用什么")
void listPassesTheTabValueThroughTheDoor() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyId(any(AdminUserEntity.class), eq(COMPANY_ID))).thenReturn(COMPANY_ID);
controller().list(request, "面霜", COMPANY_ID);
verify(dataReadScope).readCompanyId(any(AdminUserEntity.class), eq(COMPANY_ID));
verify(productCategoryService).list("面霜", COMPANY_ID);
}
@Test
@DisplayName("列表:非超管由出口判成\"不筛\",controller 不许自己补一个公司 id 进去")
void listUsesTheDorsVerdictForNonSuperAdmin() {
HttpServletRequest request = login();
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(user());
when(dataReadScope.readCompanyId(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.readCompanyId(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))
.readCompanyId(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);
}
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;
}
}
@@ -0,0 +1,310 @@
package com.nanri.aiimage.modules.productcategory.service;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.model.dto.ProductCategorySaveRequest;
import com.nanri.aiimage.modules.productcategory.model.entity.ProductCategoryEntity;
import com.nanri.aiimage.modules.productcategory.model.vo.ProductCategoryListVo;
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.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 「商品类目」按公司视图的那几条不变量(V147 / 需求 2026-10-05「切 tab 数据还一样」)。
*
* <p>这一页的归属是<b>物化列</b>而不是账号集合,所以判据形状与 readScope 那一族不同:
* 可见集 = {@code company_id IN (0, X)},其中 0 是内置节点的哨兵。两支最容易静默坏掉的形状
* 都由本文件钉住:① 哨兵那半不许丢(丢了第 2 家是一棵空树,连自建根都挂不上);
* ② 给 LLM 用的那棵全局树不许被顺手加上公司谓词(加了货源归类的候选就按公司分叉)。</p>
*/
@ExtendWith(MockitoExtension.class)
class ProductCategoryCompanyScopeTest {
private static final long BUILTIN = 0L;
private static final Long OPERATOR_ID = 7L;
/** 故意取 2:DEFAULT 1 那一家通不过"值等于会话公司"这种断言,取 2 才钉得住"真从会话推导"。 */
private static final Long COMPANY_ID = 2L;
private static final Long BUILTIN_PARENT_ID = 10L;
@Mock
private ProductCategoryMapper productCategoryMapper;
@Mock
private CompanyScopeSupport companyScopeSupport;
private ProductCategoryService service;
@BeforeAll
static void initTableInfo() {
// Lambda 条件要解析列名,没有 TableInfo 时 getSqlSegment() 里根本不会出现 company_id。
TableInfoHelper.initTableInfo(
new MapperBuilderAssistant(new MybatisConfiguration(), ""),
ProductCategoryEntity.class);
}
@BeforeEach
void setUp() {
service = new ProductCategoryService(productCategoryMapper, companyScopeSupport);
}
@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()} 唯一的消费者是
* 货源/外观的类目归类({@code SimilarAsinLlmService} 读的是全局树)。给它加公司谓词会让同一个
* "面霜"有 N 个 category_key、LLM 分类结果按公司分叉,那是成本不只是口径。
*/
@Test
@DisplayName("给 LLM 用的全局树不带公司谓词:按公司切会让归类结果按公司分叉")
void globalTreeForTheLlmConsumerStaysUnscoped() {
when(productCategoryMapper.selectList(any())).thenReturn(List.of(row(1L, null, "护肤品", BUILTIN)));
service.list();
LambdaQueryWrapper<ProductCategoryEntity> query = capturedListWrapper();
String sql = query.getSqlSegment();
// 两条一起才算非恒真:只看"不含 company_id"时,一条空 segment(列名解析不到、wrapper 根本没拼)
// 也会通过,那条断言就变成恒绿。先证明 wrapper 真渲染了东西,再证明它一个实参都没带。
assertTrue(sql.contains("ORDER BY"), "wrapper 根本没渲染,下面的否证是空话:" + sql);
assertFalse(sql.contains("company_id"),
"无参 list() 被接上了公司谓词 —— 货源归类的候选树随之按公司分叉:" + sql);
assertTrue(query.getParamNameValuePairs().isEmpty(),
"全局树带出了实参(说明有谓词被塞进来):" + query.getParamNameValuePairs());
}
@Test
@DisplayName("搜索的公司谓词必须在整条 OR 之外:AND 结合更紧会让前两列命中不受公司约束")
void searchKeepsTheOrGroupWrappedBeforeTheCompanyPredicate() {
when(productCategoryMapper.selectCount(any())).thenReturn(0L);
when(productCategoryMapper.selectList(any())).thenReturn(List.of());
service.search("面霜", 1, 20, COMPANY_ID);
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 两条查询都要带公司谓词");
}
@Test
@DisplayName("分页 children 的 count 与 list 两条查询同源,且子类目数徽章也按可见集聚合")
void childrenScopeCountListAndChildBadgeTogether() {
when(productCategoryMapper.selectCount(any())).thenReturn(1L);
when(productCategoryMapper.selectList(any())).thenReturn(List.of(row(20L, BUILTIN_PARENT_ID, "面霜", COMPANY_ID)));
when(productCategoryMapper.selectMaps(any())).thenReturn(List.of());
service.children(BUILTIN_PARENT_ID, 1, 20, COMPANY_ID);
ArgumentCaptor<Wrapper<ProductCategoryEntity>> countCaptor = ArgumentCaptor.forClass(Wrapper.class);
verify(productCategoryMapper).selectCount(countCaptor.capture());
assertTrue(countCaptor.getValue().getSqlSegment().contains("company_id IN"));
LambdaQueryWrapper<ProductCategoryEntity> pageQuery = capturedListWrapper();
assertTrue(pageQuery.getSqlSegment().contains("company_id IN"));
assertTrue(pageQuery.getSqlSegment().contains("parent_id"));
// 「子类目数」徽章走全表聚合:不加公司谓词就会把别家子节点数算进来,数字与点开看到的树不一致。
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));
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);
}
private ProductCategorySaveRequest saveRequest(String name, Long parentId) {
ProductCategorySaveRequest request = new ProductCategorySaveRequest();
request.setName(name);
request.setParentId(parentId);
return request;
}
private static ProductCategoryEntity row(Long id, Long parentId, String name, Long companyId) {
ProductCategoryEntity entity = new ProductCategoryEntity();
entity.setId(id);
entity.setParentId(parentId);
entity.setName(name);
entity.setCategoryKey("cat_" + id);
entity.setSortOrder(100);
entity.setCompanyId(companyId);
entity.setIsBuiltin(companyId == BUILTIN);
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,86 @@
package com.nanri.aiimage.modules.shopdatacrawl.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.modules.shopdatacrawl.mapper.ShopDataCrawlAdminTasksMapper;
import com.nanri.aiimage.modules.shopdatacrawl.mapper.ShopDataCrawlItemMapper;
import com.nanri.aiimage.modules.shopdatacrawl.spi.DuplicateCheckRefreshPort;
import com.nanri.aiimage.modules.shopdatacrawl.spi.ManagedShopNamesPort;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* 店铺数据记录(D 类第二页)的公司 tab:可见店铺集的三条出口必须各不相同。
*
* <p>这一页的单位是「店铺」而不是行,所以公司条件落在店铺名集合上(与撞款页同一个 normalize);
* 两处最容易写错且都不报错的形状是:超管没切 tab 时给出空集合(整页突然空),
* 以及空成员集时给出 null(在这套语义里是"全量",等于把第 1 家的数据交给第 2 家)。</p>
*/
class ShopDataCrawlAdminTasksCompanyScopeTest {
private ManagedShopNamesPort port;
private ShopDataCrawlAdminTasksService service;
@BeforeEach
void setUp() {
port = mock(ManagedShopNamesPort.class);
service = new ShopDataCrawlAdminTasksService(
mock(ShopDataCrawlAdminTasksMapper.class), port,
mock(ShopDataCrawlItemMapper.class),
mock(FileResultMapper.class),
mock(ShopDataCrawlDailyFileService.class),
mock(OssStorageService.class),
mock(ShopDataCrawlTaskService.class),
mock(DuplicateCheckRefreshPort.class),
new ObjectMapper());
}
@Test
@DisplayName("超管没切公司 tab=null(全量),逐字等于接线前")
void superAdminWithoutCompanySeesEverything() {
assertThat(service.resolveVisibleShopKeys(1L, true, null)).isNull();
verify(port, never()).selectManagedShopNames(any());
verify(port, never()).selectShopNamesOwnedByMembers(anyList());
}
@Test
@DisplayName("超管切到某家公司=按店铺负责人取那家的店铺名,小写去空格")
void superAdminOnCompanyTabUsesShopOwnerRuler() {
when(port.selectShopNamesOwnedByMembers(List.of(7L, 8L)))
.thenReturn(List.of(" ShopA ", "shopa", "ShopB"));
assertThat(service.resolveVisibleShopKeys(1L, true, List.of(7L, 8L)))
.containsExactly("shopa", "shopb");
}
@Test
@DisplayName("空成员集=空列表而不是 null:这家没有店铺,不许退化成全量")
void emptyMemberSetIsNoShopsNotEverything() {
when(port.selectShopNamesOwnedByMembers(List.of())).thenReturn(List.of());
List<String> keys = service.resolveVisibleShopKeys(1L, true, List.of());
assertThat(keys).isNotNull();
assertThat(keys).isEmpty();
}
@Test
@DisplayName("非超管仍按分组关系推,公司成员集不参与(tab 不是安全边界)")
void nonSuperKeepsGroupBasedView() {
when(port.selectManagedShopNames(9L)).thenReturn(List.of("ShopC"));
assertThat(service.resolveVisibleShopKeys(9L, false, List.of(7L))).containsExactly("shopc");
verify(port, never()).selectShopNamesOwnedByMembers(anyList());
}
}
@@ -0,0 +1,180 @@
package com.nanri.aiimage.modules.shopduplicatecheck.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.nanri.aiimage.modules.shopduplicatecheck.TestFixtures;
import com.nanri.aiimage.modules.shopduplicatecheck.mapper.ShopDuplicateCheckSourceMapper;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.builder.annotation.MapperAnnotationBuilder;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* 店铺撞款监控的公司 tab(D 类第一页)。
*
* <p>要钉住的不是"筛了没筛",而是三件各自会静默出错的事:</p>
* <ol>
* <li><b>公司这一支必须换尺子</b>,从"主管分组关系"换到"店铺行自己的负责人"
* ({@code biz_shop_manage.created_by_id})。留在分组尺子上,第 1 家 tab 会把 12 个分组
* 里只挂 user_id 的那 2 个也算进来,与已上线的「店铺管理」页对不上——同一个 tab 两家页面前后
* 给出不同的店铺集合,比空页更容易被当成 bug 报。</li>
* <li><b>{@code null} 在这一页是"全量"而不是"没筛出东西"</b>。空成员集若退化成 null,
* "切到一家还没有店铺的账号公司"= 看到全部数据(越界方向恰好是少隔离那一侧)。</li>
* <li><b>非超管不许跟着 tab 改口径</b>(spec §4:tab 是视图开关,不是安全边界)。</li>
* </ol>
*/
class ShopDataDuplicateCheckCompanyScopeTest {
private ShopDuplicateCheckSourceMapper mapper;
private ShopDataDuplicateCheckQueryService service;
private ShopDataDuplicateCheckScanService.DuplicateScanView view;
@BeforeEach
void setUp() {
mapper = mock(ShopDuplicateCheckSourceMapper.class);
service = new ShopDataDuplicateCheckQueryService(mapper);
view = TestFixtures.view();
}
@Test
@DisplayName("超管没切公司 tab=全量(null),与接线前逐字一致")
void superAdminWithoutCompanyTabSeesEverything() {
assertThat(service.resolveVisibleShopKeys(1L, true, null)).isNull();
verify(mapper, never()).selectManagedShopNames(any());
verify(mapper, never()).selectShopNamesOwnedBy(anyList());
}
@Test
@DisplayName("超管切到某家公司=只按店铺负责人推,且不再碰分组尺子")
void companyTabSwitchesToTheShopOwnerRuler() {
when(mapper.selectShopNamesOwnedBy(List.of(7L, 8L)))
.thenReturn(Arrays.asList(" ShopA ", "ShopB", " ", null));
when(mapper.selectManagedShopNames(1L)).thenReturn(List.of("ShopZ"));
Set<String> keys = service.resolveVisibleShopKeys(1L, true, List.of(7L, 8L));
// trim + 小写 + 丢空:与主管那一支同一个 normalize,否则交集会因为大小写漏掉整店
assertThat(keys).containsExactly("shopa", "shopb");
verify(mapper, never()).selectManagedShopNames(any());
}
@Test
@DisplayName("空成员集=这家一家店铺都没有:必须是空集合,绝不能是 null(null=全量)")
void emptyMemberSetMeansNoShopsNotEverything() {
Set<String> keys = service.resolveVisibleShopKeys(1L, true, List.of());
assertThat(keys).isNotNull();
assertThat(keys).isEmpty();
// 空列表真喂进 mapper 会产出非法的 IN ()(见 mapperScript 那两支),所以必须在这里就挡住
verify(mapper, never()).selectShopNamesOwnedBy(anyList());
}
@Test
@DisplayName("非超管的可见范围只由分组关系决定,传进来的公司成员集不参与")
void nonSuperKeepsTheGroupBasedView() {
when(mapper.selectManagedShopNames(9L)).thenReturn(List.of("ShopC"));
Set<String> keys = service.resolveVisibleShopKeys(9L, false, List.of(7L));
assertThat(keys).containsExactly("shopc");
verify(mapper, never()).selectShopNamesOwnedBy(anyList());
}
@Test
@DisplayName("分组筛选叠在公司集之后:同组里别家公司的店不许被放回来")
void groupFilterNeverWidensTheCompanySet() {
// 夹具里 GroupA 含 ShopA + ShopB。公司集只给 shopa ⇒ 选 GroupA 也只能看到 shopa。
assertThat(service.withGroupFilter(Set.of("shopa"), view, "GroupA")).containsExactly("shopa");
assertThat(service.withGroupFilter(Set.of(), view, "GroupA")).isEmpty();
// 反向对照:不存在的分组名给出空集——证明这条链真在求交,而不是原样把入参退回来
assertThat(service.withGroupFilter(Set.of("shopa"), view, "NoSuchGroup")).isEmpty();
}
// ------------------------------------------------------------------ 端口
@Test
@DisplayName("端口(店铺数据记录用的那一条)对空/ null 成员集直接给空列表,不落 SQL")
void portGuardsEmptyMemberSet() {
ManagedShopNamesPortAdapter adapter = new ManagedShopNamesPortAdapter(mapper);
assertThat(adapter.selectShopNamesOwnedByMembers(List.of())).isEmpty();
assertThat(adapter.selectShopNamesOwnedByMembers(null)).isEmpty();
verify(mapper, never()).selectShopNamesOwnedBy(anyList());
when(mapper.selectShopNamesOwnedBy(List.of(3L))).thenReturn(List.of("ShopD"));
assertThat(adapter.selectShopNamesOwnedByMembers(List.of(3L))).containsExactly("ShopD");
}
// ------------------------------------------------------- 注解 SQL 真的能解析
/**
* {@code @Select} 里的 {@code <script>} + {@code foreach} 只有运行期才会报错,mock 掉的 mapper
* 一条也测不到。这里把注解原文交给 MyBatis 自己的动态 SQL 引擎跑一遍——
* 破坏点包括:{@code <>} 忘了转义(XML 解析当场抛)、foreach 的 collection 名写错(参数取不到)、
* #{mid} 被写成 ${mid}(占位符数对不上=SQL 注入面)。
*/
@Test
@DisplayName("selectShopNamesOwnedBy 的动态 SQL:两个成员=两个占位符,且字面量仍是参数绑定")
void mapperScriptBindsEveryMemberIdAsParameter() throws Exception {
String sql = boundSqlFor(List.of(7L, 8L)).getSql();
assertThat(sql)
.contains("biz_shop_manage")
.contains("created_by_id IN")
.doesNotContain("<script>")
.doesNotContain("foreach")
.doesNotContain("$");
// 占位符个数=成员个数:写成 ${mid} 会在这里露出来(少一个 ? 而串里多出字面值)
assertThat(sql.chars().filter(c -> c == '?').count()).isEqualTo(2);
assertThat(boundSqlFor(List.of(7L, 8L)).getParameterMappings()).hasSize(2);
}
@Test
@DisplayName("同一支 SQL 对空成员集产出残缺语句(IN 后面什么都没有)——端口那支 return List.of() 是承重的")
void mapperScriptCannotSurviveEmptyMemberSet() throws Exception {
String sql = boundSqlFor(List.of()).getSql();
// 实测这一版 MyBatis 的 foreach 在零元素时连括号都不给,语句就停在 "... created_by_id IN" 上:
// 1064 语法错。所以"空成员=这家没有店铺"必须在 Java 侧兜住,不能把空列表喂进 SQL。
assertThat(sql.trim()).endsWith("created_by_id IN");
assertThat(sql.chars().filter(c -> c == '?').count()).isZero();
}
@Test
@DisplayName("转义后的 <> 在生成的 SQL 里必须是真比较符,不能被吃掉或留成实体")
void mapperScriptKeepsTheNotEmptyPredicate() throws Exception {
String sql = boundSqlFor(List.of(7L)).getSql();
assertThat(sql).contains("<>");
assertThat(sql).doesNotContain("&lt;");
}
private static BoundSql boundSqlFor(List<Long> memberIds) throws Exception {
Method method = ShopDuplicateCheckSourceMapper.class
.getMethod("selectShopNamesOwnedBy", List.class);
String script = String.join(" ", method.getAnnotation(Select.class).value());
Configuration configuration = new MybatisConfiguration();
// 走注解构建器的同一条路径:把这条语句注册进 configuration,再向它要 BoundSql
new MapperAnnotationBuilder(configuration, ShopDuplicateCheckSourceMapper.class)
.parse();
MappedStatement statement = configuration.getMappedStatement(
ShopDuplicateCheckSourceMapper.class.getName() + ".selectShopNamesOwnedBy");
return statement.getBoundSql(Map.of("memberIds", memberIds));
}
}
@@ -230,7 +230,7 @@ class SkipPriceAsinServiceTest {
when(skipPriceAsinMapper.selectList(any())).thenReturn(List.of()); when(skipPriceAsinMapper.selectList(any())).thenReturn(List.of());
service.page(1, 15, null, null, null, null, service.page(1, 15, null, null, null, null,
new BigDecimal("10.00"), new BigDecimal("20.00"), null, true); new BigDecimal("10.00"), new BigDecimal("20.00"), null, true, null);
ArgumentCaptor<Wrapper<SkipPriceAsinEntity>> captor = ArgumentCaptor.forClass(Wrapper.class); ArgumentCaptor<Wrapper<SkipPriceAsinEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(skipPriceAsinMapper).selectCount(captor.capture()); verify(skipPriceAsinMapper).selectCount(captor.capture());
@@ -252,7 +252,7 @@ class SkipPriceAsinServiceTest {
when(skipPriceAsinMapper.selectList(any())).thenReturn(List.of()); when(skipPriceAsinMapper.selectList(any())).thenReturn(List.of());
service.page(1, 15, null, null, null, "DE", service.page(1, 15, null, null, null, "DE",
new BigDecimal("15.00"), null, null, true); new BigDecimal("15.00"), null, null, true, null);
ArgumentCaptor<Wrapper<SkipPriceAsinEntity>> captor = ArgumentCaptor.forClass(Wrapper.class); ArgumentCaptor<Wrapper<SkipPriceAsinEntity>> captor = ArgumentCaptor.forClass(Wrapper.class);
verify(skipPriceAsinMapper).selectCount(captor.capture()); verify(skipPriceAsinMapper).selectCount(captor.capture());