4 Commits

26 changed files with 1404 additions and 800 deletions
@@ -16,13 +16,12 @@ export const PLATFORM_TABS: readonly PlatformTabDef[] = [
]
/** 京东侧独占菜单的 menuKey 唯一清单(与 routes.ts 的 menuKey 逐字一致,用例钉住)。
* 2026-11-17 加京东分类管理(用户口径「这边分组是京东的分组管理的而不是亚马逊的」——
* 分类管理子菜单归京东侧,不与亚马逊侧混排)。
* 2026-11-17 晚:分类管理子菜单(admin_jd_category_manage,V204)随「京东分类管理并到
* 京东数据库分类编辑里」用户口径整体下线(页/路由/菜单行 V208 删),key 从清单摘除。
* 后续京东新页面上线把 key 加进这里即可,清单外的 key(含店铺管理/生成记录等
* 存量页)一律归亚马逊或双侧清单。 */
export const JD_MENU_KEYS: readonly string[] = [
'admin_jd_database',
'admin_jd_category_manage',
]
/** 双侧共用菜单(2026-11-17 用户口径「这些亚马逊这边也要有」):三个账号域页面在两个
+16 -2
View File
@@ -7,17 +7,18 @@ import { useRoute } from 'vue-router'
import { COMPANY_STATUS_ACTIVE } from '@/api/companies-dto'
import { useCompanyTabStore } from '@/stores/company-tab'
import { useAdminSessionStore } from '@/stores/admin-session'
import { usePlatformTabStore } from '@/stores/platform-tab'
import { companyTabAppliesTo, companyTabInitFailureMessage } from '@/layout/company-tab-model'
import { showAdminFeedback } from '@/components/admin-feedback-ui'
const route = useRoute()
const tab = useCompanyTabStore()
const session = useAdminSessionStore()
const platformTab = usePlatformTabStore()
const tabs = computed(() => tab.companies.filter((c) => c.status === COMPANY_STATUS_ACTIVE))
const show = computed(() => tab.visibleForOperator && companyTabAppliesTo(route.meta.menuKey))
watch(() => session.isSuperAdmin, (v) => {
if (!v) return
function ensureLoaded() {
// 2026-10-05 修复轮 1:改前这里是 `void tab.initialize()`,store 里也只有 try/finally ⇒
// GET /companies 抛错时异常变成 unhandled rejection(全仓 src 无 errorHandler/unhandledrejection 兜底),
// 现场只剩"tab 条没画出来",Task 13 人工清单第一项无从判断是权限问题还是接口挂了。
@@ -29,7 +30,20 @@ watch(() => session.isSuperAdmin, (v) => {
console.warn('[company-tab] 公司目录没取到,tab 条不渲染', error)
showAdminFeedback(companyTabInitFailureMessage(error), 'warning')
})
}
watch(() => session.isSuperAdmin, (v) => {
if (!v) return
ensureLoaded()
}, { immediate: true })
// 平台 tab 切换=公司目录换一份(V206 平台分侧;2026-11-17 用户口径「亚马逊侧别再挂京东-团队,
// 京东侧同理」):store 按 loadedPlatform 对撞早退,切了台必然重拉。非超管目录恒空不发请求,
// 这里同样按超管闸早退。
watch(() => platformTab.active, () => {
if (!session.isSuperAdmin) return
ensureLoaded()
})
</script>
<template>
@@ -122,12 +122,10 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
steps: ['筛选记录', '核对结论明细', '到任务中心下载原表'],
},
admin_jd_database: {
text: '本页只读:客户端采集的京东店铺商品自动同步到这里(同店铺同商品只保留最新一次),按分公司隔离分页展示;点行查看全部属性与图片,可用自定义分组归档商品。',
steps: ['筛选商品记录', '查看属性与图片明细', '按分组归档管理'],
},
admin_jd_category_manage: {
text: '本页维护京东自定义分类:分类按数据权限分组隔离,当前组只组长/超管可新建、改名、删除(删除不删商品,只解挂归属);给商品归类请到「京东数据库」页勾选后「批量编辑分类」。',
steps: ['切换分组', '新建或改名分类', '到京东数据库页归类商品'],
// 2026-11-17 分类管理子菜单并入本页(用户口径「京东分类管理并到京东数据库分类编辑里」,
// 原 admin_jd_category_manage 条目随之摘除):分类建/改名/删在工具栏「分类管理」。
text: '本页只读:客户端采集的京东店铺商品自动同步到这里(同店铺同商品只保留最新一次),按分公司隔离分页展示;点行查看全部属性与图片;分类的新建/改名/删除在工具栏「分类管理」,给商品归类先勾选再「批量编辑分类」。',
steps: ['筛选商品记录', '查看属性与图片明细', '用「分类管理」维护分类并批量归类'],
},
}
@@ -8,6 +8,7 @@ import { formatDateTime } from '@/utils/datetime'
import { fetchCompanies } from '@/api/companies'
import { COMPANY_STATUS_ACTIVE, type CompanyItem } from '@/api/companies-dto'
import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
import { usePlatformTabStore } from '@/stores/platform-tab'
import OldPagination from '@/components/OldPagination.vue'
import CompanyEditorDialog from './CompanyEditorDialog.vue'
@@ -17,6 +18,9 @@ import LoadFailureBar from '@/components/LoadFailureBar.vue'
const session = useAdminSessionStore()
// 平台 tab(V206):公司列表按当前平台过滤,新建默认落当前平台。
const platformTab = usePlatformTabStore()
// 公司 tab 条(2026-11-17 起按平台过滤)共用这一份目录:公司翻档/启停后必须强制重拉,
// 否则 18 个页面的 tab 条端着旧名单,刚翻去京东的公司还挂在亚马逊侧。
const companyTab = useCompanyTabStore()
const loading = ref(false)
const loadFailure = ref('')
const rows = ref<CompanyItem[]>([])
@@ -60,6 +64,15 @@ function openEdit(company: CompanyItem) {
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 各看各的公司。
watch(() => platformTab.active, () => {
page.value = 1
@@ -136,7 +149,7 @@ onMounted(loadCompanies)
/>
</section>
<CompanyEditorDialog v-model="editorVisible" :company="editingCompany" :platform="platformTab.active" @saved="loadCompanies" />
<CompanyEditorDialog v-model="editorVisible" :company="editingCompany" :platform="platformTab.active" @saved="onCompaniesSaved" />
</div>
</template>
@@ -182,26 +182,32 @@ function goJump() {
// ② 用户名全平台唯一(V143 的唯一索引),留着上一家填的关键字去筛新一家 ⇒ 必然空页,而输入框还显示着那个值。
watch(() => companyTab.activeId, () => { filters.createdByAdminId = null; filters.keyword = ''; filters.page = 1; void loadUsers() })
// 切平台 tab(V206)= 同样的重取数:列表按平台过滤,候选/关键字跨平台无意义,一并清掉。
// 切平台 tab(V206)= 同样的重取数:列表按平台过滤,候选/关键字跨平台无意义,一并清掉;
// 建「公司超级管理员」的公司候选也按平台换一份(2026-11-17:京东 tab 下不能还选到亚马逊公司)。
watch(() => platformTab.active, () => {
filters.createdByAdminId = null
filters.keyword = ''
filters.page = 1
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(() => {
void loadUsers()
// 公司目录仅站点超管拉取(建「公司超级管理员」时选公司用);非超管不发这个请求,后端 403 兜底
if (isSuperAdmin.value) {
void fetchCompanies()
.then((items) => {
companyOptions.value = items.map((c) => ({ id: c.id, companyName: c.companyName }))
})
.catch(() => {
companyOptions.value = []
})
}
loadCompanyOptions()
})
</script>
@@ -3,7 +3,7 @@
* 京东数据库页勾选商品(翻页累计,由页面持有勾选集)→ 本对话框选目标分类或移出分类 →
* 一次批量归类。归属写「本组」的归属行(biz_jd_product_group_assign,V203 一组一商品一行),
* 归类不置人工编辑锁(采集照常更新价格/库存)。本组无分类时只有提示不给提交
* (移出对未分类行是无谓操作),引导去「京东分类管理」新建。 */
* (移出对未分类行是无谓操作),引导去工具栏「分类管理」新建(2026-11-17 独立页并回本页)。 */
import { computed, ref, watch } from 'vue'
import { batchAssignJdProductGroup, type JdProductGroup } from './jd-product-api.ts'
import { requestErrorMessage } from '../../api/envelope.ts'
@@ -78,7 +78,7 @@ async function submit(): Promise<void> {
</p>
<p v-if="errorText" class="group-error">{{ errorText }}</p>
<div v-if="!categories.length" class="batch-empty">本组暂无分类,先去「京东分类管理」新建一个</div>
<div v-if="!categories.length" class="batch-empty">本组暂无分类,先用工具栏「分类管理」新建一个</div>
<ul v-else class="option-list">
<li
v-for="group in categories"
@@ -0,0 +1,454 @@
<script setup lang="ts">
/** 分类管理对话框(2026-11-17 用户口径「京东分类管理并到京东数据库分类编辑里,
* 做一个搜索和添加 删除 编辑 分类名称即可」):原 V204 独立子菜单页(JdCategoryManagerPage)
* 整体并入本对话框,从京东数据库页工具栏「分类管理」打开。
* 职责不变:当前数据权限分组的分类建/改名/删除+新增的名称搜索;商品归类不在这里
* (去「批量编辑分类」)。列表状态自管理(写操作后自刷新并 emit changed 让父页刷筛选下拉)。
* 权限口径(V203)不变:本组管理员/公司超管/平台超管可写(editable);同组普通号
* 只读可看(无新建行,改名/删除按钮逐行不渲染),后端同口径 403 兜底。 */
import { computed, ref, watch } from 'vue'
import {
createJdProductGroup,
deleteJdProductGroup,
fetchJdProductGroups,
updateJdProductGroup,
type JdProductGroup,
} from './jd-product-api.ts'
import { openAdminConfirm } from '@/components/admin-confirm'
import { showAdminFeedback } from '@/components/admin-feedback-ui'
import { loadFailureMessage } from '@/components/load-failure-model'
import LoadFailureBar from '@/components/LoadFailureBar.vue'
import { requestErrorMessage } from '../../api/envelope.ts'
const props = defineProps<{
visible: boolean
/** 当前数据权限分组(分类的作用域;<=0=不属于任何分组,只留空态)。 */
ownerGroupId: number
ownerGroupName: string
/** 当前分组可写(scope 的 editable):建/改名/删除控件全挂它。 */
editable: boolean
}>()
const emit = defineEmits<{ (event: 'close'): void; (event: 'changed'): void }>()
const loading = ref(false)
/** 首屏取数失败(可见红条+重试);写操作失败走 errorText 红条(无重试语义)。 */
const loadFailure = ref('')
const errorText = ref('')
const groups = ref<JdProductGroup[]>([])
/** 搜索:按分类名称包含过滤(本地过滤,不另发请求)。 */
const keyword = ref('')
/** 新建:只收名称(排序输入 2026-11-15 客户口径下线,sortOrder 恒 0,后端契约不变)。 */
const createName = ref('')
const creating = ref(false)
/** 改名:正在编辑的分类 id 与草稿名。 */
const editingId = ref(0)
const editingName = ref('')
const saving = ref(false)
const canCreate = computed(() => props.editable && createName.value.trim().length > 0 && !creating.value && !saving.value)
/** 搜索命中(名称包含,大小写不敏感;空关键字=全量)。 */
const filteredGroups = computed(() => {
const kw = keyword.value.trim().toLowerCase()
if (!kw) return groups.value
return groups.value.filter((group) => group.name.toLowerCase().includes(kw))
})
/** 空表文案分四种:不属于任何组 / 本组没分类(可管理)/ 本组没分类(只读)/ 搜索无命中。 */
const emptyListText = computed(() => {
if (props.ownerGroupId <= 0) return '你还不属于任何数据权限分组'
if (!groups.value.length) {
return props.editable ? '本组暂无分类,先新建一个' : '本组暂无分类'
}
return '没有匹配的分类'
})
async function loadGroups(): Promise<void> {
if (props.ownerGroupId <= 0) {
groups.value = []
loading.value = false
loadFailure.value = ''
errorText.value = ''
return
}
loading.value = true
loadFailure.value = ''
try {
groups.value = await fetchJdProductGroups(props.ownerGroupId)
} catch (error) {
loadFailure.value = loadFailureMessage(error, '分类列表加载失败')
groups.value = []
} finally {
loading.value = false
}
}
async function submitCreate(): Promise<void> {
const name = createName.value.trim()
if (!name || creating.value || !props.editable) return
creating.value = true
errorText.value = ''
try {
await createJdProductGroup({ name, sortOrder: 0, ownerGroupId: props.ownerGroupId })
createName.value = ''
keyword.value = ''
showAdminFeedback(`已新建分类「${name}」`, 'success')
emit('changed')
await loadGroups()
} catch (error) {
errorText.value = requestErrorMessage(error) || '新建分类失败'
} finally {
creating.value = false
}
}
function startRename(group: JdProductGroup): void {
editingId.value = group.id
editingName.value = group.name
errorText.value = ''
}
function cancelRename(): void {
editingId.value = 0
editingName.value = ''
}
async function submitRename(group: JdProductGroup): Promise<void> {
const name = editingName.value.trim()
if (!name || saving.value) return
saving.value = true
errorText.value = ''
try {
await updateJdProductGroup(group.id, { name, sortOrder: group.sortOrder })
groups.value = groups.value.map((item) => (item.id === group.id ? { ...item, name } : item))
cancelRename()
showAdminFeedback(`已把分类改名为「${name}」`, 'success')
emit('changed')
} catch (error) {
errorText.value = requestErrorMessage(error) || '改名失败'
} finally {
saving.value = false
}
}
/** 删除分类不删商品:只解挂本组归属行(商品回到未分类),后端 JdProductGroupService.delete。 */
async function removeGroup(group: JdProductGroup): Promise<void> {
const ok = await openAdminConfirm({ title: '删除分类', message: `确定删除分类「${group.name}」吗?删除后该分类下 ${group.productCount} 个商品回到未分类。`, confirmText: '确认删除', danger: true })
if (!ok || saving.value) return
saving.value = true
errorText.value = ''
try {
await deleteJdProductGroup(group.id)
showAdminFeedback(`已删除分类「${group.name}」`, 'success')
emit('changed')
await loadGroups()
} catch (error) {
errorText.value = requestErrorMessage(error) || '删除分类失败'
} finally {
saving.value = false
}
}
watch(
() => props.visible,
(visible) => {
if (visible) {
keyword.value = ''
errorText.value = ''
loadFailure.value = ''
cancelRename()
createName.value = ''
void loadGroups()
}
},
// immediate:对话框可能以 visible=true 直接挂载(测试/复用场景),这时也要首取。
{ immediate: true },
)
</script>
<template>
<div v-if="visible" class="modal-mask" @click.self="emit('close')">
<div class="manage-modal">
<div class="modal-head">
<h3>分类管理<span v-if="ownerGroupName" class="modal-sub">· {{ ownerGroupName }}</span></h3>
<button class="modal-close" type="button" aria-label="关闭" @click="emit('close')">×</button>
</div>
<p class="modal-tip">
分类按「数据权限分组」隔离,当前组{{ editable ? '只组长/超管可维护' : '由组长/超管维护' }};
给商品归类:关掉本框,勾选商品后点「批量编辑分类」。
</p>
<div class="manage-bar">
<input v-model="keyword" class="search-input" type="text" placeholder="搜索分类名称" aria-label="搜索分类名称" />
<div v-if="editable" class="group-create">
<input v-model="createName" type="text" placeholder="输入新分类名称" aria-label="新分类名称" @keyup.enter="submitCreate" />
<button class="btn" type="button" :disabled="!canCreate" @click="submitCreate">新建</button>
</div>
</div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadGroups" />
<p v-if="errorText" class="group-error">{{ errorText }}</p>
<ul class="option-list">
<template v-if="filteredGroups.length">
<li v-for="group in filteredGroups" :key="group.id" class="option-row">
<template v-if="editingId === group.id">
<input v-model="editingName" class="rename-input" type="text" aria-label="分类新名称" @keyup.enter="submitRename(group)" />
<span class="row-actions">
<button class="btn btn-sm" type="button" :disabled="saving" @click="submitRename(group)">保存</button>
<button class="btn btn-sm btn-secondary" type="button" @click="cancelRename">取消</button>
</span>
</template>
<template v-else>
<span class="option-name" :title="group.name">{{ group.name }}</span>
<span class="option-meta" title="该分类下的商品数">{{ group.productCount }}</span>
<span v-if="editable" class="row-actions">
<button class="btn btn-sm btn-secondary" type="button" :disabled="saving" @click="startRename(group)">改名</button>
<button class="btn btn-sm btn-danger" type="button" :disabled="saving" @click="removeGroup(group)">删除</button>
</span>
</template>
</li>
</template>
<li v-else-if="loading" class="manage-empty">加载中...</li>
<li v-else class="manage-empty">{{ emptyListText }}</li>
</ul>
<div class="modal-foot">
<button class="btn btn-secondary" type="button" @click="emit('close')">关闭</button>
</div>
</div>
</div>
</template>
<style scoped>
.modal-mask {
position: fixed;
inset: 0;
z-index: 2800;
display: flex;
align-items: center;
justify-content: center;
padding: 40px 20px;
background: rgba(45, 66, 86, 0.36);
backdrop-filter: blur(6px);
}
.manage-modal {
display: flex;
flex-direction: column;
width: min(480px, 100%);
max-height: 80vh;
padding: 18px 20px 20px;
border: 1px solid #c7d7e5;
border-radius: 14px;
background: #ffffff;
box-shadow: 0 22px 60px rgba(39, 67, 94, 0.2);
}
.modal-head {
display: flex;
align-items: center;
justify-content: space-between;
}
.modal-head h3 {
margin: 0;
font-size: 15px;
font-weight: 650;
color: #24384d;
}
.modal-sub {
margin-left: 6px;
color: #5b6f83;
font-size: 13px;
font-weight: 500;
}
.modal-close {
width: 30px;
height: 30px;
border: 1px solid transparent;
border-radius: 9px;
background: none;
color: #5b6f83;
font-size: 20px;
line-height: 1;
cursor: pointer;
}
.modal-close:hover {
border-color: #cbd9e6;
background: #eef4fa;
color: #24384d;
}
.modal-tip {
margin: 8px 0 10px;
color: #8293a5;
font-size: 12.5px;
line-height: 1.5;
}
.manage-bar {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
margin-bottom: 12px;
}
.search-input,
.group-create input {
min-height: 36px;
padding: 6px 12px;
border: 1px solid #cbd9e6;
border-radius: 9px;
background: #f8fbfd;
color: #24384d;
font-size: 13px;
font-family: inherit;
outline: none;
transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
}
.search-input:hover,
.group-create input:hover {
border-color: #9fb7cd;
}
.search-input:focus,
.group-create input:focus {
background: #ffffff;
border-color: #5f85ad;
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
}
.search-input {
flex: 1;
min-width: 140px;
}
.group-create {
display: flex;
flex: 1;
gap: 8px;
min-width: 220px;
}
.group-create input {
flex: 1;
min-width: 0;
}
.group-error {
margin: 0 0 8px;
padding: 10px 12px;
border: 1px solid #f0c9c2;
border-radius: 10px;
background: #fdf1ef;
color: #a04432;
font-size: 13px;
}
.option-list {
flex: 1;
min-height: 0;
overflow-y: auto;
margin: 0;
padding: 0;
list-style: none;
border-top: 1px solid #e7eef5;
}
.option-row {
display: flex;
align-items: center;
gap: 10px;
padding: 9px 8px;
border-bottom: 1px solid #e7eef5;
font-size: 13.5px;
}
.option-row:hover {
background: #f1f7fb;
}
.option-name {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: #24384d;
}
.option-meta {
flex: none;
min-width: 22px;
padding: 1px 7px;
border-radius: 9px;
background: #eef4fa;
color: #4e6479;
font-size: 12px;
text-align: center;
white-space: nowrap;
}
.row-actions {
flex: none;
white-space: nowrap;
}
.manage-empty {
padding: 30px 12px;
text-align: center;
color: #8293a5;
font-size: 13px;
list-style: none;
}
.rename-input {
flex: 1;
min-width: 0;
min-height: 32px;
padding: 4px 10px;
border: 1px solid #cbd9e6;
border-radius: 8px;
font-size: 13.5px;
font-family: inherit;
outline: none;
}
.rename-input:focus {
background: #ffffff;
border-color: #5f85ad;
}
.modal-foot {
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 14px;
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 36px;
padding: 6px 14px;
border: 1px solid #4f78a5;
border-radius: 9px;
background: linear-gradient(135deg, #5f85ad, #4f78a5);
color: #ffffff;
font-family: inherit;
font-size: 13px;
cursor: pointer;
}
.btn:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.btn-sm {
min-height: 28px;
padding: 3px 10px;
font-size: 12.5px;
margin-right: 6px;
}
.btn-sm:last-child {
margin-right: 0;
}
.btn-secondary {
background: #ffffff;
color: #5b6f83;
border-color: #c7d7e5;
}
.btn-secondary:hover:not(:disabled) {
color: #2f5d8b;
border-color: #95b1cb;
background: #edf5fb;
}
/* 危险动作与全站 .btn-danger 同形(实心红渐变+白字)。 */
.btn-danger {
background: linear-gradient(135deg, #c06d77, #b35f6a);
border-color: #b35f6a;
color: #ffffff;
}
.btn-danger:hover:not(:disabled) {
background: linear-gradient(135deg, #cb7c84, #b96570);
}
</style>
@@ -1,486 +0,0 @@
<script setup lang="ts">
/** 京东分类管理(2026-11-17 用户口径「店铺分类弹窗删了,加个京东分类管理的子菜单维护 CRUD」):
* 当前数据权限分组的分类建/改名/删除独立成页(V204 菜单行);分组作用域与京东数据库页
* 同一套(京东的分组管理,非亚马逊——platform-scope JD_MENU_KEYS 京东侧)。
* 商品归类不在这里:去「京东数据库」页勾选商品后「批量编辑分类」。
* 权限口径(V203):本组管理员/公司超管/平台超管可写(scope 的 editable);同组普通号
* 只读(无新建行,改名/删除按钮逐行不渲染),后端同口径 403 兜底。 */
import { computed, onMounted, ref } from 'vue'
import {
createJdProductGroup,
deleteJdProductGroup,
fetchJdCategoryScope,
fetchJdProductGroups,
updateJdProductGroup,
type JdCategoryGroupOption,
type JdProductGroup,
} from './jd-product-api.ts'
import { openAdminConfirm } from '@/components/admin-confirm'
import { showAdminFeedback } from '@/components/admin-feedback-ui'
import { loadFailureMessage } from '@/components/load-failure-model'
import LoadFailureBar from '@/components/LoadFailureBar.vue'
import { requestErrorMessage } from '../../api/envelope.ts'
const loading = ref(false)
/** 首屏取数失败(可见红条+重试);写操作失败走 errorText 红条(无重试语义)。 */
const loadFailure = ref('')
const errorText = ref('')
const groups = ref<JdProductGroup[]>([])
/** 新建:只收名称(排序输入 2026-11-15 客户口径下线,sortOrder 恒 0,后端契约不变)。 */
const createName = ref('')
const creating = ref(false)
/** 改名:正在编辑的分类 id 与草稿名。 */
const editingId = ref(0)
const editingName = ref('')
const saving = ref(false)
/** 分类作用域:可见分组 + 每组可写标记。失败回空作用域(页面提示不属于任何分组)。 */
const categoryScope = ref<JdCategoryGroupOption[]>([])
const scopeDefaultGroupId = ref(0)
const ownerGroupId = ref(0)
const currentGroupOption = computed<JdCategoryGroupOption | null>(() =>
categoryScope.value.find((group) => group.id === ownerGroupId.value) || null)
const currentGroupName = computed(() => currentGroupOption.value?.name || '')
/** 分类可管理(建/改名/删除):本组管理员、公司超管、平台超管(后端 scope 判)。 */
const canManage = computed(() => currentGroupOption.value?.editable === true)
/** 分组下拉只在能看多组时才渲染;只有一组(含无可见组)时按锁定态展示。 */
const canSwitchGroup = computed(() => categoryScope.value.length > 1)
const canCreate = computed(() => canManage.value && createName.value.trim().length > 0 && !creating.value && !saving.value)
/** 空表文案分三种:不属于任何组 / 本组还没分类(可管理)/ 本组还没分类(只读)。 */
const emptyListText = computed(() => {
if (ownerGroupId.value <= 0) return '你还不属于任何数据权限分组'
return canManage.value ? '本组暂无分类,先新建一个' : '本组暂无分类'
})
async function loadScope(): Promise<void> {
try {
const scope = await fetchJdCategoryScope()
categoryScope.value = scope.groups
scopeDefaultGroupId.value = scope.defaultGroupId ?? 0
} catch {
categoryScope.value = []
scopeDefaultGroupId.value = 0
}
const keep = categoryScope.value.some((group) => group.id === ownerGroupId.value)
if (!keep) ownerGroupId.value = scopeDefaultGroupId.value
await loadGroups()
}
async function loadGroups(): Promise<void> {
if (ownerGroupId.value <= 0) {
groups.value = []
loading.value = false
loadFailure.value = ''
errorText.value = ''
return
}
loading.value = true
loadFailure.value = ''
try {
groups.value = await fetchJdProductGroups(ownerGroupId.value)
} catch (error) {
loadFailure.value = loadFailureMessage(error, '分类列表加载失败')
groups.value = []
} finally {
loading.value = false
}
}
/** 切换「分组」下拉:列表换成本组(跨组分类不可见,V203)。 */
async function changeOwnerGroup(next: number): Promise<void> {
if (next === ownerGroupId.value) return
ownerGroupId.value = next
cancelRename()
createName.value = ''
await loadGroups()
}
async function submitCreate(): Promise<void> {
const name = createName.value.trim()
if (!name || creating.value || !canManage.value) return
creating.value = true
errorText.value = ''
try {
await createJdProductGroup({ name, sortOrder: 0, ownerGroupId: ownerGroupId.value })
createName.value = ''
showAdminFeedback(`已新建分类「${name}」`, 'success')
await loadGroups()
} catch (error) {
errorText.value = requestErrorMessage(error) || '新建分类失败'
} finally {
creating.value = false
}
}
function startRename(group: JdProductGroup): void {
editingId.value = group.id
editingName.value = group.name
errorText.value = ''
}
function cancelRename(): void {
editingId.value = 0
editingName.value = ''
}
async function submitRename(group: JdProductGroup): Promise<void> {
const name = editingName.value.trim()
if (!name || saving.value) return
saving.value = true
errorText.value = ''
try {
await updateJdProductGroup(group.id, { name, sortOrder: group.sortOrder })
groups.value = groups.value.map((item) => (item.id === group.id ? { ...item, name } : item))
cancelRename()
showAdminFeedback(`已把分类改名为「${name}」`, 'success')
} catch (error) {
errorText.value = requestErrorMessage(error) || '改名失败'
} finally {
saving.value = false
}
}
/** 删除分类不删商品:只解挂本组归属行(商品回到未分类),后端 JdProductGroupService.delete。 */
async function removeGroup(group: JdProductGroup): Promise<void> {
const ok = await openAdminConfirm({ title: '删除分类', message: `确定删除分类「${group.name}」吗?删除后该分类下 ${group.productCount} 个商品回到未分类。`, confirmText: '确认删除', danger: true })
if (!ok || saving.value) return
saving.value = true
errorText.value = ''
try {
await deleteJdProductGroup(group.id)
showAdminFeedback(`已删除分类「${group.name}」`, 'success')
await loadGroups()
} catch (error) {
errorText.value = requestErrorMessage(error) || '删除分类失败'
} finally {
saving.value = false
}
}
onMounted(() => {
void loadScope()
})
</script>
<template>
<div class="jd-category-view">
<section class="panel-box">
<div class="jd-panel-head">
<h3>京东分类管理</h3>
</div>
<p class="page-tip">
分类按「数据权限分组」隔离(京东侧的分组,不同组看不到彼此的分类):当前组只组长/超管可维护;
商品归类去「京东数据库」页勾选商品后「批量编辑分类」,删除分类不删商品(只解挂归属)。
</p>
<div class="scope-row">
<div class="form-group">
<label>分组</label>
<select
v-if="canSwitchGroup"
:value="ownerGroupId"
aria-label="当前分组"
@change="changeOwnerGroup(Number(($event.target as HTMLSelectElement).value))"
>
<option v-for="group in categoryScope" :key="group.id" :value="group.id">{{ group.label }}</option>
</select>
<span v-else-if="currentGroupName" class="group-locked" title="你的数据权限内只有这一个分组">{{ currentGroupName }}</span>
<span v-else class="group-locked group-locked-empty">你还不属于任何数据权限分组</span>
</div>
<div v-if="canManage" class="group-create">
<input v-model="createName" type="text" placeholder="输入新分类名称" @keyup.enter="submitCreate" />
<button class="btn" type="button" :disabled="!canCreate" @click="submitCreate">新建</button>
</div>
</div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadGroups" />
<p v-if="errorText" class="group-error">{{ errorText }}</p>
<div class="table-scroll">
<table>
<thead>
<tr>
<th>分类名称</th>
<th style="width: 96px">商品数</th>
<th v-if="canManage" style="width: 150px">操作</th>
</tr>
</thead>
<tbody>
<template v-if="groups.length">
<tr v-for="group in groups" :key="group.id">
<td>
<template v-if="editingId === group.id">
<input v-model="editingName" class="rename-input" type="text" @keyup.enter="submitRename(group)" />
<span class="row-actions">
<button class="btn btn-sm" type="button" :disabled="saving" @click="submitRename(group)">保存</button>
<button class="btn btn-sm btn-secondary" type="button" @click="cancelRename">取消</button>
</span>
</template>
<template v-else>
<span class="group-name" :title="group.name">{{ group.name }}</span>
</template>
</td>
<td>{{ group.productCount }}</td>
<td v-if="canManage" class="ops-cell">
<button class="btn btn-sm" type="button" :disabled="saving" @click="startRename(group)">改名</button>
<button class="btn btn-sm btn-danger" type="button" :disabled="saving" @click="removeGroup(group)">删除</button>
</td>
</tr>
</template>
<tr v-else-if="loading">
<td :colspan="canManage ? 3 : 2" class="empty-tip">加载中...</td>
</tr>
<tr v-else>
<td :colspan="canManage ? 3 : 2" class="empty-tip">{{ emptyListText }}</td>
</tr>
</tbody>
</table>
</div>
</section>
</div>
</template>
<style scoped>
.jd-category-view {
font-family: inherit;
color: var(--c-text, #24384d);
display: flex;
flex-direction: column;
gap: 18px;
}
.panel-box {
width: 100%;
min-width: 0;
padding: 20px 22px 24px;
border: 1px solid #d8e3ee;
border-radius: 14px;
background: linear-gradient(145deg, #ffffff, #f9fbfd);
box-shadow: 0 1px 2px rgba(39, 67, 94, 0.04), 0 14px 30px -24px rgba(39, 67, 94, 0.28);
}
.jd-panel-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.jd-panel-head h3 {
margin: 0;
font-size: 15px;
font-weight: 650;
color: #24384d;
letter-spacing: 0.2px;
}
.page-tip {
margin: 0 0 14px;
color: #8293a5;
font-size: 12.5px;
line-height: 1.6;
}
.scope-row {
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: flex-end;
margin-bottom: 14px;
}
.form-group {
display: flex;
flex-direction: column;
gap: 7px;
min-width: 200px;
}
.form-group label {
color: #5b6f83;
font-size: 12.5px;
font-weight: 600;
}
.form-group select,
.group-create input {
min-height: 42px;
padding: 8px 12px;
border: 1px solid #cbd9e6;
border-radius: 9px;
background: #f8fbfd;
color: #24384d;
font-size: 13.5px;
font-family: inherit;
outline: none;
transition: border-color 160ms ease, box-shadow 160ms ease, background 160ms ease;
}
.form-group select:hover,
.group-create input:hover {
border-color: #9fb7cd;
}
.form-group select:focus,
.group-create input:focus {
background: #ffffff;
border-color: #5f85ad;
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
}
/* 与京东数据库页筛选行同款自绘箭头:appearance:none 后补 padding-right 给箭头留位。 */
.form-group select {
min-width: 220px;
padding-right: 34px;
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath d='M1 1.5 6 6.5 11 1.5' fill='none' stroke='%235b6f83' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 12px center;
appearance: none;
-webkit-appearance: none;
cursor: pointer;
}
.group-create {
display: flex;
gap: 8px;
}
.group-create input {
width: 220px;
}
/* 只有一个可见分组时锁定的组名:与下拉同高同壳的静态芯片(京东数据库页同款)。 */
.group-locked {
display: inline-flex;
align-items: center;
min-height: 42px;
padding: 0 12px;
border: 1px solid #dbe5ee;
border-radius: 9px;
background: #f1f6fb;
color: #4e6479;
font-size: 13.5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.group-locked-empty {
color: #8293a5;
}
.group-error {
margin: 0 0 10px;
padding: 10px 12px;
border: 1px solid #f0c9c2;
border-radius: 10px;
background: #fdf1ef;
color: #a04432;
font-size: 13px;
}
.table-scroll {
width: 100%;
min-width: 0;
overflow-x: auto;
border: 1px solid #dbe5ee;
border-radius: 10px;
background: #ffffff;
}
.table-scroll table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
}
.table-scroll th,
.table-scroll td {
padding: 10px 12px;
text-align: left;
font-size: 13.5px;
line-height: 1.5;
border-bottom: 1px solid #e0e8ef;
vertical-align: middle;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.table-scroll th {
background: #edf4fa;
color: #4e6479;
border-bottom-color: #d5e1eb;
font-size: 12.5px;
font-weight: 600;
letter-spacing: 0.4px;
}
.table-scroll tbody tr:hover td {
background: #f1f7fb;
}
.table-scroll tbody tr:last-child td {
border-bottom: 0;
}
.group-name {
color: #24384d;
}
.rename-input {
width: 200px;
min-height: 32px;
padding: 4px 10px;
border: 1px solid #cbd9e6;
border-radius: 8px;
font-size: 13.5px;
font-family: inherit;
outline: none;
}
.rename-input:focus {
background: #ffffff;
border-color: #5f85ad;
}
.row-actions {
margin-left: 8px;
white-space: nowrap;
}
.ops-cell {
display: flex;
flex-wrap: wrap;
gap: 4px;
overflow: visible;
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
min-height: 38px;
padding: 7px 16px;
border: 1px solid #4f78a5;
border-radius: 9px;
background: linear-gradient(135deg, #5f85ad, #4f78a5);
color: #ffffff;
font-family: inherit;
font-size: 13px;
cursor: pointer;
transition: background 160ms ease, box-shadow 160ms ease;
}
.btn:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.btn-sm {
min-height: 28px;
padding: 3px 10px;
font-size: 12.5px;
margin-right: 6px;
}
.btn-sm:last-child {
margin-right: 0;
}
.btn-secondary {
background: #ffffff;
color: #5b6f83;
border-color: #c7d7e5;
}
.btn-secondary:hover:not(:disabled) {
color: #2f5d8b;
border-color: #95b1cb;
background: #edf5fb;
}
/* 危险动作与全站 .btn-danger 同形(实心红渐变+白字)。 */
.btn-danger {
background: linear-gradient(135deg, #c06d77, #b35f6a);
border-color: #b35f6a;
color: #ffffff;
}
.btn-danger:hover:not(:disabled) {
background: linear-gradient(135deg, #cb7c84, #b96570);
}
.empty-tip {
padding: 44px 24px;
text-align: center;
color: #8293a5;
font-size: 13.5px;
}
</style>
@@ -2,8 +2,10 @@
/** 京东公共商品库:支持分类和京麦类目组合筛选。
* V203(2026-11-16 用户口径):分类按「数据权限分组」隔离——不同组看不到彼此的分类,
* 能看多组的人用筛选行「分组」下拉切换当前组(只有一组时锁定显示)。
* 2026-11-17 用户口径:店铺分类弹窗下线(建/改名/删分类挪「京东分类管理」子菜单页);
* 本页工具栏改「批量编辑分类」——勾选商品(翻页累计记忆)后选目标分类归入或移出。 */
* 2026-11-17 用户口径:店铺分类弹窗下线,本页工具栏改「批量编辑分类」——勾选商品
* (翻页累计记忆)后选目标分类归入或移出;同日第二刀「京东分类管理并到京东数据库分类
* 编辑里」:V204 独立子菜单页(JdCategoryManagerPage)下线,建/改名/删分类收进工具栏
* 「分类管理」对话框(JdCategoryManageDialog,带名称搜索)。 */
import { computed, onMounted, reactive, ref } from 'vue'
import {
deleteJdProducts,
@@ -22,6 +24,7 @@ import JdProductDetailDrawer from './JdProductDetailDrawer.vue'
import JdProductEditDrawer from './JdProductEditDrawer.vue'
import JdCategoryCascader from './JdCategoryCascader.vue'
import JdBatchAssignDialog from './JdBatchAssignDialog.vue'
import JdCategoryManageDialog from './JdCategoryManageDialog.vue'
import OldPagination from '@/components/OldPagination.vue'
import { showAdminFeedback } from '@/components/admin-feedback-ui'
import { openAdminConfirm } from '@/components/admin-confirm'
@@ -55,6 +58,8 @@ const detailItem = ref<JdProductItem | null>(null)
const detailVisible = ref(false)
/** 批量编辑分类对话框(2026-11-17 替代下线的店铺分类弹窗)。 */
const batchEditVisible = ref(false)
/** 分类管理对话框(2026-11-17 第二刀:独立子菜单页并进来,建/改名/删+搜索)。 */
const manageVisible = ref(false)
/** 行级编辑抽屉(2026-11-15 用户口径「每一条数据后面 需要编辑或者删除;编辑的话
* 这里面都是可以编辑的」):删除走下面的 removeOne(同一条删除链),编辑走独立抽屉。 */
const editItem = ref<JdProductItem | null>(null)
@@ -151,6 +156,17 @@ async function openBatchEdit(): Promise<void> {
batchEditVisible.value = true
}
/** 打开分类管理(对话框自取列表);入口对所有人渲染——同组普通号只读可看(V203),
* 写控件由对话框按 editable 分档。 */
function openManage(): void {
manageVisible.value = true
}
/** 分类管理里有写操作(建/改/删):刷一遍筛选下拉与商品数徽标。 */
async function onManaged(): Promise<void> {
await loadGroupOptions()
}
/** 批量归类完成(对话框已关):清勾选+重取列表(行集 groupName 变了)。
* 移出分类 targetName 为 null;updated 是后端实际写入/解挂的归属行数。 */
async function onBatchAssigned(updated: number, targetName: string | null): Promise<void> {
@@ -181,8 +197,8 @@ async function load(): Promise<void> {
total.value = result.total
if (result.page >= 1) page.value = result.page
// 勾选跨页记忆(2026-11-17 用户口径「支持勾选翻页也要记住」):翻页/重取/改筛选都
// 不清勾选集——批量编辑分类与批量删除都按累计 id 提交,操作前的确认弹窗点名数量,
// 工具栏「清除勾选」给显式的反悔出口。
// 不清勾选集——批量编辑分类与批量删除都按累计 id 提交,操作前的确认弹窗点名数量;
// 「清除勾选」按钮同日用户口径删除,勾选只在批量操作成功后自动清。
} catch (error) {
loadFailure.value = loadFailureMessage(error, '京东商品列表加载失败')
showAdminFeedback(loadFailure.value, 'error')
@@ -246,7 +262,8 @@ async function copyText(text: string): Promise<void> {
// ---------------- 删除(先删桶、全成功才删库行,语义在后端 JdProductDeleteService) ----------------
/** 勾选集(按商品 id,跨页累计记忆,2026-11-17 用户口径)。翻页/重取不清;显式出口
* 是工具栏「清除勾选」,批量删除/批量归类成功后自动清。 */
* 曾是工具栏「清除勾选」,同日用户口径「清除勾选这个按钮删除」后只剩批量删除/
* 批量归类成功后自动清。 */
const selectedIds = ref<Set<number>>(new Set())
const deleting = ref(false)
@@ -270,11 +287,6 @@ function toggleSelectAll(checked: boolean): void {
selectedIds.value = next
}
/** 显式清空勾选(跨页累计后用户需要一个看得见的反悔口)。 */
function clearSelection(): void {
selectedIds.value = new Set()
}
/** 单行删除入口(行内按钮):确认弹窗点名商品编码与「桶内图片一并删除」。 */
async function removeOne(row: JdProductItem): Promise<void> {
await removeMany([row.id], `确定删除商品「${row.productCode || row.title}」吗?`)
@@ -386,19 +398,20 @@ onMounted(async () => {
@click="openBatchEdit"
>批量编辑分类</button>
<!-- 商品行写只对平台超管;分类写由当前分组 editable 决定(本组管理员/公司超管/平台超管)。
非超管看到只读提示,分类维护入口指向「京东分类管理」子菜单页(同组普通号在那页只读查看)。 -->
<span v-if="!isSuperAdmin" class="jd-readonly-tip">只读:编辑/删除仅超级管理员可用;分类由本组管理员在「京东分类管理」维护</span>
非超管看到只读提示,分类维护入口=工具栏「分类管理」(只读可看,写控件按 editable 分档)。 -->
<span v-if="!isSuperAdmin" class="jd-readonly-tip">只读:编辑/删除仅超级管理员可用;分类在本页「分类管理」查看与维护</span>
<select v-model="filter.groupId" aria-label="筛选店铺分类" @change="apply">
<option value="">全部分类</option>
<option v-for="group in groupOptions" :key="group.id" :value="String(group.id)">{{ group.name }}</option>
</select>
<!-- 清除勾选(2026-11-17 勾选跨页记忆的显式反悔口):只在有勾选时出现。 -->
<!-- 分类管理(2026-11-17 用户口径「京东分类管理并到京东数据库分类编辑里」):V204 独立
子菜单页整体并入本对话框(搜索+新建+改名+删除)。入口对所有人渲染(同组普通号
只读可看,V203),写控件由对话框按当前分组 editable 分档。 -->
<button
v-if="selectedCount"
class="btn btn-secondary jd-clear-btn"
class="btn btn-secondary jd-manage-btn"
type="button"
@click="clearSelection"
>清除勾选</button>
@click="openManage"
>分类管理</button>
<!-- 批量删除 2026-11-16 客户口径「不要勾选后才显示」:常显,勾选 0 时置灰。
同日写权限收窄到超管:非超管整颗按钮不渲染(勾选列 2026-11-17 起对本组可写
分类管理员开放,服务批量归类)。 -->
@@ -488,6 +501,14 @@ onMounted(async () => {
@close="batchEditVisible = false"
@done="onBatchAssigned"
/>
<JdCategoryManageDialog
:visible="manageVisible"
:owner-group-id="ownerGroupId"
:owner-group-name="currentGroupName"
:editable="canManageCategories"
@close="manageVisible = false"
@changed="onManaged"
/>
<JdProductDetailDrawer
:item="detailItem"
:visible="detailVisible"
@@ -168,8 +168,8 @@ h3 {
.jd-delete-btn {
margin-left: auto;
}
/* 清除勾选(勾选跨页记忆的显式反悔口):贴着删除勾选(同一组勾选管理动作)。 */
.jd-clear-btn {
/* 分类管理(2026-11-17 独立分类管理页并入本页的对话框入口):贴着分类筛选下拉。 */
.jd-manage-btn {
margin-left: 6px;
}
/* 危险动作(删除勾选):与全站 .btn-danger 同形——实心红渐变+白字。
+3 -3
View File
@@ -45,10 +45,10 @@ export const adminPages: AdminPageDef[] = [
{ path: 'asin-center/skip-price', menuKey: 'admin_skip_price_asin', title: '最低价ASIN', companyScoped: true, load: () => import('@/pages/asin/SkipPricePage.vue') },
{ path: 'patent-center/clean-items', menuKey: 'admin_appearance_patent_clean_items', title: '外观专利数据库', companyScoped: true, load: () => import('@/pages/patent/AppearancePatentCleanItemsPage.vue') },
// 京东数据库 2026-11-16 退出公司 tab(参考品牌数据库先例):数据全平台公共,不按公司取数。
// 2026-11-17 第二刀:V204 独立「京东分类管理」子菜单页(jd-center/categories)整体并入
// 本页工具栏「分类管理」对话框(JdCategoryManageDialog),路由与菜单行(V208 删 V204 行)
// 一并下线——用户口径「京东分类管理并到京东数据库分类编辑里」。
{ path: 'jd-center/database', menuKey: 'admin_jd_database', title: '京东数据库', companyScoped: false, load: () => import('@/pages/jd/JdDatabasePage.vue') },
// 京东分类管理 2026-11-17(用户口径「店铺分类弹窗下线,加个京东分类管理的子菜单维护 CRUD」):
// 分类建/改名/删除独立成页(V204 菜单行同 key),归类在京东数据库页「批量编辑分类」。
{ path: 'jd-center/categories', menuKey: 'admin_jd_category_manage', title: '京东分类管理', companyScoped: false, load: () => import('@/pages/jd/JdCategoryManagerPage.vue') },
]
export function routeOf(page: AdminPageDef): RouteRecordRaw {
+28 -4
View File
@@ -2,6 +2,8 @@ import { defineStore } from 'pinia'
import { fetchCompanies } from '@/api/companies'
import type { CompanyItem } from '@/api/companies-dto'
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'
/** 公司 tab 的状态。成员 user ids **不在这里缓存**——每次请求交后端解析,
@@ -12,6 +14,11 @@ export const useCompanyTabStore = defineStore('company-tab', {
activeId: null as number | null,
loading: false,
loaded: false,
/** 当前这份目录是按哪个平台 tab 拉的(V206 平台分侧,2026-11-17 用户口径「公司 tab
* 条也按平台分侧,两边各看各的公司」)。空串=还没按平台拉过。早退闸拿它对撞当前
* tab:一致才免拉,平台切了就重拉一份;`fetchCompanies` 失败时不翻转它,旧清单
* (可能过时)继续顶着,下一次切台/重进页面会再试。 */
loadedPlatform: '' as PlatformTabId | '',
/** GET /companies 失败时的原因。**只住 store 与 console,不在模板里渲染**——
* §12 第 5 条没批任何新的用户可见提示,接口暴露禁令高于"失败可见"。
* 取不到目录时 loaded 保持 false ⇒ visibleForOperator 为 false ⇒ tab 条整体不画(fail-closed,观感与改前一致)。 */
@@ -35,15 +42,27 @@ export const useCompanyTabStore = defineStore('company-tab', {
},
},
actions: {
async initialize() {
/** 拉公司目录(按当前平台 tab 过滤,后端 GET /api/admin/companies?platform=…)。
* `force`=绕开「该平台已拉过」的早退闸(公司编辑弹窗翻档/启停后的 refresh 用),
* 旧清单保留到成功那刻再整份替换,取数期间 tab 条不闪空。 */
async initialize(options?: { force?: boolean }) {
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
// 失败后 loaded 仍是 false ⇒ 下一次 watch 命中超管会重试;重试前先清掉旧原因,免得留着一条已经翻篇的错误。
this.error = ''
try {
this.companies = await fetchCompanies()
this.activeId = firstSelectableCompanyId(this.companies)
const companies = await fetchCompanies(platform)
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
} catch (error) {
// 2026-10-05 修复轮 1:改前只有 try/finally ⇒ GET /companies 抛错时零痕迹(loaded 永远 false、
@@ -57,6 +76,11 @@ export const useCompanyTabStore = defineStore('company-tab', {
this.loading = false
}
},
/** 公司目录被编辑(公司管理翻档/启停/改名)后的强制重拉:不受 loadedPlatform 早退闸
* 限制。失败语义与 initialize 同口径(error + rethrow),调用方自行决定要不要提示。 */
async refresh() {
await this.initialize({ force: true })
},
setActiveId(id: number) {
this.activeId = id
},
@@ -17,8 +17,10 @@ const KEYWORD_USAGE_MIGRATION = join(process.cwd(), '..', 'backend-java', 'src',
'V175__move_gating_and_add_keyword_usage_menu.sql')
const JD_DATABASE_MIGRATION = join(process.cwd(), '..', 'backend-java', 'src', 'main', 'resources', 'db',
'V196__jd_database_menu.sql')
const JD_CATEGORY_MANAGE_MIGRATION = join(process.cwd(), '..', 'backend-java', 'src', 'main', 'resources', 'db',
'V204__jd_category_manage_menu.sql')
/** V204 插入的「京东分类管理」菜单行已随 2026-11-17 用户口径「京东分类管理并到京东数据库
* 分类编辑里」由 V208 删除(页面并入 JdDatabasePage 工具栏「分类管理」对话框)。 */
const JD_CATEGORY_MANAGE_DROP_MIGRATION = join(process.cwd(), '..', 'backend-java', 'src', 'main', 'resources', 'db',
'V208__drop_jd_category_manage_menu.sql')
interface MigrationMenu {
name: string
@@ -124,23 +126,15 @@ test('V196 新增的京东数据库菜单 key 必须在路由注册表登记', (
assert.ok(!sql.includes('user_column_permission'), 'V196 不得预插授权行(默认仅超管可见)')
})
test('V204 新增的京东分类管理菜单 key 必须在路由注册表登记(2026-11-17 弹窗下线、CRUD 挪子菜单页)', () => {
const sql = readFileSync(JD_CATEGORY_MANAGE_MIGRATION, 'utf8')
const menus = menusInsertedBy(sql)
const insertCount = (sql.match(/INSERT INTO `columns`/g) || []).length
assert.ok(menus.length > 0, 'V204 应当插入后台菜单,一条都没解析出来说明正则失效')
assert.equal(menus.length, insertCount, `解析到 ${menus.length} 条,但迁移有 ${insertCount} 条 INSERT INTO columns`)
test('V208 删掉 V204 的京东分类管理菜单行,且注册表不再认这个 key(2026-11-17 分类管理并入京东数据库页)', () => {
// V204 本体已应用不可回改(铁律 10,文件原样保留作历史取证);下线动作由 V208 出 DELETE,
// 页面并入京东数据库页工具栏「分类管理」对话框。
const sql = readFileSync(JD_CATEGORY_MANAGE_DROP_MIGRATION, 'utf8')
assert.ok(sql.includes("DELETE FROM `columns` WHERE `column_key` = 'admin_jd_category_manage'"),
'V208 必须 DELETE admin_jd_category_manage 菜单行(授权行随外键 CASCADE)')
const menu = menus.find((item) => item.columnKey === 'admin_jd_category_manage')
assert.ok(menu, 'V204 必须插入 admin_jd_category_manage 菜单')
const page = adminPages.find((item) => item.menuKey === 'admin_jd_category_manage')
assert.ok(page, 'routes.ts 必须有 admin_jd_category_manage 页面,否则菜单点进去 404')
assert.equal(page.path, menu.routePath, '库里的 route_path 应与注册表路径一致')
assert.equal(page.title, menu.name, '页面标题应与菜单名一致')
assert.equal(page.companyScoped, false, '分类按数据权限分组隔离(V203),不按公司 tab 取数')
// 每公司一套树,挂数据管理组、排序 69(V196 京东数据库占 68)。
assert.ok(sql.includes("grp.`column_key` = 'admin_group_data'"), 'V204 必须把京东分类管理挂到数据管理组')
assert.ok(/'京东分类管理', 'admin_jd_category_manage', 'admin', 'jd-center\/categories', 69/.test(sql), '京东分类管理排序应为 69')
assert.ok(!sql.includes('user_column_permission'), 'V204 不得预插授权行(默认仅超管可见)')
const registered = adminPages.find((item) => item.menuKey === 'admin_jd_category_manage')
assert.ok(!registered, 'routes.ts 不得再登记 admin_jd_category_manage(页面已并入京东数据库页,残留=404 入口)')
const jdRouteGone = !adminPages.some((item) => item.path === 'jd-center/categories')
assert.ok(jdRouteGone, 'jd-center/categories 路由必须下线')
})
@@ -32,14 +32,13 @@ test('routes 注册表出现京东数据库页面且退出公司 tab(2026-11-1
assert.equal(page.companyScoped, false, '京东数据库全平台公共,不画公司 tab(AC-6 已被 11-15/11-16 口径推翻)')
})
/** 2026-11-17 用户口径「店铺分类弹窗删了,加个京东分类管理的子菜单维护 CRUD」(V204):
* 分类建/改名/删除独立成页,与京东数据库页同在京东平台侧(platform-scope 用例另钉)。 */
test('routes 注册表出现京东分类管理页面(V204 子菜单),与京东数据库并排退出公司 tab', () => {
const page = adminPages.find((item) => item.menuKey === 'admin_jd_category_manage')
assert.ok(page, 'routes.ts 缺 menuKey=admin_jd_category_manage 的注册行')
assert.equal(page.path, 'jd-center/categories', 'route_path 必须与 V204 菜单一侧一致')
assert.equal(page.title, '京东分类管理', '菜单标题以「京东分类管理」为准')
assert.equal(page.companyScoped, false, '分类按数据权限分组隔离(V203),不画公司 tab')
/** 2026-11-17 用户口径「京东分类管理并到京东数据库分类编辑里」:V204 独立子菜单页下线
* (分类建/改名/删收进京东数据库页工具栏「分类管理」对话框),路由注册表不得再登记该 key。 */
test('routes 注册表不再登记京东分类管理独立页(V204 页并入京东数据库页,残留=404 入口)', () => {
assert.ok(!adminPages.some((item) => item.menuKey === 'admin_jd_category_manage'),
'admin_jd_category_manage 注册行必须已删(页面并入京东数据库页)')
assert.ok(!adminPages.some((item) => item.path === 'jd-center/categories'),
'jd-center/categories 路由必须下线')
})
/** 详情面的 SKU 矩阵解析(V198):后端下发 camelCase,snake 容错;坏行不炸整块。 */
@@ -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()
})
})
@@ -0,0 +1,214 @@
/**
* 京东分类管理对话框(JdCategoryManageDialog)的挂载契约。
*
* 2026-11-17 用户口径「京东分类管理并到京东数据库分类编辑里,做一个搜索和添加 删除
* 编辑 分类名称即可」:V204 独立子菜单页(JdCategoryManagerPage,已删)整体并入本对话框,
* 从京东数据库页工具栏「分类管理」打开。原页面契约逐条承接:当前数据权限分组的
* 分类建/改名/删除;新增名称搜索(本地过滤)。商品归类不在这里(去「批量编辑分类」)。
* 权限口径(V203)不变:editable 才渲染写控件;同组普通号只读可看。
*
* 跑法:`npx vitest run tests/mount/jd-category-manage-dialog.mount.test.ts`
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { createPinia, setActivePinia, type Pinia } from 'pinia'
import JdCategoryManageDialog from '@/pages/jd/JdCategoryManageDialog.vue'
const jdApi = vi.hoisted(() => ({
fetchJdProductGroups: vi.fn(),
createJdProductGroup: vi.fn(),
updateJdProductGroup: vi.fn(),
deleteJdProductGroup: vi.fn(),
}))
const confirmMock = vi.hoisted(() => vi.fn())
vi.mock('@/pages/jd/jd-product-api.ts', () => jdApi)
vi.mock('@/components/admin-confirm', () => ({ openAdminConfirm: confirmMock }))
/** 分组 id 常量:默认作用域就这一个可见且可写的组(组长档形状)。 */
const GROUP_A = 11
function group(id: number, name: string, productCount = 0, sortOrder = 0) {
return { id, name, ownerGroupId: GROUP_A, sortOrder, productCount }
}
let pinia: Pinia
beforeEach(() => {
vi.clearAllMocks()
pinia = createPinia()
setActivePinia(pinia)
jdApi.fetchJdProductGroups.mockResolvedValue([])
confirmMock.mockResolvedValue(true)
})
async function mountDialog(editable = true): Promise<VueWrapper<Element>> {
const wrapper = mount(JdCategoryManageDialog, {
global: { plugins: [pinia] },
props: {
visible: true,
ownerGroupId: GROUP_A,
ownerGroupName: '甲组',
editable,
},
})
await flushPromises()
await flushPromises()
return wrapper
}
describe('京东分类管理对话框(V204 独立页 2026-11-17 并入京东数据库页)', () => {
it('打开即按当前分组取分类(ownerGroupId 必带);标题带当前分组名', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
const wrapper = await mountDialog()
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledWith(GROUP_A)
expect(wrapper.get('.manage-modal').text()).toContain('分类管理')
expect(wrapper.get('.manage-modal').text()).toContain('甲组', '标题/上下文带当前分组名')
expect(wrapper.findAll('.option-row')).toHaveLength(1)
wrapper.unmount()
})
it('新建分类:落当前分组归属(ownerGroupId 必带),成功后清输入重取并通知父页刷新', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
const wrapper = await mountDialog()
await wrapper.get('.group-create input').setValue('上新区')
await wrapper.findAll('button').find((b) => b.text() === '新建')!.trigger('click')
await flushPromises()
expect(jdApi.createJdProductGroup).toHaveBeenCalledWith({ name: '上新区', sortOrder: 0, ownerGroupId: GROUP_A })
expect((wrapper.get('.group-create input').element as HTMLInputElement).value).toBe('')
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledTimes(2, '成功后重取分类列表')
expect(wrapper.emitted('changed'), '写成功必须 emit changed 让父页刷筛选下拉').toBeTruthy()
wrapper.unmount()
})
it('搜索:按名称包含本地过滤(不发额外请求),命中后新建会清关键字', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3), group(8, '裤装', 1), group(9, '配饰', 0)])
const wrapper = await mountDialog()
const callsBefore = jdApi.fetchJdProductGroups.mock.calls.length
await wrapper.get('.search-input').setValue('裙')
await flushPromises()
expect(wrapper.findAll('.option-row')).toHaveLength(1, '「裙」只命中裙装')
expect(wrapper.findAll('.option-row')[0].text()).toContain('裙装')
expect(jdApi.fetchJdProductGroups.mock.calls.length).toBe(callsBefore, '搜索是本地过滤,不另发请求')
expect(wrapper.text()).not.toContain('裤装', '不匹配项不出现')
await wrapper.get('.group-create input').setValue('上新区')
await wrapper.findAll('button').find((b) => b.text() === '新建')!.trigger('click')
await flushPromises()
expect((wrapper.get('.search-input').element as HTMLInputElement).value).toBe('',
'新建成功清关键字(新分类不被旧搜索藏住)')
wrapper.unmount()
})
it('搜索无命中给显式空态文案(不是空列表静默)', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
const wrapper = await mountDialog()
await wrapper.get('.search-input').setValue('不存在的分类')
expect(wrapper.get('.manage-empty').text()).toBe('没有匹配的分类')
wrapper.unmount()
})
it('改名:行内编辑后按 (id, {name, sortOrder}) 提交并 emit changed', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
const wrapper = await mountDialog()
await wrapper.findAll('button').find((b) => b.text() === '改名')!.trigger('click')
await wrapper.get('.rename-input').setValue('长裙')
await wrapper.findAll('button').find((b) => b.text() === '保存')!.trigger('click')
await flushPromises()
expect(jdApi.updateJdProductGroup).toHaveBeenCalledWith(7, { name: '长裙', sortOrder: 0 })
expect(wrapper.emitted('changed')).toBeTruthy()
wrapper.unmount()
})
it('删除:二次确认文案点名商品数(删除不删商品,只解挂归属),确认后调端点重取', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
const wrapper = await mountDialog()
await wrapper.findAll('button').find((b) => b.text() === '删除')!.trigger('click')
await flushPromises()
expect(confirmMock).toHaveBeenCalledTimes(1)
const options = confirmMock.mock.calls[0][0]
expect(options.title).toBe('删除分类')
expect(options.message).toContain('确定删除分类「裙装」吗')
expect(options.message).toContain('3 个商品回到未分类', '文案点名该分类下的商品数')
expect(options.danger).toBe(true)
expect(jdApi.deleteJdProductGroup).toHaveBeenCalledWith(7)
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledTimes(2, '删除成功后重取列表')
expect(wrapper.emitted('changed')).toBeTruthy()
wrapper.unmount()
})
it('删除确认点取消就不发请求(防误删第一道闸)', async () => {
confirmMock.mockResolvedValue(false)
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
const wrapper = await mountDialog()
await wrapper.findAll('button').find((b) => b.text() === '删除')!.trigger('click')
await flushPromises()
expect(confirmMock).toHaveBeenCalledTimes(1)
expect(jdApi.deleteJdProductGroup).not.toHaveBeenCalled()
wrapper.unmount()
})
it('只读档(editable=false):无新建行、无搜索仍可用、无改名/删除按钮', async () => {
const wrapper = await mountDialog(false)
expect(wrapper.find('.group-create').exists()).toBe(false, '只读账号不渲染新建行')
expect(wrapper.findAll('button').some((b) => b.text() === '改名')).toBe(false)
expect(wrapper.findAll('button').some((b) => b.text() === '删除')).toBe(false)
expect(wrapper.get('.search-input').exists()).toBe(true, '搜索是读面,只读档保留')
wrapper.unmount()
})
it('不属于任何数据权限分组(ownerGroupId<=0):不发取数请求,空态直说', async () => {
const wrapper = mount(JdCategoryManageDialog, {
global: { plugins: [pinia] },
props: { visible: true, ownerGroupId: 0, ownerGroupName: '', editable: false },
})
await flushPromises()
await flushPromises()
expect(jdApi.fetchJdProductGroups).not.toHaveBeenCalled()
expect(wrapper.get('.manage-empty').text()).toBe('你还不属于任何数据权限分组')
expect(wrapper.find('.group-create').exists()).toBe(false)
wrapper.unmount()
})
it('本组暂无分类:可写档文案引导新建,只读档直说', async () => {
const writable = await mountDialog(true)
expect(writable.get('.manage-empty').text()).toBe('本组暂无分类,先新建一个')
writable.unmount()
const readonly = await mountDialog(false)
expect(readonly.get('.manage-empty').text()).toBe('本组暂无分类')
readonly.unmount()
})
it('加载失败:红条可见且重试真能重跑(取数页硬规矩)', async () => {
jdApi.fetchJdProductGroups.mockRejectedValueOnce(new Error('上游 502'))
const wrapper = mount(JdCategoryManageDialog, {
global: { plugins: [pinia] },
props: { visible: true, ownerGroupId: GROUP_A, ownerGroupName: '甲组', editable: true },
})
await flushPromises()
await flushPromises()
const bar = wrapper.find('.load-failure-bar')
expect(bar.exists()).toBe(true, '失败态必须可见(不是一闪而过的 toast)')
expect(bar.text()).toContain('分类列表加载失败')
expect(bar.text()).toContain('上游 502', '后端/网络原因要进文案')
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
await bar.find('button').trigger('click')
await flushPromises()
await flushPromises()
expect(wrapper.find('.load-failure-bar').exists()).toBe(false, '重试成功后红条消失')
expect(wrapper.text()).toContain('裙装')
wrapper.unmount()
})
it('页面职责边界(反向钉):归类不在本对话框——不出现批量归类/删除勾选入口', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
const wrapper = await mountDialog()
expect(wrapper.findAll('button').some((b) => b.text() === '批量编辑分类')).toBe(false, '归类入口在京东数据库页')
expect(wrapper.text()).toContain('批量编辑分类', '但提示要指路(关掉本框去勾选商品归类)')
expect(jdApi.deleteJdProductGroup).not.toHaveBeenCalled()
wrapper.unmount()
})
})
@@ -1,172 +0,0 @@
/**
* 京东分类管理页(V204,2026-11-17 用户口径「店铺分类弹窗删了,加个京东分类管理的子菜单
* 维护 CRUD」)的挂载契约:当前数据权限分组的分类建/改名/删除独立成页;分组作用域与
* 京东数据库页同一套(京东侧分组,非亚马逊——platform-scope JD_MENU_KEYS);
* 商品归类不在这里(去京东数据库页「批量编辑分类」)。
*
* 跑法:`npx vitest run tests/mount/jd-category-manager-page.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 JdCategoryManagerPage from '@/pages/jd/JdCategoryManagerPage.vue'
const jdApi = vi.hoisted(() => ({
fetchJdCategoryScope: vi.fn(),
fetchJdProductGroups: vi.fn(),
createJdProductGroup: vi.fn(),
updateJdProductGroup: vi.fn(),
deleteJdProductGroup: vi.fn(),
}))
const confirmMock = vi.hoisted(() => vi.fn())
vi.mock('@/pages/jd/jd-product-api.ts', () => jdApi)
vi.mock('@/components/admin-confirm', () => ({ openAdminConfirm: confirmMock }))
/** 分组 id 常量:默认作用域就这一个可见且可写的组(组长档形状)。 */
const GROUP_A = 11
function singleGroupScope(editable = true) {
return {
platformSuperAdmin: false,
defaultGroupId: GROUP_A,
groups: [{ id: GROUP_A, name: '甲组', label: '甲组', editable }],
}
}
function group(id: number, name: string, productCount = 0, sortOrder = 0) {
return { id, name, ownerGroupId: GROUP_A, sortOrder, productCount }
}
let pinia: Pinia
beforeEach(() => {
vi.clearAllMocks()
pinia = createPinia()
setActivePinia(pinia)
jdApi.fetchJdCategoryScope.mockResolvedValue(singleGroupScope())
jdApi.fetchJdProductGroups.mockResolvedValue([])
confirmMock.mockResolvedValue(true)
})
async function mountPage(): Promise<ReturnType<typeof mount>> {
const wrapper = mount(JdCategoryManagerPage, { global: { plugins: [pinia] } })
await flushPromises()
await flushPromises()
return wrapper
}
describe('京东分类管理(V204 子菜单页)', () => {
it('首屏按默认组取分类;多组可见出「分组」下拉,切组重取', async () => {
jdApi.fetchJdCategoryScope.mockResolvedValue({
platformSuperAdmin: true,
defaultGroupId: GROUP_A,
groups: [
{ id: GROUP_A, name: 'A组', label: '甲公司 / A组', editable: true },
{ id: 12, name: 'B组', label: '甲公司 / B组', editable: false },
],
})
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
const wrapper = await mountPage()
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledWith(GROUP_A)
const picker = wrapper.get('[aria-label="当前分组"]')
expect((picker.element as HTMLSelectElement).closest('.form-group')?.querySelector('label')?.textContent).toBe('分组',
'分组是带标签的表单控件(与京东数据库页筛选行同口径)')
expect(picker.findAll('option').map((o) => o.text())).toEqual(['甲公司 / A组', '甲公司 / B组'])
await picker.setValue('12')
await flushPromises()
// 切组后分类按新组重取(跨组不可见,V203)。
expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith(12)
wrapper.unmount()
})
it('新建分类:落当前分组归属(ownerGroupId 必带),成功后清输入并重取', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
const wrapper = await mountPage()
await wrapper.get('.group-create input').setValue('上新区')
await wrapper.findAll('button').find((b) => b.text() === '新建')!.trigger('click')
await flushPromises()
expect(jdApi.createJdProductGroup).toHaveBeenCalledWith({ name: '上新区', sortOrder: 0, ownerGroupId: GROUP_A })
expect((wrapper.get('.group-create input').element as HTMLInputElement).value).toBe('')
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledTimes(2, '成功后重取分类列表')
wrapper.unmount()
})
it('改名:行内编辑后按 (id, {name, sortOrder}) 提交', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
const wrapper = await mountPage()
await wrapper.findAll('button').find((b) => b.text() === '改名')!.trigger('click')
await wrapper.get('.rename-input').setValue('长裙')
await wrapper.findAll('button').find((b) => b.text() === '保存')!.trigger('click')
await flushPromises()
expect(jdApi.updateJdProductGroup).toHaveBeenCalledWith(7, { name: '长裙', sortOrder: 0 })
wrapper.unmount()
})
it('删除:二次确认文案点名商品数(删除不删商品,只解挂归属),确认后调端点重取', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
const wrapper = await mountPage()
await wrapper.findAll('button').find((b) => b.text() === '删除')!.trigger('click')
await flushPromises()
expect(confirmMock).toHaveBeenCalledTimes(1)
const options = confirmMock.mock.calls[0][0]
expect(options.title).toBe('删除分类')
expect(options.message).toContain('确定删除分类「裙装」吗')
expect(options.message).toContain('3 个商品回到未分类', '文案点名该分类下的商品数')
expect(options.danger).toBe(true)
expect(jdApi.deleteJdProductGroup).toHaveBeenCalledWith(7)
wrapper.unmount()
})
it('只读档(editable=false):无新建行、无改名/删除按钮,空表文案不带「先新建」', async () => {
jdApi.fetchJdCategoryScope.mockResolvedValue(singleGroupScope(false))
jdApi.fetchJdProductGroups.mockResolvedValue([])
const wrapper = await mountPage()
expect(wrapper.find('.group-create').exists()).toBe(false, '只读账号不渲染新建行')
expect(wrapper.findAll('button').some((b) => b.text() === '改名')).toBe(false)
expect(wrapper.findAll('button').some((b) => b.text() === '删除')).toBe(false)
expect(wrapper.find('thead').text()).not.toContain('操作', '只读档连操作列表头都不渲染')
expect(wrapper.find('.empty-tip').text()).toBe('本组暂无分类')
wrapper.unmount()
})
it('不属于任何数据权限分组:锁定芯片直说空态,不出下拉与新建行', async () => {
jdApi.fetchJdCategoryScope.mockResolvedValue({ platformSuperAdmin: false, defaultGroupId: null, groups: [] })
const wrapper = await mountPage()
expect(wrapper.find('[aria-label="当前分组"]').exists()).toBe(false)
expect(wrapper.get('.group-locked').text()).toBe('你还不属于任何数据权限分组')
expect(wrapper.find('.group-create').exists()).toBe(false)
expect(wrapper.find('.empty-tip').text()).toBe('你还不属于任何数据权限分组')
wrapper.unmount()
})
it('加载失败:红条可见且重试真能重跑(取数页硬规矩),切组后重取成功即清', async () => {
jdApi.fetchJdProductGroups.mockRejectedValueOnce(new Error('上游 502'))
const wrapper = mount(JdCategoryManagerPage, { global: { plugins: [pinia] } })
await flushPromises()
await flushPromises()
const bar = wrapper.find('.load-failure-bar')
expect(bar.exists()).toBe(true, '失败态必须可见(不是一闪而过的 toast)')
expect(bar.text()).toContain('分类列表加载失败')
expect(bar.text()).toContain('上游 502', '后端/网络原因要进文案')
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
await bar.find('button').trigger('click')
await flushPromises()
await flushPromises()
expect(wrapper.find('.load-failure-bar').exists()).toBe(false, '重试成功后红条消失')
expect(wrapper.text()).toContain('裙装')
wrapper.unmount()
})
it('页面职责边界(反向钉):归类不在本页——页面不出现批量归类/商品列表入口', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([group(7, '裙装', 3)])
const wrapper = await mountPage()
expect(wrapper.findAll('button').some((b) => b.text() === '批量编辑分类')).toBe(false, '归类入口在京东数据库页')
expect(wrapper.text()).toContain('京东数据库', '页内提示指路「京东数据库」页')
expect(jdApi.deleteJdProductGroup).not.toHaveBeenCalled()
wrapper.unmount()
})
})
@@ -4,8 +4,11 @@
* 形态:panel-box + 筛选行(商品编码/标题关键字/类目/分组/同步起止 date 对)+
* 查询/重置 + 自绘明细表(点行开详情抽屉)+ OldPagination;
* 分组下拉 2026-11-16 用户口径「做成分组」上移进筛选行=带标签的表单控件(不再是工具栏裸下拉);
* 店铺分类弹窗 2026-11-17 用户口径下线:工具栏改「批量编辑分类」(勾选跨页累计+归入/移出),
* 分类建/改名/删除挪「京东分类管理」子菜单页(V204,另见 jd-category-manager-page.mount.test.ts)。
* 店铺分类弹窗 2026-11-17 用户口径下线:工具栏改「批量编辑分类」(勾选跨页累计+归入/移出);
* 同日第二刀「京东分类管理并到京东数据库分类编辑里」:V204 独立子菜单页下线
* (jd-category-manager-page.mount.test.ts 随之删除),建/改名/删分类+搜索收进工具栏
* 「分类管理」对话框(另见 jd-category-manage-dialog.mount.test.ts);
* 「清除勾选」按钮同日用户口径删除(勾选只在批量操作成功后自动清)。
* 公司维度 2026-11-16 整页摘除(「删除掉公司 tab,参考品牌数据库」):页面不消费公司 tab
* store、列表/类目下拉不带 company_id(反向钉在 company-tab-wiring「公司维度不得回流」)。
* 商品状态筛选/列与导出按钮已随 2026-11-15 客户口径从前端下线(后端端点保留);
@@ -114,7 +117,7 @@ async function mountWith(payload: unknown): Promise<VueWrapper<Element>> {
* 勾选跨页累计记忆(翻页/重取不清)→ 对话框选目标分类归入或移出 → 按 (ids, groupId,
* ownerGroupId) 提交;成功后清勾选并重取。旧弹窗的「勾选翻页即清」口径同日废止。 */
describe('批量编辑分类(店铺分类弹窗 2026-11-17 下线后的替代入口)', () => {
it('勾选跨页记忆:第 1 页勾 1 行翻到第 2 页再勾 1 行,删除按累计 2 行提交,清除勾选可显式清零', async () => {
it('勾选跨页记忆:第 1 页勾 1 行翻到第 2 页再勾 1 行,删除按累计 2 行提交;「清除勾选」按钮已删(2026-11-17 用户口径)', async () => {
jdApi.fetchJdProductList
.mockImplementationOnce(() => Promise.resolve({ items: [item(1)], total: 40, page: 1, pageSize: 20 }))
.mockImplementation(() => Promise.resolve({ items: [item(2)], total: 40, page: 2, pageSize: 20 }))
@@ -122,7 +125,6 @@ describe('批量编辑分类(店铺分类弹窗 2026-11-17 下线后的替代
await flushPromises()
await flushPromises()
const deleteBtn = () => wrapper.get('.jd-delete-btn')
const clearBtn = () => wrapper.findAll('button').find((b) => b.text() === '清除勾选')
await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true)
expect(deleteBtn().text()).toContain('删除勾选(1)')
@@ -133,7 +135,8 @@ describe('批量编辑分类(店铺分类弹窗 2026-11-17 下线后的替代
expect(deleteBtn().text()).toContain('删除勾选(1)', '翻页后第 1 页的勾选仍在累计集里')
await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true)
expect(deleteBtn().text()).toContain('删除勾选(2)', '第 2 页再勾 1 行,累计 2 行')
expect(clearBtn(), '有勾选时「清除勾选」出现').toBeTruthy()
expect(wrapper.findAll('button').some((b) => b.text() === '清除勾选')).toBe(false,
'「清除勾选」按钮 2026-11-17 用户口径删除(显式反悔口没了,勾选只在批量操作成功后自动清)')
// 累计勾选直达删除:跨页的行一起删(确认弹窗点名总数)。
jdApi.deleteJdProducts.mockResolvedValueOnce({ deleted: 2, imagesDeleted: 0, objectsDeleted: 0, objectsKept: 0, objectsSkipped: 0 })
@@ -143,12 +146,7 @@ describe('批量编辑分类(店铺分类弹窗 2026-11-17 下线后的替代
expect(confirmMock.mock.calls.at(-1)![0].message).toContain('确定删除勾选的 2 个商品吗', '确认文案点名累计总数')
// 跨页累计的 id 一起提交。
expect(jdApi.deleteJdProducts).toHaveBeenLastCalledWith([1, 2])
// 显式反悔口:清除勾选后按钮回置灰。
await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true)
await clearBtn()!.trigger('click')
expect(deleteBtn().text()).toContain('删除勾选(0)')
expect(wrapper.findAll('button').some((b) => b.text() === '清除勾选')).toBe(false, '勾选 0 时清除按钮消失')
expect(deleteBtn().text()).toContain('删除勾选(0)', '批量删除成功后自动清勾选')
wrapper.unmount()
})
@@ -206,7 +204,7 @@ describe('批量编辑分类(店铺分类弹窗 2026-11-17 下线后的替代
wrapper.unmount()
})
it('本组暂无分类:对话框只留提示不给提交(移出对未分类行是无谓操作),引导去分类管理页', async () => {
it('本组暂无分类:对话框只留提示不给提交(移出对未分类行是无谓操作),引导去工具栏「分类管理」新建', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([])
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true)
@@ -214,7 +212,7 @@ describe('批量编辑分类(店铺分类弹窗 2026-11-17 下线后的替代
await flushPromises()
const modal = wrapper.get('.batch-modal')
expect(modal.text()).toContain('本组暂无分类')
expect(modal.text()).toContain('京东分类管理', '空态把维护入口指向「京东分类管理」')
expect(modal.text()).toContain('分类管理', '空态把维护入口指向工具栏「分类管理」(独立页 2026-11-17 并入本页)')
expect(modal.findAll('button').some((b) => b.text() === '移出分类' && b.attributes('disabled') === undefined)).toBe(false,
'无分类时移出不可提交')
expect(jdApi.batchAssignJdProductGroup).not.toHaveBeenCalled()
@@ -231,6 +229,60 @@ describe('批量编辑分类(店铺分类弹窗 2026-11-17 下线后的替代
})
})
/** 分类管理入口(2026-11-17 用户口径「京东分类管理并到京东数据库分类编辑里」):
* V204 独立子菜单页下线,工具栏「分类管理」打开 JdCategoryManageDialog(搜索+新建+
* 改名+删除);入口对所有人渲染(同组普通号只读可看),写控件由对话框按 editable 分档;
* 对话框 CRUD 成功 emit changed ⇒ 父页刷分类筛选下拉。 */
describe('分类管理入口(V204 独立页并入京东数据库页)', () => {
it('工具栏「分类管理」入口常显(勾选 0 也可用),点开渲染对话框且按当前分组取分类', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '裙装', sortOrder: 0, productCount: 3 }])
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
const manageBtn = () => wrapper.findAll('button').find((b) => b.text() === '分类管理')
expect(manageBtn(), '入口常显(不等勾选)').toBeTruthy()
expect(wrapper.find('.manage-modal').exists()).toBe(false, '未点开时不渲染对话框')
const callsBefore = jdApi.fetchJdProductGroups.mock.calls.length
await manageBtn()!.trigger('click')
await flushPromises()
const modal = wrapper.get('.manage-modal')
expect(modal.text()).toContain('分类管理')
expect(modal.text()).toContain('甲组', '标题带当前分组名')
expect(modal.get('.search-input').exists()).toBe(true, '搜索框是本对话框新能力')
expect(modal.text()).toContain('裙装')
expect(jdApi.fetchJdProductGroups.mock.calls.length).toBeGreaterThan(callsBefore,
'对话框打开时按当前分组自取列表')
wrapper.unmount()
})
it('对话框内删分类成功(emit changed)后父页重取分类下拉(筛选选项与商品数徽标同步刷新)', async () => {
// 取数按次序变形:页面首屏=裙装;对话框打开与 changed 后的重取=删后列表(只剩裤装)。
let groupFetchCount = 0
jdApi.fetchJdProductGroups.mockImplementation(() => {
groupFetchCount += 1
return groupFetchCount === 1
? Promise.resolve([{ id: 7, name: '裙装', sortOrder: 0, productCount: 3 }])
: Promise.resolve([{ id: 8, name: '裤装', sortOrder: 1, productCount: 1 }])
})
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
expect(wrapper.get('[aria-label="筛选店铺分类"]').text()).toContain('裙装', '首屏下拉含首取分类')
await wrapper.findAll('button').find((b) => b.text() === '分类管理')!.trigger('click')
await flushPromises()
const modal = wrapper.get('.manage-modal')
confirmMock.mockResolvedValue(true)
jdApi.deleteJdProductGroup.mockResolvedValueOnce(undefined)
await modal.findAll('button').find((b) => b.text() === '删除')!.trigger('click')
await flushPromises()
await flushPromises()
expect(jdApi.deleteJdProductGroup, '删除按钮属于当前列表行').toHaveBeenCalledWith(8)
// changed → 父页 loadGroupOptions:下拉按新列表重取(最后一次调用拿到删后列表)。
const select = wrapper.get('[aria-label="筛选店铺分类"]')
expect(select.text()).toContain('裤装', '下拉刷新出新一轮分类')
expect(select.text()).not.toContain('裙装', '删掉的分类不再出现在筛选下拉')
wrapper.unmount()
})
})
describe('京东数据库页(v1.4 Phase 5)', () => {
it('挂载后按首屏分页参数取列表(pageSize 默认 20、不带公司维度),行数=本页条数', async () => {
const wrapper = await mountWith({ items: [item(1), item(2), item(3)], total: 42, page: 1, pageSize: 20 })
@@ -699,10 +751,10 @@ describe('京东数据库页(v1.4 Phase 5)', () => {
})
/** 写权限分档(2026-11-16 用户口径收窄商品行写;2026-11-17 弹窗下线后更新):
* 商品行写(编辑/删除/勾选批量删)只对平台超管渲染;分类写(批量编辑分类)由 scope 的
* 每组 editable 决定(本组管理员/公司超管/平台超管)——同组普通号在本页只读,
* 只读查看入口在「京东分类管理」子菜单页(V204)。勾选列 2026-11-17 起对本组可写
* 分类管理员开放(服务批量归类),商品行按钮仍只归平台超管。 */
* 商品行写(编辑/删除/勾选批量删)只对平台超管渲染;分类写(批量编辑分类、分类管理)由
* scope 的每组 editable 决定(本组管理员/公司超管/平台超管)——同组普通号在本页只读,
* 分类维护入口=工具栏「分类管理」对话框(V204 独立页 2026-11-17 并入,只读可看)。
* 勾选列 2026-11-17 起对本组可写分类管理员开放(服务批量归类),商品行按钮仍只归平台超管。 */
describe('京东数据库写权限分档(商品行写=平台超管;分类写=本组 editable)', () => {
it('非超管且本组不可写:无勾选列、无操作列、无删除勾选、无批量编辑分类;列表/筛选/详情照常', async () => {
useAdminSessionStore().user = { id: 2, username: 'ops', role: 'admin' }
@@ -717,9 +769,11 @@ describe('京东数据库写权限分档(商品行写=平台超管;分类
expect(wrapper.findAll('tbody input[type="checkbox"]')).toHaveLength(0, '不可写分类的普通号没有勾选列')
expect(wrapper.find('.jd-delete-btn').exists()).toBe(false, '批量删除按钮不渲染')
expect(wrapper.findAll('button').some((b) => b.text() === '批量编辑分类')).toBe(false, '分类写入口不渲染(本组不可写)')
expect(wrapper.findAll('button').some((b) => b.text() === '分类管理')).toBe(true,
'分类管理入口是读面,普通号也能打开看(写控件由对话框按 editable 分档)')
expect(wrapper.find('thead').text()).not.toContain('操作', '操作列(编辑/删除)不渲染')
expect(wrapper.text()).toContain('只读:编辑/删除仅超级管理员可用', '只读提示必须看得见并区分两类写权限')
expect(wrapper.text()).toContain('京东分类管理', '提示把分类维护入口指向「京东分类管理」子菜单页')
expect(wrapper.text()).toContain('分类在本页「分类管理」查看与维护', '提示把分类维护入口指向本页「分类管理」(独立页已并入)')
// 读面不受影响:筛选下拉、列表行、点行开详情都还在。
expect(wrapper.get('[aria-label="筛选店铺分类"]').exists()).toBe(true, '分类筛选是读面,保留')
@@ -834,7 +888,7 @@ describe('京东数据库分类按数据权限分组隔离(V203)', () => {
wrapper.unmount()
})
it('不属于任何数据权限分组:分类全空、不给切换也不给批量归类入口(空态兜底在「京东分类管理」页)', async () => {
it('不属于任何数据权限分组:分类全空、不给切换也不给批量归类入口', async () => {
jdApi.fetchJdCategoryScope.mockResolvedValue({ platformSuperAdmin: false, defaultGroupId: null, groups: [] })
const wrapper = await mountWith({ items: [item(1, { groupId: null, groupName: '' })], total: 1, page: 1, pageSize: 20 })
expect(wrapper.find('[aria-label="当前分组"]').exists()).toBe(false)
@@ -36,8 +36,8 @@ const OPS_MIN_COL_PX: Record<string, number> = {
'src/pages/asin/ProductCategoryPage.vue': 138,
'src/pages/asin/QueryAsinPage.vue': 138,
'src/pages/asin/SkipPricePage.vue': 138,
// 京东分类管理(V204):改名/删除两颗 btn-sm(两字 53×2+gap+左右 padding 24)。
'src/pages/jd/JdCategoryManagerPage.vue': 138,
// 京东分类管理页(V204)2026-11-17 下线:CRUD 并入京东数据库页「分类管理」对话框
// (对话框无表格操作列,不进本表)。
'src/pages/records/DeviceLogsPage.vue': 138,
'src/pages/records/RecordsDigitalHumanVersionPage.vue': 287,
'src/pages/records/RecordsSoftwareVersionPage.vue': 77,
@@ -40,7 +40,6 @@ const TREE: AdminMenuNode[] = [
node('admin_query_asin', '查询ASIN', '/asin-center/query'),
node('admin_appearance_patent_clean_items', '外观专利数据库', '/patent-center/clean-items'),
node('admin_jd_database', '京东数据库', '/jd-center/database'),
node('admin_jd_category_manage', '京东分类管理', '/jd-center/categories'),
node('admin_product_categories', '商品类目', '/asin-center/categories'),
]),
]
@@ -60,24 +59,20 @@ test('menuKey 平台归属:京东独占即 [jd],双侧清单即两侧,其
assert.deepEqual(platformsOfMenuKey(''), ['amazon'])
})
test('京东 tab:账号与权限只余双侧三项,数据管理只余京东两页(数据库+分类管理);顺序与 route 原样透传', () => {
test('京东 tab:账号与权限只余双侧三项,数据管理只余京东独占页(2026-11-17 分类管理并入京东数据库页后只剩数据库一页);顺序与 route 原样透传', () => {
const filtered = filterMenuTreeByPlatform(TREE, 'jd')
assert.deepEqual(filtered.map((item) => item.key), ['admin_group_account', 'admin_group_data'])
assert.deepEqual(groupChildKeys(filtered, 'admin_group_account'),
['admin_users', 'admin_group_manage', 'admin_companies'])
// 2026-11-17 用户口径「这边分组是京东的分组管理的而不是亚马逊的」:分类管理子菜单
// 归京东侧(JD_MENU_KEYS),亚马逊 tab 侧看不到它(亚马逊用例反向钉住)。
assert.deepEqual(groupChildKeys(filtered, 'admin_group_data'),
['admin_jd_database', 'admin_jd_category_manage'])
// 2026-11-17 晚用户口径「京东分类管理并到京东数据库分类编辑里」:分类管理子菜单
// (V204)下线,京东侧数据管理组只剩京东数据库一页。
assert.deepEqual(groupChildKeys(filtered, 'admin_group_data'), ['admin_jd_database'])
const jd = filtered[1].children![0]
assert.equal(jd.route, '/jd-center/database')
assert.equal(jd.name, '京东数据库')
const categoryManage = filtered[1].children![1]
assert.equal(categoryManage.route, '/jd-center/categories', 'V204 菜单行的 route_path 与注册表一致')
assert.equal(categoryManage.name, '京东分类管理')
})
test('亚马逊 tab:除京东独占两页外全数保留(含 2026-11-17 回归的双侧账号域三页),分组结构不变', () => {
test('亚马逊 tab:除京东独占页外全数保留(含 2026-11-17 回归的双侧账号域三页),分组结构不变', () => {
const filtered = filterMenuTreeByPlatform(TREE, 'amazon')
assert.deepEqual(groupChildKeys(filtered, 'admin_group_account'),
['admin_columns', 'admin_users', 'admin_group_manage', 'admin_user_secrets',
@@ -120,13 +115,13 @@ test('tab 显示依据:两侧都有可见页才画 tab 条,仅一侧授权
assert.deepEqual(visiblePlatformsFor(null), [])
})
test('平台 tab 定义与两份菜单清单钉死(防清单漂移):京东独占两页、双侧共用账号域三页', () => {
test('平台 tab 定义与两份菜单清单钉死(防清单漂移):京东独占仅数据库一页、双侧共用账号域三页', () => {
assert.deepEqual(PLATFORM_TABS, [
{ id: 'amazon', label: '亚马逊' },
{ id: 'jd', label: '京东' },
])
assert.deepEqual([...JD_MENU_KEYS].sort(),
['admin_jd_category_manage', 'admin_jd_database'])
// 2026-11-17 晚分类管理(admin_jd_category_manage)并入京东数据库页后从清单摘除。
assert.deepEqual([...JD_MENU_KEYS], ['admin_jd_database'])
assert.deepEqual([...BOTH_PLATFORM_MENU_KEYS].sort(),
['admin_companies', 'admin_group_manage', 'admin_users'])
})
@@ -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.security.AdminAuthSupport;
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.modules.company.mapper.CompanyMapper;
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
@@ -27,11 +28,13 @@ import java.util.Set;
* 京东数据库分类的「当前分组」作用域解析(V203,2026-11-16 用户口径)。
*
* <p>口径:「组」=公司内的<b>数据权限分组</b>({@code biz_shop_manage_group}),公司→组两级隔离。
* 四档:</p>
* 2026-11-17 用户口径「同理京东那边也是」加一条平台闸:<b>只有京东档({@code platform='jd'},
* V206 列)的分组才进京东侧作用域</b>——亚马逊档与 NULL 一律不进下拉(四档角色先各自圈完
* 可见集,最后统一过这道闸)。四档:</p>
* <ul>
* <li><b>平台超管</b>:全部公司全部组可读可写;</li>
* <li><b>公司超管</b>:本公司全部组可读可写(与「公司超管看本公司全部成员」同源);</li>
* <li><b>管理员(组长)</b>:可见=自己带的组 + 自己所属组的组长;可写=自己带的组;</li>
* <li><b>平台超管</b>:全部公司全部<b>京东档</b>组可读可写;</li>
* <li><b>公司超管</b>:本公司全部<b>京东档</b>组可读可写(与「公司超管看本公司全部成员」同源);</li>
* <li><b>管理员(组长)</b>:可见=自己带的组 + 自己所属组的组长(过平台闸后);可写=自己带的组;</li>
* <li><b>普通号</b>:可见同上,可写空(能开弹窗看,不能增删改分类、不能归类)。</li>
* </ul>
*
@@ -144,39 +147,49 @@ public class JdCategoryScopeService {
String role = adminAuthSupport.currentRole(user);
Map<Long, ShopManageGroupEntity> visible = new LinkedHashMap<>();
Set<Long> writable = new LinkedHashSet<>();
if (dataReadScope.isPlatformSuperAdmin(user)) {
boolean platformSuperAdmin = dataReadScope.isPlatformSuperAdmin(user);
if (platformSuperAdmin) {
collect(visible, shopManageGroupMapper.selectAllGroups());
writable.addAll(visible.keySet());
return assemble(true, user.getCompanyId(), visible, writable);
}
if (DeviceSessionPolicy.isCompanySuperAdmin(role)) {
} else if (DeviceSessionPolicy.isCompanySuperAdmin(role)) {
Long companyId = user.getCompanyId();
if (companyId != null && companyId > 0) {
collect(visible, companyGroups(companyId));
writable.addAll(visible.keySet());
}
return assemble(false, companyId, visible, writable);
}
// 管理员(组长):自己带的组可写;自己所属组的组长带的分组只读可见。
List<ShopManageGroupEntity> led = ledGroups(user.getId());
collect(visible, led);
if ("admin".equals(role)) {
for (ShopManageGroupEntity group : led) {
if (group.getId() != null) {
writable.add(group.getId());
} else {
// 管理员(组长):自己带的组可写;自己所属组的组长带的分组只读可见。
List<ShopManageGroupEntity> led = ledGroups(user.getId());
collect(visible, led);
if ("admin".equals(role)) {
for (ShopManageGroupEntity group : led) {
if (group.getId() != null) {
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) {
collect(visible, ledGroups(user.getCreatedById()));
}
List<Long> memberOfLeaders = shopManageGroupMapper.selectLeaderIdsByMemberUserId(user.getId());
if (memberOfLeaders != null) {
for (Long leaderId : memberOfLeaders) {
collect(visible, ledGroups(leaderId));
}
}
return assemble(false, user.getCompanyId(), visible, writable);
// 2026-11-17 用户口径「同理京东那边也是」:京东侧作用域只认京东档(platform='jd')的
// 数据权限分组——亚马逊档与 NULL 一律不进下拉。V206 存量默认 amazon、京东侧数据由编辑
// 弹窗翻档,这里不做「NULL/缺列当 jd」的宽判:宽了会把没翻档的存量整批带进京东侧,
// 等于平台分侧白做。
retainJdPlatformGroups(visible, writable);
return assemble(platformSuperAdmin, user.getCompanyId(), visible, writable);
}
/** 只留京东档分组,并让可写集跟着可见集收缩(writable ⊆ visible 的既有不变量保持)。 */
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) {
@@ -0,0 +1,34 @@
-- 迁移 V208:下线后管菜单「京东分类管理」(2026-11-17 用户口径「京东分类管理并到
-- 京东数据库分类编辑里,做一个搜索和添加 删除 编辑 分类名称即可」)
-- =============================================================
-- 1. 变更目的:V204 插入的独立子菜单行(jd-center/categories)整体下线——分类建/改名/删
-- 收进京东数据库页工具栏「分类管理」对话框(前端 JdCategoryManageDialog,复用既有
-- /api/admin/jd-product-groups 读写端点,鉴权锚 admin_jd_database 不变)。V204 本体
-- 已应用不可回改(铁律 10),本迁移只出 DELETE;授权过的 user→column 行随 columns
-- 外键 ON DELETE CASCADE 一并清(V204 头注释第 5 节口径)。
--
-- 2. 形状口径:按 column_key 全表删(该 key 每公司一行,V204 按公司逐家插入;key 是
-- 稳定权限标识、不撞别的菜单)。不新增任何行。
--
-- 3. 影响表与数据量:columns 删 N 行(N=公司数),字典小表,毫秒级。
--
-- 4. 可重跑性:DELETE 按谓词幂等,重跑 no-op;自检闸门只读。
--
-- 5. 回滚:无需脚本——重放 V204 两段 INSERT(均带 NOT EXISTS 守卫,幂等)即可重建菜单行;
-- 前端路由(jd-center/categories)已随本窗口下线,回滚菜单前须先回滚前端发布。
-- =============================================================
-- ---------- 1. 删除菜单行(授权行随外键 CASCADE) ----------
DELETE FROM `columns` WHERE `column_key` = 'admin_jd_category_manage';
-- ---------- 2. 自检闸门:残留不为 0 就抛 1048(列 must_be_zero NOT NULL) ----------
CREATE TEMPORARY TABLE IF NOT EXISTS `_v208_gate` (`must_be_zero` INT NOT NULL);
-- 闸门:按 key 与按 route_path 两个方向都不得有残留(防改 key 换壳残留路由)。
INSERT INTO `_v208_gate`
SELECT IF(COUNT(*) = 0, 0, NULL)
FROM `columns`
WHERE `column_key` = 'admin_jd_category_manage'
OR (`menu_type` = 'admin' AND `route_path` = 'jd-center/categories');
DROP TEMPORARY TABLE `_v208_gate`;
@@ -36,7 +36,7 @@ class CompanyVoTest {
});
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("created_at")).isEqualTo("2026-10-04 14:05");
// 库里没读到的时间给空串:前端 formatDateTime 才有占位,不会渲染出 undefined
@@ -0,0 +1,158 @@
package com.nanri.aiimage.modules.jd;
import com.nanri.aiimage.modules.task.model.CollectChannel;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* v1.5 京东商品上架到京麦(Phase 0 预置的验收契约,蓝图 docs/ITERATION_PLAN.md §1 AC / §4)。
*
* <p><b>Pending-to-Active 机制</b>:标 {@code @Disabled("Pending Phase 2")} 的方法是 Phase 2
* (后端地基:V208+ 迁移 / JdPublishController / JdPublishTaskService / 派发三件套)落地后才
* 能跑绿的契约,实现合入的同一个 Phase 里必须移除注解跑绿——蓝图对应 Phase 的【待激活验收
* 测试】栏登记了这份清单。唯一不 skip 的方法 {@link #京东分类读取口全仓唯一_B11301绊线()} 是
* <b>立即生效</b>的存量绊线:B113-01 拍板「分类选项唯一来源 GET /api/jd-collect/groups」,
* 任何面(含本迭代新增的发布面)都不许开第二个京东分类读取口。
*
* <p>Pending 方法全部写成<b>源码绊线</b>(读源文件断言关键形状),不 import 尚不存在的新类,
* Phase 0 落盘即可编译;判据形状照 {@code JdTaskPullSpiImplTest}(白名单段绊线)与
* {@code JdCollectGroupsEndpointTest}(controller 绊线)先例。
*/
class JdPublishContractPendingTest {
private static final Path MAIN_JAVA = Path.of("src/main/java");
private static final Path APP_YML = Path.of("src/main/resources/application.yml");
private static final Path DB_DIR = Path.of("src/main/resources/db");
private static final Path MODULE_REGISTRY =
MAIN_JAVA.resolve("com/nanri/aiimage/common/module/TaskModuleRegistry.java");
private static final Path PUBLISH_CONTROLLER =
MAIN_JAVA.resolve("com/nanri/aiimage/modules/jd/controller/JdPublishController.java");
private static final Path PUBLISH_SERVICE =
MAIN_JAVA.resolve("com/nanri/aiimage/modules/jd/service/JdPublishTaskService.java");
private static final Path PUBLISH_SPI =
MAIN_JAVA.resolve("com/nanri/aiimage/modules/jd/service/JdPublishTaskPullSpiImpl.java");
private static final String PUBLISH_MODULE = "JD_PUBLISH";
private static final String PUBLISH_QUEUE_TYPE = "jd-product-publish-run";
// ---------------------------------------------------------------- AC-9(立即生效)
/** AC-9 服务端半边(B113-01):京东分类读取口全仓唯一,就是 JdCollectController 的 /groups。 */
@Test
void 京东分类读取口全仓唯一_B11301绊线() throws IOException {
// 判据:同文件同时出现 jd-collect 前缀与 /groups 映射(类级 @RequestMapping 与
// 方法级 @GetMapping 分开写,拼接串搜不到——照 JdCollectGroupsEndpointTest 的断言口径)。
List<String> hits = new ArrayList<>();
try (Stream<Path> files = Files.walk(MAIN_JAVA)) {
files.filter(p -> p.toString().endsWith(".java")).forEach(p -> {
try {
String source = Files.readString(p);
if (source.contains("jd-collect") && source.contains("@GetMapping(\"/groups\")")) {
hits.add(p.toString().replace('\\', '/'));
}
} catch (IOException e) {
throw new IllegalStateException("读源码失败: " + p, e);
}
});
}
assertEquals(List.of("src/main/java/com/nanri/aiimage/modules/jd/controller/JdCollectController.java"),
hits.stream().sorted().toList(),
"B113-01:/api/jd-collect/groups 是京东分类的唯一读取口,"
+ "发布面(或任何新面)需要分类数据必须消费同一出口,不得自开第二份");
}
// ---------------------------------------------------------------- AC-2(Pending Phase 2:派发三件套)
@Test
@Disabled("Pending Phase 2: AC-2 派发三件套——client-task-pull 白名单加 JD_PUBLISH 后移除本注解")
void client_task_pull白名单默认值含JD_PUBLISH_源码绊线() throws IOException {
// 照 JdTaskPullSpiImplTest 同判据:白名单不含模块名时 SPI 装载了也不会被走到。
// 逐行定位 AIIMAGE_CLIENT_TASK_PULL_MODULE_TYPES 那一行再断言,比全文 contains 精确。
String whitelistLine = Files.readAllLines(APP_YML).stream()
.filter(line -> line.contains("AIIMAGE_CLIENT_TASK_PULL_MODULE_TYPES"))
.findFirst()
.orElseThrow(() -> new AssertionError("application.yml 缺 client-task-pull.module-types 白名单行"));
assertTrue(whitelistLine.contains(PUBLISH_MODULE),
"client-task-pull 白名单默认值必须含 JD_PUBLISH(铁律 32:漏加=任务永不执行)");
}
@Test
@Disabled("Pending Phase 2: AC-2 LOCAL_DEFAULT_MODULES——JD_PUBLISH 进清单后移除本注解")
void JD_PUBLISH默认通道必须是LOCAL_铁律19同形() {
// 京东发布必须由客户端已登录京麦的 Chrome 执行,Linux worker 永远跑不了:
// 不进 LOCAL_DEFAULT_MODULES 就会默认 ONLINE ⇒ 任务被推给无京麦登录态的机器(铁律 19)。
// 参数是字符串,编译期可引用;Phase 2 之前返回 ONLINE,由 @Disabled 保护。
assertEquals(CollectChannel.LOCAL, CollectChannel.defaultFor(PUBLISH_MODULE),
"JD_PUBLISH 必须进 CollectChannel.LOCAL_DEFAULT_MODULES(defaultFor 判据,照 JD_SHOP_COLLECT 同形)");
}
@Test
@Disabled("Pending Phase 2: AC-2 SPI 实现——JdPublishTaskPullSpiImpl 落地后移除本注解")
void 派发SPI实现存在且队列类型为jd_product_publish_run() throws IOException {
assertTrue(Files.exists(PUBLISH_SPI), "缺 ClientTaskPullSpi 实现:JdPublishTaskPullSpiImpl(铁律 32 第一件)");
assertTrue(Files.readString(PUBLISH_SPI).contains(PUBLISH_QUEUE_TYPE),
"SPI 的 QUEUE_TYPE 必须是 " + PUBLISH_QUEUE_TYPE + "(客户端按它分发,两处不同值任务永不执行)");
// 建单成功页面推送的载荷 type 与 SPI 同值(铁律 32 第三件:enqueue 页面推送)
assertTrue(Files.exists(PUBLISH_SERVICE), "缺 JdPublishTaskService(建单/生命周期/明细下发)");
assertTrue(Files.readString(PUBLISH_SERVICE).contains(PUBLISH_QUEUE_TYPE),
"JdPublishTaskService 建单成功推送的载荷 type 必须与 SPI QUEUE_TYPE 同值");
}
@Test
@Disabled("Pending Phase 2: AC-2 registry 登记——TaskModuleRegistry 加 JD_PUBLISH 后移除本注解")
void TaskModuleRegistry登记JD_PUBLISH模块_源码绊线() throws IOException {
assertTrue(Files.exists(MODULE_REGISTRY), "TaskModuleRegistry 缺失");
assertTrue(Files.readString(MODULE_REGISTRY).contains(PUBLISH_MODULE),
"TaskModuleRegistry 必须登记 JD_PUBLISH 条目(module_type 承载方)");
}
// ---------------------------------------------------------------- AC-1(Pending Phase 2:建单端点)
@Test
@Disabled("Pending Phase 2: AC-1 建单端点——JdPublishController 落地后移除本注解")
void 建单端点形状与归属校验_源码绊线() throws IOException {
assertTrue(Files.exists(PUBLISH_CONTROLLER), "缺 JdPublishController(蓝图 §3:POST /api/jd-publish/tasks)");
String source = Files.readString(PUBLISH_CONTROLLER);
assertTrue(source.contains("jd-publish/tasks"), "缺建单端点路径 /api/jd-publish/tasks");
assertTrue(source.contains("@PostMapping"), "建单必须是 POST 端点");
// AC-9 归属半边:选了他人商品要业务码拒绝(照 JdCollectController 的 fail-closed 鉴权形状)
assertTrue(source.contains("requireOwnershipUserId"),
"建单/items 下发必须走 adminAuthSupport.requireOwnershipUserId(选他人商品要业务码拒绝)");
}
@Test
@Disabled("Pending Phase 2: AC-1 发布明细表——V208+ 迁移落地后移除本注解")
void 发布明细表迁移存在且表名为biz_jd_publish_item() throws IOException {
// 蓝图 §3:V207 已被 users_jd_publish_quota 占用(5c7a310e),发布明细表从 V208 起号。
// 号段断言放宽到 V208~V229:开工时仍须按 MigrationInventoryTest 复核当窗可用号(铁律 33)。
assertTrue(Files.isDirectory(DB_DIR), "缺 db 迁移目录");
try (Stream<Path> files = Files.list(DB_DIR)) {
boolean hit = files.map(p -> p.getFileName().toString())
.anyMatch(name -> name.matches("V2(?:0[89]|[12][0-9])__.*jd_publish_item.*\\.sql"));
assertTrue(hit, "db/ 缺 biz_jd_publish_item 迁移(V208+ 号段,表名照蓝图 §3)");
}
}
// ---------------------------------------------------------------- AC-8(Pending Phase 2:配额闸)
@Test
@Disabled("Pending Phase 2: AC-8 配额闸——建单入口接 assertWithinQuota 后移除本注解")
void 建单入口必须接JdPublishQuotaService配额闸_源码绊线() throws IOException {
assertTrue(Files.exists(PUBLISH_SERVICE), "缺 JdPublishTaskService");
String source = Files.readString(PUBLISH_SERVICE);
assertTrue(source.contains("assertWithinQuota"),
"建单入口必须调 JdPublishQuotaService.assertWithinQuota(原语已预留,AC-8;"
+ "超配额当场业务码拒绝,不得到执行侧静默降级)");
}
}
@@ -30,7 +30,8 @@ import static org.mockito.Mockito.when;
/**
* 京东数据库分类「当前分组」作用域判据(V203;2026-11-16 用户口径)。
*
* <p>四档矩阵:平台超管=全部公司全部组可读可写;公司超管=本公司全部组;
* <p>四档矩阵(2026-11-17 起各档可见集最后统一过「只留京东档 platform='jd' 分组」的平台闸):
* 平台超管=全部公司全部组可读可写;公司超管=本公司全部组;
* 管理员(组长)=自己带的组可写、自己所属组的组长带的分组只读;
* 普通号=与管理员同可见、<b>零可写</b>(能开弹窗看,不能增删改分类、不能归类)。
* 另钉三条收敛语义:不可见组读 403(不做空结果降级)、无分组上下文读回 null(页面照常可用)、
@@ -86,6 +87,70 @@ class JdCategoryScopeServiceTest {
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
void 公司超管_本公司全部组可读可写() {
AdminUserEntity operator = user(USER_ID, COMPANY_ID);
@@ -319,10 +384,20 @@ class JdCategoryScopeServiceTest {
}
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();
group.setId(id);
group.setCompanyId(companyId);
group.setGroupName(name);
group.setPlatform(platform);
return group;
}
@@ -331,6 +406,7 @@ class JdCategoryScopeServiceTest {
ShopManageGroupEntity group = new ShopManageGroupEntity();
group.setId(id);
group.setGroupName(name);
group.setPlatform("jd");
return group;
}
+81
View File
@@ -0,0 +1,81 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { existsSync, readFileSync, readdirSync } from 'node:fs'
import { join } from 'node:path'
/** v1.5 京东发布用户端契约(蓝图 docs/ITERATION_PLAN.md §1 AC-9 / §3 / §4 Phase 4)。
*
* 两组:
* 1. **立即生效**(AC-9 前端绊线,B113-01):`/api/jd-collect/groups` 是京东分类的
* 唯一读取口——全 src 不得出现第三个裸 URL 消费点;发布页要分类数据必须走
* endpoints.jdCollect.groups 的既有 fetch 函数(出现第二个分类口即红)。
* 2. **Pending Phase 4**(每支带 skip):JdPublishTab(分类→商品→改价→建单→实时面板)
* 落地后移除对应 skip 跑绿——蓝图 §4 Phase 4【待激活验收测试】登记的就是这份清单。
*/
const ROOT = process.cwd()
function read(relativePath: string, what: string): string {
const path = join(ROOT, relativePath)
assert.ok(existsSync(path), `${what} 尚未落地(蓝图 §4 Phase 4):${path}`)
return readFileSync(path, 'utf8')
}
/** 递归收集 src 下 .ts/.vue 源文件 */
function collectSourceFiles(dir: string, acc: string[] = []): string[] {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const full = join(dir, entry.name)
if (entry.isDirectory()) collectSourceFiles(full, acc)
else if (/\.(ts|vue)$/.test(entry.name)) acc.push(full)
}
return acc
}
// ---------------------------------------------------------- AC-9 前端绊线(立即生效)
test('AC-9: 京东分类读取口全 src 唯一(B113-01 绊线)', () => {
const hits = collectSourceFiles(join(ROOT, 'src'))
.filter((f) => readFileSync(f, 'utf8').includes('jd-collect/groups'))
.map((f) => f.replace(/\\/g, '/').replace(ROOT.replace(/\\/g, '/') + '/', ''))
assert.deepEqual(hits.sort(), [
'src/shared/api/endpoints.ts',
'src/shared/api/types/modules/jd-collect.ts',
], 'B113-01:/api/jd-collect/groups 是京东分类唯一读取口——发布页要分类必须消费 endpoints.jdCollect.groups 既有出口,不得新增裸 URL 消费点')
})
// ---------------------------------------------------------- Pending Phase 4
test('AC-9: JdPublishTab 分类选择消费唯一 groups 出口', { skip: 'Pending Phase 4: JdPublishTab 落地后移除 skip' }, () => {
const tab = read('src/pages/jd/JdPublishTab.vue', '商品上架页')
assert.ok(tab.includes('jdCollect'), 'JdPublishTab 的分类数据必须走 endpoints.jdCollect/groups 既有 fetch(AC-9),不得自拼 URL')
assert.ok(!tab.includes('jd-collect/groups'), 'JdPublishTab 不得裸写分类 URL(B113-01 绊线)')
})
test('AC-9: 商品列表只拉归属当前用户的行(owner 过滤)', { skip: 'Pending Phase 4: JdPublishTab 落地后移除 skip' }, () => {
const tab = read('src/pages/jd/JdPublishTab.vue', '商品上架页')
assert.ok(tab.includes('productIds') || tab.includes('productId'),
'JdPublishTab 建单提交必须携带勾选的商品 id 集合(服务端按 owner 校验,跨用户商品 0 返回)')
})
test('建单请求体形状:categoryId + productIds + priceRule{mode,value}', { skip: 'Pending Phase 4: JdPublishTab 落地后移除 skip' }, () => {
const tab = read('src/pages/jd/JdPublishTab.vue', '商品上架页')
// 蓝图 §3 死契约:POST /api/jd-publish/tasks 请求体 {categoryId, productIds[], priceRule:{mode,value?}}
assert.ok(tab.includes('categoryId'), '建单体缺 categoryId(所选自定义分类)')
assert.ok(tab.includes('priceRule'), '建单体缺 priceRule(统一改价规则;mode: none|percent|fixed)')
assert.ok(tab.includes("'percent'") && tab.includes("'fixed'") && tab.includes("'none'"),
'priceRule.mode 三档(none/percent/fixed)必须与蓝图 §3 同值')
})
test('endpoints 注册 jdPublish 端点组(建单/items/chunk 三件)', { skip: 'Pending Phase 4: endpoints 扩组后移除 skip' }, () => {
const endpoints = read('src/shared/api/endpoints.ts', 'endpoints.ts')
assert.ok(endpoints.includes('jdPublish'), 'endpoints.ts 缺 jdPublish 端点组')
assert.ok(endpoints.includes('/api/jd-publish/tasks'), 'jdPublish 组缺建单端点 /api/jd-publish/tasks')
})
test('商品上架占位卡转正式:jd-publish 卡挂 /jd-publish 路由', { skip: 'Pending Phase 4: 占位卡转正式时移除 skip(须同步改 jd-console-tool-catalog.test.ts 的占位锁)' }, () => {
const catalog = read('src/pages/jd/tool-catalog.ts', 'jd/tool-catalog.ts')
const router = read('src/router/index.ts', 'router/index.ts')
assert.ok(/id:\s*'jd-publish'[\s\S]*?href:\s*'\/jd-publish'/.test(catalog),
'jd-publish 卡须补 href 指向 /jd-publish(转正式)')
assert.ok(router.includes("path: '/jd-publish'"), 'router 缺 /jd-publish 路由')
})