Compare commits

..

3 Commits

13 changed files with 447 additions and 89 deletions
+16 -2
View File
@@ -7,17 +7,18 @@ import { useRoute } from 'vue-router'
import { COMPANY_STATUS_ACTIVE } from '@/api/companies-dto' import { COMPANY_STATUS_ACTIVE } from '@/api/companies-dto'
import { useCompanyTabStore } from '@/stores/company-tab' import { useCompanyTabStore } from '@/stores/company-tab'
import { useAdminSessionStore } from '@/stores/admin-session' import { useAdminSessionStore } from '@/stores/admin-session'
import { usePlatformTabStore } from '@/stores/platform-tab'
import { companyTabAppliesTo, companyTabInitFailureMessage } from '@/layout/company-tab-model' import { companyTabAppliesTo, companyTabInitFailureMessage } from '@/layout/company-tab-model'
import { showAdminFeedback } from '@/components/admin-feedback-ui' import { showAdminFeedback } from '@/components/admin-feedback-ui'
const route = useRoute() const route = useRoute()
const tab = useCompanyTabStore() const tab = useCompanyTabStore()
const session = useAdminSessionStore() const session = useAdminSessionStore()
const platformTab = usePlatformTabStore()
const tabs = computed(() => tab.companies.filter((c) => c.status === COMPANY_STATUS_ACTIVE)) const tabs = computed(() => tab.companies.filter((c) => c.status === COMPANY_STATUS_ACTIVE))
const show = computed(() => tab.visibleForOperator && companyTabAppliesTo(route.meta.menuKey)) const show = computed(() => tab.visibleForOperator && companyTabAppliesTo(route.meta.menuKey))
watch(() => session.isSuperAdmin, (v) => { function ensureLoaded() {
if (!v) return
// 2026-10-05 修复轮 1:改前这里是 `void tab.initialize()`,store 里也只有 try/finally ⇒ // 2026-10-05 修复轮 1:改前这里是 `void tab.initialize()`,store 里也只有 try/finally ⇒
// GET /companies 抛错时异常变成 unhandled rejection(全仓 src 无 errorHandler/unhandledrejection 兜底), // GET /companies 抛错时异常变成 unhandled rejection(全仓 src 无 errorHandler/unhandledrejection 兜底),
// 现场只剩"tab 条没画出来",Task 13 人工清单第一项无从判断是权限问题还是接口挂了。 // 现场只剩"tab 条没画出来",Task 13 人工清单第一项无从判断是权限问题还是接口挂了。
@@ -29,7 +30,20 @@ watch(() => session.isSuperAdmin, (v) => {
console.warn('[company-tab] 公司目录没取到,tab 条不渲染', error) console.warn('[company-tab] 公司目录没取到,tab 条不渲染', error)
showAdminFeedback(companyTabInitFailureMessage(error), 'warning') showAdminFeedback(companyTabInitFailureMessage(error), 'warning')
}) })
}
watch(() => session.isSuperAdmin, (v) => {
if (!v) return
ensureLoaded()
}, { immediate: true }) }, { immediate: true })
// 平台 tab 切换=公司目录换一份(V206 平台分侧;2026-11-17 用户口径「亚马逊侧别再挂京东-团队,
// 京东侧同理」):store 按 loadedPlatform 对撞早退,切了台必然重拉。非超管目录恒空不发请求,
// 这里同样按超管闸早退。
watch(() => platformTab.active, () => {
if (!session.isSuperAdmin) return
ensureLoaded()
})
</script> </script>
<template> <template>
@@ -8,6 +8,7 @@ import { formatDateTime } from '@/utils/datetime'
import { fetchCompanies } from '@/api/companies' import { fetchCompanies } from '@/api/companies'
import { COMPANY_STATUS_ACTIVE, type CompanyItem } from '@/api/companies-dto' import { COMPANY_STATUS_ACTIVE, type CompanyItem } from '@/api/companies-dto'
import { useAdminSessionStore } from '@/stores/admin-session' import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
import { usePlatformTabStore } from '@/stores/platform-tab' import { usePlatformTabStore } from '@/stores/platform-tab'
import OldPagination from '@/components/OldPagination.vue' import OldPagination from '@/components/OldPagination.vue'
import CompanyEditorDialog from './CompanyEditorDialog.vue' import CompanyEditorDialog from './CompanyEditorDialog.vue'
@@ -17,6 +18,9 @@ import LoadFailureBar from '@/components/LoadFailureBar.vue'
const session = useAdminSessionStore() const session = useAdminSessionStore()
// 平台 tab(V206):公司列表按当前平台过滤,新建默认落当前平台。 // 平台 tab(V206):公司列表按当前平台过滤,新建默认落当前平台。
const platformTab = usePlatformTabStore() const platformTab = usePlatformTabStore()
// 公司 tab 条(2026-11-17 起按平台过滤)共用这一份目录:公司翻档/启停后必须强制重拉,
// 否则 18 个页面的 tab 条端着旧名单,刚翻去京东的公司还挂在亚马逊侧。
const companyTab = useCompanyTabStore()
const loading = ref(false) const loading = ref(false)
const loadFailure = ref('') const loadFailure = ref('')
const rows = ref<CompanyItem[]>([]) const rows = ref<CompanyItem[]>([])
@@ -60,6 +64,15 @@ function openEdit(company: CompanyItem) {
editorVisible.value = true editorVisible.value = true
} }
// 保存成功后:本页列表照常重拉,共享公司目录(tab 条)强制重拉一份。
// 重拉失败不弹新提示(§12 第 5 条未批的界面暴露):tab 条保留旧名单,下一次切平台 tab / 重进页面会再试。
async function onCompaniesSaved() {
await loadCompanies()
companyTab.refresh().catch((error: unknown) => {
console.warn('[company-tab] 公司保存后目录重拉失败', error)
})
}
// 切平台 tab(V206)= 重新取数:公司归属按平台分列,两 tab 各看各的公司。 // 切平台 tab(V206)= 重新取数:公司归属按平台分列,两 tab 各看各的公司。
watch(() => platformTab.active, () => { watch(() => platformTab.active, () => {
page.value = 1 page.value = 1
@@ -136,7 +149,7 @@ onMounted(loadCompanies)
/> />
</section> </section>
<CompanyEditorDialog v-model="editorVisible" :company="editingCompany" :platform="platformTab.active" @saved="loadCompanies" /> <CompanyEditorDialog v-model="editorVisible" :company="editingCompany" :platform="platformTab.active" @saved="onCompaniesSaved" />
</div> </div>
</template> </template>
@@ -182,26 +182,32 @@ function goJump() {
// ② 用户名全平台唯一(V143 的唯一索引),留着上一家填的关键字去筛新一家 ⇒ 必然空页,而输入框还显示着那个值。 // ② 用户名全平台唯一(V143 的唯一索引),留着上一家填的关键字去筛新一家 ⇒ 必然空页,而输入框还显示着那个值。
watch(() => companyTab.activeId, () => { filters.createdByAdminId = null; filters.keyword = ''; filters.page = 1; void loadUsers() }) watch(() => companyTab.activeId, () => { filters.createdByAdminId = null; filters.keyword = ''; filters.page = 1; void loadUsers() })
// 切平台 tab(V206)= 同样的重取数:列表按平台过滤,候选/关键字跨平台无意义,一并清掉。 // 切平台 tab(V206)= 同样的重取数:列表按平台过滤,候选/关键字跨平台无意义,一并清掉;
// 建「公司超级管理员」的公司候选也按平台换一份(2026-11-17:京东 tab 下不能还选到亚马逊公司)。
watch(() => platformTab.active, () => { watch(() => platformTab.active, () => {
filters.createdByAdminId = null filters.createdByAdminId = null
filters.keyword = '' filters.keyword = ''
filters.page = 1 filters.page = 1
void loadUsers() void loadUsers()
loadCompanyOptions()
}) })
// 公司目录仅站点超管拉取(建「公司超级管理员」时选公司用);非超管不发这个请求,后端 403 兜底。
// 按当前平台 tab 过滤(V206)——公司本身已按平台分侧,候选下拉跟着 tab 走。
function loadCompanyOptions() {
if (!isSuperAdmin.value) return
void fetchCompanies(platformTab.active)
.then((items) => {
companyOptions.value = items.map((c) => ({ id: c.id, companyName: c.companyName }))
})
.catch(() => {
companyOptions.value = []
})
}
onMounted(() => { onMounted(() => {
void loadUsers() void loadUsers()
// 公司目录仅站点超管拉取(建「公司超级管理员」时选公司用);非超管不发这个请求,后端 403 兜底 loadCompanyOptions()
if (isSuperAdmin.value) {
void fetchCompanies()
.then((items) => {
companyOptions.value = items.map((c) => ({ id: c.id, companyName: c.companyName }))
})
.catch(() => {
companyOptions.value = []
})
}
}) })
</script> </script>
+28 -4
View File
@@ -2,6 +2,8 @@ import { defineStore } from 'pinia'
import { fetchCompanies } from '@/api/companies' import { fetchCompanies } from '@/api/companies'
import type { CompanyItem } from '@/api/companies-dto' import type { CompanyItem } from '@/api/companies-dto'
import { useAdminSessionStore } from '@/stores/admin-session' import { useAdminSessionStore } from '@/stores/admin-session'
import { usePlatformTabStore } from '@/stores/platform-tab'
import type { PlatformTabId } from '@/config/platform-scope'
import { firstSelectableCompanyId, companyIdForRequest } from '@/layout/company-tab-model' import { firstSelectableCompanyId, companyIdForRequest } from '@/layout/company-tab-model'
/** 公司 tab 的状态。成员 user ids **不在这里缓存**——每次请求交后端解析, /** 公司 tab 的状态。成员 user ids **不在这里缓存**——每次请求交后端解析,
@@ -12,6 +14,11 @@ export const useCompanyTabStore = defineStore('company-tab', {
activeId: null as number | null, activeId: null as number | null,
loading: false, loading: false,
loaded: false, loaded: false,
/** 当前这份目录是按哪个平台 tab 拉的(V206 平台分侧,2026-11-17 用户口径「公司 tab
* 条也按平台分侧,两边各看各的公司」)。空串=还没按平台拉过。早退闸拿它对撞当前
* tab:一致才免拉,平台切了就重拉一份;`fetchCompanies` 失败时不翻转它,旧清单
* (可能过时)继续顶着,下一次切台/重进页面会再试。 */
loadedPlatform: '' as PlatformTabId | '',
/** GET /companies 失败时的原因。**只住 store 与 console,不在模板里渲染**—— /** GET /companies 失败时的原因。**只住 store 与 console,不在模板里渲染**——
* §12 第 5 条没批任何新的用户可见提示,接口暴露禁令高于"失败可见"。 * §12 第 5 条没批任何新的用户可见提示,接口暴露禁令高于"失败可见"。
* 取不到目录时 loaded 保持 false ⇒ visibleForOperator 为 false ⇒ tab 条整体不画(fail-closed,观感与改前一致)。 */ * 取不到目录时 loaded 保持 false ⇒ visibleForOperator 为 false ⇒ tab 条整体不画(fail-closed,观感与改前一致)。 */
@@ -35,15 +42,27 @@ export const useCompanyTabStore = defineStore('company-tab', {
}, },
}, },
actions: { actions: {
async initialize() { /** 拉公司目录(按当前平台 tab 过滤,后端 GET /api/admin/companies?platform=…)。
* `force`=绕开「该平台已拉过」的早退闸(公司编辑弹窗翻档/启停后的 refresh 用),
* 旧清单保留到成功那刻再整份替换,取数期间 tab 条不闪空。 */
async initialize(options?: { force?: boolean }) {
const session = useAdminSessionStore() const session = useAdminSessionStore()
if (this.loaded || this.loading || !session.isSuperAdmin) return const platform = usePlatformTabStore().active
const alreadyLoadedForThisPlatform = this.loaded && this.loadedPlatform === platform
if ((!options?.force && alreadyLoadedForThisPlatform) || this.loading || !session.isSuperAdmin) return
this.loading = true this.loading = true
// 失败后 loaded 仍是 false ⇒ 下一次 watch 命中超管会重试;重试前先清掉旧原因,免得留着一条已经翻篇的错误。 // 失败后 loaded 仍是 false ⇒ 下一次 watch 命中超管会重试;重试前先清掉旧原因,免得留着一条已经翻篇的错误。
this.error = '' this.error = ''
try { try {
this.companies = await fetchCompanies() const companies = await fetchCompanies(platform)
this.activeId = firstSelectableCompanyId(this.companies) this.companies = companies
this.loadedPlatform = platform
// 换台重拉后旧选中未必还在新清单里(跨平台公司不重叠):还在就保住(别的页可能正按它取数),
// 不在就回落「id 最小的启用公司」。force 重拉同平台时,选中公司仍在 ⇒ 选中不跳。
const stillListed = this.activeId !== null && companies.some((c) => c.id === this.activeId)
if (!stillListed) {
this.activeId = firstSelectableCompanyId(companies)
}
this.loaded = true this.loaded = true
} catch (error) { } catch (error) {
// 2026-10-05 修复轮 1:改前只有 try/finally ⇒ GET /companies 抛错时零痕迹(loaded 永远 false、 // 2026-10-05 修复轮 1:改前只有 try/finally ⇒ GET /companies 抛错时零痕迹(loaded 永远 false、
@@ -57,6 +76,11 @@ export const useCompanyTabStore = defineStore('company-tab', {
this.loading = false this.loading = false
} }
}, },
/** 公司目录被编辑(公司管理翻档/启停/改名)后的强制重拉:不受 loadedPlatform 早退闸
* 限制。失败语义与 initialize 同口径(error + rethrow),调用方自行决定要不要提示。 */
async refresh() {
await this.initialize({ force: true })
},
setActiveId(id: number) { setActiveId(id: number) {
this.activeId = id this.activeId = id
}, },
@@ -0,0 +1,115 @@
/**
* 公司 tab 条 × 平台 tab(2026-11-17 用户口径「亚马逊侧别再挂京东-团队,京东侧同理」)的挂载契约:
* 目录请求必须带 platform=当前平台;切平台 tab 重拉一份;跨平台旧选中不在新清单里 ⇒ 回落「id 最小启用公司」;
* 同平台 force 重拉(公司编辑保存后的 refresh)不跳选中。京东侧只有一家公司时 tab 条整体不画
* (visibleForOperator 的 length > 1 既有语义),但 activeId 仍落在那一家 ⇒ 各页取数照样按它收窄。
* 不用 readFileSync(source-pin-ratchet 对台账外新文件带读点即红),全部走真实挂载断言。
*
* 跑法:`npx vitest run tests/mount/company-tabs-platform.mount.test.ts`
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount } from '@vue/test-utils'
import { createPinia, setActivePinia, type Pinia } from 'pinia'
import CompanyTabs from '@/layout/CompanyTabs.vue'
import { usePlatformTabStore } from '@/stores/platform-tab'
import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
const companiesApi = vi.hoisted(() => ({
fetchCompanies: vi.fn(),
}))
vi.mock('@/api/companies', () => companiesApi)
vi.mock('vue-router', () => ({
useRoute: () => ({ meta: { menuKey: 'admin_group_manage' } }),
}))
const AMAZON_COMPANIES = [
{ id: 1, companyName: '厦门米椿花', status: 1, platform: 'amazon' },
{ id: 2, companyName: '德阳-团队', status: 1, platform: 'amazon' },
{ id: 3, companyName: '先锋-团队', status: 1, platform: 'amazon' },
]
const JD_COMPANIES = [{ id: 4, companyName: '京东-团队', status: 1, platform: 'jd' }]
let pinia: Pinia
beforeEach(() => {
vi.clearAllMocks()
window.localStorage.removeItem('admin-platform-tab')
pinia = createPinia()
setActivePinia(pinia)
const session = useAdminSessionStore()
session.user = { id: 1, username: 'root', role: 'super_admin' }
companiesApi.fetchCompanies.mockImplementation(async (platform?: string) =>
platform === 'jd' ? JD_COMPANIES : AMAZON_COMPANIES)
})
function tabTexts(wrapper: ReturnType<typeof mount>) {
return wrapper.findAll('.company-tab').map((b) => b.text())
}
describe('CompanyTabs × 平台 tab', () => {
it('亚马逊 tab(默认):目录请求带 platform=amazon,只画亚马逊公司的 tab', async () => {
const wrapper = mount(CompanyTabs)
await flushPromises()
expect(companiesApi.fetchCompanies).toHaveBeenCalledWith('amazon')
expect(tabTexts(wrapper)).toEqual(['厦门米椿花', '德阳-团队', '先锋-团队'])
expect(useCompanyTabStore().activeId).toBe(1)
wrapper.unmount()
})
it('切到京东 tab:重拉 platform=jd;京东侧仅一家 ⇒ tab 条不画,但 activeId 落在京东-团队(各页取数按它收窄)', async () => {
const wrapper = mount(CompanyTabs)
await flushPromises()
usePlatformTabStore().setActive('jd')
await flushPromises()
expect(companiesApi.fetchCompanies).toHaveBeenLastCalledWith('jd')
expect(wrapper.find('.company-tabs').exists()).toBe(false)
const tabStore = useCompanyTabStore()
expect(tabStore.companies.map((c) => c.companyName)).toEqual(['京东-团队'])
expect(tabStore.activeId).toBe(4)
expect(tabStore.requestCompanyId).toBe(4)
wrapper.unmount()
})
it('切回亚马逊:再拉 platform=amazon,旧选中(京东-团队)不在清单 ⇒ 回落 id 最小的启用公司', async () => {
const wrapper = mount(CompanyTabs)
await flushPromises()
usePlatformTabStore().setActive('jd')
await flushPromises()
usePlatformTabStore().setActive('amazon')
await flushPromises()
expect(tabTexts(wrapper)).toEqual(['厦门米椿花', '德阳-团队', '先锋-团队'])
expect(useCompanyTabStore().activeId).toBe(1)
wrapper.unmount()
})
it('同平台 force 重拉(公司保存后的 refresh):选中公司仍在 ⇒ 选中不跳;请求带当前平台', async () => {
const wrapper = mount(CompanyTabs)
await flushPromises()
const tabStore = useCompanyTabStore()
tabStore.setActiveId(2)
await tabStore.refresh()
await flushPromises()
expect(companiesApi.fetchCompanies).toHaveBeenLastCalledWith('amazon')
expect(tabStore.activeId).toBe(2)
expect(tabStore.companies).toHaveLength(3)
wrapper.unmount()
})
it('非超管不发目录请求:切平台 tab 也不发', async () => {
const session = useAdminSessionStore()
session.user = { id: 5, username: '公司管理员', role: 'admin' }
const wrapper = mount(CompanyTabs)
await flushPromises()
usePlatformTabStore().setActive('jd')
await flushPromises()
expect(companiesApi.fetchCompanies).not.toHaveBeenCalled()
wrapper.unmount()
})
})
@@ -120,6 +120,9 @@ public class AdminJdProductController {
@RequestParam(name = "synced_from", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedFrom, @RequestParam(name = "synced_from", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedFrom,
@Parameter(description = "同步结束时间(包含,ISO datetime)") @Parameter(description = "同步结束时间(包含,ISO datetime)")
@RequestParam(name = "synced_to", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedTo, @RequestParam(name = "synced_to", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedTo,
@Parameter(description = "分类状态快筛(2026-11-17 用户口径「加个已分类和未分类的筛选」):"
+ "true=当前分组下有分类,false=未分类,缺省=全部;按 V203 归属表 SQL 侧下推")
@RequestParam(name = "classified", required = false) Boolean classified,
HttpServletRequest request) { HttpServletRequest request) {
RequestOperator operator = requireJdAccess(request); RequestOperator operator = requireJdAccess(request);
if (request.getParameter("grouped") != null || request.getParameter("ungrouped") != null) { if (request.getParameter("grouped") != null || request.getParameter("ungrouped") != null) {
@@ -131,7 +134,8 @@ public class AdminJdProductController {
requireVisibleCategory(scope, groupId); requireVisibleCategory(scope, groupId);
} }
return ApiResponse.success(jdProductQueryService.page(page, pageSize, return ApiResponse.success(jdProductQueryService.page(page, pageSize,
productCode, titleKeyword, category, groupId, syncedFrom, syncedTo, scopedOwnerGroupId)); productCode, titleKeyword, category, groupId, syncedFrom, syncedTo, classified,
scopedOwnerGroupId));
} }
@GetMapping("/categories") @GetMapping("/categories")
@@ -49,13 +49,18 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
* 「分类不要了,全部整合到类目里」撤掉(独立「分类」筛选框前端下线, * 「分类不要了,全部整合到类目里」撤掉(独立「分类」筛选框前端下线,
* {@code groupId} 改由类目面板「自定义分类」选中驱动)。 * {@code groupId} 改由类目面板「自定义分类」选中驱动)。
* 店铺名过滤参数已随 2026-11-15 客户口径「店铺不需要」同窗撤掉(DB 列与详情/回传链不动)。 * 店铺名过滤参数已随 2026-11-15 客户口径「店铺不需要」同窗撤掉(DB 列与详情/回传链不动)。
* {@code classified}+{@code ownerGroupId}(2026-11-17 用户口径「加个已分类和未分类的筛选」):
* 按 V203 归属表 EXISTS/NOT EXISTS 快筛分类状态,NULL=不过滤;与 11-16 撤掉的旧
* grouped/ungrouped(读已停用的 biz_jd_product.group_id 列)不是一回事。
*/ */
long countProducts(@Param("productCode") String productCode, long countProducts(@Param("productCode") String productCode,
@Param("titleKeyword") String titleKeyword, @Param("titleKeyword") String titleKeyword,
@Param("category") String category, @Param("category") String category,
@Param("groupId") Long groupId, @Param("groupId") Long groupId,
@Param("syncedFrom") LocalDateTime syncedFrom, @Param("syncedFrom") LocalDateTime syncedFrom,
@Param("syncedTo") LocalDateTime syncedTo); @Param("syncedTo") LocalDateTime syncedTo,
@Param("classified") Boolean classified,
@Param("ownerGroupId") Long ownerGroupId);
/** /**
* 商品上架配额计数({@code JdPublishQuotaService}):按 owner uid 集(管理员本人+ * 商品上架配额计数({@code JdPublishQuotaService}):按 owner uid 集(管理员本人+
@@ -95,6 +100,8 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
@Param("groupId") Long groupId, @Param("groupId") Long groupId,
@Param("syncedFrom") LocalDateTime syncedFrom, @Param("syncedFrom") LocalDateTime syncedFrom,
@Param("syncedTo") LocalDateTime syncedTo, @Param("syncedTo") LocalDateTime syncedTo,
@Param("classified") Boolean classified,
@Param("ownerGroupId") Long ownerGroupId,
@Param("offset") long offset, @Param("offset") long offset,
@Param("limit") int limit); @Param("limit") int limit);
@@ -8,6 +8,7 @@ import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity; import com.nanri.aiimage.common.model.entity.ShopManageGroupEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.security.DeviceSessionPolicy; import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import com.nanri.aiimage.common.service.AdminPlatformScope;
import com.nanri.aiimage.common.service.DataReadScope; import com.nanri.aiimage.common.service.DataReadScope;
import com.nanri.aiimage.modules.company.mapper.CompanyMapper; import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity; import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
@@ -27,11 +28,13 @@ import java.util.Set;
* 京东数据库分类的「当前分组」作用域解析(V203,2026-11-16 用户口径)。 * 京东数据库分类的「当前分组」作用域解析(V203,2026-11-16 用户口径)。
* *
* <p>口径:「组」=公司内的<b>数据权限分组</b>({@code biz_shop_manage_group}),公司→组两级隔离。 * <p>口径:「组」=公司内的<b>数据权限分组</b>({@code biz_shop_manage_group}),公司→组两级隔离。
* 四档:</p> * 2026-11-17 用户口径「同理京东那边也是」加一条平台闸:<b>只有京东档({@code platform='jd'},
* V206 列)的分组才进京东侧作用域</b>——亚马逊档与 NULL 一律不进下拉(四档角色先各自圈完
* 可见集,最后统一过这道闸)。四档:</p>
* <ul> * <ul>
* <li><b>平台超管</b>:全部公司全部组可读可写;</li> * <li><b>平台超管</b>:全部公司全部<b>京东档</b>组可读可写;</li>
* <li><b>公司超管</b>:本公司全部组可读可写(与「公司超管看本公司全部成员」同源);</li> * <li><b>公司超管</b>:本公司全部<b>京东档</b>组可读可写(与「公司超管看本公司全部成员」同源);</li>
* <li><b>管理员(组长)</b>:可见=自己带的组 + 自己所属组的组长;可写=自己带的组;</li> * <li><b>管理员(组长)</b>:可见=自己带的组 + 自己所属组的组长(过平台闸后);可写=自己带的组;</li>
* <li><b>普通号</b>:可见同上,可写空(能开弹窗看,不能增删改分类、不能归类)。</li> * <li><b>普通号</b>:可见同上,可写空(能开弹窗看,不能增删改分类、不能归类)。</li>
* </ul> * </ul>
* *
@@ -144,39 +147,49 @@ public class JdCategoryScopeService {
String role = adminAuthSupport.currentRole(user); String role = adminAuthSupport.currentRole(user);
Map<Long, ShopManageGroupEntity> visible = new LinkedHashMap<>(); Map<Long, ShopManageGroupEntity> visible = new LinkedHashMap<>();
Set<Long> writable = new LinkedHashSet<>(); Set<Long> writable = new LinkedHashSet<>();
if (dataReadScope.isPlatformSuperAdmin(user)) { boolean platformSuperAdmin = dataReadScope.isPlatformSuperAdmin(user);
if (platformSuperAdmin) {
collect(visible, shopManageGroupMapper.selectAllGroups()); collect(visible, shopManageGroupMapper.selectAllGroups());
writable.addAll(visible.keySet()); writable.addAll(visible.keySet());
return assemble(true, user.getCompanyId(), visible, writable); } else if (DeviceSessionPolicy.isCompanySuperAdmin(role)) {
}
if (DeviceSessionPolicy.isCompanySuperAdmin(role)) {
Long companyId = user.getCompanyId(); Long companyId = user.getCompanyId();
if (companyId != null && companyId > 0) { if (companyId != null && companyId > 0) {
collect(visible, companyGroups(companyId)); collect(visible, companyGroups(companyId));
writable.addAll(visible.keySet()); writable.addAll(visible.keySet());
} }
return assemble(false, companyId, visible, writable); } else {
} // 管理员(组长):自己带的组可写;自己所属组的组长带的分组只读可见。
// 管理员(组长):自己带的组可写;自己所属组的组长带的分组只读可见。 List<ShopManageGroupEntity> led = ledGroups(user.getId());
List<ShopManageGroupEntity> led = ledGroups(user.getId()); collect(visible, led);
collect(visible, led); if ("admin".equals(role)) {
if ("admin".equals(role)) { for (ShopManageGroupEntity group : led) {
for (ShopManageGroupEntity group : led) { if (group.getId() != null) {
if (group.getId() != null) { writable.add(group.getId());
writable.add(group.getId()); }
}
}
if (user.getCreatedById() != null && user.getCreatedById() > 0) {
collect(visible, ledGroups(user.getCreatedById()));
}
List<Long> memberOfLeaders = shopManageGroupMapper.selectLeaderIdsByMemberUserId(user.getId());
if (memberOfLeaders != null) {
for (Long leaderId : memberOfLeaders) {
collect(visible, ledGroups(leaderId));
} }
} }
} }
if (user.getCreatedById() != null && user.getCreatedById() > 0) { // 2026-11-17 用户口径「同理京东那边也是」:京东侧作用域只认京东档(platform='jd')的
collect(visible, ledGroups(user.getCreatedById())); // 数据权限分组——亚马逊档与 NULL 一律不进下拉。V206 存量默认 amazon、京东侧数据由编辑
} // 弹窗翻档,这里不做「NULL/缺列当 jd」的宽判:宽了会把没翻档的存量整批带进京东侧,
List<Long> memberOfLeaders = shopManageGroupMapper.selectLeaderIdsByMemberUserId(user.getId()); // 等于平台分侧白做。
if (memberOfLeaders != null) { retainJdPlatformGroups(visible, writable);
for (Long leaderId : memberOfLeaders) { return assemble(platformSuperAdmin, user.getCompanyId(), visible, writable);
collect(visible, ledGroups(leaderId)); }
}
} /** 只留京东档分组,并让可写集跟着可见集收缩(writable ⊆ visible 的既有不变量保持)。 */
return assemble(false, user.getCompanyId(), visible, writable); private static void retainJdPlatformGroups(Map<Long, ShopManageGroupEntity> visible, Set<Long> writable) {
visible.values().removeIf(group -> !AdminPlatformScope.JD.equals(group.getPlatform()));
writable.retainAll(visible.keySet());
} }
private List<ShopManageGroupEntity> companyGroups(Long companyId) { private List<ShopManageGroupEntity> companyGroups(Long companyId) {
@@ -79,14 +79,18 @@ public class JdProductQueryService {
* 分页查询商品行({@code synced_at} 倒序)。 * 分页查询商品行({@code synced_at} 倒序)。
* *
* <p>过滤面:商品编码 contains、标题关键词 contains、类目 eq、分组 eq(2026-11-16 起 * <p>过滤面:商品编码 contains、标题关键词 contains、类目 eq、分组 eq(2026-11-16 起
* 由类目面板「自定义分类」选中驱动)、同步起止(datetime 闭区间)。 * 由类目面板「自定义分类」选中驱动)、同步起止(datetime 闭区间)、分类状态档
* 未分类/已分类两档(ungrouped/grouped)与独立「分类」筛选框随同日口径 * {@code classified}(2026-11-17 用户口径「加个已分类和未分类的筛选」:true=当前分组下
* 「分类不要了,全部整合到类目里」整批撤掉。 * 有分类、false=没有、null=全部;按 V203 归属表 EXISTS/NOT EXISTS 在 SQL 侧下推,
* 判据与 {@link #fillGroupNames} 填分类列的条件同形——「筛选说未分类的行,列表分类列
* 也必须是未分类」)。
* 2026-11-16 撤掉的旧 ungrouped/grouped 两档读的是已停用的 biz_jd_product.group_id 列,
* 与本档不是一回事;独立「分类」筛选框的撤掉口径不变。
* 公司维过滤已随 2026-11-16 摘公司 tab 整批撤掉(全平台公共)。</p> * 公司维过滤已随 2026-11-16 摘公司 tab 整批撤掉(全平台公共)。</p>
*/ */
public JdProductPageVo page(Long page, Long pageSize, public JdProductPageVo page(Long page, Long pageSize,
String productCode, String titleKeyword, String category, Long groupId, String productCode, String titleKeyword, String category, Long groupId,
LocalDateTime syncedFrom, LocalDateTime syncedTo, Long ownerGroupId) { LocalDateTime syncedFrom, LocalDateTime syncedTo, Boolean classified, Long ownerGroupId) {
if (syncedFrom != null && syncedTo != null && syncedFrom.isAfter(syncedTo)) { if (syncedFrom != null && syncedTo != null && syncedFrom.isAfter(syncedTo)) {
throw new BusinessException("开始时间不能晚于结束时间"); throw new BusinessException("开始时间不能晚于结束时间");
} }
@@ -94,14 +98,14 @@ public class JdProductQueryService {
long safeSize = pageSize == null ? PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT long safeSize = pageSize == null ? PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT
: Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE); : Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE);
Filter filter = filter(productCode, titleKeyword, category, Filter filter = filter(productCode, titleKeyword, category,
groupId, syncedFrom, syncedTo); groupId, syncedFrom, syncedTo, classified);
long total = jdProductMapper.countProducts(filter.productCode(), long total = jdProductMapper.countProducts(filter.productCode(),
filter.titleKeyword(), filter.category(), filter.groupId(), filter.titleKeyword(), filter.category(), filter.groupId(),
filter.syncedFrom(), filter.syncedTo()); filter.syncedFrom(), filter.syncedTo(), filter.classified(), ownerGroupId);
List<JdProductEntity> rows = total <= 0 ? List.of() List<JdProductEntity> rows = total <= 0 ? List.of()
: jdProductMapper.selectProductPage(filter.productCode(), : jdProductMapper.selectProductPage(filter.productCode(),
filter.titleKeyword(), filter.category(), filter.groupId(), filter.titleKeyword(), filter.category(), filter.groupId(),
filter.syncedFrom(), filter.syncedTo(), filter.syncedFrom(), filter.syncedTo(), filter.classified(), ownerGroupId,
(safePage - 1) * safeSize, (int) safeSize); (safePage - 1) * safeSize, (int) safeSize);
List<JdProductListItemVo> items = rows.stream().map(this::toListItem).toList(); List<JdProductListItemVo> items = rows.stream().map(this::toListItem).toList();
fillGroupNames(items, ownerGroupId); fillGroupNames(items, ownerGroupId);
@@ -176,18 +180,19 @@ public class JdProductQueryService {
// ---------------------------------------------------------------- 过滤面 // ---------------------------------------------------------------- 过滤面
/** 服务侧过滤面归一:groupId ≤0 按没选处理,文本 trim 后空串归 null(无公司维,2026-11-16 摘)。 */ /** 服务侧过滤面归一:groupId ≤0 按没选处理,文本 trim 后空串归 null(无公司维,2026-11-16 摘);
* classified 原样直传(null=不过滤该面,2026-11-17 分类状态快筛)。 */
private record Filter(String productCode, String titleKeyword, private record Filter(String productCode, String titleKeyword,
String category, Long groupId, String category, Long groupId,
LocalDateTime syncedFrom, LocalDateTime syncedTo) { LocalDateTime syncedFrom, LocalDateTime syncedTo, Boolean classified) {
} }
private static Filter filter(String productCode, String titleKeyword, private static Filter filter(String productCode, String titleKeyword,
String category, Long groupId, String category, Long groupId,
LocalDateTime syncedFrom, LocalDateTime syncedTo) { LocalDateTime syncedFrom, LocalDateTime syncedTo, Boolean classified) {
Long safeGroupId = groupId != null && groupId > 0 ? groupId : null; Long safeGroupId = groupId != null && groupId > 0 ? groupId : null;
return new Filter(trimToNull(productCode), trimToNull(titleKeyword), return new Filter(trimToNull(productCode), trimToNull(titleKeyword),
trimToNull(category), safeGroupId, syncedFrom, syncedTo); trimToNull(category), safeGroupId, syncedFrom, syncedTo, classified);
} }
// ---------------------------------------------------------------- 列表/详情搬运 // ---------------------------------------------------------------- 列表/详情搬运
@@ -122,6 +122,29 @@
WHERE a.product_id = p.id AND a.category_id = #{groupId} WHERE a.product_id = p.id AND a.category_id = #{groupId}
) )
</if> </if>
<!-- 分类状态快筛(2026-11-17 用户口径「加个已分类和未分类的筛选」):已分类=在
「当前数据权限分组」(owner_group_id)下有 category_id 非空的归属行——与读侧
fillGroupNames 把分类列填出来的条件同形;未分类=NOT EXISTS。谓词 SQL 侧下推
(铁律 20 同形,不得 Java 侧对已取页 filter)。owner_group_id 为 NULL(作用域
无可分组)时 EXISTS 恒假、NOT EXISTS 恒真——与列表「分类列全空」口径天然一致,
不需要服务侧特判。与 2026-11-16 撤掉的旧 grouped/ungrouped 不是一回事:那两档
读的是已停用的 biz_jd_product.group_id 列,本档读 V203 归属表。 -->
<if test="classified != null">
<choose>
<when test="classified == true">
AND EXISTS (
SELECT 1 FROM biz_jd_product_group_assign cs
WHERE cs.product_id = p.id AND cs.owner_group_id = #{ownerGroupId} AND cs.category_id IS NOT NULL
)
</when>
<otherwise>
AND NOT EXISTS (
SELECT 1 FROM biz_jd_product_group_assign cs
WHERE cs.product_id = p.id AND cs.owner_group_id = #{ownerGroupId} AND cs.category_id IS NOT NULL
)
</otherwise>
</choose>
</if>
<if test="syncedFrom != null">AND p.synced_at &gt;= #{syncedFrom}</if> <if test="syncedFrom != null">AND p.synced_at &gt;= #{syncedFrom}</if>
<if test="syncedTo != null">AND p.synced_at &lt;= #{syncedTo}</if> <if test="syncedTo != null">AND p.synced_at &lt;= #{syncedTo}</if>
</sql> </sql>
@@ -36,7 +36,7 @@ class CompanyVoTest {
}); });
assertThat(json.keySet()).containsExactlyInAnyOrder( assertThat(json.keySet()).containsExactlyInAnyOrder(
"id", "company_name", "status", "remark", "created_at", "updated_at"); "id", "company_name", "status", "remark", "platform", "created_at", "updated_at");
assertThat(json.get("company_name")).isEqualTo("福州数富"); assertThat(json.get("company_name")).isEqualTo("福州数富");
assertThat(json.get("created_at")).isEqualTo("2026-10-04 14:05"); assertThat(json.get("created_at")).isEqualTo("2026-10-04 14:05");
// 库里没读到的时间给空串:前端 formatDateTime 才有占位,不会渲染出 undefined // 库里没读到的时间给空串:前端 formatDateTime 才有占位,不会渲染出 undefined
@@ -164,6 +164,10 @@ class AdminJdProductControllerTest {
} }
assertFalse(source.contains("@RequestParam(name = \"ungrouped\"")); assertFalse(source.contains("@RequestParam(name = \"ungrouped\""));
assertFalse(source.contains("@RequestParam(name = \"grouped\"")); assertFalse(source.contains("@RequestParam(name = \"grouped\""));
// 2026-11-17 分类状态快筛:新参数名 classified(不复用旧 grouped/ungrouped 两档——
// 那两档读已停用的 biz_jd_product.group_id 列,语义不同,旧参数仍必须被拒收)。
assertTrue(source.contains("@RequestParam(name = \"classified\""),
"分类状态快筛参数 classified 必须在册(2026-11-17 用户口径)");
// company_id 参数已随 2026-11-16「删除掉公司 tab」整批摘除(读侧零公司维度支另有反向钉)。 // company_id 参数已随 2026-11-16「删除掉公司 tab」整批摘除(读侧零公司维度支另有反向钉)。
assertFalse(source.contains("company_id"), "company_id 请求参数必须已删除,不得回潜"); assertFalse(source.contains("company_id"), "company_id 请求参数必须已删除,不得回潜");
// 商品状态筛选框已随 2026-11-15 客户口径从前端下线 ⇒ 服务端同名参数一起撤(反向钉住防回潜)。 // 商品状态筛选框已随 2026-11-15 客户口径从前端下线 ⇒ 服务端同名参数一起撤(反向钉住防回潜)。
@@ -279,8 +283,8 @@ class AdminJdProductControllerTest {
// 读:菜单权限命中即放行(公共库一人一份全量)。 // 读:菜单权限命中即放行(公共库一人一份全量)。
JdProductPageVo pageVo = new JdProductPageVo(); JdProductPageVo pageVo = new JdProductPageVo();
pageVo.setItems(List.of()); pageVo.setItems(List.of());
when(queryService.page(1L, 20L, null, null, null, null, null, null, GROUP_ID)).thenReturn(pageVo); when(queryService.page(1L, 20L, null, null, null, null, null, null, null, GROUP_ID)).thenReturn(pageVo);
assertEquals(Boolean.TRUE, controller.page(1L, 20L, null, null, null, null, null, null, null, request) assertEquals(Boolean.TRUE, controller.page(1L, 20L, null, null, null, null, null, null, null, null, request)
.isSuccess(), "非超管有菜单权限时读必须放行(读写分档只收窄写)"); .isSuccess(), "非超管有菜单权限时读必须放行(读写分档只收窄写)");
// 商品行写:四条写入口一律 403,且业务服务一次都没被调到(不能「先写再拒」)。 // 商品行写:四条写入口一律 403,且业务服务一次都没被调到(不能「先写再拒」)。
@@ -429,11 +433,11 @@ class AdminJdProductControllerTest {
when(groupService.requireCategory(8L)).thenReturn(category(8L, 20L)); when(groupService.requireCategory(8L)).thenReturn(category(8L, 20L));
BusinessException ex = assertThrows(BusinessException.class, BusinessException ex = assertThrows(BusinessException.class,
() -> controller.page(1L, 20L, null, null, null, 8L, null, null, null, request)); () -> controller.page(1L, 20L, null, null, null, 8L, null, null, null, null, request));
assertTrue(ex.getMessage().contains("无权查看该分组的分类"), assertTrue(ex.getMessage().contains("无权查看该分组的分类"),
"跨组分类筛选必须 403 点名分组,不做空结果降级"); "跨组分类筛选必须 403 点名分组,不做空结果降级");
verify(queryService, never()).page(any(), any(), any(), any(), any(), any(), any(), any(), any()); verify(queryService, never()).page(any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
} }
// ===================== 行为样本 ===================== // ===================== 行为样本 =====================
@@ -461,13 +465,13 @@ class AdminJdProductControllerTest {
pageVo.setTotal(0L); pageVo.setTotal(0L);
pageVo.setPage(1L); pageVo.setPage(1L);
pageVo.setPageSize((long) PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT); pageVo.setPageSize((long) PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT);
when(queryService.page(1L, 20L, null, null, null, null, null, null, GROUP_ID)).thenReturn(pageVo); when(queryService.page(1L, 20L, null, null, null, null, null, null, null, GROUP_ID)).thenReturn(pageVo);
// 请求面没有 company_id:任何授权身份看到的都是同一份全量;分类列按 owner_group_id 取。 // 请求面没有 company_id:任何授权身份看到的都是同一份全量;分类列按 owner_group_id 取。
ApiResponse<JdProductPageVo> response = controller.page(1L, 20L, null, null, null, null, ApiResponse<JdProductPageVo> response = controller.page(1L, 20L, null, null, null, null,
GROUP_ID, null, null, request); GROUP_ID, null, null, null, request);
verify(queryService).page(1L, 20L, null, null, null, null, null, null, GROUP_ID); verify(queryService).page(1L, 20L, null, null, null, null, null, null, null, GROUP_ID);
assertEquals(Boolean.TRUE, response.isSuccess(), "拒绝走 403 业务码,放行必须是 success 信封(B80-03)"); assertEquals(Boolean.TRUE, response.isSuccess(), "拒绝走 403 业务码,放行必须是 success 信封(B80-03)");
assertEquals(pageVo, response.getData()); assertEquals(pageVo, response.getData());
} }
@@ -491,12 +495,12 @@ class AdminJdProductControllerTest {
for (String value : List.of("true", "false", "")) { for (String value : List.of("true", "false", "")) {
when(request.getParameter(name)).thenReturn(value); when(request.getParameter(name)).thenReturn(value);
BusinessException ex = assertThrows(BusinessException.class, BusinessException ex = assertThrows(BusinessException.class,
() -> controller.page(1L, 20L, null, null, null, 7L, null, null, null, request)); () -> controller.page(1L, 20L, null, null, null, 7L, null, null, null, null, request));
assertTrue(ex.getMessage().contains("刷新页面")); assertTrue(ex.getMessage().contains("刷新页面"));
when(request.getParameter(name)).thenReturn(null); when(request.getParameter(name)).thenReturn(null);
} }
} }
verify(queryService, never()).page(any(), any(), any(), any(), any(), any(), any(), any(), any()); verify(queryService, never()).page(any(), any(), any(), any(), any(), any(), any(), any(), any(), any());
} }
@Test @Test
@@ -615,23 +619,23 @@ class AdminJdProductControllerTest {
void 查询服务分页钳制防溢出() { void 查询服务分页钳制防溢出() {
JdProductMapper mapper = mock(JdProductMapper.class); JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = queryService(mapper); JdProductQueryService service = queryService(mapper);
when(mapper.countProducts(any(), any(), any(), any(), any(), any())).thenReturn(1L); when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(1L);
// page=0 / size=null ⇒ 归一为第 1 页、默认 20 条;offset = 0。 // page=0 / size=null ⇒ 归一为第 1 页、默认 20 条;offset = 0。
service.page(0L, null, null, null, null, null, null, null, null); service.page(0L, null, null, null, null, null, null, null, null, null);
ArgumentCaptor<Long> offset = ArgumentCaptor.forClass(Long.class); ArgumentCaptor<Long> offset = ArgumentCaptor.forClass(Long.class);
ArgumentCaptor<Integer> limit = ArgumentCaptor.forClass(Integer.class); ArgumentCaptor<Integer> limit = ArgumentCaptor.forClass(Integer.class);
verify(mapper).selectProductPage(isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), verify(mapper).selectProductPage(isNull(), isNull(), isNull(), isNull(), isNull(), isNull(),
offset.capture(), limit.capture()); isNull(), isNull(), offset.capture(), limit.capture());
assertEquals(0L, offset.getValue()); assertEquals(0L, offset.getValue());
assertEquals(PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT, limit.getValue()); assertEquals(PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT, limit.getValue());
// page=Long.MAX_VALUE / size=500 ⇒ 钳到 10_000 页、100 条;乘积 999_900 不得变负(铁律 15)。 // page=Long.MAX_VALUE / size=500 ⇒ 钳到 10_000 页、100 条;乘积 999_900 不得变负(铁律 15)。
service.page(Long.MAX_VALUE, 500L, null, null, null, null, null, null, null); service.page(Long.MAX_VALUE, 500L, null, null, null, null, null, null, null, null);
ArgumentCaptor<Long> offsetMax = ArgumentCaptor.forClass(Long.class); ArgumentCaptor<Long> offsetMax = ArgumentCaptor.forClass(Long.class);
ArgumentCaptor<Integer> limitMax = ArgumentCaptor.forClass(Integer.class); ArgumentCaptor<Integer> limitMax = ArgumentCaptor.forClass(Integer.class);
verify(mapper, times(2)).selectProductPage(any(), any(), any(), any(), any(), any(), verify(mapper, times(2)).selectProductPage(any(), any(), any(), any(), any(), any(),
offsetMax.capture(), limitMax.capture()); any(), any(), offsetMax.capture(), limitMax.capture());
assertEquals(999_900L, offsetMax.getValue(), "(page-1)*page_size 最大 999_900,钳制后不得溢出变负"); assertEquals(999_900L, offsetMax.getValue(), "(page-1)*page_size 最大 999_900,钳制后不得溢出变负");
assertEquals(100, limitMax.getValue()); assertEquals(100, limitMax.getValue());
} }
@@ -643,23 +647,77 @@ class AdminJdProductControllerTest {
LocalDateTime from = LocalDateTime.of(2026, 11, 14, 12, 0); LocalDateTime from = LocalDateTime.of(2026, 11, 14, 12, 0);
LocalDateTime to = LocalDateTime.of(2026, 11, 14, 8, 0); LocalDateTime to = LocalDateTime.of(2026, 11, 14, 8, 0);
BusinessException ex = assertThrows(BusinessException.class, BusinessException ex = assertThrows(BusinessException.class,
() -> service.page(1L, 20L, null, null, null, null, from, to, null)); () -> service.page(1L, 20L, null, null, null, null, from, to, null, null));
assertTrue(ex.getMessage().contains("开始时间不能晚于结束时间"), "倒挂时间按业务异常拒绝"); assertTrue(ex.getMessage().contains("开始时间不能晚于结束时间"), "倒挂时间按业务异常拒绝");
verify(mapper, never()).countProducts(any(), any(), any(), any(), any(), any()); verify(mapper, never()).countProducts(any(), any(), any(), any(), any(), any(), any(), any());
} }
@Test @Test
void 查询服务过滤面原样直传且空串归null() { void 查询服务过滤面原样直传且空串归null() {
JdProductMapper mapper = mock(JdProductMapper.class); JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = queryService(mapper); JdProductQueryService service = queryService(mapper);
when(mapper.countProducts(any(), any(), any(), any(), any(), any())).thenReturn(1L); when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(1L);
service.page(1L, 20L, " SKU-1 ", " 连衣裙 ", " 艺考形体服 ", 7L, null, null, null); service.page(1L, 20L, " SKU-1 ", " 连衣裙 ", " 艺考形体服 ", 7L, null, null, null, null);
verify(mapper).countProducts("SKU-1", "连衣裙", "艺考形体服", 7L, null, null); verify(mapper).countProducts("SKU-1", "连衣裙", "艺考形体服", 7L, null, null, null, null);
verify(mapper).selectProductPage("SKU-1", "连衣裙", "艺考形体服", 7L, null, null, 0L, 20); verify(mapper).selectProductPage("SKU-1", "连衣裙", "艺考形体服", 7L, null, null, null, null, 0L, 20);
service.page(1L, 20L, " ", null, null, 0L, null, null, null); service.page(1L, 20L, " ", null, null, 0L, null, null, null, null);
verify(mapper).countProducts(null, null, null, null, null, null); verify(mapper).countProducts(null, null, null, null, null, null, null, null);
verify(mapper).selectProductPage(null, null, null, null, null, null, 0L, 20); verify(mapper).selectProductPage(null, null, null, null, null, null, null, null, 0L, 20);
}
/**
* 分类状态快筛(2026-11-17 用户口径「加个已分类和未分类的筛选」):
* ① classified+ownerGroupId 必须原样下传给 mapper(谓词在 XML 的 EXISTS/NOT EXISTS 段,
* 铁律 20 同形——不得 Java 侧对已取页 filter);
* ② XML 绊线:两分支谓词逐字在册(改回 Java filter 或摘掉 owner_group_id 关联即红);
* ③ 控制器把请求的 classified 直传服务(不吞、不改写)。
*/
@Test
void 分类状态快筛必须SQL下推且classified与ownerGroupId成对直传() throws IOException {
// ② XML 绊线:classified 档的 EXISTS/NOT EXISTS 两分支都在 productConds 里,
// 且按「当前分组」owner_group_id+category_id 非空判——与读侧填分类列同形。
Path xml = findJdProductMapperXml();
String xmlText = stripComments(Files.readString(xml)).replaceAll("(?s)<!--.*?-->", "");
assertTrue(xmlText.contains("classified == true"),
"XML 必须有 classified==true 的已分类分支(SQL 侧下推,铁律 20 同形)");
assertTrue(xmlText.contains("cs.owner_group_id = #{ownerGroupId}")
&& xmlText.contains("cs.category_id IS NOT NULL"),
"已分类判据必须按当前分组归属行且 category_id 非空(与 fillGroupNames 同形)");
assertTrue(xmlText.contains("NOT EXISTS"), "未分类档必须是 NOT EXISTS(不是空结果降级)");
assertEquals(2, count(xmlText, "cs.product_id = p.id"),
"EXISTS/NOT EXISTS 两分支各一处商品关联,缺一个即红");
// ① 服务直传:classified 与 ownerGroupId 成对进 mapper(计数与分页同一过滤面)。
JdProductMapper mapper = mock(JdProductMapper.class);
JdProductQueryService service = queryService(mapper);
when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(1L);
service.page(1L, 20L, null, null, null, null, null, null, Boolean.TRUE, GROUP_ID);
verify(mapper).countProducts(null, null, null, null, null, null, true, GROUP_ID);
verify(mapper).selectProductPage(null, null, null, null, null, null, true, GROUP_ID, 0L, 20);
service.page(1L, 20L, null, null, null, null, null, null, Boolean.FALSE, GROUP_ID);
verify(mapper).countProducts(null, null, null, null, null, null, false, GROUP_ID);
verify(mapper).selectProductPage(null, null, null, null, null, null, false, GROUP_ID, 0L, 20);
// ③ 控制器直传:classified 原样进服务(owner_group_id 仍按作用域收敛后的值)。
JdProductQueryService queryService = mock(JdProductQueryService.class);
JdCategoryScopeService scopeService = mock(JdCategoryScopeService.class);
AdminAuthSupport authSupport = mock(AdminAuthSupport.class);
AdminJdProductController controller = new AdminJdProductController(
queryService, mock(JdProductDeleteService.class), mock(JdProductUpdateService.class),
mock(JdProductGroupService.class), scopeService, authSupport,
mock(PermissionMenuService.class));
AdminUserEntity operator = new AdminUserEntity();
operator.setId(7L);
HttpServletRequest request = mock(HttpServletRequest.class);
when(authSupport.requireUser(request)).thenReturn(operator);
when(authSupport.currentRole(operator)).thenReturn("super_admin");
JdCategoryScopeService.JdCategoryScope scope = writableScope(GROUP_ID, COMPANY_ID);
when(scopeService.resolve(operator)).thenReturn(scope);
when(scopeService.readGroupOrNull(scope, null)).thenReturn(GROUP_ID);
controller.page(1L, 20L, null, null, null, null, null, null, null, Boolean.TRUE, request);
verify(queryService).page(1L, 20L, null, null, null, null, null, null, Boolean.TRUE, GROUP_ID);
} }
@Test @Test
@@ -807,8 +865,8 @@ class AdminJdProductControllerTest {
JdProductEntity categorized = productEntity(1L); JdProductEntity categorized = productEntity(1L);
JdProductEntity missing = productEntity(2L); JdProductEntity missing = productEntity(2L);
when(mapper.countProducts(any(), any(), any(), any(), any(), any())).thenReturn(2L); when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(2L);
when(mapper.selectProductPage(any(), any(), any(), any(), any(), any(), when(mapper.selectProductPage(any(), any(), any(), any(), any(), any(), any(), any(),
anyLong(), anyInt())).thenReturn(List.of(categorized, missing)); anyLong(), anyInt())).thenReturn(List.of(categorized, missing));
when(assignMapper.selectList(any())).thenReturn(List.of( when(assignMapper.selectList(any())).thenReturn(List.of(
assign(1L, GROUP_ID, 3L), assign(2L, GROUP_ID, 99L))); assign(1L, GROUP_ID, 3L), assign(2L, GROUP_ID, 99L)));
@@ -817,7 +875,7 @@ class AdminJdProductControllerTest {
category.setName("秋冬款"); category.setName("秋冬款");
when(categoryMapper.selectBatchIds(any())).thenReturn(List.of(category)); when(categoryMapper.selectBatchIds(any())).thenReturn(List.of(category));
JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null, GROUP_ID); JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null, null, GROUP_ID);
assertEquals(3L, vo.getItems().get(0).getGroupId(), "分类 id 取本组归属行"); assertEquals(3L, vo.getItems().get(0).getGroupId(), "分类 id 取本组归属行");
assertEquals("秋冬款", vo.getItems().get(0).getGroupName(), "行集归属一次取齐分类名(无逐行查询)"); assertEquals("秋冬款", vo.getItems().get(0).getGroupName(), "行集归属一次取齐分类名(无逐行查询)");
@@ -832,11 +890,11 @@ class AdminJdProductControllerTest {
JdProductGroupAssignMapper assignMapper = mock(JdProductGroupAssignMapper.class); JdProductGroupAssignMapper assignMapper = mock(JdProductGroupAssignMapper.class);
JdProductQueryService service = queryService(mapper, mock(JdProductImageMapper.class), JdProductQueryService service = queryService(mapper, mock(JdProductImageMapper.class),
mock(JdProductSkuMapper.class), mock(JdProductGroupMapper.class), assignMapper); mock(JdProductSkuMapper.class), mock(JdProductGroupMapper.class), assignMapper);
when(mapper.countProducts(any(), any(), any(), any(), any(), any())).thenReturn(1L); when(mapper.countProducts(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(1L);
when(mapper.selectProductPage(any(), any(), any(), any(), any(), any(), when(mapper.selectProductPage(any(), any(), any(), any(), any(), any(), any(), any(),
anyLong(), anyInt())).thenReturn(List.of(productEntity(1L))); anyLong(), anyInt())).thenReturn(List.of(productEntity(1L)));
JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null, null); JdProductPageVo vo = service.page(1L, 20L, null, null, null, null, null, null, null, null);
assertNull(vo.getItems().get(0).getGroupId(), "不属于任何分组的账号:分类列一律空(未分类)"); assertNull(vo.getItems().get(0).getGroupId(), "不属于任何分组的账号:分类列一律空(未分类)");
assertNull(vo.getItems().get(0).getGroupName()); assertNull(vo.getItems().get(0).getGroupName());
@@ -30,7 +30,8 @@ import static org.mockito.Mockito.when;
/** /**
* 京东数据库分类「当前分组」作用域判据(V203;2026-11-16 用户口径)。 * 京东数据库分类「当前分组」作用域判据(V203;2026-11-16 用户口径)。
* *
* <p>四档矩阵:平台超管=全部公司全部组可读可写;公司超管=本公司全部组; * <p>四档矩阵(2026-11-17 起各档可见集最后统一过「只留京东档 platform='jd' 分组」的平台闸):
* 平台超管=全部公司全部组可读可写;公司超管=本公司全部组;
* 管理员(组长)=自己带的组可写、自己所属组的组长带的分组只读; * 管理员(组长)=自己带的组可写、自己所属组的组长带的分组只读;
* 普通号=与管理员同可见、<b>零可写</b>(能开弹窗看,不能增删改分类、不能归类)。 * 普通号=与管理员同可见、<b>零可写</b>(能开弹窗看,不能增删改分类、不能归类)。
* 另钉三条收敛语义:不可见组读 403(不做空结果降级)、无分组上下文读回 null(页面照常可用)、 * 另钉三条收敛语义:不可见组读 403(不做空结果降级)、无分组上下文读回 null(页面照常可用)、
@@ -86,6 +87,70 @@ class JdCategoryScopeServiceTest {
assertThat(scope.canWrite(20L)).isTrue(); assertThat(scope.canWrite(20L)).isTrue();
} }
/**
* 2026-11-17 用户口径「同理京东那边也是」:京东侧下拉只认京东档(platform='jd')分组。
* 亚马逊档与 NULL 档(未翻档的存量)一律滤掉,可写集跟着收缩;过滤后只剩一家公司 ⇒
* 组名不带公司前缀(既有「单公司不啰嗦」口径不变)。
*/
@Test
void 平台超管_只显示京东档分组_亚马逊档与NULL档不进下拉() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
when(adminAuthSupport.currentRole(operator)).thenReturn("super_admin");
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(true);
when(shopManageGroupMapper.selectAllGroups()).thenReturn(List.of(
group(10L, 1L, "A组"),
amazonGroup(20L, 2L, "B组"),
groupOfPlatform(30L, 3L, "C组", null)));
CompanyEntity first = new CompanyEntity();
first.setId(1L);
first.setCompanyName("甲公司");
when(companyMapper.selectBatchIds(any())).thenReturn(List.of(first));
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
assertThat(scope.visibleGroupIds()).containsExactly(10L);
assertThat(scope.writableGroupIds()).containsExactly(10L);
assertThat(scope.defaultGroupId()).isEqualTo(10L);
assertThat(scope.groups()).extracting(JdCategoryGroupOptionVo::getLabel)
.containsExactly("A组");
// 亚马逊档组读/写双拒(不是 403,是压根不可见)。
assertThat(scope.canRead(20L)).isFalse();
assertThat(scope.canWrite(20L)).isFalse();
}
@Test
void 公司超管_本公司亚马逊档组同样被滤掉() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
when(adminAuthSupport.currentRole(operator)).thenReturn("company_super_admin");
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
when(shopManageGroupMapper.selectList(any())).thenReturn(List.of(
group(10L, COMPANY_ID, "A组"), amazonGroup(11L, COMPANY_ID, "B组")));
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
assertThat(scope.visibleGroupIds()).containsExactly(10L);
assertThat(scope.writableGroupIds()).containsExactly(10L);
assertThat(scope.groups()).extracting(JdCategoryGroupOptionVo::getLabel)
.containsExactly("A组");
verify(companyMapper, never()).selectBatchIds(any());
}
@Test
void 组长_带的组全是亚马逊档时空作用域不报错() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
when(adminAuthSupport.currentRole(operator)).thenReturn("admin");
when(dataReadScope.isPlatformSuperAdmin(operator)).thenReturn(false);
when(shopManageGroupMapper.selectLedGroups(USER_ID))
.thenReturn(List.of(amazonGroup(10L, COMPANY_ID, "自己的组")));
when(shopManageGroupMapper.selectLeaderIdsByMemberUserId(USER_ID)).thenReturn(List.of());
JdCategoryScopeService.JdCategoryScope scope = service.resolve(operator);
assertThat(scope.visibleGroupIds()).isEmpty();
assertThat(scope.writableGroupIds()).isEmpty();
assertThat(scope.defaultGroupId()).isNull();
}
@Test @Test
void 公司超管_本公司全部组可读可写() { void 公司超管_本公司全部组可读可写() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID); AdminUserEntity operator = user(USER_ID, COMPANY_ID);
@@ -319,10 +384,20 @@ class JdCategoryScopeServiceTest {
} }
private static ShopManageGroupEntity group(long id, long companyId, String name) { private static ShopManageGroupEntity group(long id, long companyId, String name) {
return groupOfPlatform(id, companyId, name, "jd");
}
/** 亚马逊档组(V206 存量默认档):2026-11-17 起不进京东侧作用域。 */
private static ShopManageGroupEntity amazonGroup(long id, long companyId, String name) {
return groupOfPlatform(id, companyId, name, "amazon");
}
private static ShopManageGroupEntity groupOfPlatform(long id, long companyId, String name, String platform) {
ShopManageGroupEntity group = new ShopManageGroupEntity(); ShopManageGroupEntity group = new ShopManageGroupEntity();
group.setId(id); group.setId(id);
group.setCompanyId(companyId); group.setCompanyId(companyId);
group.setGroupName(name); group.setGroupName(name);
group.setPlatform(platform);
return group; return group;
} }
@@ -331,6 +406,7 @@ class JdCategoryScopeServiceTest {
ShopManageGroupEntity group = new ShopManageGroupEntity(); ShopManageGroupEntity group = new ShopManageGroupEntity();
group.setId(id); group.setId(id);
group.setGroupName(name); group.setGroupName(name);
group.setPlatform("jd");
return group; return group;
} }