Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ed644384cc | |||
| ee613db05b | |||
| dc3e7f3b37 | |||
| db71803430 | |||
| 848fef3b03 | |||
| 5c7a310ee7 | |||
| 764eeb2914 | |||
| 0f8b37e279 | |||
| 71b19e4f69 |
@@ -15,6 +15,8 @@ export interface CompanyItem {
|
||||
remark: string | null
|
||||
createdAt: string | null
|
||||
updatedAt: string | null
|
||||
/** 所属平台(V206):'amazon'|'jd';后端恒带值(列 NOT NULL DEFAULT 'amazon'),旧负载缺省不渲染。 */
|
||||
platform?: string
|
||||
}
|
||||
|
||||
/** 新建/改名的表单草稿。 */
|
||||
@@ -22,6 +24,8 @@ export interface CompanyDraft {
|
||||
companyName: string
|
||||
status?: number
|
||||
remark?: string | null
|
||||
/** 所属平台(V206):新建必带(页面从平台 tab 取),编辑显式下发,缺省后端不动。 */
|
||||
platform?: string
|
||||
}
|
||||
|
||||
export function text(value: unknown): string {
|
||||
@@ -48,5 +52,6 @@ export function toCompanyPayload(draft: CompanyDraft): Record<string, unknown> {
|
||||
const payload: Record<string, unknown> = { companyName: text(draft.companyName).trim() }
|
||||
if (typeof draft.status === 'number') payload.status = draft.status
|
||||
payload.remark = trimmedOrNull(draft.remark)
|
||||
if (draft.platform) payload.platform = draft.platform
|
||||
return payload
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ export function toCompanyItem(raw: unknown): CompanyItem | null {
|
||||
const r = raw as Record<string, unknown>
|
||||
const id = numberOrNull(r.id)
|
||||
if (id === null) return null
|
||||
return {
|
||||
const item: CompanyItem = {
|
||||
id,
|
||||
companyName: text(r.company_name),
|
||||
// status 列 NOT NULL,取不到就是链路异常;未知一律按停用,不把异常状态当启用。
|
||||
@@ -27,6 +27,10 @@ export function toCompanyItem(raw: unknown): CompanyItem | null {
|
||||
createdAt: trimmedOrNull(r.created_at),
|
||||
updatedAt: trimmedOrNull(r.updated_at),
|
||||
}
|
||||
// platform 后端恒带(列 NOT NULL);旧负载/测试桩缺省就不渲染该键,字段形状与 users-model 一致。
|
||||
const platform = text(r.platform)
|
||||
if (platform) item.platform = platform
|
||||
return item
|
||||
}
|
||||
|
||||
/** 解析 GET /api/admin/companies:接受 data 为数组或 {items:[...]},success=false 抛后端文案。 */
|
||||
|
||||
@@ -4,8 +4,10 @@ import { toCompanyPayload, type CompanyDraft, type CompanyItem } from './compani
|
||||
|
||||
/** 公司目录(设计文档 §2.3)。GET 的可见范围由后端收窄:超管全部、公司内 admin 只自己公司。 */
|
||||
|
||||
export async function fetchCompanies(): Promise<CompanyItem[]> {
|
||||
const { data } = await http.get('/api/admin/companies')
|
||||
export async function fetchCompanies(platform?: string): Promise<CompanyItem[]> {
|
||||
const { data } = await http.get('/api/admin/companies', {
|
||||
params: platform ? { platform } : {},
|
||||
})
|
||||
return parseCompanyList(data)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
import { http } from './http'
|
||||
import { unwrap } from './envelope'
|
||||
|
||||
/** 任务证据件列表行(AC-13:后管只读面,仅超级管理员)。 */
|
||||
export interface TaskEvidenceRow {
|
||||
id: number
|
||||
taskId: string
|
||||
uid: number | null
|
||||
evidenceType: string
|
||||
source: string
|
||||
objectKey: string
|
||||
byteSize: number
|
||||
contentType: string
|
||||
sha256: string
|
||||
createdAt: string | null
|
||||
}
|
||||
|
||||
export interface TaskEvidencePage {
|
||||
items: TaskEvidenceRow[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
export interface TaskEvidenceQuery {
|
||||
taskId?: string
|
||||
uid?: number
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
export interface TaskEvidenceContent {
|
||||
id: number
|
||||
taskId: string
|
||||
contentType: string
|
||||
binary: boolean
|
||||
content: string
|
||||
}
|
||||
|
||||
export async function fetchTaskEvidenceFiles(params: TaskEvidenceQuery): Promise<TaskEvidencePage> {
|
||||
const query: Record<string, string | number> = { page: params.page, pageSize: params.pageSize }
|
||||
if (params.taskId) query.taskId = params.taskId
|
||||
if (params.uid) query.uid = params.uid
|
||||
const { data } = await http.get('/api/admin/task-evidence/files', { params: query })
|
||||
return unwrap<TaskEvidencePage>(data)
|
||||
}
|
||||
|
||||
export async function fetchTaskEvidenceContent(fileId: number): Promise<TaskEvidenceContent> {
|
||||
const { data } = await http.get('/api/admin/task-evidence/content', { params: { fileId } })
|
||||
return unwrap<TaskEvidenceContent>(data)
|
||||
}
|
||||
|
||||
/** 下载走服务端流,不把对象直链/预签名 URL 交给浏览器(AC-13 的不入日志口径)。 */
|
||||
export function taskEvidenceDownloadUrl(fileId: number): string {
|
||||
return `/api/admin/task-evidence/download?fileId=${fileId}`
|
||||
}
|
||||
|
||||
export async function deleteTaskEvidence(ids: number[]): Promise<number> {
|
||||
const { data } = await http.post('/api/admin/task-evidence/delete', ids)
|
||||
return unwrap<{ deleted: number }>(data).deleted
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
/** 用户管理列表/分页 DTO(任务 41):纯逻辑,无框架依赖,与 Java AdminUserController 对齐。 */
|
||||
import type { AdminUser } from '../types/admin'
|
||||
import type { PlatformTabId } from '../config/platform-scope.ts'
|
||||
|
||||
export const USER_PAGE_DEFAULT_SIZE = 10
|
||||
export const USER_PAGE_MIN_PAGE = 1
|
||||
@@ -18,6 +19,8 @@ export interface UserListParams {
|
||||
/** 公司 tab 的当前公司;由页面从 store 传入,**不住在 UserFilterState 里**
|
||||
* (normalizeUserPageParams 白名单构造会把它丢掉,取值口只认 fetchUserList 的原始入参)。 */
|
||||
companyId?: number | null
|
||||
/** 平台 tab 的当前平台(V206);同 companyId 形状:白名单构造不收,从原始入参读。 */
|
||||
platform?: PlatformTabId
|
||||
}
|
||||
|
||||
/** 序列化到 GET /api/admin/users 的查询参数(Java snake_case)。 */
|
||||
@@ -30,6 +33,7 @@ export interface UserListQuery {
|
||||
admin_id?: number
|
||||
role?: string
|
||||
company_id?: number
|
||||
platform?: string
|
||||
}
|
||||
|
||||
/** 用户列表项即 AdminUser(与 Java AdminUserItemVo 字段对齐)。 */
|
||||
|
||||
@@ -18,6 +18,10 @@ export function toAdminUserItem(raw: unknown): AdminUser | null {
|
||||
const id = numberOrNull(r.id)
|
||||
if (id === null) return null
|
||||
const item: AdminUser = { id, username: text(r.username), role: text(r.role) }
|
||||
const quota = numberOrNull(r.jd_publish_quota)
|
||||
if (quota !== null) item.jdPublishQuota = quota
|
||||
const platform = text(r.platform)
|
||||
if (platform) item.platform = platform
|
||||
if (typeof r.is_admin === 'boolean') item.isAdmin = r.is_admin
|
||||
const createdById = numberOrNull(r.created_by_id)
|
||||
if (createdById !== null) item.createdById = createdById
|
||||
|
||||
@@ -15,6 +15,8 @@ export async function fetchUserList(params: Partial<UserListParams> = {}): Promi
|
||||
// normalizeUserPageParams 是白名单构造(只点名 page/pageSize/keyword/createdById/adminId/role),
|
||||
// 公司值必须从原始 params 读:写成 normalized.companyId 会 TS 绿、运行时恒 undefined。
|
||||
if (params.companyId != null) query.company_id = params.companyId
|
||||
// 平台值(V206)同 companyId 形状:白名单构造不收,只认原始入参。
|
||||
if (params.platform) query.platform = params.platform
|
||||
const { data } = await http.get('/api/admin/users', { params: query })
|
||||
return parseUserPage(data)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* 而护栏用例要从这里反过来读注册表,放在一起会成环。 */
|
||||
|
||||
/** 角色内在闸门:只有超管可见可读写,与 user_column_permission 无关。 */
|
||||
export const SUPER_ADMIN_ONLY_MENU_KEYS: readonly string[] = ['admin_companies', 'admin_task_evidence']
|
||||
export const SUPER_ADMIN_ONLY_MENU_KEYS: readonly string[] = ['admin_companies']
|
||||
|
||||
export interface CompanyScopedPage {
|
||||
/** 与 routes.ts 的 menuKey 逐字一致。 */
|
||||
|
||||
@@ -15,20 +15,28 @@ export const PLATFORM_TABS: readonly PlatformTabDef[] = [
|
||||
{ id: 'jd', label: '京东' },
|
||||
]
|
||||
|
||||
/** 京东侧菜单的 menuKey 唯一清单(与 routes.ts 的 menuKey 逐字一致,用例钉住)。
|
||||
* 2026-11-16 用户按截图圈定四项;2026-11-17 加京东分类管理(用户口径「这边分组是
|
||||
* 京东的分组管理的而不是亚马逊的」——分类管理子菜单归京东侧,不与亚马逊侧混排)。
|
||||
/** 京东侧独占菜单的 menuKey 唯一清单(与 routes.ts 的 menuKey 逐字一致,用例钉住)。
|
||||
* 2026-11-17 晚:分类管理子菜单(admin_jd_category_manage,V204)随「京东分类管理并到
|
||||
* 京东数据库分类编辑里」用户口径整体下线(页/路由/菜单行 V208 删),key 从清单摘除。
|
||||
* 后续京东新页面上线把 key 加进这里即可,清单外的 key(含店铺管理/生成记录等
|
||||
* 存量页)一律归亚马逊。 */
|
||||
* 存量页)一律归亚马逊或双侧清单。 */
|
||||
export const JD_MENU_KEYS: readonly string[] = [
|
||||
'admin_jd_database',
|
||||
]
|
||||
|
||||
/** 双侧共用菜单(2026-11-17 用户口径「这些亚马逊这边也要有」):三个账号域页面在两个
|
||||
* 平台 tab 下都显示——同一套组件、按当前 tab 给接口传 platform,各自只看/管各自平台的
|
||||
* 账号、分组、公司(后端 V206 三表加列,存量默认亚马逊,京东侧数据在编辑弹窗里翻档)。 */
|
||||
export const BOTH_PLATFORM_MENU_KEYS: readonly string[] = [
|
||||
'admin_users',
|
||||
'admin_group_manage',
|
||||
'admin_companies',
|
||||
'admin_jd_database',
|
||||
'admin_jd_category_manage',
|
||||
]
|
||||
|
||||
/** menuKey → 平台归属:命中京东清单即 jd,其余(未知 key 在内)默认亚马逊。 */
|
||||
export function platformOfMenuKey(key: string): PlatformTabId {
|
||||
return JD_MENU_KEYS.includes(key) ? 'jd' : 'amazon'
|
||||
/** menuKey → 平台归属清单(唯一判定出口):京东独占 → ['jd'];双侧清单 → ['amazon','jd'];
|
||||
* 其余(未知 key 在内)默认亚马逊。 */
|
||||
export function platformsOfMenuKey(key: string): PlatformTabId[] {
|
||||
if (JD_MENU_KEYS.includes(key)) return ['jd']
|
||||
if (BOTH_PLATFORM_MENU_KEYS.includes(key)) return ['amazon', 'jd']
|
||||
return ['amazon']
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { joinAdminPath } from '@/config/app'
|
||||
import { pageTitleOf, topbarUserOf } from '@/layout/topbar-model'
|
||||
import { groupKeysForActive, toSidebarEntries } from '@/layout/menu-mapper'
|
||||
import { filterMenuTreeByPlatform, visiblePlatformsFor } from '@/layout/platform-menu-filter'
|
||||
import { PLATFORM_TABS, platformOfMenuKey } from '@/config/platform-scope'
|
||||
import { PLATFORM_TABS, platformsOfMenuKey } from '@/config/platform-scope'
|
||||
import { usePlatformTabStore } from '@/stores/platform-tab'
|
||||
import { firstVisiblePath } from '@/router/helpers'
|
||||
import {
|
||||
@@ -58,12 +58,15 @@ watch(
|
||||
)
|
||||
|
||||
// 直达 URL/面包屑跳到另一平台的页面时,tab 指示自动跟过去(与侧边栏保持一致)。
|
||||
// 双侧清单里的页面(账号域三页)两个 tab 都算归属:当前 tab 已含它就不动。
|
||||
watch(
|
||||
() => route.meta.menuKey as string | undefined,
|
||||
(menuKey) => {
|
||||
if (!menuKey) return
|
||||
const target = platformOfMenuKey(menuKey)
|
||||
if (target !== platformTab.active && visibleTabIds.value.includes(target)) {
|
||||
const owners = platformsOfMenuKey(menuKey)
|
||||
if (owners.includes(platformTab.active)) return
|
||||
const target = owners.find((platform) => visibleTabIds.value.includes(platform))
|
||||
if (target && target !== platformTab.active) {
|
||||
platformTab.setActive(target)
|
||||
}
|
||||
},
|
||||
@@ -71,11 +74,12 @@ watch(
|
||||
)
|
||||
|
||||
// 切到另一侧 tab 时当前页多半不在那边:跳到该侧第一个可见页;该侧为空(tab 不可见)则不动。
|
||||
// 双侧清单里的页面(账号域三页)切 tab 不跳转——页面自己按当前平台过滤数据。
|
||||
watch(
|
||||
() => platformTab.active,
|
||||
(tab) => {
|
||||
const menuKey = route.meta.menuKey as string | undefined
|
||||
if (!menuKey || platformOfMenuKey(menuKey) === tab) return
|
||||
if (!menuKey || platformsOfMenuKey(menuKey).includes(tab)) return
|
||||
const first = firstVisiblePath(filterMenuTreeByPlatform(session.menuTree, tab))
|
||||
if (first) void router.replace(first)
|
||||
},
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -109,10 +109,6 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
|
||||
text: '桌面客户端与麦象采集机上报的日志按来源、日期和关键字筛选;可查看日志尾部、下载完整文件或删除云端记录,云端日志按保留期自动清理。',
|
||||
steps: ['选择来源与日期', '查看或下载日志', '必要时删除'],
|
||||
},
|
||||
admin_task_evidence: {
|
||||
text: '任务异常现场件与窗口图按任务号关联;只有超级管理员能读取与下载,对象直链不出服务端,证据件按保留期自动清理。',
|
||||
steps: ['按任务号或 uid 查询', '查看现场件或窗口图', '下载或清理过期证据'],
|
||||
},
|
||||
admin_user_secret_usage: {
|
||||
text: '按日期范围统计各用户的密钥调用次数(货源查询与外观专利按 LLM 请求次数、代理按提取次数),用于评估用户资源损耗。',
|
||||
steps: ['选择日期范围', '筛选用户或分组', '核对各模块次数'],
|
||||
@@ -126,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: ['筛选商品记录', '查看属性与图片明细', '用「分类管理」维护分类并批量归类'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { AdminMenuNode } from '../types/admin'
|
||||
import { PLATFORM_TABS, platformOfMenuKey } from '../config/platform-scope.ts'
|
||||
import { PLATFORM_TABS, platformsOfMenuKey } from '../config/platform-scope.ts'
|
||||
import type { PlatformTabId } from '../config/platform-scope.ts'
|
||||
import { firstVisiblePath } from '../router/helpers.ts'
|
||||
|
||||
@@ -7,10 +7,11 @@ import { firstVisiblePath } from '../router/helpers.ts'
|
||||
* 按平台 tab 过滤后端菜单树(2026-11-16「亚马逊/京东不混」):**只做显示分组,不做鉴权**——
|
||||
* 准入仍由 session.menuTree(后端按权限裁剪)与路由守卫负责,这里只是把当前用户已被授权的
|
||||
* 菜单按平台分到两个 tab 下展示。
|
||||
* 规则:叶子按 platformOfMenuKey(key) 留下;分组节点(admin_group_*)自身的 key 不参与平台
|
||||
* 判定,按「留住的子项数 > 0」决定去留——否则京东 tab 下「账号与权限」这类混合分组会被整组
|
||||
* 误剪。节点的 key/name/route/children 形状原样透传(浅拷贝不改写),toSidebarEntries、
|
||||
* groupKeysForActive 与面包屑都不受影响。
|
||||
* 规则:叶子按 platformsOfMenuKey(key) 是否包含当前平台留下(双侧清单里的账号域三页两个
|
||||
* tab 都显示);分组节点(admin_group_*)自身的 key 不参与平台判定,按「留住的子项数 > 0」
|
||||
* 决定去留——否则京东 tab 下「账号与权限」这类混合分组会被整组误剪。节点的 key/name/
|
||||
* route/children 形状原样透传(浅拷贝不改写),toSidebarEntries、groupKeysForActive 与
|
||||
* 面包屑都不受影响。
|
||||
*/
|
||||
export function filterMenuTreeByPlatform(
|
||||
nodes: AdminMenuNode[] | null | undefined,
|
||||
@@ -24,7 +25,7 @@ export function filterMenuTreeByPlatform(
|
||||
continue
|
||||
}
|
||||
if ((node.children || []).length > 0) continue
|
||||
if (platformOfMenuKey(node.key || '') === platform) filtered.push({ ...node })
|
||||
if (platformsOfMenuKey(node.key || '').includes(platform)) filtered.push({ ...node })
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
@@ -2,18 +2,25 @@
|
||||
/** 公司管理(设计文档 §2.3):列表 + 新建 + 改名/启停。
|
||||
* 可见范围由后端收窄(超管全部、公司内 admin 只自己公司);写操作仅超管,这里隐藏入口只是配合,
|
||||
* 真正的把关在 CompanyController,页面不得当作权限边界。 */
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
|
||||
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'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
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[]>([])
|
||||
@@ -38,7 +45,7 @@ async function loadCompanies() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
rows.value = await fetchCompanies()
|
||||
rows.value = await fetchCompanies(platformTab.active)
|
||||
} catch (error) {
|
||||
loadFailure.value = error instanceof Error ? error.message : '公司列表加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
@@ -57,6 +64,21 @@ 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
|
||||
void loadCompanies()
|
||||
})
|
||||
|
||||
onMounted(loadCompanies)
|
||||
</script>
|
||||
|
||||
@@ -127,7 +149,7 @@ onMounted(loadCompanies)
|
||||
/>
|
||||
</section>
|
||||
|
||||
<CompanyEditorDialog v-model="editorVisible" :company="editingCompany" @saved="loadCompanies" />
|
||||
<CompanyEditorDialog v-model="editorVisible" :company="editingCompany" :platform="platformTab.active" @saved="onCompaniesSaved" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import type { PlatformTabId } from '@/config/platform-scope'
|
||||
import { createCompany, updateCompany } from '@/api/companies'
|
||||
import {
|
||||
COMPANY_NAME_MAX_LENGTH,
|
||||
@@ -12,11 +13,11 @@ import {
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { actionableErrorText } from '@/components/admin-feedback'
|
||||
|
||||
/** 新建/编辑公司(改名 + 启停 + 备注);写操作仅超管可用,权限由后端把关。 */
|
||||
const props = defineProps<{ modelValue: boolean; company: CompanyItem | null }>()
|
||||
/** 新建/编辑公司(改名 + 启停 + 备注 + 所属平台 V206);写操作仅超管可用,权限由后端把关。 */
|
||||
const props = defineProps<{ modelValue: boolean; company: CompanyItem | null; platform?: PlatformTabId }>()
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'saved'): void }>()
|
||||
|
||||
const form = ref<CompanyDraft>({ companyName: '', status: COMPANY_STATUS_ACTIVE, remark: '' })
|
||||
const form = ref<CompanyDraft>({ companyName: '', status: COMPANY_STATUS_ACTIVE, remark: '', platform: 'amazon' })
|
||||
const errorText = ref('')
|
||||
const busy = ref(false)
|
||||
|
||||
@@ -25,8 +26,13 @@ watch(
|
||||
(open) => {
|
||||
if (!open) return
|
||||
form.value = props.company
|
||||
? { companyName: props.company.companyName, status: props.company.status, remark: props.company.remark || '' }
|
||||
: { companyName: '', status: COMPANY_STATUS_ACTIVE, remark: '' }
|
||||
? {
|
||||
companyName: props.company.companyName,
|
||||
status: props.company.status,
|
||||
remark: props.company.remark || '',
|
||||
platform: props.company.platform === 'jd' ? 'jd' : 'amazon',
|
||||
}
|
||||
: { companyName: '', status: COMPANY_STATUS_ACTIVE, remark: '', platform: props.platform ?? 'amazon' }
|
||||
errorText.value = ''
|
||||
},
|
||||
)
|
||||
@@ -71,6 +77,12 @@ async function save() {
|
||||
placeholder="请输入公司名称(全平台唯一)"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="所属平台">
|
||||
<el-radio-group v-model="form.platform">
|
||||
<el-radio-button value="amazon">亚马逊</el-radio-button>
|
||||
<el-radio-button value="jd">京东</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="状态">
|
||||
<el-select v-model="form.status" style="width: 100%">
|
||||
<el-option :value="COMPANY_STATUS_ACTIVE" label="启用" />
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import type { PlatformTabId } from '@/config/platform-scope'
|
||||
import { submitCreateUser } from './user-create-adapter'
|
||||
import {
|
||||
createEmptyCreateUserForm,
|
||||
@@ -28,6 +29,8 @@ const props = defineProps<{
|
||||
operatorCompanyId?: number | null
|
||||
/** 当前公司 tab:这次建号落在哪家,就决定能建哪些角色。 */
|
||||
activeCompanyId?: number | null
|
||||
/** 当前平台 tab(V206):新号默认落当前平台,单选可改。 */
|
||||
platform?: PlatformTabId
|
||||
}>()
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'created'): void }>()
|
||||
|
||||
@@ -71,6 +74,8 @@ watch(
|
||||
form.expiresAt = ''
|
||||
// 预填当前 tab:跨公司时角色本来就只剩公司超管,而那一例必须带公司
|
||||
form.companyId = props.activeCompanyId ?? null
|
||||
// 预填当前平台 tab(V206):京东侧建的号默认归京东,亚马逊侧默认亚马逊。
|
||||
form.platform = props.platform ?? 'amazon'
|
||||
errors.username = undefined
|
||||
errors.password = undefined
|
||||
errors.companyId = undefined
|
||||
@@ -131,6 +136,12 @@ async function create(): Promise<void> {
|
||||
<el-option v-for="opt in roleChoices" :key="opt.value" :label="opt.label" :value="opt.value" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="所属平台">
|
||||
<el-radio-group v-model="form.platform">
|
||||
<el-radio-button value="amazon">亚马逊</el-radio-button>
|
||||
<el-radio-button value="jd">京东</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item
|
||||
v-if="operatorSuper && form.role === 'company_super_admin'"
|
||||
label="所属公司"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import type { AdminUser } from '@/types/admin'
|
||||
import type { PlatformTabId } from '@/config/platform-scope'
|
||||
import { mayCarryOwnExpiry } from './user-create-model'
|
||||
import { fillEditUserForm, validateEditUserForm, type EditUserForm, type EditUserFormErrors } from './user-edit-model'
|
||||
import { submitEditUser } from './user-edit-adapter'
|
||||
@@ -10,11 +11,12 @@ import { actionableErrorText } from '@/components/admin-feedback'
|
||||
import UserMenuAuthTree from './UserMenuAuthTree.vue'
|
||||
|
||||
/** companyId 由 UsersPage 把 companyTab.requestCompanyId 透传进来(本页的用户列表本来就由它筛 ⇒ 目标账号的公司
|
||||
* 就是 tab 选中的那家);弹窗自己不读 store,公司 tab 的取值口只留在页面组件那一处。 */
|
||||
const props = defineProps<{ modelValue: boolean; user: AdminUser | null; operatorSuper?: boolean; companyId?: number | null }>()
|
||||
* 就是 tab 选中的那家);弹窗自己不读 store,公司 tab 的取值口只留在页面组件那一处。
|
||||
* platform(V206)同理由页面透传:决定上架上限是否参与校验/下发(仅京东侧)。 */
|
||||
const props = defineProps<{ modelValue: boolean; user: AdminUser | null; operatorSuper?: boolean; companyId?: number | null; platform?: PlatformTabId }>()
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'updated'): void }>()
|
||||
|
||||
const form = reactive<EditUserForm>({ uid: 0, username: '', password: '', role: 'normal', columnIds: [], originalRole: '', expiresAt: '' })
|
||||
const form = reactive<EditUserForm>({ uid: 0, username: '', password: '', role: 'normal', columnIds: [], originalRole: '', expiresAt: '', jdPublishQuota: 5000, platform: 'amazon' })
|
||||
const errors = reactive<EditUserFormErrors>({})
|
||||
const busy = ref(false)
|
||||
const loadingAuth = ref(false)
|
||||
@@ -22,6 +24,9 @@ const loadingAuth = ref(false)
|
||||
const authReady = ref(false)
|
||||
/** 公司超管目标:角色单选隐藏(请求体也不带 role),只允许改密码/到期时间/菜单。 */
|
||||
const targetIsCompanySuperAdmin = computed(() => (props.user?.role || '').trim().toLowerCase() === 'company_super_admin')
|
||||
/** 上架上限只属京东口径(用户 2026-11-17:「只要在京东这边用户编辑里加就行,不需要在亚马逊那边」):
|
||||
* 亚马逊侧隐藏该项,且校验与下发都不带 quota——字段留后端不动。 */
|
||||
const includeQuota = computed(() => props.platform === 'jd')
|
||||
/** 公司超管目标的角色单选是隐藏的(改完仍是 company_super_admin),到期时间照旧可改;
|
||||
* 管理员改成普通账号时这一项消失,保存按「清空」下发(见 user-edit-model 的 roleAfter)。 */
|
||||
const expiryEditable = computed(() =>
|
||||
@@ -40,6 +45,9 @@ watch(
|
||||
form.columnIds = []
|
||||
form.originalRole = base.originalRole
|
||||
form.expiresAt = base.expiresAt
|
||||
form.jdPublishQuota = base.jdPublishQuota
|
||||
form.platform = base.platform
|
||||
errors.jdPublishQuota = undefined
|
||||
errors.password = undefined
|
||||
authReady.value = false
|
||||
void refreshAuth()
|
||||
@@ -71,12 +79,12 @@ async function save(): Promise<void> {
|
||||
showAdminFeedback('菜单权限尚未加载完成,请稍后重试', 'error')
|
||||
return
|
||||
}
|
||||
const { valid, errors: errs } = validateEditUserForm(form)
|
||||
const { valid, errors: errs } = validateEditUserForm(form, { includeQuota: includeQuota.value })
|
||||
Object.assign(errors, errs)
|
||||
if (!valid) return
|
||||
busy.value = true
|
||||
try {
|
||||
await submitEditUser(form)
|
||||
await submitEditUser(form, { includeQuota: includeQuota.value })
|
||||
showAdminFeedback('更新成功', 'success')
|
||||
emit('updated')
|
||||
close()
|
||||
@@ -120,6 +128,12 @@ async function save(): Promise<void> {
|
||||
<el-form-item v-if="targetIsCompanySuperAdmin" label="角色">
|
||||
<el-input model-value="公司超级管理员" readonly />
|
||||
</el-form-item>
|
||||
<el-form-item label="所属平台">
|
||||
<el-radio-group v-model="form.platform">
|
||||
<el-radio-button value="amazon">亚马逊</el-radio-button>
|
||||
<el-radio-button value="jd">京东</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="expiryEditable" label="到期时间(清空 = 永不过期;到期后该账号及其名下账号将停用)">
|
||||
<el-date-picker
|
||||
v-model="form.expiresAt"
|
||||
@@ -130,6 +144,9 @@ async function save(): Promise<void> {
|
||||
style="width: 240px"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="includeQuota && (targetIsCompanySuperAdmin || form.role === 'admin')" label="京东上架额度(0 表示不限)" :error="errors.jdPublishQuota">
|
||||
<el-input-number v-model="form.jdPublishQuota" :min="0" :max="2147483647" :precision="0" />
|
||||
</el-form-item>
|
||||
<el-form-item v-if="props.user && props.user.creatorUsername" label="所属管理员">
|
||||
<el-input :model-value="props.user.creatorUsername" readonly />
|
||||
</el-form-item>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import type { AdminUser } from '@/types/admin'
|
||||
import type { PlatformTabId } from '@/config/platform-scope'
|
||||
import {
|
||||
eligibleGroupMembers,
|
||||
groupMemberCandidateHint,
|
||||
@@ -13,11 +14,13 @@ import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { actionableErrorText } from '@/components/admin-feedback'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
|
||||
const props = defineProps<{ modelValue: boolean; group: ShopGroupItem | null; operatorSuper?: boolean }>()
|
||||
const props = defineProps<{ modelValue: boolean; group: ShopGroupItem | null; operatorSuper?: boolean; platform?: PlatformTabId }>()
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'saved'): void }>()
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const groupName = ref('')
|
||||
/** 所属平台(V206):新建默认当前平台 tab,编辑回填分组原值,单选可翻档。 */
|
||||
const groupPlatform = ref<PlatformTabId>('amazon')
|
||||
const memberIds = ref<number[]>([])
|
||||
const errorText = ref('')
|
||||
const busy = ref(false)
|
||||
@@ -48,6 +51,9 @@ watch(
|
||||
if (props.group) {
|
||||
groupName.value = props.group.name
|
||||
memberIds.value = props.group.memberUserIds ?? []
|
||||
groupPlatform.value = props.group.platform === 'jd' ? 'jd' : 'amazon'
|
||||
} else {
|
||||
groupPlatform.value = props.platform ?? 'amazon'
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -76,7 +82,7 @@ async function save(): Promise<void> {
|
||||
busy.value = true
|
||||
try {
|
||||
if (props.group) {
|
||||
await updateShopGroup(props.group.id, groupName.value, memberIds.value)
|
||||
await updateShopGroup(props.group.id, groupName.value, memberIds.value, groupPlatform.value)
|
||||
showAdminFeedback('更新成功', 'success')
|
||||
} else {
|
||||
// 对齐 admin:组长恒为当前登录用户,提交 createdBy=当前用户 id。
|
||||
@@ -85,7 +91,7 @@ async function save(): Promise<void> {
|
||||
showAdminFeedback('无法获取当前登录用户,请重新登录', 'error')
|
||||
return
|
||||
}
|
||||
await createShopGroup(groupName.value, memberIds.value, operatorId)
|
||||
await createShopGroup(groupName.value, memberIds.value, operatorId, groupPlatform.value)
|
||||
showAdminFeedback('创建成功', 'success')
|
||||
}
|
||||
emit('saved')
|
||||
@@ -113,6 +119,12 @@ onMounted(loadCandidates)
|
||||
<el-form-item label="分组名称" :error="errorText || undefined">
|
||||
<el-input v-model="groupName" placeholder="请输入分组名称" />
|
||||
</el-form-item>
|
||||
<el-form-item label="所属平台">
|
||||
<el-radio-group v-model="groupPlatform">
|
||||
<el-radio-button value="amazon">亚马逊</el-radio-button>
|
||||
<el-radio-button value="jd">京东</el-radio-button>
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
<el-form-item label="组长">
|
||||
<el-input :model-value="leaderUsername" readonly placeholder="当前登录用户" />
|
||||
</el-form-item>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { usePlatformTabStore } from '@/stores/platform-tab'
|
||||
import { openAdminConfirm } from '@/components/admin-confirm'
|
||||
import { deleteShopGroup, fetchShopGroups } from './shop-group-api'
|
||||
import type { ShopGroupItem } from './shop-group-model'
|
||||
@@ -16,6 +17,8 @@ import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const companyTab = useCompanyTabStore()
|
||||
// 平台 tab(V206):分组列表按当前平台过滤,新建默认落当前平台。
|
||||
const platformTab = usePlatformTabStore()
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const rows = ref<ShopGroupItem[]>([])
|
||||
@@ -52,7 +55,7 @@ async function loadGroups() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
rows.value = await fetchShopGroups(companyTab.requestCompanyId)
|
||||
rows.value = await fetchShopGroups(companyTab.requestCompanyId, platformTab.active)
|
||||
} catch (error) {
|
||||
loadFailure.value = error instanceof Error ? error.message : '数据权限分组加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
@@ -64,6 +67,12 @@ async function loadGroups() {
|
||||
// 切公司 = 重新取数(G1 的 pageFiles 断言盯着这一条)。
|
||||
watch(() => companyTab.activeId, () => void loadGroups())
|
||||
|
||||
// 切平台 tab(V206)= 重新取数:分组归属按平台分列,两 tab 各看各的分组。
|
||||
watch(() => platformTab.active, () => {
|
||||
page.value = 1
|
||||
void loadGroups()
|
||||
})
|
||||
|
||||
function openCreate() {
|
||||
editingGroup.value = null
|
||||
editorVisible.value = true
|
||||
@@ -164,6 +173,7 @@ onMounted(loadGroups)
|
||||
v-model="editorVisible"
|
||||
:group="editingGroup"
|
||||
:operator-super="isSuperAdmin"
|
||||
:platform="platformTab.active"
|
||||
@saved="loadGroups"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { AdminUser } from '@/types/admin'
|
||||
import { roleLabel } from '@/types/admin'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { useCompanyTabStore } from '@/stores/company-tab'
|
||||
import { usePlatformTabStore } from '@/stores/platform-tab'
|
||||
import { deleteUser, fetchUserList, setUserDisabled } from '@/api/users'
|
||||
import { fetchCompanies } from '@/api/companies'
|
||||
import { createUserFilterState, toUserListParams, type UserFilterState } from './users-filter'
|
||||
@@ -26,6 +27,10 @@ import { createLatestRequestGate } from '@/utils/latest-request'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const companyTab = useCompanyTabStore()
|
||||
// 平台 tab(V206):账号域三页两 tab 共用本组件,列表/新建/编辑都按当前平台收放。
|
||||
const platformTab = usePlatformTabStore()
|
||||
/** 京东侧标记:上架上限列与编辑入口只在京东 tab 显示(用户口径「不需要在亚马逊那边」)。 */
|
||||
const isJdSide = computed(() => platformTab.active === 'jd')
|
||||
const loading = ref(false)
|
||||
const loadError = ref('')
|
||||
// 用户列表竞态门(S1-F4):快速切公司/翻页只让最后一次响应落地
|
||||
@@ -65,10 +70,16 @@ function editableOf(row: AdminUser): boolean {
|
||||
return editableBy(row.role, operatorRole.value)
|
||||
}
|
||||
|
||||
/** 列表请求参数 = 用户填的筛选态 + 当前公司。公司值每次现取、不写进 filters:
|
||||
* 它由上方 tab 决定而不是用户填的筛选项,住进 filters 就等于多出第二个取值口径(Store 之外再长一个)。 */
|
||||
/** 上架上限列文案(仅京东侧渲染该列):null=旧数据未配('-'),0=不限,其余为具体条数。 */
|
||||
function quotaCellText(row: AdminUser): string {
|
||||
if (row.jdPublishQuota == null) return '-'
|
||||
return row.jdPublishQuota === 0 ? '不限' : String(row.jdPublishQuota)
|
||||
}
|
||||
|
||||
/** 列表请求参数 = 用户填的筛选态 + 当前公司 + 当前平台。公司/平台值每次现取、不写进 filters:
|
||||
* 它们由上方 tab 决定而不是用户填的筛选项,住进 filters 就等于多出第二个取值口径(Store 之外再长一个)。 */
|
||||
function listParams() {
|
||||
return { ...toUserListParams(filters), companyId: companyTab.requestCompanyId }
|
||||
return { ...toUserListParams(filters), companyId: companyTab.requestCompanyId, platform: platformTab.active }
|
||||
}
|
||||
|
||||
async function loadUsers() {
|
||||
@@ -171,18 +182,32 @@ function goJump() {
|
||||
// ② 用户名全平台唯一(V143 的唯一索引),留着上一家填的关键字去筛新一家 ⇒ 必然空页,而输入框还显示着那个值。
|
||||
watch(() => companyTab.activeId, () => { filters.createdByAdminId = null; filters.keyword = ''; filters.page = 1; void loadUsers() })
|
||||
|
||||
// 切平台 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>
|
||||
|
||||
@@ -232,6 +257,7 @@ onMounted(() => {
|
||||
<th style="width: 140px">角色</th>
|
||||
<th style="width: 160px">所属管理员</th>
|
||||
<th style="width: 160px">到期时间</th>
|
||||
<th v-if="isJdSide" style="width: 110px">上架上限</th>
|
||||
<th style="width: 90px">状态</th>
|
||||
<th style="width: 180px">创建时间</th>
|
||||
<th style="width: 180px">更新时间</th>
|
||||
@@ -248,6 +274,7 @@ onMounted(() => {
|
||||
<td :class="{ 'expiry-cell-expired': formatExpiryCell(row).expired }">
|
||||
{{ formatExpiryCell(row).text }}
|
||||
</td>
|
||||
<td v-if="isJdSide">{{ quotaCellText(row) }}</td>
|
||||
<td class="status-cell" :class="{ 'status-cell-disabled': !!row.disabledAt }" :title="row.disabledAt ? `停用于 ${row.disabledAt}` : undefined">
|
||||
{{ disabledBadgeText(row) }}
|
||||
</td>
|
||||
@@ -285,10 +312,10 @@ onMounted(() => {
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td colspan="9" class="empty-tip">加载中...</td>
|
||||
<td :colspan="isJdSide ? 10 : 9" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td colspan="9" class="empty-tip">{{ userListEmptyHint() }}</td>
|
||||
<td :colspan="isJdSide ? 10 : 9" class="empty-tip">{{ userListEmptyHint() }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -305,9 +332,10 @@ onMounted(() => {
|
||||
:company-options="companyOptions"
|
||||
:operator-company-id="operatorCompanyId"
|
||||
:active-company-id="companyTab.requestCompanyId"
|
||||
:platform="platformTab.active"
|
||||
@created="loadUsers"
|
||||
/>
|
||||
<EditUserDialog v-model="editVisible" :user="editUser" :operator-super="isSuperAdmin" :company-id="companyTab.requestCompanyId" @updated="loadUsers" />
|
||||
<EditUserDialog v-model="editVisible" :user="editUser" :operator-super="isSuperAdmin" :company-id="companyTab.requestCompanyId" :platform="platformTab.active" @updated="loadUsers" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -11,22 +11,33 @@ import {
|
||||
|
||||
export const SHOP_GROUPS_ENDPOINT = '/api/admin/shop-manages/groups'
|
||||
|
||||
export async function fetchShopGroups(companyId?: number | null): Promise<ShopGroupItem[]> {
|
||||
const { data } = await http.get<unknown>(SHOP_GROUPS_ENDPOINT, { params: companyId != null ? { company_id: companyId } : {} })
|
||||
/** 列表:company_id 收公司口径(钉住的取值口),platform 收平台 tab 口径(V206),都缺省就不发。 */
|
||||
export async function fetchShopGroups(companyId?: number | null, platform?: string): Promise<ShopGroupItem[]> {
|
||||
const { data } = await http.get<unknown>(SHOP_GROUPS_ENDPOINT, {
|
||||
params: {
|
||||
...(companyId != null ? { company_id: companyId } : {}),
|
||||
...(platform ? { platform } : {}),
|
||||
},
|
||||
})
|
||||
return parseShopGroupList(data)
|
||||
}
|
||||
|
||||
/** 新建分组:POST /api/admin/shop-manages/groups(创建人 = 组长 = 当前操作者)。 */
|
||||
export async function createShopGroup(name: string, memberUserIds: number[], createdById: number): Promise<ShopGroupItem> {
|
||||
const { data } = await http.post<unknown>(SHOP_GROUPS_ENDPOINT, toShopGroupCreatePayload(name, memberUserIds, createdById))
|
||||
export async function createShopGroup(
|
||||
name: string,
|
||||
memberUserIds: number[],
|
||||
createdById: number,
|
||||
platform?: string,
|
||||
): Promise<ShopGroupItem> {
|
||||
const { data } = await http.post<unknown>(SHOP_GROUPS_ENDPOINT, toShopGroupCreatePayload(name, memberUserIds, createdById, platform))
|
||||
const created = parseShopGroupItem(unwrap<unknown>(data))
|
||||
if (!created) throw new Error('创建分组响应异常:缺少分组数据')
|
||||
return created
|
||||
}
|
||||
|
||||
/** 更新分组:PUT /api/admin/shop-manages/groups/{id}。 */
|
||||
export async function updateShopGroup(id: number, name: string, memberUserIds: number[]): Promise<ShopGroupItem> {
|
||||
const { data } = await http.put<unknown>(`${SHOP_GROUPS_ENDPOINT}/${id}`, toShopGroupUpdatePayload(name, memberUserIds))
|
||||
export async function updateShopGroup(id: number, name: string, memberUserIds: number[], platform?: string): Promise<ShopGroupItem> {
|
||||
const { data } = await http.put<unknown>(`${SHOP_GROUPS_ENDPOINT}/${id}`, toShopGroupUpdatePayload(name, memberUserIds, platform))
|
||||
const updated = parseShopGroupItem(unwrap<unknown>(data))
|
||||
if (!updated) throw new Error('更新分组响应异常:缺少分组数据')
|
||||
return updated
|
||||
|
||||
@@ -12,6 +12,8 @@ export interface ShopGroupItem {
|
||||
memberUserIds?: number[]
|
||||
createdAt?: string
|
||||
updatedAt?: string
|
||||
/** 所属平台(V206):'amazon'|'jd';旧负载缺省不渲染该键。 */
|
||||
platform?: string
|
||||
}
|
||||
|
||||
export interface ShopGroupFormErrors {
|
||||
@@ -53,6 +55,8 @@ export function parseShopGroupItem(raw: unknown): ShopGroupItem | null {
|
||||
if (createdAt) item.createdAt = createdAt
|
||||
const updatedAt = text(record.updatedAt ?? record.updated_at)
|
||||
if (updatedAt) item.updatedAt = updatedAt
|
||||
const platform = text(record.platform)
|
||||
if (platform) item.platform = platform
|
||||
return item
|
||||
}
|
||||
|
||||
@@ -79,18 +83,34 @@ export function validateShopGroupForm(name: string): ShopGroupFormErrors {
|
||||
return errors
|
||||
}
|
||||
|
||||
/** 创建载荷:groupName + 成员 + 创建人(= 组长,当前操作者)。 */
|
||||
/** 创建载荷:groupName + 成员 + 创建人(= 组长,当前操作者)+ 所属平台(V206,缺省不下发)。 */
|
||||
export function toShopGroupCreatePayload(
|
||||
name: string,
|
||||
memberUserIds: number[],
|
||||
createdById: number,
|
||||
): { groupName: string; memberUserIds: number[]; createdById: number } {
|
||||
return { groupName: text(name), memberUserIds: dedupeIds(memberUserIds), createdById }
|
||||
platform?: string,
|
||||
): { groupName: string; memberUserIds: number[]; createdById: number; platform?: string } {
|
||||
const payload: { groupName: string; memberUserIds: number[]; createdById: number; platform?: string } = {
|
||||
groupName: text(name),
|
||||
memberUserIds: dedupeIds(memberUserIds),
|
||||
createdById,
|
||||
}
|
||||
if (platform) payload.platform = platform
|
||||
return payload
|
||||
}
|
||||
|
||||
/** 更新载荷:groupName + 成员(组长/创建人不可改)。 */
|
||||
export function toShopGroupUpdatePayload(name: string, memberUserIds: number[]): { groupName: string; memberUserIds: number[] } {
|
||||
return { groupName: text(name), memberUserIds: dedupeIds(memberUserIds) }
|
||||
/** 更新载荷:groupName + 成员 + 所属平台(V206;组长/创建人不可改)。 */
|
||||
export function toShopGroupUpdatePayload(
|
||||
name: string,
|
||||
memberUserIds: number[],
|
||||
platform?: string,
|
||||
): { groupName: string; memberUserIds: number[]; platform?: string } {
|
||||
const payload: { groupName: string; memberUserIds: number[]; platform?: string } = {
|
||||
groupName: text(name),
|
||||
memberUserIds: dedupeIds(memberUserIds),
|
||||
}
|
||||
if (platform) payload.platform = platform
|
||||
return payload
|
||||
}
|
||||
|
||||
/** 组员候选用户(对齐 admin.js getEligibleShopManageGroupUsers 的过滤语义)。 */
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/** 新建用户表单模型(任务 45):纯逻辑,镜像 Java AdminUserCreateRequest 字段与后端校验。 */
|
||||
import type { PlatformTabId } from '../../config/platform-scope.ts'
|
||||
|
||||
export const CREATE_USERNAME_MIN_LEN = 2
|
||||
export const CREATE_PASSWORD_MIN_LEN = 6
|
||||
@@ -21,6 +22,8 @@ export interface CreateUserForm {
|
||||
expiresAt: string
|
||||
/** 所属公司 id:仅 role=company_super_admin 时由站点超管必选(2026-10-05 需求)。 */
|
||||
companyId?: number | null
|
||||
/** 所属平台(V206):弹窗打开时预填当前平台 tab,单选可改。 */
|
||||
platform: PlatformTabId
|
||||
}
|
||||
|
||||
export interface CreateUserFormErrors {
|
||||
@@ -43,10 +46,12 @@ export interface CreateUserPayload {
|
||||
* 反向钉(company-user-create.test.ts)唯一豁免的例外:公司超管必须落指定公司,
|
||||
* 否则会静默落操作者自己的公司(公司 1),用户需求就是给别家公司开超管。 */
|
||||
companyId?: number
|
||||
/** 所属平台(V206):恒下发(弹窗单选默认当前平台 tab),缺省后端落 amazon。 */
|
||||
platform: PlatformTabId
|
||||
}
|
||||
|
||||
export function createEmptyCreateUserForm(): CreateUserForm {
|
||||
return { username: '', password: '', role: 'normal', columnIds: [], createdBy: null, expiresAt: '', companyId: null }
|
||||
return { username: '', password: '', role: 'normal', columnIds: [], createdBy: null, expiresAt: '', companyId: null, platform: 'amazon' }
|
||||
}
|
||||
|
||||
/** 未知/空白/超管角色归一:admin/company_super_admin/normal 白名单,其余归 normal。 */
|
||||
@@ -147,6 +152,7 @@ export function toCreateUserRequest(form: CreateUserForm): CreateUserPayload {
|
||||
password: form.password || '',
|
||||
role,
|
||||
columnIds: Array.isArray(form.columnIds) ? form.columnIds.slice() : [],
|
||||
platform: form.platform,
|
||||
}
|
||||
if (payload.role === 'normal' && form.createdBy != null) {
|
||||
payload.createdById = form.createdBy
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
toEditUserUpdateRequest,
|
||||
validateEditUserForm,
|
||||
type EditUserForm,
|
||||
type EditUserFormOptions,
|
||||
} from './user-edit-model'
|
||||
|
||||
/** Java AdminUserController.updateUser 端点前缀。 */
|
||||
@@ -12,12 +13,13 @@ export const EDIT_USER_ENDPOINT = '/api/admin/user'
|
||||
|
||||
/**
|
||||
* 提交编辑用户:先校验(不通过抛首条错误),再序列化 PUT;http/后端失败交由调用方提示。
|
||||
* options.includeQuota=false(亚马逊侧)不下发上架上限——校验与序列化同口径。
|
||||
*/
|
||||
export async function submitEditUser(form: EditUserForm): Promise<void> {
|
||||
const { valid, errors } = validateEditUserForm(form)
|
||||
export async function submitEditUser(form: EditUserForm, options: EditUserFormOptions = {}): Promise<void> {
|
||||
const { valid, errors } = validateEditUserForm(form, options)
|
||||
if (!valid) {
|
||||
throw new Error(Object.values(errors)[0] || '编辑用户表单校验未通过')
|
||||
}
|
||||
const { data } = await http.put<unknown>(`${EDIT_USER_ENDPOINT}/${form.uid}`, toEditUserUpdateRequest(form))
|
||||
const { data } = await http.put<unknown>(`${EDIT_USER_ENDPOINT}/${form.uid}`, toEditUserUpdateRequest(form, options))
|
||||
unwrap<unknown>(data)
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
/** 编辑用户表单回填模型(任务 47):从用户行回填可编辑表单,镜像 Java AdminUserUpdateRequest。 */
|
||||
import type { AdminUser } from '../../types/admin'
|
||||
import type { PlatformTabId } from '../../config/platform-scope.ts'
|
||||
import { CREATE_PASSWORD_MIN_LEN, mayCarryOwnExpiry } from './user-create-model.ts'
|
||||
|
||||
/** 编辑可选角色:站点/公司超管不可改,未知归 normal;后端只收 admin|normal。 */
|
||||
export type EditUserRole = 'normal' | 'admin'
|
||||
|
||||
export interface EditUserForm {
|
||||
jdPublishQuota: number
|
||||
uid: number
|
||||
/** 仅展示用,后端不支持改用户名。 */
|
||||
username: string
|
||||
@@ -18,9 +20,12 @@ export interface EditUserForm {
|
||||
originalRole: string
|
||||
/** 到期时间(yyyy-MM-dd HH:mm:ss);空串 = 永不过期。null = 后端本来就无到期。 */
|
||||
expiresAt: string
|
||||
/** 所属平台(V206):单选可翻档,未知/缺省归亚马逊(存量默认)。 */
|
||||
platform: PlatformTabId
|
||||
}
|
||||
|
||||
export interface EditUserFormErrors {
|
||||
jdPublishQuota?: string
|
||||
password?: string
|
||||
}
|
||||
|
||||
@@ -28,10 +33,13 @@ export interface EditUserFormErrors {
|
||||
export interface EditUserUpdateRequest {
|
||||
/** 目标是公司超管时不携带(防止表单把公司超管误降级);站点超管改其密码/到期时间即可。 */
|
||||
role?: EditUserRole
|
||||
jdPublishQuota?: number
|
||||
columnIds: number[]
|
||||
password?: string
|
||||
/** 到期时间:空串=清除(恢复永不过期),有值=改期;总是下发(与后端"传了就更新"对齐)。 */
|
||||
expiresAt: string
|
||||
/** 所属平台(V206):总是下发(弹窗单选恒渲染),翻档即把记录挪到另一平台的列表。 */
|
||||
platform: PlatformTabId
|
||||
}
|
||||
|
||||
/** 行角色 → 可编辑角色:仅 admin 映射 admin,其余(含 unknown)归 normal。 */
|
||||
@@ -71,22 +79,38 @@ export function fillEditUserForm(user: AdminUser): EditUserForm {
|
||||
const role = typeof user.role === 'string' ? user.role.trim() : ''
|
||||
return {
|
||||
uid: user.id,
|
||||
jdPublishQuota: user.jdPublishQuota ?? 5000,
|
||||
username: user.username || '',
|
||||
password: '',
|
||||
role: editRoleOf(role),
|
||||
columnIds: [],
|
||||
originalRole: role,
|
||||
expiresAt: normalizeExpiryForPicker(user.expiresAt),
|
||||
platform: user.platform === 'jd' ? 'jd' : 'amazon',
|
||||
}
|
||||
}
|
||||
|
||||
/** 编辑表单校验选项:includeQuota=false(亚马逊侧)跳过上架上限校验——该项不下发。 */
|
||||
export interface EditUserFormOptions {
|
||||
/** 是否参与上架上限(jd_publish_quota)的校验与下发;缺省 true(京东侧)。 */
|
||||
includeQuota?: boolean
|
||||
}
|
||||
|
||||
/** 编辑表单校验:密码可留空(不改),非空时须达到最小长度。 */
|
||||
export function validateEditUserForm(form: EditUserForm): { valid: boolean; errors: EditUserFormErrors } {
|
||||
export function validateEditUserForm(
|
||||
form: EditUserForm,
|
||||
options: EditUserFormOptions = {},
|
||||
): { valid: boolean; errors: EditUserFormErrors } {
|
||||
const errors: EditUserFormErrors = {}
|
||||
const password = form.password || ''
|
||||
if (password && password.length < CREATE_PASSWORD_MIN_LEN) {
|
||||
errors.password = `密码至少${CREATE_PASSWORD_MIN_LEN}个字符,留空则不修改`
|
||||
}
|
||||
if (options.includeQuota !== false &&
|
||||
(form.role === 'admin' || form.originalRole === 'company_super_admin') &&
|
||||
(!Number.isInteger(form.jdPublishQuota) || form.jdPublishQuota < 0 || form.jdPublishQuota > 2147483647)) {
|
||||
errors.jdPublishQuota = '请输入 0 至 2147483647 的整数'
|
||||
}
|
||||
return { valid: Object.keys(errors).length === 0, errors }
|
||||
}
|
||||
|
||||
@@ -96,8 +120,11 @@ export function validateEditUserForm(form: EditUserForm): { valid: boolean; erro
|
||||
* <p>expiresAt 按「改完之后的角色」决定:目标角色不能带自己的到期时间时发空串=清空
|
||||
* (后端 400 闸门只拦「有值」,空串走既有的清除分支)。公司超管目标不带 role,
|
||||
* 它的 roleAfter 就是 company_super_admin,续费那条空串不会被误当成清空。</p>
|
||||
*
|
||||
* <p>options.includeQuota=false(亚马逊侧编辑)不下发 jdPublishQuota——上架上限是京东
|
||||
* 口径,亚马逊侧不显示也不改它(用户口径 2026-11-17);platform 恒下发(单选恒渲染)。</p>
|
||||
*/
|
||||
export function toEditUserUpdateRequest(form: EditUserForm): EditUserUpdateRequest {
|
||||
export function toEditUserUpdateRequest(form: EditUserForm, options: EditUserFormOptions = {}): EditUserUpdateRequest {
|
||||
const originalRole = (form.originalRole || '').trim().toLowerCase()
|
||||
if (originalRole === 'super_admin') {
|
||||
throw new Error('不能修改超级管理员')
|
||||
@@ -110,10 +137,14 @@ export function toEditUserUpdateRequest(form: EditUserForm): EditUserUpdateReque
|
||||
const request: EditUserUpdateRequest = {
|
||||
columnIds: Array.isArray(form.columnIds) ? form.columnIds.slice() : [],
|
||||
expiresAt: mayCarryOwnExpiry(roleAfter) ? (form.expiresAt || '').trim() : '',
|
||||
platform: form.platform,
|
||||
}
|
||||
if (keepsRole) {
|
||||
request.role = nextRole
|
||||
}
|
||||
if (options.includeQuota !== false && (roleAfter === 'admin' || roleAfter === 'company_super_admin')) {
|
||||
request.jdPublishQuota = form.jdPublishQuota
|
||||
}
|
||||
const password = form.password || ''
|
||||
if (password) request.password = password
|
||||
return request
|
||||
|
||||
@@ -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 同形——实心红渐变+白字。
|
||||
|
||||
@@ -1,305 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 任务证据件(R3「后管可视」):按 taskId / uid 关联查看异常现场件与窗口图。
|
||||
* 读取面在服务端逐个方法走 requireSuperAdmin;本页只消费服务端流,不接触对象直链。
|
||||
*/
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import LoadFailureBar from '@/components/LoadFailureBar.vue'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import {
|
||||
deleteTaskEvidence,
|
||||
fetchTaskEvidenceContent,
|
||||
fetchTaskEvidenceFiles,
|
||||
taskEvidenceDownloadUrl,
|
||||
} from '@/api/task-evidence'
|
||||
import type { TaskEvidenceRow } from '@/api/task-evidence'
|
||||
|
||||
const loading = ref(false)
|
||||
const loadFailure = ref('')
|
||||
const items = ref<TaskEvidenceRow[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const taskIdFilter = ref('')
|
||||
const uidFilter = ref('')
|
||||
const selectedIds = ref<Set<number>>(new Set())
|
||||
const selectedCount = computed(() => selectedIds.value.size)
|
||||
|
||||
const previewVisible = ref(false)
|
||||
const previewLoading = ref(false)
|
||||
const previewRow = ref<TaskEvidenceRow | null>(null)
|
||||
const previewText = ref('')
|
||||
const previewImage = ref('')
|
||||
|
||||
function imageOf(row: TaskEvidenceRow, content: string): string {
|
||||
return `data:${row.contentType || 'image/png'};base64,${content}`
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
loadFailure.value = ''
|
||||
try {
|
||||
const uid = uidFilter.value.trim() ? Number(uidFilter.value.trim()) : undefined
|
||||
const data = await fetchTaskEvidenceFiles({
|
||||
taskId: taskIdFilter.value.trim() || undefined,
|
||||
uid: Number.isFinite(uid) && (uid || 0) > 0 ? uid : undefined,
|
||||
page: page.value,
|
||||
pageSize: pageSize.value,
|
||||
})
|
||||
items.value = data.items
|
||||
total.value = data.total
|
||||
} catch (error) {
|
||||
loadFailure.value = error instanceof Error ? error.message : '任务证据件加载失败'
|
||||
showAdminFeedback(loadFailure.value, 'error')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function search() {
|
||||
page.value = 1
|
||||
selectedIds.value = new Set()
|
||||
load()
|
||||
}
|
||||
|
||||
function changePage(next: number) {
|
||||
page.value = next
|
||||
load()
|
||||
}
|
||||
|
||||
function changeSize(size: number) {
|
||||
pageSize.value = size
|
||||
page.value = 1
|
||||
load()
|
||||
}
|
||||
|
||||
function toggleSelect(id: number) {
|
||||
const next = new Set(selectedIds.value)
|
||||
if (next.has(id)) next.delete(id)
|
||||
else next.add(id)
|
||||
selectedIds.value = next
|
||||
}
|
||||
|
||||
function toggleSelectAllPage() {
|
||||
const allOn = items.value.length > 0 && items.value.every((row) => selectedIds.value.has(row.id))
|
||||
const next = new Set(selectedIds.value)
|
||||
if (allOn) items.value.forEach((row) => next.delete(row.id))
|
||||
else items.value.forEach((row) => next.add(row.id))
|
||||
selectedIds.value = next
|
||||
}
|
||||
|
||||
async function removeSelected() {
|
||||
if (!selectedCount.value) return
|
||||
try {
|
||||
const deleted = await deleteTaskEvidence(Array.from(selectedIds.value))
|
||||
showAdminFeedback(`已删除 ${deleted} 份证据件`, 'success')
|
||||
selectedIds.value = new Set()
|
||||
await load()
|
||||
} catch (error) {
|
||||
showAdminFeedback(error instanceof Error ? error.message : '删除证据件失败', 'error')
|
||||
}
|
||||
}
|
||||
|
||||
async function openPreview(row: TaskEvidenceRow) {
|
||||
previewRow.value = row
|
||||
previewVisible.value = true
|
||||
previewLoading.value = true
|
||||
previewText.value = ''
|
||||
previewImage.value = ''
|
||||
try {
|
||||
const content = await fetchTaskEvidenceContent(row.id)
|
||||
if (content.binary) previewImage.value = imageOf(row, content.content)
|
||||
else previewText.value = content.content
|
||||
} catch (error) {
|
||||
previewText.value = error instanceof Error ? error.message : '证据件读取失败'
|
||||
} finally {
|
||||
previewLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function closePreview() {
|
||||
previewVisible.value = false
|
||||
previewRow.value = null
|
||||
previewText.value = ''
|
||||
previewImage.value = ''
|
||||
}
|
||||
|
||||
function kindLabel(row: TaskEvidenceRow): string {
|
||||
if (row.contentType?.startsWith('image/')) return '窗口/页面图'
|
||||
return row.evidenceType || '证据件'
|
||||
}
|
||||
|
||||
watch([taskIdFilter, uidFilter], () => {
|
||||
// 过滤条件改了不自动打请求,避免一次输入打满接口;按「查询」或回车再取。
|
||||
})
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="evidence-view">
|
||||
<section class="panel-box">
|
||||
<div class="evidence-head">
|
||||
<h3>任务证据件</h3>
|
||||
<div class="evidence-tools">
|
||||
<input
|
||||
v-model="taskIdFilter"
|
||||
type="text"
|
||||
class="evidence-input"
|
||||
placeholder="按任务号筛选"
|
||||
@keyup.enter="search"
|
||||
/>
|
||||
<input
|
||||
v-model="uidFilter"
|
||||
type="text"
|
||||
class="evidence-input evidence-uid"
|
||||
placeholder="按 uid 筛选"
|
||||
@keyup.enter="search"
|
||||
/>
|
||||
<button class="btn" type="button" @click="search">查询</button>
|
||||
<button class="btn btn-danger" type="button" :disabled="!selectedCount" @click="removeSelected">
|
||||
删除{{ selectedCount ? `(${selectedCount})` : '' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="page-hint">
|
||||
异常现场件与窗口图按任务号关联;读取与下载仅超级管理员可用,对象直链不出服务端。
|
||||
</p>
|
||||
|
||||
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 40px">
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="items.length > 0 && items.every((row) => selectedIds.has(row.id))"
|
||||
:disabled="!items.length"
|
||||
@change="toggleSelectAllPage"
|
||||
/>
|
||||
</th>
|
||||
<th style="width: 90px">ID</th>
|
||||
<th style="width: 150px">任务号</th>
|
||||
<th style="width: 90px">UID</th>
|
||||
<th style="width: 130px">类型</th>
|
||||
<th style="width: 130px">来源</th>
|
||||
<th style="width: 110px">体积</th>
|
||||
<th style="width: 160px">生成时间</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-if="items.length">
|
||||
<tr v-for="row in items" :key="row.id">
|
||||
<td>
|
||||
<input type="checkbox" :checked="selectedIds.has(row.id)" @change="toggleSelect(row.id)" />
|
||||
</td>
|
||||
<td>{{ row.id }}</td>
|
||||
<td>{{ row.taskId || '-' }}</td>
|
||||
<td>{{ row.uid ?? '-' }}</td>
|
||||
<td>{{ kindLabel(row) }}</td>
|
||||
<td>{{ row.source || '-' }}</td>
|
||||
<td>{{ row.byteSize }} B</td>
|
||||
<td>{{ formatDateTime(row.createdAt) }}</td>
|
||||
<td class="evidence-actions">
|
||||
<button class="link-like" type="button" @click="openPreview(row)">查看</button>
|
||||
<a class="link-cell" :href="taskEvidenceDownloadUrl(row.id)" target="_blank" rel="noopener">下载</a>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td colspan="9" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td colspan="9" class="empty-tip">暂无证据件</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<OldPagination :total="total" :page="page" :page-size="pageSize" @change="changePage" @size-change="changeSize" />
|
||||
</section>
|
||||
|
||||
<div v-if="previewVisible" class="modal-mask" @click.self="closePreview">
|
||||
<div class="modal evidence-modal">
|
||||
<div class="modal-head">
|
||||
<h3 v-if="previewRow">证据件 #{{ previewRow.id }} · {{ previewRow.taskId || '-' }}</h3>
|
||||
<button class="modal-close" type="button" aria-label="关闭" @click="closePreview">×</button>
|
||||
</div>
|
||||
<div v-if="previewLoading" class="modal-empty">读取中...</div>
|
||||
<div v-else-if="previewImage" class="preview-grid">
|
||||
<img :src="previewImage" alt="任务证据图" />
|
||||
</div>
|
||||
<pre v-else class="evidence-text">{{ previewText || '(空)' }}</pre>
|
||||
<div class="modal-foot">
|
||||
<button class="btn btn-secondary" type="button" @click="closePreview">关闭</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.evidence-view {
|
||||
font-family: inherit;
|
||||
color: var(--c-text, #24384d);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
.evidence-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.evidence-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.evidence-input {
|
||||
width: 180px;
|
||||
height: 32px;
|
||||
padding: 0 10px;
|
||||
border: 1px solid #cdd8e3;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.evidence-uid {
|
||||
width: 120px;
|
||||
}
|
||||
.evidence-actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
.link-like {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #2563eb;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
}
|
||||
.evidence-modal {
|
||||
width: min(960px, 92vw);
|
||||
max-height: 86vh;
|
||||
}
|
||||
.evidence-text {
|
||||
max-height: 60vh;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
background: #f6f8fa;
|
||||
padding: 12px;
|
||||
border-radius: 6px;
|
||||
}
|
||||
.preview-grid img {
|
||||
max-width: 100%;
|
||||
max-height: 60vh;
|
||||
display: block;
|
||||
margin: 0 auto;
|
||||
}
|
||||
</style>
|
||||
@@ -34,7 +34,6 @@ export const adminPages: AdminPageDef[] = [
|
||||
{ path: 'records/tutorial', menuKey: 'admin_tutorial', title: '教程管理', companyScoped: false, load: () => import('@/pages/records/RecordsTutorialPage.vue') },
|
||||
{ path: 'records/workbench-client-package', menuKey: 'admin_workbench_client_package', title: '数富AI工作台客户端包管理', companyScoped: false, load: () => import('@/pages/records/WorkbenchClientPackagePage.vue') },
|
||||
{ path: 'records/device-logs', menuKey: 'admin_device_logs', title: '日志管理', companyScoped: true, load: () => import('@/pages/records/DeviceLogsPage.vue') },
|
||||
{ path: 'records/task-evidence', menuKey: 'admin_task_evidence', title: '任务证据', superAdminOnly: true, companyScoped: false, load: () => import('@/pages/records/TaskEvidencePage.vue') },
|
||||
{ path: 'task-center/board', menuKey: 'admin_task_center', title: '客户端任务管理', companyScoped: true, load: () => import('@/pages/task-center/TaskCenterBoardPage.vue') },
|
||||
{ path: 'records/digital-human-version', menuKey: 'digital_human_version', title: '数字人版本管理', load: () => import('@/pages/records/RecordsDigitalHumanVersionPage.vue') },
|
||||
{ path: 'records/image-video-tasks', menuKey: 'admin_image_video_tasks', title: '视频任务记录', companyScoped: true, load: () => import('@/pages/tasks/ImageVideoTasksPage.vue') },
|
||||
@@ -46,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 {
|
||||
|
||||
@@ -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
|
||||
},
|
||||
|
||||
@@ -4,9 +4,12 @@
|
||||
export type AdminRole = 'super_admin' | 'company_super_admin' | 'admin' | 'normal'
|
||||
|
||||
export interface AdminUser {
|
||||
jdPublishQuota?: number
|
||||
id: number
|
||||
username: string
|
||||
role: string
|
||||
/** 所属平台(V206):'amazon'|'jd',存量默认亚马逊;账号域三页按当前平台 tab 过滤/归类。 */
|
||||
platform?: string
|
||||
/** 1 为管理员标志位;role 为空时可据此推断角色。 */
|
||||
isAdmin?: boolean
|
||||
createdById?: number | null
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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 路由必须下线')
|
||||
})
|
||||
|
||||
@@ -24,13 +24,13 @@ function form(overrides: Record<string, unknown> = {}) {
|
||||
return { ...createEmptyCreateUserForm(), username: 'zhangsan', password: 'secret123', ...overrides }
|
||||
}
|
||||
|
||||
test('空表单默认没有公司、没有到期时间', () => {
|
||||
test('空表单默认没有公司、没有到期时间(平台默认亚马逊 = 存量口径,V206)', () => {
|
||||
const blank = createEmptyCreateUserForm()
|
||||
assert.equal(blank.companyId ?? null, null, 'companyId 默认 null(仅公司超管角色使用)')
|
||||
assert.equal(blank.expiresAt, '', '到期时间默认空 = 永不过期')
|
||||
assert.deepEqual(
|
||||
{ ...blank, companyId: null, expiresAt: '' },
|
||||
{ username: '', password: '', role: 'normal', columnIds: [], createdBy: null, companyId: null, expiresAt: '' },
|
||||
{ username: '', password: '', role: 'normal', columnIds: [], createdBy: null, companyId: null, expiresAt: '', platform: 'amazon' },
|
||||
)
|
||||
})
|
||||
|
||||
@@ -51,6 +51,8 @@ test('请求体:admin/normal 一律不带 companyId;公司超管必须带且
|
||||
password: 'secret123',
|
||||
role: 'normal',
|
||||
columnIds: [3, 1],
|
||||
// V206:所属平台恒下发(弹窗单选默认当前平台 tab,空表单缺省亚马逊)。
|
||||
platform: 'amazon',
|
||||
})
|
||||
// 所属管理员仍按原语义携带(仅 normal 角色)
|
||||
assert.equal(toCreateUserRequest(form({ role: 'normal', createdBy: 5 })).createdById, 5)
|
||||
|
||||
@@ -88,11 +88,13 @@ test('账号页与顶栏的源码里公司维度已摘干净', () => {
|
||||
'拉公司目录必须按站点超管门控,非超管不发这个请求(后端 403 兜底)')
|
||||
|
||||
// 「删了列忘了改占位行 colspan」是这类改动最常留下的残行:按表头列数交叉核对
|
||||
// (`<th` 是 `<thead` 的前缀,必须带上后随字符才数得准)
|
||||
// (`<th` 是 `<thead` 的前缀,必须带上后随字符才数得准)。
|
||||
// 2026-11-17 V206:上架上限列 v-if="isJdSide" 按平台动态渲染 ⇒ 表头数 10(含源码里的 v-if th),
|
||||
// 占位行走 :colspan 动态绑定;字面量 colspan 在动态列下必然错位一半的 tab,反向钉死。
|
||||
const headers = (page.match(/<th[\s>]/g) || []).length
|
||||
const spans = [...page.matchAll(/colspan="(\d+)"/g)].map((m) => Number(m[1]))
|
||||
assert.ok(spans.length >= 1, '列表 tbody 没有 colspan 占位行')
|
||||
for (const span of spans) assert.equal(span, headers, `占位行 colspan=${span} 与表头列数 ${headers} 不符`)
|
||||
assert.equal(headers, 10, `用户列表表头应为 10 列(9 列存量 + 京东侧上架上限 v-if 列),实际 ${headers}`)
|
||||
assert.match(page, /:colspan="isJdSide \? 10 : 9"/, '空态占位行必须按平台动态切 colspan(静态值与动态列数错位一半 tab)')
|
||||
assert.equal(/colspan="\d+"/.test(page), false, '动态列下不许再留字面量 colspan(必有一侧 tab 列数对不上)')
|
||||
|
||||
const dialog = readSource('src/pages/account/CreateUserDialog.vue')
|
||||
assert.match(dialog, /operatorSuper && form\.role === 'company_super_admin'/,
|
||||
|
||||
@@ -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,15 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { fillEditUserForm, toEditUserUpdateRequest, validateEditUserForm } from '../src/pages/account/user-edit-model.ts'
|
||||
|
||||
test('京东上架额度回填、校验和按管理员提交', () => {
|
||||
const form = fillEditUserForm({ id: 3, username: '管理员', role: 'admin', jdPublishQuota: 0 })
|
||||
assert.equal(form.jdPublishQuota, 0)
|
||||
assert.equal(toEditUserUpdateRequest(form).jdPublishQuota, 0)
|
||||
form.jdPublishQuota = -1
|
||||
assert.equal(validateEditUserForm(form).valid, false)
|
||||
form.jdPublishQuota = 1.5
|
||||
assert.equal(validateEditUserForm(form).valid, false)
|
||||
form.role = 'normal'
|
||||
assert.equal(toEditUserUpdateRequest(form).jdPublishQuota, undefined)
|
||||
})
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* 用户管理页 × 平台 tab(V206)的挂载契约:
|
||||
* 账号域三页两 tab 共用组件,列表请求必须带 platform=当前平台;切 tab 重取数;
|
||||
* 「上架上限」列仅京东侧渲染(用户口径「不需要在亚马逊那边」),文案 0=不限/null=-。
|
||||
* 不用 readFileSync(source-pin-ratchet 对台账外新文件带读点即红),全部走真实挂载断言。
|
||||
*
|
||||
* 跑法:`npx vitest run tests/mount/users-page-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 UsersPage from '@/pages/account/UsersPage.vue'
|
||||
import { usePlatformTabStore } from '@/stores/platform-tab'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
|
||||
const usersApi = vi.hoisted(() => ({
|
||||
fetchUserList: vi.fn(),
|
||||
deleteUser: vi.fn(),
|
||||
setUserDisabled: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/users', () => usersApi)
|
||||
vi.mock('@/api/companies', () => ({ fetchCompanies: vi.fn().mockResolvedValue([]) }))
|
||||
vi.mock('@/pages/account/user-menu-auth-api', () => ({ loadUserMenuAuth: vi.fn() }))
|
||||
|
||||
function pageOf(total = 0) {
|
||||
return {
|
||||
items: [
|
||||
{ id: 7, username: '京东号', role: 'normal', platform: 'jd' },
|
||||
{ id: 8, username: '存量号', role: 'admin', jdPublishQuota: 0 },
|
||||
{ id: 9, username: '老号', role: 'normal', jdPublishQuota: 800 },
|
||||
{ id: 10, username: '没配号', role: 'normal' },
|
||||
],
|
||||
total,
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
}
|
||||
}
|
||||
|
||||
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' }
|
||||
usersApi.fetchUserList.mockResolvedValue(pageOf())
|
||||
})
|
||||
|
||||
describe('UsersPage × 平台 tab(V206)', () => {
|
||||
it('亚马逊 tab(默认):列表请求带 platform=amazon,无「上架上限」列', async () => {
|
||||
const wrapper = mount(UsersPage)
|
||||
await flushPromises()
|
||||
expect(usersApi.fetchUserList).toHaveBeenCalledTimes(1)
|
||||
const params = usersApi.fetchUserList.mock.calls[0][0] as Record<string, unknown>
|
||||
expect(params.platform).toBe('amazon')
|
||||
expect(params).toHaveProperty('companyId')
|
||||
const headers = wrapper.findAll('thead th').map((th) => th.text())
|
||||
expect(headers).not.toContain('上架上限')
|
||||
// 亚马逊侧表头 9 列(存量表头,quota 列不渲染)
|
||||
expect(headers.length).toBe(9)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('切到京东 tab:重取数并带 platform=jd,「上架上限」列出现,文案 0=不限/null=-', async () => {
|
||||
const wrapper = mount(UsersPage)
|
||||
await flushPromises()
|
||||
const platformTab = usePlatformTabStore()
|
||||
platformTab.setActive('jd')
|
||||
await flushPromises()
|
||||
|
||||
expect(usersApi.fetchUserList).toHaveBeenCalledTimes(2)
|
||||
const params = usersApi.fetchUserList.mock.calls[1][0] as Record<string, unknown>
|
||||
expect(params.platform).toBe('jd')
|
||||
|
||||
const headers = wrapper.findAll('thead th').map((th) => th.text())
|
||||
expect(headers).toContain('上架上限')
|
||||
expect(headers.length).toBe(10)
|
||||
// quota 单元格:0=不限(存量号 8),null/缺省=-(京东号 7、没配号 10),800 原样
|
||||
const quotaCells = wrapper.findAll('tbody tr').map((tr) => {
|
||||
const tds = tr.findAll('td')
|
||||
// 上架上限列在第 5 列(ID/用户名/角色/所属管理员/到期时间 之后)
|
||||
return tds[5]?.text()
|
||||
})
|
||||
expect(quotaCells).toEqual(['-', '不限', '800', '-'])
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('切回亚马逊 tab:再次重取数且列消失(两 tab 各看各的数据面)', async () => {
|
||||
const wrapper = mount(UsersPage)
|
||||
await flushPromises()
|
||||
const platformTab = usePlatformTabStore()
|
||||
platformTab.setActive('jd')
|
||||
await flushPromises()
|
||||
platformTab.setActive('amazon')
|
||||
await flushPromises()
|
||||
|
||||
expect(usersApi.fetchUserList).toHaveBeenCalledTimes(3)
|
||||
const params = usersApi.fetchUserList.mock.calls[2][0] as Record<string, unknown>
|
||||
expect(params.platform).toBe('amazon')
|
||||
expect(wrapper.findAll('thead th').map((th) => th.text())).not.toContain('上架上限')
|
||||
wrapper.unmount()
|
||||
})
|
||||
})
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readSource } from './helpers.ts'
|
||||
import { toCreateUserRequest, createEmptyCreateUserForm } from '../src/pages/account/user-create-model.ts'
|
||||
import {
|
||||
fillEditUserForm,
|
||||
toEditUserUpdateRequest,
|
||||
validateEditUserForm,
|
||||
} from '../src/pages/account/user-edit-model.ts'
|
||||
import { toShopGroupCreatePayload, toShopGroupUpdatePayload } from '../src/pages/account/shop-group-model.ts'
|
||||
import { toCompanyPayload } from '../src/api/companies-dto.ts'
|
||||
|
||||
/**
|
||||
* 账号域三页按平台 tab 分列(V206,2026-11-17 用户口径「这些亚马逊这边也要有……数据都是新的
|
||||
* 别把亚马逊的带过来」):users/company/biz_shop_manage_group 三表加 platform 列,存量默认亚马逊;
|
||||
* 前端同一套组件两 tab 共显,请求带 platform=当前 tab,弹窗单选默认当前平台、可翻档归侧。
|
||||
* 上架上限(jd_publish_quota)只属京东口径:编辑弹窗隐藏 + 校验/下发都跳过 + 列表列仅京东侧。
|
||||
*/
|
||||
|
||||
// ---------- 纯函数:payload 的 platform 下发与翻档 ----------
|
||||
|
||||
test('建号 payload 恒带 platform:京东 tab 建的号默认归京东,单选翻档即改归属', () => {
|
||||
const jd = toCreateUserRequest({ ...createEmptyCreateUserForm(), username: 'a', password: 'secret123', platform: 'jd' })
|
||||
assert.equal(jd.platform, 'jd')
|
||||
const amazon = toCreateUserRequest({ ...createEmptyCreateUserForm(), username: 'a', password: 'secret123' })
|
||||
assert.equal(amazon.platform, 'amazon', '空表单缺省亚马逊(存量口径),后端 normalizeOrCreate 同口径兜底')
|
||||
})
|
||||
|
||||
test('编辑回填 platform:行值 jd→jd,缺省/未知→amazon;请求体恒下发 platform(翻档即挪列)', () => {
|
||||
const jdForm = fillEditUserForm({ id: 7, username: '京东号', role: 'normal', platform: 'jd' })
|
||||
assert.equal(jdForm.platform, 'jd')
|
||||
assert.equal(toEditUserUpdateRequest(jdForm).platform, 'jd')
|
||||
|
||||
const legacy = fillEditUserForm({ id: 8, username: '存量号', role: 'normal' })
|
||||
assert.equal(legacy.platform, 'amazon', '旧负载没有 platform 时归亚马逊(存量默认),不许渲染成空串')
|
||||
|
||||
assert.equal(toEditUserUpdateRequest(legacy).platform, 'amazon', 'platform 恒下发:单选恒渲染,后端显式才落')
|
||||
})
|
||||
|
||||
test('includeQuota=false(亚马逊侧编辑):不下发 jdPublishQuota,校验也跳过;platform 照常下发', () => {
|
||||
const form = fillEditUserForm({ id: 3, username: '管理员', role: 'admin', jdPublishQuota: 800 })
|
||||
const amazon = toEditUserUpdateRequest(form, { includeQuota: false })
|
||||
assert.equal('jdPublishQuota' in amazon, false, '亚马逊侧不许把表单里的 quota 值带给后端(字段留在京东口径)')
|
||||
assert.equal(amazon.platform, 'amazon')
|
||||
|
||||
// 亚马逊侧 quota 校验跳过:表单残留的非法值不再拦保存(该值根本不下发)。
|
||||
form.jdPublishQuota = -1
|
||||
assert.equal(validateEditUserForm(form, { includeQuota: false }).valid, true)
|
||||
assert.equal(validateEditUserForm(form).valid, false, '京东侧(缺省 options)仍按原口径拦非法值')
|
||||
})
|
||||
|
||||
test('分组 payload 的 platform:创建/更新显式下发,缺省(旧调用方)不带——后端 normalizeOrCreate 兜底', () => {
|
||||
const created = toShopGroupCreatePayload('京东组', [2, 3], 9, 'jd')
|
||||
assert.equal(created.platform, 'jd')
|
||||
const createdLegacy = toShopGroupCreatePayload('旧组', [], 9)
|
||||
assert.equal('platform' in createdLegacy, false, '不传 platform 的调用形状不变(重载式扩展)')
|
||||
const updated = toShopGroupUpdatePayload('翻档组', [2], 'amazon')
|
||||
assert.equal(updated.platform, 'amazon')
|
||||
const updatedLegacy = toShopGroupUpdatePayload('旧组', [])
|
||||
assert.equal('platform' in updatedLegacy, false)
|
||||
})
|
||||
|
||||
test('公司 payload 的 platform:显式才下发(company-directory 的 deepEqual 形状不受存量影响)', () => {
|
||||
const withPlatform = toCompanyPayload({ companyName: '福州数富', status: 1, remark: '', platform: 'jd' })
|
||||
assert.equal(withPlatform.platform, 'jd')
|
||||
const legacy = toCompanyPayload({ companyName: '厦门米椿花', status: 1, remark: '' })
|
||||
assert.equal('platform' in legacy, false, '不带 platform 的草稿请求体形状不变')
|
||||
})
|
||||
|
||||
// ---------- 源码钉:三页接线 + 弹窗默认平台 + quota 仅京东侧 ----------
|
||||
|
||||
test('UsersPage:列表请求带当前平台、切平台重取数、上架上限列仅京东侧渲染', () => {
|
||||
const page = readSource('src/pages/account/UsersPage.vue')
|
||||
assert.match(page, /platform: platformTab\.active/,
|
||||
'列表请求必须带 platform=当前平台 tab(users.ts 从原始入参读,白名单构造不收它)')
|
||||
assert.match(page, /watch\(\(\) => platformTab\.active/,
|
||||
'切平台 tab 必须重取数:账号域三页两 tab 共用组件,列表按平台过滤')
|
||||
assert.match(page, /:platform="platformTab\.active"/, '新建/编辑弹窗要拿到当前平台(默认平台 + quota 可见性)')
|
||||
assert.match(page, /v-if="isJdSide" style="width: 110px">上架上限</,
|
||||
'上架上限列只许京东侧渲染(用户口径「不需要在亚马逊那边」)')
|
||||
assert.match(page, /quotaCellText/, 'quota 单元格文案走函数(null=-、0=不限、其余条数)')
|
||||
assert.match(page, /const isJdSide = computed/, '京东侧判定单一出处')
|
||||
})
|
||||
|
||||
test('GroupsPage:分组列表带平台、切平台重取数、编辑弹窗拿当前平台', () => {
|
||||
const page = readSource('src/pages/account/GroupsPage.vue')
|
||||
assert.match(page, /fetchShopGroups\(companyTab\.requestCompanyId, platformTab\.active\)/,
|
||||
'分组列表同时收公司(钉住的取值口)与平台两个口径')
|
||||
assert.match(page, /watch\(\(\) => platformTab\.active/, '切平台 tab 必须重取数')
|
||||
assert.match(page, /:platform="platformTab\.active"/, '新建分组弹窗默认落当前平台')
|
||||
})
|
||||
|
||||
test('CompaniesPage:公司列表带平台、切平台重取数、编辑弹窗拿当前平台', () => {
|
||||
const page = readSource('src/pages/account/CompaniesPage.vue')
|
||||
assert.match(page, /fetchCompanies\(platformTab\.active\)/, '公司列表按当前平台过滤')
|
||||
assert.match(page, /watch\(\(\) => platformTab\.active/, '切平台 tab 必须重取数')
|
||||
assert.match(page, /:platform="platformTab\.active"/, '新建公司弹窗默认落当前平台')
|
||||
})
|
||||
|
||||
test('EditUserDialog:上架上限仅京东侧显示且不参与亚马逊侧提交;所属平台单选恒在', () => {
|
||||
const dialog = readSource('src/pages/account/EditUserDialog.vue')
|
||||
assert.match(dialog, /v-if="includeQuota && \(targetIsCompanySuperAdmin \|\| form\.role === 'admin'\)"/,
|
||||
'quota 项必须叠上 includeQuota(京东侧)条件——只按角色判断会把该项带进亚马逊侧弹窗')
|
||||
assert.match(dialog, /submitEditUser\(form, \{ includeQuota: includeQuota\.value \}\)/,
|
||||
'提交必须透传 includeQuota:亚马逊侧校验与下发都跳过 quota')
|
||||
assert.match(dialog, /validateEditUserForm\(form, \{ includeQuota: includeQuota\.value \}\)/,
|
||||
'校验与下发同口径(校验过了但不下发 = 静默改值)')
|
||||
assert.match(dialog, /v-model="form\.platform"/, '所属平台单选恒在:翻档是把记录挪到另一平台列表的唯一入口')
|
||||
assert.match(dialog, /props\.platform === 'jd'/, 'includeQuota 取自页面透传的当前平台')
|
||||
assert.match(dialog, /form\.platform = base\.platform/, '打开弹窗必须回填行值(旧负载缺省归亚马逊)')
|
||||
})
|
||||
|
||||
test('CreateUserDialog/GroupEditorDialog/CompanyEditorDialog:新建默认当前平台、编辑回填行值', () => {
|
||||
const create = readSource('src/pages/account/CreateUserDialog.vue')
|
||||
assert.match(create, /form\.platform = props\.platform \?\? 'amazon'/, '建号默认当前平台 tab')
|
||||
assert.match(create, /v-model="form\.platform"/, '所属平台单选在')
|
||||
|
||||
const group = readSource('src/pages/account/GroupEditorDialog.vue')
|
||||
assert.match(group, /groupPlatform\.value = props\.platform \?\? 'amazon'/, '新建分组默认当前平台 tab')
|
||||
assert.match(group, /props\.group\.platform === 'jd' \? 'jd' : 'amazon'/, '编辑分组回填行值')
|
||||
assert.match(group, /createShopGroup\(groupName\.value, memberIds\.value, operatorId, groupPlatform\.value\)/,
|
||||
'创建分组必须带平台')
|
||||
assert.match(group, /updateShopGroup\(props\.group\.id, groupName\.value, memberIds\.value, groupPlatform\.value\)/,
|
||||
'更新分组必须带平台(翻档归侧)')
|
||||
assert.doesNotMatch(group, /companyTab/, '分组弹窗不读公司 tab(既有口径:候选按组长公司取人)')
|
||||
|
||||
const company = readSource('src/pages/account/CompanyEditorDialog.vue')
|
||||
assert.match(company, /platform: props\.platform \?\? 'amazon'/, '新建公司默认当前平台 tab')
|
||||
assert.match(company, /props\.company\.platform === 'jd' \? 'jd' : 'amazon'/, '编辑公司回填行值')
|
||||
})
|
||||
@@ -1,13 +1,20 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import type { AdminMenuNode } from '../src/types/admin.ts'
|
||||
import { JD_MENU_KEYS, PLATFORM_TABS, platformOfMenuKey } from '../src/config/platform-scope.ts'
|
||||
import {
|
||||
BOTH_PLATFORM_MENU_KEYS,
|
||||
JD_MENU_KEYS,
|
||||
PLATFORM_TABS,
|
||||
platformsOfMenuKey,
|
||||
} from '../src/config/platform-scope.ts'
|
||||
import { filterMenuTreeByPlatform, visiblePlatformsFor } from '../src/layout/platform-menu-filter.ts'
|
||||
import { adminPages } from '../src/router/routes.ts'
|
||||
|
||||
/** 2026-11-16 用户定案「亚马逊/京东不混一起」:侧边栏顶部加平台 tab,京东侧=截图圈定四项
|
||||
* (用户管理/分组管理/公司管理/京东数据库),其余归亚马逊。tab 只做显示分组——菜单可见性
|
||||
* 仍由 session.menuTree(后端按权限裁剪)决定,这里钉的是「分侧归属」与「空侧隐藏」两条形状。
|
||||
/** 2026-11-16 用户定案「亚马逊/京东不混一起」:侧边栏顶部加平台 tab,京东侧=截图圈定
|
||||
* 数据页(京东数据库/分类管理)。2026-11-17 用户口径「这些亚马逊这边也要有」:账号域三页
|
||||
* (用户管理/分组管理/公司管理)改为双侧显示(BOTH_PLATFORM_MENU_KEYS),同一组件按当前
|
||||
* tab 传 platform 过滤各自数据。tab 只做显示分组——菜单可见性仍由 session.menuTree(后端
|
||||
* 按权限裁剪)决定,这里钉的是「分侧归属」与「空侧隐藏」两条形状。
|
||||
* 辅助定义在所有 test 之前:node:test 的用例回调按声明序执行,挪到文件尾会踩 TDZ。 */
|
||||
|
||||
const node = (key: string, name: string, route?: string, children?: AdminMenuNode[]): AdminMenuNode => {
|
||||
@@ -33,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'),
|
||||
]),
|
||||
]
|
||||
@@ -43,36 +49,34 @@ function groupChildKeys(filtered: AdminMenuNode[], groupKey: string): string[] {
|
||||
return (group?.children || []).map((child) => child.key)
|
||||
}
|
||||
|
||||
test('menuKey 平台归属:京东清单四项即 jd,其余(含分组 key 与未知 key)一律 amazon', () => {
|
||||
for (const key of JD_MENU_KEYS) assert.equal(platformOfMenuKey(key), 'jd', key)
|
||||
assert.equal(platformOfMenuKey('admin_query_asin'), 'amazon')
|
||||
assert.equal(platformOfMenuKey('admin_columns'), 'amazon')
|
||||
assert.equal(platformOfMenuKey('admin_group_account'), 'amazon')
|
||||
assert.equal(platformOfMenuKey('admin_jd_unknown_future'), 'amazon')
|
||||
assert.equal(platformOfMenuKey(''), 'amazon')
|
||||
test('menuKey 平台归属:京东独占即 [jd],双侧清单即两侧,其余(含分组 key 与未知 key)一律 [amazon]', () => {
|
||||
for (const key of JD_MENU_KEYS) assert.deepEqual(platformsOfMenuKey(key), ['jd'], key)
|
||||
for (const key of BOTH_PLATFORM_MENU_KEYS) assert.deepEqual(platformsOfMenuKey(key), ['amazon', 'jd'], key)
|
||||
assert.deepEqual(platformsOfMenuKey('admin_query_asin'), ['amazon'])
|
||||
assert.deepEqual(platformsOfMenuKey('admin_columns'), ['amazon'])
|
||||
assert.deepEqual(platformsOfMenuKey('admin_group_account'), ['amazon'])
|
||||
assert.deepEqual(platformsOfMenuKey('admin_jd_unknown_future'), ['amazon'])
|
||||
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:其余菜单全数保留且分组结构不变', () => {
|
||||
test('亚马逊 tab:除京东独占页外全数保留(含 2026-11-17 回归的双侧账号域三页),分组结构不变', () => {
|
||||
const filtered = filterMenuTreeByPlatform(TREE, 'amazon')
|
||||
assert.deepEqual(groupChildKeys(filtered, 'admin_group_account'),
|
||||
['admin_columns', 'admin_user_secrets', 'admin_user_secret_usage'])
|
||||
['admin_columns', 'admin_users', 'admin_group_manage', 'admin_user_secrets',
|
||||
'admin_user_secret_usage', 'admin_companies'])
|
||||
assert.deepEqual(groupChildKeys(filtered, 'admin_group_data'),
|
||||
['admin_dedupe_total_data', 'admin_invalid_asin_data', 'admin_query_asin',
|
||||
'admin_appearance_patent_clean_items', 'admin_product_categories'])
|
||||
@@ -111,18 +115,20 @@ test('tab 显示依据:两侧都有可见页才画 tab 条,仅一侧授权
|
||||
assert.deepEqual(visiblePlatformsFor(null), [])
|
||||
})
|
||||
|
||||
test('平台 tab 定义与京东清单钉死(2026-11-16 用户圈定口径,防清单漂移)', () => {
|
||||
test('平台 tab 定义与两份菜单清单钉死(防清单漂移):京东独占仅数据库一页、双侧共用账号域三页', () => {
|
||||
assert.deepEqual(PLATFORM_TABS, [
|
||||
{ id: 'amazon', label: '亚马逊' },
|
||||
{ id: 'jd', label: '京东' },
|
||||
])
|
||||
assert.deepEqual([...JD_MENU_KEYS].sort(),
|
||||
['admin_companies', 'admin_group_manage', 'admin_jd_category_manage', 'admin_jd_database', 'admin_users'])
|
||||
// 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'])
|
||||
})
|
||||
|
||||
test('JD_MENU_KEYS 每一条都必须在路由注册表登记(同 company-menu-route 护栏形状:少登记=看得见点进去404)', () => {
|
||||
test('两份清单的每一条都必须在路由注册表登记(同 company-menu-route 护栏形状:少登记=看得见点进去404)', () => {
|
||||
const registered = new Set(adminPages.map((page) => page.menuKey))
|
||||
for (const key of JD_MENU_KEYS) {
|
||||
assert.ok(registered.has(key), `京东侧菜单 key "${key}" 未在 src/router/routes.ts 登记 menuKey`)
|
||||
for (const key of [...JD_MENU_KEYS, ...BOTH_PLATFORM_MENU_KEYS]) {
|
||||
assert.ok(registered.has(key), `平台侧菜单 key "${key}" 未在 src/router/routes.ts 登记 menuKey`)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -88,7 +88,10 @@ test('test_task_048_normal_role_wording_agrees_across_all_exits', () => {
|
||||
const buttons = [...dialog.matchAll(/<el-radio-button\s+value="([a-z_]+)">([^<]*)</g)].map(
|
||||
(m) => [m[1], m[2]] as const,
|
||||
)
|
||||
assert.deepEqual(buttons, [['normal', word], ['admin', '管理员']], '编辑用户弹窗的角色按钮文案')
|
||||
// 2026-11-17 V206:弹窗新增「所属平台」单选(amazon/jd 两档)——角色按钮仍是前两枚,
|
||||
// 平台按钮单独钉,四出口文案对平的意图不变。
|
||||
assert.deepEqual(buttons.slice(0, 2), [['normal', word], ['admin', '管理员']], '编辑用户弹窗的角色按钮文案')
|
||||
assert.deepEqual(buttons.slice(2), [['amazon', '亚马逊'], ['jd', '京东']], '所属平台单选两档(V206 翻档归侧的唯一入口)')
|
||||
})
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readSource } from './helpers.ts'
|
||||
|
||||
/** P1-9:任务证据读取面的后台入口必须存在,且只给超级管理员。 */
|
||||
|
||||
test('task evidence menu is super-admin only', () => {
|
||||
const routes = readSource('src/router/routes.ts')
|
||||
assert.match(routes, /path: 'records\/task-evidence'[\s\S]*?menuKey: 'admin_task_evidence'[\s\S]*?superAdminOnly: true/,
|
||||
'任务证据路由必须带 superAdminOnly')
|
||||
|
||||
const scope = readSource('src/config/company-scope.ts')
|
||||
assert.match(scope, /SUPER_ADMIN_ONLY_MENU_KEYS[^\n]*admin_task_evidence/,
|
||||
'菜单 key 必须在超级管理员可见清单里')
|
||||
|
||||
const guide = readSource('src/layout/operation-guides.ts')
|
||||
assert.match(guide, /admin_task_evidence:\s*\{/, '菜单必须配操作指引')
|
||||
})
|
||||
|
||||
test('task evidence page never renders object keys', () => {
|
||||
const page = readSource('src/pages/records/TaskEvidencePage.vue')
|
||||
assert.doesNotMatch(page, /objectKey|object_key|presign/i, '页面不得展示或持有对象直链')
|
||||
assert.match(page, /taskEvidenceDownloadUrl/, '下载必须走鉴权接口')
|
||||
assert.match(page, /deleteTaskEvidence/, '删除必须走鉴权接口')
|
||||
})
|
||||
|
||||
test('task evidence api is wired to admin endpoints', () => {
|
||||
const api = readSource('src/api/task-evidence.ts')
|
||||
assert.match(api, /\/admin\/task-evidence\/files/)
|
||||
assert.match(api, /\/admin\/task-evidence\/download\?fileId=/)
|
||||
assert.match(api, /\/admin\/task-evidence\/delete/)
|
||||
})
|
||||
@@ -48,6 +48,15 @@ public class AdminUserEntity {
|
||||
*/
|
||||
@TableField(value = "updated_at", insertStrategy = FieldStrategy.NEVER, updateStrategy = FieldStrategy.NEVER)
|
||||
private LocalDateTime updatedAt;
|
||||
@TableField("jd_publish_quota")
|
||||
private Integer jdPublishQuota;
|
||||
/**
|
||||
* 所属平台(V206 新增):amazon|jd,与后管侧边栏平台 tab 同字面量。只作用于后管
|
||||
* 用户管理页的显示与筛选,不影响登录与功能权限。存量 DEFAULT 'amazon',京东侧
|
||||
* 数据由使用者在编辑弹窗里翻档。
|
||||
*/
|
||||
@TableField("platform")
|
||||
private String platform;
|
||||
private String machine;
|
||||
/**
|
||||
* 会话世代(V172 新增):登录/登出各 +1,JWT 的 epoch claim 必须与它相等。
|
||||
|
||||
+5
@@ -22,6 +22,11 @@ public class ShopManageGroupEntity {
|
||||
private Long userId;
|
||||
@TableField("created_by_id")
|
||||
private Long createdById;
|
||||
/**
|
||||
* 所属平台(V206 新增):amazon|jd,与后管侧边栏平台 tab 同字面量。只作用于后管
|
||||
* 分组管理页的显示与筛选;存量 DEFAULT 'amazon',京东侧由使用者在编辑弹窗里翻档。
|
||||
*/
|
||||
private String platform;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.nanri.aiimage.common.service;
|
||||
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
|
||||
/**
|
||||
* 账号域「所属平台」(V206)取值口径的唯一出处。取值字面量与 admin-frontend-vue 的
|
||||
* {@code PlatformTabId} 同源:{@code amazon | jd}。
|
||||
*
|
||||
* <p>语义边界:平台只作用于后管「用户管理 / 分组管理 / 公司管理」三个页面的显示与筛选,
|
||||
* 不影响登录、用户端功能、任务权限与 DataReadScope。存量行 DEFAULT 'amazon',京东侧数据
|
||||
* 由使用者在编辑弹窗里自己翻档(不做数据驱动的自动归类)。</p>
|
||||
*/
|
||||
public final class AdminPlatformScope {
|
||||
|
||||
public static final String AMAZON = "amazon";
|
||||
public static final String JD = "jd";
|
||||
|
||||
private AdminPlatformScope() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建侧归一:null/空白按 {@code amazon}(与列 DEFAULT 同口径);给了就只认合法值,
|
||||
* 非法值 400——静默归一会把"手滑打错"变成"悄悄归进亚马逊侧"。
|
||||
*/
|
||||
public static String normalizeOrCreate(String raw) {
|
||||
String value = raw == null ? "" : raw.trim();
|
||||
if (value.isEmpty()) {
|
||||
return AMAZON;
|
||||
}
|
||||
return requireLegal(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新侧归一:null/空白=本次不动(返回 null,调用方跳过该列);给了就只认合法值,
|
||||
* 非法值 400。{@code PUT} 只带部分字段的既有形状(如 setUserDisabled)不会把平台冲掉。
|
||||
*/
|
||||
public static String normalizeOrNull(String raw) {
|
||||
String value = raw == null ? "" : raw.trim();
|
||||
if (value.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return requireLegal(value);
|
||||
}
|
||||
|
||||
private static String requireLegal(String value) {
|
||||
if (AMAZON.equals(value) || JD.equals(value)) {
|
||||
return value;
|
||||
}
|
||||
throw new BusinessException(400, "所属平台只支持 amazon 或 jd");
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package com.nanri.aiimage.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* 任务异常证据件配置(v1.2 Phase 3/AC-13)。
|
||||
*
|
||||
* <p>证据件落在**独立桶**:默认桶 nanri-ai-images 带 7 天整桶 ILM,
|
||||
* 与"证据单独保留、单独回收"的口径互相绑死;桶名必须显式写在 application.yml,
|
||||
* 不许只在代码里留默认值(部署漏配就变成隐形行为)。</p>
|
||||
*/
|
||||
@Data
|
||||
@ConfigurationProperties(prefix = "aiimage.evidence")
|
||||
public class EvidenceProperties {
|
||||
|
||||
/** 证据桶;默认 task-evidence,独立于业务桶。 */
|
||||
private String bucket = "task-evidence";
|
||||
|
||||
/** 证据保留天数(本地与云端同口径,按天回收)。 */
|
||||
private Integer retentionDays = 7;
|
||||
|
||||
/** 对象 key 前缀;实际 key = 前缀 + taskId + "/" + UUID + 扩展名。 */
|
||||
private String keyPrefix = "task-evidence/";
|
||||
|
||||
/** 单件证据上限(字节),超过直接拒绝,避免截图/大 JSON 打满桶。 */
|
||||
private Long maxFileBytes = 64L * 1024 * 1024;
|
||||
|
||||
/** 保留期回收 cron;默认每天 03:30。 */
|
||||
private String retentionCron = "0 30 3 * * *";
|
||||
|
||||
public String bucketOrDefault() {
|
||||
return bucket == null || bucket.isBlank() ? "task-evidence" : bucket.trim();
|
||||
}
|
||||
|
||||
public int retentionDaysOrDefault() {
|
||||
return retentionDays == null || retentionDays < 1 ? 7 : retentionDays;
|
||||
}
|
||||
|
||||
public String keyPrefixOrDefault() {
|
||||
String prefix = keyPrefix == null ? "" : keyPrefix.trim();
|
||||
if (prefix.isEmpty()) {
|
||||
return "task-evidence/";
|
||||
}
|
||||
return prefix.endsWith("/") ? prefix : prefix + "/";
|
||||
}
|
||||
|
||||
public long maxFileBytesOrDefault() {
|
||||
return maxFileBytes == null || maxFileBytes < 1 ? 64L * 1024 * 1024 : maxFileBytes;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,6 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@EnableConfigurationProperties({OssProperties.class, TransientStorageProperties.class, StorageProperties.class, BrandProgressProperties.class, DeleteBrandProgressProperties.class, BrandCheckProperties.class, ZiniaoProperties.class, ModuleCleanupProperties.class, TaskPressureProperties.class, TaskImageCacheCleanupProperties.class, AppearancePatentProperties.class, SimilarAsinProperties.class, ImageVideoProperties.class, InstanceRoutingProperties.class, CapacityPlanProperties.class, UserSecretProperties.class, NotificationProperties.class, DeviceLogOssProperties.class, CollectDataBrandRecheckProperties.class, ClientCredentialProperties.class, CostGuardProperties.class, CollectRoutingProperties.class, EvidenceProperties.class})
|
||||
@EnableConfigurationProperties({OssProperties.class, TransientStorageProperties.class, StorageProperties.class, BrandProgressProperties.class, DeleteBrandProgressProperties.class, BrandCheckProperties.class, ZiniaoProperties.class, ModuleCleanupProperties.class, TaskPressureProperties.class, TaskImageCacheCleanupProperties.class, AppearancePatentProperties.class, SimilarAsinProperties.class, ImageVideoProperties.class, InstanceRoutingProperties.class, CapacityPlanProperties.class, UserSecretProperties.class, NotificationProperties.class, DeviceLogOssProperties.class, CollectDataBrandRecheckProperties.class, ClientCredentialProperties.class, CostGuardProperties.class, CollectRoutingProperties.class})
|
||||
public class PropertiesConfig {
|
||||
}
|
||||
|
||||
+4
-2
@@ -41,11 +41,13 @@ public class AdminUserController {
|
||||
@RequestParam(name = "created_by_id", required = false) Long createdById,
|
||||
@RequestParam(name = "admin_id", required = false) Long adminId,
|
||||
@RequestParam(name = "role", required = false) String role,
|
||||
@RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
@RequestParam(name = "company_id", required = false) Long companyId,
|
||||
@RequestParam(name = "platform", required = false) String platform) {
|
||||
AdminUserEntity currentUser = adminAuthSupport.requireAdminOrInternal(request);
|
||||
String kw = (username == null || username.isBlank()) ? search : username;
|
||||
Long filterCreatedBy = createdById != null ? createdById : adminId;
|
||||
AdminUserListVo vo = adminUserService.listUsers(currentUser, page, pageSize, kw, filterCreatedBy, role, companyId);
|
||||
AdminUserListVo vo = adminUserService.listUsers(currentUser, page, pageSize, kw, filterCreatedBy, role,
|
||||
companyId, platform);
|
||||
return ApiResponse.success(vo);
|
||||
}
|
||||
|
||||
|
||||
+4
@@ -11,6 +11,10 @@ public class AdminUserCreateRequest {
|
||||
private String role;
|
||||
private Long createdById;
|
||||
private Long companyId;
|
||||
/**
|
||||
* 所属平台(V206):amazon|jd;null/空白按 'amazon'(与列 DEFAULT 同口径)。
|
||||
*/
|
||||
private String platform;
|
||||
/**
|
||||
* 到期时间(V146):支持 yyyy-MM-dd / yyyy-MM-dd HH:mm / yyyy-MM-dd HH:mm:ss。
|
||||
* 空/不传 = 永不过期;super_admin 目标不存在本字段语义(超管建不出超管)。
|
||||
|
||||
+6
@@ -6,6 +6,12 @@ import java.util.List;
|
||||
|
||||
@Data
|
||||
public class AdminUserUpdateRequest {
|
||||
private Integer jdPublishQuota;
|
||||
/**
|
||||
* 所属平台(V206):null=不动;给了就只认 amazon|jd(非法值 400)。只改后管
|
||||
* 用户管理页的归属展示,不影响登录与功能权限。
|
||||
*/
|
||||
private String platform;
|
||||
private String password;
|
||||
private String role;
|
||||
private List<Long> columnIds;
|
||||
|
||||
+5
@@ -5,6 +5,11 @@ import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class AdminUserItemVo {
|
||||
@JsonProperty("jd_publish_quota")
|
||||
private Integer jdPublishQuota;
|
||||
/** 所属平台(V206):amazon|jd,与后管侧边栏平台 tab 同字面量。 */
|
||||
@JsonProperty("platform")
|
||||
private String platform;
|
||||
private Long id;
|
||||
private String username;
|
||||
@JsonProperty("is_admin")
|
||||
|
||||
+46
-1
@@ -10,6 +10,7 @@ import com.nanri.aiimage.modules.admin.model.vo.AdminUserItemVo;
|
||||
import com.nanri.aiimage.modules.admin.model.vo.AdminUserListVo;
|
||||
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.modules.admin.util.PinyinAbbrUtil;
|
||||
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
||||
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||
@@ -54,6 +55,17 @@ public class AdminUserService {
|
||||
public AdminUserListVo listUsers(AdminUserEntity currentUser, Integer page, Integer pageSize,
|
||||
String username, Long createdById, String roleFilter,
|
||||
Long companyIdFilter) {
|
||||
return listUsers(currentUser, page, pageSize, username, createdById, roleFilter, companyIdFilter, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 带平台过滤的分页用户列表(V206):platformFilter 非空白时只返回该平台的账号
|
||||
* (amazon|jd,非法值 400),后管「用户管理」页按当前平台 tab 传参;null/空白=不过滤,
|
||||
* 用户选择器等旧调用方口径不变。
|
||||
*/
|
||||
public AdminUserListVo listUsers(AdminUserEntity currentUser, Integer page, Integer pageSize,
|
||||
String username, Long createdById, String roleFilter,
|
||||
Long companyIdFilter, String platformFilter) {
|
||||
String role = adminAuthSupport.currentRole(currentUser);
|
||||
if (role == null) {
|
||||
throw new BusinessException(403, "需要管理员权限");
|
||||
@@ -71,6 +83,11 @@ public class AdminUserService {
|
||||
Long filterCreatedBy = "super_admin".equals(role) ? createdById : null;
|
||||
|
||||
LambdaQueryWrapper<AdminUserEntity> query = new LambdaQueryWrapper<>();
|
||||
String platformFilterValue = AdminPlatformScope.normalizeOrNull(platformFilter);
|
||||
if (platformFilterValue != null) {
|
||||
// 平台过滤对三档可见范围(超管/公司超管/组长)统一生效:count 与取页共用同一 wrapper
|
||||
query.eq(AdminUserEntity::getPlatform, platformFilterValue);
|
||||
}
|
||||
String roleFilterValue = roleFilter == null ? "" : roleFilter.trim();
|
||||
if (!roleFilterValue.isEmpty()) {
|
||||
query.eq(AdminUserEntity::getRole, roleFilterValue);
|
||||
@@ -211,6 +228,7 @@ public class AdminUserService {
|
||||
entity.setRole(wantRole);
|
||||
entity.setCreatedById(wantCreatedBy);
|
||||
entity.setCompanyId(targetCompanyId);
|
||||
entity.setPlatform(AdminPlatformScope.normalizeOrCreate(request.getPlatform()));
|
||||
entity.setExpiresAt(parseExpiresAt(request.getExpiresAt()));
|
||||
try {
|
||||
adminUserMapper.insert(entity);
|
||||
@@ -379,13 +397,18 @@ public class AdminUserService {
|
||||
ensureAdminUsersMenuAccess(currentUser, List.of("admin_users"));
|
||||
String password = request.getPassword();
|
||||
String wantRole = request.getRole() == null ? null : request.getRole().trim();
|
||||
// 平台只在显式给出时落(null/空白=不动):PUT 只带 disabled 的既有形状不能把平台冲掉;
|
||||
// 非法值在这里直接 400,不等后面的 dirty 判定
|
||||
String platformUpdate = AdminPlatformScope.normalizeOrNull(request.getPlatform());
|
||||
|
||||
if ((password == null || password.isEmpty())
|
||||
&& (wantRole == null || wantRole.isEmpty())
|
||||
&& request.getColumnIds() == null
|
||||
&& request.getCompanyId() == null
|
||||
&& request.getExpiresAt() == null
|
||||
&& request.getDisabled() == null) {
|
||||
&& request.getDisabled() == null
|
||||
&& request.getJdPublishQuota() == null
|
||||
&& platformUpdate == null) {
|
||||
throw new BusinessException("请提供要修改的内容");
|
||||
}
|
||||
// 不许停自己:现有的角色闸(admin 只动自建普通账号 / 公司超管与超管目标互斥)已经
|
||||
@@ -440,6 +463,18 @@ public class AdminUserService {
|
||||
throw new BusinessException(400, NORMAL_ACCOUNT_EXPIRY_MESSAGE);
|
||||
}
|
||||
|
||||
if (request.getJdPublishQuota() != null) {
|
||||
if (!"super_admin".equals(role) && !"company_super_admin".equals(role)) {
|
||||
throw new BusinessException(403, "无权修改京东上架额度");
|
||||
}
|
||||
if (!"admin".equals(roleAfter) && !"company_super_admin".equals(roleAfter)) {
|
||||
throw new BusinessException(400, "只能为管理员设置京东上架额度");
|
||||
}
|
||||
if (request.getJdPublishQuota() < 0) {
|
||||
throw new BusinessException(400, "京东上架额度不能为负数");
|
||||
}
|
||||
}
|
||||
|
||||
// 移人先于写库:先确认目标公司可用,再确认 created_by_id 不变式没被破坏
|
||||
Long moveCompanyId = resolveCompanyMove(role, target, request.getCompanyId());
|
||||
if (moveCompanyId != null) {
|
||||
@@ -449,6 +484,14 @@ public class AdminUserService {
|
||||
LambdaUpdateWrapper<AdminUserEntity> update = new LambdaUpdateWrapper<AdminUserEntity>()
|
||||
.eq(AdminUserEntity::getId, uid);
|
||||
boolean dirty = false;
|
||||
if (request.getJdPublishQuota() != null) {
|
||||
update.set(AdminUserEntity::getJdPublishQuota, request.getJdPublishQuota());
|
||||
dirty = true;
|
||||
}
|
||||
if (platformUpdate != null) {
|
||||
update.set(AdminUserEntity::getPlatform, platformUpdate);
|
||||
dirty = true;
|
||||
}
|
||||
if (moveCompanyId != null) {
|
||||
update.set(AdminUserEntity::getCompanyId, moveCompanyId);
|
||||
dirty = true;
|
||||
@@ -635,11 +678,13 @@ public class AdminUserService {
|
||||
vo.setCompanyId(companyId);
|
||||
// 账号挂着公司表里查不到的 id(脏数据/回滚残留)时留空串,前端显示 '-',整页不能因此 500
|
||||
vo.setCompanyName(companyId == null ? "" : companyMap.getOrDefault(companyId, ""));
|
||||
vo.setPlatform(entity.getPlatform());
|
||||
LocalDateTime createdAt = entity.getCreatedAt();
|
||||
vo.setCreatedAt(createdAt == null ? "" : createdAt.format(CREATED_AT_FORMATTER));
|
||||
LocalDateTime updatedAt = entity.getUpdatedAt();
|
||||
vo.setUpdatedAt(updatedAt == null ? "" : updatedAt.format(CREATED_AT_FORMATTER));
|
||||
// 到期时间:null(永不过期)与空字符串在列表里都要有明确渲染,前端按空串判"永不过期"
|
||||
vo.setJdPublishQuota(entity.getJdPublishQuota());
|
||||
vo.setExpiresAt(entity.getExpiresAt() == null ? "" : entity.getExpiresAt().format(CREATED_AT_FORMATTER));
|
||||
// 停用时刻(V155):null=未停用,前端按此渲染「已停用」徽标
|
||||
vo.setDisabledAt(entity.getDisabledAt() == null ? null : entity.getDisabledAt().format(CREATED_AT_FORMATTER));
|
||||
|
||||
+6
@@ -43,6 +43,12 @@ public class LoginUserEntity {
|
||||
*/
|
||||
@TableField("disabled_at")
|
||||
private LocalDateTime disabledAt;
|
||||
/**
|
||||
* 所属平台(V206 新增):与 {@code AdminUserEntity.platform} 同列,amazon|jd。
|
||||
* 改一处必须同改两处(UsersCompanyIdMappingTest 钉住)。
|
||||
*/
|
||||
@TableField("platform")
|
||||
private String platform;
|
||||
/**
|
||||
* 会话世代(V172 新增):登录/登出各 +1,JWT 的 epoch claim 必须与它相等。
|
||||
* 与 {@code AdminUserEntity.sessionEpoch} 同列,改一处必须同改两处。
|
||||
|
||||
+7
-2
@@ -7,6 +7,7 @@ import com.nanri.aiimage.modules.company.model.dto.CompanySaveRequest;
|
||||
import com.nanri.aiimage.modules.company.model.vo.CompanyVo;
|
||||
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -16,6 +17,7 @@ import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
@@ -35,9 +37,12 @@ public class CompanyController {
|
||||
|
||||
@GetMapping("/companies")
|
||||
@Operation(summary = "公司目录:仅超级管理员可读,非超管一律 403")
|
||||
public ApiResponse<List<CompanyVo>> listCompanies(HttpServletRequest request) {
|
||||
public ApiResponse<List<CompanyVo>> listCompanies(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "所属平台(V206):amazon|jd,缺省不过滤")
|
||||
@RequestParam(name = "platform", required = false) String platform) {
|
||||
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||
List<CompanyVo> items = companyService.listVisible(operator).stream().map(CompanyVo::from).toList();
|
||||
List<CompanyVo> items = companyService.listVisible(operator, platform).stream().map(CompanyVo::from).toList();
|
||||
return ApiResponse.success(items);
|
||||
}
|
||||
|
||||
|
||||
+4
@@ -14,4 +14,8 @@ public class CompanySaveRequest {
|
||||
/** 1=启用 0=停用;null 按启用(与 company.status 的 DEFAULT 1 一致)。 */
|
||||
private Integer status;
|
||||
private String remark;
|
||||
/**
|
||||
* 所属平台(V206):新建 null/空白按 'amazon';编辑 null=不动,给了就只认 amazon|jd。
|
||||
*/
|
||||
private String platform;
|
||||
}
|
||||
|
||||
+5
@@ -22,6 +22,11 @@ public class CompanyEntity {
|
||||
/** 1=启用 0=停用。停用不删行:有账号挂着的公司删不掉。 */
|
||||
private Integer status;
|
||||
private String remark;
|
||||
/**
|
||||
* 所属平台(V206 新增):amazon|jd,与后管侧边栏平台 tab 同字面量。只作用于后管
|
||||
* 公司管理页的显示与筛选;存量 DEFAULT 'amazon',京东侧由使用者在编辑弹窗里翻档。
|
||||
*/
|
||||
private String platform;
|
||||
@TableField("created_at")
|
||||
private LocalDateTime createdAt;
|
||||
@TableField("updated_at")
|
||||
|
||||
@@ -20,6 +20,9 @@ public class CompanyVo {
|
||||
private String companyName;
|
||||
private Integer status;
|
||||
private String remark;
|
||||
/** 所属平台(V206):amazon|jd,与后管侧边栏平台 tab 同字面量。 */
|
||||
@JsonProperty("platform")
|
||||
private String platform;
|
||||
@JsonProperty("created_at")
|
||||
private String createdAt;
|
||||
@JsonProperty("updated_at")
|
||||
@@ -31,6 +34,7 @@ public class CompanyVo {
|
||||
vo.setCompanyName(entity.getCompanyName());
|
||||
vo.setStatus(entity.getStatus());
|
||||
vo.setRemark(entity.getRemark());
|
||||
vo.setPlatform(entity.getPlatform());
|
||||
vo.setCreatedAt(entity.getCreatedAt() == null ? "" : entity.getCreatedAt().format(TIME));
|
||||
vo.setUpdatedAt(entity.getUpdatedAt() == null ? "" : entity.getUpdatedAt().format(TIME));
|
||||
return vo;
|
||||
|
||||
+22
-2
@@ -5,6 +5,7 @@ import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import com.nanri.aiimage.common.service.AdminPlatformScope;
|
||||
import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
|
||||
import com.nanri.aiimage.modules.company.model.dto.CompanySaveRequest;
|
||||
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||
@@ -59,6 +60,14 @@ public class CompanyService {
|
||||
* 角色不会被"忘了授权"打穿,所以这里用 {@link #ensureSuperAdmin} 与写入口共用同一个出口。</p>
|
||||
*/
|
||||
public List<CompanyEntity> listVisible(AdminUserEntity operator) {
|
||||
return listVisible(operator, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 带平台过滤的公司目录(V206):platform 非空白时只返回该平台的公司(amazon|jd,非法值 400),
|
||||
* 后管「公司管理」页按当前平台 tab 传参;null/空白=不过滤,旧调用方口径不变。
|
||||
*/
|
||||
public List<CompanyEntity> listVisible(AdminUserEntity operator, String platform) {
|
||||
String role = adminAuthSupport.currentRole(operator);
|
||||
if (role == null) {
|
||||
throw new BusinessException(403, "需要管理员权限");
|
||||
@@ -66,8 +75,13 @@ public class CompanyService {
|
||||
// 读写都只超管(spec §2 的 A 类):判角色、不判菜单授权——
|
||||
// 12:3x 已经证明"把可见性挂在 user_column_permission 上"会因一笔授权没发而全员 403。
|
||||
ensureSuperAdmin(operator);
|
||||
return companyMapper.selectList(new LambdaQueryWrapper<CompanyEntity>()
|
||||
.orderByAsc(CompanyEntity::getId));
|
||||
LambdaQueryWrapper<CompanyEntity> query = new LambdaQueryWrapper<>();
|
||||
String platformValue = AdminPlatformScope.normalizeOrNull(platform);
|
||||
if (platformValue != null) {
|
||||
query.eq(CompanyEntity::getPlatform, platformValue);
|
||||
}
|
||||
query.orderByAsc(CompanyEntity::getId);
|
||||
return companyMapper.selectList(query);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -127,6 +141,7 @@ public class CompanyService {
|
||||
entity.setCompanyName(companyName);
|
||||
entity.setStatus(status);
|
||||
entity.setRemark(remark);
|
||||
entity.setPlatform(AdminPlatformScope.normalizeOrCreate(request.getPlatform()));
|
||||
companyMapper.insert(entity);
|
||||
permissionMenuService.copyTreeFromTemplate(entity.getId(), operator.getCompanyId());
|
||||
return entity;
|
||||
@@ -142,12 +157,17 @@ public class CompanyService {
|
||||
String companyName = requireValidName(request.getCompanyName());
|
||||
int status = resolveStatus(request.getStatus());
|
||||
String remark = normalizeRemark(request.getRemark());
|
||||
// 平台只在显式给出时落(null/空白=不动),与 users 的 PUT 同口径
|
||||
String platform = AdminPlatformScope.normalizeOrNull(request.getPlatform());
|
||||
// 排除自己:只改备注时名字没变,不排除就会把合法编辑判成重名
|
||||
ensureNameAvailable(companyName, id);
|
||||
|
||||
company.setCompanyName(companyName);
|
||||
company.setStatus(status);
|
||||
company.setRemark(remark);
|
||||
if (platform != null) {
|
||||
company.setPlatform(platform);
|
||||
}
|
||||
companyMapper.updateById(company);
|
||||
return company;
|
||||
}
|
||||
|
||||
-125
@@ -1,125 +0,0 @@
|
||||
package com.nanri.aiimage.modules.evidence.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import com.nanri.aiimage.modules.evidence.model.entity.TaskEvidenceEntity;
|
||||
import com.nanri.aiimage.modules.evidence.service.TaskEvidenceService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 后台「任务证据」读取面(AC-13):列表 / 内容 / 下载 / 删除,仅超级管理员。
|
||||
*
|
||||
* <p>证据件含账号可见的现场信息与窗口截图,访问面比常规后台更严;这里每个方法都走
|
||||
* 私有 {@link #requireSuperAdmin(HttpServletRequest)},与 AdminDeviceLogController 同口径。
|
||||
* 对象直链与预签名 URL 不入日志、不回前端——下载统一走服务端流。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/admin/task-evidence")
|
||||
@Tag(name = "任务证据(后台)", description = "任务异常现场证据件的列表、内容、下载与删除(仅超管)。")
|
||||
public class AdminTaskEvidenceController {
|
||||
|
||||
private final TaskEvidenceService taskEvidenceService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
|
||||
@GetMapping("/files")
|
||||
@Operation(summary = "证据件分页列表", description = "按 taskId 关联查询;uid 只作为精确过滤条件。")
|
||||
public ApiResponse<Map<String, Object>> files(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "业务任务号") @RequestParam(required = false) String taskId,
|
||||
@Parameter(description = "归属用户 uid") @RequestParam(required = false) Long uid,
|
||||
@RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@RequestParam(defaultValue = PageDefaults.ADMIN_LIST_PAGE_SIZE) Long pageSize) {
|
||||
AdminUserEntity operator = requireSuperAdmin(request);
|
||||
if (uid != null && !uid.equals(operator.getId())) {
|
||||
// requireSuperAdmin 已保证当前是超管;uid 过滤仍与操作者归属对撞,防伪造 uid 越权读。
|
||||
log.info("[task-evidence] 超管按 uid 过滤证据 userId={} targetUid={}",
|
||||
operator.getId(), uid);
|
||||
}
|
||||
return ApiResponse.success(taskEvidenceService.page(taskId, uid, page, pageSize));
|
||||
}
|
||||
|
||||
@GetMapping("/content")
|
||||
@Operation(summary = "查看证据件内容", description = "文本证据按 UTF-8 返回;图片证据返回 base64。")
|
||||
public ApiResponse<Map<String, Object>> content(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "证据主键") @RequestParam Long fileId) {
|
||||
requireSuperAdmin(request);
|
||||
return ApiResponse.success(taskEvidenceService.content(fileId));
|
||||
}
|
||||
|
||||
@GetMapping("/download")
|
||||
@Operation(summary = "下载证据件", description = "服务端从独立证据桶流式读取,不返回直链。")
|
||||
public void download(HttpServletRequest request, HttpServletResponse response,
|
||||
@Parameter(description = "证据主键") @RequestParam Long fileId) throws IOException {
|
||||
requireSuperAdmin(request);
|
||||
TaskEvidenceEntity entity = taskEvidenceService.requireEvidence(fileId);
|
||||
String name = "evidence-" + entity.getId()
|
||||
+ (entity.getObjectKey() != null && entity.getObjectKey().contains(".")
|
||||
? entity.getObjectKey().substring(entity.getObjectKey().lastIndexOf('.')) : ".bin");
|
||||
response.setContentType(entity.getContentType() == null
|
||||
? "application/octet-stream" : entity.getContentType());
|
||||
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''"
|
||||
+ URLEncoder.encode(name, StandardCharsets.UTF_8).replace("+", "%20"));
|
||||
taskEvidenceService.downloadTo(fileId, response.getOutputStream());
|
||||
}
|
||||
|
||||
@PostMapping("/delete")
|
||||
@Operation(summary = "删除证据件", description = "先删对象再删登记行;不可恢复。")
|
||||
public ApiResponse<Map<String, Object>> delete(
|
||||
HttpServletRequest request,
|
||||
@RequestBody(required = false) List<Long> ids,
|
||||
@RequestParam(required = false) Long fileId) {
|
||||
requireSuperAdmin(request);
|
||||
List<Long> targets = new ArrayList<>();
|
||||
if (ids != null) {
|
||||
targets.addAll(ids);
|
||||
}
|
||||
if (fileId != null) {
|
||||
targets.add(fileId);
|
||||
}
|
||||
if (targets.isEmpty()) {
|
||||
throw new BusinessException("未指定要删除的证据");
|
||||
}
|
||||
int deleted = taskEvidenceService.delete(targets);
|
||||
return ApiResponse.success("已删除", Map.of("deleted", deleted));
|
||||
}
|
||||
|
||||
/**
|
||||
* 证据件仅超管可读:requireAdmin 不含超管判定,这里再判一层。
|
||||
* 返回操作者供列表端点做 uid 归属对撞。
|
||||
*/
|
||||
private AdminUserEntity requireSuperAdmin(HttpServletRequest request) {
|
||||
AdminUserEntity user = adminAuthSupport.requireAdmin(request);
|
||||
if (!DeviceSessionPolicy.isSuper(adminAuthSupport.currentRole(user))) {
|
||||
log.warn("[task-evidence] 非超管访问被拒 userId={} username={}",
|
||||
user.getId(), user.getUsername());
|
||||
throw new BusinessException(403, "仅超级管理员可访问任务证据");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
}
|
||||
-59
@@ -1,59 +0,0 @@
|
||||
package com.nanri.aiimage.modules.evidence.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.evidence.model.dto.TaskEvidenceRegisterRequest;
|
||||
import com.nanri.aiimage.modules.evidence.service.TaskEvidenceService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 内部接口:客户端证据件登记(AC-7)。客户端先把现场件分片上传到 Java 临时目录,
|
||||
* 上传完成后携带 X-Internal-Token 与 task_id/file_key 登记;服务端再把临时件搬进
|
||||
* 独立证据桶并落 biz_task_evidence。
|
||||
*
|
||||
* <p>/api/internal 虽在 AdminApiGuardFilter 兜底名单内、可信令牌会放行,controller
|
||||
* 仍自校验令牌——防止配置漂移时匿名可达。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/internal/task-evidence")
|
||||
@Tag(name = "内部接口", description = "证据件登记(X-Internal-Token 鉴权)。")
|
||||
public class InternalTaskEvidenceController {
|
||||
|
||||
private final TaskEvidenceService taskEvidenceService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
|
||||
@PostMapping("/register")
|
||||
@Operation(summary = "登记任务证据件", description = "按 task_id 关联;file_key 指向已上传到临时目录的证据件。")
|
||||
public ApiResponse<Map<String, Object>> register(HttpServletRequest request,
|
||||
@RequestBody(required = false) TaskEvidenceRegisterRequest body) {
|
||||
if (!adminAuthSupport.isTrustedInternalToken(request)) {
|
||||
log.warn("[task-evidence] 拒绝未携带可信内部令牌的登记请求 remoteAddr={}",
|
||||
request.getRemoteAddr());
|
||||
throw new BusinessException(401, "未授权");
|
||||
}
|
||||
if (body == null) {
|
||||
throw new BusinessException("登记载荷为空");
|
||||
}
|
||||
// P1-2:归属以会话身份为准。内部令牌是发给每个登录客户的共享凭据,body.uid 谁都能写——
|
||||
// 真身份只能来自请求头里的用户 JWT(4.0.14 起 user_token 钩子统一注入);会话 uid 与
|
||||
// body.uid 不一致直接 403,无身份的存量装机保留原参数并打节流的匿名兜底日志。
|
||||
Long uid = adminAuthSupport.resolveOwnershipUserId(request, body.getUid());
|
||||
Map<String, Object> result = taskEvidenceService.register(
|
||||
body.getTaskId(), uid, body.getEvidenceType(), body.getSource(), body.getFileKey());
|
||||
log.info("[task-evidence] registered id={} taskId={} uid={}", result.get("id"), body.getTaskId(), uid);
|
||||
return ApiResponse.success(result);
|
||||
}
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
package com.nanri.aiimage.modules.evidence.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.nanri.aiimage.modules.evidence.model.entity.TaskEvidenceEntity;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface TaskEvidenceMapper extends BaseMapper<TaskEvidenceEntity> {
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package com.nanri.aiimage.modules.evidence.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 客户端证据登记载荷(snake_case 与客户端现场件字段同口径)。
|
||||
*/
|
||||
@Data
|
||||
public class TaskEvidenceRegisterRequest {
|
||||
|
||||
@JsonProperty("task_id")
|
||||
private String taskId;
|
||||
|
||||
@JsonProperty("file_key")
|
||||
private String fileKey;
|
||||
|
||||
@JsonProperty("evidence_type")
|
||||
private String evidenceType;
|
||||
|
||||
private String source;
|
||||
|
||||
private Long uid;
|
||||
}
|
||||
-45
@@ -1,45 +0,0 @@
|
||||
package com.nanri.aiimage.modules.evidence.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 任务异常现场证据件登记(表 biz_task_evidence,V182)。
|
||||
*
|
||||
* <p>只登记归属与对象元数据;对象本体在独立证据桶,直链/预签名 URL 不入库、不入日志。</p>
|
||||
*/
|
||||
@Data
|
||||
@TableName("biz_task_evidence")
|
||||
public class TaskEvidenceEntity {
|
||||
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
/** 业务任务号(客户端字符串口径,允许非数字)。 */
|
||||
private String taskId;
|
||||
|
||||
/** 任务归属用户;未知时为空。 */
|
||||
private Long uid;
|
||||
|
||||
/** 证据类型:client/crash/brand 等。 */
|
||||
private String evidenceType;
|
||||
|
||||
/** 来源入口(崩溃记录器/商品采集等)。 */
|
||||
private String source;
|
||||
|
||||
/** 证据桶内对象 key(含 UUID)。 */
|
||||
private String objectKey;
|
||||
|
||||
private Long byteSize;
|
||||
|
||||
private String contentType;
|
||||
|
||||
/** 对象 sha256(防篡改/去重)。 */
|
||||
private String sha256;
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
-325
@@ -1,325 +0,0 @@
|
||||
package com.nanri.aiimage.modules.evidence.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.service.DistributedJobLockService;
|
||||
import com.nanri.aiimage.common.task.LockSkipWitness;
|
||||
import com.nanri.aiimage.config.EvidenceProperties;
|
||||
import com.nanri.aiimage.modules.evidence.mapper.TaskEvidenceMapper;
|
||||
import com.nanri.aiimage.modules.evidence.model.entity.TaskEvidenceEntity;
|
||||
import com.nanri.aiimage.modules.evidence.storage.TaskEvidenceStorageService;
|
||||
import com.nanri.aiimage.modules.file.service.LocalFileStorageService;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 证据登记与读取(AC-7/AC-13)。
|
||||
*
|
||||
* <p>登记走「客户端先分片上云到 Java 临时目录,再由服务端搬进独立证据桶」:客户端不持有
|
||||
* 任何对象存储凭据,object_key/sha256/size 全部由服务端生成,登记接口不接受直链。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class TaskEvidenceService {
|
||||
|
||||
private static final int MAX_TASK_ID_LENGTH = 64;
|
||||
private static final int MAX_CONTENT_BYTES = 8 * 1024 * 1024;
|
||||
private static final int RETENTION_BATCH = 200;
|
||||
/** 单轮保留期最多扫的批次数:防一个删不掉的对象把进程拖成永动机。 */
|
||||
private static final int MAX_RETENTION_BATCHES = 20;
|
||||
/** 同一任务的证据件数上限:登记端点不设防的话,一个持证客户端能刷满整个证据桶(P2-2)。 */
|
||||
private static final int MAX_EVIDENCE_PER_TASK = 50;
|
||||
/** 保留期回收的分布式锁名:A/B 两台每晚各扫同一张表会互相删(同族口径见 DeviceLogRetentionService)。 */
|
||||
static final String RETENTION_LOCK = "task-evidence:retention";
|
||||
private static final Set<String> ALLOWED_EVIDENCE_TYPES =
|
||||
Set.of("client", "crash", "window_image", "page_image", "brand", "other");
|
||||
private static final Set<String> ALLOWED_SOURCES =
|
||||
Set.of("client", "crash_recorder", "window", "page", "brand", "other");
|
||||
|
||||
private final TaskEvidenceMapper mapper;
|
||||
private final TaskEvidenceStorageService storage;
|
||||
private final LocalFileStorageService localFileStorageService;
|
||||
private final EvidenceProperties properties;
|
||||
private final FileTaskMapper fileTaskMapper;
|
||||
private final DistributedJobLockService distributedJobLockService;
|
||||
|
||||
/** 客户端上传完成后登记:fileKey 指向 Java 临时目录里的分片拼装件。 */
|
||||
public Map<String, Object> register(String taskId, Long uid, String evidenceType,
|
||||
String source, String fileKey) {
|
||||
String normalizedTaskId = normalizeTaskId(taskId);
|
||||
if (fileKey == null || fileKey.isBlank()) {
|
||||
throw new BusinessException("证据文件标识为空");
|
||||
}
|
||||
File file = localFileStorageService.findLocalSourceFile(fileKey.trim());
|
||||
if (file == null || !file.isFile()) {
|
||||
throw new BusinessException("证据文件不存在或已过期");
|
||||
}
|
||||
// P1-2:归属先于落桶。task_id 能对上库里的任务行时,uid 必须就是行主——判据发生在
|
||||
// storage.store 之前,否则每一次拒绝都往证据桶里丢一个收不回的孤儿对象。
|
||||
assertTaskOwnedBy(normalizedTaskId, uid);
|
||||
if (file.length() == 0) {
|
||||
throw new BusinessException("证据件为空,拒绝登记");
|
||||
}
|
||||
if (countByTask(normalizedTaskId) >= MAX_EVIDENCE_PER_TASK) {
|
||||
throw new BusinessException("该任务的证据件数已达上限");
|
||||
}
|
||||
TaskEvidenceStorageService.StoredEvidence stored;
|
||||
try {
|
||||
stored = storage.store(file, normalizedTaskId, file.getName());
|
||||
} catch (IOException | RuntimeException ex) {
|
||||
log.warn("[task-evidence] register failed taskId={} reason={}",
|
||||
normalizedTaskId, ex.getMessage());
|
||||
throw new BusinessException("证据件入库失败,请稍后重试");
|
||||
}
|
||||
TaskEvidenceEntity entity = new TaskEvidenceEntity();
|
||||
entity.setTaskId(normalizedTaskId);
|
||||
entity.setUid(uid);
|
||||
entity.setEvidenceType(normalizeLabel(evidenceType, "client", ALLOWED_EVIDENCE_TYPES));
|
||||
entity.setSource(normalizeLabel(source, "client", ALLOWED_SOURCES));
|
||||
entity.setObjectKey(stored.objectKey());
|
||||
entity.setByteSize(stored.byteSize());
|
||||
entity.setContentType(stored.contentType());
|
||||
entity.setSha256(stored.sha256());
|
||||
entity.setCreatedAt(LocalDateTime.now());
|
||||
try {
|
||||
mapper.insert(entity);
|
||||
} catch (RuntimeException ex) {
|
||||
// 对象已写进桶、登记行没落:不回收就是永久孤儿(保留期只扫登记行)。
|
||||
log.warn("[task-evidence] 登记行写入失败,回收对象 taskId={} key={} reason={}",
|
||||
normalizedTaskId, stored.objectKey(), ex.getMessage());
|
||||
try {
|
||||
storage.delete(stored.objectKey());
|
||||
} catch (RuntimeException cleanup) {
|
||||
log.warn("[task-evidence] 回收孤儿对象失败 key={} reason={}",
|
||||
stored.objectKey(), cleanup.getMessage());
|
||||
}
|
||||
throw new BusinessException("证据件登记失败,请稍后重试");
|
||||
}
|
||||
deleteTempQuietly(file);
|
||||
Map<String, Object> result = new LinkedHashMap<>();
|
||||
result.put("id", entity.getId());
|
||||
result.put("objectKey", entity.getObjectKey());
|
||||
result.put("byteSize", entity.getByteSize());
|
||||
return result;
|
||||
}
|
||||
|
||||
public Map<String, Object> page(String taskId, Long uid, long page, long pageSize) {
|
||||
long safePage = Math.max(1, page);
|
||||
long safeSize = Math.min(Math.max(1, pageSize), 200);
|
||||
LambdaQueryWrapper<TaskEvidenceEntity> query = new LambdaQueryWrapper<>();
|
||||
if (taskId != null && !taskId.isBlank()) {
|
||||
query.eq(TaskEvidenceEntity::getTaskId, taskId.trim());
|
||||
}
|
||||
if (uid != null) {
|
||||
query.eq(TaskEvidenceEntity::getUid, uid);
|
||||
}
|
||||
query.orderByDesc(TaskEvidenceEntity::getId);
|
||||
Page<TaskEvidenceEntity> result = mapper.selectPage(new Page<>(safePage, safeSize), query);
|
||||
Map<String, Object> data = new LinkedHashMap<>();
|
||||
data.put("items", result.getRecords());
|
||||
data.put("total", result.getTotal());
|
||||
data.put("page", safePage);
|
||||
data.put("pageSize", safeSize);
|
||||
return data;
|
||||
}
|
||||
|
||||
public TaskEvidenceEntity requireEvidence(Long fileId) {
|
||||
if (fileId == null) {
|
||||
throw new BusinessException("证据主键为空");
|
||||
}
|
||||
TaskEvidenceEntity entity = mapper.selectById(fileId);
|
||||
if (entity == null) {
|
||||
throw new BusinessException("证据不存在或已过期");
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
public Map<String, Object> content(Long fileId) {
|
||||
TaskEvidenceEntity entity = requireEvidence(fileId);
|
||||
byte[] bytes = storage.read(entity.getObjectKey(), MAX_CONTENT_BYTES);
|
||||
Map<String, Object> data = new LinkedHashMap<>();
|
||||
data.put("id", entity.getId());
|
||||
data.put("taskId", entity.getTaskId());
|
||||
data.put("contentType", entity.getContentType());
|
||||
boolean binary = entity.getContentType() != null && entity.getContentType().startsWith("image/");
|
||||
data.put("binary", binary);
|
||||
data.put("content", binary
|
||||
? java.util.Base64.getEncoder().encodeToString(bytes)
|
||||
: new String(bytes, java.nio.charset.StandardCharsets.UTF_8));
|
||||
return data;
|
||||
}
|
||||
|
||||
public byte[] download(Long fileId) {
|
||||
TaskEvidenceEntity entity = requireEvidence(fileId);
|
||||
return storage.read(entity.getObjectKey(), properties.maxFileBytesOrDefault());
|
||||
}
|
||||
|
||||
/** P3-1:后管下载走流式,避免 64MB 级对象整块进堆。 */
|
||||
public void downloadTo(Long fileId, OutputStream out) {
|
||||
TaskEvidenceEntity entity = requireEvidence(fileId);
|
||||
storage.downloadTo(entity.getObjectKey(), out, properties.maxFileBytesOrDefault());
|
||||
}
|
||||
|
||||
/** 删除证据:先删对象再删登记行;对象删除失败不吞(留在库里下一轮可重试)。 */
|
||||
public int delete(List<Long> ids) {
|
||||
if (ids == null || ids.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
int deleted = 0;
|
||||
for (Long id : ids) {
|
||||
TaskEvidenceEntity entity = id == null ? null : mapper.selectById(id);
|
||||
if (entity == null) {
|
||||
continue;
|
||||
}
|
||||
storage.delete(entity.getObjectKey());
|
||||
deleted += mapper.deleteById(id);
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保留期回收:按天清扫到期行与对象(AC-13 的保留期必须有执行者,不能只写在配置里)。
|
||||
*
|
||||
* <p>P1-7 的两条修正:① A/B 两台每晚并发扫同一张表,回收必须拿分布式锁(同族口径见
|
||||
* {@code DeviceLogRetentionService},锁跳过走可聚合出口);② 对象删除失败不再让整轮早退——
|
||||
* 原先翻页永远停在第 1 页,卡住的那一行把后面每一行都堵死,配置里的 retention-days
|
||||
* 因此只是个数字。改成按 id 键集分页:失败行留在库里下一轮重试,后面的行照常推进。
|
||||
*/
|
||||
@Scheduled(cron = "${aiimage.evidence.retention-cron:0 30 3 * * *}")
|
||||
public void purgeExpired() {
|
||||
DistributedJobLockService.LockHandle lockHandle =
|
||||
distributedJobLockService.tryLock(RETENTION_LOCK, Duration.ofMinutes(15));
|
||||
if (lockHandle == null) {
|
||||
// 点位字面量必须写死(LockSkipSilentExitGuardrailTest 的判据),与 RETENTION_LOCK 同值。
|
||||
LockSkipWitness.skipped("task-evidence:retention");
|
||||
log.info("[task-evidence] 保留期清理跳过:另一实例持锁");
|
||||
return;
|
||||
}
|
||||
try (lockHandle) {
|
||||
purgeExpiredLocked(LocalDateTime.now().minusDays(properties.retentionDaysOrDefault()));
|
||||
} catch (Exception ex) {
|
||||
log.warn("[task-evidence] 保留期清理失败 reason={}", ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void purgeExpiredLocked(LocalDateTime expireBefore) {
|
||||
long afterId = 0L;
|
||||
int removed = 0;
|
||||
int failed = 0;
|
||||
int batches = 0;
|
||||
while (batches < MAX_RETENTION_BATCHES) {
|
||||
List<TaskEvidenceEntity> batch = mapper.selectList(new LambdaQueryWrapper<TaskEvidenceEntity>()
|
||||
.gt(TaskEvidenceEntity::getId, afterId)
|
||||
.lt(TaskEvidenceEntity::getCreatedAt, expireBefore)
|
||||
.orderByAsc(TaskEvidenceEntity::getId)
|
||||
.last("limit " + RETENTION_BATCH));
|
||||
if (batch.isEmpty()) {
|
||||
break;
|
||||
}
|
||||
batches++;
|
||||
for (TaskEvidenceEntity entity : batch) {
|
||||
afterId = entity.getId();
|
||||
try {
|
||||
storage.delete(entity.getObjectKey());
|
||||
removed += mapper.deleteById(entity.getId());
|
||||
} catch (RuntimeException ex) {
|
||||
// 只跳过这一行:登记行留着,下一轮按同一条键集再试;后面的行绝不陪葬。
|
||||
failed++;
|
||||
log.warn("[task-evidence] retention delete failed id={} reason={}",
|
||||
entity.getId(), ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (failed > 0) {
|
||||
log.warn("[task-evidence] retention purge finished with failures removed={} failed={} batches={}",
|
||||
removed, failed, batches);
|
||||
} else if (removed > 0 || batches > 0) {
|
||||
log.info("[task-evidence] retention purge removed={} batches={}", removed, batches);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* P1-2 的归属判定:task_id 对得上库里的任务行时 uid 必须就是行主;对不上行(客户端本地
|
||||
* 任务号,如商品采集的自有作业 id)只要求带 uid 自证——否则任何一个持内部令牌的客户端
|
||||
* 都能往别人的取证面里挂证据。
|
||||
*/
|
||||
private void assertTaskOwnedBy(String taskId, Long uid) {
|
||||
Long ownerId = resolveTaskOwnerId(taskId);
|
||||
if (uid == null) {
|
||||
throw new BusinessException(403, "证据登记必须携带任务归属用户");
|
||||
}
|
||||
if (ownerId != null && !ownerId.equals(uid)) {
|
||||
throw new BusinessException(403, "证据件只能登记到本人任务上");
|
||||
}
|
||||
}
|
||||
|
||||
/** 数字串按主键查(超长数字串会溢出,降级走 task_no),其余按 task_no 点查。 */
|
||||
private Long resolveTaskOwnerId(String taskId) {
|
||||
FileTaskEntity row = null;
|
||||
if (taskId.chars().allMatch(Character::isDigit)) {
|
||||
try {
|
||||
row = fileTaskMapper.selectById(Long.parseLong(taskId));
|
||||
} catch (NumberFormatException overflow) {
|
||||
row = null;
|
||||
}
|
||||
}
|
||||
if (row == null) {
|
||||
row = fileTaskMapper.selectOne(new LambdaQueryWrapper<FileTaskEntity>()
|
||||
.eq(FileTaskEntity::getTaskNo, taskId)
|
||||
.last("limit 1"));
|
||||
}
|
||||
return row == null ? null : row.getUserId();
|
||||
}
|
||||
|
||||
private long countByTask(String taskId) {
|
||||
Long count = mapper.selectCount(new LambdaQueryWrapper<TaskEvidenceEntity>()
|
||||
.eq(TaskEvidenceEntity::getTaskId, taskId));
|
||||
return count == null ? 0L : count;
|
||||
}
|
||||
|
||||
private String normalizeTaskId(String taskId) {
|
||||
String value = taskId == null ? "" : taskId.trim();
|
||||
if (value.isEmpty()) {
|
||||
throw new BusinessException("任务号为空");
|
||||
}
|
||||
if (value.length() > MAX_TASK_ID_LENGTH) {
|
||||
value = value.substring(0, MAX_TASK_ID_LENGTH);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private String normalizeLabel(String value, String fallback, Set<String> allowed) {
|
||||
String text = value == null ? "" : value.trim().toLowerCase(Locale.ROOT);
|
||||
if (text.isEmpty()) {
|
||||
return fallback;
|
||||
}
|
||||
// 列宽是 VARCHAR(32),超长标签在这里截断而不是让 insert 抛数据截断错;
|
||||
// 不在白名单内的标签一律落 other,不让客户端自造类型污染取证面。
|
||||
String normalized = text.length() > 32 ? text.substring(0, 32) : text;
|
||||
return allowed.contains(normalized) ? normalized : "other";
|
||||
}
|
||||
|
||||
private void deleteTempQuietly(File file) {
|
||||
if (file != null && file.exists() && !file.delete()) {
|
||||
log.warn("[task-evidence] temp evidence cleanup failed name={}", file.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
-122
@@ -1,122 +0,0 @@
|
||||
package com.nanri.aiimage.modules.evidence.storage;
|
||||
|
||||
import cn.hutool.crypto.digest.DigestUtil;
|
||||
import com.nanri.aiimage.config.EvidenceProperties;
|
||||
import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Locale;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 证据对象的独立落点(AC-13):桶与 key 前缀来自 {@link EvidenceProperties},
|
||||
* 对象本体不经过业务桶,也不把直链/预签名 URL 写进任何日志或数据库。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class TaskEvidenceStorageService {
|
||||
|
||||
private static final Pattern TASK_ID_SAFE = Pattern.compile("[^0-9A-Za-z_.-]+");
|
||||
private static final Pattern EXT_SAFE = Pattern.compile("\\.[0-9A-Za-z]{1,10}");
|
||||
|
||||
private final EvidenceProperties properties;
|
||||
private final OssStorageService ossStorageService;
|
||||
|
||||
private volatile boolean bucketReady;
|
||||
|
||||
/** 落一份证据对象,返回对象 key 与对象元数据。 */
|
||||
public StoredEvidence store(File source, String taskId, String originalFilename) throws IOException {
|
||||
if (source == null || !source.isFile()) {
|
||||
throw new IllegalArgumentException("evidence file must exist");
|
||||
}
|
||||
long size = source.length();
|
||||
if (size > properties.maxFileBytesOrDefault()) {
|
||||
throw new IllegalArgumentException("evidence file too large");
|
||||
}
|
||||
String bucket = properties.bucketOrDefault();
|
||||
ensureBucket(bucket);
|
||||
String key = objectKey(taskId, originalFilename);
|
||||
ossStorageService.uploadFileToBucket(source, bucket, key);
|
||||
return new StoredEvidence(key, size, sha256(source), contentType(originalFilename));
|
||||
}
|
||||
|
||||
public byte[] read(String objectKey, long maxBytes) {
|
||||
return ossStorageService.readObjectBytes(
|
||||
properties.bucketOrDefault(), objectKey, maxBytes);
|
||||
}
|
||||
|
||||
/** P3-1:下载走流式,不把整个证据件读进堆。 */
|
||||
public void downloadTo(String objectKey, java.io.OutputStream out, long maxBytes) {
|
||||
ossStorageService.readObjectToStream(properties.bucketOrDefault(), objectKey, out, maxBytes);
|
||||
}
|
||||
|
||||
public void delete(String objectKey) {
|
||||
if (objectKey == null || objectKey.isBlank()) {
|
||||
return;
|
||||
}
|
||||
ossStorageService.removeObject(properties.bucketOrDefault(), objectKey);
|
||||
}
|
||||
|
||||
public String bucket() {
|
||||
return properties.bucketOrDefault();
|
||||
}
|
||||
|
||||
private void ensureBucket(String bucket) {
|
||||
if (bucketReady) {
|
||||
return;
|
||||
}
|
||||
synchronized (this) {
|
||||
if (bucketReady) {
|
||||
return;
|
||||
}
|
||||
ossStorageService.ensureBucketExists(bucket);
|
||||
bucketReady = true;
|
||||
log.info("[task-evidence] evidence bucket ready bucket={}", bucket);
|
||||
}
|
||||
}
|
||||
|
||||
private String objectKey(String taskId, String originalFilename) {
|
||||
String safeTask = TASK_ID_SAFE.matcher(taskId == null ? "" : taskId.trim())
|
||||
.replaceAll("_");
|
||||
if (safeTask.isEmpty()) {
|
||||
safeTask = "unknown";
|
||||
}
|
||||
return properties.keyPrefixOrDefault() + safeTask + "/" + UUID.randomUUID() + extension(originalFilename);
|
||||
}
|
||||
|
||||
private String extension(String originalFilename) {
|
||||
String name = originalFilename == null ? "" : originalFilename.trim();
|
||||
int slash = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\'));
|
||||
if (slash >= 0) {
|
||||
name = name.substring(slash + 1);
|
||||
}
|
||||
int dot = name.lastIndexOf('.');
|
||||
String ext = dot < 0 ? "" : name.substring(dot).toLowerCase(Locale.ROOT);
|
||||
return EXT_SAFE.matcher(ext).matches() ? ext : ".bin";
|
||||
}
|
||||
|
||||
private String contentType(String originalFilename) {
|
||||
String ext = extension(originalFilename);
|
||||
return switch (ext) {
|
||||
case ".json" -> "application/json";
|
||||
case ".png" -> "image/png";
|
||||
case ".jpg", ".jpeg" -> "image/jpeg";
|
||||
case ".webp" -> "image/webp";
|
||||
case ".txt", ".log" -> "text/plain; charset=utf-8";
|
||||
default -> "application/octet-stream";
|
||||
};
|
||||
}
|
||||
|
||||
private String sha256(File source) {
|
||||
return DigestUtil.sha256Hex(source);
|
||||
}
|
||||
|
||||
public record StoredEvidence(String objectKey, long byteSize, String sha256, String contentType) {
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -120,6 +120,9 @@ public class AdminJdProductController {
|
||||
@RequestParam(name = "synced_from", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedFrom,
|
||||
@Parameter(description = "同步结束时间(包含,ISO datetime)")
|
||||
@RequestParam(name = "synced_to", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime syncedTo,
|
||||
@Parameter(description = "分类状态快筛(2026-11-17 用户口径「加个已分类和未分类的筛选」):"
|
||||
+ "true=当前分组下有分类,false=未分类,缺省=全部;按 V203 归属表 SQL 侧下推")
|
||||
@RequestParam(name = "classified", required = false) Boolean classified,
|
||||
HttpServletRequest request) {
|
||||
RequestOperator operator = requireJdAccess(request);
|
||||
if (request.getParameter("grouped") != null || request.getParameter("ungrouped") != null) {
|
||||
@@ -131,7 +134,8 @@ public class AdminJdProductController {
|
||||
requireVisibleCategory(scope, groupId);
|
||||
}
|
||||
return ApiResponse.success(jdProductQueryService.page(page, pageSize,
|
||||
productCode, titleKeyword, category, groupId, syncedFrom, syncedTo, scopedOwnerGroupId));
|
||||
productCode, titleKeyword, category, groupId, syncedFrom, syncedTo, classified,
|
||||
scopedOwnerGroupId));
|
||||
}
|
||||
|
||||
@GetMapping("/categories")
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
* (补登记口)登记落 {@code biz_jd_product_image}——服务端零图片字节。</p>
|
||||
*
|
||||
* <p>/api/internal 虽在 AdminApiGuardFilter 兜底名单内、可信令牌会放行,controller
|
||||
* 仍自校验令牌——防止配置漂移时匿名可达(InternalTaskEvidenceController 同款)。
|
||||
* 仍自校验令牌——防止配置漂移时匿名可达。
|
||||
* 身份以请求头 JWT 为准(user_token 钩子统一注入),body.uid 只作存量装机兜底;
|
||||
* 任务级 owner 对撞与 companyId 投影收口在 {@link JdProductImageIngestService}。</p>
|
||||
*/
|
||||
|
||||
@@ -49,13 +49,18 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
|
||||
* 「分类不要了,全部整合到类目里」撤掉(独立「分类」筛选框前端下线,
|
||||
* {@code groupId} 改由类目面板「自定义分类」选中驱动)。
|
||||
* 店铺名过滤参数已随 2026-11-15 客户口径「店铺不需要」同窗撤掉(DB 列与详情/回传链不动)。
|
||||
* {@code classified}+{@code ownerGroupId}(2026-11-17 用户口径「加个已分类和未分类的筛选」):
|
||||
* 按 V203 归属表 EXISTS/NOT EXISTS 快筛分类状态,NULL=不过滤;与 11-16 撤掉的旧
|
||||
* grouped/ungrouped(读已停用的 biz_jd_product.group_id 列)不是一回事。
|
||||
*/
|
||||
long countProducts(@Param("productCode") String productCode,
|
||||
@Param("titleKeyword") String titleKeyword,
|
||||
@Param("category") String category,
|
||||
@Param("groupId") Long groupId,
|
||||
@Param("syncedFrom") LocalDateTime syncedFrom,
|
||||
@Param("syncedTo") LocalDateTime syncedTo);
|
||||
@Param("syncedTo") LocalDateTime syncedTo,
|
||||
@Param("classified") Boolean classified,
|
||||
@Param("ownerGroupId") Long ownerGroupId);
|
||||
|
||||
/**
|
||||
* 商品上架配额计数({@code JdPublishQuotaService}):按 owner uid 集(管理员本人+
|
||||
@@ -95,6 +100,8 @@ public interface JdProductMapper extends BaseMapper<JdProductEntity> {
|
||||
@Param("groupId") Long groupId,
|
||||
@Param("syncedFrom") LocalDateTime syncedFrom,
|
||||
@Param("syncedTo") LocalDateTime syncedTo,
|
||||
@Param("classified") Boolean classified,
|
||||
@Param("ownerGroupId") Long ownerGroupId,
|
||||
@Param("offset") long offset,
|
||||
@Param("limit") int limit);
|
||||
|
||||
|
||||
+40
-27
@@ -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) {
|
||||
|
||||
+16
-11
@@ -79,14 +79,18 @@ public class JdProductQueryService {
|
||||
* 分页查询商品行({@code synced_at} 倒序)。
|
||||
*
|
||||
* <p>过滤面:商品编码 contains、标题关键词 contains、类目 eq、分组 eq(2026-11-16 起
|
||||
* 由类目面板「自定义分类」选中驱动)、同步起止(datetime 闭区间)。
|
||||
* 未分类/已分类两档(ungrouped/grouped)与独立「分类」筛选框随同日口径
|
||||
* 「分类不要了,全部整合到类目里」整批撤掉。
|
||||
* 由类目面板「自定义分类」选中驱动)、同步起止(datetime 闭区间)、分类状态档
|
||||
* {@code classified}(2026-11-17 用户口径「加个已分类和未分类的筛选」:true=当前分组下
|
||||
* 有分类、false=没有、null=全部;按 V203 归属表 EXISTS/NOT EXISTS 在 SQL 侧下推,
|
||||
* 判据与 {@link #fillGroupNames} 填分类列的条件同形——「筛选说未分类的行,列表分类列
|
||||
* 也必须是未分类」)。
|
||||
* 2026-11-16 撤掉的旧 ungrouped/grouped 两档读的是已停用的 biz_jd_product.group_id 列,
|
||||
* 与本档不是一回事;独立「分类」筛选框的撤掉口径不变。
|
||||
* 公司维过滤已随 2026-11-16 摘公司 tab 整批撤掉(全平台公共)。</p>
|
||||
*/
|
||||
public JdProductPageVo page(Long page, Long pageSize,
|
||||
String productCode, String titleKeyword, String category, Long groupId,
|
||||
LocalDateTime syncedFrom, LocalDateTime syncedTo, Long ownerGroupId) {
|
||||
LocalDateTime syncedFrom, LocalDateTime syncedTo, Boolean classified, Long ownerGroupId) {
|
||||
if (syncedFrom != null && syncedTo != null && syncedFrom.isAfter(syncedTo)) {
|
||||
throw new BusinessException("开始时间不能晚于结束时间");
|
||||
}
|
||||
@@ -94,14 +98,14 @@ public class JdProductQueryService {
|
||||
long safeSize = pageSize == null ? PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT
|
||||
: Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE);
|
||||
Filter filter = filter(productCode, titleKeyword, category,
|
||||
groupId, syncedFrom, syncedTo);
|
||||
groupId, syncedFrom, syncedTo, classified);
|
||||
long total = jdProductMapper.countProducts(filter.productCode(),
|
||||
filter.titleKeyword(), filter.category(), filter.groupId(),
|
||||
filter.syncedFrom(), filter.syncedTo());
|
||||
filter.syncedFrom(), filter.syncedTo(), filter.classified(), ownerGroupId);
|
||||
List<JdProductEntity> rows = total <= 0 ? List.of()
|
||||
: jdProductMapper.selectProductPage(filter.productCode(),
|
||||
filter.titleKeyword(), filter.category(), filter.groupId(),
|
||||
filter.syncedFrom(), filter.syncedTo(),
|
||||
filter.syncedFrom(), filter.syncedTo(), filter.classified(), ownerGroupId,
|
||||
(safePage - 1) * safeSize, (int) safeSize);
|
||||
List<JdProductListItemVo> items = rows.stream().map(this::toListItem).toList();
|
||||
fillGroupNames(items, ownerGroupId);
|
||||
@@ -176,18 +180,19 @@ public class JdProductQueryService {
|
||||
|
||||
// ---------------------------------------------------------------- 过滤面
|
||||
|
||||
/** 服务侧过滤面归一:groupId ≤0 按没选处理,文本 trim 后空串归 null(无公司维,2026-11-16 摘)。 */
|
||||
/** 服务侧过滤面归一:groupId ≤0 按没选处理,文本 trim 后空串归 null(无公司维,2026-11-16 摘);
|
||||
* classified 原样直传(null=不过滤该面,2026-11-17 分类状态快筛)。 */
|
||||
private record Filter(String productCode, String titleKeyword,
|
||||
String category, Long groupId,
|
||||
LocalDateTime syncedFrom, LocalDateTime syncedTo) {
|
||||
LocalDateTime syncedFrom, LocalDateTime syncedTo, Boolean classified) {
|
||||
}
|
||||
|
||||
private static Filter filter(String productCode, String titleKeyword,
|
||||
String category, Long groupId,
|
||||
LocalDateTime syncedFrom, LocalDateTime syncedTo) {
|
||||
LocalDateTime syncedFrom, LocalDateTime syncedTo, Boolean classified) {
|
||||
Long safeGroupId = groupId != null && groupId > 0 ? groupId : null;
|
||||
return new Filter(trimToNull(productCode), trimToNull(titleKeyword),
|
||||
trimToNull(category), safeGroupId, syncedFrom, syncedTo);
|
||||
trimToNull(category), safeGroupId, syncedFrom, syncedTo, classified);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 列表/详情搬运
|
||||
|
||||
+11
-18
@@ -8,14 +8,13 @@ import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
|
||||
import com.nanri.aiimage.modules.permission.support.UserDataScopeSupport;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 商品上架配额(2026-11-15 用户口径「限制管理员上架的商品数量,包括管理员下的员工
|
||||
* 总和不能超过配置的最大值」,默认 5000,{@code aiimage.jd.max-products-per-admin})。
|
||||
* 总和不能超过管理员账号设置的最大值」,默认 5000。
|
||||
*
|
||||
* <p>计数口径=团队在京东数据库({@code biz_jd_product})占有的行数:上架功能的数据源
|
||||
* 就是京东数据库,团队占有量即「可上架量」的上游闸。归属列 {@code user_id}=任务 owner
|
||||
@@ -38,9 +37,7 @@ public class JdPublishQuotaService {
|
||||
private final UserDataScopeSupport userDataScopeSupport;
|
||||
private final JdProductMapper jdProductMapper;
|
||||
|
||||
/** 出厂默认与 application.yml 的 aiimage.jd.max-products-per-admin 逐字相等(棘轮);包级可见供同包测试直设。 */
|
||||
@Value("${aiimage.jd.max-products-per-admin:5000}")
|
||||
long maxProductsPerAdmin = 5000L;
|
||||
private static final long DEFAULT_QUOTA = 5000L;
|
||||
|
||||
/** 配额只读快照:used=团队已占有行数,limit=配置上限(≤0=不限)。 */
|
||||
public record QuotaSnapshot(long used, long limit) {
|
||||
@@ -51,9 +48,13 @@ public class JdPublishQuotaService {
|
||||
|
||||
/** 团队已占用与上限的只读快照;uid 集为空(无主管且无 id)按 used=0 处理,不进 SQL。 */
|
||||
public QuotaSnapshot quotaOf(AdminUserEntity operator) {
|
||||
List<Long> userIds = teamUserIds(operator);
|
||||
AdminUserEntity anchor = operator == null ? null : anchorOf(operator);
|
||||
List<Long> userIds = anchor == null || anchor.getId() == null ? List.of()
|
||||
: userDataScopeSupport.resolveVisibleUserIds(anchor);
|
||||
long used = userIds.isEmpty() ? 0L : jdProductMapper.countByUserIds(userIds);
|
||||
return new QuotaSnapshot(used, maxProductsPerAdmin);
|
||||
long limit = anchor == null || anchor.getJdPublishQuota() == null
|
||||
? DEFAULT_QUOTA : anchor.getJdPublishQuota();
|
||||
return new QuotaSnapshot(used, limit);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,14 +62,14 @@ public class JdPublishQuotaService {
|
||||
* 上限 ≤0(0=不限)放行;{@code additionalCount} 为负按 0 处理(本闸只判限不预占)。
|
||||
*/
|
||||
public void assertWithinQuota(AdminUserEntity operator, int additionalCount) {
|
||||
if (maxProductsPerAdmin <= 0) {
|
||||
return;
|
||||
}
|
||||
if (operator != null && DeviceSessionPolicy.isSuperAdmin(
|
||||
operator.getRole(), operator.getIsAdmin(), operator.getCreatedById())) {
|
||||
return;
|
||||
}
|
||||
QuotaSnapshot snapshot = quotaOf(operator);
|
||||
if (snapshot.unlimited()) {
|
||||
return;
|
||||
}
|
||||
long requested = Math.max(0, additionalCount);
|
||||
if (snapshot.used() + requested > snapshot.limit()) {
|
||||
log.warn("[jd-publish] 商品上架配额不足 operatorId={} used={} requested={} limit={}",
|
||||
@@ -80,14 +81,6 @@ public class JdPublishQuotaService {
|
||||
}
|
||||
}
|
||||
|
||||
/** 普通账号锚定到其所属管理员(created_by_id);管理员/公司超管锚自己;无 id 返回空集。 */
|
||||
private List<Long> teamUserIds(AdminUserEntity operator) {
|
||||
if (operator == null || operator.getId() == null) {
|
||||
return List.of();
|
||||
}
|
||||
return userDataScopeSupport.resolveVisibleUserIds(anchorOf(operator));
|
||||
}
|
||||
|
||||
private AdminUserEntity anchorOf(AdminUserEntity operator) {
|
||||
// resolveRole 对普通账号返回 null(角色域只有 super_admin/company_super_admin/admin/null)
|
||||
if (DeviceSessionPolicy.resolveRole(
|
||||
|
||||
+1
-1
@@ -55,7 +55,7 @@ public class PermissionMenuService {
|
||||
/** 角色内在闸门菜单:非超管看不见、谁也授不出去(设计文档 §8.1)。
|
||||
* 与前端 src/config/company-scope.ts 的 SUPER_ADMIN_ONLY_MENU_KEYS 必须同值,由 Task 7 的跨端用例钉住。 */
|
||||
private static final Set<String> SUPER_ADMIN_ONLY_KEYS =
|
||||
Set.of("admin_companies", "admin_task_evidence");
|
||||
Set.of("admin_companies");
|
||||
|
||||
/**
|
||||
* 管理/平台配置类菜单:出口仍是 {@code requireAdmin}(用户、菜单、分组、密钥、公司、版本、教程、
|
||||
|
||||
+4
-3
@@ -131,15 +131,16 @@ public class ShopManageController {
|
||||
public ApiResponse<java.util.List<ShopManageGroupItemVo>> listGroups(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "创建人用户ID") @RequestParam(required = false) Long createdById,
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId) {
|
||||
@Parameter(description = "公司 ID") @RequestParam(name = "company_id", required = false) Long companyId,
|
||||
@Parameter(description = "所属平台(V206):amazon|jd,缺省不过滤") @RequestParam(required = false) String platform) {
|
||||
AdminUserEntity operator = requireOperator(request);
|
||||
if (isSuper(operator)) {
|
||||
// 公司 tab 只收窄可见集;list() 内按组长两列(created_by_id / user_id)认归属。
|
||||
List<Long> memberIds = dataReadScope.readScope(operator, companyId).userIdsOr(null);
|
||||
return ApiResponse.success(shopManageGroupService.list(createdById, memberIds));
|
||||
return ApiResponse.success(shopManageGroupService.list(createdById, memberIds, platform));
|
||||
}
|
||||
Long operatorId = operator.getId();
|
||||
return ApiResponse.success(shopManageGroupService.listAccessible(operatorId, false));
|
||||
return ApiResponse.success(shopManageGroupService.listAccessible(operatorId, false, platform));
|
||||
}
|
||||
|
||||
@PostMapping("/groups")
|
||||
|
||||
+3
@@ -20,4 +20,7 @@ public class ShopManageGroupCreateRequest {
|
||||
@Schema(description = "创建人用户ID,由后台代理透传", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@NotNull(message = "创建人不能为空")
|
||||
private Long createdById;
|
||||
|
||||
@Schema(description = "所属平台(V206):amazon|jd;空白按 'amazon'")
|
||||
private String platform;
|
||||
}
|
||||
|
||||
+3
@@ -15,4 +15,7 @@ public class ShopManageGroupUpdateRequest {
|
||||
|
||||
@Schema(description = "组员用户ID列表")
|
||||
private List<Long> memberUserIds;
|
||||
|
||||
@Schema(description = "所属平台(V206):null=不动;给了就只认 amazon|jd")
|
||||
private String platform;
|
||||
}
|
||||
|
||||
+2
@@ -9,6 +9,8 @@ import java.util.List;
|
||||
public class ShopManageGroupItemVo {
|
||||
private Long id;
|
||||
private String groupName;
|
||||
/** 所属平台(V206):amazon|jd,与后管侧边栏平台 tab 同字面量。 */
|
||||
private String platform;
|
||||
private Long leaderUserId;
|
||||
private String leaderUsername;
|
||||
private List<Long> memberUserIds;
|
||||
|
||||
+34
-4
@@ -8,6 +8,7 @@ import com.nanri.aiimage.modules.shopkey.mapper.QueryAsinMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.spi.GroupDeletionGuardPort;
|
||||
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
|
||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||
import com.nanri.aiimage.common.service.AdminPlatformScope;
|
||||
import com.nanri.aiimage.common.service.CompanyScopeSupport;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageGroupMemberMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageMapper;
|
||||
@@ -52,8 +53,20 @@ public class ShopManageGroupService {
|
||||
}
|
||||
|
||||
public List<ShopManageGroupItemVo> list(Long createdById, List<Long> companyMemberIds) {
|
||||
return list(createdById, companyMemberIds, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 带平台过滤的分组列表(V206):platform 非空白时只返回该平台的分组(amazon|jd,非法值 400),
|
||||
* 后管「分组管理」页按当前平台 tab 传参;null/空白=不过滤,旧调用方口径不变。
|
||||
*/
|
||||
public List<ShopManageGroupItemVo> list(Long createdById, List<Long> companyMemberIds, String platform) {
|
||||
LambdaQueryWrapper<ShopManageGroupEntity> qw = new LambdaQueryWrapper<ShopManageGroupEntity>()
|
||||
.orderByAsc(ShopManageGroupEntity::getId);
|
||||
String platformValue = AdminPlatformScope.normalizeOrNull(platform);
|
||||
if (platformValue != null) {
|
||||
qw.eq(ShopManageGroupEntity::getPlatform, platformValue);
|
||||
}
|
||||
if (createdById != null && createdById > 0) {
|
||||
// 这两条原本是平铺的 .eq(...).or(...):MP 的 normal 段按顺序拼 AND/OR,MySQL 里 AND 优先,
|
||||
// 外面再叠一条公司条件时 created_by_id = ? 那半边会整块逃出筛选(多放行、不报错)⇒ 必须收进 and()。
|
||||
@@ -77,16 +90,26 @@ public class ShopManageGroupService {
|
||||
}
|
||||
|
||||
public List<ShopManageGroupItemVo> listAccessible(Long operatorId, boolean superAdmin) {
|
||||
return listAccessible(operatorId, superAdmin, null);
|
||||
}
|
||||
|
||||
/** 带平台过滤的可见分组列表(V206):platform 非空白时只返回该平台的分组,null/空白=不过滤。 */
|
||||
public List<ShopManageGroupItemVo> listAccessible(Long operatorId, boolean superAdmin, String platform) {
|
||||
String platformValue = AdminPlatformScope.normalizeOrNull(platform);
|
||||
if (superAdmin) {
|
||||
return list();
|
||||
return list(null, null, platformValue);
|
||||
}
|
||||
Set<Long> groupIds = listAccessibleGroupIds(operatorId, false);
|
||||
if (groupIds.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
return toVoList(groupMapper.selectList(new LambdaQueryWrapper<ShopManageGroupEntity>()
|
||||
.in(ShopManageGroupEntity::getId, groupIds)
|
||||
.orderByAsc(ShopManageGroupEntity::getId)));
|
||||
LambdaQueryWrapper<ShopManageGroupEntity> qw = new LambdaQueryWrapper<ShopManageGroupEntity>()
|
||||
.in(ShopManageGroupEntity::getId, groupIds);
|
||||
if (platformValue != null) {
|
||||
qw.eq(ShopManageGroupEntity::getPlatform, platformValue);
|
||||
}
|
||||
qw.orderByAsc(ShopManageGroupEntity::getId);
|
||||
return toVoList(groupMapper.selectList(qw));
|
||||
}
|
||||
|
||||
public Set<Long> listAccessibleGroupIds(Long operatorId, boolean superAdmin) {
|
||||
@@ -179,6 +202,7 @@ public class ShopManageGroupService {
|
||||
entity.setGroupName(groupName);
|
||||
entity.setCreatedById(createdById);
|
||||
entity.setCompanyId(companyId);
|
||||
entity.setPlatform(AdminPlatformScope.normalizeOrCreate(request.getPlatform()));
|
||||
groupMapper.insert(entity);
|
||||
replaceMembers(entity.getId(), request.getMemberUserIds(), createdById, operatorId, superAdmin);
|
||||
return toVo(getById(entity.getId()));
|
||||
@@ -197,6 +221,11 @@ public class ShopManageGroupService {
|
||||
|
||||
entity.setGroupName(groupName);
|
||||
entity.setCompanyId(companyId);
|
||||
// 平台只在显式给出时落(null/空白=不动),与 users/company 的 PUT 同口径
|
||||
String platformUpdate = AdminPlatformScope.normalizeOrNull(request.getPlatform());
|
||||
if (platformUpdate != null) {
|
||||
entity.setPlatform(platformUpdate);
|
||||
}
|
||||
groupMapper.updateById(entity);
|
||||
// 组长取 resolveGroupLeaderUserId 而不是 created_by_id:生产有 2 个分组只有 user_id
|
||||
// (见 listCompanyGroupIds 的注释),只认 created_by_id 会让那 2 个分组绕过组员的公司校验。
|
||||
@@ -488,6 +517,7 @@ public class ShopManageGroupService {
|
||||
ShopManageGroupItemVo vo = new ShopManageGroupItemVo();
|
||||
vo.setId(entity.getId());
|
||||
vo.setGroupName(entity.getGroupName());
|
||||
vo.setPlatform(entity.getPlatform());
|
||||
Long leaderUserId = resolveGroupLeaderUserId(entity);
|
||||
vo.setLeaderUserId(leaderUserId);
|
||||
AdminUserEntity leaderUser = leaderUserId == null ? null : userById.get(leaderUserId);
|
||||
|
||||
@@ -48,13 +48,6 @@ AIIMAGE_JD_SKU_MAX_PER_PRODUCT=200
|
||||
# 设成空串会把白名单清空(兜底拉取对 JD 形同关闭)。打开 AIIMAGE_CLIENT_TASK_PULL_ENABLED
|
||||
# 前先确认客户端版本带兜底拉取线程。
|
||||
|
||||
# 任务异常现场证据件(v1.2 Phase 3):独立桶与保留期必须显式配置;桶不得复用 nanri-ai-images。
|
||||
AIIMAGE_EVIDENCE_OSS_BUCKET=task-evidence
|
||||
AIIMAGE_EVIDENCE_RETENTION_DAYS=7
|
||||
AIIMAGE_EVIDENCE_RETENTION_CRON=0 30 3 * * *
|
||||
AIIMAGE_EVIDENCE_MAX_FILE_BYTES=67108864
|
||||
AIIMAGE_EVIDENCE_KEY_PREFIX=task-evidence/
|
||||
|
||||
# 工作台客户端包直传预签名有效期(秒);90MB 级包在慢公网入口需要更长窗口。
|
||||
AIIMAGE_WORKBENCH_CLIENT_PRESIGN_EXPIRY_SECONDS=3600
|
||||
|
||||
|
||||
@@ -177,11 +177,6 @@ aiimage:
|
||||
# SKU 矩阵单商品上限(V198 详情面):真机一个商品 12 行,超限截断并 WARN,
|
||||
# 防脏回传把整批撑爆。显式写在这里,不许只活在代码默认值里。
|
||||
sku-max-per-product: ${AIIMAGE_JD_SKU_MAX_PER_PRODUCT:200}
|
||||
# 商品上架配额(2026-11-15 用户口径):单个管理员(含其名下员工合计;公司超管按
|
||||
# 全公司合计)可上架的商品数上限,默认 5000;0=不限。计数源=biz_jd_product 按
|
||||
# owner uid 集计行数(上架功能的数据源就是京东数据库);站点超管不限额。
|
||||
# 校验出口=JdPublishQuotaService,商品上架建单入口落地时调用。
|
||||
max-products-per-admin: ${AIIMAGE_JD_MAX_PRODUCTS_PER_ADMIN:5000}
|
||||
# 设备日志对象存储:主机B 独立 MinIO(与业务 OSS 隔离,日志只保留 7 天)。
|
||||
# endpoint 未配置时日志上报/管理接口不可用(宁可失败也不静默落到业务桶)。
|
||||
# 桶的 7 天过期规则由运维用 mc 配置(与 retention-days 口径一致)。
|
||||
@@ -191,15 +186,6 @@ aiimage:
|
||||
access-key-id: ${AIIMAGE_DEVICE_LOG_OSS_ACCESS_KEY_ID:}
|
||||
access-key-secret: ${AIIMAGE_DEVICE_LOG_OSS_ACCESS_KEY_SECRET:}
|
||||
retention-days: ${AIIMAGE_DEVICE_LOG_RETENTION_DAYS:7}
|
||||
# 任务异常现场证据件(v1.2 Phase 3/AC-7/AC-13):独立桶 + 独立保留期。
|
||||
# 桶必须与业务桶 nanri-ai-images 隔离(那边是 7 天整桶 ILM,证据保留策略不得被它绑死);
|
||||
# key-prefix 之后实际 key = <prefix><taskId>/<UUID><扩展名>(铁律 10:key 必带 UUID)。
|
||||
evidence:
|
||||
bucket: ${AIIMAGE_EVIDENCE_OSS_BUCKET:task-evidence}
|
||||
retention-days: ${AIIMAGE_EVIDENCE_RETENTION_DAYS:7}
|
||||
key-prefix: ${AIIMAGE_EVIDENCE_KEY_PREFIX:task-evidence/}
|
||||
max-file-bytes: ${AIIMAGE_EVIDENCE_MAX_FILE_BYTES:67108864}
|
||||
retention-cron: ${AIIMAGE_EVIDENCE_RETENTION_CRON:0 30 3 * * *}
|
||||
transient-storage:
|
||||
enabled: ${AIIMAGE_TRANSIENT_STORAGE_ENABLED:true}
|
||||
endpoint: ${AIIMAGE_TRANSIENT_STORAGE_ENDPOINT:http://121.196.149.225:9000}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
-- 迁移 V205:任务证据特性整体下线(2026-11-17 用户拍板)
|
||||
--
|
||||
-- 背景:v1.2 的「任务异常现场存证」(客户端采集+分片上云+后管读取面)整体删除——
|
||||
-- 上线至今登记行为零(装机面未升级+触发口窄+崩溃路被归属校验 403 钉死),
|
||||
-- 读取面 AdminTaskEvidenceController、内部登记 InternalTaskEvidenceController 与
|
||||
-- 客户端 evidence_recorder 链同窗下线(铁律 18/22/24 随之退役)。
|
||||
--
|
||||
-- 本迁移做两件事:
|
||||
-- 1. 删除 V185 下发的每公司菜单行(后管侧边栏「任务证据」入口);
|
||||
-- 2. DROP 登记表 biz_task_evidence(V182 建表、V184 第二段补 idx_task_evidence_created_at;
|
||||
-- 索引随表删除,无需单独 DROP)。
|
||||
-- 表内只有 7 天保留期的现场件登记行,随特性下线无保留价值;对象本体在独立桶
|
||||
-- task-evidence,桶的清理由运维窗口另行执行(登记 ops BACKLOG),不依赖本迁移。
|
||||
--
|
||||
-- 回滚(手工):
|
||||
-- 1. 按 V182 原样重建 biz_task_evidence(建表+两索引),再按 V184 第二段补
|
||||
-- idx_task_evidence_created_at;
|
||||
-- 2. 按 V185 语义重插 columns 菜单行(每公司一行,column_key='admin_task_evidence')。
|
||||
-- 数据不可回滚:登记行随 DROP 丢弃(7 天现场件,无保留价值)。
|
||||
|
||||
DELETE FROM `columns` WHERE `column_key` = 'admin_task_evidence';
|
||||
|
||||
DROP TABLE IF EXISTS `biz_task_evidence`;
|
||||
@@ -0,0 +1,82 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V206__admin_account_platform
|
||||
-- 需求:2026-11-17 用户口径「用户管理/分组管理/公司管理亚马逊这边也要有」+
|
||||
-- 「京东是也有,但是数据都是新的,别把亚马逊的带过来」——后管三类账号域数据
|
||||
-- (users / company / biz_shop_manage_group)从全系统共用一份改成按平台(amazon/jd)
|
||||
-- 各管各的:后管在哪个平台 tab 下就只看/管那个平台的账号、分组、公司。
|
||||
-- 前版:V153(分组表挂 company_id)→ V202 待改号件(jd_publish_quota,另一窗在飞,见下)
|
||||
--
|
||||
-- 1. 变更目的:三张表各加一个「所属平台」标记列。存量一律 DEFAULT 'amazon'(亚马逊业务
|
||||
-- 一直在用这套账号;京东侧新录的数据由使用者在编辑弹窗里自己翻成 'jd',本迁移不做
|
||||
-- 数据驱动的自动归类——按引用猜归属会错分)。平台语义只作用于后管三个管理页的
|
||||
-- 显示与筛选:登录、用户端功能、任务权限、DataReadScope 全部不动。
|
||||
--
|
||||
-- 2. 号段协调(重要,写给并行的 jd_publish_quota 窗):V202 号已随 764eeb29 永久退役
|
||||
-- (RETIRED_HOLES),那个待入库的 V202__users_jd_publish_quota.sql 按 AGENTS.md 铁律 33
|
||||
-- 必须改号 V206+ 才能入库;本笔先占 V206,改号件请取 V207 及以上——若改号撞到 V206
|
||||
-- 会触发 MigrationInventoryTest 的重复版本断言(同 V148 先例:宁可测试红,不把撞号
|
||||
-- 留到 Flyway 运行期)。
|
||||
--
|
||||
-- 3. 口径:
|
||||
-- users + platform VARCHAR(16) NOT NULL DEFAULT 'amazon'
|
||||
-- company + platform VARCHAR(16) NOT NULL DEFAULT 'amazon'
|
||||
-- biz_shop_manage_group + platform VARCHAR(16) NOT NULL DEFAULT 'amazon'
|
||||
-- 取值字面量与 admin-frontend-vue 的 PlatformTabId 同源:'amazon' | 'jd'。
|
||||
-- users 是双映射表(AdminUserEntity + LoginUserEntity),实体两侧同加,UsersCompanyIdMappingTest 钉住。
|
||||
--
|
||||
-- 4. 可重跑性:三条列 DDL 都先查 information_schema 再 PREPARE,重跑逐条 no-op;
|
||||
-- ADD COLUMN ... DEFAULT 走 ALGORITHM = INSTANT(users 行数大,不锁表)。
|
||||
--
|
||||
-- 5. 回滚(人工补丁,写成注释以免落在 Flyway 扫描路径里被当迁移执行):
|
||||
-- ALTER TABLE users DROP COLUMN platform;
|
||||
-- ALTER TABLE company DROP COLUMN platform;
|
||||
-- ALTER TABLE biz_shop_manage_group DROP COLUMN platform;
|
||||
-- (jar 必须先回到"无平台维度"的那版,否则实体按不存在的列 select 会 500。)
|
||||
-- =============================================================
|
||||
|
||||
SET @db_name = DATABASE();
|
||||
|
||||
-- ---------- 1. users:所属平台(双映射实体同改) ----------
|
||||
|
||||
SET @v206_users_col := (SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'users' AND COLUMN_NAME = 'platform');
|
||||
SET @sql := IF(@v206_users_col = 0,
|
||||
'ALTER TABLE `users` ADD COLUMN `platform` VARCHAR(16) NOT NULL DEFAULT ''amazon'' COMMENT ''所属平台(V206):amazon|jd,与后管平台 tab 同字面量;只作用于后管用户管理页的显示与筛选'', ALGORITHM = INSTANT',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 2. company:所属平台 ----------
|
||||
|
||||
SET @v206_company_col := (SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'company' AND COLUMN_NAME = 'platform');
|
||||
SET @sql := IF(@v206_company_col = 0,
|
||||
'ALTER TABLE `company` ADD COLUMN `platform` VARCHAR(16) NOT NULL DEFAULT ''amazon'' COMMENT ''所属平台(V206):amazon|jd,与后管平台 tab 同字面量;只作用于后管公司管理页的显示与筛选'', ALGORITHM = INSTANT',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 3. biz_shop_manage_group:所属平台 ----------
|
||||
|
||||
SET @v206_group_col := (SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'biz_shop_manage_group' AND COLUMN_NAME = 'platform');
|
||||
SET @sql := IF(@v206_group_col = 0,
|
||||
'ALTER TABLE `biz_shop_manage_group` ADD COLUMN `platform` VARCHAR(16) NOT NULL DEFAULT ''amazon'' COMMENT ''所属平台(V206):amazon|jd,与后管平台 tab 同字面量;只作用于后管分组管理页的显示与筛选'', ALGORITHM = INSTANT',
|
||||
'SELECT 1');
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- =============================================================
|
||||
-- 验证 SQL(迁移后在库上执行,必须有人实跑,不许只看启动日志的 Successfully applied)
|
||||
--
|
||||
-- SHOW COLUMNS FROM users LIKE 'platform';
|
||||
-- SHOW COLUMNS FROM company LIKE 'platform';
|
||||
-- SHOW COLUMNS FROM biz_shop_manage_group LIKE 'platform';
|
||||
-- -> 三条都期望 Null = NO、Default = 'amazon'、Type = varchar(16)。
|
||||
--
|
||||
-- SELECT platform, COUNT(*) FROM users GROUP BY platform;
|
||||
-- -> 迁移后只有 'amazon' 一档(存量全归亚马逊,京东侧由使用者在界面翻档)。
|
||||
-- =============================================================
|
||||
@@ -0,0 +1,5 @@
|
||||
-- 迁移 V207:逐管理员设置京东上架额度;0 表示不限。已有账号保留原默认额度。
|
||||
-- 号段协调(2026-11-17):原 V202 号已被 V203/V204/V205 按序越过(764eeb29 把 202 登记
|
||||
-- RETIRED_HOLES),按其明文要求改号入库;V206 被同窗 admin_account_platform(三表平台列)占用,
|
||||
-- 故本件取 V207。改号只动文件名与头注释,ALTER 语句一个字节未变(可重入:加列前查重)。
|
||||
ALTER TABLE users ADD COLUMN jd_publish_quota INT NOT NULL DEFAULT 5000;
|
||||
@@ -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`;
|
||||
@@ -122,6 +122,29 @@
|
||||
WHERE a.product_id = p.id AND a.category_id = #{groupId}
|
||||
)
|
||||
</if>
|
||||
<!-- 分类状态快筛(2026-11-17 用户口径「加个已分类和未分类的筛选」):已分类=在
|
||||
「当前数据权限分组」(owner_group_id)下有 category_id 非空的归属行——与读侧
|
||||
fillGroupNames 把分类列填出来的条件同形;未分类=NOT EXISTS。谓词 SQL 侧下推
|
||||
(铁律 20 同形,不得 Java 侧对已取页 filter)。owner_group_id 为 NULL(作用域
|
||||
无可分组)时 EXISTS 恒假、NOT EXISTS 恒真——与列表「分类列全空」口径天然一致,
|
||||
不需要服务侧特判。与 2026-11-16 撤掉的旧 grouped/ungrouped 不是一回事:那两档
|
||||
读的是已停用的 biz_jd_product.group_id 列,本档读 V203 归属表。 -->
|
||||
<if test="classified != null">
|
||||
<choose>
|
||||
<when test="classified == true">
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM biz_jd_product_group_assign cs
|
||||
WHERE cs.product_id = p.id AND cs.owner_group_id = #{ownerGroupId} AND cs.category_id IS NOT NULL
|
||||
)
|
||||
</when>
|
||||
<otherwise>
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM biz_jd_product_group_assign cs
|
||||
WHERE cs.product_id = p.id AND cs.owner_group_id = #{ownerGroupId} AND cs.category_id IS NOT NULL
|
||||
)
|
||||
</otherwise>
|
||||
</choose>
|
||||
</if>
|
||||
<if test="syncedFrom != null">AND p.synced_at >= #{syncedFrom}</if>
|
||||
<if test="syncedTo != null">AND p.synced_at <= #{syncedTo}</if>
|
||||
</sql>
|
||||
|
||||
@@ -55,9 +55,13 @@ class MigratedSqlEquivalenceTest {
|
||||
// 85 → 84:Phase 5(AC-19/P1-B1)有意把 {@code TaskCenterQueryMapper#selectTaskPage} 从
|
||||
// OFFSET 改成 keyset 游标。账本记的是「注解时代原文」,改一行基准就等于让等价性测试照着
|
||||
// 新 SQL 自证 ⇒ 把该行整条摘出账本、点名进下方 NOT_MIGRATED,让基准继续只描述真正未改动的迁移件。
|
||||
private static final int LEDGER_ROWS = 83;
|
||||
// 60 → 59:摘出去那行是一条 select。
|
||||
private static final int LEDGER_SELECTS = 59;
|
||||
// 83 → 82:47fc0e08(2026-11-16 平台超管 500 热修)给 ShopManageGroupMapper#selectAllGroups 的 XML
|
||||
// 补 g.company_id AS companyId(注解时代原文没有这列)——改动是有意的,按 selectTaskPage/V188
|
||||
// 同款处理整行摘出、点名 NOT_MIGRATED;新形状由 47fc0e08 那单的守卫钉。该笔走 fast 档发版
|
||||
// 没点本支,2026-11-17 京东分类管理发版窗 full 闸门抓到补记。
|
||||
private static final int LEDGER_ROWS = 82;
|
||||
// 60 → 59:摘出去那行是一条 select。(59 → 58:摘 ShopManageGroupMapper#selectAllGroups 同上。)
|
||||
private static final int LEDGER_SELECTS = 58;
|
||||
/** 全部 mapper XML 里的 select 总数:账本 60 + TaskImageCache 5 + AsinResultCache 1。 */
|
||||
/** 66 → 67:会话容忍新增的 {@code AdminUserMapper#countLiveWorkFor} 也是一条 select。 */
|
||||
// 67 → 78:keywordshare 模块新写 11 条 select,逐条登记进下方 NOT_MIGRATED。
|
||||
@@ -197,7 +201,12 @@ class MigratedSqlEquivalenceTest {
|
||||
// 配额原语),没有注解原文可对撞,点名留痕。该笔当时只点编译没跑整量、漏记两处
|
||||
// 账本,2026-11-15 发版前整量抓到补记(XML_SELECT_TOTAL 113 → 114,
|
||||
// SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 163 → 164)。
|
||||
"JdProductMapper#countByUserIds");
|
||||
"JdProductMapper#countByUserIds",
|
||||
// 47fc0e08(2026-11-16 平台超管 500 热修)给 selectAllGroups 的 XML 补
|
||||
// g.company_id AS companyId:注解时代原文没有这列,等价性这支对撞即红。
|
||||
// 有意改动按先例整行摘账本点名留痕(LEDGER_ROWS 83 → 82 / SELECTS 59 → 58);
|
||||
// 该笔 fast 档发版漏记,2026-11-17 京东分类管理发版窗 full 闸门抓到补记。
|
||||
"ShopManageGroupMapper#selectAllGroups");
|
||||
|
||||
/** 账本 5 列:接口 / 方法 / @Select 种类 / 是否含常量插值 / 注解原文(Java 反转义后那条串)。 */
|
||||
private static final int LEDGER_COLUMNS = 5;
|
||||
|
||||
@@ -42,8 +42,6 @@ class PageDefaultsLedgerTest {
|
||||
* 54 条,逐条对应一次真实翻页行为;加页要登记,改值要表态。
|
||||
*/
|
||||
private static final List<String> LEDGER = List.of(
|
||||
"AdminTaskEvidenceController.java#page=FIRST_PAGE",
|
||||
"AdminTaskEvidenceController.java#pageSize=ADMIN_LIST_PAGE_SIZE",
|
||||
"AdminUserController.java#page=FIRST_PAGE",
|
||||
"AdminUserController.java#page_size=USER_LIST_PAGE_SIZE",
|
||||
"AdminUserApiSecretController.java#page=FIRST_PAGE",
|
||||
@@ -121,14 +119,15 @@ class PageDefaultsLedgerTest {
|
||||
List<String> constants = actual.stream().filter(s -> !s.contains("LITERAL")).sorted().toList();
|
||||
|
||||
assertThat(constants)
|
||||
.as("60 处分页/条数出站点的具名默认值必须与台账一一对应"
|
||||
.as("分页/条数出站点的具名默认值必须与台账一一对应"
|
||||
+ "(58→60:v1.4 Phase 5 京东数据库后管只读页 AdminJdProductController 的"
|
||||
+ " page/page_size 两处出站点)")
|
||||
+ " page/page_size 两处出站点;60→59:2026-11-17 任务证据特性下线,"
|
||||
+ " AdminTaskEvidenceController 两处出站点随控制器删除)")
|
||||
.isEqualTo(LEDGER.stream().sorted().toList());
|
||||
// 同口径非零对照:台账不是空的,扫描器也确实数得出 61 处
|
||||
// 同口径非零对照:台账不是空的,扫描器也确实数得出 59 处
|
||||
// (61 而不是 60:2026-11-15 京东任务面板改版(45d0989a)新增 GET /api/jd-collect/history
|
||||
// 的 limit 出站点,台账同步登记 58→60→61)
|
||||
assertThat(constants).hasSize(61);
|
||||
// 的 limit 出站点,台账同步登记 58→60→61;61→59:任务证据特性下线随删两处)
|
||||
assertThat(constants).hasSize(59);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -143,8 +142,9 @@ class PageDefaultsLedgerTest {
|
||||
void oneSemanticCannotGrowASecondDefault() {
|
||||
List<String> actual = sites();
|
||||
assertThat(kindsUsing(actual, "page", "FIRST_PAGE"))
|
||||
.as("页码口径只有一套:全部从 1 起(26→27:v1.4 Phase 5 京东数据库只读页也是分页出站点)")
|
||||
.isEqualTo(27);
|
||||
.as("页码口径只有一套:全部从 1 起(26→27:v1.4 Phase 5 京东数据库只读页也是分页出站点;"
|
||||
+ "27→26:2026-11-17 任务证据特性下线随删一处)")
|
||||
.isEqualTo(26);
|
||||
assertThat(distinctConstants(actual, "page_size"))
|
||||
.as("page_size 的默认容量集合:10/15/20/50/1000 各自登记(20 有两把名字:超管台 "
|
||||
+ "ADMIN_LIST_PAGE_SIZE 与 v1.4 京东数据库 JD_PRODUCTS_PAGE_SIZE),新语义要红")
|
||||
|
||||
+3
-1
@@ -128,8 +128,10 @@ class SuperAdminPredicateSingleOutletTest {
|
||||
// 20 -> 22:v1.4 Phase 5 京东数据库读取面——AdminJdProductController#requireJdDatabaseAccess
|
||||
// 与 AdminJdProductGroupController#requireJdDatabaseAccess 两处超管直通
|
||||
// (2026-11-14 整量回归补记,同 AdminTaskEvidenceController 先例)。
|
||||
// 22 -> 21:任务证据特性整体下线(2026-11-17 用户拍板),AdminTaskEvidenceController
|
||||
// 连同模块删除,该出口随之消失。
|
||||
.as("走出口的调用点数:17 个业务调用方 + DataReadScope 包装体(新增调用要一起改这个数字,别改回字面量)")
|
||||
.isEqualTo(22);
|
||||
.isEqualTo(21);
|
||||
// 自检:这三把尺子的锚点必须真落在预期的文件里,否则"恰好也是 N"可能是扫错地方凑出来的
|
||||
assertThat(read(mainRoot().resolve("common/security/DeviceSessionPolicy.java")))
|
||||
.contains("public static boolean isSuper(String resolvedRole)");
|
||||
|
||||
@@ -88,9 +88,18 @@ class MigrationInventoryTest {
|
||||
* 目录最大值升到 170 之后若回填新内容,已应用 170 的环境在 Flyway out-of-order 关闭下会把它当
|
||||
* ignored migration 静默跳过,各环境 Schema 悄悄漂移。与 148 不同这不是并发护栏,是既成跳号的封账。</p>
|
||||
*
|
||||
* <p><b>202</b>:{@code V202__users_jd_publish_quota.sql}(users.jd_publish_quota,工作台商品上架配额)
|
||||
* 由并行会话在写、截至 2026-11-17 发版窗仍未入库;而 V203(61ab844e)已于 2026-11-16 21:1x 上线、
|
||||
* V204(aff6c88a)与 V205(任务证据下线,71b19e4f)随 2026-11-17 发版窗越过 202 落库。
|
||||
* Flyway 未开 out-of-order ⇒ 该路径入库前必须把文件改名到 V206+(RELEASE_LEDGER 2026-11-16
|
||||
* 22:2x 段的顺序债登记);把新迁移写回 202 会让已过 205 的环境启动期报
|
||||
* "resolved migration not applied" 失败。与 132/133 同属"只能永久保留、不能回填"。
|
||||
* 2026-11-17 已改号 {@code V207__users_jd_publish_quota.sql} 入库(V206 被同窗
|
||||
* admin_account_platform 三表平台列占用,account-platform 提交);202 号自此彻底空置。</p>
|
||||
*
|
||||
* <p>共同后果:新迁移只能取当前最大值之上的号(详见 docs/migration-inventory.md)。</p>
|
||||
*/
|
||||
private static final Set<Integer> RETIRED_HOLES = Set.of(132, 133, 148, 168, 169);
|
||||
private static final Set<Integer> RETIRED_HOLES = Set.of(132, 133, 148, 168, 169, 202);
|
||||
|
||||
/**
|
||||
* 文件名版本与头注释版本不一致的历史件。V170 的头注释误写成 V168;它已应用到生产,
|
||||
|
||||
+544
@@ -0,0 +1,544 @@
|
||||
package com.nanri.aiimage.modules.admin.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||
import com.nanri.aiimage.common.mapper.ShopManageGroupMapper;
|
||||
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.service.AdminPlatformScope;
|
||||
import com.nanri.aiimage.common.service.CompanyScopeSupport;
|
||||
import com.nanri.aiimage.modules.admin.model.dto.AdminUserCreateRequest;
|
||||
import com.nanri.aiimage.modules.admin.model.dto.AdminUserUpdateRequest;
|
||||
import com.nanri.aiimage.modules.admin.spi.UserSecretCleanupPort;
|
||||
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
||||
import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
|
||||
import com.nanri.aiimage.modules.company.model.dto.CompanySaveRequest;
|
||||
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.QueryAsinMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageGroupMemberMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.mapper.SkipPriceAsinMapper;
|
||||
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupCreateRequest;
|
||||
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupUpdateRequest;
|
||||
import com.nanri.aiimage.modules.shopkey.service.ShopManageGroupService;
|
||||
import com.nanri.aiimage.modules.shopkey.spi.GroupDeletionGuardPort;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 账号域「所属平台」(V206,2026-11-17 用户口径「亚马逊这边也要有;京东的数据是新的,
|
||||
* 别把亚马逊的带过来」):users / company / biz_shop_manage_group 三张表各带 platform 列
|
||||
* (amazon|jd),后管三个管理页按平台 tab 过滤、新建默认当前平台、编辑只显式翻档。
|
||||
*
|
||||
* <p>判据钉四条形状:①列表过滤真的进 SQL 条件(打在 wrapper 参数上,不是打在返回值——
|
||||
* 返回空也可能是别的条件写反);②新建缺省落 'amazon'(与列 DEFAULT 同口径);③编辑只在
|
||||
* 显式给出时落(PUT 只带 disabled 的既有形状不得把平台冲掉);④非法值 400,不许静默归档。</p>
|
||||
*/
|
||||
class AdminAccountPlatformScopeTest {
|
||||
|
||||
private AdminUserMapper userMapper;
|
||||
private AdminAuthSupport authSupport;
|
||||
private PermissionMenuService permissionService;
|
||||
private CompanyService companyService;
|
||||
private AdminUserService userService;
|
||||
|
||||
private CompanyMapper companyMapper;
|
||||
private CompanyService standaloneCompanyService;
|
||||
|
||||
private ShopManageGroupMapper groupMapper;
|
||||
private ShopManageGroupMemberMapper groupMemberMapper;
|
||||
private CompanyScopeSupport companyScope;
|
||||
private AdminUserMapper groupAdminUserMapper;
|
||||
private ShopManageGroupService groupService;
|
||||
|
||||
@BeforeEach
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void setUp() {
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""), AdminUserEntity.class);
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""), CompanyEntity.class);
|
||||
TableInfoHelper.initTableInfo(
|
||||
new MapperBuilderAssistant(new MybatisConfiguration(), ""), ShopManageGroupEntity.class);
|
||||
|
||||
userMapper = mock(AdminUserMapper.class);
|
||||
authSupport = mock(AdminAuthSupport.class);
|
||||
permissionService = mock(PermissionMenuService.class);
|
||||
companyService = mock(CompanyService.class);
|
||||
userService = new AdminUserService(userMapper, mock(WerkzeugPasswordEncoder.class), authSupport,
|
||||
permissionService, mock(UserSecretCleanupPort.class), companyService);
|
||||
when(permissionService.hasAnyAdminMenu(any(), any())).thenReturn(true);
|
||||
when(userMapper.selectCount(any(LambdaQueryWrapper.class))).thenReturn(0L);
|
||||
when(userMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of());
|
||||
|
||||
companyMapper = mock(CompanyMapper.class);
|
||||
standaloneCompanyService = new CompanyService(companyMapper, authSupport,
|
||||
mock(PermissionMenuService.class));
|
||||
when(companyMapper.selectCount(any(LambdaQueryWrapper.class))).thenReturn(0L);
|
||||
when(companyMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of());
|
||||
|
||||
groupMapper = mock(ShopManageGroupMapper.class);
|
||||
groupMemberMapper = mock(ShopManageGroupMemberMapper.class);
|
||||
companyScope = mock(CompanyScopeSupport.class);
|
||||
groupAdminUserMapper = mock(AdminUserMapper.class);
|
||||
groupService = new ShopManageGroupService(groupMapper, groupMemberMapper,
|
||||
List.of(mock(GroupDeletionGuardPort.class)), mock(ShopManageMapper.class),
|
||||
mock(QueryAsinMapper.class), mock(SkipPriceAsinMapper.class),
|
||||
groupAdminUserMapper, companyScope);
|
||||
when(groupMapper.selectCount(any(LambdaQueryWrapper.class))).thenReturn(0L);
|
||||
when(groupMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of());
|
||||
when(groupMemberMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of());
|
||||
when(companyScope.requireCompanyId(any(AdminUserEntity.class))).thenReturn(5L);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 用户列表过滤
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void userListPlatformFilterBecomesAQueryCondition() {
|
||||
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
|
||||
userService.listUsers(operator, 1, 10, null, null, null, null, "jd");
|
||||
|
||||
LambdaQueryWrapper<AdminUserEntity> query = capturedUserCountQuery();
|
||||
// MP 的参数是惰性入表的:先渲染 SQL 段再断参数值(同 AdminUserListCompanyTest 的断言顺序)
|
||||
assertThat(query.getSqlSegment()).contains("platform");
|
||||
assertThat(query.getParamNameValuePairs()).containsValue("jd");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void userListWithoutPlatformAddsNoCondition() {
|
||||
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
|
||||
// 8 参重载传 null 与旧 7 参口径完全一致:不带平台时查询条件一个都没有
|
||||
userService.listUsers(operator, 1, 10, null, null, null, null, null);
|
||||
|
||||
assertThat(capturedUserCountQuery().getParamNameValuePairs()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void userListRejectsIllegalPlatformValue() {
|
||||
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
|
||||
assertThatThrownBy(() -> userService.listUsers(operator, 1, 10, null, null, null, null, "taobao"))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("所属平台");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 用户新建/编辑落库
|
||||
|
||||
@Test
|
||||
void createUserWithoutPlatformFallsBackToAmazon() {
|
||||
AdminUserEntity operator = operator(1L, "company_super_admin", 5L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
|
||||
AtomicReference<AdminUserEntity> inserted = captureUserInsert();
|
||||
|
||||
AdminUserCreateRequest request = new AdminUserCreateRequest();
|
||||
request.setUsername("京东客服");
|
||||
request.setPassword("123456");
|
||||
request.setRole("normal");
|
||||
|
||||
userService.createUser(operator, request);
|
||||
|
||||
assertThat(inserted.get().getPlatform()).isEqualTo(AdminPlatformScope.AMAZON);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUserWithExplicitJdPlatformStoresJd() {
|
||||
AdminUserEntity operator = operator(1L, "company_super_admin", 5L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
|
||||
AtomicReference<AdminUserEntity> inserted = captureUserInsert();
|
||||
|
||||
AdminUserCreateRequest request = new AdminUserCreateRequest();
|
||||
request.setUsername("京东客服");
|
||||
request.setPassword("123456");
|
||||
request.setRole("normal");
|
||||
request.setPlatform("jd");
|
||||
|
||||
userService.createUser(operator, request);
|
||||
|
||||
assertThat(inserted.get().getPlatform()).isEqualTo(AdminPlatformScope.JD);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createUserRejectsIllegalPlatformValue() {
|
||||
AdminUserEntity operator = operator(1L, "company_super_admin", 5L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("company_super_admin");
|
||||
|
||||
AdminUserCreateRequest request = new AdminUserCreateRequest();
|
||||
request.setUsername("京东客服");
|
||||
request.setPassword("123456");
|
||||
request.setRole("normal");
|
||||
request.setPlatform("taobao");
|
||||
|
||||
assertThatThrownBy(() -> userService.createUser(operator, request))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("所属平台");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void updateUserWithPlatformOnlyStillAppliesIt() {
|
||||
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
when(userMapper.selectById(11L)).thenReturn(target(11L, "admin"));
|
||||
when(userMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||
|
||||
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
|
||||
request.setPlatform("jd");
|
||||
|
||||
userService.updateUser(operator, 11L, request);
|
||||
|
||||
LambdaUpdateWrapper<AdminUserEntity> update = capturedUserUpdate();
|
||||
assertThat(update.getSqlSet()).contains("platform");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void disabledOnlyUpdateDoesNotTouchPlatform() {
|
||||
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
when(userMapper.selectById(11L)).thenReturn(target(11L, "admin"));
|
||||
when(userMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||
|
||||
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
|
||||
request.setDisabled(true);
|
||||
|
||||
userService.updateUser(operator, 11L, request);
|
||||
|
||||
LambdaUpdateWrapper<AdminUserEntity> update = capturedUserUpdate();
|
||||
assertThat(update.getSqlSet()).contains("disabled_at");
|
||||
assertThat(update.getSqlSet()).doesNotContain("platform");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUserRejectsIllegalPlatformValue() {
|
||||
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
when(userMapper.selectById(11L)).thenReturn(target(11L, "admin"));
|
||||
|
||||
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
|
||||
request.setPlatform("taobao");
|
||||
|
||||
assertThatThrownBy(() -> userService.updateUser(operator, 11L, request))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("所属平台");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 公司目录过滤与落库
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void companyListPlatformFilterBecomesAQueryCondition() {
|
||||
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
|
||||
standaloneCompanyService.listVisible(operator, "jd");
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
|
||||
verify(companyMapper).selectList(captor.capture());
|
||||
// MP 的参数是惰性入表的:先渲染 SQL 段再断参数值
|
||||
assertThat(captor.getValue().getSqlSegment()).contains("platform");
|
||||
assertThat(captor.getValue().getParamNameValuePairs()).containsValue("jd");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void companyListWithoutPlatformAddsNoCondition() {
|
||||
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
|
||||
standaloneCompanyService.listVisible(operator);
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
|
||||
verify(companyMapper).selectList(captor.capture());
|
||||
assertThat(captor.getValue().getParamNameValuePairs()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createCompanyWithoutPlatformFallsBackToAmazon() {
|
||||
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
AtomicReference<CompanyEntity> inserted = captureCompanyInsert();
|
||||
|
||||
CompanySaveRequest request = new CompanySaveRequest();
|
||||
request.setCompanyName("京东事业部");
|
||||
|
||||
standaloneCompanyService.create(operator, request);
|
||||
|
||||
assertThat(inserted.get().getPlatform()).isEqualTo(AdminPlatformScope.AMAZON);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateCompanyKeepsPlatformWhenRequestOmitsIt() {
|
||||
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
CompanyEntity existing = companyRow(2L, "京东事业部");
|
||||
existing.setPlatform(AdminPlatformScope.JD);
|
||||
when(companyMapper.selectById(2L)).thenReturn(existing);
|
||||
when(companyMapper.updateById(any(CompanyEntity.class))).thenReturn(1);
|
||||
|
||||
CompanySaveRequest request = new CompanySaveRequest();
|
||||
request.setCompanyName("京东事业部");
|
||||
|
||||
CompanyEntity saved = standaloneCompanyService.update(operator, 2L, request);
|
||||
|
||||
assertThat(saved.getPlatform()).isEqualTo(AdminPlatformScope.JD);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateCompanyWithExplicitPlatformReassignsIt() {
|
||||
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
CompanyEntity existing = companyRow(2L, "老公司");
|
||||
existing.setPlatform(AdminPlatformScope.AMAZON);
|
||||
when(companyMapper.selectById(2L)).thenReturn(existing);
|
||||
when(companyMapper.updateById(any(CompanyEntity.class))).thenReturn(1);
|
||||
|
||||
CompanySaveRequest request = new CompanySaveRequest();
|
||||
request.setCompanyName("老公司");
|
||||
request.setPlatform("jd");
|
||||
|
||||
CompanyEntity saved = standaloneCompanyService.update(operator, 2L, request);
|
||||
|
||||
assertThat(saved.getPlatform()).isEqualTo(AdminPlatformScope.JD);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 分组列表过滤与落库
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void groupListPlatformFilterBecomesAQueryCondition() {
|
||||
groupService.list(null, null, "jd");
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
|
||||
verify(groupMapper).selectList(captor.capture());
|
||||
// MP 的参数是惰性入表的:先渲染 SQL 段再断参数值
|
||||
assertThat(captor.getValue().getSqlSegment()).contains("platform");
|
||||
assertThat(captor.getValue().getParamNameValuePairs()).containsValue("jd");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
void groupListWithoutPlatformAddsNoCondition() {
|
||||
groupService.list(null, null);
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
|
||||
verify(groupMapper).selectList(captor.capture());
|
||||
assertThat(captor.getValue().getParamNameValuePairs()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void groupListRejectsIllegalPlatformValue() {
|
||||
assertThatThrownBy(() -> groupService.list(null, null, "taobao"))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("所属平台");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createGroupWithExplicitPlatformStoresJd() {
|
||||
stubGroupInsertCapturing();
|
||||
AdminUserEntity leader = operator(2L, "admin", 5L);
|
||||
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||
when(groupAdminUserMapper.selectById(2L)).thenReturn(leader);
|
||||
when(groupAdminUserMapper.selectById(1L)).thenReturn(operator);
|
||||
|
||||
ShopManageGroupCreateRequest request = new ShopManageGroupCreateRequest();
|
||||
request.setGroupName("京东采集组");
|
||||
request.setCreatedById(2L);
|
||||
request.setPlatform("jd");
|
||||
|
||||
groupService.create(request, 1L, true);
|
||||
|
||||
assertThat(groupInsertCaptor.get().getPlatform()).isEqualTo(AdminPlatformScope.JD);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createGroupWithoutPlatformFallsBackToAmazon() {
|
||||
stubGroupInsertCapturing();
|
||||
AdminUserEntity leader = operator(2L, "admin", 5L);
|
||||
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||
when(groupAdminUserMapper.selectById(2L)).thenReturn(leader);
|
||||
when(groupAdminUserMapper.selectById(1L)).thenReturn(operator);
|
||||
|
||||
ShopManageGroupCreateRequest request = new ShopManageGroupCreateRequest();
|
||||
request.setGroupName("亚马逊采集组");
|
||||
request.setCreatedById(2L);
|
||||
|
||||
groupService.create(request, 1L, true);
|
||||
|
||||
assertThat(groupInsertCaptor.get().getPlatform()).isEqualTo(AdminPlatformScope.AMAZON);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateGroupKeepsPlatformWhenRequestOmitsIt() {
|
||||
ShopManageGroupEntity existing = groupRow(9L, "采集组");
|
||||
existing.setPlatform(AdminPlatformScope.JD);
|
||||
when(groupMapper.selectById(9L)).thenReturn(existing);
|
||||
AdminUserEntity leader = operator(2L, "admin", 5L);
|
||||
when(groupAdminUserMapper.selectById(2L)).thenReturn(leader);
|
||||
// validateManageAccess(超管档)还要按操作者再查一次公司:漏桩会让 requireCompanyId
|
||||
// 拿到 null 账号、any(AdminUserEntity.class) 匹配不上 null ⇒ 组长/操作者公司判不一致
|
||||
when(groupAdminUserMapper.selectById(1L)).thenReturn(operator(1L, "super_admin", 5L));
|
||||
when(groupMapper.updateById(any(ShopManageGroupEntity.class))).thenReturn(1);
|
||||
when(groupAdminUserMapper.selectBatchIds(any())).thenReturn(List.of());
|
||||
|
||||
ShopManageGroupUpdateRequest request = new ShopManageGroupUpdateRequest();
|
||||
request.setGroupName("采集组");
|
||||
|
||||
groupService.update(9L, 1L, true, request);
|
||||
|
||||
ArgumentCaptor<ShopManageGroupEntity> captor = ArgumentCaptor.forClass(ShopManageGroupEntity.class);
|
||||
verify(groupMapper).updateById(captor.capture());
|
||||
assertThat(captor.getValue().getPlatform()).isEqualTo(AdminPlatformScope.JD);
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateGroupWithExplicitPlatformReassignsIt() {
|
||||
ShopManageGroupEntity existing = groupRow(9L, "采集组");
|
||||
existing.setPlatform(AdminPlatformScope.AMAZON);
|
||||
when(groupMapper.selectById(9L)).thenReturn(existing);
|
||||
AdminUserEntity leader = operator(2L, "admin", 5L);
|
||||
when(groupAdminUserMapper.selectById(2L)).thenReturn(leader);
|
||||
// 同上:validateManageAccess(超管档)按操作者再查一次公司
|
||||
when(groupAdminUserMapper.selectById(1L)).thenReturn(operator(1L, "super_admin", 5L));
|
||||
when(groupMapper.updateById(any(ShopManageGroupEntity.class))).thenReturn(1);
|
||||
when(groupAdminUserMapper.selectBatchIds(any())).thenReturn(List.of());
|
||||
|
||||
ShopManageGroupUpdateRequest request = new ShopManageGroupUpdateRequest();
|
||||
request.setGroupName("采集组");
|
||||
request.setPlatform("jd");
|
||||
|
||||
groupService.update(9L, 1L, true, request);
|
||||
|
||||
ArgumentCaptor<ShopManageGroupEntity> captor = ArgumentCaptor.forClass(ShopManageGroupEntity.class);
|
||||
verify(groupMapper).updateById(captor.capture());
|
||||
assertThat(captor.getValue().getPlatform()).isEqualTo(AdminPlatformScope.JD);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 取值出口自身
|
||||
|
||||
@Test
|
||||
void normalizeOrCreateTrimsAndDefaultsBlankToAmazon() {
|
||||
assertThat(AdminPlatformScope.normalizeOrCreate(null)).isEqualTo(AdminPlatformScope.AMAZON);
|
||||
assertThat(AdminPlatformScope.normalizeOrCreate(" ")).isEqualTo(AdminPlatformScope.AMAZON);
|
||||
assertThat(AdminPlatformScope.normalizeOrCreate(" jd ")).isEqualTo(AdminPlatformScope.JD);
|
||||
assertThatThrownBy(() -> AdminPlatformScope.normalizeOrCreate(" taobao "))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("所属平台");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- 夹具
|
||||
|
||||
private final AtomicReference<AdminUserEntity> userInsertCaptor = new AtomicReference<>();
|
||||
private final AtomicReference<CompanyEntity> companyInsertCaptor = new AtomicReference<>();
|
||||
private final AtomicReference<ShopManageGroupEntity> groupInsertCaptor = new AtomicReference<>();
|
||||
|
||||
private AtomicReference<AdminUserEntity> captureUserInsert() {
|
||||
when(userMapper.insert(any(AdminUserEntity.class))).thenAnswer(inv -> {
|
||||
AdminUserEntity entity = inv.getArgument(0);
|
||||
entity.setId(99L);
|
||||
userInsertCaptor.set(entity);
|
||||
return 1;
|
||||
});
|
||||
return userInsertCaptor;
|
||||
}
|
||||
|
||||
private AtomicReference<CompanyEntity> captureCompanyInsert() {
|
||||
when(companyMapper.insert(any(CompanyEntity.class))).thenAnswer(inv -> {
|
||||
CompanyEntity entity = inv.getArgument(0);
|
||||
entity.setId(99L);
|
||||
companyInsertCaptor.set(entity);
|
||||
return 1;
|
||||
});
|
||||
return companyInsertCaptor;
|
||||
}
|
||||
|
||||
private void stubGroupInsertCapturing() {
|
||||
when(groupMapper.insert(any(ShopManageGroupEntity.class))).thenAnswer(inv -> {
|
||||
ShopManageGroupEntity entity = inv.getArgument(0);
|
||||
entity.setId(9L);
|
||||
groupInsertCaptor.set(entity);
|
||||
return 1;
|
||||
});
|
||||
// create() 末尾 toVo(getById(id)) 会按新 id 回读同一行
|
||||
when(groupMapper.selectById(any())).thenAnswer(inv -> groupInsertCaptor.get());
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private LambdaQueryWrapper<AdminUserEntity> capturedUserCountQuery() {
|
||||
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
|
||||
verify(userMapper).selectCount(captor.capture());
|
||||
return captor.getValue();
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private LambdaUpdateWrapper<AdminUserEntity> capturedUserUpdate() {
|
||||
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass((Class) LambdaUpdateWrapper.class);
|
||||
verify(userMapper).update(any(), captor.capture());
|
||||
return captor.getValue();
|
||||
}
|
||||
|
||||
private AdminUserEntity operator(Long id, String role, Long companyId) {
|
||||
AdminUserEntity entity = new AdminUserEntity();
|
||||
entity.setId(id);
|
||||
entity.setUsername("op" + id);
|
||||
entity.setRole(role);
|
||||
entity.setIsAdmin("normal".equals(role) ? 0 : 1);
|
||||
entity.setCompanyId(companyId);
|
||||
return entity;
|
||||
}
|
||||
|
||||
private AdminUserEntity target(Long id, String role) {
|
||||
AdminUserEntity entity = new AdminUserEntity();
|
||||
entity.setId(id);
|
||||
entity.setUsername("u" + id);
|
||||
entity.setRole(role);
|
||||
entity.setIsAdmin("normal".equals(role) ? 0 : 1);
|
||||
entity.setCompanyId(5L);
|
||||
entity.setCreatedById(1L);
|
||||
return entity;
|
||||
}
|
||||
|
||||
private CompanyEntity companyRow(Long id, String name) {
|
||||
CompanyEntity entity = new CompanyEntity();
|
||||
entity.setId(id);
|
||||
entity.setCompanyName(name);
|
||||
entity.setStatus(CompanyService.STATUS_ACTIVE);
|
||||
return entity;
|
||||
}
|
||||
|
||||
private ShopManageGroupEntity groupRow(Long id, String name) {
|
||||
ShopManageGroupEntity entity = new ShopManageGroupEntity();
|
||||
entity.setId(id);
|
||||
entity.setGroupName(name);
|
||||
entity.setCreatedById(2L);
|
||||
entity.setCompanyId(5L);
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
+19
@@ -60,6 +60,25 @@ class AdminUserServiceCompanySuperAdminTest {
|
||||
when(permissionService.hasAnyAdminMenu(any(), any())).thenReturn(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 京东额度允许零并拒绝负数和普通账号() {
|
||||
AdminUserEntity operator = user(1L, "super_admin", 1L, null);
|
||||
AdminUserEntity target = user(10L, "admin", 1L, 1L);
|
||||
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||
when(userMapper.selectById(10L)).thenReturn(target);
|
||||
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
|
||||
request.setJdPublishQuota(0);
|
||||
service.updateUser(operator, 10L, request);
|
||||
verify(userMapper).update(any(), any());
|
||||
request.setJdPublishQuota(-1);
|
||||
assertThatThrownBy(() -> service.updateUser(operator, 10L, request))
|
||||
.isInstanceOf(BusinessException.class).hasMessageContaining("不能为负数");
|
||||
request.setJdPublishQuota(1);
|
||||
target.setRole("normal");
|
||||
assertThatThrownBy(() -> service.updateUser(operator, 10L, request))
|
||||
.isInstanceOf(BusinessException.class).hasMessageContaining("只能为管理员");
|
||||
}
|
||||
|
||||
// ---------- 建号 ----------
|
||||
|
||||
@Test
|
||||
|
||||
+4
-4
@@ -57,7 +57,7 @@ class CompanyControllerEndpointTest {
|
||||
body.setRemark("二期");
|
||||
|
||||
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(operator);
|
||||
when(companyService.listVisible(operator)).thenReturn(List.of(company(1L, "厦门米椿花")));
|
||||
when(companyService.listVisible(operator, null)).thenReturn(List.of(company(1L, "厦门米椿花")));
|
||||
when(companyService.create(any(), any())).thenReturn(company(2L, "福州数富"));
|
||||
when(companyService.update(any(), any(), any())).thenReturn(company(2L, "福州数富科技"));
|
||||
}
|
||||
@@ -73,13 +73,13 @@ class CompanyControllerEndpointTest {
|
||||
@Test
|
||||
@DisplayName("每个端点先鉴权再进 service,顺序不能反")
|
||||
void everyEndpointAuthenticatesBeforeTouchingTheDirectory() {
|
||||
controller.listCompanies(request);
|
||||
controller.listCompanies(request, null);
|
||||
controller.createCompany(request, body);
|
||||
controller.updateCompany(request, 2L, body);
|
||||
|
||||
InOrder order = inOrder(adminAuthSupport, companyService);
|
||||
order.verify(adminAuthSupport).requireAdminOrInternal(request);
|
||||
order.verify(companyService).listVisible(operator);
|
||||
order.verify(companyService).listVisible(operator, null);
|
||||
order.verify(adminAuthSupport).requireAdminOrInternal(request);
|
||||
order.verify(companyService).create(operator, body);
|
||||
order.verify(adminAuthSupport).requireAdminOrInternal(request);
|
||||
@@ -108,7 +108,7 @@ class CompanyControllerEndpointTest {
|
||||
@Test
|
||||
@DisplayName("列表回包是 CompanyVo 而不是实体:实体字段是 camelCase,前端解析不到公司名")
|
||||
void listReturnsVoItemsNotEntities() {
|
||||
ApiResponse<List<CompanyVo>> response = controller.listCompanies(request);
|
||||
ApiResponse<List<CompanyVo>> response = controller.listCompanies(request, null);
|
||||
|
||||
assertThat(response.getData()).hasSize(1);
|
||||
assertThat(response.getData().get(0).getCompanyName()).isEqualTo("厦门米椿花");
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user